Files
F-r-ldraledigplannerare/backend/app/main.py
T
jacobh2 8cfb9c82c6 Let a day removed from a period stay removed
Taking one day out of a period the planner placed did nothing that
lasted: the period still asked for a full week, so the next sync put the
day straight back. The option was disabled rather than lying about it.

A removed day is now recorded as its own thing — no leave for this
parent, this child, this date — and the planner honours it on every
later sync. It is kept apart from the working-day overrides, which
answer a different question about the calendar rather than about the
plan.

The day belongs to the parent whose band was clicked, so removing one
parent's day leaves their partner's alone; where both parents were to be
off on one funding arrangement, the partner is simply funded on their
own instead. A removed day shortens what the period is asking for rather
than counting as a day the plan failed to find, so the advice about
closing a shortfall does not start arguing for a day nobody wants.

Nothing is removed without a way back: the toast undoes it, and the day
itself is marked in the calendar and offers to restore.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ei7gCZzdd751uZtPzb1Pep
2026-09-19 16:05:17 +02:00

142 lines
5.0 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_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_day_exclusions import router as planned_day_exclusions_router
from app.routers.planned_days import router as planned_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(planned_day_exclusions_router)
app.include_router(vacation_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"}