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
144 lines
5.1 KiB
Python
144 lines
5.1 KiB
Python
"""FastAPI application entrypoint.
|
|
|
|
Opens a database connection on startup, runs Alembic migrations, registers
|
|
routers, locks CORS to the configured frontend origin(s), and attaches a
|
|
rate-limiter to the app (applied per-endpoint via decorators).
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from collections.abc import AsyncIterator
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from slowapi import _rate_limit_exceeded_handler
|
|
from slowapi.errors import RateLimitExceeded
|
|
from starlette.middleware.gzip import GZipMiddleware
|
|
|
|
from app.config import settings
|
|
from app.db.connection import connect, run_migrations
|
|
from app.rate_limit import limiter
|
|
from app.routers import vacation_days
|
|
from app.routers.analytics import router as analytics_router
|
|
from app.routers.auth import router as auth_router
|
|
from app.routers.calendar import router as calendar_router
|
|
from app.routers.day_assertion import router as day_assertion_router
|
|
from app.routers.day_overrides import router as day_overrides_router
|
|
from app.routers.fetch_data import router as fetch_data_router
|
|
from app.routers.fetch_data import scraper_router
|
|
from app.routers.leave_wishes import router as leave_wishes_router
|
|
from app.routers.plan import router as plan_router
|
|
from app.routers.planned_days import router as planned_days_router
|
|
from app.routers.preschool_planning_days import router as preschool_planning_days_router
|
|
from app.routers.settings import child_router, settings_child_router, tips_router
|
|
from app.routers.workspace import _inv_router as invitations_router
|
|
from app.routers.workspace import router as workspace_router
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _configure_logging() -> None:
|
|
level = logging.getLevelName(settings.log_level.upper())
|
|
|
|
handler = logging.StreamHandler()
|
|
handler.setLevel(level)
|
|
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
|
|
|
|
app_logger = logging.getLogger("app")
|
|
app_logger.handlers.clear()
|
|
app_logger.addHandler(handler)
|
|
app_logger.setLevel(level)
|
|
app_logger.propagate = False
|
|
app_logger.disabled = False
|
|
|
|
for name, log in logging.Logger.manager.loggerDict.items():
|
|
if (name == "app" or name.startswith("app.")) and isinstance(log, logging.Logger):
|
|
log.disabled = False
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
_configure_logging()
|
|
|
|
if settings.database_type == "sqlite":
|
|
try:
|
|
await asyncio.to_thread(run_migrations, f"sqlite:///{settings.sqlite_path}")
|
|
except Exception as exc:
|
|
logger.error("Migration failed — DB schema may be incomplete: %s", exc, exc_info=True)
|
|
raise
|
|
|
|
# Re-enable after migrations: alembic's env.py calls fileConfig() which may
|
|
# still touch logger state even with disable_existing_loggers=False.
|
|
for name, log in logging.Logger.manager.loggerDict.items():
|
|
if (name == "app" or name.startswith("app.")) and isinstance(log, logging.Logger):
|
|
log.disabled = False
|
|
|
|
app.state.db_connection = await connect(settings.sqlite_path)
|
|
try:
|
|
yield
|
|
finally:
|
|
await app.state.db_connection.close()
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
is_production = settings.app_env == "production"
|
|
app = FastAPI(
|
|
title="Föräldraledigplannerare API",
|
|
lifespan=lifespan,
|
|
docs_url=None if is_production else "/docs",
|
|
redoc_url=None if is_production else "/redoc",
|
|
openapi_url=None if is_production else "/openapi.json",
|
|
)
|
|
|
|
app.state.limiter = limiter
|
|
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
|
|
|
@app.middleware("http")
|
|
async def log_error_responses(request: Request, call_next):
|
|
response = await call_next(request)
|
|
if response.status_code >= 400:
|
|
logger.warning("%s %s %d", request.method, request.url.path, response.status_code)
|
|
return response
|
|
|
|
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=list(settings.cors_origins),
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
_register_routers(app)
|
|
return app
|
|
|
|
|
|
def _register_routers(app: FastAPI) -> None:
|
|
app.include_router(auth_router)
|
|
app.include_router(workspace_router)
|
|
app.include_router(invitations_router)
|
|
app.include_router(fetch_data_router)
|
|
app.include_router(scraper_router)
|
|
app.include_router(analytics_router)
|
|
app.include_router(tips_router)
|
|
app.include_router(leave_wishes_router)
|
|
app.include_router(plan_router)
|
|
app.include_router(child_router)
|
|
app.include_router(settings_child_router)
|
|
app.include_router(planned_days_router)
|
|
app.include_router(day_assertion_router)
|
|
app.include_router(vacation_days.router)
|
|
app.include_router(preschool_planning_days_router)
|
|
app.include_router(day_overrides_router)
|
|
app.include_router(calendar_router)
|
|
|
|
|
|
app = create_app()
|
|
|
|
|
|
@app.get("/health", tags=["health"])
|
|
async def health() -> dict[str, str]:
|
|
return {"status": "ok"}
|