New Base func
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { makeTaxCode } from '@/tests/helpers'
|
||||
|
||||
// ============================================================
|
||||
// Mock — separate client (no .then) from query builder (thenable)
|
||||
// ============================================================
|
||||
|
||||
let resultIdx: number
|
||||
let results: Array<{ data?: unknown; error?: unknown; count?: number | null }>
|
||||
|
||||
function makeBuilder() {
|
||||
const b: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'not', 'or', 'order', 'limit', 'is']) {
|
||||
b[m] = vi.fn().mockReturnValue(b)
|
||||
}
|
||||
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||||
b.maybeSingle = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||||
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
|
||||
return b
|
||||
}
|
||||
|
||||
function makeClient() {
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => makeBuilder()),
|
||||
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(async () => makeClient()),
|
||||
}))
|
||||
|
||||
import { getTaxCodeByCode, calculateMomsFromTaxCodes } from '../tax-code-service'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resultIdx = 0
|
||||
results = []
|
||||
})
|
||||
|
||||
describe('getTaxCodeByCode', () => {
|
||||
it('prefers user code over system code', async () => {
|
||||
const userCode = makeTaxCode({
|
||||
id: 'tc-user',
|
||||
user_id: 'user-1',
|
||||
code: 'MP1',
|
||||
description: 'Custom 25% moms',
|
||||
rate: 25,
|
||||
})
|
||||
|
||||
results = [{ data: userCode, error: null }]
|
||||
|
||||
const result = await getTaxCodeByCode('user-1', 'MP1')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.user_id).toBe('user-1')
|
||||
expect(result!.description).toBe('Custom 25% moms')
|
||||
})
|
||||
|
||||
it('returns null when code does not exist', async () => {
|
||||
results = [{ data: null, error: { code: 'PGRST116' } }]
|
||||
|
||||
const result = await getTaxCodeByCode('user-1', 'NONEXISTENT')
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateMomsFromTaxCodes', () => {
|
||||
it('aggregates correctly to moms boxes', async () => {
|
||||
const mp1 = makeTaxCode({
|
||||
code: 'MP1',
|
||||
rate: 25,
|
||||
moms_basis_boxes: ['05'],
|
||||
moms_tax_boxes: ['10'],
|
||||
moms_input_boxes: [],
|
||||
is_output_vat: true,
|
||||
})
|
||||
const ip1 = makeTaxCode({
|
||||
code: 'IP1',
|
||||
rate: 25,
|
||||
moms_basis_boxes: [],
|
||||
moms_tax_boxes: [],
|
||||
moms_input_boxes: ['48'],
|
||||
is_output_vat: false,
|
||||
})
|
||||
|
||||
const lines = [
|
||||
{ tax_code: 'MP1', debit_amount: 0, credit_amount: 10000, journal_entry_id: 'je1', journal_entries: {} },
|
||||
{ tax_code: 'MP1', debit_amount: 0, credit_amount: 5000, journal_entry_id: 'je2', journal_entries: {} },
|
||||
{ tax_code: 'IP1', debit_amount: 2500, credit_amount: 0, journal_entry_id: 'je3', journal_entries: {} },
|
||||
]
|
||||
|
||||
results = [
|
||||
// 0: journal lines query (thenable — no .single())
|
||||
{ data: lines, error: null },
|
||||
// 1: getTaxCodes query (thenable — no .single())
|
||||
{ data: [mp1, ip1], error: null },
|
||||
]
|
||||
|
||||
const result = await calculateMomsFromTaxCodes('user-1', '2024-01-01', '2024-12-31')
|
||||
|
||||
expect(result.length).toBeGreaterThan(0)
|
||||
// Results should be sorted by box
|
||||
for (let i = 1; i < result.length; i++) {
|
||||
expect(result[i].box >= result[i - 1].box).toBe(true)
|
||||
}
|
||||
// Check that we have the expected boxes
|
||||
const boxes = result.map((r) => r.box)
|
||||
expect(boxes).toContain('05')
|
||||
expect(boxes).toContain('10')
|
||||
expect(boxes).toContain('48')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import type { TaxCode } from '@/types'
|
||||
|
||||
/**
|
||||
* Tax Code Service
|
||||
*
|
||||
* Manages decoupled tax codes for momsdeklaration.
|
||||
* Tax codes map journal entry lines to specific moms rutor (boxes)
|
||||
* on the Swedish VAT declaration form.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get all active tax codes for a user (including system codes)
|
||||
*/
|
||||
export async function getTaxCodes(userId: string): Promise<TaxCode[]> {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('tax_codes')
|
||||
.select('*')
|
||||
.or(`user_id.eq.${userId},user_id.is.null`)
|
||||
.order('code')
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Failed to fetch tax codes: ${error.message}`)
|
||||
}
|
||||
|
||||
return (data as TaxCode[]) || []
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single tax code by code string
|
||||
*/
|
||||
export async function getTaxCodeByCode(
|
||||
userId: string,
|
||||
code: string
|
||||
): Promise<TaxCode | null> {
|
||||
const supabase = await createClient()
|
||||
|
||||
// Prefer user-specific code over system code
|
||||
const { data, error } = await supabase
|
||||
.from('tax_codes')
|
||||
.select('*')
|
||||
.eq('code', code)
|
||||
.or(`user_id.eq.${userId},user_id.is.null`)
|
||||
.order('user_id', { ascending: false, nullsFirst: false })
|
||||
.limit(1)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return null
|
||||
}
|
||||
|
||||
return data as TaxCode
|
||||
}
|
||||
|
||||
/**
|
||||
* Moms box result from tax code aggregation
|
||||
*/
|
||||
export interface MomsBoxResult {
|
||||
/** Ruta number (e.g. '05', '10', '48') */
|
||||
box: string
|
||||
/** Sum of amounts for this box */
|
||||
amount: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate momsdeklaration from journal entry lines grouped by tax_code,
|
||||
* then mapped via the tax_codes table to moms boxes.
|
||||
*
|
||||
* This is the new, tax-code-driven approach that replaces the hardcoded
|
||||
* category-based VAT calculation.
|
||||
*/
|
||||
export async function calculateMomsFromTaxCodes(
|
||||
userId: string,
|
||||
periodStart: string,
|
||||
periodEnd: string
|
||||
): Promise<MomsBoxResult[]> {
|
||||
const supabase = await createClient()
|
||||
|
||||
// Fetch journal entry lines with tax_code in the period
|
||||
const { data: lines, error: linesError } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(`
|
||||
tax_code,
|
||||
debit_amount,
|
||||
credit_amount,
|
||||
journal_entry_id,
|
||||
journal_entries!inner (
|
||||
user_id,
|
||||
entry_date,
|
||||
status,
|
||||
fiscal_period_id
|
||||
)
|
||||
`)
|
||||
.not('tax_code', 'is', null)
|
||||
.eq('journal_entries.user_id', userId)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
.gte('journal_entries.entry_date', periodStart)
|
||||
.lte('journal_entries.entry_date', periodEnd)
|
||||
|
||||
if (linesError) {
|
||||
throw new Error(`Failed to fetch journal lines: ${linesError.message}`)
|
||||
}
|
||||
|
||||
// Fetch all tax codes for lookup
|
||||
const taxCodes = await getTaxCodes(userId)
|
||||
const taxCodeMap = new Map<string, TaxCode>()
|
||||
for (const tc of taxCodes) {
|
||||
// User codes take precedence over system codes
|
||||
if (!taxCodeMap.has(tc.code) || tc.user_id) {
|
||||
taxCodeMap.set(tc.code, tc)
|
||||
}
|
||||
}
|
||||
|
||||
// Aggregate amounts by moms box
|
||||
const boxTotals = new Map<string, number>()
|
||||
|
||||
for (const line of lines || []) {
|
||||
if (!line.tax_code) continue
|
||||
|
||||
const taxCode = taxCodeMap.get(line.tax_code)
|
||||
if (!taxCode) continue
|
||||
|
||||
const netAmount = Number(line.debit_amount || 0) - Number(line.credit_amount || 0)
|
||||
const absAmount = Math.abs(netAmount)
|
||||
|
||||
// For output VAT: debit_amount goes to basis boxes, tax amount to tax boxes
|
||||
// For input VAT: the amount goes to input boxes
|
||||
const allBoxes = [
|
||||
...taxCode.moms_basis_boxes,
|
||||
...taxCode.moms_tax_boxes,
|
||||
...taxCode.moms_input_boxes,
|
||||
]
|
||||
|
||||
for (const box of allBoxes) {
|
||||
const current = boxTotals.get(box) || 0
|
||||
boxTotals.set(box, current + absAmount)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to result array
|
||||
const results: MomsBoxResult[] = []
|
||||
for (const [box, amount] of boxTotals) {
|
||||
results.push({
|
||||
box,
|
||||
amount: Math.round(amount * 100) / 100,
|
||||
})
|
||||
}
|
||||
|
||||
return results.sort((a, b) => a.box.localeCompare(b.box))
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed tax codes for a user by calling the database function
|
||||
*/
|
||||
export async function seedTaxCodes(userId: string): Promise<void> {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { error } = await supabase.rpc('seed_tax_codes_for_user', {
|
||||
p_user_id: userId,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Failed to seed tax codes: ${error.message}`)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user