fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,165 @@
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')
})
})
@@ -0,0 +1,275 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { extensionRegistry } from '@/lib/extensions/registry'
import {
maybeCreatePaymentLinkForInvoice,
applyPaymentLinkToInvoice,
} from '@/lib/extensions/payment-links'
import { makeInvoice } from '@/tests/helpers'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Invoice } from '@/types'
const log = { warn: vi.fn() }
// The bridge reads company_settings.invoice_payment_links_enabled before
// calling the provider: `enabled: null` models a missing settings row.
function settingsChain(enabled: boolean | null) {
const maybeSingle = vi.fn().mockResolvedValue({
data: enabled === null ? null : { invoice_payment_links_enabled: enabled },
error: null,
})
const eq = vi.fn().mockReturnValue({ maybeSingle })
return { select: vi.fn().mockReturnValue({ eq }) }
}
function mockClient(enabled: boolean | null = true) {
const from = vi.fn((table: string) => {
if (table === 'company_settings') return settingsChain(enabled)
throw new Error(`unexpected table ${table}`)
})
return { client: { from } as unknown as SupabaseClient, from }
}
function eligibleInvoice(overrides: Partial<Invoice> = {}): Invoice {
return makeInvoice({
payment_link_url: null,
document_type: 'invoice',
credited_invoice_id: null,
...overrides,
})
}
function registerProvider(create: (...args: unknown[]) => Promise<unknown>) {
extensionRegistry.register({
id: 'fake-psp',
name: 'Fake PSP',
version: '1.0.0',
services: { createInvoicePaymentLink: create as (...args: unknown[]) => Promise<unknown> },
})
}
describe('maybeCreatePaymentLinkForInvoice', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
extensionRegistry.unregister('fake-psp')
})
it('returns null when no provider extension is registered', async () => {
const { client, from } = mockClient()
const result = await maybeCreatePaymentLinkForInvoice(
client, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toBeNull()
// Without a provider the settings query never runs (core build stays DB-free).
expect(from).not.toHaveBeenCalled()
})
it.each([
['a manually pasted link exists', { payment_link_url: 'https://buy.stripe.com/x' }],
['the per-invoice toggle is off', { payment_link_auto: false }],
['the document is a proforma', { document_type: 'proforma' as const }],
['the document is a credit note', { credited_invoice_id: 'orig-1' }],
])('skips the provider when %s', async (_label, overrides) => {
const create = vi.fn()
registerProvider(create)
const result = await maybeCreatePaymentLinkForInvoice(
mockClient().client, 'company-1', 'user-1',
eligibleInvoice(overrides as Partial<Invoice>), log,
)
expect(result).toBeNull()
expect(create).not.toHaveBeenCalled()
})
it('skips the provider when the company has not enabled payment links', async () => {
const create = vi.fn()
registerProvider(create)
const result = await maybeCreatePaymentLinkForInvoice(
mockClient(false).client, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toBeNull()
expect(create).not.toHaveBeenCalled()
})
it('treats a missing settings row as disabled', async () => {
const create = vi.fn()
registerProvider(create)
const result = await maybeCreatePaymentLinkForInvoice(
mockClient(null).client, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toBeNull()
expect(create).not.toHaveBeenCalled()
})
it('fails closed (no link, no throw) when the settings read throws', async () => {
const create = vi.fn()
registerProvider(create)
const broken = {
from: vi.fn(() => {
throw new Error('db down')
}),
} as unknown as SupabaseClient
const result = await maybeCreatePaymentLinkForInvoice(
broken, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toBeNull()
expect(create).not.toHaveBeenCalled()
})
it('returns the provider link on success', async () => {
const create = vi.fn().mockResolvedValue({
url: 'https://buy.stripe.com/test_abc',
externalId: 'plink_1',
})
registerProvider(create)
const { client } = mockClient()
const invoice = eligibleInvoice()
const result = await maybeCreatePaymentLinkForInvoice(
client, 'company-1', 'user-1', invoice, log,
)
expect(result).toEqual({
ok: true,
url: 'https://buy.stripe.com/test_abc',
externalId: 'plink_1',
})
expect(create).toHaveBeenCalledWith(client, 'company-1', 'user-1', invoice)
})
it('treats a provider null (not eligible) as no link', async () => {
registerProvider(vi.fn().mockResolvedValue(null))
const result = await maybeCreatePaymentLinkForInvoice(
mockClient().client, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toBeNull()
})
it('never throws: a provider failure becomes { ok: false, reason }', async () => {
registerProvider(vi.fn().mockRejectedValue(new Error('stripe down')))
const result = await maybeCreatePaymentLinkForInvoice(
mockClient().client, 'company-1', 'user-1', eligibleInvoice(), log,
)
expect(result).toEqual({ ok: false, reason: 'stripe down' })
expect(log.warn).toHaveBeenCalled()
})
})
describe('applyPaymentLinkToInvoice', () => {
function mockPersist(error: { message: string } | null, enabled: boolean = true) {
const eqCompany = vi.fn().mockResolvedValue({ error })
const eqId = vi.fn().mockReturnValue({ eq: eqCompany })
const update = vi.fn().mockReturnValue({ eq: eqId })
const from = vi.fn((table: string) => {
if (table === 'company_settings') return settingsChain(enabled)
return { update }
})
return { client: { from } as unknown as SupabaseClient, from, update, eqId, eqCompany }
}
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
extensionRegistry.unregister('fake-psp')
})
it('is a no-op when no provider is registered', async () => {
const persist = mockPersist(null)
const invoice = eligibleInvoice()
const result = await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
)
expect(result).toEqual({ failure: null })
expect(persist.from).not.toHaveBeenCalled()
expect(invoice.payment_link_url).toBeNull()
})
it('is a no-op when the company has not enabled payment links', async () => {
const create = vi.fn()
registerProvider(create)
const persist = mockPersist(null, false)
const invoice = eligibleInvoice()
const result = await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
)
expect(result).toEqual({ failure: null })
expect(create).not.toHaveBeenCalled()
expect(persist.update).not.toHaveBeenCalled()
expect(invoice.payment_link_url).toBeNull()
})
it('persists the link, then mirrors it onto the invoice object', async () => {
registerProvider(vi.fn().mockResolvedValue({
url: 'https://buy.stripe.com/test_abc',
externalId: 'plink_1',
}))
const persist = mockPersist(null)
const invoice = eligibleInvoice()
const result = await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
)
expect(result).toEqual({ failure: null })
expect(persist.update).toHaveBeenCalledWith({
payment_link_url: 'https://buy.stripe.com/test_abc',
stripe_payment_link_id: 'plink_1',
})
expect(persist.eqId).toHaveBeenCalledWith('id', invoice.id)
expect(persist.eqCompany).toHaveBeenCalledWith('company_id', 'company-1')
expect(invoice.payment_link_url).toBe('https://buy.stripe.com/test_abc')
expect(invoice.stripe_payment_link_id).toBe('plink_1')
})
it('persist failure returns { failure } and does NOT mutate the invoice', async () => {
registerProvider(vi.fn().mockResolvedValue({
url: 'https://buy.stripe.com/test_abc',
externalId: 'plink_1',
}))
const persist = mockPersist({ message: 'row is locked' })
const invoice = eligibleInvoice()
const result = await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
{ logPrefix: 'invoices.send: ', logContext: { invoiceId: invoice.id } },
)
expect(result).toEqual({ failure: 'row is locked' })
expect(invoice.payment_link_url).toBeNull()
expect(invoice.stripe_payment_link_id).toBeUndefined()
expect(log.warn).toHaveBeenCalledWith(
'invoices.send: payment link created but not persisted; sending without it',
{ invoiceId: invoice.id, err: { message: 'row is locked' } },
)
})
it('provider failure returns { failure: reason } without touching the DB', async () => {
registerProvider(vi.fn().mockRejectedValue(new Error('stripe down')))
const persist = mockPersist(null)
const invoice = eligibleInvoice()
const result = await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
)
expect(result).toEqual({ failure: 'stripe down' })
expect(persist.update).not.toHaveBeenCalled()
expect(invoice.payment_link_url).toBeNull()
})
it('passes the invoiceNumber override to the provider without mutating the invoice', async () => {
const create = vi.fn().mockResolvedValue({
url: 'https://buy.stripe.com/test_abc',
externalId: 'plink_1',
})
registerProvider(create)
const persist = mockPersist(null)
const invoice = eligibleInvoice({ invoice_number: null })
await applyPaymentLinkToInvoice(
persist.client, 'company-1', 'user-1', invoice, log,
{ invoiceNumber: 'F-2026-0042' },
)
expect(create).toHaveBeenCalledWith(
persist.client,
'company-1',
'user-1',
expect.objectContaining({ invoice_number: 'F-2026-0042' }),
)
expect(invoice.invoice_number).toBeNull()
})
})
+161
View File
@@ -0,0 +1,161 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { extensionRegistry, setContextFactory } from '../registry'
import { eventBus } from '@/lib/events/bus'
import type { Extension, ExtensionContext } from '../types'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn().mockResolvedValue({
from: vi.fn(),
storage: { from: vi.fn() },
}),
}))
beforeEach(() => {
extensionRegistry.clear()
eventBus.clear()
})
function makeExtension(overrides: Partial<Extension> = {}): Extension {
return {
id: 'test-ext',
name: 'Test Extension',
version: '1.0.0',
...overrides,
}
}
describe('ExtensionRegistry', () => {
it('register() stores extension, queryable via get() and getAll()', () => {
const ext = makeExtension()
extensionRegistry.register(ext)
expect(extensionRegistry.get('test-ext')).toBe(ext)
expect(extensionRegistry.getAll()).toEqual([ext])
})
it('register() wires event handlers to the bus', async () => {
const handler = vi.fn()
const ext = makeExtension({
id: 'event-ext',
eventHandlers: [{ eventType: 'journal_entry.committed', handler }],
})
extensionRegistry.register(ext)
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1', companyId: 'company-1' },
})
expect(handler).toHaveBeenCalled()
expect(handler.mock.calls[0][0]).toEqual({ entry: { id: 'e1' }, userId: 'u1', companyId: 'company-1' })
})
it('register() skips duplicate registration (same id)', () => {
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const ext1 = makeExtension()
const ext2 = makeExtension({ name: 'Duplicate' })
extensionRegistry.register(ext1)
extensionRegistry.register(ext2)
// Original is kept
expect(extensionRegistry.get('test-ext')!.name).toBe('Test Extension')
expect(extensionRegistry.getAll()).toHaveLength(1)
consoleSpy.mockRestore()
})
it('unregister() removes extension and unsubscribes handlers', async () => {
const handler = vi.fn()
const ext = makeExtension({
id: 'removable',
eventHandlers: [{ eventType: 'journal_entry.committed', handler }],
})
extensionRegistry.register(ext)
extensionRegistry.unregister('removable')
expect(extensionRegistry.get('removable')).toBeUndefined()
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1', companyId: 'company-1' },
})
expect(handler).not.toHaveBeenCalled()
})
it('getByCapability() filters correctly', () => {
const ext1 = makeExtension({
id: 'with-settings',
settingsPanel: { label: 'Test', path: '/test' },
})
const ext2 = makeExtension({ id: 'without-settings' })
extensionRegistry.register(ext1)
extensionRegistry.register(ext2)
const withSettings = extensionRegistry.getByCapability('settingsPanel')
expect(withSettings).toHaveLength(1)
expect(withSettings[0].id).toBe('with-settings')
})
it('clear() removes all extensions and unsubscribes all handlers', async () => {
const handler1 = vi.fn()
const handler2 = vi.fn()
extensionRegistry.register(
makeExtension({
id: 'ext1',
eventHandlers: [{ eventType: 'journal_entry.committed', handler: handler1 }],
})
)
extensionRegistry.register(
makeExtension({
id: 'ext2',
eventHandlers: [{ eventType: 'journal_entry.drafted', handler: handler2 }],
})
)
extensionRegistry.clear()
expect(extensionRegistry.getAll()).toHaveLength(0)
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1', companyId: 'company-1' },
})
await eventBus.emit({
type: 'journal_entry.drafted',
payload: { entry: { id: 'e1' } as never, userId: 'u1', companyId: 'company-1' },
})
expect(handler1).not.toHaveBeenCalled()
expect(handler2).not.toHaveBeenCalled()
})
it('handler receives ExtensionContext when context factory is set', async () => {
const handler = vi.fn()
const mockCtx = { extensionId: 'ctx-ext', userId: 'u1', companyId: 'company-1' } as ExtensionContext
setContextFactory((_supabase, _userId, _extId) => mockCtx)
const ext = makeExtension({
id: 'ctx-ext',
eventHandlers: [{ eventType: 'journal_entry.committed', handler }],
})
extensionRegistry.register(ext)
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1', companyId: 'company-1' },
})
expect(handler).toHaveBeenCalledWith(
{ entry: { id: 'e1' }, userId: 'u1', companyId: 'company-1' },
mockCtx
)
})
})
+112
View File
@@ -0,0 +1,112 @@
import { resolve, join } from 'path'
import { readdirSync, readFileSync } from 'fs'
/**
* Build EXTENSION_DEFINITIONS from manifest.json files so the test
* is independent of extensions.config.json.
*/
function buildDefinitionsFromManifests(): Record<string, unknown[]> {
const extensionsDir = resolve(__dirname, '../../../extensions')
const result: Record<string, unknown[]> = {}
function walk(dir: string) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name)
if (entry.isDirectory()) {
walk(fullPath)
} else if (entry.name === 'manifest.json') {
const manifest = JSON.parse(readFileSync(fullPath, 'utf-8'))
const sector: string = manifest.sector
if (!result[sector]) result[sector] = []
result[sector].push({
slug: manifest.id,
sector: manifest.sector,
...manifest.definition,
})
}
}
}
walk(extensionsDir)
return result
}
vi.mock('@/lib/extensions/_generated/sector-definitions', () => ({
EXTENSION_DEFINITIONS: buildDefinitionsFromManifests(),
}))
import {
SECTORS,
getSector,
getExtensionDefinition,
getAllExtensions,
getExtensionsBySector,
} from '../sectors'
describe('sectors registry', () => {
it('should have 1 sector', () => {
expect(SECTORS.length).toBe(1)
})
it('should have 19 total extensions', () => {
expect(getAllExtensions().length).toBe(19)
})
it('should have unique slugs within each sector', () => {
for (const sector of SECTORS) {
const slugs = sector.extensions.map(e => e.slug)
const uniqueSlugs = new Set(slugs)
expect(uniqueSlugs.size).toBe(slugs.length)
}
})
it('should have at least one extension per sector', () => {
for (const sector of SECTORS) {
expect(sector.extensions.length).toBeGreaterThan(0)
}
})
it('getSector returns correct sector', () => {
const sector = getSector('general')
expect(sector).toBeDefined()
expect(sector!.slug).toBe('general')
expect(sector!.name).toBe('Generella verktyg')
})
it('getSector returns undefined for unknown slug', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sector = getSector('invalid' as any)
expect(sector).toBeUndefined()
})
it('getExtensionDefinition returns correct extension', () => {
const ext = getExtensionDefinition('general', 'mcp-server')
expect(ext).toBeDefined()
expect(ext!.slug).toBe('mcp-server')
expect(ext!.name).toBe('MCP-server (API)')
expect(ext!.sector).toBe('general')
})
it('getExtensionDefinition returns undefined for unknown extension', () => {
const ext = getExtensionDefinition('general', 'nonexistent')
expect(ext).toBeUndefined()
})
it('getExtensionsBySector returns extensions for a sector', () => {
const extensions = getExtensionsBySector('general')
expect(extensions.length).toBe(19)
})
it('all extensions have required fields', () => {
for (const ext of getAllExtensions()) {
expect(ext.slug).toBeTruthy()
expect(ext.name).toBeTruthy()
expect(ext.sector).toBeTruthy()
expect(ext.category).toBeTruthy()
expect(ext.description).toBeTruthy()
expect(ext.longDescription).toBeTruthy()
expect(ext.icon).toBeTruthy()
expect(ext.dataPattern).toBeTruthy()
}
})
})
@@ -0,0 +1,16 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'fs'
import { resolve } from 'path'
describe('type decoupling', () => {
it('types/index.ts must not import from @/extensions/', () => {
const typesPath = resolve(__dirname, '../../../types/index.ts')
const content = readFileSync(typesPath, 'utf-8')
const extensionImports = content
.split('\n')
.filter((line) => /from\s+['"]@\/extensions\//.test(line))
expect(extensionImports).toEqual([])
})
})
+177
View File
@@ -0,0 +1,177 @@
import { describe, it, expect } from 'vitest'
import {
validateSwedishPersonalNumber,
validatePositiveNumber,
validateNonNegativeNumber,
validateMaxNumber,
validateRequired,
validateDateNotFuture,
} from '../validation'
describe('validateSwedishPersonalNumber', () => {
it('accepts a valid personal number with dash', () => {
// 811228-9874 is a valid test number (Luhn passes)
expect(validateSwedishPersonalNumber('19811228-9874')).toBeNull()
})
it('accepts a valid personal number without dash', () => {
expect(validateSwedishPersonalNumber('198112289874')).toBeNull()
})
it('rejects empty string', () => {
expect(validateSwedishPersonalNumber('')).toBe('Personnummer kravs')
})
it('rejects too short input', () => {
expect(validateSwedishPersonalNumber('19811228')).toBe('Format: YYYYMMDD-XXXX (12 siffror)')
})
it('rejects too long input', () => {
expect(validateSwedishPersonalNumber('198112289874555')).toBe('Format: YYYYMMDD-XXXX (12 siffror)')
})
it('rejects non-numeric characters', () => {
expect(validateSwedishPersonalNumber('19811228ABCD')).toBe('Format: YYYYMMDD-XXXX (12 siffror)')
})
it('rejects invalid month', () => {
expect(validateSwedishPersonalNumber('199913011234')).toBe('Ogiltig månad')
})
it('rejects month 00', () => {
expect(validateSwedishPersonalNumber('199900011234')).toBe('Ogiltig månad')
})
it('rejects invalid day', () => {
expect(validateSwedishPersonalNumber('199901321234')).toBe('Ogiltig dag')
})
it('rejects day 00', () => {
expect(validateSwedishPersonalNumber('199901001234')).toBe('Ogiltig dag')
})
it('rejects year before 1900', () => {
expect(validateSwedishPersonalNumber('189901011234')).toBe('Ogiltigt år')
})
it('rejects future year', () => {
const futureYear = new Date().getFullYear() + 1
expect(validateSwedishPersonalNumber(`${futureYear}01011234`)).toBe('Ogiltigt år')
})
it('rejects invalid Luhn checksum', () => {
// Change last digit to break checksum
expect(validateSwedishPersonalNumber('19811228-9875')).toBe('Ogiltig kontrollsiffra')
})
it('handles spaces in input', () => {
expect(validateSwedishPersonalNumber('1981 1228 9874')).toBeNull()
})
})
describe('validatePositiveNumber', () => {
it('returns null for positive number', () => {
expect(validatePositiveNumber(5)).toBeNull()
})
it('returns null for positive string number', () => {
expect(validatePositiveNumber('42.5')).toBeNull()
})
it('rejects zero', () => {
expect(validatePositiveNumber(0)).toBe('Varde maste vara storre an 0')
})
it('rejects negative number', () => {
expect(validatePositiveNumber(-3)).toBe('Varde maste vara storre an 0')
})
it('rejects NaN string', () => {
expect(validatePositiveNumber('abc')).toBe('Varde maste vara storre an 0')
})
})
describe('validateNonNegativeNumber', () => {
it('returns null for positive number', () => {
expect(validateNonNegativeNumber(5)).toBeNull()
})
it('returns null for zero', () => {
expect(validateNonNegativeNumber(0)).toBeNull()
})
it('rejects negative number', () => {
expect(validateNonNegativeNumber(-1)).toBe('Varde kan inte vara negativt')
})
it('rejects NaN string', () => {
expect(validateNonNegativeNumber('xyz')).toBe('Varde kan inte vara negativt')
})
})
describe('validateMaxNumber', () => {
it('returns null when value is under max', () => {
expect(validateMaxNumber(5, 10)).toBeNull()
})
it('returns null when value equals max', () => {
expect(validateMaxNumber(10, 10)).toBeNull()
})
it('rejects when value exceeds max', () => {
expect(validateMaxNumber(15, 10)).toBe('Varde kan inte overskrida 10')
})
it('rejects NaN input', () => {
expect(validateMaxNumber('abc', 10)).toBe('Ogiltigt varde')
})
it('works with string numbers', () => {
expect(validateMaxNumber('8', 10)).toBeNull()
})
})
describe('validateRequired', () => {
it('returns null for non-empty string', () => {
expect(validateRequired('hello')).toBeNull()
})
it('returns null for number', () => {
expect(validateRequired(42)).toBeNull()
})
it('returns null for zero', () => {
expect(validateRequired(0)).toBeNull()
})
it('rejects empty string', () => {
expect(validateRequired('')).toBe('Obligatoriskt falt')
})
it('rejects undefined', () => {
expect(validateRequired(undefined)).toBe('Obligatoriskt falt')
})
it('rejects null', () => {
expect(validateRequired(null)).toBe('Obligatoriskt falt')
})
})
describe('validateDateNotFuture', () => {
it('returns null for past date', () => {
expect(validateDateNotFuture('2020-01-01')).toBeNull()
})
it('returns null for today', () => {
const today = new Date().toISOString().slice(0, 10)
expect(validateDateNotFuture(today)).toBeNull()
})
it('rejects future date', () => {
expect(validateDateNotFuture('2099-01-01')).toBe('Datum kan inte vara i framtiden')
})
it('rejects empty string', () => {
expect(validateDateNotFuture('')).toBe('Datum kravs')
})
})
+20
View File
@@ -0,0 +1,20 @@
// AUTO-GENERATED: do not edit. Run `npm run setup:extensions` to regenerate.
export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
'calendar',
'enable-banking',
'email',
'arcim-migration',
'tic',
'mcp-server',
'cloud-backup',
'skatteverket',
'invoice-inbox',
'document-extraction',
'stripe',
'whatsapp-inbox',
'woocommerce',
'shopify',
'zettle',
'mail',
])
+37
View File
@@ -0,0 +1,37 @@
// AUTO-GENERATED: do not edit. Run `npm run setup:extensions` to regenerate.
import type { Extension } from '../types'
import { calendarExtension } from '@/extensions/general/calendar'
import { enableBankingExtension } from '@/extensions/general/enable-banking'
import { emailExtension } from '@/extensions/general/email'
import { arcimMigrationExtension } from '@/extensions/general/arcim-migration'
import { ticExtension } from '@/extensions/general/tic'
import { mcpServerExtension } from '@/extensions/general/mcp-server'
import { cloudBackupExtension } from '@/extensions/general/cloud-backup'
import { skatteverketExtension } from '@/extensions/general/skatteverket'
import { invoiceInboxExtension } from '@/extensions/general/invoice-inbox'
import { documentExtractionExtension } from '@/extensions/general/document-extraction'
import { stripeExtension } from '@/extensions/general/stripe'
import { whatsappInboxExtension } from '@/extensions/general/whatsapp-inbox'
import { woocommerceExtension } from '@/extensions/general/woocommerce'
import { shopifyExtension } from '@/extensions/general/shopify'
import { zettleExtension } from '@/extensions/general/zettle'
import { mailExtension } from '@/extensions/general/mail'
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
calendarExtension,
enableBankingExtension,
emailExtension,
arcimMigrationExtension,
ticExtension,
mcpServerExtension,
cloudBackupExtension,
skatteverketExtension,
invoiceInboxExtension,
documentExtractionExtension,
stripeExtension,
whatsappInboxExtension,
woocommerceExtension,
shopifyExtension,
zettleExtension,
mailExtension,
]
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
// AUTO-GENERATED: do not edit. Run `npm run setup:extensions` to regenerate.
import dynamic from 'next/dynamic'
import type { ComponentType } from 'react'
import type { WorkspaceComponentProps } from '../workspace-registry'
export const WORKSPACES: Record<string, ComponentType<WorkspaceComponentProps>> = {
'general/calendar': dynamic(() => import('@/components/extensions/general/CalendarWorkspace')),
'general/enable-banking': dynamic(() => import('@/components/extensions/general/EnableBankingWorkspace')),
'general/arcim-migration': dynamic(() => import('@/components/extensions/general/ArcimMigrationWorkspace')),
'general/tic': dynamic(() => import('@/components/extensions/general/TicWorkspace')),
'general/cloud-backup': dynamic(() => import('@/components/extensions/general/CloudBackupWorkspace')),
'general/invoice-inbox': dynamic(() => import('@/components/extensions/general/InvoiceInboxWorkspace')),
}
+158
View File
@@ -0,0 +1,158 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { CoreEvent } from '@/lib/events/types'
import { eventBus } from '@/lib/events/bus'
import { ingestTransactions } from '@/lib/transactions/ingest'
import { listForCompany as cashAccountsList, getPrimary as cashAccountsGetPrimary } from '@/lib/cash-accounts/service'
import { createLogger } from '@/lib/logger'
import type {
ExtensionContext,
ExtensionLogger,
ExtensionSettings,
ExtensionStorage,
ExtensionServices,
} from './types'
/**
* Create a prefixed logger for an extension. When `bind` is supplied the
* fields (e.g. requestId, userId, companyId) are merged into every log line.
*/
function createExtLogger(extensionId: string, bind?: Record<string, unknown>): ExtensionLogger {
const logger = bind
? createLogger(`ext:${extensionId}`, bind)
: createLogger(`ext:${extensionId}`)
return {
info: (message: string, ...args: unknown[]) => logger.info(message, ...args),
warn: (message: string, ...args: unknown[]) => logger.warn(message, ...args),
error: (message: string, ...args: unknown[]) => logger.error(message, ...args),
}
}
/**
* Create a settings accessor scoped to a specific extension.
*/
function createSettings(
supabase: SupabaseClient,
userId: string,
companyId: string,
extensionId: string
): ExtensionSettings {
return {
async get<T>(key?: string): Promise<T | null> {
const lookupKey = key ?? 'settings'
const { data } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', extensionId)
.eq('key', lookupKey)
.single()
return (data?.value as T) ?? null
},
async set<T>(key: string, value: T): Promise<void> {
const { error } = await supabase
.from('extension_data')
.upsert(
{
user_id: userId,
company_id: companyId,
extension_id: extensionId,
key,
value,
},
{ onConflict: 'company_id,extension_id,key' }
)
if (error) {
throw new Error(`extension_data set failed for ${extensionId}/${key}: ${error.message}`)
}
},
async clear(key: string): Promise<void> {
const { error } = await supabase
.from('extension_data')
.delete()
.eq('company_id', companyId)
.eq('extension_id', extensionId)
.eq('key', key)
if (error) {
throw new Error(`extension_data clear failed for ${extensionId}/${key}: ${error.message}`)
}
},
}
}
/**
* Create a storage accessor wrapping Supabase storage.
*/
function createStorage(supabase: SupabaseClient): ExtensionStorage {
return {
async download(bucket: string, path: string) {
const { data, error } = await supabase.storage
.from(bucket)
.download(path)
return { data, error: error?.message }
},
async upload(bucket: string, path: string, data: ArrayBuffer, options?: { contentType?: string }) {
const { error } = await supabase.storage
.from(bucket)
.upload(path, data, options ? { contentType: options.contentType } : undefined)
if (error) return { path: '', error: error.message }
return { path }
},
getPublicUrl(bucket: string, path: string): string {
const { data } = supabase.storage
.from(bucket)
.getPublicUrl(path)
return data.publicUrl
},
}
}
/**
* Create core services exposed to extensions.
*/
function createServices(): ExtensionServices {
return {
ingestTransactions,
getCashAccounts: (supabase, companyId, opts) => cashAccountsList(supabase, companyId, opts),
getPrimaryCashAccount: (supabase, companyId, currency) =>
cashAccountsGetPrimary(supabase, companyId, currency),
}
}
/**
* Build a fully populated ExtensionContext.
*
* The context gives extensions access to Supabase, event emission, settings,
* storage, logging, and core services: without importing from core modules.
*
* `requestId` (when supplied by the dispatcher) flows through the bound logger
* and is exposed on the context so handlers can pass it into
* `errorResponseFromCode(...)` for the envelope + `X-Request-Id` header.
*/
export function createExtensionContext(
supabase: SupabaseClient,
userId: string,
companyId: string,
extensionId: string,
requestId?: string,
): ExtensionContext {
const logBindings: Record<string, unknown> = { userId, companyId, extensionId }
if (requestId) logBindings.requestId = requestId
return {
userId,
companyId,
extensionId,
requestId,
supabase,
emit: (event: CoreEvent) => eventBus.emit(event),
settings: createSettings(supabase, userId, companyId, extensionId),
storage: createStorage(supabase),
log: createExtLogger(extensionId, logBindings),
services: createServices(),
}
}
+95
View File
@@ -0,0 +1,95 @@
// Translation key lookup for extension and sector slugs.
//
// Extension manifests ship Swedish-only names/descriptions in the data layer
// (lib/extensions/_generated/sector-definitions.ts and lib/extensions/sectors.ts).
// Translation happens at the render layer via these slug → key helpers.
//
// For known slugs, return the translation key under the `extensions` namespace.
// For unknown slugs, return null: callers fall back to the manifest values.
export function extensionNameKey(slug: string): string | null {
switch (slug) {
case 'enable-banking':
return 'ext_enable_banking_name'
case 'email':
return 'ext_email_name'
case 'arcim-migration':
return 'ext_arcim_migration_name'
case 'tic':
return 'ext_tic_name'
case 'mcp-server':
return 'ext_mcp_server_name'
case 'cloud-backup':
return 'ext_cloud_backup_name'
case 'skatteverket':
return 'ext_skatteverket_name'
case 'invoice-inbox':
return 'ext_invoice_inbox_name'
default:
return null
}
}
export function extensionDescriptionKey(slug: string): string | null {
switch (slug) {
case 'enable-banking':
return 'ext_enable_banking_description'
case 'email':
return 'ext_email_description'
case 'arcim-migration':
return 'ext_arcim_migration_description'
case 'tic':
return 'ext_tic_description'
case 'mcp-server':
return 'ext_mcp_server_description'
case 'cloud-backup':
return 'ext_cloud_backup_description'
case 'skatteverket':
return 'ext_skatteverket_description'
case 'invoice-inbox':
return 'ext_invoice_inbox_description'
default:
return null
}
}
export function extensionLongDescriptionKey(slug: string): string | null {
switch (slug) {
case 'enable-banking':
return 'ext_enable_banking_long_description'
case 'email':
return 'ext_email_long_description'
case 'arcim-migration':
return 'ext_arcim_migration_long_description'
case 'tic':
return 'ext_tic_long_description'
case 'mcp-server':
return 'ext_mcp_server_long_description'
case 'cloud-backup':
return 'ext_cloud_backup_long_description'
case 'skatteverket':
return 'ext_skatteverket_long_description'
case 'invoice-inbox':
return 'ext_invoice_inbox_long_description'
default:
return null
}
}
export function sectorNameKey(slug: string): string | null {
switch (slug) {
case 'general':
return 'sector_general_name'
default:
return null
}
}
export function sectorDescriptionKey(slug: string): string | null {
switch (slug) {
case 'general':
return 'sector_general_description'
default:
return null
}
}
+78
View File
@@ -0,0 +1,78 @@
import {
Camera,
Wand,
MessageSquare,
Bell,
Inbox,
Landmark,
UtensilsCrossed,
ChefHat,
Wine,
FileSpreadsheet,
HandCoins,
HardHat,
Calculator,
FolderKanban,
Hotel,
TrendingUp,
BedDouble,
Monitor,
Clock,
ReceiptText,
ShoppingCart,
Store,
BarChart3,
Layers,
Puzzle,
TextSearch,
Ship,
FileText,
Shield,
Briefcase,
Truck,
ArrowRightLeft,
Mail,
MessageCircle,
type LucideIcon,
} from 'lucide-react'
const ICON_MAP: Record<string, LucideIcon> = {
Camera,
Wand,
MessageSquare,
Bell,
Inbox,
Landmark,
UtensilsCrossed,
ChefHat,
Wine,
FileSpreadsheet,
HandCoins,
HardHat,
Calculator,
FolderKanban,
Hotel,
TrendingUp,
BedDouble,
Monitor,
Clock,
ReceiptText,
ShoppingCart,
Store,
BarChart3,
Layers,
Puzzle,
TextSearch,
Ship,
FileText,
Shield,
Briefcase,
Truck,
ArrowRightLeft,
Mail,
MessageCircle,
}
export function resolveIcon(name: string): LucideIcon {
return ICON_MAP[name] ?? Puzzle
}
+20
View File
@@ -0,0 +1,20 @@
import { extensionRegistry } from './registry'
import { FIRST_PARTY_EXTENSIONS } from './_generated/extension-list'
let loaded = false
/**
* Load and register all configured extensions.
* Idempotent: safe to call multiple times.
*
* Extensions are controlled by extensions.config.json.
* Run `npm run setup:extensions` to regenerate after config changes.
*/
export function loadExtensions(): void {
if (loaded) return
loaded = true
for (const extension of FIRST_PARTY_EXTENSIONS) {
extensionRegistry.register(extension)
}
}
+163
View File
@@ -0,0 +1,163 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { extensionRegistry } from '@/lib/extensions/registry'
import type { Invoice } from '@/types'
/**
* Core-side bridge to an extension-provided invoice payment link service.
*
* The send routes call this to auto-fill `invoices.payment_link_url` before
* the email/PDF render. Core must never import extension code, so the
* provider is resolved through the registry: an extension that exposes
* `services.createInvoicePaymentLink` (today: the Stripe extension) becomes
* the provider. With zero extensions enabled this is a no-op, keeping the
* extension-free core build and its tests untouched.
*
* The provider itself decides eligibility that only it can know (active
* connection, capability, sandbox, live/test mode) and returns null when it
* declines. This bridge handles the invoice-shaped eligibility that is true
* for ANY provider, and never throws: a payment link is a convenience, an
* invoice send must not fail because a PSP is down.
*/
export const CREATE_INVOICE_PAYMENT_LINK_SERVICE = 'createInvoicePaymentLink'
export interface ProvidedPaymentLink {
url: string
externalId: string
}
export type PaymentLinkOutcome =
| { ok: true; url: string; externalId: string }
| { ok: false; reason: string }
| null
interface MinimalLog {
warn(message: string, ...args: unknown[]): void
}
export interface ApplyPaymentLinkOptions {
/**
* Invoice number to use for link creation when the caller holds a fresher
* value than the invoice object (the v1 route re-reads the number after
* atomic allocation). The invoice object itself is not touched.
*/
invoiceNumber?: string | null
/** Route-specific prefix for the persist-failure warning message. */
logPrefix?: string
/** Extra structured context attached to the persist-failure warning. */
logContext?: Record<string, unknown>
}
export async function maybeCreatePaymentLinkForInvoice(
supabase: SupabaseClient,
companyId: string,
userId: string,
invoice: Invoice,
log?: MinimalLog,
): Promise<PaymentLinkOutcome> {
// Provider-agnostic eligibility. A manually pasted link always wins; only
// real, non-credit invoices carry a payment request; the per-invoice
// toggle opts out entirely.
if (invoice.payment_link_url) return null
if (invoice.payment_link_auto === false) return null
if (invoice.document_type && invoice.document_type !== 'invoice') return null
if (invoice.credited_invoice_id) return null
const provider = extensionRegistry
.getAll()
.find((ext) => typeof ext.services?.[CREATE_INVOICE_PAYMENT_LINK_SERVICE] === 'function')
if (!provider) return null
// Company-wide opt-in from the invoice settings page. Checked here, after
// the provider lookup (so the extension-free core build never queries), so
// every send path obeys it: dashboard, v1, MCP, recurring schedules. Fail
// closed on a read error: the feature defaults to off and a link is a
// convenience, never worth blocking a send over.
try {
const { data: settings } = await supabase
.from('company_settings')
.select('invoice_payment_links_enabled')
.eq('company_id', companyId)
.maybeSingle()
if (settings?.invoice_payment_links_enabled !== true) return null
} catch {
return null
}
try {
const result = (await provider.services![CREATE_INVOICE_PAYMENT_LINK_SERVICE](
supabase,
companyId,
userId,
invoice,
)) as ProvidedPaymentLink | null
if (result && typeof result.url === 'string' && typeof result.externalId === 'string') {
return { ok: true, url: result.url, externalId: result.externalId }
}
return null
} catch (err) {
const reason = err instanceof Error ? err.message : String(err)
log?.warn('payment link provider failed; sending without a link', {
provider: provider.id,
invoiceId: invoice.id,
reason,
})
return { ok: false, reason }
}
}
/**
* Full send-route flow: create a payment link (if a provider extension is
* enabled), persist it on the invoices row, and only then mirror it onto the
* in-memory invoice object so the email button and PDF QR carry it.
*
* Shared by the dashboard and v1 send routes. Never throws and never blocks
* the send: any failure (provider error or persist error) is returned as
* `{ failure }` for the caller to surface as a non-blocking warning. A link
* that was created but could not be persisted is deliberately NOT copied onto
* the invoice: a link rendered on the PDF but missing from the DB could never
* be matched back to this invoice when the payment event arrives.
*/
export async function applyPaymentLinkToInvoice(
supabase: SupabaseClient,
companyId: string,
userId: string,
invoice: Invoice,
log: MinimalLog,
opts: ApplyPaymentLinkOptions = {},
): Promise<{ failure: string | null }> {
const linkInvoice =
opts.invoiceNumber !== undefined
? { ...invoice, invoice_number: opts.invoiceNumber }
: invoice
const outcome = await maybeCreatePaymentLinkForInvoice(
supabase,
companyId,
userId,
linkInvoice,
log,
)
if (!outcome) return { failure: null }
if (!outcome.ok) return { failure: outcome.reason }
const { error: persistError } = await supabase
.from('invoices')
.update({
payment_link_url: outcome.url,
stripe_payment_link_id: outcome.externalId,
})
.eq('id', invoice.id)
.eq('company_id', companyId)
if (persistError) {
log.warn(
`${opts.logPrefix ?? ''}payment link created but not persisted; sending without it`,
opts.logContext ? { ...opts.logContext, err: persistError } : persistError,
)
return { failure: persistError.message }
}
invoice.payment_link_url = outcome.url
invoice.stripe_payment_link_id = outcome.externalId
return { failure: null }
}
+120
View File
@@ -0,0 +1,120 @@
import { eventBus } from '@/lib/events/bus'
import type { CoreEventType } from '@/lib/events/types'
import type { Extension, ExtensionContext } from './types'
import type { SupabaseClient } from '@supabase/supabase-js'
/** Factory function type for creating extension contexts */
export type ContextFactory = (
supabase: SupabaseClient,
userId: string,
companyId: string,
extensionId: string
) => ExtensionContext
/** Lazy-loaded context factory: set during initialization */
let contextFactory: ContextFactory | null = null
/**
* Set the context factory used to build ExtensionContext for event handlers.
* Called once during system initialization.
*/
export function setContextFactory(factory: ContextFactory): void {
contextFactory = factory
}
/**
* Extension Registry: singleton that manages extension lifecycle.
*
* - register() stores extension and wires event handlers to the bus
* - unregister() unhooks handlers and removes extension
* - getAll(), get(), getByCapability() for querying
*/
class ExtensionRegistry {
private extensions = new Map<string, Extension>()
private unsubscribers = new Map<string, (() => void)[]>()
/**
* Register an extension: store it and wire its event handlers to the bus.
*
* Each handler is wrapped so it receives `(payload, ctx)`. The context is
* built lazily when the event fires, using the userId from the payload and
* a Supabase client created from the current request cookies.
*/
register(extension: Extension): void {
if (this.extensions.has(extension.id)) {
// Extension already registered: skip silently (expected during hot reloads)
return
}
this.extensions.set(extension.id, extension)
// Wire event handlers to the bus
const unsubs: (() => void)[] = []
if (extension.eventHandlers) {
for (const { eventType, handler } of extension.eventHandlers) {
// Wrap handler to inject ExtensionContext as second argument
const wrappedHandler = async (payload: { userId: string; companyId?: string; [key: string]: unknown }) => {
let ctx: ExtensionContext | undefined
if (contextFactory && payload.userId) {
try {
// Dynamic import to avoid circular deps at module load time
const { createClient } = await import('@/lib/supabase/server')
const supabase = await createClient()
const companyId = payload.companyId ?? payload.userId // fallback for legacy events
ctx = contextFactory(supabase, payload.userId, companyId, extension.id)
} catch {
// Context creation failed (e.g. no request cookies in cron jobs).
// Handler still gets called: ctx will be undefined.
}
}
return handler(payload, ctx)
}
const unsub = eventBus.on(eventType as CoreEventType, wrappedHandler)
unsubs.push(unsub)
}
}
this.unsubscribers.set(extension.id, unsubs)
}
/**
* Unregister an extension: unhook all event handlers and remove.
*/
unregister(extensionId: string): void {
const unsubs = this.unsubscribers.get(extensionId)
if (unsubs) {
for (const unsub of unsubs) {
unsub()
}
this.unsubscribers.delete(extensionId)
}
this.extensions.delete(extensionId)
}
/** Get all registered extensions. */
getAll(): Extension[] {
return [...this.extensions.values()]
}
/** Get a specific extension by ID. */
get(id: string): Extension | undefined {
return this.extensions.get(id)
}
/** Get all extensions that have a specific capability. */
getByCapability(key: keyof Extension): Extension[] {
return [...this.extensions.values()].filter(
(ext) => ext[key] !== undefined && ext[key] !== null
)
}
/** Clear all extensions (useful for testing). */
clear(): void {
for (const id of this.extensions.keys()) {
this.unregister(id)
}
}
}
/** Module-level singleton */
export const extensionRegistry = new ExtensionRegistry()
+77
View File
@@ -0,0 +1,77 @@
import type { Sector, SectorSlug, ExtensionDefinition } from './types'
import { EXTENSION_DEFINITIONS } from './_generated/sector-definitions'
import { WORKSPACES } from './_generated/workspace-map'
import { requiredCapabilityForExtension } from '@/lib/entitlements/keys'
import type { CapabilityKey } from '@/lib/entitlements/keys'
// ============================================================
// Sector & Extension Registry
// ============================================================
//
// Sector shells are structural and always present.
// Extension definitions per sector come from the generated file
// (controlled by extensions.config.json).
// ============================================================
/** Sector shells: structural metadata, always available */
const SECTOR_SHELLS: Omit<Sector, 'extensions'>[] = [
{
slug: 'general',
name: 'Generella verktyg',
icon: 'Layers',
description: 'Verktyg som passar alla verksamheter',
},
]
/** Full sectors with extensions merged from generated definitions */
export const SECTORS: Sector[] = SECTOR_SHELLS.map(shell => ({
...shell,
extensions: EXTENSION_DEFINITIONS[shell.slug] ?? [],
}))
// ============================================================
// Helper functions
// ============================================================
export function getSector(slug: SectorSlug): Sector | undefined {
return SECTORS.find(s => s.slug === slug)
}
export function getExtensionDefinition(sectorSlug: string, extensionSlug: string): ExtensionDefinition | undefined {
const sector = SECTORS.find(s => s.slug === sectorSlug)
return sector?.extensions.find(e => e.slug === extensionSlug)
}
/**
* Paid capability an extension requires, resolved by its registry id (== slug).
* The API-route dispatcher keys off this so a paid extension is gated at the
* request chokepoint, reusing the same EXTENSION_REQUIRED_CAPABILITY map that
* hides its sidebar item and blocks its page (lib/entitlements/keys).
*/
export function requiredCapabilityForExtensionId(extensionId: string): CapabilityKey | undefined {
const ext = getAllExtensions().find(e => e.slug === extensionId)
return ext ? requiredCapabilityForExtension(ext.sector, ext.slug) : undefined
}
export function getAllExtensions(): ExtensionDefinition[] {
return SECTORS.flatMap(s => s.extensions)
}
export function getExtensionsBySector(slug: SectorSlug): ExtensionDefinition[] {
return getSector(slug)?.extensions ?? []
}
/** Extensions with a workspace and a quickAction href, for sidebar nav. */
export function getExtensionNavItems(): { href: string; label: string; icon: string }[] {
return getAllExtensions()
.filter(e => {
const key = `${e.sector}/${e.slug}`
return key in WORKSPACES && !!e.quickAction?.href
})
.sort((a, b) => (a.quickAction!.order ?? 0) - (b.quickAction!.order ?? 0))
.map(e => ({
href: e.quickAction!.href!,
label: e.quickAction!.label,
icon: e.quickAction!.icon,
}))
}
@@ -0,0 +1,39 @@
import dynamic from 'next/dynamic'
import type { ComponentType } from 'react'
/**
* Settings panel registry
*
* Maps extension IDs to dynamically imported settings panel components.
* This allows the core settings page to render extension-provided settings
* panels without directly importing from extension directories.
*/
const SETTINGS_PANELS: Record<string, ComponentType> = {
'enable-banking': dynamic(
() => import('@/extensions/general/enable-banking/components/BankingSettingsPanel')
),
'cloud-backup': dynamic(
() => import('@/extensions/general/cloud-backup/components/CloudBackupCard')
),
stripe: dynamic(
() => import('@/extensions/general/stripe/components/StripeSettingsPanel')
),
woocommerce: dynamic(
() => import('@/extensions/general/woocommerce/components/WooCommerceSettingsPanel')
),
shopify: dynamic(
() => import('@/extensions/general/shopify/components/ShopifySettingsPanel')
),
zettle: dynamic(
() => import('@/extensions/general/zettle/components/ZettleSettingsPanel')
),
}
/**
* Get the settings panel component for an extension.
* Returns null if the extension has no registered settings panel.
*/
export function getSettingsPanel(extensionId: string): ComponentType | null {
return SETTINGS_PANELS[extensionId] ?? null
}
+239
View File
@@ -0,0 +1,239 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { CoreEvent, CoreEventType } from '@/lib/events/types'
import type {
CashAccount,
EntityType,
IngestOptions,
IngestResult,
RawTransaction,
} from '@/types'
// ============================================================
// Extension Marketplace Types
// ============================================================
/** Extension category for marketplace grouping */
export type ExtensionCategory = 'accounting' | 'reports' | 'import' | 'operations'
/** Sector slugs for extension organization */
export type SectorSlug = 'general'
/** How an extension gets its data */
export type ExtensionDataPattern = 'core' | 'manual' | 'both'
/** Dashboard quick action declared by an extension */
export interface QuickActionDefinition {
label: string
description: string
icon: string
href?: string
event?: string
order?: number
}
/** Extension metadata for the marketplace and workspace routing */
export interface ExtensionDefinition {
slug: string
name: string
sector: SectorSlug
category: ExtensionCategory
description: string
longDescription: string
icon: string
entityTypes?: EntityType[]
dataPattern: ExtensionDataPattern
readsCoreTables?: string[]
hasOwnData?: boolean
quickAction?: QuickActionDefinition
/** Notice shown when enabling: e.g. external subscription requirement */
subscriptionNotice?: string
}
/** Sector definition with its extensions */
export interface Sector {
slug: SectorSlug
name: string
icon: string
description: string
extensions: ExtensionDefinition[]
}
// ============================================================
// Extension Interface & Supporting Types
// ============================================================
/** A route exposed by an extension (page route) */
export interface RouteDefinition {
path: string
label: string
}
/**
* An API route exposed by an extension.
*
* Auth/context modes (mutually exclusive: combining throws at dispatch time):
* - default: requires auth AND a resolved company; ctx is passed to the handler
* - `skipAuth: true`: no auth, no ctx (e.g. OAuth callbacks)
* - `skipCompanyContext: true`: auth required, no ctx (pre-onboarding routes)
*/
export interface ApiRouteDefinition {
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
path: string
/** Skip auth check for this route (e.g. OAuth callbacks from external providers) */
skipAuth?: boolean
/**
* Require auth but NOT a resolved company context. Use for routes that
* legitimately run during onboarding (before the user has a company):
* e.g. TIC /lookup used by Step2CompanyDetails to fetch company info
* while the user types their org number. Handler is called without a
* ctx argument; handlers that opt in must tolerate a missing context.
*
* Must NOT be combined with `skipAuth: true`: the dispatcher treats
* that as a misconfiguration and returns 500.
*/
skipCompanyContext?: boolean
handler: (request: Request, ctx?: ExtensionContext) => Promise<Response>
}
/** Sidebar navigation item added by an extension */
export interface SidebarItem {
label: string
icon?: string
path: string
order?: number
}
/** Report type added by an extension */
export interface ReportDefinition {
id: string
name: string
description: string
}
/** Settings panel exposed by an extension */
export interface SettingsPanelDefinition {
label: string
path: string
}
/** Tax code definition added by an extension */
export interface TaxCodeDefinition {
code: string
rate: number
description: string
}
/** Dimension type definition added by an extension */
export interface DimensionDefinition {
id: string
name: string
description: string
}
/** Mapping rule type added by an extension */
export interface MappingRuleTypeDefinition {
id: string
name: string
description: string
}
/** Event handler registration for an extension */
export interface ExtensionEventHandler {
eventType: CoreEventType
// eslint-disable-next-line @typescript-eslint/no-explicit-any
handler: (payload: any, ctx?: ExtensionContext) => Promise<void> | void
}
/** Logger interface for extensions */
export interface ExtensionLogger {
info(message: string, ...args: unknown[]): void
warn(message: string, ...args: unknown[]): void
error(message: string, ...args: unknown[]): void
}
/** Settings accessor for extension-scoped key-value data */
export interface ExtensionSettings {
get<T>(key?: string): Promise<T | null>
set<T>(key: string, value: T): Promise<void>
/**
* Remove a stored key. Use this to clear state instead of `set(key, null)`,
* which fails against the `value jsonb NOT NULL` constraint on extension_data.
* No-op when the key does not exist.
*/
clear(key: string): Promise<void>
}
/** Storage accessor wrapping Supabase storage */
export interface ExtensionStorage {
download(bucket: string, path: string): Promise<{ data: Blob | null; error?: string }>
upload(bucket: string, path: string, data: ArrayBuffer, options?: { contentType?: string }): Promise<{ path: string; error?: string }>
getPublicUrl(bucket: string, path: string): string
}
/** Core services exposed to extensions */
export interface ExtensionServices {
ingestTransactions(supabase: SupabaseClient, companyId: string, userId: string, raw: RawTransaction[], options?: IngestOptions): Promise<IngestResult>
/**
* List a company's cash accounts (cash_accounts table). Replaces ad-hoc reads
* of bank_connections.accounts_data for routing decisions. Returns rows
* sorted by `is_primary DESC, ledger_account ASC`.
*/
getCashAccounts(supabase: SupabaseClient, companyId: string, opts?: { enabledOnly?: boolean }): Promise<CashAccount[]>
/**
* Primary cash account for a company, optionally filtered by currency.
* Falls back to the global primary when no currency-specific row matches.
* Used by the skattekonto __PRIMARY_SEK__ sentinel and transfer-pairing.
*/
getPrimaryCashAccount(supabase: SupabaseClient, companyId: string, currency?: string): Promise<CashAccount | null>
}
/** Context passed to extension lifecycle hooks and event handlers */
export interface ExtensionContext {
userId: string
companyId: string
extensionId: string
/**
* Stable id for the inbound HTTP request: `req_<uuid>`.
* Included in the response envelope and in the `X-Request-Id` header so
* support staff can grep stdout logs by it.
*/
requestId?: string
supabase: SupabaseClient
emit(event: CoreEvent): Promise<void>
settings: ExtensionSettings
storage: ExtensionStorage
log: ExtensionLogger
services: ExtensionServices
}
/**
* Extension interface: the contract for all add-ons.
*
* Extensions declare what they provide (routes, event handlers, sidebar items, etc.)
* and the registry wires them into the system.
*/
export interface Extension {
id: string
name: string
version: string
sector?: SectorSlug
// Surfaces
routes?: RouteDefinition[]
apiRoutes?: ApiRouteDefinition[]
sidebarItems?: SidebarItem[]
eventHandlers?: ExtensionEventHandler[]
mappingRuleTypes?: MappingRuleTypeDefinition[]
reportTypes?: ReportDefinition[]
settingsPanel?: SettingsPanelDefinition
taxCodes?: TaxCodeDefinition[]
dimensionTypes?: DimensionDefinition[]
/** Named services this extension provides to core via registry lookup */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
services?: Record<string, (...args: any[]) => Promise<any>>
// Lifecycle hooks
onInstall?(ctx: ExtensionContext): Promise<void>
onUninstall?(ctx: ExtensionContext): Promise<void>
}
+86
View File
@@ -0,0 +1,86 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
interface ExtensionDataRecord {
id: string
key: string
value: Record<string, unknown>
created_at: string
updated_at: string
}
export function useExtensionData(sector: string, slug: string) {
const [data, setData] = useState<ExtensionDataRecord[]>([])
const [isLoading, setIsLoading] = useState(true)
const basePath = `/api/extensions/${sector}/${slug}/data`
const mountedRef = useRef(true)
useEffect(() => {
mountedRef.current = true
return () => { mountedRef.current = false }
}, [])
const refresh = useCallback(async () => {
setIsLoading(true)
try {
const res = await fetch(basePath)
if (res.ok) {
const json = await res.json()
if (mountedRef.current) setData(json.data ?? [])
}
} finally {
if (mountedRef.current) setIsLoading(false)
}
}, [basePath])
useEffect(() => {
refresh()
}, [refresh])
const save = useCallback(async (key: string, value: Record<string, unknown>) => {
const res = await fetch(basePath, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value }),
})
if (res.ok) {
const json = await res.json()
setData(prev => {
const idx = prev.findIndex(d => d.key === key)
if (idx >= 0) {
const updated = [...prev]
updated[idx] = json.data
return updated
}
return [...prev, json.data]
})
return json.data
}
return null
}, [basePath])
const remove = useCallback(async (key: string) => {
const res = await fetch(`${basePath}?key=${encodeURIComponent(key)}`, {
method: 'DELETE',
})
if (res.ok) {
setData(prev => prev.filter(d => d.key !== key))
}
}, [basePath])
const getByPrefix = useCallback(async (prefix: string): Promise<ExtensionDataRecord[]> => {
const res = await fetch(`${basePath}?prefix=${encodeURIComponent(prefix)}`)
if (res.ok) {
const json = await res.json()
return json.data ?? []
}
return []
}, [basePath])
const getByKey = useCallback((key: string) => {
return data.find(d => d.key === key) ?? null
}, [data])
return { data, isLoading, save, remove, getByPrefix, getByKey, refresh }
}
+62
View File
@@ -0,0 +1,62 @@
import { luhnValidate } from '@/lib/bankgiro/luhn'
/**
* Validates a Swedish personal number (YYYYMMDD-XXXX) using Luhn checksum.
* Returns an error message string, or null if valid.
*/
export function validateSwedishPersonalNumber(pnr: string): string | null {
if (!pnr) return 'Personnummer kravs'
// Accept YYYYMMDD-XXXX or YYYYMMDDXXXX
const cleaned = pnr.replace(/[-\s]/g, '')
if (!/^\d{12}$/.test(cleaned)) {
return 'Format: YYYYMMDD-XXXX (12 siffror)'
}
const year = parseInt(cleaned.slice(0, 4))
const month = parseInt(cleaned.slice(4, 6))
const day = parseInt(cleaned.slice(6, 8))
if (month < 1 || month > 12) return 'Ogiltig månad'
if (day < 1 || day > 31) return 'Ogiltig dag'
if (year < 1900 || year > new Date().getFullYear()) return 'Ogiltigt år'
// Luhn check on the last 10 digits (YYMMDDXXXX)
const luhnDigits = cleaned.slice(2)
if (!luhnValidate(luhnDigits)) return 'Ogiltig kontrollsiffra'
return null
}
export function validatePositiveNumber(value: number | string): string | null {
const num = typeof value === 'string' ? parseFloat(value) : value
if (isNaN(num) || num <= 0) return 'Varde maste vara storre an 0'
return null
}
export function validateNonNegativeNumber(value: number | string): string | null {
const num = typeof value === 'string' ? parseFloat(value) : value
if (isNaN(num) || num < 0) return 'Varde kan inte vara negativt'
return null
}
export function validateMaxNumber(value: number | string, max: number): string | null {
const num = typeof value === 'string' ? parseFloat(value) : value
if (isNaN(num)) return 'Ogiltigt varde'
if (num > max) return `Varde kan inte overskrida ${max}`
return null
}
export function validateRequired(value: string | number | undefined | null): string | null {
if (value === undefined || value === null || value === '') return 'Obligatoriskt falt'
return null
}
export function validateDateNotFuture(dateStr: string): string | null {
if (!dateStr) return 'Datum kravs'
const date = new Date(dateStr)
const today = new Date()
today.setHours(23, 59, 59, 999)
if (date > today) return 'Datum kan inte vara i framtiden'
return null
}
+13
View File
@@ -0,0 +1,13 @@
import type { ComponentType } from 'react'
import { WORKSPACES } from './_generated/workspace-map'
export interface WorkspaceComponentProps {
userId: string
}
export function getWorkspaceComponent(
sector: string,
slug: string
): ComponentType<WorkspaceComponentProps> | null {
return WORKSPACES[`${sector}/${slug}`] ?? null
}