File size: 1,903 Bytes
30fa1aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""Date and number helpers. Dates are local school days written as "YYYY-MM-DD"."""
from __future__ import annotations

from datetime import date, datetime, time, timedelta, timezone
from statistics import median as _median


def today() -> str:
    return date.today().isoformat()


def parse_ymd(s: str) -> date:
    return date.fromisoformat(s)


def add_days(s: str, n: int) -> str:
    return (parse_ymd(s) + timedelta(days=n)).isoformat()


def add_school_days(s: str, n: int) -> str:
    """Step n school days (Mon–Fri) from s; negative n goes back."""
    d = parse_ymd(s)
    step = -1 if n < 0 else 1
    left = abs(n)
    while left:
        d += timedelta(days=step)
        if d.weekday() < 5:
            left -= 1
    return d.isoformat()


def meal_id_for(day: str, grade: str = "") -> str:
    """("2026-09-26", "P1") -> "260926-P1"."""
    y, m, d = day.split("-")
    return f"{y[2:]}{m}{d}-{grade or 'LUNCH'}"


def iso(dt: datetime) -> str:
    """UTC timestamp in the same shape as JavaScript's toISOString()."""
    return dt.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")


def now_iso() -> str:
    return iso(datetime.now(timezone.utc))


def local_iso(day: str, hhmm: str) -> str:
    h, m = (int(x) for x in hhmm.split(":"))
    return iso(datetime.combine(parse_ymd(day), time(h, m)).astimezone())


def local_midnight_iso(day: str) -> str:
    return local_iso(day, "00:00")


def rnd(v: float | None, dp: int = 1) -> float | None:
    return None if v is None else round(v, dp)


def median(values: list[float]) -> float | None:
    return _median(values) if values else None


def mean(values: list[float]) -> float | None:
    return sum(values) / len(values) if values else None


def pct(part: float | None, whole: float | None) -> float | None:
    if part is None or not whole:
        return None
    return part / whole * 100