feat: complete multi-tenant refactor + settings validation + fiscal period API (#156)
* feat: complete multi-tenant refactor for reconciliation, arcim, settings validation - Migrate bank-reconciliation to company_id (all functions + tests) - Migrate arcim-migration entity mappers and orchestrator to company_id - Fix enable-banking reconciliation calls to use companyId - Add Swedish law validation to settings schema: - VAT number required when VAT-registered (ML 11 kap. 8§) - Moms period required when VAT-registered (SFL 26 kap.) - Aktiebolag must use accrual accounting (BFNAR 2006:1) - Fix fiscal year period creation: always 12 months after first year (BFL 3 kap.) - Add plusgiro, website, pays_salaries fields to CompanySettings - Add plusgiro to invoice PDF template - Add fiscal period CRUD and opening balances API routes - Add frame-src CSP directive for future iframe embedding - Fix unlinked_1930_lines RPC to use company_id parameter - Update CLAUDE.md documentation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review findings (P1 + P2) - Fix reconciliation events emitting companyId as userId — thread actual userId through runReconciliation and manualLink - Move VAT cross-field validation (vat_number, moms_period) from schema refinements to route handler where effective stored state is available, preventing false rejection on partial updates - Add plusgiro format validation regex (N-N pattern) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
fad4899cb4
commit
e89f2c402d
@@ -1004,7 +1004,47 @@ describe('UpdateSettingsSchema', () => {
|
||||
it('accepts partial update', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
company_name: 'My AB',
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts vat_registered: true with required vat_number and moms_period', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
vat_registered: true,
|
||||
vat_number: 'SE556123456701',
|
||||
moms_period: 'quarterly',
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts vat_registered: true without vat_number at schema level (route-level check uses effective state)', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
vat_registered: true,
|
||||
moms_period: 'quarterly',
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts vat_registered: true without moms_period at schema level (route-level check uses effective state)', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
vat_registered: true,
|
||||
vat_number: 'SE556123456701',
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects aktiebolag with kontantmetoden (BFNAR 2006:1)', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
entity_type: 'aktiebolag',
|
||||
accounting_method: 'cash',
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('allows enskild firma with kontantmetoden', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
entity_type: 'enskild_firma',
|
||||
accounting_method: 'cash',
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
+16
-1
@@ -366,7 +366,7 @@ export const UpdateSettingsSchema = z.object({
|
||||
country: z.string().optional(),
|
||||
f_skatt: z.boolean().optional(),
|
||||
vat_registered: z.boolean().optional(),
|
||||
vat_number: z.string().optional(),
|
||||
vat_number: z.string().regex(/^SE\d{12}$/, 'Momsregistreringsnummer måste vara SE följt av 12 siffror').nullable().optional(),
|
||||
moms_period: MomsPeriodSchema.nullable().optional(),
|
||||
fiscal_year_start_month: z.number().int().min(1).max(12).optional(),
|
||||
preliminary_tax_monthly: z.number().nullable().optional(),
|
||||
@@ -374,6 +374,7 @@ export const UpdateSettingsSchema = z.object({
|
||||
clearing_number: z.string().regex(/^\d{4,5}$/, 'Clearingnummer måste vara 4-5 siffror').optional().or(z.literal('')),
|
||||
account_number: z.string().regex(/^\d{6,12}$/, 'Kontonummer måste vara 6-12 siffror').optional().or(z.literal('')),
|
||||
bankgiro: z.string().regex(/^(\d{3,4}-\d{4}|\d{7,8})$/, 'Ogiltigt bankgironummer (7-8 siffror)').nullable().optional().or(z.literal('')),
|
||||
plusgiro: z.string().regex(/^\d{1,7}-\d{1}$/, 'Ogiltigt plusgironummer').nullable().optional().or(z.literal('')),
|
||||
iban: z.string().optional(),
|
||||
bic: z.string().optional(),
|
||||
accounting_method: AccountingMethodSchema.optional(),
|
||||
@@ -381,7 +382,9 @@ export const UpdateSettingsSchema = z.object({
|
||||
next_invoice_number: z.number().int().positive().optional(),
|
||||
invoice_default_days: z.number().int().positive().optional(),
|
||||
invoice_default_notes: z.string().nullable().optional(),
|
||||
phone: z.string().optional(),
|
||||
email: z.string().email().optional(),
|
||||
website: z.string().optional().or(z.literal('')),
|
||||
pays_salaries: z.boolean().optional(),
|
||||
sector_slug: z.string().nullable().optional(),
|
||||
}).refine(
|
||||
@@ -396,6 +399,18 @@ export const UpdateSettingsSchema = z.object({
|
||||
message: 'Enskild firma must have fiscal year starting in January (BFL 3 kap.)',
|
||||
path: ['fiscal_year_start_month'],
|
||||
}
|
||||
).refine(
|
||||
(data) => {
|
||||
// BFNAR 2006:1: Aktiebolag must use accrual accounting (faktureringsmetoden)
|
||||
if (data.entity_type === 'aktiebolag' && data.accounting_method !== undefined) {
|
||||
return data.accounting_method === 'accrual'
|
||||
}
|
||||
return true
|
||||
},
|
||||
{
|
||||
message: 'Aktiebolag måste använda faktureringsmetoden (BFNAR 2006:1)',
|
||||
path: ['accounting_method'],
|
||||
}
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -151,20 +151,12 @@ export async function createNextPeriod(
|
||||
const nextStart = new Date(current.period_end)
|
||||
nextStart.setDate(nextStart.getDate() + 1)
|
||||
|
||||
// Compute period length from current period to handle broken fiscal years
|
||||
const currentStart = new Date(current.period_start)
|
||||
const currentEnd = new Date(current.period_end)
|
||||
|
||||
// Calculate months difference
|
||||
const monthsDiff =
|
||||
(currentEnd.getFullYear() - currentStart.getFullYear()) * 12 +
|
||||
(currentEnd.getMonth() - currentStart.getMonth())
|
||||
|
||||
// Next period end: add same number of months from next start, then go to end of that month
|
||||
// After a broken first fiscal year, subsequent years should always be
|
||||
// 12 months (standard fiscal year). The first year is the only one that
|
||||
// can be longer/shorter than 12 months per BFL 3 kap.
|
||||
const nextEnd = new Date(nextStart)
|
||||
nextEnd.setMonth(nextEnd.getMonth() + monthsDiff)
|
||||
// Go to end of the month
|
||||
nextEnd.setMonth(nextEnd.getMonth() + 1)
|
||||
nextEnd.setMonth(nextEnd.getMonth() + 12)
|
||||
// Go to last day of that month
|
||||
nextEnd.setDate(0)
|
||||
|
||||
const nextStartStr = nextStart.toISOString().split('T')[0]
|
||||
|
||||
@@ -503,6 +503,12 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
<Text style={styles.paymentValue}>{company.bankgiro}</Text>
|
||||
</View>
|
||||
)}
|
||||
{company.plusgiro && (
|
||||
<View style={styles.paymentRow}>
|
||||
<Text style={styles.paymentLabel}>Plusgiro:</Text>
|
||||
<Text style={styles.paymentValue}>{company.plusgiro}</Text>
|
||||
</View>
|
||||
)}
|
||||
{company.iban && (
|
||||
<View style={styles.paymentRow}>
|
||||
<Text style={styles.paymentLabel}>IBAN:</Text>
|
||||
|
||||
@@ -278,7 +278,7 @@ describe('runReconciliation', () => {
|
||||
// from('transactions').select — unmatched
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await runReconciliation(supabase as never, 'user-1')
|
||||
const result = await runReconciliation(supabase as never, 'company-1')
|
||||
|
||||
expect(result.matches).toEqual([])
|
||||
expect(result.applied).toBe(0)
|
||||
@@ -300,7 +300,7 @@ describe('runReconciliation', () => {
|
||||
// from('transactions') returns unmatched transactions
|
||||
enqueue({ data: [tx] })
|
||||
|
||||
const result = await runReconciliation(supabase as never, 'user-1', { dryRun: true })
|
||||
const result = await runReconciliation(supabase as never, 'company-1', { dryRun: true })
|
||||
|
||||
expect(result.matches).toHaveLength(1)
|
||||
expect(result.matches[0].method).toBe('auto_exact')
|
||||
@@ -325,7 +325,7 @@ describe('runReconciliation', () => {
|
||||
// Update transaction with link
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const result = await runReconciliation(supabase as never, 'user-1', { dryRun: false })
|
||||
const result = await runReconciliation(supabase as never, 'company-1', { dryRun: false })
|
||||
|
||||
expect(result.matches).toHaveLength(1)
|
||||
expect(result.applied).toBe(1)
|
||||
@@ -379,7 +379,7 @@ describe('manualLink', () => {
|
||||
// Transaction query returns null
|
||||
enqueue({ data: null, error: { message: 'Not found' } })
|
||||
|
||||
const result = await manualLink(supabase as never, 'user-1', 'tx-1', 'je-1')
|
||||
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1')
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBe('Transaction not found')
|
||||
@@ -392,7 +392,7 @@ describe('manualLink', () => {
|
||||
// Transaction found but already linked
|
||||
enqueue({ data: tx })
|
||||
|
||||
const result = await manualLink(supabase as never, 'user-1', 'tx-1', 'je-1')
|
||||
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1')
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBe('Transaction is already linked to a journal entry')
|
||||
@@ -405,11 +405,11 @@ describe('manualLink', () => {
|
||||
// Transaction found
|
||||
enqueue({ data: tx })
|
||||
// Journal entry found
|
||||
enqueue({ data: { id: 'je-1', user_id: 'user-1', status: 'posted' } })
|
||||
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
|
||||
// No 1930 lines
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await manualLink(supabase as never, 'user-1', 'tx-1', 'je-1')
|
||||
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1')
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBe('Journal entry has no line on account 1930')
|
||||
@@ -422,7 +422,7 @@ describe('manualLink', () => {
|
||||
// Transaction found
|
||||
enqueue({ data: tx })
|
||||
// Journal entry found
|
||||
enqueue({ data: { id: 'je-1', user_id: 'user-1', status: 'posted' } })
|
||||
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
|
||||
// 1930 line exists
|
||||
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0 }] })
|
||||
// No existing link
|
||||
@@ -430,7 +430,7 @@ describe('manualLink', () => {
|
||||
// Update succeeds
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const result = await manualLink(supabase as never, 'user-1', 'tx-1', 'je-1')
|
||||
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1')
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
@@ -488,7 +488,7 @@ describe('unlinkReconciliation', () => {
|
||||
},
|
||||
})
|
||||
|
||||
const result = await unlinkReconciliation(supabase as never, 'user-1', 'tx-1')
|
||||
const result = await unlinkReconciliation(supabase as never, 'company-1', 'tx-1')
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain('Cannot unlink')
|
||||
@@ -508,7 +508,7 @@ describe('unlinkReconciliation', () => {
|
||||
// Update succeeds
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const result = await unlinkReconciliation(supabase as never, 'user-1', 'tx-1')
|
||||
const result = await unlinkReconciliation(supabase as never, 'company-1', 'tx-1')
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
@@ -126,19 +126,19 @@ export function tryReconcileTransaction(
|
||||
*/
|
||||
export async function runReconciliation(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
options: ReconciliationOptions = {}
|
||||
companyId: string,
|
||||
options: ReconciliationOptions & { userId?: string } = {}
|
||||
): Promise<ReconciliationRunResult> {
|
||||
const { dateFrom, dateTo, dryRun = false } = options
|
||||
|
||||
// Fetch unlinked GL lines via RPC
|
||||
const glLines = await fetchUnlinkedGLLines(supabase, userId, dateFrom, dateTo)
|
||||
const glLines = await fetchUnlinkedGLLines(supabase, companyId, dateFrom, dateTo)
|
||||
|
||||
// Fetch unmatched transactions
|
||||
let query = supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.eq('currency', 'SEK')
|
||||
|
||||
@@ -172,7 +172,7 @@ export async function runReconciliation(
|
||||
is_business: true,
|
||||
})
|
||||
.eq('id', match.transaction.id)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (error) {
|
||||
errors++
|
||||
@@ -185,8 +185,8 @@ export async function runReconciliation(
|
||||
transaction: match.transaction,
|
||||
journalEntryId: match.glLine.journal_entry_id,
|
||||
method: match.method,
|
||||
userId,
|
||||
companyId: userId,
|
||||
userId: options.userId ?? companyId,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
@@ -210,7 +210,7 @@ export async function runReconciliation(
|
||||
*/
|
||||
export async function getReconciliationStatus(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
dateFrom?: string,
|
||||
dateTo?: string
|
||||
): Promise<ReconciliationStatus> {
|
||||
@@ -218,7 +218,7 @@ export async function getReconciliationStatus(
|
||||
let txQuery = supabase
|
||||
.from('transactions')
|
||||
.select('amount, journal_entry_id, reconciliation_method')
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.eq('currency', 'SEK')
|
||||
|
||||
if (dateFrom) txQuery = txQuery.gte('date', dateFrom)
|
||||
@@ -229,9 +229,9 @@ export async function getReconciliationStatus(
|
||||
// Get GL 1930 lines (all, not just unlinked)
|
||||
let glQuery = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('debit_amount, credit_amount, journal_entries!inner(user_id, entry_date, status)')
|
||||
.select('debit_amount, credit_amount, journal_entries!inner(company_id, entry_date, status)')
|
||||
.eq('account_number', '1930')
|
||||
.eq('journal_entries.company_id', userId)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
|
||||
if (dateFrom) glQuery = glQuery.gte('journal_entries.entry_date', dateFrom)
|
||||
@@ -259,7 +259,7 @@ export async function getReconciliationStatus(
|
||||
).length
|
||||
|
||||
// Unlinked GL lines count
|
||||
const unlinkedLines = await fetchUnlinkedGLLines(supabase, userId, dateFrom, dateTo)
|
||||
const unlinkedLines = await fetchUnlinkedGLLines(supabase, companyId, dateFrom, dateTo)
|
||||
|
||||
const difference = Math.round((bankTotal - glBalance) * 100) / 100
|
||||
|
||||
@@ -284,16 +284,17 @@ export async function getReconciliationStatus(
|
||||
*/
|
||||
export async function manualLink(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
transactionId: string,
|
||||
journalEntryId: string
|
||||
journalEntryId: string,
|
||||
userId?: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
// Fetch transaction
|
||||
const { data: tx, error: txError } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (txError || !tx) {
|
||||
@@ -307,9 +308,9 @@ export async function manualLink(
|
||||
// Fetch journal entry + verify it has a 1930 line
|
||||
const { data: entry, error: entryError } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, user_id, status')
|
||||
.select('id, company_id, status')
|
||||
.eq('id', journalEntryId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (entryError || !entry) {
|
||||
@@ -336,7 +337,7 @@ export async function manualLink(
|
||||
.from('transactions')
|
||||
.select('id')
|
||||
.eq('journal_entry_id', journalEntryId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (existingLink) {
|
||||
@@ -352,7 +353,7 @@ export async function manualLink(
|
||||
is_business: true,
|
||||
})
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) {
|
||||
return { success: false, error: 'Failed to link transaction' }
|
||||
@@ -365,8 +366,8 @@ export async function manualLink(
|
||||
transaction: tx as Transaction,
|
||||
journalEntryId,
|
||||
method: 'manual' as ReconciliationMethod,
|
||||
userId,
|
||||
companyId: userId,
|
||||
userId: userId ?? companyId,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
@@ -382,7 +383,7 @@ export async function manualLink(
|
||||
*/
|
||||
export async function unlinkReconciliation(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
transactionId: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
// Fetch transaction
|
||||
@@ -390,7 +391,7 @@ export async function unlinkReconciliation(
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, reconciliation_method')
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (txError || !tx) {
|
||||
@@ -413,13 +414,13 @@ export async function unlinkReconciliation(
|
||||
is_business: null,
|
||||
})
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', userId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) {
|
||||
return { success: false, error: 'Failed to unlink transaction' }
|
||||
}
|
||||
|
||||
logMatchEvent(supabase, userId, transactionId, 'unmatched', {
|
||||
logMatchEvent(supabase, companyId, transactionId, 'unmatched', {
|
||||
previousState: {
|
||||
journal_entry_id: tx.journal_entry_id,
|
||||
reconciliation_method: tx.reconciliation_method,
|
||||
@@ -441,7 +442,7 @@ export async function fetchUnlinkedGLLines(
|
||||
dateTo?: string
|
||||
): Promise<UnlinkedGLLine[]> {
|
||||
const { data, error } = await supabase.rpc('get_unlinked_1930_lines', {
|
||||
p_user_id: companyId,
|
||||
p_company_id: companyId,
|
||||
p_date_from: dateFrom || null,
|
||||
p_date_to: dateTo || null,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user