Initial commit with webpage
This commit is contained in:
commit
26875de1dd
55 files changed
+5726
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""Mamadachi web backend: device API, dashboard and database."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
"""Chart view-models. Python works out the geometry (percent positions, nice
|
||||
axis ticks); the templates draw plain HTML/SVG, so there is no JS chart
|
||||
library to load and the charts stay crisp at phone width."""
|
||||
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from .models import DeviceReport
|
||||
from .services.catalog import battery_percent
|
||||
from .services.stats import DayStats
|
||||
from .timeutil import Formatter, local_today, unix
|
||||
|
||||
|
||||
@dataclass
|
||||
class Column:
|
||||
label: str
|
||||
value: float
|
||||
height: float # % of plot height
|
||||
tip: str
|
||||
show_value: bool
|
||||
display: str
|
||||
partial: bool = False # today: the day isn't over yet
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tick:
|
||||
label: str
|
||||
pct: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class ColumnChart:
|
||||
key: str
|
||||
title: str
|
||||
cat: str
|
||||
columns: list[Column]
|
||||
ticks: list[Tick]
|
||||
summary: str
|
||||
|
||||
|
||||
def nice_ticks(vmax: float, *, integer: bool, target: int = 3) -> list[float]:
|
||||
vmax = vmax if vmax > 0 else 1
|
||||
raw = vmax / target
|
||||
mag = 10 ** math.floor(math.log10(raw))
|
||||
steps = (1, 2, 5, 10) if integer else (1, 2, 2.5, 5, 10)
|
||||
step = next(m * mag for m in steps if m * mag >= raw)
|
||||
if integer:
|
||||
step = max(1, round(step))
|
||||
top = step * math.ceil(vmax / step)
|
||||
return [i * step for i in range(int(round(top / step)) + 1)]
|
||||
|
||||
|
||||
def column_chart(
|
||||
key: str,
|
||||
title: str,
|
||||
cat: str,
|
||||
days: list[DayStats],
|
||||
get: Callable[[DayStats], float],
|
||||
fmt: Callable[[float], str],
|
||||
f: Formatter,
|
||||
*,
|
||||
integer: bool = True,
|
||||
summary: str = "",
|
||||
) -> ColumnChart:
|
||||
values = [get(d) for d in days]
|
||||
ticks = nice_ticks(max(values, default=0), integer=integer)
|
||||
top = ticks[-1]
|
||||
# Label the newest day and the highest one; the axis and tooltips carry the rest.
|
||||
peak = max(range(len(values)), key=lambda i: values[i], default=-1)
|
||||
today = local_today(f.tz)
|
||||
cols = []
|
||||
for i, (d, v) in enumerate(zip(days, values)):
|
||||
partial = d.day == today
|
||||
cols.append(
|
||||
Column(
|
||||
label=f.day_short(d.day),
|
||||
value=v,
|
||||
height=v / top * 100 if top else 0,
|
||||
tip=f"{f.day(d.day)}{' so far' if partial else ''} · {fmt(v)}",
|
||||
show_value=(i == len(days) - 1 or i == peak) and v > 0,
|
||||
display=fmt(v),
|
||||
partial=partial,
|
||||
)
|
||||
)
|
||||
return ColumnChart(
|
||||
key=key,
|
||||
title=title,
|
||||
cat=cat,
|
||||
columns=cols,
|
||||
ticks=[Tick(f"{t:g}", t / top * 100) for t in ticks],
|
||||
summary=summary,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LinePoint:
|
||||
x: float # 0..1000 (viewBox units)
|
||||
y: float # 0..300
|
||||
t: int
|
||||
tip: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class LineChart:
|
||||
path: str
|
||||
area: str
|
||||
points: list[LinePoint]
|
||||
yticks: list[Tick]
|
||||
xticks: list[Tick]
|
||||
empty: bool
|
||||
|
||||
|
||||
BATTERY_MIN_MV, BATTERY_MAX_MV = 3300, 4300
|
||||
VB_W, VB_H = 1000, 300
|
||||
|
||||
|
||||
def battery_chart(reports: list[DeviceReport], f: Formatter, start: datetime, end: datetime) -> LineChart:
|
||||
pts = [r for r in reports if r.battery_mv]
|
||||
span = (end - start).total_seconds() or 1
|
||||
|
||||
def y_of(mv: float) -> float:
|
||||
mv = min(max(mv, BATTERY_MIN_MV), BATTERY_MAX_MV)
|
||||
return VB_H - (mv - BATTERY_MIN_MV) / (BATTERY_MAX_MV - BATTERY_MIN_MV) * VB_H
|
||||
|
||||
points = []
|
||||
for r in pts:
|
||||
x = (r.received_at - start).total_seconds() / span * VB_W
|
||||
pct = battery_percent(r.battery_mv)
|
||||
charging = " · charging" if r.charging else ""
|
||||
points.append(
|
||||
LinePoint(
|
||||
x=round(x, 1),
|
||||
y=round(y_of(r.battery_mv), 1),
|
||||
t=unix(r.received_at),
|
||||
tip=f"{r.battery_mv / 1000:.2f} V · {pct}%{charging}|{f.when(r.received_at)}",
|
||||
)
|
||||
)
|
||||
path = " ".join(f"{'M' if i == 0 else 'L'}{p.x},{p.y}" for i, p in enumerate(points))
|
||||
area = f"{path} L{points[-1].x},{VB_H} L{points[0].x},{VB_H} Z" if points else ""
|
||||
yticks = [
|
||||
Tick(f"{mv / 1000:.1f} V", (mv - BATTERY_MIN_MV) / (BATTERY_MAX_MV - BATTERY_MIN_MV) * 100)
|
||||
for mv in (3400, 3600, 3800, 4000, 4200)
|
||||
]
|
||||
days = max(1, round(span / 86400))
|
||||
step = max(1, days // 5)
|
||||
xticks = []
|
||||
for i in range(0, days + 1, step):
|
||||
t = start + timedelta(days=i)
|
||||
if t <= end:
|
||||
xticks.append(Tick(f.day_short(f.local(t).date()), (t - start).total_seconds() / span * 100))
|
||||
return LineChart(path=path, area=area, points=points, yticks=yticks, xticks=xticks, empty=not points)
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"""Command-line helpers.
|
||||
|
||||
python -m app.cli migrate apply database migrations
|
||||
python -m app.cli create-device "Name" register a device, print its token
|
||||
python -m app.cli seed-demo --days 21 fill the database with fake newborn data
|
||||
python -m app.cli reset --yes delete ALL events, presses and devices
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from sqlalchemy import delete
|
||||
|
||||
from .db import SessionLocal
|
||||
from .main import run_migrations
|
||||
from .models import Device, DeviceReport, Event, Press
|
||||
from .services.catalog import ensure_defaults
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(prog="python -m app.cli")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
sub.add_parser("migrate", help="apply database migrations")
|
||||
cd = sub.add_parser("create-device", help="register a device and print its token")
|
||||
cd.add_argument("name", nargs="?", default="Mamadachi")
|
||||
sd = sub.add_parser("seed-demo", help="add a demo device with N days of fake presses")
|
||||
sd.add_argument("--days", type=int, default=21)
|
||||
sd.add_argument("--seed", type=int, default=7)
|
||||
rs = sub.add_parser("reset", help="delete all events, presses, devices and reports")
|
||||
rs.add_argument("--yes", action="store_true", help="really do it")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
run_migrations()
|
||||
with SessionLocal() as db:
|
||||
ensure_defaults(db)
|
||||
if args.cmd == "migrate":
|
||||
print("Database is up to date.")
|
||||
elif args.cmd == "create-device":
|
||||
from .services.ingest import create_device
|
||||
|
||||
dev, token = create_device(db, args.name)
|
||||
print(f"Device #{dev.id} {dev.name!r} created.")
|
||||
print(f"Token (shown once): {token}")
|
||||
elif args.cmd == "seed-demo":
|
||||
from .demo import seed_demo
|
||||
|
||||
n = seed_demo(db, days=args.days, seed=args.seed)
|
||||
print(f"Replayed {n} demo presses over {args.days} days.")
|
||||
elif args.cmd == "reset":
|
||||
if not args.yes:
|
||||
print("This deletes every event, press, device and sync report. Re-run with --yes.")
|
||||
return 1
|
||||
for model in (Press, Event, DeviceReport, Device):
|
||||
db.execute(delete(model))
|
||||
db.commit()
|
||||
print("All events, presses, devices and reports deleted. Settings were kept.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Settings, read from environment variables (or a local .env file).
|
||||
|
||||
Every setting has a safe local default, so `uvicorn app.main:app` works with no
|
||||
configuration: it uses a SQLite file next to this folder and no password.
|
||||
In production you set DATABASE_URL, SECRET_KEY and DASHBOARD_PASSWORD on the host.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
WEB_DIR = Path(__file__).resolve().parent.parent
|
||||
DEV_SECRET = "dev-only-secret-change-me"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=WEB_DIR / ".env", extra="ignore")
|
||||
|
||||
# "development" or "production". Production turns on secure cookies and
|
||||
# warns loudly about missing secrets.
|
||||
app_env: str = "development"
|
||||
|
||||
# Postgres in production (Neon, Supabase, Render...), SQLite locally.
|
||||
database_url: str = f"sqlite:///{(WEB_DIR / 'mamadachi.db').as_posix()}"
|
||||
|
||||
# Signs the login cookie. Any long random string; keep it secret.
|
||||
secret_key: str = DEV_SECRET
|
||||
|
||||
# One shared password for the dashboard. Empty = no login (local dev only!).
|
||||
dashboard_password: str = ""
|
||||
|
||||
# Timezone used until the parent picks one on the Settings page.
|
||||
default_timezone: str = "UTC"
|
||||
|
||||
# Run database migrations when the app starts. Leave on unless you run
|
||||
# `alembic upgrade head` yourself as a deploy step.
|
||||
auto_migrate: bool = True
|
||||
|
||||
# Production refuses to start on SQLite, because most hosts wipe the disk
|
||||
# on every deploy. Set true only if the file sits on a persistent volume.
|
||||
allow_sqlite_in_production: bool = False
|
||||
|
||||
log_level: str = "INFO"
|
||||
|
||||
@field_validator("database_url")
|
||||
@classmethod
|
||||
def _normalise_db_url(cls, v: str) -> str:
|
||||
# Hosts hand out "postgres://..." or "postgresql://..."; SQLAlchemy needs
|
||||
# to be told to use the psycopg (v3) driver.
|
||||
for prefix in ("postgres://", "postgresql://"):
|
||||
if v.startswith(prefix):
|
||||
return "postgresql+psycopg://" + v[len(prefix):]
|
||||
return v
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return self.app_env.lower() in {"prod", "production"}
|
||||
|
||||
@property
|
||||
def is_sqlite(self) -> bool:
|
||||
return self.database_url.startswith("sqlite")
|
||||
|
||||
@property
|
||||
def login_required(self) -> bool:
|
||||
return bool(self.dashboard_password)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Database engine and sessions."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
|
||||
def make_engine(url: str) -> Engine:
|
||||
if url.startswith("sqlite"):
|
||||
engine = create_engine(url, connect_args={"check_same_thread": False})
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def _sqlite_pragmas(dbapi_conn, _record): # noqa: ANN001
|
||||
cur = dbapi_conn.cursor()
|
||||
cur.execute("PRAGMA foreign_keys=ON")
|
||||
cur.execute("PRAGMA journal_mode=WAL")
|
||||
cur.close()
|
||||
|
||||
return engine
|
||||
|
||||
return create_engine(
|
||||
url,
|
||||
# Managed Postgres drops idle connections (Neon scales to zero, poolers
|
||||
# time out). Test each connection before use instead of failing a request.
|
||||
pool_pre_ping=True,
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
pool_recycle=300,
|
||||
# Prepared statements break behind PgBouncer-style transaction poolers
|
||||
# (Supabase port 6543, Neon "-pooler" hosts). This app is tiny; skip them.
|
||||
connect_args={"prepare_threshold": None, "connect_timeout": 10},
|
||||
)
|
||||
|
||||
|
||||
engine = make_engine(get_settings().database_url)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||
|
||||
|
||||
def get_db() -> Iterator[Session]:
|
||||
"""FastAPI dependency: one session per request, always closed."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"""Realistic fake data for a newborn, pushed through the real sync code path
|
||||
(as if a Mamadachi had been in use for N days). For demos and testing only."""
|
||||
|
||||
import random
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .models import Event
|
||||
from .schemas import DeviceEventIn, SyncRequest
|
||||
from .services.catalog import DEFAULT_BUTTONS, get_profile
|
||||
from .services.ingest import create_device, ingest
|
||||
from .timeutil import safe_zone, unix, utcnow
|
||||
|
||||
BUTTON = {slug: n for n, slug in enumerate(DEFAULT_BUTTONS, start=1)}
|
||||
|
||||
|
||||
def _newborn_presses(start: datetime, end: datetime, tz, rng: random.Random) -> list[tuple[datetime, int]]: # noqa: ANN001
|
||||
presses: list[tuple[datetime, int]] = []
|
||||
t = start
|
||||
side = "nurse_left"
|
||||
last_pump = start
|
||||
last_vitamin_day = None
|
||||
while t < end:
|
||||
hour = t.astimezone(tz).hour
|
||||
night = hour >= 22 or hour < 6
|
||||
# -- feed
|
||||
if rng.random() < 0.85:
|
||||
presses.append((t, BUTTON[side]))
|
||||
other = "nurse_right" if side == "nurse_left" else "nurse_left"
|
||||
if rng.random() < 0.8:
|
||||
presses.append((t + timedelta(minutes=rng.randint(12, 22)), BUTTON[other]))
|
||||
side = other
|
||||
else:
|
||||
presses.append((t, BUTTON["bottle"]))
|
||||
# -- diaper
|
||||
change = t + timedelta(minutes=rng.randint(20, 35))
|
||||
if rng.random() < 0.85:
|
||||
presses.append((change, BUTTON["wet"]))
|
||||
if rng.random() < (0.25 if night else 0.4):
|
||||
presses.append((change + timedelta(seconds=20), BUTTON["dirty"]))
|
||||
# -- vitamin D once a day after the first morning feed
|
||||
local = t.astimezone(tz)
|
||||
if local.hour >= 8 and last_vitamin_day != local.date():
|
||||
presses.append((t + timedelta(minutes=40), BUTTON["medicine"]))
|
||||
last_vitamin_day = local.date()
|
||||
# -- pump a couple of times a day
|
||||
if not night and t - last_pump > timedelta(hours=rng.uniform(7, 10)):
|
||||
presses.append((t + timedelta(minutes=50), BUTTON["pump"]))
|
||||
last_pump = t
|
||||
# -- sleep until shortly before the next feed
|
||||
gap = timedelta(hours=rng.uniform(3.2, 4.4) if night else rng.uniform(2.2, 3.3))
|
||||
nxt = t + gap
|
||||
sleep_start = t + timedelta(minutes=rng.randint(45, 70))
|
||||
sleep_end = nxt - timedelta(minutes=rng.randint(4, 15))
|
||||
if sleep_end - sleep_start > timedelta(minutes=20):
|
||||
presses.append((sleep_start, BUTTON["sleep"]))
|
||||
if sleep_end < end:
|
||||
presses.append((sleep_end, BUTTON["sleep"]))
|
||||
t = nxt
|
||||
presses.sort()
|
||||
return [(when, b) for when, b in presses if when < end]
|
||||
|
||||
|
||||
def seed_demo(db: Session, days: int = 21, seed: int = 7) -> int:
|
||||
"""Create a "Demo Mamadachi" and replay `days` of presses through hourly syncs."""
|
||||
rng = random.Random(seed)
|
||||
profile = get_profile(db)
|
||||
tz = safe_zone(profile.timezone)
|
||||
now = utcnow().replace(microsecond=0)
|
||||
start = now - timedelta(days=days)
|
||||
presses = _newborn_presses(start, now - timedelta(minutes=10), tz, rng)
|
||||
|
||||
device, _token = create_device(db, "Demo Mamadachi")
|
||||
seq = 0
|
||||
battery = 4150.0
|
||||
i = 0
|
||||
sync_at = start + timedelta(hours=1)
|
||||
while sync_at <= now:
|
||||
batch: list[DeviceEventIn] = []
|
||||
while i < len(presses) and presses[i][0] <= sync_at:
|
||||
seq += 1
|
||||
batch.append(DeviceEventIn(seq=seq, time=unix(presses[i][0]), button=presses[i][1]))
|
||||
i += 1
|
||||
battery -= rng.uniform(0.3, 0.9) # ~15 mV a day
|
||||
charging = False
|
||||
if battery < 3720: # a recharge partway through
|
||||
battery, charging = 4180.0, True
|
||||
req = SyncRequest(
|
||||
device_time=unix(sync_at) - rng.randint(0, 2),
|
||||
firmware="0.1.0-demo",
|
||||
battery_mv=round(battery + rng.uniform(-6, 6)),
|
||||
charging=charging,
|
||||
rssi=rng.randint(-72, -52),
|
||||
boot_count=seq,
|
||||
queue_len=0,
|
||||
events=batch,
|
||||
)
|
||||
ingest(db, device, req, received_at=sync_at + timedelta(seconds=rng.randint(1, 4)))
|
||||
sync_at += timedelta(minutes=profile.sync_interval_min)
|
||||
|
||||
# A couple of notes, like a parent would add.
|
||||
for ev in db.scalars(select(Event).where(Event.kind_slug == "bottle").limit(6)):
|
||||
ev.note = f"{rng.choice([60, 75, 90, 90, 120])} ml"
|
||||
db.commit()
|
||||
return seq
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
"""The web app: device API + dashboard + JSON API in one process.
|
||||
|
||||
Run locally: uvicorn app.main:app --reload
|
||||
API docs: http://localhost:8000/docs
|
||||
"""
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import text
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from . import __version__
|
||||
from .config import DEV_SECRET, WEB_DIR, get_settings
|
||||
from .db import SessionLocal, engine
|
||||
from .routes import admin, api, auth, device_api, pages
|
||||
from .services.catalog import ensure_defaults
|
||||
from .web import APP_DIR, LoginRequired, render
|
||||
|
||||
log = logging.getLogger("mamadachi")
|
||||
|
||||
|
||||
def run_migrations() -> None:
|
||||
"""Bring the database schema up to date (same as `alembic upgrade head`)."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
cfg = Config(str(WEB_DIR / "alembic.ini"))
|
||||
cfg.set_main_option("script_location", str(WEB_DIR / "migrations"))
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI): # noqa: ANN201
|
||||
settings = get_settings()
|
||||
logging.basicConfig(level=settings.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
if settings.is_production:
|
||||
# Fail loudly at deploy time rather than quietly losing data later.
|
||||
if settings.is_sqlite and not settings.allow_sqlite_in_production:
|
||||
raise RuntimeError(
|
||||
"DATABASE_URL is not set, so the app would store data in a SQLite file that this host "
|
||||
"deletes on every deploy. Set DATABASE_URL to your Postgres connection string."
|
||||
)
|
||||
if settings.login_required and settings.secret_key == DEV_SECRET:
|
||||
raise RuntimeError("Set SECRET_KEY to a long random string, or anyone could forge a login cookie.")
|
||||
if not settings.login_required:
|
||||
log.error("DASHBOARD_PASSWORD is not set: anyone with the URL can see the dashboard.")
|
||||
if settings.auto_migrate:
|
||||
run_migrations()
|
||||
with SessionLocal() as db:
|
||||
ensure_defaults(db)
|
||||
log.info("Mamadachi %s ready (%s)", __version__, engine.url.render_as_string(hide_password=True))
|
||||
yield
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
app = FastAPI(
|
||||
title="Mamadachi",
|
||||
version=__version__,
|
||||
summary="Baby-event tracker: device sync API, dashboard API and website.",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def same_origin_and_headers(request: Request, call_next): # noqa: ANN001, ANN201
|
||||
# Block cross-site form posts (CSRF). Browsers send Origin on POST; the
|
||||
# device doesn't, and it authenticates with its token anyway.
|
||||
if request.method not in ("GET", "HEAD", "OPTIONS"):
|
||||
origin = request.headers.get("origin")
|
||||
if origin and origin != "null" and urlsplit(origin).netloc != request.headers.get("host"):
|
||||
return PlainTextResponse("Cross-site request blocked.", status_code=403)
|
||||
response: Response = await call_next(request)
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
response.headers.setdefault("Referrer-Policy", "same-origin")
|
||||
response.headers.setdefault("X-Frame-Options", "DENY")
|
||||
return response
|
||||
|
||||
|
||||
app.add_middleware(
|
||||
SessionMiddleware,
|
||||
secret_key=settings.secret_key,
|
||||
session_cookie="mamadachi",
|
||||
max_age=60 * 60 * 24 * 90, # stay logged in for 90 days on the parent's phone
|
||||
same_site="lax",
|
||||
https_only=settings.is_production,
|
||||
)
|
||||
|
||||
app.mount("/static", StaticFiles(directory=APP_DIR / "static"), name="static")
|
||||
|
||||
|
||||
@app.exception_handler(LoginRequired)
|
||||
async def _login_redirect(request: Request, _exc: LoginRequired) -> RedirectResponse:
|
||||
target = request.url.path + (f"?{request.url.query}" if request.url.query else "")
|
||||
return RedirectResponse(f"/login?next={target}", status_code=303)
|
||||
|
||||
|
||||
def _wants_html(request: Request) -> bool:
|
||||
return not request.url.path.startswith("/api/") and "text/html" in request.headers.get("accept", "")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _http_error(request: Request, exc: StarletteHTTPException) -> Response:
|
||||
if _wants_html(request):
|
||||
with SessionLocal() as db:
|
||||
return render(request, db, "error.html", status_code=exc.status_code, code=exc.status_code, detail=exc.detail)
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=getattr(exc, "headers", None))
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
# Log what the device sent wrong: invaluable while writing firmware.
|
||||
log.warning("422 on %s: %s", request.url.path, exc.errors()[:3])
|
||||
return JSONResponse({"detail": exc.errors()}, status_code=422)
|
||||
|
||||
|
||||
@app.get("/healthz", include_in_schema=False)
|
||||
def healthz() -> dict:
|
||||
"""Liveness: the process is up. Used by the host's health checks."""
|
||||
return {"ok": True, "version": __version__}
|
||||
|
||||
|
||||
@app.get("/readyz", include_in_schema=False)
|
||||
def readyz() -> JSONResponse:
|
||||
"""Readiness: the database answers too."""
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.error("database check failed: %s", e)
|
||||
return JSONResponse({"ok": False, "database": "unreachable"}, status_code=503)
|
||||
return JSONResponse({"ok": True, "database": "ok"})
|
||||
|
||||
|
||||
@app.get("/manifest.webmanifest", include_in_schema=False)
|
||||
def manifest() -> JSONResponse:
|
||||
"""Lets the parent "Add to Home Screen" and open the dashboard like an app."""
|
||||
return JSONResponse(
|
||||
{
|
||||
"name": "Mamadachi",
|
||||
"short_name": "Mamadachi",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f9f9f7",
|
||||
"theme_color": "#f9f9f7",
|
||||
"icons": [{"src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any"}],
|
||||
},
|
||||
media_type="application/manifest+json",
|
||||
)
|
||||
|
||||
|
||||
app.include_router(device_api.router)
|
||||
app.include_router(api.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(pages.router)
|
||||
app.include_router(admin.router)
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
"""Database tables.
|
||||
|
||||
profile ─┐ one row: baby name, birth date, timezone, display prefs
|
||||
event_kinds ─┬─ buttons what each of the 8 buttons means (editable)
|
||||
└─ events the log the parent sees and edits
|
||||
devices ─┬─ presses raw button presses exactly as the device sent them
|
||||
└─ device_reports one row per sync: battery, signal, clock skew...
|
||||
|
||||
Presses are the device's append-only record (used to drop duplicate uploads);
|
||||
events are derived from them (or typed in by hand) and can be edited. A sleep
|
||||
start and stop are two presses but one event with started_at/ended_at.
|
||||
|
||||
After changing anything here, create a migration:
|
||||
alembic revision --autogenerate -m "describe the change"
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
Boolean,
|
||||
Date,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
MetaData,
|
||||
SmallInteger,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class UTCDateTime(TypeDecorator):
|
||||
"""Timezone-aware UTC datetimes on both Postgres and SQLite.
|
||||
|
||||
SQLite has no timezone support, so values are stored as naive UTC there
|
||||
and turned back into aware datetimes on the way out.
|
||||
"""
|
||||
|
||||
impl = DateTime(timezone=True)
|
||||
cache_ok = True
|
||||
|
||||
def process_bind_param(self, value: datetime | None, dialect): # noqa: ANN001
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("naive datetime given to a UTCDateTime column; attach a timezone")
|
||||
value = value.astimezone(timezone.utc)
|
||||
return value.replace(tzinfo=None) if dialect.name == "sqlite" else value
|
||||
|
||||
def process_result_value(self, value: datetime | None, dialect): # noqa: ANN001
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def alembic_render_item(type_, obj, autogen_context): # noqa: ANN001, ANN201
|
||||
"""Write UTCDateTime into migration files as a plain timestamp column, so
|
||||
migrations don't depend on app code that may change later."""
|
||||
if type_ == "type" and isinstance(obj, UTCDateTime):
|
||||
return "sa.DateTime(timezone=True)"
|
||||
return False
|
||||
|
||||
|
||||
def alembic_compare_type(context, inspected_column, metadata_column, inspected_type, metadata_type): # noqa: ANN001, ANN201
|
||||
if isinstance(metadata_type, UTCDateTime) and isinstance(inspected_type, DateTime):
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
# Predictable constraint names make migrations (and SQLite batch mode) reliable.
|
||||
metadata = MetaData(
|
||||
naming_convention={
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class Profile(Base):
|
||||
"""The baby and the family's display preferences. Always exactly one row (id=1)."""
|
||||
|
||||
__tablename__ = "profile"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
baby_name: Mapped[str] = mapped_column(String(80), default="Baby")
|
||||
birth_date: Mapped[date | None] = mapped_column(Date)
|
||||
timezone: Mapped[str] = mapped_column(String(64), default="UTC")
|
||||
clock_24h: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# How often the device should sync, sent to it in every sync response.
|
||||
sync_interval_min: Mapped[int] = mapped_column(Integer, default=60)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, onupdate=utcnow)
|
||||
|
||||
|
||||
class Kind(Base):
|
||||
"""A type of event: "Wet diaper", "Sleep"... Kinds are never deleted, only hidden."""
|
||||
|
||||
__tablename__ = "event_kinds"
|
||||
|
||||
slug: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
label: Mapped[str] = mapped_column(String(40))
|
||||
# Up to 10 characters, for the device's 200x200 e-paper.
|
||||
short: Mapped[str] = mapped_column(String(12))
|
||||
emoji: Mapped[str] = mapped_column(String(16), default="")
|
||||
# sleep | feeding | diaper | pump | health | activity | other (see catalog.py)
|
||||
category: Mapped[str] = mapped_column(String(16))
|
||||
# "instant": one press = one event.
|
||||
# "duration": first press starts it, next press ends it (sleep, tummy time).
|
||||
mode: Mapped[str] = mapped_column(String(10), default="instant")
|
||||
# For duration kinds: a start older than this is treated as forgotten, so the
|
||||
# next press starts a new session instead of ending a 2-day "nap".
|
||||
max_minutes: Mapped[int | None] = mapped_column(Integer)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
|
||||
@property
|
||||
def is_duration(self) -> bool:
|
||||
return self.mode == "duration"
|
||||
|
||||
@property
|
||||
def max_duration(self) -> timedelta | None:
|
||||
return timedelta(minutes=self.max_minutes) if self.max_minutes else None
|
||||
|
||||
|
||||
class ButtonMap(Base):
|
||||
"""Which kind each physical button (1-8) logs."""
|
||||
|
||||
__tablename__ = "buttons"
|
||||
|
||||
button: Mapped[int] = mapped_column(SmallInteger, primary_key=True, autoincrement=False)
|
||||
kind_slug: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("event_kinds.slug", ondelete="SET NULL", onupdate="CASCADE")
|
||||
)
|
||||
|
||||
kind: Mapped[Kind | None] = relationship(lazy="joined")
|
||||
|
||||
|
||||
class Device(Base):
|
||||
__tablename__ = "devices"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(80))
|
||||
# SHA-256 of the device's API token. The token itself is never stored.
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
token_hint: Mapped[str] = mapped_column(String(12), default="")
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
|
||||
# Latest state, copied from the most recent sync.
|
||||
last_seen_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
firmware: Mapped[str | None] = mapped_column(String(32))
|
||||
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
||||
charging: Mapped[bool | None] = mapped_column(Boolean)
|
||||
rssi: Mapped[int | None] = mapped_column(SmallInteger)
|
||||
clock_skew_s: Mapped[int | None] = mapped_column(Integer)
|
||||
boot_count: Mapped[int | None] = mapped_column(Integer)
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self.revoked_at is None
|
||||
|
||||
|
||||
class DeviceReport(Base):
|
||||
"""One row per sync. Battery voltage over weeks shows real battery life."""
|
||||
|
||||
__tablename__ = "device_reports"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"), index=True)
|
||||
received_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, index=True)
|
||||
firmware: Mapped[str | None] = mapped_column(String(32))
|
||||
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
||||
charging: Mapped[bool | None] = mapped_column(Boolean)
|
||||
rssi: Mapped[int | None] = mapped_column(SmallInteger)
|
||||
clock_skew_s: Mapped[int | None] = mapped_column(Integer)
|
||||
boot_count: Mapped[int | None] = mapped_column(Integer)
|
||||
queue_len: Mapped[int | None] = mapped_column(Integer)
|
||||
events_received: Mapped[int] = mapped_column(Integer, default=0)
|
||||
events_new: Mapped[int] = mapped_column(Integer, default=0)
|
||||
duration_ms: Mapped[int | None] = mapped_column(Integer)
|
||||
extra: Mapped[dict[str, Any] | None] = mapped_column(JSON)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
"""One thing that happened to the baby. Duration kinds have an end time."""
|
||||
|
||||
__tablename__ = "events"
|
||||
__table_args__ = (Index("ix_events_kind_open", "kind_slug", "ended_at"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
kind_slug: Mapped[str] = mapped_column(
|
||||
ForeignKey("event_kinds.slug", onupdate="CASCADE"), index=True
|
||||
)
|
||||
started_at: Mapped[datetime] = mapped_column(UTCDateTime, index=True)
|
||||
ended_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
note: Mapped[str | None] = mapped_column(Text)
|
||||
source: Mapped[str] = mapped_column(String(8), default="manual") # device | manual
|
||||
device_id: Mapped[int | None] = mapped_column(ForeignKey("devices.id", ondelete="SET NULL"))
|
||||
button: Mapped[int | None] = mapped_column(SmallInteger)
|
||||
# True when the device's clock was wrong and the server shifted the time.
|
||||
clock_corrected: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, onupdate=utcnow)
|
||||
# Soft delete, so "Undo" works and nothing is lost to a mis-tap at 3 a.m.
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(UTCDateTime, index=True)
|
||||
|
||||
kind: Mapped[Kind] = relationship(lazy="joined")
|
||||
|
||||
@property
|
||||
def is_open(self) -> bool:
|
||||
return self.kind.is_duration and self.ended_at is None
|
||||
|
||||
@property
|
||||
def duration(self) -> timedelta | None:
|
||||
if self.ended_at is None:
|
||||
return None
|
||||
return self.ended_at - self.started_at
|
||||
|
||||
|
||||
class Press(Base):
|
||||
"""A button press exactly as uploaded. Append-only.
|
||||
|
||||
(device_id, seq, device_time) identifies a press: a retried upload repeats
|
||||
all three and is ignored. The time is part of the key so a device whose
|
||||
sequence counter restarts at 1 (reflash, erased flash) isn't mistaken for
|
||||
a replay of old presses.
|
||||
"""
|
||||
|
||||
__tablename__ = "presses"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("device_id", "seq", "device_time", name="uq_presses_identity"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
|
||||
seq: Mapped[int] = mapped_column(Integer)
|
||||
button: Mapped[int] = mapped_column(SmallInteger)
|
||||
device_time: Mapped[datetime] = mapped_column(UTCDateTime) # as the device's RTC said
|
||||
occurred_at: Mapped[datetime] = mapped_column(UTCDateTime) # after clock correction
|
||||
received_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
clock_corrected: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# instant | start | end: what this press did to the event log.
|
||||
role: Mapped[str] = mapped_column(String(8), default="instant")
|
||||
event_id: Mapped[int | None] = mapped_column(ForeignKey("events.id", ondelete="SET NULL"))
|
||||
Whitespace-only changes.
@@ -0,0 +1,245 @@
|
||||
"""Device management and Settings pages."""
|
||||
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..charts import battery_chart
|
||||
from ..db import get_db
|
||||
from ..models import ButtonMap, Device, DeviceReport, Kind, Press
|
||||
from ..services.catalog import CATEGORIES, NUM_BUTTONS, all_kinds, battery_percent, button_map, get_profile
|
||||
from ..services.ingest import create_device, rotate_token
|
||||
from ..timeutil import is_valid_zone, utcnow, zone_choices
|
||||
from ..web import flash, formatter, redirect, render, require_login
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_login)], include_in_schema=False)
|
||||
|
||||
Db = Annotated[Session, Depends(get_db)]
|
||||
|
||||
BATTERY_DAYS = 30
|
||||
|
||||
|
||||
def signal_quality(rssi: int | None) -> str:
|
||||
if rssi is None:
|
||||
return ""
|
||||
if rssi >= -55:
|
||||
return "excellent"
|
||||
if rssi >= -67:
|
||||
return "good"
|
||||
if rssi >= -75:
|
||||
return "fair"
|
||||
return "weak"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Device
|
||||
|
||||
|
||||
def _device_page(request: Request, db: Session, new_token: str | None = None, new_device: Device | None = None) -> HTMLResponse:
|
||||
f = formatter(db)
|
||||
now = utcnow()
|
||||
devices = list(db.scalars(select(Device).order_by(Device.revoked_at.is_not(None), Device.created_at)))
|
||||
press_counts = dict(db.execute(select(Press.device_id, func.count()).group_by(Press.device_id)).all())
|
||||
since = now - timedelta(days=BATTERY_DAYS)
|
||||
cards = []
|
||||
for dev in devices:
|
||||
reports = list(
|
||||
db.scalars(
|
||||
select(DeviceReport)
|
||||
.where(DeviceReport.device_id == dev.id, DeviceReport.received_at >= since)
|
||||
.order_by(DeviceReport.received_at)
|
||||
)
|
||||
)
|
||||
cards.append(
|
||||
{
|
||||
"dev": dev,
|
||||
"battery_pct": battery_percent(dev.battery_mv),
|
||||
"signal": signal_quality(dev.rssi),
|
||||
"presses": press_counts.get(dev.id, 0),
|
||||
"chart": battery_chart(reports, f, since, now),
|
||||
"log": list(reversed(reports[-15:])),
|
||||
}
|
||||
)
|
||||
base = str(request.base_url).rstrip("/")
|
||||
if request.headers.get("x-forwarded-proto") == "https":
|
||||
base = base.replace("http://", "https://", 1)
|
||||
return render(
|
||||
request,
|
||||
db,
|
||||
"device.html",
|
||||
cards=cards,
|
||||
new_token=new_token,
|
||||
new_device=new_device,
|
||||
base_url=base,
|
||||
buttons=button_map(db),
|
||||
battery_days=BATTERY_DAYS,
|
||||
)
|
||||
|
||||
|
||||
def _get_device(db: Session, device_id: int) -> Device:
|
||||
dev = db.get(Device, device_id)
|
||||
if dev is None:
|
||||
raise HTTPException(404, "No such device")
|
||||
return dev
|
||||
|
||||
|
||||
@router.get("/device", response_class=HTMLResponse)
|
||||
def device_page(request: Request, db: Db) -> HTMLResponse:
|
||||
return _device_page(request, db)
|
||||
|
||||
|
||||
@router.post("/device/new", response_class=HTMLResponse)
|
||||
def device_new(request: Request, db: Db, name: Annotated[str, Form()] = "Mamadachi") -> HTMLResponse:
|
||||
dev, token = create_device(db, name[:80])
|
||||
# Rendered straight away (no redirect): the token is shown exactly once.
|
||||
return _device_page(request, db, new_token=token, new_device=dev)
|
||||
|
||||
|
||||
@router.post("/device/{device_id}/rotate", response_class=HTMLResponse)
|
||||
def device_rotate(request: Request, db: Db, device_id: int) -> HTMLResponse:
|
||||
dev = _get_device(db, device_id)
|
||||
token = rotate_token(db, dev)
|
||||
return _device_page(request, db, new_token=token, new_device=dev)
|
||||
|
||||
|
||||
@router.post("/device/{device_id}/revoke")
|
||||
def device_revoke(request: Request, db: Db, device_id: int) -> RedirectResponse:
|
||||
dev = _get_device(db, device_id)
|
||||
dev.revoked_at = utcnow()
|
||||
db.commit()
|
||||
flash(request, f"{dev.name} can no longer sync. Its events stay in the log.")
|
||||
return redirect("/device")
|
||||
|
||||
|
||||
@router.post("/device/{device_id}/rename")
|
||||
def device_rename(request: Request, db: Db, device_id: int, name: Annotated[str, Form()]) -> RedirectResponse:
|
||||
dev = _get_device(db, device_id)
|
||||
if name.strip():
|
||||
dev.name = name.strip()[:80]
|
||||
db.commit()
|
||||
flash(request, "Renamed.")
|
||||
return redirect("/device")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Settings
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request, db: Db) -> HTMLResponse:
|
||||
return render(
|
||||
request,
|
||||
db,
|
||||
"settings.html",
|
||||
kinds=all_kinds(db),
|
||||
buttons=button_map(db),
|
||||
zones=zone_choices(),
|
||||
categories=CATEGORIES,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/settings/profile")
|
||||
def save_profile(
|
||||
request: Request,
|
||||
db: Db,
|
||||
baby_name: Annotated[str, Form()],
|
||||
timezone: Annotated[str, Form()],
|
||||
birth_date: Annotated[str, Form()] = "",
|
||||
clock_24h: Annotated[bool, Form()] = False,
|
||||
sync_interval_min: Annotated[int, Form(ge=5, le=24 * 60)] = 60,
|
||||
) -> RedirectResponse:
|
||||
p = get_profile(db)
|
||||
if not is_valid_zone(timezone):
|
||||
flash(request, f"Unknown timezone {timezone!r}.", level="error")
|
||||
return redirect("/settings")
|
||||
try:
|
||||
bd = date.fromisoformat(birth_date) if birth_date else None
|
||||
except ValueError:
|
||||
flash(request, "That birth date doesn't look right.", level="error")
|
||||
return redirect("/settings")
|
||||
p.baby_name = baby_name.strip()[:80] or "Baby"
|
||||
p.timezone = timezone
|
||||
p.birth_date = bd
|
||||
p.clock_24h = clock_24h
|
||||
p.sync_interval_min = sync_interval_min
|
||||
db.commit()
|
||||
flash(request, "Profile saved.")
|
||||
return redirect("/settings")
|
||||
|
||||
|
||||
@router.post("/settings/timezone")
|
||||
def set_timezone(request: Request, db: Db, timezone: Annotated[str, Form()], next: Annotated[str, Form()] = "/") -> RedirectResponse:
|
||||
"""One-click fix from the "your browser is in another timezone" banner."""
|
||||
if is_valid_zone(timezone):
|
||||
get_profile(db).timezone = timezone
|
||||
db.commit()
|
||||
flash(request, f"Timezone set to {timezone}.")
|
||||
return redirect(next if next.startswith("/") and not next.startswith("//") else "/")
|
||||
|
||||
|
||||
@router.post("/settings/buttons")
|
||||
async def save_buttons(request: Request, db: Db) -> RedirectResponse:
|
||||
form = await request.form()
|
||||
valid = {k.slug for k in all_kinds(db)}
|
||||
for n in range(1, NUM_BUTTONS + 1):
|
||||
slug = str(form.get(f"button_{n}", ""))
|
||||
row = db.get(ButtonMap, n) or ButtonMap(button=n)
|
||||
row.kind_slug = slug if slug in valid else None
|
||||
db.add(row)
|
||||
db.commit()
|
||||
flash(request, "Button layout saved. The device picks it up at its next sync.")
|
||||
return redirect("/settings#buttons")
|
||||
|
||||
|
||||
@router.post("/settings/kinds")
|
||||
async def save_kinds(request: Request, db: Db) -> RedirectResponse:
|
||||
form = await request.form()
|
||||
for kind in all_kinds(db):
|
||||
p = f"{kind.slug}__"
|
||||
if f"{p}label" not in form:
|
||||
continue
|
||||
kind.label = str(form[f"{p}label"]).strip()[:40] or kind.label
|
||||
kind.short = str(form.get(f"{p}short", "")).strip()[:10] or kind.label[:10]
|
||||
kind.emoji = str(form.get(f"{p}emoji", "")).strip()[:8]
|
||||
kind.mode = "duration" if form.get(f"{p}mode") == "duration" else "instant"
|
||||
raw_max = str(form.get(f"{p}max", "")).strip()
|
||||
kind.max_minutes = int(raw_max) if raw_max.isdigit() and int(raw_max) > 0 else None
|
||||
kind.active = form.get(f"{p}active") == "on" or kind.slug == "other"
|
||||
db.commit()
|
||||
flash(request, "Event types saved.")
|
||||
return redirect("/settings#kinds")
|
||||
|
||||
|
||||
@router.post("/settings/kinds/new")
|
||||
def add_kind(
|
||||
request: Request,
|
||||
db: Db,
|
||||
label: Annotated[str, Form()],
|
||||
category: Annotated[str, Form()],
|
||||
emoji: Annotated[str, Form()] = "",
|
||||
mode: Annotated[str, Form()] = "instant",
|
||||
) -> RedirectResponse:
|
||||
label = label.strip()[:40]
|
||||
slug = re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_")[:32] or "custom"
|
||||
base, n = slug, 2
|
||||
while db.get(Kind, slug) is not None:
|
||||
slug, n = f"{base[:29]}_{n}", n + 1
|
||||
max_order = db.scalar(select(func.max(Kind.sort_order))) or 0
|
||||
db.add(
|
||||
Kind(
|
||||
slug=slug,
|
||||
label=label or "Custom",
|
||||
short=label[:10] or "Custom",
|
||||
emoji=emoji.strip()[:8],
|
||||
category=category if category in CATEGORIES else "other",
|
||||
mode="duration" if mode == "duration" else "instant",
|
||||
max_minutes=180 if mode == "duration" else None,
|
||||
sort_order=max_order + 10,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
flash(request, f"Added {label}. Assign it to a button above if you like.")
|
||||
return redirect("/settings#kinds")
|
||||
@@ -0,0 +1,243 @@
|
||||
"""JSON API for the dashboard's data, for scripts, a future phone app, or a
|
||||
Google Sheets sync. Uses the same login as the website."""
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import ButtonMap, Device, DeviceReport, Event, Kind, Press
|
||||
from ..schemas import DayOut, EventCreate, EventOut, EventUpdate, KindOut
|
||||
from ..services import events as ev_svc
|
||||
from ..services.catalog import all_kinds, get_profile
|
||||
from ..services.stats import daily_stats
|
||||
from ..timeutil import local_today, safe_zone, unix, utcnow
|
||||
from ..web import require_api_login
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["dashboard"], dependencies=[Depends(require_api_login)])
|
||||
|
||||
Db = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def event_out(ev: Event) -> EventOut:
|
||||
dur = ev.duration
|
||||
return EventOut(
|
||||
id=ev.id,
|
||||
kind=ev.kind_slug,
|
||||
label=ev.kind.label,
|
||||
emoji=ev.kind.emoji,
|
||||
category=ev.kind.category,
|
||||
started_at=ev.started_at,
|
||||
ended_at=ev.ended_at,
|
||||
duration_s=int(dur.total_seconds()) if dur is not None else None,
|
||||
note=ev.note,
|
||||
source=ev.source,
|
||||
device_id=ev.device_id,
|
||||
button=ev.button,
|
||||
clock_corrected=ev.clock_corrected,
|
||||
deleted=ev.deleted_at is not None,
|
||||
)
|
||||
|
||||
|
||||
def _aware(dt: datetime | None) -> datetime | None:
|
||||
if dt is not None and dt.tzinfo is None:
|
||||
raise HTTPException(422, "Datetimes need a timezone, e.g. 2026-10-16T13:05:00-04:00 or ...Z")
|
||||
return dt
|
||||
|
||||
|
||||
def _kind(db: Session, slug: str) -> Kind:
|
||||
kind = db.get(Kind, slug)
|
||||
if kind is None:
|
||||
raise HTTPException(422, f"Unknown kind {slug!r}. See GET /api/v1/kinds.")
|
||||
return kind
|
||||
|
||||
|
||||
def _event(db: Session, event_id: int) -> Event:
|
||||
ev = db.get(Event, event_id)
|
||||
if ev is None:
|
||||
raise HTTPException(404, "No such event.")
|
||||
return ev
|
||||
|
||||
|
||||
@router.get("/kinds", response_model=list[KindOut])
|
||||
def list_kinds(db: Db) -> list[Kind]:
|
||||
return all_kinds(db)
|
||||
|
||||
|
||||
@router.get("/events", response_model=list[EventOut])
|
||||
def list_events(
|
||||
db: Db,
|
||||
since: Annotated[datetime | None, Query(description="Only events at or after this time.")] = None,
|
||||
until: Annotated[datetime | None, Query(description="Only events before this time.")] = None,
|
||||
category: Annotated[str | None, Query(description="sleep, feeding, diaper, ...")] = None,
|
||||
kind: Annotated[str | None, Query()] = None,
|
||||
limit: Annotated[int, Query(ge=1, le=5000)] = 200,
|
||||
) -> list[EventOut]:
|
||||
"""Newest first."""
|
||||
evs = ev_svc.search_events(
|
||||
db,
|
||||
after=_aware(since),
|
||||
before=_aware(until),
|
||||
categories={category} if category else None,
|
||||
kinds={kind} if kind else None,
|
||||
limit=limit,
|
||||
)
|
||||
return [event_out(e) for e in evs]
|
||||
|
||||
|
||||
@router.post("/events", response_model=EventOut, status_code=201)
|
||||
def create_event(body: EventCreate, db: Db) -> EventOut:
|
||||
kind = _kind(db, body.kind)
|
||||
started = _aware(body.started_at) or utcnow()
|
||||
try:
|
||||
if body.ended_at is None and body.started_at is None:
|
||||
# "Log it now" behaves like a button press: ends an open session.
|
||||
ev, _ = ev_svc.apply_press(db, kind, started, source="manual", note=body.note)
|
||||
db.commit()
|
||||
else:
|
||||
ev = ev_svc.create_manual(db, kind, started, _aware(body.ended_at), body.note)
|
||||
except ev_svc.EventError as e:
|
||||
raise HTTPException(422, str(e)) from None
|
||||
return event_out(ev)
|
||||
|
||||
|
||||
@router.patch("/events/{event_id}", response_model=EventOut)
|
||||
def update_event(event_id: int, body: EventUpdate, db: Db) -> EventOut:
|
||||
ev = _event(db, event_id)
|
||||
kind = _kind(db, body.kind) if body.kind else ev.kind
|
||||
ended = None if body.clear_end else (_aware(body.ended_at) or ev.ended_at)
|
||||
try:
|
||||
ev_svc.update_event(
|
||||
db,
|
||||
ev,
|
||||
kind=kind,
|
||||
started_at=_aware(body.started_at) or ev.started_at,
|
||||
ended_at=ended,
|
||||
note=body.note if body.note is not None else ev.note,
|
||||
)
|
||||
except ev_svc.EventError as e:
|
||||
raise HTTPException(422, str(e)) from None
|
||||
return event_out(ev)
|
||||
|
||||
|
||||
@router.delete("/events/{event_id}", status_code=204)
|
||||
def delete_event(event_id: int, db: Db) -> None:
|
||||
ev_svc.delete_event(db, _event(db, event_id))
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/restore", response_model=EventOut)
|
||||
def restore_event(event_id: int, db: Db) -> EventOut:
|
||||
ev = _event(db, event_id)
|
||||
ev_svc.restore_event(db, ev)
|
||||
return event_out(ev)
|
||||
|
||||
|
||||
@router.get("/stats/daily", response_model=list[DayOut])
|
||||
def stats_daily(db: Db, days: Annotated[int, Query(ge=1, le=366)] = 14) -> list[DayOut]:
|
||||
"""Per-day totals in the family's timezone, oldest first, today last."""
|
||||
tz = safe_zone(get_profile(db).timezone)
|
||||
today = local_today(tz)
|
||||
return [
|
||||
DayOut(
|
||||
date=d.day.isoformat(),
|
||||
feeds=d.feeds,
|
||||
wet=d.wet,
|
||||
dirty=d.dirty,
|
||||
pump=d.pump,
|
||||
sleep_min=round(d.sleep_min),
|
||||
longest_sleep_min=round(d.longest_sleep_min),
|
||||
counts=dict(d.counts),
|
||||
)
|
||||
for d in daily_stats(db, tz, today - timedelta(days=days - 1), today)
|
||||
]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ export / backup
|
||||
|
||||
|
||||
@router.get("/export.csv", tags=["export"])
|
||||
def export_csv(db: Db) -> StreamingResponse:
|
||||
"""Every event as a spreadsheet (opens in Excel, Numbers or Google Sheets)."""
|
||||
profile = get_profile(db)
|
||||
tz = safe_zone(profile.timezone)
|
||||
buf = io.StringIO()
|
||||
w = csv.writer(buf)
|
||||
w.writerow(
|
||||
["id", "date", "start", "end", "duration_min", "type", "category", "note", "source",
|
||||
"button", "start_utc", "end_utc"]
|
||||
)
|
||||
rows = db.scalars(select(Event).where(ev_svc.live()).order_by(Event.started_at))
|
||||
for ev in rows:
|
||||
s = ev.started_at.astimezone(tz)
|
||||
e = ev.ended_at.astimezone(tz) if ev.ended_at else None
|
||||
w.writerow([
|
||||
ev.id,
|
||||
s.date().isoformat(),
|
||||
s.strftime("%H:%M"),
|
||||
e.strftime("%H:%M") if e else "",
|
||||
round(ev.duration.total_seconds() / 60) if ev.duration is not None else "",
|
||||
ev.kind.label,
|
||||
ev.kind.category,
|
||||
ev.note or "",
|
||||
ev.source,
|
||||
ev.button or "",
|
||||
ev.started_at.isoformat(),
|
||||
ev.ended_at.isoformat() if ev.ended_at else "",
|
||||
])
|
||||
name = f"mamadachi-{profile.baby_name.lower().replace(' ', '-')}-{local_today(tz).isoformat()}.csv"
|
||||
return StreamingResponse(
|
||||
iter([buf.getvalue()]),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{name}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/export.json", tags=["export"])
|
||||
def export_json(db: Db) -> JSONResponse:
|
||||
"""A full backup of every table (minus device token hashes)."""
|
||||
def dt(v: datetime | None) -> str | None:
|
||||
return v.astimezone(timezone.utc).isoformat() if v else None
|
||||
|
||||
profile = get_profile(db)
|
||||
data = {
|
||||
"exported_at": dt(utcnow()),
|
||||
"format": "mamadachi-backup-1",
|
||||
"profile": {
|
||||
"baby_name": profile.baby_name,
|
||||
"birth_date": profile.birth_date.isoformat() if profile.birth_date else None,
|
||||
"timezone": profile.timezone,
|
||||
"clock_24h": profile.clock_24h,
|
||||
"sync_interval_min": profile.sync_interval_min,
|
||||
},
|
||||
"kinds": [KindOut.model_validate(k).model_dump() for k in all_kinds(db)],
|
||||
"buttons": [{"button": b.button, "kind": b.kind_slug} for b in db.scalars(select(ButtonMap))],
|
||||
"devices": [
|
||||
{"id": d.id, "name": d.name, "created_at": dt(d.created_at), "revoked_at": dt(d.revoked_at),
|
||||
"last_seen_at": dt(d.last_seen_at), "firmware": d.firmware}
|
||||
for d in db.scalars(select(Device))
|
||||
],
|
||||
"events": [
|
||||
event_out(e).model_dump(mode="json")
|
||||
for e in db.scalars(select(Event).order_by(Event.started_at))
|
||||
],
|
||||
"presses": [
|
||||
{"device_id": p.device_id, "seq": p.seq, "button": p.button, "device_time": unix(p.device_time),
|
||||
"occurred_at": dt(p.occurred_at), "received_at": dt(p.received_at), "role": p.role,
|
||||
"event_id": p.event_id}
|
||||
for p in db.scalars(select(Press).order_by(Press.id))
|
||||
],
|
||||
"device_reports": [
|
||||
{"device_id": r.device_id, "received_at": dt(r.received_at), "battery_mv": r.battery_mv,
|
||||
"charging": r.charging, "rssi": r.rssi, "clock_skew_s": r.clock_skew_s, "firmware": r.firmware,
|
||||
"events_received": r.events_received, "events_new": r.events_new, "extra": r.extra}
|
||||
for r in db.scalars(select(DeviceReport).order_by(DeviceReport.id))
|
||||
],
|
||||
}
|
||||
name = f"mamadachi-backup-{local_today(safe_zone(profile.timezone)).isoformat()}.json"
|
||||
return JSONResponse(data, headers={"Content-Disposition": f'attachment; filename="{name}"'})
|
||||
@@ -0,0 +1,49 @@
|
||||
"""The single shared dashboard password. Not user accounts: see README for
|
||||
what to add before more than one family uses this."""
|
||||
|
||||
import secrets
|
||||
import time
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import get_db
|
||||
from ..web import redirect, render
|
||||
|
||||
router = APIRouter(include_in_schema=False)
|
||||
|
||||
|
||||
def _safe_next(url: str | None) -> str:
|
||||
return url if url and url.startswith("/") and not url.startswith("//") else "/"
|
||||
|
||||
|
||||
@router.get("/login", response_class=HTMLResponse)
|
||||
def login_form(request: Request, db: Annotated[Session, Depends(get_db)], next: str = "/") -> Response:
|
||||
if not get_settings().login_required:
|
||||
return redirect("/")
|
||||
return render(request, db, "login.html", next=_safe_next(next), error=None)
|
||||
|
||||
|
||||
@router.post("/login", response_class=HTMLResponse)
|
||||
def login(
|
||||
request: Request,
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
password: Annotated[str, Form()],
|
||||
next: Annotated[str, Form()] = "/",
|
||||
) -> Response:
|
||||
expected = get_settings().dashboard_password
|
||||
if expected and secrets.compare_digest(password.encode(), expected.encode()):
|
||||
request.session.clear()
|
||||
request.session["auth"] = True
|
||||
return redirect(_safe_next(next))
|
||||
time.sleep(1) # slows down password guessing
|
||||
return render(request, db, "login.html", status_code=401, next=_safe_next(next), error="That's not the password.")
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(request: Request) -> RedirectResponse:
|
||||
request.session.clear()
|
||||
return redirect("/login")
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The API the Mamadachi itself talks to. One endpoint, one round trip per wake:
|
||||
upload queued presses + telemetry, get back the button layout and what to draw."""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import Device
|
||||
from ..schemas import SyncRequest, SyncResponse
|
||||
from ..services.ingest import IngestResult, device_for_token, ingest, sync_response
|
||||
|
||||
router = APIRouter(prefix="/api/v1/device", tags=["device"])
|
||||
|
||||
|
||||
def current_device(
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
authorization: Annotated[str | None, Header(description="Bearer mmd_...")] = None,
|
||||
) -> Device:
|
||||
token = ""
|
||||
if authorization and authorization.lower().startswith("bearer "):
|
||||
token = authorization[7:].strip()
|
||||
device = device_for_token(db, token)
|
||||
if device is None:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Unknown or revoked device token.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return device
|
||||
|
||||
|
||||
@router.post("/sync", response_model=SyncResponse)
|
||||
def sync(
|
||||
req: SyncRequest,
|
||||
device: Annotated[Device, Depends(current_device)],
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
) -> SyncResponse:
|
||||
"""Upload presses and telemetry; receive config and display status.
|
||||
|
||||
**200** = every event in `events` is stored (new or already known): delete
|
||||
them from the device. Any other status: keep them and retry with backoff.
|
||||
Send at most 500 events per request; if more are queued, sync again
|
||||
straight away (`queue_len` tells the server more are coming).
|
||||
"""
|
||||
try:
|
||||
result = ingest(db, device, req)
|
||||
except IntegrityError:
|
||||
# Two uploads of the same batch raced each other. Nothing is lost:
|
||||
# the device gets a 409, keeps the batch, and the retry is a no-op.
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=409, detail="Concurrent upload, retry.") from None
|
||||
return sync_response(db, result)
|
||||
|
||||
|
||||
@router.get("/config", response_model=SyncResponse)
|
||||
def config(
|
||||
device: Annotated[Device, Depends(current_device)],
|
||||
db: Annotated[Session, Depends(get_db)],
|
||||
) -> SyncResponse:
|
||||
"""Same response as an empty sync, without recording a report. Handy for
|
||||
testing the token and the display from a laptop."""
|
||||
return sync_response(db, IngestResult(0, 0, 0, None, False, None))
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Dashboard pages: Today, Log (history + edit), Trends."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from typing import Annotated
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..charts import column_chart
|
||||
from ..db import get_db
|
||||
from ..models import Event, Kind
|
||||
from ..services import events as ev_svc
|
||||
from ..services.catalog import CATEGORIES, all_kinds, button_map, get_profile
|
||||
from ..services.stats import averages, build_summary, daily_stats, feed_intervals, group_feeds, rhythm
|
||||
from ..timeutil import fmt_duration, local_day_bounds, local_today, parse_local_input, utcnow
|
||||
from ..web import flash, formatter, redirect, render, require_login
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_login)], include_in_schema=False)
|
||||
|
||||
Db = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def _safe_next(url: str | None, default: str = "/") -> str:
|
||||
return url if url and url.startswith("/") and not url.startswith("//") else default
|
||||
|
||||
|
||||
def _get_event(db: Session, event_id: int) -> Event:
|
||||
ev = db.get(Event, event_id)
|
||||
if ev is None:
|
||||
raise HTTPException(404, "No such event")
|
||||
return ev
|
||||
|
||||
|
||||
def _get_kind(db: Session, slug: str) -> Kind:
|
||||
kind = db.get(Kind, slug)
|
||||
if kind is None:
|
||||
raise HTTPException(400, "Unknown event type")
|
||||
return kind
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Today
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def today(request: Request, db: Db) -> HTMLResponse:
|
||||
profile = get_profile(db)
|
||||
f = formatter(db)
|
||||
s = build_summary(db, profile)
|
||||
day = local_today(f.tz, s.now)
|
||||
quick = [k for k in all_kinds(db, active_only=True)]
|
||||
on_buttons = {k.slug for k in button_map(db).values() if k}
|
||||
quick.sort(key=lambda k: (k.slug not in on_buttons, k.sort_order))
|
||||
return render(
|
||||
request,
|
||||
db,
|
||||
"today.html",
|
||||
s=s,
|
||||
quick=quick,
|
||||
open_slugs={e.kind_slug for e in s.open},
|
||||
row=rhythm(db, f.tz, f, day, day, s.now)[0],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/quick")
|
||||
def quick_log(request: Request, db: Db, kind: Annotated[str, Form()], next: Annotated[str, Form()] = "/") -> RedirectResponse:
|
||||
"""One tap = one button press, same rules as the device."""
|
||||
k = _get_kind(db, kind)
|
||||
f = formatter(db)
|
||||
ev, role = ev_svc.apply_press(db, k, utcnow(), source="manual")
|
||||
db.commit()
|
||||
if role == "end":
|
||||
flash(request, f"{k.emoji} {k.label} ended · {fmt_duration(ev.duration.total_seconds())}")
|
||||
elif role == "start":
|
||||
flash(request, f"{k.emoji} {k.label} started at {f.time(ev.started_at)}", undo=f"/events/{ev.id}/delete")
|
||||
else:
|
||||
flash(request, f"{k.emoji} {k.label} logged at {f.time(ev.started_at)}", undo=f"/events/{ev.id}/delete")
|
||||
return redirect(_safe_next(next))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Log
|
||||
|
||||
|
||||
DAYS_PER_PAGE = 7
|
||||
|
||||
|
||||
@router.get("/log", response_class=HTMLResponse)
|
||||
def log(request: Request, db: Db, before: str | None = None, cat: str | None = None) -> HTMLResponse:
|
||||
f = formatter(db)
|
||||
today_d = local_today(f.tz)
|
||||
try:
|
||||
last_day = min(date.fromisoformat(before), today_d) if before else today_d
|
||||
except ValueError:
|
||||
last_day = today_d
|
||||
first_day = last_day - timedelta(days=DAYS_PER_PAGE - 1)
|
||||
start, _ = local_day_bounds(first_day, f.tz)
|
||||
_, end = local_day_bounds(last_day, f.tz)
|
||||
cats = {cat} if cat in CATEGORIES else None
|
||||
events = [e for e in ev_svc.events_between(db, start, end, categories=cats) if e.started_at >= start]
|
||||
|
||||
by_day: dict[date, list[Event]] = {}
|
||||
for ev in reversed(events):
|
||||
by_day.setdefault(f.local(ev.started_at).date(), []).append(ev)
|
||||
stats = {d.day: d for d in daily_stats(db, f.tz, first_day, last_day)}
|
||||
days = [(d, by_day.get(d, []), stats[d]) for d in sorted(stats, reverse=True)]
|
||||
|
||||
return render(
|
||||
request,
|
||||
db,
|
||||
"log.html",
|
||||
days=days,
|
||||
cat=cat if cats else None,
|
||||
kinds=all_kinds(db, active_only=True),
|
||||
newer=(last_day + timedelta(days=DAYS_PER_PAGE)).isoformat() if last_day < today_d else None,
|
||||
older=(first_day - timedelta(days=1)).isoformat(),
|
||||
default_start=f.input_value(utcnow()),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/events")
|
||||
def create_event(
|
||||
request: Request,
|
||||
db: Db,
|
||||
kind: Annotated[str, Form()],
|
||||
started_at: Annotated[str, Form()],
|
||||
ended_at: Annotated[str, Form()] = "",
|
||||
note: Annotated[str, Form()] = "",
|
||||
) -> RedirectResponse:
|
||||
k = _get_kind(db, kind)
|
||||
f = formatter(db)
|
||||
try:
|
||||
start = parse_local_input(started_at, f.tz) or utcnow()
|
||||
end = parse_local_input(ended_at, f.tz) if k.is_duration else None
|
||||
ev = ev_svc.create_manual(db, k, start, end, note.strip())
|
||||
except (ev_svc.EventError, ValueError) as e:
|
||||
flash(request, str(e), level="error")
|
||||
return redirect("/log")
|
||||
flash(request, f"{k.emoji} {k.label} added for {f.when(ev.started_at)}", undo=f"/events/{ev.id}/delete")
|
||||
return redirect("/log")
|
||||
|
||||
|
||||
@router.get("/events/{event_id}", response_class=HTMLResponse)
|
||||
def edit_event(request: Request, db: Db, event_id: int) -> HTMLResponse:
|
||||
ev = _get_event(db, event_id)
|
||||
return render(request, db, "event_edit.html", ev=ev, kinds=all_kinds(db))
|
||||
|
||||
|
||||
@router.post("/events/{event_id}")
|
||||
def save_event(
|
||||
request: Request,
|
||||
db: Db,
|
||||
event_id: int,
|
||||
kind: Annotated[str, Form()],
|
||||
started_at: Annotated[str, Form()],
|
||||
ended_at: Annotated[str, Form()] = "",
|
||||
note: Annotated[str, Form()] = "",
|
||||
) -> RedirectResponse:
|
||||
ev = _get_event(db, event_id)
|
||||
k = _get_kind(db, kind)
|
||||
f = formatter(db)
|
||||
try:
|
||||
start = parse_local_input(started_at, f.tz)
|
||||
if start is None:
|
||||
raise ev_svc.EventError("A start time is needed.")
|
||||
ev_svc.update_event(db, ev, kind=k, started_at=start, ended_at=parse_local_input(ended_at, f.tz), note=note.strip())
|
||||
except (ev_svc.EventError, ValueError) as e:
|
||||
flash(request, str(e), level="error")
|
||||
return redirect(f"/events/{event_id}")
|
||||
flash(request, "Saved.")
|
||||
return redirect(f"/log?before={f.local(ev.started_at).date().isoformat()}")
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/end")
|
||||
def end_event(request: Request, db: Db, event_id: int, next: Annotated[str, Form()] = "/") -> RedirectResponse:
|
||||
ev = _get_event(db, event_id)
|
||||
try:
|
||||
ev_svc.end_session(db, ev)
|
||||
flash(request, f"{ev.kind.emoji} {ev.kind.label} ended · {fmt_duration(ev.duration.total_seconds())}")
|
||||
except ev_svc.EventError as e:
|
||||
flash(request, str(e), level="error")
|
||||
return redirect(_safe_next(next))
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/delete")
|
||||
def delete_event(request: Request, db: Db, event_id: int) -> RedirectResponse:
|
||||
ev = _get_event(db, event_id)
|
||||
ev_svc.delete_event(db, ev)
|
||||
flash(request, f"Deleted {ev.kind.label}.", undo=f"/events/{ev.id}/restore")
|
||||
return redirect(_back(request, event_id, "/log"))
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/restore")
|
||||
def restore_event(request: Request, db: Db, event_id: int) -> RedirectResponse:
|
||||
ev = _get_event(db, event_id)
|
||||
ev_svc.restore_event(db, ev)
|
||||
flash(request, f"Restored {ev.kind.label}.")
|
||||
return redirect(_back(request, event_id, "/log"))
|
||||
|
||||
|
||||
def _back(request: Request, event_id: int, fallback: str) -> str:
|
||||
"""The page the button was on, unless that's the event's own edit page."""
|
||||
parts = urlsplit(request.headers.get("referer", ""))
|
||||
path = parts.path + (f"?{parts.query}" if parts.query else "")
|
||||
if not path.startswith("/") or path.startswith("//") or path.startswith(f"/events/{event_id}"):
|
||||
return fallback
|
||||
return path
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Trends
|
||||
|
||||
|
||||
RANGES = (7, 14, 30)
|
||||
|
||||
|
||||
@router.get("/trends", response_class=HTMLResponse)
|
||||
def trends(request: Request, db: Db, days: int = 14) -> HTMLResponse:
|
||||
days = days if days in RANGES else 14
|
||||
f = formatter(db)
|
||||
now = utcnow()
|
||||
last = local_today(f.tz, now)
|
||||
first = last - timedelta(days=days - 1)
|
||||
stats = daily_stats(db, f.tz, first, last, now)
|
||||
avg = averages(stats[:-1] or stats) # today is still in progress
|
||||
start, _ = local_day_bounds(first, f.tz)
|
||||
feeds = group_feeds(ev_svc.events_between(db, start, now, categories={"feeding"}))
|
||||
intervals = feed_intervals(feeds)
|
||||
|
||||
def fmt_count(v: float) -> str:
|
||||
return f"{v:g}"
|
||||
|
||||
def fmt_hours(v: float) -> str:
|
||||
return f"{v:.1f} h"
|
||||
|
||||
def avg_text(key: str, fmt) -> str: # noqa: ANN001
|
||||
v = avg.get(key)
|
||||
return f"Average {fmt(v)} a day" if v is not None else "No data yet"
|
||||
|
||||
charts = [
|
||||
column_chart("feeds", "Feeds per day", "feeding", stats, lambda d: d.feeds, fmt_count, f,
|
||||
summary=avg_text("feeds", lambda v: f"{v:.1f}")),
|
||||
column_chart("sleep", "Sleep per day", "sleep", stats, lambda d: round(d.sleep_h, 1), fmt_hours, f,
|
||||
integer=False, summary=avg_text("sleep_min", lambda v: fmt_duration(v * 60))),
|
||||
column_chart("wet", "Wet diapers per day", "diaper", stats, lambda d: d.wet, fmt_count, f,
|
||||
summary=avg_text("wet", lambda v: f"{v:.1f}")),
|
||||
column_chart("dirty", "Dirty diapers per day", "diaper", stats, lambda d: d.dirty, fmt_count, f,
|
||||
summary=avg_text("dirty", lambda v: f"{v:.1f}")),
|
||||
]
|
||||
longest = max(stats, key=lambda d: d.longest_sleep_min, default=None)
|
||||
return render(
|
||||
request,
|
||||
db,
|
||||
"trends.html",
|
||||
days=days,
|
||||
ranges=RANGES,
|
||||
stats=list(reversed(stats)),
|
||||
charts=charts,
|
||||
rows=rhythm(db, f.tz, f, first, last, now),
|
||||
avg=avg,
|
||||
median_interval=sorted(intervals)[len(intervals) // 2] if intervals else None,
|
||||
longest=longest if longest and longest.longest_sleep_min > 0 else None,
|
||||
)
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
"""Request and response shapes for the JSON APIs. FastAPI validates incoming
|
||||
JSON against these and documents them at /docs."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
MAX_EVENTS_PER_SYNC = 500
|
||||
UNIX_2100 = 4_102_444_800
|
||||
|
||||
# ------------------------------------------------------------------ device API
|
||||
|
||||
|
||||
class DeviceEventIn(BaseModel):
|
||||
seq: int = Field(ge=0, le=2**31 - 1, description="Per-device counter, +1 for every press. Kept in NVS.")
|
||||
time: int = Field(ge=0, le=UNIX_2100, description="When pressed: UNIX seconds (UTC) from the RTC.")
|
||||
button: int = Field(ge=0, le=255, description="Button number, 1-8.")
|
||||
|
||||
|
||||
class SyncRequest(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"example": {
|
||||
"device_time": 1760630400,
|
||||
"firmware": "0.1.0",
|
||||
"battery_mv": 3987,
|
||||
"charging": False,
|
||||
"rssi": -61,
|
||||
"boot_count": 42,
|
||||
"queue_len": 0,
|
||||
"events": [
|
||||
{"seq": 101, "time": 1760620000, "button": 6},
|
||||
{"seq": 102, "time": 1760627000, "button": 6},
|
||||
{"seq": 103, "time": 1760627100, "button": 4},
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
device_time: int | None = Field(
|
||||
None, ge=0, le=UNIX_2100, description="The RTC's current time (UNIX s, UTC), read just before sending."
|
||||
)
|
||||
firmware: str | None = Field(None, max_length=32)
|
||||
battery_mv: int | None = Field(None, ge=0, le=10_000, description="Cell voltage in millivolts.")
|
||||
charging: bool | None = Field(None, description="USB power present (MCP23017 GPB1).")
|
||||
rssi: int | None = Field(None, ge=-127, le=0, description="Wi-Fi signal, dBm.")
|
||||
boot_count: int | None = Field(None, ge=0)
|
||||
queue_len: int | None = Field(None, ge=0, description="Presses still waiting on the device after this batch.")
|
||||
events: list[DeviceEventIn] = Field(default_factory=list, max_length=MAX_EVENTS_PER_SYNC)
|
||||
diag: dict[str, Any] | None = Field(None, description="Anything else worth logging. Stored as-is, max 2 kB.")
|
||||
|
||||
@field_validator("diag")
|
||||
@classmethod
|
||||
def _small_diag(cls, v: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if v is not None and len(json.dumps(v)) > 2048:
|
||||
raise ValueError("diag is larger than 2 kB")
|
||||
return v
|
||||
|
||||
|
||||
class ButtonOut(BaseModel):
|
||||
button: int
|
||||
kind: str | None
|
||||
label: str
|
||||
short: str
|
||||
emoji: str
|
||||
mode: Literal["instant", "duration"]
|
||||
|
||||
|
||||
class LastOut(BaseModel):
|
||||
kind: str
|
||||
short: str
|
||||
time: int
|
||||
|
||||
|
||||
class OpenOut(BaseModel):
|
||||
kind: str
|
||||
short: str
|
||||
since: int
|
||||
|
||||
|
||||
class TodayOut(BaseModel):
|
||||
feeds: int
|
||||
wet: int
|
||||
dirty: int
|
||||
sleep_min: int
|
||||
|
||||
|
||||
class DisplayStatus(BaseModel):
|
||||
"""Everything the e-paper needs. Times are UNIX seconds; the device turns
|
||||
them into "2h 10m ago" with its own clock, so the text stays right between syncs."""
|
||||
|
||||
baby_name: str
|
||||
last_feed: LastOut | None
|
||||
next_side: Literal["L", "R"] | None
|
||||
last_diaper: LastOut | None
|
||||
open: list[OpenOut]
|
||||
today: TodayOut
|
||||
|
||||
|
||||
class SyncResponse(BaseModel):
|
||||
ok: bool = True
|
||||
server_time: int = Field(description="UNIX seconds (UTC). Set the RTC from this if it's off.")
|
||||
ack_seq: int | None = Field(
|
||||
description="Highest seq in this batch. Everything you sent is stored: delete it from the queue."
|
||||
)
|
||||
received: int
|
||||
stored: int
|
||||
duplicates: int
|
||||
clock_skew_s: int | None = Field(description="Server time minus device_time. Positive = device is behind.")
|
||||
clock_corrected: bool = Field(description="True if event times in this batch were shifted by clock_skew_s.")
|
||||
tz_offset_s: int = Field(description="Family's current UTC offset, for showing local time on the display.")
|
||||
sync_interval_s: int = Field(description="How long to wait before the next routine sync.")
|
||||
config_version: str = Field(description="Changes whenever the button layout changes.")
|
||||
buttons: list[ButtonOut]
|
||||
status: DisplayStatus
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ dashboard API
|
||||
|
||||
|
||||
class KindOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
slug: str
|
||||
label: str
|
||||
short: str
|
||||
emoji: str
|
||||
category: str
|
||||
mode: str
|
||||
max_minutes: int | None
|
||||
active: bool
|
||||
|
||||
|
||||
class EventOut(BaseModel):
|
||||
id: int
|
||||
kind: str
|
||||
label: str
|
||||
emoji: str
|
||||
category: str
|
||||
started_at: datetime
|
||||
ended_at: datetime | None
|
||||
duration_s: int | None
|
||||
note: str | None
|
||||
source: str
|
||||
device_id: int | None
|
||||
button: int | None
|
||||
clock_corrected: bool
|
||||
deleted: bool
|
||||
|
||||
|
||||
class EventCreate(BaseModel):
|
||||
kind: str
|
||||
started_at: datetime | None = Field(None, description="Defaults to now. Include a timezone offset.")
|
||||
ended_at: datetime | None = None
|
||||
note: str | None = Field(None, max_length=2000)
|
||||
|
||||
|
||||
class EventUpdate(BaseModel):
|
||||
kind: str | None = None
|
||||
started_at: datetime | None = None
|
||||
ended_at: datetime | None = None
|
||||
clear_end: bool = Field(False, description="Set true to reopen a session (remove its end time).")
|
||||
note: str | None = Field(None, max_length=2000)
|
||||
|
||||
|
||||
class DayOut(BaseModel):
|
||||
date: str
|
||||
feeds: int
|
||||
wet: int
|
||||
dirty: int
|
||||
pump: int
|
||||
sleep_min: int
|
||||
longest_sleep_min: int
|
||||
counts: dict[str, int]
|
||||
Whitespace-only changes.
@@ -0,0 +1,114 @@
|
||||
"""Built-in event kinds, the default button layout, and first-run setup."""
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import ButtonMap, Kind, Profile
|
||||
|
||||
NUM_BUTTONS = 8
|
||||
|
||||
# Category order is fixed: it decides each category's chart colour (series-1..7
|
||||
# in style.css). Sleep, feeding and diaper take the first three slots because
|
||||
# they share the rhythm chart, and those three stay distinguishable for
|
||||
# colour-blind readers.
|
||||
CATEGORIES: dict[str, str] = {
|
||||
"sleep": "Sleep",
|
||||
"feeding": "Feeding",
|
||||
"diaper": "Diapers",
|
||||
"pump": "Pumping",
|
||||
"health": "Health",
|
||||
"activity": "Activity",
|
||||
"other": "Other",
|
||||
}
|
||||
|
||||
DEFAULT_KINDS: list[dict] = [
|
||||
dict(slug="nurse_left", label="Nursing (left)", short="Nurse L", emoji="🤱", category="feeding"),
|
||||
dict(slug="nurse_right", label="Nursing (right)", short="Nurse R", emoji="🤱", category="feeding"),
|
||||
dict(slug="bottle", label="Bottle", short="Bottle", emoji="🍼", category="feeding"),
|
||||
dict(slug="solids", label="Solids", short="Solids", emoji="🥣", category="feeding"),
|
||||
dict(slug="wet", label="Wet diaper", short="Wet", emoji="💧", category="diaper"),
|
||||
dict(slug="dirty", label="Dirty diaper", short="Dirty", emoji="💩", category="diaper"),
|
||||
dict(slug="sleep", label="Sleep", short="Sleep", emoji="😴", category="sleep",
|
||||
mode="duration", max_minutes=12 * 60),
|
||||
dict(slug="pump", label="Pumping", short="Pump", emoji="🥛", category="pump"),
|
||||
dict(slug="medicine", label="Medicine", short="Meds", emoji="💊", category="health"),
|
||||
dict(slug="tummy_time", label="Tummy time", short="Tummy", emoji="🧸", category="activity",
|
||||
mode="duration", max_minutes=60),
|
||||
dict(slug="bath", label="Bath", short="Bath", emoji="🛁", category="activity"),
|
||||
dict(slug="other", label="Other", short="Other", emoji="📝", category="other"),
|
||||
]
|
||||
|
||||
# Button 1..8 on the board (SW1..SW8 = MCP23017 GPA0..GPA6, GPB0).
|
||||
DEFAULT_BUTTONS = ["nurse_left", "nurse_right", "bottle", "wet", "dirty", "sleep", "pump", "medicine"]
|
||||
|
||||
FALLBACK_KIND = "other" # presses from unassigned buttons land here
|
||||
|
||||
# Kinds the "next side" suggestion looks at.
|
||||
NURSE_SIDES = {"nurse_left": "L", "nurse_right": "R"}
|
||||
|
||||
|
||||
def ensure_defaults(db: Session) -> None:
|
||||
"""Create the profile row, built-in kinds and button layout if missing.
|
||||
|
||||
Safe to run on every start: it only adds what isn't there and never
|
||||
overwrites the parent's edits.
|
||||
"""
|
||||
if db.get(Profile, 1) is None:
|
||||
db.add(Profile(id=1, timezone=get_settings().default_timezone))
|
||||
|
||||
existing = set(db.scalars(select(Kind.slug)))
|
||||
for order, spec in enumerate(DEFAULT_KINDS):
|
||||
if spec["slug"] not in existing:
|
||||
db.add(Kind(**{"mode": "instant", "max_minutes": None, "sort_order": order * 10, **spec}))
|
||||
db.flush()
|
||||
|
||||
have_buttons = set(db.scalars(select(ButtonMap.button)))
|
||||
for n, slug in enumerate(DEFAULT_BUTTONS, start=1):
|
||||
if n not in have_buttons:
|
||||
db.add(ButtonMap(button=n, kind_slug=slug))
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_profile(db: Session) -> Profile:
|
||||
profile = db.get(Profile, 1)
|
||||
if profile is None:
|
||||
ensure_defaults(db)
|
||||
profile = db.get(Profile, 1)
|
||||
return profile
|
||||
|
||||
|
||||
def all_kinds(db: Session, *, active_only: bool = False) -> list[Kind]:
|
||||
q = select(Kind).order_by(Kind.sort_order, Kind.label)
|
||||
if active_only:
|
||||
q = q.where(Kind.active.is_(True))
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def button_map(db: Session) -> dict[int, Kind | None]:
|
||||
rows = db.scalars(select(ButtonMap).order_by(ButtonMap.button))
|
||||
mapping: dict[int, Kind | None] = {n: None for n in range(1, NUM_BUTTONS + 1)}
|
||||
for row in rows:
|
||||
mapping[row.button] = row.kind
|
||||
return mapping
|
||||
|
||||
|
||||
# Resting voltage -> charge for a single-cell LiPo. Approximate (the curve
|
||||
# varies with cell, temperature and load), but good enough for a gauge.
|
||||
_LIPO_CURVE = [
|
||||
(4200, 100), (4150, 95), (4110, 90), (4080, 85), (4020, 80), (3980, 75),
|
||||
(3950, 70), (3910, 65), (3870, 60), (3850, 55), (3840, 50), (3820, 45),
|
||||
(3800, 40), (3790, 35), (3770, 30), (3750, 25), (3730, 20), (3710, 15),
|
||||
(3690, 10), (3610, 5), (3270, 0),
|
||||
]
|
||||
|
||||
|
||||
def battery_percent(mv: int | None) -> int | None:
|
||||
if mv is None or mv <= 0:
|
||||
return None
|
||||
if mv >= _LIPO_CURVE[0][0]:
|
||||
return 100
|
||||
for (v_hi, p_hi), (v_lo, p_lo) in zip(_LIPO_CURVE, _LIPO_CURVE[1:]):
|
||||
if v_lo <= mv <= v_hi:
|
||||
return round(p_lo + (p_hi - p_lo) * (mv - v_lo) / (v_hi - v_lo))
|
||||
return 0
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Creating, editing and querying events. Shared by the device API, the JSON
|
||||
API and the dashboard, so a button press and a tap on the website behave the same."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Device, Event, Kind
|
||||
from ..timeutil import utcnow
|
||||
|
||||
# Longest session the queries look back for when a range starts mid-session.
|
||||
LOOKBACK = timedelta(days=1)
|
||||
|
||||
|
||||
def live() -> object:
|
||||
"""WHERE clause for events that haven't been deleted."""
|
||||
return Event.deleted_at.is_(None)
|
||||
|
||||
|
||||
def find_open_session(db: Session, kind: Kind, at: datetime) -> Event | None:
|
||||
"""The unfinished session of `kind` that a press at `at` would end, if any."""
|
||||
q = (
|
||||
select(Event)
|
||||
.where(live(), Event.kind_slug == kind.slug, Event.ended_at.is_(None), Event.started_at <= at)
|
||||
.order_by(Event.started_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
if kind.max_duration:
|
||||
q = q.where(Event.started_at >= at - kind.max_duration)
|
||||
return db.scalars(q).first()
|
||||
|
||||
|
||||
def apply_press(
|
||||
db: Session,
|
||||
kind: Kind,
|
||||
at: datetime,
|
||||
*,
|
||||
source: str,
|
||||
device: Device | None = None,
|
||||
button: int | None = None,
|
||||
note: str | None = None,
|
||||
clock_corrected: bool = False,
|
||||
) -> tuple[Event, str]:
|
||||
"""Record one press of `kind` at `at`. Returns (event, role).
|
||||
|
||||
Instant kinds: a new event (role "instant").
|
||||
Duration kinds: ends the open session if there is one ("end"), otherwise
|
||||
starts a new one ("start").
|
||||
"""
|
||||
if kind.is_duration:
|
||||
open_ev = find_open_session(db, kind, at)
|
||||
if open_ev is not None:
|
||||
open_ev.ended_at = at
|
||||
db.flush()
|
||||
return open_ev, "end"
|
||||
|
||||
ev = Event(
|
||||
kind=kind,
|
||||
started_at=at,
|
||||
source=source,
|
||||
device_id=device.id if device else None,
|
||||
button=button,
|
||||
note=note,
|
||||
clock_corrected=clock_corrected,
|
||||
)
|
||||
db.add(ev)
|
||||
db.flush()
|
||||
return ev, "start" if kind.is_duration else "instant"
|
||||
|
||||
|
||||
def events_between(
|
||||
db: Session,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
*,
|
||||
categories: set[str] | None = None,
|
||||
) -> list[Event]:
|
||||
"""Live events that overlap [start, end), oldest first."""
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Event.started_at < end, Event.started_at >= start - LOOKBACK)
|
||||
.order_by(Event.started_at)
|
||||
)
|
||||
if categories:
|
||||
q = q.where(Kind.category.in_(categories))
|
||||
out = []
|
||||
for ev in db.scalars(q):
|
||||
if ev.started_at >= start or effective_end(ev) > start:
|
||||
out.append(ev)
|
||||
return out
|
||||
|
||||
|
||||
def effective_end(ev: Event, now: datetime | None = None) -> datetime:
|
||||
"""Where to draw/count a session up to. Open sessions run until now, capped
|
||||
at the kind's maximum so a forgotten stop doesn't count as 3 days of sleep."""
|
||||
if ev.ended_at is not None:
|
||||
return ev.ended_at
|
||||
if not ev.kind.is_duration:
|
||||
return ev.started_at
|
||||
end = now or utcnow()
|
||||
if ev.kind.max_duration:
|
||||
end = min(end, ev.started_at + ev.kind.max_duration)
|
||||
return max(end, ev.started_at)
|
||||
|
||||
|
||||
def is_stale(ev: Event, now: datetime | None = None) -> bool:
|
||||
"""An open session that has run past its kind's maximum: probably a forgotten stop."""
|
||||
if not ev.is_open or not ev.kind.max_duration:
|
||||
return False
|
||||
return (now or utcnow()) - ev.started_at > ev.kind.max_duration
|
||||
|
||||
|
||||
def open_sessions(db: Session) -> list[Event]:
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Event.ended_at.is_(None), Kind.mode == "duration")
|
||||
.order_by(Event.started_at.desc())
|
||||
)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def recent_events(db: Session, limit: int = 10) -> list[Event]:
|
||||
q = select(Event).where(live()).order_by(Event.started_at.desc()).limit(limit)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def search_events(
|
||||
db: Session,
|
||||
*,
|
||||
before: datetime | None = None,
|
||||
after: datetime | None = None,
|
||||
categories: set[str] | None = None,
|
||||
kinds: set[str] | None = None,
|
||||
include_deleted: bool = False,
|
||||
limit: int = 200,
|
||||
) -> list[Event]:
|
||||
"""Newest first."""
|
||||
q = select(Event).join(Event.kind).order_by(Event.started_at.desc()).limit(limit)
|
||||
if not include_deleted:
|
||||
q = q.where(live())
|
||||
if before:
|
||||
q = q.where(Event.started_at < before)
|
||||
if after:
|
||||
q = q.where(or_(Event.started_at >= after, Event.ended_at >= after))
|
||||
if categories:
|
||||
q = q.where(Kind.category.in_(categories))
|
||||
if kinds:
|
||||
q = q.where(Event.kind_slug.in_(kinds))
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
class EventError(ValueError):
|
||||
"""Invalid input from a form or the API; the message is shown to the user."""
|
||||
|
||||
|
||||
def validate_times(kind: Kind, started_at: datetime, ended_at: datetime | None) -> None:
|
||||
now = utcnow()
|
||||
if started_at > now + timedelta(minutes=5):
|
||||
raise EventError("That time is in the future.")
|
||||
if ended_at is not None:
|
||||
if not kind.is_duration:
|
||||
raise EventError(f"{kind.label} doesn't have an end time.")
|
||||
if ended_at < started_at:
|
||||
raise EventError("The end is before the start.")
|
||||
if ended_at > now + timedelta(minutes=5):
|
||||
raise EventError("The end time is in the future.")
|
||||
|
||||
|
||||
def create_manual(
|
||||
db: Session, kind: Kind, started_at: datetime, ended_at: datetime | None, note: str | None
|
||||
) -> Event:
|
||||
validate_times(kind, started_at, ended_at)
|
||||
ev = Event(kind=kind, started_at=started_at, ended_at=ended_at, note=note or None, source="manual")
|
||||
db.add(ev)
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def update_event(
|
||||
db: Session,
|
||||
ev: Event,
|
||||
*,
|
||||
kind: Kind,
|
||||
started_at: datetime,
|
||||
ended_at: datetime | None,
|
||||
note: str | None,
|
||||
) -> Event:
|
||||
if not kind.is_duration:
|
||||
ended_at = None
|
||||
validate_times(kind, started_at, ended_at)
|
||||
ev.kind = kind
|
||||
ev.started_at = started_at
|
||||
ev.ended_at = ended_at
|
||||
ev.note = note or None
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def end_session(db: Session, ev: Event, at: datetime | None = None) -> Event:
|
||||
if not ev.is_open:
|
||||
raise EventError("That event is already finished.")
|
||||
ev.ended_at = max(at or utcnow(), ev.started_at)
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def delete_event(db: Session, ev: Event) -> None:
|
||||
ev.deleted_at = utcnow()
|
||||
db.commit()
|
||||
|
||||
|
||||
def restore_event(db: Session, ev: Event) -> None:
|
||||
ev.deleted_at = None
|
||||
db.commit()
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Device sync: store a batch of presses exactly once, turn them into events,
|
||||
and tell the device what to show.
|
||||
|
||||
The contract with the firmware, in one line: **HTTP 200 means every press in
|
||||
the batch is safely stored, so delete them all from the device's queue.**
|
||||
Anything else (timeout, 5xx, no Wi-Fi) means keep them and retry later;
|
||||
retries are harmless because duplicates are recognised and skipped.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Device, DeviceReport, Kind, Press, Profile
|
||||
from ..schemas import (
|
||||
ButtonOut,
|
||||
DisplayStatus,
|
||||
LastOut,
|
||||
OpenOut,
|
||||
SyncRequest,
|
||||
SyncResponse,
|
||||
TodayOut,
|
||||
)
|
||||
from ..timeutil import from_unix, safe_zone, unix, utcnow
|
||||
from .catalog import FALLBACK_KIND, button_map, get_profile
|
||||
from .events import apply_press
|
||||
from .stats import build_summary, is_stale
|
||||
|
||||
log = logging.getLogger("mamadachi.sync")
|
||||
|
||||
# Below this the device clock is "right" (RV-3028 drifts ~1 ppm, a few s/month).
|
||||
CLOCK_TOLERANCE = timedelta(minutes=2)
|
||||
|
||||
TOKEN_PREFIX = "mmd_"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- tokens
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return TOKEN_PREFIX + secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
def create_device(db: Session, name: str) -> tuple[Device, str]:
|
||||
"""Register a device. Returns (device, token); the token is shown once and never stored."""
|
||||
token = new_token()
|
||||
dev = Device(name=name.strip() or "Mamadachi", token_hash=hash_token(token), token_hint=token[-4:])
|
||||
db.add(dev)
|
||||
db.commit()
|
||||
return dev, token
|
||||
|
||||
|
||||
def rotate_token(db: Session, dev: Device) -> str:
|
||||
token = new_token()
|
||||
dev.token_hash = hash_token(token)
|
||||
dev.token_hint = token[-4:]
|
||||
dev.revoked_at = None
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
def device_for_token(db: Session, token: str) -> Device | None:
|
||||
if not token:
|
||||
return None
|
||||
dev = db.scalars(select(Device).where(Device.token_hash == hash_token(token))).first()
|
||||
return dev if dev is not None and dev.active else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- sync
|
||||
|
||||
|
||||
@dataclass
|
||||
class IngestResult:
|
||||
received: int
|
||||
stored: int
|
||||
duplicates: int
|
||||
skew_s: int | None
|
||||
corrected: bool
|
||||
ack_seq: int | None
|
||||
|
||||
|
||||
def ingest(db: Session, device: Device, req: SyncRequest, received_at: datetime | None = None) -> IngestResult:
|
||||
"""Store a sync batch. Commits once at the end, so it's all-or-nothing."""
|
||||
t0 = utcnow()
|
||||
received_at = received_at or t0
|
||||
|
||||
skew = None
|
||||
if req.device_time is not None:
|
||||
skew = round((received_at - from_unix(req.device_time)).total_seconds())
|
||||
corrected = skew is not None and abs(skew) > CLOCK_TOLERANCE.total_seconds()
|
||||
|
||||
# The same press twice in one batch is a firmware bug, but harmless.
|
||||
batch = {(e.seq, e.time): e for e in req.events}
|
||||
existing: set[tuple[int, datetime]] = set()
|
||||
if batch:
|
||||
rows = db.execute(
|
||||
select(Press.seq, Press.device_time).where(
|
||||
Press.device_id == device.id,
|
||||
Press.seq.in_(sorted({seq for seq, _ in batch})),
|
||||
)
|
||||
)
|
||||
existing = {(seq, t) for seq, t in rows}
|
||||
|
||||
buttons = button_map(db)
|
||||
fallback: Kind | None = None
|
||||
new_presses: list[tuple[Press, int]] = []
|
||||
for (seq, t), e in batch.items():
|
||||
device_time = from_unix(t)
|
||||
if (seq, device_time) in existing:
|
||||
continue
|
||||
occurred = device_time + timedelta(seconds=skew) if corrected else device_time
|
||||
press_corrected = corrected
|
||||
if occurred > received_at + CLOCK_TOLERANCE:
|
||||
# A press "in the future" can't be right. Best guess: it just happened.
|
||||
occurred, press_corrected = received_at, True
|
||||
press = Press(
|
||||
device_id=device.id,
|
||||
seq=seq,
|
||||
button=e.button,
|
||||
device_time=device_time,
|
||||
occurred_at=occurred,
|
||||
received_at=received_at,
|
||||
clock_corrected=press_corrected,
|
||||
)
|
||||
new_presses.append((press, e.button))
|
||||
|
||||
# Oldest first, so a sleep start is seen before its stop.
|
||||
new_presses.sort(key=lambda pb: (pb[0].occurred_at, pb[0].seq))
|
||||
for press, button in new_presses:
|
||||
kind = buttons.get(button)
|
||||
note = None
|
||||
if kind is None or not kind.active:
|
||||
if fallback is None:
|
||||
fallback = db.get(Kind, FALLBACK_KIND)
|
||||
note = f"Button {button} has no event type assigned."
|
||||
kind = fallback
|
||||
ev, role = apply_press(
|
||||
db,
|
||||
kind,
|
||||
press.occurred_at,
|
||||
source="device",
|
||||
device=device,
|
||||
button=button,
|
||||
note=note,
|
||||
clock_corrected=press.clock_corrected,
|
||||
)
|
||||
press.role = role
|
||||
press.event_id = ev.id
|
||||
db.add(press)
|
||||
|
||||
device.last_seen_at = received_at
|
||||
device.firmware = req.firmware or device.firmware
|
||||
device.battery_mv = req.battery_mv
|
||||
device.charging = req.charging
|
||||
device.rssi = req.rssi
|
||||
device.clock_skew_s = skew
|
||||
device.boot_count = req.boot_count
|
||||
db.add(
|
||||
DeviceReport(
|
||||
device_id=device.id,
|
||||
received_at=received_at,
|
||||
firmware=req.firmware,
|
||||
battery_mv=req.battery_mv,
|
||||
charging=req.charging,
|
||||
rssi=req.rssi,
|
||||
clock_skew_s=skew,
|
||||
boot_count=req.boot_count,
|
||||
queue_len=req.queue_len,
|
||||
events_received=len(req.events),
|
||||
events_new=len(new_presses),
|
||||
duration_ms=round((utcnow() - t0).total_seconds() * 1000),
|
||||
extra=req.diag,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
result = IngestResult(
|
||||
received=len(req.events),
|
||||
stored=len(new_presses),
|
||||
duplicates=len(req.events) - len(new_presses),
|
||||
skew_s=skew,
|
||||
corrected=corrected,
|
||||
ack_seq=max((e.seq for e in req.events), default=None),
|
||||
)
|
||||
log.info(
|
||||
"sync device=%s received=%d stored=%d dup=%d skew=%ss battery=%smV rssi=%s",
|
||||
device.id, result.received, result.stored, result.duplicates, skew, req.battery_mv, req.rssi,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- response
|
||||
|
||||
|
||||
def config_for_device(db: Session) -> tuple[str, list[ButtonOut]]:
|
||||
buttons = []
|
||||
for n, kind in button_map(db).items():
|
||||
if kind is None or not kind.active:
|
||||
buttons.append(ButtonOut(button=n, kind=None, label="Unassigned", short="-", emoji="", mode="instant"))
|
||||
else:
|
||||
buttons.append(
|
||||
ButtonOut(button=n, kind=kind.slug, label=kind.label, short=kind.short, emoji=kind.emoji, mode=kind.mode)
|
||||
)
|
||||
blob = json.dumps([b.model_dump() for b in buttons], sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha1(blob.encode()).hexdigest()[:8], buttons
|
||||
|
||||
|
||||
def display_status(db: Session, profile: Profile, now: datetime) -> DisplayStatus:
|
||||
s = build_summary(db, profile, now)
|
||||
last_feed = None
|
||||
if s.last_feed:
|
||||
first = s.last_feed.events[0]
|
||||
last_feed = LastOut(kind=first.kind_slug, short=first.kind.short, time=unix(s.last_feed.start))
|
||||
last_diaper = None
|
||||
if s.last_diaper:
|
||||
d = s.last_diaper
|
||||
last_diaper = LastOut(kind=d.kind_slug, short=d.kind.short, time=unix(d.started_at))
|
||||
return DisplayStatus(
|
||||
baby_name=profile.baby_name,
|
||||
last_feed=last_feed,
|
||||
next_side=s.next_side,
|
||||
last_diaper=last_diaper,
|
||||
open=[
|
||||
OpenOut(kind=e.kind_slug, short=e.kind.short, since=unix(e.started_at))
|
||||
for e in s.open
|
||||
if not is_stale(e, now)
|
||||
],
|
||||
today=TodayOut(
|
||||
feeds=s.today.feeds, wet=s.today.wet, dirty=s.today.dirty, sleep_min=round(s.today.sleep_min)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def sync_response(db: Session, result: IngestResult) -> SyncResponse:
|
||||
now = utcnow()
|
||||
profile = get_profile(db)
|
||||
offset = now.astimezone(safe_zone(profile.timezone)).utcoffset()
|
||||
version, buttons = config_for_device(db)
|
||||
return SyncResponse(
|
||||
server_time=unix(now),
|
||||
ack_seq=result.ack_seq,
|
||||
received=result.received,
|
||||
stored=result.stored,
|
||||
duplicates=result.duplicates,
|
||||
clock_skew_s=result.skew_s,
|
||||
clock_corrected=result.corrected,
|
||||
tz_offset_s=int(offset.total_seconds()) if offset else 0,
|
||||
sync_interval_s=profile.sync_interval_min * 60,
|
||||
config_version=version,
|
||||
buttons=buttons,
|
||||
status=display_status(db, profile, now),
|
||||
)
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Turning the event log into answers: when did she last eat, how much did she
|
||||
sleep, what does a typical day look like. All computed in Python from a few
|
||||
hundred rows, so it works the same on SQLite and Postgres."""
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from statistics import mean, median
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import Device, Event, Kind, Profile
|
||||
from ..timeutil import Formatter, fmt_duration, local_day_bounds, local_today, safe_zone, utcnow
|
||||
from .catalog import CATEGORIES, NURSE_SIDES, battery_percent
|
||||
from .events import effective_end, events_between, is_stale, live, open_sessions, recent_events
|
||||
|
||||
# Feeding presses this close together are one feed (left side, then right side).
|
||||
FEED_GAP = timedelta(minutes=30)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- feeds
|
||||
|
||||
|
||||
@dataclass
|
||||
class Feed:
|
||||
events: list[Event]
|
||||
|
||||
@property
|
||||
def start(self) -> datetime:
|
||||
return self.events[0].started_at
|
||||
|
||||
@property
|
||||
def sides(self) -> list[str]:
|
||||
return [NURSE_SIDES[e.kind_slug] for e in self.events if e.kind_slug in NURSE_SIDES]
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
parts: list[str] = []
|
||||
sides = self.sides
|
||||
if sides:
|
||||
parts.append("Nursing " + " → ".join(_dedupe_runs(sides)))
|
||||
for e in self.events:
|
||||
if e.kind_slug not in NURSE_SIDES and e.kind.label not in parts:
|
||||
parts.append(e.kind.label)
|
||||
return " + ".join(parts)
|
||||
|
||||
|
||||
def _dedupe_runs(items: list[str]) -> list[str]:
|
||||
out: list[str] = []
|
||||
for it in items:
|
||||
if not out or out[-1] != it:
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
|
||||
def group_feeds(events: list[Event]) -> list[Feed]:
|
||||
"""Group feeding events into feeds: a new feed starts after a FEED_GAP pause."""
|
||||
feeds: list[Feed] = []
|
||||
last: Event | None = None
|
||||
for ev in sorted((e for e in events if e.kind.category == "feeding"), key=lambda e: e.started_at):
|
||||
if last is None or ev.started_at - last.started_at > FEED_GAP:
|
||||
feeds.append(Feed([ev]))
|
||||
else:
|
||||
feeds[-1].events.append(ev)
|
||||
last = ev
|
||||
return feeds
|
||||
|
||||
|
||||
def next_side(feeds: list[Feed]) -> str | None:
|
||||
"""Suggest the breast to start on: the opposite of the last nursing feed's first side."""
|
||||
for feed in reversed(feeds):
|
||||
if feed.sides:
|
||||
return "R" if feed.sides[0] == "L" else "L"
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- per-day stats
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayStats:
|
||||
day: date
|
||||
feeds: int = 0
|
||||
wet: int = 0
|
||||
dirty: int = 0
|
||||
pump: int = 0
|
||||
sleep_min: float = 0.0
|
||||
longest_sleep_min: float = 0.0
|
||||
naps: int = 0
|
||||
counts: Counter = field(default_factory=Counter)
|
||||
has_data: bool = False
|
||||
|
||||
@property
|
||||
def sleep_h(self) -> float:
|
||||
return self.sleep_min / 60
|
||||
|
||||
|
||||
def _days(first: date, last: date) -> list[date]:
|
||||
return [first + timedelta(days=i) for i in range((last - first).days + 1)]
|
||||
|
||||
|
||||
def daily_stats(db: Session, tz: ZoneInfo, first: date, last: date, now: datetime | None = None) -> list[DayStats]:
|
||||
now = now or utcnow()
|
||||
start, _ = local_day_bounds(first, tz)
|
||||
_, end = local_day_bounds(last, tz)
|
||||
events = events_between(db, start - FEED_GAP, end)
|
||||
stats = {d: DayStats(d) for d in _days(first, last)}
|
||||
|
||||
for feed in group_feeds(events):
|
||||
d = feed.start.astimezone(tz).date()
|
||||
if d in stats:
|
||||
stats[d].feeds += 1
|
||||
|
||||
for ev in events:
|
||||
start_day = ev.started_at.astimezone(tz).date()
|
||||
if start_day in stats:
|
||||
stats[start_day].has_data = True
|
||||
stats[start_day].counts[ev.kind_slug] += 1
|
||||
if ev.kind.is_duration:
|
||||
s, e = ev.started_at, effective_end(ev, now)
|
||||
minutes = (e - s).total_seconds() / 60
|
||||
if ev.kind.category == "sleep":
|
||||
if start_day in stats:
|
||||
stats[start_day].naps += 1
|
||||
stats[start_day].longest_sleep_min = max(stats[start_day].longest_sleep_min, minutes)
|
||||
# A night's sleep counts towards each day it covers.
|
||||
for d in _days(max(first, start_day), min(last, e.astimezone(tz).date())):
|
||||
d0, d1 = local_day_bounds(d, tz)
|
||||
overlap = (min(e, d1) - max(s, d0)).total_seconds() / 60
|
||||
if overlap > 0:
|
||||
stats[d].sleep_min += overlap
|
||||
stats[d].has_data = True
|
||||
elif start_day in stats:
|
||||
ds = stats[start_day]
|
||||
if ev.kind_slug == "wet":
|
||||
ds.wet += 1
|
||||
elif ev.kind_slug == "dirty":
|
||||
ds.dirty += 1
|
||||
elif ev.kind.category == "pump":
|
||||
ds.pump += 1
|
||||
|
||||
return [stats[d] for d in sorted(stats)]
|
||||
|
||||
|
||||
def averages(days: list[DayStats]) -> dict[str, float | None]:
|
||||
"""Mean per day over the days that have any data (so the days before the
|
||||
device arrived don't drag the averages down)."""
|
||||
with_data = [d for d in days if d.has_data]
|
||||
if not with_data:
|
||||
return {"feeds": None, "sleep_min": None, "wet": None, "dirty": None, "days": 0}
|
||||
return {
|
||||
"feeds": mean(d.feeds for d in with_data),
|
||||
"sleep_min": mean(d.sleep_min for d in with_data),
|
||||
"wet": mean(d.wet for d in with_data),
|
||||
"dirty": mean(d.dirty for d in with_data),
|
||||
"days": len(with_data),
|
||||
}
|
||||
|
||||
|
||||
def feed_intervals(feeds: list[Feed]) -> list[float]:
|
||||
"""Minutes between the starts of consecutive feeds (gaps over 12 h are ignored:
|
||||
those are missing data, not a real interval)."""
|
||||
gaps = [(b.start - a.start).total_seconds() / 60 for a, b in zip(feeds, feeds[1:])]
|
||||
return [g for g in gaps if g <= 12 * 60]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rhythm chart
|
||||
|
||||
|
||||
@dataclass
|
||||
class Mark:
|
||||
cat: str # sleep | feeding | diaper | other
|
||||
shape: str # bar | dot | diamond | ring | tick
|
||||
left: float # % across the day
|
||||
width: float = 0.0
|
||||
tip: str = ""
|
||||
open: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class RhythmRow:
|
||||
day: date
|
||||
marks: list[Mark]
|
||||
now_pct: float | None = None
|
||||
|
||||
|
||||
RHYTHM_CATS = {"sleep", "feeding", "diaper"} # everything else is drawn as grey "other"
|
||||
|
||||
|
||||
def rhythm(db: Session, tz: ZoneInfo, f: Formatter, first: date, last: date, now: datetime | None = None) -> list[RhythmRow]:
|
||||
"""One row per day (newest first): sleep as bars, feeds as dots, diapers as diamonds."""
|
||||
now = now or utcnow()
|
||||
start, _ = local_day_bounds(first, tz)
|
||||
_, end = local_day_bounds(last, tz)
|
||||
events = events_between(db, start - FEED_GAP, end)
|
||||
rows = []
|
||||
for d in reversed(_days(first, last)):
|
||||
d0, d1 = local_day_bounds(d, tz)
|
||||
span = (d1 - d0).total_seconds() # 23 or 25 h on DST days
|
||||
|
||||
def pct(t: datetime) -> float:
|
||||
return max(0.0, min(100.0, (t - d0).total_seconds() / span * 100))
|
||||
|
||||
marks: list[Mark] = []
|
||||
for ev in events:
|
||||
cat = ev.kind.category
|
||||
if ev.kind.is_duration:
|
||||
s, e = ev.started_at, effective_end(ev, now)
|
||||
if e <= d0 or s >= d1:
|
||||
continue
|
||||
dur = fmt_duration((e - s).total_seconds())
|
||||
tip = f"{ev.kind.emoji} {ev.kind.label} · {f.time(s)}–{f.time(e) if ev.ended_at else 'now'} · {dur}"
|
||||
marks.append(
|
||||
Mark(
|
||||
cat=cat if cat == "sleep" else "other",
|
||||
shape="bar",
|
||||
left=pct(s),
|
||||
width=max(0.4, pct(e) - pct(s)),
|
||||
tip=tip,
|
||||
open=ev.ended_at is None,
|
||||
)
|
||||
)
|
||||
elif d0 <= ev.started_at < d1 and cat != "feeding":
|
||||
shape = "tick"
|
||||
if cat == "diaper":
|
||||
shape = "diamond" if ev.kind_slug == "dirty" else "ring"
|
||||
marks.append(
|
||||
Mark(
|
||||
cat=cat if cat in RHYTHM_CATS else "other",
|
||||
shape=shape,
|
||||
left=pct(ev.started_at),
|
||||
tip=f"{ev.kind.emoji} {ev.kind.label} · {f.time(ev.started_at)}",
|
||||
)
|
||||
)
|
||||
for feed in group_feeds(events):
|
||||
if d0 <= feed.start < d1:
|
||||
marks.append(
|
||||
Mark(
|
||||
cat="feeding",
|
||||
shape="dot",
|
||||
left=pct(feed.start),
|
||||
tip=f"{feed.events[0].kind.emoji} {feed.label} · {f.time(feed.start)}",
|
||||
)
|
||||
)
|
||||
# Bars first so dots and diamonds sit on top of them.
|
||||
marks.sort(key=lambda m: (m.shape != "bar", m.left))
|
||||
rows.append(RhythmRow(day=d, marks=marks, now_pct=pct(now) if d0 <= now < d1 else None))
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the "Today" summary
|
||||
|
||||
|
||||
@dataclass
|
||||
class Alert:
|
||||
level: str # info | warning | serious
|
||||
text: str
|
||||
href: str | None = None
|
||||
link_text: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Summary:
|
||||
now: datetime
|
||||
tz: ZoneInfo
|
||||
last_feed: Feed | None
|
||||
next_side: str | None
|
||||
last_diaper: Event | None
|
||||
last_sleep: Event | None
|
||||
open: list[Event]
|
||||
today: DayStats
|
||||
avg: dict[str, float | None]
|
||||
feed_interval_min: float | None
|
||||
recent: list[Event]
|
||||
device: Device | None
|
||||
alerts: list[Alert]
|
||||
|
||||
@property
|
||||
def sleeping(self) -> Event | None:
|
||||
return next((e for e in self.open if e.kind.category == "sleep" and not is_stale(e, self.now)), None)
|
||||
|
||||
|
||||
def latest_in_category(db: Session, category: str, limit: int = 1) -> list[Event]:
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Kind.category == category)
|
||||
.order_by(Event.started_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def build_summary(db: Session, profile: Profile, now: datetime | None = None) -> Summary:
|
||||
now = now or utcnow()
|
||||
tz = safe_zone(profile.timezone)
|
||||
today = local_today(tz, now)
|
||||
|
||||
recent_feeding = list(reversed(latest_in_category(db, "feeding", limit=40)))
|
||||
feeds = group_feeds(recent_feeding)
|
||||
diapers = latest_in_category(db, "diaper")
|
||||
sleeps = latest_in_category(db, "sleep")
|
||||
|
||||
week = daily_stats(db, tz, today - timedelta(days=7), today, now)
|
||||
feeds_7d = [f for f in feeds if f.start >= now - timedelta(days=7)]
|
||||
intervals = feed_intervals(feeds_7d)
|
||||
|
||||
devices = list(db.scalars(select(Device).where(Device.revoked_at.is_(None))))
|
||||
devices.sort(key=lambda d: d.last_seen_at or d.created_at, reverse=True)
|
||||
opens = open_sessions(db)
|
||||
|
||||
return Summary(
|
||||
now=now,
|
||||
tz=tz,
|
||||
last_feed=feeds[-1] if feeds else None,
|
||||
next_side=next_side(feeds),
|
||||
last_diaper=diapers[0] if diapers else None,
|
||||
last_sleep=sleeps[0] if sleeps else None,
|
||||
open=opens,
|
||||
today=week[-1],
|
||||
avg=averages(week[:-1]),
|
||||
feed_interval_min=median(intervals) if intervals else None,
|
||||
recent=recent_events(db, 8),
|
||||
device=devices[0] if devices else None,
|
||||
alerts=build_alerts(devices, opens, profile, now),
|
||||
)
|
||||
|
||||
|
||||
def build_alerts(devices: list[Device], opens: list[Event], profile: Profile, now: datetime) -> list[Alert]:
|
||||
f = Formatter(safe_zone(profile.timezone), profile.clock_24h)
|
||||
alerts: list[Alert] = []
|
||||
settings = get_settings()
|
||||
if settings.is_production and not settings.login_required:
|
||||
alerts.append(Alert("serious", "This dashboard has no password. Set DASHBOARD_PASSWORD on your host."))
|
||||
|
||||
for ev in opens:
|
||||
if is_stale(ev, now):
|
||||
alerts.append(
|
||||
Alert(
|
||||
"warning",
|
||||
f"{ev.kind.label} started {f.when(ev.started_at)} was never stopped.",
|
||||
href=f"/events/{ev.id}",
|
||||
link_text="Fix the end time",
|
||||
)
|
||||
)
|
||||
|
||||
if not devices:
|
||||
alerts.append(Alert("info", "No Mamadachi is connected yet.", href="/device", link_text="Add a device"))
|
||||
for dev in devices:
|
||||
if dev.last_seen_at is None:
|
||||
alerts.append(Alert("info", f"{dev.name} hasn't synced yet.", href="/device", link_text="Setup steps"))
|
||||
continue
|
||||
silent = now - dev.last_seen_at
|
||||
if silent > timedelta(hours=max(24, 3 * profile.sync_interval_min / 60)):
|
||||
alerts.append(
|
||||
Alert(
|
||||
"warning",
|
||||
f"{dev.name} last synced {f.ago(dev.last_seen_at, now)}. Presses since then are still on the device.",
|
||||
href="/device",
|
||||
link_text="Device details",
|
||||
)
|
||||
)
|
||||
pct = battery_percent(dev.battery_mv)
|
||||
if pct is not None and not dev.charging and pct <= 20:
|
||||
alerts.append(
|
||||
Alert(
|
||||
"serious" if pct <= 10 else "warning",
|
||||
f"{dev.name} battery is at {pct}%. Charge it over USB-C.",
|
||||
)
|
||||
)
|
||||
if dev.clock_skew_s is not None and abs(dev.clock_skew_s) > 120:
|
||||
alerts.append(
|
||||
Alert(
|
||||
"info",
|
||||
f"{dev.name}'s clock was {fmt_duration(abs(dev.clock_skew_s))} off at its last sync; "
|
||||
"its event times were corrected.",
|
||||
)
|
||||
)
|
||||
return alerts
|
||||
|
||||
|
||||
def category_label(cat: str) -> str:
|
||||
return CATEGORIES.get(cat, cat.title())
|
||||
@@ -0,0 +1,155 @@
|
||||
// Small progressive enhancements. Every page works without this file.
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
// ---- live "2h 05m" counters ------------------------------------------
|
||||
const fmtDuration = (secs) => {
|
||||
const mins = Math.max(0, Math.floor(secs / 60));
|
||||
const d = Math.floor(mins / 1440), h = Math.floor((mins % 1440) / 60), m = mins % 60;
|
||||
if (d) return `${d}d ${h}h`;
|
||||
if (h) return `${h}h ${String(m).padStart(2, "0")}m`;
|
||||
return `${m}m`;
|
||||
};
|
||||
const tick = () => {
|
||||
const now = Date.now() / 1000;
|
||||
document.querySelectorAll("[data-since]").forEach((el) => {
|
||||
el.textContent = fmtDuration(now - Number(el.dataset.since));
|
||||
});
|
||||
document.querySelectorAll("[data-ago]").forEach((el) => {
|
||||
const s = now - Number(el.dataset.ago);
|
||||
el.textContent = s < 60 ? "just now" : `${fmtDuration(s)} ago`;
|
||||
});
|
||||
};
|
||||
tick();
|
||||
setInterval(tick, 30_000);
|
||||
|
||||
// ---- keep the Today page fresh -----------------------------------------
|
||||
// Reload when the parent comes back to the tab, or every N s while open,
|
||||
// unless they're in the middle of typing something.
|
||||
const auto = document.querySelector("[data-autorefresh]");
|
||||
if (auto) {
|
||||
const every = Number(auto.dataset.autorefresh) * 1000;
|
||||
let loaded = Date.now();
|
||||
const busy = () => document.activeElement && /INPUT|SELECT|TEXTAREA/.test(document.activeElement.tagName);
|
||||
const maybeReload = () => {
|
||||
if (document.visibilityState === "visible" && !busy() && Date.now() - loaded > every) {
|
||||
loaded = Date.now();
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
setInterval(maybeReload, 15_000);
|
||||
document.addEventListener("visibilitychange", maybeReload);
|
||||
}
|
||||
|
||||
// ---- confirm before destructive buttons --------------------------------
|
||||
document.addEventListener("submit", (e) => {
|
||||
const msg = e.target.dataset && e.target.dataset.confirm;
|
||||
if (msg && !window.confirm(msg)) e.preventDefault();
|
||||
});
|
||||
|
||||
// ---- copy buttons ------------------------------------------------------
|
||||
document.querySelectorAll("[data-copy]").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const src = document.querySelector(btn.dataset.copy);
|
||||
try {
|
||||
await navigator.clipboard.writeText(src.textContent.trim());
|
||||
btn.textContent = "Copied";
|
||||
} catch {
|
||||
const r = document.createRange();
|
||||
r.selectNodeContents(src);
|
||||
getSelection().removeAllRanges();
|
||||
getSelection().addRange(r);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---- show "End" only for start/stop event types ------------------------
|
||||
document.querySelectorAll("[data-kind-form]").forEach((form) => {
|
||||
const select = form.querySelector("select[name=kind]");
|
||||
const end = form.querySelector("[data-end-field]");
|
||||
if (!select || !end) return;
|
||||
const sync = () => {
|
||||
end.hidden = select.selectedOptions[0]?.dataset.duration !== "1";
|
||||
};
|
||||
select.addEventListener("change", sync);
|
||||
sync();
|
||||
});
|
||||
|
||||
// ---- timezone mismatch hint --------------------------------------------
|
||||
const hint = document.getElementById("tz-hint");
|
||||
try {
|
||||
const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
if (hint && browserTz && browserTz !== document.body.dataset.tz) {
|
||||
hint.querySelector("[data-browser-tz]").textContent = browserTz;
|
||||
hint.querySelector("input[name=timezone]").value = browserTz;
|
||||
hint.hidden = false;
|
||||
}
|
||||
} catch { /* old browser: no hint */ }
|
||||
const tzSelect = document.querySelector("[data-tz-select]");
|
||||
if (tzSelect && document.body.dataset.tz === "UTC") {
|
||||
const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const opt = [...tzSelect.options].find((o) => o.value === browserTz);
|
||||
if (opt) opt.selected = true;
|
||||
}
|
||||
|
||||
// ---- tooltips ------------------------------------------------------------
|
||||
const tip = document.getElementById("tip");
|
||||
const showTip = (text, x, y) => {
|
||||
const [head, rest] = String(text).split("|");
|
||||
tip.replaceChildren();
|
||||
const strong = document.createElement("strong");
|
||||
strong.textContent = head;
|
||||
tip.append(strong);
|
||||
if (rest) {
|
||||
const span = document.createElement("span");
|
||||
span.textContent = rest;
|
||||
tip.append(span);
|
||||
}
|
||||
tip.hidden = false;
|
||||
const w = tip.offsetWidth, h = tip.offsetHeight;
|
||||
const left = Math.min(Math.max(8, x - w / 2), innerWidth - w - 8);
|
||||
const top = y - h - 14 < 8 ? y + 18 : y - h - 14;
|
||||
tip.style.left = `${left}px`;
|
||||
tip.style.top = `${top}px`;
|
||||
};
|
||||
const hideTip = () => { tip.hidden = true; };
|
||||
let hideTimer;
|
||||
document.addEventListener("pointerover", (e) => {
|
||||
const el = e.target.closest("[data-tip]");
|
||||
if (!el) return;
|
||||
clearTimeout(hideTimer);
|
||||
showTip(el.dataset.tip, e.clientX, e.clientY);
|
||||
if (e.pointerType === "touch") hideTimer = setTimeout(hideTip, 2500);
|
||||
});
|
||||
document.addEventListener("pointermove", (e) => {
|
||||
const el = e.target.closest("[data-tip]");
|
||||
if (el && !tip.hidden && e.pointerType !== "touch") showTip(el.dataset.tip, e.clientX, e.clientY);
|
||||
});
|
||||
document.addEventListener("pointerout", (e) => {
|
||||
if (e.target.closest("[data-tip]") && e.pointerType !== "touch") hideTip();
|
||||
});
|
||||
addEventListener("scroll", hideTip, { passive: true });
|
||||
|
||||
// ---- line chart crosshair ---------------------------------------------------
|
||||
document.querySelectorAll("[data-line]").forEach((chart) => {
|
||||
const plot = chart.querySelector(".line-plot");
|
||||
const data = JSON.parse(plot.querySelector("script[type='application/json']").textContent);
|
||||
const cross = plot.querySelector(".line-cross");
|
||||
const dot = plot.querySelector(".line-dot");
|
||||
if (!data.length) return;
|
||||
const move = (e) => {
|
||||
const r = plot.getBoundingClientRect();
|
||||
const xPct = ((e.clientX - r.left) / r.width) * 100;
|
||||
let best = data[0];
|
||||
for (const p of data) if (Math.abs(p[0] - xPct) < Math.abs(best[0] - xPct)) best = p;
|
||||
cross.style.left = `${best[0]}%`;
|
||||
dot.style.left = `${best[0]}%`;
|
||||
dot.style.top = `${100 - best[1]}%`;
|
||||
cross.hidden = dot.hidden = false;
|
||||
showTip(best[2], r.left + (best[0] / 100) * r.width, r.top + (1 - best[1] / 100) * r.height);
|
||||
};
|
||||
plot.addEventListener("pointermove", move);
|
||||
plot.addEventListener("pointerdown", move);
|
||||
plot.addEventListener("pointerleave", () => { cross.hidden = dot.hidden = true; hideTip(); });
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<rect width="64" height="64" rx="14" fill="#f9f9f7"/>
|
||||
<path d="M32 7c12.4 0 21 12 21 25.8C53 46 43.9 56 32 56S11 46 11 32.8C11 19 19.6 7 32 7Z" fill="#0b0b0b"/>
|
||||
<rect x="21" y="20" width="22" height="17" rx="4" fill="#f9f9f7"/>
|
||||
<circle cx="27.5" cy="27.5" r="1.8" fill="#0b0b0b"/>
|
||||
<circle cx="36.5" cy="27.5" r="1.8" fill="#0b0b0b"/>
|
||||
<path d="M28.5 31.5c2 1.8 5 1.8 7 0" stroke="#0b0b0b" stroke-width="1.6" fill="none" stroke-linecap="round"/>
|
||||
<circle cx="24" cy="46" r="2.6" fill="#eb6834"/>
|
||||
<circle cx="32" cy="47.5" r="2.6" fill="#2a78d6"/>
|
||||
<circle cx="40" cy="46" r="2.6" fill="#1baf7a"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 679 B |
@@ -0,0 +1,453 @@
|
||||
/* Mamadachi dashboard. Mobile first; no framework.
|
||||
Colour roles follow the validated data-viz palette: categories always wear
|
||||
the same series colour (sleep = 1, feeding = 2, diaper = 3, ...). */
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f9f9f7;
|
||||
--surface: #fcfcfb;
|
||||
--raised: #ffffff;
|
||||
--ink: #0b0b0b;
|
||||
--ink-2: #52514e;
|
||||
--muted: #898781;
|
||||
--grid: #e1e0d9;
|
||||
--baseline: #c3c2b7;
|
||||
--border: rgba(11, 11, 11, 0.10);
|
||||
--wash: rgba(11, 11, 11, 0.04);
|
||||
--focus: #2a78d6;
|
||||
|
||||
--series-1: #2a78d6; /* sleep */
|
||||
--series-2: #eb6834; /* feeding */
|
||||
--series-3: #1baf7a; /* diaper */
|
||||
--series-4: #eda100; /* pump */
|
||||
--series-5: #e87ba4; /* health */
|
||||
--series-6: #008300; /* activity */
|
||||
--other: #a3a19b; /* other / folded */
|
||||
|
||||
--good: #0ca30c;
|
||||
--warning: #fab219;
|
||||
--serious: #ec835a;
|
||||
--critical: #d03b3b;
|
||||
--good-ink: #006300;
|
||||
|
||||
--radius: 14px;
|
||||
--gap: 16px;
|
||||
--font: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
color-scheme: dark;
|
||||
--page: #0d0d0d;
|
||||
--surface: #1a1a19;
|
||||
--raised: #222220;
|
||||
--ink: #ffffff;
|
||||
--ink-2: #c3c2b7;
|
||||
--muted: #898781;
|
||||
--grid: #2c2c2a;
|
||||
--baseline: #383835;
|
||||
--border: rgba(255, 255, 255, 0.10);
|
||||
--wash: rgba(255, 255, 255, 0.05);
|
||||
--focus: #3987e5;
|
||||
--series-1: #3987e5;
|
||||
--series-2: #d95926;
|
||||
--series-3: #199e70;
|
||||
--series-4: #c98500;
|
||||
--series-5: #d55181;
|
||||
--series-6: #008300;
|
||||
--other: #6b6a65;
|
||||
--good-ink: #0ca30c;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--page: #0d0d0d; --surface: #1a1a19; --raised: #222220; --ink: #ffffff; --ink-2: #c3c2b7;
|
||||
--muted: #898781; --grid: #2c2c2a; --baseline: #383835; --border: rgba(255, 255, 255, 0.10);
|
||||
--wash: rgba(255, 255, 255, 0.05); --focus: #3987e5; --series-1: #3987e5; --series-2: #d95926;
|
||||
--series-3: #199e70; --series-4: #c98500; --series-5: #d55181; --series-6: #008300; --other: #6b6a65;
|
||||
--good-ink: #0ca30c;
|
||||
}
|
||||
|
||||
.cat-sleep { --c: var(--series-1); }
|
||||
.cat-feeding { --c: var(--series-2); }
|
||||
.cat-diaper { --c: var(--series-3); }
|
||||
.cat-pump { --c: var(--series-4); }
|
||||
.cat-health { --c: var(--series-5); }
|
||||
.cat-activity { --c: var(--series-6); }
|
||||
.cat-other { --c: var(--other); }
|
||||
|
||||
/* ------------------------------------------------------------ base */
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--page);
|
||||
color: var(--ink);
|
||||
font: 16px/1.45 var(--font);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
h1, h2, h3 { margin: 0 0 8px; line-height: 1.2; font-weight: 650; }
|
||||
h1 { font-size: 1.5rem; }
|
||||
h2 { font-size: 1.1rem; }
|
||||
h3 { font-size: 0.95rem; }
|
||||
p { margin: 0 0 8px; }
|
||||
a { color: inherit; text-decoration-color: var(--baseline); text-underline-offset: 3px; }
|
||||
a:hover { text-decoration-color: currentColor; }
|
||||
code, pre { font-family: ui-monospace, "SF Mono", Consolas, monospace; font-size: 0.85em; }
|
||||
:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 6px; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
.wrap { max-width: 980px; margin: 0 auto; padding: 0 16px; }
|
||||
.muted { color: var(--ink-2); }
|
||||
.small { font-size: 0.85rem; }
|
||||
.emoji { font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif; }
|
||||
.empty { padding: 8px 0; }
|
||||
ul.plain { list-style: none; margin: 0; padding: 0; }
|
||||
.links li { padding: 6px 0; }
|
||||
|
||||
/* ------------------------------------------------------------ header */
|
||||
|
||||
.top {
|
||||
position: sticky; top: 0; z-index: 10;
|
||||
background: color-mix(in srgb, var(--page) 88%, transparent);
|
||||
backdrop-filter: saturate(1.4) blur(10px);
|
||||
-webkit-backdrop-filter: saturate(1.4) blur(10px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding-top: env(safe-area-inset-top);
|
||||
}
|
||||
.top-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 12px; padding-bottom: 6px; }
|
||||
.brand { display: flex; align-items: center; gap: 8px; text-decoration: none; font-weight: 700; letter-spacing: -0.01em; }
|
||||
.logo { width: 26px; height: 26px; color: var(--ink); }
|
||||
.baby { font-size: 0.95rem; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tabs { display: flex; gap: 4px; overflow-x: auto; scrollbar-width: none; padding-bottom: 8px; }
|
||||
.tabs::-webkit-scrollbar { display: none; }
|
||||
.tabs a {
|
||||
flex: none; padding: 6px 12px; border-radius: 999px; text-decoration: none;
|
||||
color: var(--ink-2); font-weight: 550; font-size: 0.95rem;
|
||||
}
|
||||
.tabs a:hover { background: var(--wash); color: var(--ink); }
|
||||
.tabs a[aria-current="page"] { background: var(--ink); color: var(--page); }
|
||||
|
||||
main.wrap { padding-top: 16px; padding-bottom: 24px; display: flex; flex-direction: column; gap: var(--gap); }
|
||||
main.wrap > div[data-autorefresh] { display: flex; flex-direction: column; gap: var(--gap); }
|
||||
.foot { display: flex; gap: 16px; align-items: center; padding-bottom: 32px; font-size: 0.85rem; }
|
||||
.foot form { margin: 0; }
|
||||
|
||||
/* ------------------------------------------------------------ cards & tiles */
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
.card-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; flex-wrap: wrap; margin-bottom: 8px; }
|
||||
.card-head h2 { margin: 0; }
|
||||
.eyebrow { font-size: 0.8rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink-2); margin: 0 0 2px; }
|
||||
|
||||
.hero { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 20px; }
|
||||
.hero-num { font-size: clamp(3rem, 12vw, 4.25rem); font-weight: 650; line-height: 1; letter-spacing: -0.03em; margin: 4px 0 10px; }
|
||||
.hero .muted { margin: 0; }
|
||||
.next-side {
|
||||
flex: none; text-align: center; padding: 12px 16px; border-radius: 12px;
|
||||
background: var(--wash); min-width: 96px;
|
||||
}
|
||||
.next-side strong { display: block; font-size: 1.6rem; font-weight: 650; }
|
||||
|
||||
.tiles { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
@media (min-width: 760px) { .tiles { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
|
||||
.tile { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px; min-width: 0; }
|
||||
.tile-label { display: flex; align-items: center; gap: 6px; font-size: 0.85rem; color: var(--ink-2); margin-bottom: 4px; }
|
||||
.tile-value { font-size: 1.6rem; font-weight: 650; line-height: 1.15; margin: 0 0 4px; }
|
||||
.tile-value small { font-size: 0.85rem; font-weight: 500; color: var(--ink-2); }
|
||||
.tile-sub { font-size: 0.8rem; color: var(--ink-2); margin: 0; }
|
||||
|
||||
.dot { flex: none; display: inline-block; width: 9px; height: 9px; border-radius: 50%; background: var(--c, var(--other)); }
|
||||
.key { display: inline-block; width: 10px; height: 10px; border-radius: 3px; background: var(--c); margin-right: 8px; vertical-align: 0; }
|
||||
|
||||
.running ul li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 6px 0; flex-wrap: wrap; }
|
||||
.running form { margin: 0; }
|
||||
|
||||
/* ------------------------------------------------------------ alerts & flashes */
|
||||
|
||||
.alert, .flash {
|
||||
display: flex; align-items: flex-start; gap: 10px; padding: 10px 14px;
|
||||
border-radius: 12px; border: 1px solid var(--border); background: var(--surface); font-size: 0.95rem;
|
||||
}
|
||||
.flash { align-items: center; justify-content: space-between; background: var(--raised); }
|
||||
.flash form { margin: 0; flex: none; }
|
||||
.flash-error { border-color: var(--critical); }
|
||||
.alert-icon {
|
||||
flex: none; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center;
|
||||
font-size: 0.75rem; font-weight: 800; color: #0b0b0b;
|
||||
}
|
||||
.alert-info .alert-icon { background: var(--grid); color: var(--ink); }
|
||||
.alert-warning { border-left: 4px solid var(--warning); }
|
||||
.alert-warning .alert-icon { background: var(--warning); }
|
||||
.alert-serious { border-left: 4px solid var(--critical); }
|
||||
.alert-serious .alert-icon { background: var(--critical); color: #fff; }
|
||||
.alert-label { font-weight: 650; }
|
||||
|
||||
/* ------------------------------------------------------------ buttons & forms */
|
||||
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
||||
font: inherit; font-weight: 600; font-size: 0.95rem;
|
||||
padding: 9px 16px; border-radius: 10px; border: 1px solid transparent;
|
||||
background: var(--ink); color: var(--page); cursor: pointer; text-decoration: none;
|
||||
min-height: 40px;
|
||||
}
|
||||
.btn:hover { opacity: 0.88; }
|
||||
.btn-ghost { background: transparent; color: var(--ink); border-color: var(--baseline); }
|
||||
.btn-ghost:hover { background: var(--wash); opacity: 1; }
|
||||
.btn-danger { background: transparent; color: var(--critical); border-color: var(--critical); }
|
||||
.btn-small { padding: 5px 12px; min-height: 32px; font-size: 0.875rem; }
|
||||
.btn-wide { width: 100%; }
|
||||
.link-btn { font: inherit; font-weight: 600; background: none; border: 0; padding: 4px 6px; color: var(--ink); text-decoration: underline; text-underline-offset: 3px; cursor: pointer; }
|
||||
.actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
.actions form { margin: 0; }
|
||||
|
||||
label { display: flex; flex-direction: column; gap: 4px; font-size: 0.875rem; font-weight: 550; min-width: 0; }
|
||||
label.check { flex-direction: row; align-items: center; gap: 8px; font-weight: 500; }
|
||||
input[type="text"], input[type="password"], input[type="number"], input[type="date"],
|
||||
input[type="datetime-local"], select {
|
||||
font: inherit; font-weight: 400; font-size: 1rem; /* 16px stops iOS zooming in */
|
||||
width: 100%; min-width: 0; padding: 8px 10px; min-height: 40px;
|
||||
border-radius: 10px; border: 1px solid var(--baseline); background: var(--raised); color: var(--ink);
|
||||
}
|
||||
input[type="checkbox"] { width: 18px; height: 18px; accent-color: var(--ink); }
|
||||
.form-grid { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 8px; align-items: end; }
|
||||
@media (min-width: 640px) {
|
||||
.form-grid { grid-template-columns: 1fr 1fr; }
|
||||
.form-grid .span-2 { grid-column: span 2; }
|
||||
}
|
||||
.form-error { color: var(--critical); font-weight: 600; }
|
||||
.inline-form { display: flex; gap: 8px; flex-wrap: wrap; margin: 0; }
|
||||
.inline-form input { flex: 1 1 180px; width: auto; }
|
||||
|
||||
details > summary { cursor: pointer; list-style: none; display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
|
||||
details > summary::-webkit-details-marker { display: none; }
|
||||
details > summary h2, details > summary h3 { margin: 0; }
|
||||
details > summary::before { content: "▸"; color: var(--muted); font-size: 0.8em; transition: transform 0.15s; }
|
||||
details[open] > summary::before { transform: rotate(90deg); }
|
||||
details[open] > summary { margin-bottom: 12px; }
|
||||
|
||||
/* ------------------------------------------------------------ quick log */
|
||||
|
||||
.quick { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; }
|
||||
.quick form { margin: 0; }
|
||||
.quick-btn {
|
||||
width: 100%; display: flex; align-items: center; gap: 8px; text-align: left;
|
||||
font: inherit; font-weight: 550; font-size: 0.95rem; color: var(--ink);
|
||||
padding: 10px 12px; min-height: 48px; border-radius: 12px; cursor: pointer;
|
||||
background: var(--raised); border: 1px solid var(--border);
|
||||
box-shadow: inset 3px 0 0 var(--c);
|
||||
}
|
||||
.quick-btn:hover { background: var(--wash); }
|
||||
.quick-btn:active { transform: scale(0.98); }
|
||||
.quick-btn .emoji { font-size: 1.25rem; }
|
||||
.quick-btn.is-open { border-color: var(--c); box-shadow: inset 0 0 0 1px var(--c), inset 3px 0 0 var(--c); }
|
||||
|
||||
/* ------------------------------------------------------------ event list */
|
||||
|
||||
.events { list-style: none; margin: 0; padding: 0; }
|
||||
.events.card { padding: 4px 16px; }
|
||||
.ev {
|
||||
display: grid; grid-template-columns: 4.6rem auto 1fr auto auto; align-items: baseline;
|
||||
column-gap: 10px; padding: 10px 0; border-top: 1px solid var(--grid);
|
||||
}
|
||||
.ev:first-child { border-top: 0; }
|
||||
.ev time { font-variant-numeric: tabular-nums; color: var(--ink-2); font-size: 0.9rem; white-space: nowrap; }
|
||||
.ev time .muted { display: block; font-size: 0.75rem; }
|
||||
.ev .dot { align-self: center; }
|
||||
.ev-main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.ev-title { font-weight: 550; }
|
||||
.ev-main .muted { font-size: 0.875rem; }
|
||||
.note { font-size: 0.875rem; color: var(--ink-2); font-style: italic; overflow-wrap: anywhere; }
|
||||
.ev-src { font-size: 0.75rem; white-space: nowrap; }
|
||||
.ev-edit { font-size: 0.85rem; color: var(--ink-2); padding: 4px 0 4px 4px; }
|
||||
.badge { display: inline-block; font-size: 0.8rem; font-weight: 600; padding: 1px 8px; border-radius: 999px; width: fit-content; margin-top: 2px; }
|
||||
.badge-live { background: color-mix(in srgb, var(--series-1) 16%, transparent); color: var(--ink); }
|
||||
|
||||
.day { display: flex; flex-direction: column; gap: 8px; }
|
||||
.day-head { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 4px 12px; padding: 0 4px; }
|
||||
.day-head h2 { margin: 0; }
|
||||
.day-head p { margin: 0; }
|
||||
|
||||
.chips, .segmented { display: flex; gap: 6px; overflow-x: auto; scrollbar-width: none; padding-bottom: 2px; }
|
||||
.chips::-webkit-scrollbar, .segmented::-webkit-scrollbar { display: none; }
|
||||
.chips a, .segmented a {
|
||||
flex: none; display: inline-flex; align-items: center; gap: 6px; text-decoration: none;
|
||||
padding: 6px 12px; border-radius: 999px; border: 1px solid var(--border); background: var(--surface);
|
||||
font-size: 0.9rem; font-weight: 550; color: var(--ink-2);
|
||||
}
|
||||
.chips a[aria-current], .segmented a[aria-current] { background: var(--ink); color: var(--page); border-color: var(--ink); }
|
||||
.pager { display: flex; justify-content: space-between; }
|
||||
|
||||
.pill { display: inline-block; font-size: 0.8rem; font-weight: 600; padding: 2px 10px; border-radius: 999px; background: var(--wash); margin: 2px 0; }
|
||||
.pill-ok { background: color-mix(in srgb, var(--good) 18%, transparent); color: var(--good-ink); }
|
||||
.pill-off { background: var(--wash); color: var(--ink-2); }
|
||||
|
||||
/* ------------------------------------------------------------ legend */
|
||||
|
||||
.legend { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 0.8rem; color: var(--ink-2); }
|
||||
.legend li { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.lg { display: inline-block; flex: none; }
|
||||
.lg-bar { width: 16px; height: 8px; border-radius: 3px; background: var(--c); }
|
||||
.lg-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--c); }
|
||||
.lg-ring { width: 9px; height: 9px; border-radius: 2px; transform: rotate(45deg); border: 2px solid var(--c); }
|
||||
.lg-diamond { width: 9px; height: 9px; border-radius: 2px; transform: rotate(45deg); background: var(--c); }
|
||||
.lg-tick { width: 3px; height: 11px; border-radius: 2px; background: var(--c); }
|
||||
|
||||
/* ------------------------------------------------------------ rhythm chart */
|
||||
|
||||
.rhythm { display: flex; flex-direction: column; gap: 4px; margin-top: 4px; }
|
||||
.rh-row { display: grid; grid-template-columns: 3.2rem 1fr; align-items: center; gap: 8px; }
|
||||
.rhythm.compact .rh-row { grid-template-columns: 0 1fr; gap: 0; }
|
||||
.rh-label { font-size: 0.75rem; color: var(--ink-2); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.rh-ticks { position: relative; height: 16px; }
|
||||
.rh-ticks span { position: absolute; transform: translateX(-50%); font-size: 0.75rem; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.rh-ticks span:first-child { transform: none; }
|
||||
.rh-track {
|
||||
position: relative; height: 22px;
|
||||
background-image: linear-gradient(to right, var(--grid) 1px, transparent 1px);
|
||||
background-size: 25% 100%;
|
||||
border-right: 1px solid var(--grid);
|
||||
}
|
||||
.rhythm.compact .rh-track { height: 30px; }
|
||||
.rh-track::after { content: ""; position: absolute; left: 0; right: 0; top: 50%; border-top: 1px solid var(--grid); }
|
||||
.m { position: absolute; top: 50%; z-index: 1; cursor: default; }
|
||||
.m-bar {
|
||||
height: 10px; transform: translateY(-50%); border-radius: 4px; background: var(--c);
|
||||
box-shadow: 0 0 0 1px var(--surface); min-width: 3px;
|
||||
}
|
||||
.rhythm.compact .m-bar { height: 14px; }
|
||||
.m-bar.m-open { background: repeating-linear-gradient(135deg, var(--c) 0 6px, color-mix(in srgb, var(--c) 55%, var(--surface)) 6px 9px); }
|
||||
.m-dot, .m-ring, .m-diamond { width: 10px; height: 10px; margin-left: -5px; margin-top: -5px; z-index: 2; }
|
||||
.m-dot { border-radius: 50%; background: var(--c); box-shadow: 0 0 0 2px var(--surface); }
|
||||
.m-diamond { border-radius: 2px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 2px var(--surface); }
|
||||
.m-ring { border-radius: 2px; transform: rotate(45deg); background: var(--surface); border: 2px solid var(--c); box-shadow: 0 0 0 1px var(--surface); }
|
||||
.m-tick { width: 3px; height: 12px; margin-left: -1.5px; margin-top: -6px; border-radius: 2px; background: var(--c); }
|
||||
.m::before { content: ""; position: absolute; inset: -7px; } /* bigger hit area than the mark */
|
||||
.m:hover { filter: brightness(1.12); z-index: 3; }
|
||||
.m-now { position: absolute; top: -3px; bottom: -3px; width: 2px; margin-left: -1px; background: var(--ink); border-radius: 1px; z-index: 4; }
|
||||
|
||||
/* ------------------------------------------------------------ column charts */
|
||||
|
||||
.chart-grid { display: grid; grid-template-columns: 1fr; gap: var(--gap); }
|
||||
@media (min-width: 760px) { .chart-grid { grid-template-columns: 1fr 1fr; } }
|
||||
.chart { margin: 0; }
|
||||
.chart figcaption h3 { display: flex; align-items: center; margin-bottom: 2px; }
|
||||
.chart figcaption p { font-size: 0.85rem; margin-bottom: 12px; }
|
||||
.cols { --label-w: 2rem; }
|
||||
.cols-plot { position: relative; height: 140px; margin: 8px 0 0 var(--label-w); border-bottom: 1px solid var(--baseline); }
|
||||
.gridline { position: absolute; left: 0; right: 0; border-top: 1px solid var(--grid); height: 0; }
|
||||
.gridline em {
|
||||
position: absolute; right: 100%; transform: translateY(-50%); padding-right: 6px;
|
||||
font-style: normal; font-size: 0.72rem; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap;
|
||||
}
|
||||
.cols-bars { position: absolute; inset: 0; display: flex; align-items: flex-end; gap: 2px; }
|
||||
.col { flex: 1; height: 100%; display: flex; align-items: flex-end; justify-content: center; position: relative; }
|
||||
.col:hover { background: var(--wash); border-radius: 4px 4px 0 0; }
|
||||
.col-bar { position: relative; width: min(24px, 70%); background: var(--c); border-radius: 4px 4px 0 0; min-height: 0; }
|
||||
.col-bar.is-zero { height: 0 !important; }
|
||||
.col-bar.is-partial { opacity: 0.55; }
|
||||
.col-bar b {
|
||||
position: absolute; bottom: 100%; left: 50%; transform: translateX(-50%); padding-bottom: 3px;
|
||||
font-size: 0.75rem; font-weight: 650; color: var(--ink); white-space: nowrap;
|
||||
}
|
||||
.cols-x { display: flex; gap: 2px; margin-left: var(--label-w); padding-top: 4px; }
|
||||
.cols-x span { flex: 1; text-align: center; font-size: 0.7rem; color: var(--muted); white-space: nowrap; overflow: visible; min-width: 0; }
|
||||
|
||||
/* ------------------------------------------------------------ line chart (battery) */
|
||||
|
||||
.line { --label-w: 3rem; margin: 8px 0 12px; }
|
||||
.line-plot { position: relative; height: 160px; margin-left: var(--label-w); border-bottom: 1px solid var(--baseline); touch-action: pan-y; }
|
||||
.line-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
||||
.line-path { fill: none; stroke: var(--series-1); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; }
|
||||
.line-area { fill: var(--series-1); opacity: 0.1; stroke: none; }
|
||||
.line-cross { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--baseline); pointer-events: none; }
|
||||
.line-dot { position: absolute; width: 10px; height: 10px; margin: -5px 0 0 -5px; border-radius: 50%; background: var(--series-1); box-shadow: 0 0 0 2px var(--surface); pointer-events: none; }
|
||||
.line-x { position: relative; height: 18px; margin-left: var(--label-w); }
|
||||
.line-x span { position: absolute; transform: translateX(-50%); font-size: 0.72rem; color: var(--muted); white-space: nowrap; top: 4px; }
|
||||
.line-x span:first-child { transform: none; }
|
||||
|
||||
/* ------------------------------------------------------------ tooltip */
|
||||
|
||||
.tip {
|
||||
position: fixed; z-index: 50; pointer-events: none; max-width: 260px;
|
||||
background: var(--raised); color: var(--ink); border: 1px solid var(--border);
|
||||
border-radius: 10px; padding: 6px 10px; font-size: 0.85rem; line-height: 1.35;
|
||||
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.16);
|
||||
}
|
||||
.tip strong { display: block; font-weight: 650; }
|
||||
.tip span { color: var(--ink-2); }
|
||||
|
||||
/* ------------------------------------------------------------ device & tables */
|
||||
|
||||
.facts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 16px; margin: 4px 0 16px; }
|
||||
@media (min-width: 760px) { .facts { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
|
||||
.facts dt { font-size: 0.8rem; color: var(--ink-2); }
|
||||
.facts dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; }
|
||||
.facts dd .muted { font-weight: 400; font-size: 0.85rem; }
|
||||
.device.is-revoked { opacity: 0.7; }
|
||||
.device h3 { margin-top: 4px; }
|
||||
.device details { margin: 12px 0; }
|
||||
.token-card { border: 2px solid var(--ink); }
|
||||
.copy-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
|
||||
.copy-row code { font-size: 0.95rem; padding: 8px 10px; background: var(--wash); border-radius: 8px; overflow-wrap: anywhere; }
|
||||
pre.code { background: var(--wash); border-radius: 10px; padding: 12px; overflow-x: auto; margin: 0 0 12px; white-space: pre; }
|
||||
.steps { padding-left: 20px; }
|
||||
.steps li { margin-bottom: 6px; }
|
||||
|
||||
.table-scroll { overflow-x: auto; }
|
||||
.num-table { border-collapse: collapse; width: 100%; font-size: 0.875rem; }
|
||||
.num-table th, .num-table td { padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--grid); white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.num-table th:first-child { text-align: left; font-weight: 550; }
|
||||
.num-table thead th { color: var(--ink-2); font-weight: 600; font-size: 0.8rem; }
|
||||
|
||||
/* ------------------------------------------------------------ settings */
|
||||
|
||||
.button-grid { display: grid; grid-template-columns: 1fr; gap: 8px; margin: 8px 0 16px; }
|
||||
@media (min-width: 560px) { .button-grid { grid-template-columns: 1fr 1fr; grid-auto-flow: column; grid-template-rows: repeat(4, auto); } }
|
||||
.button-slot { flex-direction: row; align-items: center; gap: 10px; }
|
||||
.button-num {
|
||||
flex: none; width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center;
|
||||
background: var(--ink); color: var(--page); font-weight: 700; font-size: 0.9rem;
|
||||
}
|
||||
.kinds { display: flex; flex-direction: column; gap: 8px; margin: 8px 0 16px; }
|
||||
.kind-row {
|
||||
display: grid; grid-template-columns: 4rem 1fr 1fr; gap: 8px 10px; align-items: end;
|
||||
border: 1px solid var(--border); border-radius: 12px; padding: 8px 12px 12px; margin: 0;
|
||||
}
|
||||
.kind-row legend { display: flex; align-items: center; gap: 6px; font-size: 0.75rem; color: var(--ink-2); padding: 0 4px; }
|
||||
.kind-row.is-hidden { opacity: 0.6; }
|
||||
.k-mode { grid-column: span 2; }
|
||||
@media (min-width: 760px) {
|
||||
.kind-row { grid-template-columns: 4rem 1.4fr 1fr 1.2fr 0.8fr auto; }
|
||||
.k-mode { grid-column: auto; }
|
||||
}
|
||||
.k-emoji input { text-align: center; }
|
||||
.k-active { padding-bottom: 10px; }
|
||||
.add-kind { margin-top: 8px; }
|
||||
|
||||
.login { max-width: 420px; width: 100%; margin: 40px auto; }
|
||||
.login form { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; }
|
||||
|
||||
.device-chip { text-align: center; font-size: 0.85rem; margin: 0; }
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.ev { grid-template-columns: 4.1rem auto 1fr auto; }
|
||||
.ev-src { display: none; }
|
||||
.hero { padding: 16px; }
|
||||
.next-side { min-width: 80px; padding: 10px 12px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; }
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.m, .dot, .key, .col-bar, .lg { forced-color-adjust: none; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>{% block title %}{{ profile.baby_name if logged_in else "Mamadachi" }}{% endblock %} · Mamadachi</title>
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="theme-color" content="#f9f9f7" media="(prefers-color-scheme: light)">
|
||||
<meta name="theme-color" content="#0d0d0d" media="(prefers-color-scheme: dark)">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-title" content="Mamadachi">
|
||||
<link rel="icon" href="/static/icon.svg" type="image/svg+xml">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="stylesheet" href="/static/style.css?v={{ app_version }}">
|
||||
<script src="/static/app.js?v={{ app_version }}" defer></script>
|
||||
</head>
|
||||
<body data-tz="{{ profile.timezone }}">
|
||||
<header class="top">
|
||||
<div class="wrap top-row">
|
||||
<a class="brand" href="/">
|
||||
<svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><path d="M16 2.5c6.8 0 11.5 6.6 11.5 14.2 0 7.3-5 12.8-11.5 12.8S4.5 24 4.5 16.7C4.5 9.1 9.2 2.5 16 2.5Z" fill="currentColor"/><rect x="10" y="10.5" width="12" height="9" rx="2.2" fill="var(--surface)"/><circle cx="11.5" cy="24" r="1.5" fill="var(--surface)"/><circle cx="16" cy="24.8" r="1.5" fill="var(--surface)"/><circle cx="20.5" cy="24" r="1.5" fill="var(--surface)"/></svg>
|
||||
<span>Mamadachi</span>
|
||||
</a>
|
||||
{% if logged_in %}
|
||||
<div class="baby">
|
||||
<strong>{{ profile.baby_name }}</strong>{% if age %}<span class="muted"> · {{ age }}</span>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if logged_in %}
|
||||
<nav class="wrap tabs" aria-label="Main">
|
||||
{% for href, label in nav %}
|
||||
<a href="{{ href }}" {% if path == href or (href != '/' and path.startswith(href)) or (href == '/log' and path.startswith('/events')) %}aria-current="page"{% endif %}>{{ label }}</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
</header>
|
||||
|
||||
<main class="wrap">
|
||||
{% for m in flashes %}
|
||||
<div class="flash flash-{{ m.level }}" role="status">
|
||||
<span>{{ m.text }}</span>
|
||||
{% if m.undo %}
|
||||
<form method="post" action="{{ m.undo }}"><button class="link-btn">Undo</button></form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if logged_in %}
|
||||
<div id="tz-hint" class="flash flash-info" hidden>
|
||||
<span>Your phone is set to <strong data-browser-tz></strong>, but times here use {{ profile.timezone }}.</span>
|
||||
<form method="post" action="/settings/timezone">
|
||||
<input type="hidden" name="timezone" value="">
|
||||
<input type="hidden" name="next" value="{{ path }}">
|
||||
<button class="link-btn">Use my timezone</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer class="wrap foot muted">
|
||||
<span>Mamadachi {{ app_version }}</span>
|
||||
{% if logged_in %}
|
||||
<a href="/docs">API</a>
|
||||
{% if login_required %}
|
||||
<form method="post" action="/logout"><button class="link-btn">Log out</button></form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</footer>
|
||||
<div id="tip" class="tip" role="tooltip" hidden></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,119 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "macros.html" as ui %}
|
||||
{% block title %}Device{% endblock %}
|
||||
{% block content %}
|
||||
|
||||
{% if new_token %}
|
||||
<section class="card token-card" aria-live="polite">
|
||||
<h2>Token for {{ new_device.name }}</h2>
|
||||
<p>Copy it now: it is shown <strong>only once</strong>. If you lose it, rotate it to get a new one.</p>
|
||||
<div class="copy-row">
|
||||
<code id="token">{{ new_token }}</code>
|
||||
<button class="btn btn-small" data-copy="#token">Copy</button>
|
||||
</div>
|
||||
<p class="small">Put it in the firmware's <code>secrets.h</code>, next to the Wi-Fi credentials:</p>
|
||||
<pre class="code" id="secrets">#define MAMADACHI_SYNC_URL "{{ base_url }}/api/v1/device/sync"
|
||||
#define MAMADACHI_TOKEN "{{ new_token }}"</pre>
|
||||
<p class="small">Or test it from your computer, pretending to be the device:</p>
|
||||
<pre class="code">python tools/fake_device.py --url {{ base_url }} --token {{ new_token }} press 6
|
||||
python tools/fake_device.py --url {{ base_url }} --token {{ new_token }} sync</pre>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% for c in cards %}
|
||||
{% set dev = c.dev %}
|
||||
<section class="card device{% if not dev.active %} is-revoked{% endif %}">
|
||||
<div class="card-head">
|
||||
<h2>{{ dev.name }}</h2>
|
||||
<span class="pill {{ 'pill-ok' if dev.active else 'pill-off' }}">{{ 'Active' if dev.active else 'Revoked' }}</span>
|
||||
</div>
|
||||
<dl class="facts">
|
||||
<div><dt>Last sync</dt><dd>{% if dev.last_seen_at %}<span data-ago="{{ f.unix(dev.last_seen_at) }}">{{ f.ago(dev.last_seen_at, now) }}</span>{% else %}never{% endif %}</dd></div>
|
||||
<div><dt>Battery</dt><dd>{% if dev.battery_mv %}{{ c.battery_pct }}% <span class="muted">{{ '%.2f' % (dev.battery_mv / 1000) }} V{% if dev.charging %} · charging{% endif %}</span>{% else %}–{% endif %}</dd></div>
|
||||
<div><dt>Wi-Fi signal</dt><dd>{% if dev.rssi is not none %}{{ c.signal }} <span class="muted">{{ dev.rssi }} dBm</span>{% else %}–{% endif %}</dd></div>
|
||||
<div><dt>Firmware</dt><dd>{{ dev.firmware or '–' }}</dd></div>
|
||||
<div><dt>Clock</dt><dd>{% if dev.clock_skew_s is none %}–{% elif dev.clock_skew_s|abs <= 120 %}in sync <span class="muted">{{ dev.clock_skew_s }} s</span>{% else %}off by {{ f.duration(dev.clock_skew_s|abs) }}{% endif %}</dd></div>
|
||||
<div><dt>Presses received</dt><dd>{{ c.presses }}</dd></div>
|
||||
<div><dt>Boots</dt><dd>{{ dev.boot_count if dev.boot_count is not none else '–' }}</dd></div>
|
||||
<div><dt>Token</dt><dd><code>mmd_…{{ dev.token_hint }}</code></dd></div>
|
||||
</dl>
|
||||
|
||||
<h3>Battery, last {{ battery_days }} days</h3>
|
||||
{{ ui.battery_chart(c.chart) }}
|
||||
|
||||
{% if c.log %}
|
||||
<details>
|
||||
<summary><h3>Recent syncs</h3></summary>
|
||||
<div class="table-scroll">
|
||||
<table class="num-table">
|
||||
<thead><tr><th scope="col">When</th><th scope="col">Presses</th><th scope="col">Battery</th><th scope="col">Signal</th><th scope="col">Clock</th><th scope="col">Server time</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in c.log %}
|
||||
<tr>
|
||||
<th scope="row">{{ f.when(r.received_at) }}</th>
|
||||
<td>{{ r.events_new }}{% if r.events_received != r.events_new %} <span class="muted">({{ r.events_received - r.events_new }} repeat)</span>{% endif %}</td>
|
||||
<td>{{ '%.2f V' % (r.battery_mv / 1000) if r.battery_mv else '–' }}</td>
|
||||
<td>{{ r.rssi if r.rssi is not none else '–' }}</td>
|
||||
<td>{{ '%+d s' % r.clock_skew_s if r.clock_skew_s is not none else '–' }}</td>
|
||||
<td>{{ r.duration_ms if r.duration_ms is not none else '–' }} ms</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
|
||||
<div class="actions">
|
||||
<form method="post" action="/device/{{ dev.id }}/rename" class="inline-form">
|
||||
<input type="text" name="name" value="{{ dev.name }}" aria-label="Device name" maxlength="80">
|
||||
<button class="btn btn-ghost btn-small">Rename</button>
|
||||
</form>
|
||||
<form method="post" action="/device/{{ dev.id }}/rotate" data-confirm="Make a new token? The old one stops working, so the device needs reflashing with the new one.">
|
||||
<button class="btn btn-ghost btn-small">{{ 'New token' if dev.active else 'Re-enable with new token' }}</button>
|
||||
</form>
|
||||
{% if dev.active %}
|
||||
<form method="post" action="/device/{{ dev.id }}/revoke" data-confirm="Stop {{ dev.name }} from syncing? Its past events stay.">
|
||||
<button class="btn btn-danger btn-small">Revoke</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endfor %}
|
||||
|
||||
<section class="card">
|
||||
<h2>{{ 'Add a device' if cards else 'Connect your Mamadachi' }}</h2>
|
||||
<p class="muted small">Each device gets its own secret token. It sends it with every sync, so the server knows the presses are really from your Mamadachi.</p>
|
||||
<form method="post" action="/device/new" class="inline-form">
|
||||
<input type="text" name="name" value="Mamadachi{% if cards %} {{ cards | length + 1 }}{% endif %}" aria-label="Device name" maxlength="80">
|
||||
<button class="btn">Create token</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<details>
|
||||
<summary><h2>How the device syncs</h2><span class="muted small">For firmware work</span></summary>
|
||||
<ol class="steps small">
|
||||
<li>Every press is queued on the device with a <strong>seq</strong> (a counter kept in NVS, +1 per press), the <strong>time</strong> from the RV-3028 (UNIX seconds, UTC) and the <strong>button</strong> number (1–8).</li>
|
||||
<li>When it's time to sync (every {{ profile.sync_interval_min }} min, or after a press if you like), it joins Wi-Fi and makes <strong>one</strong> HTTPS request:</li>
|
||||
</ol>
|
||||
<pre class="code">POST {{ base_url }}/api/v1/device/sync
|
||||
Authorization: Bearer mmd_…
|
||||
Content-Type: application/json
|
||||
|
||||
{"device_time": 1760630400, "firmware": "0.1.0", "battery_mv": 3987,
|
||||
"charging": false, "rssi": -61, "boot_count": 42, "queue_len": 0,
|
||||
"events": [{"seq": 101, "time": 1760620000, "button": 6},
|
||||
{"seq": 102, "time": 1760627000, "button": 6}]}</pre>
|
||||
<ol class="steps small" start="3">
|
||||
<li><strong>HTTP 200</strong>: every event sent is stored. Delete them from the queue. Anything else (no Wi-Fi, timeout, 5xx): keep them and try again later. Resending is safe: the server skips presses it already has.</li>
|
||||
<li>The response carries <code>server_time</code> (set the RTC if it drifted), <code>tz_offset_s</code> (to show local time), the <code>buttons</code> layout with short labels for the e-paper, and a <code>status</code> block: last feed, next side, ongoing sleep, today's counts.</li>
|
||||
<li>Send at most 500 events per request. If more are queued, sync again right away.</li>
|
||||
</ol>
|
||||
<p class="small">Current layout:
|
||||
{% for n, k in buttons.items() %}<span class="pill">{{ n }}: {{ k.short if k else '–' }}</span> {% endfor %}
|
||||
</p>
|
||||
<p class="small">Full field reference: <a href="/docs#/device">API docs</a>.</p>
|
||||
</details>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,9 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ code }}{% endblock %}
|
||||
{% block content %}
|
||||
<section class="card login">
|
||||
<h1>{{ {404: "Not found", 401: "Please log in", 403: "Not allowed"}.get(code, "Something went wrong") }}</h1>
|
||||
<p class="muted">{{ detail if detail and detail != "Not Found" else "That page doesn't exist." }}</p>
|
||||
<a class="btn" href="/">Back to today</a>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,48 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Edit {{ ev.kind.label }}{% endblock %}
|
||||
{% block content %}
|
||||
<p><a href="/log?before={{ f.local(ev.started_at).date().isoformat() }}" class="small">← Back to the log</a></p>
|
||||
|
||||
<section class="card">
|
||||
<h1><span class="emoji" aria-hidden="true">{{ ev.kind.emoji }}</span> {{ ev.kind.label }}</h1>
|
||||
<p class="muted small">
|
||||
{% if ev.source == 'device' %}From the Mamadachi (button {{ ev.button }}){% else %}Added on the website{% endif %}
|
||||
· recorded {{ f.when(ev.created_at) }}
|
||||
{% if ev.clock_corrected %}<br>⏱ The device's clock was off when this was uploaded, so its time was corrected.{% endif %}
|
||||
{% if ev.deleted_at %}<br><strong>Deleted {{ f.when(ev.deleted_at) }}.</strong>{% endif %}
|
||||
</p>
|
||||
|
||||
<form method="post" action="/events/{{ ev.id }}" class="form-grid" data-kind-form>
|
||||
<label>Type
|
||||
<select name="kind">
|
||||
{% for k in kinds %}
|
||||
<option value="{{ k.slug }}" data-duration="{{ 1 if k.is_duration else 0 }}" {% if k.slug == ev.kind_slug %}selected{% endif %}>{{ k.emoji }} {{ k.label }}{% if not k.active %} (hidden){% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>Start
|
||||
<input type="datetime-local" name="started_at" value="{{ f.input_value(ev.started_at) }}" required>
|
||||
</label>
|
||||
<label data-end-field {% if not ev.kind.is_duration %}hidden{% endif %}><span>End <span class="muted">(empty = still going)</span></span>
|
||||
<input type="datetime-local" name="ended_at" value="{{ f.input_value(ev.ended_at) }}">
|
||||
</label>
|
||||
<label class="span-2">Note
|
||||
<input type="text" name="note" maxlength="2000" value="{{ ev.note or '' }}">
|
||||
</label>
|
||||
<div class="span-2 actions">
|
||||
<button class="btn">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<div class="actions">
|
||||
{% if ev.is_open %}
|
||||
<form method="post" action="/events/{{ ev.id }}/end"><input type="hidden" name="next" value="/events/{{ ev.id }}"><button class="btn btn-ghost">End now</button></form>
|
||||
{% endif %}
|
||||
{% if ev.deleted_at %}
|
||||
<form method="post" action="/events/{{ ev.id }}/restore"><button class="btn btn-ghost">Restore</button></form>
|
||||
{% else %}
|
||||
<form method="post" action="/events/{{ ev.id }}/delete" data-confirm="Delete this {{ ev.kind.label | lower }}? You can undo it right after."><button class="btn btn-danger">Delete</button></form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,59 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "macros.html" as ui %}
|
||||
{% block title %}Log{% endblock %}
|
||||
{% block content %}
|
||||
<section class="card">
|
||||
<details class="add-event" {% if not days or not days[0][1] %}open{% endif %}>
|
||||
<summary><h2>Add an event</h2><span class="muted small">Forgot the Mamadachi? Log it here.</span></summary>
|
||||
<form method="post" action="/events" class="form-grid" data-kind-form>
|
||||
<label>Type
|
||||
<select name="kind" required>
|
||||
{% for k in kinds %}<option value="{{ k.slug }}" data-duration="{{ 1 if k.is_duration else 0 }}">{{ k.emoji }} {{ k.label }}</option>{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>Start
|
||||
<input type="datetime-local" name="started_at" value="{{ default_start }}" required>
|
||||
</label>
|
||||
<label data-end-field hidden><span>End <span class="muted">(leave empty if still going)</span></span>
|
||||
<input type="datetime-local" name="ended_at">
|
||||
</label>
|
||||
<label class="span-2"><span>Note <span class="muted">(optional)</span></span>
|
||||
<input type="text" name="note" maxlength="2000" placeholder="e.g. 90 ml formula, fussy before">
|
||||
</label>
|
||||
<div class="span-2"><button class="btn">Add</button></div>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<nav class="chips" aria-label="Filter by type">
|
||||
<a href="/log" {% if not cat %}aria-current="true"{% endif %}>All</a>
|
||||
{% for key, label in CATEGORIES.items() %}
|
||||
<a href="/log?cat={{ key }}" {% if cat == key %}aria-current="true"{% endif %}><span class="dot cat-{{ key }}"></span>{{ label }}</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
|
||||
{% for day, events, st in days %}
|
||||
<section class="day">
|
||||
<div class="day-head">
|
||||
<h2>{{ f.day(day, today) }} <span class="muted">{{ day.strftime('%b') }} {{ day.day }}</span></h2>
|
||||
<p class="muted small">
|
||||
{{ st.feeds }} feed{{ '' if st.feeds == 1 else 's' }} ·
|
||||
{{ f.duration(st.sleep_min * 60) if st.sleep_min else '0m' }} sleep ·
|
||||
{{ st.wet }} wet · {{ st.dirty }} dirty
|
||||
</p>
|
||||
</div>
|
||||
{% if events %}
|
||||
<ul class="events card">
|
||||
{% for ev in events %}{{ ui.event_row(ev, f, now) }}{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="muted empty card">Nothing logged{% if cat %} in {{ CATEGORIES[cat] | lower }}{% endif %}.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endfor %}
|
||||
|
||||
<nav class="pager">
|
||||
{% if newer %}<a class="btn btn-ghost" href="/log?before={{ newer }}{% if cat %}&cat={{ cat }}{% endif %}">← Newer</a>{% else %}<span></span>{% endif %}
|
||||
<a class="btn btn-ghost" href="/log?before={{ older }}{% if cat %}&cat={{ cat }}{% endif %}">Older →</a>
|
||||
</nav>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,15 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Log in{% endblock %}
|
||||
{% block content %}
|
||||
<section class="card login">
|
||||
<h1>Welcome back</h1>
|
||||
<form method="post" action="/login">
|
||||
<input type="hidden" name="next" value="{{ next }}">
|
||||
<label>Password
|
||||
<input type="password" name="password" autocomplete="current-password" required autofocus>
|
||||
</label>
|
||||
{% if error %}<p class="form-error" role="alert">{{ error }}</p>{% endif %}
|
||||
<button class="btn btn-wide">Log in</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,122 @@
|
||||
{# Reusable pieces. Import with: {% import "macros.html" as ui %} #}
|
||||
|
||||
{% macro alerts(items) %}
|
||||
{% for a in items %}
|
||||
<div class="alert alert-{{ a.level }}" role="{{ 'alert' if a.level == 'serious' else 'status' }}">
|
||||
<span class="alert-icon" aria-hidden="true">{{ {'info': 'i', 'warning': '!', 'serious': '!!'}[a.level] }}</span>
|
||||
<span><strong class="alert-label">{{ {'info': 'Note', 'warning': 'Heads up', 'serious': 'Important'}[a.level] }}:</strong>
|
||||
{{ a.text }}{% if a.href %} <a href="{{ a.href }}">{{ a.link_text or 'Details' }}</a>{% endif %}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
{% macro event_row(ev, f, now, show_day=false) %}
|
||||
<li class="ev{% if ev.is_open %} is-open{% endif %}">
|
||||
<time datetime="{{ ev.started_at.isoformat() }}">{% if show_day %}<span class="muted">{{ f.day(ev.started_at) }}</span> {% endif %}{{ f.time(ev.started_at) }}</time>
|
||||
<span class="dot cat-{{ ev.kind.category }}" aria-hidden="true"></span>
|
||||
<span class="ev-main">
|
||||
<span class="ev-title"><span class="emoji" aria-hidden="true">{{ ev.kind.emoji }}</span> {{ ev.kind.label }}</span>
|
||||
{% if ev.kind.is_duration %}
|
||||
{% if ev.ended_at %}<span class="muted">until {{ f.time(ev.ended_at) }} · {{ f.duration(ev.duration.total_seconds()) }}</span>
|
||||
{% else %}<span class="badge badge-live">in progress · <span data-since="{{ f.unix(ev.started_at) }}">{{ f.duration((now - ev.started_at).total_seconds()) }}</span></span>{% endif %}
|
||||
{% endif %}
|
||||
{% if ev.note %}<span class="note">{{ ev.note }}</span>{% endif %}
|
||||
</span>
|
||||
<span class="ev-src muted" title="{{ 'From the Mamadachi, button ' ~ ev.button if ev.source == 'device' else 'Added on the website' }}">
|
||||
{%- if ev.source == 'device' %}B{{ ev.button }}{% else %}web{% endif -%}
|
||||
{%- if ev.clock_corrected %} ⏱{% endif -%}
|
||||
</span>
|
||||
<a class="ev-edit" href="/events/{{ ev.id }}" aria-label="Edit {{ ev.kind.label }} at {{ f.time(ev.started_at) }}">Edit</a>
|
||||
</li>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
{% macro rhythm_legend() %}
|
||||
<ul class="legend" aria-label="Legend">
|
||||
<li><span class="lg lg-bar cat-sleep"></span>Sleep</li>
|
||||
<li><span class="lg lg-dot cat-feeding"></span>Feed</li>
|
||||
<li><span class="lg lg-ring cat-diaper"></span>Wet diaper</li>
|
||||
<li><span class="lg lg-diamond cat-diaper"></span>Dirty diaper</li>
|
||||
<li><span class="lg lg-tick cat-other"></span>Other</li>
|
||||
</ul>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
{% macro rhythm_chart(rows, f, compact=false) %}
|
||||
<div class="rhythm{% if compact %} compact{% endif %}">
|
||||
<div class="rh-row rh-axis" aria-hidden="true">
|
||||
<span class="rh-label"></span>
|
||||
<div class="rh-ticks">
|
||||
{% for h in [0, 6, 12, 18] %}<span style="left: {{ h / 24 * 100 }}%">{{ f.hour_label(h) }}</span>{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% for row in rows %}
|
||||
<div class="rh-row">
|
||||
<span class="rh-label">{% if not compact %}{{ f.day_short(row.day) }}{% endif %}</span>
|
||||
<div class="rh-track">
|
||||
{% for m in row.marks %}
|
||||
{% if m.shape == 'bar' %}
|
||||
<span class="m m-bar cat-{{ m.cat }}{% if m.open %} m-open{% endif %}" style="left: {{ '%.2f' % m.left }}%; width: {{ '%.2f' % m.width }}%" data-tip="{{ m.tip }}"></span>
|
||||
{% else %}
|
||||
<span class="m m-{{ m.shape }} cat-{{ m.cat }}" style="left: {{ '%.2f' % m.left }}%" data-tip="{{ m.tip }}"></span>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if row.now_pct is not none %}<span class="m-now" style="left: {{ '%.2f' % row.now_pct }}%" data-tip="Now"></span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
{% macro column_chart(c) %}
|
||||
<figure class="card chart">
|
||||
<figcaption>
|
||||
<h3><span class="key cat-{{ c.cat }}" aria-hidden="true"></span>{{ c.title }}</h3>
|
||||
<p class="muted">{{ c.summary }}</p>
|
||||
</figcaption>
|
||||
<div class="cols" role="img" aria-label="{{ c.title }}: {% for col in c.columns %}{{ col.tip }}{% if not loop.last %}; {% endif %}{% endfor %}">
|
||||
<div class="cols-plot">
|
||||
{% for t in c.ticks %}<span class="gridline" style="bottom: {{ t.pct }}%"><em>{{ t.label }}</em></span>{% endfor %}
|
||||
<div class="cols-bars">
|
||||
{% for col in c.columns %}
|
||||
<div class="col" data-tip="{{ col.tip }}">
|
||||
<div class="col-bar cat-{{ c.cat }}{% if col.value == 0 %} is-zero{% endif %}{% if col.partial %} is-partial{% endif %}" style="height: {{ '%.2f' % col.height }}%">
|
||||
{% if col.show_value %}<b>{{ col.display }}</b>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% set n = c.columns | length %}
|
||||
{% set step = 1 if n <= 7 else (2 if n <= 14 else 5) %}
|
||||
<div class="cols-x">
|
||||
{% for col in c.columns %}<span>{% if (n - 1 - loop.index0) % step == 0 %}{{ col.label }}{% endif %}</span>{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</figure>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
{% macro battery_chart(c) %}
|
||||
{% if c.empty %}
|
||||
<p class="muted empty">No battery readings in this period yet.</p>
|
||||
{% else %}
|
||||
<div class="line" data-line>
|
||||
<div class="line-plot">
|
||||
{% for t in c.yticks %}<span class="gridline" style="bottom: {{ '%.2f' % t.pct }}%"><em>{{ t.label }}</em></span>{% endfor %}
|
||||
<svg viewBox="0 0 1000 300" preserveAspectRatio="none" aria-hidden="true">
|
||||
<path class="line-area" d="{{ c.area }}"></path>
|
||||
<path class="line-path" d="{{ c.path }}"></path>
|
||||
</svg>
|
||||
<span class="line-cross" hidden></span>
|
||||
<span class="line-dot" hidden></span>
|
||||
<script type="application/json">[{% for p in c.points %}[{{ p.x / 10 }}, {{ 100 - p.y / 3 }}, {{ p.tip | tojson }}]{% if not loop.last %},{% endif %}{% endfor %}]</script>
|
||||
</div>
|
||||
<div class="line-x" aria-hidden="true">
|
||||
{% for t in c.xticks %}<span style="left: {{ '%.2f' % t.pct }}%">{{ t.label }}</span>{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endmacro %}
|
||||
@@ -0,0 +1,103 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Settings{% endblock %}
|
||||
{% block content %}
|
||||
<section class="card" id="profile">
|
||||
<h2>Baby</h2>
|
||||
<form method="post" action="/settings/profile" class="form-grid">
|
||||
<label>Name
|
||||
<input type="text" name="baby_name" value="{{ profile.baby_name }}" maxlength="80" required>
|
||||
</label>
|
||||
<label>Birth date
|
||||
<input type="date" name="birth_date" value="{{ profile.birth_date.isoformat() if profile.birth_date else '' }}">
|
||||
</label>
|
||||
<label>Timezone
|
||||
<select name="timezone" data-tz-select>
|
||||
{% for z in zones %}<option {% if z == profile.timezone %}selected{% endif %}>{{ z }}</option>{% endfor %}
|
||||
{% if profile.timezone not in zones %}<option selected>{{ profile.timezone }}</option>{% endif %}
|
||||
</select>
|
||||
</label>
|
||||
<label><span>Device sync interval <span class="muted">(minutes)</span></span>
|
||||
<input type="number" name="sync_interval_min" value="{{ profile.sync_interval_min }}" min="5" max="1440" step="5">
|
||||
</label>
|
||||
<label class="check span-2">
|
||||
<input type="checkbox" name="clock_24h" value="true" {% if profile.clock_24h %}checked{% endif %}>
|
||||
24-hour clock
|
||||
</label>
|
||||
<div class="span-2"><button class="btn">Save</button></div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="card" id="buttons">
|
||||
<h2>Buttons</h2>
|
||||
<p class="muted small">What each button on the Mamadachi logs (SW1–SW8 on the board). Changes reach the device at its next sync; presses already logged keep their type.</p>
|
||||
<form method="post" action="/settings/buttons">
|
||||
<div class="button-grid">
|
||||
{% for n, k in buttons.items() %}
|
||||
<label class="button-slot">
|
||||
<span class="button-num">{{ n }}</span>
|
||||
<select name="button_{{ n }}">
|
||||
<option value="">— unassigned —</option>
|
||||
{% for kind in kinds if kind.active or (k and kind.slug == k.slug) %}
|
||||
<option value="{{ kind.slug }}" {% if k and kind.slug == k.slug %}selected{% endif %}>{{ kind.emoji }} {{ kind.label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<button class="btn">Save layout</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="card" id="kinds">
|
||||
<h2>Event types</h2>
|
||||
<p class="muted small">
|
||||
<strong>Single press</strong>: each press is one event (a diaper).
|
||||
<strong>Start / stop</strong>: the first press starts it, the next ends it (sleep). If a start is older than <em>auto-close</em> minutes, the next press starts a new one instead, so a forgotten stop doesn't become a 2-day nap.
|
||||
</p>
|
||||
<form method="post" action="/settings/kinds">
|
||||
<div class="kinds">
|
||||
{% for k in kinds %}
|
||||
<fieldset class="kind-row{% if not k.active %} is-hidden{% endif %}">
|
||||
<legend><span class="dot cat-{{ k.category }}"></span>{{ categories[k.category] }}</legend>
|
||||
<label class="k-emoji">Icon<input type="text" name="{{ k.slug }}__emoji" value="{{ k.emoji }}" maxlength="8"></label>
|
||||
<label class="k-label">Name<input type="text" name="{{ k.slug }}__label" value="{{ k.label }}" maxlength="40" required></label>
|
||||
<label class="k-short">On device<input type="text" name="{{ k.slug }}__short" value="{{ k.short }}" maxlength="10"></label>
|
||||
<label class="k-mode">Press
|
||||
<select name="{{ k.slug }}__mode">
|
||||
<option value="instant" {% if not k.is_duration %}selected{% endif %}>Single press</option>
|
||||
<option value="duration" {% if k.is_duration %}selected{% endif %}>Start / stop</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="k-max"><span>Auto-close <span class="muted">min</span></span><input type="number" name="{{ k.slug }}__max" value="{{ k.max_minutes or '' }}" min="1" max="2880"></label>
|
||||
<label class="check k-active"><input type="checkbox" name="{{ k.slug }}__active" {% if k.active %}checked{% endif %} {% if k.slug == 'other' %}disabled checked{% endif %}> Show</label>
|
||||
</fieldset>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<button class="btn">Save types</button>
|
||||
</form>
|
||||
|
||||
<details class="add-kind">
|
||||
<summary><h3>Add a type</h3></summary>
|
||||
<form method="post" action="/settings/kinds/new" class="form-grid">
|
||||
<label>Name<input type="text" name="label" maxlength="40" required placeholder="e.g. Vitamin D"></label>
|
||||
<label><span>Icon <span class="muted">(an emoji)</span></span><input type="text" name="emoji" maxlength="8"></label>
|
||||
<label>Group
|
||||
<select name="category">{% for key, label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||
</label>
|
||||
<label>Press
|
||||
<select name="mode"><option value="instant">Single press</option><option value="duration">Start / stop</option></select>
|
||||
</label>
|
||||
<div class="span-2"><button class="btn">Add type</button></div>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section class="card" id="data">
|
||||
<h2>Your data</h2>
|
||||
<ul class="plain links">
|
||||
<li><a href="/api/v1/export.csv">Download every event as a spreadsheet (CSV)</a></li>
|
||||
<li><a href="/api/v1/export.json">Download a full backup (JSON)</a></li>
|
||||
<li><a href="/docs">API documentation</a> <span class="muted small">for scripts and the firmware</span></li>
|
||||
</ul>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,123 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "macros.html" as ui %}
|
||||
{% block content %}
|
||||
<div data-autorefresh="120">
|
||||
{{ ui.alerts(s.alerts) }}
|
||||
|
||||
<section class="hero card">
|
||||
<div class="hero-main">
|
||||
<p class="eyebrow">Since last feed</p>
|
||||
{% if s.last_feed %}
|
||||
<p class="hero-num" data-since="{{ f.unix(s.last_feed.start) }}">{{ f.duration((s.now - s.last_feed.start).total_seconds()) }}</p>
|
||||
<p class="muted">{{ s.last_feed.label }} · started {{ f.when(s.last_feed.start) if f.local(s.last_feed.start).date() != today else f.time(s.last_feed.start) }}
|
||||
{% if s.feed_interval_min %}<br>Usually every {{ f.duration(s.feed_interval_min * 60) }} this week{% endif %}</p>
|
||||
{% else %}
|
||||
<p class="hero-num">–</p>
|
||||
<p class="muted">No feeds logged yet.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if s.next_side %}
|
||||
<div class="next-side">
|
||||
<span class="eyebrow">Next side</span>
|
||||
<strong>{{ 'Left' if s.next_side == 'L' else 'Right' }}</strong>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% set running = s.open | rejectattr("kind.category", "equalto", "sleep") | list %}
|
||||
{% if running %}
|
||||
<section class="card running">
|
||||
<h2>In progress</h2>
|
||||
<ul class="plain">
|
||||
{% for ev in running %}
|
||||
<li>
|
||||
<span><span class="emoji" aria-hidden="true">{{ ev.kind.emoji }}</span> {{ ev.kind.label }} since {{ f.time(ev.started_at) }}
|
||||
· <strong data-since="{{ f.unix(ev.started_at) }}">{{ f.duration((s.now - ev.started_at).total_seconds()) }}</strong></span>
|
||||
<form method="post" action="/events/{{ ev.id }}/end"><input type="hidden" name="next" value="/"><button class="btn btn-small">End now</button></form>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<section class="tiles" aria-label="Today so far">
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-sleep"></span>{% if s.sleeping %}Asleep{% else %}Awake{% endif %}</p>
|
||||
{% if s.sleeping %}
|
||||
<p class="tile-value" data-since="{{ f.unix(s.sleeping.started_at) }}">{{ f.duration((s.now - s.sleeping.started_at).total_seconds()) }}</p>
|
||||
<p class="tile-sub">since {{ f.time(s.sleeping.started_at) }}</p>
|
||||
{% elif s.last_sleep and s.last_sleep.ended_at %}
|
||||
<p class="tile-value" data-since="{{ f.unix(s.last_sleep.ended_at) }}">{{ f.duration((s.now - s.last_sleep.ended_at).total_seconds()) }}</p>
|
||||
<p class="tile-sub">woke at {{ f.time(s.last_sleep.ended_at) }}</p>
|
||||
{% else %}
|
||||
<p class="tile-value">–</p><p class="tile-sub">no sleep logged</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-sleep"></span>Sleep today</p>
|
||||
<p class="tile-value">{{ f.duration(s.today.sleep_min * 60) if s.today.sleep_min else '0m' }}</p>
|
||||
<p class="tile-sub">{% if s.avg.sleep_min is not none %}7-day avg {{ f.duration(s.avg.sleep_min * 60) }}{% else %} {% endif %}</p>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-feeding"></span>Feeds today</p>
|
||||
<p class="tile-value">{{ s.today.feeds }}</p>
|
||||
<p class="tile-sub">{% if s.avg.feeds is not none %}7-day avg {{ '%.1f' % s.avg.feeds }}{% else %} {% endif %}</p>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-diaper"></span>Diapers today</p>
|
||||
<p class="tile-value">{{ s.today.wet }} <small>wet</small> · {{ s.today.dirty }} <small>dirty</small></p>
|
||||
<p class="tile-sub">{% if s.avg.wet is not none %}7-day avg {{ '%.1f' % s.avg.wet }} · {{ '%.1f' % s.avg.dirty }}{% else %} {% endif %}
|
||||
{% if s.last_diaper %}<br>last {{ f.ago(s.last_diaper.started_at, s.now) }}{% endif %}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>Log now</h2>
|
||||
<p class="muted small">Same as pressing the button on the Mamadachi.</p>
|
||||
</div>
|
||||
<div class="quick">
|
||||
{% for k in quick %}
|
||||
<form method="post" action="/quick">
|
||||
<input type="hidden" name="kind" value="{{ k.slug }}">
|
||||
<input type="hidden" name="next" value="/">
|
||||
<button class="quick-btn cat-{{ k.category }}{% if k.slug in open_slugs %} is-open{% endif %}">
|
||||
<span class="emoji" aria-hidden="true">{{ k.emoji }}</span>
|
||||
<span>{% if k.slug in open_slugs %}End {{ k.label | lower }}{% else %}{{ k.label }}{% endif %}</span>
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>Today</h2>
|
||||
{{ ui.rhythm_legend() }}
|
||||
</div>
|
||||
{{ ui.rhythm_chart([row], f, compact=true) }}
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>Recent</h2>
|
||||
<a href="/log" class="small">Full log →</a>
|
||||
</div>
|
||||
{% if s.recent %}
|
||||
<ul class="events">
|
||||
{% for ev in s.recent %}{{ ui.event_row(ev, f, s.now, show_day=(f.local(ev.started_at).date() != today)) }}{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="muted empty">Nothing yet. Press a button on the Mamadachi, or tap one above.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if s.device %}
|
||||
<p class="device-chip muted">
|
||||
<a href="/device">{{ s.device.name }}</a> ·
|
||||
{% if s.device.last_seen_at %}synced <span data-ago="{{ f.unix(s.device.last_seen_at) }}">{{ f.ago(s.device.last_seen_at, s.now) }}</span>{% else %}never synced{% endif %}
|
||||
{% if s.device.battery_mv %} · battery {{ s.device.battery_mv | battery_pct }}%{% if s.device.charging %} (charging){% endif %}{% endif %}
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,73 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "macros.html" as ui %}
|
||||
{% block title %}Trends{% endblock %}
|
||||
{% block content %}
|
||||
<nav class="segmented" aria-label="Date range">
|
||||
{% for r in ranges %}
|
||||
<a href="/trends?days={{ r }}" {% if r == days %}aria-current="true"{% endif %}>Last {{ r }} days</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
|
||||
<section class="tiles" aria-label="Averages">
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-feeding"></span>Feeds a day</p>
|
||||
<p class="tile-value">{{ '%.1f' % avg.feeds if avg.feeds is not none else '–' }}</p>
|
||||
<p class="tile-sub">average, full days only</p>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-feeding"></span>Between feeds</p>
|
||||
<p class="tile-value">{{ f.duration(median_interval * 60) if median_interval else '–' }}</p>
|
||||
<p class="tile-sub">typical (median), start to start</p>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-sleep"></span>Sleep a day</p>
|
||||
<p class="tile-value">{{ f.duration(avg.sleep_min * 60) if avg.sleep_min is not none else '–' }}</p>
|
||||
<p class="tile-sub">average, full days only</p>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<p class="tile-label"><span class="dot cat-sleep"></span>Longest sleep</p>
|
||||
<p class="tile-value">{{ f.duration(longest.longest_sleep_min * 60) if longest else '–' }}</p>
|
||||
<p class="tile-sub">{{ f.day(longest.day, today) if longest else 'none yet' }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div>
|
||||
<h2>Daily rhythm</h2>
|
||||
<p class="muted small">Each row is one day, midnight to midnight. Hover or tap a mark for details.</p>
|
||||
</div>
|
||||
{{ ui.rhythm_legend() }}
|
||||
</div>
|
||||
{{ ui.rhythm_chart(rows, f) }}
|
||||
</section>
|
||||
|
||||
<div class="chart-grid">
|
||||
{% for c in charts %}{{ ui.column_chart(c) }}{% endfor %}
|
||||
</div>
|
||||
|
||||
<section class="card">
|
||||
<details>
|
||||
<summary><h2>Table</h2><span class="muted small">The same numbers, day by day</span></summary>
|
||||
<div class="table-scroll">
|
||||
<table class="num-table">
|
||||
<thead><tr><th scope="col">Day</th><th scope="col">Feeds</th><th scope="col">Sleep</th><th scope="col">Longest</th><th scope="col">Wet</th><th scope="col">Dirty</th><th scope="col">Pumping</th></tr></thead>
|
||||
<tbody>
|
||||
{% for d in stats %}
|
||||
<tr>
|
||||
<th scope="row">{{ f.day(d.day, today) }}{% if (today - d.day).days >= 7 %}{% else %} <span class="muted">{{ d.day.strftime('%b') }} {{ d.day.day }}</span>{% endif %}</th>
|
||||
<td>{{ d.feeds }}</td>
|
||||
<td>{{ f.duration(d.sleep_min * 60) if d.sleep_min else '–' }}</td>
|
||||
<td>{{ f.duration(d.longest_sleep_min * 60) if d.longest_sleep_min else '–' }}</td>
|
||||
<td>{{ d.wet }}</td>
|
||||
<td>{{ d.dirty }}</td>
|
||||
<td>{{ d.pump }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="muted small">A feed is every feeding press within {{ 30 }} minutes of the one before (left then right side counts once). Sleep that crosses midnight counts toward both days.</p>
|
||||
</details>
|
||||
</section>
|
||||
{% endblock %}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
"""Time helpers. Everything is stored in UTC; local time is only for display
|
||||
and for deciding where "today" starts in the family's timezone."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def from_unix(ts: int | float) -> datetime:
|
||||
return datetime.fromtimestamp(ts, timezone.utc)
|
||||
|
||||
|
||||
def unix(dt: datetime) -> int:
|
||||
return int(dt.timestamp())
|
||||
|
||||
|
||||
def safe_zone(name: str | None) -> ZoneInfo:
|
||||
try:
|
||||
return ZoneInfo(name or "UTC")
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
return ZoneInfo("UTC")
|
||||
|
||||
|
||||
def is_valid_zone(name: str) -> bool:
|
||||
try:
|
||||
ZoneInfo(name)
|
||||
return True
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def zone_choices() -> list[str]:
|
||||
return sorted(z for z in available_timezones() if "/" in z and not z.startswith(("Etc/", "SystemV/")))
|
||||
|
||||
|
||||
def local_day_start(d: date, tz: ZoneInfo) -> datetime:
|
||||
"""Local midnight of `d`, in UTC. DST-safe: zoneinfo picks the right offset."""
|
||||
return datetime.combine(d, time.min, tzinfo=tz).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def local_day_bounds(d: date, tz: ZoneInfo) -> tuple[datetime, datetime]:
|
||||
return local_day_start(d, tz), local_day_start(d + timedelta(days=1), tz)
|
||||
|
||||
|
||||
def local_today(tz: ZoneInfo, now: datetime | None = None) -> date:
|
||||
return (now or utcnow()).astimezone(tz).date()
|
||||
|
||||
|
||||
def parse_local_input(value: str, tz: ZoneInfo) -> datetime | None:
|
||||
"""Parse an <input type="datetime-local"> value ("2026-10-16T13:05") as local time."""
|
||||
value = (value or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
naive = datetime.fromisoformat(value)
|
||||
return naive.replace(tzinfo=tz).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def fmt_duration(seconds: float | None, *, short: bool = False) -> str:
|
||||
"""3h 05m, 45m, 2d 4h. Rounded down to the minute."""
|
||||
if seconds is None:
|
||||
return ""
|
||||
minutes = max(0, int(seconds // 60))
|
||||
days, rem = divmod(minutes, 1440)
|
||||
hours, mins = divmod(rem, 60)
|
||||
if days:
|
||||
return f"{days}d {hours}h"
|
||||
if hours:
|
||||
return f"{hours}h" if short and mins == 0 else f"{hours}h {mins:02d}m"
|
||||
return f"{mins}m"
|
||||
|
||||
|
||||
def baby_age(birth: date | None, today: date) -> str:
|
||||
if birth is None or birth > today:
|
||||
return ""
|
||||
days = (today - birth).days
|
||||
if days < 14:
|
||||
return f"{days} day{'s' if days != 1 else ''} old"
|
||||
if days < 7 * 13:
|
||||
weeks, d = divmod(days, 7)
|
||||
return f"{weeks} weeks" + (f" {d} day{'s' if d != 1 else ''}" if d else "")
|
||||
months = (today.year - birth.year) * 12 + today.month - birth.month - (today.day < birth.day)
|
||||
if months < 24:
|
||||
return f"{months} months"
|
||||
return f"{months // 12} years"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Formatter:
|
||||
"""Per-request display helpers, exposed to templates as `f`."""
|
||||
|
||||
tz: ZoneInfo
|
||||
clock_24h: bool = False
|
||||
|
||||
def local(self, dt: datetime) -> datetime:
|
||||
return dt.astimezone(self.tz)
|
||||
|
||||
def time(self, dt: datetime | None) -> str:
|
||||
if dt is None:
|
||||
return ""
|
||||
lt = self.local(dt)
|
||||
if self.clock_24h:
|
||||
return lt.strftime("%H:%M")
|
||||
return lt.strftime("%I:%M %p").lstrip("0").replace("AM", "am").replace("PM", "pm")
|
||||
|
||||
def hour_label(self, hour: int) -> str:
|
||||
if self.clock_24h:
|
||||
return f"{hour:02d}"
|
||||
h = hour % 12 or 12
|
||||
return f"{h}{'am' if hour % 24 < 12 else 'pm'}"
|
||||
|
||||
def day(self, d: date | datetime, today: date | None = None) -> str:
|
||||
if isinstance(d, datetime):
|
||||
d = self.local(d).date()
|
||||
today = today or local_today(self.tz)
|
||||
if d == today:
|
||||
return "Today"
|
||||
if d == today - timedelta(days=1):
|
||||
return "Yesterday"
|
||||
if (today - d).days < 7:
|
||||
return d.strftime("%A")
|
||||
return f"{d.strftime('%a %b')} {d.day}"
|
||||
|
||||
def day_short(self, d: date) -> str:
|
||||
return f"{d.strftime('%a')[:2]} {d.day}"
|
||||
|
||||
def when(self, dt: datetime | None) -> str:
|
||||
if dt is None:
|
||||
return ""
|
||||
return f"{self.day(dt)}, {self.time(dt)}"
|
||||
|
||||
def input_value(self, dt: datetime | None) -> str:
|
||||
"""Value for <input type="datetime-local">."""
|
||||
return self.local(dt).strftime("%Y-%m-%dT%H:%M") if dt else ""
|
||||
|
||||
def ago(self, dt: datetime | None, now: datetime | None = None) -> str:
|
||||
if dt is None:
|
||||
return "never"
|
||||
secs = ((now or utcnow()) - dt).total_seconds()
|
||||
if secs < 60:
|
||||
return "just now"
|
||||
return f"{fmt_duration(secs)} ago"
|
||||
|
||||
duration = staticmethod(fmt_duration)
|
||||
unix = staticmethod(unix)
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
"""Shared helpers for the HTML pages: templates, login check, flash messages."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import __version__
|
||||
from .config import get_settings
|
||||
from .services.catalog import CATEGORIES, battery_percent, get_profile
|
||||
from .timeutil import Formatter, baby_age, local_today, safe_zone, utcnow
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent
|
||||
|
||||
templates = Jinja2Templates(directory=APP_DIR / "templates")
|
||||
templates.env.globals.update(CATEGORIES=CATEGORIES, app_version=__version__)
|
||||
templates.env.filters["battery_pct"] = battery_percent
|
||||
|
||||
NAV = [
|
||||
("/", "Today"),
|
||||
("/log", "Log"),
|
||||
("/trends", "Trends"),
|
||||
("/device", "Device"),
|
||||
("/settings", "Settings"),
|
||||
]
|
||||
|
||||
|
||||
class LoginRequired(Exception):
|
||||
"""Raised by page routes; turned into a redirect to /login in main.py."""
|
||||
|
||||
|
||||
def is_logged_in(request: Request) -> bool:
|
||||
return not get_settings().login_required or request.session.get("auth") is True
|
||||
|
||||
|
||||
def require_login(request: Request) -> None:
|
||||
if not is_logged_in(request):
|
||||
raise LoginRequired()
|
||||
|
||||
|
||||
def require_api_login(request: Request) -> None:
|
||||
if not is_logged_in(request):
|
||||
raise HTTPException(status_code=401, detail="Log in to the dashboard first.")
|
||||
|
||||
|
||||
def flash(request: Request, text: str, *, level: str = "ok", undo: str | None = None) -> None:
|
||||
"""Show a one-time message on the next page. `undo` is a POST URL for an Undo button."""
|
||||
request.session.setdefault("flash", []).append({"text": text, "level": level, "undo": undo})
|
||||
|
||||
|
||||
def redirect(url: str) -> RedirectResponse:
|
||||
return RedirectResponse(url, status_code=303)
|
||||
|
||||
|
||||
def formatter(db: Session) -> Formatter:
|
||||
profile = get_profile(db)
|
||||
return Formatter(safe_zone(profile.timezone), profile.clock_24h)
|
||||
|
||||
|
||||
def render(request: Request, db: Session, template: str, status_code: int = 200, **ctx: Any) -> HTMLResponse:
|
||||
profile = get_profile(db)
|
||||
f = Formatter(safe_zone(profile.timezone), profile.clock_24h)
|
||||
now = utcnow()
|
||||
today = local_today(f.tz, now)
|
||||
settings = get_settings()
|
||||
base = {
|
||||
"profile": profile,
|
||||
"f": f,
|
||||
"now": now,
|
||||
"today": today,
|
||||
"age": baby_age(profile.birth_date, today),
|
||||
"nav": NAV,
|
||||
"path": request.url.path,
|
||||
"flashes": request.session.pop("flash", []),
|
||||
"logged_in": is_logged_in(request),
|
||||
"login_required": settings.login_required,
|
||||
"is_production": settings.is_production,
|
||||
}
|
||||
base.update(ctx)
|
||||
return templates.TemplateResponse(request, template, base, status_code=status_code)
|
||||
Reference in new issue
Block a user