Open-source personal finance manager. Self-hosted, privacy-first.
fix(payees): say why a duplicate person was rejected (#726)
Tássio Noronha1cbdb3355a5d
diff --git a/backend/app/services/payee_service.py b/backend/app/services/payee_service.pyindex c784b8d6..fb4b303e 100644--- a/backend/app/services/payee_service.py+++ b/backend/app/services/payee_service.py@@ -191,7 +191,8 @@ async def create_payee(if not name:raise ValueError("Payee name cannot be empty")- # Check uniqueness+ # Raised as a code, like the tax-id errors above: the client turns it into+ # a translated sentence, which prose in English here could never be.existing = await session.execute(select(Payee).where(Payee.workspace_id == workspace_id,@@ -199,7 +200,7 @@ async def create_payee())if existing.scalar_one_or_none():- raise ValueError("A payee with this name already exists")+ raise ValueError("duplicate_payee_name")fields = data.model_dump(exclude={"tax_ids"})fields["name"] = name@@ -246,7 +247,7 @@ async def update_payee())if existing.scalar_one_or_none():- raise ValueError("A payee with this name already exists")+ raise ValueError("duplicate_payee_name")for key, value in update_data.items():setattr(payee, key, value)diff --git a/backend/tests/test_payee_service.py b/backend/tests/test_payee_service.pyindex b9d2ed99..3231688b 100644--- a/backend/tests/test_payee_service.py+++ b/backend/tests/test_payee_service.py@@ -75,7 +75,7 @@ async def test_create_payee_with_notes(session: AsyncSession, test_user, test_wo@pytest.mark.asyncioasync def test_create_payee_duplicate_name_rejected(session: AsyncSession, test_user, test_workspace):await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Starbucks"))- with pytest.raises(ValueError, match="already exists"):+ with pytest.raises(ValueError, match="duplicate_payee_name"):await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="starbucks")) # case-insensitive@@ -364,7 +364,7 @@ async def test_update_payee_duplicate_name_rejected(session: AsyncSession, test_await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="A"))b = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="B"))- with pytest.raises(ValueError, match="already exists"):+ with pytest.raises(ValueError, match="duplicate_payee_name"):await update_payee(session, b.id, test_workspace.id, PayeeUpdate(name="A"))diff --git a/backend/tests/test_payees_api.py b/backend/tests/test_payees_api.pyindex 993b6a6e..fea6c099 100644--- a/backend/tests/test_payees_api.py+++ b/backend/tests/test_payees_api.py@@ -153,6 +153,21 @@ async def test_create_payee_duplicate(client: AsyncClient, auth_headers):json={"name": "unique"}, # case-insensitive duplicate)assert resp.status_code == 400+ # A code, not prose: the client owns the wording and the language.+ assert resp.json()["detail"] == "duplicate_payee_name"+++async def test_rename_payee_onto_existing_name_rejected(client: AsyncClient, auth_headers):+ await _create_payee(client, auth_headers, "Taken")+ other = await _create_payee(client, auth_headers, "Free")++ resp = await client.patch(+ f"/api/payees/{other['id']}", headers=auth_headers,+ json={"name": "taken"},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"] == "duplicate_payee_name"# ---------------------------------------------------------------------------diff --git a/frontend/src/lib/payee-error-message.test.ts b/frontend/src/lib/payee-error-message.test.tsnew file mode 100644index 00000000..c7cb9e78--- /dev/null+++ b/frontend/src/lib/payee-error-message.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest'+import type { TFunction } from 'i18next'+import { payeeErrorMessage } from './payee-error-message'++// Echoes the key back, with the fallback when one is given, so a test asserts+// which message was chosen rather than what a locale file happens to say.+const t = ((key: string, fallback?: string) => fallback ?? key) as unknown as TFunction++function apiError(detail: unknown) {+ return { response: { data: { detail } } }+}++describe('payeeErrorMessage', () => {+ it('names the collision when the workspace already has that name', () => {+ expect(payeeErrorMessage(apiError('duplicate_payee_name'), t)).toBe('payees.duplicateName')+ })++ it('leads with the document that failed validation', () => {+ expect(payeeErrorMessage(apiError('invalid_tax_id:cpf:checksum'), t))+ .toBe('CPF: payees.invalidTaxId')+ })++ it('leads with the document that is already on the person', () => {+ expect(payeeErrorMessage(apiError('duplicate_tax_id:cnpj'), t))+ .toBe('CNPJ: payees.duplicateTaxId')+ })++ it('falls back to the caller for a code it does not know', () => {+ expect(payeeErrorMessage(apiError('something_else'), t)).toBeNull()+ })++ // A network failure or a 500 carries no detail; the caller's generic message+ // is the honest thing to show, not a mangled read of an absent field.+ it('falls back to the caller when the error carries no detail', () => {+ expect(payeeErrorMessage(new Error('Network Error'), t)).toBeNull()+ expect(payeeErrorMessage(apiError(undefined), t)).toBeNull()+ expect(payeeErrorMessage(apiError([{ msg: 'field required' }]), t)).toBeNull()+ })+})diff --git a/frontend/src/lib/payee-error-message.ts b/frontend/src/lib/payee-error-message.tsnew file mode 100644index 00000000..bdd76d88--- /dev/null+++ b/frontend/src/lib/payee-error-message.ts@@ -0,0 +1,27 @@+import type { TFunction } from 'i18next'++/** Turn the server's machine-readable rejection into something a person can+ * act on.+ *+ * The codes carry the part the user has to look at — which document, or that+ * the name is taken — and the sentence around it is translated here, because+ * the server has no idea what language anyone reads. Anything else returns+ * null so the caller falls back to its generic message rather than putting a+ * raw code, or a stack of English prose, in front of someone. */+export function payeeErrorMessage(error: unknown, t: TFunction): string | null {+ const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ if (typeof detail !== 'string') return null++ if (detail === 'duplicate_payee_name') return t('payees.duplicateName')++ // `invalid_tax_id:<kind>:<reason>` and `duplicate_tax_id:<kind>`. The reason+ // is useful in logs; the document name is what the user needs on screen.+ const [code, kind = ''] = detail.split(':')+ if (code === 'invalid_tax_id' || code === 'duplicate_tax_id') {+ const name = t(`fiscal.kind.${kind}`, kind.toUpperCase())+ const message = code === 'invalid_tax_id' ? 'payees.invalidTaxId' : 'payees.duplicateTaxId'+ return `${name}: ${t(message)}`+ }++ return null+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex f314afaa..ac8bbf6c 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1366,6 +1366,8 @@"taxIdKind": "Dokumentart","searchTaxIdKind": "Dokument oder Land suchen…","invalidTaxId": "Prüfe dieses Dokument: es sieht nicht gültig aus.",+ "duplicateName": "Eine Person mit diesem Namen existiert bereits.",+ "duplicateTaxId": "dieses Dokument ist bereits bei dieser Person.","add": "Empfänger hinzufügen","edit": "Empfänger bearbeiten","created": "Zahlungsempfänger erstellt",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex a5a603ec..399b06b5 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1365,6 +1365,8 @@"taxIdKind": "Document type","searchTaxIdKind": "Search document or country…","invalidTaxId": "Check this document: it does not look valid.",+ "duplicateName": "A person with this name already exists.",+ "duplicateTaxId": "this document is already on this person.","add": "Add Payee","edit": "Edit Payee","created": "Payee created",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 4ae5926a..be227178 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1366,6 +1366,8 @@"taxIdKind": "Tipo de documento","searchTaxIdKind": "Buscar documento o país…","invalidTaxId": "Revisa este documento: no parece válido.",+ "duplicateName": "Ya existe una persona con este nombre.",+ "duplicateTaxId": "este documento ya está en esta persona.","add": "Agregar beneficiario","edit": "Editar beneficiario","created": "Beneficiario creado",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 55d30c3e..beb51ba7 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1366,6 +1366,8 @@"taxIdKind": "Type de document","searchTaxIdKind": "Rechercher un document ou un pays…","invalidTaxId": "Vérifiez ce document : il ne semble pas valide.",+ "duplicateName": "Une personne portant ce nom existe déjà.",+ "duplicateTaxId": "ce document est déjà sur cette personne.","add": "Ajouter un bénéficiaire","edit": "Modifier le bénéficiaire","created": "Bénéficiaire créé",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex c0d089dd..6e5b5f83 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1366,6 +1366,8 @@"taxIdKind": "Tipo di documento","searchTaxIdKind": "Cerca documento o paese…","invalidTaxId": "Controlla questo documento: non sembra valido.",+ "duplicateName": "Esiste già una persona con questo nome.",+ "duplicateTaxId": "questo documento è già su questa persona.","add": "Aggiungi beneficiario","edit": "Modifica beneficiario","created": "Beneficiario creato",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex f121cb22..f9f571c9 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -1366,6 +1366,8 @@"taxIdKind": "Documenttype","searchTaxIdKind": "Document of land zoeken…","invalidTaxId": "Controleer dit document: het lijkt niet geldig.",+ "duplicateName": "Er bestaat al een persoon met deze naam.",+ "duplicateTaxId": "dit document staat al bij deze persoon.","add": "Begunstigde toevoegen","edit": "Begunstigde bewerken","created": "Begunstigde aangemaakt",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 5e1ef17b..9ac35e95 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1446,6 +1446,8 @@"taxIdKind": "Typ dokumentu","searchTaxIdKind": "Szukaj dokumentu lub kraju…","invalidTaxId": "Sprawdź ten dokument: nie wygląda na prawidłowy.",+ "duplicateName": "Osoba o tej nazwie już istnieje.",+ "duplicateTaxId": "ten dokument jest już przypisany do tej osoby.","add": "Dodaj odbiorcę","edit": "Edytuj odbiorcę","created": "Utworzono odbiorcę",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex faeffb09..a434c369 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1366,6 +1366,8 @@"taxIdKind": "Tipo de documento","searchTaxIdKind": "Buscar documento ou país…","invalidTaxId": "Confira este documento: ele não parece válido.",+ "duplicateName": "Já existe uma pessoa com este nome.",+ "duplicateTaxId": "este documento já está nesta pessoa.","add": "Adicionar Pessoa","edit": "Editar Pessoa","created": "Pessoa criada",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex ff148adc..9b552207 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1366,6 +1366,8 @@"taxIdKind": "Tipo de documento","searchTaxIdKind": "Procurar documento ou país…","invalidTaxId": "Verifica este documento: não parece válido.",+ "duplicateName": "Já existe uma pessoa com este nome.",+ "duplicateTaxId": "este documento já está nesta pessoa.","add": "Adicionar Entidade","edit": "Editar Entidade","created": "Entidade criada",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 4b47bffb..bad6bbae 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1374,6 +1374,8 @@"taxIdKind": "Тип документа","searchTaxIdKind": "Поиск документа или страны…","invalidTaxId": "Проверьте этот документ: он выглядит недействительным.",+ "duplicateName": "Человек с таким именем уже существует.",+ "duplicateTaxId": "этот документ уже добавлен этому человеку.","add": "Добавить получателя","edit": "Редактировать получателя","created": "Получатель создан",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex bbee3127..dcf4df8a 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1374,6 +1374,8 @@"taxIdKind": "Тип документа","searchTaxIdKind": "Пошук документа або країни…","invalidTaxId": "Перевірте цей документ: він не виглядає дійсним.",+ "duplicateName": "Людина з таким іменем уже існує.",+ "duplicateTaxId": "цей документ уже додано цій людині.","add": "Додати отримувача","edit": "Редагувати отримувача","created": "Отримувача створено",diff --git a/frontend/src/pages/payees.tsx b/frontend/src/pages/payees.tsxindex 4c1dbb94..7bf1d48b 100644--- a/frontend/src/pages/payees.tsx+++ b/frontend/src/pages/payees.tsx@@ -1,6 +1,5 @@import { useState, useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'-import type { TFunction } from 'i18next'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { useNavigate, useSearchParams } from 'react-router-dom'@@ -51,18 +50,7 @@ import { useAuth } from '@/contexts/auth-context'import { useWorkspace } from '@/contexts/workspace-context'import type { Payee } from '@/types'import { formatCurrency } from '@/lib/format'---/** Turn the server's machine-readable document error into something a person- * can act on. It arrives as `invalid_tax_id:<kind>:<reason>`; the reason is- * useful in logs, the document name is what the user needs to look at. */-function taxIdErrorMessage(error: unknown, t: TFunction): string | null {- const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail- if (typeof detail !== 'string' || !detail.startsWith('invalid_tax_id:')) return null- const kind = detail.split(':')[1] ?? ''- const name = t(`fiscal.kind.${kind}`, kind.toUpperCase())- return `${name}: ${t('payees.invalidTaxId')}`-}+import { payeeErrorMessage } from '@/lib/payee-error-message'export default function PayeesPage() {const { t } = useTranslation()@@ -204,7 +192,7 @@ export default function PayeesPage() {setDialogOpen(false)toast.success(t('payees.created'))},- onError: (e: unknown) => toast.error(taxIdErrorMessage(e, t) ?? t('common.error')),+ onError: (e: unknown) => toast.error(payeeErrorMessage(e, t) ?? t('common.error')),})const updateMutation = useMutation({@@ -215,7 +203,7 @@ export default function PayeesPage() {setEditingPayee(null)toast.success(t('payees.updated'))},- onError: (e: unknown) => toast.error(taxIdErrorMessage(e, t) ?? t('common.error')),+ onError: (e: unknown) => toast.error(payeeErrorMessage(e, t) ?? t('common.error')),})const deleteMutation = useMutation({