docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,369 +0,0 @@
|
||||
/**
|
||||
* The "nytt att bokföra" digest: opt-in sweep, empty-skip, the recoverable
|
||||
* claim lifecycle (pending -> send -> sent, stale takeover), and the
|
||||
* counts-only email body.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
const mockIsConfigured = vi.fn()
|
||||
const mockSendEmail = vi.fn()
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
getEmailService: () => ({ isConfigured: mockIsConfigured, sendEmail: mockSendEmail }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandForCompany: vi.fn(async () => null),
|
||||
}))
|
||||
vi.mock('@/lib/branding/service', () => ({
|
||||
getBranding: () => ({ appUrl: 'https://app.testbrand.example' }),
|
||||
}))
|
||||
|
||||
import { runBookkeepingDigest, buildDigestEmail } from '../bookkeeping-digest'
|
||||
|
||||
interface TableFixture {
|
||||
optedIn?: Array<{ user_id: string }>
|
||||
members?: Array<{ user_id: string; company_id: string }>
|
||||
txCount?: number
|
||||
inboxCount?: number
|
||||
companyName?: string
|
||||
claimError?: { code?: string; message: string } | null
|
||||
/** Row returned when acquireClaim inspects an existing claim after 23505. */
|
||||
existingClaim?: { id: string; delivery_status: string; sent_at: string | null } | null
|
||||
/** Whether the stale-takeover lease UPDATE wins (returns the row). */
|
||||
leaseWon?: boolean
|
||||
}
|
||||
|
||||
interface RecordedWrite {
|
||||
table: string
|
||||
op: 'insert' | 'update' | 'delete'
|
||||
payload?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand-rolled mock: the assertions need recorded write payloads and order
|
||||
* (claim insert before send, sent-update after), which
|
||||
* createQueuedMockSupabase cannot key by table.
|
||||
*/
|
||||
function makeSupabase(fx: TableFixture) {
|
||||
const writes: RecordedWrite[] = []
|
||||
const countBuilder = (count: number) => {
|
||||
const b: Record<string, unknown> = {}
|
||||
Object.assign(b, {
|
||||
eq: () => b,
|
||||
gte: () => b,
|
||||
not: () => b,
|
||||
is: () => b,
|
||||
in: () => b,
|
||||
then: (resolve: (v: unknown) => void) => resolve({ data: null, error: null, count }),
|
||||
})
|
||||
return b
|
||||
}
|
||||
const from = (table: string) => {
|
||||
const builder: Record<string, unknown> = {}
|
||||
const finish = () => {
|
||||
if (table === 'notification_settings') return { data: fx.optedIn ?? [], error: null }
|
||||
if (table === 'company_members') return { data: fx.members ?? [], error: null }
|
||||
if (table === 'profiles') {
|
||||
const ids = new Set((fx.members ?? []).map((m) => m.user_id))
|
||||
return {
|
||||
data: [...ids].map((id) => ({ id, email: `${id}@testbrand.example` })),
|
||||
error: null,
|
||||
}
|
||||
}
|
||||
return { data: [], error: null }
|
||||
}
|
||||
Object.assign(builder, {
|
||||
select: (_cols?: string, opts?: { head?: boolean }) => {
|
||||
if (table === 'transactions' && opts?.head) return countBuilder(fx.txCount ?? 0)
|
||||
if (table === 'invoice_inbox_items' && opts?.head) return countBuilder(fx.inboxCount ?? 0)
|
||||
return builder
|
||||
},
|
||||
insert: (payload: Record<string, unknown>) => {
|
||||
writes.push({ table, op: 'insert', payload })
|
||||
return Promise.resolve({ data: null, error: fx.claimError ?? null })
|
||||
},
|
||||
update: (payload: Record<string, unknown>) => {
|
||||
writes.push({ table, op: 'update', payload })
|
||||
const ub: Record<string, unknown> = {}
|
||||
Object.assign(ub, {
|
||||
eq: () => ub,
|
||||
lte: () => ub,
|
||||
// The lease-renewal UPDATE ends in .select('id'): winning returns
|
||||
// the row, losing returns [].
|
||||
select: () =>
|
||||
Promise.resolve({ data: fx.leaseWon ? [{ id: 'claim-1' }] : [], error: null }),
|
||||
then: (resolve: (v: unknown) => void) => resolve({ data: null, error: null }),
|
||||
})
|
||||
return ub
|
||||
},
|
||||
delete: () => {
|
||||
writes.push({ table, op: 'delete' })
|
||||
return builder
|
||||
},
|
||||
eq: () => builder,
|
||||
in: () => builder,
|
||||
gte: () => builder,
|
||||
not: () => builder,
|
||||
is: () => builder,
|
||||
order: () => builder,
|
||||
range: () => builder,
|
||||
maybeSingle: async () => {
|
||||
if (table === 'companies') {
|
||||
return { data: { name: fx.companyName ?? 'Testbolaget AB' }, error: null }
|
||||
}
|
||||
if (table === 'notification_log') {
|
||||
return { data: fx.existingClaim ?? null, error: null }
|
||||
}
|
||||
return { data: null, error: null }
|
||||
},
|
||||
then: (resolve: (v: unknown) => void) => resolve(finish()),
|
||||
})
|
||||
return builder
|
||||
}
|
||||
return { supabase: { from } as unknown as SupabaseClient, writes }
|
||||
}
|
||||
|
||||
const NOW = new Date('2026-08-31T05:45:00Z')
|
||||
|
||||
const oneUserOneCompany = {
|
||||
optedIn: [{ user_id: 'u1' }],
|
||||
members: [{ user_id: 'u1', company_id: 'c1' }],
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockIsConfigured.mockReturnValue(true)
|
||||
mockSendEmail.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
describe('runBookkeepingDigest', () => {
|
||||
it('does nothing when email is not configured', async () => {
|
||||
mockIsConfigured.mockReturnValue(false)
|
||||
const { supabase } = makeSupabase({ optedIn: [{ user_id: 'u1' }] })
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.sent).toBe(0)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does nothing when nobody opted in', async () => {
|
||||
const { supabase, writes } = makeSupabase({ optedIn: [] })
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary).toMatchObject({ optedInUsers: 0, sent: 0 })
|
||||
expect(writes).toHaveLength(0)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips companies with nothing new instead of sending empty mail', async () => {
|
||||
const { supabase } = makeSupabase({ ...oneUserOneCompany, txCount: 0, inboxCount: 0 })
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.skippedEmpty).toBe(1)
|
||||
expect(summary.sent).toBe(0)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('claims as pending BEFORE sending, marks sent only after the provider accepted', async () => {
|
||||
const { supabase, writes } = makeSupabase({ ...oneUserOneCompany, txCount: 3, inboxCount: 1 })
|
||||
let claimsAtSendTime = -1
|
||||
mockSendEmail.mockImplementation(async () => {
|
||||
claimsAtSendTime = writes.filter((w) => w.op === 'insert').length
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.sent).toBe(1)
|
||||
expect(claimsAtSendTime).toBe(1)
|
||||
const insert = writes.find((w) => w.op === 'insert')
|
||||
expect(insert?.table).toBe('notification_log')
|
||||
expect(insert?.payload).toMatchObject({
|
||||
user_id: 'u1',
|
||||
company_id: 'c1',
|
||||
notification_type: 'bookkeeping_digest',
|
||||
delivery_status: 'pending',
|
||||
})
|
||||
// Flipped to 'sent' only after sendEmail resolved successfully.
|
||||
const sentUpdate = writes.find(
|
||||
(w) => w.op === 'update' && w.payload?.delivery_status === 'sent',
|
||||
)
|
||||
expect(sentUpdate).toBeDefined()
|
||||
const mail = mockSendEmail.mock.calls[0][0]
|
||||
expect(mail.to).toBe('[email protected]')
|
||||
expect(mail.subject).toContain('Nytt att bokföra')
|
||||
expect(mail.text).toContain('3 nya banktransaktioner')
|
||||
expect(mail.text).toContain('1 nytt underlag')
|
||||
// Data minimization: counts only, never amounts.
|
||||
expect(mail.text).not.toMatch(/\d+[.,]\d{2}\s*(kr|SEK)/i)
|
||||
})
|
||||
|
||||
it('a 23505 with an already-sent claim means another run delivered today: no email', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
...oneUserOneCompany,
|
||||
txCount: 2,
|
||||
claimError: { code: '23505', message: 'duplicate key' },
|
||||
existingClaim: { id: 'claim-1', delivery_status: 'sent', sent_at: NOW.toISOString() },
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.skippedDuplicate).toBe(1)
|
||||
expect(summary.sent).toBe(0)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('a fresh pending claim belongs to a run in flight: no takeover, no email', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
...oneUserOneCompany,
|
||||
txCount: 2,
|
||||
claimError: { code: '23505', message: 'duplicate key' },
|
||||
existingClaim: {
|
||||
id: 'claim-1',
|
||||
delivery_status: 'pending',
|
||||
sent_at: new Date(Date.now() - 60_000).toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.skippedDuplicate).toBe(1)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('takes over a STALE pending claim (a run that died before sending) and sends', async () => {
|
||||
const { supabase, writes } = makeSupabase({
|
||||
...oneUserOneCompany,
|
||||
txCount: 2,
|
||||
claimError: { code: '23505', message: 'duplicate key' },
|
||||
existingClaim: {
|
||||
id: 'claim-1',
|
||||
delivery_status: 'pending',
|
||||
sent_at: new Date(Date.now() - 60 * 60_000).toISOString(),
|
||||
},
|
||||
leaseWon: true,
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.sent).toBe(1)
|
||||
expect(mockSendEmail).toHaveBeenCalledTimes(1)
|
||||
// Lease renewal update happened before the send-completion update.
|
||||
expect(writes.filter((w) => w.op === 'update').length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
it('loses the stale-takeover race cleanly: no email', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
...oneUserOneCompany,
|
||||
txCount: 2,
|
||||
claimError: { code: '23505', message: 'duplicate key' },
|
||||
existingClaim: {
|
||||
id: 'claim-1',
|
||||
delivery_status: 'pending',
|
||||
sent_at: new Date(Date.now() - 60 * 60_000).toISOString(),
|
||||
},
|
||||
leaseWon: false,
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.skippedDuplicate).toBe(1)
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the claim pending when the send fails, so a later run can retry', async () => {
|
||||
mockSendEmail.mockResolvedValue({ success: false, error: 'smtp down' })
|
||||
const { supabase, writes } = makeSupabase({ ...oneUserOneCompany, txCount: 2 })
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.failed).toBe(1)
|
||||
expect(summary.sent).toBe(0)
|
||||
// The claim is neither deleted nor marked sent: it stays 'pending' and
|
||||
// becomes takeover-eligible once stale.
|
||||
expect(writes.some((w) => w.op === 'delete')).toBe(false)
|
||||
expect(
|
||||
writes.some((w) => w.op === 'update' && w.payload?.delivery_status === 'sent'),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('sends to every opted-in member of the same company', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
optedIn: [{ user_id: 'u1' }, { user_id: 'u2' }],
|
||||
members: [
|
||||
{ user_id: 'u1', company_id: 'c1' },
|
||||
{ user_id: 'u2', company_id: 'c1' },
|
||||
],
|
||||
txCount: 5,
|
||||
})
|
||||
|
||||
const summary = await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
expect(summary.sent).toBe(2)
|
||||
const recipients = mockSendEmail.mock.calls.map((c) => c[0].to).sort()
|
||||
expect(recipients).toEqual(['[email protected]', '[email protected]'])
|
||||
})
|
||||
|
||||
it('strips CRLF from the company name so it cannot inject mail headers', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
...oneUserOneCompany,
|
||||
txCount: 1,
|
||||
companyName: 'Evil AB\r\nBcc: [email protected]',
|
||||
})
|
||||
|
||||
await runBookkeepingDigest(supabase, NOW)
|
||||
|
||||
const mail = mockSendEmail.mock.calls[0][0]
|
||||
expect(mail.subject).not.toMatch(/[\r\n]/)
|
||||
expect(mail.subject).toBe('Nytt att bokföra i Evil AB Bcc: [email protected]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildDigestEmail', () => {
|
||||
it('renders singular and plural Swedish correctly', () => {
|
||||
const one = buildDigestEmail({
|
||||
companyName: 'Testbolaget AB',
|
||||
counts: { newTransactions: 1, newInboxItems: 1 },
|
||||
baseUrl: 'https://app.testbrand.example',
|
||||
appName: 'Accounted',
|
||||
})
|
||||
expect(one.text).toContain('1 ny banktransaktion att bokföra')
|
||||
expect(one.text).toContain('1 nytt underlag i inkorgen')
|
||||
expect(one.subject).toBe('Nytt att bokföra i Testbolaget AB')
|
||||
|
||||
const many = buildDigestEmail({
|
||||
companyName: null,
|
||||
counts: { newTransactions: 4, newInboxItems: 2 },
|
||||
baseUrl: 'https://app.testbrand.example',
|
||||
appName: 'Accounted',
|
||||
})
|
||||
expect(many.subject).toBe('Nytt att bokföra')
|
||||
expect(many.text).toContain('4 nya banktransaktioner att bokföra')
|
||||
expect(many.text).toContain('2 nya underlag i inkorgen')
|
||||
})
|
||||
|
||||
it('omits the zero category', () => {
|
||||
const mail = buildDigestEmail({
|
||||
companyName: null,
|
||||
counts: { newTransactions: 2, newInboxItems: 0 },
|
||||
baseUrl: 'https://app.testbrand.example',
|
||||
appName: 'Accounted',
|
||||
})
|
||||
expect(mail.text).not.toContain('underlag i inkorgen')
|
||||
})
|
||||
|
||||
it('escapes html in the company name', () => {
|
||||
const mail = buildDigestEmail({
|
||||
companyName: '<b>Evil & Co</b>',
|
||||
counts: { newTransactions: 1, newInboxItems: 0 },
|
||||
baseUrl: 'https://app.testbrand.example',
|
||||
appName: 'Accounted',
|
||||
})
|
||||
expect(mail.html).not.toContain('<b>Evil')
|
||||
expect(mail.html).toContain('<b>Evil & Co</b>')
|
||||
})
|
||||
})
|
||||
@@ -1,199 +0,0 @@
|
||||
/**
|
||||
* Recipient resolution for notification emails.
|
||||
*
|
||||
* The regression this guards: the four notification senders used the
|
||||
* PostgREST embed company_members → profiles!inner(email), but no FK links
|
||||
* those tables, so the embed 400'd and every recipient resolved to null.
|
||||
* The helper resolves membership and email as two separate queries.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
const { warnRecorder } = vi.hoisted(() => ({ warnRecorder: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/logger', () => ({
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
warn: warnRecorder,
|
||||
error: vi.fn(),
|
||||
child() {
|
||||
return this
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
import { resolveMemberEmail, resolveMemberEmails } from '../member-email'
|
||||
|
||||
interface QueryRecord {
|
||||
table: string
|
||||
columns?: string
|
||||
filters: Record<string, unknown>
|
||||
}
|
||||
|
||||
function makeSupabase(opts: {
|
||||
memberRows?: Array<{ user_id: string | null }> | null
|
||||
membersError?: { message: string } | null
|
||||
profileRows?: Array<{ id: string; email: string | null }> | null
|
||||
profilesError?: { message: string } | null
|
||||
}) {
|
||||
const queries: QueryRecord[] = []
|
||||
const from = (table: string) => {
|
||||
const record: QueryRecord = { table, filters: {} }
|
||||
queries.push(record)
|
||||
const result = () => {
|
||||
if (table === 'company_members') {
|
||||
return {
|
||||
data: opts.membersError ? null : opts.memberRows ?? [],
|
||||
error: opts.membersError ?? null,
|
||||
}
|
||||
}
|
||||
if (table === 'profiles') {
|
||||
return {
|
||||
data: opts.profilesError ? null : opts.profileRows ?? [],
|
||||
error: opts.profilesError ?? null,
|
||||
}
|
||||
}
|
||||
return { data: null, error: null }
|
||||
}
|
||||
const builder: Record<string, unknown> = {}
|
||||
Object.assign(builder, {
|
||||
select: (columns: string) => {
|
||||
record.columns = columns
|
||||
return builder
|
||||
},
|
||||
eq: (key: string, value: unknown) => {
|
||||
record.filters[key] = value
|
||||
return builder
|
||||
},
|
||||
in: (key: string, value: unknown) => {
|
||||
record.filters[key] = value
|
||||
return builder
|
||||
},
|
||||
order: () => builder,
|
||||
range: () => builder,
|
||||
maybeSingle: async () => {
|
||||
const r = result()
|
||||
const rows = r.data as Array<Record<string, unknown>> | null
|
||||
return { data: rows?.[0] ?? null, error: r.error }
|
||||
},
|
||||
then: (resolve: (v: unknown) => void) => resolve(result()),
|
||||
})
|
||||
return builder
|
||||
}
|
||||
return { supabase: { from } as unknown as SupabaseClient, queries }
|
||||
}
|
||||
|
||||
function warnedWith(fragment: string): boolean {
|
||||
return warnRecorder.mock.calls.some(
|
||||
(call) => typeof call[0] === 'string' && call[0].includes(fragment),
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('resolveMemberEmail', () => {
|
||||
it('resolves an active member to their profile email via two queries (no embed)', async () => {
|
||||
const { supabase, queries } = makeSupabase({
|
||||
memberRows: [{ user_id: 'user-1' }],
|
||||
profileRows: [{ id: 'user-1', email: '[email protected]' }],
|
||||
})
|
||||
|
||||
const email = await resolveMemberEmail(supabase, 'company-1', 'user-1')
|
||||
|
||||
expect(email).toBe('[email protected]')
|
||||
const memberQuery = queries.find((q) => q.table === 'company_members')
|
||||
// The embed column list is exactly what broke: assert it is gone.
|
||||
expect(memberQuery?.columns).toBe('user_id')
|
||||
expect(memberQuery?.filters).toMatchObject({ company_id: 'company-1', user_id: 'user-1' })
|
||||
const profileQuery = queries.find((q) => q.table === 'profiles')
|
||||
expect(profileQuery?.columns).toBe('email')
|
||||
expect(profileQuery?.filters).toMatchObject({ id: 'user-1' })
|
||||
})
|
||||
|
||||
it('returns null for a user who is no longer a member (no profile query at all)', async () => {
|
||||
const { supabase, queries } = makeSupabase({
|
||||
memberRows: [],
|
||||
profileRows: [{ id: 'user-1', email: '[email protected]' }],
|
||||
})
|
||||
|
||||
expect(await resolveMemberEmail(supabase, 'company-1', 'user-1')).toBeNull()
|
||||
expect(queries.some((q) => q.table === 'profiles')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns null when the profile has no email', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
memberRows: [{ user_id: 'user-1' }],
|
||||
profileRows: [{ id: 'user-1', email: null }],
|
||||
})
|
||||
expect(await resolveMemberEmail(supabase, 'company-1', 'user-1')).toBeNull()
|
||||
})
|
||||
|
||||
it('logs and returns null (never throws) on a member query error', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
membersError: { message: 'permission denied for table company_members' },
|
||||
})
|
||||
expect(await resolveMemberEmail(supabase, 'company-1', 'user-1')).toBeNull()
|
||||
expect(warnedWith('could not read company members')).toBe(true)
|
||||
})
|
||||
|
||||
it('logs and returns null (never throws) on a profile query error', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
memberRows: [{ user_id: 'user-1' }],
|
||||
profilesError: { message: 'timeout' },
|
||||
})
|
||||
expect(await resolveMemberEmail(supabase, 'company-1', 'user-1')).toBeNull()
|
||||
expect(warnedWith('could not read profile email')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveMemberEmails', () => {
|
||||
it('maps every member with a profile email, keyed by user id', async () => {
|
||||
const { supabase, queries } = makeSupabase({
|
||||
memberRows: [{ user_id: 'user-1' }, { user_id: 'user-2' }, { user_id: 'user-3' }],
|
||||
profileRows: [
|
||||
{ id: 'user-1', email: '[email protected]' },
|
||||
{ id: 'user-2', email: '[email protected]' },
|
||||
{ id: 'user-3', email: null },
|
||||
],
|
||||
})
|
||||
|
||||
const emails = await resolveMemberEmails(supabase, 'company-1')
|
||||
|
||||
expect(emails.get('user-1')).toBe('[email protected]')
|
||||
expect(emails.get('user-2')).toBe('[email protected]')
|
||||
expect(emails.has('user-3')).toBe(false)
|
||||
const memberQuery = queries.find((q) => q.table === 'company_members')
|
||||
expect(memberQuery?.columns).toBe('user_id')
|
||||
const profileQuery = queries.find((q) => q.table === 'profiles')
|
||||
expect(profileQuery?.columns).toBe('id, email')
|
||||
expect(profileQuery?.filters).toMatchObject({ id: ['user-1', 'user-2', 'user-3'] })
|
||||
})
|
||||
|
||||
it('returns an empty map for a company with no members (no profile query)', async () => {
|
||||
const { supabase, queries } = makeSupabase({ memberRows: [] })
|
||||
const emails = await resolveMemberEmails(supabase, 'company-1')
|
||||
expect(emails.size).toBe(0)
|
||||
expect(queries.some((q) => q.table === 'profiles')).toBe(false)
|
||||
})
|
||||
|
||||
it('logs and returns an empty map on a member query error', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
membersError: { message: 'permission denied for table company_members' },
|
||||
})
|
||||
const emails = await resolveMemberEmails(supabase, 'company-1')
|
||||
expect(emails.size).toBe(0)
|
||||
expect(warnedWith('could not read company members')).toBe(true)
|
||||
})
|
||||
|
||||
it('logs and returns an empty map on a profiles query error', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
memberRows: [{ user_id: 'user-1' }],
|
||||
profilesError: { message: 'timeout' },
|
||||
})
|
||||
const emails = await resolveMemberEmails(supabase, 'company-1')
|
||||
expect(emails.size).toBe(0)
|
||||
expect(warnedWith('could not read member emails')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,496 +0,0 @@
|
||||
/**
|
||||
* Daily "nytt att bokföra" email digest.
|
||||
*
|
||||
* Users asked for an email when there is new work to book: bank transactions
|
||||
* that synced overnight and documents that landed in the inbox. The digest is
|
||||
* strictly opt-in (notification_settings.email_digest_enabled, default false)
|
||||
* and runs daily after the 05:00 bank sync so the night's imports are counted
|
||||
* the same morning.
|
||||
*
|
||||
* One email per user per company per day: dedup goes through notification_log
|
||||
* under type 'bookkeeping_digest', guarded by a partial unique index on
|
||||
* (user_id, reference_id) (migration 20260831100000). reference_id is a
|
||||
* deterministic uuid derived from (company, digest date), so overlapping cron
|
||||
* invocations race on the insert and exactly one wins. The claim is
|
||||
* recoverable: it is inserted as delivery_status 'pending', flipped to 'sent'
|
||||
* only after the provider accepted the mail, and a 'pending' claim older than
|
||||
* STALE_CLAIM_MS (a run that died before sending, or a send that failed) can
|
||||
* be atomically taken over by a later run, so an interruption never silently
|
||||
* swallows that day's digest.
|
||||
*
|
||||
* The body carries counts only, never amounts or counterparties: the mere
|
||||
* existence of company mail is sensitive financial signal, so the details
|
||||
* live behind login (same data-minimization stance as the skattekonto drift
|
||||
* and kvittens emails).
|
||||
*
|
||||
* Best-effort by design: a digest failure must never fail the cron run for
|
||||
* other users or companies.
|
||||
*/
|
||||
import { createHash } from 'crypto'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { getSenderForBrand, getBaseUrlForBrand } from '@/lib/email/brand-sender'
|
||||
import { resolveBrandForCompany } from '@/lib/branding/resolve'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { chunk } from '@/lib/utils'
|
||||
import { escapeHtml } from '@/lib/email/user-text'
|
||||
|
||||
const log = createLogger('bookkeeping-digest')
|
||||
|
||||
/** The digest counts changes in the last 24h: one cron cadence back. */
|
||||
const WINDOW_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
/**
|
||||
* A 'pending' claim older than this is considered abandoned (the run that
|
||||
* inserted it died before sending) and may be taken over by a later run.
|
||||
* The cron is daily, so anything measured in minutes is safely stale.
|
||||
*/
|
||||
const STALE_CLAIM_MS = 15 * 60 * 1000
|
||||
|
||||
/**
|
||||
* Max ids per PostgREST .in() filter: ids travel in the GET query string,
|
||||
* and an unchunked list 414s past proxy URL limits (same limit and
|
||||
* rationale as lib/worklist/categories.ts).
|
||||
*/
|
||||
const IN_CLAUSE_CHUNK = 150
|
||||
|
||||
export interface DigestCounts {
|
||||
newTransactions: number
|
||||
newInboxItems: number
|
||||
}
|
||||
|
||||
export interface DigestRunSummary {
|
||||
optedInUsers: number
|
||||
companiesConsidered: number
|
||||
sent: number
|
||||
skippedEmpty: number
|
||||
skippedDuplicate: number
|
||||
failed: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Count what arrived in the window and is still unhandled, using the same
|
||||
* anchors as the worklist counts (lib/worklist/categories.ts). Transactions:
|
||||
* created in the window, not yet booked (journal_entry_id anchor only; rows
|
||||
* junction-linked via samlingsverifikat are a rounding error a few hours
|
||||
* after import), not marked private, and not ignored. Inbox items: created
|
||||
* in the window and not yet terminal on any of the three markers
|
||||
* (supplier invoice created, booked directly, or matched to a transaction;
|
||||
* status stays 'received' in all three cases).
|
||||
*/
|
||||
export async function countNewToBook(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
sinceIso: string
|
||||
): Promise<DigestCounts> {
|
||||
const [txHead, inboxHead] = await Promise.all([
|
||||
supabase
|
||||
.from('transactions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.gte('created_at', sinceIso)
|
||||
.is('journal_entry_id', null)
|
||||
.not('is_business', 'is', false)
|
||||
.eq('is_ignored', false),
|
||||
supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.gte('created_at', sinceIso)
|
||||
.in('status', ['received', 'processing'])
|
||||
.is('created_supplier_invoice_id', null)
|
||||
.is('created_journal_entry_id', null)
|
||||
.is('matched_transaction_id', null),
|
||||
])
|
||||
if (txHead.error) throw new Error(`transactions count failed: ${txHead.error.message}`)
|
||||
if (inboxHead.error) throw new Error(`inbox count failed: ${inboxHead.error.message}`)
|
||||
return {
|
||||
newTransactions: txHead.count ?? 0,
|
||||
newInboxItems: inboxHead.count ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the digest for every opted-in user. Requires a SERVICE-ROLE client:
|
||||
* both the settings sweep and the profile email lookups cross user
|
||||
* boundaries that RLS would silently empty out.
|
||||
*/
|
||||
export async function runBookkeepingDigest(
|
||||
supabase: SupabaseClient,
|
||||
now: Date
|
||||
): Promise<DigestRunSummary> {
|
||||
const summary: DigestRunSummary = {
|
||||
optedInUsers: 0,
|
||||
companiesConsidered: 0,
|
||||
sent: 0,
|
||||
skippedEmpty: 0,
|
||||
skippedDuplicate: 0,
|
||||
failed: 0,
|
||||
}
|
||||
|
||||
const email = getEmailService()
|
||||
if (!email.isConfigured()) {
|
||||
log.info('bookkeeping digest skipped: email service not configured')
|
||||
return summary
|
||||
}
|
||||
|
||||
const optedIn = await fetchAllRows<{ user_id: string }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('notification_settings')
|
||||
.select('user_id')
|
||||
.eq('email_digest_enabled', true)
|
||||
.order('user_id', { ascending: true })
|
||||
.range(from, to)
|
||||
)
|
||||
summary.optedInUsers = optedIn.length
|
||||
if (optedIn.length === 0) return summary
|
||||
|
||||
const userIds = optedIn.map((r) => r.user_id)
|
||||
const memberships: Array<{ user_id: string; company_id: string }> = []
|
||||
for (const idChunk of chunk(userIds, IN_CLAUSE_CHUNK)) {
|
||||
const page = await fetchAllRows<{ user_id: string; company_id: string }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('company_members')
|
||||
.select('user_id, company_id')
|
||||
.in('user_id', idChunk)
|
||||
// (company_id, user_id) is unique per membership: stable total order
|
||||
// for range paging.
|
||||
.order('company_id', { ascending: true })
|
||||
.order('user_id', { ascending: true })
|
||||
.range(from, to)
|
||||
)
|
||||
memberships.push(...page)
|
||||
}
|
||||
|
||||
const usersByCompany = new Map<string, string[]>()
|
||||
for (const m of memberships) {
|
||||
if (!m.user_id || !m.company_id) continue
|
||||
const list = usersByCompany.get(m.company_id) ?? []
|
||||
list.push(m.user_id)
|
||||
usersByCompany.set(m.company_id, list)
|
||||
}
|
||||
summary.companiesConsidered = usersByCompany.size
|
||||
|
||||
const sinceIso = new Date(now.getTime() - WINDOW_MS).toISOString()
|
||||
const digestDate = now.toISOString().slice(0, 10)
|
||||
|
||||
for (const [companyId, companyUserIds] of usersByCompany) {
|
||||
try {
|
||||
const counts = await countNewToBook(supabase, companyId, sinceIso)
|
||||
if (counts.newTransactions === 0 && counts.newInboxItems === 0) {
|
||||
summary.skippedEmpty += companyUserIds.length
|
||||
continue
|
||||
}
|
||||
const result = await sendDigestForCompany(supabase, {
|
||||
companyId,
|
||||
userIds: companyUserIds,
|
||||
counts,
|
||||
digestDate,
|
||||
})
|
||||
summary.sent += result.sent
|
||||
summary.skippedDuplicate += result.skippedDuplicate
|
||||
summary.failed += result.failed
|
||||
} catch (err) {
|
||||
summary.failed += companyUserIds.length
|
||||
log.warn('bookkeeping digest failed for company', {
|
||||
companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
|
||||
interface CompanyDigestInput {
|
||||
companyId: string
|
||||
userIds: string[]
|
||||
counts: DigestCounts
|
||||
digestDate: string
|
||||
}
|
||||
|
||||
async function sendDigestForCompany(
|
||||
supabase: SupabaseClient,
|
||||
input: CompanyDigestInput
|
||||
): Promise<{ sent: number; skippedDuplicate: number; failed: number }> {
|
||||
const out = { sent: 0, skippedDuplicate: 0, failed: 0 }
|
||||
const email = getEmailService()
|
||||
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
.select('name')
|
||||
.eq('id', input.companyId)
|
||||
.maybeSingle()
|
||||
const rawCompanyName = (company as { name?: string } | null)?.name ?? null
|
||||
// The name reaches the Subject header: sanitize against header injection.
|
||||
const companyName = rawCompanyName ? sanitizeHeaderText(rawCompanyName) || null : null
|
||||
|
||||
// One brand resolution per company; sender identity and link base follow
|
||||
// the company's brand (white-label rule: mail goes out in the brand of the
|
||||
// company it concerns).
|
||||
const brand = await resolveBrandForCompany(input.companyId)
|
||||
const sender = getSenderForBrand(brand)
|
||||
const baseUrl = getBaseUrlForBrand(brand)
|
||||
|
||||
// The recipient allowlist is the set of active members: an opted-in user
|
||||
// removed from the company must not keep receiving its digest.
|
||||
const memberEmails = await resolveCompanyMemberEmails(supabase, input.companyId, input.userIds)
|
||||
|
||||
const referenceUuid = toReferenceUuid(
|
||||
`bookkeeping_digest:${input.companyId}:${input.digestDate}`
|
||||
)
|
||||
|
||||
for (const userId of input.userIds) {
|
||||
const recipient = memberEmails.get(userId)
|
||||
if (!recipient) continue
|
||||
|
||||
const claim = await acquireClaim(supabase, userId, input.companyId, referenceUuid)
|
||||
if (claim === 'duplicate') {
|
||||
out.skippedDuplicate++
|
||||
continue
|
||||
}
|
||||
if (claim === 'error') {
|
||||
// Without a claim we cannot guarantee once-per-day: fail closed.
|
||||
out.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
const message = buildDigestEmail({
|
||||
companyName,
|
||||
counts: input.counts,
|
||||
baseUrl,
|
||||
appName: brand?.appName ?? 'Accounted',
|
||||
})
|
||||
|
||||
let sendResult: Awaited<ReturnType<typeof email.sendEmail>>
|
||||
try {
|
||||
sendResult = await email.sendEmail({
|
||||
to: recipient,
|
||||
subject: message.subject,
|
||||
text: message.text,
|
||||
html: message.html,
|
||||
...(sender.fromName ? { fromName: sender.fromName } : {}),
|
||||
...(sender.fromAddress ? { fromAddress: sender.fromAddress } : {}),
|
||||
...(sender.replyTo ? { replyTo: sender.replyTo } : {}),
|
||||
})
|
||||
} catch (err) {
|
||||
// The claim stays 'pending': a later run takes it over once stale.
|
||||
out.failed++
|
||||
log.warn('digest email send threw', {
|
||||
companyId: input.companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (!sendResult.success) {
|
||||
out.failed++
|
||||
log.warn('digest email send failed', {
|
||||
companyId: input.companyId,
|
||||
error: sendResult.error,
|
||||
})
|
||||
continue
|
||||
}
|
||||
await markClaimSent(supabase, userId, referenceUuid)
|
||||
out.sent++
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
type ClaimOutcome = 'acquired' | 'duplicate' | 'error'
|
||||
|
||||
/**
|
||||
* Acquire the once-per-day send claim. The insert (delivery_status
|
||||
* 'pending') is made atomic by the partial unique index on
|
||||
* (user_id, reference_id) for this notification_type; the loser of two
|
||||
* overlapping runs gets 23505. A 'pending' claim whose sent_at lease is
|
||||
* older than STALE_CLAIM_MS belonged to a run that died before sending (or
|
||||
* whose send failed): it is taken over by atomically renewing the lease,
|
||||
* conditioned on the row still being the same stale 'pending', so exactly
|
||||
* one contender wins.
|
||||
*/
|
||||
async function acquireClaim(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
referenceUuid: string
|
||||
): Promise<ClaimOutcome> {
|
||||
const { error: claimError } = await supabase.from('notification_log').insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
notification_type: 'bookkeeping_digest',
|
||||
reference_id: referenceUuid,
|
||||
days_before: 0,
|
||||
delivery_status: 'pending',
|
||||
})
|
||||
if (!claimError) return 'acquired'
|
||||
if (claimError.code !== '23505') {
|
||||
log.warn('digest claim insert failed', { companyId, error: claimError.message })
|
||||
return 'error'
|
||||
}
|
||||
|
||||
const { data: existing, error: readError } = await supabase
|
||||
.from('notification_log')
|
||||
.select('id, delivery_status, sent_at')
|
||||
.eq('user_id', userId)
|
||||
.eq('notification_type', 'bookkeeping_digest')
|
||||
.eq('reference_id', referenceUuid)
|
||||
.maybeSingle()
|
||||
if (readError || !existing) return 'duplicate'
|
||||
const row = existing as { id: string; delivery_status: string; sent_at: string | null }
|
||||
if (row.delivery_status !== 'pending') return 'duplicate'
|
||||
const staleCutoffIso = new Date(Date.now() - STALE_CLAIM_MS).toISOString()
|
||||
if (row.sent_at && row.sent_at > staleCutoffIso) return 'duplicate'
|
||||
|
||||
const { data: taken, error: takeError } = await supabase
|
||||
.from('notification_log')
|
||||
.update({ sent_at: new Date().toISOString() })
|
||||
.eq('id', row.id)
|
||||
.eq('delivery_status', 'pending')
|
||||
.lte('sent_at', staleCutoffIso)
|
||||
.select('id')
|
||||
if (takeError || !taken || taken.length === 0) return 'duplicate'
|
||||
return 'acquired'
|
||||
}
|
||||
|
||||
/**
|
||||
* Flip the claim to 'sent' after the provider accepted the mail. Best-effort:
|
||||
* if this update fails the claim stays 'pending' and a stale takeover could
|
||||
* resend, which is the accepted trade against silently losing the digest.
|
||||
*/
|
||||
async function markClaimSent(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
referenceUuid: string
|
||||
): Promise<void> {
|
||||
const { error } = await supabase
|
||||
.from('notification_log')
|
||||
.update({ delivery_status: 'sent', sent_at: new Date().toISOString() })
|
||||
.eq('user_id', userId)
|
||||
.eq('notification_type', 'bookkeeping_digest')
|
||||
.eq('reference_id', referenceUuid)
|
||||
if (error) {
|
||||
log.warn('could not mark digest claim sent', { userId, referenceUuid, error: error.message })
|
||||
}
|
||||
}
|
||||
|
||||
interface DigestEmailContent {
|
||||
subject: string
|
||||
text: string
|
||||
html: string
|
||||
}
|
||||
|
||||
/** Exported for tests: counts only, no amounts or counterparties. */
|
||||
export function buildDigestEmail(input: {
|
||||
companyName: string | null
|
||||
counts: DigestCounts
|
||||
baseUrl: string
|
||||
appName: string
|
||||
}): DigestEmailContent {
|
||||
const inCompany = input.companyName ? ` i ${input.companyName}` : ''
|
||||
const subject = `Nytt att bokföra${inCompany}`
|
||||
|
||||
const lines: string[] = []
|
||||
if (input.counts.newTransactions > 0) {
|
||||
lines.push(
|
||||
input.counts.newTransactions === 1
|
||||
? '1 ny banktransaktion att bokföra'
|
||||
: `${input.counts.newTransactions} nya banktransaktioner att bokföra`
|
||||
)
|
||||
}
|
||||
if (input.counts.newInboxItems > 0) {
|
||||
lines.push(
|
||||
input.counts.newInboxItems === 1
|
||||
? '1 nytt underlag i inkorgen'
|
||||
: `${input.counts.newInboxItems} nya underlag i inkorgen`
|
||||
)
|
||||
}
|
||||
|
||||
const intro = `Sedan igår har det kommit in nytt${inCompany ? ` till ${input.companyName}` : ''}:`
|
||||
const text = [
|
||||
intro,
|
||||
'',
|
||||
...lines.map((l) => `- ${l}`),
|
||||
'',
|
||||
`Logga in för att bokföra: ${input.baseUrl}`,
|
||||
'',
|
||||
`Du får det här mejlet för att du har slagit på daglig sammanfattning i ${input.appName}. Stäng av under Inställningar > Aviseringar.`,
|
||||
].join('\n')
|
||||
|
||||
const html = [
|
||||
`<p>${escapeHtml(intro)}</p>`,
|
||||
`<ul>${lines.map((l) => `<li>${escapeHtml(l)}</li>`).join('')}</ul>`,
|
||||
`<p><a href="${escapeHtml(input.baseUrl)}">Logga in för att bokföra</a></p>`,
|
||||
`<p style="color:#6b7280;font-size:12px">Du får det här mejlet för att du har slagit på daglig sammanfattning i ${escapeHtml(input.appName)}. Stäng av under Inställningar > Aviseringar.</p>`,
|
||||
].join('')
|
||||
|
||||
return { subject, text, html }
|
||||
}
|
||||
|
||||
/**
|
||||
* Member allowlist + emails for the given users, batched (not per-user
|
||||
* round-trips like resolveMemberEmail). Same two-step shape as
|
||||
* lib/notifications/member-email.ts and for the same reason: there is no FK
|
||||
* from company_members.user_id to profiles, so a PostgREST embed 400s.
|
||||
*/
|
||||
async function resolveCompanyMemberEmails(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userIds: string[]
|
||||
): Promise<Map<string, string>> {
|
||||
const emails = new Map<string, string>()
|
||||
const { data: members, error: memberError } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.in('user_id', userIds)
|
||||
if (memberError) {
|
||||
log.warn('could not read company members for digest recipients', {
|
||||
companyId,
|
||||
error: memberError.message,
|
||||
})
|
||||
return emails
|
||||
}
|
||||
const memberIds = (members ?? [])
|
||||
.map((m) => (m as { user_id: string | null }).user_id)
|
||||
.filter((id): id is string => typeof id === 'string')
|
||||
if (memberIds.length === 0) return emails
|
||||
|
||||
const { data: profiles, error: profileError } = await supabase
|
||||
.from('profiles')
|
||||
.select('id, email')
|
||||
.in('id', memberIds)
|
||||
if (profileError) {
|
||||
log.warn('could not read profile emails for digest recipients', {
|
||||
companyId,
|
||||
error: profileError.message,
|
||||
})
|
||||
return emails
|
||||
}
|
||||
for (const row of (profiles ?? []) as Array<{ id: string; email: string | null }>) {
|
||||
if (row.email) emails.set(row.id, row.email)
|
||||
}
|
||||
return emails
|
||||
}
|
||||
|
||||
/**
|
||||
* notification_log.reference_id is a uuid column, but the digest's natural
|
||||
* key is (company, date). Same deterministic SHA-256-to-uuid mapping as the
|
||||
* kvittens notification.
|
||||
*/
|
||||
function toReferenceUuid(referenceKey: string): string {
|
||||
const hex = createHash('sha256').update(referenceKey).digest('hex')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Company names are user-controlled and reach the Subject header: strip
|
||||
* CR/LF and other control characters so the value can never smuggle extra
|
||||
* mail headers.
|
||||
*/
|
||||
function sanitizeHeaderText(input: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return input.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* Recipient resolution for notification emails.
|
||||
*
|
||||
* Every outbound notification restricts its recipient to active members of
|
||||
* the company: a token owner, schedule owner, or configured contact who has
|
||||
* since been removed must never receive company mail (the bare existence of
|
||||
* some notifications is sensitive financial signal).
|
||||
*
|
||||
* The lookup is deliberately two queries. `company_members.user_id`
|
||||
* references auth.users, not public.profiles, so the PostgREST embed
|
||||
* `profiles!inner(email)` has no foreign-key relationship to traverse and
|
||||
* fails the whole query with a 400. That embed shipped in four notification
|
||||
* senders and silently killed all of them: the recipient resolved to null
|
||||
* and every mail was skipped as "no recipient". Adding the FK instead would
|
||||
* mean a migration on a core tenancy table for zero functional gain
|
||||
* (see DECISIONS.md 2026-08-25).
|
||||
*
|
||||
* Both functions are best-effort and never throw: a failed lookup logs and
|
||||
* resolves to "no recipient", because notification delivery must never fail
|
||||
* the sync/cron/reconciliation that triggered it. Logging alone is not the
|
||||
* safety net (the embed bug WAS logged by one caller and nobody read it):
|
||||
* callers verify delivery end to end after deploy.
|
||||
*
|
||||
* SERVICE-ROLE CLIENT REQUIRED. Under an RLS user client these lookups
|
||||
* silently degrade: company_members is readable company-wide, but the
|
||||
* profiles SELECT policy is own-row-only, so resolveMemberEmails would
|
||||
* return at most the caller's own email and resolveMemberEmail(other user)
|
||||
* always null. Every current caller is a service-role cron path; keep it
|
||||
* that way or widen the profiles policy first.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
|
||||
const log = createLogger('member-email')
|
||||
|
||||
/**
|
||||
* Resolve one user's email, only if they are still an active member of the
|
||||
* company. Returns null (never throws) when the user is not a member, has no
|
||||
* profile email, or a query fails.
|
||||
*/
|
||||
export async function resolveMemberEmail(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string
|
||||
): Promise<string | null> {
|
||||
const { data: member, error: memberError } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle()
|
||||
if (memberError) {
|
||||
log.warn('could not read company members for notification recipient', {
|
||||
companyId,
|
||||
userId,
|
||||
error: memberError.message,
|
||||
})
|
||||
return null
|
||||
}
|
||||
if (!member) return null
|
||||
|
||||
const { data: profile, error: profileError } = await supabase
|
||||
.from('profiles')
|
||||
.select('email')
|
||||
.eq('id', userId)
|
||||
.maybeSingle()
|
||||
if (profileError) {
|
||||
log.warn('could not read profile email for notification recipient', {
|
||||
companyId,
|
||||
userId,
|
||||
error: profileError.message,
|
||||
})
|
||||
return null
|
||||
}
|
||||
return (profile as { email?: string | null } | null)?.email ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve every active member's email for a company, as a map of
|
||||
* user_id → email. Used by senders that route to a configured contact
|
||||
* address but must verify it against the member allowlist (skattekonto
|
||||
* drift alert). Returns an empty map (never throws) on any query failure,
|
||||
* which callers treat as "no authorised recipient".
|
||||
*/
|
||||
export async function resolveMemberEmails(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string
|
||||
): Promise<Map<string, string>> {
|
||||
const emails = new Map<string, string>()
|
||||
|
||||
// fetchAllRows with stable ordering: PostgREST silently caps unpaged
|
||||
// reads at 1000 rows, which would drop members from the allowlist.
|
||||
let members: Array<{ user_id: string | null }>
|
||||
try {
|
||||
members = await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.order('user_id', { ascending: true })
|
||||
.range(from, to)
|
||||
)
|
||||
} catch (err) {
|
||||
log.warn('could not read company members for notification allowlist', {
|
||||
companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
return emails
|
||||
}
|
||||
|
||||
const userIds = members
|
||||
.map((m) => m.user_id)
|
||||
.filter((id): id is string => typeof id === 'string')
|
||||
if (userIds.length === 0) return emails
|
||||
|
||||
let profiles: Array<{ id: string; email: string | null }>
|
||||
try {
|
||||
profiles = await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('profiles')
|
||||
.select('id, email')
|
||||
.in('id', userIds)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to)
|
||||
)
|
||||
} catch (err) {
|
||||
log.warn('could not read member emails for notification allowlist', {
|
||||
companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
return emails
|
||||
}
|
||||
|
||||
for (const row of profiles) {
|
||||
if (row.email) emails.set(row.id, row.email)
|
||||
}
|
||||
return emails
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import {
|
||||
computeMultiUserState,
|
||||
MULTI_USER_GRACE_DAYS,
|
||||
type MultiUserGrantRow,
|
||||
} from '@/lib/entitlements/multi-user-state'
|
||||
import { isMultiUserEnforced } from '@/lib/entitlements/multi-user'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { getSenderForCompany, getBaseUrlForBrand } from '@/lib/email/brand-sender'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const logger = createLogger('notifications/multi-user-grace')
|
||||
|
||||
/**
|
||||
* Multi-user grace reminders: mails company OWNERS when the 20-day grace
|
||||
* window opens (their extra members will pause) and again on its last day.
|
||||
*
|
||||
* Windowing keeps the daily cron idempotent without a sent-log: with the
|
||||
* newest multi_user expiry E and grace end G = E + 20d,
|
||||
* "start" mail : E in (now - 24h, now] (the lapse happened since the
|
||||
* previous daily run)
|
||||
* "final" mail : G in (now, now + 24h] (the freeze lands before the
|
||||
* next daily run)
|
||||
* The two windows can only both hit for a sub-24h grace, which the 20-day
|
||||
* constant rules out. Companies with no non-owner members are skipped:
|
||||
* single-person companies must never hear about the seat gate.
|
||||
*
|
||||
* The launch cohort's mail is sent by hand (founder decision 2026-09-01);
|
||||
* this cron owns every FUTURE lapse: trial ends, subscription cancellations.
|
||||
*/
|
||||
|
||||
const DAY_MS = 86_400_000
|
||||
|
||||
export interface MultiUserGraceSummary {
|
||||
companiesInGrace: number
|
||||
startMails: number
|
||||
finalMails: number
|
||||
errors: number
|
||||
skipped?: 'not_enforced' | 'email_not_configured'
|
||||
}
|
||||
|
||||
interface GrantRow {
|
||||
company_id: string | null
|
||||
team_id: string | null
|
||||
expires_at: string | null
|
||||
metadata: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
interface TrackedGrant extends MultiUserGrantRow {
|
||||
metadata: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export async function runMultiUserGraceReminders(
|
||||
supabase: SupabaseClient,
|
||||
now: Date,
|
||||
): Promise<MultiUserGraceSummary> {
|
||||
const summary: MultiUserGraceSummary = {
|
||||
companiesInGrace: 0,
|
||||
startMails: 0,
|
||||
finalMails: 0,
|
||||
errors: 0,
|
||||
}
|
||||
if (!isMultiUserEnforced()) {
|
||||
summary.skipped = 'not_enforced'
|
||||
return summary
|
||||
}
|
||||
const emailService = getEmailService()
|
||||
if (!emailService.isConfigured()) {
|
||||
summary.skipped = 'email_not_configured'
|
||||
return summary
|
||||
}
|
||||
|
||||
// All multi_user grants in one read: the key has at most a handful of rows
|
||||
// per company, and the whole-table scan on one capability_key is what the
|
||||
// idx_capability_grants_key index exists for.
|
||||
const { data: grantRows, error: grantsError } = await supabase
|
||||
.from('capability_grants')
|
||||
.select('company_id, team_id, expires_at, metadata')
|
||||
.eq('capability_key', CAPABILITY.multi_user)
|
||||
if (grantsError) {
|
||||
throw new Error(`multi-user grace: grants read failed: ${grantsError.message}`)
|
||||
}
|
||||
const grants = (grantRows ?? []) as GrantRow[]
|
||||
|
||||
const companyGrants = new Map<string, TrackedGrant[]>()
|
||||
const teamGrants = new Map<string, TrackedGrant[]>()
|
||||
for (const g of grants) {
|
||||
if (g.company_id) {
|
||||
const list = companyGrants.get(g.company_id) ?? []
|
||||
list.push({ expires_at: g.expires_at, metadata: g.metadata })
|
||||
companyGrants.set(g.company_id, list)
|
||||
}
|
||||
if (g.team_id) {
|
||||
const list = teamGrants.get(g.team_id) ?? []
|
||||
list.push({ expires_at: g.expires_at, metadata: g.metadata })
|
||||
teamGrants.set(g.team_id, list)
|
||||
}
|
||||
}
|
||||
|
||||
if (companyGrants.size === 0 && teamGrants.size === 0) return summary
|
||||
|
||||
// Candidate companies: company-scoped grant holders PLUS every company of
|
||||
// a team that holds grants (a byrå whose team agreement lapses has client
|
||||
// companies with zero company-scoped rows, and their owners must be mailed
|
||||
// like anyone else's).
|
||||
const companies = new Map<string, { id: string; name: string; team_id: string | null }>()
|
||||
const companyIds = [...companyGrants.keys()]
|
||||
for (let i = 0; i < companyIds.length; i += 200) {
|
||||
const chunk = companyIds.slice(i, i + 200)
|
||||
const { data, error } = await supabase
|
||||
.from('companies')
|
||||
.select('id, name, team_id, archived_at')
|
||||
.in('id', chunk)
|
||||
.is('archived_at', null)
|
||||
if (error) throw new Error(`multi-user grace: companies read failed: ${error.message}`)
|
||||
for (const c of (data ?? []) as { id: string; name: string; team_id: string | null }[]) {
|
||||
companies.set(c.id, c)
|
||||
}
|
||||
}
|
||||
const teamIds = [...teamGrants.keys()]
|
||||
for (let i = 0; i < teamIds.length; i += 200) {
|
||||
const chunk = teamIds.slice(i, i + 200)
|
||||
const { data, error } = await supabase
|
||||
.from('companies')
|
||||
.select('id, name, team_id, archived_at')
|
||||
.in('team_id', chunk)
|
||||
.is('archived_at', null)
|
||||
if (error) throw new Error(`multi-user grace: team companies read failed: ${error.message}`)
|
||||
for (const c of (data ?? []) as { id: string; name: string; team_id: string | null }[]) {
|
||||
companies.set(c.id, c)
|
||||
}
|
||||
}
|
||||
|
||||
const nowMs = now.getTime()
|
||||
for (const company of companies.values()) {
|
||||
const rows = [
|
||||
...(companyGrants.get(company.id) ?? []),
|
||||
...(company.team_id ? (teamGrants.get(company.team_id) ?? []) : []),
|
||||
]
|
||||
const access = computeMultiUserState(rows, nowMs)
|
||||
if (access.state !== 'grace' || !access.graceEndsAt) continue
|
||||
summary.companiesInGrace += 1
|
||||
|
||||
const graceEndMs = new Date(access.graceEndsAt).getTime()
|
||||
const lapseMs = graceEndMs - MULTI_USER_GRACE_DAYS * DAY_MS
|
||||
// The launch cohort's start mail is sent by hand (founder decision
|
||||
// 2026-09-01): the grandfather backfill row expires at deploy time, so
|
||||
// without this check the first cron run after deploy would re-mail the
|
||||
// whole cohort. The day-19 final reminder still goes out.
|
||||
const anchorIsGrandfather = rows.some(
|
||||
(r) =>
|
||||
r.expires_at !== null &&
|
||||
new Date(r.expires_at).getTime() === lapseMs &&
|
||||
(r.metadata as { reason?: string } | null)?.reason === 'multi_user_grandfather',
|
||||
)
|
||||
const isStart = !anchorIsGrandfather && lapseMs > nowMs - DAY_MS && lapseMs <= nowMs
|
||||
const isFinal = graceEndMs > nowMs && graceEndMs <= nowMs + DAY_MS
|
||||
if (!isStart && !isFinal) continue
|
||||
|
||||
try {
|
||||
const sent = await sendGraceMail(supabase, {
|
||||
companyId: company.id,
|
||||
companyName: company.name,
|
||||
kind: isFinal ? 'final' : 'start',
|
||||
graceEndsAt: access.graceEndsAt,
|
||||
})
|
||||
if (sent === 0) continue
|
||||
if (isFinal) summary.finalMails += sent
|
||||
else summary.startMails += sent
|
||||
} catch (err) {
|
||||
summary.errors += 1
|
||||
logger.error('multi-user grace mail failed', err as Error, { companyId: company.id })
|
||||
}
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
|
||||
async function sendGraceMail(
|
||||
supabase: SupabaseClient,
|
||||
args: { companyId: string; companyName: string; kind: 'start' | 'final'; graceEndsAt: string },
|
||||
): Promise<number> {
|
||||
// Sandbox/demo companies have no billing: never mail them.
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('is_sandbox, company_name')
|
||||
.eq('company_id', args.companyId)
|
||||
.maybeSingle()
|
||||
if ((settings as { is_sandbox?: boolean } | null)?.is_sandbox === true) return 0
|
||||
const companyName =
|
||||
(settings as { company_name?: string | null } | null)?.company_name || args.companyName
|
||||
|
||||
const { data: members } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id, role')
|
||||
.eq('company_id', args.companyId)
|
||||
const memberRows = (members ?? []) as { user_id: string; role: string }[]
|
||||
const affected = memberRows.filter((m) => m.role !== 'owner')
|
||||
// Single-person companies never hear about the seat gate.
|
||||
if (affected.length === 0) return 0
|
||||
const owners = memberRows.filter((m) => m.role === 'owner')
|
||||
if (owners.length === 0) return 0
|
||||
|
||||
const { data: profiles } = await supabase
|
||||
.from('profiles')
|
||||
.select('id, email')
|
||||
.in('id', memberRows.map((m) => m.user_id))
|
||||
const emailById = new Map(
|
||||
((profiles ?? []) as { id: string; email: string | null }[]).map((p) => [p.id, p.email]),
|
||||
)
|
||||
const ownerEmails = owners.map((o) => emailById.get(o.user_id)).filter((e): e is string => !!e)
|
||||
const affectedEmails = affected
|
||||
.map((a) => emailById.get(a.user_id))
|
||||
.filter((e): e is string => !!e)
|
||||
if (ownerEmails.length === 0) return 0
|
||||
|
||||
const sender = await getSenderForCompany(args.companyId)
|
||||
const appUrl = sender.brand ? getBaseUrlForBrand(sender.brand) : getBranding().appUrl
|
||||
const billingUrl = `${appUrl}/settings/billing`
|
||||
const freezeDate = formatDate(args.graceEndsAt)
|
||||
const affectedList = affectedEmails.join(', ')
|
||||
|
||||
const subject =
|
||||
args.kind === 'final'
|
||||
? `Imorgon pausas fler användare i ${companyName}`
|
||||
: `Fler användare i ${companyName} kräver betald plan`
|
||||
const intro =
|
||||
args.kind === 'final'
|
||||
? `Imorgon (${freezeDate}) pausas följande konton från ${companyName}: ${affectedList}.`
|
||||
: `Från och med den ${freezeDate} ingår flera användare endast i den betalda planen. Då pausas följande konton från ${companyName}: ${affectedList}.`
|
||||
const outro =
|
||||
'Ingen data försvinner och inga användare tas bort. Uppgraderar ni, nu eller senare, ' +
|
||||
'får alla tillbaka sin åtkomst direkt.'
|
||||
const body = `Hej!\n\n${intro}\n\n${outro}\n\nUppgradera här: ${billingUrl}\n`
|
||||
const html =
|
||||
`<p>Hej!</p><p>${intro}</p><p>${outro}</p>` +
|
||||
`<p><a href="${billingUrl}">Uppgradera till betald plan</a></p>`
|
||||
|
||||
const emailService = getEmailService()
|
||||
let sent = 0
|
||||
for (const to of ownerEmails) {
|
||||
const result = await emailService.sendEmail({
|
||||
to,
|
||||
subject,
|
||||
html,
|
||||
text: body,
|
||||
fromName: sender.fromName ?? undefined,
|
||||
fromAddress: sender.fromAddress ?? undefined,
|
||||
replyTo: sender.replyTo ?? undefined,
|
||||
})
|
||||
if (result.success) sent += 1
|
||||
else logger.warn('multi-user grace mail send failed', { companyId: args.companyId })
|
||||
}
|
||||
return sent
|
||||
}
|
||||
Reference in New Issue
Block a user