Complete NextSteps roadmap: planning engine UI, calendar cluster, flexible wishes
Works through every numbered item in NextSteps260913.md section 3, plus the three known verification issues in section 4.1. Surface what the backend already computed: - 3.1 render surplus_advice in PlanResults, mirroring the shortfall remedies - 3.2 surface VacationBalance.is_assumed so assumed statutory years are visible - 3.3 age-4 expiry given the proposed plan, via a new Age4Projection reusing the existing _age4_projections arithmetic (Dashboard stat verified, not rebuilt) Calendar cluster (one pass over the holiday data): - new GET /api/calendar/days exposing roda dagar, klamdagar and day overrides, paginated four years at a time - 3.4 shade roda dagar/klamdagar, with R/K badges so colour is not the only signal - 3.6 click-to-override behind an explicit mode toggle, leaving drag multi-select intact - 3.7 click month/year to advance - 3.8 per-year red-days list in Settings, statutory days plus overrides i18n: - 3.5 five backend-generated Swedish surfaces converted to message_key + data, following the tips_service pattern; old string fields replaced, not kept Flexible wishes (3.9): - PLANNING_ENGINE_SPEC section 10: window_mode, candidate search, cost function, deterministic tie-break, two-pass ordering, test matrix rows 15-24 - backend: entity, migration 006, _FULL_SCHEMA sync, repository, allocator - frontend: season-preset toggle in WishEditor, unplaced outcome rendering Fixes (4.1): - pin typecheck to the local tsc rather than npx resolving a newer TypeScript - ignore generated coverage/ and dist/ in the ESLint flat config - fix the flaky usePlanApply test properly, with waitFor rather than a retry Tests: backend 361 -> 404, frontend 540 -> 704. Coverage 89.47% -> 96.52% lines. Not yet verified in a browser. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RXMhc9nT6sNz1SL4j8dznL
This commit is contained in:
@@ -0,0 +1,345 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Demo: run the pure planning-engine Allocator on a realistic family.
|
||||
|
||||
Builds an `AllocationInput` entirely in memory (no database) using Swedish
|
||||
defaults — two parents on a joint 240/240 split, 25 semesterdagar/year each,
|
||||
a child born 2026-03-01 — plus two recurring wishes ("6 veckor sommar" and
|
||||
"4 veckor jul") running until the child turns 4. Runs `Allocator().propose()`
|
||||
(the pure half of the planning engine — see app.services.allocation_service)
|
||||
and prints a human-readable Swedish summary per window.
|
||||
|
||||
Usage (from backend/):
|
||||
uv run python scripts/demo_plan.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from uuid import uuid4
|
||||
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
from app.entities.leave_wish import LeaveWish
|
||||
from app.services.allocation_service import (
|
||||
AllocationInput,
|
||||
Allocator,
|
||||
ChildFacts,
|
||||
DayPool,
|
||||
ParentFacts,
|
||||
PlanProposal,
|
||||
VacationBudget,
|
||||
WindowOutcome,
|
||||
)
|
||||
from app.utils.holidays import get_swedish_holidays
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Build a realistic AllocationInput, in memory, Swedish defaults.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
CHILD_BIRTH_DATE = date(2026, 3, 1)
|
||||
TODAY = date.today()
|
||||
|
||||
|
||||
def _build_input() -> tuple[AllocationInput, dict]:
|
||||
child = ChildFacts(
|
||||
id=uuid4(),
|
||||
birth_date=CHILD_BIRTH_DATE,
|
||||
fourth_birthday=CHILD_BIRTH_DATE + relativedelta(years=4),
|
||||
preschool_start_date=CHILD_BIRTH_DATE + relativedelta(years=1, months=4),
|
||||
preschool_planning_days_per_year=6,
|
||||
)
|
||||
|
||||
parent_1 = ParentFacts(
|
||||
uuid=uuid4(), name="Alex", salary_type="monthly", employment_status="employed"
|
||||
)
|
||||
parent_2 = ParentFacts(
|
||||
uuid=uuid4(), name="Sam", salary_type="monthly", employment_status="employed"
|
||||
)
|
||||
|
||||
# 390 sjukpenning-days + 90 lägstanivå-days = 480 total, split 240/240
|
||||
# between the two parents (the default joint-custody split, see
|
||||
# app.config.LeaveRules).
|
||||
pools = {
|
||||
(parent_1.uuid, child.id): DayPool(
|
||||
sjukpenning_left=195, lagsta_left=45, dubbeldagar_left=60
|
||||
),
|
||||
(parent_2.uuid, child.id): DayPool(
|
||||
sjukpenning_left=195, lagsta_left=45, dubbeldagar_left=60
|
||||
),
|
||||
}
|
||||
|
||||
horizon_end = child.fourth_birthday + relativedelta(years=1)
|
||||
vacation = {
|
||||
(parent_1.uuid, year): VacationBudget(total_days=25, saved_days_in=0, already_used=0)
|
||||
for year in range(TODAY.year, horizon_end.year + 1)
|
||||
}
|
||||
vacation.update(
|
||||
{
|
||||
(parent_2.uuid, year): VacationBudget(total_days=25, saved_days_in=0, already_used=0)
|
||||
for year in range(TODAY.year, horizon_end.year + 1)
|
||||
}
|
||||
)
|
||||
|
||||
summer_wish = LeaveWish(
|
||||
id=uuid4(),
|
||||
workspace_id=uuid4(),
|
||||
child_id=child.id,
|
||||
name="Sommar",
|
||||
window_start_month=6,
|
||||
window_start_day=15,
|
||||
window_end_month=7,
|
||||
window_end_day=26, # 6 weeks
|
||||
target_weeks=6,
|
||||
recurrence="yearly",
|
||||
first_year=CHILD_BIRTH_DATE.year,
|
||||
last_year=None, # until the child's 4th birthday
|
||||
priority=1,
|
||||
parent_mode="either", # lets the allocator swap between parents
|
||||
parent_personal_data_uuid=None,
|
||||
)
|
||||
christmas_wish = LeaveWish(
|
||||
id=uuid4(),
|
||||
workspace_id=summer_wish.workspace_id,
|
||||
child_id=child.id,
|
||||
name="Jul",
|
||||
window_start_month=12,
|
||||
window_start_day=20,
|
||||
window_end_month=1,
|
||||
window_end_day=16, # wraps into January; 28 days = 4 weeks
|
||||
target_weeks=4,
|
||||
recurrence="yearly",
|
||||
first_year=CHILD_BIRTH_DATE.year,
|
||||
last_year=None,
|
||||
priority=1,
|
||||
parent_mode="either",
|
||||
parent_personal_data_uuid=None,
|
||||
)
|
||||
|
||||
holidays_map: dict[date, str] = {}
|
||||
for year in range(TODAY.year, horizon_end.year + 2):
|
||||
holidays_map.update(get_swedish_holidays(year))
|
||||
|
||||
alloc_input = AllocationInput(
|
||||
today=TODAY,
|
||||
horizon_end=horizon_end,
|
||||
planning_goal="balanced",
|
||||
planning_mode="couple",
|
||||
children=[child],
|
||||
parents=[parent_1, parent_2],
|
||||
pools=pools,
|
||||
vacation=vacation,
|
||||
wishes=[summer_wish, christmas_wish],
|
||||
existing_planned=[],
|
||||
holidays=holidays_map,
|
||||
)
|
||||
|
||||
names = {parent_1.uuid: parent_1.name, parent_2.uuid: parent_2.name}
|
||||
return alloc_input, names
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Pretty-print helpers (Swedish)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
DAY_TYPE_LABELS = {
|
||||
"vacation": "semesterdagar",
|
||||
"sjukpenning": "FP-dagar (sjukpenningnivå)",
|
||||
"lagsta": "FP-dagar (lägstanivå)",
|
||||
"free": "fria dagar (helg/röd dag)",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RenderedWindow:
|
||||
heading: str
|
||||
body_lines: list[str]
|
||||
|
||||
|
||||
def _render_window(outcome: WindowOutcome) -> _RenderedWindow:
|
||||
heading = (
|
||||
f"{outcome.wish_name} {outcome.year} "
|
||||
f"({outcome.start_date.isoformat()} → {outcome.end_date.isoformat()})"
|
||||
)
|
||||
lines: list[str] = []
|
||||
lines.append(
|
||||
f" {outcome.weeks_wished} veckor önskade -> {outcome.weeks_funded:.1f} veckor finansierade"
|
||||
)
|
||||
|
||||
breakdown_bits = []
|
||||
for key in ("free", "vacation", "sjukpenning", "lagsta"):
|
||||
count = outcome.cost_breakdown.get(key, 0)
|
||||
if count:
|
||||
breakdown_bits.append(f"{count} {DAY_TYPE_LABELS[key]}")
|
||||
if breakdown_bits:
|
||||
lines.append(" Dagar: " + ", ".join(breakdown_bits))
|
||||
|
||||
lines.append(f" Strategi: {outcome.strategy}")
|
||||
lines.append(f" Förklaring: {_render_window_explanation(outcome)}")
|
||||
|
||||
if outcome.shortfall_days > 0:
|
||||
lines.append(f" ⚠ Underskott: {outcome.shortfall_days} dagar kunde inte finansieras")
|
||||
for remedy in outcome.remedies:
|
||||
lines.append(f" → {_render_message(remedy.message_key, remedy.data)}")
|
||||
else:
|
||||
lines.append(" ✓ Fullt finansierad")
|
||||
|
||||
return _RenderedWindow(heading=heading, body_lines=lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# §3.5 — the engine now returns `message_key` + `data` (not pre-rendered
|
||||
# Swedish, see `PlanResults.tsx` / `frontend/src/i18n/sv.ts` for the real
|
||||
# UI-facing catalogue) so it can be shown in either locale. This script is a
|
||||
# developer CLI, not the UI — it only needs a Swedish rendering, so it keeps
|
||||
# a tiny local copy of the same templates rather than reaching into the
|
||||
# frontend's TypeScript i18n files.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SV_TEMPLATES: dict[str, str] = {
|
||||
"planRemedies.reduce_preschool_reserve": (
|
||||
"Minska förskolans planeringsdagar ({reserved} reserverade) frigör {reserved} dagar"
|
||||
),
|
||||
"planRemedies.carry_vacation_forward": (
|
||||
"{spare_total} semesterdagar från tidigare år kan sparas framåt"
|
||||
),
|
||||
"planRemedies.lower_priority_wish": (
|
||||
"Sänk {wish_name} från {from_weeks} till {to_weeks} veckor frigör {freed_days} dagar"
|
||||
),
|
||||
"planRemedies.shift_window_into_free_days": "Flytta {wish_name} närmare en helg frigör {shift_gain} dagar",
|
||||
"planWarnings.days_lost_at_age_4": (
|
||||
"riskerar att förlora {expiring_days} dagar vid barnets 4-årsdag "
|
||||
"({fourth_birthday}) om inte fler dagar tas ut innan dess"
|
||||
),
|
||||
"planWarnings.sgi_risk": (
|
||||
"riskerar SGI-skyddet veckan som börjar {week_start} "
|
||||
"({days_planned} dagar planerade, minst {min_days_per_week} krävs)"
|
||||
),
|
||||
"planWarnings.vacation_expiring": (
|
||||
"har {saved_days_in} sparade semesterdagar från {year} som riskerar att gå förlorade"
|
||||
),
|
||||
"planSurplusAdvice.wish_more_leave": (
|
||||
"har råd med ytterligare {weeks} veckor ledigt — lägg till en vecka på "
|
||||
"sommaren eller ett höstlov"
|
||||
),
|
||||
"planSurplusAdvice.shift_mix_to_fp": (
|
||||
"kan byta semesterdagar mot föräldrapenningdagar under planen"
|
||||
),
|
||||
"planSurplusAdvice.front_load_early_years": (
|
||||
"har ett stort överskott — ta ut fler dagar nu medan barnet är litet"
|
||||
),
|
||||
"planSurplusAdvice.use_less_vacation": (
|
||||
"kan ta ut färre semesterdagar ({years_text}) utan att gå under lägsta "
|
||||
"uttaget ({min_vacation_days_per_year} dagar/år)"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _render_message(message_key: str, data: dict) -> str:
|
||||
template = _SV_TEMPLATES.get(message_key)
|
||||
if template is None:
|
||||
return f"[{message_key}] {data}"
|
||||
try:
|
||||
return template.format(**data)
|
||||
except KeyError:
|
||||
return f"[{message_key}] {data}"
|
||||
|
||||
|
||||
def _render_window_explanation(outcome: WindowOutcome) -> str:
|
||||
data = outcome.data
|
||||
text = (
|
||||
f"{data['wish_name']} {data['year']} — {data['weeks_wished']} veckor önskade, "
|
||||
f"{data['weeks_funded']} veckor finansierade"
|
||||
)
|
||||
if data.get("shortfall_days", 0):
|
||||
text += f" ({data['shortfall_days']} dagar saknas)"
|
||||
|
||||
bits: list[str] = []
|
||||
cost = outcome.cost_breakdown
|
||||
fp_days = cost.get("sjukpenning", 0) + cost.get("lagsta", 0)
|
||||
if cost.get("vacation", 0) > 0 and fp_days > 0:
|
||||
bits.append(f"du behåller lönen {cost['vacation']} dagar och sparar {fp_days} FP-dagar")
|
||||
elif cost.get("vacation", 0) > 0:
|
||||
bits.append(f"{cost['vacation']} semesterdagar")
|
||||
if cost.get("sjukpenning", 0) > 0:
|
||||
bits.append(f"{cost['sjukpenning']} föräldrapenningdagar (sjukpenningnivå)")
|
||||
if cost.get("lagsta", 0) > 0:
|
||||
bits.append(f"{cost['lagsta']} föräldrapenningdagar (lägstanivå)")
|
||||
if cost.get("free", 0) > 0:
|
||||
bits.append(f"{cost['free']} helt fria dagar (helg/röd dag)")
|
||||
if bits:
|
||||
text += ": " + ", ".join(bits)
|
||||
return text
|
||||
|
||||
|
||||
def _print_report(proposal: PlanProposal, parent_names: dict) -> None:
|
||||
print("=" * 78)
|
||||
print("FÖRÄLDRALEDIGHETSPLAN — förslag (ej sparat)")
|
||||
print(f"Barn fött: {CHILD_BIRTH_DATE.isoformat()} | Dagens datum: {TODAY.isoformat()}")
|
||||
print("=" * 78)
|
||||
print()
|
||||
|
||||
outcomes = sorted(proposal.outcomes, key=lambda o: (o.year, o.start_date))
|
||||
if not outcomes:
|
||||
print("Inga fönster inom planeringshorisonten (allt ligger i det förflutna).")
|
||||
for outcome in outcomes:
|
||||
rendered = _render_window(outcome)
|
||||
print(rendered.heading)
|
||||
for line in rendered.body_lines:
|
||||
print(line)
|
||||
print()
|
||||
|
||||
total_wished_weeks = sum(o.weeks_wished for o in outcomes)
|
||||
total_funded_weeks = sum(o.weeks_funded for o in outcomes)
|
||||
total_shortfall = sum(o.shortfall_days for o in outcomes)
|
||||
print("-" * 78)
|
||||
print(
|
||||
f"Totalt: {total_wished_weeks} veckor önskade, {total_funded_weeks:.1f} veckor "
|
||||
f"finansierade över {len(outcomes)} fönster ({total_shortfall} dagar i underskott totalt)."
|
||||
)
|
||||
print()
|
||||
|
||||
if proposal.warnings:
|
||||
print("Varningar:")
|
||||
for warning in proposal.warnings:
|
||||
name = parent_names.get(warning.data.get("parent_personal_data_uuid"), "")
|
||||
body = _render_message(warning.message_key, warning.data)
|
||||
print(f" [{warning.kind}] {name} {body}".strip())
|
||||
print()
|
||||
|
||||
if proposal.surplus_advice:
|
||||
print("Förslag (överskott vid 4-årsdagen, §9.2):")
|
||||
for advice in proposal.surplus_advice:
|
||||
name = parent_names.get(advice.data.get("parent_personal_data_uuid"), "")
|
||||
body = _render_message(advice.message_key, advice.data)
|
||||
print(f" → [{advice.kind}] {name} {body}".strip())
|
||||
print()
|
||||
|
||||
print("Kvarvarande saldon efter planen:")
|
||||
for (parent_uuid, child_id), pool in proposal.balances_after.pools_after.items():
|
||||
name = parent_names.get(parent_uuid, str(parent_uuid))
|
||||
print(
|
||||
f" {name}: {pool.sjukpenning_left} sjukpenningdagar, "
|
||||
f"{pool.lagsta_left} lägstanivådagar, {pool.dubbeldagar_left} dubbeldagar kvar"
|
||||
)
|
||||
print()
|
||||
for (parent_uuid, year), budget in sorted(
|
||||
proposal.balances_after.vacation_after.items(), key=lambda kv: (str(kv[0][0]), kv[0][1])
|
||||
):
|
||||
name = parent_names.get(parent_uuid, str(parent_uuid))
|
||||
used = budget.already_used
|
||||
if used == 0:
|
||||
continue
|
||||
print(
|
||||
f" {name} {year}: {used}/{budget.total_days + budget.saved_days_in} semesterdagar använda"
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
alloc_input, parent_names = _build_input()
|
||||
proposal = Allocator().propose(alloc_input)
|
||||
_print_report(proposal, parent_names)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+312
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fetch and cache Swedish calendar data (holidays, de facto days).
|
||||
|
||||
This script fetches Swedish holiday data from the Dagsmart API
|
||||
(https://api.dagsmart.se/) and caches it locally as JSON.
|
||||
|
||||
The cache is used by the planning engine to determine working days
|
||||
without making API calls at runtime, ensuring the planner is offline
|
||||
and deterministic.
|
||||
|
||||
Rate limiting: 5 requests per 10 seconds (enforced via time.sleep).
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
# Configuration
|
||||
DAGSMART_API_BASE = "https://api.dagsmart.se/v3/holidays"
|
||||
CURRENT_YEAR = datetime.date.today().year
|
||||
YEARS_TO_FETCH = 10 # Fetch 10 years forward from current year (inclusive)
|
||||
RATE_LIMIT_DELAY = 2.5 # 5 requests per 10 seconds; conservative margin
|
||||
OUTPUT_DIR = Path(__file__).parent.parent / "app" / "data"
|
||||
OUTPUT_FILE = OUTPUT_DIR / "swedish_calendar.json"
|
||||
|
||||
|
||||
def validate_api_response(data: dict[str, Any]) -> None:
|
||||
"""Validate that API response has expected structure."""
|
||||
if "year" not in data:
|
||||
raise ValueError("API response missing 'year' field")
|
||||
if "days" not in data:
|
||||
raise ValueError("API response missing 'days' field")
|
||||
if not isinstance(data["days"], list):
|
||||
raise ValueError("API 'days' field must be a list")
|
||||
|
||||
# Validate each day record
|
||||
for day in data["days"]:
|
||||
if "date" not in day:
|
||||
raise ValueError("API day record missing 'date'")
|
||||
if "holidayType" not in day:
|
||||
raise ValueError("API day record missing 'holidayType'")
|
||||
if "workingDay" not in day:
|
||||
raise ValueError("API day record missing 'workingDay'")
|
||||
if "observances" not in day:
|
||||
raise ValueError("API day record missing 'observances'")
|
||||
if not isinstance(day["observances"], list):
|
||||
raise ValueError("API day 'observances' must be a list")
|
||||
|
||||
|
||||
def fetch_year(year: int, max_retries: int = 5) -> dict[str, Any]:
|
||||
"""Fetch calendar data for a single year from Dagsmart API.
|
||||
|
||||
Implements exponential backoff retry for rate limiting (429 responses).
|
||||
|
||||
Args:
|
||||
year: Calendar year to fetch
|
||||
max_retries: Maximum number of retry attempts
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from API
|
||||
|
||||
Raises:
|
||||
httpx.HTTPError: On network or HTTP errors
|
||||
ValueError: On invalid response format
|
||||
"""
|
||||
url = f"{DAGSMART_API_BASE}?year={year}"
|
||||
print(f"Fetching {year}...", file=sys.stderr)
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
response = httpx.get(url, timeout=10.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
validate_api_response(data)
|
||||
return data
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429 and attempt < max_retries - 1:
|
||||
# Rate limited; wait and retry with exponential backoff
|
||||
wait_time = 5 * (2**attempt)
|
||||
print(
|
||||
f"Rate limited (429). Waiting {wait_time}s before retry "
|
||||
f"({attempt + 1}/{max_retries})...",
|
||||
file=sys.stderr,
|
||||
)
|
||||
time.sleep(wait_time)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Failed to fetch calendar for year {year} from {url}: {e}"
|
||||
) from e
|
||||
except httpx.HTTPError as e:
|
||||
raise RuntimeError(f"Failed to fetch calendar for year {year} from {url}: {e}") from e
|
||||
|
||||
|
||||
def normalize_day(day: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize a day from API response into our schema.
|
||||
|
||||
Normalizes category to consistent "de_facto" spelling and lowercases names.
|
||||
|
||||
Args:
|
||||
day: Day record from Dagsmart API response
|
||||
|
||||
Returns:
|
||||
Normalized day record with our schema
|
||||
"""
|
||||
# Extract name from the first observance
|
||||
observances = day.get("observances", [])
|
||||
name_sv = "Unknown"
|
||||
name_en = "Unknown"
|
||||
|
||||
if observances:
|
||||
primary_observance = observances[0]
|
||||
name_data = primary_observance.get("name", {})
|
||||
name_sv = name_data.get("sv", "Unknown")
|
||||
name_en = name_data.get("en", "Unknown")
|
||||
|
||||
# Normalize category: vendor uses "defacto", we use "de_facto"
|
||||
category = day["holidayType"]
|
||||
if category == "defacto":
|
||||
category = "de_facto"
|
||||
|
||||
# Normalize names to lowercase for consistency
|
||||
name_sv = name_sv.lower() if name_sv != "Unknown" else name_sv
|
||||
name_en = name_en.lower() if name_en != "Unknown" else name_en
|
||||
|
||||
return {
|
||||
"date": day["date"],
|
||||
"name_sv": name_sv,
|
||||
"name_en": name_en,
|
||||
"category": category,
|
||||
"working_day": day["workingDay"],
|
||||
}
|
||||
|
||||
|
||||
def compute_bridge_days(year: int, non_working_dates: set[str]) -> list[dict[str, Any]]:
|
||||
"""Compute bridge days (klämdagar) for a year.
|
||||
|
||||
A bridge day is an ordinary working day (Mon-Fri) that:
|
||||
- Is not already a public or de facto day
|
||||
- Has a non-working day immediately before or after
|
||||
(weekends count as non-working)
|
||||
|
||||
These are days where employers often grant leave because taking one
|
||||
vacation day bridges between two non-working days, creating a longer
|
||||
continuous break.
|
||||
|
||||
Args:
|
||||
year: Calendar year
|
||||
non_working_dates: Set of date strings (YYYY-MM-DD) that are non-working
|
||||
|
||||
Returns:
|
||||
List of bridge day records
|
||||
"""
|
||||
bridge_days = []
|
||||
|
||||
# Iterate through all days in the year
|
||||
start_date = datetime.date(year, 1, 1)
|
||||
end_date = datetime.date(year, 12, 31)
|
||||
current = start_date
|
||||
|
||||
while current <= end_date:
|
||||
# Check if it's a working day (Mon-Fri)
|
||||
if current.weekday() < 5: # 0-4 are Mon-Fri
|
||||
date_str = current.isoformat()
|
||||
|
||||
# Not already in non-working set
|
||||
if date_str not in non_working_dates:
|
||||
# Check if day before and after are both non-working
|
||||
prev_day = current - datetime.timedelta(days=1)
|
||||
next_day = current + datetime.timedelta(days=1)
|
||||
|
||||
prev_is_nonworking = (
|
||||
prev_day.isoformat() in non_working_dates
|
||||
or prev_day.weekday() >= 5 # Saturday or Sunday
|
||||
)
|
||||
next_is_nonworking = (
|
||||
next_day.isoformat() in non_working_dates or next_day.weekday() >= 5
|
||||
)
|
||||
|
||||
if prev_is_nonworking and next_is_nonworking:
|
||||
bridge_days.append(
|
||||
{
|
||||
"date": date_str,
|
||||
"name_sv": "klämdag",
|
||||
"name_en": "bridge day",
|
||||
"category": "bridge_day",
|
||||
"working_day": True,
|
||||
}
|
||||
)
|
||||
|
||||
current += datetime.timedelta(days=1)
|
||||
|
||||
return bridge_days
|
||||
|
||||
|
||||
def normalize_year(api_response: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize API response for a year into our schema.
|
||||
|
||||
Includes computing bridge days (klämdagar) from the calendar.
|
||||
|
||||
Args:
|
||||
api_response: Full API response for a year
|
||||
|
||||
Returns:
|
||||
Normalized year record with our schema
|
||||
"""
|
||||
year = api_response["year"]
|
||||
normalized_days = [normalize_day(d) for d in api_response["days"]]
|
||||
|
||||
# Sort by date
|
||||
normalized_days.sort(key=lambda d: d["date"])
|
||||
|
||||
# Compute bridge days (klämdagar) from the calendar
|
||||
non_working_dates = {d["date"] for d in normalized_days if not d["working_day"]}
|
||||
bridge_days = compute_bridge_days(year, non_working_dates)
|
||||
|
||||
# Add bridge days to the list
|
||||
normalized_days.extend(bridge_days)
|
||||
|
||||
# Final sort
|
||||
normalized_days.sort(key=lambda d: d["date"])
|
||||
|
||||
return {
|
||||
"year": year,
|
||||
"days": normalized_days,
|
||||
}
|
||||
|
||||
|
||||
def fetch_all_years() -> dict[str, Any]:
|
||||
"""Fetch and normalize calendar data for all required years.
|
||||
|
||||
Returns:
|
||||
Complete calendar object with all years
|
||||
"""
|
||||
all_years = []
|
||||
end_year = CURRENT_YEAR + YEARS_TO_FETCH
|
||||
|
||||
for year in range(CURRENT_YEAR, end_year):
|
||||
try:
|
||||
api_response = fetch_year(year)
|
||||
normalized = normalize_year(api_response)
|
||||
all_years.append(normalized)
|
||||
except RuntimeError as e:
|
||||
print(f"ERROR: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Rate limiting: 5 requests per 10 seconds = 2 seconds per request
|
||||
time.sleep(RATE_LIMIT_DELAY)
|
||||
|
||||
return {
|
||||
"years": all_years,
|
||||
}
|
||||
|
||||
|
||||
def write_calendar_atomic(calendar_data: dict[str, Any]) -> None:
|
||||
"""Write calendar data to file atomically.
|
||||
|
||||
This function writes to a temporary file first, then renames it
|
||||
to the target file. This ensures we never leave a partial/corrupt
|
||||
cache file behind if the script fails.
|
||||
|
||||
Args:
|
||||
calendar_data: Complete calendar object to write
|
||||
"""
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write to a temporary file first
|
||||
temp_file = OUTPUT_FILE.with_suffix(".tmp")
|
||||
|
||||
try:
|
||||
with open(temp_file, "w") as f:
|
||||
json.dump(calendar_data, f, indent=2, sort_keys=True, ensure_ascii=False)
|
||||
f.write("\n") # Add trailing newline for clean git diffs
|
||||
except Exception as e:
|
||||
# Clean up temp file if write failed
|
||||
if temp_file.exists():
|
||||
temp_file.unlink()
|
||||
raise RuntimeError(f"Failed to write temporary calendar file: {e}") from e
|
||||
|
||||
# Atomically rename to target
|
||||
try:
|
||||
temp_file.replace(OUTPUT_FILE)
|
||||
print(f"Wrote calendar to {OUTPUT_FILE}", file=sys.stderr)
|
||||
except Exception as e:
|
||||
if temp_file.exists():
|
||||
temp_file.unlink()
|
||||
raise RuntimeError(f"Failed to move calendar file to final location: {e}") from e
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Main entry point."""
|
||||
print(
|
||||
f"Fetching Swedish calendar for years {CURRENT_YEAR}-{CURRENT_YEAR + YEARS_TO_FETCH - 1}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
calendar_data = fetch_all_years()
|
||||
|
||||
print(f"Fetched {len(calendar_data['years'])} years", file=sys.stderr)
|
||||
|
||||
write_calendar_atomic(calendar_data)
|
||||
|
||||
print("Done.", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user