Files
accounted/extensions/general/receipt-ocr/lib/__tests__/receipt-pipeline.test.ts
T
MattssonandClaude Opus 4.6 0dd1f5ebc1 feat: multi-tenant company refactor (GNU-19) (#153)
* feat: multi-tenant company refactor (GNU-19)

Introduce companies table, company_members, and user_preferences to
support multiple companies per user. All data scoping changes from
user_id to company_id across the entire codebase.

Key changes:
- Database migration: new tables, company_id on 40+ tables, backfill,
  RLS rewrite from user_id to company-member-based, updated RPCs
- Types: Company, CompanyMember, CompanyRole, UserPreferences types;
  company_id added to all entity interfaces; companyId on all events
- Engine: all 7 core functions take companyId; storno, period, year-end
  services updated; 16 report generators updated
- Middleware: company context resolution (cookie → prefs → first company)
- API routes: ~120 routes updated with requireCompanyId()
- Frontend: CompanyProvider context, layout/dashboard/onboarding updated
- Extensions: context factory, 9 extensions, all lib files updated
- Tests: 1880 tests passing, all helpers updated with company_id defaults

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add database migrations for multi-tenant company and team system (GNU-19)

Adds company_invitations, company creation RPC, team_members, account
deletion RPC, and teams table refactor migrations. Updates base
multi-tenant migration with cascading FKs and onboarding_step column.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add team types and update core infrastructure for multi-tenancy (GNU-19)

Adds TeamRole, MemberSource, and Team types. Refactors Supabase service
client to be stateless, updates middleware for team-aware routing, extends
CompanyContext with team/role fields, and updates extension service types
to accept companyId.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: thread company_id through business logic functions (GNU-19)

Replaces user_id scoping with company_id across all lib modules:
bookkeeping, documents, transactions, invoices, reconciliation, tax,
deadlines, and import. Updates corresponding tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: thread company_id through API routes and extensions (GNU-19)

Updates all existing API routes to extract and pass companyId. Updates
enable-banking and arcim-migration extensions for company-scoped
transaction ingestion and sync.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add company and team management API routes (GNU-19)

Adds CRUD endpoints for company members, company invitations, team
members, and team invitations. Includes invite token utilities, email
templates, and company switch server action.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add team/company UI components, pages, and dashboard updates (GNU-19)

Adds CompanySwitcher, ConsultantEmptyState, Step0RoleChoice, company
members and team management panels. Updates dashboard layout for
team-aware routing, onboarding for multi-step role choice, and auth
callback for team invite acceptance. Ignores supabase/.branches/.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add null guards for company in import page (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: move appUrl declaration to outer scope in invite route (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add optional chaining for company.name in members section (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add optional chaining for second company.name in members section (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add null guards for company in extension components (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: pass companyId to executeSIEImport in arcim-migration extension (GNU-19)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: update tests to use companyId instead of userId and improve type handling

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:41:52 +02:00

185 lines
5.5 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
// Mock server-only
vi.mock('server-only', () => ({}))
// Mock receipt analyzer
vi.mock('../receipt-analyzer', () => ({
analyzeReceipt: vi.fn(),
}))
// Mock receipt categorizer
vi.mock('../receipt-categorizer', () => ({
processLineItems: vi.fn(),
getDefaultClassification: vi.fn().mockReturnValue({
defaultIsBusiness: true,
requiresReview: false,
warningMessage: null,
}),
}))
// Mock receipt matcher
vi.mock('../receipt-matcher', () => ({
autoMatchReceipts: vi.fn(),
}))
// Mock event bus
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: vi.fn(), clear: vi.fn() },
}))
import { processReceiptFromDocument } from '../receipt-pipeline'
import { analyzeReceipt } from '../receipt-analyzer'
import { processLineItems } from '../receipt-categorizer'
import { autoMatchReceipts } from '../receipt-matcher'
function createMockSupabase() {
const mockResult = { data: null, error: null }
const chain = {
insert: vi.fn().mockReturnThis(),
update: vi.fn().mockReturnThis(),
select: vi.fn().mockReturnThis(),
single: vi.fn().mockImplementation(() => Promise.resolve(mockResult)),
eq: vi.fn().mockReturnThis(),
is: vi.fn().mockReturnThis(),
lt: vi.fn().mockReturnThis(),
gte: vi.fn().mockReturnThis(),
lte: vi.fn().mockReturnThis(),
}
const supabase = {
from: vi.fn().mockReturnValue(chain),
}
return { supabase, chain, setResult: (data: unknown, error: unknown = null) => {
mockResult.data = data as null
mockResult.error = error as null
} }
}
const mockExtraction = {
merchant: {
name: 'ICA Maxi',
orgNumber: '556123-4567',
vatNumber: null,
isForeign: false,
},
receipt: {
date: '2024-06-15',
time: '14:30',
currency: 'SEK',
},
lineItems: [
{ description: 'Mjölk', quantity: 1, unitPrice: 15, lineTotal: 15, vatRate: 12, suggestedCategory: 'other' },
],
totals: { subtotal: 13.39, vatAmount: 1.61, total: 15 },
flags: { isRestaurant: false, isSystembolaget: false, isForeignMerchant: false },
confidence: 0.92,
}
describe('processReceiptFromDocument', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
vi.mocked(analyzeReceipt).mockResolvedValue(mockExtraction)
vi.mocked(processLineItems).mockReturnValue([
{ ...mockExtraction.lineItems[0], category: 'expense_other' as const, basAccount: '6991', confidence: 0.8 },
])
vi.mocked(autoMatchReceipts).mockReturnValue([])
})
it('creates receipt record with extracted data', async () => {
const { supabase, chain, setResult } = createMockSupabase()
const receipt = {
id: 'receipt-1',
user_id: 'user-1',
status: 'extracted',
merchant_name: 'ICA Maxi',
total_amount: 15,
receipt_date: '2024-06-15',
}
// First from() = receipts insert
setResult(receipt)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await processReceiptFromDocument(supabase as any, 'user-1', 'company-1', 'base64data', 'image/jpeg', {
documentId: 'doc-1',
source: 'email',
emailFrom: 'sender@example.com',
storageUrl: 'https://storage.example.com/file.jpg',
})
expect(result.receipt.id).toBe('receipt-1')
expect(analyzeReceipt).toHaveBeenCalledWith('base64data', 'image/jpeg')
expect(processLineItems).toHaveBeenCalledWith(mockExtraction.lineItems)
// Verify receipt insert includes source and email_from
expect(chain.insert).toHaveBeenCalledWith(
expect.objectContaining({
source: 'email',
email_from: 'sender@example.com',
document_id: 'doc-1',
})
)
})
it('emits receipt.extracted event', async () => {
const { supabase, setResult } = createMockSupabase()
const receipt = { id: 'receipt-1', user_id: 'user-1' }
setResult(receipt)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await processReceiptFromDocument(supabase as any, 'user-1', 'company-1', 'base64data', 'image/jpeg', {
documentId: 'doc-1',
source: 'upload',
storageUrl: 'https://storage.example.com/file.jpg',
})
expect(eventBus.emit).toHaveBeenCalledWith({
type: 'receipt.extracted',
payload: expect.objectContaining({
receipt,
documentId: 'doc-1',
confidence: 0.92,
userId: 'user-1',
companyId: 'company-1',
}),
})
})
it('throws when receipt insert fails', async () => {
const { supabase, setResult } = createMockSupabase()
setResult(null, { message: 'insert failed' })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await expect(processReceiptFromDocument(supabase as any, 'user-1', 'company-1', 'base64data', 'image/jpeg', {
documentId: null,
source: 'upload',
storageUrl: 'https://storage.example.com/file.jpg',
})).rejects.toThrow('Failed to create receipt')
})
it('sets email_from to null when not provided', async () => {
const { supabase, chain, setResult } = createMockSupabase()
setResult({ id: 'receipt-1', user_id: 'user-1' })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await processReceiptFromDocument(supabase as any, 'user-1', 'company-1', 'base64data', 'image/jpeg', {
documentId: null,
source: 'upload',
storageUrl: 'https://storage.example.com/file.jpg',
})
expect(chain.insert).toHaveBeenCalledWith(
expect.objectContaining({
source: 'upload',
email_from: null,
})
)
})
})