Files
accounted/extensions/general/enable-banking/lib/__tests__/sync.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

170 lines
5.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
// Mock api-client
const mockGetAllTransactionsWithRaw = vi.fn()
const mockConvertTransaction = vi.fn()
const mockGetAccountBalance = vi.fn()
vi.mock('../api-client', () => ({
getAllTransactionsWithRaw: (...args: unknown[]) => mockGetAllTransactionsWithRaw(...args),
convertTransaction: (...args: unknown[]) => mockConvertTransaction(...args),
getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args),
}))
// Mock document service
const mockUploadDocument = vi.fn()
vi.mock('@/lib/core/documents/document-service', () => ({
uploadDocument: (...args: unknown[]) => mockUploadDocument(...args),
}))
// Mock ingest
const mockIngest = vi.fn()
import { syncAccountTransactions } from '../sync'
import type { StoredAccount } from '../../types'
const USER_ID = 'user-1'
const COMPANY_ID = 'company-1'
const CONNECTION_ID = 'conn-1'
function makeAccount(overrides: Partial<StoredAccount> = {}): StoredAccount {
return {
uid: 'acc-uid-1',
currency: 'SEK',
...overrides,
}
}
describe('syncAccountTransactions', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetAccountBalance.mockRejectedValue(new Error('skip'))
mockIngest.mockResolvedValue({ imported: 1, duplicates: 0, errors: 0, reconciled: 0, auto_categorized: 0, auto_matched_invoices: 0, transaction_ids: ['tx-1'] })
})
it('calls uploadDocument for each raw page with correct filename pattern', async () => {
const rawPage1 = JSON.stringify({ transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }] })
const rawPage2 = JSON.stringify({ transactions: [{ transaction_amount: { amount: '200', currency: 'SEK' } }] })
mockGetAllTransactionsWithRaw.mockResolvedValue({
transactions: [
{ transaction_amount: { amount: '100', currency: 'SEK' } },
{ transaction_amount: { amount: '200', currency: 'SEK' } },
],
rawPages: [rawPage1, rawPage2],
})
mockConvertTransaction.mockImplementation((tx: { transaction_amount: { amount: string } }) => ({
id: `tx-${tx.transaction_amount.amount}`,
date: '2024-06-15',
booking_date: '2024-06-15',
amount: parseFloat(tx.transaction_amount.amount),
currency: 'SEK',
description: 'Test',
}))
mockUploadDocument.mockResolvedValue({ id: 'doc-1' })
const account = makeAccount()
await syncAccountTransactions(
{} as never,
COMPANY_ID,
USER_ID,
CONNECTION_ID,
account,
'2024-01-01',
'2024-12-31',
mockIngest
)
expect(mockUploadDocument).toHaveBeenCalledTimes(2)
// Verify filename pattern
const firstCall = mockUploadDocument.mock.calls[0]
expect(firstCall[3].name).toMatch(/^psd2-response_conn-1_acc-uid-1_.*_p1\.json$/)
expect(firstCall[3].type).toBe('application/json')
expect(firstCall[4]).toEqual({ upload_source: 'api' })
const secondCall = mockUploadDocument.mock.calls[1]
expect(secondCall[3].name).toMatch(/^psd2-response_conn-1_acc-uid-1_.*_p2\.json$/)
})
it('completes sync even if uploadDocument throws', async () => {
mockGetAllTransactionsWithRaw.mockResolvedValue({
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
rawPages: ['{"transactions":[]}'],
})
mockConvertTransaction.mockReturnValue({
id: 'tx-1',
date: '2024-06-15',
booking_date: '2024-06-15',
amount: 100,
currency: 'SEK',
description: 'Test',
})
mockUploadDocument.mockRejectedValue(new Error('Storage error'))
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const account = makeAccount()
const result = await syncAccountTransactions(
{} as never,
COMPANY_ID,
USER_ID,
CONNECTION_ID,
account,
'2024-01-01',
'2024-12-31',
mockIngest
)
expect(result.imported).toBe(1)
expect(result.errors).toBe(0)
expect(errorSpy).toHaveBeenCalledWith(
expect.stringContaining('Failed to archive raw response'),
expect.any(Error)
)
errorSpy.mockRestore()
})
it('passes raw transactions to ingest function', async () => {
mockGetAllTransactionsWithRaw.mockResolvedValue({
transactions: [{ transaction_amount: { amount: '500', currency: 'SEK' } }],
rawPages: ['{}'],
})
mockConvertTransaction.mockReturnValue({
id: 'tx-500',
date: '2024-06-15',
booking_date: '2024-06-15',
amount: -500,
currency: 'SEK',
description: 'Purchase',
counterparty_name: 'Store',
merchant_category_code: '5411',
})
mockUploadDocument.mockResolvedValue({ id: 'doc-1' })
const account = makeAccount()
await syncAccountTransactions(
{} as never,
COMPANY_ID,
USER_ID,
CONNECTION_ID,
account,
'2024-01-01',
'2024-12-31',
mockIngest
)
expect(mockIngest).toHaveBeenCalledTimes(1)
const rawTxns = mockIngest.mock.calls[0][3]
expect(rawTxns).toHaveLength(1)
expect(rawTxns[0].external_id).toBe('conn-1_tx-500')
expect(rawTxns[0].import_source).toBe('enable_banking')
})
})