Open-source personal finance manager. Self-hosted, privacy-first.
feat(transactions): allow editing descriptions of bank-synced transactions (#1057)
Fredson Sumiebb9830142b6
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex e869d5ce..f3dc000a 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -1377,6 +1377,17 @@ async def _resync_installment_series_total(row.installment_total_amount = total+def _preserve_original_description(tx: Transaction) -> None:+ """Keep the bank text before a user rename overwrites it.++ Rows that pre-date the original_description column have nothing stored,+ so without this a hand edit is indistinguishable from the provider's text+ and rename rules would clobber it. Manual rows have no bank text to keep.+ """+ if tx.original_description is None and tx.source != "manual":+ tx.original_description = tx.description++async def _apply_update_to_row(session: AsyncSession,user_id: uuid.UUID,@@ -1409,6 +1420,7 @@ async def _apply_update_to_row(and update_data["description"] != tx.description)if description_changed:+ _preserve_original_description(tx)tx.description_is_rule_managed = Falsefx_keys = {"amount_primary", "fx_rate_used"}@@ -1479,6 +1491,7 @@ async def _apply_update_to_row(key == "description"and update_data[key] != paired_tx.description):+ _preserve_original_description(paired_tx)paired_tx.description_is_rule_managed = Falsesetattr(paired_tx, key, update_data[key])else:diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.pyindex 2d76ad57..35a3edf0 100644--- a/backend/tests/test_rule_service.py+++ b/backend/tests/test_rule_service.py@@ -842,6 +842,75 @@ async def test_apply_all_rules_preserves_manually_edited_import_description(assert transaction.notes == "#delivery"+async def test_apply_all_rules_preserves_edited_legacy_synced_description(+ session: AsyncSession, test_user, test_workspace+):+ """A synced row from before original_description existed keeps its edit.++ The edit backfills the bank text, which is what lets the rules tell the+ user's wording apart from the provider's.+ """+ account = Account(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Synced",+ type="checking",+ balance=Decimal("1000"),+ currency="BRL",+ )+ session.add(account)+ await session.flush()+ transaction = Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ description="PAG*LOJA 123",+ original_description=None,+ amount=Decimal("80.00"),+ date=date(2026, 1, 12),+ type="debit",+ source="sync",+ payee="LOJA EXEMPLO",+ )+ session.add(transaction)+ await session.commit()++ updated = await update_transaction(+ session,+ transaction.id,+ test_workspace.id,+ test_user.id,+ TransactionUpdate(description="Birthday gift"),+ )+ assert updated is not None+ assert updated.original_description == "PAG*LOJA 123"++ await create_rule(+ session,+ test_workspace.id,+ test_user.id,+ RuleCreate(+ name="Loja normalization",+ conditions=[+ RuleCondition(field="payee", op="contains", value="LOJA EXEMPLO")+ ],+ actions=[+ RuleAction(op="set_description", value="Loja Exemplo"),+ RuleAction(op="append_notes", value="#shopping"),+ ],+ apply_to_existing=False,+ ),+ )++ assert await apply_all_rules(session, test_workspace.id) == 1+ await session.refresh(transaction)+ assert transaction.description == "Birthday gift"+ assert transaction.original_description == "PAG*LOJA 123"+ assert transaction.description_is_rule_managed is False+ assert transaction.notes == "#shopping"++@pytest.mark.asyncioasync def test_apply_single_rule_preserves_manually_edited_import_description(session: AsyncSession, test_user, test_workspacediff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.pyindex a11db395..1f7e5c9e 100644--- a/backend/tests/test_transaction_service.py+++ b/backend/tests/test_transaction_service.py@@ -633,6 +633,54 @@ async def test_update_transaction(session: AsyncSession, test_user, test_workspaassert updated.description_is_rule_managed is False+async def test_update_transaction_backfills_original_description_on_legacy_rows(+ session: AsyncSession, test_user, test_workspace, txn_account+):+ synced = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=txn_account.id,+ description="PAG*LOJA 123",+ original_description=None,+ amount=Decimal("10"),+ date=date(2025, 3, 1),+ type="debit",+ source="sync",+ created_at=datetime.now(timezone.utc),+ )+ manual = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=txn_account.id,+ description="Lunch",+ original_description=None,+ amount=Decimal("10"),+ date=date(2025, 3, 1),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ session.add_all([synced, manual])+ await session.commit()++ updated = await update_transaction(+ session, synced.id, test_workspace.id, test_user.id,+ TransactionUpdate(description="Birthday gift"),+ )+ assert updated is not None+ assert updated.description == "Birthday gift"+ assert updated.original_description == "PAG*LOJA 123"++ updated = await update_transaction(+ session, manual.id, test_workspace.id, test_user.id,+ TransactionUpdate(description="Team lunch"),+ )+ assert updated is not None+ assert updated.description == "Team lunch"+ assert updated.original_description is None++@pytest.mark.asyncioasync def test_update_transaction_not_found(session: AsyncSession, test_user, test_workspace):result = await update_transaction(diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex 652e354a..3ec6606a 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -521,8 +521,8 @@ function TransactionForm({const formRef = useRef<HTMLFormElement>(null)const descriptionRef = useRef<HTMLTextAreaElement>(null)- // Bank-synced descriptions are read-only and can be long; auto-grow the- // textarea so the full text is always visible (issue #256).+ // Bank-synced descriptions can be long; auto-grow the textarea so the full+ // text is always visible (issue #256).useEffect(() => {const el = descriptionRef.currentif (!el) return@@ -804,6 +804,7 @@ function TransactionForm({: {}const txData = isSynced? {+ ...(description !== transaction?.description ? { description } : {}),category_id: categoryId || null,payee_id: payeeId || null,notes: notes.trim() || null,@@ -959,9 +960,17 @@ function TransactionForm({{isSynced ? (<textarearef={descriptionRef}- className="w-full border border-input rounded-md px-3 py-2 text-sm bg-muted/40 text-muted-foreground resize-none overflow-hidden cursor-default outline-none focus:outline-none focus-visible:outline-none"+ className="w-full border border-input rounded-md px-3 py-2 text-sm bg-card dark:bg-input/30 shadow-xs resize-none overflow-hidden outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-ring/30 focus-visible:ring-[2px]"value={description}- readOnly+ onChange={(e) => setDescription(e.target.value)}+ // Descriptions are single-line; Enter saves like the Input does.+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.nativeEvent.isComposing) {+ e.preventDefault()+ formRef.current?.requestSubmit()+ }+ }}+ requiredrows={1}/>) : (@@ -973,10 +982,19 @@ function TransactionForm({/>)}{transaction?.original_description &&- transaction.original_description !== transaction.description && (- <p className="text-xs text-muted-foreground">- {t('transactions.originalDescription')}: {transaction.original_description}- </p>+ transaction.original_description !== description && (+ <div className="flex items-start justify-between gap-3 text-xs text-muted-foreground">+ <p>+ {t('transactions.originalDescription')}: {transaction.original_description}+ </p>+ <button+ type="button"+ onClick={() => setDescription(transaction.original_description ?? '')}+ className="shrink-0 underline underline-offset-2 hover:text-foreground transition-colors cursor-pointer"+ >+ {t('transactions.restoreOriginalDescription')}+ </button>+ </div>)}{/* Rows that pre-date the original_description column have noprovenance to show, so the raw payee stays the only hint at whatdiff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 204e4378..0d3b41c4 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -887,6 +887,7 @@"monthNext": "Nächster Monat","description": "Beschreibung","originalDescription": "Ursprüngliche Beschreibung",+ "restoreOriginalDescription": "Original wiederherstellen","amount": "Betrag","status": "Status","date": "Datum",@@ -970,7 +971,7 @@"statusCleared": "Abgewickelt","sortAsc": "Aufsteigend sortieren","sortDesc": "Absteigend sortieren",- "syncedInfo": "Bank-synchronisierte Transaktion — nur Kategorie und Notizen können bearbeitet werden",+ "syncedInfo": "Bank-synchronisierte Transaktion — Betrag, Datum und Konto können nicht bearbeitet werden","uncategorized": "Nicht kategorisiert","selected": "ausgewählt","summaryCount": "{{count}} Transaktionen",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 44a70a74..253f7071 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1071,6 +1071,7 @@"monthNext": "Επόμενος μήνας","description": "Περιγραφή","originalDescription": "Αρχική περιγραφή",+ "restoreOriginalDescription": "Επαναφορά αρχικής","amount": "Ποσό","status": "Κατάσταση","date": "Ημερομηνία",@@ -1154,7 +1155,7 @@"statusCleared": "Εκκαθαρίστηκε","sortAsc": "Αύξουσα ταξινόμηση","sortDesc": "Φθίνουσα ταξινόμηση",- "syncedInfo": "Συγχρονισμένη συναλλαγή από τράπεζα — μόνο η κατηγορία και οι σημειώσεις μπορούν να επεξεργαστούν",+ "syncedInfo": "Συγχρονισμένη συναλλαγή από τράπεζα — το ποσό, η ημερομηνία και ο λογαριασμός δεν μπορούν να επεξεργαστούν","uncategorized": "Χωρίς κατηγορία","selected": "επιλεγμένα","summaryCount": "{{count}} συναλλαγές",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 127d69cc..e1338424 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -887,6 +887,7 @@"monthNext": "Next month","description": "Description","originalDescription": "Original description",+ "restoreOriginalDescription": "Restore original","amount": "Amount","status": "Status","date": "Date",@@ -970,7 +971,7 @@"statusCleared": "Cleared","sortAsc": "Sort ascending","sortDesc": "Sort descending",- "syncedInfo": "Bank-synced transaction — only category and notes can be edited",+ "syncedInfo": "Bank-synced transaction — amount, date and account can't be edited","uncategorized": "Uncategorized","selected": "selected","summaryCount": "{{count}} transactions",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 4d5373ac..3f2e6101 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -889,6 +889,7 @@"monthNext": "Mes siguiente","description": "Descripción","originalDescription": "Descripción original",+ "restoreOriginalDescription": "Restaurar original","amount": "Importe","status": "Estado","date": "Fecha",@@ -972,7 +973,7 @@"statusCleared": "Conciliada","sortAsc": "Orden ascendente","sortDesc": "Orden descendente",- "syncedInfo": "Transacción sincronizada con el banco — solo se pueden editar categoría y notas",+ "syncedInfo": "Transacción sincronizada con el banco — el importe, la fecha y la cuenta no se pueden editar","uncategorized": "Sin categorizar","selected": "seleccionado","summaryCount": "{{count}} transacciones",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex b3f3756a..0d1011cf 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -889,6 +889,7 @@"monthNext": "Mois suivant","description": "Description","originalDescription": "Description d'origine",+ "restoreOriginalDescription": "Restaurer l'original","amount": "Montant","status": "Statut","date": "Date",@@ -972,7 +973,7 @@"statusCleared": "Rapprochée","sortAsc": "Trier par ordre croissant","sortDesc": "Trier par ordre décroissant",- "syncedInfo": "Transaction synchronisée depuis la banque — seules la catégorie et les notes peuvent être modifiées",+ "syncedInfo": "Transaction synchronisée depuis la banque — le montant, la date et le compte ne peuvent pas être modifiés","uncategorized": "Non catégorisée","selected": "sélectionnée(s)","summaryCount": "{{count}} transactions",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex 863ca2a7..b03aba31 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -887,6 +887,7 @@"monthNext": "अगला महीना","description": "विवरण","originalDescription": "मूल विवरण",+ "restoreOriginalDescription": "मूल पुनर्स्थापित करें","amount": "राशि","status": "स्थिति","date": "तिथि",@@ -970,7 +971,7 @@"statusCleared": "क्लियर","sortAsc": "बढ़ते क्रम में लगाएँ","sortDesc": "घटते क्रम में लगाएँ",- "syncedInfo": "बैंक-सिंक किया गया लेन-देन — केवल श्रेणी और नोट्स संपादित किए जा सकते हैं",+ "syncedInfo": "बैंक-सिंक किया गया लेन-देन — राशि, तिथि और खाता संपादित नहीं किए जा सकते","uncategorized": "अवर्गीकृत","selected": "चयनित","summaryCount": "{{count}} लेन-देन",diff --git a/frontend/src/locales/i18n.test.ts b/frontend/src/locales/i18n.test.tsindex b1db8dc6..c1571f1e 100644--- a/frontend/src/locales/i18n.test.ts+++ b/frontend/src/locales/i18n.test.ts@@ -219,6 +219,7 @@ describe('i18n locale files', () => {it('contains imported-description normalization labels in every locale', () => {const required = ['transactions.originalDescription',+ 'transactions.restoreOriginalDescription','rules.setDescription','rules.descriptionValuePlaceholder','rules.invalidDescriptionValue',diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 29994791..0131ee46 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -889,6 +889,7 @@"monthNext": "Mese successivo","description": "Descrizione","originalDescription": "Descrizione originale",+ "restoreOriginalDescription": "Ripristina originale","amount": "Importo","status": "Stato","date": "Data",@@ -972,7 +973,7 @@"statusCleared": "Contabilizzata","sortAsc": "Ordine crescente","sortDesc": "Ordine decrescente",- "syncedInfo": "Transazione sincronizzata dalla banca — si possono modificare solo categoria e note",+ "syncedInfo": "Transazione sincronizzata dalla banca — importo, data e conto non possono essere modificati","uncategorized": "Senza categoria","selected": "selezionate","summaryCount": "{{count}} transazioni",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 821caa52..76c6246a 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -887,6 +887,7 @@"monthNext": "翌月","description": "摘要","originalDescription": "元の摘要",+ "restoreOriginalDescription": "元に戻す","amount": "金額","status": "ステータス","date": "日付",@@ -970,7 +971,7 @@"statusCleared": "清算済み","sortAsc": "昇順で並べ替え","sortDesc": "降順で並べ替え",- "syncedInfo": "銀行同期の取引 — 編集できるのはカテゴリとメモのみです",+ "syncedInfo": "銀行同期の取引 — 金額、日付、口座は編集できません","uncategorized": "未分類","selected": "件選択中","summaryCount": "{{count}}件",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 03ba6cab..491fe40d 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -887,6 +887,7 @@"monthNext": "Volgende maand","description": "Beschrijving","originalDescription": "Originele beschrijving",+ "restoreOriginalDescription": "Origineel herstellen","amount": "Bedrag","status": "Status","date": "Datum",@@ -970,7 +971,7 @@"statusCleared": "Gewist","sortAsc": "Sorteer oplopend","sortDesc": "Sorteer aflopend",- "syncedInfo": "Bankgesynchroniseerde transactie: alleen categorie en notities kunnen worden bewerkt",+ "syncedInfo": "Bankgesynchroniseerde transactie: bedrag, datum en rekening kunnen niet worden bewerkt","uncategorized": "Niet gecategoriseerd","selected": "geselecteerd","summaryCount": "{{count}} transacties",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 980764dc..a1351a95 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -901,6 +901,7 @@"monthNext": "Następny miesiąc","description": "Opis","originalDescription": "Oryginalny opis",+ "restoreOriginalDescription": "Przywróć oryginał","amount": "Kwota","status": "Status","date": "Data",@@ -987,7 +988,7 @@"statusCleared": "Rozliczona","sortAsc": "Sortuj rosnąco","sortDesc": "Sortuj malejąco",- "syncedInfo": "Transakcja zsynchronizowana z bankiem — edytować można tylko kategorię i notatki",+ "syncedInfo": "Transakcja zsynchronizowana z bankiem — kwoty, daty i konta nie można edytować","uncategorized": "Nieskategoryzowane","selected": "zaznaczono","summaryCount_one": "{{count}} transakcja",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex f50be1ba..067a7d52 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -889,6 +889,7 @@"monthNext": "Próximo mês","description": "Descrição","originalDescription": "Descrição original",+ "restoreOriginalDescription": "Restaurar original","amount": "Valor","status": "Status","date": "Data",@@ -972,7 +973,7 @@"statusCleared": "Compensada","sortAsc": "Ordem crescente","sortDesc": "Ordem decrescente",- "syncedInfo": "Transação sincronizada — apenas categoria e notas podem ser editadas",+ "syncedInfo": "Transação sincronizada — valor, data e conta não podem ser editados","uncategorized": "Sem categoria","selected": "selecionadas","summaryCount": "{{count}} transações",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 57b94a83..48eb3435 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -889,6 +889,7 @@"monthNext": "Próximo mês","description": "Descrição","originalDescription": "Descrição original",+ "restoreOriginalDescription": "Repor original","amount": "Valor","status": "Estado","date": "Data",@@ -972,7 +973,7 @@"statusCleared": "Compensada","sortAsc": "Ordem crescente","sortDesc": "Ordem decrescente",- "syncedInfo": "Transação sincronizada — apenas categoria e notas podem ser editadas",+ "syncedInfo": "Transação sincronizada — valor, data e conta não podem ser editados","uncategorized": "Sem categoria","selected": "selecionadas","summaryCount": "{{count}} transações",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex e5ff3aba..dd804cbe 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -895,6 +895,7 @@"monthNext": "Следующий месяц","description": "Описание","originalDescription": "Исходное описание",+ "restoreOriginalDescription": "Восстановить исходное","amount": "Сумма","status": "Статус","date": "Дата",@@ -978,7 +979,7 @@"statusCleared": "Проведена","sortAsc": "Сортировка по возрастанию","sortDesc": "Сортировка по убыванию",- "syncedInfo": "Транзакция, синхронизированная с банком — можно редактировать только категорию и примечания",+ "syncedInfo": "Транзакция, синхронизированная с банком — сумму, дату и счёт изменить нельзя","uncategorized": "Без категории","selected": "выбрано","summaryCount": "{{count}} транзакций",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex b9f39549..ff32bc4a 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -903,6 +903,7 @@"monthNext": "Ďalší mesiac","description": "Popis","originalDescription": "Pôvodný popis",+ "restoreOriginalDescription": "Obnoviť pôvodný","amount": "Suma","status": "Stav","date": "Dátum",@@ -990,7 +991,7 @@"statusCleared": "Zaúčtovaná","sortAsc": "Zoradiť vzostupne","sortDesc": "Zoradiť zostupne",- "syncedInfo": "Transakcia synchronizovaná z banky — upraviť sa dá len kategória a poznámka",+ "syncedInfo": "Transakcia synchronizovaná z banky — sumu, dátum a účet nemožno upraviť","uncategorized": "Bez kategórie","selected": "vybraných","summaryCount": "{{count}} transakcií",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 97c07de9..7899d104 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -895,6 +895,7 @@"monthNext": "Наступний місяць","description": "Опис","originalDescription": "Початковий опис",+ "restoreOriginalDescription": "Відновити початковий","amount": "Сума","status": "Статус","date": "Дата",@@ -978,7 +979,7 @@"statusCleared": "Проведена","sortAsc": "Сортування за зростанням","sortDesc": "Сортування за спаданням",- "syncedInfo": "Транзакція, синхронізована з банком — можна редагувати лише категорію та примітки",+ "syncedInfo": "Транзакція, синхронізована з банком — суму, дату та рахунок змінити не можна","uncategorized": "Без категорії","selected": "обрано","summaryCount": "{{count}} транзакцій",