Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

chore(transaction-dialog): remove disabled state for category selecton on transfer (#150)

Gustavo Henrique Rodrigues Guterresf679bf2f9d93
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index 85d0a724..84911899 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -42,6 +42,7 @@ class TransactionUpdate(BaseModel):
notes: Optional[str] = None
amount_primary: Optional[Decimal] = None
fx_rate_used: Optional[Decimal] = None
+ apply_to_transfer_pair: bool = False
# CC bucketing override (issue #92). Empty string / explicit null clears
# it back to auto. Only meaningful for credit-card accounts.
effective_bill_date: Optional[_Date] = None
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index 336f1da6..830a739d 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -629,6 +629,7 @@ async def update_transaction(
return None
update_data = data.model_dump(exclude_unset=True)
+ apply_to_transfer_pair = update_data.pop("apply_to_transfer_pair", False)
# Verify the new account belongs to the user before touching the row.
# When changing the account on one side of a transfer pair, refuse to
@@ -693,7 +694,8 @@ async def update_transaction(
# Cascade changes to paired transfer transaction
cascade_fields = {"amount", "date", "description", "notes"}
- if transaction.transfer_pair_id and (cascade_fields & update_data.keys()):
+ should_cascade_category = apply_to_transfer_pair and "category_id" in update_data
+ if transaction.transfer_pair_id and ((cascade_fields & update_data.keys()) or should_cascade_category):
paired = await session.execute(
select(Transaction).where(
Transaction.transfer_pair_id == transaction.transfer_pair_id,
@@ -702,6 +704,8 @@ async def update_transaction(
)
paired_tx = paired.scalar_one_or_none()
if paired_tx:
+ if should_cascade_category:
+ paired_tx.category_id = transaction.category_id
for key in cascade_fields & update_data.keys():
if key == "amount" and paired_tx.currency != transaction.currency:
from decimal import Decimal
diff --git a/backend/tests/test_transfer_api.py b/backend/tests/test_transfer_api.py
index 8fa2f175..7d3d1414 100644
--- a/backend/tests/test_transfer_api.py
+++ b/backend/tests/test_transfer_api.py
@@ -255,6 +255,136 @@ async def test_update_cascades_to_paired_transaction(
assert credit_data["date"] == new_date
+async def test_update_transfer_category_only_updates_edited_side_without_flag(
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ second_account: Account,
+ test_categories,
+):
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 180.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer recategorize",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ debit_id = data["debit"]["id"]
+ credit_id = data["credit"]["id"]
+
+ update_response = await client.patch(
+ f"/api/transactions/{debit_id}",
+ json={"category_id": str(test_categories[0].id)},
+ headers=auth_headers,
+ )
+ assert update_response.status_code == 200
+ assert update_response.json()["category_id"] == str(test_categories[0].id)
+
+ credit_response = await client.get(
+ f"/api/transactions/{credit_id}", headers=auth_headers
+ )
+ assert credit_response.status_code == 200
+ assert credit_response.json()["category_id"] is None
+
+
+async def test_update_transfer_category_can_apply_to_paired_transaction(
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ second_account: Account,
+ test_categories,
+):
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 220.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer paired category",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ debit_id = data["debit"]["id"]
+ credit_id = data["credit"]["id"]
+
+ update_response = await client.patch(
+ f"/api/transactions/{debit_id}",
+ json={
+ "category_id": str(test_categories[1].id),
+ "apply_to_transfer_pair": True,
+ },
+ headers=auth_headers,
+ )
+ assert update_response.status_code == 200
+ assert update_response.json()["category_id"] == str(test_categories[1].id)
+
+ credit_response = await client.get(
+ f"/api/transactions/{credit_id}", headers=auth_headers
+ )
+ assert credit_response.status_code == 200
+ assert credit_response.json()["category_id"] == str(test_categories[1].id)
+
+
+async def test_clear_transfer_category_can_apply_to_paired_transaction(
+ client: AsyncClient,
+ auth_headers,
+ test_account: Account,
+ second_account: Account,
+ test_categories,
+):
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 260.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer clear category",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ debit_id = data["debit"]["id"]
+ credit_id = data["credit"]["id"]
+
+ seed_response = await client.patch(
+ f"/api/transactions/{debit_id}",
+ json={
+ "category_id": str(test_categories[0].id),
+ "apply_to_transfer_pair": True,
+ },
+ headers=auth_headers,
+ )
+ assert seed_response.status_code == 200
+
+ clear_response = await client.patch(
+ f"/api/transactions/{debit_id}",
+ json={"category_id": None, "apply_to_transfer_pair": True},
+ headers=auth_headers,
+ )
+ assert clear_response.status_code == 200
+ assert clear_response.json()["category_id"] is None
+
+ credit_response = await client.get(
+ f"/api/transactions/{credit_id}", headers=auth_headers
+ )
+ assert credit_response.status_code == 200
+ assert credit_response.json()["category_id"] is None
+
+
async def _create_manual_tx(
client: AsyncClient,
auth_headers: dict,
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 68dec54e..ba9de6ba 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -620,7 +620,6 @@ function TransactionForm({
className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
- disabled={!!transaction?.transfer_pair_id}
>
<option value="">{t('transactions.noCategory')}</option>
{categories.map((cat) => (
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ad2a2efd..4b605d02 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -280,7 +280,10 @@ export const transactions = {
const { data } = await api.post('/transactions', transaction)
return data
},
- update: async (id: string, transaction: Partial<Transaction>): Promise<Transaction> => {
+ update: async (
+ id: string,
+ transaction: Partial<Transaction> & { apply_to_transfer_pair?: boolean },
+ ): Promise<Transaction> => {
const { data } = await api.patch(`/transactions/${id}`, transaction)
return data
},
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index d3407951..77884304 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -251,6 +251,10 @@
"unlinkTransfer": "Unlink transfer",
"unlinkTransferConfirm": "Unlink this transfer? Both transactions will be treated as regular transactions again.",
"unlinkTransferSuccess": "Transfer unlinked",
+ "confirmTransferCategoryTitle": "Apply this category to the paired transfer too?",
+ "confirmTransferCategoryDesc": "Transfers come in pairs. You can update only this transaction or apply the same category change to both sides.",
+ "confirmTransferCategorySingle": "Only this transaction",
+ "confirmTransferCategoryBoth": "Update both",
"filtersBar": {
"filters": "Filters",
"filterBy": "Filter by",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 6e5166e2..b41cc06c 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -251,6 +251,10 @@
"unlinkTransfer": "Desvincular transferência",
"unlinkTransferConfirm": "Desvincular esta transferência? Ambas as transações voltarão a ser tratadas como transações normais.",
"unlinkTransferSuccess": "Transferência desvinculada",
+ "confirmTransferCategoryTitle": "Aplicar esta categoria também à transferência pareada?",
+ "confirmTransferCategoryDesc": "Transferências vêm em pares. Você pode atualizar só esta transação ou aplicar a mesma mudança de categoria aos dois lados.",
+ "confirmTransferCategorySingle": "Só esta transação",
+ "confirmTransferCategoryBoth": "Atualizar ambas",
"filtersBar": {
"filters": "Filtros",
"filterBy": "Filtrar por",
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 78ef9bca..e2892ede 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -7,6 +7,13 @@ import { transactions, categories as categoriesApi, accounts as accountsApi, rec
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
import {
Table,
TableBody,
@@ -27,6 +34,15 @@ import { TransactionsFilterBar } from '@/components/transactions-filter-bar'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
+type TransactionUpdatePayload = Partial<Transaction> & {
+ apply_to_transfer_pair?: boolean
+}
+
+type PendingTransferCategoryUpdate = {
+ id: string
+ data: TransactionUpdatePayload
+}
+
function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)
}
@@ -58,6 +74,8 @@ export default function TransactionsPage() {
const [searchQuery, setSearchQuery] = useState(() => searchParams.get('q') ?? '')
const [dialogOpen, setDialogOpen] = useState(false)
const [editingTx, setEditingTx] = useState<Transaction | null>(null)
+ const [pendingTransferCategoryUpdate, setPendingTransferCategoryUpdate] =
+ useState<PendingTransferCategoryUpdate | null>(null)
const [formResetKey, setFormResetKey] = useState(0)
const [duplicateDraft, setDuplicateDraft] = useState<Partial<Transaction> | null>(null)
const [filterPayee, setFilterPayee] = useState<string>(searchParams.get('payee_id') ?? '')
@@ -264,7 +282,7 @@ export default function TransactionsPage() {
})
const updateMutation = useMutation({
- mutationFn: ({ id, ...data }: Partial<Transaction> & { id: string }) =>
+ mutationFn: ({ id, ...data }: TransactionUpdatePayload & { id: string }) =>
transactions.update(id, data),
onSuccess: () => {
invalidateAfterTxMutation()
@@ -424,6 +442,43 @@ export default function TransactionsPage() {
const totalPages = data ? Math.ceil(data.total / 20) : 0
+ const isTransferCategoryPromptOpen = !!pendingTransferCategoryUpdate
+
+ const submitPendingTransferCategoryUpdate = (applyToTransferPair: boolean) => {
+ if (!pendingTransferCategoryUpdate) return
+ const { id, data } = pendingTransferCategoryUpdate
+ updateMutation.mutate({
+ id,
+ ...data,
+ apply_to_transfer_pair: applyToTransferPair,
+ })
+ setPendingTransferCategoryUpdate(null)
+ }
+
+ const handleTransactionSave = (
+ data: Partial<Transaction>,
+ recurringData?: { frequency: string; end_date?: string },
+ pendingFiles?: File[],
+ action?: SaveAction,
+ ) => {
+ if (!editingTx) {
+ createMutation.mutate({ tx: data, recurringData, pendingFiles, action })
+ return
+ }
+
+ const isTransferCategoryChange =
+ !!editingTx.transfer_pair_id &&
+ Object.prototype.hasOwnProperty.call(data, 'category_id') &&
+ data.category_id !== editingTx.category_id
+
+ if (isTransferCategoryChange) {
+ setPendingTransferCategoryUpdate({ id: editingTx.id, data })
+ return
+ }
+
+ updateMutation.mutate({ id: editingTx.id, ...data })
+ }
+
return (
<div>
<PageHeader
@@ -829,26 +884,67 @@ export default function TransactionsPage() {
{/* Add/Edit Dialog */}
<TransactionDialog
open={dialogOpen}
- onClose={() => { setDialogOpen(false); setEditingTx(null); setDuplicateDraft(null) }}
+ onClose={() => {
+ setDialogOpen(false)
+ setEditingTx(null)
+ setDuplicateDraft(null)
+ setPendingTransferCategoryUpdate(null)
+ }}
transaction={editingTx}
duplicateDraft={duplicateDraft}
formResetKey={formResetKey}
categories={categoriesList ?? []}
accounts={accountsList ?? []}
recurringMatch={editingTx ? recurringList?.find(r => r.description === editingTx.description && r.type === editingTx.type) : undefined}
- onSave={(data, recurringData, pendingFiles, action) => {
- if (editingTx) {
- updateMutation.mutate({ id: editingTx.id, ...data })
- } else {
- createMutation.mutate({ tx: data, recurringData, pendingFiles, action })
- }
- }}
+ onSave={handleTransactionSave}
onDelete={editingTx ? () => deleteMutation.mutate(editingTx.id) : undefined}
onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}
loading={createMutation.isPending || updateMutation.isPending || deleteMutation.isPending || unlinkTransferMutation.isPending}
error={createMutation.error || updateMutation.error ? extractApiError(createMutation.error || updateMutation.error) : null}
isSynced={editingTx?.source === 'sync'}
/>
+
+ <Dialog
+ open={isTransferCategoryPromptOpen}
+ onOpenChange={(open) => {
+ if (!open) setPendingTransferCategoryUpdate(null)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('transactions.confirmTransferCategoryTitle')}</DialogTitle>
+ </DialogHeader>
+ <p className="text-sm text-muted-foreground">
+ {t('transactions.confirmTransferCategoryDesc')}
+ </p>
+ <DialogFooter className="flex-row flex-nowrap items-center justify-end gap-2 sm:space-x-0">
+ <Button
+ className="shrink-0"
+ variant="outline"
+ onClick={() => setPendingTransferCategoryUpdate(null)}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button
+ className="min-w-0 flex-1 truncate"
+ variant="outline"
+ onClick={() => submitPendingTransferCategoryUpdate(false)}
+ disabled={updateMutation.isPending}
+ >
+ {t('transactions.confirmTransferCategorySingle')}
+ </Button>
+ <Button
+ className="min-w-0 flex-1 truncate"
+ onClick={() => submitPendingTransferCategoryUpdate(true)}
+ disabled={updateMutation.isPending}
+ >
+ {updateMutation.isPending
+ ? t('common.loading')
+ : t('transactions.confirmTransferCategoryBoth')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</div>
)
}