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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user