commit 26875de1ddc9a3a38de66c85e5bdfa5dddc9379c Author: Will Kelly Date: Fri Nov 6 11:42:34 2026 -0500 Initial commit with webpage diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..2093963 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.venv +.env +*.db +*.db-* +__pycache__ +.pytest_cache +tests +tools/.fake_device_state.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5708be --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.venv/ +.env +*.db +*.db-shm +*.db-wal +__pycache__/ +.pytest_cache/ +tools/.fake_device_state.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b9d68f4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +# One image for every host (Render, Fly.io, Railway, a VPS...). +# docker build -t mamadachi-web . +# docker run -p 8000:8000 -e DATABASE_URL=postgresql://... mamadachi-web +FROM python:3.13-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PORT=8000 \ + APP_ENV=production + +WORKDIR /app +COPY requirements.txt . +RUN pip install -r requirements.txt + +COPY alembic.ini ./ +COPY migrations ./migrations +COPY app ./app +COPY tools ./tools + +# Don't run as root inside the container. +RUN useradd --create-home --uid 10001 mamadachi && chown -R mamadachi /app +USER mamadachi + +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD python -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/healthz', timeout=4)" + +# Migrations run inside the app at startup (AUTO_MIGRATE=true). +# --proxy-headers: trust the host's HTTPS proxy so URLs and cookies say https. +CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port ${PORT} --proxy-headers --forwarded-allow-ips='*' --no-server-header"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..a1bb2e3 --- /dev/null +++ b/README.md @@ -0,0 +1,207 @@ +# Mamadachi web: device API, dashboard and database + +One small Python service does three jobs: + +``` + Mamadachi (ESP32-C6) Parent's phone / laptop + │ POST /api/v1/device/sync │ https://…/ (dashboard) + │ (presses + battery, once per wake) │ /api/v1/… (JSON API, CSV export) + ▼ ▼ + ┌──────────────────────────── FastAPI app (app/) ───────────────────────────┐ + │ device_api.py ─ ingest.py ─┐ pages.py / admin.py ─ HTML │ + │ ├─ events.py, stats.py (the shared logic) │ + │ api.py (JSON) ─────────────┘ │ + └──────────────────────────────────┬────────────────────────────────────────┘ + ▼ + Postgres in production (Neon / Supabase) + SQLite file on your computer (web/mamadachi.db) +``` + +* **Dashboard** (mobile-first, dark mode for night feeds, can be added to the home screen): + * **Today**: time since the last feed, which side next, asleep/awake, today's counts against the 7-day average, one-tap logging, and today's timeline. + * **Log**: every event by day. Add, edit, delete and undo. + * **Trends**: a daily-rhythm chart and per-day feeds, sleep and diapers. + * **Device**: battery curve, signal, clock, the sync log and tokens. + * **Settings**: baby profile, timezone, what each of the 8 buttons means, event types, and export. +* **Device API**: one request per wake. It uploads the queued presses and telemetry, and gets back the button labels, the time and what to draw on the e-paper. +* **Database**: 7 tables, versioned with Alembic migrations. They work the same on SQLite and Postgres. + +## Run it on your computer + +From this `web/` folder, in PowerShell: + +```powershell +python -m venv .venv +.venv\Scripts\pip install -r requirements-dev.txt +.venv\Scripts\python -m app.cli seed-demo --days 21 # optional: 3 weeks of fake newborn data +.venv\Scripts\python -m uvicorn app.main:app --reload +``` + +On Linux or macOS, use `python3 -m venv .venv`, then the same commands with `.venv/bin/` in place of `.venv\Scripts\`. + +Open http://127.0.0.1:8000. No password is set locally. The interactive API reference is at http://127.0.0.1:8000/docs. + +* `python -m app.cli reset --yes` deletes the demo data and keeps your settings. +* `python -m app.cli create-device "Proto 1"` prints a device token. The **Device** page can do the same. +* `.venv\Scripts\python -m pytest` runs the test suite (49 tests, a few seconds) on SQLite. Run it before every deploy. +* To run the same tests on real Postgres, the database production uses, start a throwaway one with Docker. **Never point `TEST_DATABASE_URL` at real data: every test empties the tables.** + ```powershell + docker run -d --rm --name pg-test -e POSTGRES_PASSWORD=test -p 55432:5432 postgres:17-alpine + $env:TEST_DATABASE_URL = "postgresql://postgres:test@127.0.0.1:55432/postgres"; .venv\Scripts\python -m pytest + ``` + +### Try the device API without hardware + +`tools/fake_device.py` behaves like the firmware should. It queues presses in a local file and only deletes them after an HTTP 200: + +```powershell +.venv\Scripts\python tools\fake_device.py press 6 # sleep starts +.venv\Scripts\python tools\fake_device.py press 4 --ago 10 # wet diaper 10 min ago +.venv\Scripts\python tools\fake_device.py --token mmd_xxx sync +.venv\Scripts\python tools\fake_device.py --token mmd_xxx sync --clock-off 3600 # RTC an hour slow +``` + +Use `--url https://your-app.onrender.com` to point it at the deployed server. + +## The device protocol (what the firmware needs to do) + +``` +POST /api/v1/device/sync +Authorization: Bearer mmd_… (the device token, in secrets.h) +Content-Type: application/json (required) + +{"device_time": 1760630400, RTC now, UNIX seconds UTC + "firmware": "0.1.0", "battery_mv": 3987, "charging": false, "rssi": -61, + "boot_count": 42, "queue_len": 0, + "events": [{"seq": 101, "time": 1760620000, "button": 6}, …]} ≤ 500 per request +``` + +**The one rule: HTTP 200 means every event you sent is stored, so delete them all. Any other result means keep them and retry later.** Retries are safe, because the server recognises a press it already has (same `seq` and `time`) and skips it. A 401 means the token is wrong or revoked. A 422 is a firmware bug, and the server logs what was wrong with the request. + +What the firmware has to keep: + +* **`seq`**: a per-press counter in NVS. If it resets, nothing breaks: the press time is part of the identity. +* **`time`**: read from the RV-3028's UNIX-time register when the button is pressed. +* **Wrong clock?** The server compares `device_time` with its own clock. If they differ by more than 2 minutes, it shifts the event times and marks them as corrected. The response's `server_time` lets you set the RTC. + +What comes back (abridged): + +```json +{"ok": true, "server_time": 1760630402, "ack_seq": 102, "stored": 2, "duplicates": 0, + "clock_skew_s": 2, "clock_corrected": false, "tz_offset_s": -14400, "sync_interval_s": 3600, + "config_version": "a1b2c3d4", + "buttons": [{"button": 1, "kind": "nurse_left", "short": "Nurse L", "mode": "instant"}, …], + "status": {"baby_name": "Mia", "last_feed": {"kind": "nurse_left", "short": "Nurse L", "time": 1760620000}, + "next_side": "R", "last_diaper": {…}, "open": [{"kind": "sleep", "short": "Sleep", "since": 1760627000}], + "today": {"feeds": 6, "wet": 5, "dirty": 2, "sleep_min": 540}}} +``` + +Every time in the response is a UNIX timestamp. The device works out "Fed 2h 10m ago" from its own RTC, so the e-paper stays correct while the device sleeps. `tz_offset_s` is the offset for displaying local time. Re-draw the button labels only when `config_version` changes. + +**How presses become events.** Each button maps to an event type in **Settings**. A "single press" type (a diaper) logs one event per press. A "start / stop" type (sleep) starts on the first press and ends on the next. If the start is older than the type's auto-close limit (12 h for sleep), the next press starts a new session instead. A forgotten stop is flagged on the dashboard. Unassigned buttons are logged as "Other" rather than dropped. + +**Firmware tips for battery and reliability** + +* Use HTTPS with ESP-IDF's certificate bundle (`esp_crt_bundle_attach`). All the hosts below serve publicly trusted certificates. Set a 10–15 s HTTP timeout. +* Make one request per wake, then sleep. Don't sync on every press: with deep sleep, an hourly sync costs far less than a Wi-Fi join per press. A quick sync after a press, if the device was already awake, is fine. +* After a failure, back off (1 min, 5 min, 30 min…). Never drop the queue. Keep it in flash, not RTC RAM, so a brown-out doesn't lose presses. +* Follow `sync_interval_s`. You can then change the interval in Settings without reflashing. + +## Where to host it + +You need two things: somewhere to **run the app** and a **Postgres database**. Keep them in the same region. My recommendation for this stage: + +| | Service | Cost | Why | +|---|---|---|---| +| **App** | **[Render](https://render.com)**, web service, `0.5c-512mb` instance | ~$7/mo | Push to GitHub and it deploys. HTTPS, logs and environment variables are in a web UI. It never sleeps. | +| **Database** | **[Neon](https://neon.com)**, Free plan | $0 | Real Postgres that never gets paused. It scales to zero when idle and wakes in under a second. It has 0.5 GB storage (years of presses) and 6 h point-in-time restore. | + +**Avoid Render's Free web plan for this.** It sleeps after 15 minutes without traffic and takes about a minute to wake. The device would wait that minute with its radio on, which drains the battery, or time out and retry. The paid instance removes that problem. Render's free Postgres is also deleted after 30 days. + +**Supabase** works as the database too: change the connection string and nothing else. Its table editor is nicer than Neon's, and Supabase Auth is a good option once you add real accounts. The catch is that **free Supabase projects pause after 7 days without activity**. If the device is offline for a week (say, a trip), the next sync fails until someone clicks "restore" in the Supabase dashboard. Use the **Session pooler** connection string (port 5432), because Supabase's direct connection is IPv6-only and many hosts can't reach it. Pro is $25/mo and removes the pause. + +**Fly.io** is the cheaper alternative for the app, at about $2/mo for an always-on 256 MB machine. It's driven from the command line, it can deploy straight from this folder without GitHub, and `fly.toml` is ready. Fly has had no free allowance for new accounts since late 2024. + +### Deploy: Neon + Render, step by step + +1. **Put the project on GitHub.** The Mamadachi folder isn't a git repository yet. Run `git init` at the top level, commit, and push to a **private** GitHub repo. `web/.gitignore` already keeps out `.venv`, `.env` and the local database. +2. **Create the database.** Sign up at neon.com and create a project in **AWS US East 2 (Ohio)**. Copy the connection string. It looks like `postgresql://user:pass@ep-xxx.us-east-2.aws.neon.tech/neondb?sslmode=require`. +3. **Create the app.** In Render, choose **New → Blueprint**, pick the repo and set the blueprint path to `web/render.yaml`. When asked, paste `DATABASE_URL` (from step 2) and pick a `DASHBOARD_PASSWORD`. Render generates `SECRET_KEY` itself. +4. Wait for the first deploy. The app creates its tables on start. Open `https://mamadachi-xxxx.onrender.com` and log in. +5. **Settings**: set the baby's name, birth date and timezone. On the **Device** page, create a token and put it and the URL in the firmware's `secrets.h`. +6. Check it from your computer: `python tools\fake_device.py --url https://… --token mmd_… status`. + +From then on, `git push` deploys. Render runs the new version, waits for `/healthz` to answer, then switches traffic, so a broken build never replaces a working one. + +**Safety checks built in:** in production the app **refuses to start** if `DATABASE_URL` is missing. Otherwise it would quietly write to a SQLite file that the host deletes on every deploy. It also refuses to start if a password is set without a `SECRET_KEY`, and it shows a red banner if there's no dashboard password. + +### CI and the image registry (Gitea) + +`.gitea/workflows/web.yml`, at the top of the repo, runs the tests on SQLite and on Postgres for every push and pull request that touches `web/`. If they pass, it builds the Docker image and pushes it to your Gitea's container registry: + +| You push | Image tags | +|---|---| +| a commit to `main` | `gitea.yourdomain.com//mamadachi-web:sha-1a2b3c4` | +| a tag `v0.2.0` | the same `sha-…` tag, plus `:0.2.0` | +| a pull request | none (tests only) | + +There's deliberately no `:latest`. Your deployment names an exact tag, so you always know what's running and can roll back. + +One-time setup: + +1. **Turn on Actions.** Set `[actions] ENABLED = true` in Gitea's `app.ini` (it's on by default from 1.21), then tick **Actions** in the repo's **Settings**. +2. **Run a runner.** Start an [`act_runner`](https://docs.gitea.com/usage/actions/act-runner) container, for example on the NAS, and register it with a token from **Site Administration → Actions → Runners**. Keep its default `ubuntu-latest` label. Leave `container.docker_host` empty in its config, so jobs can use the host's Docker to build the image. That gives the runner root-level access to the host, which is fine for your own repos only. +3. **Make a token.** Under **User settings → Applications**, create an access token with **package: read and write**. Add it to the repo under **Settings → Actions → Secrets** as `REGISTRY_TOKEN`. +4. **Check Gitea's `ROOT_URL`.** It must be the public HTTPS name, for example `https://gitea.yourdomain.com/`, because the workflow takes the registry host from it. Otherwise, set a repo variable `REGISTRY` to the right host. If the token belongs to someone other than whoever pushes, set a variable `REGISTRY_USER` to the token's owner. +5. **Raise the proxy's upload limit.** On the proxy in front of Gitea (NPMPlus), add `client_max_body_size 0;` under the proxy host's **Advanced** tab. Otherwise pushing an image layer fails with `413`. + +**Releasing:** `git tag v0.2.0 && git push --tags`. Wait for the workflow, change the image tag in the server's compose file, snapshot the data, then redeploy. To roll back, set the previous tag. If the release included a database migration, also restore the snapshot. + +**Pulling on the server:** run `docker login gitea.yourdomain.com` once, with a token that can read packages. Private packages need it. + +## Running it + +* **Changing the database schema:** edit `app/models.py`, then run `.venv\Scripts\alembic revision --autogenerate -m "what changed"`. Read the generated file in `migrations/versions/` and commit it. The app applies new migrations on its next start. A test fails if you forget the migration. +* **Backups:** Neon keeps 6 hours of history on the free plan. For more, download **Settings → Full backup (JSON)** now and then. The more automatic option is a weekly `pg_dump` from a scheduled GitHub Action. **Settings → spreadsheet (CSV)** is the export to hand to a pediatrician or to open in Google Sheets. +* **Logs:** Render → service → Logs. Every sync logs one line, for example `sync device=1 received=3 stored=3 dup=0 skew=2s battery=3987mV rssi=-61`. A bad request from the firmware logs a `422` line with the reason. +* **Health:** `/healthz` shows the process is up. `/readyz` also checks the database. Point a free uptime monitor (UptimeRobot or Better Stack) at `/readyz` to get an email when it's down. + +## What's deliberately simple, and the road to robust + +Built in now: per-device secret tokens (only hashes are stored), a dashboard password with a signed 90-day cookie, HTTPS-only cookies in production, cross-site form protection, idempotent syncs, soft-delete with undo, clock-skew correction, input validation with size limits, health checks, pinned dependencies and tests. + +Before anyone outside your family uses it, roughly in this order: + +1. **Version control and CI.** Use git now. Then add a GitHub Action that runs `pytest` on every push, so Render only deploys code that passes. +2. **Monitoring.** An uptime check on `/readyz`, plus error tracking (Sentry's free tier is 5 lines in `main.py`) so you hear about crashes before a parent does. +3. **Backups you've restored at least once.** A backup you've never restored is a hope, not a backup. +4. **Real accounts and families.** Add a `families` table with a `family_id` on profile, devices, kinds, buttons and events, and filter every query by it. Then add login with email links or passwords: Supabase Auth, Clerk, or FastAPI-Users. That replaces the single `DASHBOARD_PASSWORD`. Add password reset and inviting a partner. +5. **Device claiming.** Typing tokens into `secrets.h` doesn't scale. At manufacture, give each unit a unique ID and secret. The e-paper shows a short pairing code, the parent types it into the website, and the server links the device to their family. For the home Wi-Fi password, use ESP-IDF's Wi-Fi provisioning over BLE. +6. **Abuse protection.** Rate-limit `/login` and `/api/v1/device/sync` (for example with `slowapi`), add CSRF tokens on forms, and lock the CORS policy. +7. **Privacy and law.** This is data about a child's health and routine. Write a privacy policy, let families export and delete everything (export already exists), keep EU users' data in an EU region if you sell there (GDPR), and check the rules for selling a radio device (the external-antenna FCC/CE note in the hardware README). +8. **Over-the-air firmware updates.** Add `firmware_url` and `firmware_version` to the sync response. The device already reports its version, so the server can tell it when to update (ESP-IDF `esp_https_ota`). +9. **Integrations.** The project README mentions Google Sheets. The CSV export and `/api/v1/events` are the starting point. A nightly job could push new rows to a sheet the parent connects with Google OAuth. + +## Layout + +``` +web/ +├── app/ +│ ├── main.py app setup, middleware, health checks, startup migrations +│ ├── config.py settings from environment variables +│ ├── db.py, models.py database connection and tables +│ ├── schemas.py JSON shapes for the APIs (validated, documented at /docs) +│ ├── services/ +│ │ ├── ingest.py device sync: dedupe, clock correction, tokens, response +│ │ ├── events.py press → event rules (start/stop pairing), edits, queries +│ │ ├── stats.py feeds, sleep totals, daily stats, rhythm chart, alerts +│ │ └── catalog.py default event types, button layout, battery curve +│ ├── routes/ device_api, api (JSON), pages + admin (HTML), auth +│ ├── charts.py chart geometry (no JS chart library) +│ ├── templates/, static/ HTML, CSS and a little JS +│ ├── demo.py, cli.py demo data and command-line helpers +├── migrations/ Alembic schema history +├── tests/ pytest: sync rules, stats, pages, auth, migrations +├── tools/fake_device.py device simulator +├── Dockerfile, render.yaml, fly.toml, .env.example +``` diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..1370d72 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,13 @@ +# Alembic = database migrations. The database URL comes from app/config.py +# (DATABASE_URL), not from this file. +# +# alembic upgrade head apply all migrations +# alembic revision --autogenerate -m "add x" after editing app/models.py +# alembic history list migrations +# +# The app also runs `upgrade head` by itself on start (AUTO_MIGRATE=true). + +[alembic] +script_location = %(here)s/migrations +prepend_sys_path = . +file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..ae9744b --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,3 @@ +"""Mamadachi web backend: device API, dashboard and database.""" + +__version__ = "0.1.0" diff --git a/app/charts.py b/app/charts.py new file mode 100644 index 0000000..ca292ca --- /dev/null +++ b/app/charts.py @@ -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) diff --git a/app/cli.py b/app/cli.py new file mode 100644 index 0000000..6500ec9 --- /dev/null +++ b/app/cli.py @@ -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()) diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..be20d11 --- /dev/null +++ b/app/config.py @@ -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() diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000..047f23b --- /dev/null +++ b/app/db.py @@ -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() diff --git a/app/demo.py b/app/demo.py new file mode 100644 index 0000000..95ea340 --- /dev/null +++ b/app/demo.py @@ -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 diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..21cbde4 --- /dev/null +++ b/app/main.py @@ -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) diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..d6dce0c --- /dev/null +++ b/app/models.py @@ -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")) diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routes/admin.py b/app/routes/admin.py new file mode 100644 index 0000000..527eed6 --- /dev/null +++ b/app/routes/admin.py @@ -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") diff --git a/app/routes/api.py b/app/routes/api.py new file mode 100644 index 0000000..6200da3 --- /dev/null +++ b/app/routes/api.py @@ -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}"'}) diff --git a/app/routes/auth.py b/app/routes/auth.py new file mode 100644 index 0000000..52ef58f --- /dev/null +++ b/app/routes/auth.py @@ -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") diff --git a/app/routes/device_api.py b/app/routes/device_api.py new file mode 100644 index 0000000..797491d --- /dev/null +++ b/app/routes/device_api.py @@ -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)) diff --git a/app/routes/pages.py b/app/routes/pages.py new file mode 100644 index 0000000..2d332a9 --- /dev/null +++ b/app/routes/pages.py @@ -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, + ) diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..1dcb937 --- /dev/null +++ b/app/schemas.py @@ -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] diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/services/catalog.py b/app/services/catalog.py new file mode 100644 index 0000000..a058b10 --- /dev/null +++ b/app/services/catalog.py @@ -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 diff --git a/app/services/events.py b/app/services/events.py new file mode 100644 index 0000000..0eca99f --- /dev/null +++ b/app/services/events.py @@ -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() diff --git a/app/services/ingest.py b/app/services/ingest.py new file mode 100644 index 0000000..c0c56ee --- /dev/null +++ b/app/services/ingest.py @@ -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), + ) diff --git a/app/services/stats.py b/app/services/stats.py new file mode 100644 index 0000000..19a4d0f --- /dev/null +++ b/app/services/stats.py @@ -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()) diff --git a/app/static/app.js b/app/static/app.js new file mode 100644 index 0000000..79cc902 --- /dev/null +++ b/app/static/app.js @@ -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(); }); + }); +})(); diff --git a/app/static/icon.svg b/app/static/icon.svg new file mode 100644 index 0000000..8712f98 --- /dev/null +++ b/app/static/icon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/app/static/style.css b/app/static/style.css new file mode 100644 index 0000000..7b2ca0e --- /dev/null +++ b/app/static/style.css @@ -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; } +} diff --git a/app/templates/base.html b/app/templates/base.html new file mode 100644 index 0000000..2774bf7 --- /dev/null +++ b/app/templates/base.html @@ -0,0 +1,72 @@ + + + + + + {% block title %}{{ profile.baby_name if logged_in else "Mamadachi" }}{% endblock %} · Mamadachi + + + + + + + + + + + +
+
+ + + Mamadachi + + {% if logged_in %} +
+ {{ profile.baby_name }}{% if age %} · {{ age }}{% endif %} +
+ {% endif %} +
+ {% if logged_in %} + + {% endif %} +
+ +
+ {% for m in flashes %} +
+ {{ m.text }} + {% if m.undo %} +
+ {% endif %} +
+ {% endfor %} + {% if logged_in %} + + {% endif %} + {% block content %}{% endblock %} +
+ +
+ Mamadachi {{ app_version }} + {% if logged_in %} + API + {% if login_required %} +
+ {% endif %} + {% endif %} +
+ + + diff --git a/app/templates/device.html b/app/templates/device.html new file mode 100644 index 0000000..41af730 --- /dev/null +++ b/app/templates/device.html @@ -0,0 +1,119 @@ +{% extends "base.html" %} +{% import "macros.html" as ui %} +{% block title %}Device{% endblock %} +{% block content %} + +{% if new_token %} +
+

