Skip to content

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

Assign transactions to existing categorization rules (#347)

Danny Felize3d2e4e5e696
diff --git a/backend/app/api/rules.py b/backend/app/api/rules.py
index f0fafc6f..f9ba0dd3 100644
--- a/backend/app/api/rules.py
+++ b/backend/app/api/rules.py
@@ -15,6 +15,7 @@ from app.schemas.rule import (
RuleCreateResponse,
RuleImportRequest,
RuleImportResponse,
+ RuleMutationResponse,
RuleRead,
RuleUpdate,
)
@@ -24,6 +25,31 @@ from app.services.rule_service import DuplicateRuleError
router = APIRouter(prefix="/api/rules", tags=["rules"])
+def _normalize_conditions(conditions: list[dict]) -> list[dict]:
+ return [
+ {
+ "field": condition.get("field"),
+ "op": condition.get("op"),
+ "value": condition.get("value"),
+ }
+ for condition in conditions
+ ]
+
+
+def _rule_match_definition_changed(rule: RuleRead, data: RuleUpdate) -> bool:
+ update_data = data.model_dump(exclude_unset=True)
+ if (
+ "conditions_op" in update_data
+ and update_data["conditions_op"] != rule.conditions_op
+ ):
+ return True
+ if "conditions" not in update_data:
+ return False
+ return _normalize_conditions(update_data["conditions"] or []) != _normalize_conditions(
+ rule.conditions or []
+ )
+
+
@router.get("", response_model=list[RuleRead])
async def list_rules(
ctx: WorkspaceContext = Depends(current_workspace),
@@ -88,13 +114,18 @@ async def import_rules(
)
[email protected]("/{rule_id}", response_model=RuleRead)
[email protected]("/{rule_id}", response_model=RuleMutationResponse)
async def update_rule(
rule_id: uuid.UUID,
data: RuleUpdate,
ctx: WorkspaceContext = Depends(current_writable_workspace),
session: AsyncSession = Depends(get_async_session),
):
+ current_rule = await rule_service.get_rule(session, rule_id, ctx.workspace.id)
+ if not current_rule:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")
+ should_apply = _rule_match_definition_changed(current_rule, data)
+
try:
rule = await rule_service.update_rule(session, rule_id, ctx.workspace.id, data)
except DuplicateRuleError:
@@ -104,7 +135,14 @@ async def update_rule(
)
if not rule:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")
- return rule
+ applied_count = (
+ await rule_service.apply_single_rule(session, ctx.workspace.id, rule)
+ if should_apply
+ else 0
+ )
+ response = RuleMutationResponse.model_validate(rule)
+ response.applied_count = applied_count
+ return response
@router.delete("/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.py
index dab995a2..c43cebfe 100644
--- a/backend/app/schemas/rule.py
+++ b/backend/app/schemas/rule.py
@@ -47,12 +47,16 @@ class RuleRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
-class RuleCreateResponse(RuleRead):
- """A created rule plus how many existing transactions it just affected."""
+class RuleMutationResponse(RuleRead):
+ """A changed rule plus how many existing transactions it just affected."""
applied_count: int = 0
+class RuleCreateResponse(RuleMutationResponse):
+ """A created rule response kept for API compatibility."""
+
+
class RuleExportItem(BaseModel):
name: str
conditions_op: str = "and"
diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.py
index 9357a4ed..9a0d26ee 100644
--- a/backend/tests/test_new_rules_api.py
+++ b/backend/tests/test_new_rules_api.py
@@ -6,8 +6,9 @@ from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.user import User
+from app.schemas.rule import RuleAction, RuleCondition, RuleCreate
from app.services.category_service import create_default_categories
-from app.services.rule_service import create_default_rules
+from app.services.rule_service import create_default_rules, create_rule
@@ -138,7 +139,85 @@ async def test_update_rule(client: AsyncClient, auth_headers, test_rules):
headers=auth_headers,
)
assert response.status_code == 200
- assert response.json()["name"] == "Updated Name"
+ data = response.json()
+ assert data["name"] == "Updated Name"
+ assert "applied_count" in data
+
+
+async def test_update_rule_name_does_not_apply_to_existing_transactions(
+ client: AsyncClient,
+ auth_headers,
+ session: AsyncSession,
+ test_user: User,
+ test_workspace,
+ test_transactions,
+ test_categories,
+):
+ cat_food = str(test_categories[0].id)
+ rule = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Netflix direct",
+ conditions_op="and",
+ conditions=[RuleCondition(field="description", op="contains", value="NETFLIX")],
+ actions=[RuleAction(op="set_category", value=cat_food)],
+ priority=5,
+ is_active=True,
+ ),
+ )
+
+ response = await client.patch(
+ f"/api/rules/{rule.id}",
+ json={"name": "Netflix renamed"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["applied_count"] == 0
+
+ items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
+ netflix = {t["description"]: t for t in items}.get("NETFLIX")
+ assert netflix is not None
+ assert netflix["category_id"] is None
+
+
+async def test_update_rule_applies_to_existing_transactions(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ """Updating a rule immediately applies the new definition to history.
+
+ This covers adding a new merchant/pattern to an existing rule from a
+ transaction detail modal without requiring an explicit apply-all call.
+ """
+ cat_food = str(test_categories[0].id)
+ create_payload = {
+ "name": "Streaming",
+ "conditions_op": "and",
+ "conditions": [{"field": "description", "op": "contains", "value": "ZZZ_NOMATCH"}],
+ "actions": [{"op": "set_category", "value": cat_food}],
+ "priority": 5,
+ "is_active": True,
+ }
+ create_response = await client.post("/api/rules", json=create_payload, headers=auth_headers)
+ assert create_response.status_code == 201
+ assert create_response.json()["applied_count"] == 0
+
+ rule_id = create_response.json()["id"]
+ update_response = await client.patch(
+ f"/api/rules/{rule_id}",
+ json={"conditions": [{"field": "description", "op": "contains", "value": "NETFLIX"}]},
+ headers=auth_headers,
+ )
+ assert update_response.status_code == 200
+ assert update_response.json()["applied_count"] >= 1
+
+ items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
+ netflix = {t["description"]: t for t in items}.get("NETFLIX")
+ assert netflix is not None
+ assert netflix["category_id"] == cat_food
@pytest.mark.asyncio
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 0900d8d1..1febfa7f 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -1,10 +1,12 @@
-import { useState, useEffect, useCallback, useRef } from 'react'
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { getAccountName } from '@/lib/account-utils'
import { useTranslation } from 'react-i18next'
import { useDateLocale } from '@/hooks/use-display-locale'
-import { useQuery } from '@tanstack/react-query'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
-import { currencies as currenciesApi, transactions as transactionsApi, settings as settingsApi, payees as payeesApi } from '@/lib/api'
+import { currencies as currenciesApi, transactions as transactionsApi, settings as settingsApi, payees as payeesApi, rules as rulesApi } from '@/lib/api'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+import { normalizeRuleMatchValue } from '@/lib/rule-match-utils'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -13,23 +15,31 @@ import { DatePickerInput } from '@/components/ui/date-picker-input'
import {
Dialog,
DialogContent,
+ DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
-import { AlertTriangle, ChevronDown, ChevronLeft, Download, Eye, EyeClosed, Paperclip, Upload, X, FileText, Plus, Unlink, SlidersHorizontal } from 'lucide-react'
+import { AlertTriangle, ChevronDown, ChevronLeft, Download, Eye, EyeClosed, Paperclip, Upload, X, FileText, Plus, Unlink, SlidersHorizontal, ListPlus } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
import { CategorySelect } from '@/components/category-select'
import { TransactionAttachments } from '@/components/transaction-attachments'
import type { AttachmentPreview } from '@/components/transaction-attachments'
import { TransactionSplitsSection } from '@/components/transaction-splits-section'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
-import type { Transaction, RecurringTransaction, TransactionSplitsInput, CategoryGroup, Category } from '@/types'
+import type { Transaction, RecurringTransaction, TransactionSplitsInput, CategoryGroup, Category, Rule, RuleCondition } from '@/types'
import { toast } from 'sonner'
export type SaveAction = 'save' | 'saveAndNew' | 'saveAndDuplicate'
@@ -62,6 +72,14 @@ function isImageType(contentType: string): boolean {
return contentType.startsWith('image/')
}
+function getRuleCategoryId(rule: Rule): string | null {
+ return rule.actions.find(action => action.op === 'set_category' && action.value)?.value ?? null
+}
+
+function canExtendRuleFromTransaction(rule: Rule): boolean {
+ return rule.is_active && !!getRuleCategoryId(rule) && (rule.conditions_op === 'or' || rule.conditions.length <= 1)
+}
+
export function TransactionDialog({
open,
onClose,
@@ -318,6 +336,7 @@ function TransactionForm({
hasPreview: boolean
}) {
const { t } = useTranslation()
+ const queryClient = useQueryClient()
const { user } = useAuth()
const { privacyMode, MASK } = usePrivacyMode()
const userCurrency = user?.preferences?.currency_display ?? 'USD'
@@ -405,6 +424,63 @@ function TransactionForm({
}, [description, isSynced])
const [isIgnored, setIsIgnored] = useState(seed?.is_ignored ?? false)
const [togglingIgnore, setTogglingIgnore] = useState(false)
+ const [addToRuleOpen, setAddToRuleOpen] = useState(false)
+
+ const { data: rulesList, isLoading: rulesLoading } = useQuery({
+ queryKey: ['rules'],
+ queryFn: rulesApi.list,
+ enabled: !!transaction && !!onCreateRule,
+ })
+ const extendableRules = useMemo(
+ () => (rulesList ?? []).filter(canExtendRuleFromTransaction),
+ [rulesList],
+ )
+
+ const extendRuleMutation = useMutation({
+ mutationFn: async ({
+ rule,
+ condition,
+ }: {
+ rule: Rule
+ condition: RuleCondition
+ }) => {
+ const duplicate = rule.conditions.some(existing =>
+ existing.field === condition.field &&
+ existing.op === condition.op &&
+ normalizeRuleMatchValue(existing.value) === normalizeRuleMatchValue(condition.value)
+ )
+ if (duplicate) {
+ throw new Error('duplicate-condition')
+ }
+
+ return rulesApi.update(rule.id, {
+ conditions_op: rule.conditions.length <= 1 ? 'or' : rule.conditions_op,
+ conditions: [...rule.conditions, condition],
+ })
+ },
+ onSuccess: (updatedRule) => {
+ const targetCategoryId = getRuleCategoryId(updatedRule)
+ if (targetCategoryId) setCategoryId(targetCategoryId)
+ queryClient.invalidateQueries({ queryKey: ['rules'] })
+ const applied = updatedRule.applied_count ?? 0
+ if (applied > 0) {
+ invalidateFinancialQueries(queryClient)
+ }
+ setAddToRuleOpen(false)
+ toast.success(
+ applied > 0
+ ? t('rules.updatedAndApplied', { count: applied })
+ : t('transactions.addedToExistingRule'),
+ )
+ },
+ onError: (error) => {
+ if (error instanceof Error && error.message === 'duplicate-condition') {
+ toast.info(t('transactions.duplicateRuleCondition'))
+ } else {
+ toast.error(t('common.error'))
+ }
+ },
+ })
const handleToggleIgnore = async () => {
if (!seed?.id || togglingIgnore) return
@@ -952,16 +1028,37 @@ function TransactionForm({
</Button>
)}
{transaction && onCreateRule && (
- <Button
- type="button"
- variant="outline"
- onClick={() => onCreateRule(transaction)}
- className="gap-1.5 whitespace-nowrap"
- title={t('transactions.createRule')}
- >
- <SlidersHorizontal size={16} />
- {t('transactions.createRule')}
- </Button>
+ <div className="inline-flex">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onCreateRule(transaction)}
+ className="gap-1.5 rounded-r-none whitespace-nowrap"
+ title={t('transactions.createRule')}
+ >
+ <SlidersHorizontal size={16} />
+ {t('transactions.createRule')}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ aria-label={t('transactions.ruleActions')}
+ className="rounded-l-none border-l-0 px-2 has-[>svg]:px-2"
+ disabled={extendRuleMutation.isPending}
+ >
+ <ChevronDown />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-56">
+ <DropdownMenuItem onSelect={() => setAddToRuleOpen(true)}>
+ <ListPlus size={16} />
+ {t('transactions.addToExistingRule')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
)}
</div>
<div className="flex flex-wrap gap-2 justify-end sm:ml-auto">
@@ -1005,10 +1102,163 @@ function TransactionForm({
)}
</div>
</DialogFooter>
+ {transaction && addToRuleOpen && (
+ <AddTransactionToRuleDialog
+ open={true}
+ onOpenChange={setAddToRuleOpen}
+ transactionDescription={transaction.description}
+ rules={extendableRules}
+ categories={categories}
+ loadingRules={rulesLoading}
+ loading={extendRuleMutation.isPending}
+ onSubmit={({ rule, condition }) => extendRuleMutation.mutate({ rule, condition })}
+ />
+ )}
</form>
)
}
+function AddTransactionToRuleDialog({
+ open,
+ onOpenChange,
+ transactionDescription,
+ rules,
+ categories,
+ loadingRules,
+ loading,
+ onSubmit,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ transactionDescription: string
+ rules: Rule[]
+ categories: Category[]
+ loadingRules: boolean
+ loading: boolean
+ onSubmit: (data: { rule: Rule; condition: RuleCondition }) => void
+}) {
+ const { t } = useTranslation()
+ const [ruleId, setRuleId] = useState('')
+ const [matchOp, setMatchOp] = useState<'contains' | 'starts_with'>('contains')
+ const [matchText, setMatchText] = useState(transactionDescription)
+
+ const effectiveRuleId = ruleId && rules.some(rule => rule.id === ruleId)
+ ? ruleId
+ : rules[0]?.id ?? ''
+ const selectedRule = rules.find(rule => rule.id === effectiveRuleId) ?? null
+
+ function getCategoryName(rule: Rule): string {
+ const categoryId = getRuleCategoryId(rule)
+ return categories.find(category => category.id === categoryId)?.name ?? t('transactions.category')
+ }
+
+ function handleSubmit(event: React.FormEvent) {
+ event.preventDefault()
+ // This dialog renders inside the transaction's <form>; without stopping
+ // propagation the submit event bubbles up the React tree (portals preserve
+ // it) and also triggers the parent transaction save.
+ event.stopPropagation()
+ if (!selectedRule || !matchText.trim()) return
+ onSubmit({
+ rule: selectedRule,
+ condition: {
+ field: 'description',
+ op: matchOp,
+ value: matchText.trim(),
+ },
+ })
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('transactions.addToExistingRuleTitle')}</DialogTitle>
+ <DialogDescription>
+ {t('transactions.addToExistingRuleDescription')}
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label>{t('transactions.existingRule')}</Label>
+ <Select
+ value={effectiveRuleId}
+ onValueChange={setRuleId}
+ disabled={loadingRules || loading || rules.length === 0}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue
+ className="min-w-0 flex-1 text-left [&_span]:items-start [&_span]:text-left"
+ placeholder={loadingRules
+ ? t('common.loading')
+ : t('transactions.noExistingRules')}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {rules.map(rule => (
+ <SelectItem key={rule.id} value={rule.id}>
+ <span className="flex w-full min-w-0 flex-col items-start text-left">
+ <span className="w-full truncate">{rule.name}</span>
+ <span className="w-full text-xs text-muted-foreground truncate">
+ {getCategoryName(rule)}
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {!loadingRules && rules.length === 0 && (
+ <p className="text-xs text-muted-foreground">{t('transactions.noExistingRules')}</p>
+ )}
+ </div>
+
+ <div className="grid grid-cols-[140px_1fr] gap-3">
+ <div className="space-y-2">
+ <Label>{t('transactions.matchOperator')}</Label>
+ <Select
+ value={matchOp}
+ onValueChange={(value) => setMatchOp(value as 'contains' | 'starts_with')}
+ disabled={loading}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="contains">{t('rules.opContains')}</SelectItem>
+ <SelectItem value="starts_with">{t('rules.opStartsWith')}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-2 min-w-0">
+ <Label>{t('transactions.matchText')}</Label>
+ <Input
+ value={matchText}
+ onChange={(event) => setMatchText(event.target.value)}
+ disabled={loading}
+ autoFocus
+ />
+ </div>
+ </div>
+
+ <DialogFooter className="pt-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={loading}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={!selectedRule || !matchText.trim() || loading}>
+ {loading ? t('common.loading') : t('transactions.assignRule')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index f22a778b..dafa5d3e 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -794,7 +794,7 @@ export const rules = {
const { data } = await api.post('/rules', rule)
return data
},
- update: async (id: string, rule: Partial<Rule>): Promise<Rule> => {
+ update: async (id: string, rule: Partial<Rule>): Promise<Rule & { applied_count: number }> => {
const { data } = await api.patch(`/rules/${id}`, rule)
return data
},
diff --git a/frontend/src/lib/rule-match-utils.test.ts b/frontend/src/lib/rule-match-utils.test.ts
new file mode 100644
index 00000000..6ed048c7
--- /dev/null
+++ b/frontend/src/lib/rule-match-utils.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from 'vitest'
+
+import { normalizeRuleMatchValue } from './rule-match-utils'
+
+describe('normalizeRuleMatchValue', () => {
+ it('normalizes case, whitespace, and accents for duplicate checks', () => {
+ expect(normalizeRuleMatchValue(' Café ')).toBe('CAFE')
+ expect(normalizeRuleMatchValue('Niño')).toBe(normalizeRuleMatchValue('nino'))
+ })
+})
diff --git a/frontend/src/lib/rule-match-utils.ts b/frontend/src/lib/rule-match-utils.ts
new file mode 100644
index 00000000..70722cda
--- /dev/null
+++ b/frontend/src/lib/rule-match-utils.ts
@@ -0,0 +1,7 @@
+export function normalizeRuleMatchValue(value: string | number): string {
+ return String(value ?? '')
+ .trim()
+ .toUpperCase()
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+}
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 96753ae5..1da64802 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -291,6 +291,17 @@
"addManual": "Add Transaction",
"duplicate": "Duplicate",
"createRule": "Create Rule",
+ "ruleActions": "Rule actions",
+ "addToExistingRule": "Add to existing rule",
+ "addToExistingRuleTitle": "Add transaction to rule",
+ "addToExistingRuleDescription": "Choose an active category rule and add this transaction description as another future match.",
+ "existingRule": "Existing rule",
+ "matchOperator": "Match type",
+ "matchText": "Description match",
+ "assignRule": "Add to rule",
+ "noExistingRules": "No active category rules available",
+ "addedToExistingRule": "Rule updated. Future matches will use this category.",
+ "duplicateRuleCondition": "That rule already includes this match.",
"saveAndNew": "Save & New",
"saveAndDuplicate": "Save & Duplicate",
"moreSaveOptions": "More save options",
@@ -744,6 +755,7 @@
"add": "Add",
"created": "Rule created",
"createdAndApplied": "Rule created and applied to {{count}} transactions",
+ "updatedAndApplied": "Rule updated and applied to {{count}} transactions",
"updated": "Rule updated",
"deleted": "Rule deleted",
"applied": "Rules applied to {{count}} transactions",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 07de51ce..11ea5c68 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -291,6 +291,17 @@
"addManual": "Agregar transacción",
"duplicate": "Duplicar",
"createRule": "Crear regla",
+ "ruleActions": "Acciones de regla",
+ "addToExistingRule": "Agregar a regla existente",
+ "addToExistingRuleTitle": "Agregar transacción a una regla",
+ "addToExistingRuleDescription": "Elige una regla de categoría activa y agrega la descripción de esta transacción como otra coincidencia futura.",
+ "existingRule": "Regla existente",
+ "matchOperator": "Tipo de coincidencia",
+ "matchText": "Coincidencia en descripción",
+ "assignRule": "Agregar a regla",
+ "noExistingRules": "No hay reglas de categoría activas disponibles",
+ "addedToExistingRule": "Regla actualizada. Las próximas coincidencias usarán esta categoría.",
+ "duplicateRuleCondition": "Esa regla ya incluye esta coincidencia.",
"saveAndNew": "Guardar y nuevo",
"saveAndDuplicate": "Guardar y duplicar",
"moreSaveOptions": "Más opciones de guardado",
@@ -744,6 +755,7 @@
"add": "Agregar",
"created": "Regla creada",
"createdAndApplied": "Regla creada y aplicada a {{count}} transacciones",
+ "updatedAndApplied": "Regla actualizada y aplicada a {{count}} transacciones",
"updated": "Regla actualizada",
"deleted": "Regla eliminada",
"applied": "Reglas aplicadas a {{count}} transacciones",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index c44e0ef0..539ff163 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -291,6 +291,17 @@
"addManual": "Aggiungi transazione",
"duplicate": "Duplica",
"createRule": "Crea regola",
+ "ruleActions": "Azioni regola",
+ "addToExistingRule": "Aggiungi a regola esistente",
+ "addToExistingRuleTitle": "Aggiungi transazione a una regola",
+ "addToExistingRuleDescription": "Scegli una regola di categoria attiva e aggiungi la descrizione di questa transazione come futura corrispondenza.",
+ "existingRule": "Regola esistente",
+ "matchOperator": "Tipo di corrispondenza",
+ "matchText": "Corrispondenza descrizione",
+ "assignRule": "Aggiungi alla regola",
+ "noExistingRules": "Nessuna regola di categoria attiva disponibile",
+ "addedToExistingRule": "Regola aggiornata. Le prossime corrispondenze useranno questa categoria.",
+ "duplicateRuleCondition": "Questa regola include gia questa corrispondenza.",
"saveAndNew": "Salva e nuova",
"saveAndDuplicate": "Salva e duplica",
"moreSaveOptions": "Altre opzioni di salvataggio",
@@ -744,6 +755,7 @@
"add": "Aggiungi",
"created": "Regola creata",
"createdAndApplied": "Regola creata e applicata a {{count}} transazioni",
+ "updatedAndApplied": "Regola aggiornata e applicata a {{count}} transazioni",
"updated": "Regola aggiornata",
"deleted": "Regola eliminata",
"applied": "Regole applicate a {{count}} transazioni",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 68162b87..18ea52c2 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -297,6 +297,17 @@
"addManual": "Dodaj transakcję",
"duplicate": "Duplikuj",
"createRule": "Utwórz regułę",
+ "ruleActions": "Akcje reguły",
+ "addToExistingRule": "Dodaj do istniejącej reguły",
+ "addToExistingRuleTitle": "Dodaj transakcję do reguły",
+ "addToExistingRuleDescription": "Wybierz aktywną regułę kategorii i dodaj opis tej transakcji jako kolejne przyszłe dopasowanie.",
+ "existingRule": "Istniejąca reguła",
+ "matchOperator": "Typ dopasowania",
+ "matchText": "Dopasowanie opisu",
+ "assignRule": "Dodaj do reguły",
+ "noExistingRules": "Brak aktywnych reguł kategorii",
+ "addedToExistingRule": "Reguła zaktualizowana. Przyszłe dopasowania użyją tej kategorii.",
+ "duplicateRuleCondition": "Ta reguła już zawiera to dopasowanie.",
"saveAndNew": "Zapisz i nowa",
"saveAndDuplicate": "Zapisz i duplikuj",
"moreSaveOptions": "Więcej opcji zapisu",
@@ -795,6 +806,7 @@
"add": "Dodaj",
"created": "Utworzono regułę",
"createdAndApplied": "Utworzono regułę i zastosowano do {{count}} transakcji",
+ "updatedAndApplied": "Zaktualizowano regułę i zastosowano do {{count}} transakcji",
"updated": "Zaktualizowano regułę",
"deleted": "Usunięto regułę",
"applied_one": "Zastosowano reguły do {{count}} transakcji",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 1ffbd9ac..dfe897c9 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -291,6 +291,17 @@
"addManual": "Adicionar Transação",
"duplicate": "Duplicar",
"createRule": "Criar Regra",
+ "ruleActions": "Ações da regra",
+ "addToExistingRule": "Adicionar a regra existente",
+ "addToExistingRuleTitle": "Adicionar transação a uma regra",
+ "addToExistingRuleDescription": "Escolha uma regra de categoria ativa e adicione a descrição desta transação como outra correspondência futura.",
+ "existingRule": "Regra existente",
+ "matchOperator": "Tipo de correspondência",
+ "matchText": "Correspondência na descrição",
+ "assignRule": "Adicionar à regra",
+ "noExistingRules": "Nenhuma regra de categoria ativa disponível",
+ "addedToExistingRule": "Regra atualizada. Próximas correspondências usarão esta categoria.",
+ "duplicateRuleCondition": "Essa regra já inclui esta correspondência.",
"saveAndNew": "Salvar e novo",
"saveAndDuplicate": "Salvar e duplicar",
"moreSaveOptions": "Mais opções de salvar",
@@ -744,6 +755,7 @@
"add": "Adicionar",
"created": "Regra criada",
"createdAndApplied": "Regra criada e aplicada a {{count}} transações",
+ "updatedAndApplied": "Regra atualizada e aplicada a {{count}} transações",
"updated": "Regra atualizada",
"deleted": "Regra excluída",
"applied": "Regras aplicadas a {{count}} transações",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 57100189..2fd787f5 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -291,6 +291,17 @@
"addManual": "Добавить транзакцию",
"duplicate": "Дублировать",
"createRule": "Создать правило",
+ "ruleActions": "Действия правила",
+ "addToExistingRule": "Добавить в существующее правило",
+ "addToExistingRuleTitle": "Добавить транзакцию в правило",
+ "addToExistingRuleDescription": "Выберите активное правило категории и добавьте описание этой транзакции как будущее совпадение.",
+ "existingRule": "Существующее правило",
+ "matchOperator": "Тип совпадения",
+ "matchText": "Совпадение описания",
+ "assignRule": "Добавить в правило",
+ "noExistingRules": "Нет активных правил категорий",
+ "addedToExistingRule": "Правило обновлено. Будущие совпадения будут использовать эту категорию.",
+ "duplicateRuleCondition": "Это правило уже содержит такое совпадение.",
"saveAndNew": "Сохранить и добавить",
"saveAndDuplicate": "Сохранить и дублировать",
"moreSaveOptions": "Другие варианты сохранения",
@@ -744,6 +755,7 @@
"add": "Добавить",
"created": "Правило создано",
"createdAndApplied": "Правило создано и применено к {{count}} транзакциям",
+ "updatedAndApplied": "Правило обновлено и применено к {{count}} транзакциям",
"updated": "Правило обновлено",
"deleted": "Правило удалено",
"applied": "Правила применены к {{count}} транзакциям",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 8375f221..b9318af5 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -291,6 +291,17 @@
"addManual": "Додати транзакцію",
"duplicate": "Дублювати",
"createRule": "Створити правило",
+ "ruleActions": "Дії правила",
+ "addToExistingRule": "Додати до наявного правила",
+ "addToExistingRuleTitle": "Додати транзакцію до правила",
+ "addToExistingRuleDescription": "Виберіть активне правило категорії та додайте опис цієї транзакції як майбутній збіг.",
+ "existingRule": "Наявне правило",
+ "matchOperator": "Тип збігу",
+ "matchText": "Збіг опису",
+ "assignRule": "Додати до правила",
+ "noExistingRules": "Немає активних правил категорій",
+ "addedToExistingRule": "Правило оновлено. Майбутні збіги використовуватимуть цю категорію.",
+ "duplicateRuleCondition": "Це правило вже містить такий збіг.",
"saveAndNew": "Зберегти й додати",
"saveAndDuplicate": "Зберегти й дублювати",
"moreSaveOptions": "Інші варіанти збереження",
@@ -744,6 +755,7 @@
"add": "Додати",
"created": "Правило створено",
"createdAndApplied": "Правило створено й застосовано до {{count}} транзакцій",
+ "updatedAndApplied": "Правило оновлено й застосовано до {{count}} транзакцій",
"updated": "Правило оновлено",
"deleted": "Правило видалено",
"applied": "Правила застосовано до {{count}} транзакцій",
diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsx
index 59389bd9..f146a5bb 100644
--- a/frontend/src/pages/rules.tsx
+++ b/frontend/src/pages/rules.tsx
@@ -190,12 +190,18 @@ export default function RulesPage() {
const updateMutation = useMutation({
mutationFn: ({ id, ...data }: Partial<Rule> & { id: string }) => rulesApi.update(id, data),
- onSuccess: () => {
+ onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey: ['rules'] })
queryClient.invalidateQueries({ queryKey: ['rule-packs'] })
setDialogOpen(false)
setEditing(null)
- toast.success(t('rules.updated'))
+ const applied = result.applied_count ?? 0
+ if (applied > 0) {
+ invalidateFinancialQueries(queryClient)
+ toast.success(t('rules.updatedAndApplied', { count: applied }))
+ } else {
+ toast.success(t('rules.updated'))
+ }
},
onError: (error: unknown) => {
const err = error as { response?: { status?: number } }
@@ -579,4 +585,3 @@ function RulePacksDialog({ open, onClose }: { open: boolean; onClose: () => void
</Dialog>
)
}
-