Fix/bank sync bas (#1284)

* fix(year-end): stop revaluing FX items that were not on the balance sheet

The year-end close ran currency revaluation as an unconditional step before
the irreversible close, and the revaluation queried LIVE open invoices with
no date scoping. An invoice issued after balansdagen, settled before it, or
never booked at all was therefore revalued into the year being closed,
writing down a 1510/2440 that stood at zero. Because the entry lands inside
the same run that closes the period, the only remedy left was a rattelse in
the following year.

The population is now measured as of balansdagen, reusing the reconstruction
the reskontra reports already use (fetchPaymentsAsOf / outstandingAsOf): the
invoice_date ceiling is unconditional (post-dated invoices make the bug
reachable for a current period too) and the widening to 'paid' applies only
to a historical date, where a since-settled invoice was still open then.

Rows that carry no balance-sheet exposure are skipped per row rather than per
company: an unbooked registration is not on 1510/2440. Deliberately NOT keyed
on accounting_method, since BFL 5 kap 2 § 3 st requires kontantmetoden
companies to book their outstanding fordringar/skulder at balansdagen, and
those converted rows are genuine exposure that ARL 4 kap. 13 § must value.

The readiness warning stays ungated on purpose: an unbooked FX row is exactly
what deserves a warning, because /book still posts it into the year about to
close and lockPeriod/closePeriod then removes that remedy for good.

The wizard preview now lists the per-invoice revaluation rows it will post
instead of three aggregate numbers, so the user approves line-level content
before the close.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(bookkeeping): reach accounts outside BAS 2026 from a verifikat rattelse

A user could not move a verifikat line to konto 8022: the picker reported no
such account and offered no way forward. 8022 was dropped from BAS 2026 (it
is in BAS 2018), so it is a legitimate company-specific underkonto rather
than a catalog gap. Verified against the official bas.se kontoplan that our
BAS reference already matches BAS 2026, so 8022 is deliberately NOT added to
it: seeding a retired account would push it onto every company.

StrikeLinesDialog and CorrectionEntryDialog were the only account pickers in
the app that never passed onCreateAccount, so their combobox rendered a dead
empty state. Both now open AddAccountDialog prefilled, then refetch the chart
and select the new account on the initiating line, leaving the half-finished
rattelse intact.

AccountCombobox closed its dropdown on the fourth digit of any committed
number, which hid the empty state before it was ever painted and made the
create affordance unreachable for exactly the numbers that need it. It now
closes only when the number matches something, so focus still advances to the
belopp field for real accounts.

No change to posting rules: correct_entry_lines_inline validates chart
membership, not BAS membership, and account creation already required the
same write role.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(vacation): adjust vacation accrual calculations for mid-year hires and update related logic

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-29 13:28:51 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 108f348c84
commit 3bbf2a051b
19 changed files with 1063 additions and 109 deletions
@@ -0,0 +1,41 @@
import { describe, it, expect } from 'vitest'
import { splitCreateAccountPrefill } from '../create-account-prefill'
describe('splitCreateAccountPrefill', () => {
it('routes a full account number to the number field', () => {
// The support case: 8022 is a retired BAS account, so the picker finds
// nothing and the user reaches for "Skapa konto" with the number typed.
expect(splitCreateAccountPrefill('8022')).toEqual({ initialAccountNumber: '8022' })
})
it('routes a partial account number to the number field', () => {
expect(splitCreateAccountPrefill('80')).toEqual({ initialAccountNumber: '80' })
})
it('routes a name fragment to the name field', () => {
expect(splitCreateAccountPrefill('andelar i dotterföretag')).toEqual({
initialAccountName: 'andelar i dotterföretag',
})
})
it('treats a number longer than four digits as a name, not a number', () => {
// The dialog would silently truncate it to four digits; keeping it in the
// name field makes the mistake visible instead.
expect(splitCreateAccountPrefill('80221')).toEqual({ initialAccountName: '80221' })
})
it('treats a mixed string as a name', () => {
expect(splitCreateAccountPrefill('8022 dotter')).toEqual({ initialAccountName: '8022 dotter' })
})
it('trims surrounding whitespace before deciding', () => {
expect(splitCreateAccountPrefill(' 8022 ')).toEqual({ initialAccountNumber: '8022' })
})
it('returns neither prefill for an empty or blank string', () => {
// Spreading {} leaves both props undefined, so the dialog opens blank
// rather than with an empty-string name.
expect(splitCreateAccountPrefill('')).toEqual({})
expect(splitCreateAccountPrefill(' ')).toEqual({})
})
})
@@ -63,16 +63,33 @@ function mockRates(rates: Partial<Record<Currency, number>>) {
})
}
// Helper to build mock supabase
function createMockSupabase(config: {
/**
* Extra tables the preview reads besides the two invoice ledgers:
* company_settings decides the FX exposure scope (cash/deferred/accrual) and
* the payment tables feed the as-of-balansdagen outstanding reconstruction.
*/
interface MockTablesConfig {
invoices?: ReturnType<typeof makeInvoice>[]
supplierInvoices?: ReturnType<typeof makeSupplierInvoice>[]
settings?: Record<string, unknown>
invoicePayments?: Record<string, unknown>[]
supplierInvoicePayments?: Record<string, unknown>[]
existingRevaluation?: boolean
}) {
const fromMap: Record<string, unknown[]> = {
}
function buildFromMap(config: MockTablesConfig): Record<string, unknown[]> {
return {
invoices: config.invoices || [],
supplier_invoices: config.supplierInvoices || [],
company_settings: config.settings ? [config.settings] : [],
invoice_payments: config.invoicePayments || [],
supplier_invoice_payments: config.supplierInvoicePayments || [],
}
}
// Helper to build mock supabase
function createMockSupabase(config: MockTablesConfig) {
const fromMap = buildFromMap(config)
const supabase = {
from: vi.fn().mockImplementation((table: string) => {
@@ -143,6 +160,20 @@ function buildFilterChain(data: unknown[]) {
return chain
})
// ISO date strings compare correctly as strings, matching PostgREST lte.
chain.lte = vi.fn().mockImplementation((col: string, val: string) => {
filtered = filtered.filter((row) => {
const v = (row as Record<string, unknown>)[col]
return v != null && String(v) <= val
})
return chain
})
// Terminal used by fetchFxExposureScope's company_settings read.
chain.maybeSingle = vi.fn().mockImplementation(() =>
Promise.resolve({ data: filtered[0] ?? null, error: null })
)
// Paging stability order: no-op in the mock (data is already deterministic).
chain.order = vi.fn().mockImplementation(() => chain)
@@ -162,11 +193,7 @@ function buildFilterChain(data: unknown[]) {
}
// Better mock for supabase that supports journal_entries idempotency check
function createFullMockSupabase(config: {
invoices?: ReturnType<typeof makeInvoice>[]
supplierInvoices?: ReturnType<typeof makeSupplierInvoice>[]
existingRevaluation?: boolean
}) {
function createFullMockSupabase(config: MockTablesConfig) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase: any = {
from: vi.fn().mockImplementation((table: string) => {
@@ -184,10 +211,7 @@ function createFullMockSupabase(config: {
return journalChain
}
const fromMap: Record<string, unknown[]> = {
invoices: config.invoices || [],
supplier_invoices: config.supplierInvoices || [],
}
const fromMap = buildFromMap(config)
return buildFilterChain(fromMap[table] || [])
}),
}
@@ -1074,4 +1098,381 @@ describe('currency-revaluation', () => {
expect(result!.preview.totalGain).toBe(1000) // 1000 * (12 - 11)
})
})
// Regression: a year-end close revalued FX invoices that were NOT on the
// balance sheet on balansdagen (issued later, settled earlier, or never
// booked at all), writing down a 1510 that stood at zero. The population
// must be measured AS OF the closing date, gated by the company's booking
// mode, exactly like countOpenFxItemsAtBalansdagen in year-end-service.
describe('as-of balansdagen population', () => {
it('excludes an invoice issued after balansdagen', async () => {
const laterInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2025-03-10',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({ invoices: [laterInvoice] })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(0)
expect(preview.lines).toHaveLength(0)
expect(preview.unconvertedFxCount).toBe(0)
})
it('includes an invoice settled after balansdagen at its as-of outstanding', async () => {
// Paid in full in February 2025: on 2024-12-31 the whole amount was
// still an open monetary item and must be valued (ÅRL 4 kap. 13 §).
const settledLater = makeInvoice({
id: 'inv-settled-later',
status: 'paid',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
paid_amount: 1000,
remaining_amount: 0,
paid_at: '2025-02-01',
invoice_date: '2024-11-15',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [settledLater],
invoicePayments: [
{
company_id: 'company-1',
invoice_id: 'inv-settled-later',
amount: 1000,
payment_date: '2025-02-01',
},
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(1000)
expect(preview.totalGain).toBe(1000) // 1000 * (12 - 11)
})
it('excludes the part of an invoice that was already paid on balansdagen', async () => {
const partiallySettled = makeInvoice({
id: 'inv-partial-asof',
status: 'paid',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
paid_amount: 1000,
remaining_amount: 0,
paid_at: '2025-01-20',
invoice_date: '2024-11-15',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [partiallySettled],
invoicePayments: [
// 600 paid before balansdagen, 400 after: only 400 was open.
{
company_id: 'company-1',
invoice_id: 'inv-partial-asof',
amount: 600,
payment_date: '2024-12-10',
},
{
company_id: 'company-1',
invoice_id: 'inv-partial-asof',
amount: 400,
payment_date: '2025-01-20',
},
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(400)
expect(preview.totalGain).toBe(400) // 400 * (12 - 11)
})
it('excludes an unbooked row for a kontantmetoden company', async () => {
// A registered-but-unbooked invoice is not on 1510, so revaluing it
// fabricated a write-down of an account that stood at zero.
const eurInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2024-11-15',
journal_entry_id: null,
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [eurInvoice],
settings: { company_id: 'company-1', accounting_method: 'cash' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(0)
expect(preview.lines).toHaveLength(0)
})
it('still revalues a kontantmetoden company row booked at balansdagen', async () => {
// BFL 5 kap 2 § 3 st: kontantmetoden companies must book their
// outstanding fordringar/skulder at year-end. Those converted rows ARE
// on 1510 and must be valued at balansdagskurs (ÅRL 4 kap. 13 §), so
// gating on accounting_method rather than on the row would drop them.
const bookedEur = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2024-11-15',
journal_entry_id: 'je-yearend-conversion',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [bookedEur],
settings: { company_id: 'company-1', accounting_method: 'cash' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.totalGain).toBe(1000) // 1000 * (12 - 11)
})
it('excludes a post-dated invoice even when balansdagen is not historical', async () => {
// The date ceiling is unconditional: an invoice issued after the
// balансdagen is not on the balance sheet being valued, whether or not
// that date happens to be in the past.
const future = new Date(Date.now() + 90 * 86400000).toISOString().slice(0, 10)
const postDated = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10)
const beforeToday = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10)
const openNow = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: beforeToday,
})
const laterInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 500,
invoice_date: future,
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({ invoices: [openNow, laterInvoice] })
// Balansdagen between the two invoice dates, still in the future.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', postDated)
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(1000)
})
it('values a still-open invoice at what it owed on balansdagen', async () => {
// The common straddling case: the row is 'partially_paid' today, so the
// OLD status list already fetched it, but its live paid_amount reflects
// payments made after balansdagen.
const straddling = makeInvoice({
id: 'inv-straddle',
status: 'partially_paid',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
paid_amount: 900,
remaining_amount: 100,
invoice_date: '2024-10-01',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [straddling],
invoicePayments: [
{ company_id: 'company-1', invoice_id: 'inv-straddle', amount: 300, payment_date: '2024-11-05' },
{ company_id: 'company-1', invoice_id: 'inv-straddle', amount: 600, payment_date: '2025-02-11' },
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
// 700 was open on balansdagen, not the live 100.
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(700)
expect(preview.totalGain).toBe(700)
})
it('applies the same as-of reconstruction to payables', async () => {
const straddlingPayable = makeSupplierInvoice({
id: 'si-straddle',
status: 'partially_paid',
currency: 'EUR',
exchange_rate: 11.0,
total: 2000,
remaining_amount: 200,
invoice_date: '2024-10-01',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
supplierInvoices: [straddlingPayable],
supplierInvoicePayments: [
{ company_id: 'company-1', supplier_invoice_id: 'si-straddle', amount: 500, payment_date: '2024-12-01' },
{ company_id: 'company-1', supplier_invoice_id: 'si-straddle', amount: 1300, payment_date: '2025-03-04' },
],
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
// 1500 was owed on balansdagen; a rising rate is a LOSS on a payable.
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(1500)
expect(preview.totalLoss).toBe(1500)
expect(preview.totalGain).toBe(0)
})
it('excludes an unbooked payable under deferred booking', async () => {
const bookedSi = makeSupplierInvoice({
status: 'registered',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
remaining_amount: 1000,
invoice_date: '2024-11-01',
registration_journal_entry_id: 'je-si-1',
})
const unbookedSi = makeSupplierInvoice({
status: 'registered',
currency: 'EUR',
exchange_rate: 11.0,
total: 400,
remaining_amount: 400,
invoice_date: '2024-11-02',
registration_journal_entry_id: null,
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
supplierInvoices: [bookedSi, unbookedSi],
settings: {
company_id: 'company-1',
accounting_method: 'accrual',
defer_invoice_booking: true,
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(1000)
expect(preview.totalLoss).toBe(1000)
})
it('renders a preview instead of throwing when settings cannot be read', async () => {
// previewCurrencyRevaluation is the read-only surface: the year-end
// preview must still render (same contract as the missing-rate path).
const eurInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2024-11-15',
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({ invoices: [eurInvoice] })
const original = supabase.from
supabase.from = vi.fn().mockImplementation((table: string) => {
if (table === 'company_settings') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
maybeSingle: vi.fn().mockResolvedValue({
data: null,
error: { message: 'connection reset' },
}),
}),
}),
}
}
return original(table)
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.totalGain).toBe(1000)
})
it('under deferred booking only revalues rows whose registration is booked', async () => {
const bookedInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2024-11-15',
journal_entry_id: 'je-1',
})
const unbookedInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 500,
invoice_date: '2024-11-20',
journal_entry_id: null,
})
mockRates({ EUR: 12.0 })
const supabase = createMockSupabase({
invoices: [bookedInvoice, unbookedInvoice],
settings: {
company_id: 'company-1',
accounting_method: 'accrual',
defer_invoice_booking: true,
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preview = await previewCurrencyRevaluation(supabase as any, 'company-1', '2024-12-31')
expect(preview.items).toHaveLength(1)
expect(preview.items[0].amount_in_currency).toBe(1000)
expect(preview.totalGain).toBe(1000) // only the booked 1000 EUR row
})
it('executeCurrencyRevaluation posts nothing when nothing was open on balansdagen', async () => {
// The Oppy case end to end: only a post-balansdagen invoice exists, so
// the year-end run must not create any verifikat at all.
const laterInvoice = makeInvoice({
status: 'sent',
currency: 'EUR',
exchange_rate: 11.0,
total: 1000,
invoice_date: '2025-03-10',
})
mockRates({ EUR: 12.0 })
const supabase = createFullMockSupabase({
invoices: [laterInvoice],
existingRevaluation: false,
})
const result = await executeCurrencyRevaluation(supabase, 'company-1', '2024-12-31', 'period-1')
expect(result).toBeNull()
expect(mockedCreateEntry).not.toHaveBeenCalled()
})
})
})
+22
View File
@@ -0,0 +1,22 @@
/**
* Split the search string an account picker was showing when the user reached
* for "Skapa konto" into AddAccountDialog's two prefill props.
*
* The combobox hands over whatever was typed, which is either a partial/full
* account number ("8022") or a name fragment ("andelar i dotterföretag").
* Feeding a name into initialAccountNumber would be silently dropped by the
* dialog's digits-only filter, and feeding a number into initialAccountName
* would put "8022" in the name field.
*/
export interface CreateAccountPrefill {
initialAccountNumber?: string
initialAccountName?: string
}
export function splitCreateAccountPrefill(prefill: string): CreateAccountPrefill {
const trimmed = prefill.trim()
if (!trimmed) return {}
return /^\d{1,4}$/.test(trimmed)
? { initialAccountNumber: trimmed }
: { initialAccountName: trimmed }
}
+165 -38
View File
@@ -2,6 +2,12 @@ import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import {
fetchPaymentsAsOf,
outstandingAsOf,
todayIsoDate,
type PaymentsAsOf,
} from '@/lib/reports/reskontra-payments'
import {
BookkeepingDatabaseError,
CurrencyRevaluationAlreadyExistsError,
@@ -80,6 +86,59 @@ function hasUsableRate(rate: number | null | undefined): boolean {
return rate != null && Number(rate) > 0
}
/**
* Which invoice rows can carry balance-sheet FX exposure for this company.
*
* ÅRL 4 kap. 13 § revalues MONETARY ITEMS ON THE BALANCE SHEET, and an invoice
* row only puts anything on 1510/2440 once its registration is booked. Under
* #967 "Registrera men bokför inte" (and under kontantmetoden) a registered
* invoice can sit in the reskontra with nothing on the balance sheet at all;
* revaluing those fabricated a write-down of an account standing at zero.
*
* NOT keyed on accounting_method: kontantmetoden companies must still book
* their outstanding fordringar/skulder at balansdagen (BFL 5 kap 2 § 3 st), and
* those year-end-converted rows are genuine FX exposure that has to be valued.
* The predicate is therefore per row ("is this one booked?"), never per company
* ("does this company use the cash method?"):
* - 'booked_only': only rows carrying a registration entry are on the balance
* sheet (kontantmetoden, or faktureringsmetoden with defer_invoice_booking)
* - 'all': inline booking at issue, the historical default. Every open row is
* booked, including legacy/SIE-imported rows that predate the entry links,
* so requiring a link there would silently drop real exposure.
*/
export type FxExposureScope = 'all' | 'booked_only'
export function fxExposureScope(
settings:
| { accounting_method?: string | null; defer_invoice_booking?: boolean | null }
| null
| undefined
): FxExposureScope {
// No settings row: historical default (accrual, book at issue).
if (!settings) return 'all'
if ((settings.accounting_method || 'accrual') !== 'accrual') return 'booked_only'
return settings.defer_invoice_booking ? 'booked_only' : 'all'
}
/**
* Never throws: `previewCurrencyRevaluation` is the read-only surface and the
* year-end preview must still render (same contract as the missing-rate path).
* A settings row that cannot be read falls back to the historical default,
* which is also what a missing row means.
*/
export async function fetchFxExposureScope(
supabase: SupabaseClient,
companyId: string
): Promise<FxExposureScope> {
const { data, error } = await supabase
.from('company_settings')
.select('accounting_method, defer_invoice_booking')
.eq('company_id', companyId)
.maybeSingle()
if (error) return 'all'
return fxExposureScope(data)
}
/**
* Fetch open foreign-currency receivables (invoices).
* Returns invoices with status 'sent', 'overdue' or 'partially_paid' and
@@ -92,24 +151,44 @@ function hasUsableRate(rate: number | null | undefined): boolean {
* monetary item that ÅRL 4 kap. 13 § values at balansdagen. Omitting it made
* partially paid foreign receivables entirely invisible to the revaluation
* (the payables side has always included it).
*
* When `asOfDate` is given the population is measured AS OF that date, not as
* of now. Two independent adjustments:
* - the date ceiling (`invoice_date <= asOfDate`) is UNCONDITIONAL: an invoice
* issued after the balансdagen was not on the balance sheet being valued,
* whether or not that date happens to be in the past. Post-dated invoices
* make this reachable for a current period too.
* - the status widening to 'paid' applies only to a historical date, where an
* invoice settled since (in March, say) was still open on 31 December. For
* today or the future the stored open state IS the as-of state.
* The caller recomputes each row's outstanding from the payment history (see
* previewCurrencyRevaluation). Same reconstruction contract as
* countOpenFxItemsAtBalansdagen in year-end-service and the reskontra reports.
*/
export async function getOpenForeignCurrencyReceivables(
supabase: SupabaseClient,
companyId: string
companyId: string,
asOfDate?: string
): Promise<Invoice[]> {
const historical = asOfDate != null && asOfDate < todayIsoDate()
try {
// Paginated with a stable id order so a company with >1000 open FX invoices
// is fully revalued rather than silently truncated at 1000 rows.
return await fetchAllRows<Invoice>(({ from, to }) =>
supabase
return await fetchAllRows<Invoice>(({ from, to }) => {
const base = supabase
.from('invoices')
.select('*')
.eq('company_id', companyId)
.in('status', ['sent', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
.order('id', { ascending: true })
.range(from, to)
, { dedupeBy: (i) => i.id })
.in(
'status',
historical
? ['sent', 'overdue', 'partially_paid', 'paid']
: ['sent', 'overdue', 'partially_paid']
)
const scoped = asOfDate != null ? base.lte('invoice_date', asOfDate) : base
return scoped.order('id', { ascending: true }).range(from, to)
}, { dedupeBy: (i) => i.id })
} catch (err) {
throw new BookkeepingDatabaseError(
'fetch_currency_receivables',
@@ -123,24 +202,34 @@ export async function getOpenForeignCurrencyReceivables(
* Returns supplier invoices with open statuses and non-SEK currency,
* INCLUDING ones with no `exchange_rate` (see the receivables note above).
* Uses remaining_amount for partial payments.
*
* `asOfDate` behaves as on the receivables side: the date ceiling is
* unconditional, the widening to 'paid' applies only to a historical date.
*/
export async function getOpenForeignCurrencyPayables(
supabase: SupabaseClient,
companyId: string
companyId: string,
asOfDate?: string
): Promise<SupplierInvoice[]> {
const historical = asOfDate != null && asOfDate < todayIsoDate()
try {
// Paginated with a stable id order so a company with >1000 open FX payables
// is fully revalued rather than silently truncated at 1000 rows.
return await fetchAllRows<SupplierInvoice>(({ from, to }) =>
supabase
return await fetchAllRows<SupplierInvoice>(({ from, to }) => {
const base = supabase
.from('supplier_invoices')
.select('*')
.eq('company_id', companyId)
.in('status', ['registered', 'approved', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
.order('id', { ascending: true })
.range(from, to)
, { dedupeBy: (i) => i.id })
.in(
'status',
historical
? ['registered', 'approved', 'overdue', 'partially_paid', 'paid']
: ['registered', 'approved', 'overdue', 'partially_paid']
)
const scoped = asOfDate != null ? base.lte('invoice_date', asOfDate) : base
return scoped.order('id', { ascending: true }).range(from, to)
}, { dedupeBy: (i) => i.id })
} catch (err) {
throw new BookkeepingDatabaseError(
'fetch_currency_payables',
@@ -171,26 +260,67 @@ export async function previewCurrencyRevaluation(
companyId: string,
closingDate: string
): Promise<CurrencyRevaluationPreviewWithExclusions> {
const emptyPreview: CurrencyRevaluationPreviewWithExclusions = {
items: [],
lines: [],
closingRates: {},
totalGain: 0,
totalLoss: 0,
netEffect: 0,
unconvertedFx: [],
unconvertedFxCount: 0,
missingClosingRates: [],
}
const scope = await fetchFxExposureScope(supabase, companyId)
const [receivables, payables] = await Promise.all([
getOpenForeignCurrencyReceivables(supabase, companyId),
getOpenForeignCurrencyPayables(supabase, companyId),
getOpenForeignCurrencyReceivables(supabase, companyId, closingDate),
getOpenForeignCurrencyPayables(supabase, companyId, closingDate),
])
// For a historical balansdagen the live status/paid_amount columns describe
// today, not the balance sheet being valued: reconstruct each row's
// outstanding from the payment history, the same walk-back the reskontra
// reports and countOpenFxItemsAtBalansdagen use.
const isHistorical = closingDate < todayIsoDate()
const [receivablePayments, payablePayments]: [PaymentsAsOf | null, PaymentsAsOf | null] =
await Promise.all([
isHistorical && receivables.length > 0
? fetchPaymentsAsOf(supabase, 'invoice_payments', 'invoice_id', companyId, closingDate)
: null,
isHistorical && payables.length > 0
? fetchPaymentsAsOf(
supabase,
'supplier_invoice_payments',
'supplier_invoice_id',
companyId,
closingDate
)
: null,
])
// Partition into rows we can revalue and rows with no original rate, and
// collect the distinct currencies of the revaluable rows.
const currencies = new Set<Currency>()
const unconvertedFx: UnconvertedFxItem[] = []
const revaluableReceivables: Array<{ inv: Invoice; outstanding: number }> = []
const revaluablePayables: SupplierInvoice[] = []
const revaluablePayables: Array<{ si: SupplierInvoice; outstanding: number }> = []
for (const inv of receivables) {
// Deferred booking: an unbooked registration is not on 1510, so it is not
// a monetary item to revalue (nor unmeasured exposure to report).
if (scope === 'booked_only' && !inv.journal_entry_id) continue
// Only the OUTSTANDING amount is a monetary item at balansdagen: the paid
// part has already been settled at its own realized rate. Kundreskontran
// derives outstanding from total - paid_amount (see year-end-service),
// so the same definition is used here, öre-rounded.
const outstanding =
Math.round(((Number(inv.total) || 0) - (Number(inv.paid_amount) || 0)) * 100) / 100
// Nothing outstanding: nothing to revalue, and no exposure to report.
const total = Number(inv.total) || 0
const live = Math.round((total - (Number(inv.paid_amount) || 0)) * 100) / 100
const outstanding = receivablePayments
? outstandingAsOf(inv, total, live, receivablePayments, closingDate)
: live
// Nothing outstanding on balansdagen: nothing to revalue, no exposure.
if (outstanding <= 0) continue
if (!hasUsableRate(inv.exchange_rate)) {
unconvertedFx.push({
@@ -207,34 +337,31 @@ export async function previewCurrencyRevaluation(
}
for (const si of payables) {
// Nothing outstanding: nothing to revalue, and no exposure to report.
if (Number(si.remaining_amount) <= 0) continue
// See the receivables note: unbooked registrations carry no 2440 balance.
if (scope === 'booked_only' && !si.registration_journal_entry_id) continue
const total = Number(si.total) || 0
const live = Number(si.remaining_amount) || 0
const outstanding = payablePayments
? outstandingAsOf(si, total, live, payablePayments, closingDate)
: live
// Nothing outstanding on balansdagen: nothing to revalue, no exposure.
if (outstanding <= 0) continue
if (!hasUsableRate(si.exchange_rate)) {
unconvertedFx.push({
type: 'payable',
source_id: si.id,
reference: si.supplier_invoice_number,
currency: si.currency as Currency,
amount_in_currency: si.remaining_amount,
amount_in_currency: outstanding,
})
continue
}
currencies.add(si.currency as Currency)
revaluablePayables.push(si)
revaluablePayables.push({ si, outstanding })
}
if (currencies.size === 0) {
return {
items: [],
lines: [],
closingRates: {},
totalGain: 0,
totalLoss: 0,
netEffect: 0,
unconvertedFx,
unconvertedFxCount: unconvertedFx.length,
missingClosingRates: [],
}
return { ...emptyPreview, unconvertedFx, unconvertedFxCount: unconvertedFx.length }
}
// Fetch closing rates one currency at a time through fetchExchangeRate: it
@@ -294,12 +421,12 @@ export async function previewCurrencyRevaluation(
})
}
// Process payables (use remaining_amount for partial payments)
for (const si of revaluablePayables) {
// Process payables (outstanding as of balansdagen, mirroring receivables)
for (const { si, outstanding } of revaluablePayables) {
const closingRate = rateMap.get(si.currency as Currency)
if (!closingRate || !si.exchange_rate) continue
const amountInCurrency = si.remaining_amount
const amountInCurrency = outstanding
const originalSek = Math.round(amountInCurrency * si.exchange_rate * 100) / 100
const closingSek = Math.round(amountInCurrency * closingRate * 100) / 100