fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* renderChannelContextNotes: the one string WhatsApp chat context becomes on
|
||||
* its way into a verifikat description. Pins precedence (representation >
|
||||
* user_note > caption), the caption opt-in, the 220-char cap, and whole-name
|
||||
* participant truncation ("… och N till", never a name cut mid-way).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
renderChannelContextNotes,
|
||||
renderChannelParticipant,
|
||||
CHANNEL_CONTEXT_NOTES_MAX,
|
||||
} from '../channel-context-notes'
|
||||
import type { InboxChannelContext } from '@/types'
|
||||
|
||||
function repCtx(
|
||||
participants: { name: string; company: string | null }[],
|
||||
purpose: string | null = null,
|
||||
extra: Partial<InboxChannelContext> = {},
|
||||
): InboxChannelContext {
|
||||
return {
|
||||
channel: 'whatsapp',
|
||||
representation: {
|
||||
participants,
|
||||
purpose,
|
||||
event_date: null,
|
||||
raw_answer: 'raw',
|
||||
answered_at: '2026-08-01T12:00:00Z',
|
||||
},
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
describe('renderChannelContextNotes', () => {
|
||||
it('renders a full representation answer: participants with company, then purpose', () => {
|
||||
const ctx = repCtx(
|
||||
[
|
||||
{ name: 'Anna Berg', company: 'Volvo' },
|
||||
{ name: 'Jakob W', company: null },
|
||||
],
|
||||
'uppföljning av avtal',
|
||||
)
|
||||
expect(renderChannelContextNotes(ctx)).toBe(
|
||||
'Representation: Anna Berg (Volvo), Jakob W · Syfte: uppföljning av avtal',
|
||||
)
|
||||
})
|
||||
|
||||
it('renders a self participant (no company) as the bare name', () => {
|
||||
expect(renderChannelParticipant({ name: ' Jakob W ', company: null })).toBe('Jakob W')
|
||||
expect(renderChannelParticipant({ name: 'Anna', company: ' ' })).toBe('Anna')
|
||||
const ctx = repCtx([{ name: 'Jakob W', company: null }], 'lunch med kund')
|
||||
expect(renderChannelContextNotes(ctx)).toBe(
|
||||
'Representation: Jakob W · Syfte: lunch med kund',
|
||||
)
|
||||
})
|
||||
|
||||
it('renders purpose alone when the participant list is empty', () => {
|
||||
const ctx = repCtx([], 'kundmiddag')
|
||||
expect(renderChannelContextNotes(ctx)).toBe('Syfte: kundmiddag')
|
||||
})
|
||||
|
||||
it('truncates the participant list by whole names with "… och N till"', () => {
|
||||
const participants = Array.from({ length: 12 }, (_, i) => ({
|
||||
name: `Deltagare Efternamnsson ${i + 1}`,
|
||||
company: 'Företagsnamnet Aktiebolag',
|
||||
}))
|
||||
const ctx = repCtx(participants, 'branschmässa i Göteborg')
|
||||
const line = renderChannelContextNotes(ctx)!
|
||||
|
||||
expect(line.length).toBeLessThanOrEqual(CHANNEL_CONTEXT_NOTES_MAX)
|
||||
expect(line).toMatch(/… och \d+ till/)
|
||||
// Whole names only: every rendered participant appears in full or not at
|
||||
// all. The first is always kept; the last is always dropped here.
|
||||
expect(line).toContain('Deltagare Efternamnsson 1 (Företagsnamnet Aktiebolag)')
|
||||
expect(line).not.toContain('Deltagare Efternamnsson 12')
|
||||
// The dropped count accounts for every name not printed.
|
||||
const [, dropped] = line.match(/… och (\d+) till/)!
|
||||
const printed = participants.filter((p) => line.includes(`${p.name} (${p.company})`)).length
|
||||
expect(printed + Number(dropped)).toBe(participants.length)
|
||||
// No name was cut mid-way: the truncation marker follows a complete
|
||||
// "(company)" closing paren, not a partial name.
|
||||
expect(line).toMatch(/\(Företagsnamnet Aktiebolag\) … och \d+ till/)
|
||||
// Purpose survives truncation.
|
||||
expect(line).toContain('Syfte: branschmässa i Göteborg')
|
||||
})
|
||||
|
||||
it('keeps at least one participant even when the line still overflows, then caps free text', () => {
|
||||
const ctx = repCtx(
|
||||
[
|
||||
{ name: 'Anna Berg', company: 'Volvo' },
|
||||
{ name: 'Bo Ek', company: null },
|
||||
],
|
||||
'x'.repeat(400),
|
||||
)
|
||||
const line = renderChannelContextNotes(ctx)!
|
||||
expect(line.length).toBeLessThanOrEqual(CHANNEL_CONTEXT_NOTES_MAX)
|
||||
expect(line).toContain('Representation: Anna Berg (Volvo)')
|
||||
expect(line.endsWith('…')).toBe(true)
|
||||
})
|
||||
|
||||
it('renders user_note alone', () => {
|
||||
const ctx: InboxChannelContext = {
|
||||
channel: 'whatsapp',
|
||||
user_note: 'Parkering vid kundbesök i Uppsala',
|
||||
}
|
||||
expect(renderChannelContextNotes(ctx)).toBe('Parkering vid kundbesök i Uppsala')
|
||||
})
|
||||
|
||||
it('appends user_note after the representation answer', () => {
|
||||
const ctx = repCtx([{ name: 'Anna Berg', company: 'Volvo' }], 'avtalslunch', {
|
||||
user_note: 'Betald privat',
|
||||
})
|
||||
expect(renderChannelContextNotes(ctx)).toBe(
|
||||
'Representation: Anna Berg (Volvo) · Syfte: avtalslunch · Betald privat',
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the caption only when nothing else exists AND it was asked for', () => {
|
||||
const captionOnly: InboxChannelContext = {
|
||||
channel: 'whatsapp',
|
||||
caption: 'Kvitto taxi till kundmöte',
|
||||
}
|
||||
expect(renderChannelContextNotes(captionOnly, { includeCaption: true })).toBe(
|
||||
'Kvitto taxi till kundmöte',
|
||||
)
|
||||
|
||||
// Caption is ignored the moment an explicit answer exists.
|
||||
const withNote: InboxChannelContext = {
|
||||
channel: 'whatsapp',
|
||||
caption: 'Kvitto taxi till kundmöte',
|
||||
user_note: 'Resa till Arlanda',
|
||||
}
|
||||
expect(renderChannelContextNotes(withNote, { includeCaption: true })).toBe('Resa till Arlanda')
|
||||
})
|
||||
|
||||
// The caption is chat text nobody was asked for and nobody reviewed, while
|
||||
// every unattended caller (bulk-book, the routes' server-side defaults)
|
||||
// writes the result into an immutable verifikat. Opt-in, never default.
|
||||
it('leaves the caption out by default', () => {
|
||||
const captionOnly: InboxChannelContext = {
|
||||
channel: 'whatsapp',
|
||||
caption: 'kvittot från igår, Annas sjukbesök, hon betalade',
|
||||
}
|
||||
expect(renderChannelContextNotes(captionOnly)).toBeNull()
|
||||
expect(renderChannelContextNotes(captionOnly, {})).toBeNull()
|
||||
expect(renderChannelContextNotes(captionOnly, { includeCaption: false })).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the answered parts and drops the caption when captions are off', () => {
|
||||
const ctx = repCtx([{ name: 'Anna Berg', company: 'Volvo' }], 'avtalslunch', {
|
||||
caption: 'privat text som ingen granskat',
|
||||
user_note: 'Betald privat',
|
||||
})
|
||||
const line = renderChannelContextNotes(ctx)!
|
||||
expect(line).toBe('Representation: Anna Berg (Volvo) · Syfte: avtalslunch · Betald privat')
|
||||
expect(line).not.toContain('privat text som ingen granskat')
|
||||
})
|
||||
|
||||
it('caps a runaway caption', () => {
|
||||
const ctx: InboxChannelContext = { channel: 'whatsapp', caption: 'k'.repeat(500) }
|
||||
const line = renderChannelContextNotes(ctx, { includeCaption: true })!
|
||||
expect(line.length).toBeLessThanOrEqual(CHANNEL_CONTEXT_NOTES_MAX)
|
||||
expect(line.endsWith('…')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns null for empty input', () => {
|
||||
expect(renderChannelContextNotes(null)).toBeNull()
|
||||
expect(renderChannelContextNotes(undefined)).toBeNull()
|
||||
expect(renderChannelContextNotes({ channel: 'whatsapp' })).toBeNull()
|
||||
expect(
|
||||
renderChannelContextNotes({
|
||||
channel: 'whatsapp',
|
||||
caption: 'ignorerad utan opt-in',
|
||||
user_note: '',
|
||||
representation: {
|
||||
participants: [{ name: ' ', company: null }],
|
||||
purpose: ' ',
|
||||
event_date: null,
|
||||
raw_answer: 'nej',
|
||||
answered_at: '2026-08-01T12:00:00Z',
|
||||
},
|
||||
}),
|
||||
).toBeNull()
|
||||
expect(
|
||||
renderChannelContextNotes(
|
||||
{
|
||||
channel: 'whatsapp',
|
||||
caption: ' ',
|
||||
user_note: '',
|
||||
representation: {
|
||||
participants: [{ name: ' ', company: null }],
|
||||
purpose: ' ',
|
||||
event_date: null,
|
||||
raw_answer: 'nej',
|
||||
answered_at: '2026-08-01T12:00:00Z',
|
||||
},
|
||||
},
|
||||
{ includeCaption: true },
|
||||
),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('is deterministic (same input, same output)', () => {
|
||||
const ctx = repCtx(
|
||||
[{ name: 'Anna Berg', company: 'Volvo' }],
|
||||
'uppföljning av avtal',
|
||||
{ user_note: 'Kortköp' },
|
||||
)
|
||||
expect(renderChannelContextNotes(ctx)).toBe(renderChannelContextNotes(ctx))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,321 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
FALLBACK_CONFIDENCE_FACTOR,
|
||||
levenshteinDistance,
|
||||
normalizeMerchantName,
|
||||
normalizeForMatch,
|
||||
calculateMerchantSimilarity,
|
||||
calculateMatchConfidence,
|
||||
amountVarianceForMatch,
|
||||
bestProminentAmountVariance,
|
||||
} from '../core-receipt-matcher'
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
describe('levenshteinDistance', () => {
|
||||
it('returns 0 for identical strings', () => {
|
||||
expect(levenshteinDistance('abc', 'abc')).toBe(0)
|
||||
})
|
||||
|
||||
it('returns length of other string for empty string', () => {
|
||||
expect(levenshteinDistance('', 'abc')).toBe(3)
|
||||
expect(levenshteinDistance('abc', '')).toBe(3)
|
||||
})
|
||||
|
||||
it('calculates correct edit distance', () => {
|
||||
expect(levenshteinDistance('kitten', 'sitting')).toBe(3)
|
||||
expect(levenshteinDistance('saturday', 'sunday')).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeMerchantName', () => {
|
||||
it('lowercases and trims', () => {
|
||||
expect(normalizeMerchantName(' ICA MAXI ')).toBe('ica maxi')
|
||||
})
|
||||
|
||||
it('removes Swedish company suffixes', () => {
|
||||
expect(normalizeMerchantName('Telia AB')).toBe('telia')
|
||||
})
|
||||
|
||||
it('removes special characters but keeps Swedish letters', () => {
|
||||
expect(normalizeMerchantName('Café Överkås!')).toBe('café överkås')
|
||||
})
|
||||
|
||||
it('collapses whitespace', () => {
|
||||
expect(normalizeMerchantName('ica maxi stockholm')).toBe('ica maxi stockholm')
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateMerchantSimilarity', () => {
|
||||
it('returns 1 for exact match', () => {
|
||||
expect(calculateMerchantSimilarity('ICA Maxi', 'ICA Maxi')).toBe(1)
|
||||
})
|
||||
|
||||
it('returns 1 for match after normalization', () => {
|
||||
expect(calculateMerchantSimilarity('Telia AB', 'telia')).toBe(1)
|
||||
})
|
||||
|
||||
it('returns 0.9 when one contains the other', () => {
|
||||
expect(calculateMerchantSimilarity('ICA', 'ICA MAXI STOCKHOLM')).toBe(0.9)
|
||||
})
|
||||
|
||||
it('returns 0 for empty strings', () => {
|
||||
expect(calculateMerchantSimilarity('', 'abc')).toBe(0)
|
||||
expect(calculateMerchantSimilarity('abc', '')).toBe(0)
|
||||
})
|
||||
|
||||
it('returns score between 0 and 1 for partial matches', () => {
|
||||
const score = calculateMerchantSimilarity('ICA Maxi', 'Coop Forum')
|
||||
expect(score).toBeGreaterThanOrEqual(0)
|
||||
expect(score).toBeLessThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('gives high score for word overlap', () => {
|
||||
const score = calculateMerchantSimilarity('ICA Maxi Stockholm', 'ICA Maxi Solna')
|
||||
expect(score).toBeGreaterThan(0.7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateMatchConfidence', () => {
|
||||
it('gives high confidence for exact date + amount + merchant', () => {
|
||||
const { confidence, matchReasons } = calculateMatchConfidence(0, 0, 1.0)
|
||||
expect(confidence).toBeGreaterThan(0.9)
|
||||
expect(matchReasons).toContain('Exakt datum')
|
||||
expect(matchReasons).toContain('Exakt belopp')
|
||||
expect(matchReasons).toContain('Handlare matchar')
|
||||
})
|
||||
|
||||
it('gives lower confidence when date is off', () => {
|
||||
const exact = calculateMatchConfidence(0, 0, 1.0)
|
||||
const dateOff = calculateMatchConfidence(2, 0, 1.0)
|
||||
expect(dateOff.confidence).toBeLessThan(exact.confidence)
|
||||
})
|
||||
|
||||
it('gives lower confidence when amount is off', () => {
|
||||
const exact = calculateMatchConfidence(0, 0, 1.0)
|
||||
const amountOff = calculateMatchConfidence(0, 0.03, 1.0)
|
||||
expect(amountOff.confidence).toBeLessThan(exact.confidence)
|
||||
})
|
||||
|
||||
it('gives lower confidence with no merchant similarity when other signals are imperfect', () => {
|
||||
// With imperfect date/amount, missing merchant signal lowers overall confidence
|
||||
const withMerchant = calculateMatchConfidence(1, 0.02, 0.8)
|
||||
const noMerchant = calculateMatchConfidence(1, 0.02, 0)
|
||||
expect(noMerchant.confidence).toBeLessThan(withMerchant.confidence)
|
||||
})
|
||||
|
||||
it('respects custom tolerances', () => {
|
||||
// With wider tolerance, same variance should give higher score
|
||||
const narrow = calculateMatchConfidence(2, 0.03, 0.5, 3, 0.05)
|
||||
const wide = calculateMatchConfidence(2, 0.03, 0.5, 7, 0.10)
|
||||
expect(wide.confidence).toBeGreaterThan(narrow.confidence)
|
||||
})
|
||||
|
||||
it('drops the amount signal when amountVariance is null (cross-currency)', () => {
|
||||
// A null variance means the amounts could not be compared across
|
||||
// currencies. Confidence must rely on date + merchant only, never reward
|
||||
// a coincidental same-number match (750 EUR vs 750 SEK).
|
||||
const { confidence, matchReasons } = calculateMatchConfidence(0, null, 1.0)
|
||||
// Date (1.0) + merchant (1.0) both perfect, amount excluded → still ~1.0,
|
||||
// but no amount reason is emitted.
|
||||
expect(confidence).toBeGreaterThan(0.9)
|
||||
expect(matchReasons).not.toContain('Exakt belopp')
|
||||
expect(matchReasons).toContain('Exakt datum')
|
||||
expect(matchReasons).toContain('Handlare matchar')
|
||||
})
|
||||
|
||||
it('does not let a coincidental number reward a cross-currency mismatch', () => {
|
||||
// Same date, no merchant signal. With a real 0 amountVariance the score is
|
||||
// high; with null (uncomparable currencies) it must fall back to date only.
|
||||
const sameNumber = calculateMatchConfidence(5, 0, 0, 120)
|
||||
const uncomparable = calculateMatchConfidence(5, null, 0, 120)
|
||||
expect(uncomparable.confidence).toBeLessThan(sameNumber.confidence)
|
||||
})
|
||||
})
|
||||
|
||||
describe('amountVarianceForMatch', () => {
|
||||
it('compares raw magnitudes for same-currency rows (expense sign-agnostic)', () => {
|
||||
// 750 EUR underlag vs a -750 EUR bank expense → exact.
|
||||
expect(amountVarianceForMatch(750, 'EUR', null, -750, 'EUR', -8625)).toBe(0)
|
||||
})
|
||||
|
||||
it('does NOT match 750 EUR against 750 SEK (the reported bug)', () => {
|
||||
// No FX rate (receiptSek null) and different currencies → not comparable,
|
||||
// so the amount signal is dropped rather than rewarding the coincidence.
|
||||
expect(amountVarianceForMatch(750, 'EUR', null, -750, 'SEK', -750)).toBeNull()
|
||||
})
|
||||
|
||||
it('normalises to SEK when a rate is available and matches the equivalent charge', () => {
|
||||
// 750 EUR ≈ 8625 SEK (rate 11.5). A -8505 SEK bank charge is ~1.4% off.
|
||||
const v = amountVarianceForMatch(750, 'EUR', 8625, -8505, 'SEK', -8505)
|
||||
expect(v).not.toBeNull()
|
||||
expect(v!).toBeLessThan(0.05)
|
||||
})
|
||||
|
||||
it('flags a real SEK mismatch as a large variance', () => {
|
||||
const v = amountVarianceForMatch(750, 'EUR', 8625, -500, 'SEK', -500)
|
||||
expect(v!).toBeGreaterThan(0.05)
|
||||
})
|
||||
|
||||
it('returns null when there is no underlag total or it is zero', () => {
|
||||
expect(amountVarianceForMatch(null, 'SEK', null, -100, 'SEK', -100)).toBeNull()
|
||||
expect(amountVarianceForMatch(0, 'SEK', 0, -100, 'SEK', -100)).toBeNull()
|
||||
})
|
||||
|
||||
it('treats currency codes case-insensitively', () => {
|
||||
expect(amountVarianceForMatch(100, 'eur', null, -100, 'EUR', -1150)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bestProminentAmountVariance', () => {
|
||||
it('picks the closest of several printed amounts and names it', () => {
|
||||
// An agreement listing both a monthly price and a one-off price: the
|
||||
// one-off 2500 matches the -2500 AVGIFT charge exactly.
|
||||
const best = bestProminentAmountVariance(
|
||||
[
|
||||
{ amount: 49, label: 'Månadspris' },
|
||||
{ amount: 2500, label: 'Engångspris' },
|
||||
],
|
||||
'SEK',
|
||||
-2500,
|
||||
'SEK',
|
||||
-2500,
|
||||
)
|
||||
expect(best).toEqual({ variance: 0, amount: 2500, label: 'Engångspris' })
|
||||
})
|
||||
|
||||
it('returns null when nothing is comparable', () => {
|
||||
expect(bestProminentAmountVariance([], 'SEK', -2500, 'SEK', -2500)).toBeNull()
|
||||
// Cross-currency without a rate stays incomparable, like a total would.
|
||||
expect(
|
||||
bestProminentAmountVariance([{ amount: 2500, label: null }], 'EUR', -2500, 'SEK', -2500),
|
||||
).toBeNull()
|
||||
// Zero amounts carry no signal (amountVarianceForMatch drops them).
|
||||
expect(
|
||||
bestProminentAmountVariance([{ amount: 0, label: null }], 'SEK', -2500, 'SEK', -2500),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('the discount factor keeps fallback agreement below certainty', () => {
|
||||
// Exact date + exact amount + no merchant normalises to 1.0; a fallback
|
||||
// match must not present that as certainty (this exact geometry scored
|
||||
// "100% säkerhet" on a wrong same-day transaction before the factor).
|
||||
const { confidence } = calculateMatchConfidence(0, 0, 0)
|
||||
const discounted = roundOre(confidence * FALLBACK_CONFIDENCE_FACTOR)
|
||||
expect(confidence).toBe(1)
|
||||
expect(discounted).toBeLessThan(1)
|
||||
})
|
||||
|
||||
it('a disagreeing fallback amount scores no better than a disagreeing total', () => {
|
||||
// Renormalized weights made a wrong fallback amount OUTSCORE a wrong
|
||||
// invoice total (0.67 vs 0.60 with exact date + merchant); the factor
|
||||
// approach scores both at full weight and then discounts the fallback.
|
||||
const asTotal = calculateMatchConfidence(0, 1.4, 0.9).confidence
|
||||
const asFallback = roundOre(asTotal * FALLBACK_CONFIDENCE_FACTOR)
|
||||
expect(asFallback).toBeLessThanOrEqual(asTotal)
|
||||
expect(asFallback).toBeLessThan(0.6)
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeForMatch', () => {
|
||||
it('leaves the frozen key normalizer alone', () => {
|
||||
// normalizeMerchantName feeds a PERSISTED unique key with a SQL mirror.
|
||||
// If this ever fails, the konteringskarta join is about to drift.
|
||||
expect(normalizeMerchantName('Telia AB')).toBe('telia')
|
||||
expect(normalizeMerchantName('Café Överkås!')).toBe('café överkås')
|
||||
})
|
||||
|
||||
it('strips the Swedish card rails', () => {
|
||||
expect(normalizeForMatch('Ryde Sweden AB K8066 Kortköp/uttag')).toBe('ryde sweden')
|
||||
expect(normalizeForMatch('Kortköp 260612 Prime Video')).toBe('prime video')
|
||||
expect(normalizeForMatch('ELGIGANTEN S/25-07-14')).toBe('elgiganten s')
|
||||
})
|
||||
|
||||
it('folds the three ways banks mangle Swedish letters', () => {
|
||||
// Same merchant, spelled three ways by three feeds.
|
||||
const a = normalizeForMatch('Alviks kött och fisk')
|
||||
expect(normalizeForMatch('Alviks koett och fisk')).toBe(a)
|
||||
expect(normalizeForMatch('Alviks k??tt och fisk')).not.toBe('')
|
||||
})
|
||||
|
||||
it('keeps both sides of a processor marker', () => {
|
||||
// The merchant is second in K*IKEA and first in GOOGLE*PLAY.
|
||||
expect(normalizeForMatch('K*IKEA GALLE')).toContain('ikea')
|
||||
expect(normalizeForMatch('GOOGLE*PLAY')).toContain('google')
|
||||
})
|
||||
|
||||
it('drops legal forms and reference numbers', () => {
|
||||
expect(normalizeForMatch('Adobe Systems Software Ireland Ltd')).toBe('adobe systems software ireland')
|
||||
expect(normalizeForMatch('GOOGLE ADS8047863617')).toBe('google ads')
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateMerchantSimilarity on real confirmed pairs', () => {
|
||||
// Every pair below is one a human actually made in production
|
||||
// (invoice_inbox_items.matched_transaction_id), so these are recall targets,
|
||||
// not invented examples.
|
||||
const CONFIRMED: Array<[string, string]> = [
|
||||
['APPLE COM/SE', 'APPLE COM/SE/25-02-20'],
|
||||
['Word and Sound Medien GmbH', 'Word and Sound GmbH'],
|
||||
['Anomaly', 'ANOMALY,SAN FRANCISCO,US Kortköp'],
|
||||
['Tradera Marketplace AB', 'TRADERA 1022'],
|
||||
['DigitalOcean LLC', 'DIGITALOCEAN.COM AMSTERDAM Kortköp/uttag'],
|
||||
['Cinode AB', 'WWW.CINODE.COM'],
|
||||
['Kjell & Company', 'KjellCo Oktober'],
|
||||
['Hostinger International Ltd.', 'Hostinger Apr JW'],
|
||||
['OpenAI OpCo, LLC', 'OPENAI *CHATGP'],
|
||||
['Google Ads', 'GOOGLE ADS8047863617'],
|
||||
['Elgiganten', 'ELGIGANTEN S/25-07-14'],
|
||||
['Hanko GmbH', 'HANKO IO'],
|
||||
['Panduro', 'PANDURO LUND'],
|
||||
['Rusta Lindingö 135', 'RUSTA LINDING?? 135'],
|
||||
['Loopia AB', 'Loopia'],
|
||||
['Kilo Code', 'KILO CODE INC,SAN FRANCISCO,US Kortköp'],
|
||||
['DNH GODADDY', 'DNH GODADDY /25-07-06'],
|
||||
['Adobe Systems Software Ireland Ltd', 'Adobe'],
|
||||
['Lennart & Bror Kött (Alviks kött och fisk AB)', 'Alviks koett och fisk K3667 Kortköp/uttag'],
|
||||
['Ryde Sweden AB', 'Ryde Sweden AB K8066 Kortköp/uttag'],
|
||||
['IKEA', 'K*IKEA GALLE'],
|
||||
['Espresso House', 'ESPRESSO HOUSE 1234 STOCKHOLM'],
|
||||
]
|
||||
|
||||
it.each(CONFIRMED)('recognises %s ↔ %s', (receipt, bank) => {
|
||||
expect(calculateMerchantSimilarity(receipt, bank)).toBeGreaterThanOrEqual(0.6)
|
||||
})
|
||||
|
||||
// Aggressive folding buys recall; these guard the price of it.
|
||||
const DIFFERENT: Array<[string, string]> = [
|
||||
['Cloudflare', 'Clas Ohlson'],
|
||||
['SJ AB', 'Skatteverket'],
|
||||
['Adobe', 'Apple'],
|
||||
['ICA Maxi Stockholm', 'Coop Solna'],
|
||||
['Anthropic, PBC', 'Anomaly'],
|
||||
['Hostinger International Ltd.', 'Hanko GmbH'],
|
||||
['Google Ads', 'Google Cloud EMEA Limited'],
|
||||
]
|
||||
|
||||
it.each(DIFFERENT)('keeps %s apart from %s', (a, b) => {
|
||||
expect(calculateMerchantSimilarity(a, b)).toBeLessThan(0.6)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Swedish bank vocabulary that wraps a merchant name without being part of it.
|
||||
* Drawn from a real ledger, where "Utlägg Norwegian" against "Norwegian Air
|
||||
* Shuttle AOC AS" scored 0.18 and an exact 1 998 kr match was never proposed.
|
||||
*/
|
||||
describe('payment words are not merchant names', () => {
|
||||
it('sees through an expense reimbursement', () => {
|
||||
expect(calculateMerchantSimilarity('Utlägg Norwegian', 'Norwegian Air Shuttle AOC AS'))
|
||||
.toBeGreaterThan(0.8)
|
||||
})
|
||||
|
||||
it('sees through a transfer', () => {
|
||||
expect(calculateMerchantSimilarity('Kontorsplatser j Bg-bet. via internet', 'Kontorsplatser AB'))
|
||||
.toBeGreaterThan(0.8)
|
||||
})
|
||||
|
||||
it('still tells two different merchants apart', () => {
|
||||
expect(calculateMerchantSimilarity('Utlägg Norwegian', 'Scandinavian Airlines System'))
|
||||
.toBeLessThan(0.5)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
INBOX_UPLOAD_COMPLETE_URL,
|
||||
INBOX_UPLOAD_CREATE_URL,
|
||||
uploadViaSignedUrl,
|
||||
} from '../direct-upload'
|
||||
|
||||
const UPLOAD_ID = '33333333-3333-4333-8333-333333333333'
|
||||
const SIGNED_URL =
|
||||
'https://proj.supabase.co/storage/v1/object/upload/sign/documents/documents/c/u/pending/x.pdf?token=signed'
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function reservationResponse(): Response {
|
||||
return jsonResponse({
|
||||
data: { upload_id: UPLOAD_ID, upload_url: SIGNED_URL, expires_at: '2026-08-28T12:00:00.000Z' },
|
||||
})
|
||||
}
|
||||
|
||||
function fakeFile(): File {
|
||||
return new File([new Uint8Array(16)], 'faktura.pdf', { type: 'application/pdf' })
|
||||
}
|
||||
|
||||
type Call = { url: string; init: RequestInit | undefined }
|
||||
|
||||
function fetchSequence(responses: Array<Response | (() => Response)>) {
|
||||
const calls: Call[] = []
|
||||
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
calls.push({ url: String(input), init })
|
||||
const next = responses.shift()
|
||||
if (!next) throw new Error('unexpected fetch')
|
||||
return typeof next === 'function' ? next() : next
|
||||
}) as unknown as typeof fetch
|
||||
return { fetchImpl, calls }
|
||||
}
|
||||
|
||||
describe('uploadViaSignedUrl', () => {
|
||||
it('runs create, PUT to the raw signed URL, then complete, and resolves to the complete response', async () => {
|
||||
const completeRes = jsonResponse({ data: { inbox_item_id: 'inbox-1' } })
|
||||
const { fetchImpl, calls } = fetchSequence([
|
||||
reservationResponse(),
|
||||
new Response(null, { status: 200 }),
|
||||
completeRes,
|
||||
])
|
||||
const file = fakeFile()
|
||||
|
||||
const res = await uploadViaSignedUrl(file, {
|
||||
fetchImpl,
|
||||
matchedTransactionId: 'tx-1',
|
||||
skipExtraction: true,
|
||||
})
|
||||
|
||||
expect(res).toBe(completeRes)
|
||||
expect(calls.map((c) => c.url)).toEqual([INBOX_UPLOAD_CREATE_URL, SIGNED_URL, INBOX_UPLOAD_COMPLETE_URL])
|
||||
|
||||
// 1. create: JSON metadata only, never the bytes
|
||||
expect(calls[0].init?.method).toBe('POST')
|
||||
expect(JSON.parse(String(calls[0].init?.body))).toEqual({
|
||||
file_name: 'faktura.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
size_bytes: 16,
|
||||
})
|
||||
|
||||
// 2. PUT: the file itself, typed, no upsert onto an existing key
|
||||
expect(calls[1].init?.method).toBe('PUT')
|
||||
expect(calls[1].init?.headers).toEqual({ 'content-type': 'application/pdf', 'x-upsert': 'false' })
|
||||
expect(calls[1].init?.body).toBe(file)
|
||||
|
||||
// 3. complete: the reservation plus the same options /upload takes
|
||||
expect(calls[2].init?.method).toBe('POST')
|
||||
expect(JSON.parse(String(calls[2].init?.body))).toEqual({
|
||||
upload_id: UPLOAD_ID,
|
||||
file_name: 'faktura.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
matched_transaction_id: 'tx-1',
|
||||
skip_extraction: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('defaults to no matched transaction and extraction on', async () => {
|
||||
const { fetchImpl, calls } = fetchSequence([
|
||||
reservationResponse(),
|
||||
new Response(null, { status: 200 }),
|
||||
jsonResponse({ data: {} }),
|
||||
])
|
||||
|
||||
await uploadViaSignedUrl(fakeFile(), { fetchImpl })
|
||||
|
||||
expect(JSON.parse(String(calls[2].init?.body))).toMatchObject({
|
||||
matched_transaction_id: null,
|
||||
skip_extraction: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the create response unchanged when the reservation is refused, and sends nothing else', async () => {
|
||||
const limited = jsonResponse({ error: { code: 'RATE_LIMITED', message: 'För många' } }, 429)
|
||||
const { fetchImpl, calls } = fetchSequence([limited])
|
||||
|
||||
const res = await uploadViaSignedUrl(fakeFile(), { fetchImpl })
|
||||
|
||||
expect(res).toBe(limited)
|
||||
expect(calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('aborts before complete when Storage rejects the PUT, surfacing the status in an envelope', async () => {
|
||||
const { fetchImpl, calls } = fetchSequence([
|
||||
reservationResponse(),
|
||||
new Response('token expired', { status: 403 }),
|
||||
])
|
||||
|
||||
const res = await uploadViaSignedUrl(fakeFile(), { fetchImpl })
|
||||
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(res.ok).toBe(false)
|
||||
expect(res.status).toBe(403)
|
||||
const body = (await res.json()) as { error: { code: string; message: string } }
|
||||
expect(body.error.code).toBe('INBOX_UPLOAD_STORAGE_REJECTED')
|
||||
expect(body.error.message).toContain('403')
|
||||
expect(body.error.message).toContain('Försök igen')
|
||||
})
|
||||
|
||||
it('throws when the reservation is malformed rather than PUTting to nowhere', async () => {
|
||||
const { fetchImpl, calls } = fetchSequence([jsonResponse({ data: { upload_id: UPLOAD_ID } })])
|
||||
|
||||
await expect(uploadViaSignedUrl(fakeFile(), { fetchImpl })).rejects.toThrow(/upload_url/)
|
||||
expect(calls).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,179 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseVoucherRefFromFileName } from '@/lib/documents/filename-voucher-ref'
|
||||
|
||||
describe('parseVoucherRefFromFileName', () => {
|
||||
it('parses the SpeedLedger prefix form (series + number + internal id)', () => {
|
||||
expect(parseVoucherRefFromFileName('A31_8c2db060-79ba-4b6e-9f3d-4b0042aa5c52.pdf')).toEqual({
|
||||
series: 'A',
|
||||
number: 31,
|
||||
pattern: 'series_number',
|
||||
autoSelectable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('parses a bare series + number filename', () => {
|
||||
expect(parseVoucherRefFromFileName('V123.pdf')).toMatchObject({ series: 'V', number: 123 })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['A-31 kvitto.pdf', 'A', 31],
|
||||
['A_31.jpg', 'A', 31],
|
||||
['A 31 leverantorsfaktura.png', 'A', 31],
|
||||
['2024-A-31.pdf', 'A', 31],
|
||||
['2024_A31_underlag.pdf', 'A', 31],
|
||||
['ver_A31.pdf', 'A', 31],
|
||||
['Verifikat A31.pdf', 'A', 31],
|
||||
['BC7.pdf', 'BC', 7],
|
||||
])('parses %s', (fileName, series, number) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toMatchObject({ series, number })
|
||||
})
|
||||
|
||||
it('uppercases the series so a lowercase export still joins', () => {
|
||||
expect(parseVoucherRefFromFileName('a31_x.pdf')).toMatchObject({ series: 'A' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
// Paper sizes: every scanner emits an A4.pdf.
|
||||
'A4.pdf',
|
||||
'A4 scan.pdf',
|
||||
'a4.pdf',
|
||||
'A3 ritning.pdf',
|
||||
// A batch scanner's zero-padded counter normalizes onto the same refs.
|
||||
'A0004.pdf',
|
||||
'A001.pdf',
|
||||
// Skatteverket blanketter and quarters.
|
||||
'K10.pdf',
|
||||
'K10 blankett 2024.pdf',
|
||||
'K4.pdf',
|
||||
'N9.pdf',
|
||||
'Q1 2024.pdf',
|
||||
])('parses %s but never pre-selects it: more often a document name than a ref', (fileName) => {
|
||||
const parsed = parseVoucherRefFromFileName(fileName)
|
||||
expect(parsed).not.toBeNull()
|
||||
expect(parsed?.autoSelectable).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['IMG_0031.jpg', 'DSC00123.JPG', 'DOC001.pdf', 'SCN0007.pdf', 'Del 1 av 3.pdf'])(
|
||||
'parses %s but never pre-selects a three-letter series: cameras, not ledgers',
|
||||
(fileName) => {
|
||||
const parsed = parseVoucherRefFromFileName(fileName)
|
||||
expect(parsed).not.toBeNull()
|
||||
expect(parsed?.autoSelectable).toBe(false)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
['A7.pdf', 'A', 7],
|
||||
['A31.pdf', 'A', 31],
|
||||
['K1.pdf', 'K', 1],
|
||||
['K14.pdf', 'K', 14],
|
||||
['LB2.pdf', 'LB', 2],
|
||||
])('keeps %s auto-selectable: just outside the collision list', (fileName, series, number) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toEqual({
|
||||
series,
|
||||
number,
|
||||
pattern: 'series_number',
|
||||
autoSelectable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
'underlag/2024/A31_kvitto.pdf',
|
||||
'underlag\\A31.pdf',
|
||||
// The manual-reference box feeds arbitrary typed text through this same
|
||||
// parser. Splitting on the separator would turn a typed date into a
|
||||
// voucher number and hand the user an irreversible link to approve.
|
||||
'2024/01/31 kvitto.pdf',
|
||||
'2024/01/31',
|
||||
])('does not strip a path component out of %s', (input) => {
|
||||
expect(parseVoucherRefFromFileName(input)).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['Verifikation 31.pdf', 31],
|
||||
['verifikation31.pdf', 31],
|
||||
['Verifikat 31.pdf', 31],
|
||||
// `ver` is a prefix word, not a series: without that rule this one form
|
||||
// came back auto-selectable while every spelled-out variant did not.
|
||||
['ver 31.pdf', 31],
|
||||
['ver31.pdf', 31],
|
||||
['VER-31.pdf', 31],
|
||||
['ver.31.pdf', 31],
|
||||
])('reads %s as a series-less reference, not a bogus series', (fileName, number) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toEqual({
|
||||
series: null,
|
||||
number,
|
||||
pattern: 'number_only',
|
||||
autoSelectable: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns a series-less parse for a number-only name, never auto-selectable', () => {
|
||||
expect(parseVoucherRefFromFileName('31.pdf')).toEqual({
|
||||
series: null,
|
||||
number: 31,
|
||||
pattern: 'number_only',
|
||||
autoSelectable: false,
|
||||
})
|
||||
expect(parseVoucherRefFromFileName('31_kvitto.pdf')).toMatchObject({ series: null, number: 31 })
|
||||
})
|
||||
|
||||
it.each([
|
||||
'20240131.pdf',
|
||||
'20240131_kvitto.pdf',
|
||||
'2024-01-31 kvitto.pdf',
|
||||
'2024_01_31.pdf',
|
||||
// Unpadded components, two-digit years and space separators are just as
|
||||
// common in receipt exports and used to slip through as voucher 2024 / 24.
|
||||
'2024-1-31 kvitto.pdf',
|
||||
'2024_1_31.pdf',
|
||||
'2024.1.31.pdf',
|
||||
'2024 01 31 kvitto.pdf',
|
||||
'24-01-31 kvitto.pdf',
|
||||
'2024/01/31.pdf',
|
||||
// Day-first and US order: the day would otherwise become a voucher number
|
||||
// that always exists in the year.
|
||||
'31.01.2024.pdf',
|
||||
'31-01-2024.pdf',
|
||||
'31_01_2024.pdf',
|
||||
'31.1.2024.pdf',
|
||||
'24.12.2024 julbord.pdf',
|
||||
'03.04.2025 ICA.pdf',
|
||||
'12.24.2024.pdf',
|
||||
'01-31-2024.pdf',
|
||||
'1-31-2024 receipt.pdf',
|
||||
'31/1/2024.pdf',
|
||||
])('refuses the date-named file %s rather than reading it as a number', (fileName) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['2024.pdf', '2024_kvitto.pdf', '1999.pdf'])(
|
||||
'refuses the year-shaped series-less name %s',
|
||||
(fileName) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toBeNull()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
'kvitto.pdf',
|
||||
'Faktura2024.pdf',
|
||||
'A31kvitto.pdf',
|
||||
'Version2_kvitto.pdf',
|
||||
'',
|
||||
'.pdf',
|
||||
])('returns null for %s instead of guessing', (fileName) => {
|
||||
expect(parseVoucherRefFromFileName(fileName)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a zero voucher number', () => {
|
||||
expect(parseVoucherRefFromFileName('A0.pdf')).toBeNull()
|
||||
expect(parseVoucherRefFromFileName('0.pdf')).toBeNull()
|
||||
})
|
||||
|
||||
it('handles a filename with no extension at all', () => {
|
||||
expect(parseVoucherRefFromFileName('A31_8c2db060-79ba-4b6e-9f3d-4b0042aa5c52')).toMatchObject({
|
||||
series: 'A',
|
||||
number: 31,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { selectInboxFields } from '@/lib/documents/inbox-field-visibility'
|
||||
|
||||
const FIELDS = [
|
||||
{ key: 'supplier.name', label: 'Leverantör' },
|
||||
{ key: 'totals.total', label: 'Totalt' },
|
||||
{ key: 'totals.vatAmount', label: 'Moms' },
|
||||
{ key: 'supplier.bankgiro', label: 'Bankgiro' },
|
||||
{ key: 'supplier.plusgiro', label: 'Plusgiro' },
|
||||
{ key: 'invoice.invoiceNumber', label: 'Fakturanr' },
|
||||
{ key: 'invoice.paymentReference', label: 'OCR/Referens' },
|
||||
{ key: 'invoice.invoiceDate', label: 'Fakturadatum' },
|
||||
{ key: 'invoice.dueDate', label: 'Förfallodatum' },
|
||||
]
|
||||
|
||||
const none = () => false
|
||||
const keys = (r: { shown: { key: string }[] }) => r.shown.map((f) => f.key)
|
||||
const labelOf = (r: { shown: { key: string; label: string }[] }, key: string) =>
|
||||
r.shown.find((f) => f.key === key)?.label
|
||||
|
||||
describe('selectInboxFields', () => {
|
||||
it('leaves invoices exactly as they are', () => {
|
||||
for (const kind of ['supplier_invoice', 'government_letter', 'other', null, undefined]) {
|
||||
const r = selectInboxFields({ documentKind: kind, fields: FIELDS, hasValue: none, showAll: false })
|
||||
expect(keys(r)).toEqual(FIELDS.map((f) => f.key))
|
||||
expect(r.hiddenCount).toBe(0)
|
||||
expect(labelOf(r, 'invoice.invoiceDate')).toBe('Fakturadatum')
|
||||
}
|
||||
})
|
||||
|
||||
it('hides the five invoice-only fields on a receipt and counts them', () => {
|
||||
const r = selectInboxFields({ documentKind: 'receipt', fields: FIELDS, hasValue: none, showAll: false })
|
||||
expect(r.hiddenCount).toBe(5)
|
||||
expect(keys(r)).toEqual([
|
||||
'supplier.name',
|
||||
'totals.total',
|
||||
'totals.vatAmount',
|
||||
'invoice.invoiceDate',
|
||||
])
|
||||
})
|
||||
|
||||
it('relabels the date as the purchase date on a receipt', () => {
|
||||
const r = selectInboxFields({ documentKind: 'receipt', fields: FIELDS, hasValue: none, showAll: false })
|
||||
expect(labelOf(r, 'invoice.invoiceDate')).toBe('Inköpsdatum')
|
||||
})
|
||||
|
||||
it('NEVER hides a field that holds a value, even on a receipt', () => {
|
||||
// Misclassification, or a hybrid restaurangnota carrying an invoice
|
||||
// number: data must never disappear behind a heuristic.
|
||||
const r = selectInboxFields({
|
||||
documentKind: 'receipt',
|
||||
fields: FIELDS,
|
||||
hasValue: (k) => k === 'invoice.invoiceNumber',
|
||||
showAll: false,
|
||||
})
|
||||
expect(keys(r)).toContain('invoice.invoiceNumber')
|
||||
expect(r.hiddenCount).toBe(4)
|
||||
})
|
||||
|
||||
it('showAll restores every field, still relabelled', () => {
|
||||
const r = selectInboxFields({ documentKind: 'receipt', fields: FIELDS, hasValue: none, showAll: true })
|
||||
expect(keys(r)).toEqual(FIELDS.map((f) => f.key))
|
||||
expect(r.hiddenCount).toBe(0)
|
||||
expect(labelOf(r, 'invoice.invoiceDate')).toBe('Inköpsdatum')
|
||||
})
|
||||
|
||||
it('does not mutate the caller’s field list', () => {
|
||||
const copy = FIELDS.map((f) => ({ ...f }))
|
||||
selectInboxFields({ documentKind: 'receipt', fields: copy, hasValue: none, showAll: true })
|
||||
expect(copy.find((f) => f.key === 'invoice.invoiceDate')?.label).toBe('Fakturadatum')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
INBOX_KIND_FILTERS,
|
||||
matchesInboxKindFilter,
|
||||
resolveInboxKind,
|
||||
type InboxDocumentKind,
|
||||
} from '@/lib/documents/inbox-kind'
|
||||
|
||||
describe('resolveInboxKind', () => {
|
||||
it.each(['receipt', 'supplier_invoice', 'government_letter', 'other'] as const)(
|
||||
'returns the AI documentKind %s when there is no sender hint',
|
||||
(kind) => {
|
||||
expect(resolveInboxKind({ extracted_data: { documentKind: kind } })).toBe(kind)
|
||||
expect(resolveInboxKind({ kind_hint: null, extracted_data: { documentKind: kind } })).toBe(kind)
|
||||
},
|
||||
)
|
||||
|
||||
it('returns null when nothing is classified', () => {
|
||||
expect(resolveInboxKind({})).toBeNull()
|
||||
expect(resolveInboxKind({ extracted_data: null })).toBeNull()
|
||||
expect(resolveInboxKind({ extracted_data: {} })).toBeNull()
|
||||
expect(resolveInboxKind({ extracted_data: { documentKind: null } })).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a documentKind outside the vocabulary', () => {
|
||||
expect(resolveInboxKind({ extracted_data: { documentKind: 'parking_ticket' } })).toBeNull()
|
||||
expect(resolveInboxKind({ kind_hint: 'invoice' })).toBeNull()
|
||||
})
|
||||
|
||||
it('lets the sender hint win over the AI classification', () => {
|
||||
expect(
|
||||
resolveInboxKind({ kind_hint: 'supplier_invoice', extracted_data: { documentKind: 'receipt' } }),
|
||||
).toBe('supplier_invoice')
|
||||
expect(
|
||||
resolveInboxKind({ kind_hint: 'receipt', extracted_data: { documentKind: 'supplier_invoice' } }),
|
||||
).toBe('receipt')
|
||||
})
|
||||
|
||||
it('uses the sender hint even before extraction has landed', () => {
|
||||
expect(resolveInboxKind({ kind_hint: 'receipt', extracted_data: null })).toBe('receipt')
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchesInboxKindFilter', () => {
|
||||
const kinds: Array<InboxDocumentKind | null> = [
|
||||
'receipt',
|
||||
'supplier_invoice',
|
||||
'government_letter',
|
||||
'other',
|
||||
null,
|
||||
]
|
||||
|
||||
it("'all' passes every kind including unclassified", () => {
|
||||
for (const kind of kinds) expect(matchesInboxKindFilter(kind, 'all')).toBe(true)
|
||||
})
|
||||
|
||||
it("'supplier_invoice' passes only supplier invoices", () => {
|
||||
expect(matchesInboxKindFilter('supplier_invoice', 'supplier_invoice')).toBe(true)
|
||||
expect(matchesInboxKindFilter('receipt', 'supplier_invoice')).toBe(false)
|
||||
expect(matchesInboxKindFilter('government_letter', 'supplier_invoice')).toBe(false)
|
||||
expect(matchesInboxKindFilter('other', 'supplier_invoice')).toBe(false)
|
||||
expect(matchesInboxKindFilter(null, 'supplier_invoice')).toBe(false)
|
||||
})
|
||||
|
||||
it("'underlag' passes receipt, government_letter and other", () => {
|
||||
expect(matchesInboxKindFilter('receipt', 'underlag')).toBe(true)
|
||||
expect(matchesInboxKindFilter('government_letter', 'underlag')).toBe(true)
|
||||
expect(matchesInboxKindFilter('other', 'underlag')).toBe(true)
|
||||
expect(matchesInboxKindFilter('supplier_invoice', 'underlag')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps unclassified items out of both narrow filters', () => {
|
||||
expect(matchesInboxKindFilter(null, 'underlag')).toBe(false)
|
||||
expect(matchesInboxKindFilter(null, 'supplier_invoice')).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the three filters in menu order', () => {
|
||||
expect(INBOX_KIND_FILTERS).toEqual(['all', 'supplier_invoice', 'underlag'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
linkDocuments,
|
||||
formatFailedDocumentNames,
|
||||
type DocumentLinkTarget,
|
||||
} from '../link-documents'
|
||||
|
||||
function okResponse(): Response {
|
||||
return new Response(JSON.stringify({ data: { id: 'doc' } }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function errorResponse(status: number, code?: string, message?: string): Response {
|
||||
return new Response(
|
||||
JSON.stringify(code ? { error: { code, message } } : {}),
|
||||
{ status, headers: { 'Content-Type': 'application/json' } },
|
||||
)
|
||||
}
|
||||
|
||||
const targets: DocumentLinkTarget[] = [
|
||||
{ documentId: 'doc-1', fileName: 'kvitto-1.pdf' },
|
||||
{ documentId: 'doc-2', fileName: 'kvitto-2.pdf' },
|
||||
{ documentId: 'doc-3', fileName: 'kvitto-3.pdf' },
|
||||
]
|
||||
|
||||
describe('linkDocuments', () => {
|
||||
it('links every document when all calls succeed', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(okResponse())
|
||||
|
||||
const result = await linkDocuments(targets, 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.linked).toEqual(['doc-1', 'doc-2', 'doc-3'])
|
||||
expect(result.failed).toEqual([])
|
||||
expect(result.allLinked).toBe(true)
|
||||
expect(result.firstLinkedId).toBe('doc-1')
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('POSTs to the link endpoint with the journal entry id', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(okResponse())
|
||||
|
||||
await linkDocuments([{ documentId: 'doc-1', fileName: 'a.pdf' }], 'entry-9', { fetchImpl })
|
||||
|
||||
const [url, init] = fetchImpl.mock.calls[0]
|
||||
expect(url).toBe('/api/documents/doc-1/link')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(JSON.parse(init.body)).toEqual({ journal_entry_id: 'entry-9' })
|
||||
})
|
||||
|
||||
it('passes inbox_item_id and transaction_id through only when set', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(okResponse())
|
||||
|
||||
await linkDocuments(
|
||||
[{ documentId: 'doc-1', inboxItemId: 'inbox-1', transactionId: 'tx-1' }],
|
||||
'entry-1',
|
||||
{ fetchImpl },
|
||||
)
|
||||
|
||||
expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toEqual({
|
||||
journal_entry_id: 'entry-1',
|
||||
inbox_item_id: 'inbox-1',
|
||||
transaction_id: 'tx-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports the specific documents that failed when some succeed', async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(okResponse())
|
||||
.mockResolvedValueOnce(errorResponse(500, 'DOC_LINK_FAILED', 'Kunde inte bifoga underlag'))
|
||||
.mockResolvedValueOnce(okResponse())
|
||||
|
||||
const result = await linkDocuments(targets, 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.linked).toEqual(['doc-1', 'doc-3'])
|
||||
expect(result.allLinked).toBe(false)
|
||||
expect(result.failed).toHaveLength(1)
|
||||
expect(result.failed[0]).toEqual({
|
||||
documentId: 'doc-2',
|
||||
fileName: 'kvitto-2.pdf',
|
||||
status: 500,
|
||||
code: 'DOC_LINK_FAILED',
|
||||
reason: 'Kunde inte bifoga underlag',
|
||||
})
|
||||
// The caller must be able to name the missing underlag to the user.
|
||||
expect(formatFailedDocumentNames(result.failed)).toBe('kvitto-2.pdf')
|
||||
})
|
||||
|
||||
it('reports a non-ok response as a failure (the old empty-catch hid these)', async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValue(errorResponse(403, 'PERIOD_LOCKED', 'Bokföringen är låst'))
|
||||
|
||||
const result = await linkDocuments([targets[0]], 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.linked).toEqual([])
|
||||
expect(result.allLinked).toBe(false)
|
||||
expect(result.failed[0].status).toBe(403)
|
||||
expect(result.failed[0].code).toBe('PERIOD_LOCKED')
|
||||
})
|
||||
|
||||
it('handles a non-ok response with a non-JSON body', async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValue(new Response('<html>502</html>', { status: 502 }))
|
||||
|
||||
const result = await linkDocuments([targets[0]], 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.allLinked).toBe(false)
|
||||
expect(result.failed[0]).toEqual({
|
||||
documentId: 'doc-1',
|
||||
fileName: 'kvitto-1.pdf',
|
||||
status: 502,
|
||||
code: null,
|
||||
reason: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports every document when all links fail', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(errorResponse(500, 'DOC_LINK_FAILED'))
|
||||
|
||||
const result = await linkDocuments(targets, 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.linked).toEqual([])
|
||||
expect(result.failed).toHaveLength(3)
|
||||
expect(result.firstLinkedId).toBeNull()
|
||||
expect(result.allLinked).toBe(false)
|
||||
expect(formatFailedDocumentNames(result.failed)).toBe(
|
||||
'kvitto-1.pdf, kvitto-2.pdf, kvitto-3.pdf',
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a thrown network error instead of swallowing it', async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(okResponse())
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockResolvedValueOnce(okResponse())
|
||||
|
||||
const result = await linkDocuments(targets, 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result.linked).toEqual(['doc-1', 'doc-3'])
|
||||
expect(result.failed).toEqual([
|
||||
{
|
||||
documentId: 'doc-2',
|
||||
fileName: 'kvitto-2.pdf',
|
||||
status: 0,
|
||||
code: null,
|
||||
reason: 'Failed to fetch',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('never rejects, even when every call throws', async () => {
|
||||
const fetchImpl = vi.fn().mockRejectedValue(new Error('offline'))
|
||||
|
||||
await expect(linkDocuments(targets, 'entry-1', { fetchImpl })).resolves.toMatchObject({
|
||||
linked: [],
|
||||
allLinked: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('treats an empty target list as nothing to do', async () => {
|
||||
const fetchImpl = vi.fn()
|
||||
|
||||
const result = await linkDocuments([], 'entry-1', { fetchImpl })
|
||||
|
||||
expect(result).toEqual({ linked: [], failed: [], firstLinkedId: null, allLinked: true })
|
||||
expect(fetchImpl).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('encodes the document id in the URL', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue(okResponse())
|
||||
|
||||
await linkDocuments([{ documentId: 'a/b c' }], 'entry-1', { fetchImpl })
|
||||
|
||||
expect(fetchImpl.mock.calls[0][0]).toBe('/api/documents/a%2Fb%20c/link')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatFailedDocumentNames', () => {
|
||||
it('falls back to the document id when the file name is missing', () => {
|
||||
expect(
|
||||
formatFailedDocumentNames([
|
||||
{ documentId: 'doc-1', fileName: null, status: 500, code: null, reason: null },
|
||||
{ documentId: 'doc-2', fileName: 'kvitto.pdf', status: 0, code: null, reason: null },
|
||||
]),
|
||||
).toBe('doc-1, kvitto.pdf')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,354 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { buildUnderlagPlan, planPermitsAttach } from '@/lib/documents/underlag-import'
|
||||
import type { FiscalPeriodRow, VoucherRow } from '@/lib/documents/voucher-ref-resolver'
|
||||
|
||||
const PERIOD_OPEN = 'period-open'
|
||||
const PERIOD_LOCKED = 'period-locked'
|
||||
|
||||
const PERIODS: FiscalPeriodRow[] = [
|
||||
{
|
||||
id: PERIOD_OPEN,
|
||||
period_start: '2024-01-01',
|
||||
period_end: '2024-12-31',
|
||||
is_closed: false,
|
||||
locked_at: null,
|
||||
},
|
||||
{
|
||||
id: PERIOD_LOCKED,
|
||||
period_start: '2023-01-01',
|
||||
period_end: '2023-12-31',
|
||||
is_closed: true,
|
||||
locked_at: null,
|
||||
},
|
||||
]
|
||||
|
||||
function makeVoucher(overrides: Partial<VoucherRow> & Pick<VoucherRow, 'id'>): VoucherRow {
|
||||
return {
|
||||
fiscal_period_id: PERIOD_OPEN,
|
||||
entry_date: '2024-03-14',
|
||||
description: 'Inköp kontorsmaterial',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 47,
|
||||
source_voucher_series: 'A',
|
||||
source_voucher_number: 31,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal Supabase double keyed on the query SHAPE rather than call order:
|
||||
* buildUnderlagPlan fires the voucher and period reads concurrently, so an
|
||||
* order-sensitive queue would make these tests flaky for no benefit.
|
||||
*/
|
||||
function makeSupabase(opts: {
|
||||
vouchers: VoucherRow[]
|
||||
periods?: FiscalPeriodRow[]
|
||||
/** Total migrated entries in the company, regardless of the number filter. */
|
||||
sourceRefCount?: number
|
||||
}): SupabaseClient {
|
||||
const periods = opts.periods ?? PERIODS
|
||||
|
||||
const from = (table: string) => {
|
||||
let filteredByNumber = false
|
||||
|
||||
const result = () => {
|
||||
if (table === 'fiscal_periods') return { data: periods, error: null, count: periods.length }
|
||||
// Only the number-filtered read returns the voucher rows; the bare
|
||||
// count read answers "does this ledger have ANY source refs at all".
|
||||
return {
|
||||
data: filteredByNumber ? opts.vouchers : [],
|
||||
error: null,
|
||||
count: opts.sourceRefCount ?? opts.vouchers.length,
|
||||
}
|
||||
}
|
||||
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'not', 'order', 'limit', 'maybeSingle', 'single']) {
|
||||
chain[method] = () => chain
|
||||
}
|
||||
chain.in = () => {
|
||||
filteredByNumber = true
|
||||
return chain
|
||||
}
|
||||
chain.range = () => Promise.resolve(result())
|
||||
chain.then = (onFulfilled: (value: unknown) => unknown) =>
|
||||
Promise.resolve(result()).then(onFulfilled)
|
||||
return chain
|
||||
}
|
||||
|
||||
return { from } as unknown as SupabaseClient
|
||||
}
|
||||
|
||||
describe('buildUnderlagPlan', () => {
|
||||
it('matches a filename prefix to the migrated verifikat it names', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', [
|
||||
'A31_8c2db060-79ba-4b6e-9f3d-4b0042aa5c52.pdf',
|
||||
], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0]).toMatchObject({
|
||||
file_name: 'A31_8c2db060-79ba-4b6e-9f3d-4b0042aa5c52.pdf',
|
||||
status: 'matched',
|
||||
parsed_ref: { series: 'A', number: 31 },
|
||||
journal_entry_id: 'je-1',
|
||||
})
|
||||
expect(plan.rows[0].candidates[0]).toMatchObject({
|
||||
voucher_label: 'A47',
|
||||
source_voucher_label: 'A31',
|
||||
period_locked: false,
|
||||
})
|
||||
expect(plan.summary).toMatchObject({ total: 1, matched: 1 })
|
||||
})
|
||||
|
||||
it('matches on the SOURCE number, not our renumbered one', async () => {
|
||||
// The import renumbered source A31 to A47. A file named after our own
|
||||
// number must NOT match: A47 does not exist in the source system.
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A47_kvitto.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('no_match')
|
||||
})
|
||||
|
||||
it('reports a locked period instead of proposing a link the DB will refuse', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-1', fiscal_period_id: PERIOD_LOCKED })],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_LOCKED)
|
||||
|
||||
expect(plan.rows[0]).toMatchObject({ status: 'period_locked', journal_entry_id: 'je-1' })
|
||||
expect(plan.rows[0].candidates[0].period_locked).toBe(true)
|
||||
expect(plan.summary.period_locked).toBe(1)
|
||||
})
|
||||
|
||||
it('treats a period with locked_at set as locked even when not closed', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-1' })],
|
||||
periods: [{ ...PERIODS[0], locked_at: '2025-01-31T00:00:00Z' }],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('period_locked')
|
||||
})
|
||||
|
||||
it('resolves ONLY inside the declared year when a ref exists in several', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [
|
||||
makeVoucher({ id: 'je-2023', fiscal_period_id: PERIOD_LOCKED, entry_date: '2023-03-14' }),
|
||||
makeVoucher({ id: 'je-2024' }),
|
||||
],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('matched')
|
||||
expect(plan.rows[0].journal_entry_id).toBe('je-2024')
|
||||
// The other year's A31 is not even offered as a candidate.
|
||||
expect(plan.rows[0].candidates.map((c) => c.journal_entry_id)).toEqual(['je-2024'])
|
||||
})
|
||||
|
||||
it('NEVER proposes a verifikat outside the declared year, even as the only one', async () => {
|
||||
// The defect this scoping exists for: a partial migration, or a year whose
|
||||
// A31 the importer skipped, leaves exactly one A31 in the whole ledger.
|
||||
// Treating that single hit as identity attached a 2023 receipt to a 2025
|
||||
// verifikat, permanently and undetectably.
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-other-year', fiscal_period_id: PERIOD_LOCKED })],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('no_match')
|
||||
expect(plan.rows[0].journal_entry_id).toBeNull()
|
||||
expect(plan.rows[0].candidates).toEqual([])
|
||||
})
|
||||
|
||||
it('still hands back a choice when one ref repeats INSIDE the declared year', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [
|
||||
makeVoucher({ id: 'je-a' }),
|
||||
makeVoucher({ id: 'je-b', entry_date: '2024-09-02' }),
|
||||
],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('ambiguous')
|
||||
expect(plan.rows[0].journal_entry_id).toBeNull()
|
||||
expect(plan.rows[0].candidates.map((c) => c.journal_entry_id)).toEqual(['je-a', 'je-b'])
|
||||
expect(plan.summary.ambiguous).toBe(1)
|
||||
})
|
||||
|
||||
it('reports which year the plan was resolved against', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.fiscal_period_id).toBe(PERIOD_OPEN)
|
||||
})
|
||||
|
||||
it('never auto-selects a collision-list ref, even on a clean single hit', async () => {
|
||||
// "A4.pdf" is a scanner's paper size far more often than verifikat A4,
|
||||
// and verifikat A4 exists in every migrated ledger, so the collision is
|
||||
// guaranteed. The parse survives, the pre-tick does not.
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-a4', source_voucher_number: 4, voucher_number: 4 })],
|
||||
})
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A4 scan.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0]).toMatchObject({
|
||||
status: 'needs_confirmation',
|
||||
parsed_ref: { series: 'A', number: 4 },
|
||||
journal_entry_id: 'je-a4',
|
||||
})
|
||||
})
|
||||
|
||||
it('never auto-selects a series-less filename, even on a single hit', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0]).toMatchObject({
|
||||
status: 'needs_confirmation',
|
||||
parsed_ref: { series: null, number: 31 },
|
||||
journal_entry_id: 'je-1',
|
||||
})
|
||||
expect(plan.summary.needs_confirmation).toBe(1)
|
||||
})
|
||||
|
||||
it('reports an unreadable filename as unparsed without touching the ledger', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['kvitto ica.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0]).toMatchObject({
|
||||
status: 'unparsed',
|
||||
parsed_ref: null,
|
||||
journal_entry_id: null,
|
||||
candidates: [],
|
||||
})
|
||||
expect(plan.summary.unparsed).toBe(1)
|
||||
})
|
||||
|
||||
it('flags a ledger with no source refs at all, so the miss is explained', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [], sourceRefCount: 0 })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('no_match')
|
||||
expect(plan.no_source_refs).toBe(true)
|
||||
})
|
||||
|
||||
it('does not blame missing source refs when the ledger has them', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [], sourceRefCount: 120 })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.rows[0].status).toBe('no_match')
|
||||
expect(plan.no_source_refs).toBe(false)
|
||||
})
|
||||
|
||||
it('skips the diagnostic round-trip once anything matched', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })], sourceRefCount: 0 })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', ['A31.pdf', 'kvitto.pdf'], PERIOD_OPEN)
|
||||
|
||||
expect(plan.no_source_refs).toBe(false)
|
||||
})
|
||||
|
||||
it('counts a mixed batch correctly', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
const plan = await buildUnderlagPlan(supabase, 'company-1', [
|
||||
'A31_a.pdf',
|
||||
'A31_b.pdf',
|
||||
'A99.pdf',
|
||||
'kvitto.pdf',
|
||||
], PERIOD_OPEN)
|
||||
|
||||
expect(plan.summary).toEqual({
|
||||
total: 4,
|
||||
matched: 2,
|
||||
needs_confirmation: 0,
|
||||
ambiguous: 0,
|
||||
period_locked: 0,
|
||||
no_match: 1,
|
||||
unparsed: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('planPermitsAttach', () => {
|
||||
it('override permits an unresolvable filename onto any same-year target', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [] })
|
||||
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'kvitto ica.pdf', 'je-1', PERIOD_OPEN, true),
|
||||
).resolves.toBe(true)
|
||||
// A parsed ref with no candidate in the year is unresolvable too.
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'A99.pdf', 'je-1', PERIOD_OPEN, true),
|
||||
).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('override does NOT permit a resolvable filename onto a different target', async () => {
|
||||
// The hole this closes: a lying client could set override=true and scatter
|
||||
// cleanly-named underlag across arbitrary same-year verifikat.
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-other', PERIOD_OPEN, true),
|
||||
).resolves.toBe(false)
|
||||
// The target the filename actually points at stays permitted, of course.
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-1', PERIOD_OPEN, true),
|
||||
).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('accepts the entry the filename resolves to', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
await expect(planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-1', PERIOD_OPEN, false)).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('accepts any candidate of an ambiguous filename: the user picked one', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-a' }), makeVoucher({ id: 'je-b' })],
|
||||
})
|
||||
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-b', PERIOD_OPEN, false),
|
||||
).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a target in another fiscal year even when the ref matches', async () => {
|
||||
const supabase = makeSupabase({
|
||||
vouchers: [makeVoucher({ id: 'je-other-year', fiscal_period_id: PERIOD_LOCKED })],
|
||||
})
|
||||
|
||||
await expect(
|
||||
planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-other-year', PERIOD_OPEN, false),
|
||||
).resolves.toBe(false)
|
||||
})
|
||||
|
||||
it('refuses an entry the filename does not point at', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
await expect(planPermitsAttach(supabase, 'company-1', 'A31.pdf', 'je-other', PERIOD_OPEN, false)).resolves.toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses an unreadable filename outright', async () => {
|
||||
const supabase = makeSupabase({ vouchers: [makeVoucher({ id: 'je-1' })] })
|
||||
|
||||
await expect(planPermitsAttach(supabase, 'company-1', 'kvitto.pdf', 'je-1', PERIOD_OPEN, false)).resolves.toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* The unlinked-document predicate, and above all the mime allow-list, which is
|
||||
* the part that decides whether this surface is useful or actively harmful.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import {
|
||||
fetchUnlinkedDocuments,
|
||||
UNDERLAG_MIME_TYPES,
|
||||
UNLINKED_DOCUMENT_SCAN_CAP,
|
||||
} from '../unlinked-documents'
|
||||
|
||||
type Enqueue = (r: { data?: unknown; error?: unknown; count?: number | null }) => void
|
||||
|
||||
/** One empty result per referencing table, so nothing claims any candidate. */
|
||||
function enqueueNoReferences(enqueue: Enqueue) {
|
||||
for (let i = 0; i < 8; i += 1) enqueue({ data: [] })
|
||||
}
|
||||
|
||||
const doc = (id: string, overrides: Record<string, unknown> = {}) => ({
|
||||
id,
|
||||
file_name: `${id}.pdf`,
|
||||
mime_type: 'application/pdf',
|
||||
file_size_bytes: 1024,
|
||||
upload_source: 'api',
|
||||
created_at: '2026-08-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('UNDERLAG_MIME_TYPES', () => {
|
||||
it('excludes application/json, which on this surface is only the PSD2 archive', () => {
|
||||
// Measured on production 2026-08-27: of the document rows referenced by
|
||||
// nothing, application/json was 11 309 of 11 309 archived PSD2 bank-API
|
||||
// responses, and 0 of 4 495 pdf/png/jpeg/heic rows were. Those archives are
|
||||
// unlinked BY DESIGN. Admitting them here would hand an agent 11 309 items
|
||||
// of work it must not do, which is worse than showing nothing at all.
|
||||
expect(UNDERLAG_MIME_TYPES).not.toContain('application/json')
|
||||
})
|
||||
|
||||
it('is an allow-list, so a future machine payload format stays out by default', () => {
|
||||
// The alternative, excluding known-bad filenames, leaks every new archive
|
||||
// format until someone notices and adds another exclusion.
|
||||
for (const mime of UNDERLAG_MIME_TYPES) {
|
||||
expect(mime === 'application/pdf' || mime.startsWith('image/')).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchUnlinkedDocuments', () => {
|
||||
it('costs exactly one query when the company has no candidates', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
// Deliberately NOT enqueueing the eight reference lookups: if the early
|
||||
// return regressed, the mock would starve and this test would fail.
|
||||
|
||||
const result = await fetchUnlinkedDocuments(supabase as never, 'company-1')
|
||||
|
||||
expect(result).toEqual({ documents: [], count: 0, capped: false })
|
||||
})
|
||||
|
||||
it('returns candidates that no table references', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [doc('d-1'), doc('d-2')] })
|
||||
enqueueNoReferences(enqueue)
|
||||
|
||||
const result = await fetchUnlinkedDocuments(supabase as never, 'company-1')
|
||||
|
||||
expect(result.count).toBe(2)
|
||||
expect(result.documents.map((d) => d.id)).toEqual(['d-1', 'd-2'])
|
||||
expect(result.capped).toBe(false)
|
||||
})
|
||||
|
||||
it('drops a candidate claimed by any one of the eight referencing tables', async () => {
|
||||
// Walk the tables one at a time: a document claimed only by the Nth table
|
||||
// must still be excluded, which is what catches a missing entry in the list.
|
||||
for (let table = 0; table < 8; table += 1) {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [doc('d-claimed'), doc('d-free')] })
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
// Every referencing query selects its own column name, and the
|
||||
// implementation reads whichever key the row carries.
|
||||
enqueue({ data: i === table ? [{ document_id: 'd-claimed', document_attachment_id: 'd-claimed', xml_document_id: 'd-claimed', dokument_id: 'd-claimed', file_document_id: 'd-claimed' }] : [] })
|
||||
}
|
||||
|
||||
const result = await fetchUnlinkedDocuments(supabase as never, 'company-1')
|
||||
|
||||
expect(result.documents.map((d) => d.id), `table index ${table}`).toEqual(['d-free'])
|
||||
}
|
||||
})
|
||||
|
||||
it('reports capped when the candidate scan hits the limit', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const many = Array.from({ length: 3 }, (_, i) => doc(`d-${i}`))
|
||||
enqueue({ data: many })
|
||||
enqueueNoReferences(enqueue)
|
||||
|
||||
const result = await fetchUnlinkedDocuments(supabase as never, 'company-1', { limit: 3 })
|
||||
|
||||
// count is a floor, not a total, and the caller says so in its prose.
|
||||
expect(result.capped).toBe(true)
|
||||
expect(result.count).toBe(3)
|
||||
})
|
||||
|
||||
it('keeps the scan cap small enough that the eight .in() lookups stay valid URLs', () => {
|
||||
// Each candidate id is echoed back through eight .in(column, ids) queries,
|
||||
// and a UUID costs ~38 bytes in a PostgREST query string. Past a few
|
||||
// hundred the URL exceeds what the gateway accepts, the lookups fail, and
|
||||
// the "claims nothing" fallback turns every candidate into a false
|
||||
// positive. This is the constraint that sets the cap, not table size.
|
||||
const bytesPerLookup = UNLINKED_DOCUMENT_SCAN_CAP * 38
|
||||
expect(bytesPerLookup).toBeLessThan(16_000)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { uploadedFileBaseName } from '@/lib/documents/upload-file-name'
|
||||
|
||||
describe('uploadedFileBaseName', () => {
|
||||
it('returns a bare filename unchanged', () => {
|
||||
expect(uploadedFileBaseName('A31_8c2db060.pdf')).toBe('A31_8c2db060.pdf')
|
||||
})
|
||||
|
||||
it('strips the folder-relative path Chrome writes for a folder selection', () => {
|
||||
// Real shape from a Fortnox export: <year>/<month>/<type>/<file>.
|
||||
expect(
|
||||
uploadedFileBaseName(
|
||||
'2026/06/Leverantörsfakturor/A166_90493_62864442_Hetzner_2026-05-13_089000921156.pdf',
|
||||
),
|
||||
).toBe('A166_90493_62864442_Hetzner_2026-05-13_089000921156.pdf')
|
||||
})
|
||||
|
||||
it('strips Windows-style separators too', () => {
|
||||
expect(uploadedFileBaseName('2026\\01\\Verifikationer\\A17_kvitto.pdf')).toBe('A17_kvitto.pdf')
|
||||
})
|
||||
|
||||
it('keeps dots, spaces and Swedish characters inside the name', () => {
|
||||
expect(uploadedFileBaseName('2026/01/A17_Förhandsavi 2026 Årsavgift 734 314 922.pdf')).toBe(
|
||||
'A17_Förhandsavi 2026 Årsavgift 734 314 922.pdf',
|
||||
)
|
||||
expect(uploadedFileBaseName('A31.kvitto.v2.pdf')).toBe('A31.kvitto.v2.pdf')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest'
|
||||
import {
|
||||
HOSTED_MAX_UPLOAD_BYTES,
|
||||
HOSTED_REQUEST_BODY_LIMIT_BYTES,
|
||||
INBOX_MAX_UPLOAD_BYTES,
|
||||
exceedsHostedUploadLimit,
|
||||
exceedsInboxUploadLimit,
|
||||
formatMegabytes,
|
||||
inboxTooLargeMessage,
|
||||
isShrinkableImage,
|
||||
tooLargeMessage,
|
||||
} from '../upload-size'
|
||||
import { shrinkImageForUpload } from '../shrink-image'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('upload size limits', () => {
|
||||
it('stays under the platform ceiling so the multipart envelope fits', () => {
|
||||
expect(HOSTED_MAX_UPLOAD_BYTES).toBeLessThan(HOSTED_REQUEST_BODY_LIMIT_BYTES)
|
||||
})
|
||||
|
||||
it('flags a file over the limit on hosted', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', '')
|
||||
expect(exceedsHostedUploadLimit(HOSTED_MAX_UPLOAD_BYTES + 1)).toBe(true)
|
||||
expect(exceedsHostedUploadLimit(HOSTED_MAX_UPLOAD_BYTES)).toBe(false)
|
||||
})
|
||||
|
||||
// Docker self-hosting has no proxy in front of the app, so the route's own
|
||||
// MAX_FILE_SIZE governs and nothing should be refused or re-encoded here.
|
||||
it('never flags a file on self-hosted', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
|
||||
expect(exceedsHostedUploadLimit(50 * 1024 * 1024)).toBe(false)
|
||||
})
|
||||
|
||||
it('recognises the image types a canvas can re-encode', () => {
|
||||
expect(isShrinkableImage('image/jpeg')).toBe(true)
|
||||
expect(isShrinkableImage('image/HEIC')).toBe(true)
|
||||
expect(isShrinkableImage('application/pdf')).toBe(false)
|
||||
expect(isShrinkableImage('')).toBe(false)
|
||||
expect(isShrinkableImage(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('names both the actual size and the ceiling', () => {
|
||||
const message = tooLargeMessage(6 * 1024 * 1024)
|
||||
expect(message).toContain('6,0 MB')
|
||||
expect(message).toContain(formatMegabytes(HOSTED_MAX_UPLOAD_BYTES))
|
||||
})
|
||||
})
|
||||
|
||||
// The inbox ceiling is the route's own MAX_FILE_SIZE (10 MB), mirrored here
|
||||
// because core components cannot import from the extension. Files between
|
||||
// the hosted body limit and this one take the direct-to-storage path.
|
||||
describe('inbox upload ceiling', () => {
|
||||
it('sits above the hosted body limit and matches the route promise of 10 MB', () => {
|
||||
expect(INBOX_MAX_UPLOAD_BYTES).toBe(10 * 1024 * 1024)
|
||||
expect(INBOX_MAX_UPLOAD_BYTES).toBeGreaterThan(HOSTED_REQUEST_BODY_LIMIT_BYTES)
|
||||
})
|
||||
|
||||
it('applies on every deployment: self-hosted has the same route cap', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
|
||||
expect(exceedsInboxUploadLimit(INBOX_MAX_UPLOAD_BYTES + 1)).toBe(true)
|
||||
expect(exceedsInboxUploadLimit(INBOX_MAX_UPLOAD_BYTES)).toBe(false)
|
||||
})
|
||||
|
||||
it('names the actual size and the inbox ceiling, not the hosted one', () => {
|
||||
const message = inboxTooLargeMessage(12 * 1024 * 1024)
|
||||
expect(message).toContain('12,0 MB')
|
||||
expect(message).toContain(formatMegabytes(INBOX_MAX_UPLOAD_BYTES))
|
||||
expect(message).not.toContain(formatMegabytes(HOSTED_MAX_UPLOAD_BYTES))
|
||||
})
|
||||
})
|
||||
|
||||
describe('shrinkImageForUpload', () => {
|
||||
function fakeFile(size: number, type: string): File {
|
||||
return { size, type, name: 'kvitto.heic', lastModified: 0 } as File
|
||||
}
|
||||
|
||||
it('returns a file that already fits untouched', async () => {
|
||||
const file = fakeFile(1024, 'image/jpeg')
|
||||
expect(await shrinkImageForUpload(file)).toBe(file)
|
||||
})
|
||||
|
||||
it('returns a PDF untouched: there is nothing a canvas can do with it', async () => {
|
||||
const file = fakeFile(9 * 1024 * 1024, 'application/pdf')
|
||||
expect(await shrinkImageForUpload(file)).toBe(file)
|
||||
})
|
||||
|
||||
// No createImageBitmap outside a browser (and none for HEIC outside Safari):
|
||||
// the caller falls back to the size message rather than a silent failure.
|
||||
it('returns the original where the browser cannot decode it', async () => {
|
||||
const file = fakeFile(9 * 1024 * 1024, 'image/heic')
|
||||
expect(await shrinkImageForUpload(file)).toBe(file)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildVoucherIndex,
|
||||
candidatesForNumber,
|
||||
candidatesForRef,
|
||||
periodIdForDate,
|
||||
resolveDatedRef,
|
||||
sourceVoucherLabel,
|
||||
voucherLabel,
|
||||
type FiscalPeriodRow,
|
||||
type VoucherRow,
|
||||
} from '@/lib/documents/voucher-ref-resolver'
|
||||
|
||||
const PERIOD_2024 = 'period-2024'
|
||||
const PERIOD_2025 = 'period-2025'
|
||||
|
||||
const periods: FiscalPeriodRow[] = [
|
||||
{
|
||||
id: PERIOD_2024,
|
||||
period_start: '2024-01-01',
|
||||
period_end: '2024-12-31',
|
||||
is_closed: false,
|
||||
locked_at: null,
|
||||
},
|
||||
{
|
||||
id: PERIOD_2025,
|
||||
period_start: '2025-01-01',
|
||||
period_end: '2025-12-31',
|
||||
is_closed: false,
|
||||
locked_at: null,
|
||||
},
|
||||
]
|
||||
|
||||
function makeVoucher(overrides: Partial<VoucherRow> & Pick<VoucherRow, 'id'>): VoucherRow {
|
||||
return {
|
||||
fiscal_period_id: PERIOD_2024,
|
||||
entry_date: '2024-03-14',
|
||||
description: 'Import: A31',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 47,
|
||||
source_voucher_series: 'A',
|
||||
source_voucher_number: 31,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildVoucherIndex', () => {
|
||||
it('indexes an entry by both its period key and its source ref', () => {
|
||||
const index = buildVoucherIndex([makeVoucher({ id: 'je-1' })])
|
||||
|
||||
expect(index.byPeriodKey.get(`${PERIOD_2024}|A|31`)).toBe('je-1')
|
||||
expect(candidatesForRef(index, { series: 'A', number: 31 })).toHaveLength(1)
|
||||
expect(index.ambiguousPeriodKeys.size).toBe(0)
|
||||
})
|
||||
|
||||
it('skips entries with no source ref (non-SIE and pre-2026-04 imports)', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-1', source_voucher_series: null, source_voucher_number: null }),
|
||||
])
|
||||
|
||||
expect(index.byPeriodKey.size).toBe(0)
|
||||
expect(index.bySourceRef.size).toBe(0)
|
||||
expect(index.byNumber.size).toBe(0)
|
||||
})
|
||||
|
||||
it('drops BOTH entries when one source ref repeats inside a fiscal year', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-1' }),
|
||||
makeVoucher({ id: 'je-2' }),
|
||||
])
|
||||
|
||||
expect(index.byPeriodKey.has(`${PERIOD_2024}|A|31`)).toBe(false)
|
||||
expect(index.ambiguousPeriodKeys.has(`${PERIOD_2024}|A|31`)).toBe(true)
|
||||
// Both stay discoverable so a caller can present the choice.
|
||||
expect(candidatesForRef(index, { series: 'A', number: 31 })).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps a third repeat out of byPeriodKey once the key is ambiguous', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-1' }),
|
||||
makeVoucher({ id: 'je-2' }),
|
||||
makeVoucher({ id: 'je-3' }),
|
||||
])
|
||||
|
||||
expect(index.byPeriodKey.has(`${PERIOD_2024}|A|31`)).toBe(false)
|
||||
expect(candidatesForRef(index, { series: 'A', number: 31 })).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('keeps the same source ref in different fiscal years apart', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-2024' }),
|
||||
makeVoucher({ id: 'je-2025', fiscal_period_id: PERIOD_2025, entry_date: '2025-03-14' }),
|
||||
])
|
||||
|
||||
expect(index.byPeriodKey.get(`${PERIOD_2024}|A|31`)).toBe('je-2024')
|
||||
expect(index.byPeriodKey.get(`${PERIOD_2025}|A|31`)).toBe('je-2025')
|
||||
expect(candidatesForRef(index, { series: 'A', number: 31 })).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('matches series case-insensitively on both sides', () => {
|
||||
const index = buildVoucherIndex([makeVoucher({ id: 'je-1', source_voucher_series: 'a' })])
|
||||
|
||||
expect(candidatesForRef(index, { series: 'A', number: 31 })).toHaveLength(1)
|
||||
expect(index.byPeriodKey.get(`${PERIOD_2024}|A|31`)).toBe('je-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('candidatesForNumber', () => {
|
||||
it('finds a number across every series', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-a', source_voucher_series: 'A' }),
|
||||
makeVoucher({ id: 'je-b', source_voucher_series: 'B' }),
|
||||
])
|
||||
|
||||
expect(candidatesForNumber(index, 31).map((v) => v.id)).toEqual(['je-a', 'je-b'])
|
||||
expect(candidatesForNumber(index, 999)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('periodIdForDate', () => {
|
||||
it('finds the period containing the date, inclusive of both bounds', () => {
|
||||
expect(periodIdForDate(periods, '2024-01-01')).toBe(PERIOD_2024)
|
||||
expect(periodIdForDate(periods, '2024-12-31')).toBe(PERIOD_2024)
|
||||
expect(periodIdForDate(periods, '2025-06-01')).toBe(PERIOD_2025)
|
||||
expect(periodIdForDate(periods, '2023-06-01')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveDatedRef', () => {
|
||||
const index = buildVoucherIndex([
|
||||
makeVoucher({ id: 'je-2024' }),
|
||||
makeVoucher({ id: 'je-2025', fiscal_period_id: PERIOD_2025, entry_date: '2025-03-14' }),
|
||||
])
|
||||
|
||||
it('resolves via the fiscal period the attachment date falls in', () => {
|
||||
expect(resolveDatedRef(index, periods, { series: 'A', number: 31, date: '2024-05-02' })).toBe(
|
||||
'je-2024',
|
||||
)
|
||||
expect(resolveDatedRef(index, periods, { series: 'A', number: 31, date: '2025-05-02' })).toBe(
|
||||
'je-2025',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns undefined when the date falls outside every known period', () => {
|
||||
expect(
|
||||
resolveDatedRef(index, periods, { series: 'A', number: 31, date: '2023-05-02' }),
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('resolves a financial-year window when exactly one entry falls inside it', () => {
|
||||
expect(
|
||||
resolveDatedRef(index, periods, {
|
||||
series: 'A',
|
||||
number: 31,
|
||||
date: '2024-01-01',
|
||||
dateTo: '2024-12-31',
|
||||
}),
|
||||
).toBe('je-2024')
|
||||
})
|
||||
|
||||
it('refuses a financial-year window that spans two candidates', () => {
|
||||
expect(
|
||||
resolveDatedRef(index, periods, {
|
||||
series: 'A',
|
||||
number: 31,
|
||||
date: '2024-01-01',
|
||||
dateTo: '2025-12-31',
|
||||
}),
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns undefined for an ambiguous key rather than picking one', () => {
|
||||
const ambiguous = buildVoucherIndex([makeVoucher({ id: 'je-1' }), makeVoucher({ id: 'je-2' })])
|
||||
|
||||
expect(
|
||||
resolveDatedRef(ambiguous, periods, { series: 'A', number: 31, date: '2024-05-02' }),
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('labels', () => {
|
||||
it('separates our voucher label from the source label', () => {
|
||||
const entry = makeVoucher({ id: 'je-1' })
|
||||
|
||||
expect(voucherLabel(entry)).toBe('A47')
|
||||
expect(sourceVoucherLabel(entry)).toBe('A31')
|
||||
})
|
||||
|
||||
it('returns null when a label is not fully populated', () => {
|
||||
expect(voucherLabel({ voucher_series: 'A', voucher_number: null })).toBeNull()
|
||||
expect(sourceVoucherLabel({ source_voucher_series: null, source_voucher_number: 31 })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Render the verified human answers captured on a chat-sourced inbox item
|
||||
* (invoice_inbox_items.channel_context, written by the WhatsApp intake bot)
|
||||
* as ONE compact Swedish line for the booking notes path.
|
||||
*
|
||||
* The rendered string travels through the existing `notes` parameters
|
||||
* (book-direct, convert, bulk-book via categorize-core) and ends up appended
|
||||
* to the verifikat description, which caps at 500 chars in
|
||||
* lib/bookkeeping/transaction-entries.ts. This renderer therefore stays well
|
||||
* under that: at most CHANNEL_CONTEXT_NOTES_MAX chars, truncating the
|
||||
* participant list by WHOLE names ("… och 3 till"), never mid-name.
|
||||
*
|
||||
* Precedence: representation answers first (Skatteverket's dokumentationskrav
|
||||
* for representation: deltagare + syfte belong on the verifikat), then the
|
||||
* sender's explicit note. Both are answers a human typed to a question the bot
|
||||
* asked, having been told they reach the bookkeeping. The photo caption is the
|
||||
* weakest signal: nobody was asked for it and nobody reviewed it, so it is
|
||||
* OFF by default and only renders where a human sees the result before it is
|
||||
* posted (see ChannelContextNotesOptions.includeCaption).
|
||||
*
|
||||
* Core lib: must not import from @/extensions. Deliberately Swedish-only
|
||||
* output: the verifikat description is a regulatory surface (see
|
||||
* .claude/rules/i18n.md), not UI chrome.
|
||||
*/
|
||||
import type { InboxChannelContext } from '@/types'
|
||||
|
||||
/**
|
||||
* Cap on the rendered line. 220 leaves the description's 500-char cap plenty
|
||||
* of room for the bank text / supplier prefix it is appended to.
|
||||
*/
|
||||
export const CHANNEL_CONTEXT_NOTES_MAX = 220
|
||||
|
||||
/** "Anna Berg (Volvo)" with a company, bare "Jakob W" without (the sender
|
||||
* themselves usually answers without naming their own company). */
|
||||
export function renderChannelParticipant(p: {
|
||||
name: string
|
||||
company: string | null
|
||||
}): string {
|
||||
const name = (p.name ?? '').trim()
|
||||
if (!name) return ''
|
||||
const company = (p.company ?? '').trim()
|
||||
return company ? `${name} (${company})` : name
|
||||
}
|
||||
|
||||
function buildLine(
|
||||
names: string[],
|
||||
droppedCount: number,
|
||||
purpose: string | null,
|
||||
userNote: string | null,
|
||||
): string {
|
||||
const parts: string[] = []
|
||||
if (names.length > 0) {
|
||||
const suffix = droppedCount > 0 ? ` … och ${droppedCount} till` : ''
|
||||
parts.push(`Representation: ${names.join(', ')}${suffix}`)
|
||||
}
|
||||
if (purpose) parts.push(`Syfte: ${purpose}`)
|
||||
if (userNote) parts.push(userNote)
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** Last-resort cap for free text (purpose/note/caption): the whole-name rule
|
||||
* above governs the participant list; a runaway free-text field is cut with
|
||||
* an ellipsis instead. Result is always <= CHANNEL_CONTEXT_NOTES_MAX. */
|
||||
function capFreeText(line: string): string {
|
||||
if (line.length <= CHANNEL_CONTEXT_NOTES_MAX) return line
|
||||
return `${line.slice(0, CHANNEL_CONTEXT_NOTES_MAX - 1).trimEnd()}…`
|
||||
}
|
||||
|
||||
export interface ChannelContextNotesOptions {
|
||||
/**
|
||||
* Render the raw photo caption when there is neither a representation
|
||||
* answer nor a sender note. Default false.
|
||||
*
|
||||
* Off by default on purpose. The representation answer and the note are
|
||||
* replies to a question the bot asked, so the sender knew they were writing
|
||||
* bookkeeping text; the caption is whatever happened to be typed next to a
|
||||
* photo and nobody reviewed it. Every unattended path (bulk-book, the
|
||||
* server-side note defaults used by MCP and API callers) writes straight
|
||||
* into a posted verifikat, which BFL 5 kap 5 § only lets you change through
|
||||
* a formal rättelse. Pass true only where a human sees the string and can
|
||||
* edit or delete it before booking: today that is the Bokför direkt dialog
|
||||
* prefill.
|
||||
*/
|
||||
includeCaption?: boolean
|
||||
}
|
||||
|
||||
export function renderChannelContextNotes(
|
||||
ctx: InboxChannelContext | null | undefined,
|
||||
options: ChannelContextNotesOptions = {},
|
||||
): string | null {
|
||||
if (!ctx) return null
|
||||
|
||||
const names = (ctx.representation?.participants ?? [])
|
||||
.map(renderChannelParticipant)
|
||||
.filter((n) => n.length > 0)
|
||||
const purpose = ctx.representation?.purpose?.trim() || null
|
||||
const userNote = ctx.user_note?.trim() || null
|
||||
const caption = options.includeCaption ? ctx.caption?.trim() || null : null
|
||||
|
||||
// Caption (when allowed) only if there is neither a representation answer
|
||||
// nor a note.
|
||||
if (names.length === 0 && !purpose && !userNote) {
|
||||
return caption ? capFreeText(caption) : null
|
||||
}
|
||||
|
||||
// Full participant list first; drop whole names from the end until the
|
||||
// line fits. Keeps at least one name so the representation trail never
|
||||
// degrades to a bare count.
|
||||
let keep = names.length
|
||||
for (;;) {
|
||||
const line = buildLine(names.slice(0, keep), names.length - keep, purpose, userNote)
|
||||
if (line.length <= CHANNEL_CONTEXT_NOTES_MAX) return line
|
||||
if (keep > 1) {
|
||||
keep--
|
||||
continue
|
||||
}
|
||||
return capFreeText(line)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* Core Receipt Matcher: pure matching utility functions extracted from the
|
||||
* receipt-ocr extension so they can be reused by the document matching engine.
|
||||
*
|
||||
* These are pure functions with no Supabase or extension dependencies.
|
||||
*/
|
||||
|
||||
// Matching configuration (re-exported for consumers)
|
||||
/**
|
||||
* How far a receipt's date may sit from the bank's before the date stops
|
||||
* counting as agreement.
|
||||
*
|
||||
* Ten days, not three. A card purchase settles days after it happens, an
|
||||
* international one routinely a week later, and a forwarded receipt carries
|
||||
* the date of the purchase while the statement carries the date of the
|
||||
* posting. At three days the signal scored zero for ordinary, correct pairs
|
||||
* and took a quarter of the weight down with it: a receipt matching to within
|
||||
* 1% from a merchant the matcher recognised still capped at 0.62, under every
|
||||
* threshold that decides anything.
|
||||
*
|
||||
* The date remains real evidence at this width. A receipt from March still
|
||||
* disagrees with a purchase in September.
|
||||
*/
|
||||
export const DATE_TOLERANCE_DAYS = 10
|
||||
export const AMOUNT_TOLERANCE_PERCENT = 0.05
|
||||
|
||||
/**
|
||||
* Tolerance for a total that had to be converted into kronor first.
|
||||
*
|
||||
* A same-currency comparison is two readings of one number, so 5% is generous.
|
||||
* A converted one carries a second, known error: Riksbanken publishes a mid
|
||||
* rate and a card issuer charges its own, typically a point or two away, on a
|
||||
* settlement day that need not be the receipt's. Holding both to the same bar
|
||||
* treats a rate spread as if it were a disagreement about the sum. Measured
|
||||
* against real statements, the spread ran 1.2% to 3%.
|
||||
*/
|
||||
export const CONVERTED_AMOUNT_TOLERANCE_PERCENT = 0.09
|
||||
|
||||
/**
|
||||
* Flat discount on a confidence scored from a prominentAmounts fallback
|
||||
* (bankintyg, avtal, contracts: no invoice-style total). Such an amount is one
|
||||
* of possibly several figures printed on the document rather than "what the
|
||||
* buyer pays", so an agreement is real evidence but must stay weaker than a
|
||||
* total agreeing.
|
||||
*
|
||||
* A discount FACTOR, deliberately not a reduced amount weight inside
|
||||
* calculateMatchConfidence: the confidence is normalised over the included
|
||||
* weights, so shrinking the amount weight both let a date+amount-only fallback
|
||||
* reach 1.0 ((0.25+0.3)/0.55) and, when the amount DISAGREED, shrank the
|
||||
* penalty so a wrong fallback amount outscored a wrong invoice total
|
||||
* (0.67 vs 0.60). Scoring at full weight and discounting the result keeps
|
||||
* agreement capped below certainty and disagreement at least as damning as it
|
||||
* is for a real total.
|
||||
*/
|
||||
export const FALLBACK_CONFIDENCE_FACTOR = 0.85
|
||||
|
||||
/**
|
||||
* Normalize a merchant name for comparison.
|
||||
* Removes special characters, Swedish company suffixes, and extra whitespace.
|
||||
*
|
||||
* FROZEN. This is not merely a helper: `normalizeCounterpartyName`
|
||||
* (lib/bookkeeping/counterparty-templates.ts) ends in this function, and its
|
||||
* output is PERSISTED as `categorization_templates.counterparty_name` under
|
||||
* UNIQUE (company_id, counterparty_name), with a hand-written SQL mirror
|
||||
* `public.normalize_counterparty_key()` that the ledger-context RPC recomputes
|
||||
* at query time. Change this and stored keys stop equalling computed ones: the
|
||||
* konteringskarta join misses, learned vat_treatment degrades to history, and
|
||||
* `insertOrUpdateTemplate` silently inserts a SECOND row per merchant, orphaning
|
||||
* the occurrence counts instead of migrating them.
|
||||
*
|
||||
* To improve MATCHING, edit `normalizeForMatch` below, which nothing persists.
|
||||
* To improve the canonical KEY, it is a three-part atomic change: this function
|
||||
* + CREATE OR REPLACE of the SQL mirror + a backfill/merge migration over
|
||||
* categorization_templates, with tests/pg/ledger-usage-stats-rpc.pg.test.ts
|
||||
* extended in the same commit.
|
||||
*/
|
||||
export function normalizeMerchantName(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^\w\såäöé]/g, '') // Remove special chars except Swedish letters
|
||||
.replace(/\b(ab|hb|kb|ek|för|stiftelse)\b/g, '') // Remove company suffixes
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Legal-form tokens that carry no identity. Deliberately wider than the frozen
|
||||
* key normalizer's list: a receipt says "Adobe Systems Software Ireland Ltd"
|
||||
* where the bank says "Adobe", and only the matcher needs to see through that.
|
||||
*/
|
||||
const LEGAL_FORM_TOKENS =
|
||||
/\b(ab|hb|kb|ek|för|stiftelse|inc|llc|ltd|limited|gmbh|oy|oyj|ap|aps|pbc|plc|sarl|bv|nv|corp|corporation|company|filial|int|international)\b/g
|
||||
|
||||
/**
|
||||
* Noise the Swedish card rails staple onto a merchant, observed in production:
|
||||
* `Ryde Sweden AB K8066 Kortköp/uttag`, `Kortköp 260612 Prime Video-*NL5EK5W`,
|
||||
* `ELGIGANTEN S/25-07-14`, `Qstar Lilla Edet 6531 K8781 Kortköp/uttag`.
|
||||
*/
|
||||
const CARD_TOKEN = /\bk\d{4}\b/g
|
||||
const CARD_VERB = /\bkort(kop|kop\/uttag)?\b|\buttag\b/g
|
||||
/**
|
||||
* Swedish words a bank statement puts around a merchant name that are not part
|
||||
* of it. "Utlägg Norwegian" is an expense reimbursement for a Norwegian
|
||||
* ticket, not a company called Utlägg: leaving the word in cost the pair its
|
||||
* token-subset match and dropped merchant similarity to 0.18, which was enough
|
||||
* to keep an exact 1 998 kr match from ever being proposed.
|
||||
*/
|
||||
const PAYMENT_NOISE = /\butl[aä]gg\b|\b[oö]verf[oö]ring\b|\bvia internet\b|\bbg-?bet\b|\bautogiro\b/g
|
||||
const CARD_DATE_PREFIX = /^\s*kortkop\s+\d{6}\s*/
|
||||
const TRAILING_DATE = /\s*\/?\s*\d{2}-\d{2}-\d{2}\s*$/
|
||||
/**
|
||||
* Reference numbers, which banks glue straight onto the name
|
||||
* ("GOOGLE ADS8047863617"), so this deliberately has no word boundary. Runs of
|
||||
* three digits or fewer stay: they are often part of the identity
|
||||
* ("Rusta Lindingö 135", "7-Eleven").
|
||||
*/
|
||||
const LONG_DIGIT_RUN = /\d{4,}/g
|
||||
const DOMAIN_TAIL = /\.(com|se|io|ai|co|net|org|nu|dk|no|fi|de|uk)\b/g
|
||||
|
||||
/**
|
||||
* Fold a merchant string down to the part that actually identifies it, for
|
||||
* SIMILARITY ONLY. Nothing persists this, so it can be aggressive where the
|
||||
* frozen key normalizer must not be.
|
||||
*
|
||||
* Aggressive folding is safe here precisely because it is applied to BOTH sides
|
||||
* of every comparison: an over-eager fold that turns "Boeing" into "boing" does
|
||||
* so for the receipt and the bank row alike, so the pair still matches. The only
|
||||
* real risk is two genuinely different merchants colliding, which the amount and
|
||||
* date signals then have to disagree with.
|
||||
*/
|
||||
export function normalizeForMatch(name: string): string {
|
||||
let s = name.toLowerCase()
|
||||
|
||||
// Banks disagree about diacritics: one writes "kött", another transliterates
|
||||
// to "koett", a third mangles the encoding into "LINDING??". Fold all three
|
||||
// to the same base letters so they stop being three different merchants.
|
||||
s = s.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||||
s = s.replace(/\?{2,}|�/g, ' ')
|
||||
s = s.replace(/oe/g, 'o').replace(/ae/g, 'a').replace(/aa/g, 'a')
|
||||
|
||||
// A processor marker hides the merchant on one side or the other:
|
||||
// GOOGLE*PLAY puts it first, K*IKEA GALLE puts it second. Keep both.
|
||||
s = s.replace(/[*_]+/g, ' ')
|
||||
|
||||
s = s.replace(CARD_DATE_PREFIX, ' ')
|
||||
s = s.replace(TRAILING_DATE, ' ')
|
||||
s = s.replace(CARD_TOKEN, ' ')
|
||||
s = s.replace(CARD_VERB, ' ')
|
||||
s = s.replace(PAYMENT_NOISE, ' ')
|
||||
s = s.replace(DOMAIN_TAIL, ' ')
|
||||
s = s.replace(/\bwww\b/g, ' ')
|
||||
|
||||
// Punctuation to space rather than nothing, so "Word,and" stays two tokens.
|
||||
s = s.replace(/[^\w\s]/g, ' ')
|
||||
s = s.replace(LONG_DIGIT_RUN, ' ')
|
||||
s = s.replace(LEGAL_FORM_TOKENS, ' ')
|
||||
|
||||
return s.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Levenshtein (edit) distance between two strings.
|
||||
*/
|
||||
export function levenshteinDistance(str1: string, str2: string): number {
|
||||
const m = str1.length
|
||||
const n = str2.length
|
||||
|
||||
const dp: number[][] = Array(m + 1)
|
||||
.fill(null)
|
||||
.map(() => Array(n + 1).fill(0))
|
||||
|
||||
for (let i = 0; i <= m; i++) dp[i][0] = i
|
||||
for (let j = 0; j <= n; j++) dp[0][j] = j
|
||||
|
||||
for (let i = 1; i <= m; i++) {
|
||||
for (let j = 1; j <= n; j++) {
|
||||
const cost = str1[i - 1] === str2[j - 1] ? 0 : 1
|
||||
dp[i][j] = Math.min(
|
||||
dp[i - 1][j] + 1, // deletion
|
||||
dp[i][j - 1] + 1, // insertion
|
||||
dp[i - 1][j - 1] + cost // substitution
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return dp[m][n]
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate merchant name similarity using Levenshtein distance and word overlap.
|
||||
* Returns a value between 0 (no match) and 1 (exact match).
|
||||
*/
|
||||
export function calculateMerchantSimilarity(name1: string, name2: string): number {
|
||||
if (!name1 || !name2) return 0
|
||||
|
||||
// Matching-only folding: sees through card tokens, processor stars,
|
||||
// transliterated diacritics and legal forms, none of which change identity.
|
||||
const n1 = normalizeForMatch(name1)
|
||||
const n2 = normalizeForMatch(name2)
|
||||
if (!n1 || !n2) return 0
|
||||
|
||||
// Exact match
|
||||
if (n1 === n2) return 1
|
||||
|
||||
// One contains the other. Also covers the bank's fixed-width truncation
|
||||
// ("apple com bi" inside "apple com bill"), which is a prefix by nature.
|
||||
if (n1.includes(n2) || n2.includes(n1)) return 0.9
|
||||
|
||||
const words1 = n1.split(/\s+/).filter(Boolean)
|
||||
const words2 = n2.split(/\s+/).filter(Boolean)
|
||||
const set1 = new Set(words1)
|
||||
const set2 = new Set(words2)
|
||||
const commonWords = words1.filter((w) => set2.has(w))
|
||||
|
||||
// Every token of the shorter name appears in the longer one: "Adobe" against
|
||||
// "Adobe Systems Software Ireland", or a receipt's legal name against the
|
||||
// bank's trading name. Scored level with substring containment because it is
|
||||
// the same claim, made token-wise instead of character-wise.
|
||||
const smaller = set1.size <= set2.size ? set1 : set2
|
||||
const larger = smaller === set1 ? set2 : set1
|
||||
if (smaller.size > 0 && [...smaller].every((w) => larger.has(w))) return 0.9
|
||||
|
||||
// Word overlap
|
||||
if (commonWords.length > 0) {
|
||||
const overlapScore = commonWords.length / Math.max(words1.length, words2.length)
|
||||
if (overlapScore >= 0.5) return 0.7 + overlapScore * 0.2
|
||||
}
|
||||
|
||||
// Levenshtein similarity
|
||||
const distance = levenshteinDistance(n1, n2)
|
||||
const maxLength = Math.max(n1.length, n2.length)
|
||||
return 1 - distance / maxLength
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the relative amount variance between a bank transaction and an
|
||||
* underlag (receipt/invoice) total, currency-aware. Feeds the `amountVariance`
|
||||
* argument of calculateMatchConfidence.
|
||||
*
|
||||
* Returns `null` when the amounts cannot be compared: either there is no
|
||||
* underlag total, or the two are in different currencies and the underlag has
|
||||
* no SEK value (no FX rate). A null result is the signal for
|
||||
* calculateMatchConfidence to drop the amount weight entirely instead of
|
||||
* comparing raw magnitudes across currencies: that cross-currency raw compare
|
||||
* is exactly what made a 750 EUR receipt falsely match a 750 SEK transaction.
|
||||
*
|
||||
* Magnitudes are compared (Math.abs) because a bank expense row is negative
|
||||
* while an underlag total is positive.
|
||||
*
|
||||
* @param receiptTotal underlag total in its own currency (sign-agnostic)
|
||||
* @param receiptCurrency underlag currency, e.g. 'EUR'
|
||||
* @param receiptSek underlag total converted to SEK, or null if unknown
|
||||
* @param txAmount transaction amount in its own currency (sign-agnostic)
|
||||
* @param txCurrency transaction currency, e.g. 'SEK'
|
||||
* @param txSek transaction amount in SEK (equals txAmount for SEK rows)
|
||||
*/
|
||||
export function amountVarianceForMatch(
|
||||
receiptTotal: number | null,
|
||||
receiptCurrency: string,
|
||||
receiptSek: number | null,
|
||||
txAmount: number,
|
||||
txCurrency: string,
|
||||
txSek: number,
|
||||
): number | null {
|
||||
if (receiptTotal == null) return null
|
||||
const absTotal = Math.abs(receiptTotal)
|
||||
if (absTotal === 0) return null
|
||||
|
||||
// Same currency → compare raw magnitudes (most reliable, needs no rate).
|
||||
if (txCurrency.toUpperCase() === receiptCurrency.toUpperCase()) {
|
||||
return Math.abs(Math.abs(txAmount) - absTotal) / absTotal
|
||||
}
|
||||
|
||||
// Different currencies → compare in SEK, but only with an SEK value for both.
|
||||
if (receiptSek != null && Math.abs(receiptSek) > 0) {
|
||||
return Math.abs(Math.abs(txSek) - Math.abs(receiptSek)) / Math.abs(receiptSek)
|
||||
}
|
||||
|
||||
// Cross-currency with no rate → not comparable.
|
||||
return null
|
||||
}
|
||||
|
||||
export interface ProminentAmountMatch {
|
||||
variance: number
|
||||
/** The printed amount that produced the variance. */
|
||||
amount: number
|
||||
/** The document's own label for it ("Insatt belopp", "Engångspris"). */
|
||||
label: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback amount variance for documents with no invoice-style total but one
|
||||
* or more prominent amounts (bankintyg "Insatt belopp", an agreement's
|
||||
* "Engångspris", ...). Tries each amount against the transaction and returns
|
||||
* the smallest variance, or null when none is comparable.
|
||||
*
|
||||
* Same-currency only by construction: prominent amounts never carry a resolved
|
||||
* SEK value, so a cross-currency pair stays incomparable (receiptSek = null in
|
||||
* amountVarianceForMatch) exactly like a cross-currency total without a rate.
|
||||
* Returns the closest amount with its variance and the document's own label.
|
||||
*
|
||||
* Callers must multiply the resulting confidence by
|
||||
* FALLBACK_CONFIDENCE_FACTOR (see its comment for why a factor, not a weight),
|
||||
* and should surface WHICH amount matched: a bare "Exakt belopp" with no
|
||||
* number attached is certainty the reader cannot check.
|
||||
*/
|
||||
export function bestProminentAmountVariance(
|
||||
amounts: readonly { amount: number; label: string | null }[],
|
||||
receiptCurrency: string,
|
||||
txAmount: number,
|
||||
txCurrency: string,
|
||||
txSek: number,
|
||||
): ProminentAmountMatch | null {
|
||||
let best: ProminentAmountMatch | null = null
|
||||
for (const candidate of amounts) {
|
||||
if (!Number.isFinite(candidate.amount)) continue
|
||||
const variance = amountVarianceForMatch(
|
||||
candidate.amount,
|
||||
receiptCurrency,
|
||||
null,
|
||||
txAmount,
|
||||
txCurrency,
|
||||
txSek,
|
||||
)
|
||||
if (variance != null && (best == null || variance < best.variance)) {
|
||||
best = { variance, amount: candidate.amount, label: candidate.label }
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a weighted match confidence score from date, amount, and merchant signals.
|
||||
* Weights: amount 40%, merchant 35%, date 25%.
|
||||
*
|
||||
* When merchant similarity is 0, the merchant weight is excluded from the
|
||||
* total weight so the confidence is normalized across the active signals only.
|
||||
*
|
||||
* `amountVariance` may be `null` when the candidate and the underlag are in
|
||||
* different currencies and no FX rate was available to normalise them. In that
|
||||
* case the amount signal is dropped entirely (same treatment as a missing
|
||||
* merchant) rather than comparing raw magnitudes across currencies: that is
|
||||
* what made a 750 EUR receipt falsely match a 750 SEK transaction.
|
||||
*/
|
||||
export function calculateMatchConfidence(
|
||||
dateVariance: number,
|
||||
amountVariance: number | null,
|
||||
merchantSimilarity: number,
|
||||
dateTolerance: number = DATE_TOLERANCE_DAYS,
|
||||
amountTolerance: number = AMOUNT_TOLERANCE_PERCENT
|
||||
): { confidence: number; matchReasons: string[] } {
|
||||
const matchReasons: string[] = []
|
||||
let totalWeight = 0
|
||||
let weightedScore = 0
|
||||
|
||||
// Date score (weight: 25%)
|
||||
const dateScore = Math.max(0, 1 - dateVariance / dateTolerance)
|
||||
if (dateScore >= 0.8) {
|
||||
matchReasons.push(dateVariance === 0 ? 'Exakt datum' : `Datum ±${Math.round(dateVariance)} dagar`)
|
||||
}
|
||||
weightedScore += dateScore * 0.25
|
||||
totalWeight += 0.25
|
||||
|
||||
// Amount score (weight: 40%): only counted when the amounts are comparable
|
||||
// (same currency, or both normalisable to SEK).
|
||||
if (amountVariance != null) {
|
||||
const amountScore = Math.max(0, 1 - amountVariance / amountTolerance)
|
||||
if (amountVariance < 0.01) {
|
||||
matchReasons.push('Exakt belopp')
|
||||
} else if (amountVariance < amountTolerance) {
|
||||
matchReasons.push(`Belopp ±${Math.round(amountVariance * 100)}%`)
|
||||
}
|
||||
weightedScore += amountScore * 0.4
|
||||
totalWeight += 0.4
|
||||
}
|
||||
|
||||
// Merchant score (weight: 35%): only counted when there's data
|
||||
if (merchantSimilarity > 0) {
|
||||
if (merchantSimilarity >= 0.9) {
|
||||
matchReasons.push('Handlare matchar')
|
||||
} else if (merchantSimilarity >= 0.6) {
|
||||
matchReasons.push('Trolig handlarmatch')
|
||||
}
|
||||
weightedScore += merchantSimilarity * 0.35
|
||||
totalWeight += 0.35
|
||||
}
|
||||
|
||||
const confidence = totalWeight > 0 ? weightedScore / totalWeight : 0
|
||||
|
||||
return {
|
||||
confidence: Math.round(confidence * 100) / 100,
|
||||
matchReasons,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Direct-to-storage upload for the document inbox (issue #1551).
|
||||
*
|
||||
* The platform rejects a request body over 4.5 MB before the route runs
|
||||
* (see upload-size.ts), and a PDF cannot be shrunk the way a photo can. This
|
||||
* path keeps the bytes out of the function body altogether:
|
||||
*
|
||||
* 1. POST /upload/create mints a short-lived signed Storage URL
|
||||
* 2. PUT <upload_url> the browser sends the bytes straight to Storage
|
||||
* 3. POST /upload/complete the server reads the object back out of Storage,
|
||||
* hashes it, archives it and runs the normal
|
||||
* inbox pipeline (extraction, inbox row)
|
||||
*
|
||||
* The hash is computed server-side from the stored object in step 3; nothing
|
||||
* the browser says about the content is trusted. The URL from step 1 is the
|
||||
* raw Storage URL on purpose: the same-origin /api/storage proxy the MCP
|
||||
* tools use buffers the body inside a function and would hit the same
|
||||
* ceiling.
|
||||
*
|
||||
* Resolves to the Response that ended the sequence: the /upload/complete
|
||||
* response on success (the same `{ data }` shape as the multipart /upload),
|
||||
* or the first failing step's response, so callers keep their existing
|
||||
* `if (!res.ok)` handling. A Storage rejection in step 2 is surfaced as a
|
||||
* synthesized error envelope carrying Storage's status, and step 3 is never
|
||||
* attempted after it: an abandoned reservation leaves no document row (the
|
||||
* pending object is swept on a later create).
|
||||
*/
|
||||
|
||||
const INBOX_ROUTE_BASE = '/api/extensions/ext/invoice-inbox'
|
||||
export const INBOX_UPLOAD_CREATE_URL = `${INBOX_ROUTE_BASE}/upload/create`
|
||||
export const INBOX_UPLOAD_COMPLETE_URL = `${INBOX_ROUTE_BASE}/upload/complete`
|
||||
|
||||
export interface DirectUploadOptions {
|
||||
/** Pre-match the new inbox item to a bank transaction (same as /upload). */
|
||||
matchedTransactionId?: string | null
|
||||
/** Bring-your-own-extraction opt-out (same as /upload's skip_extraction). */
|
||||
skipExtraction?: boolean
|
||||
/** Injectable for tests; defaults to the global fetch. */
|
||||
fetchImpl?: typeof fetch
|
||||
}
|
||||
|
||||
interface SignedUploadReservation {
|
||||
upload_id: string
|
||||
upload_url: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage answered the PUT with a failure. Wrapped in the standard envelope
|
||||
* so getResponseErrorMessage() reads it like any route failure. Never a
|
||||
* session-expiry false positive: notifySessionExpired keys on a header only
|
||||
* the app's own 401 carries.
|
||||
*/
|
||||
function storageRejectedResponse(status: number): Response {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
code: 'INBOX_UPLOAD_STORAGE_REJECTED',
|
||||
message: `Lagringstjänsten tog inte emot filen (HTTP ${status}). Försök igen.`,
|
||||
message_en: `The storage service did not accept the file (HTTP ${status}). Try again.`,
|
||||
},
|
||||
}),
|
||||
{ status, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function uploadViaSignedUrl(
|
||||
file: File,
|
||||
options: DirectUploadOptions = {},
|
||||
): Promise<Response> {
|
||||
// Wrapped rather than referenced: a detached `fetch` loses its receiver.
|
||||
const fetchImpl: typeof fetch = options.fetchImpl ?? ((input, init) => fetch(input, init))
|
||||
|
||||
const createRes = await fetchImpl(INBOX_UPLOAD_CREATE_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
file_name: file.name,
|
||||
mime_type: file.type,
|
||||
size_bytes: file.size,
|
||||
}),
|
||||
})
|
||||
if (!createRes.ok) return createRes
|
||||
|
||||
const created = (await createRes.json()) as { data?: Partial<SignedUploadReservation> }
|
||||
const reservation = created.data
|
||||
if (!reservation?.upload_id || !reservation.upload_url) {
|
||||
throw new Error('Signed upload reservation is missing upload_id or upload_url')
|
||||
}
|
||||
|
||||
const put = await fetchImpl(reservation.upload_url, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': file.type, 'x-upsert': 'false' },
|
||||
body: file,
|
||||
})
|
||||
if (!put.ok) return storageRejectedResponse(put.status)
|
||||
|
||||
return fetchImpl(INBOX_UPLOAD_COMPLETE_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
upload_id: reservation.upload_id,
|
||||
file_name: file.name,
|
||||
mime_type: file.type,
|
||||
matched_transaction_id: options.matchedTransactionId ?? null,
|
||||
skip_extraction: options.skipExtraction === true,
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Read a source-system voucher reference out of an underlag filename.
|
||||
*
|
||||
* Systems that export receipts alongside a SIE file name each file after the
|
||||
* verifikat it belongs to: SpeedLedger writes `A31_<internal-uuid>.pdf`, Fortnox
|
||||
* `V123.pdf`, others `2024-A-31 kvitto.pdf`. That prefix is a deterministic
|
||||
* pointer into the ledger, which is why underlag import does not need to read
|
||||
* the document at all: no AI, no amount matching, no date windows.
|
||||
*
|
||||
* Design rule: an unrecognised name returns null. A wrong parse attaches
|
||||
* räkenskapsinformation to the wrong verifikat, and that cannot be undone
|
||||
* (BFL 7 kap), so the cost of guessing is far higher than the cost of asking.
|
||||
*/
|
||||
|
||||
export type VoucherRefPattern =
|
||||
/** `A31`, `A31_uuid`, `A-31 kvitto`, `2024_A31`, `ver A31` */
|
||||
| 'series_number'
|
||||
/** `31`, `31_kvitto`: a number with no series at all. */
|
||||
| 'number_only'
|
||||
|
||||
export interface ParsedFileNameRef {
|
||||
/** Null when the filename carried a number but no series. */
|
||||
series: string | null
|
||||
number: number
|
||||
pattern: VoucherRefPattern
|
||||
/**
|
||||
* Whether this parse may be pre-selected in a bulk plan. Three classes are
|
||||
* never auto-selectable, even on a single-candidate hit:
|
||||
* - series-less parses (`31.pdf` can point at any series);
|
||||
* - refs on the collision list (`A4.pdf` is far more often a scanner's
|
||||
* paper size than verifikat A4, `K10.pdf` a blankett);
|
||||
* - three-letter series (`IMG_0031.jpg`: real SIE series are 1-2 chars,
|
||||
* three letters is a camera or scanner prefix).
|
||||
* They all still parse and resolve; a human confirms with one click.
|
||||
*/
|
||||
autoSelectable: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional noise ahead of the reference: a year folder prefix and the words
|
||||
* some exporters prepend. Kept tight on purpose, `(?:19|20)\d{2}` rather than
|
||||
* any 4 digits, so a voucher number is never eaten as a year.
|
||||
*
|
||||
* `ifikation` must precede `ifikat` in the alternation: regex alternation is
|
||||
* first-match, so the short branch would otherwise consume `Verifikat` out of
|
||||
* `Verifikation 31` and leave `ion` for the series group to swallow.
|
||||
*/
|
||||
const YEAR_NOISE = '(?:(?:19|20)\\d{2}[-_. ]+)?'
|
||||
/**
|
||||
* The lookahead is load-bearing, not decoration. Without it the engine
|
||||
* backtracks into the shorter alternatives and `Verifikation 31` matches `ver`
|
||||
* + `ifikat`, leaving `ion` for the series group to swallow as series `ION`.
|
||||
* Requiring the word to end here means the prefix is either the whole word or
|
||||
* not consumed at all.
|
||||
*/
|
||||
const VER_NOISE = '(?:ver(?:ifikation|ifikat)?(?![A-Za-zÅÄÖåäö])[-_. ]*)?'
|
||||
|
||||
/** `A31`, `A-31`, `A_31`, `A 31`, optionally followed by `_`/`-`/space + anything. */
|
||||
const SERIES_NUMBER_RE = new RegExp(
|
||||
`^${YEAR_NOISE}${VER_NOISE}([A-Za-zÅÄÖåäö]{1,3})[-_. ]?(\\d{1,7})(?:[-_. ].*)?$`,
|
||||
'i',
|
||||
)
|
||||
|
||||
/**
|
||||
* `31`, `31_kvitto`, `Verifikat 31`. The `ver` prefix is allowed here but the
|
||||
* year prefix is NOT: `2024 31` is far more likely a date fragment than
|
||||
* voucher 31 of 2024, and this branch has no series to corroborate it with.
|
||||
*/
|
||||
const NUMBER_ONLY_RE = new RegExp(`^${VER_NOISE}(\\d{1,6})(?:[-_. ].*)?$`, 'i')
|
||||
|
||||
/**
|
||||
* A date-named file, never a voucher number. Deliberately loose where the
|
||||
* parser is strict: unpadded components (`2024-1-31`), two-digit years
|
||||
* (`24-01-31`), any of `-_. /` as separator, and the compact `20240131`.
|
||||
* A false positive here costs one manual assignment; a false negative attaches
|
||||
* a receipt to a verifikat whose number happens to equal a year fragment.
|
||||
*/
|
||||
const DATE_PREFIX_RE = new RegExp(
|
||||
'^(?:' +
|
||||
// 20240131
|
||||
'(?:19|20)\\d{6}' +
|
||||
// 2024-01-31, 2024-1-31, 24-01-31, 2024 01 31, 2024/01/31
|
||||
'|(?:19|20)?\\d{2}[-_. /]\\d{1,2}[-_. /]\\d{1,2}' +
|
||||
// 31.01.2024, 31/1/2024, 12-24-2024: day-first and US order. Without this
|
||||
// the day becomes a voucher number that always exists in the year.
|
||||
'|\\d{1,2}[-_. /]\\d{1,2}[-_. /](?:19|20)\\d{2}' +
|
||||
')(?!\\d)',
|
||||
)
|
||||
|
||||
/**
|
||||
* `ver` is a prefix word, never a series. Without this `ver 31.pdf` parses as
|
||||
* series VER and comes back auto-selectable, while the spelled-out
|
||||
* `Verifikat 31.pdf` correctly yields a series-less reference that requires
|
||||
* confirmation. Same filename, two trust levels, decided by an abbreviation.
|
||||
*/
|
||||
const NOT_A_SERIES = new Set(['VER'])
|
||||
|
||||
/**
|
||||
* Refs that are, in the wild, far more often document names than voucher
|
||||
* references: A0-A6 are paper sizes (every scanner emits an `A4.pdf`),
|
||||
* K2-K13 / N1-N9 / T1-T2 are Skatteverket blanketter, Q1-Q4 are quarters.
|
||||
* Verifikat A4 genuinely exists in every migrated ledger, which is exactly
|
||||
* why these must not be pre-selected: the review table cannot tell a scanned
|
||||
* "A4.pdf" from the real receipt for voucher A4, and a wrong link is
|
||||
* permanent. Demoted, not refused: a genuine A4 costs one click.
|
||||
*
|
||||
* The inconsistency this fixes: `31.pdf` already required confirmation while
|
||||
* `A4 scan.pdf`, which carries LESS voucher evidence in a single-series
|
||||
* company, was pre-ticked.
|
||||
*/
|
||||
const COLLISION_REFS = new Set([
|
||||
'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6',
|
||||
'K2', 'K3', 'K4', 'K5', 'K6', 'K7', 'K8', 'K9', 'K10', 'K11', 'K12', 'K13',
|
||||
'N1', 'N2', 'N3', 'N4', 'N5', 'N6', 'N7', 'N8', 'N9',
|
||||
'T1', 'T2',
|
||||
'Q1', 'Q2', 'Q3', 'Q4',
|
||||
])
|
||||
|
||||
/** Real SIE series are 1-2 characters; three letters is IMG/DSC/DOC/SCN. */
|
||||
const MAX_AUTO_SERIES_LENGTH = 2
|
||||
|
||||
/**
|
||||
* Any four-digit run that reads as a calendar year. Used to refuse a
|
||||
* SERIES-LESS parse: `2024` alone is overwhelmingly a year, not verifikat 2024.
|
||||
*/
|
||||
const YEAR_LIKE_RE = /^(?:19|20)\d{2}$/
|
||||
|
||||
/**
|
||||
* Trim only. Directory components are NOT stripped: `file.name` from an
|
||||
* `<input type=file>` never carries a path, while the manual-reference box
|
||||
* feeds arbitrary user text through this same parser, where splitting on `/`
|
||||
* would quietly turn the typed date `2024/01/31` into voucher 31. The one
|
||||
* place a path does show up is the multipart `filename` of an upload (Chrome
|
||||
* writes the folder-relative path for folder selections); the attach route
|
||||
* reduces that to a basename before it reaches here, see
|
||||
* `lib/documents/upload-file-name.ts`.
|
||||
*/
|
||||
function baseName(fileName: string): string {
|
||||
return fileName.trim()
|
||||
}
|
||||
|
||||
/** Drop the extension, but only a real-looking one (`.pdf`, `.jpeg`). */
|
||||
function stripExtension(name: string): string {
|
||||
return name.replace(/\.[A-Za-z0-9]{1,5}$/, '')
|
||||
}
|
||||
|
||||
export function parseVoucherRefFromFileName(fileName: string): ParsedFileNameRef | null {
|
||||
const stem = stripExtension(baseName(fileName))
|
||||
if (!stem) return null
|
||||
|
||||
// A file named after its date is the single most common false positive: the
|
||||
// digits parse cleanly and point at a verifikat number that has nothing to do
|
||||
// with the receipt. Refuse the whole name rather than try to be clever.
|
||||
if (DATE_PREFIX_RE.test(stem)) return null
|
||||
|
||||
const seriesMatch = SERIES_NUMBER_RE.exec(stem)
|
||||
if (seriesMatch) {
|
||||
const series = seriesMatch[1].toUpperCase()
|
||||
const number = Number(seriesMatch[2])
|
||||
if (!NOT_A_SERIES.has(series) && Number.isInteger(number) && number > 0) {
|
||||
// The check runs on the NORMALIZED ref: a scanner's `A0004.pdf` parses
|
||||
// to number 4 and must be caught by the same A4 entry.
|
||||
const autoSelectable =
|
||||
series.length <= MAX_AUTO_SERIES_LENGTH && !COLLISION_REFS.has(`${series}${number}`)
|
||||
return { series, number, pattern: 'series_number', autoSelectable }
|
||||
}
|
||||
}
|
||||
|
||||
const numberMatch = NUMBER_ONLY_RE.exec(stem)
|
||||
if (numberMatch && !YEAR_LIKE_RE.test(numberMatch[1])) {
|
||||
const number = Number(numberMatch[1])
|
||||
if (Number.isInteger(number) && number > 0) {
|
||||
return { series: null, number, pattern: 'number_only', autoSelectable: false }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Which extracted fields the Underlag rail should show for a document.
|
||||
*
|
||||
* A kassakvitto has no due date, no OCR reference, no invoice number and no
|
||||
* bankgiro: it is already paid. Rendering those as four empty boxes made the
|
||||
* rail read as "extraction failed" when in truth the concepts do not exist
|
||||
* on the document. The date is mislabelled too: on a receipt the document
|
||||
* date is the purchase date, not a "Fakturadatum".
|
||||
*
|
||||
* Two rules keep this safe when the AI classification is wrong:
|
||||
* 1. A field that HAS a value is never hidden.
|
||||
* 2. Hiding is reversible in one click (the caller renders a toggle), so
|
||||
* a receipt that really does carry an invoice number stays reachable.
|
||||
*
|
||||
* React-free on purpose: this repo has no jsdom or testing-library, so
|
||||
* display logic is tested here rather than through the component.
|
||||
*/
|
||||
|
||||
/** Concepts that exist on an invoice but not on a paid receipt. */
|
||||
export const INVOICE_ONLY_FIELD_KEYS: ReadonlySet<string> = new Set([
|
||||
'invoice.dueDate',
|
||||
'invoice.invoiceNumber',
|
||||
'invoice.paymentReference',
|
||||
'supplier.bankgiro',
|
||||
'supplier.plusgiro',
|
||||
])
|
||||
|
||||
/** Labels that read wrong on a receipt. */
|
||||
export const RECEIPT_FIELD_LABELS: Readonly<Record<string, string>> = {
|
||||
'invoice.invoiceDate': 'Inköpsdatum',
|
||||
}
|
||||
|
||||
export interface VisibleField {
|
||||
key: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export function selectInboxFields<T extends VisibleField>(opts: {
|
||||
/** extracted_data.documentKind; anything but 'receipt' keeps today's list. */
|
||||
documentKind: string | null | undefined
|
||||
fields: readonly T[]
|
||||
/** True when the field currently holds a value (draft or extracted). */
|
||||
hasValue: (key: string) => boolean
|
||||
/** User clicked "show invoice fields". */
|
||||
showAll: boolean
|
||||
}): { shown: T[]; hiddenCount: number } {
|
||||
const { documentKind, fields, hasValue, showAll } = opts
|
||||
if (documentKind !== 'receipt') return { shown: [...fields], hiddenCount: 0 }
|
||||
|
||||
const shown: T[] = []
|
||||
let hiddenCount = 0
|
||||
for (const field of fields) {
|
||||
if (!showAll && INVOICE_ONLY_FIELD_KEYS.has(field.key) && !hasValue(field.key)) {
|
||||
hiddenCount += 1
|
||||
continue
|
||||
}
|
||||
const label = RECEIPT_FIELD_LABELS[field.key]
|
||||
shown.push(label ? { ...field, label } : field)
|
||||
}
|
||||
return { shown, hiddenCount }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Which kind of document an inbox item is, for the list-row badge and the
|
||||
* type filter (issue #2129: "one Inkorg view that shows whether each row is
|
||||
* a leverantörsfaktura or bokföringsunderlag").
|
||||
*
|
||||
* Two sources, in priority order:
|
||||
* 1. kind_hint: what the sender declared through the +lev / +ver
|
||||
* plus-address tag. A column, so it survives re-extraction.
|
||||
* 2. extracted_data.documentKind: the AI classification.
|
||||
*
|
||||
* Anything outside the known vocabulary resolves to null and shows nothing,
|
||||
* rather than guessing.
|
||||
*
|
||||
* React-free on purpose: this repo has no jsdom or testing-library, so the
|
||||
* predicate is tested here rather than through the component.
|
||||
*/
|
||||
|
||||
export const INBOX_DOCUMENT_KINDS = [
|
||||
'receipt',
|
||||
'supplier_invoice',
|
||||
'government_letter',
|
||||
'other',
|
||||
] as const
|
||||
|
||||
export type InboxDocumentKind = (typeof INBOX_DOCUMENT_KINDS)[number]
|
||||
|
||||
/**
|
||||
* 'underlag' is everything that is not a supplier invoice: receipts,
|
||||
* government letters and other documents all book as bokföringsunderlag.
|
||||
*/
|
||||
export type InboxKindFilter = 'all' | 'supplier_invoice' | 'underlag'
|
||||
|
||||
export const INBOX_KIND_FILTERS: readonly InboxKindFilter[] = ['all', 'supplier_invoice', 'underlag']
|
||||
|
||||
export interface InboxKindSource {
|
||||
kind_hint?: string | null
|
||||
extracted_data?: { documentKind?: string | null } | null
|
||||
}
|
||||
|
||||
function isInboxDocumentKind(value: unknown): value is InboxDocumentKind {
|
||||
return typeof value === 'string' && (INBOX_DOCUMENT_KINDS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** The kind to show for an item: the sender's hint first, then the AI's. */
|
||||
export function resolveInboxKind(item: InboxKindSource): InboxDocumentKind | null {
|
||||
if (isInboxDocumentKind(item.kind_hint)) return item.kind_hint
|
||||
const aiKind = item.extracted_data?.documentKind
|
||||
return isInboxDocumentKind(aiKind) ? aiKind : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resolved kind passes the type filter. An unclassified item
|
||||
* (null) only passes 'all': the narrow filters promise a known kind.
|
||||
*/
|
||||
export function matchesInboxKindFilter(
|
||||
kind: InboxDocumentKind | null,
|
||||
filter: InboxKindFilter,
|
||||
): boolean {
|
||||
if (filter === 'all') return true
|
||||
if (kind === null) return false
|
||||
if (filter === 'supplier_invoice') return kind === 'supplier_invoice'
|
||||
return kind !== 'supplier_invoice'
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Link underlag (receipts, invoices, other räkenskapsinformation) to a
|
||||
* journal entry via POST /api/documents/{id}/link.
|
||||
*
|
||||
* Why this is a shared helper and not an inline loop per dialog:
|
||||
*
|
||||
* BFL 5 kap 7 § requires a verifikation to carry a reference to the underlag
|
||||
* it rests on, and BFL 7 kap requires that underlag to be archived with the
|
||||
* verifikat for 7 years. By the time this runs the verifikat is already
|
||||
* committed (the voucher number is assigned atomically), so a failed link
|
||||
* cannot be rolled back: it leaves a verifikat whose underlag is missing from
|
||||
* the archive. That is a compliance defect, and the only way it becomes
|
||||
* recoverable is if the user is told about it. Callers must therefore never
|
||||
* report plain success while `failed` is non-empty, and must never discard the
|
||||
* user's files on a failure.
|
||||
*
|
||||
* The contract: this function never throws and never swallows. Every target
|
||||
* ends up in exactly one of `linked` or `failed`, and a failure carries enough
|
||||
* (file name, HTTP status, error code) to name the specific documents that did
|
||||
* not attach.
|
||||
*/
|
||||
|
||||
export interface DocumentLinkTarget {
|
||||
/** documents.id: the row POST /api/documents/{id}/link is addressed at. */
|
||||
documentId: string
|
||||
/** Shown to the user when this document fails to attach. */
|
||||
fileName?: string | null
|
||||
/** Inbox item consumed by this link (the "choose from inbox" flow). */
|
||||
inboxItemId?: string | null
|
||||
/** Bank transaction the document should also be pinned to. */
|
||||
transactionId?: string | null
|
||||
}
|
||||
|
||||
export interface DocumentLinkFailure {
|
||||
documentId: string
|
||||
fileName: string | null
|
||||
/** HTTP status, or 0 when the request never produced a response (offline). */
|
||||
status: number
|
||||
/** Structured error code from the API envelope, when the server sent one. */
|
||||
code: string | null
|
||||
/** Best-effort human-readable reason (envelope message or thrown message). */
|
||||
reason: string | null
|
||||
}
|
||||
|
||||
export interface LinkDocumentsResult {
|
||||
/** documentIds that attached, in input order. */
|
||||
linked: string[]
|
||||
/** Everything that did not attach. Empty means the underlag is on the books. */
|
||||
failed: DocumentLinkFailure[]
|
||||
/** First document that attached: the "first linked doc wins" pin source. */
|
||||
firstLinkedId: string | null
|
||||
/** True when nothing failed (also true for an empty target list). */
|
||||
allLinked: boolean
|
||||
}
|
||||
|
||||
export interface LinkDocumentsOptions {
|
||||
/** Injectable fetch, for tests. Defaults to the global fetch. */
|
||||
fetchImpl?: typeof fetch
|
||||
}
|
||||
|
||||
interface ErrorEnvelope {
|
||||
error?: { code?: string; message?: string; message_en?: string }
|
||||
}
|
||||
|
||||
async function readErrorEnvelope(res: Response): Promise<{ code: string | null; reason: string | null }> {
|
||||
try {
|
||||
const body = (await res.json()) as ErrorEnvelope | null
|
||||
const err = body?.error
|
||||
return { code: err?.code ?? null, reason: err?.message ?? err?.message_en ?? null }
|
||||
} catch {
|
||||
// Non-JSON body (proxy error page, empty 502): the status alone is the
|
||||
// signal. Still a failure, never a silent success.
|
||||
return { code: null, reason: null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Link every target to `journalEntryId`, sequentially (input order is the
|
||||
* "first linked doc wins" order the link route relies on for its transaction
|
||||
* pin). Resolves with a per-document verdict; never rejects.
|
||||
*/
|
||||
export async function linkDocuments(
|
||||
targets: DocumentLinkTarget[],
|
||||
journalEntryId: string,
|
||||
options: LinkDocumentsOptions = {},
|
||||
): Promise<LinkDocumentsResult> {
|
||||
// Wrapped rather than assigned so the global fetch keeps its receiver.
|
||||
const doFetch: typeof fetch =
|
||||
options.fetchImpl ?? ((input, init) => globalThis.fetch(input, init))
|
||||
|
||||
const linked: string[] = []
|
||||
const failed: DocumentLinkFailure[] = []
|
||||
|
||||
for (const target of targets) {
|
||||
const fileName = target.fileName?.trim() ? target.fileName.trim() : null
|
||||
try {
|
||||
const res = await doFetch(`/api/documents/${encodeURIComponent(target.documentId)}/link`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
journal_entry_id: journalEntryId,
|
||||
...(target.inboxItemId ? { inbox_item_id: target.inboxItemId } : {}),
|
||||
...(target.transactionId ? { transaction_id: target.transactionId } : {}),
|
||||
}),
|
||||
})
|
||||
if (res.ok) {
|
||||
linked.push(target.documentId)
|
||||
continue
|
||||
}
|
||||
// A 4xx/5xx here is the exact case the old inline loops missed: the
|
||||
// request completed, so nothing threw, but the underlag never attached.
|
||||
const { code, reason } = await readErrorEnvelope(res)
|
||||
failed.push({ documentId: target.documentId, fileName, status: res.status, code, reason })
|
||||
} catch (err) {
|
||||
failed.push({
|
||||
documentId: target.documentId,
|
||||
fileName,
|
||||
status: 0,
|
||||
code: null,
|
||||
reason: err instanceof Error ? err.message : null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
linked,
|
||||
failed,
|
||||
firstLinkedId: linked[0] ?? null,
|
||||
allLinked: failed.length === 0,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Comma-separated file names for the "these did not attach" message. Falls
|
||||
* back to the document id so a nameless document is still identifiable: the
|
||||
* user must always be able to tell WHICH underlag is missing.
|
||||
*/
|
||||
export function formatFailedDocumentNames(failures: DocumentLinkFailure[]): string {
|
||||
return failures.map((f) => f.fileName ?? f.documentId).join(', ')
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { HOSTED_MAX_UPLOAD_BYTES, isShrinkableImage } from './upload-size'
|
||||
|
||||
/**
|
||||
* Re-encode an oversized photo in the browser so it fits the platform's
|
||||
* request-body ceiling (see upload-size.ts for why that ceiling exists).
|
||||
*
|
||||
* Only reached for files that cannot be sent as they are. The archived
|
||||
* document is whatever comes back from here, so the goal is a faithful,
|
||||
* durably readable reproduction of the receipt (BFL 7 kap: "varaktigt läsbart
|
||||
* skick"), not the smallest possible file. 2400px on the long edge keeps the
|
||||
* small print on a receipt legible while taking a 12 MP phone photo well under
|
||||
* the limit; quality steps down only if that is not enough.
|
||||
*
|
||||
* Returns the original file untouched when the browser cannot decode it (HEIC
|
||||
* outside Safari, a corrupt image) or when re-encoding would not help. The
|
||||
* caller then reports the honest size message rather than uploading something
|
||||
* that is going to be rejected in transit.
|
||||
*/
|
||||
|
||||
const MAX_EDGE_PX = 2400
|
||||
const QUALITY_STEPS = [0.85, 0.7, 0.55]
|
||||
|
||||
export async function shrinkImageForUpload(
|
||||
file: File,
|
||||
maxBytes: number = HOSTED_MAX_UPLOAD_BYTES,
|
||||
): Promise<File> {
|
||||
if (file.size <= maxBytes) return file
|
||||
if (!isShrinkableImage(file.type)) return file
|
||||
if (typeof createImageBitmap !== 'function' || typeof document === 'undefined') return file
|
||||
|
||||
try {
|
||||
const bitmap = await createImageBitmap(file)
|
||||
const scale = Math.min(1, MAX_EDGE_PX / Math.max(bitmap.width, bitmap.height))
|
||||
const width = Math.max(1, Math.round(bitmap.width * scale))
|
||||
const height = Math.max(1, Math.round(bitmap.height * scale))
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) {
|
||||
bitmap.close()
|
||||
return file
|
||||
}
|
||||
context.drawImage(bitmap, 0, 0, width, height)
|
||||
bitmap.close()
|
||||
|
||||
for (const quality of QUALITY_STEPS) {
|
||||
const blob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/jpeg', quality)
|
||||
})
|
||||
if (!blob) return file
|
||||
if (blob.size <= maxBytes) {
|
||||
return new File([blob], jpegName(file.name), {
|
||||
type: 'image/jpeg',
|
||||
lastModified: file.lastModified,
|
||||
})
|
||||
}
|
||||
}
|
||||
return file
|
||||
} catch {
|
||||
// A decode the browser refuses (HEIC off Safari) is not an error worth
|
||||
// surfacing on its own: the size message the caller falls back to is the
|
||||
// one the user can act on.
|
||||
return file
|
||||
}
|
||||
}
|
||||
|
||||
function jpegName(name: string): string {
|
||||
const base = name.replace(/\.[^.]+$/, '') || 'underlag'
|
||||
return `${base}.jpg`
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* Underlag import: attach a folder of receipt files to already-migrated
|
||||
* verifikat, using nothing but the voucher reference in each filename.
|
||||
*
|
||||
* A SIE file carries the ledger but not the underlag, so a migrating customer
|
||||
* has to bring the receipts over separately. Systems that export both name each
|
||||
* receipt after its verifikat (`A31_<id>.pdf`), and the SIE import preserved
|
||||
* that same identity on every entry, so the pairing is a lookup rather than an
|
||||
* interpretation. No AI, no amount matching, no date windows.
|
||||
*
|
||||
* This module only PLANS. Nothing here writes: the plan goes back to the user,
|
||||
* who approves it, and each approved row is then attached one file at a time.
|
||||
* That split is deliberate: linking a document to a posted verifikat makes it
|
||||
* räkenskapsinformation, which can never be re-pointed (BFL 7 kap), so a bulk
|
||||
* write with no preview would be an unrecoverable mistake by design.
|
||||
*
|
||||
* EVERY plan is scoped to one fiscal year, which the user declares. That is not
|
||||
* ceremony. Source systems restart voucher numbering every year and a filename
|
||||
* carries no year, so `A31` alone does not identify a verifikat. An earlier
|
||||
* version resolved company-wide and treated "only one candidate exists" as
|
||||
* proof of identity: with a partial migration, or with the year's A31 among the
|
||||
* vouchers the importer skipped (empty, single-line, unbalanced), that silently
|
||||
* attached a 2023 receipt to a 2025 verifikat, permanently. Cardinality is not
|
||||
* identity. Scoping cannot make the year inferable, so it makes it asserted:
|
||||
* a file can only ever land in the year the user named.
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { parseVoucherRefFromFileName } from '@/lib/documents/filename-voucher-ref'
|
||||
import {
|
||||
buildVoucherIndex,
|
||||
candidatesForNumber,
|
||||
candidatesForRef,
|
||||
fetchFiscalPeriods,
|
||||
fetchVouchersForNumbers,
|
||||
hasSourceRefVouchers,
|
||||
sourceVoucherLabel,
|
||||
voucherLabel,
|
||||
type FiscalPeriodRow,
|
||||
type VoucherRow,
|
||||
} from '@/lib/documents/voucher-ref-resolver'
|
||||
|
||||
export type UnderlagPlanStatus =
|
||||
/** Exactly one open verifikat: safe to pre-select. */
|
||||
| 'matched'
|
||||
/** Resolved, but the filename gave no series: a human confirms the pick. */
|
||||
| 'needs_confirmation'
|
||||
/** The ref exists in several fiscal years: the user picks which one. */
|
||||
| 'ambiguous'
|
||||
/** The only candidate sits in a closed or locked period: the DB will refuse. */
|
||||
| 'period_locked'
|
||||
/** Parsed a ref, but no migrated verifikat carries it. */
|
||||
| 'no_match'
|
||||
/** The filename carries no readable voucher reference. */
|
||||
| 'unparsed'
|
||||
|
||||
export interface UnderlagPlanCandidate {
|
||||
journal_entry_id: string
|
||||
/** Our own label after renumbering, e.g. `A47`. */
|
||||
voucher_label: string | null
|
||||
/** The label the source system used, i.e. what the filename says, e.g. `A31`. */
|
||||
source_voucher_label: string | null
|
||||
entry_date: string
|
||||
description: string | null
|
||||
period_locked: boolean
|
||||
}
|
||||
|
||||
export interface UnderlagPlanRow {
|
||||
file_name: string
|
||||
status: UnderlagPlanStatus
|
||||
parsed_ref: { series: string | null; number: number } | null
|
||||
/** The single resolved target, when there is exactly one. */
|
||||
journal_entry_id: string | null
|
||||
/** Every candidate, so an ambiguous row can be resolved by hand. */
|
||||
candidates: UnderlagPlanCandidate[]
|
||||
}
|
||||
|
||||
export interface UnderlagPlanSummary {
|
||||
total: number
|
||||
matched: number
|
||||
needs_confirmation: number
|
||||
ambiguous: number
|
||||
period_locked: number
|
||||
no_match: number
|
||||
unparsed: number
|
||||
}
|
||||
|
||||
export interface UnderlagPlan {
|
||||
rows: UnderlagPlanRow[]
|
||||
summary: UnderlagPlanSummary
|
||||
/** The fiscal year every row in this plan was resolved against. */
|
||||
fiscal_period_id: string
|
||||
/**
|
||||
* True when the SELECTED fiscal year holds no migrated entry carrying a
|
||||
* source voucher ref. Either that year was never imported from SIE, or the
|
||||
* import predates the columns (added 2026-04-21 and never backfilled), in
|
||||
* which case filename matching cannot work for it at all and the UI must say
|
||||
* so instead of showing 400 misses. Often it just means the wrong year is
|
||||
* selected, which is the first thing worth telling the user.
|
||||
*/
|
||||
no_source_refs: boolean
|
||||
}
|
||||
|
||||
function isPeriodLocked(period: FiscalPeriodRow | undefined): boolean {
|
||||
return period ? period.is_closed || period.locked_at !== null : false
|
||||
}
|
||||
|
||||
function toCandidate(entry: VoucherRow, periods: Map<string, FiscalPeriodRow>): UnderlagPlanCandidate {
|
||||
return {
|
||||
journal_entry_id: entry.id,
|
||||
voucher_label: voucherLabel(entry),
|
||||
source_voucher_label: sourceVoucherLabel(entry),
|
||||
entry_date: entry.entry_date,
|
||||
description: entry.description ?? null,
|
||||
period_locked: isPeriodLocked(periods.get(entry.fiscal_period_id)),
|
||||
}
|
||||
}
|
||||
|
||||
function emptySummary(): UnderlagPlanSummary {
|
||||
return {
|
||||
total: 0,
|
||||
matched: 0,
|
||||
needs_confirmation: 0,
|
||||
ambiguous: 0,
|
||||
period_locked: 0,
|
||||
no_match: 0,
|
||||
unparsed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the match plan for a set of filenames, inside one declared fiscal year.
|
||||
* Reads only: no upload, no link.
|
||||
*
|
||||
* The same function backs the preview and the per-file attach check, so the
|
||||
* server can never link a file to a verifikat the preview would not have
|
||||
* proposed.
|
||||
*/
|
||||
export async function buildUnderlagPlan(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fileNames: string[],
|
||||
fiscalPeriodId: string,
|
||||
): Promise<UnderlagPlan> {
|
||||
const parsed = fileNames.map((fileName) => ({
|
||||
fileName,
|
||||
ref: parseVoucherRefFromFileName(fileName),
|
||||
}))
|
||||
|
||||
const numbers = parsed.map((p) => p.ref?.number).filter((n): n is number => n != null)
|
||||
|
||||
const [vouchers, periodRows] = await Promise.all([
|
||||
fetchVouchersForNumbers(supabase, companyId, numbers, fiscalPeriodId),
|
||||
fetchFiscalPeriods(supabase, companyId),
|
||||
])
|
||||
|
||||
// The single most important line in this module: candidates outside the
|
||||
// declared year are dropped BEFORE the index is built, so no downstream
|
||||
// branch can ever see, count or propose one.
|
||||
const index = buildVoucherIndex(
|
||||
vouchers.filter((entry) => entry.fiscal_period_id === fiscalPeriodId),
|
||||
)
|
||||
const periods = new Map(periodRows.map((p) => [p.id, p]))
|
||||
|
||||
const summary = emptySummary()
|
||||
summary.total = parsed.length
|
||||
|
||||
const rows: UnderlagPlanRow[] = parsed.map(({ fileName, ref }) => {
|
||||
if (!ref) {
|
||||
summary.unparsed++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'unparsed',
|
||||
parsed_ref: null,
|
||||
journal_entry_id: null,
|
||||
candidates: [],
|
||||
}
|
||||
}
|
||||
|
||||
const parsedRef = { series: ref.series, number: ref.number }
|
||||
const entries = ref.series
|
||||
? candidatesForRef(index, { series: ref.series, number: ref.number })
|
||||
: candidatesForNumber(index, ref.number)
|
||||
const candidates = entries.map((entry) => toCandidate(entry, periods))
|
||||
|
||||
if (candidates.length === 0) {
|
||||
summary.no_match++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'no_match',
|
||||
parsed_ref: parsedRef,
|
||||
journal_entry_id: null,
|
||||
candidates: [],
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.length > 1) {
|
||||
// Inside one fiscal year a source ref should be unique, so this is either
|
||||
// a re-imported year or a series-less filename hitting several series.
|
||||
// Hand the choice back rather than pick.
|
||||
summary.ambiguous++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'ambiguous',
|
||||
parsed_ref: parsedRef,
|
||||
journal_entry_id: null,
|
||||
candidates,
|
||||
}
|
||||
}
|
||||
|
||||
const only = candidates[0]
|
||||
if (only.period_locked) {
|
||||
summary.period_locked++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'period_locked',
|
||||
parsed_ref: parsedRef,
|
||||
journal_entry_id: only.journal_entry_id,
|
||||
candidates,
|
||||
}
|
||||
}
|
||||
|
||||
if (!ref.autoSelectable) {
|
||||
summary.needs_confirmation++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'needs_confirmation',
|
||||
parsed_ref: parsedRef,
|
||||
journal_entry_id: only.journal_entry_id,
|
||||
candidates,
|
||||
}
|
||||
}
|
||||
|
||||
summary.matched++
|
||||
return {
|
||||
file_name: fileName,
|
||||
status: 'matched',
|
||||
parsed_ref: parsedRef,
|
||||
journal_entry_id: only.journal_entry_id,
|
||||
candidates,
|
||||
}
|
||||
})
|
||||
|
||||
// Only worth a round-trip when nothing landed: the answer distinguishes
|
||||
// "wrong filenames" from "this year holds no source refs to match against",
|
||||
// which most often means the wrong year is selected.
|
||||
const no_source_refs =
|
||||
summary.matched + summary.needs_confirmation + summary.ambiguous + summary.period_locked === 0
|
||||
? !(await hasSourceRefVouchers(supabase, companyId, fiscalPeriodId))
|
||||
: false
|
||||
|
||||
return { rows, summary, fiscal_period_id: fiscalPeriodId, no_source_refs }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether attaching `fileName` to `journalEntryId` is permitted by the plan.
|
||||
*
|
||||
* Guards the attach route against a stale or wrong client: the file the browser
|
||||
* uploads must land on a verifikat the preview would propose for that name.
|
||||
* `fiscalPeriodId` is the caller-supplied declared year, which the route has
|
||||
* ALREADY asserted equal to the target entry's own period before calling this;
|
||||
* this function only decides the filename-to-target question inside that year.
|
||||
*
|
||||
* `override` marks a deliberate manual assignment. It is honored ONLY when the
|
||||
* filename is unresolvable in the declared year (no parse, or no candidate):
|
||||
* a filename the resolver CAN place must land where it points, override or
|
||||
* not, otherwise a lying client could scatter cleanly-named underlag across
|
||||
* arbitrary same-year verifikat. The shipped UI only ever overrides rows whose
|
||||
* filenames resolved to nothing, so this costs it no capability.
|
||||
*/
|
||||
export async function planPermitsAttach(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fileName: string,
|
||||
journalEntryId: string,
|
||||
fiscalPeriodId: string,
|
||||
override: boolean,
|
||||
): Promise<boolean> {
|
||||
const plan = await buildUnderlagPlan(supabase, companyId, [fileName], fiscalPeriodId)
|
||||
const row = plan.rows[0]
|
||||
if (!row) return false
|
||||
if (row.candidates.some((candidate) => candidate.journal_entry_id === journalEntryId)) {
|
||||
return true
|
||||
}
|
||||
return override && row.candidates.length === 0
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Documents in the archive that are attached to nothing.
|
||||
*
|
||||
* A `document_attachments` row is reachable from eight places: a journal
|
||||
* entry (its own `journal_entry_id`), a bank transaction, a receipt, an
|
||||
* inbox item, a supplier invoice, an invoice delivery, an inbound Peppol
|
||||
* document, an årsredovisning submission, and a ROT/RUT payout request. A
|
||||
* row referenced by none of them is stored, retained for seven years under
|
||||
* BFL, and connected to no bookkeeping at all. Nothing surfaces those today,
|
||||
* so they accumulate silently: 4 497 of them across 210 companies as of
|
||||
* 2026-08-27, 481 of them created in the preceding week.
|
||||
*
|
||||
* ## Why the mime allow-list is the whole design
|
||||
*
|
||||
* The obvious predicate, "current version with no journal_entry_id and no
|
||||
* referencing row", returns 15 806 rows on production. 11 309 of those are
|
||||
* `application/json` and every single one is named `psd2-response_<ts>_pN.json`:
|
||||
* the archived bank-API responses the PSD2 integration stores as evidence of
|
||||
* each fetch. They are SUPPOSED to have no verifikat and no transaction. Put
|
||||
* them on an attention surface and an agent is handed 11 309 items of busywork
|
||||
* that it must not action, which is worse than showing nothing.
|
||||
*
|
||||
* Measured on production 2026-08-27: of the unreferenced rows,
|
||||
* `application/json` was 11 309 of 11 309 PSD2 archive, and pdf / png / jpeg /
|
||||
* heic were 0 of 4 495. The split is clean, so the rule is an allow-list of
|
||||
* the mime types an underlag can actually be, not a filename exclusion. A new
|
||||
* machine-payload format (XML, CSV, an audit bundle) stays out by default
|
||||
* rather than needing another exclusion added after it starts leaking.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* Mime types a bookkeeping underlag can plausibly be: something a human could
|
||||
* open and read as a receipt or an invoice. Everything else on this surface is
|
||||
* a machine payload that is unlinked by design.
|
||||
*/
|
||||
export const UNDERLAG_MIME_TYPES = [
|
||||
'application/pdf',
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/heic',
|
||||
'image/webp',
|
||||
'image/tiff',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* The candidate scan is bounded, and the bound is set by URL length rather
|
||||
* than by table size.
|
||||
*
|
||||
* Every candidate id is sent back through eight `.in(column, ids)` lookups,
|
||||
* and a UUID costs ~38 bytes in a PostgREST query string, so 300 ids is
|
||||
* already a ~12 KB URL per lookup. A cap in the thousands would exceed what
|
||||
* the gateway accepts and the eight lookups would start failing, which the
|
||||
* error handling below would read as "nothing claims these" and would turn
|
||||
* every candidate into a false positive. Small and honest beats large and
|
||||
* silently wrong.
|
||||
*
|
||||
* 300 covers all but one company on production (median 3, worst 1 298 as of
|
||||
* 2026-08-27). When the cap is hit, `capped` says so and `count` becomes a
|
||||
* floor rather than a total, because the caller renders a number either way
|
||||
* and a silently truncated one would read as "nearly done".
|
||||
*/
|
||||
export const UNLINKED_DOCUMENT_SCAN_CAP = 300
|
||||
|
||||
/**
|
||||
* A type alias, not an interface, on purpose: the attention resource assigns
|
||||
* these straight into its `samples: Record<string, unknown>[]` field, and an
|
||||
* interface has no implicit index signature so that assignment does not
|
||||
* type-check. Vitest does not typecheck, so this only ever shows up in
|
||||
* `npm run build`.
|
||||
*/
|
||||
export type UnlinkedDocument = {
|
||||
id: string
|
||||
file_name: string
|
||||
mime_type: string | null
|
||||
file_size_bytes: number | null
|
||||
upload_source: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface UnlinkedDocumentsResult {
|
||||
documents: UnlinkedDocument[]
|
||||
count: number
|
||||
capped: boolean
|
||||
}
|
||||
|
||||
const COLUMNS = 'id, file_name, mime_type, file_size_bytes, upload_source, created_at'
|
||||
|
||||
/**
|
||||
* The eight tables that can claim a document, as [table, column] pairs.
|
||||
*
|
||||
* `journal_entry_id` is deliberately absent: it lives on the document row
|
||||
* itself and is already excluded by the column filter below.
|
||||
*/
|
||||
const REFERENCING_COLUMNS: ReadonlyArray<readonly [table: string, column: string]> = [
|
||||
['transactions', 'document_id'],
|
||||
['receipts', 'document_id'],
|
||||
['invoice_inbox_items', 'document_id'],
|
||||
['supplier_invoices', 'document_id'],
|
||||
['invoice_deliveries', 'document_attachment_id'],
|
||||
['peppol_inbound_documents', 'xml_document_id'],
|
||||
['arsredovisning_submissions', 'dokument_id'],
|
||||
['rot_rut_payout_requests', 'file_document_id'],
|
||||
]
|
||||
|
||||
/**
|
||||
* Underlag-shaped documents in this company's archive that nothing references.
|
||||
*
|
||||
* Two passes, the same shape as `fetchPurchasesWithoutUnderlag`: the column
|
||||
* filter is the cheap part the database can index, and the eight reference
|
||||
* lookups settle it afterwards for the candidates that survived. They run only
|
||||
* when there are candidates, so the common case (a company with none) costs
|
||||
* exactly one query.
|
||||
*/
|
||||
export async function fetchUnlinkedDocuments(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
options?: { limit?: number },
|
||||
): Promise<UnlinkedDocumentsResult> {
|
||||
const cap = options?.limit ?? UNLINKED_DOCUMENT_SCAN_CAP
|
||||
|
||||
const { data: candidates } = await supabase
|
||||
.from('document_attachments')
|
||||
.select(COLUMNS)
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.not('is_current_version', 'is', false)
|
||||
.in('mime_type', UNDERLAG_MIME_TYPES as unknown as string[])
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(cap)
|
||||
|
||||
const rows = (candidates ?? []) as UnlinkedDocument[]
|
||||
if (rows.length === 0) return { documents: [], count: 0, capped: false }
|
||||
|
||||
const ids = rows.map((r) => r.id)
|
||||
const referenced = new Set<string>()
|
||||
|
||||
// Fetched once for the whole candidate set rather than per row. A failing
|
||||
// lookup is treated as "claims nothing", which can only ever ADD a row to
|
||||
// the list; the alternative (dropping the whole category on one bad table)
|
||||
// would hide real work because an unrelated feature's table misbehaved.
|
||||
await Promise.all(
|
||||
REFERENCING_COLUMNS.map(async ([table, column]) => {
|
||||
const { data } = await supabase.from(table).select(column).in(column, ids)
|
||||
// The column name is resolved at runtime, so the client cannot infer a
|
||||
// row type here; `unknown` first because the inferred error union does
|
||||
// not overlap the record shape.
|
||||
const referencingRows = (data ?? []) as unknown as Array<Record<string, string | null>>
|
||||
for (const row of referencingRows) {
|
||||
const value = row[column]
|
||||
if (value) referenced.add(value)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const documents = rows.filter((r) => !referenced.has(r.id))
|
||||
return { documents, count: documents.length, capped: rows.length >= cap }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* The name of an uploaded file as the user saw it: the last path segment of
|
||||
* whatever the browser wrote into the multipart `filename` parameter.
|
||||
*
|
||||
* `File.name` in the browser is a bare filename by spec. The `filename` the
|
||||
* same browser writes into multipart/form-data is not guaranteed to be that
|
||||
* string: Chrome fills it with `webkitRelativePath` for files that came from
|
||||
* a folder selection. A receipt picked out of a Fortnox export as
|
||||
* `2026/06/Leverantörsfakturor/A166_Hetzner.pdf` therefore arrives server-side
|
||||
* under that whole path, while every client-side read of `file.name`, and so
|
||||
* every preview the user approved, said `A166_Hetzner.pdf`.
|
||||
*
|
||||
* Any server logic that compares an uploaded name to something the client
|
||||
* computed from `File.name`, or stores the name for the user to read back,
|
||||
* must go through this first. Both separators are stripped: Chrome writes `/`
|
||||
* on every platform, legacy Windows clients sent `\`. Nothing else is
|
||||
* normalized, on purpose: the voucher-ref parser must see the name exactly as
|
||||
* the exporting system wrote it.
|
||||
*/
|
||||
export function uploadedFileBaseName(name: string): string {
|
||||
const cut = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'))
|
||||
return cut === -1 ? name : name.slice(cut + 1)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* What the hosting platform will actually carry, as opposed to what the
|
||||
* upload routes say they accept.
|
||||
*
|
||||
* Vercel rejects a request body over 4.5 MB itself, before the function runs:
|
||||
* the caller gets a plain-text 413 (FUNCTION_PAYLOAD_TOO_LARGE) and nothing
|
||||
* reaches the route, so nothing lands in the function logs either. That is why
|
||||
* a user reporting "uploading from my phone just fails" was invisible in
|
||||
* production while every upload that did arrive returned 200. A phone photo
|
||||
* routinely exceeds it: iPhone JPEG capture ("Most Compatible") lands at
|
||||
* 4-12 MB, well over the route's own 10 MB promise that can never be reached
|
||||
* on hosted.
|
||||
*
|
||||
* Self-hosted Docker has no such proxy limit, so the route's own MAX_FILE_SIZE
|
||||
* governs there and none of this applies.
|
||||
*/
|
||||
|
||||
import { isSelfHosted } from '@/lib/env/public-flags'
|
||||
|
||||
/** The platform's hard ceiling on a request body. */
|
||||
export const HOSTED_REQUEST_BODY_LIMIT_BYTES = Math.round(4.5 * 1024 * 1024)
|
||||
|
||||
/**
|
||||
* The largest file we will put in a multipart body. Below the hard ceiling by
|
||||
* enough to cover the multipart envelope (boundaries, part headers, the file
|
||||
* name) so a file that just fits does not fail on the framing around it.
|
||||
*/
|
||||
export const HOSTED_MAX_UPLOAD_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export function isHostedDeployment(): boolean {
|
||||
return !isSelfHosted()
|
||||
}
|
||||
|
||||
/**
|
||||
* Image types a browser canvas can decode and re-encode. HEIC/HEIF are
|
||||
* included deliberately: Safari on iOS decodes them natively, and iOS is
|
||||
* exactly where the oversized photos come from. Elsewhere the decode throws
|
||||
* and the caller keeps the original, which then gets the honest size message
|
||||
* instead of a silent failure.
|
||||
*/
|
||||
const SHRINKABLE_IMAGE_TYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/jpg',
|
||||
'image/png',
|
||||
'image/heic',
|
||||
'image/heif',
|
||||
'image/webp',
|
||||
])
|
||||
|
||||
export function isShrinkableImage(type: string | null | undefined): boolean {
|
||||
return SHRINKABLE_IMAGE_TYPES.has(String(type ?? '').toLowerCase())
|
||||
}
|
||||
|
||||
/** True when this file cannot be sent as-is on a hosted deployment. */
|
||||
export function exceedsHostedUploadLimit(size: number): boolean {
|
||||
return isHostedDeployment() && size > HOSTED_MAX_UPLOAD_BYTES
|
||||
}
|
||||
|
||||
export function formatMegabytes(bytes: number): string {
|
||||
return `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB`
|
||||
}
|
||||
|
||||
/**
|
||||
* The sentence for a file that is over the limit and cannot be shrunk (a PDF,
|
||||
* or an image the browser would not decode). Names both the actual size and
|
||||
* the ceiling: "too large" without either is the kind of message that sends a
|
||||
* user back to support rather than to a solution.
|
||||
*
|
||||
* Still the right message for the surfaces that post a multipart body
|
||||
* (ReconciliationUnderlag, support attachments). The document inbox no
|
||||
* longer refuses at this ceiling: see inboxTooLargeMessage.
|
||||
*/
|
||||
export function tooLargeMessage(size: number): string {
|
||||
return (
|
||||
`Filen är ${formatMegabytes(size)} och gränsen är ${formatMegabytes(HOSTED_MAX_UPLOAD_BYTES)}. ` +
|
||||
'Fotografera om kvittot, eller komprimera PDF:en, och försök igen.'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The document inbox's own ceiling: MAX_FILE_SIZE in the invoice-inbox
|
||||
* extension and MAX_DOCUMENT_SIZE in the document service, both 10 MB.
|
||||
* Mirrored here because core components must not import from extensions.
|
||||
*
|
||||
* Between HOSTED_MAX_UPLOAD_BYTES and this one, the inbox sends the bytes
|
||||
* straight to Storage through a signed URL (direct-upload.ts) so the
|
||||
* platform's body cap no longer decides what can be filed; this one still
|
||||
* does, on hosted and self-hosted alike.
|
||||
*/
|
||||
export const INBOX_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
|
||||
/** True when the file is over the inbox ceiling on any deployment. */
|
||||
export function exceedsInboxUploadLimit(size: number): boolean {
|
||||
return size > INBOX_MAX_UPLOAD_BYTES
|
||||
}
|
||||
|
||||
/**
|
||||
* The inbox's sentence for a file over its ceiling. Same shape as
|
||||
* tooLargeMessage (actual size, then the limit), but the limit it names is
|
||||
* the one that actually applies on that surface now.
|
||||
*/
|
||||
export function inboxTooLargeMessage(size: number): string {
|
||||
return (
|
||||
`Filen är ${formatMegabytes(size)} och gränsen för dokumentinkorgen är ${formatMegabytes(INBOX_MAX_UPLOAD_BYTES)}. ` +
|
||||
'Komprimera PDF:en, eller dela upp den, och försök igen.'
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Resolve a SOURCE-system voucher reference to the gnubok verifikat it became.
|
||||
*
|
||||
* The SIE importer renumbers vouchers per target series (so source `A31` may
|
||||
* land as `A47` here), but it preserves the source identity on every entry:
|
||||
* `journal_entries.source_voucher_series` + `source_voucher_number`, written by
|
||||
* the `import_sie_journal_entries` RPC straight from #VER. That pair is the only
|
||||
* safe join key back to the old system. Matching on our own `voucher_number`
|
||||
* instead silently attaches underlag to the wrong verifikat as soon as the
|
||||
* import skipped an empty or unbalanced voucher, which it routinely does.
|
||||
*
|
||||
* Two consumers, one resolution truth:
|
||||
* - the provider migration sweep (Bokio/Fortnox), which knows each attachment's
|
||||
* voucher ref AND its date/financial year, and
|
||||
* - the underlag file import, which only knows what the filename says.
|
||||
*
|
||||
* Hence two entry points: `resolveDatedRef` when a date narrows the candidates,
|
||||
* and `candidatesForRef` when it does not and the caller must handle ambiguity
|
||||
* itself (surface the choice rather than guess: an underlag on the wrong
|
||||
* verifikat is räkenskapsinformation and cannot be re-pointed afterwards).
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
|
||||
/** A voucher as written in the source system. */
|
||||
export interface SourceVoucherRef {
|
||||
series: string
|
||||
number: number
|
||||
}
|
||||
|
||||
/** A source ref plus the date window that narrows it to one fiscal year. */
|
||||
export interface DatedSourceVoucherRef extends SourceVoucherRef {
|
||||
/** Attachment date, or the financial year start when only that is known. */
|
||||
date: string
|
||||
/** Financial year end, when the source only pins the attachment to a year. */
|
||||
dateTo?: string
|
||||
}
|
||||
|
||||
export interface VoucherRow {
|
||||
id: string
|
||||
fiscal_period_id: string
|
||||
entry_date: string
|
||||
source_voucher_series: string | null
|
||||
source_voucher_number: number | null
|
||||
// Display-only, and fetched only by the reads that need them: the provider
|
||||
// sweep resolves thousands of entries and never renders any of this.
|
||||
description?: string | null
|
||||
voucher_series?: string | null
|
||||
voucher_number?: number | null
|
||||
}
|
||||
|
||||
export interface FiscalPeriodRow {
|
||||
id: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
is_closed: boolean
|
||||
locked_at: string | null
|
||||
}
|
||||
|
||||
export interface VoucherIndex {
|
||||
/**
|
||||
* (period, series, number) → entry id, for keys that resolve to exactly one
|
||||
* verifikat. Keys seen more than once are removed and recorded as ambiguous.
|
||||
*/
|
||||
byPeriodKey: Map<string, string>
|
||||
/** "series|number" → every entry carrying it, across all fiscal years. */
|
||||
bySourceRef: Map<string, VoucherRow[]>
|
||||
/** number → every entry carrying it in ANY series, for series-less filenames. */
|
||||
byNumber: Map<number, VoucherRow[]>
|
||||
ambiguousPeriodKeys: Set<string>
|
||||
}
|
||||
|
||||
/** Find the fiscal period whose date range contains a given date. */
|
||||
export function periodIdForDate(periods: FiscalPeriodRow[], date: string): string | null {
|
||||
const period = periods.find((p) => p.period_start <= date && date <= p.period_end)
|
||||
return period?.id ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Series comparison is case-insensitive on both sides of the join. SIE writes
|
||||
* series uppercase in practice but the spec does not require it, and a filename
|
||||
* is whatever the user's export tool produced: `a31.pdf` must still find `A31`.
|
||||
*/
|
||||
function normalizeSeries(series: string): string {
|
||||
return series.trim().toUpperCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory key for a verifikat: fiscal period + series + number. Scoping by
|
||||
* period is essential: source systems restart voucher numbering every year, so
|
||||
* `A31` alone is not unique once several years are migrated.
|
||||
*/
|
||||
export function voucherKey(periodId: string, series: string, number: number): string {
|
||||
return `${periodId}|${normalizeSeries(series)}|${number}`
|
||||
}
|
||||
|
||||
/** "series|number", the period-agnostic key. */
|
||||
export function sourceRefKey(series: string, number: number): string {
|
||||
return `${normalizeSeries(series)}|${number}`
|
||||
}
|
||||
|
||||
export function buildVoucherIndex(vouchers: VoucherRow[]): VoucherIndex {
|
||||
const byPeriodKey = new Map<string, string>()
|
||||
const bySourceRef = new Map<string, VoucherRow[]>()
|
||||
const byNumber = new Map<number, VoucherRow[]>()
|
||||
const ambiguousPeriodKeys = new Set<string>()
|
||||
|
||||
// Get-or-create + push, never copy: the provider sweep indexes every
|
||||
// migrated entry in the company, and per-row array copies turn that O(n²).
|
||||
const appendTo = <K,>(map: Map<K, VoucherRow[]>, key: K, row: VoucherRow) => {
|
||||
const list = map.get(key)
|
||||
if (list) list.push(row)
|
||||
else map.set(key, [row])
|
||||
}
|
||||
|
||||
for (const v of vouchers) {
|
||||
if (v.source_voucher_series == null || v.source_voucher_number == null) continue
|
||||
|
||||
appendTo(bySourceRef, sourceRefKey(v.source_voucher_series, v.source_voucher_number), v)
|
||||
appendTo(byNumber, v.source_voucher_number, v)
|
||||
|
||||
const key = voucherKey(v.fiscal_period_id, v.source_voucher_series, v.source_voucher_number)
|
||||
if (byPeriodKey.has(key)) {
|
||||
// Two entries share one source ref inside one fiscal year: neither can be
|
||||
// chosen without guessing, so drop both rather than attach blind.
|
||||
byPeriodKey.delete(key)
|
||||
ambiguousPeriodKeys.add(key)
|
||||
} else if (!ambiguousPeriodKeys.has(key)) {
|
||||
byPeriodKey.set(key, v.id)
|
||||
}
|
||||
}
|
||||
|
||||
return { byPeriodKey, bySourceRef, byNumber, ambiguousPeriodKeys }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a ref that carries date information. Returns undefined when the ref
|
||||
* matches nothing or is ambiguous: callers count it as unmatched, never guess.
|
||||
*/
|
||||
export function resolveDatedRef(
|
||||
index: VoucherIndex,
|
||||
periods: FiscalPeriodRow[],
|
||||
ref: DatedSourceVoucherRef,
|
||||
): string | undefined {
|
||||
if (ref.dateTo) {
|
||||
// The source pinned the attachment to a financial year, not a day: accept
|
||||
// it only when exactly one migrated verifikat in that window carries the ref.
|
||||
const candidates = (index.bySourceRef.get(sourceRefKey(ref.series, ref.number)) ?? []).filter(
|
||||
(voucher) => ref.date <= voucher.entry_date && voucher.entry_date <= ref.dateTo!,
|
||||
)
|
||||
return candidates.length === 1 ? candidates[0].id : undefined
|
||||
}
|
||||
|
||||
const periodId = periodIdForDate(periods, ref.date)
|
||||
return periodId ? index.byPeriodKey.get(voucherKey(periodId, ref.series, ref.number)) : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Every migrated verifikat carrying a source ref, across all fiscal years.
|
||||
* A filename gives no date, so a ref that hits several years is genuinely
|
||||
* ambiguous and the caller must ask instead of picking one.
|
||||
*/
|
||||
export function candidatesForRef(index: VoucherIndex, ref: SourceVoucherRef): VoucherRow[] {
|
||||
return index.bySourceRef.get(sourceRefKey(ref.series, ref.number)) ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* Candidates for a filename that carried a number but no series (`31.pdf`).
|
||||
* Searches every series, so this is only usable when it yields exactly one hit,
|
||||
* and the caller must still make a human confirm it.
|
||||
*/
|
||||
export function candidatesForNumber(index: VoucherIndex, number: number): VoucherRow[] {
|
||||
return index.byNumber.get(number) ?? []
|
||||
}
|
||||
|
||||
// Both selects are written out inline at their call site rather than hoisted
|
||||
// into a shared constant. tests/schema/no-phantom-columns.test.ts resolves
|
||||
// column lists by scanning the AST for string literals passed to .select();
|
||||
// a constant is opaque to it, and hiding this query surface would drop all
|
||||
// eight journal_entries columns out of the phantom-column net on the one code
|
||||
// path that writes irreversible räkenskapsinformation links.
|
||||
|
||||
/**
|
||||
* Statuses a resolved verifikat may have to receive underlag. Posted is the
|
||||
* normal case; reversed stays in, because a storno'd original remains
|
||||
* räkenskapsinformation and its underlag belongs on it. Draft and cancelled
|
||||
* are excluded: the SIE import RPC posts every entry inside its own
|
||||
* transaction, so a draft with a source ref should be unobservable, but the
|
||||
* link is irreversible, and an invariant that lives in another file is not an
|
||||
* invariant this module may lean on.
|
||||
*/
|
||||
const ATTACHABLE_STATUSES = ['posted', 'reversed']
|
||||
|
||||
/**
|
||||
* All entries that carry a source voucher ref, resolution columns only.
|
||||
*
|
||||
* A stable `.order('id')` is required: fetchAllRows pages with `.range()`, and
|
||||
* PostgREST paging without a deterministic order can skip or repeat rows once
|
||||
* the table exceeds one page (journal_entries crosses 1000 after a couple of
|
||||
* migrated years), which would defeat both resolution and any dedup built on it.
|
||||
*/
|
||||
export async function fetchSourceRefVouchers(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<VoucherRow[]> {
|
||||
return fetchAllRows<VoucherRow>(({ from, to }) =>
|
||||
supabase
|
||||
.from('journal_entries')
|
||||
.select('id, fiscal_period_id, entry_date, source_voucher_series, source_voucher_number')
|
||||
.eq('company_id', companyId)
|
||||
.not('source_voucher_number', 'is', null)
|
||||
.in('status', ATTACHABLE_STATUSES)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
}
|
||||
|
||||
/** PostgREST puts `.in()` lists in the URL, so the filter is chunked. */
|
||||
const REF_QUERY_CHUNK = 200
|
||||
|
||||
/**
|
||||
* Only the entries that could match one of `numbers`, rather than every
|
||||
* migrated entry in the company. The filename flow resolves a handful of refs
|
||||
* per request and would otherwise pull thousands of rows into memory each time.
|
||||
* Series is filtered in memory afterwards: it is case-insensitive here and a
|
||||
* series-less filename has to search across all of them anyway.
|
||||
*
|
||||
* Carries the display columns too, because this is the read behind a plan the
|
||||
* user has to be able to read before approving it.
|
||||
*
|
||||
* `fiscalPeriodId` narrows the read at the DB. It is an OPTIMIZATION, not the
|
||||
* enforcement: buildUnderlagPlan re-filters the rows in memory before indexing,
|
||||
* and that in-memory filter is the line the year guarantee rests on.
|
||||
*/
|
||||
export async function fetchVouchersForNumbers(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
numbers: number[],
|
||||
fiscalPeriodId?: string,
|
||||
): Promise<VoucherRow[]> {
|
||||
const unique = [...new Set(numbers)]
|
||||
if (unique.length === 0) return []
|
||||
|
||||
const rows: VoucherRow[] = []
|
||||
for (let i = 0; i < unique.length; i += REF_QUERY_CHUNK) {
|
||||
const chunk = unique.slice(i, i + REF_QUERY_CHUNK)
|
||||
const chunkRows = await fetchAllRows<VoucherRow>(({ from, to }) => {
|
||||
let query = supabase
|
||||
.from('journal_entries')
|
||||
.select(
|
||||
'id, fiscal_period_id, entry_date, description, voucher_series, voucher_number, source_voucher_series, source_voucher_number',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.in('source_voucher_number', chunk)
|
||||
.in('status', ATTACHABLE_STATUSES)
|
||||
if (fiscalPeriodId) query = query.eq('fiscal_period_id', fiscalPeriodId)
|
||||
return query.order('id', { ascending: true }).range(from, to)
|
||||
})
|
||||
rows.push(...chunkRows)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a fiscal year holds any SIE-imported entry carrying a source ref.
|
||||
* Distinguishes "the filenames are wrong" from "this year was never imported
|
||||
* from SIE", which are the same empty plan on screen but different problems.
|
||||
*/
|
||||
export async function hasSourceRefVouchers(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fiscalPeriodId: string,
|
||||
): Promise<boolean> {
|
||||
const { count, error } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('fiscal_period_id', fiscalPeriodId)
|
||||
.not('source_voucher_number', 'is', null)
|
||||
|
||||
if (error) throw new Error(`Failed to count migrated vouchers: ${error.message}`)
|
||||
return (count ?? 0) > 0
|
||||
}
|
||||
|
||||
export async function fetchFiscalPeriods(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<FiscalPeriodRow[]> {
|
||||
return fetchAllRows<FiscalPeriodRow>(({ from, to }) =>
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, period_start, period_end, is_closed, locked_at')
|
||||
.eq('company_id', companyId)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
}
|
||||
|
||||
/** Our own label for a verifikat (`A47`), as opposed to the source label. */
|
||||
export function voucherLabel(entry: Pick<VoucherRow, 'voucher_series' | 'voucher_number'>): string | null {
|
||||
return entry.voucher_series && entry.voucher_number != null
|
||||
? `${entry.voucher_series}${entry.voucher_number}`
|
||||
: null
|
||||
}
|
||||
|
||||
/** The label the source system used (`A31`), which is what filenames carry. */
|
||||
export function sourceVoucherLabel(
|
||||
entry: Pick<VoucherRow, 'source_voucher_series' | 'source_voucher_number'>,
|
||||
): string | null {
|
||||
return entry.source_voucher_series && entry.source_voucher_number != null
|
||||
? `${entry.source_voucher_series}${entry.source_voucher_number}`
|
||||
: null
|
||||
}
|
||||
Reference in New Issue
Block a user