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>
This commit is contained in:
Mattsson
2026-03-31 16:41:52 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 1756af6c5e
commit 0dd1f5ebc1
290 changed files with 7690 additions and 1339 deletions
+5 -5
View File
@@ -33,7 +33,7 @@ export async function getAuditLog(
let query = supabase
.from('audit_log')
.select('*', { count: 'exact' })
.eq('user_id', userId)
.eq('company_id', userId)
.order('created_at', { ascending: false })
.range(offset, offset + pageSize - 1)
@@ -78,7 +78,7 @@ export async function getEntityHistory(
const { data, error } = await supabase
.from('audit_log')
.select('*')
.eq('user_id', userId)
.eq('company_id', userId)
.eq('table_name', tableName)
.eq('record_id', recordId)
.order('created_at', { ascending: true })
@@ -105,7 +105,7 @@ export async function getCorrectionChain(
.from('journal_entries')
.select('id, reverses_id, reversed_by_id, correction_of_id')
.eq('id', journalEntryId)
.eq('user_id', userId)
.eq('company_id', userId)
.single()
if (entryError || !entry) {
@@ -122,7 +122,7 @@ export async function getCorrectionChain(
const { data: referencing } = await supabase
.from('journal_entries')
.select('id')
.eq('user_id', userId)
.eq('company_id', userId)
.or(`reverses_id.eq.${journalEntryId},reversed_by_id.eq.${journalEntryId},correction_of_id.eq.${journalEntryId}`)
for (const ref of referencing || []) {
@@ -133,7 +133,7 @@ export async function getCorrectionChain(
const { data, error } = await supabase
.from('audit_log')
.select('*')
.eq('user_id', userId)
.eq('company_id', userId)
.eq('table_name', 'journal_entries')
.in('record_id', Array.from(relatedIds))
.order('created_at', { ascending: true })
@@ -53,7 +53,7 @@ describe('lockPeriod', () => {
eventBus.on('period.locked', handler)
const supabase = makeClient()
const result = await lockPeriod(supabase as never, 'user-1', 'fp-1')
const result = await lockPeriod(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.locked_at).toBeTruthy()
expect(handler).toHaveBeenCalledOnce()
@@ -69,7 +69,7 @@ describe('lockPeriod', () => {
results = [{ data: period, error: null }]
const supabase = makeClient()
await expect(lockPeriod(supabase as never, 'user-1', 'fp-1')).rejects.toThrow('already locked')
await expect(lockPeriod(supabase as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow('already locked')
})
})
@@ -89,7 +89,7 @@ describe('closePeriod', () => {
]
const supabase = makeClient()
const result = await closePeriod(supabase as never, 'user-1', 'fp-1')
const result = await closePeriod(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.is_closed).toBe(true)
})
@@ -104,7 +104,7 @@ describe('closePeriod', () => {
results = [{ data: period, error: null }]
const supabase = makeClient()
await expect(closePeriod(supabase as never, 'user-1', 'fp-1')).rejects.toThrow('must be locked')
await expect(closePeriod(supabase as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow('must be locked')
})
it('rejects if no closing_entry_id', async () => {
@@ -118,7 +118,7 @@ describe('closePeriod', () => {
results = [{ data: period, error: null }]
const supabase = makeClient()
await expect(closePeriod(supabase as never, 'user-1', 'fp-1')).rejects.toThrow(
await expect(closePeriod(supabase as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
'Year-end closing must be executed'
)
})
@@ -147,7 +147,7 @@ describe('createNextPeriod', () => {
]
const supabase = makeClient()
const result = await createNextPeriod(supabase as never, 'user-1', 'fp-2024')
const result = await createNextPeriod(supabase as never, 'company-1', 'user-1', 'fp-2024')
expect(result.period_start).toBe('2025-01-01')
expect(result.period_end).toBe('2025-12-31')
expect(result.previous_period_id).toBe('fp-2024')
@@ -175,7 +175,7 @@ describe('createNextPeriod', () => {
]
const supabase = makeClient()
const result = await createNextPeriod(supabase as never, 'user-1', 'fp-2024')
const result = await createNextPeriod(supabase as never, 'company-1', 'user-1', 'fp-2024')
expect(result.period_start).toBe('2024-07-01')
expect(result.period_end).toBe('2025-06-30')
})
@@ -98,7 +98,7 @@ describe('correctEntry', () => {
it('creates reversal with swapped debit/credit lines', async () => {
setupResults()
const supabase = makeClient()
const result = await correctEntry(supabase as never, 'user-1', 'orig-1', correctedLines)
const result = await correctEntry(supabase as never, 'company-1', 'user-1', 'orig-1', correctedLines)
expect(result.reversal).toBeDefined()
expect(result.reversal.reverses_id).toBe('orig-1')
})
@@ -106,7 +106,7 @@ describe('correctEntry', () => {
it('links original ↔ reversal ↔ corrected via IDs', async () => {
setupResults()
const supabase = makeClient()
const result = await correctEntry(supabase as never, 'user-1', 'orig-1', correctedLines)
const result = await correctEntry(supabase as never, 'company-1', 'user-1', 'orig-1', correctedLines)
expect(result.reversal.id).toBe('reversal-1')
expect(result.corrected.id).toBe('corrected-1')
expect(result.corrected.correction_of_id).toBe('orig-1')
@@ -121,7 +121,7 @@ describe('correctEntry', () => {
const supabase = makeClient()
await expect(
correctEntry(supabase as never, 'user-1', 'orig-1', [
correctEntry(supabase as never, 'company-1', 'user-1', 'orig-1', [
{ account_number: '5420', debit_amount: 1200, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 1000 },
])
@@ -135,11 +135,11 @@ describe('correctEntry', () => {
eventBus.on('journal_entry.corrected', handler)
const supabase = makeClient()
await correctEntry(supabase as never, 'user-1', 'orig-1', correctedLines)
await correctEntry(supabase as never, 'company-1', 'user-1', 'orig-1', correctedLines)
expect(handler).toHaveBeenCalledOnce()
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({ userId: 'user-1' })
expect.objectContaining({ userId: 'user-1', companyId: 'company-1' })
)
})
})
@@ -95,7 +95,7 @@ describe('validateYearEndReadiness', () => {
} as never)
const supabase = makeClient()
const result = await validateYearEndReadiness(supabase as never, 'user-1', 'fp-1')
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.ready).toBe(false)
expect(result.errors.some((e: string) => e.includes('draft'))).toBe(true)
})
@@ -120,7 +120,7 @@ describe('validateYearEndReadiness', () => {
} as never)
const supabase = makeClient()
const result = await validateYearEndReadiness(supabase as never, 'user-1', 'fp-1')
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.ready).toBe(false)
expect(result.trialBalanceBalanced).toBe(false)
expect(result.errors.some((e: string) => e.includes('Trial balance'))).toBe(true)
@@ -156,7 +156,7 @@ describe('validateYearEndReadiness', () => {
totalCredit: 10000,
} as never)
const result = await validateYearEndReadiness(supabase as never, 'user-1', 'fp-1')
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.some((w: string) => w.includes('gap'))).toBe(true)
expect(result.voucherGaps).toHaveLength(1)
})
@@ -187,7 +187,7 @@ describe('previewYearEndClosing', () => {
} as never)
const supabase = makeClient()
const preview = await previewYearEndClosing(supabase as never, 'user-1', 'fp-1')
const preview = await previewYearEndClosing(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(preview.netResult).toBe(150000)
expect(preview.closingAccount).toBe('2099')
@@ -215,7 +215,7 @@ describe('previewYearEndClosing', () => {
} as never)
const supabase = makeClient()
const preview = await previewYearEndClosing(supabase as never, 'user-1', 'fp-1')
const preview = await previewYearEndClosing(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(preview.closingAccount).toBe('2010')
expect(preview.closingAccountName).toBe('Eget kapital')
+17 -12
View File
@@ -5,10 +5,11 @@ import type { FiscalPeriod, PeriodStatus } from '@/types'
/**
* Lock a fiscal period — prevents new journal entries from being posted.
* Requires: period exists, belongs to user, not already locked/closed.
* Requires: period exists, belongs to company, not already locked/closed.
*/
export async function lockPeriod(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<FiscalPeriod> {
@@ -18,7 +19,7 @@ export async function lockPeriod(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !period) {
@@ -37,7 +38,7 @@ export async function lockPeriod(
const { count: unbookedCount } = await supabase
.from('transactions')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.is('journal_entry_id', null)
.eq('is_business', true)
.gte('date', period.period_start)
@@ -53,7 +54,7 @@ export async function lockPeriod(
.from('fiscal_periods')
.update({ locked_at: new Date().toISOString() })
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.select()
.single()
@@ -65,7 +66,7 @@ export async function lockPeriod(
await eventBus.emit({
type: 'period.locked',
payload: { period: result, userId },
payload: { period: result, companyId, userId },
})
return result
@@ -77,6 +78,7 @@ export async function lockPeriod(
*/
export async function closePeriod(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<FiscalPeriod> {
@@ -85,7 +87,7 @@ export async function closePeriod(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !period) {
@@ -111,7 +113,7 @@ export async function closePeriod(
closed_at: new Date().toISOString(),
})
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.select()
.single()
@@ -129,6 +131,7 @@ export async function closePeriod(
*/
export async function createNextPeriod(
supabase: SupabaseClient,
companyId: string,
userId: string,
currentPeriodId: string
): Promise<FiscalPeriod> {
@@ -137,7 +140,7 @@ export async function createNextPeriod(
.from('fiscal_periods')
.select('*')
.eq('id', currentPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !current) {
@@ -177,7 +180,7 @@ export async function createNextPeriod(
const { data: overlapping } = await supabase
.from('fiscal_periods')
.select('id')
.eq('user_id', userId)
.eq('company_id', companyId)
.lte('period_start', nextEndStr)
.gte('period_end', nextStartStr)
.limit(1)
@@ -194,6 +197,7 @@ export async function createNextPeriod(
const { data: newPeriod, error: insertError } = await supabase
.from('fiscal_periods')
.insert({
company_id: companyId,
user_id: userId,
name,
period_start: nextStartStr,
@@ -215,6 +219,7 @@ export async function createNextPeriod(
*/
export async function getPeriodStatus(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<PeriodStatus> {
@@ -223,7 +228,7 @@ export async function getPeriodStatus(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !period) {
@@ -234,7 +239,7 @@ export async function getPeriodStatus(
const { count: draftCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'draft')
@@ -245,7 +250,7 @@ export async function getPeriodStatus(
const { data: nextPeriod } = await supabase
.from('fiscal_periods')
.select('id')
.eq('user_id', userId)
.eq('company_id', companyId)
.eq('previous_period_id', fiscalPeriodId)
.maybeSingle()
+8 -4
View File
@@ -24,6 +24,7 @@ import { validateBalance, getNextVoucherNumber, getSwedishLocalDate } from '@/li
*/
export async function correctEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
originalEntryId: string,
correctedLines: CreateJournalEntryLineInput[]
@@ -41,7 +42,7 @@ export async function correctEntry(
.from('journal_entries')
.select('*, lines:journal_entry_lines(*)')
.eq('id', originalEntryId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !original) {
@@ -57,7 +58,7 @@ export async function correctEntry(
// ===== Step 1: Create storno (reversal) entry =====
const reversalVoucherNumber = await getNextVoucherNumber(
supabase,
userId,
companyId,
original.fiscal_period_id,
original.voucher_series || 'A'
)
@@ -65,6 +66,7 @@ export async function correctEntry(
const { data: reversalEntry, error: reversalError } = await supabase
.from('journal_entries')
.insert({
company_id: companyId,
user_id: userId,
fiscal_period_id: original.fiscal_period_id,
voucher_number: reversalVoucherNumber,
@@ -147,7 +149,7 @@ export async function correctEntry(
try {
const correctedVoucherNumber = await getNextVoucherNumber(
supabase,
userId,
companyId,
original.fiscal_period_id,
original.voucher_series || 'A'
)
@@ -157,7 +159,7 @@ export async function correctEntry(
const { data: accounts } = await supabase
.from('chart_of_accounts')
.select('id, account_number')
.eq('user_id', userId)
.eq('company_id', companyId)
.in('account_number', accountNumbers)
const accountIdMap = new Map<string, string>()
@@ -168,6 +170,7 @@ export async function correctEntry(
const { data: newEntry, error: correctedError } = await supabase
.from('journal_entries')
.insert({
company_id: companyId,
user_id: userId,
fiscal_period_id: original.fiscal_period_id,
voucher_number: correctedVoucherNumber,
@@ -254,6 +257,7 @@ export async function correctEntry(
original: original as JournalEntry,
storno: result.reversal,
corrected: result.corrected,
companyId,
userId,
},
})
+35 -29
View File
@@ -24,6 +24,7 @@ import type {
*/
export async function validateYearEndReadiness(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<YearEndValidation> {
@@ -35,7 +36,7 @@ export async function validateYearEndReadiness(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (fetchError || !period) {
@@ -63,7 +64,7 @@ export async function validateYearEndReadiness(
const { count: draftCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'draft')
@@ -75,7 +76,7 @@ export async function validateYearEndReadiness(
// Check: voucher continuity
let voucherGaps: VoucherGap[] = []
const { data: gaps, error: gapsError } = await supabase.rpc('detect_voucher_gaps', {
p_user_id: userId,
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: 'A',
})
@@ -88,7 +89,7 @@ export async function validateYearEndReadiness(
}
// Check: trial balance is balanced
const trialBalance = await generateTrialBalance(supabase, userId, fiscalPeriodId)
const trialBalance = await generateTrialBalance(supabase, companyId, fiscalPeriodId)
const trialBalanceBalanced = trialBalance.isBalanced
if (!trialBalanceBalanced) {
@@ -101,7 +102,7 @@ export async function validateYearEndReadiness(
const { count: entryCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'posted')
@@ -113,7 +114,7 @@ export async function validateYearEndReadiness(
const { count: revalCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('source_type', 'currency_revaluation')
.eq('status', 'posted')
@@ -123,7 +124,7 @@ export async function validateYearEndReadiness(
const { count: fxReceivables } = await supabase
.from('invoices')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.in('status', ['sent', 'overdue'])
.neq('currency', 'SEK')
.not('exchange_rate', 'is', null)
@@ -131,7 +132,7 @@ export async function validateYearEndReadiness(
const { count: fxPayables } = await supabase
.from('supplier_invoices')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('company_id', companyId)
.in('status', ['registered', 'approved', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
.not('exchange_rate', 'is', null)
@@ -159,6 +160,7 @@ export async function validateYearEndReadiness(
*/
export async function previewYearEndClosing(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<YearEndPreview> {
@@ -167,7 +169,7 @@ export async function previewYearEndClosing(
const { data: settings } = await supabase
.from('company_settings')
.select('entity_type')
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
const entityType = settings?.entity_type ?? 'aktiebolag'
@@ -178,11 +180,11 @@ export async function previewYearEndClosing(
: 'Årets resultat'
// Get income statement for net result
const incomeStatement = await generateIncomeStatement(supabase, userId, fiscalPeriodId)
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
const netResult = incomeStatement.net_result
// Get trial balance for individual account balances in class 3-8
const { rows } = await generateTrialBalance(supabase, userId, fiscalPeriodId)
const { rows } = await generateTrialBalance(supabase, companyId, fiscalPeriodId)
const resultAccounts = rows.filter(
(r) => r.account_class >= 3 && r.account_class <= 8
)
@@ -255,14 +257,14 @@ export async function previewYearEndClosing(
.from('fiscal_periods')
.select('period_end')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
let currencyRevaluation = null
if (periodData) {
const revalPreview = await previewCurrencyRevaluation(
supabase,
userId,
companyId,
periodData.period_end
)
if (revalPreview.items.length > 0) {
@@ -293,11 +295,12 @@ export async function previewYearEndClosing(
*/
export async function executeYearEndClosing(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string
): Promise<YearEndResult> {
// 1. Validate readiness
const validation = await validateYearEndReadiness(supabase, userId, fiscalPeriodId)
const validation = await validateYearEndReadiness(supabase, companyId, userId, fiscalPeriodId)
if (!validation.ready) {
throw new Error(`Year-end closing not ready: ${validation.errors.join('; ')}`)
}
@@ -307,7 +310,7 @@ export async function executeYearEndClosing(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (!period) {
@@ -319,20 +322,21 @@ export async function executeYearEndClosing(
// the closing entry then zeros out.
const revaluationResult = await executeCurrencyRevaluation(
supabase,
userId,
companyId,
period.period_end,
fiscalPeriodId
fiscalPeriodId,
userId
)
// 3. Get closing preview (now includes revaluation effects in trial balance)
const preview = await previewYearEndClosing(supabase, userId, fiscalPeriodId)
const preview = await previewYearEndClosing(supabase, companyId, userId, fiscalPeriodId)
if (preview.closingLines.length === 0) {
throw new Error('No result accounts to close — period has no activity')
}
// 4. Create closing entry via the journal engine
const closingEntry = await createJournalEntry(supabase, userId, {
const closingEntry = await createJournalEntry(supabase, companyId, userId, {
fiscal_period_id: fiscalPeriodId,
entry_date: period.period_end,
description: `Årsbokslut ${period.name}`,
@@ -346,24 +350,25 @@ export async function executeYearEndClosing(
.from('fiscal_periods')
.update({ closing_entry_id: closingEntry.id })
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
if (updateError) {
throw new Error(`Failed to set closing_entry_id: ${updateError.message}`)
}
// 6. Lock the period
await lockPeriod(supabase, userId, fiscalPeriodId)
await lockPeriod(supabase, companyId, userId, fiscalPeriodId)
// 7. Close the period
await closePeriod(supabase, userId, fiscalPeriodId)
await closePeriod(supabase, companyId, userId, fiscalPeriodId)
// 8. Create next period
const nextPeriod = await createNextPeriod(supabase, userId, fiscalPeriodId)
const nextPeriod = await createNextPeriod(supabase, companyId, userId, fiscalPeriodId)
// 9. Generate opening balances in next period
const openingBalanceEntry = await generateOpeningBalances(
supabase,
companyId,
userId,
fiscalPeriodId,
nextPeriod.id
@@ -374,13 +379,13 @@ export async function executeYearEndClosing(
.from('fiscal_periods')
.select('*')
.eq('id', fiscalPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (closedPeriod) {
await eventBus.emit({
type: 'period.year_closed',
payload: { period: closedPeriod as FiscalPeriod, userId },
payload: { period: closedPeriod as FiscalPeriod, companyId, userId },
})
}
@@ -401,6 +406,7 @@ export async function executeYearEndClosing(
*/
export async function generateOpeningBalances(
supabase: SupabaseClient,
companyId: string,
userId: string,
closedPeriodId: string,
nextPeriodId: string
@@ -411,7 +417,7 @@ export async function generateOpeningBalances(
.from('fiscal_periods')
.select('*')
.eq('id', nextPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (!nextPeriod) {
@@ -419,7 +425,7 @@ export async function generateOpeningBalances(
}
// Get trial balance of closed period (includes the closing entry)
const { rows } = await generateTrialBalance(supabase, userId, closedPeriodId)
const { rows } = await generateTrialBalance(supabase, companyId, closedPeriodId)
// Filter to balance sheet accounts (class 1-2) with non-zero closing balance
const balanceSheetAccounts = rows.filter(
@@ -467,7 +473,7 @@ export async function generateOpeningBalances(
}
// Create opening balance entry in next period
const openingEntry = await createJournalEntry(supabase, userId, {
const openingEntry = await createJournalEntry(supabase, companyId, userId, {
fiscal_period_id: nextPeriodId,
entry_date: nextPeriod.period_start,
description: `Ingående balans ${nextPeriod.name}`,
@@ -484,7 +490,7 @@ export async function generateOpeningBalances(
opening_balances_set: true,
})
.eq('id', nextPeriodId)
.eq('user_id', userId)
.eq('company_id', companyId)
if (updateError) {
throw new Error(`Failed to set opening_balance_entry_id: ${updateError.message}`)
@@ -74,7 +74,7 @@ describe('uploadDocument', () => {
const supabase = makeClient()
const buffer = new TextEncoder().encode('test content').buffer
const result = await uploadDocument(supabase as never, 'user-1', {
const result = await uploadDocument(supabase as never, 'user-1', 'company-1', {
name: 'test.pdf',
buffer: buffer as ArrayBuffer,
type: 'application/pdf',
@@ -87,6 +87,7 @@ describe('uploadDocument', () => {
expect.objectContaining({
document: expect.objectContaining({ id: 'doc-1' }),
userId: 'user-1',
companyId: 'company-1',
})
)
})
+6 -5
View File
@@ -57,6 +57,7 @@ export async function computeSHA256(buffer: ArrayBuffer): Promise<string> {
export async function uploadDocument(
supabase: SupabaseClient,
userId: string,
companyId: string,
file: { name: string; buffer: ArrayBuffer; type?: string },
metadata: {
upload_source?: DocumentUploadSource
@@ -116,7 +117,7 @@ export async function uploadDocument(
await eventBus.emit({
type: 'document.uploaded',
payload: { document: result, userId },
payload: { document: result, userId, companyId },
})
return result
@@ -192,7 +193,7 @@ export async function createNewVersion(
*/
export async function linkToJournalEntry(
supabase: SupabaseClient,
userId: string,
companyId: string,
documentId: string,
journalEntryId: string,
journalEntryLineId?: string
@@ -205,7 +206,7 @@ export async function linkToJournalEntry(
journal_entry_line_id: journalEntryLineId || null,
})
.eq('id', documentId)
.eq('user_id', userId)
.eq('company_id', companyId)
.select()
.single()
@@ -221,7 +222,7 @@ export async function linkToJournalEntry(
*/
export async function verifyIntegrity(
supabase: SupabaseClient,
userId: string,
companyId: string,
documentId: string
): Promise<{ valid: boolean; storedHash: string; computedHash: string }> {
@@ -230,7 +231,7 @@ export async function verifyIntegrity(
.from('document_attachments')
.select('storage_path, sha256_hash')
.eq('id', documentId)
.eq('user_id', userId)
.eq('company_id', companyId)
.single()
if (docError || !doc) {
+3 -3
View File
@@ -17,7 +17,7 @@ export async function getTaxCodes(supabase: SupabaseClient, userId: string): Pro
const { data, error } = await supabase
.from('tax_codes')
.select('*')
.or(`user_id.eq.${userId},user_id.is.null`)
.or(`company_id.eq.${userId},company_id.is.null`)
.order('code')
if (error) {
@@ -41,7 +41,7 @@ export async function getTaxCodeByCode(
.from('tax_codes')
.select('*')
.eq('code', code)
.or(`user_id.eq.${userId},user_id.is.null`)
.or(`company_id.eq.${userId},company_id.is.null`)
.order('user_id', { ascending: false, nullsFirst: false })
.limit(1)
.single()
@@ -93,7 +93,7 @@ export async function calculateMomsFromTaxCodes(
)
`)
.not('tax_code', 'is', null)
.eq('journal_entries.user_id', userId)
.eq('journal_entries.company_id', userId)
.eq('journal_entries.status', 'posted')
.gte('journal_entries.entry_date', periodStart)
.lte('journal_entries.entry_date', periodEnd)