Token for {{ new_device.name }}

+

Copy it now: it is shown only once. If you lose it, rotate it to get a new one.

+
+ {{ new_token }} + +
+

Put it in the firmware's secrets.h, next to the Wi-Fi credentials:

+
#define MAMADACHI_SYNC_URL "{{ base_url }}/api/v1/device/sync"
+#define MAMADACHI_TOKEN    "{{ new_token }}"
+

Or test it from your computer, pretending to be the device:

+
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
+
+{% endif %} + +{% for c in cards %} +{% set dev = c.dev %} +
+
+

{{ dev.name }}

+ {{ 'Active' if dev.active else 'Revoked' }} +
+
+
Last sync
{% if dev.last_seen_at %}{{ f.ago(dev.last_seen_at, now) }}{% else %}never{% endif %}
+
Battery
{% if dev.battery_mv %}{{ c.battery_pct }}% {{ '%.2f' % (dev.battery_mv / 1000) }} V{% if dev.charging %} · charging{% endif %}{% else %}–{% endif %}
+
Wi-Fi signal
{% if dev.rssi is not none %}{{ c.signal }} {{ dev.rssi }} dBm{% else %}–{% endif %}
+
Firmware
{{ dev.firmware or '–' }}
+
Clock
{% if dev.clock_skew_s is none %}–{% elif dev.clock_skew_s|abs <= 120 %}in sync {{ dev.clock_skew_s }} s{% else %}off by {{ f.duration(dev.clock_skew_s|abs) }}{% endif %}
+
Presses received
{{ c.presses }}
+
Boots
{{ dev.boot_count if dev.boot_count is not none else '–' }}
+
Token
mmd_…{{ dev.token_hint }}
+
+ +

