Give tips a date, a scope per child, and a dismissal that sticks

Three faults, all invisible while the tests passed. Advice was built for the
first child only, so a second child got none. The planned days feeding every
count were fetched once per parent and appended to one list, so a couple's
days were counted twice and every intensity and projection derived from them
was wrong. And dismissing a tip forgot the moment the page reloaded.

Tips now carry the date they concern, lifted from figures the rules already
computed, so a view of a month can show only what applies to it. They are
built per child and identified per child, so the same rule firing for two
children is two separate pieces of advice.

A dismissal is stored against a fingerprint of the facts that were dismissed.
When those facts change the advice returns with its new numbers, rather than
one click silencing a warning about a forfeiture that keeps growing.
This commit is contained in:
2026-09-17 22:32:03 +02:00
parent c15cd44cb4
commit fdbfb7d580
20 changed files with 1396 additions and 57 deletions
@@ -0,0 +1,305 @@
"""Regression tests for `TipsService._build_context` and multi-child scoping.
`_build_context` used to have two bugs:
1. Single-child only: it read `children[0]` and fetched leave/planned-day
data for that child alone, so a workspace with two children got tips
about one and silence about the other.
2. Doubled planned days: `list_by_workspace_child` already returns every
parent's days for a child, but the old code called it *inside* the
per-parent loop and kept appending — an N-parent workspace saw every
planned day N times, corrupting every count-sensitive rule (intensity,
SGI, age-4 projections).
These tests go through the real sqlite repositories (via the `tips_service`
fixture in conftest.py), not hand-built `TipsContext`s, because the bugs
lived in the fetching/wiring code itself.
"""
from datetime import date, datetime, timedelta
from uuid import uuid4
import pytest_asyncio
from app.entities.child import Child
from app.entities.parental_leave import ParentalLeaveFetch, TierData
from app.entities.personal_data import PersonalData
from app.entities.planned_leave import PlannedLeaveDay
from app.entities.workspace import Workspace
from app.repositories_impl.sqlite.child_repository import SQLiteChildRepository
from app.repositories_impl.sqlite.parental_leave_repository import SQLiteParentalLeaveRepository
from app.repositories_impl.sqlite.personal_data_repository import SQLitePersonalDataRepository
from app.repositories_impl.sqlite.planned_leave_repository import SQLitePlannedLeaveRepository
from app.repositories_impl.sqlite.workspace_repository import SQLiteWorkspaceRepository
from app.services.tips_service import TipsService
from app.utils.errors import NotFoundError
def _make_fetch(
personal_data_uuid,
workspace_id,
child_id,
total: int = 240,
used: int = 20,
) -> ParentalLeaveFetch:
now = datetime.now()
tier = TierData(
sjukpenning_total=390,
sjukpenning_used=used,
sjukpenning_left=390 - used,
lagsta_niva_total=90,
lagsta_niva_used=0,
lagsta_niva_left=90,
)
return ParentalLeaveFetch(
id=uuid4(),
personal_data_uuid=personal_data_uuid,
workspace_id=workspace_id,
child_id=child_id,
source="manual",
fetched_at=now,
total_days=total,
days_used=used,
days_left=total - used,
reserved_days_total=90,
reserved_days_left=90,
transferable_days_left=50,
dubbeldagar_left=60,
tier_data=tier,
created_at=now,
updated_at=now,
)
def _make_planned_day(
workspace_id, child_id, parent_uuid, day: date, day_type: str = "sjukpenning"
) -> PlannedLeaveDay:
return PlannedLeaveDay(
id=uuid4(),
workspace_id=workspace_id,
child_id=child_id,
parent_personal_data_uuid=parent_uuid,
date=day,
day_type=day_type,
)
@pytest_asyncio.fixture
async def two_parent_one_child_workspace(
workspace_repo: SQLiteWorkspaceRepository,
personal_data_repo: SQLitePersonalDataRepository,
child_repo: SQLiteChildRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
):
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent1 = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Alice", created_at=now)
)
parent2 = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Bob", created_at=now)
)
child = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Barn",
birth_date=date.today().replace(year=date.today().year - 1),
created_at=now,
)
)
# A known, small day set: 3 future planned days for parent1 only.
today = date.today()
for i in range(3):
await planned_leave_repo.create(
_make_planned_day(ws.id, child.id, parent1.uuid, today + timedelta(days=i + 40))
)
return ws, parent1, parent2, child
class TestPlannedDaysNotDoubledAcrossParents:
async def test_build_context_does_not_double_planned_days(
self,
tips_service: TipsService,
two_parent_one_child_workspace,
) -> None:
ws, _parent1, _parent2, _child = two_parent_one_child_workspace
_workspace_ctx, child_contexts = await tips_service._build_context(ws.id)
assert len(child_contexts) == 1
# 3 planned days were seeded once each; with two parents in the
# workspace, the old code (which re-fetched `list_by_workspace_child`
# inside the per-parent loop and kept appending) would return 6.
assert len(child_contexts[0].planned_days) == 3, (
"planned days were duplicated across parents — "
f"got {len(child_contexts[0].planned_days)} for 2 parents, expected 3"
)
class TestMultiChildContexts:
async def test_each_child_gets_its_own_scoped_context(
self,
tips_service: TipsService,
workspace_repo: SQLiteWorkspaceRepository,
personal_data_repo: SQLitePersonalDataRepository,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
) -> None:
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Alice", created_at=now)
)
child_a = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="A",
birth_date=date(2023, 1, 1),
created_at=now,
)
)
child_b = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="B",
birth_date=date(2025, 1, 1),
created_at=now,
)
)
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child_a.id, used=10))
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child_b.id, used=200))
workspace_ctx, child_contexts = await tips_service._build_context(ws.id)
assert workspace_ctx.children == []
assert {c.children[0].id for c in child_contexts} == {child_a.id, child_b.id}
by_child = {c.children[0].id: c for c in child_contexts}
assert by_child[child_a.id].leave_by_parent[parent.uuid].days_used == 10
assert by_child[child_b.id].leave_by_parent[parent.uuid].days_used == 200
async def test_get_tips_scopes_tip_ids_and_data_per_child(
self,
tips_service: TipsService,
workspace_repo: SQLiteWorkspaceRepository,
personal_data_repo: SQLitePersonalDataRepository,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
) -> None:
"""Two children both eligible for `preserve_for_age_4` must produce
two distinct tips, not one deduped/overwritten result — see the task
brief: "a tip about child A must not dedupe against the same rule
firing for child B".
"""
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Alice", created_at=now)
)
child_a = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Adam",
birth_date=date.today().replace(year=date.today().year - 1),
created_at=now,
)
)
child_b = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Berit",
birth_date=date.today().replace(year=date.today().year - 2),
created_at=now,
)
)
# total=240, used=20 -> projected_left=220, expiring=220-96=124 for both.
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child_a.id, used=20))
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child_b.id, used=20))
tips = await tips_service.get_tips(ws.id)
preserve_tips = [t for t in tips if t.id.startswith("preserve_for_age_4:")]
assert len(preserve_tips) == 2, "expected one preserve_for_age_4 tip per child"
ids = {t.id for t in preserve_tips}
assert ids == {
f"preserve_for_age_4:{child_a.id}",
f"preserve_for_age_4:{child_b.id}",
}
child_names = {t.data["child_name"] for t in preserve_tips}
assert child_names == {"Adam", "Berit"}
class TestDismissals:
async def test_dismiss_hides_tip_until_data_changes(
self,
tips_service: TipsService,
workspace_repo: SQLiteWorkspaceRepository,
personal_data_repo: SQLitePersonalDataRepository,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
) -> None:
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Alice", created_at=now)
)
child = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Barn",
birth_date=date.today().replace(year=date.today().year - 1),
created_at=now,
)
)
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child.id, used=20))
tips = await tips_service.get_tips(ws.id)
tip = next(t for t in tips if t.id.startswith("preserve_for_age_4:"))
original_expiring = tip.data["expiring_days"]
await tips_service.dismiss(ws.id, tip.id)
tips_after_dismiss = await tips_service.get_tips(ws.id)
assert tip.id not in {t.id for t in tips_after_dismiss}
# The situation changes materially: add planned FP days before the
# 4th birthday, which shrinks `expiring_days`. The stale dismissal
# must not silence the new figure.
fourth_bday = child.birth_date.replace(year=child.birth_date.year + 4)
for i in range(30):
await planned_leave_repo.create(
_make_planned_day(
ws.id,
child.id,
parent.uuid,
fourth_bday - timedelta(days=i + 1),
)
)
tips_after_change = await tips_service.get_tips(ws.id)
resurfaced = next((t for t in tips_after_change if t.id == tip.id), None)
assert resurfaced is not None, "dismissal must expire once expiring_days changes"
assert resurfaced.data["expiring_days"] != original_expiring
async def test_dismiss_unknown_tip_raises_not_found(
self,
tips_service: TipsService,
workspace_repo: SQLiteWorkspaceRepository,
) -> None:
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
try:
await tips_service.dismiss(ws.id, "not_a_real_tip")
raised = False
except NotFoundError:
raised = True
assert raised
@@ -0,0 +1,123 @@
"""Tests for the TipDismissal repository.
Follows the DayOverride reference pattern (upsert-by-natural-key, UNIQUE
constraint on the natural key): arrange an entity, exercise the repo, assert
on the result.
"""
from datetime import datetime
from uuid import uuid4
import pytest
from app.entities.tip_dismissal import TipDismissal
from app.entities.workspace import Workspace
from app.repositories_impl.sqlite.tip_dismissal_repository import SQLiteTipDismissalRepository
from app.repositories_impl.sqlite.workspace_repository import SQLiteWorkspaceRepository
from app.utils.errors import NotFoundError
from tests.conftest import SeededIds
def _make(workspace_id=None, **overrides) -> TipDismissal:
base = dict(
id=uuid4(),
workspace_id=workspace_id or uuid4(),
tip_id="preserve_for_age_4:child-1",
data_hash="deadbeef",
dismissed_at=datetime.now(),
)
base.update(overrides)
return TipDismissal(**base)
class TestSQLiteTipDismissalRepository:
async def test_create_and_get_by_id(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
) -> None:
entity = _make(workspace_id=seeded_ids.workspace_id)
await tip_dismissal_repo.create(entity)
fetched = await tip_dismissal_repo.get_by_id(entity.id)
assert fetched is not None
assert fetched.tip_id == "preserve_for_age_4:child-1"
assert fetched.data_hash == "deadbeef"
async def test_get_by_workspace_tip(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
) -> None:
entity = _make(workspace_id=seeded_ids.workspace_id)
await tip_dismissal_repo.create(entity)
found = await tip_dismissal_repo.get_by_workspace_tip(
seeded_ids.workspace_id, "preserve_for_age_4:child-1"
)
assert found is not None
assert found.id == entity.id
missing = await tip_dismissal_repo.get_by_workspace_tip(uuid4(), "no_such_tip")
assert missing is None
async def test_update_refreshes_hash_and_timestamp(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
) -> None:
entity = _make(workspace_id=seeded_ids.workspace_id)
await tip_dismissal_repo.create(entity)
entity.data_hash = "newhash"
updated = await tip_dismissal_repo.update(entity.id, entity)
assert updated.data_hash == "newhash"
async def test_update_missing_raises(
self, tip_dismissal_repo: SQLiteTipDismissalRepository
) -> None:
with pytest.raises(NotFoundError):
await tip_dismissal_repo.update(uuid4(), _make())
async def test_delete(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
) -> None:
entity = _make(workspace_id=seeded_ids.workspace_id)
await tip_dismissal_repo.create(entity)
await tip_dismissal_repo.delete(entity.id)
assert await tip_dismissal_repo.get_by_id(entity.id) is None
async def test_delete_missing_raises(
self, tip_dismissal_repo: SQLiteTipDismissalRepository
) -> None:
with pytest.raises(NotFoundError):
await tip_dismissal_repo.delete(uuid4())
async def test_list_by_workspace_filters(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
workspace_repo: SQLiteWorkspaceRepository,
) -> None:
ws = seeded_ids.workspace_id
ws2 = await workspace_repo.create(
Workspace(id=uuid4(), name="WS2", created_at=datetime.now())
)
await tip_dismissal_repo.create(_make(workspace_id=ws, tip_id="a"))
await tip_dismissal_repo.create(_make(workspace_id=ws, tip_id="b"))
await tip_dismissal_repo.create(_make(workspace_id=ws2.id, tip_id="c"))
rows = await tip_dismissal_repo.list_by_workspace(ws)
assert {r.tip_id for r in rows} == {"a", "b"}
async def test_unique_constraint_per_workspace_tip(
self,
tip_dismissal_repo: SQLiteTipDismissalRepository,
seeded_ids: SeededIds,
) -> None:
await tip_dismissal_repo.create(_make(workspace_id=seeded_ids.workspace_id, tip_id="x"))
with pytest.raises(Exception): # sqlite3.IntegrityError via aiosqlite
await tip_dismissal_repo.create(_make(workspace_id=seeded_ids.workspace_id, tip_id="x"))
@@ -0,0 +1,30 @@
"""Tests for `hash_tip_data` — the dismissal-expiry fingerprint.
See `app.entities.tip_dismissal.TipDismissal` and
`TipsService._drop_stale_dismissed`: a dismissal only stays silent while the
rule's `data` still hashes the same. These tests pin the two properties that
matter for that contract: stability (same data → same hash, regardless of
key order) and sensitivity (any value change → a different hash).
"""
from app.utils.tip_predicates import hash_tip_data
class TestHashTipData:
def test_stable_regardless_of_key_order(self) -> None:
a = hash_tip_data({"parent_name": "Alice", "expiring_days": 12})
b = hash_tip_data({"expiring_days": 12, "parent_name": "Alice"})
assert a == b
def test_changes_when_a_value_changes(self) -> None:
a = hash_tip_data({"parent_name": "Alice", "expiring_days": 12})
b = hash_tip_data({"parent_name": "Alice", "expiring_days": 13})
assert a != b
def test_changes_when_a_key_is_added_or_removed(self) -> None:
a = hash_tip_data({"parent_name": "Alice"})
b = hash_tip_data({"parent_name": "Alice", "expiring_days": 12})
assert a != b
def test_empty_data_hashes_consistently(self) -> None:
assert hash_tip_data({}) == hash_tip_data({})
+159
View File
@@ -0,0 +1,159 @@
"""API-level tests for `GET /api/tips/{workspace_id}` and its dismiss route.
Guards two things a unit test on the service can't see:
- the wire shape (`TipResponse`) actually carries `anchor_date`/
`anchor_range` and `message_key` + `data` — not rendered prose;
- the dismiss endpoint round-trips through the real DB and a second GET
no longer returns the dismissed tip.
"""
from datetime import date, datetime
from uuid import uuid4
import aiosqlite
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from app.dependencies import get_connection, get_current_user
from app.entities.child import Child
from app.entities.parental_leave import ParentalLeaveFetch, TierData
from app.entities.personal_data import PersonalData
from app.entities.user import User
from app.entities.workspace import Workspace
from app.main import app
from app.repositories_impl.sqlite.child_repository import SQLiteChildRepository
from app.repositories_impl.sqlite.parental_leave_repository import SQLiteParentalLeaveRepository
from app.repositories_impl.sqlite.personal_data_repository import SQLitePersonalDataRepository
from app.repositories_impl.sqlite.workspace_repository import SQLiteWorkspaceRepository
def _make_fetch(personal_data_uuid, workspace_id, child_id, used: int = 20) -> ParentalLeaveFetch:
now = datetime.now()
tier = TierData(
sjukpenning_total=390,
sjukpenning_used=used,
sjukpenning_left=390 - used,
lagsta_niva_total=90,
lagsta_niva_used=0,
lagsta_niva_left=90,
)
return ParentalLeaveFetch(
id=uuid4(),
personal_data_uuid=personal_data_uuid,
workspace_id=workspace_id,
child_id=child_id,
source="manual",
fetched_at=now,
total_days=240,
days_used=used,
days_left=240 - used,
reserved_days_total=90,
reserved_days_left=90,
transferable_days_left=50,
dubbeldagar_left=60,
tier_data=tier,
created_at=now,
updated_at=now,
)
@pytest_asyncio.fixture
async def client(connection: aiosqlite.Connection) -> AsyncClient:
app.dependency_overrides[get_connection] = lambda: connection
app.dependency_overrides[get_current_user] = lambda: User(
id=uuid4(),
personal_data_uuid=uuid4(),
email="test@example.com",
hashed_password="not-a-real-hash",
created_at=datetime.now(),
)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
yield ac
app.dependency_overrides.pop(get_connection, None)
app.dependency_overrides.pop(get_current_user, None)
@pytest_asyncio.fixture
async def workspace_with_expiring_days(connection: aiosqlite.Connection):
now = datetime.now()
workspace_repo = SQLiteWorkspaceRepository(connection)
personal_data_repo = SQLitePersonalDataRepository(connection)
child_repo = SQLiteChildRepository(connection)
parental_leave_repo = SQLiteParentalLeaveRepository(connection)
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent = await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Alice", created_at=now)
)
child = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Barn",
birth_date=date.today().replace(year=date.today().year - 1),
created_at=now,
)
)
await parental_leave_repo.create(_make_fetch(parent.uuid, ws.id, child.id, used=20))
return ws, child
class TestGetTipsOverTheWire:
async def test_response_carries_anchor_date_and_no_rendered_prose(
self,
client: AsyncClient,
workspace_with_expiring_days,
) -> None:
ws, child = workspace_with_expiring_days
response = await client.get(f"/api/tips/{ws.id}")
assert response.status_code == 200
body = response.json()
preserve = next(t for t in body if t["id"].startswith("preserve_for_age_4:"))
assert preserve["id"] == f"preserve_for_age_4:{child.id}"
assert preserve["message_key"] == "tips.preserve_for_age_4"
assert preserve["anchor_date"] == (
child.birth_date.replace(year=child.birth_date.year + 4).isoformat()
)
assert preserve["anchor_range"] is None
assert preserve["data"]["child_id"] == str(child.id)
assert preserve["data"]["child_name"] == "Barn"
# Never rendered Swedish prose — only message_key + data.
for tip in body:
assert isinstance(tip["message_key"], str) and tip["message_key"].startswith("tips.")
for value in tip["data"].values():
assert not isinstance(value, dict)
class TestDismissTipOverTheWire:
async def test_dismiss_then_get_excludes_the_tip(
self,
client: AsyncClient,
workspace_with_expiring_days,
) -> None:
ws, _child = workspace_with_expiring_days
before = await client.get(f"/api/tips/{ws.id}")
tip = next(t for t in before.json() if t["id"].startswith("preserve_for_age_4:"))
dismiss_response = await client.post(
f"/api/tips/{ws.id}/dismissals", json={"tip_id": tip["id"]}
)
assert dismiss_response.status_code == 204
after = await client.get(f"/api/tips/{ws.id}")
assert tip["id"] not in {t["id"] for t in after.json()}
async def test_dismiss_unknown_tip_returns_404(
self,
client: AsyncClient,
workspace_with_expiring_days,
) -> None:
ws, _child = workspace_with_expiring_days
response = await client.post(
f"/api/tips/{ws.id}/dismissals", json={"tip_id": "not_a_real_tip"}
)
assert response.status_code == 404