8a6ce7093e
* feat: implement skattekonto drift detection and alerting - Add skattekonto drift computation logic to compare Skatteverket's saldo with GL 1630 sum. - Implement alerting mechanism for significant drift changes, with throttling to prevent alert spamming. - Introduce database functions to sum GL 1630 entries and list unbooked skattekonto rows. feat: create own account transfer detection - Develop logic to detect transfers between a company's own cash accounts based on counterparty IBAN. - Implement tests to validate detection logic under various scenarios, including matching and non-matching IBANs. feat: establish cash accounts as a first-class entity - Create cash_accounts table to manage routable cash accounts, replacing ad-hoc JSONB structures. - Implement functions for listing, upserting, and managing cash accounts, including primary account designation. feat: enhance GL line reconciliation functionality - Modify get_unlinked_1930_lines RPC to accept any account number for reconciliation, improving flexibility for different currencies. - Update related functions to ensure compatibility with the new cash_accounts structure. feat: capture counterparty IBAN in transactions - Add counterparty_iban column to transactions table to facilitate intra-account transfer detection. - Create index for efficient lookups based on counterparty IBAN. * feat: Enhance cash account handling and reconciliation processes - Updated reconciliation routes to enforce cash account validation for all account numbers, including '1930'. - Improved error handling for unknown cash accounts in reconciliation status and unmatched entries routes. - Changed CashAccountSelector to use sessionStorage instead of localStorage for better data privacy. - Fixed mapping for employer payroll taxes to route to the correct account (2730 instead of 2731). - Added safety checks for company IDs in the guessCounterAccount function to prevent injection vulnerabilities. - Introduced atomic RPC for setting primary cash accounts to avoid intermediate states during updates. - Seeded default cash accounts for new companies to ensure reconciliation routes are accessible from day one. - Updated email notifications for drift detection to avoid exposing sensitive financial data. - Enhanced bank reconciliation logic to handle multi-currency transactions correctly. - Renamed and updated tests to reflect changes in the underlying RPCs and ensure accurate coverage. - Migrated existing cash account rules to correct mappings in compliance with Swedish accounting standards.
159 lines
4.8 KiB
TypeScript
159 lines
4.8 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 { 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(),
|
|
}
|
|
}
|