782415122d
The calendar mixed two kinds of truth in one table. `planned_leave_day` was simultaneously the allocator's output cache, the user's override store (`is_pinned`, plus ad-hoc rows with no `wish_id`), and the resource ledger that analytics and the age-4 maths read. The planner therefore had to ask "am I allowed to touch this row?" on every sync, and got it wrong at the edges. Every user assertion is now one `day_assertion` row — a concrete `day_type` replaces a pinned day, a row with no `wish_id` replaces an ad-hoc day, and `day_type='none'` replaces `planned_day_exclusion`. `planned_leave_day` becomes purely derived with a single writer, and `PlanningService.pinned_keys()` is the single answer to "is this day pinned", used by the allocator's loader, by `sync_plan` and by the read router alike. On top of that, every calendar band is now a real event: an ad-hoc band opens the same full editor as a wish-backed one and saving it promotes it to a `LeaveWish`, so it can be named, repeated yearly, assigned to either or both parents, and handed to the planner. "Planering" is a `moveable` toggle plus a from/to month bound plus a separate lock/unlock action on the days themselves, replacing a three-rung ladder whose "planner decides" rung set a search window equal to the drawn dates and so could never move anything. Bugs found and fixed along the way: - The plan erased its own history. Fixed windows clip to today, so an elapsed auto-placed day fell into `stale_keys` and was deleted on the next sync — and a background sync runs on every workspace load. Past rows are now frozen and counted as spent. - Migration 010's downgrade silently destroyed every pinned day and exclusion (`is_pinned` returned as DEFAULT 0, the exclusion table came back empty, exit 0, no warning). It now reconstructs both from `day_assertion`, and 009 itemises what it cannot recover before dropping the table. - Deleting a period left its assertions behind, locking those dates forever with no UI path to clear them. Wish deletion now clears them by `wish_id`. - `DayAssertionService` and `LeaveWishService` committed multi-statement writes without a transaction; a crash mid-write diverged the tables or half-deleted a series. Both now run in a unit of work. - A sibling year's shortfall was never surfaced: the toast only inspected the edited occurrence's outcome, so a fully unfunded later year rendered as an empty band with no warning. - A flexible window whose bound had entirely elapsed was dropped from the proposal with no outcome at all. It now reports as `unplaced`. - Unlocking a period deleted its days instead of returning them to the planner. - The e2e global setup posted to a route deleted in this change, which would have failed the whole suite before its first test. Gates: backend 938 tests / 91% coverage, frontend 1351 / 97.4 | 92.2 | 94.37 | 97.4. Migrations 009 and 010 audited against a hand-built realistic database: the upgrade reconciles exactly and a constraint violation fails safe, leaving the schema at 008. Not complete. Step 4's toggle, month picker and lock/unlock action are verified by browser walk and unit tests, but the partial-lock readout was not exercised. `ideas.md` §7 adds a full plan for the vacation-forfeiture defect (the planner detects expiring days and then does nothing about them) — not implemented here. Remaining smaller items are listed in the session's restructure notes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T4wjgbVL4HAC5Rdaw75VbV
217 lines
9.4 KiB
Python
217 lines
9.4 KiB
Python
"""Business logic for DayAssertion — the intent-vs-derived-output restructure's
|
|
|
|
single record of "what the user asserts about one calendar day" (see
|
|
`app/entities/day_assertion.py`). Restructure step 3b: this service is now
|
|
the ONE write path behind `POST /api/day-assertions`, superseding both the
|
|
old hand-pin write on `/api/planned-days` and `/api/planned-day-exclusions`
|
|
(both deleted). It owns the natural-key upsert convention AND mirrors every
|
|
write into `planned_leave_day`, the same way `PlannedDayExclusionService`
|
|
used to for the `'none'` case — a `DayAssertion` for a concrete `day_type` is
|
|
also, immediately, a `planned_leave_day` row with that same day_type/
|
|
is_dubbeldag/wish_id (so the calendar renders it without waiting for the
|
|
next `POST /api/plan/sync`), and a `day_type='none'` assertion still deletes
|
|
whatever `planned_leave_day` row occupied that slot.
|
|
|
|
Enforces the SAME guard `PlanningService.add_planned_day`/`update` used to
|
|
(`app.services.day_guards.reject_illegal_free_day` — a free day can never be
|
|
`vacation`, and may be `sjukpenning`/`lagsta` only when the workspace opted
|
|
in) and the same per-day dubbeldagar-window check
|
|
(`AnalyticsService.validate_dubbeldagar`), so hand-pinning a day through this
|
|
endpoint is exactly as guarded as the legacy `/api/planned-days` write was —
|
|
both optional constructor deps, like `PlanningService`'s own guards, so a
|
|
caller that never wires them (older direct-construction call sites) keeps
|
|
whatever behaviour it had.
|
|
"""
|
|
|
|
from datetime import date, datetime
|
|
from uuid import UUID, uuid4
|
|
|
|
from app.entities.day_assertion import DAY_TYPE_NONE, DayAssertion
|
|
from app.entities.planned_leave import PlannedLeaveDay
|
|
from app.entities.workspace import Workspace
|
|
from app.repositories.day_assertion_repository import DayAssertionRepository
|
|
from app.repositories.day_override_repository import DayOverrideRepository
|
|
from app.repositories.planned_leave_repository import PlannedLeaveRepository
|
|
from app.repositories.unit_of_work import NoOpUnitOfWork, UnitOfWork
|
|
from app.repositories.workspace_repository import WorkspaceRepository
|
|
from app.services.analytics_service import AnalyticsService
|
|
from app.services.day_guards import reject_illegal_free_day
|
|
from app.utils.errors import NotFoundError, ValidationError
|
|
|
|
_VALID_DAY_TYPES = frozenset({"sjukpenning", "lagsta", "vacation", DAY_TYPE_NONE})
|
|
|
|
|
|
class DayAssertionService:
|
|
def __init__(
|
|
self,
|
|
repo: DayAssertionRepository,
|
|
planned_leave_repo: PlannedLeaveRepository | None = None,
|
|
analytics_service: AnalyticsService | None = None,
|
|
workspace_repo: WorkspaceRepository | None = None,
|
|
day_override_repo: DayOverrideRepository | None = None,
|
|
uow: UnitOfWork | None = None,
|
|
) -> None:
|
|
self._repo = repo
|
|
# Only needed for the `planned_leave_day` mirroring below — optional
|
|
# so a direct-construction caller that only wants pure assertion
|
|
# semantics (tests) doesn't have to wire it.
|
|
self._planned_leave_repo = planned_leave_repo
|
|
self._analytics = analytics_service
|
|
self._workspace_repo = workspace_repo
|
|
self._day_override_repo = day_override_repo
|
|
# Adversarial-review fix (restructure step 3b): `assert_day`/`clear`
|
|
# each do an assertion write followed by a `planned_leave_day` mirror
|
|
# write (create-or-replace, or a delete) — two separate commits with
|
|
# no unit of work, exactly the shape `PlanningService` wraps in
|
|
# `self._uow()` everywhere else. Defaults to a no-op so existing
|
|
# direct-construction call sites (tests) keep today's per-write-commit
|
|
# behavior; `app.dependencies.get_day_assertion_service` always wires
|
|
# a real `SQLiteUnitOfWork`.
|
|
self._uow = uow or NoOpUnitOfWork()
|
|
|
|
async def _reject_illegal_free_day(self, workspace_id: UUID, d: date, day_type: str) -> None:
|
|
if self._workspace_repo is None or self._day_override_repo is None:
|
|
return
|
|
overrides = {
|
|
o.date: o.is_working_day
|
|
for o in await self._day_override_repo.list_by_workspace(workspace_id)
|
|
}
|
|
workspace: Workspace | None = await self._workspace_repo.get_by_id(workspace_id)
|
|
reject_illegal_free_day(workspace, overrides, d, day_type)
|
|
|
|
async def assert_day(
|
|
self,
|
|
workspace_id: UUID,
|
|
child_id: UUID,
|
|
parent_personal_data_uuid: UUID,
|
|
day: date,
|
|
day_type: str,
|
|
is_dubbeldag: bool = False,
|
|
wish_id: UUID | None = None,
|
|
) -> DayAssertion:
|
|
"""Record (or overwrite) the user's assertion for this (workspace,
|
|
|
|
child, parent, date), and mirror it into `planned_leave_day` so the
|
|
calendar reflects it immediately. `day_type='none'` is the
|
|
exclusion-shaped assertion — "the planner may not place leave here"
|
|
— and mirrors by DELETING any `planned_leave_day` row at this key
|
|
instead. Idempotent by natural key: asserting the same slot again
|
|
overwrites rather than duplicating, and always OVERWRITES whatever
|
|
assertion already exists there (never merges), matching
|
|
`PlannedDayExclusionService.exclude()`'s precedent.
|
|
"""
|
|
if day_type not in _VALID_DAY_TYPES:
|
|
raise ValidationError(f"invalid day_type for a DayAssertion: {day_type!r}")
|
|
|
|
await self._reject_illegal_free_day(workspace_id, day, day_type)
|
|
if is_dubbeldag and self._analytics is not None:
|
|
# `DubbeldagError` is itself a `ValidationError` (see
|
|
# `app.utils.errors`) — nothing to translate, matches
|
|
# `PlanningService.add_planned_day`'s own Validation 1 exactly.
|
|
await self._analytics.validate_dubbeldagar(child_id, day)
|
|
|
|
now = datetime.now()
|
|
async with self._uow():
|
|
created = await self._repo.upsert(
|
|
DayAssertion(
|
|
id=uuid4(),
|
|
workspace_id=workspace_id,
|
|
child_id=child_id,
|
|
parent_personal_data_uuid=parent_personal_data_uuid,
|
|
date=day,
|
|
day_type=day_type,
|
|
is_dubbeldag=is_dubbeldag,
|
|
wish_id=wish_id,
|
|
created_at=now,
|
|
updated_at=now,
|
|
)
|
|
)
|
|
await self._mirror_into_planned_leave(
|
|
workspace_id,
|
|
child_id,
|
|
parent_personal_data_uuid,
|
|
day,
|
|
day_type,
|
|
is_dubbeldag,
|
|
wish_id,
|
|
)
|
|
return created
|
|
|
|
async def _mirror_into_planned_leave(
|
|
self,
|
|
workspace_id: UUID,
|
|
child_id: UUID,
|
|
parent_personal_data_uuid: UUID,
|
|
day: date,
|
|
day_type: str,
|
|
is_dubbeldag: bool,
|
|
wish_id: UUID | None,
|
|
) -> None:
|
|
if self._planned_leave_repo is None:
|
|
return
|
|
existing = [
|
|
row
|
|
for row in await self._planned_leave_repo.list_by_workspace_child(
|
|
workspace_id, child_id, from_date=day, to_date=day
|
|
)
|
|
if row.parent_personal_data_uuid == parent_personal_data_uuid
|
|
]
|
|
if existing:
|
|
await self._planned_leave_repo.delete_many([row.id for row in existing])
|
|
if day_type == DAY_TYPE_NONE:
|
|
return
|
|
now = datetime.now()
|
|
await self._planned_leave_repo.create(
|
|
PlannedLeaveDay(
|
|
id=uuid4(),
|
|
workspace_id=workspace_id,
|
|
child_id=child_id,
|
|
parent_personal_data_uuid=parent_personal_data_uuid,
|
|
date=day,
|
|
day_type=day_type,
|
|
is_dubbeldag=is_dubbeldag,
|
|
wish_id=wish_id,
|
|
created_at=now,
|
|
updated_at=now,
|
|
)
|
|
)
|
|
|
|
async def clear(
|
|
self,
|
|
workspace_id: UUID,
|
|
child_id: UUID,
|
|
parent_personal_data_uuid: UUID,
|
|
day: date,
|
|
) -> None:
|
|
"""Retract the assertion at this slot, if any (a no-op when none
|
|
|
|
exists), and delete the mirrored `planned_leave_day` row at the same
|
|
key, if any. Used for: un-pinning a hand-added day entirely (the
|
|
Advanced modal's plain delete), deleting an ad-hoc band's days, and
|
|
restoring a `day_type='none'` exclusion.
|
|
"""
|
|
async with self._uow():
|
|
await self._repo.delete_by_natural_key(
|
|
workspace_id, child_id, parent_personal_data_uuid, day
|
|
)
|
|
if self._planned_leave_repo is None:
|
|
return
|
|
existing = [
|
|
row
|
|
for row in await self._planned_leave_repo.list_by_workspace_child(
|
|
workspace_id, child_id, from_date=day, to_date=day
|
|
)
|
|
if row.parent_personal_data_uuid == parent_personal_data_uuid
|
|
]
|
|
if existing:
|
|
await self._planned_leave_repo.delete_many([row.id for row in existing])
|
|
|
|
async def get(self, assertion_id: UUID, workspace_id: UUID | None = None) -> DayAssertion:
|
|
entity = await self._repo.get_by_id(assertion_id)
|
|
if entity is None or (workspace_id is not None and entity.workspace_id != workspace_id):
|
|
raise NotFoundError(f"DayAssertion {assertion_id} not found")
|
|
return entity
|
|
|
|
async def list_for_workspace(self, workspace_id: UUID) -> list[DayAssertion]:
|
|
return await self._repo.list_by_workspace(workspace_id)
|