c8461397c8
* feat(api): implement commit functionality for journal entries * fix(extensions): make ExtensionSettings.clear() a real delete so disconnect flows work The 2026-03-30 multi-tenant refactor dropped all RLS policies on extension_data and recreated only SELECT/INSERT/UPDATE. Combined with `value jsonb NOT NULL`, every extension that called `settings.set(key, null)` to clear stored state (cloud-backup disconnect, skatteverket OAuth/AGI cleanup, arcim-migration consent reset) silently failed — the upsert hit the NOT NULL constraint and the error was swallowed, leaving users stuck with stale connection rows. Adds an `extension_data_delete` RLS policy, a `clear(key)` method backed by a real DELETE, switches the four affected handlers, and makes `set()` throw on Supabase error so this class of silent failure can't recur. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(journal-entries): add draft saving functionality to journal entry form * feat: add periodisk sammanställning report generation and CSV export - Implemented period date helpers in `period-dates.ts` for calculating start and end dates based on period type (monthly, quarterly, yearly). - Created `periodisk-sammanstallning.ts` to generate the periodisk sammanställning report, including data fetching, validation, and warning handling. - Developed CSV serializer in `periodisk-sammanstallning-csv.ts` for exporting the report in SKV574008 format. - Added new columns to `company_settings` for storing periodisk sammanställning settings and tax contact information via migration. - Introduced a new migration to add a `paid_with_private_funds` flag to `supplier_invoices` for tracking out-of-pocket expenses. - Updated journal entries to include the new source type for privately paid supplier invoices. * feat(migrations): add paid_with_private_funds flag to supplier_invoices and expand journal_entries.source_type CHECK * fix(ai_requests): drop existing policies and trigger before creating new ones * fix(migrations): ensure extension_data has a proper DELETE policy for ExtensionSettings.clear() * fix(supplier-invoices): update error handling for invalid input in POST request * fix: correct capitalization in project title * fix(migrations): resolve duplicate version 20260513120000 Two migrations shared the same timestamp prefix, causing schema_migrations_pkey collision on Supabase preview branches. Bump extension_data_delete_policy to 20260513120001. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
166 lines
6.1 KiB
TypeScript
166 lines
6.1 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { createExtensionContext } from '../context-factory'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
import { createMockSupabase } from '@/tests/helpers'
|
|
|
|
vi.mock('@/lib/transactions/ingest', () => ({
|
|
ingestTransactions: vi.fn().mockResolvedValue({
|
|
imported: 0, duplicates: 0, reconciled: 0,
|
|
auto_categorized: 0, auto_matched_invoices: 0, errors: 0,
|
|
transaction_ids: [],
|
|
}),
|
|
}))
|
|
|
|
vi.mock('@/lib/logger', () => ({
|
|
createLogger: (module: string) => {
|
|
const prefix = `[${module}]`
|
|
return {
|
|
info: (message: string, ...args: unknown[]) => console.log(prefix, message, ...args),
|
|
warn: (message: string, ...args: unknown[]) => console.warn(prefix, message, ...args),
|
|
error: (message: string, ...args: unknown[]) => console.error(prefix, message, ...args),
|
|
}
|
|
},
|
|
}))
|
|
|
|
beforeEach(() => {
|
|
eventBus.clear()
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
describe('createExtensionContext', () => {
|
|
it('returns context with correct userId and extensionId', () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
expect(ctx.userId).toBe('user-1')
|
|
expect(ctx.extensionId).toBe('test-ext')
|
|
})
|
|
|
|
it('provides supabase client', () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
expect(ctx.supabase).toBe(supabase)
|
|
})
|
|
|
|
it('emit() delegates to eventBus.emit()', async () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
const handler = vi.fn()
|
|
eventBus.on('journal_entry.committed', handler)
|
|
|
|
await ctx.emit({
|
|
type: 'journal_entry.committed',
|
|
payload: { entry: { id: 'e1' } as never, userId: 'user-1', companyId: 'company-1' },
|
|
})
|
|
|
|
expect(handler).toHaveBeenCalledWith({ entry: { id: 'e1' }, userId: 'user-1', companyId: 'company-1' })
|
|
})
|
|
|
|
it('log methods prefix with extensionId', () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'my-ext')
|
|
|
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
|
|
ctx.log.info('hello', 42)
|
|
ctx.log.warn('caution')
|
|
ctx.log.error('oops')
|
|
|
|
expect(logSpy).toHaveBeenCalledWith('[ext:my-ext]', 'hello', 42)
|
|
expect(warnSpy).toHaveBeenCalledWith('[ext:my-ext]', 'caution')
|
|
expect(errorSpy).toHaveBeenCalledWith('[ext:my-ext]', 'oops')
|
|
|
|
logSpy.mockRestore()
|
|
warnSpy.mockRestore()
|
|
errorSpy.mockRestore()
|
|
})
|
|
|
|
it('settings.get() queries extension_data table', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: { value: { autoOcr: true } }, error: null })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'mcp-server')
|
|
const result = await ctx.settings.get<{ autoOcr: boolean }>('settings')
|
|
|
|
expect(result).toEqual({ autoOcr: true })
|
|
expect(supabase.from).toHaveBeenCalledWith('extension_data')
|
|
})
|
|
|
|
it('settings.get() without key defaults to "settings"', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: { value: { foo: 'bar' } }, error: null })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
const result = await ctx.settings.get<{ foo: string }>()
|
|
|
|
expect(result).toEqual({ foo: 'bar' })
|
|
})
|
|
|
|
it('settings.get() returns null when no data', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: null, error: null })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
const result = await ctx.settings.get('missing-key')
|
|
|
|
expect(result).toBeNull()
|
|
})
|
|
|
|
it('settings.set() upserts into extension_data table', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: null, error: null })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
await ctx.settings.set('my-key', { value: 123 })
|
|
|
|
expect(supabase.from).toHaveBeenCalledWith('extension_data')
|
|
})
|
|
|
|
it('settings.set() throws when supabase returns an error', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: null, error: { message: 'null value in column "value" violates not-null constraint' } })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
await expect(ctx.settings.set('my-key', null)).rejects.toThrow(/extension_data set failed/)
|
|
})
|
|
|
|
it('settings.clear() deletes from extension_data table', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: null, error: null })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
await ctx.settings.clear('my-key')
|
|
|
|
expect(supabase.from).toHaveBeenCalledWith('extension_data')
|
|
})
|
|
|
|
it('settings.clear() throws when supabase returns an error', async () => {
|
|
const { supabase, mockResult } = createMockSupabase()
|
|
mockResult({ data: null, error: { message: 'permission denied' } })
|
|
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
await expect(ctx.settings.clear('my-key')).rejects.toThrow(/extension_data clear failed/)
|
|
})
|
|
|
|
it('storage.getPublicUrl() returns URL string', () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
const url = ctx.storage.getPublicUrl('documents', 'path/to/file.pdf')
|
|
expect(typeof url).toBe('string')
|
|
})
|
|
|
|
it('services.ingestTransactions is a function', () => {
|
|
const { supabase } = createMockSupabase()
|
|
const ctx = createExtensionContext(supabase as never, 'user-1', 'company-1', 'test-ext')
|
|
|
|
expect(typeof ctx.services.ingestTransactions).toBe('function')
|
|
})
|
|
})
|