Files
accounted/lib/parties/ledger-key.ts
T
Jakob Wennberg fc04578818 feat(parties): suggestion pipeline from ledger keys and linked documents (#2172)
* feat(parties): phase 1 substrate, one party per counterpart

Adds the identity layer above customers and suppliers, which keep their
tables and every foreign key and gain a nullable party_id.

- parties: company-scoped identity with status (suggested | confirmed),
  kind, alias keys, origin and merged_into. One live party per org number
  and company, enforced by a partial unique index; merged losers leave the
  index so a merge can be undone. This is the unique key the
  duplicate-invoice guard has lacked, since suppliers never had one.
- party_facts: statements with a source, a rank (preferred | normal |
  deprecated) and two time axes, never overwritten.
- party_identities: bankgiro, plusgiro, IBAN and friends per party, with
  seen and paid counts and a known | unverified status.
- party_decisions: every human action on a party as a labelled example.
- normalize_org_number(text): SQL mirror of lib/invariants/org-number.ts
  (strip separators, drop the century on 12 digits, Luhn check, 10 digits).
- ensure_party(): find by org number inside the company, else create.
  Name-only rows never merge at insert time; a name merge is a recorded
  human decision.
- Backfill: one party per existing supplier and customer, merged on org
  number, suppliers first so both roles land on one party.
- Archive contract: the four tables are master data in the full archive.

Observed parties (keys derived from voucher and bank text) are not stored;
they stay computed by the ledger-context RPC. No posted entry is touched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(parties): observed parties from voucher text, ledger_key and its mirror

Migrants arrive with vouchers, not bank transactions, so the bank-keyed
ledger context is empty for them. This adds the description-keyed twin.

- public.ledger_key(text): legibility key on top of the frozen
  normalize_counterparty_key mirror: strips AP-register prefixes (levfakt,
  leverantörsfaktura från N, levbet, faktura, kvitto, utgift), the supplier
  number that follows them, and trailing 1-3 digit runs, never "inköp".
  Mirrored by lib/parties/ledger-key.ts; the pair is pinned by a shared
  fixture list in the pg test.
- public.get_observed_parties(company, from_date, limit): posted vouchers
  grouped by ledger_key(description) with occurrences, variants, expense
  and revenue SEK from the lines, first/last seen, median cadence and the
  Laplace-smoothed dominant result account. Excludes storno, opening
  balance, year-end and VAT settlement, and vouchers that carry a bank
  merchant name (those stay with get_ledger_deep_context). SECURITY
  INVOKER, so RLS scopes it. Never stored.
- lib/parties/classify.ts: the deterministic pre-classifier moved out of
  the evaluation script so product and evaluation share one implementation
  (0.965 agreement with the founder labels, party recall 0.99).
- lib/parties/observed.ts: RPC wrapper that classifies each row and
  derives a display rhythm from the cadence.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): tenant-safe composite foreign keys on every party link

Facts, identities, decisions, customers.party_id, suppliers.party_id and
parties.merged_into now reference parties(id, company_id), so a row can
only point at a party in its own company. ON DELETE SET NULL names
party_id so role rows keep their company_id. Adds a pg-real test that
rejects every cross-company link and checks company_id survives a party
delete.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(parties): suggestion pipeline from ledger keys and linked documents

Phase 1c of the parties plan. Fills a migrant's register with suggested
parties from what the ledger already knows, never as facts:

- get_ledger_key_evidence(company): hard keys per ledger_key from the
  documents linked to posted vouchers (org number via normalize_org_number,
  VAT, bankgiro, plusgiro, printed name). Documents whose supplier org is
  the company's own are the company's sales invoices and only count in
  self_docs.
- apply_party_suggestions(company, user, items): upserts suggestions.
  Attaches by explicit party_id, org number or an exact alias key; never
  by name. Identities become known at two sightings. Idempotent.
- decide_parties(company, user, ids, kind, note): bulk confirm or dismiss
  with one party_decisions row each.
- parties.suggested_reason: the evidence summary the queue shows per row.
- lib/parties/suggest.ts: buildSuggestions (pure) and
  suggestPartiesForCompany. Keys that mix two org numbers keep neither the
  hard key nor identities; same-core live parties are reported as
  similar_to for a person to decide. coreKey() moves into ledger-key.ts.

55 unit tests and 14 pg-real tests pass locally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(parties): decide_parties dismisses suggested parties only

Dismiss is the queue's answer to a suggestion; a confirmed party is never
archived through it. Superagent P2 on #2172.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(parties): type the rpc mock with its args so the ratchet stays clean

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 18:18:12 +02:00

57 lines
2.3 KiB
TypeScript

import { normalizeCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
/**
* Legibility key for a voucher description: the identity string an observed
* party is grouped and displayed by.
*
* Built on top of normalizeCounterpartyName() (mirrored in SQL by
* normalize_counterparty_key) and adds the stages the AP registers of Fortnox,
* Visma and BL make necessary: "Levfakt BEIJER BYGGMATERIAL AB (2089)" and
* "Levfakt Beijer Byggmaterial AB, 097" must land on one key,
* "Leverantörsfaktura från 18 Loopia" on "loopia".
*
* Mirrored in SQL by public.ledger_key() (migration 20260902170000) and pinned
* by tests/pg/observed-parties-rpc.pg.test.ts. Change both or neither.
*
* "inköp" is deliberately not a stripped prefix: it turns the generic
* "inköp av varor" into a vendor-looking "varor" (measured 2026-07-27).
*/
const AP_PREFIX = /^(levfakt|levfkt|leverantörsfaktura från|leverantörsfaktura|levbet|faktura|kvitto|utgift)\s+/
const LEADING_SUPPLIER_NUMBER = /^\d{1,5}\s+/
const TRAILING_SHORT_DIGITS = /(\s+\d{1,3})+$/
export function ledgerKey(raw: string | null | undefined): string {
const k = normalizeCounterpartyName(raw ?? '')
if (!k) return ''
const stripped = k
.replace(AP_PREFIX, '')
.replace(LEADING_SUPPLIER_NUMBER, '')
.replace(TRAILING_SHORT_DIGITS, '')
.replace(/\s+/g, ' ')
.trim()
return stripped === '' ? k : stripped
}
const CORE_AP_PREFIX = /^(levfakt|levfkt|lev\.?fakt\.?|leverantörsfaktura från|leverantörsfaktura|levbet\.?|kvitto|faktura|utgift|inköp)\s+/
const CORE_LEGAL_FORM = /\b(ab|aktiebolag|hb|kb|sverige|sweden|ltd|limited|oy|gmbh|inc|sarl|publ|filial)\b/g
/**
* The "core" of a key: what is left when AP prefixes, digit runs and legal
* form suffixes are gone. Two keys with one core are the same trade name,
* which is NOT the same party (Fortnox AB and Fortnox Finans AB share one),
* so the core only ever ranks or annotates candidates; it never merges.
* Measured on the document-anchored gold set 2026-09-02: pair precision
* 0.909, recall 0.776 (scripts/parties/README.md).
*/
export function coreKey(key: string): string {
return key
.toLowerCase()
.replace(CORE_AP_PREFIX, '')
.replace(/\b\d+\b/g, '')
.replace(CORE_LEGAL_FORM, '')
.replace(/[^a-zåäöé ]+/g, ' ')
.split(/\s+/)
.filter(Boolean)
.join(' ')
}