Battery, last {{ battery_days }} days

+ {{ ui.battery_chart(c.chart) }} + + {% if c.log %} +
+

Recent syncs

+
+ + + + {% for r in c.log %} + + + + + + + + + {% endfor %} + +
WhenPressesBatterySignalClockServer time
{{ f.when(r.received_at) }}{{ r.events_new }}{% if r.events_received != r.events_new %} ({{ r.events_received - r.events_new }} repeat){% endif %}{{ '%.2f V' % (r.battery_mv / 1000) if r.battery_mv else '–' }}{{ r.rssi if r.rssi is not none else '–' }}{{ '%+d s' % r.clock_skew_s if r.clock_skew_s is not none else '–' }}{{ r.duration_ms if r.duration_ms is not none else '–' }} ms
+
+
+ {% endif %} + +
+
+ + +
+
+ +
+ {% if dev.active %} +
+ +
+ {% endif %} +
+
+{% endfor %} + +
+

{{ 'Add a device' if cards else 'Connect your Mamadachi' }}

+

Each device gets its own secret token. It sends it with every sync, so the server knows the presses are really from your Mamadachi.

+
+ + +
+
+ +
+
+

How the device syncs

For firmware work
+
    +
  1. Every press is queued on the device with a seq (a counter kept in NVS, +1 per press), the time from the RV-3028 (UNIX seconds, UTC) and the button number (1–8).
  2. +
  3. 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 one HTTPS request:
  4. +
+
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}]}
+
    +
  1. HTTP 200: 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.
  2. +
  3. The response carries server_time (set the RTC if it drifted), tz_offset_s (to show local time), the buttons layout with short labels for the e-paper, and a status block: last feed, next side, ongoing sleep, today's counts.
  4. +
  5. Send at most 500 events per request. If more are queued, sync again right away.
  6. +
+

Current layout: + {% for n, k in buttons.items() %}{{ n }}: {{ k.short if k else '–' }} {% endfor %} +

+

Full field reference: API docs.

+
+
+{% endblock %} diff --git a/app/templates/error.html b/app/templates/error.html new file mode 100644 index 0000000..3de5ee0 --- /dev/null +++ b/app/templates/error.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} +{% block title %}{{ code }}{% endblock %} +{% block content %} + +{% endblock %} diff --git a/app/templates/event_edit.html b/app/templates/event_edit.html new file mode 100644 index 0000000..d3a7667 --- /dev/null +++ b/app/templates/event_edit.html @@ -0,0 +1,48 @@ +{% extends "base.html" %} +{% block title %}Edit {{ ev.kind.label }}{% endblock %} +{% block content %} +

← Back to the log

+ +
+

{{ ev.kind.label }}

+

+ {% 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 %}
⏱ The device's clock was off when this was uploaded, so its time was corrected.{% endif %} + {% if ev.deleted_at %}
Deleted {{ f.when(ev.deleted_at) }}.{% endif %} +

+ +
+ + + + +
+ +
+
+
+ +
+ {% if ev.is_open %} +
+ {% endif %} + {% if ev.deleted_at %} +
+ {% else %} +
+ {% endif %} +
+{% endblock %} diff --git a/app/templates/log.html b/app/templates/log.html new file mode 100644 index 0000000..591bee1 --- /dev/null +++ b/app/templates/log.html @@ -0,0 +1,59 @@ +{% extends "base.html" %} +{% import "macros.html" as ui %} +{% block title %}Log{% endblock %} +{% block content %} +
+
+

Add an event

Forgot the Mamadachi? Log it here.
+
+ + + + +
+
+
+
+ + + +{% for day, events, st in days %} +
+
+

{{ f.day(day, today) }} {{ day.strftime('%b') }} {{ day.day }}

+

