* 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>
155 lines
4.5 KiB
TypeScript
155 lines
4.5 KiB
TypeScript
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 { 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,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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(),
|
|
}
|
|
}
|