feat(settings): rename learned counterparty templates (#2454)
* feat(settings): rename learned counterparty templates A user asked why a learned template under Inställningar > Mallar can be deleted but not renamed. Nothing legal or ledger-shaped blocks a rename; the one real obstacle was that the learn path keys templates by the normalized bank description, so a renamed row would stop receiving re-approvals and a duplicate would appear under the old key. Why it occurred: counterparty_name doubles as display name and as the learn/upsert key, and the only write path for it was the learner. There was no rename because every later approval would have forked the row. What was simplified instead of added: no display-label column, no new table, no migration. The rename moves the old key into counterparty_aliases, which the matcher already checks first, and the learn lookup (findTemplateByKey) now resolves name-then-alias so re-approvals and SIE re-imports land on the renamed row. Why this over the proposed shape: a separate label would have kept the key untouched but added a second name field for users to reason about; renaming the key with an alias trail gives the user exactly what they asked for with one fewer concept. Duplicate names are refused with 409 (active twin) or the invisible soft-deleted twin is removed (inactive). Fixes #2453 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CgYn5GEp4N5Dxjc1S9Ljbq * fix(bookkeeping): resolve the normalized-name match tier through aliases after a rename Skeptic refutation on 819894559: the alias tier compares raw lowercased bank descriptors, so the normalized key a rename pushes into aliases ("spotify") never matched there, and the name tier only knew the new label ("musik"). A renamed template kept learning through findTemplateByKey but was never proposed again for the merchant it was learned from. nameMap now also resolves aliases, with a real counterparty_name always winning over another row's alias. Refs #2453 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CgYn5GEp4N5Dxjc1S9Ljbq * fix(bookkeeping): canonical name beats a borrowed alias; unique-name race returns 409 Review findings on #2454: - The alias tier ran before the name tier, so a bank line that is exactly another template's canonical name could resolve to a row holding that string as a rename alias. Aliases claimed by a different template's counterparty_name are now skipped when building the alias map. - The PATCH twin check and the update are separate statements; a learn or a concurrent rename between them surfaced as 500. Postgres 23505 on the update now maps to the same 409 as the pre-check. Refs #2453 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CgYn5GEp4N5Dxjc1S9Ljbq --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
bb28968151
commit
e996d70955
@@ -520,6 +520,9 @@ describe('counterparty-templates', () => {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
contains: () => chain,
|
||||
order: () => chain,
|
||||
limit: () => chain,
|
||||
maybeSingle: async () => ({ data: null, error: null }),
|
||||
insert: async (payload: Record<string, unknown>) => {
|
||||
inserted.push(payload)
|
||||
@@ -710,15 +713,123 @@ describe('counterparty-templates', () => {
|
||||
expect(supabase.from).toHaveBeenCalledWith('categorization_templates')
|
||||
})
|
||||
|
||||
it('does DB lookup when existingTemplate is undefined', async () => {
|
||||
it('does DB lookup by name, then by alias, when existingTemplate is undefined', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null }) // select returns null
|
||||
enqueue({ data: null }) // select by name returns null
|
||||
enqueue({ data: null }) // select by alias returns null
|
||||
enqueue({ data: null }) // insert
|
||||
|
||||
await insertOrUpdateTemplate(supabase as never, 'user-1', baseParams)
|
||||
|
||||
// Two calls: select + insert
|
||||
expect(supabase.from).toHaveBeenCalledTimes(2)
|
||||
// Three calls: select by name + select by alias + insert
|
||||
expect(supabase.from).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('re-approval lands on a renamed template through its alias, not as a new row', async () => {
|
||||
// A user rename moves the bank-derived key into counterparty_aliases.
|
||||
// The learn path derives its key from the bank description, so without
|
||||
// the alias leg every later approval would insert a duplicate.
|
||||
const { supabase, enqueue, findCall, calls } = createQueuedMockSupabase()
|
||||
const renamed = makeCategorizationTemplate({
|
||||
id: 'renamed-1',
|
||||
counterparty_name: 'spotify',
|
||||
counterparty_aliases: ['spotify ab stockholm 4471 kortköp', 'spotify ab stockholm 4471'],
|
||||
debit_account: '6200',
|
||||
credit_account: '1930',
|
||||
occurrence_count: 5,
|
||||
})
|
||||
enqueue({ data: null }) // select by name: nothing under the old key
|
||||
enqueue({ data: renamed }) // select by alias: the renamed row
|
||||
enqueue({ data: null }) // update
|
||||
|
||||
await insertOrUpdateTemplate(supabase as never, 'user-1', {
|
||||
...baseParams,
|
||||
counterpartyName: 'spotify ab stockholm 4471',
|
||||
})
|
||||
|
||||
const aliasFilter = findCall('categorization_templates', 'contains')
|
||||
expect(aliasFilter).toEqual(['counterparty_aliases', ['spotify ab stockholm 4471']])
|
||||
expect(calls.some((c) => c.method === 'insert')).toBe(false)
|
||||
const payload = findCall('categorization_templates', 'update')?.[0] as { occurrence_count: number }
|
||||
expect(payload.occurrence_count).toBe(6)
|
||||
})
|
||||
})
|
||||
|
||||
// ── findCounterpartyTemplate after a rename ──────────────────
|
||||
|
||||
describe('findCounterpartyTemplate after a user rename', () => {
|
||||
it('still proposes a template renamed to a label for a new bank-line variant of the merchant', async () => {
|
||||
// Learned from "Kortköp 260612 SPOTIFY AB" (key "spotify"), then renamed
|
||||
// to "Musik" by the user: the old key sits in aliases. Next month's line
|
||||
// carries a new date, so the raw-descriptor alias tier misses; the
|
||||
// normalized-name tier must resolve through the alias instead.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const renamed = makeCategorizationTemplate({
|
||||
id: 'renamed-1',
|
||||
counterparty_name: 'musik',
|
||||
counterparty_aliases: ['kortköp 260612 spotify ab', 'spotify'],
|
||||
occurrence_count: 2,
|
||||
confidence: 0.6,
|
||||
})
|
||||
enqueue({ data: [renamed] })
|
||||
|
||||
const tx = makeTransaction({
|
||||
merchant_name: null,
|
||||
original_description: 'Kortköp 260705 SPOTIFY AB',
|
||||
description: 'Kortköp 260705 SPOTIFY AB',
|
||||
})
|
||||
const match = await findCounterpartyTemplate(supabase as never, 'company-1', tx)
|
||||
|
||||
expect(match?.template.id).toBe('renamed-1')
|
||||
expect(match?.matchMethod).toBe('exact_normalized')
|
||||
})
|
||||
|
||||
it('a real counterparty_name beats another template carrying the same string as alias', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const owner = makeCategorizationTemplate({
|
||||
id: 'owner',
|
||||
counterparty_name: 'spotify',
|
||||
counterparty_aliases: [],
|
||||
occurrence_count: 4,
|
||||
})
|
||||
const other = makeCategorizationTemplate({
|
||||
id: 'other',
|
||||
counterparty_name: 'musik',
|
||||
counterparty_aliases: ['spotify'],
|
||||
occurrence_count: 9,
|
||||
})
|
||||
enqueue({ data: [other, owner] })
|
||||
|
||||
const tx = makeTransaction({
|
||||
merchant_name: null,
|
||||
original_description: 'Kortköp 260705 SPOTIFY AB',
|
||||
description: 'Kortköp 260705 SPOTIFY AB',
|
||||
})
|
||||
const match = await findCounterpartyTemplate(supabase as never, 'company-1', tx)
|
||||
|
||||
expect(match?.template.id).toBe('owner')
|
||||
})
|
||||
|
||||
it('a bank line that is exactly a canonical name resolves to its owner, not to a row holding it as alias', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const owner = makeCategorizationTemplate({
|
||||
id: 'owner',
|
||||
counterparty_name: 'spotify',
|
||||
counterparty_aliases: [],
|
||||
occurrence_count: 4,
|
||||
})
|
||||
const other = makeCategorizationTemplate({
|
||||
id: 'other',
|
||||
counterparty_name: 'musik',
|
||||
counterparty_aliases: ['spotify'],
|
||||
occurrence_count: 9,
|
||||
})
|
||||
enqueue({ data: [other, owner] })
|
||||
|
||||
const tx = makeTransaction({ merchant_name: 'spotify', original_description: 'spotify', description: 'spotify' })
|
||||
const match = await findCounterpartyTemplate(supabase as never, 'company-1', tx)
|
||||
|
||||
expect(match?.template.id).toBe('owner')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -324,19 +324,38 @@ export async function findCounterpartyTemplatesBatch(
|
||||
|
||||
const templates = allTemplates as CategorizationTemplate[]
|
||||
|
||||
// Build alias lookup: lowercase alias → template
|
||||
// Build alias lookup: lowercase alias → template. An alias that equals
|
||||
// another template's canonical counterparty_name (only reachable through a
|
||||
// user rename) must not shadow that template when a bank line is exactly
|
||||
// that string: the canonical owner wins.
|
||||
const canonicalOwner = new Map<string, CategorizationTemplate>()
|
||||
for (const tmpl of templates) {
|
||||
canonicalOwner.set(tmpl.counterparty_name, tmpl)
|
||||
}
|
||||
const aliasMap = new Map<string, CategorizationTemplate>()
|
||||
for (const tmpl of templates) {
|
||||
for (const alias of tmpl.counterparty_aliases || []) {
|
||||
const owner = canonicalOwner.get(alias)
|
||||
if (owner && owner.id !== tmpl.id) continue
|
||||
aliasMap.set(alias, tmpl)
|
||||
}
|
||||
}
|
||||
|
||||
// Build normalized name lookup
|
||||
// Build normalized name lookup. A user rename (PATCH
|
||||
// /api/settings/counterparty-templates) moves the bank-derived key into
|
||||
// counterparty_aliases; without the alias leg here, a template renamed to a
|
||||
// human label ("musik") would keep learning through findTemplateByKey but
|
||||
// never be proposed again, since the alias tier above only sees raw
|
||||
// descriptors. A real counterparty_name always wins over an alias.
|
||||
const nameMap = new Map<string, CategorizationTemplate>()
|
||||
for (const tmpl of templates) {
|
||||
nameMap.set(tmpl.counterparty_name, tmpl)
|
||||
}
|
||||
for (const tmpl of templates) {
|
||||
for (const alias of tmpl.counterparty_aliases || []) {
|
||||
if (!nameMap.has(alias)) nameMap.set(alias, tmpl)
|
||||
}
|
||||
}
|
||||
|
||||
for (const tx of transactions) {
|
||||
// Identity anchors on the immutable bank original, not the working title:
|
||||
@@ -752,6 +771,38 @@ export interface TemplateUpsertParams {
|
||||
defaultDimensions?: Record<string, string> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the template that owns a learned key: by counterparty_name first,
|
||||
* then by alias. A user rename moves the old key into counterparty_aliases
|
||||
* (PATCH /api/settings/counterparty-templates), so the alias leg is what
|
||||
* keeps re-approvals landing on the renamed row instead of inserting a
|
||||
* second template under the bank-derived name.
|
||||
*/
|
||||
async function findTemplateByKey(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
counterpartyName: string
|
||||
): Promise<CategorizationTemplate | null> {
|
||||
const { data: byName } = await supabase
|
||||
.from('categorization_templates')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('counterparty_name', counterpartyName)
|
||||
.maybeSingle()
|
||||
if (byName) return byName as CategorizationTemplate
|
||||
|
||||
const { data: byAlias } = await supabase
|
||||
.from('categorization_templates')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.contains('counterparty_aliases', [counterpartyName])
|
||||
.order('occurrence_count', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
return (byAlias as CategorizationTemplate | null) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Low-level insert-or-update for a counterparty template.
|
||||
*
|
||||
@@ -781,13 +832,7 @@ export async function insertOrUpdateTemplate(
|
||||
// Resolve existing template
|
||||
let existing: CategorizationTemplate | null = null
|
||||
if (existingTemplate === undefined) {
|
||||
const { data } = await supabase
|
||||
.from('categorization_templates')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('counterparty_name', params.counterpartyName)
|
||||
.maybeSingle()
|
||||
existing = data as CategorizationTemplate | null
|
||||
existing = await findTemplateByKey(supabase, companyId, params.counterpartyName)
|
||||
} else {
|
||||
existing = existingTemplate
|
||||
}
|
||||
@@ -1370,11 +1415,19 @@ export async function populateTemplatesFromSieVouchers(
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
|
||||
// Keyed by counterparty_name, then by alias: a renamed template keeps its
|
||||
// old bank-derived key as an alias (see findTemplateByKey), and a SIE
|
||||
// re-import must update that row rather than insert a duplicate.
|
||||
const templateMap = new Map<string, CategorizationTemplate>()
|
||||
if (existingTemplates) {
|
||||
for (const t of existingTemplates) {
|
||||
templateMap.set(t.counterparty_name, t as CategorizationTemplate)
|
||||
}
|
||||
for (const t of existingTemplates) {
|
||||
for (const alias of (t.counterparty_aliases as string[] | null) || []) {
|
||||
if (!templateMap.has(alias)) templateMap.set(alias, t as CategorizationTemplate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let count = 0
|
||||
|
||||
Reference in New Issue
Block a user