+ {{ 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 +

+
+ {% if events %} +
    + {% for ev in events %}{{ ui.event_row(ev, f, now) }}{% endfor %} +
+ {% else %} +

Nothing logged{% if cat %} in {{ CATEGORIES[cat] | lower }}{% endif %}.

+ {% endif %} +
+{% endfor %} + + +{% endblock %} diff --git a/app/templates/login.html b/app/templates/login.html new file mode 100644 index 0000000..cef5aee --- /dev/null +++ b/app/templates/login.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block title %}Log in{% endblock %} +{% block content %} + +{% endblock %} diff --git a/app/templates/macros.html b/app/templates/macros.html new file mode 100644 index 0000000..45ac8c9 --- /dev/null +++ b/app/templates/macros.html @@ -0,0 +1,122 @@ +{# Reusable pieces. Import with: {% import "macros.html" as ui %} #} + +{% macro alerts(items) %} +{% for a in items %} +
+ + {{ {'info': 'Note', 'warning': 'Heads up', 'serious': 'Important'}[a.level] }}: + {{ a.text }}{% if a.href %} {{ a.link_text or 'Details' }}{% endif %} +
+{% endfor %} +{% endmacro %} + + +{% macro event_row(ev, f, now, show_day=false) %} +
  • + + + + {{ ev.kind.label }} + {% if ev.kind.is_duration %} + {% if ev.ended_at %}until {{ f.time(ev.ended_at) }} · {{ f.duration(ev.duration.total_seconds()) }} + {% else %}in progress · {{ f.duration((now - ev.started_at).total_seconds()) }}{% endif %} + {% endif %} + {% if ev.note %}{{ ev.note }}{% endif %} + + + {%- if ev.source == 'device' %}B{{ ev.button }}{% else %}web{% endif -%} + {%- if ev.clock_corrected %} ⏱{% endif -%} + + Edit +
  • +{% endmacro %} + + +{% macro rhythm_legend() %} + +{% endmacro %} + + +{% macro rhythm_chart(rows, f, compact=false) %} +
    + + {% for row in rows %} +
    + {% if not compact %}{{ f.day_short(row.day) }}{% endif %} +
    + {% for m in row.marks %} + {% if m.shape == 'bar' %} + + {% else %} + + {% endif %} + {% endfor %} + {% if row.now_pct is not none %}{% endif %} +
    +
    + {% endfor %} +
    +{% endmacro %} + + +{% macro column_chart(c) %} +
    +
    +

    {{ c.title }}

    +

    {{ c.summary }}

    +
    + +
    +{% endmacro %} + + +{% macro battery_chart(c) %} +{% if c.empty %} +

    No battery readings in this period yet.

    +{% else %} +
    +
    + {% for t in c.yticks %}{{ t.label }}{% endfor %} + + + + +
    + +
    +{% endif %} +{% endmacro %} diff --git a/app/templates/settings.html b/app/templates/settings.html new file mode 100644 index 0000000..a7a08bc --- /dev/null +++ b/app/templates/settings.html @@ -0,0 +1,103 @@ +{% extends "base.html" %} +{% block title %}Settings{% endblock %} +{% block content %} +
    +

    Baby

    +
    + + + + + +
    +
    +
    + +
    +

    Buttons

    +

    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.

    +
    +
    + {% for n, k in buttons.items() %} + + {% endfor %} +
    + +
    +
    + +
    +

    Event types

    +

    + Single press: each press is one event (a diaper). + Start / stop: the first press starts it, the next ends it (sleep). If a start is older than auto-close minutes, the next press starts a new one instead, so a forgotten stop doesn't become a 2-day nap. +

    +
    +
    + {% for k in kinds %} +
    + {{ categories[k.category] }} + + + + + + +
    + {% endfor %} +
    + +
    + +
    +

    Add a type

    +
    + + + + +
    +
    +
    +
    + +
    +

    Your data

    + +
    +{% endblock %} diff --git a/app/templates/today.html b/app/templates/today.html new file mode 100644 index 0000000..31b2719 --- /dev/null +++ b/app/templates/today.html @@ -0,0 +1,123 @@ +{% extends "base.html" %} +{% import "macros.html" as ui %} +{% block content %} +
    +{{ ui.alerts(s.alerts) }} + +
    +
    +

    Since last feed

    + {% if s.last_feed %} +

    {{ f.duration((s.now - s.last_feed.start).total_seconds()) }}

    +

    {{ 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 %}
    Usually every {{ f.duration(s.feed_interval_min * 60) }} this week{% endif %}

    + {% else %} +

    –

    +

    No feeds logged yet.

    + {% endif %} +
    + {% if s.next_side %} +
    + Next side + {{ 'Left' if s.next_side == 'L' else 'Right' }} +
    + {% endif %} +
    + +{% set running = s.open | rejectattr("kind.category", "equalto", "sleep") | list %} +{% if running %} +
    +

    In progress

    +
      + {% for ev in running %} +
    • + {{ ev.kind.label }} since {{ f.time(ev.started_at) }} + · {{ f.duration((s.now - ev.started_at).total_seconds()) }} +
      +
    • + {% endfor %} +
    +
    +{% endif %} + +
    +
    +

    {% if s.sleeping %}Asleep{% else %}Awake{% endif %}

    + {% if s.sleeping %} +

    {{ f.duration((s.now - s.sleeping.started_at).total_seconds()) }}

    +

    since {{ f.time(s.sleeping.started_at) }}

    + {% elif s.last_sleep and s.last_sleep.ended_at %} +

    {{ f.duration((s.now - s.last_sleep.ended_at).total_seconds()) }}

    +

    woke at {{ f.time(s.last_sleep.ended_at) }}

    + {% else %} +

    –

    no sleep logged

    + {% endif %} +
    +
    +

    Sleep today

    +

    {{ f.duration(s.today.sleep_min * 60) if s.today.sleep_min else '0m' }}

    +

    {% if s.avg.sleep_min is not none %}7-day avg {{ f.duration(s.avg.sleep_min * 60) }}{% else %} {% endif %}

    +
    +
    +

    Feeds today

    +

    {{ s.today.feeds }}

    +

    {% if s.avg.feeds is not none %}7-day avg {{ '%.1f' % s.avg.feeds }}{% else %} {% endif %}

    +
    +
    +

    Diapers today

    +

    {{ s.today.wet }} wet · {{ s.today.dirty }} dirty

    +

    {% if s.avg.wet is not none %}7-day avg {{ '%.1f' % s.avg.wet }} · {{ '%.1f' % s.avg.dirty }}{% else %} {% endif %} + {% if s.last_diaper %}
    last {{ f.ago(s.last_diaper.started_at, s.now) }}{% endif %}

    +
    +
    + +
    +
    +

    Log now

    +

    Same as pressing the button on the Mamadachi.

    +
    +
    + {% for k in quick %} +
    + + + +
    + {% endfor %} +
    +
    + +
    +
    +

    Today

    + {{ ui.rhythm_legend() }} +
    + {{ ui.rhythm_chart([row], f, compact=true) }} +
    + +
    +
    +

    Recent

    + Full log → +
    + {% if s.recent %} +
      + {% for ev in s.recent %}{{ ui.event_row(ev, f, s.now, show_day=(f.local(ev.started_at).date() != today)) }}{% endfor %} +
    + {% else %} +

    Nothing yet. Press a button on the Mamadachi, or tap one above.

    + {% endif %} +
    + +{% if s.device %} +

    + {{ s.device.name }} · + {% if s.device.last_seen_at %}synced {{ f.ago(s.device.last_seen_at, s.now) }}{% else %}never synced{% endif %} + {% if s.device.battery_mv %} · battery {{ s.device.battery_mv | battery_pct }}%{% if s.device.charging %} (charging){% endif %}{% endif %} +

    +{% endif %} +
    +{% endblock %} diff --git a/app/templates/trends.html b/app/templates/trends.html new file mode 100644 index 0000000..03b72f8 --- /dev/null +++ b/app/templates/trends.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% import "macros.html" as ui %} +{% block title %}Trends{% endblock %} +{% block content %} + + +
    +
    +

    Feeds a day

    +

    {{ '%.1f' % avg.feeds if avg.feeds is not none else '–' }}

    +

    average, full days only

    +
    +
    +

    Between feeds

    +

    {{ f.duration(median_interval * 60) if median_interval else '–' }}

    +

    typical (median), start to start

    +
    +
    +

    Sleep a day

    +

    {{ f.duration(avg.sleep_min * 60) if avg.sleep_min is not none else '–' }}

    +

    average, full days only

    +
    +
    +

    Longest sleep

    +

    {{ f.duration(longest.longest_sleep_min * 60) if longest else '–' }}

    +

    {{ f.day(longest.day, today) if longest else 'none yet' }}

    +
    +
    + +
    +
    +
    +

    Daily rhythm

    +

    Each row is one day, midnight to midnight. Hover or tap a mark for details.

    +
    + {{ ui.rhythm_legend() }} +
    + {{ ui.rhythm_chart(rows, f) }} +
    + +
    + {% for c in charts %}{{ ui.column_chart(c) }}{% endfor %} +
    + +
    +
    +

    Table

    The same numbers, day by day
    +
    + + + + {% for d in stats %} + + + + + + + + + + {% endfor %} + +
    DayFeedsSleepLongestWetDirtyPumping
    {{ f.day(d.day, today) }}{% if (today - d.day).days >= 7 %}{% else %} {{ d.day.strftime('%b') }} {{ d.day.day }}{% endif %}{{ d.feeds }}{{ f.duration(d.sleep_min * 60) if d.sleep_min else '–' }}{{ f.duration(d.longest_sleep_min * 60) if d.longest_sleep_min else '–' }}{{ d.wet }}{{ d.dirty }}{{ d.pump }}
    +
    +

    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.

    +
    +
    +{% endblock %} diff --git a/app/timeutil.py b/app/timeutil.py new file mode 100644 index 0000000..1188ebc --- /dev/null +++ b/app/timeutil.py @@ -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 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 .""" + 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) diff --git a/app/web.py b/app/web.py new file mode 100644 index 0000000..8d8d4f6 --- /dev/null +++ b/app/web.py @@ -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) diff --git a/fly.toml b/fly.toml new file mode 100644 index 0000000..bcc5be6 --- /dev/null +++ b/fly.toml @@ -0,0 +1,33 @@ +# Fly.io alternative to Render. From this folder: +# fly launch --no-deploy --copy-config (pick a unique app name) +# fly secrets set DATABASE_URL=... DASHBOARD_PASSWORD=... SECRET_KEY=$(python -c "import secrets;print(secrets.token_urlsafe(32))") +# fly deploy +app = "mamadachi" # change to something unique +primary_region = "iad" # Ashburn, next to AWS us-east-1 (put the database there too) + +[build] + dockerfile = "Dockerfile" + +[env] + APP_ENV = "production" + PORT = "8000" + DEFAULT_TIMEZONE = "America/New_York" + +[http_service] + internal_port = 8000 + force_https = true + # Keep one machine running: a cold start would keep the device's radio on longer. + auto_stop_machines = "off" + auto_start_machines = true + min_machines_running = 1 + + [[http_service.checks]] + interval = "30s" + timeout = "5s" + grace_period = "20s" + method = "GET" + path = "/healthz" + +[[vm]] + size = "shared-cpu-1x" + memory = "256mb" diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..e7bc460 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,38 @@ +"""Alembic environment: points migrations at the app's models and database.""" + +import logging + +from alembic import context +from sqlalchemy import create_engine, pool + +from app.config import get_settings +from app.models import Base, alembic_compare_type, alembic_render_item + +if not logging.getLogger().handlers: + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") + +target_metadata = Base.metadata +url = get_settings().database_url + + +def configure(**kw) -> None: # noqa: ANN003 + context.configure( + target_metadata=target_metadata, + render_item=alembic_render_item, + compare_type=alembic_compare_type, + render_as_batch=url.startswith("sqlite"), # SQLite can't ALTER most things in place + **kw, + ) + + +if context.is_offline_mode(): + configure(url=url, literal_binds=True) + with context.begin_transaction(): + context.run_migrations() +else: + engine = create_engine(url, poolclass=pool.NullPool) + with engine.connect() as connection: + configure(connection=connection) + with context.begin_transaction(): + context.run_migrations() + engine.dispose() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..e67e889 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,25 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +${imports if imports else ""} + +revision: str = ${repr(up_revision)} +down_revision: str | None = ${repr(down_revision)} +branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} +depends_on: str | Sequence[str] | None = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/20261016_0001_initial_schema.py b/migrations/versions/20261016_0001_initial_schema.py new file mode 100644 index 0000000..9160cf4 --- /dev/null +++ b/migrations/versions/20261016_0001_initial_schema.py @@ -0,0 +1,150 @@ +"""initial schema + +Revision ID: 0001 +Revises: +Create Date: 2026-10-16 21:39:18.627803 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + + +revision: str = '0001' +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('devices', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=80), nullable=False), + sa.Column('token_hash', sa.String(length=64), nullable=False), + sa.Column('token_hint', sa.String(length=12), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('revoked_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('last_seen_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('firmware', sa.String(length=32), nullable=True), + sa.Column('battery_mv', sa.Integer(), nullable=True), + sa.Column('charging', sa.Boolean(), nullable=True), + sa.Column('rssi', sa.SmallInteger(), nullable=True), + sa.Column('clock_skew_s', sa.Integer(), nullable=True), + sa.Column('boot_count', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id', name=op.f('pk_devices')), + sa.UniqueConstraint('token_hash', name=op.f('uq_devices_token_hash')) + ) + op.create_table('event_kinds', + sa.Column('slug', sa.String(length=32), nullable=False), + sa.Column('label', sa.String(length=40), nullable=False), + sa.Column('short', sa.String(length=12), nullable=False), + sa.Column('emoji', sa.String(length=16), nullable=False), + sa.Column('category', sa.String(length=16), nullable=False), + sa.Column('mode', sa.String(length=10), nullable=False), + sa.Column('max_minutes', sa.Integer(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('active', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('slug', name=op.f('pk_event_kinds')) + ) + op.create_table('profile', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('baby_name', sa.String(length=80), nullable=False), + sa.Column('birth_date', sa.Date(), nullable=True), + sa.Column('timezone', sa.String(length=64), nullable=False), + sa.Column('clock_24h', sa.Boolean(), nullable=False), + sa.Column('sync_interval_min', sa.Integer(), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint('id', name=op.f('pk_profile')) + ) + op.create_table('buttons', + sa.Column('button', sa.SmallInteger(), autoincrement=False, nullable=False), + sa.Column('kind_slug', sa.String(length=32), nullable=True), + sa.ForeignKeyConstraint(['kind_slug'], ['event_kinds.slug'], name=op.f('fk_buttons_kind_slug_event_kinds'), onupdate='CASCADE', ondelete='SET NULL'), + sa.PrimaryKeyConstraint('button', name=op.f('pk_buttons')) + ) + op.create_table('device_reports', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('device_id', sa.Integer(), nullable=False), + sa.Column('received_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('firmware', sa.String(length=32), nullable=True), + sa.Column('battery_mv', sa.Integer(), nullable=True), + sa.Column('charging', sa.Boolean(), nullable=True), + sa.Column('rssi', sa.SmallInteger(), nullable=True), + sa.Column('clock_skew_s', sa.Integer(), nullable=True), + sa.Column('boot_count', sa.Integer(), nullable=True), + sa.Column('queue_len', sa.Integer(), nullable=True), + sa.Column('events_received', sa.Integer(), nullable=False), + sa.Column('events_new', sa.Integer(), nullable=False), + sa.Column('duration_ms', sa.Integer(), nullable=True), + sa.Column('extra', sa.JSON(), nullable=True), + sa.ForeignKeyConstraint(['device_id'], ['devices.id'], name=op.f('fk_device_reports_device_id_devices'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_device_reports')) + ) + with op.batch_alter_table('device_reports', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_device_reports_device_id'), ['device_id'], unique=False) + batch_op.create_index(batch_op.f('ix_device_reports_received_at'), ['received_at'], unique=False) + + op.create_table('events', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('kind_slug', sa.String(length=32), nullable=False), + sa.Column('started_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('ended_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('note', sa.Text(), nullable=True), + sa.Column('source', sa.String(length=8), nullable=False), + sa.Column('device_id', sa.Integer(), nullable=True), + sa.Column('button', sa.SmallInteger(), nullable=True), + sa.Column('clock_corrected', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['device_id'], ['devices.id'], name=op.f('fk_events_device_id_devices'), ondelete='SET NULL'), + sa.ForeignKeyConstraint(['kind_slug'], ['event_kinds.slug'], name=op.f('fk_events_kind_slug_event_kinds'), onupdate='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_events')) + ) + with op.batch_alter_table('events', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_events_deleted_at'), ['deleted_at'], unique=False) + batch_op.create_index('ix_events_kind_open', ['kind_slug', 'ended_at'], unique=False) + batch_op.create_index(batch_op.f('ix_events_kind_slug'), ['kind_slug'], unique=False) + batch_op.create_index(batch_op.f('ix_events_started_at'), ['started_at'], unique=False) + + op.create_table('presses', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('device_id', sa.Integer(), nullable=False), + sa.Column('seq', sa.Integer(), nullable=False), + sa.Column('button', sa.SmallInteger(), nullable=False), + sa.Column('device_time', sa.DateTime(timezone=True), nullable=False), + sa.Column('occurred_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('received_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('clock_corrected', sa.Boolean(), nullable=False), + sa.Column('role', sa.String(length=8), nullable=False), + sa.Column('event_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['device_id'], ['devices.id'], name=op.f('fk_presses_device_id_devices'), ondelete='CASCADE'), + sa.ForeignKeyConstraint(['event_id'], ['events.id'], name=op.f('fk_presses_event_id_events'), ondelete='SET NULL'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_presses')), + sa.UniqueConstraint('device_id', 'seq', 'device_time', name='uq_presses_identity') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('presses') + with op.batch_alter_table('events', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_events_started_at')) + batch_op.drop_index(batch_op.f('ix_events_kind_slug')) + batch_op.drop_index('ix_events_kind_open') + batch_op.drop_index(batch_op.f('ix_events_deleted_at')) + + op.drop_table('events') + with op.batch_alter_table('device_reports', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_device_reports_received_at')) + batch_op.drop_index(batch_op.f('ix_device_reports_device_id')) + + op.drop_table('device_reports') + op.drop_table('buttons') + op.drop_table('profile') + op.drop_table('event_kinds') + op.drop_table('devices') + # ### end Alembic commands ### diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..ecae71c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "mamadachi-web" +version = "0.1.0" +description = "Mamadachi backend: device sync API, dashboard and database" +requires-python = ">=3.12" + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["."] +addopts = "-q" +filterwarnings = ["ignore::DeprecationWarning", "ignore:Using .httpx. with .starlette.testclient."] + +[tool.ruff] +line-length = 120 +target-version = "py312" diff --git a/render.yaml b/render.yaml new file mode 100644 index 0000000..a8b53d9 --- /dev/null +++ b/render.yaml @@ -0,0 +1,29 @@ +# Render Blueprint: one always-on web service, built from web/Dockerfile. +# Render looks for render.yaml at the repo root by default; when you create the +# Blueprint, change the Blueprint path to web/render.yaml (or move this file up a level). +# The database lives elsewhere (Neon / Supabase); paste its URL when Render asks. +services: + - type: web + name: mamadachi + runtime: docker + rootDir: web # only changes under web/ trigger a deploy + dockerfilePath: ./web/Dockerfile # Docker paths are relative to the repo root + dockerContext: ./web + # 0.5 CPU / 512 MB, about $7/mo, never sleeps (formerly called "Starter"). + # Don't use "free": it sleeps after 15 min idle and takes ~1 min to wake, + # so the device would sit with its radio on, burning battery, or time out. + plan: 0.5c-512mb + region: ohio # same AWS region as the database (us-east-2) + healthCheckPath: /healthz + autoDeploy: true # every push to the branch deploys + envVars: + - key: APP_ENV + value: production + - key: DATABASE_URL + sync: false # asked for on first deploy: paste the Postgres URL + - key: DASHBOARD_PASSWORD + sync: false + - key: SECRET_KEY + generateValue: true + - key: DEFAULT_TIMEZONE + value: America/New_York diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..9b5d281 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest==9.1.1 +httpx==0.28.1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c784692 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +# Runtime dependencies, pinned to the versions the tests ran against. +# Upgrade deliberately: bump a pin, run `pytest`, then deploy. +fastapi==0.143.3 +starlette==1.8.0 +uvicorn[standard]==0.54.0 +sqlalchemy==2.1.5 +alembic==1.20.0 +psycopg[binary]==3.3.6 +pydantic==2.14.1 +pydantic-settings==2.16.0 +jinja2==3.1.6 +python-multipart==0.0.32 +itsdangerous==2.2.0 +tzdata==2026.5 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..be2a394 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,67 @@ +import os +import tempfile +from pathlib import Path + +# Point the app at a throwaway database before any app module is imported: +# a temp SQLite file, or TEST_DATABASE_URL to run the suite against Postgres. +# Never point TEST_DATABASE_URL at real data: every test empties the tables. +_TMP = Path(tempfile.mkdtemp(prefix="mamadachi-test-")) +os.environ["DATABASE_URL"] = os.environ.get("TEST_DATABASE_URL") or f"sqlite:///{(_TMP / 'test.db').as_posix()}" +os.environ["DASHBOARD_PASSWORD"] = "" +os.environ["DEFAULT_TIMEZONE"] = "America/New_York" +os.environ["APP_ENV"] = "development" + +import pytest # noqa: E402 +from fastapi.testclient import TestClient # noqa: E402 +from sqlalchemy import delete # noqa: E402 + +from app.config import get_settings # noqa: E402 +from app.db import SessionLocal # noqa: E402 +from app.main import app # noqa: E402 +from app.models import ButtonMap, Device, DeviceReport, Event, Kind, Press, Profile # noqa: E402 +from app.services.catalog import ensure_defaults # noqa: E402 +from app.services.ingest import create_device # noqa: E402 + + +@pytest.fixture(scope="session") +def _app_started(): + with TestClient(app) as c: # runs startup: migrations + defaults + yield c + + +@pytest.fixture +def db(): + s = SessionLocal() + yield s + s.close() + + +@pytest.fixture(autouse=True) +def clean_db(_app_started): + """Every test starts from an empty log and default settings.""" + with SessionLocal() as s: + for model in (Press, Event, DeviceReport, Device, ButtonMap, Kind, Profile): + s.execute(delete(model)) + s.commit() + ensure_defaults(s) + settings = get_settings() + saved = settings.dashboard_password + yield + settings.dashboard_password = saved + + +@pytest.fixture +def client(_app_started): + # Fresh cookies for each test; the app itself stays started. + with TestClient(app, base_url="http://testserver") as c: + yield c + + +@pytest.fixture +def device(db): + dev, token = create_device(db, "Test Mamadachi") + return dev, token + + +def auth(token: str) -> dict: + return {"Authorization": f"Bearer {token}"} diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..d9fec83 --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,14 @@ +"""Catches "edited models.py but forgot the migration".""" + +from alembic.autogenerate import compare_metadata +from alembic.migration import MigrationContext + +from app.db import engine +from app.models import Base, alembic_compare_type + + +def test_migrations_match_models(_app_started): + with engine.connect() as conn: + ctx = MigrationContext.configure(conn, opts={"compare_type": alembic_compare_type}) + diff = compare_metadata(ctx, Base.metadata) + assert diff == [], f"Models and migrations differ; run: alembic revision --autogenerate\n{diff}" diff --git a/tests/test_stats.py b/tests/test_stats.py new file mode 100644 index 0000000..d56f718 --- /dev/null +++ b/tests/test_stats.py @@ -0,0 +1,120 @@ +"""The numbers on the dashboard.""" + +from datetime import date, datetime, timedelta + +import pytest + +from app.charts import nice_ticks +from app.models import Kind +from app.services import events as ev_svc +from app.services.catalog import battery_percent, get_profile +from app.services.stats import build_summary, daily_stats, group_feeds, next_side +from app.timeutil import baby_age, local_day_start, safe_zone, utcnow + +NY = safe_zone("America/New_York") + + +def at(d: date, hour: int, minute: int = 0) -> datetime: + return local_day_start(d, NY) + timedelta(hours=hour, minutes=minute) + + +def press(db, slug, when): + ev, _ = ev_svc.apply_press(db, db.get(Kind, slug), when, source="manual") + db.commit() + return ev + + +def test_left_then_right_is_one_feed(db): + d = date(2026, 10, 1) + press(db, "nurse_left", at(d, 10)) + press(db, "nurse_right", at(d, 10, 15)) + press(db, "bottle", at(d, 13)) + feeds = group_feeds(ev_svc.events_between(db, at(d, 0), at(d, 23))) + assert len(feeds) == 2 + assert feeds[0].sides == ["L", "R"] + assert feeds[0].label == "Nursing L → R" + assert next_side(feeds) == "R" # last nursing feed started on the left + + +def test_sleep_across_midnight_counts_toward_both_days(db): + d = date(2026, 10, 1) + press(db, "sleep", at(d, 22)) + press(db, "sleep", at(d + timedelta(days=1), 6)) + days = daily_stats(db, NY, d, d + timedelta(days=1), now=at(d + timedelta(days=2), 0)) + assert [round(x.sleep_min) for x in days] == [120, 360] + assert days[0].longest_sleep_min == 480 + assert days[0].naps == 1 + + +def test_dst_day_is_25_hours(db): + # US clocks fall back on 2026-11-01, so that local day lasts 25 h. + d = date(2026, 11, 1) + midnight = at(d, 0) + for start, end in [(0, 11), (13, 25)]: # hours after midnight, real elapsed time + press(db, "sleep", midnight + timedelta(hours=start)) + press(db, "sleep", midnight + timedelta(hours=end) - timedelta(minutes=1)) + days = daily_stats(db, NY, d, d, now=midnight + timedelta(days=2)) + assert round(days[0].sleep_min) == 11 * 60 - 1 + 12 * 60 - 1 # nothing clipped at hour 24 + + +def test_forgotten_sleep_is_capped_and_flagged(db): + now = utcnow() + ev = press(db, "sleep", now - timedelta(hours=20)) + assert ev_svc.effective_end(ev, now) == ev.started_at + timedelta(hours=12) + assert ev_svc.is_stale(ev, now) + s = build_summary(db, get_profile(db), now) + assert s.sleeping is None # a stale session doesn't count as asleep + assert any("never stopped" in a.text for a in s.alerts) + + +def test_counts_for_today(db): + now = utcnow() + for minutes in (10, 20, 30): + press(db, "wet", now - timedelta(minutes=minutes)) + press(db, "dirty", now - timedelta(minutes=5)) + s = build_summary(db, get_profile(db), now) + assert (s.today.wet, s.today.dirty) == (3, 1) + assert s.last_diaper.kind_slug == "dirty" + + +def test_deleted_events_are_ignored(db): + now = utcnow() + ev = press(db, "wet", now - timedelta(minutes=10)) + ev_svc.delete_event(db, ev) + assert build_summary(db, get_profile(db), now).today.wet == 0 + ev_svc.restore_event(db, ev) + assert build_summary(db, get_profile(db), now).today.wet == 1 + + +def test_manual_event_validation(db): + sleep = db.get(Kind, "sleep") + now = utcnow() + with pytest.raises(ev_svc.EventError): + ev_svc.create_manual(db, sleep, now + timedelta(hours=2), None, None) + with pytest.raises(ev_svc.EventError): + ev_svc.create_manual(db, sleep, now - timedelta(hours=1), now - timedelta(hours=2), None) + with pytest.raises(ev_svc.EventError): + ev_svc.create_manual(db, db.get(Kind, "wet"), now - timedelta(hours=1), now, None) + + +@pytest.mark.parametrize( + ("mv", "pct"), + [(None, None), (4250, 100), (4200, 100), (3840, 50), (3700, 12), (3270, 0), (3000, 0)], +) +def test_battery_percent(mv, pct): + assert battery_percent(mv) == pct + + +def test_nice_ticks(): + assert nice_ticks(8, integer=True) == [0, 5, 10] + assert nice_ticks(3, integer=True) == [0, 1, 2, 3] + assert nice_ticks(0, integer=True) == [0, 1] + assert nice_ticks(16.8, integer=False) == [0, 10, 20] + + +def test_baby_age(): + born = date(2026, 9, 1) + assert baby_age(born, date(2026, 9, 6)) == "5 days old" + assert baby_age(born, date(2026, 10, 16)) == "6 weeks 3 days" + assert baby_age(born, date(2027, 3, 1)) == "6 months" + assert baby_age(None, date(2026, 10, 16)) == "" diff --git a/tests/test_sync.py b/tests/test_sync.py new file mode 100644 index 0000000..eae9eb4 --- /dev/null +++ b/tests/test_sync.py @@ -0,0 +1,165 @@ +"""The device API: the part the firmware depends on.""" + +from datetime import timedelta + +from sqlalchemy import func, select + +from app.models import Event, Press +from app.timeutil import unix, utcnow +from tests.conftest import auth + +URL = "/api/v1/device/sync" + + +def sync(client, token, events, device_time=None, **extra): + body = {"device_time": device_time if device_time is not None else unix(utcnow()), "events": events, **extra} + return client.post(URL, json=body, headers=auth(token)) + + +def test_needs_a_valid_token(client, device): + assert client.post(URL, json={"events": []}).status_code == 401 + assert client.post(URL, json={"events": []}, headers=auth("mmd_wrong")).status_code == 401 + assert sync(client, device[1], []).status_code == 200 + + +def test_revoked_device_is_rejected(client, db, device): + dev, token = device + dev.revoked_at = utcnow() + db.commit() + assert sync(client, token, []).status_code == 401 + + +def test_stores_presses_once(client, db, device): + _, token = device + t = unix(utcnow() - timedelta(hours=1)) + events = [ + {"seq": 1, "time": t, "button": 4}, + {"seq": 2, "time": t + 60, "button": 5}, + {"seq": 3, "time": t + 120, "button": 3}, + ] + r = sync(client, token, events, battery_mv=3950, rssi=-60, firmware="0.1.0") + assert r.status_code == 200, r.text + body = r.json() + assert (body["received"], body["stored"], body["duplicates"], body["ack_seq"]) == (3, 3, 0, 3) + + # The response got lost and the device retries the same batch: nothing doubles. + r2 = sync(client, token, events) + assert (r2.json()["stored"], r2.json()["duplicates"]) == (0, 3) + assert db.scalar(select(func.count()).select_from(Event)) == 3 + assert db.scalar(select(func.count()).select_from(Press)) == 3 + + +def test_seq_counter_reset_is_not_mistaken_for_a_retry(client, db, device): + _, token = device + t = unix(utcnow() - timedelta(hours=2)) + sync(client, token, [{"seq": 1, "time": t, "button": 4}]) + # Reflashed device: counter starts at 1 again, but it's a new press. + r = sync(client, token, [{"seq": 1, "time": t + 3600, "button": 4}]) + assert r.json()["stored"] == 1 + assert db.scalar(select(func.count()).select_from(Event)) == 2 + + +def test_sleep_presses_pair_into_one_session(client, db, device): + _, token = device + t = unix(utcnow() - timedelta(hours=3)) + r = sync(client, token, [{"seq": 1, "time": t, "button": 6}, {"seq": 2, "time": t + 5400, "button": 6}]) + assert r.json()["stored"] == 2 + sleeps = db.scalars(select(Event).where(Event.kind_slug == "sleep")).all() + assert len(sleeps) == 1 + assert sleeps[0].duration == timedelta(minutes=90) + roles = [p.role for p in db.scalars(select(Press).order_by(Press.seq))] + assert roles == ["start", "end"] + + +def test_sleep_start_and_stop_in_separate_syncs(client, db, device): + _, token = device + t = unix(utcnow() - timedelta(hours=3)) + sync(client, token, [{"seq": 1, "time": t, "button": 6}]) + body = sync(client, token, []).json() + assert [o["kind"] for o in body["status"]["open"]] == ["sleep"] + sync(client, token, [{"seq": 2, "time": t + 3600, "button": 6}]) + ev = db.scalars(select(Event)).one() + assert ev.duration == timedelta(hours=1) + + +def test_forgotten_stop_starts_a_new_session(client, db, device): + _, token = device + t = unix(utcnow() - timedelta(hours=20)) + # 13 h later is past sleep's 12 h auto-close, so this is a new nap, not a 13 h one. + sync(client, token, [{"seq": 1, "time": t, "button": 6}, {"seq": 2, "time": t + 13 * 3600, "button": 6}]) + sleeps = db.scalars(select(Event).order_by(Event.started_at)).all() + assert len(sleeps) == 2 + assert all(s.ended_at is None for s in sleeps) + + +def test_wrong_device_clock_is_corrected(client, db, device): + _, token = device + real_now = utcnow() + device_now = real_now - timedelta(days=1) # RTC lost a day + pressed = device_now - timedelta(hours=1) + r = sync(client, token, [{"seq": 1, "time": unix(pressed), "button": 4}], device_time=unix(device_now)) + body = r.json() + assert body["clock_corrected"] is True + assert abs(body["clock_skew_s"] - 86400) < 5 + assert abs(body["server_time"] - unix(real_now)) < 5 + ev = db.scalars(select(Event)).one() + assert ev.clock_corrected + assert abs((ev.started_at - (real_now - timedelta(hours=1))).total_seconds()) < 5 + + +def test_small_clock_drift_is_left_alone(client, db, device): + _, token = device + now = utcnow() + pressed = unix(now - timedelta(minutes=30)) + r = sync(client, token, [{"seq": 1, "time": pressed, "button": 4}], device_time=unix(now) - 30) + assert r.json()["clock_corrected"] is False + assert unix(db.scalars(select(Event)).one().started_at) == pressed + + +def test_unassigned_button_is_kept_not_dropped(client, db, device): + _, token = device + r = sync(client, token, [{"seq": 1, "time": unix(utcnow()) - 60, "button": 9}]) + assert r.status_code == 200 + ev = db.scalars(select(Event)).one() + assert ev.kind_slug == "other" + assert "Button 9" in ev.note + + +def test_response_tells_the_device_what_to_show(client, device): + _, token = device + t = unix(utcnow() - timedelta(minutes=40)) + body = sync(client, token, [{"seq": 1, "time": t, "button": 1}, {"seq": 2, "time": t + 300, "button": 4}]).json() + assert [b["kind"] for b in body["buttons"]] == [ + "nurse_left", "nurse_right", "bottle", "wet", "dirty", "sleep", "pump", "medicine", + ] + assert body["buttons"][5]["mode"] == "duration" + status = body["status"] + assert status["last_feed"]["kind"] == "nurse_left" + assert status["last_feed"]["time"] == t + assert status["next_side"] == "R" + assert status["last_diaper"]["short"] == "Wet" + assert body["sync_interval_s"] == 3600 + assert body["tz_offset_s"] in (-4 * 3600, -5 * 3600) # America/New_York + assert len(body["config_version"]) == 8 + + +def test_bad_payload_is_a_422(client, device): + _, token = device + r = client.post(URL, json={"events": [{"seq": 1, "time": 5, "button": -1}]}, headers=auth(token)) + assert r.status_code == 422 + r = client.post(URL, json={"events": [{"time": 5, "button": 1}]}, headers=auth(token)) + assert r.status_code == 422 + + +def test_telemetry_is_recorded(client, db, device): + dev, token = device + sync(client, token, [], battery_mv=3800, rssi=-70, charging=True, firmware="0.2.0", diag={"wake": "timer"}) + db.refresh(dev) + assert (dev.battery_mv, dev.rssi, dev.charging, dev.firmware) == (3800, -70, True, "0.2.0") + assert dev.last_seen_at is not None + + +def test_config_endpoint(client, device): + r = client.get("/api/v1/device/config", headers=auth(device[1])) + assert r.status_code == 200 + assert r.json()["received"] == 0 diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..d98ea7e --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,171 @@ +"""The dashboard pages, its JSON API and the login gate.""" + +from datetime import timedelta + +from sqlalchemy import select + +from app.config import get_settings +from app.demo import seed_demo +from app.models import Event +from app.timeutil import utcnow +from tests.conftest import auth + + +def test_every_page_renders_with_demo_data(client, db): + seed_demo(db, days=3) + ev_id = db.scalars(select(Event.id).limit(1)).one() + for url in ["/", "/log", "/log?cat=sleep", "/log?before=2026-01-01", "/trends", "/trends?days=7", + "/trends?days=30", "/device", "/settings", f"/events/{ev_id}"]: + r = client.get(url) + assert r.status_code == 200, url + assert "Since last feed" in client.get("/").text + + +def test_empty_database_renders(client): + for url in ["/", "/log", "/trends", "/device", "/settings"]: + assert client.get(url).status_code == 200, url + + +def test_quick_log_then_undo(client, db): + r = client.post("/quick", data={"kind": "wet", "next": "/"}, follow_redirects=False) + assert r.status_code == 303 + ev = db.scalars(select(Event)).one() + assert ev.source == "manual" and ev.kind_slug == "wet" + + client.post(f"/events/{ev.id}/delete") + db.refresh(ev) + assert ev.deleted_at is not None + client.post(f"/events/{ev.id}/restore") + db.refresh(ev) + assert ev.deleted_at is None + + +def test_quick_log_toggles_sleep(client, db): + client.post("/quick", data={"kind": "sleep"}) + assert db.scalars(select(Event)).one().ended_at is None + client.post("/quick", data={"kind": "sleep"}) + db.expire_all() + assert db.scalars(select(Event)).one().ended_at is not None + + +def test_manual_event_uses_family_timezone(client, db): + # 2026-10-01 13:05 in New York (EDT, UTC-4) is 17:05 UTC. + client.post("/events", data={"kind": "bottle", "started_at": "2026-10-01T13:05", "note": "90 ml"}) + ev = db.scalars(select(Event)).one() + assert ev.started_at.isoformat() == "2026-10-01T17:05:00+00:00" + assert ev.note == "90 ml" + + +def test_edit_event(client, db): + client.post("/events", data={"kind": "sleep", "started_at": "2026-10-01T13:00"}) + ev = db.scalars(select(Event)).one() + client.post(f"/events/{ev.id}", data={"kind": "sleep", "started_at": "2026-10-01T13:00", + "ended_at": "2026-10-01T14:30", "note": ""}) + db.refresh(ev) + assert ev.duration == timedelta(minutes=90) + + +def test_button_layout_reaches_the_device(client, device): + client.post("/settings/buttons", data={f"button_{n}": "wet" for n in range(1, 9)}) + body = client.get("/api/v1/device/config", headers=auth(device[1])).json() + assert {b["kind"] for b in body["buttons"]} == {"wet"} + + +def test_add_kind(client): + client.post("/settings/kinds/new", data={"label": "Vitamin D", "category": "health", "emoji": "☀️"}) + kinds = client.get("/api/v1/kinds").json() + assert any(k["slug"] == "vitamin_d" and k["category"] == "health" for k in kinds) + + +def test_register_device_shows_token_once(client): + r = client.post("/device/new", data={"name": "Kitchen"}) + assert "mmd_" in r.text and "Kitchen" in r.text + assert r.text.count("only once") == 1 + assert "mmd_" not in client.get("/device").text.replace("mmd_…", "") + + +def test_json_api_crud(client): + r = client.post("/api/v1/events", json={"kind": "wet"}) + assert r.status_code == 201 + eid = r.json()["id"] + start = (utcnow() - timedelta(hours=2)).isoformat() + r = client.patch(f"/api/v1/events/{eid}", json={"kind": "dirty", "started_at": start, "note": "big one"}) + assert r.json()["kind"] == "dirty" and r.json()["note"] == "big one" + assert len(client.get("/api/v1/events?category=diaper").json()) == 1 + assert client.delete(f"/api/v1/events/{eid}").status_code == 204 + assert client.get("/api/v1/events").json() == [] + assert len(client.get("/api/v1/stats/daily?days=7").json()) == 7 + + +def test_api_rejects_naive_datetimes(client): + r = client.post("/api/v1/events", json={"kind": "wet", "started_at": "2026-10-01T10:00:00"}) + assert r.status_code == 422 + + +def test_exports(client, db): + seed_demo(db, days=1) + csv = client.get("/api/v1/export.csv") + assert csv.status_code == 200 and csv.text.startswith("id,date,start") + backup = client.get("/api/v1/export.json").json() + assert backup["format"] == "mamadachi-backup-1" + assert backup["events"] and backup["presses"] and backup["device_reports"] + assert "token_hash" not in str(backup) + + +def test_password_gate(client): + get_settings().dashboard_password = "hunter2" + r = client.get("/", follow_redirects=False) + assert r.status_code == 303 and r.headers["location"].startswith("/login") + assert client.get("/api/v1/events").status_code == 401 + assert client.post("/login", data={"password": "nope"}).status_code == 401 + r = client.post("/login", data={"password": "hunter2", "next": "/trends"}, follow_redirects=False) + assert r.headers["location"] == "/trends" + assert client.get("/").status_code == 200 + assert client.get("/api/v1/events").status_code == 200 + + +def test_device_api_ignores_dashboard_password(client, device): + get_settings().dashboard_password = "hunter2" + r = client.post("/api/v1/device/sync", json={"events": []}, headers=auth(device[1])) + assert r.status_code == 200 + + +def test_cross_site_form_post_is_blocked(client, db): + r = client.post("/quick", data={"kind": "wet"}, headers={"Origin": "https://evil.example"}) + assert r.status_code == 403 + assert db.scalars(select(Event)).first() is None + ok = client.post("/quick", data={"kind": "wet"}, headers={"Origin": "http://testserver"}) + assert ok.status_code == 200 + + +def test_health(client): + assert client.get("/healthz").json()["ok"] is True + assert client.get("/readyz").json()["database"] == "ok" + + +def test_unknown_page_is_friendly(client): + r = client.get("/nope", headers={"Accept": "text/html"}) + assert r.status_code == 404 and "Not found" in r.text + + +def test_production_refuses_to_start_on_sqlite(): + import pytest + from fastapi.testclient import TestClient + + from app.main import app + + settings = get_settings() + saved = (settings.app_env, settings.database_url) + settings.app_env = "production" + try: + if settings.is_sqlite: + with pytest.raises(RuntimeError, match="DATABASE_URL"): + with TestClient(app): + pass + settings.database_url = "postgresql+psycopg://x@nowhere/db" # only checked, never connected + settings.dashboard_password = "pw" + with pytest.raises(RuntimeError, match="SECRET_KEY"): + with TestClient(app): + pass + finally: + settings.app_env, settings.database_url = saved diff --git a/tools/fake_device.py b/tools/fake_device.py new file mode 100644 index 0000000..e7a368a --- /dev/null +++ b/tools/fake_device.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Pretend to be a Mamadachi. Standard library only, so it runs anywhere. + +It keeps a queue file like the real firmware keeps flash: presses wait there +until a sync succeeds, and are only deleted on HTTP 200. + + python tools/fake_device.py press 6 # queue a press of button 6 (offline) + python tools/fake_device.py press 4 --ago 30 # ...that happened 30 min ago + python tools/fake_device.py --token mmd_... sync # upload the queue to a local server + python tools/fake_device.py --url https://your-app.onrender.com --token mmd_... sync + python tools/fake_device.py --token mmd_... sync --clock-off 3600 # RTC 1 h slow + python tools/fake_device.py --token mmd_... status # what the e-paper would show + +URL and token can also come from MAMADACHI_URL / MAMADACHI_TOKEN. +The default URL is http://127.0.0.1:8000 (on Windows, "localhost" adds a 2 s IPv6 delay). +""" + +import argparse +import json +import os +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +STATE = Path(__file__).with_name(".fake_device_state.json") + + +def load() -> dict: + if STATE.exists(): + return json.loads(STATE.read_text()) + return {"seq": 0, "queue": [], "boots": 1} + + +def save(state: dict) -> None: + STATE.write_text(json.dumps(state, indent=2)) + + +def post(url: str, token: str, body: dict) -> tuple[int, dict]: + req = urllib.request.Request( + url.rstrip("/") + "/api/v1/device/sync", + data=json.dumps(body).encode(), + headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=15) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + +def show_status(resp: dict) -> None: + now = resp["server_time"] + s = resp["status"] + + def ago(t: int) -> str: + m = (now - t) // 60 + return f"{m // 60}h {m % 60:02d}m ago" if m >= 60 else f"{m}m ago" + + print(f" {s['baby_name']}") + if s["last_feed"]: + side = f" next: {s['next_side']}" if s["next_side"] else "" + print(f" Fed {ago(s['last_feed']['time'])} ({s['last_feed']['short']}){side}") + for o in s["open"]: + print(f" {o['short']} since {ago(o['since'])}") + t = s["today"] + print(f" Today: {t['feeds']} feeds, {t['wet']} wet, {t['dirty']} dirty, {t['sleep_min'] // 60}h{t['sleep_min'] % 60:02d} sleep") + print(" Buttons: " + " ".join(f"{b['button']}={b['short']}" for b in resp["buttons"])) + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--url", default=os.environ.get("MAMADACHI_URL", "http://127.0.0.1:8000")) + p.add_argument("--token", default=os.environ.get("MAMADACHI_TOKEN")) + sub = p.add_subparsers(dest="cmd", required=True) + pr = sub.add_parser("press", help="queue a button press") + pr.add_argument("button", type=int, help="1-8") + pr.add_argument("--ago", type=float, default=0, help="minutes ago") + sy = sub.add_parser("sync", help="upload the queue") + sy.add_argument("--clock-off", type=int, default=0, help="seconds the RTC is behind (simulate drift)") + sy.add_argument("--battery", type=int, default=3950, help="mV") + sub.add_parser("status", help="sync with an empty queue and print what the display would show") + sub.add_parser("forget", help="delete the local queue/state file") + args = p.parse_args() + + state = load() + if args.cmd == "forget": + STATE.unlink(missing_ok=True) + print("State cleared.") + return 0 + if args.cmd == "press": + state["seq"] += 1 + state["queue"].append({"seq": state["seq"], "time": int(time.time() - args.ago * 60), "button": args.button}) + save(state) + print(f"Queued press #{state['seq']} (button {args.button}). {len(state['queue'])} waiting; run 'sync'.") + return 0 + + if not args.token: + print("Need --token (or MAMADACHI_TOKEN). Create one on the dashboard's Device page.", file=sys.stderr) + return 2 + batch = state["queue"][:500] if args.cmd == "sync" else [] + clock_off = getattr(args, "clock_off", 0) + body = { + "device_time": int(time.time()) - clock_off, + "firmware": "fake-0.1", + "battery_mv": getattr(args, "battery", 3950), + "charging": False, + "rssi": -60, + "boot_count": state["boots"], + "queue_len": len(state["queue"]) - len(batch), + "events": [dict(e, time=e["time"] - clock_off) for e in batch], + } + t0 = time.time() + try: + status, resp = post(args.url, args.token, body) + except OSError as e: + print(f"Network error, keeping {len(batch)} presses queued: {e}", file=sys.stderr) + return 1 + ms = (time.time() - t0) * 1000 + if status != 200: + print(f"HTTP {status}, keeping {len(batch)} presses queued: {resp.get('detail')}", file=sys.stderr) + return 1 + # HTTP 200: the server has everything we sent. Now (and only now) delete it. + sent = {(e["seq"], e["time"]) for e in batch} + state["queue"] = [e for e in state["queue"] if (e["seq"], e["time"]) not in sent] + save(state) + print(f"HTTP 200 in {ms:.0f} ms: {resp['stored']} new, {resp['duplicates']} already known." + f" Clock skew {resp['clock_skew_s']} s{' (corrected)' if resp['clock_corrected'] else ''}.") + show_status(resp) + return 0 + + +if __name__ == "__main__": + sys.exit(main())