feat(parties): Förslag från bokföringen, confirmed straight into Leverantörer and Kunder (#2206)
* feat(parties): Kontakter register, suggestion queue, dossier and merge Phase 1's two surfaces on top of the parties substrate: - /parties page: one list with the five-way switch (Alla, Kunder, Leverantörer, Förslag, Bara i bokföringen), search, a 12-month/all period picker, and at most one attention line. Confirmed rows show roles as muted text, rhythm, underlag, dominant account and money. Observed rows are computed and never stored; a generic band keeps unattributed spend visible. - Suggestion queue: a reason per row, hard-key rows pre-ticked, bulk confirm behind one dialog, dismiss on hover, undo on the toast. - Dossier slide-over: Pengar, Bokföring, Vad Accounted vet (facts and identities with source and count), Underlag och verifikat, Historik. - Merge dialog with a visible, swappable survivor and undo. - API: GET /api/parties, GET /api/parties/[id], POST suggest, decide, decide/undo, merge, merge/undo (withRouteContext, Zod, 15 tests). - Migration 20260903090000: decide_parties snapshots the reason it clears; undo_party_decisions reverses confirm/dismiss within 30 days; decision kind 'undo'. - The pipeline runs after SIE import and provider migration (non-blocking) so a migrant's register is full on arrival. - Nav entry under Register; sv/en strings. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): pass explicit interpolation values to next-intl next build's type check rejects a typed interface where the translator wants an index-signature record. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): retry label on the load-failed state Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): hard keys for companies without org number, readable names, look-alikes at read time - get_ledger_key_evidence dropped every document for a company whose own org number is NULL (the self check compared against NULL). Replaced in 20260903100000 with a coalesced comparison; pg test covers it. - Display names come from the printed name on documents, otherwise from the voucher text with the AP/AR prefix and supplier number removed. - Look-alike parties (same core, or one core extending the other by whole words: Fortnox / Fortnox Finans) are detected when the register is read, never stored, and feed the Dubblett? chip and the merge dialog. - Queue shows Intäkt beside Kostnad; dossier hides zero money rows and formats bankgiro/plusgiro; merge dialog cancels with Avbryt; no synchronous setState inside effects. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): link every new supplier and customer to a party on write The backfill covered the rows that existed on 2026-09-02; 108 rows created since had no party and never reached the register. A BEFORE INSERT/UPDATE trigger on customers and suppliers now calls ensure_party on every write path at once: find-or-create by org number inside the company, never by name; a private customer gets a kind=person party without any number; a nameless row stays unlinked; a foreign party id is refused with the same error as the composite foreign key; a link to a merged party follows the chain to the survivor; the clear that ON DELETE SET NULL performs is kept. ensure_party lets the trigger act for the row's owner (pg_trigger_depth() > 0); the RPC path is unchanged. The migration also links the rows created since the backfill. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): dossier hides dismissed parties and follows merges to the survivor The register hid archived parties while the dossier still served them by id, and a merged party's dossier pointed at a dead row. Superagent P2 on #2206; three unit tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the role-link migration past main's 20260903110000 Two files with one version would collide in schema_migrations. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): confirm suggestions into Leverantörer and Kunder, no third noun Founder decision after the walkthrough: users know two words. The page becomes the queue 'Förslag från bokföringen' with 'Bara i bokföringen' beside it; the Kontakter nav entry and the Alla/Kunder/Leverantörer views go. Each suggestion shows what it becomes (Blir), read from the ledger side and changeable per row; confirming calls promote_parties, which creates the supplier and/or customer row from the party's facts, never a duplicate, and is undoable for 30 days through undo_party_promotions (the created rows are archived, the party returns to the queue). Leverantörer and Kunder carry the one attention line that leads here. The dossier offers Lägg upp som leverantör / som kund. Migration 20260903130000, 5 pg tests, route and unit tests updated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): write bankgiro and plusgiro the way the supplier form does Identities are stored as digits; suppliers carry 5317-0900. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the four queue migrations past main's 20260903170000 Main merged 20260903120000_skattekonto_transactions_realtime_publication with the same version as the role-link trigger; the preview database refused the duplicate key. All four now sit after main's newest so the set applies in one ordered run on prod. 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>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
e2d38b0ab3
commit
b996da60ee
@@ -3993,3 +3993,43 @@ export const SalesOrderListQuerySchema = z.object({
|
||||
customer_id: uuid.optional(),
|
||||
q: z.string().max(200).optional(),
|
||||
})
|
||||
|
||||
// ── Parties (Kontakter register) ───────────────────────────────────────────
|
||||
|
||||
export const PartiesRegisterQuerySchema = z.object({
|
||||
view: z.enum(['suggested', 'observed']).optional(),
|
||||
q: z.string().max(120).optional(),
|
||||
period: z.enum(['12m', 'all']).optional(),
|
||||
})
|
||||
|
||||
export const PartyDecideSchema = z.object({
|
||||
partyIds: z.array(uuid).min(1).max(500),
|
||||
kind: z.enum(['confirm', 'dismiss']),
|
||||
note: z.string().max(500).optional(),
|
||||
})
|
||||
|
||||
export const PartyPromoteSchema = z.object({
|
||||
items: z
|
||||
.array(
|
||||
z.object({
|
||||
partyId: uuid,
|
||||
roles: z.array(z.enum(['supplier', 'customer'])).min(1).max(2),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(500),
|
||||
})
|
||||
|
||||
export const PartyUndoDecisionsSchema = z.object({
|
||||
partyIds: z.array(uuid).min(1).max(500),
|
||||
})
|
||||
|
||||
export const PartyMergeSchema = z.object({
|
||||
survivorId: uuid,
|
||||
mergedIds: z.array(uuid).min(1).max(50),
|
||||
note: z.string().max(500).optional(),
|
||||
})
|
||||
|
||||
export const PartyUndoMergeSchema = z.object({
|
||||
decisionId: uuid,
|
||||
})
|
||||
|
||||
@@ -39,6 +39,7 @@ import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { classifyAccount } from '@/lib/bookkeeping/account-classifier'
|
||||
import { computeSRUCode } from '@/lib/bookkeeping/bas-data/sru-mapping'
|
||||
import { populateTemplatesFromSieVouchers } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { suggestPartiesForCompany } from '@/lib/parties/suggest'
|
||||
import { markEntriesNoDocRequired } from '@/lib/bookkeeping/no-doc-required'
|
||||
import { monthsBetween, parseDateParts } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import { findUntransferredResults } from '@/lib/reports/imbalance-diagnosis'
|
||||
@@ -2992,6 +2993,17 @@ export async function executeSIEImport(
|
||||
}
|
||||
}
|
||||
|
||||
// Fill the Kontakter register from the imported vouchers (non-blocking):
|
||||
// suggested parties only, nothing is confirmed on the user's behalf.
|
||||
if (result.success && parsed.vouchers.length > 0) {
|
||||
try {
|
||||
const summary = await suggestPartiesForCompany(supabase, companyId, userId)
|
||||
console.info(`[sie-import] party suggestions: ${summary.created} new, ${summary.attached} attached, ${summary.skipped} skipped`)
|
||||
} catch (partyError) {
|
||||
console.error('[sie-import] Failed to suggest parties:', partyError)
|
||||
}
|
||||
}
|
||||
|
||||
// Opt-in: mark imported verifikat as "Inget underlag krävs" (non-blocking).
|
||||
// Migrated vouchers carry their underlag in the source system, so the user
|
||||
// can choose to keep all of them out of "Att hantera: saknade underlag" in
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { defaultRoles, getDossier } from '../register'
|
||||
import type { LedgerStats } from '../register'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const PARTY = '11111111-1111-4111-8111-111111111111'
|
||||
const SURVIVOR = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
function row(over: Record<string, unknown>) {
|
||||
return {
|
||||
id: PARTY,
|
||||
display_name: 'Loopia AB',
|
||||
legal_name: null,
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
kind: 'company',
|
||||
status: 'suggested',
|
||||
alias_keys: ['loopia'],
|
||||
suggested_reason: null,
|
||||
created_at: '2026-09-03T00:00:00Z',
|
||||
merged_into: null,
|
||||
archived_at: null,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('getDossier', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('hides a dismissed (archived) party like the register does', async () => {
|
||||
enqueue({ data: row({ archived_at: '2026-09-03T10:00:00Z' }) })
|
||||
expect(await getDossier(supabase as never, 'company-1', PARTY)).toBeNull()
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('follows a merged party to its survivor', async () => {
|
||||
enqueue({ data: row({ merged_into: SURVIVOR }) })
|
||||
enqueue({ data: SURVIVOR }) // canonical_party_id
|
||||
enqueue({ data: null }) // survivor lookup: absent, so the walk ends here
|
||||
expect(await getDossier(supabase as never, 'company-1', PARTY)).toBeNull()
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('canonical_party_id', { p_party_id: PARTY })
|
||||
expect(supabase.from).toHaveBeenCalledTimes(2)
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(2, 'parties')
|
||||
})
|
||||
|
||||
it('returns null for an unknown id without touching anything else', async () => {
|
||||
enqueue({ data: null })
|
||||
expect(await getDossier(supabase as never, 'company-1', PARTY)).toBeNull()
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('defaultRoles', () => {
|
||||
const stats = (over: Partial<LedgerStats>): LedgerStats => ({
|
||||
occurrences: 3,
|
||||
expenseSek: 0,
|
||||
revenueSek: 0,
|
||||
firstSeen: null,
|
||||
lastSeen: null,
|
||||
cadenceDays: null,
|
||||
rhythm: null,
|
||||
dominantAccount: null,
|
||||
dominantShare: null,
|
||||
variants: [],
|
||||
...over,
|
||||
})
|
||||
|
||||
it('reads the ledger side', () => {
|
||||
expect(defaultRoles(stats({ expenseSek: 1000 }))).toEqual(['supplier'])
|
||||
expect(defaultRoles(stats({ revenueSek: 1000 }))).toEqual(['customer'])
|
||||
expect(defaultRoles(stats({ expenseSek: 10, revenueSek: 10 }))).toEqual(['supplier', 'customer'])
|
||||
})
|
||||
|
||||
it('falls back to the dominant account, then to supplier', () => {
|
||||
expect(defaultRoles(stats({ dominantAccount: '3011' }))).toEqual(['customer'])
|
||||
expect(defaultRoles(stats({ dominantAccount: '6212' }))).toEqual(['supplier'])
|
||||
expect(defaultRoles(null)).toEqual(['supplier'])
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { coreKey } from '../ledger-key'
|
||||
import { coreKey, displayNameFromVoucherText } from '../ledger-key'
|
||||
import type { ObservedParty } from '../observed'
|
||||
import { buildSuggestions, suggestPartiesForCompany, type ExistingParty, type LedgerKeyEvidence } from '../suggest'
|
||||
|
||||
@@ -38,6 +38,17 @@ describe('coreKey', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('displayNameFromVoucherText', () => {
|
||||
it('drops AP/AR prefixes and supplier numbers but keeps casing and legal form', () => {
|
||||
expect(displayNameFromVoucherText('Levfakt BEIJER BYGGMATERIAL AB (2089)')).toBe('BEIJER BYGGMATERIAL AB')
|
||||
expect(displayNameFromVoucherText('Levfakt Beijer Byggmaterial AB, 097')).toBe('Beijer Byggmaterial AB')
|
||||
expect(displayNameFromVoucherText('Kundbet Acme Konsult AB')).toBe('Acme Konsult AB')
|
||||
expect(displayNameFromVoucherText('Leverantörsfaktura från 18 Loopia')).toBe('Loopia')
|
||||
expect(displayNameFromVoucherText('UBER *TRIP HELP.UBER.COM')).toBe('UBER *TRIP HELP.UBER.COM')
|
||||
expect(displayNameFromVoucherText('Inköp av varor')).toBe('Inköp av varor')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSuggestions', () => {
|
||||
it('skips keys the pre-classifier does not call party', () => {
|
||||
const r = buildSuggestions({
|
||||
@@ -192,3 +203,23 @@ describe('suggestPartiesForCompany', () => {
|
||||
await expect(suggestPartiesForCompany({ rpc } as never, 'co', 'user')).rejects.toThrow(/get_observed_parties failed: boom/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('similarAmong', () => {
|
||||
it('pairs same-core and whole-word-extended names, never unrelated ones', async () => {
|
||||
const { similarAmong } = await import('../register')
|
||||
const m = similarAmong([
|
||||
{ id: 'a', display_name: 'Fortnox AB', alias_keys: ['fortnox'] },
|
||||
{ id: 'b', display_name: 'Fortnox Finans AB', alias_keys: ['fortnox finans'] },
|
||||
{ id: 'c', display_name: 'Rikshem Uppsala KB', alias_keys: [] },
|
||||
{ id: 'd', display_name: 'Rikshem', alias_keys: [] },
|
||||
{ id: 'e', display_name: 'Fortum Markets AB', alias_keys: [] },
|
||||
{ id: 'f', display_name: 'Levfakt Beijer Byggmaterial AB 2089', alias_keys: ['beijer byggmaterial'] },
|
||||
{ id: 'g', display_name: 'BEIJER BYGGMATERIAL', alias_keys: [] },
|
||||
])
|
||||
expect(m.get('a')!.map((s) => s.id)).toEqual(['b'])
|
||||
expect(m.get('b')!.map((s) => s.id)).toEqual(['a'])
|
||||
expect(m.get('c')!.map((s) => s.id)).toEqual(['d'])
|
||||
expect(m.get('e')).toEqual([])
|
||||
expect(m.get('f')!.map((s) => s.id)).toEqual(['g'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -54,3 +54,19 @@ export function coreKey(key: string): string {
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
const DISPLAY_PREFIX =
|
||||
/^(levfakt|levfkt|lev\.?fakt\.?|leverantörsfaktura från\s+\d*|leverantörsfaktura|levbet\.?|kundbet\.?|kundfaktura|kundfakt|inbetalning från|inbetalning|utbetalning till|utbetalning|betalning till|betalning|faktura från|faktura|kvitto|utgift)\s+/i
|
||||
const DISPLAY_SUFFIX = /(\s*[,(]\s*\d{1,6}\s*\)?|\s+\d{1,4})+$/
|
||||
|
||||
/**
|
||||
* A display name from raw voucher text: the AP/AR prefix and the supplier
|
||||
* number go, the casing and the legal form stay. "Levfakt BEIJER
|
||||
* BYGGMATERIAL AB (2089)" reads "BEIJER BYGGMATERIAL AB"; "Kundbet Acme
|
||||
* Konsult AB" reads "Acme Konsult AB". Used only when no document carries
|
||||
* a printed name; nothing here is generated, only removed.
|
||||
*/
|
||||
export function displayNameFromVoucherText(raw: string): string {
|
||||
const cleaned = raw.trim().replace(DISPLAY_PREFIX, '').replace(DISPLAY_SUFFIX, '').trim()
|
||||
return cleaned.length >= 2 ? cleaned : raw.trim()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
/**
|
||||
* Parties, phase 1: the read model behind "Förslag från bokföringen".
|
||||
*
|
||||
* The user's registers are Leverantörer and Kunder (founder decision
|
||||
* 2026-09-03: no third noun). This model serves the queue in front of them:
|
||||
* suggested parties with a reason per row and the role each will become,
|
||||
* and observed parties the ledger names but nothing owns yet. Money, rhythm
|
||||
* and the dominant account come from get_observed_parties joined through the
|
||||
* party's alias keys, so a suggestion shows the numbers a migrant saw in
|
||||
* the reveal. Confirmed parties are read here only for counts and for the
|
||||
* dossier; the user sees them as suppliers and customers.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { coreKey } from './ledger-key'
|
||||
import { getObservedParties, type ObservedParty } from './observed'
|
||||
import type { SuggestionReason } from './suggest'
|
||||
|
||||
export type RegisterView = 'suggested' | 'observed'
|
||||
export type PartyRole = 'supplier' | 'customer'
|
||||
export type RegisterPeriod = '12m' | 'all'
|
||||
|
||||
export interface PartyRoleLink {
|
||||
customerId: string | null
|
||||
supplierId: string | null
|
||||
}
|
||||
|
||||
export interface LedgerStats {
|
||||
occurrences: number
|
||||
expenseSek: number
|
||||
revenueSek: number
|
||||
firstSeen: string | null
|
||||
lastSeen: string | null
|
||||
cadenceDays: number | null
|
||||
rhythm: ObservedParty['rhythm']
|
||||
dominantAccount: string | null
|
||||
dominantShare: number | null
|
||||
variants: string[]
|
||||
}
|
||||
|
||||
export interface RegisterRow {
|
||||
id: string
|
||||
displayName: string
|
||||
orgNumber: string | null
|
||||
kind: string
|
||||
status: 'confirmed' | 'suggested'
|
||||
roles: PartyRoleLink
|
||||
stats: LedgerStats | null
|
||||
/** Sales invoices for a customer role; supplier invoices for a supplier role. */
|
||||
invoiceCount: number
|
||||
reason: SuggestionReason | null
|
||||
/** Live parties sharing this party's core name: a merge question, never a merge. */
|
||||
similar: Array<{ id: string; displayName: string }>
|
||||
/** What confirming this suggestion creates, read from which side of the ledger it sits on. */
|
||||
defaultRoles: PartyRole[]
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface ObservedRow {
|
||||
key: string
|
||||
name: string
|
||||
stats: LedgerStats
|
||||
label: ObservedParty['label']
|
||||
}
|
||||
|
||||
export interface RegisterCounts {
|
||||
suggested: number
|
||||
/** Suggestions whose default role includes supplier / customer (a row can count in both). */
|
||||
suggestedSuppliers: number
|
||||
suggestedCustomers: number
|
||||
observed: number
|
||||
confirmed: number
|
||||
}
|
||||
|
||||
export interface Register {
|
||||
counts: RegisterCounts
|
||||
rows: RegisterRow[]
|
||||
observed: ObservedRow[]
|
||||
/** Observed keys the pre-classifier calls a category: unattributed spend. */
|
||||
generic: { count: number; expenseSek: number; examples: string[] }
|
||||
period: RegisterPeriod
|
||||
}
|
||||
|
||||
interface PartyRecord {
|
||||
id: string
|
||||
display_name: string
|
||||
org_number: string | null
|
||||
kind: string
|
||||
status: 'confirmed' | 'suggested'
|
||||
alias_keys: string[]
|
||||
suggested_reason: SuggestionReason | null
|
||||
created_at: string
|
||||
archived_at?: string | null
|
||||
}
|
||||
|
||||
export function statsFrom(o: ObservedParty): LedgerStats {
|
||||
return {
|
||||
occurrences: o.occurrences,
|
||||
expenseSek: Number(o.expense_sek) || 0,
|
||||
revenueSek: Number(o.revenue_sek) || 0,
|
||||
firstSeen: o.first_seen ?? null,
|
||||
lastSeen: o.last_seen ?? null,
|
||||
cadenceDays: o.cadence_days,
|
||||
rhythm: o.rhythm,
|
||||
dominantAccount: o.dominant_account_number,
|
||||
dominantShare: o.dominant_account_share,
|
||||
variants: o.variants ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
/** Sum the observed keys a party owns into one stats block. */
|
||||
export function mergeStats(parts: ObservedParty[]): LedgerStats | null {
|
||||
if (parts.length === 0) return null
|
||||
const sorted = [...parts].sort((a, b) => b.occurrences - a.occurrences)
|
||||
const lead = statsFrom(sorted[0]!)
|
||||
const out: LedgerStats = { ...lead, variants: [] }
|
||||
let first: string | null = null
|
||||
let last: string | null = null
|
||||
for (const p of sorted) {
|
||||
if (p !== sorted[0]) {
|
||||
out.occurrences += p.occurrences
|
||||
out.expenseSek += Number(p.expense_sek) || 0
|
||||
out.revenueSek += Number(p.revenue_sek) || 0
|
||||
}
|
||||
if (p.first_seen && (!first || p.first_seen < first)) first = p.first_seen
|
||||
if (p.last_seen && (!last || p.last_seen > last)) last = p.last_seen
|
||||
for (const v of p.variants ?? []) if (!out.variants.includes(v)) out.variants.push(v)
|
||||
}
|
||||
out.firstSeen = first
|
||||
out.lastSeen = last
|
||||
out.expenseSek = roundOre(out.expenseSek)
|
||||
out.revenueSek = roundOre(out.revenueSek)
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Same-core parties among the live rows. Read-time, never stored: the
|
||||
* selection eval measured 9% false merges on shared trade names, so this
|
||||
* only ever asks.
|
||||
*/
|
||||
export function similarAmong(parties: Array<{ id: string; display_name: string; alias_keys: string[] }>): Map<string, Array<{ id: string; displayName: string }>> {
|
||||
const byCore = new Map<string, Array<{ id: string; displayName: string }>>()
|
||||
const coresOf = new Map<string, Set<string>>()
|
||||
for (const p of parties) {
|
||||
const cores = new Set<string>()
|
||||
const c = coreKey(p.display_name)
|
||||
if (c) cores.add(c)
|
||||
for (const a of p.alias_keys) {
|
||||
const ac = coreKey(a)
|
||||
if (ac) cores.add(ac)
|
||||
}
|
||||
coresOf.set(p.id, cores)
|
||||
for (const core of cores) byCore.set(core, [...(byCore.get(core) ?? []), { id: p.id, displayName: p.display_name }])
|
||||
}
|
||||
// Cores that extend another core by whole words share its first word:
|
||||
// "fortnox finans" reaches "fortnox" and the other way round.
|
||||
const byFirstWord = new Map<string, string[]>()
|
||||
for (const core of byCore.keys()) {
|
||||
const first = core.split(' ')[0]!
|
||||
byFirstWord.set(first, [...(byFirstWord.get(first) ?? []), core])
|
||||
}
|
||||
const extendsCore = (a: string, b: string) => a === b || a.startsWith(b + ' ') || b.startsWith(a + ' ')
|
||||
const out = new Map<string, Array<{ id: string; displayName: string }>>()
|
||||
for (const p of parties) {
|
||||
const seen = new Set<string>([p.id])
|
||||
const similar: Array<{ id: string; displayName: string }> = []
|
||||
for (const core of coresOf.get(p.id) ?? []) {
|
||||
for (const candidate of byFirstWord.get(core.split(' ')[0]!) ?? []) {
|
||||
if (!extendsCore(core, candidate)) continue
|
||||
for (const other of byCore.get(candidate) ?? []) {
|
||||
if (seen.has(other.id)) continue
|
||||
seen.add(other.id)
|
||||
similar.push(other)
|
||||
}
|
||||
}
|
||||
}
|
||||
out.set(p.id, similar)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Expense side becomes a supplier, revenue side a customer, both sides both.
|
||||
* A row with no money at all (documents only) is a supplier: the documents
|
||||
* that carry hard keys are supplier invoices.
|
||||
*/
|
||||
export function defaultRoles(stats: LedgerStats | null): PartyRole[] {
|
||||
if (!stats) return ['supplier']
|
||||
const roles: PartyRole[] = []
|
||||
if (stats.expenseSek > 0) roles.push('supplier')
|
||||
if (stats.revenueSek > 0) roles.push('customer')
|
||||
if (roles.length === 0) {
|
||||
if (stats.dominantAccount && /^3/.test(stats.dominantAccount)) return ['customer']
|
||||
return ['supplier']
|
||||
}
|
||||
return roles
|
||||
}
|
||||
|
||||
function periodStart(period: RegisterPeriod, now = new Date()): string | null {
|
||||
if (period === 'all') return null
|
||||
const d = new Date(now)
|
||||
d.setUTCFullYear(d.getUTCFullYear() - 1)
|
||||
return d.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function normalizeQuery(q: string | undefined): string {
|
||||
return (q ?? '').trim().toLowerCase()
|
||||
}
|
||||
|
||||
function matches(q: string, ...fields: Array<string | null | undefined>): boolean {
|
||||
if (!q) return true
|
||||
const digits = q.replace(/[^0-9]/g, '')
|
||||
return fields.some((f) => {
|
||||
if (!f) return false
|
||||
const s = f.toLowerCase()
|
||||
if (s.includes(q)) return true
|
||||
return digits.length >= 4 && s.replace(/[^0-9]/g, '').includes(digits)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the register for one company. Reads only; the pipeline that fills the
|
||||
* suggested tier is suggestPartiesForCompany.
|
||||
*/
|
||||
export async function getRegister(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
options: { view?: RegisterView; q?: string; period?: RegisterPeriod } = {},
|
||||
): Promise<Register> {
|
||||
const period = options.period ?? '12m'
|
||||
const q = normalizeQuery(options.q)
|
||||
|
||||
const [parties, customers, suppliers, observed, customerCounts, supplierCounts] = await Promise.all([
|
||||
// Archived (dismissed) parties stay out of the list but keep their keys
|
||||
// claimed, so a dismissed suggestion does not resurface as observed.
|
||||
fetchAllRows<PartyRecord>(({ from, to }) =>
|
||||
supabase
|
||||
.from('parties')
|
||||
.select('id, display_name, org_number, kind, status, alias_keys, suggested_reason, created_at, archived_at')
|
||||
.eq('company_id', companyId)
|
||||
.is('merged_into', null)
|
||||
.order('display_name', { ascending: true })
|
||||
.range(from, to),
|
||||
),
|
||||
fetchAllRows<{ id: string; party_id: string | null }>(({ from, to }) =>
|
||||
supabase.from('customers').select('id, party_id').eq('company_id', companyId).not('party_id', 'is', null).range(from, to),
|
||||
),
|
||||
fetchAllRows<{ id: string; party_id: string | null }>(({ from, to }) =>
|
||||
supabase.from('suppliers').select('id, party_id').eq('company_id', companyId).not('party_id', 'is', null).range(from, to),
|
||||
),
|
||||
getObservedParties(supabase, companyId, { fromDate: periodStart(period), limit: 5000 }),
|
||||
fetchAllRows<{ customer_id: string }>(({ from, to }) =>
|
||||
supabase.from('invoices').select('customer_id').eq('company_id', companyId).not('customer_id', 'is', null).range(from, to),
|
||||
),
|
||||
fetchAllRows<{ supplier_id: string }>(({ from, to }) =>
|
||||
supabase.from('supplier_invoices').select('supplier_id').eq('company_id', companyId).not('supplier_id', 'is', null).range(from, to),
|
||||
),
|
||||
])
|
||||
|
||||
const customerByParty = new Map<string, string>()
|
||||
for (const c of customers) if (c.party_id && !customerByParty.has(c.party_id)) customerByParty.set(c.party_id, c.id)
|
||||
const supplierByParty = new Map<string, string>()
|
||||
for (const s of suppliers) if (s.party_id && !supplierByParty.has(s.party_id)) supplierByParty.set(s.party_id, s.id)
|
||||
const invoicesByCustomer = new Map<string, number>()
|
||||
for (const r of customerCounts) invoicesByCustomer.set(r.customer_id, (invoicesByCustomer.get(r.customer_id) ?? 0) + 1)
|
||||
const invoicesBySupplier = new Map<string, number>()
|
||||
for (const r of supplierCounts) invoicesBySupplier.set(r.supplier_id, (invoicesBySupplier.get(r.supplier_id) ?? 0) + 1)
|
||||
|
||||
const observedByKey = new Map(observed.map((o) => [o.key, o]))
|
||||
const claimedKeys = new Set<string>()
|
||||
const similarById = similarAmong(parties.filter((p) => !p.archived_at))
|
||||
const rows: RegisterRow[] = []
|
||||
for (const p of parties) {
|
||||
const parts: ObservedParty[] = []
|
||||
for (const k of p.alias_keys) {
|
||||
const o = observedByKey.get(k)
|
||||
if (o) {
|
||||
parts.push(o)
|
||||
claimedKeys.add(k)
|
||||
}
|
||||
}
|
||||
if (p.archived_at) continue
|
||||
const customerId = customerByParty.get(p.id) ?? null
|
||||
const supplierId = supplierByParty.get(p.id) ?? null
|
||||
const stats = mergeStats(parts)
|
||||
rows.push({
|
||||
id: p.id,
|
||||
displayName: p.display_name,
|
||||
orgNumber: p.org_number,
|
||||
kind: p.kind,
|
||||
status: p.status,
|
||||
roles: { customerId, supplierId },
|
||||
stats,
|
||||
invoiceCount: (customerId ? (invoicesByCustomer.get(customerId) ?? 0) : 0) + (supplierId ? (invoicesBySupplier.get(supplierId) ?? 0) : 0),
|
||||
reason: p.status === 'suggested' ? p.suggested_reason : null,
|
||||
similar: similarById.get(p.id) ?? [],
|
||||
defaultRoles: p.kind === 'person' ? ['customer'] : defaultRoles(stats),
|
||||
createdAt: p.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
const observedRows: ObservedRow[] = []
|
||||
const generic = { count: 0, expenseSek: 0, examples: [] as string[] }
|
||||
for (const o of observed) {
|
||||
if (claimedKeys.has(o.key)) continue
|
||||
if (o.label === 'party' || o.label === 'unsure') {
|
||||
observedRows.push({ key: o.key, name: o.name || o.key, stats: statsFrom(o), label: o.label })
|
||||
} else if (o.label === 'category') {
|
||||
generic.count += 1
|
||||
generic.expenseSek += Number(o.expense_sek) || 0
|
||||
if (generic.examples.length < 3) generic.examples.push(o.name || o.key)
|
||||
}
|
||||
}
|
||||
generic.expenseSek = roundOre(generic.expenseSek)
|
||||
|
||||
const suggestedRows = rows.filter((r) => r.status === 'suggested')
|
||||
const counts: RegisterCounts = {
|
||||
suggested: suggestedRows.length,
|
||||
suggestedSuppliers: suggestedRows.filter((r) => r.defaultRoles.includes('supplier')).length,
|
||||
suggestedCustomers: suggestedRows.filter((r) => r.defaultRoles.includes('customer')).length,
|
||||
observed: observedRows.length,
|
||||
confirmed: rows.length - suggestedRows.length,
|
||||
}
|
||||
|
||||
const view = options.view ?? 'suggested'
|
||||
const byMoney = (a: RegisterRow, b: RegisterRow) =>
|
||||
(b.stats?.expenseSek ?? 0) + (b.stats?.revenueSek ?? 0) - ((a.stats?.expenseSek ?? 0) + (a.stats?.revenueSek ?? 0)) ||
|
||||
a.displayName.localeCompare(b.displayName, 'sv')
|
||||
const selected = (view === 'suggested' ? suggestedRows : []).filter((r) => matches(q, r.displayName, r.orgNumber)).sort(byMoney)
|
||||
const observedSelected =
|
||||
view === 'observed'
|
||||
? observedRows
|
||||
.filter((r) => matches(q, r.name, r.key))
|
||||
.sort((a, b) => b.stats.expenseSek + b.stats.revenueSek - (a.stats.expenseSek + a.stats.revenueSek))
|
||||
: []
|
||||
|
||||
return { counts, rows: selected, observed: observedSelected, generic, period }
|
||||
}
|
||||
|
||||
// ── Dossier ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PartyFact {
|
||||
id: string
|
||||
field: string
|
||||
value: unknown
|
||||
rank: string
|
||||
source: string
|
||||
reference: Record<string, unknown> | null
|
||||
fetchedAt: string | null
|
||||
recordedAt: string
|
||||
}
|
||||
|
||||
export interface PartyIdentity {
|
||||
id: string
|
||||
scheme: string
|
||||
value: string
|
||||
status: 'known' | 'unverified'
|
||||
source: string
|
||||
firstSeen: string | null
|
||||
lastSeen: string | null
|
||||
seenCount: number
|
||||
}
|
||||
|
||||
export interface PartyDecision {
|
||||
id: string
|
||||
kind: string
|
||||
note: string | null
|
||||
createdAt: string
|
||||
before: Record<string, unknown> | null
|
||||
after: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export interface PartyVoucher {
|
||||
id: string
|
||||
entryDate: string
|
||||
description: string
|
||||
voucher: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface Dossier {
|
||||
party: RegisterRow & { aliasKeys: string[]; legalName: string | null; vatNumber: string | null }
|
||||
facts: PartyFact[]
|
||||
identities: PartyIdentity[]
|
||||
decisions: PartyDecision[]
|
||||
vouchers: PartyVoucher[]
|
||||
similar: Array<{ id: string; displayName: string; orgNumber: string | null; status: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* The dossier for one party. A dismissed (archived) party is hidden here as
|
||||
* it is in the register; a merged party resolves to its survivor, so a
|
||||
* stale link lands on the right dossier instead of a dead one.
|
||||
*/
|
||||
export async function getDossier(supabase: SupabaseClient, companyId: string, partyId: string, hops = 0): Promise<Dossier | null> {
|
||||
const { data: party, error } = await supabase
|
||||
.from('parties')
|
||||
.select('id, display_name, legal_name, org_number, vat_number, kind, status, alias_keys, suggested_reason, created_at, merged_into, archived_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', partyId)
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`parties lookup failed: ${error.message}`)
|
||||
if (!party) return null
|
||||
const p = party as PartyRecord & { legal_name: string | null; vat_number: string | null; merged_into: string | null }
|
||||
if (p.merged_into) {
|
||||
if (hops >= 16) return null
|
||||
const { data: survivor, error: chainError } = await supabase.rpc('canonical_party_id', { p_party_id: p.id })
|
||||
if (chainError) throw new Error(`canonical_party_id failed: ${chainError.message}`)
|
||||
if (!survivor || survivor === p.id) return null
|
||||
return getDossier(supabase, companyId, survivor as string, hops + 1)
|
||||
}
|
||||
if (p.archived_at) return null
|
||||
|
||||
const [facts, identities, decisions, customer, supplier, observed] = await Promise.all([
|
||||
supabase
|
||||
.from('party_facts')
|
||||
.select('id, field, value, rank, source, reference, fetched_at, recorded_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('party_id', partyId)
|
||||
.is('superseded_at', null)
|
||||
.order('recorded_at', { ascending: false }),
|
||||
supabase
|
||||
.from('party_identities')
|
||||
.select('id, scheme, value, status, source, first_seen, last_seen, seen_count')
|
||||
.eq('company_id', companyId)
|
||||
.eq('party_id', partyId)
|
||||
.order('seen_count', { ascending: false }),
|
||||
supabase
|
||||
.from('party_decisions')
|
||||
.select('id, kind, note, created_at, before, after')
|
||||
.eq('company_id', companyId)
|
||||
.eq('party_id', partyId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(50),
|
||||
supabase.from('customers').select('id').eq('company_id', companyId).eq('party_id', partyId).limit(1).maybeSingle(),
|
||||
supabase.from('suppliers').select('id').eq('company_id', companyId).eq('party_id', partyId).limit(1).maybeSingle(),
|
||||
getObservedParties(supabase, companyId, { limit: 5000 }),
|
||||
])
|
||||
for (const r of [facts, identities, decisions]) if (r.error) throw new Error(`dossier read failed: ${r.error.message}`)
|
||||
|
||||
const parts = observed.filter((o) => p.alias_keys.includes(o.key))
|
||||
const stats = mergeStats(parts)
|
||||
|
||||
// Recent vouchers: the observed variants are the raw descriptions.
|
||||
let vouchers: PartyVoucher[] = []
|
||||
if (stats && stats.variants.length > 0) {
|
||||
const { data } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, entry_date, description, voucher_series, voucher_number, journal_entry_lines(debit_amount, account_number)')
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'posted')
|
||||
.in('description', stats.variants.slice(0, 200))
|
||||
.order('entry_date', { ascending: false })
|
||||
.limit(12)
|
||||
vouchers = ((data ?? []) as Array<{
|
||||
id: string
|
||||
entry_date: string
|
||||
description: string
|
||||
voucher_series: string | null
|
||||
voucher_number: number | null
|
||||
journal_entry_lines: Array<{ debit_amount: number | null; account_number: string }> | null
|
||||
}>).map((e) => ({
|
||||
id: e.id,
|
||||
entryDate: e.entry_date,
|
||||
description: e.description,
|
||||
voucher: e.voucher_series && e.voucher_number != null ? `${e.voucher_series}-${e.voucher_number}` : '',
|
||||
amount: roundOre(
|
||||
(e.journal_entry_lines ?? [])
|
||||
.filter((l) => /^[3-8][0-9]{3}$/.test(l.account_number))
|
||||
.reduce((s, l) => s + (Number(l.debit_amount) || 0), 0),
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
const reason = p.status === 'suggested' ? p.suggested_reason : null
|
||||
const live = await fetchAllRows<{ id: string; display_name: string; org_number: string | null; status: string; alias_keys: string[] }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('parties')
|
||||
.select('id, display_name, org_number, status, alias_keys')
|
||||
.eq('company_id', companyId)
|
||||
.is('merged_into', null)
|
||||
.is('archived_at', null)
|
||||
.range(from, to),
|
||||
)
|
||||
const liveById = new Map(live.map((l) => [l.id, l]))
|
||||
const similarIds = new Set<string>((similarAmong(live).get(p.id) ?? []).map((s) => s.id))
|
||||
for (const s of reason?.similar_to ?? []) if (liveById.has(s.party_id) && s.party_id !== p.id) similarIds.add(s.party_id)
|
||||
const similar: Dossier['similar'] = [...similarIds].map((id) => {
|
||||
const l = liveById.get(id)!
|
||||
return { id: l.id, displayName: l.display_name, orgNumber: l.org_number, status: l.status }
|
||||
})
|
||||
|
||||
return {
|
||||
party: {
|
||||
id: p.id,
|
||||
displayName: p.display_name,
|
||||
legalName: p.legal_name,
|
||||
vatNumber: p.vat_number,
|
||||
orgNumber: p.org_number,
|
||||
kind: p.kind,
|
||||
status: p.status,
|
||||
aliasKeys: p.alias_keys,
|
||||
roles: { customerId: (customer.data as { id: string } | null)?.id ?? null, supplierId: (supplier.data as { id: string } | null)?.id ?? null },
|
||||
stats,
|
||||
invoiceCount: 0,
|
||||
reason,
|
||||
similar: similar.map((s) => ({ id: s.id, displayName: s.displayName })),
|
||||
defaultRoles: p.kind === 'person' ? ['customer'] : defaultRoles(stats),
|
||||
createdAt: p.created_at,
|
||||
},
|
||||
facts: ((facts.data ?? []) as Array<Record<string, unknown>>).map((f) => ({
|
||||
id: f.id as string,
|
||||
field: f.field as string,
|
||||
value: f.value,
|
||||
rank: f.rank as string,
|
||||
source: f.source as string,
|
||||
reference: (f.reference as Record<string, unknown> | null) ?? null,
|
||||
fetchedAt: (f.fetched_at as string | null) ?? null,
|
||||
recordedAt: f.recorded_at as string,
|
||||
})),
|
||||
identities: ((identities.data ?? []) as Array<Record<string, unknown>>).map((i) => ({
|
||||
id: i.id as string,
|
||||
scheme: i.scheme as string,
|
||||
value: i.value as string,
|
||||
status: i.status as 'known' | 'unverified',
|
||||
source: i.source as string,
|
||||
firstSeen: (i.first_seen as string | null) ?? null,
|
||||
lastSeen: (i.last_seen as string | null) ?? null,
|
||||
seenCount: Number(i.seen_count) || 0,
|
||||
})),
|
||||
decisions: ((decisions.data ?? []) as Array<Record<string, unknown>>).map((d) => ({
|
||||
id: d.id as string,
|
||||
kind: d.kind as string,
|
||||
note: (d.note as string | null) ?? null,
|
||||
createdAt: d.created_at as string,
|
||||
before: (d.before as Record<string, unknown> | null) ?? null,
|
||||
after: (d.after as Record<string, unknown> | null) ?? null,
|
||||
})),
|
||||
vouchers,
|
||||
similar,
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { coreKey } from './ledger-key'
|
||||
import { coreKey, displayNameFromVoucherText } from './ledger-key'
|
||||
import { getObservedParties, type ObservedParty } from './observed'
|
||||
|
||||
export interface IdentityEvidence {
|
||||
@@ -110,7 +110,7 @@ function pickName(observed: ObservedParty, evidence: LedgerKeyEvidence | undefin
|
||||
// upper-cased, truncated and prefixed by whatever the source system did.
|
||||
const printed = evidence?.names[0]?.name
|
||||
if (printed && printed.length >= 2) return { display: printed, legal: printed }
|
||||
return { display: observed.name || observed.key }
|
||||
return { display: displayNameFromVoucherText(observed.name || observed.key) }
|
||||
}
|
||||
|
||||
function identitiesFrom(evidence: LedgerKeyEvidence | undefined): SuggestionIdentity[] {
|
||||
|
||||
Reference in New Issue
Block a user