Open-source personal finance manager. Self-hosted, privacy-first.
fix: edit accounts and add balance date field (#5)
gmiranda13bb9ca742df40
diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 8783bb12..1ea0afe5 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -1,5 +1,5 @@import uuid-from datetime import datetime+from datetime import date, datetimefrom decimal import Decimalfrom typing import Optional@@ -17,6 +17,7 @@ class AccountCreate(BaseModel):name: strtype: strbalance: Decimal = Decimal("0.00")+ balance_date: Optional[date] = Nonecurrency: str = "BRL"@@ -24,6 +25,7 @@ class AccountUpdate(BaseModel):name: Optional[str] = Nonetype: Optional[str] = Nonebalance: Optional[Decimal] = None+ balance_date: Optional[date] = Noneclass AccountRead(AccountBase):diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex f05235e1..af1582b8 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -122,7 +122,7 @@ async def create_account(session: AsyncSession, user_id: uuid.UUID, data: Accoundescription="Saldo inicial",amount=data.balance,currency=data.currency,- date=_Date.today(),+ date=data.balance_date or _Date.today(),type=opening_type,source="opening_balance",)@@ -144,9 +144,45 @@ async def update_account(if account.connection_id is not None:raise ValueError("Cannot edit bank-connected accounts")- for key, value in data.model_dump(exclude_unset=True).items():+ update_data = data.model_dump(exclude_unset=True)+ balance_date = update_data.pop("balance_date", None)++ for key, value in update_data.items():setattr(account, key, value)+ # When balance changes, sync the opening_balance transaction+ if "balance" in update_data:+ new_balance = update_data["balance"]+ existing_opening = await session.execute(+ select(Transaction).where(+ Transaction.account_id == account_id,+ Transaction.source == "opening_balance",+ )+ )+ opening_tx = existing_opening.scalar_one_or_none()+ opening_type = "debit" if account.type == "credit_card" else "credit"++ if new_balance > Decimal("0.00"):+ if opening_tx:+ opening_tx.amount = new_balance+ opening_tx.type = opening_type+ if balance_date:+ opening_tx.date = balance_date+ else:+ opening_tx = Transaction(+ user_id=account.user_id,+ account_id=account_id,+ description="Saldo inicial",+ amount=new_balance,+ currency=account.currency,+ date=balance_date or _Date.today(),+ type=opening_type,+ source="opening_balance",+ )+ session.add(opening_tx)+ elif opening_tx:+ await session.delete(opening_tx)+await session.commit()await session.refresh(account)return accountdiff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 89c72828..83c8a6c2 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -111,6 +111,7 @@"openingBalance": "opening balance","notFound": "Account not found.","balance": "Balance",+ "balanceDate": "Balance date","lastSync": "Last sync","sync": "Sync","disconnect": "Disconnect",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex d8d373d1..2d1a377e 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -111,6 +111,7 @@"openingBalance": "saldo inicial","notFound": "Conta não encontrada.","balance": "Saldo",+ "balanceDate": "Data do saldo","lastSync": "Última sincronização","sync": "Sincronizar","disconnect": "Desconectar",diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 6cb9a476..a3b11903 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useEffect, useState } from 'react'import { Link } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'@@ -14,6 +14,7 @@ import {DialogTitle,DialogFooter,} from '@/components/ui/dialog'+import { DatePickerInput } from '@/components/ui/date-picker-input'import { Badge } from '@/components/ui/badge'import { Skeleton } from '@/components/ui/skeleton'import type { Account, BankConnection } from '@/types'@@ -510,7 +511,7 @@ export default function AccountsPage() {if (editingAccount) {updateMutation.mutate({ id: editingAccount.id, ...data })} else {- createMutation.mutate(data as { name: string; type: string; balance?: number; currency?: string })+ createMutation.mutate(data as { name: string; type: string; balance?: number; balance_date?: string; currency?: string })}}}loading={createMutation.isPending || updateMutation.isPending}@@ -529,7 +530,7 @@ function AccountDialog({open: booleanonClose: () => voidaccount: Account | null- onSave: (data: { name?: string; type?: string; balance?: number; currency?: string }) => void+ onSave: (data: { name?: string; type?: string; balance?: number; balance_date?: string; currency?: string }) => voidloading: boolean}) {const { t } = useTranslation()@@ -537,6 +538,15 @@ function AccountDialog({const [type, setType] = useState(account?.type ?? 'checking')const [balance, setBalance] = useState(account?.balance?.toString() ?? '0')const [currency, setCurrency] = useState(account?.currency ?? 'BRL')+ const [balanceDate, setBalanceDate] = useState(new Date().toISOString().slice(0, 10))++ useEffect(() => {+ setName(account?.name ?? '')+ setType(account?.type ?? 'checking')+ setBalance(account?.balance?.toString() ?? '0')+ setCurrency(account?.currency ?? 'BRL')+ setBalanceDate(new Date().toISOString().slice(0, 10))+ }, [account])return (<Dialog open={open} onOpenChange={onClose}>@@ -550,10 +560,7 @@ function AccountDialog({key={account?.id ?? 'new'}onSubmit={(e) => {e.preventDefault()- onSave(account- ? { name, type, currency }- : { name, type, balance: parseFloat(balance), currency }- )+ onSave({ name, type, balance: parseFloat(balance), balance_date: balanceDate, currency })}}className="space-y-4">@@ -587,7 +594,7 @@ function AccountDialog({</select></div></div>- {!account && (+ <div className="grid grid-cols-2 gap-4"><div className="space-y-2"><Label>{t('accounts.balance')}</Label><Input@@ -597,7 +604,15 @@ function AccountDialog({onChange={(e) => setBalance(e.target.value)}/></div>- )}+ <div className="space-y-2">+ <Label>{t('accounts.balanceDate')}</Label>+ <DatePickerInput+ value={balanceDate}+ onChange={setBalanceDate}+ className="w-full justify-start"+ />+ </div>+ </div><DialogFooter><Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}