Skip to content

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

fix: harden transaction and rule safety (#375)

Albert Dolkuna1fd914533c0
diff --git a/backend/app/api/rules.py b/backend/app/api/rules.py
index f9ba0dd3..c0c68580 100644
--- a/backend/app/api/rules.py
+++ b/backend/app/api/rules.py
@@ -38,16 +38,21 @@ def _normalize_conditions(conditions: list[dict]) -> list[dict]:
def _rule_match_definition_changed(rule: RuleRead, data: RuleUpdate) -> bool:
update_data = data.model_dump(exclude_unset=True)
+ if update_data.get("is_active") is True and not rule.is_active:
+ return 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 []
- )
+ if "conditions" in update_data:
+ if _normalize_conditions(update_data["conditions"] or []) != _normalize_conditions(
+ rule.conditions or []
+ ):
+ return True
+ if "actions" in update_data:
+ return [a.model_dump() for a in data.actions or []] != (rule.actions or [])
+ return False
@router.get("", response_model=list[RuleRead])
@@ -71,9 +76,20 @@ async def create_rule(
status_code=status.HTTP_409_CONFLICT,
detail="A rule with this name already exists",
)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# Apply the new rule to existing transactions so it takes effect on history
# immediately, and report how many were touched for a transparent toast.
- applied_count = await rule_service.apply_single_rule(session, ctx.workspace.id, rule)
+ applied_count = (
+ await rule_service.apply_single_rule(
+ session,
+ ctx.workspace.id,
+ rule,
+ overwrite_existing_categories=data.overwrite_existing_categories,
+ )
+ if data.apply_to_existing
+ else 0
+ )
response = RuleCreateResponse.model_validate(rule)
response.applied_count = applied_count
return response
@@ -112,6 +128,8 @@ async def import_rules(
status_code=status.HTTP_409_CONFLICT,
detail="Import would overwrite existing rules. Confirm overwrite to continue.",
)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
@router.patch("/{rule_id}", response_model=RuleMutationResponse)
@@ -124,7 +142,10 @@ async def update_rule(
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)
+ if data.apply_to_existing is None:
+ should_apply = _rule_match_definition_changed(current_rule, data)
+ else:
+ should_apply = data.apply_to_existing
try:
rule = await rule_service.update_rule(session, rule_id, ctx.workspace.id, data)
@@ -133,10 +154,17 @@ async def update_rule(
status_code=status.HTTP_409_CONFLICT,
detail="A rule with this name already exists",
)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
if not rule:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")
applied_count = (
- await rule_service.apply_single_rule(session, ctx.workspace.id, rule)
+ await rule_service.apply_single_rule(
+ session,
+ ctx.workspace.id,
+ rule,
+ overwrite_existing_categories=data.overwrite_existing_categories,
+ )
if should_apply
else 0
)
@@ -162,7 +190,9 @@ async def list_rule_packs(
session: AsyncSession = Depends(get_async_session),
):
"""List available country-specific rule packs with installed status."""
- installed_map = await rule_service.get_installed_packs(session, ctx.user_id)
+ installed_map = await rule_service.get_installed_packs(
+ session, ctx.workspace.id, ctx.user_id
+ )
packs = []
for code, pack in rule_service.RULE_PACKS.items():
packs.append({
@@ -192,6 +222,7 @@ async def install_rule_pack(
lang = (ctx.user.preferences or {}).get("language", "pt-BR")
result = await rule_service.install_rule_pack(
session,
+ ctx.workspace.id,
ctx.user_id,
pack_code,
lang,
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index a33bacf0..a38f9b8e 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -208,9 +208,12 @@ async def bulk_categorize(
ctx: WorkspaceContext = Depends(current_writable_workspace),
session: AsyncSession = Depends(get_async_session),
):
- count = await transaction_service.bulk_update_category(
- session, ctx.workspace.id, data.transaction_ids, data.category_id
- )
+ try:
+ count = await transaction_service.bulk_update_category(
+ session, ctx.workspace.id, data.transaction_ids, data.category_id
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
return {"updated": count}
@@ -395,6 +398,7 @@ async def update_transaction(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
if not transaction:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
+ transaction = await transaction_service.get_transaction(session, transaction.id, ctx.workspace.id)
primary_currency = ctx.user.primary_currency
return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)
diff --git a/backend/app/providers/simplefin.py b/backend/app/providers/simplefin.py
index b67e68b1..02ef2157 100644
--- a/backend/app/providers/simplefin.py
+++ b/backend/app/providers/simplefin.py
@@ -25,6 +25,7 @@ import logging
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation
from typing import Any, Optional
+from urllib.parse import unquote, urlsplit, urlunsplit
import httpx
@@ -82,11 +83,35 @@ def _epoch_to_date(value: Any) -> Optional[date]:
if value is None or value == "":
return None
try:
- return datetime.fromtimestamp(int(value), tz=timezone.utc).date()
+ seconds = int(value)
+ if seconds <= 0:
+ return None
+ return datetime.fromtimestamp(seconds, tz=timezone.utc).date()
except (ValueError, TypeError, OSError):
return None
+def _accounts_url_and_auth(access_url: str) -> tuple[str, Optional[tuple[str, str]]]:
+ parsed = urlsplit(access_url.rstrip("/"))
+ if parsed.username is None:
+ return f"{access_url.rstrip('/')}/accounts", None
+ host = parsed.hostname or ""
+ if parsed.port:
+ host = f"{host}:{parsed.port}"
+ url = urlunsplit((parsed.scheme, host, f"{parsed.path}/accounts", parsed.query, ""))
+ return url, (unquote(parsed.username), unquote(parsed.password or ""))
+
+
+def _redact_userinfo(url: str) -> str:
+ parsed = urlsplit(url)
+ if parsed.username is None:
+ return url
+ host = parsed.hostname or ""
+ if parsed.port:
+ host = f"{host}:{parsed.port}"
+ return urlunsplit((parsed.scheme, f"***:***@{host}", parsed.path, parsed.query, parsed.fragment))
+
+
def _to_decimal(value: Any) -> Optional[Decimal]:
if value is None or value == "":
return None
@@ -180,8 +205,9 @@ class SimpleFinProvider(BankProvider):
).timestamp()))
if account_id:
params["account"] = account_id
+ url, auth = _accounts_url_and_auth(access_url)
async with await self._client(credentials) as client:
- resp = await client.get(f"{access_url}/accounts", params=params)
+ resp = await client.get(url, params=params, auth=auth)
if resp.status_code in (401, 403):
raise ProviderUserActionRequired(
f"SimpleFIN refused the request ({resp.status_code})",
@@ -212,8 +238,9 @@ class SimpleFinProvider(BankProvider):
claim_url, headers={"Content-Length": "0"}
)
except httpx.HTTPError as exc:
+ message = str(exc).replace(claim_url, _redact_userinfo(claim_url))
raise RuntimeError(
- f"SimpleFIN claim request failed: {exc}"
+ f"SimpleFIN claim request failed: {message}"
) from exc
if claim_resp.status_code == 403:
# The bridge returns 403 when a setup token is reused.
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.py
index c43cebfe..4781a1fd 100644
--- a/backend/app/schemas/rule.py
+++ b/backend/app/schemas/rule.py
@@ -12,7 +12,7 @@ class RuleCondition(BaseModel):
class RuleAction(BaseModel):
- op: str # set_category, append_notes
+ op: str # set_category, set_payee, append_notes, ignore
value: Any # category UUID str or notes string
@@ -23,6 +23,8 @@ class RuleCreate(BaseModel):
actions: list[RuleAction]
priority: int = 0
is_active: bool = True
+ apply_to_existing: bool = True
+ overwrite_existing_categories: bool = False
class RuleUpdate(BaseModel):
@@ -32,6 +34,8 @@ class RuleUpdate(BaseModel):
actions: Optional[list[RuleAction]] = None
priority: Optional[int] = None
is_active: Optional[bool] = None
+ apply_to_existing: Optional[bool] = None
+ overwrite_existing_categories: bool = False
class RuleRead(BaseModel):
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index 80bafcab..14615551 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -3,7 +3,7 @@ from datetime import date as _Date
from decimal import Decimal
from typing import Literal, Optional
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.schemas.category import CategoryRead
from app.schemas.transaction_split import (
@@ -97,6 +97,12 @@ class TransactionRead(TransactionBase):
parent_owner_name: Optional[str] = None
is_ignored: bool = False
+ @model_validator(mode="after")
+ def reflect_ignored_category(self):
+ if self.category and self.category.is_ignored:
+ self.is_ignored = True
+ return self
+
model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 8cf6ac84..c41ddea5 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -635,7 +635,9 @@ async def handle_oauth_callback(
# Resolve payee entity from raw payee text
payee_id = None
if txn_data.payee:
- payee_entity = await get_or_create_payee(session, user_id, txn_data.payee)
+ payee_entity = await get_or_create_payee(
+ session, user_id, txn_data.payee, workspace_id=workspace_id
+ )
payee_id = payee_entity.id
bill = (
@@ -1014,6 +1016,7 @@ async def _sync_bill_finance_charges(
else:
tx = Transaction(
user_id=user_id,
+ workspace_id=account.workspace_id,
account_id=account.id,
external_id=external_id,
description=description,
@@ -1398,7 +1401,9 @@ async def sync_connection(
# Resolve payee entity from raw payee text
sync_payee_id = None
if txn_data.payee:
- sync_payee_entity = await get_or_create_payee(session, user_id, txn_data.payee)
+ sync_payee_entity = await get_or_create_payee(
+ session, user_id, txn_data.payee, workspace_id=workspace_id
+ )
sync_payee_id = sync_payee_entity.id
# No placeholder existed: if this charge fulfills an active bill's
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index f8e6bac2..2216a5a4 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -643,7 +643,9 @@ async def import_transactions(
import_payee_id = None
import_payee_raw = getattr(txn_data, "payee_raw", None)
if import_payee_raw:
- import_payee_entity = await get_or_create_payee(session, user_id, import_payee_raw)
+ import_payee_entity = await get_or_create_payee(
+ session, user_id, import_payee_raw, workspace_id=workspace_id
+ )
import_payee_id = import_payee_entity.id
# Recurring bill reconciliation (issue #116): if this imported charge
@@ -738,4 +740,4 @@ def normalize_amount(amount_str: str) -> str:
elif ',' in amount_str:
amount_str = amount_str.replace(',', '.')
- return amount_str
\ No newline at end of file
+ return amount_str
diff --git a/backend/app/services/rule_engine.py b/backend/app/services/rule_engine.py
index 13d5ea62..82932791 100644
--- a/backend/app/services/rule_engine.py
+++ b/backend/app/services/rule_engine.py
@@ -2,6 +2,7 @@
import re
import unicodedata
import uuid
+from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import TYPE_CHECKING
@@ -23,6 +24,19 @@ def _to_decimal(val) -> Decimal:
return Decimal("0")
+def _to_date(val) -> date | None:
+ if isinstance(val, datetime):
+ return val.date()
+ if isinstance(val, date):
+ return val
+ if isinstance(val, str):
+ try:
+ return date.fromisoformat(val)
+ except ValueError:
+ return None
+ return None
+
+
def _match_condition(condition: dict, tx: "Transaction") -> bool:
field = condition.get("field", "")
op = condition.get("op", "")
@@ -57,6 +71,20 @@ def _match_condition(condition: dict, tx: "Transaction") -> bool:
# Numeric operators
if op in ("gt", "gte", "lt", "lte"):
+ if field == "date":
+ tx_date = _to_date(tx_val)
+ val_date = _to_date(value)
+ if tx_date is None or val_date is None:
+ return False
+ if op == "gt":
+ return tx_date > val_date
+ if op == "gte":
+ return tx_date >= val_date
+ if op == "lt":
+ return tx_date < val_date
+ if op == "lte":
+ return tx_date <= val_date
+
tx_num = _to_decimal(tx_val)
val_num = _to_decimal(value)
if op == "gt":
diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.py
index d8624205..b9494152 100644
--- a/backend/app/services/rule_service.py
+++ b/backend/app/services/rule_service.py
@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.rule import Rule
from app.models.category import Category
+from app.models.payee import Payee
from app.models.transaction import Transaction
from app.schemas.rule import RuleCreate, RuleExportPayload, RuleImportResponse, RuleUpdate
from app.services.rule_engine import evaluate_conditions, apply_rule_actions
@@ -18,6 +19,65 @@ class DuplicateRuleError(Exception):
pass
+_ALLOWED_CONDITION_FIELDS = {
+ "description", "notes", "amount", "type", "account_id", "payee_id", "date",
+}
+_ALLOWED_CONDITION_OPS = {
+ "contains", "not_contains", "equals", "not_equals", "starts_with",
+ "ends_with", "regex", "gt", "gte", "lt", "lte",
+}
+_ALLOWED_ACTION_OPS = {"set_category", "set_payee", "append_notes", "ignore"}
+
+
+def _rule_item_value(item, key: str):
+ return item.get(key) if isinstance(item, dict) else getattr(item, key, None)
+
+
+async def _validate_rule_definition(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ conditions: list,
+ actions: list,
+) -> None:
+ for condition in conditions or []:
+ field = _rule_item_value(condition, "field")
+ op = _rule_item_value(condition, "op")
+ if field not in _ALLOWED_CONDITION_FIELDS or op not in _ALLOWED_CONDITION_OPS:
+ raise ValueError("Invalid rule condition")
+
+ for action in actions or []:
+ op = _rule_item_value(action, "op")
+ value = _rule_item_value(action, "value")
+ if op not in _ALLOWED_ACTION_OPS:
+ raise ValueError("Invalid rule action")
+ if op == "set_category":
+ try:
+ category_id = uuid.UUID(str(value))
+ except (TypeError, ValueError):
+ raise ValueError("Category not found")
+ exists_result = await session.execute(
+ select(Category.id).where(
+ Category.id == category_id,
+ Category.workspace_id == workspace_id,
+ )
+ )
+ if exists_result.scalar_one_or_none() is None:
+ raise ValueError("Category not found")
+ elif op == "set_payee":
+ try:
+ payee_id = uuid.UUID(str(value))
+ except (TypeError, ValueError):
+ raise ValueError("Payee not found")
+ exists_result = await session.execute(
+ select(Payee.id).where(
+ Payee.id == payee_id,
+ Payee.workspace_id == workspace_id,
+ )
+ )
+ if exists_result.scalar_one_or_none() is None:
+ raise ValueError("Payee not found")
+
+
# ─── Universal rules (work for any language/country) ───
# Category values here use internal keys (e.g. "transport") that get resolved to the
# user's actual category name at creation time.
@@ -594,6 +654,7 @@ def _required_internal_keys(pack: dict) -> set[str]:
async def _ensure_categories_for_keys(
session: AsyncSession,
+ workspace_id: Optional[uuid.UUID],
user_id: uuid.UUID,
internal_keys: set[str],
lang: str,
@@ -619,7 +680,11 @@ async def _ensure_categories_for_keys(
existing_cats = list(
(
await session.execute(
- select(Category).where(Category.user_id == user_id)
+ select(Category).where(
+ Category.workspace_id == workspace_id
+ if workspace_id is not None
+ else Category.user_id == user_id
+ )
)
).scalars().all()
)
@@ -637,7 +702,11 @@ async def _ensure_categories_for_keys(
existing_groups = list(
(
await session.execute(
- select(CategoryGroup).where(CategoryGroup.user_id == user_id)
+ select(CategoryGroup).where(
+ CategoryGroup.workspace_id == workspace_id
+ if workspace_id is not None
+ else CategoryGroup.user_id == user_id
+ )
)
).scalars().all()
)
@@ -658,6 +727,7 @@ async def _ensure_categories_for_keys(
continue
group = CategoryGroup(
user_id=user_id,
+ workspace_id=workspace_id,
name=gdata.get(lang, gdata["en"]),
icon=gdata["icon"],
color=gdata["color"],
@@ -673,6 +743,7 @@ async def _ensure_categories_for_keys(
target_group = groups_by_key.get(CATEGORY_TO_GROUP.get(key))
cat = Category(
user_id=user_id,
+ workspace_id=workspace_id,
name=data.get(lang, data["en"]),
icon=data["icon"],
color=data["color"],
@@ -687,8 +758,9 @@ async def _ensure_categories_for_keys(
async def install_rule_pack(
session: AsyncSession,
- user_id: uuid.UUID,
- pack_code: str,
+ workspace_id_or_user_id: uuid.UUID,
+ user_id_or_pack_code: uuid.UUID | str,
+ pack_code: Optional[str] = None,
lang: str = "pt-BR",
create_missing_categories: bool = False,
) -> RulePackInstallResult:
@@ -700,6 +772,14 @@ async def install_rule_pack(
"install pack, fill in what's needed". `lang` controls the names of
any newly-created categories.
"""
+ if pack_code is None:
+ workspace_id = None
+ user_id = workspace_id_or_user_id
+ pack_code = str(user_id_or_pack_code)
+ else:
+ workspace_id = workspace_id_or_user_id
+ user_id = user_id_or_pack_code
+
pack = RULE_PACKS.get(pack_code)
if not pack:
return RulePackInstallResult([], 0)
@@ -707,16 +787,26 @@ async def install_rule_pack(
categories_created = 0
if create_missing_categories:
categories_created = await _ensure_categories_for_keys(
- session, user_id, _required_internal_keys(pack), lang
+ session, workspace_id, user_id, _required_internal_keys(pack), lang
)
- result = await session.execute(select(Category).where(Category.user_id == user_id))
+ result = await session.execute(
+ select(Category).where(
+ Category.workspace_id == workspace_id
+ if workspace_id is not None
+ else Category.user_id == user_id
+ )
+ )
categories = {cat.name: str(cat.id) for cat in result.scalars().all()}
key_to_id = _resolve_categories_by_internal_key(categories)
resolved, unresolved = _build_rules_from_templates(pack["rules"], key_to_id)
- existing_names = await _get_existing_rule_names(session, user_id)
+ existing_names = (
+ await _get_existing_rule_names_for_workspace(session, workspace_id)
+ if workspace_id is not None
+ else await _get_existing_rule_names(session, user_id)
+ )
rules: list[Rule] = []
for rule_data in resolved:
@@ -724,6 +814,7 @@ async def install_rule_pack(
continue
rule = Rule(
user_id=user_id,
+ workspace_id=workspace_id,
name=rule_data["name"],
conditions_op=rule_data["conditions_op"],
conditions=rule_data["conditions"],
@@ -738,9 +829,15 @@ async def install_rule_pack(
return RulePackInstallResult(rules, unresolved, categories_created)
-async def get_installed_packs(session: AsyncSession, user_id: uuid.UUID) -> dict[str, bool]:
+async def get_installed_packs(
+ session: AsyncSession, workspace_id: uuid.UUID, user_id: Optional[uuid.UUID] = None
+) -> dict[str, bool]:
"""Check which rule packs are fully installed for a user."""
- existing_names = await _get_existing_rule_names(session, user_id)
+ existing_names = (
+ await _get_existing_rule_names_for_workspace(session, workspace_id)
+ if user_id is not None
+ else await _get_existing_rule_names(session, workspace_id)
+ )
result = {}
for code, pack in RULE_PACKS.items():
pack_names = {r["name"] for r in pack["rules"]}
@@ -840,6 +937,16 @@ async def import_rules(
if missing_required_reference:
skipped += 1
continue
+ try:
+ await _validate_rule_definition(
+ session,
+ workspace_id,
+ [condition.model_dump() for condition in incoming.conditions],
+ resolved_actions,
+ )
+ except ValueError:
+ skipped += 1
+ continue
rules_to_create.append(Rule(
user_id=user_id,
workspace_id=workspace_id,
@@ -881,6 +988,8 @@ async def create_rule(
if data.name in existing_names:
raise DuplicateRuleError(f"A rule named '{data.name}' already exists")
+ await _validate_rule_definition(session, workspace_id, data.conditions, data.actions)
+
rule = Rule(
user_id=user_id,
workspace_id=workspace_id,
@@ -904,7 +1013,10 @@ async def update_rule(
if not rule:
return None
- update_data = data.model_dump(exclude_unset=True)
+ update_data = data.model_dump(
+ exclude_unset=True,
+ exclude={"apply_to_existing", "overwrite_existing_categories"},
+ )
if "name" in update_data and update_data["name"] != rule.name:
existing_names = await _get_existing_rule_names_for_workspace(session, workspace_id)
@@ -916,6 +1028,13 @@ async def update_rule(
if "actions" in update_data and update_data["actions"] is not None:
update_data["actions"] = [a.model_dump() for a in data.actions]
+ await _validate_rule_definition(
+ session,
+ workspace_id,
+ update_data.get("conditions", rule.conditions or []),
+ update_data.get("actions", rule.actions or []),
+ )
+
for key, value in update_data.items():
setattr(rule, key, value)
@@ -974,17 +1093,20 @@ async def apply_rules_to_transaction(
async def apply_single_rule(
- session: AsyncSession, workspace_id: uuid.UUID, rule: Rule
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ rule: Rule,
+ overwrite_existing_categories: bool = False,
) -> int:
"""Apply one rule to all existing workspace transactions. Returns the number
of transactions actually modified.
Used right after a rule is created so it takes effect on history without the
user having to hit "Reapply all". Unlike `apply_all_rules` this is
- non-destructive: a transaction that already has a category keeps it (same
- semantics used when new transactions arrive), so creating a rule never
- silently overwrites manual categorizations. Payee/notes/ignore actions still
- apply on a match. Only transactions whose fields actually change are counted.
+ non-destructive by default: a transaction that already has a category keeps
+ it unless the caller explicitly opts into replacing existing categories.
+ Payee/notes/ignore actions still apply on a match. Only transactions whose
+ fields actually change are counted.
"""
if not rule.is_active:
return 0
@@ -1005,7 +1127,12 @@ async def apply_single_rule(
if not evaluate_conditions(rule.conditions_op, conditions, tx):
continue
before = (tx.category_id, tx.payee_id, tx.notes, tx.is_ignored)
- apply_rule_actions(actions, tx, category_already_set=tx.category_id is not None)
+ apply_rule_actions(
+ actions,
+ tx,
+ category_already_set=tx.category_id is not None
+ and not overwrite_existing_categories,
+ )
if before != (tx.category_id, tx.payee_id, tx.notes, tx.is_ignored):
count += 1
diff --git a/backend/app/services/split_service.py b/backend/app/services/split_service.py
index ac8a7b44..519ac6a9 100644
--- a/backend/app/services/split_service.py
+++ b/backend/app/services/split_service.py
@@ -86,6 +86,7 @@ async def _validate_members(
session: AsyncSession,
member_ids: list[uuid.UUID],
user_id: uuid.UUID,
+ workspace_id: uuid.UUID,
) -> uuid.UUID:
"""Ensure all members belong to a single group VISIBLE to `user_id`
(owner OR linked member). Returns that group's id."""
@@ -100,6 +101,7 @@ async def _validate_members(
.join(Group, GroupMember.group_id == Group.id)
.where(
GroupMember.id.in_(member_ids),
+ Group.workspace_id == workspace_id,
or_(Group.user_id == user_id, Group.id.in_(linked_group_ids)),
)
)
@@ -142,7 +144,7 @@ async def replace_splits(
if len(set(member_ids)) != len(member_ids):
raise ValueError("Each member can appear at most once per transaction")
- await _validate_members(session, member_ids, user_id)
+ await _validate_members(session, member_ids, user_id, transaction.workspace_id)
for member_id, share_amount, share_pct in _materialize(transaction.amount, payload):
session.add(
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index e368e7b5..31efff30 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -24,6 +24,40 @@ from app.services.fx_rate_service import stamp_primary_amount, convert as fx_con
from app.services._query_filters import counts_as_pnl, counts_as_user_pnl, reporting_date_col
+async def _ensure_category_in_workspace(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ category_id: Optional[uuid.UUID],
+) -> None:
+ if category_id is None:
+ return
+ result = await session.execute(
+ select(Category.id).where(
+ Category.id == category_id,
+ Category.workspace_id == workspace_id,
+ )
+ )
+ if result.scalar_one_or_none() is None:
+ raise ValueError("Category not found")
+
+
+async def _ensure_payee_in_workspace(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ payee_id: Optional[uuid.UUID],
+) -> None:
+ if payee_id is None:
+ return
+ result = await session.execute(
+ select(Payee.id).where(
+ Payee.id == payee_id,
+ Payee.workspace_id == workspace_id,
+ )
+ )
+ if result.scalar_one_or_none() is None:
+ raise ValueError("Payee not found")
+
+
def _apply_fx_override(transaction, amount, amount_primary=None, fx_rate_used=None):
"""Apply manual FX override values to a transaction.
@@ -461,8 +495,6 @@ async def get_transactions(
for tx in transactions:
tx.attachment_count = counts.get(tx.id, 0)
tx.payee_name = tx.payee_entity.name if tx.payee_entity else None
- if not tx.is_ignored and tx.category and tx.category.is_ignored:
- tx.is_ignored = True
# Tag shared rows with the viewer's share + the source group.
# Owned rows stay as-is. We pre-compute the viewer's linked
# member ids → group ids once, then look up each transaction's
@@ -651,6 +683,9 @@ async def create_transaction(
if not account:
raise ValueError("Account not found")
+ await _ensure_category_in_workspace(session, workspace_id, data.category_id)
+ await _ensure_payee_in_workspace(session, workspace_id, data.payee_id)
+
# Resolve currency: explicit value > account currency
currency = data.currency or account.currency
@@ -667,7 +702,10 @@ async def create_transaction(
type=data.type,
source="manual",
notes=data.notes,
+ effective_bill_date=data.effective_bill_date,
)
+ if data.effective_bill_date is not None:
+ await _resync_bill_link_from_override(session, transaction, account)
apply_effective_date(transaction, account)
session.add(transaction)
await session.flush() # get ID without committing
@@ -1122,6 +1160,11 @@ async def update_transaction(
if paired_tx and paired_tx.account_id == new_account_id:
raise ValueError("Cannot move transfer to the same account as its paired transaction")
+ if "category_id" in update_data:
+ await _ensure_category_in_workspace(session, workspace_id, update_data["category_id"])
+ if "payee_id" in update_data:
+ await _ensure_payee_in_workspace(session, workspace_id, update_data["payee_id"])
+
# Pop FX override fields before generic setattr loop
has_fx_override = "amount_primary" in update_data or "fx_rate_used" in update_data
override_amount_primary = update_data.pop("amount_primary", None)
@@ -1192,7 +1235,7 @@ async def update_transaction(
await split_service.replace_splits(session, transaction, splits_payload, user_id)
await session.commit()
- await session.refresh(transaction, ["splits"])
+ await session.refresh(transaction, ["category", "payee_entity", "splits"])
return transaction
@@ -1202,6 +1245,7 @@ async def bulk_update_category(
transaction_ids: list[uuid.UUID],
category_id: Optional[uuid.UUID] = None,
) -> int:
+ await _ensure_category_in_workspace(session, workspace_id, category_id)
result = await session.execute(
update(Transaction)
.where(
@@ -1341,6 +1385,7 @@ async def bulk_add_to_group(
group_result = await session.execute(
select(Group).where(
Group.id == group_id,
+ Group.workspace_id == workspace_id,
or_(Group.user_id == user_id, Group.id.in_(linked_group_ids)),
)
)
diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.py
index abfa38a1..ac6587b4 100644
--- a/backend/tests/test_import_service.py
+++ b/backend/tests/test_import_service.py
@@ -1150,6 +1150,35 @@ class TestImportTransactionsFx:
mock_provider.fetch_latest.assert_not_called()
mock_provider.fetch_historical.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_import_raw_payee_uses_workspace(self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):
+ from app.models.payee import Payee
+ from app.models.transaction import Transaction
+ from app.schemas.transaction import TransactionImport
+ from sqlalchemy import select
+
+ txns = [
+ TransactionImport(
+ description="Cafe memo",
+ amount=Decimal("12.00"),
+ date=date(2026, 1, 15),
+ type="debit",
+ currency=test_account.currency,
+ payee_raw="Cafe",
+ ),
+ ]
+
+ imported, skipped, _, _ = await import_transactions(
+ session, test_workspace.id, test_user.id, test_account.id, txns, "ofx",
+ )
+
+ assert imported == 1
+ assert skipped == 0
+ payee = (await session.execute(select(Payee).where(Payee.name == "Cafe"))).scalar_one()
+ tx = (await session.execute(select(Transaction).where(Transaction.payee_id == payee.id))).scalar_one()
+ assert payee.workspace_id == test_workspace.id
+ assert tx.workspace_id == test_workspace.id
+
@pytest.mark.asyncio
@patch("app.services.fx_rate_service._provider")
async def test_import_foreign_currency_without_fx_rate_auto_converts(
@@ -2200,4 +2229,4 @@ async def test_import_tolerates_duplicate_external_id_rows(
Transaction.external_id == "FITID-DUP",
)
)).scalars().all()
- assert len(remaining) == 2
\ No newline at end of file
+ assert len(remaining) == 2
diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.py
index 9a0d26ee..a3da4285 100644
--- a/backend/tests/test_new_rules_api.py
+++ b/backend/tests/test_new_rules_api.py
@@ -112,6 +112,31 @@ async def test_create_rule_does_not_overwrite_existing_category(
assert ifood["category_id"] == original
+async def test_create_rule_can_overwrite_existing_category_when_requested(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ original = str(test_categories[0].id) # IFOOD RESTAURANTE is pre-set to this
+ other = str(test_categories[1].id)
+ payload = {
+ "name": "iFood overwrite",
+ "conditions_op": "and",
+ "conditions": [{"field": "description", "op": "contains", "value": "IFOOD"}],
+ "actions": [{"op": "set_category", "value": other}],
+ "priority": 5,
+ "is_active": True,
+ "overwrite_existing_categories": True,
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 201
+ assert response.json()["applied_count"] >= 1
+
+ items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
+ ifood = {t["description"]: t for t in items}.get("IFOOD RESTAURANTE")
+ assert ifood["category_id"] != original
+ assert ifood["category_id"] == other
+
+
@pytest.mark.asyncio
async def test_create_rule_no_match_reports_zero(
client: AsyncClient, auth_headers, test_transactions, test_categories,
@@ -220,6 +245,105 @@ async def test_update_rule_applies_to_existing_transactions(
assert netflix["category_id"] == cat_food
+async def test_update_rule_can_skip_existing_transactions(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ cat_food = str(test_categories[0].id)
+ create_payload = {
+ "name": "Streaming skip",
+ "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
+
+ update_response = await client.patch(
+ f"/api/rules/{create_response.json()['id']}",
+ json={
+ "conditions": [{"field": "description", "op": "contains", "value": "NETFLIX"}],
+ "apply_to_existing": False,
+ },
+ headers=auth_headers,
+ )
+ assert update_response.status_code == 200
+ assert update_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_can_overwrite_existing_category_when_requested(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ original = str(test_categories[0].id) # IFOOD RESTAURANTE is pre-set to this
+ other = str(test_categories[1].id)
+ create_payload = {
+ "name": "iFood update overwrite",
+ "conditions_op": "and",
+ "conditions": [{"field": "description", "op": "contains", "value": "ZZZ_NOMATCH"}],
+ "actions": [{"op": "set_category", "value": other}],
+ "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
+
+ update_response = await client.patch(
+ f"/api/rules/{create_response.json()['id']}",
+ json={
+ "conditions": [{"field": "description", "op": "contains", "value": "IFOOD"}],
+ "overwrite_existing_categories": True,
+ },
+ 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"]
+ ifood = {t["description"]: t for t in items}.get("IFOOD RESTAURANTE")
+ assert ifood["category_id"] != original
+ assert ifood["category_id"] == other
+
+
+async def test_update_rule_inactive_to_active_applies_to_existing_transactions(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ cat_food = str(test_categories[0].id)
+ create_payload = {
+ "name": "Inactive Netflix",
+ "conditions_op": "and",
+ "conditions": [{"field": "description", "op": "contains", "value": "NETFLIX"}],
+ "actions": [{"op": "set_category", "value": cat_food}],
+ "priority": 5,
+ "is_active": False,
+ }
+ 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
+
+ update_response = await client.patch(
+ f"/api/rules/{create_response.json()['id']}",
+ json={"is_active": True},
+ 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
async def test_delete_rule(client: AsyncClient, auth_headers, test_rules):
rule_id = str(test_rules[0].id)
@@ -477,6 +601,40 @@ async def test_rule_user_isolation(
assert len(items) >= 5
+async def test_rule_pack_install_is_scoped_to_selected_workspace(
+ client: AsyncClient,
+ auth_headers,
+ session: AsyncSession,
+ test_user: User,
+):
+ from app.services.workspace_service import create_workspace
+
+ second = await create_workspace(
+ session,
+ name="Second",
+ creator=test_user,
+ self_membership=True,
+ seed_defaults=True,
+ )
+ second_headers = {**auth_headers, "X-Workspace-Id": str(second.id)}
+
+ response = await client.post("/api/rules/packs/BR/install", headers=second_headers)
+ assert response.status_code == 200
+ assert response.json()["installed"] > 0
+
+ second_packs = (await client.get("/api/rules/packs", headers=second_headers)).json()
+ assert next(p for p in second_packs if p["code"] == "BR")["installed"] is True
+
+ default_packs = (await client.get("/api/rules/packs", headers=auth_headers)).json()
+ assert next(p for p in default_packs if p["code"] == "BR")["installed"] is False
+
+ default_rules = (await client.get("/api/rules", headers=auth_headers)).json()
+ second_rules = (await client.get("/api/rules", headers=second_headers)).json()
+ assert "iFood / Rappi" not in {rule["name"] for rule in default_rules}
+ assert "iFood / Rappi" in {rule["name"] for rule in second_rules}
+
+
@pytest.mark.asyncio
async def test_export_rules_serializes_category_actions_by_name(client: AsyncClient, auth_headers, test_rules, test_categories):
response = await client.get("/api/rules/export", headers=auth_headers)
diff --git a/backend/tests/test_providers_simplefin.py b/backend/tests/test_providers_simplefin.py
index 930d3751..04b57d51 100644
--- a/backend/tests/test_providers_simplefin.py
+++ b/backend/tests/test_providers_simplefin.py
@@ -17,6 +17,7 @@ import pytest
from app.providers.base import ProviderUserActionRequired, SessionExpiredError
from app.providers.simplefin import (
SimpleFinProvider,
+ _accounts_url_and_auth,
_decode_setup_token,
_epoch_to_date,
)
@@ -73,12 +74,19 @@ def test_decode_setup_token_rejects_garbage():
def test_epoch_to_date_handles_unset():
assert _epoch_to_date(None) is None
assert _epoch_to_date("") is None
+ assert _epoch_to_date(0) is None
def test_epoch_to_date_parses_seconds():
assert _epoch_to_date(1672531200) == date(2023, 1, 1)
+def test_accounts_url_and_auth_strips_userinfo():
+ url, auth = _accounts_url_and_auth("https://u:[email protected]/simplefin")
+ assert url == "https://bridge.example/simplefin/accounts"
+ assert auth == ("u", "p")
+
+
# ----- claim flow -------------------------------------------------------------
@@ -216,6 +224,18 @@ async def test_401_response_signals_credentials_invalid():
await SimpleFinProvider().get_accounts(creds)
+async def test_accounts_request_moves_url_userinfo_to_auth_header():
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.userinfo == b""
+ assert "authorization" in request.headers
+ return httpx.Response(200, json={"accounts": []})
+
+ creds = {"access_url": "https://u:[email protected]/simplefin"}
+ with _patched_client(handler):
+ await SimpleFinProvider().get_accounts(creds)
+
+
@pytest.mark.asyncio
async def test_missing_access_url_raises_session_expired():
with pytest.raises(SessionExpiredError):
@@ -231,6 +251,8 @@ async def test_get_transactions_filters_by_account_and_parses_signs():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/simplefin/accounts"
+ assert "u:p@" not in str(request.url)
+ assert request.headers["authorization"].startswith("Basic ")
# We always request a specific account
assert request.url.params.get("account") == "acc-1"
assert request.url.params.get("pending") == "1"
@@ -284,6 +306,38 @@ async def test_get_transactions_filters_by_account_and_parses_signs():
assert by_id["t2"].type == "credit"
+async def test_get_transactions_uses_transacted_at_when_posted_zero():
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "accounts": [
+ {
+ "id": "acc-1",
+ "transactions": [
+ {
+ "id": "t1",
+ "amount": "-12.34",
+ "posted": 0,
+ "transacted_at": 1672617600,
+ "description": "Coffee",
+ },
+ ],
+ },
+ ]
+ },
+ )
+
+ creds = {"access_url": "https://u:[email protected]/simplefin"}
+ with _patched_client(handler):
+ txns = await SimpleFinProvider().get_transactions(
+ creds, "acc-1", since=date(2023, 1, 1)
+ )
+
+ assert txns[0].date == date(2023, 1, 2)
+
+
@pytest.mark.asyncio
async def test_get_transactions_chunks_long_windows():
"""``since`` more than 90 days ago → multiple requests with shifting windows."""
diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.py
index c6967abb..116d23bc 100644
--- a/backend/tests/test_rule_engine.py
+++ b/backend/tests/test_rule_engine.py
@@ -221,6 +221,36 @@ def test_lte_greater():
assert evaluate_conditions("and", conditions, tx) is False
+def test_date_gt():
+ conditions = [{"field": "date", "op": "gt", "value": "2026-02-09"}]
+ tx = make_tx(date=date(2026, 2, 10))
+ assert evaluate_conditions("and", conditions, tx) is True
+
+
+def test_date_gte_equal():
+ conditions = [{"field": "date", "op": "gte", "value": "2026-02-10"}]
+ tx = make_tx(date=date(2026, 2, 10))
+ assert evaluate_conditions("and", conditions, tx) is True
+
+
+def test_date_lt():
+ conditions = [{"field": "date", "op": "lt", "value": "2026-02-11"}]
+ tx = make_tx(date=date(2026, 2, 10))
+ assert evaluate_conditions("and", conditions, tx) is True
+
+
+def test_date_lte_equal():
+ conditions = [{"field": "date", "op": "lte", "value": "2026-02-10"}]
+ tx = make_tx(date=date(2026, 2, 10))
+ assert evaluate_conditions("and", conditions, tx) is True
+
+
+def test_invalid_date_comparison_returns_false():
+ conditions = [{"field": "date", "op": "gte", "value": "not-a-date"}]
+ tx = make_tx(date=date(2026, 2, 10))
+ assert evaluate_conditions("and", conditions, tx) is False
+
+
def test_empty_conditions_returns_false():
tx = make_tx()
assert evaluate_conditions("and", [], tx) is False
diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.py
index 81d69ef1..9966cb46 100644
--- a/backend/tests/test_rule_service.py
+++ b/backend/tests/test_rule_service.py
@@ -6,8 +6,10 @@ import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.category import Category
+from app.models.payee import Payee
from app.models.transaction import Transaction
-from app.schemas.rule import RuleAction, RuleCondition, RuleCreate, RuleUpdate
+from app.schemas.rule import RuleAction, RuleCondition, RuleCreate, RuleExportItem, RuleExportPayload, RuleUpdate
from app.services.rule_service import (
DuplicateRuleError,
RULE_PACKS,
@@ -19,6 +21,7 @@ from app.services.rule_service import (
get_installed_packs,
get_rule,
get_rules,
+ import_rules,
install_rule_pack,
update_rule,
)
@@ -193,6 +196,108 @@ async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_use
)
+async def test_create_rule_rejects_unknown_action(session: AsyncSession, test_user, test_workspace):
+ with pytest.raises(ValueError, match="Invalid rule action"):
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Bad Action",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="explode", value="nope")],
+ ),
+ )
+
+
+async def test_create_rule_rejects_category_outside_workspace(
+ session: AsyncSession, test_user, test_workspace
+):
+ with pytest.raises(ValueError, match="Category not found"):
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Wrong Category",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(uuid.uuid4()))],
+ ),
+ )
+
+
+async def test_update_rule_rejects_payee_outside_workspace(
+ session: AsyncSession, test_user, test_workspace
+):
+ payee = Payee(user_id=test_user.id, workspace_id=uuid.uuid4(), name="Foreign")
+ session.add(payee)
+ await session.commit()
+
+ rule = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Safe",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="append_notes", value="#safe")],
+ ),
+ )
+
+ with pytest.raises(ValueError, match="Payee not found"):
+ await update_rule(
+ session,
+ rule.id,
+ test_workspace.id,
+ RuleUpdate(actions=[RuleAction(op="set_payee", value=str(payee.id))]),
+ )
+
+
+async def test_import_rules_skips_invalid_rules(
+ session: AsyncSession, test_user, test_workspace
+):
+ category = Category(
+ user_id=test_user.id,
+ workspace_id=uuid.uuid4(),
+ name="Foreign",
+ icon="x",
+ color="#000000",
+ )
+ session.add(category)
+ await session.commit()
+
+ payload = RuleExportPayload(
+ rules=[
+ RuleExportItem(
+ name="Foreign category",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="set_category", value=str(category.id))],
+ ),
+ RuleExportItem(
+ name="Invalid condition",
+ conditions=[RuleCondition(field="description", op="invalid", value="X")],
+ actions=[RuleAction(op="append_notes", value="#bad")],
+ ),
+ RuleExportItem(
+ name="Valid",
+ conditions=[RuleCondition(field="description", op="contains", value="X")],
+ actions=[RuleAction(op="append_notes", value="#valid")],
+ ),
+ ]
+ )
+
+ result = await import_rules(
+ session, test_workspace.id, test_user.id, payload, overwrite=True
+ )
+
+ assert result.imported == 1
+ assert result.skipped == 2
+
+
# ---------------------------------------------------------------------------
# apply_rules_to_transaction
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
index fd2a3561..5e36c030 100644
--- a/backend/tests/test_transaction_service.py
+++ b/backend/tests/test_transaction_service.py
@@ -7,6 +7,7 @@ import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.credit_card_bill import CreditCardBill
from app.models.rule import Rule
from app.models.transaction import Transaction
from app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate
@@ -66,6 +67,53 @@ async def test_create_transaction_manual(
assert txn.category_id == test_categories[0].id
+async def test_create_transaction_honors_effective_bill_date(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Card",
+ type="credit_card",
+ balance=Decimal("0"),
+ currency="BRL",
+ statement_close_day=10,
+ payment_due_day=20,
+ )
+ bill = CreditCardBill(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ external_id="bill-1",
+ due_date=date(2025, 5, 20),
+ total_amount=Decimal("100"),
+ currency="BRL",
+ )
+ session.add_all([account, bill])
+ await session.commit()
+
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ description="Manual charge",
+ amount=Decimal("50.00"),
+ date=date(2025, 3, 5),
+ type="debit",
+ account_id=account.id,
+ effective_bill_date=date(2025, 5, 20),
+ ),
+ )
+
+ assert txn.effective_bill_date == date(2025, 5, 20)
+ assert txn.effective_date == date(2025, 5, 20)
+ assert txn.bill_id == bill.id
+
+
@pytest.mark.asyncio
async def test_create_transaction_applies_rules(
session: AsyncSession, test_user, test_workspace, test_categories, txn_account
diff --git a/backend/tests/test_transaction_service_coverage.py b/backend/tests/test_transaction_service_coverage.py
index 199a3399..4a4459c0 100644
--- a/backend/tests/test_transaction_service_coverage.py
+++ b/backend/tests/test_transaction_service_coverage.py
@@ -252,6 +252,38 @@ async def test_get_transactions_summary_excludes_ignored(session, test_user, tes
assert summary["excluded"] == Decimal("999")
+async def test_get_transactions_summary_excludes_ignored_category(
+ session, test_user, test_workspace, acct
+):
+ from app.models.category import Category
+
+ ignored = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Ignored",
+ is_ignored=True,
+ )
+ session.add(ignored)
+ await session.commit()
+
+ await _mk_txn(session, test_user, acct, description="Counted", amount=Decimal("100"), type="debit")
+ await _mk_txn(
+ session,
+ test_user,
+ acct,
+ description="Ignored by category",
+ amount=Decimal("999"),
+ type="debit",
+ category_id=ignored.id,
+ )
+ _, _, summary = await get_transactions(
+ session, test_workspace.id, test_user.id, include_summary=True
+ )
+ assert summary["expense"] == Decimal("100")
+ assert summary["excluded"] == Decimal("999")
+
+
async def test_get_transactions_summary_excludes_transfers_and_treat_as_transfer(
session, test_user, test_workspace, acct
):
diff --git a/backend/tests/test_transactions_api.py b/backend/tests/test_transactions_api.py
index 8832e247..77cea431 100644
--- a/backend/tests/test_transactions_api.py
+++ b/backend/tests/test_transactions_api.py
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
from app.models.transaction import Transaction
from app.models.category import Category
+from app.models.payee import Payee
from app.models.user import User
@@ -413,18 +414,26 @@ async def test_create_transaction_invalid_account(
@pytest.mark.asyncio
async def test_update_transaction(
- client: AsyncClient, auth_headers, test_transactions: list[Transaction],
+ client: AsyncClient, auth_headers, session: AsyncSession, test_workspace,
+ test_user: User, test_transactions: list[Transaction],
test_categories: list[Category],
):
+ payee = Payee(user_id=test_user.id, workspace_id=test_workspace.id, name="Netflix")
+ session.add(payee)
+ await session.commit()
+
txn_id = str(test_transactions[4].id) # NETFLIX, no category
response = await client.patch(
f"/api/transactions/{txn_id}",
headers=auth_headers,
- json={"category_id": str(test_categories[0].id)},
+ json={"category_id": str(test_categories[0].id), "payee_id": str(payee.id)},
)
assert response.status_code == 200
data = response.json()
assert data["category_id"] == str(test_categories[0].id)
+ assert data["category"]["id"] == str(test_categories[0].id)
+ assert data["payee_id"] == str(payee.id)
+ assert data["payee_name"] == "Netflix"
@pytest.mark.asyncio
diff --git a/backend/tests/test_transactions_api_coverage.py b/backend/tests/test_transactions_api_coverage.py
index 74533188..0a8c29e3 100644
--- a/backend/tests/test_transactions_api_coverage.py
+++ b/backend/tests/test_transactions_api_coverage.py
@@ -5,11 +5,18 @@ ignore toggle, bulk endpoints, transfer/link/counterpart/candidates, and
error branches (404/400/422).
"""
from datetime import date
+import uuid
import pytest
from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.category import Category
+from app.models.group import Group, GroupMember
+from app.models.transaction import Transaction
+from app.services.workspace_service import create_workspace
NONEXISTENT = "00000000-0000-0000-0000-000000000000"
@@ -125,6 +132,63 @@ async def test_get_transaction(client: AsyncClient, auth_headers, test_transacti
assert resp.json()["description"] == tx.description
+async def test_editing_transaction_does_not_persist_ignored_category_state(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace, test_account
+):
+ ignored = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Ignored",
+ is_ignored=True,
+ )
+ normal = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Normal",
+ )
+ session.add_all([ignored, normal])
+ await session.commit()
+
+ resp = await client.post(
+ "/api/transactions", headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "category_id": str(ignored.id),
+ "description": "Hidden fee",
+ "amount": "12.50",
+ "date": date.today().isoformat(),
+ "type": "debit",
+ },
+ )
+ assert resp.status_code == 201, resp.text
+
+ transaction_id = resp.json()["id"]
+ edit = await client.patch(
+ f"/api/transactions/{transaction_id}", headers=auth_headers, json={"notes": "edited"}
+ )
+ assert edit.status_code == 200
+ assert edit.json()["is_ignored"] is True
+ persisted = await session.scalar(
+ select(Transaction.is_ignored).where(Transaction.id == uuid.UUID(transaction_id))
+ )
+ assert persisted is False
+
+ moved = await client.patch(
+ f"/api/transactions/{transaction_id}",
+ headers=auth_headers,
+ json={"category_id": str(normal.id)},
+ )
+ assert moved.status_code == 200
+ assert moved.json()["is_ignored"] is False
+ persisted = await session.scalar(
+ select(Transaction.is_ignored).where(Transaction.id == uuid.UUID(transaction_id))
+ )
+ assert persisted is False
+
+
@pytest.mark.asyncio
async def test_get_transaction_not_found(client: AsyncClient, auth_headers, test_account):
resp = await client.get(f"/api/transactions/{NONEXISTENT}", headers=auth_headers)
@@ -162,6 +226,41 @@ async def test_create_transaction_bad_account_400(client: AsyncClient, auth_head
assert resp.status_code == 400
+async def test_create_transaction_rejects_category_from_other_workspace(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_account
+):
+ other_ws = await create_workspace(
+ session,
+ name="Other",
+ creator=test_user,
+ self_membership=True,
+ seed_defaults=False,
+ )
+ other_category = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=other_ws.id,
+ name="Other category",
+ )
+ session.add(other_category)
+ await session.commit()
+
+ resp = await client.post(
+ "/api/transactions", headers=auth_headers,
+ json={
+ "account_id": str(test_account.id),
+ "category_id": str(other_category.id),
+ "description": "Wrong category",
+ "amount": "1.00",
+ "date": date.today().isoformat(),
+ "type": "debit",
+ },
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "Category not found"
+
+
@pytest.mark.asyncio
async def test_update_transaction(client: AsyncClient, auth_headers, test_transactions):
tx = test_transactions[0]
@@ -184,6 +283,35 @@ async def test_update_transaction_not_found(client: AsyncClient, auth_headers, t
assert resp.status_code == 404
+async def test_update_transaction_rejects_category_from_other_workspace(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_transactions
+):
+ other_ws = await create_workspace(
+ session,
+ name="Other",
+ creator=test_user,
+ self_membership=True,
+ seed_defaults=False,
+ )
+ other_category = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=other_ws.id,
+ name="Other category",
+ )
+ session.add(other_category)
+ await session.commit()
+
+ tx = test_transactions[0]
+ resp = await client.patch(
+ f"/api/transactions/{tx.id}", headers=auth_headers,
+ json={"category_id": str(other_category.id)},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "Category not found"
+
+
@pytest.mark.asyncio
async def test_toggle_ignore(client: AsyncClient, auth_headers, test_transactions):
tx = test_transactions[0]
@@ -228,6 +356,37 @@ async def test_bulk_categorize(client: AsyncClient, auth_headers, test_transacti
assert resp.json()["updated"] == 2
+async def test_bulk_categorize_rejects_category_from_other_workspace(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_transactions
+):
+ other_ws = await create_workspace(
+ session,
+ name="Other",
+ creator=test_user,
+ self_membership=True,
+ seed_defaults=False,
+ )
+ other_category = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=other_ws.id,
+ name="Other category",
+ )
+ session.add(other_category)
+ await session.commit()
+
+ resp = await client.patch(
+ "/api/transactions/bulk-categorize", headers=auth_headers,
+ json={
+ "transaction_ids": [str(test_transactions[0].id)],
+ "category_id": str(other_category.id),
+ },
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "Category not found"
+
+
@pytest.mark.asyncio
async def test_bulk_add_and_remove_tags(client: AsyncClient, auth_headers, test_transactions):
ids = [str(t.id) for t in test_transactions[:2]]
@@ -256,6 +415,47 @@ async def test_bulk_add_to_group_bad_group_400(client: AsyncClient, auth_headers
assert resp.status_code == 400
+async def test_bulk_add_to_group_rejects_group_from_other_workspace(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_transactions
+):
+ other_ws = await create_workspace(
+ session,
+ name="Other",
+ creator=test_user,
+ self_membership=True,
+ seed_defaults=False,
+ )
+ group = Group(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=other_ws.id,
+ name="Other group",
+ default_currency="BRL",
+ )
+ member = GroupMember(
+ id=uuid.uuid4(),
+ group_id=group.id,
+ workspace_id=other_ws.id,
+ name="Me",
+ linked_user_id=test_user.id,
+ is_self=True,
+ )
+ session.add_all([group, member])
+ await session.commit()
+
+ resp = await client.patch(
+ "/api/transactions/bulk-add-to-group", headers=auth_headers,
+ json={
+ "transaction_ids": [str(test_transactions[0].id)],
+ "group_id": str(group.id),
+ "share_type": "equal",
+ },
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "Group not found"
+
+
# ---------------------------------------------------------------------------
# transfer / link / counterpart / candidates
# ---------------------------------------------------------------------------
diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsx
index 076a62d6..30e492cc 100644
--- a/frontend/src/components/rule-dialog.tsx
+++ b/frontend/src/components/rule-dialog.tsx
@@ -93,6 +93,8 @@ export function RuleDialog({
)
const [priority, setPriority] = useState(rule?.priority ?? 0)
const [isActive, setIsActive] = useState(rule?.is_active ?? true)
+ const [applyToExisting, setApplyToExisting] = useState(!rule)
+ const [overwriteExistingCategories, setOverwriteExistingCategories] = useState(false)
const selectClass = 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'
@@ -136,7 +138,16 @@ export function RuleDialog({
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
- onSave({ name, conditions_op: conditionsOp, conditions, actions, priority, is_active: isActive })
+ onSave({
+ name,
+ conditions_op: conditionsOp,
+ conditions,
+ actions,
+ priority,
+ is_active: isActive,
+ apply_to_existing: applyToExisting,
+ overwrite_existing_categories: applyToExisting && overwriteExistingCategories,
+ })
}
return (
@@ -339,6 +350,32 @@ export function RuleDialog({
<span className="text-sm text-foreground">{t('rules.ruleActive')}</span>
</label>
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={applyToExisting}
+ onChange={(e) => setApplyToExisting(e.target.checked)}
+ className="h-4 w-4 rounded border-border"
+ />
+ <span className="text-sm text-foreground">
+ {t('rules.applyToExisting', 'Apply matching actions to existing transactions')}
+ </span>
+ </label>
+
+ {applyToExisting && (
+ <label className="flex items-center gap-2 cursor-pointer pl-6">
+ <input
+ type="checkbox"
+ checked={overwriteExistingCategories}
+ onChange={(e) => setOverwriteExistingCategories(e.target.checked)}
+ className="h-4 w-4 rounded border-border"
+ />
+ <span className="text-sm text-foreground">
+ {t('rules.overwriteExistingCategories', 'Also replace existing categories')}
+ </span>
+ </label>
+ )}
+
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button>
<Button type="submit" disabled={loading}>
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index ead5d743..0284d94d 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Auch die benötigten Standardkategorien erstellen",
"duplicateName": "Eine Regel mit diesem Namen existiert bereits",
"sectionTitle": "Kategorisierungsregeln",
- "reapplyAll": "Alle neu anwenden",
- "confirmReapplyAll": "Alle Regeln erneut auf alle Transaktionen anwenden? Dadurch können bestehende Transaktionsfelder geändert werden.",
+ "resetAndReapplyAll": "Zurücksetzen und erneut anwenden",
+ "confirmResetAndReapplyAll": "Kategorien und Notizen übereinstimmender Transaktionen zurücksetzen und anschließend alle aktiven Regeln erneut anwenden?",
"add": "Hinzufügen",
"created": "Regel erstellt",
"createdAndApplied": "Regel erstellt und auf {{count}} Transaktionen angewendet",
@@ -801,6 +801,8 @@
"priority": "Priorität",
"conditions": "Bedingungen",
"actions": "Aktionen",
+ "applyToExisting": "Übereinstimmende Aktionen auf bestehende Transaktionen anwenden",
+ "overwriteExistingCategories": "Auch bestehende Kategorien ersetzen",
"andOp": "UND",
"orOp": "ODER",
"addCondition": "Bedingung hinzufügen",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index dbf8c441..b1b2623b 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Also create default categories the pack needs",
"duplicateName": "A rule with this name already exists",
"sectionTitle": "Categorization Rules",
- "reapplyAll": "Reapply all",
- "confirmReapplyAll": "Reapply all rules to all transactions? This can change existing transaction fields.",
+ "resetAndReapplyAll": "Reset and reapply",
+ "confirmResetAndReapplyAll": "Reset matching transaction categories and notes, then reapply all active rules?",
"add": "Add",
"created": "Rule created",
"createdAndApplied": "Rule created and applied to {{count}} transactions",
@@ -801,6 +801,8 @@
"priority": "Priority",
"conditions": "Conditions",
"actions": "Actions",
+ "applyToExisting": "Apply matching actions to existing transactions",
+ "overwriteExistingCategories": "Also replace existing categories",
"andOp": "AND",
"orOp": "OR",
"addCondition": "Add condition",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index d84ca11a..6441218f 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Crear también las categorías predeterminadas que necesita el paquete",
"duplicateName": "Ya existe una regla con este nombre",
"sectionTitle": "Reglas de categorización",
- "reapplyAll": "Reaplicar todo",
- "confirmReapplyAll": "¿Reaplicar todas las reglas a todas las transacciones? Esto puede cambiar los campos existentes de las transacciones.",
+ "resetAndReapplyAll": "Restablecer y reaplicar",
+ "confirmResetAndReapplyAll": "¿Restablecer categorías y notas de las transacciones coincidentes y reaplicar todas las reglas activas?",
"add": "Agregar",
"created": "Regla creada",
"createdAndApplied": "Regla creada y aplicada a {{count}} transacciones",
@@ -801,6 +801,8 @@
"priority": "Prioridad",
"conditions": "Condiciones",
"actions": "Acciones",
+ "applyToExisting": "Aplicar acciones coincidentes a transacciones existentes",
+ "overwriteExistingCategories": "También reemplazar categorías existentes",
"andOp": "Y",
"orOp": "O",
"addCondition": "Agregar condición",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 784ca684..968994c5 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Créer aussi les catégories par défaut dont le pack a besoin",
"duplicateName": "Une règle portant ce nom existe déjà",
"sectionTitle": "Règles de catégorisation",
- "reapplyAll": "Tout réappliquer",
- "confirmReapplyAll": "Réappliquer toutes les règles à toutes les transactions ? Cela peut modifier des champs de transactions existantes.",
+ "resetAndReapplyAll": "Réinitialiser et réappliquer",
+ "confirmResetAndReapplyAll": "Réinitialiser les catégories et les notes des transactions correspondantes, puis réappliquer toutes les règles actives ?",
"add": "Ajouter",
"created": "Règle créée",
"createdAndApplied": "Règle créée et appliquée à {{count}} transactions",
@@ -801,6 +801,8 @@
"priority": "Priorité",
"conditions": "Conditions",
"actions": "Actions",
+ "applyToExisting": "Appliquer les actions correspondantes aux transactions existantes",
+ "overwriteExistingCategories": "Remplacer aussi les catégories existantes",
"andOp": "ET",
"orOp": "OU",
"addCondition": "Ajouter une condition",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 69a4e064..ba4dede6 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Crea anche le categorie predefinite necessarie al pacchetto",
"duplicateName": "Esiste già una regola con questo nome",
"sectionTitle": "Regole di categorizzazione",
- "reapplyAll": "Riapplica tutte",
- "confirmReapplyAll": "Riapplicare tutte le regole a tutte le transazioni? Questa operazione può modificare i campi esistenti delle transazioni.",
+ "resetAndReapplyAll": "Reimposta e riapplica",
+ "confirmResetAndReapplyAll": "Reimpostare categorie e note delle transazioni corrispondenti e riapplicare tutte le regole attive?",
"add": "Aggiungi",
"created": "Regola creata",
"createdAndApplied": "Regola creata e applicata a {{count}} transazioni",
@@ -801,6 +801,8 @@
"priority": "Priorità",
"conditions": "Condizioni",
"actions": "Azioni",
+ "applyToExisting": "Applica le azioni corrispondenti alle transazioni esistenti",
+ "overwriteExistingCategories": "Sostituisci anche le categorie esistenti",
"andOp": "E",
"orOp": "O",
"addCondition": "Aggiungi condizione",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index f7518e88..3abdc058 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -835,8 +835,8 @@
"createMissingCategories": "Utwórz też domyślne kategorie wymagane przez pakiet",
"duplicateName": "Reguła o tej nazwie już istnieje",
"sectionTitle": "Reguły kategoryzacji",
- "reapplyAll": "Zastosuj ponownie wszystkie",
- "confirmReapplyAll": "Zastosować ponownie wszystkie reguły do wszystkich transakcji? Może to zmienić istniejące pola transakcji.",
+ "resetAndReapplyAll": "Zresetuj i zastosuj ponownie",
+ "confirmResetAndReapplyAll": "Zresetować kategorie i notatki pasujących transakcji, a następnie zastosować ponownie wszystkie aktywne reguły?",
"add": "Dodaj",
"created": "Utworzono regułę",
"createdAndApplied": "Utworzono regułę i zastosowano do {{count}} transakcji",
@@ -855,6 +855,8 @@
"priority": "Priorytet",
"conditions": "Warunki",
"actions": "Akcje",
+ "applyToExisting": "Zastosuj pasujące akcje do istniejących transakcji",
+ "overwriteExistingCategories": "Zastąp też istniejące kategorie",
"andOp": "ORAZ",
"orOp": "LUB",
"addCondition": "Dodaj warunek",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index eac9eff2..050883c9 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Criar também as categorias padrão que o pacote precisa",
"duplicateName": "Já existe uma regra com este nome",
"sectionTitle": "Regras de Categorização",
- "reapplyAll": "Reaplicar todas",
- "confirmReapplyAll": "Reaplicar todas as regras a todas as transações? Isso pode alterar campos existentes das transações.",
+ "resetAndReapplyAll": "Redefinir e reaplicar",
+ "confirmResetAndReapplyAll": "Redefinir categorias e notas das transações correspondentes e reaplicar todas as regras ativas?",
"add": "Adicionar",
"created": "Regra criada",
"createdAndApplied": "Regra criada e aplicada a {{count}} transações",
@@ -801,6 +801,8 @@
"priority": "Prioridade",
"conditions": "Condições",
"actions": "Ações",
+ "applyToExisting": "Aplicar ações correspondentes às transações existentes",
+ "overwriteExistingCategories": "Também substituir categorias existentes",
"andOp": "E (AND)",
"orOp": "OU (OR)",
"addCondition": "Adicionar condição",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 98661b80..f1c73fb2 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Также создать категории по умолчанию, необходимые пакету",
"duplicateName": "Правило с таким именем уже существует",
"sectionTitle": "Правила категоризации",
- "reapplyAll": "Применить заново все",
- "confirmReapplyAll": "Применить заново все правила ко всем транзакциям? Это может изменить существующие поля транзакций.",
+ "resetAndReapplyAll": "Сбросить и применить заново",
+ "confirmResetAndReapplyAll": "Сбросить категории и примечания у совпадающих транзакций, затем заново применить все активные правила?",
"add": "Добавить",
"created": "Правило создано",
"createdAndApplied": "Правило создано и применено к {{count}} транзакциям",
@@ -801,6 +801,8 @@
"priority": "Приоритет",
"conditions": "Условия",
"actions": "Действия",
+ "applyToExisting": "Применить совпадающие действия к существующим транзакциям",
+ "overwriteExistingCategories": "Также заменить существующие категории",
"andOp": "И",
"orOp": "ИЛИ",
"addCondition": "Добавить условие",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index c5eb3675..ef72b5a8 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -784,8 +784,8 @@
"createMissingCategories": "Також створити категорії за замовчуванням, необхідні пакету",
"duplicateName": "Правило з такою назвою вже існує",
"sectionTitle": "Правила категоризації",
- "reapplyAll": "Застосувати заново всі",
- "confirmReapplyAll": "Застосувати заново всі правила до всіх транзакцій? Це може змінити наявні поля транзакцій.",
+ "resetAndReapplyAll": "Скинути й застосувати заново",
+ "confirmResetAndReapplyAll": "Скинути категорії та примітки у відповідних транзакцій, а потім заново застосувати всі активні правила?",
"add": "Додати",
"created": "Правило створено",
"createdAndApplied": "Правило створено й застосовано до {{count}} транзакцій",
@@ -801,6 +801,8 @@
"priority": "Пріоритет",
"conditions": "Умови",
"actions": "Дії",
+ "applyToExisting": "Застосувати відповідні дії до наявних транзакцій",
+ "overwriteExistingCategories": "Також замінити наявні категорії",
"andOp": "І",
"orOp": "АБО",
"addCondition": "Додати умову",
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index 2d0e6438..6a0ee133 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -274,12 +274,18 @@ export default function DashboardPage() {
const createRuleMutation = useMutation({
mutationFn: (data: Omit<Rule, 'id' | 'user_id'>) => rulesApi.create(data),
- onSuccess: () => {
+ onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey: ['rules'] })
- invalidateFinancialQueries(queryClient)
setCreateRuleOpen(false)
setCreateRuleInitialData(undefined)
- toast.success(t('rules.created'))
+ const applied = result.applied_count ?? 0
+ if (applied > 0) {
+ invalidateFinancialQueries(queryClient)
+ queryClient.invalidateQueries({ queryKey: ['payees'] })
+ toast.success(t('rules.createdAndApplied', { count: applied }))
+ } else {
+ toast.success(t('rules.created'))
+ }
},
onError: (error: unknown) => {
const err = error as { response?: { status?: number } }
diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsx
index 1a6800d3..7c95bac2 100644
--- a/frontend/src/pages/rules.tsx
+++ b/frontend/src/pages/rules.tsx
@@ -173,6 +173,7 @@ export default function RulesPage() {
const applied = result.applied_count ?? 0
if (applied > 0) {
invalidateFinancialQueries(queryClient)
+ queryClient.invalidateQueries({ queryKey: ['payees'] })
toast.success(t('rules.createdAndApplied', { count: applied }))
} else {
toast.success(t('rules.created'))
@@ -198,6 +199,7 @@ export default function RulesPage() {
const applied = result.applied_count ?? 0
if (applied > 0) {
invalidateFinancialQueries(queryClient)
+ queryClient.invalidateQueries({ queryKey: ['payees'] })
toast.success(t('rules.updatedAndApplied', { count: applied }))
} else {
toast.success(t('rules.updated'))
@@ -226,6 +228,7 @@ export default function RulesPage() {
mutationFn: () => rulesApi.applyAll(),
onSuccess: (data) => {
invalidateFinancialQueries(queryClient)
+ queryClient.invalidateQueries({ queryKey: ['payees'] })
toast.success(t('rules.applied', { count: data.applied }))
},
onError: () => toast.error(t('common.error')),
@@ -345,14 +348,14 @@ export default function RulesPage() {
size="sm"
className="gap-1.5 h-8"
onClick={() => {
- if (window.confirm(t('rules.confirmReapplyAll', 'Reapply all rules to all transactions? This can change existing transaction fields.'))) {
+ if (window.confirm(t('rules.confirmResetAndReapplyAll', 'Reset matching transaction categories and notes, then reapply all active rules?'))) {
applyAllMutation.mutate()
}
}}
disabled={applyAllMutation.isPending}
>
<RefreshCw size={12} />
- <span className="hidden sm:inline">{t('rules.reapplyAll')}</span>
+ <span className="hidden sm:inline">{t('rules.resetAndReapplyAll', 'Reset and reapply')}</span>
</Button>
<Button size="sm" className="gap-1.5 h-8" onClick={openCreate}>
<Plus size={13} /> <span className="hidden sm:inline">{t('rules.add')}</span>
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index e4943867..593bea46 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -626,6 +626,7 @@ export default function TransactionsPage() {
const applied = result.applied_count ?? 0
if (applied > 0) {
invalidateAfterTxMutation()
+ queryClient.invalidateQueries({ queryKey: ['payees'] })
toast.success(t('rules.createdAndApplied', { count: applied }))
} else {
toast.success(t('rules.created'))
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 61369055..2726548b 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -360,6 +360,8 @@ export interface Rule {
actions: RuleAction[]
priority: number
is_active: boolean
+ apply_to_existing?: boolean
+ overwrite_existing_categories?: boolean
}
export interface RuleExportItem {