* feat: event log, pending operations, and MCP staging - Event log system: persist bus events to event_log table for external automation platforms. Batch insert for transaction.synced. Daily cleanup cron at 02:00 UTC. - Pending operations: MCP write tools (categorize, create customer, create invoice) now stage to pending_operations instead of executing directly. Users review and commit/reject from /pending in the web UI. - Granskning page: card-based review UI with expandable previews, commit/reject dialogs. Only shown in nav when pending ops exist. - Commit route re-executes using core lib functions (no extension imports). Guards against stale state (double-commit, deleted entities). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: stage new MCP write tools after main merge Add staging for 4 new write tools from #133: - mark_invoice_paid, send_invoice, mark_invoice_sent, match_transaction_invoice - Expand pending_operations CHECK constraint - Add commit executors with full execution logic - Add UI labels and generic preview component - Remove confirm parameter from categorize (single-call staging) - Fix UUID in pending op title (fetch transaction description) - Hide Granskning nav when no pending ops Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review feedback - Fix TS build error: use `select('*, customer:customers(*)')` for match_transaction_invoice to avoid array type inference - Add status guard to commitSendInvoice (prevents duplicate sends) - Replace auth.admin.getUserById with user email from session auth - Restore optimistic lock check in commitMatchTransactionInvoice - Fix tool description typo: expense_software → expense_office Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
211 lines
6.4 KiB
TypeScript
211 lines
6.4 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import {
|
|
createMockRequest,
|
|
parseJsonResponse,
|
|
createQueuedMockSupabase,
|
|
} from '@/tests/helpers'
|
|
|
|
// Mock supabase server (session auth)
|
|
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: () => Promise.resolve(mockSupabase),
|
|
}))
|
|
|
|
// Mock API key auth
|
|
const mockValidateApiKey = vi.fn()
|
|
const mockExtractBearerToken = vi.fn()
|
|
const mockCreateServiceClientNoCookies = vi.fn()
|
|
vi.mock('@/lib/auth/api-keys', () => ({
|
|
validateApiKey: (...args: unknown[]) => mockValidateApiKey(...args),
|
|
extractBearerToken: (...args: unknown[]) => mockExtractBearerToken(...args),
|
|
createServiceClientNoCookies: () => mockCreateServiceClientNoCookies(),
|
|
}))
|
|
|
|
import { GET } from '../route'
|
|
|
|
describe('GET /api/events', () => {
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
|
|
const sampleEvents = [
|
|
{
|
|
sequence: 1,
|
|
event_type: 'invoice.created',
|
|
entity_id: 'inv-1',
|
|
data: { invoice: { id: 'inv-1', total: 1000 } },
|
|
created_at: '2026-03-25T10:00:00Z',
|
|
},
|
|
{
|
|
sequence: 2,
|
|
event_type: 'customer.created',
|
|
entity_id: 'cust-1',
|
|
data: { customer: { id: 'cust-1', name: 'Acme AB' } },
|
|
created_at: '2026-03-25T10:01:00Z',
|
|
},
|
|
]
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
mockExtractBearerToken.mockReturnValue(null)
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
|
})
|
|
|
|
it('returns 401 when not authenticated', async () => {
|
|
mockExtractBearerToken.mockReturnValue(null)
|
|
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('returns events with session auth', async () => {
|
|
enqueue({ data: sampleEvents })
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: typeof sampleEvents
|
|
cursor: number
|
|
has_more: boolean
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(2)
|
|
expect(body.cursor).toBe(2)
|
|
expect(body.has_more).toBe(false)
|
|
})
|
|
|
|
it('returns events with API key auth', async () => {
|
|
mockExtractBearerToken.mockReturnValue('gnubok_sk_test123')
|
|
mockValidateApiKey.mockResolvedValue({ userId: 'user-1' })
|
|
|
|
const apiKeySupabase = createQueuedMockSupabase()
|
|
apiKeySupabase.enqueue({ data: sampleEvents })
|
|
mockCreateServiceClientNoCookies.mockReturnValue(apiKeySupabase.supabase)
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: typeof sampleEvents
|
|
cursor: number
|
|
has_more: boolean
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(2)
|
|
expect(mockValidateApiKey).toHaveBeenCalledWith('gnubok_sk_test123')
|
|
})
|
|
|
|
it('returns 401 for invalid API key', async () => {
|
|
mockExtractBearerToken.mockReturnValue('gnubok_sk_invalid')
|
|
mockValidateApiKey.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Invalid API key' })
|
|
})
|
|
|
|
it('returns 429 for rate-limited API key', async () => {
|
|
mockExtractBearerToken.mockReturnValue('gnubok_sk_limited')
|
|
mockValidateApiKey.mockResolvedValue({ error: 'Rate limit exceeded', status: 429 })
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(429)
|
|
})
|
|
|
|
it('supports after cursor parameter', async () => {
|
|
enqueue({ data: [sampleEvents[1]] })
|
|
|
|
const request = createMockRequest('/api/events', {
|
|
searchParams: { after: '1' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: typeof sampleEvents
|
|
cursor: number
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(1)
|
|
expect(body.cursor).toBe(2)
|
|
})
|
|
|
|
it('supports types filter parameter', async () => {
|
|
enqueue({ data: [sampleEvents[0]] })
|
|
|
|
const request = createMockRequest('/api/events', {
|
|
searchParams: { types: 'invoice.created' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: typeof sampleEvents
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toHaveLength(1)
|
|
})
|
|
|
|
it('returns has_more=true when results equal limit', async () => {
|
|
// Return exactly `limit` items to trigger has_more
|
|
const events = Array.from({ length: 2 }, (_, i) => ({
|
|
sequence: i + 1,
|
|
event_type: 'invoice.created',
|
|
entity_id: `inv-${i}`,
|
|
data: {},
|
|
created_at: '2026-03-25T10:00:00Z',
|
|
}))
|
|
enqueue({ data: events })
|
|
|
|
const request = createMockRequest('/api/events', {
|
|
searchParams: { limit: '2' },
|
|
})
|
|
const response = await GET(request)
|
|
const { body } = await parseJsonResponse<{ has_more: boolean }>(response)
|
|
|
|
expect(body.has_more).toBe(true)
|
|
})
|
|
|
|
it('returns cursor=0 when no events and no after param', async () => {
|
|
enqueue({ data: [] })
|
|
|
|
const request = createMockRequest('/api/events')
|
|
const response = await GET(request)
|
|
const { body } = await parseJsonResponse<{ cursor: number; data: unknown[] }>(response)
|
|
|
|
expect(body.data).toHaveLength(0)
|
|
expect(body.cursor).toBe(0)
|
|
})
|
|
|
|
it('returns cursor=after when no events but after param provided', async () => {
|
|
enqueue({ data: [] })
|
|
|
|
const request = createMockRequest('/api/events', {
|
|
searchParams: { after: '42' },
|
|
})
|
|
const response = await GET(request)
|
|
const { body } = await parseJsonResponse<{ cursor: number }>(response)
|
|
|
|
expect(body.cursor).toBe(42)
|
|
})
|
|
|
|
it('rejects invalid limit parameter', async () => {
|
|
const request = createMockRequest('/api/events', {
|
|
searchParams: { limit: '999' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(400)
|
|
})
|
|
})
|