* feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker - SIE import preserves each voucher's source series (B/C/I/V/...), essential for Fortnox migrations where series carry semantic meaning (kundfakturor, inbetalningar, etc.). Target numbering still goes through next_voucher_number per series; source (series, number) is stored in the migration mapping for BFNAR 2013:2 audit trail. - Execute route reads company_settings.default_voucher_series as the fallback for vouchers arriving without a series (SIE4I). - Extract shared FiscalYearSelector component; adopt in /reports and /bookkeeping. - Transaction TemplatePicker now surfaces user-created library templates (company + team scope) alongside the static registry, with a helper to convert simple library templates into the BookingTemplate shape. - Exclude 8999 "Årets resultat" from income statement financial section and monthly breakdown so year-end closing entries don't cancel the net result. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: skip Bokio SIE regression when fixtures are absent /dev_docs is gitignored (contains anonymised customer exports), so the integration test can't find its input files in CI. Gate the suite on fixture presence so it still runs locally. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address Greptile review feedback - convertLibraryToBookingTemplate: default entity_applicability to 'all' when the source template has no entity_type, so TemplatePicker doesn't silently hide it for companies with a set entity type. - FiscalYearSelector: fire onReady in the no-company early-return branch so consumers (e.g. ReportsPage) don't get stuck in a loading skeleton while the company context is still hydrating. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: arcim inbox + smart-match extension + commit metadata Three threads, all gated off in extensions.config.json (invoice-inbox and inbox-smart-match are not in the enabled list for this PR). invoice-inbox: Gmail OAuth -> Resend Inbound (v2.0.0) - Remove gmail-scanner / gmail-helpers - Add resend-inbound.ts (webhook verify, attachment fetch) and inbox-provisioning.ts (per-company @arcim.io address with rotation) - Replace /gmail/* routes with /inbox/address and admin-only /inbox/rotate - Workspace UI: card layout + MatchBlock surfacing AI transaction matches - classify-document: tightened discount/total prompt; cap confidence at 50% when line items do not reconcile with amount_incl_vat - Manifest requires RESEND_API_KEY, RESEND_INBOUND_DOMAIN, RESEND_INBOUND_WEBHOOK_SECRET inbox-smart-match (new extension) - Event-driven AI matching of receipts to bank transactions - Listens on inbox_item.classified (match now) and transaction.synced (retro-match receipts waiting for a transaction) - Uses service-role client; processing_history append is scoped by company_id from the event payload commit metadata + audit plumbing - journal_entries gains commit_method and rubric_version columns - commit_journal_entry RPC accepts both (BFNAR 2013:2 behandlingshistorik) - processing-history PII detector strips UUID-shaped substrings before personnummer pattern matching (UUIDs were triggering false positives) - New generic inbox_item.classified event Migrations - arcim_inbox: company_inboxes table, resend_email_id, email_body_text, auto-provision trigger, drops obsolete email_connections - journal_entry_commit_metadata: new columns + updated RPC - inbox_attachment_composite: resend_attachment_id + composite unique index - inbox_smart_match: correlation_id, match_reasoning, expanded match_method CHECK, pending-match and correlation indexes Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
214 lines
8.0 KiB
TypeScript
214 lines
8.0 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
import { invoiceInboxExtension } from '@/extensions/general/invoice-inbox'
|
|
import { ResendSignatureError } from '@/extensions/general/invoice-inbox/lib/resend-inbound'
|
|
import { createQueuedMockSupabase, createMockRequest } from '@/tests/helpers'
|
|
|
|
vi.mock('@/extensions/general/invoice-inbox/lib/resend-inbound', async () => {
|
|
const actual = await vi.importActual<typeof import('@/extensions/general/invoice-inbox/lib/resend-inbound')>(
|
|
'@/extensions/general/invoice-inbox/lib/resend-inbound'
|
|
)
|
|
return {
|
|
...actual,
|
|
verifyInboundWebhook: vi.fn(),
|
|
fetchReceivingEmail: vi.fn(),
|
|
fetchInboundAttachment: vi.fn(),
|
|
}
|
|
})
|
|
|
|
vi.mock('@supabase/supabase-js', () => ({
|
|
createClient: vi.fn(),
|
|
}))
|
|
|
|
import { verifyInboundWebhook, fetchReceivingEmail, fetchInboundAttachment } from '@/extensions/general/invoice-inbox/lib/resend-inbound'
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
function findRoute(method: string, path: string) {
|
|
return invoiceInboxExtension.apiRoutes!.find((r) => r.method === method && r.path === path)!
|
|
}
|
|
|
|
const webhookRoute = findRoute('POST', '/inbound')
|
|
|
|
function mockReceivedEvent(overrides?: Record<string, unknown>) {
|
|
return {
|
|
type: 'email.received' as const,
|
|
created_at: '2026-04-20T10:00:00Z',
|
|
data: {
|
|
email_id: 'em_123',
|
|
created_at: '2026-04-20T10:00:00Z',
|
|
from: 'billing@supplier.com',
|
|
to: ['acme-ab-x7f2@arcim.io'],
|
|
cc: [],
|
|
bcc: [],
|
|
subject: 'Invoice #5678',
|
|
message_id: '<msg-id@supplier.com>',
|
|
attachments: [
|
|
{
|
|
id: 'att_1',
|
|
filename: 'invoice.pdf',
|
|
size: 12345,
|
|
content_type: 'application/pdf',
|
|
content_id: 'cid1',
|
|
content_disposition: 'attachment',
|
|
},
|
|
],
|
|
...overrides,
|
|
},
|
|
}
|
|
}
|
|
|
|
describe('POST /inbound', () => {
|
|
const originalEnv = { ...process.env }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
process.env.RESEND_INBOUND_DOMAIN = 'arcim.io'
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL = 'http://localhost'
|
|
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
|
})
|
|
|
|
afterEach(() => {
|
|
process.env = { ...originalEnv }
|
|
})
|
|
|
|
it('returns 503 when RESEND_INBOUND_DOMAIN is not set', async () => {
|
|
delete process.env.RESEND_INBOUND_DOMAIN
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: { type: 'email.received' } })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(503)
|
|
})
|
|
|
|
it('returns 401 when signature verification fails', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockImplementation(() => {
|
|
throw new ResendSignatureError('bad sig')
|
|
})
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: { type: 'email.received' } })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(401)
|
|
})
|
|
|
|
it('ignores non-received events with 200', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue({
|
|
type: 'email.sent',
|
|
created_at: '',
|
|
data: {},
|
|
} as never)
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(200)
|
|
})
|
|
|
|
it('returns 404 when no recipient matches our domain', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
|
mockReceivedEvent({ to: ['random@contoso.com'] }) as never
|
|
)
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(404)
|
|
})
|
|
|
|
it('returns 404 when the address is not in company_inboxes', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(mockReceivedEvent() as never)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: null }) // company_inboxes lookup returns nothing
|
|
vi.mocked(createClient).mockReturnValue(supabase as never)
|
|
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(404)
|
|
})
|
|
|
|
it('returns 410 when the address is deprecated', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(mockReceivedEvent() as never)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'inbox-1', company_id: 'company-1', status: 'deprecated' } })
|
|
vi.mocked(createClient).mockReturnValue(supabase as never)
|
|
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(410)
|
|
})
|
|
|
|
it('skips already-processed attachments (per-attachment idempotency)', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(mockReceivedEvent() as never)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'inbox-1', company_id: 'company-1', status: 'active' } }) // inbox lookup
|
|
enqueue({ data: { created_by: 'user-owner-1' } }) // company owner
|
|
enqueue({ data: { id: 'existing-item-1' } }) // per-attachment dup check finds existing row
|
|
vi.mocked(createClient).mockReturnValue(supabase as never)
|
|
vi.mocked(fetchReceivingEmail).mockResolvedValue({
|
|
object: 'email',
|
|
id: 'em_123',
|
|
to: ['acme-ab-x7f2@arcim.io'],
|
|
from: 'billing@supplier.com',
|
|
created_at: '2026-04-20T10:00:00Z',
|
|
subject: 'Invoice #5678',
|
|
bcc: null,
|
|
cc: null,
|
|
reply_to: null,
|
|
html: null,
|
|
text: 'Body',
|
|
headers: {},
|
|
message_id: '<msg@x>',
|
|
raw: null,
|
|
attachments: [
|
|
{ id: 'att_1', filename: 'invoice.pdf', size: 100, content_type: 'application/pdf', content_id: 'cid', content_disposition: 'attachment' },
|
|
],
|
|
} as never)
|
|
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
const body = await res.json()
|
|
expect(res.status).toBe(200)
|
|
expect(body.data.results[0].duplicate).toBe(true)
|
|
expect(body.data.results[0].inbox_item_id).toBe('existing-item-1')
|
|
expect(fetchInboundAttachment).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('returns 500 when the company has no created_by owner', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(mockReceivedEvent() as never)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'inbox-1', company_id: 'company-1', status: 'active' } })
|
|
enqueue({ data: { created_by: null } }) // company with no owner
|
|
vi.mocked(createClient).mockReturnValue(supabase as never)
|
|
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
expect(res.status).toBe(500)
|
|
})
|
|
|
|
it('logs an error inbox item when email has no attachments', async () => {
|
|
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
|
mockReceivedEvent({ attachments: [] }) as never
|
|
)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'inbox-1', company_id: 'company-1', status: 'active' } })
|
|
enqueue({ data: { created_by: 'user-owner-1' } })
|
|
enqueue({ data: null }) // insert succeeds
|
|
vi.mocked(createClient).mockReturnValue(supabase as never)
|
|
vi.mocked(fetchReceivingEmail).mockResolvedValue({
|
|
object: 'email',
|
|
id: 'em_123',
|
|
to: ['acme-ab-x7f2@arcim.io'],
|
|
from: 'billing@supplier.com',
|
|
created_at: '2026-04-20T10:00:00Z',
|
|
subject: 'No attachments here',
|
|
bcc: null,
|
|
cc: null,
|
|
reply_to: null,
|
|
html: null,
|
|
text: 'Body only',
|
|
headers: {},
|
|
message_id: '<msg@x>',
|
|
raw: null,
|
|
attachments: [],
|
|
} as never)
|
|
|
|
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
|
const res = await webhookRoute.handler(request)
|
|
const body = await res.json()
|
|
expect(res.status).toBe(200)
|
|
expect(body.data.reason).toBe('no_attachments')
|
|
expect(fetchInboundAttachment).not.toHaveBeenCalled()
|
|
})
|
|
})
|