Compare commits
13
Commits
50947d077f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a01d74e9d5 | ||
|
|
f98137097c | ||
|
|
35275e6c2c | ||
|
|
a7d3575474 | ||
|
|
e2369f3a3e | ||
|
|
a37474ab82 | ||
|
|
7b1b0889c6 | ||
|
|
ffa15ff2e7 | ||
|
|
e17856b9fe | ||
|
|
533aa1cc34 | ||
|
|
baccdbd826 | ||
|
|
18aa0686c0 | ||
|
|
5a419b64dd |
No files matched your search
@@ -136,6 +136,18 @@ of them, because logging has to be one tap from wherever you are.
|
|||||||
why tabbed apps get a reputation for trapping you: flick between tabs fifteen
|
why tabbed apps get a reputation for trapping you: flick between tabs fifteen
|
||||||
times and it takes fifteen presses to escape. Two presses, always, from
|
times and it takes fifteen presses to escape. Two presses, always, from
|
||||||
anywhere.
|
anywhere.
|
||||||
|
- **Sleep tracking can be switched off** (Settings → *Track sleep*) by an
|
||||||
|
account that has stopped logging it. Everything that asks for sleep or shows
|
||||||
|
it carries `data-sleep-only` and is hidden — the log buttons, the Sleep tab,
|
||||||
|
the overview's Sleep/Awake tiles and Last sleep row, the Sleep & wake list —
|
||||||
|
along with the bar timer, and the sleep state reads as unknown, so a
|
||||||
|
`sleep-start` left over from before can't dim the log buttons or run a sleep
|
||||||
|
rail through every day's history. Nothing is deleted: sleep events stay in
|
||||||
|
History, and switching it back on brings the rest back. It is part of the
|
||||||
|
synced profile rather than a device preference, because the server's
|
||||||
|
reminders need it and it decides what a guest is asked to log. The field is
|
||||||
|
the negative `sleepOff`, so a profile from before it existed, or a client too
|
||||||
|
old to send it, means tracking.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
@@ -347,6 +359,11 @@ Opt-in push notifications for the two things that are easy to lose track of:
|
|||||||
night — and means an overdue rule fires promptly on waking instead. The server
|
night — and means an overdue rule fires promptly on waking instead. The server
|
||||||
derives sleep state exactly the way `currentSleepState()` does in `app.js`,
|
derives sleep state exactly the way `currentSleepState()` does in `app.js`,
|
||||||
tie-break included, so both sides always agree.
|
tie-break included, so both sides always agree.
|
||||||
|
- **Unless sleep isn't tracked.** With *Track sleep* off, the sleep state is
|
||||||
|
unknown whatever boundaries are left in the log: the sleep rule never fires
|
||||||
|
and the others are never suppressed. Reading the last boundary anyway would
|
||||||
|
hold the puppy asleep — and every other rule silent — from the day tracking
|
||||||
|
stopped.
|
||||||
- **One notification per rule.** Every push carries a `tag`, so a repeat replaces
|
- **One notification per rule.** Every push carries a `tag`, so a repeat replaces
|
||||||
the previous notification instead of stacking another one on the lock screen.
|
the previous notification instead of stacking another one on the lock screen.
|
||||||
- **Late syncs cancel a reminder retroactively.** Rules measure from the event's
|
- **Late syncs cancel a reminder retroactively.** Rules measure from the event's
|
||||||
|
|||||||
@@ -8,12 +8,14 @@ const app = load({
|
|||||||
names: [
|
names: [
|
||||||
"ymd", "startOfDay", "EXCLUDED_TYPE", "ALWAYS_COUNTS", "excludedSet",
|
"ymd", "startOfDay", "EXCLUDED_TYPE", "ALWAYS_COUNTS", "excludedSet",
|
||||||
"excludedDays", "isExcluded", "countedEvents", "spansExcluded",
|
"excludedDays", "isExcluded", "countedEvents", "spansExcluded",
|
||||||
"pairWindows", "sleepWindows", "sleepMsInRange", "lastEventOfType",
|
"pairWindows", "sleepWindows", "sleepIntervals", "msInIntervals", "sleepMsInRange",
|
||||||
|
"lastEventOfType",
|
||||||
"gapsBetween",
|
"gapsBetween",
|
||||||
],
|
],
|
||||||
lets: ["excludedSet"],
|
lets: ["excludedSet"],
|
||||||
// gapsBetween defaults its window to the chart picker; the checks pass it in.
|
// gapsBetween takes its window from the chart range picker (chartSpan); here
|
||||||
stubs: { chartDays: () => 7 },
|
// that is the two weeks up to and including the checks' "now" day.
|
||||||
|
stubs: { chartSpan: () => ({ from: NOW - 14 * 24 * H, to: NOW + 24 * H }) },
|
||||||
});
|
});
|
||||||
|
|
||||||
const H = 3600_000;
|
const H = 3600_000;
|
||||||
@@ -30,7 +32,7 @@ suite("what a marked day takes out of the numbers");
|
|||||||
{ id: "c", type: "pee", at: at(20, 9) },
|
{ id: "c", type: "pee", at: at(20, 9) },
|
||||||
mark(19),
|
mark(19),
|
||||||
]);
|
]);
|
||||||
eq(app.gapsBetween(evs, "pee", 14), [],
|
eq(app.gapsBetween(evs, "pee"), [],
|
||||||
"a gap reaching across a marked day is discarded rather than measured");
|
"a gap reaching across a marked day is discarded rather than measured");
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
@@ -41,7 +43,7 @@ suite("what a marked day takes out of the numbers");
|
|||||||
{ id: "g", type: "pee", at: at(20, 12) },
|
{ id: "g", type: "pee", at: at(20, 12) },
|
||||||
mark(19),
|
mark(19),
|
||||||
]);
|
]);
|
||||||
eq(app.gapsBetween(evs, "pee", 14), [4 * H, 4 * H],
|
eq(app.gapsBetween(evs, "pee"), [4 * H, 4 * H],
|
||||||
"…while the gaps either side of it survive");
|
"…while the gaps either side of it survive");
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
|
|||||||
+45
-24
@@ -4,33 +4,52 @@
|
|||||||
import { load } from "./extract.mjs";
|
import { load } from "./extract.mjs";
|
||||||
import { suite, eq, ok, report } from "./assert.mjs";
|
import { suite, eq, ok, report } from "./assert.mjs";
|
||||||
|
|
||||||
const app = load({ names: ["foodTrend"] });
|
// The food line is dailyTrend fitted to each day's grams. Today is whichever day
|
||||||
const words = load({ names: ["foodTrendSentence"] });
|
// is flagged so, as weeklyData flags it; these days put it last.
|
||||||
|
const fit = load({ names: ["dailyTrend"] });
|
||||||
|
const app = { foodTrend: (days) => fit.dailyTrend(days, (d) => d.grams) };
|
||||||
|
// The window reaches a sentence as the phrase the chart names it by. The
|
||||||
|
// reason for having no line mentions today only when the window has it.
|
||||||
|
const words = load({ names: ["noTrendSentence", "foodTrendSentence"], stubs: { chartRange: () => ({ endsToday: true }) } });
|
||||||
|
const lastDays = (n) => `the last ${n} days`;
|
||||||
|
|
||||||
// The 7/14/30 picker reaches the trend by deciding how many days weeklyData
|
// The range picker reaches the trend by deciding which days weeklyData builds —
|
||||||
// builds — there is no second mechanism, so this is the thing to hold still.
|
// there is no second mechanism, so this is the thing to hold still. The picker
|
||||||
let windowDays = 7;
|
// is the real one, reading what it stored.
|
||||||
|
const stored = new Map();
|
||||||
const weekly = load({
|
const weekly = load({
|
||||||
names: ["startOfDay", "endOfDay", "ymd", "weeklyData"],
|
names: [
|
||||||
|
"CHART_DAYS_KEY", "CHART_RANGE_KEY", "CHART_DAY_CHOICES", "CHART_MAX_DAYS",
|
||||||
|
"startOfDay", "endOfDay", "ymd", "addDays", "daysBetween", "parseYmd",
|
||||||
|
"storedCustomRange", "chartRange", "chartDayList",
|
||||||
|
"NO_KIND", "sleepIntervals", "msInIntervals", "weeklyData",
|
||||||
|
],
|
||||||
stubs: {
|
stubs: {
|
||||||
chartDays: () => windowDays,
|
localStorage: { getItem: (k) => stored.get(k) ?? null },
|
||||||
isExcluded: () => false,
|
isExcluded: () => false,
|
||||||
eventsForDay: () => [],
|
walkWindows: () => [],
|
||||||
sleepMsInRange: () => 0,
|
|
||||||
walkMsInRange: () => 0,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
suite("the day picker is what sets the trend's window");
|
suite("the range picker is what sets the trend's window");
|
||||||
for (const n of [7, 14, 30]) {
|
for (const n of [7, 14, 30]) {
|
||||||
windowDays = n;
|
stored.set(weekly.CHART_DAYS_KEY, String(n));
|
||||||
eq(weekly.weeklyData([]).length, n, `picking ${n}d gives the charts ${n} days to fit over`);
|
eq(weekly.weeklyData([]).length, n, `picking ${n}d gives the charts ${n} days to fit over`);
|
||||||
}
|
}
|
||||||
windowDays = 7;
|
{
|
||||||
|
// A custom stretch in the past: its own days, none of them today.
|
||||||
|
const ago = (n) => weekly.ymd(weekly.addDays(weekly.startOfDay(new Date()), -n));
|
||||||
|
stored.set(weekly.CHART_DAYS_KEY, "custom");
|
||||||
|
stored.set(weekly.CHART_RANGE_KEY, JSON.stringify({ from: ago(10), to: ago(3) }));
|
||||||
|
const days = weekly.weeklyData([]);
|
||||||
|
eq(days.length, 8, "a custom range gives the charts exactly its days");
|
||||||
|
eq(days.some((d) => d.isToday), false, "…and one that ends before today has no half-done day to leave out");
|
||||||
|
}
|
||||||
|
stored.clear();
|
||||||
|
|
||||||
// weeklyData's shape, as far as foodTrend reads it. Today is last, as there.
|
// weeklyData's shape, as far as the fit reads it. Today is last.
|
||||||
const days = (grams, { excluded = [] } = {}) =>
|
const days = (grams, { excluded = [] } = {}) =>
|
||||||
grams.map((g, i) => ({ grams: g, excluded: excluded.includes(i) }));
|
grams.map((g, i) => ({ grams: g, excluded: excluded.includes(i), isToday: i === grams.length - 1 }));
|
||||||
|
|
||||||
suite("it declines to fit when there is nothing to fit");
|
suite("it declines to fit when there is nothing to fit");
|
||||||
{
|
{
|
||||||
@@ -89,7 +108,7 @@ suite("marked days are skipped without shifting the line");
|
|||||||
|
|
||||||
suite("what the sentence is allowed to say");
|
suite("what the sentence is allowed to say");
|
||||||
{
|
{
|
||||||
const say = (grams, opts, win = 14) => words.foodTrendSentence(app.foodTrend(days(grams, opts)), win);
|
const say = (grams, opts, win = 14) => words.foodTrendSentence(app.foodTrend(days(grams, opts)), lastDays(win));
|
||||||
|
|
||||||
const rising = say([200, 250, 300, 350, 400, 450, 0]);
|
const rising = say([200, 250, 300, 350, 400, 450, 0]);
|
||||||
ok(/up about 250 g/.test(rising), "a clear climb gives the size of the move");
|
ok(/up about 250 g/.test(rising), "a clear climb gives the size of the move");
|
||||||
@@ -143,17 +162,19 @@ suite("what the sentence is allowed to say");
|
|||||||
{
|
{
|
||||||
let kinds = [];
|
let kinds = [];
|
||||||
const split = load({
|
const split = load({
|
||||||
names: ["NO_KIND", "FOOD_COLORS", "foodTrend", "foodTrendSentence",
|
names: ["NO_KIND", "FOOD_COLORS", "dailyTrend", "noTrendSentence", "foodTrendSentence",
|
||||||
"foodTrendMoves", "foodSeriesSentences", "foodSeriesFor"],
|
"foodTrendMoves", "foodSeriesSentences", "foodSeriesFor"],
|
||||||
stubs: {
|
stubs: {
|
||||||
|
chartRange: () => ({ endsToday: true }),
|
||||||
liveFoodKinds: () => kinds,
|
liveFoodKinds: () => kinds,
|
||||||
loadFoodKinds: () => kinds,
|
loadFoodKinds: () => kinds,
|
||||||
foodKindNames: () => new Map(kinds.map(k => [k.id, k.name])),
|
foodKindNames: () => new Map(kinds.map(k => [k.id, k.name])),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// days carrying a per-kind split, as weeklyData builds them.
|
// days carrying a per-kind split, as weeklyData builds them; the last is today.
|
||||||
const byKind = (rows) => rows.map(r => ({
|
const byKind = (rows) => rows.map((r, i) => ({
|
||||||
|
isToday: i === rows.length - 1,
|
||||||
grams: Object.values(r).reduce((s, v) => s + v, 0),
|
grams: Object.values(r).reduce((s, v) => s + v, 0),
|
||||||
gramsByKind: r,
|
gramsByKind: r,
|
||||||
excluded: false,
|
excluded: false,
|
||||||
@@ -167,7 +188,7 @@ suite("what the sentence is allowed to say");
|
|||||||
const series = split.foodSeriesFor(days);
|
const series = split.foodSeriesFor(days);
|
||||||
eq(series.length, 1, "no kinds defined gives exactly one series");
|
eq(series.length, 1, "no kinds defined gives exactly one series");
|
||||||
eq(series[0].name, "No kind", "…the unnamed one");
|
eq(series[0].name, "No kind", "…the unnamed one");
|
||||||
const s = split.foodSeriesSentences(series, 7);
|
const s = split.foodSeriesSentences(series, lastDays(7));
|
||||||
eq(s.length, 1, "…and one sentence, as before kinds existed");
|
eq(s.length, 1, "…and one sentence, as before kinds existed");
|
||||||
ok(/daily intake/.test(s[0]), "…phrased as the whole intake, not as a kind");
|
ok(/daily intake/.test(s[0]), "…phrased as the whole intake, not as a kind");
|
||||||
}
|
}
|
||||||
@@ -201,7 +222,7 @@ suite("what the sentence is allowed to say");
|
|||||||
// food is real — it has to show under the name the tombstone kept.
|
// food is real — it has to show under the name the tombstone kept.
|
||||||
kinds = [];
|
kinds = [];
|
||||||
const namesOnly = load({
|
const namesOnly = load({
|
||||||
names: ["NO_KIND", "FOOD_COLORS", "foodTrend", "foodSeriesFor"],
|
names: ["NO_KIND", "FOOD_COLORS", "dailyTrend", "foodSeriesFor"],
|
||||||
stubs: {
|
stubs: {
|
||||||
liveFoodKinds: () => [],
|
liveFoodKinds: () => [],
|
||||||
// The tombstone: gone from the picker, still carrying name and colour.
|
// The tombstone: gone from the picker, still carrying name and colour.
|
||||||
@@ -231,7 +252,7 @@ suite("what the sentence is allowed to say");
|
|||||||
{ a: 300, b: 50, c: 40, e: 9 }, { a: 0, b: 0, c: 0, e: 0 },
|
{ a: 300, b: 50, c: 40, e: 9 }, { a: 0, b: 0, c: 0, e: 0 },
|
||||||
]);
|
]);
|
||||||
const series = split.foodSeriesFor(days);
|
const series = split.foodSeriesFor(days);
|
||||||
const lines = split.foodSeriesSentences(series, 7);
|
const lines = split.foodSeriesSentences(series, lastDays(7));
|
||||||
ok(lines.some(l => /^Dry:/.test(l)), "the kind that moved gets its own sentence");
|
ok(lines.some(l => /^Dry:/.test(l)), "the kind that moved gets its own sentence");
|
||||||
ok(lines.length <= 2, `four kinds give at most two lines, got ${lines.length}`);
|
ok(lines.length <= 2, `four kinds give at most two lines, got ${lines.length}`);
|
||||||
ok(lines.some(l => /no clear trend/.test(l)),
|
ok(lines.some(l => /no clear trend/.test(l)),
|
||||||
@@ -245,7 +266,7 @@ suite("what the sentence is allowed to say");
|
|||||||
{ a: 200, b: 100 }, { a: 205, b: 98 }, { a: 198, b: 101 },
|
{ a: 200, b: 100 }, { a: 205, b: 98 }, { a: 198, b: 101 },
|
||||||
{ a: 202, b: 99 }, { a: 200, b: 100 }, { a: 0, b: 0 },
|
{ a: 202, b: 99 }, { a: 200, b: 100 }, { a: 0, b: 0 },
|
||||||
]);
|
]);
|
||||||
const lines = split.foodSeriesSentences(split.foodSeriesFor(days), 7);
|
const lines = split.foodSeriesSentences(split.foodSeriesFor(days), lastDays(7));
|
||||||
eq(lines.length, 1, "one line when nothing is claimable");
|
eq(lines.length, 1, "one line when nothing is claimable");
|
||||||
ok(/no kind shows a trend/.test(lines[0]), "…saying so plainly");
|
ok(/no kind shows a trend/.test(lines[0]), "…saying so plainly");
|
||||||
}
|
}
|
||||||
@@ -259,7 +280,7 @@ suite("what the sentence is allowed to say");
|
|||||||
let selected = "2026-09-20";
|
let selected = "2026-09-20";
|
||||||
let el = { hidden: false, textContent: "" };
|
let el = { hidden: false, textContent: "" };
|
||||||
const info = load({
|
const info = load({
|
||||||
names: ["NO_KIND", "FOOD_COLORS", "foodTrend", "foodSeriesFor", "renderFoodDayInfo"],
|
names: ["NO_KIND", "FOOD_COLORS", "dateFormatters", "fmtDate", "dailyTrend", "foodSeriesFor", "renderFoodDayInfo"],
|
||||||
stubs: {
|
stubs: {
|
||||||
document: { getElementById: () => el },
|
document: { getElementById: () => el },
|
||||||
selectedDay: () => new Date(selected + "T12:00:00"),
|
selectedDay: () => new Date(selected + "T12:00:00"),
|
||||||
|
|||||||
@@ -13,12 +13,15 @@ let excluded = new Set();
|
|||||||
let windowDays = 7;
|
let windowDays = 7;
|
||||||
|
|
||||||
const curves = load({
|
const curves = load({
|
||||||
names: ["startOfDay", "pairWindows", "sleepWindows", "sleepTrendCurves"],
|
names: ["startOfDay", "addDays", "pairWindows", "sleepWindows", "averageDays", "sleepTrendCurves"],
|
||||||
stubs: {
|
stubs: {
|
||||||
selectedDay: () => SEL,
|
selectedDay: () => SEL,
|
||||||
ymd: (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`,
|
ymd: (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`,
|
||||||
isExcluded: (d) => excluded.has(d.getDate()),
|
isExcluded: (d) => excluded.has(d.getDate()),
|
||||||
chartDays: () => windowDays,
|
// A preset window: the average runs over the N full days before the
|
||||||
|
// selected one (averageDays). A custom range isn't what's checked here.
|
||||||
|
chartRange: () => ({ custom: false, days: windowDays }),
|
||||||
|
chartDayList: () => [],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+9
-31
@@ -2,10 +2,16 @@ self: { config, lib, pkgs, ... }:
|
|||||||
|
|
||||||
let
|
let
|
||||||
cfg = config.services.puppy-tracker;
|
cfg = config.services.puppy-tracker;
|
||||||
staticPkg = self.packages.${pkgs.system}.static;
|
staticPkg = self.packages.${pkgs.stdenv.hostPlatform.system}.static;
|
||||||
serverPkg = self.packages.${pkgs.system}.server;
|
serverPkg = self.packages.${pkgs.stdenv.hostPlatform.system}.server;
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
|
# The feed schema read walks from is gone; a config that still sets it
|
||||||
|
# is told so, rather than getting an unknown-option error.
|
||||||
|
imports = [
|
||||||
|
(lib.mkRemovedOptionModule [ "services" "puppy-tracker" "integration" ] "The integration feed for schema was removed.")
|
||||||
|
];
|
||||||
|
|
||||||
options.services.puppy-tracker = {
|
options.services.puppy-tracker = {
|
||||||
enable = lib.mkEnableOption "Puppy Tracker (offline-first puppy tracking app with sync server)";
|
enable = lib.mkEnableOption "Puppy Tracker (offline-first puppy tracking app with sync server)";
|
||||||
|
|
||||||
@@ -63,24 +69,6 @@ in
|
|||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
|
|
||||||
integration = {
|
|
||||||
tokenFile = lib.mkOption {
|
|
||||||
type = lib.types.nullOr lib.types.path;
|
|
||||||
default = null;
|
|
||||||
example = "/run/agenix/schema-puppy-token";
|
|
||||||
description = ''
|
|
||||||
File holding a bearer token (just the token) that unlocks the
|
|
||||||
read-only GET /api/integration/events feed of walks and meals, used by
|
|
||||||
other services on this host. When null the endpoint doesn't exist.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
user = lib.mkOption {
|
|
||||||
type = lib.types.str;
|
|
||||||
default = "";
|
|
||||||
description = "Email of the account the feed exposes. Empty means the only account.";
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
package = lib.mkOption {
|
package = lib.mkOption {
|
||||||
type = lib.types.package;
|
type = lib.types.package;
|
||||||
default = serverPkg;
|
default = serverPkg;
|
||||||
@@ -108,17 +96,7 @@ in
|
|||||||
"-addr ${cfg.address}:${toString cfg.port}"
|
"-addr ${cfg.address}:${toString cfg.port}"
|
||||||
"-static ${cfg.staticPackage}/share/puppy-tracker"
|
"-static ${cfg.staticPackage}/share/puppy-tracker"
|
||||||
"-data /var/lib/puppy-tracker/puppy.db"
|
"-data /var/lib/puppy-tracker/puppy.db"
|
||||||
] ++ lib.optional cfg.secureCookies "-secure-cookies"
|
] ++ lib.optional cfg.secureCookies "-secure-cookies");
|
||||||
# %d is the unit's credentials directory (see LoadCredential below).
|
|
||||||
++ lib.optionals (cfg.integration.tokenFile != null) [
|
|
||||||
"-integration-token-file %d/integration-token"
|
|
||||||
"-integration-user ${lib.escapeShellArg cfg.integration.user}"
|
|
||||||
]);
|
|
||||||
|
|
||||||
# DynamicUser can't own the secret, so systemd reads it as root and
|
|
||||||
# hands the service a private copy.
|
|
||||||
LoadCredential = lib.optional (cfg.integration.tokenFile != null)
|
|
||||||
"integration-token:${toString cfg.integration.tokenFile}";
|
|
||||||
|
|
||||||
# Secrets (registration code, Web Push key) are read from env files kept
|
# Secrets (registration code, Web Push key) are read from env files kept
|
||||||
# out of the store, exposed to the server as PUPPY_INVITE_CODE and
|
# out of the store, exposed to the server as PUPPY_INVITE_CODE and
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/subtle"
|
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Integration is a read-only, token-authenticated view of one account's walks
|
|
||||||
// and meals, for other services on the same host (the household planner,
|
|
||||||
// schema, ticks off its dog duties from it). It is not a session: there is no
|
|
||||||
// cookie, it sees one configured account, and it can't write anything.
|
|
||||||
type Integration struct {
|
|
||||||
db *sql.DB
|
|
||||||
token string
|
|
||||||
// email picks the account whose events are exposed. Empty means "the only
|
|
||||||
// account", and refuses to guess once there are several.
|
|
||||||
email string
|
|
||||||
}
|
|
||||||
|
|
||||||
type integrationEvent struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
At int64 `json:"at"`
|
|
||||||
Deleted bool `json:"deleted,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (in *Integration) userID() (string, error) {
|
|
||||||
if in.email != "" {
|
|
||||||
var id string
|
|
||||||
err := in.db.QueryRow(`SELECT id FROM users WHERE email = ? COLLATE NOCASE`, in.email).Scan(&id)
|
|
||||||
return id, err
|
|
||||||
}
|
|
||||||
rows, err := in.db.Query(`SELECT id FROM users LIMIT 2`)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var ids []string
|
|
||||||
for rows.Next() {
|
|
||||||
var id string
|
|
||||||
if err := rows.Scan(&id); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
ids = append(ids, id)
|
|
||||||
}
|
|
||||||
if len(ids) != 1 {
|
|
||||||
return "", errors.New("set -integration-user: there is not exactly one account")
|
|
||||||
}
|
|
||||||
return ids[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GET /api/integration/events?since=<unix ms> returns the account's walk
|
|
||||||
// starts and meals that happened, or were changed, since then — tombstones
|
|
||||||
// included, so a consumer can undo what a deleted event did.
|
|
||||||
func (in *Integration) handleEvents(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
||||||
if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(in.token)) != 1 {
|
|
||||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "since: want unix milliseconds", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
uid, err := in.userID()
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("integration: %v", err)
|
|
||||||
http.Error(w, "no account to read from", http.StatusConflict)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rows, err := in.db.Query(`
|
|
||||||
SELECT id, type, at, deleted FROM events
|
|
||||||
WHERE user_id = ? AND type IN ('walk-start', 'eat') AND (at >= ? OR updated >= ?)
|
|
||||||
ORDER BY at`, uid, since, since)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("integration: %v", err)
|
|
||||||
http.Error(w, "server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
out := []integrationEvent{}
|
|
||||||
for rows.Next() {
|
|
||||||
var e integrationEvent
|
|
||||||
if err := rows.Scan(&e.ID, &e.Type, &e.At, &e.Deleted); err != nil {
|
|
||||||
log.Printf("integration: %v", err)
|
|
||||||
http.Error(w, "server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
out = append(out, e)
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{"events": out})
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestIntegrationEvents(t *testing.T) {
|
|
||||||
db, err := openDB(filepath.Join(t.TempDir(), "puppy.db"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer db.Close()
|
|
||||||
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u1', 'a@x', 'h', 0)`)
|
|
||||||
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u2', 'b@x', 'h', 0)`)
|
|
||||||
store := newStore(db)
|
|
||||||
store.sync("u1", "", "", []Event{
|
|
||||||
{ID: "walk", Type: "walk-start", At: 1000, UpdatedAt: 1000},
|
|
||||||
{ID: "meal", Type: "eat", At: 2000, UpdatedAt: 2000},
|
|
||||||
{ID: "pee", Type: "pee", At: 2000, UpdatedAt: 2000},
|
|
||||||
{ID: "old", Type: "eat", At: 10, UpdatedAt: 10},
|
|
||||||
{ID: "gone", Type: "eat", At: 10, UpdatedAt: 3000, Deleted: true},
|
|
||||||
})
|
|
||||||
store.sync("u2", "", "", []Event{{ID: "theirs", Type: "eat", At: 2000, UpdatedAt: 2000}})
|
|
||||||
|
|
||||||
get := func(in *Integration, auth, since string) (int, []integrationEvent) {
|
|
||||||
req := httptest.NewRequest("GET", "/api/integration/events?since="+since, nil)
|
|
||||||
if auth != "" {
|
|
||||||
req.Header.Set("Authorization", "Bearer "+auth)
|
|
||||||
}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
in.handleEvents(rec, req)
|
|
||||||
var body struct{ Events []integrationEvent }
|
|
||||||
json.NewDecoder(rec.Body).Decode(&body)
|
|
||||||
return rec.Code, body.Events
|
|
||||||
}
|
|
||||||
|
|
||||||
in := &Integration{db: db, token: "tok", email: "A@x"}
|
|
||||||
if code, _ := get(in, "", "0"); code != http.StatusUnauthorized {
|
|
||||||
t.Errorf("no token = %d", code)
|
|
||||||
}
|
|
||||||
if code, _ := get(in, "nope", "0"); code != http.StatusUnauthorized {
|
|
||||||
t.Errorf("wrong token = %d", code)
|
|
||||||
}
|
|
||||||
code, evs := get(in, "tok", "500")
|
|
||||||
if code != 200 {
|
|
||||||
t.Fatalf("code = %d", code)
|
|
||||||
}
|
|
||||||
got := map[string]bool{}
|
|
||||||
for _, e := range evs {
|
|
||||||
got[e.ID] = e.Deleted
|
|
||||||
}
|
|
||||||
// Recent walks and meals, plus the tombstone updated since; not the pee,
|
|
||||||
// not the old meal, not the other account's.
|
|
||||||
if len(got) != 3 || !got["gone"] {
|
|
||||||
t.Errorf("events = %+v", evs)
|
|
||||||
}
|
|
||||||
for _, id := range []string{"walk", "meal"} {
|
|
||||||
if _, ok := got[id]; !ok {
|
|
||||||
t.Errorf("missing %s", id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// With two accounts, no configured user is ambiguous.
|
|
||||||
if code, _ := get(&Integration{db: db, token: "tok"}, "tok", "0"); code != http.StatusConflict {
|
|
||||||
t.Errorf("ambiguous = %d", code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+23
-22
@@ -84,6 +84,11 @@ type Config struct {
|
|||||||
// PedigreeID is the dog's SKK chip or registration number. When set, the app
|
// PedigreeID is the dog's SKK chip or registration number. When set, the app
|
||||||
// unlocks the pedigree view and looks this dog up; empty means no pedigree.
|
// unlocks the pedigree view and looks this dog up; empty means no pedigree.
|
||||||
PedigreeID string `json:"pedigreeId"`
|
PedigreeID string `json:"pedigreeId"`
|
||||||
|
// SleepOff means sleep isn't being logged: the app hides its sleep buttons,
|
||||||
|
// timer and charts, and reminders stop reading the puppy as awake or asleep.
|
||||||
|
// Negative so that the zero value, and a client too old to send the field,
|
||||||
|
// both mean "tracking", which is what every profile was before it existed.
|
||||||
|
SleepOff bool `json:"sleepOff"`
|
||||||
UpdatedAt int64 `json:"updatedAt"`
|
UpdatedAt int64 `json:"updatedAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,8 +105,8 @@ func (cs *ConfigStore) get(userID string) Config {
|
|||||||
// One profile row per user. A missing row is the pre-configuration state,
|
// One profile row per user. A missing row is the pre-configuration state,
|
||||||
// so a zero-value Config is the right answer.
|
// so a zero-value Config is the right answer.
|
||||||
err := cs.db.QueryRow(
|
err := cs.db.QueryRow(
|
||||||
`SELECT name, birthday, pedigree_id, updated FROM config WHERE user_id = ?`, userID,
|
`SELECT name, birthday, pedigree_id, sleep_off, updated FROM config WHERE user_id = ?`, userID,
|
||||||
).Scan(&c.Name, &c.Birthday, &c.PedigreeID, &c.UpdatedAt)
|
).Scan(&c.Name, &c.Birthday, &c.PedigreeID, &c.SleepOff, &c.UpdatedAt)
|
||||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
log.Printf("config get: %v", err)
|
log.Printf("config get: %v", err)
|
||||||
}
|
}
|
||||||
@@ -111,19 +116,20 @@ func (cs *ConfigStore) get(userID string) Config {
|
|||||||
// merge applies an incoming config for one user with last-write-wins by
|
// merge applies an incoming config for one user with last-write-wins by
|
||||||
// UpdatedAt and returns the resulting stored config (which the caller sends back).
|
// UpdatedAt and returns the resulting stored config (which the caller sends back).
|
||||||
func (cs *ConfigStore) merge(userID string, in Config) (Config, error) {
|
func (cs *ConfigStore) merge(userID string, in Config) (Config, error) {
|
||||||
// Name/birthday/updated are last-write-wins: the incoming row replaces the
|
// Name/birthday/sleep_off/updated are last-write-wins: the incoming row replaces the
|
||||||
// stored one only when strictly newer. The pedigree id is stickier — an empty
|
// stored one only when strictly newer. The pedigree id is stickier — an empty
|
||||||
// incoming value never clears a stored one, so a clock race between devices
|
// incoming value never clears a stored one, so a clock race between devices
|
||||||
// can't drop it; when both are set, the newer profile's id wins with the rest.
|
// can't drop it; when both are set, the newer profile's id wins with the rest.
|
||||||
_, err := cs.db.Exec(`
|
_, err := cs.db.Exec(`
|
||||||
INSERT INTO config (user_id, name, birthday, pedigree_id, updated)
|
INSERT INTO config (user_id, name, birthday, pedigree_id, sleep_off, updated)
|
||||||
VALUES (?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(user_id) DO UPDATE SET
|
ON CONFLICT(user_id) DO UPDATE SET
|
||||||
name = excluded.name, birthday = excluded.birthday,
|
name = excluded.name, birthday = excluded.birthday,
|
||||||
pedigree_id = CASE WHEN excluded.pedigree_id != '' THEN excluded.pedigree_id ELSE config.pedigree_id END,
|
pedigree_id = CASE WHEN excluded.pedigree_id != '' THEN excluded.pedigree_id ELSE config.pedigree_id END,
|
||||||
|
sleep_off = excluded.sleep_off,
|
||||||
updated = excluded.updated
|
updated = excluded.updated
|
||||||
WHERE excluded.updated > config.updated`,
|
WHERE excluded.updated > config.updated`,
|
||||||
userID, in.Name, in.Birthday, in.PedigreeID, in.UpdatedAt)
|
userID, in.Name, in.Birthday, in.PedigreeID, in.SleepOff, in.UpdatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, err
|
return Config{}, err
|
||||||
}
|
}
|
||||||
@@ -468,6 +474,7 @@ func openDB(path string) (*sql.DB, error) {
|
|||||||
name TEXT NOT NULL DEFAULT '',
|
name TEXT NOT NULL DEFAULT '',
|
||||||
birthday TEXT NOT NULL DEFAULT '',
|
birthday TEXT NOT NULL DEFAULT '',
|
||||||
pedigree_id TEXT NOT NULL DEFAULT '',
|
pedigree_id TEXT NOT NULL DEFAULT '',
|
||||||
|
sleep_off INTEGER NOT NULL DEFAULT 0,
|
||||||
updated INTEGER NOT NULL DEFAULT 0
|
updated INTEGER NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
@@ -653,6 +660,15 @@ func migrateSchema(db *sql.DB) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
hasSleepOff, err := columnExists(db, "config", "sleep_off")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !hasSleepOff {
|
||||||
|
if _, err := db.Exec(`ALTER TABLE config ADD COLUMN sleep_off INTEGER NOT NULL DEFAULT 0`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -864,10 +880,6 @@ func main() {
|
|||||||
"mark session cookies Secure (enable when served over HTTPS / behind a TLS proxy)")
|
"mark session cookies Secure (enable when served over HTTPS / behind a TLS proxy)")
|
||||||
vapidKey := flag.String("vapid-key", os.Getenv("PUPPY_VAPID_KEY"),
|
vapidKey := flag.String("vapid-key", os.Getenv("PUPPY_VAPID_KEY"),
|
||||||
"base64url P-256 private key for Web Push (env PUPPY_VAPID_KEY); generated next to the DB when unset")
|
"base64url P-256 private key for Web Push (env PUPPY_VAPID_KEY); generated next to the DB when unset")
|
||||||
integrationTokenFile := flag.String("integration-token-file", "",
|
|
||||||
"file holding the bearer token for the read-only /api/integration/events; unset disables it")
|
|
||||||
integrationUser := flag.String("integration-user", "",
|
|
||||||
"email of the account /api/integration/events exposes; empty means the only account")
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
db, err := openDB(*dataPath)
|
db, err := openDB(*dataPath)
|
||||||
@@ -1033,7 +1045,7 @@ func main() {
|
|||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
writeConfig(configStore.get(userID(r)))
|
writeConfig(configStore.get(userID(r)))
|
||||||
case http.MethodPut, http.MethodPost:
|
case http.MethodPut, http.MethodPost:
|
||||||
// The profile (name, birthday, pedigree id) is the owner's to set.
|
// The profile (name, birthday, pedigree id, sleep tracking) is the owner's to set.
|
||||||
// The GET above stays open — a guest needs the name and birthday to
|
// The GET above stays open — a guest needs the name and birthday to
|
||||||
// render the header at all.
|
// render the header at all.
|
||||||
if isGuest(r) {
|
if isGuest(r) {
|
||||||
@@ -1100,17 +1112,6 @@ func main() {
|
|||||||
mux.HandleFunc("/api/reminders", auth.requireOwner(scheduler.handleReminders))
|
mux.HandleFunc("/api/reminders", auth.requireOwner(scheduler.handleReminders))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read-only feed of walks and meals for other services on this host.
|
|
||||||
if *integrationTokenFile != "" {
|
|
||||||
raw, err := os.ReadFile(*integrationTokenFile)
|
|
||||||
token := strings.TrimSpace(string(raw))
|
|
||||||
if err != nil || token == "" {
|
|
||||||
log.Fatalf("integration token file %s: unreadable or empty (%v)", *integrationTokenFile, err)
|
|
||||||
}
|
|
||||||
in := &Integration{db: db, token: token, email: *integrationUser}
|
|
||||||
mux.HandleFunc("/api/integration/events", in.handleEvents)
|
|
||||||
}
|
|
||||||
|
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("ok"))
|
w.Write([]byte("ok"))
|
||||||
})
|
})
|
||||||
|
|||||||
+16
-1
@@ -188,10 +188,25 @@ type sleepState struct {
|
|||||||
since int64 // ms epoch of that boundary
|
since int64 // ms epoch of that boundary
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sleepStateFor reads that boundary for one user. An account that has switched
|
||||||
|
// sleep tracking off has no sleep state at all,
|
||||||
|
// whatever boundaries are left in its log. Reading the last one anyway would
|
||||||
|
// leave the puppy "asleep" from the day tracking stopped, with every other
|
||||||
|
// rule silenced for good — or "awake" since then, with the sleep rule firing
|
||||||
|
// every interval forever.
|
||||||
func (sch *Scheduler) sleepStateFor(userID string) (sleepState, error) {
|
func (sch *Scheduler) sleepStateFor(userID string) (sleepState, error) {
|
||||||
|
var off bool
|
||||||
|
err := sch.db.QueryRow(`SELECT sleep_off FROM config WHERE user_id = ?`, userID).Scan(&off)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return sleepState{}, err
|
||||||
|
}
|
||||||
|
if off {
|
||||||
|
return sleepState{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
var typ string
|
var typ string
|
||||||
var at int64
|
var at int64
|
||||||
err := sch.db.QueryRow(`
|
err = sch.db.QueryRow(`
|
||||||
SELECT type, at FROM events
|
SELECT type, at FROM events
|
||||||
WHERE user_id = ? AND deleted = 0 AND type IN ('sleep-start', 'sleep-end')
|
WHERE user_id = ? AND deleted = 0 AND type IN ('sleep-start', 'sleep-end')
|
||||||
ORDER BY at DESC, updated DESC LIMIT 1`, userID).Scan(&typ, &at)
|
ORDER BY at DESC, updated DESC LIMIT 1`, userID).Scan(&typ, &at)
|
||||||
|
|||||||
@@ -188,6 +188,46 @@ func TestSleepStateMatchesLatestBoundary(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSleepStateIgnoredWhenTrackingIsOff(t *testing.T) {
|
||||||
|
sch := testScheduler(t)
|
||||||
|
now := int64(1_700_000_000_000)
|
||||||
|
configs := newConfigStore(sch.db)
|
||||||
|
|
||||||
|
// Tracking stopped while the log still says asleep.
|
||||||
|
addEvent(t, sch, "u1", "pee", now-90*minute)
|
||||||
|
addEvent(t, sch, "u1", "sleep-start", now-600*minute)
|
||||||
|
if _, err := configs.merge("u1", Config{Name: "Rex", SleepOff: true, UpdatedAt: now}); err != nil {
|
||||||
|
t.Fatalf("merge: %v", err)
|
||||||
|
}
|
||||||
|
if got := configs.get("u1"); !got.SleepOff {
|
||||||
|
t.Fatal("sleepOff did not round-trip through the config store")
|
||||||
|
}
|
||||||
|
s, err := sch.sleepStateFor("u1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sleepStateFor: %v", err)
|
||||||
|
}
|
||||||
|
if s.state != "" {
|
||||||
|
t.Errorf("state = %q, want none while tracking is off", s.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
// So an overdue pee rule fires rather than waiting for a wake-up that will
|
||||||
|
// never be logged, and the sleep rule stays quiet.
|
||||||
|
if _, ok, err := sch.due("u1", Reminder{Kind: "pee", Enabled: true, IntervalMin: 60}, 0, now, s); err != nil || !ok {
|
||||||
|
t.Errorf("pee: fired = %v (err %v), want a fire", ok, err)
|
||||||
|
}
|
||||||
|
if _, ok, err := sch.due("u1", Reminder{Kind: "sleep", Enabled: true, IntervalMin: 45}, 0, now, s); err != nil || ok {
|
||||||
|
t.Errorf("sleep: fired = %v (err %v), want no fire", ok, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Switching it back on reads the log again.
|
||||||
|
if _, err := configs.merge("u1", Config{Name: "Rex", UpdatedAt: now + 1}); err != nil {
|
||||||
|
t.Fatalf("merge: %v", err)
|
||||||
|
}
|
||||||
|
if s, err := sch.sleepStateFor("u1"); err != nil || s.state != "asleep" {
|
||||||
|
t.Errorf("tracking back on: state = %q (err %v), want asleep", s.state, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRemindersStoreDefaultsAndClamping(t *testing.T) {
|
func TestRemindersStoreDefaultsAndClamping(t *testing.T) {
|
||||||
sch := testScheduler(t)
|
sch := testScheduler(t)
|
||||||
|
|
||||||
|
|||||||
+576
-174
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,13 @@
|
|||||||
[
|
[
|
||||||
|
{ "date": "2026-11-12", "text": "Sleep tracking can be switched off. Turn off Track sleep in Settings and the Sleep start / Sleep end buttons, the asleep/awake timer, the Sleep tab, the Sleep and Awake figures and the Sleep & wake list all go away, and nothing is dimmed any more for being “unlikely” while asleep. Reminders stop going quiet while the log says asleep, and the Time to sleep reminder stops firing. Sleep you have already logged is kept, so you can switch it back on for a day whenever you want to track it" },
|
||||||
|
{ "date": "2026-10-28", "text": "The Sleep trend and Walk trend charts handle the days the clocks change. Their hour axis counted hours from midnight rather than reading the clock, so on the Sunday the clocks go back the day’s line stopped at 11 pm and left out the last hour — taking it off that day’s total and off the average day built from it — and in spring the day ran on into 1 am the next morning. Today’s line also ended an hour away from the “now” marker on those days. Both charts now follow the clock, so every day runs from midnight to midnight whatever its length" },
|
||||||
|
{ "date": "2026-10-28", "text": "His age is no longer a day short for part of the year. Depending on when he was born, counting the days since his birthday could come up one short between the clocks going forward in spring and going back in autumn, and the week and month counts in “16 weeks (3 months and 3 weeks) old” ticked over a day late" },
|
||||||
|
{ "date": "2026-10-28", "text": "The When sleeping and When walking grids draw the days the clocks change correctly. On the Sunday the clocks go back the day is 25 hours long, and everything after 3 am was drawn an hour late — the evening sleep ran off the right-hand end of the row. In spring the 23-hour day stopped short of 24h instead. Each nap and walk now sits at the time the clock showed, lining up with the hour lines like every other day, and the “now” marker does the same on those days" },
|
||||||
|
{ "date": "2026-10-03", "text": "The charts can cover any stretch of dates, not just the last 7, 14 or 30 days. Tap Custom on the “Charts cover” row and pick a from and a to date — up to a year at a time, and the to date can be in the past, so you can look back at, say, May on its own and see how much he slept or walked then. Every chart and panel that follows the 7 / 14 / 30 buttons follows the custom dates too, and their headings and trend sentences name the dates (“Over May 1 – Jun 15, daily sleep is down about 2h”). On a long range the daily bars sit edge to edge and the axis shows dates instead of weekdays, and the When sleeping and When walking grids use thinner rows so a few months still fit on the screen. The “average day” line on the Sleep trend and Walk trend is averaged over the custom dates as well. Tapping 7d, 14d or 30d goes back to the rolling window, and Custom remembers the dates you picked last" },
|
||||||
|
{ "date": "2026-10-01", "text": "The app opens straight away when you have no connection. It used to check in with the server before showing anything, and on a weak signal or with the server out of reach that check could take a long while to give up, leaving a blank screen even though all your data was already on the phone. It now opens on the account you were last signed in to and checks in the background; if that sign-in has run out you are taken to the login screen as before" },
|
||||||
|
{ "date": "2026-09-30", "text": "The Waking → pee and Meal → poo rows are gone from the Timing panel again. With a puppy who takes lots of short naps, most wake-ups were followed by another nap before any pee, so Waking → pee was built from a handful of odd cases and was hard to make sense of. The Pees, Poos and Meals rows are unchanged" },
|
||||||
|
{ "date": "2026-09-29", "text": "The Walks chart (minutes per day) has a trend line too, with a sentence under it in the same style as the sleep one: “daily walking is up about 20m — from roughly 35m a day to 55m”, or roughly steady with the average when the days vary more than they move. A day with no walk counts as a real zero — a rest day is a real figure — but the days before the very first walk you logged are left out, so starting to track walks partway through the window doesn't read as a sudden climb. Today and days marked “not counted” are left out as on every other trend" },
|
||||||
|
{ "date": "2026-09-29", "text": "The Sleep chart on the Sleep tab has a trend line through it, like the Food (grams) chart, so you can see whether he is sleeping less as he grows — the day-to-day bars vary enough to hide a steady change. A line under the chart puts it in figures: “daily sleep is down about 1.5h — from roughly 17h a day to 15.5h”, or, when the days scatter more than they move, that it is roughly steady and what the average is. Today is left out until it's over, as are days marked “not counted” and days with no sleep logged at all, which the sentence mentions so an empty bar isn't mistaken for a night without sleep. It follows the 7 / 14 / 30 day picker like the rest of the charts" },
|
||||||
{ "date": "2026-09-29", "text": "The Timing panel no longer counts the night. The gap from each day's last pee, poo or meal to the next morning's first was being measured like any other, so every window held several eight-hour-plus “gaps” that were really just bedtime — the longest figure was a sleep figure and the typical gap was pulled up with it. Only gaps within a single day are measured now, so the bars show how often he needs to go out while he's up and about. The “since the last one” marker is unchanged, so first thing in the morning it still reads as overdue — which, before the first trip out, it is" },
|
{ "date": "2026-09-29", "text": "The Timing panel no longer counts the night. The gap from each day's last pee, poo or meal to the next morning's first was being measured like any other, so every window held several eight-hour-plus “gaps” that were really just bedtime — the longest figure was a sleep figure and the typical gap was pulled up with it. Only gaps within a single day are measured now, so the bars show how often he needs to go out while he's up and about. The “since the last one” marker is unchanged, so first thing in the morning it still reads as overdue — which, before the first trip out, it is" },
|
||||||
{ "date": "2026-09-26", "text": "Tapping the tab you are already on scrolls back to the top of the page, the way it does in most phone apps — handy after scrolling a long way down Habits or the history. Switching to a different tab still leaves you where you were, as before" },
|
{ "date": "2026-09-26", "text": "Tapping the tab you are already on scrolls back to the top of the page, the way it does in most phone apps — handy after scrolling a long way down Habits or the history. Switching to a different tab still leaves you where you were, as before" },
|
||||||
{ "date": "2026-09-24", "text": "Kinds of food are now created in one place only — Settings → Food kinds. The Ate dialog no longer has a box for inventing one on the spot; it still lets you pick from the kinds you have, exactly as before. Making them mid-meal put a bit of list-keeping in the middle of logging, where the thing you actually came to do is record that the dog ate, and a kind typed in a hurry is easy to get slightly wrong — nothing stops two near-identical kinds existing, and clearing one up afterwards means relabelling every meal logged under it first" },
|
{ "date": "2026-09-24", "text": "Kinds of food are now created in one place only — Settings → Food kinds. The Ate dialog no longer has a box for inventing one on the spot; it still lets you pick from the kinds you have, exactly as before. Making them mid-meal put a bit of list-keeping in the middle of logging, where the thing you actually came to do is record that the dog ate, and a kind typed in a hurry is easy to get slightly wrong — nothing stops two near-identical kinds existing, and clearing one up afterwards means relabelling every meal logged under it first" },
|
||||||
|
|||||||
+31
-8
@@ -174,7 +174,9 @@
|
|||||||
its own). A row per timed pair, then the two one-tap moments, and
|
its own). A row per timed pair, then the two one-tap moments, and
|
||||||
last the three that open a dialog to type a value. -->
|
last the three that open a dialog to type a value. -->
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<div class="action-row">
|
<!-- data-sleep-only: hidden while sleep tracking is off in Settings,
|
||||||
|
like everything else so marked (see renderSleepTracking). -->
|
||||||
|
<div class="action-row" data-sleep-only>
|
||||||
<button class="action sleep" data-type="sleep-start">😴 Sleep start</button>
|
<button class="action sleep" data-type="sleep-start">😴 Sleep start</button>
|
||||||
<button class="action sleep" data-type="sleep-end">⏰ Sleep end</button>
|
<button class="action sleep" data-type="sleep-end">⏰ Sleep end</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -199,7 +201,7 @@
|
|||||||
above them: logging has to be one tap from wherever you are. -->
|
above them: logging has to be one tap from wherever you are. -->
|
||||||
<nav class="tabs" role="tablist" aria-label="Sections">
|
<nav class="tabs" role="tablist" aria-label="Sections">
|
||||||
<button type="button" class="tab" role="tab" data-tab="today" id="tab-today" aria-controls="tabpanel-today" aria-selected="false" tabindex="-1">Today</button>
|
<button type="button" class="tab" role="tab" data-tab="today" id="tab-today" aria-controls="tabpanel-today" aria-selected="false" tabindex="-1">Today</button>
|
||||||
<button type="button" class="tab" role="tab" data-tab="sleep" id="tab-sleep" aria-controls="tabpanel-sleep" aria-selected="false" tabindex="-1">Sleep</button>
|
<button type="button" class="tab" role="tab" data-tab="sleep" id="tab-sleep" aria-controls="tabpanel-sleep" aria-selected="false" tabindex="-1" data-sleep-only>Sleep</button>
|
||||||
<button type="button" class="tab" role="tab" data-tab="walks" id="tab-walks" aria-controls="tabpanel-walks" aria-selected="false" tabindex="-1">Walks</button>
|
<button type="button" class="tab" role="tab" data-tab="walks" id="tab-walks" aria-controls="tabpanel-walks" aria-selected="false" tabindex="-1">Walks</button>
|
||||||
<button type="button" class="tab" role="tab" data-tab="habits" id="tab-habits" aria-controls="tabpanel-habits" aria-selected="false" tabindex="-1">Habits</button>
|
<button type="button" class="tab" role="tab" data-tab="habits" id="tab-habits" aria-controls="tabpanel-habits" aria-selected="false" tabindex="-1">Habits</button>
|
||||||
<button type="button" class="tab" role="tab" data-tab="growth" id="tab-growth" aria-controls="tabpanel-growth" aria-selected="false" tabindex="-1">Growth</button>
|
<button type="button" class="tab" role="tab" data-tab="growth" id="tab-growth" aria-controls="tabpanel-growth" aria-selected="false" tabindex="-1">Growth</button>
|
||||||
@@ -215,6 +217,15 @@
|
|||||||
<button type="button" class="ghost" data-days="7">7d</button>
|
<button type="button" class="ghost" data-days="7">7d</button>
|
||||||
<button type="button" class="ghost" data-days="14">14d</button>
|
<button type="button" class="ghost" data-days="14">14d</button>
|
||||||
<button type="button" class="ghost" data-days="30">30d</button>
|
<button type="button" class="ghost" data-days="30">30d</button>
|
||||||
|
<button type="button" class="ghost" id="chart-range-custom">Custom</button>
|
||||||
|
</div>
|
||||||
|
<!-- Shown only while Custom is picked. Either end may be in the past,
|
||||||
|
so a stretch of history can be looked at on its own. -->
|
||||||
|
<div class="chart-range-fields" id="chart-range-fields" hidden>
|
||||||
|
<input type="date" id="chart-range-from" aria-label="Charts cover from" />
|
||||||
|
<span aria-hidden="true">–</span>
|
||||||
|
<input type="date" id="chart-range-to" aria-label="Charts cover to" />
|
||||||
|
<span class="muted-note" id="chart-range-days"></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -233,11 +244,11 @@
|
|||||||
Not counted in the charts and averages. Everything below is unchanged.
|
Not counted in the charts and averages. Everything below is unchanged.
|
||||||
</p>
|
</p>
|
||||||
<div class="stats">
|
<div class="stats">
|
||||||
<div class="stat">
|
<div class="stat" data-sleep-only>
|
||||||
<div class="stat-label">Sleep</div>
|
<div class="stat-label">Sleep</div>
|
||||||
<div class="stat-value" id="stat-sleep">0h 0m</div>
|
<div class="stat-value" id="stat-sleep">0h 0m</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat">
|
<div class="stat" data-sleep-only>
|
||||||
<div class="stat-label">Awake</div>
|
<div class="stat-label">Awake</div>
|
||||||
<div class="stat-value" id="stat-awake">0h 0m</div>
|
<div class="stat-value" id="stat-awake">0h 0m</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -273,7 +284,7 @@
|
|||||||
<div class="last-row"><span>Last pee</span><span id="last-pee">—</span></div>
|
<div class="last-row"><span>Last pee</span><span id="last-pee">—</span></div>
|
||||||
<div class="last-row"><span>Last poo</span><span id="last-poo">—</span></div>
|
<div class="last-row"><span>Last poo</span><span id="last-poo">—</span></div>
|
||||||
<div class="last-row"><span>Last meal</span><span id="last-eat">—</span></div>
|
<div class="last-row"><span>Last meal</span><span id="last-eat">—</span></div>
|
||||||
<div class="last-row"><span>Last sleep</span><span id="last-sleep">—</span></div>
|
<div class="last-row" data-sleep-only><span>Last sleep</span><span id="last-sleep">—</span></div>
|
||||||
<div class="last-row"><span>Last walk</span><span id="last-walk">—</span></div>
|
<div class="last-row"><span>Last walk</span><span id="last-walk">—</span></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -283,7 +294,7 @@
|
|||||||
one alternating list rather than sitting in two panels that each show
|
one alternating list rather than sitting in two panels that each show
|
||||||
half the day. Every row carries its state; the open one keeps the
|
half the day. Every row carries its state; the open one keeps the
|
||||||
highlight. -->
|
highlight. -->
|
||||||
<section class="sleepwake" data-panel="sleep-wake">
|
<section class="sleepwake" data-panel="sleep-wake" data-sleep-only>
|
||||||
<h2>Sleep & wake</h2>
|
<h2>Sleep & wake</h2>
|
||||||
<ul id="sleep-wake-list" class="wake-list"></ul>
|
<ul id="sleep-wake-list" class="wake-list"></ul>
|
||||||
<p id="sleep-wake-empty" class="empty">No sleep or wake windows yet for this day.</p>
|
<p id="sleep-wake-empty" class="empty">No sleep or wake windows yet for this day.</p>
|
||||||
@@ -301,7 +312,9 @@
|
|||||||
<h2>Sleep <span class="muted-note" data-chart-days-label>(last 7 days)</span></h2>
|
<h2>Sleep <span class="muted-note" data-chart-days-label>(last 7 days)</span></h2>
|
||||||
<div class="chart">
|
<div class="chart">
|
||||||
<div class="chart-title">Hours per day</div>
|
<div class="chart-title">Hours per day</div>
|
||||||
<svg id="chart-sleep" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Sleep hours per day"></svg>
|
<svg id="chart-sleep" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Sleep hours per day, with a trend line"></svg>
|
||||||
|
<!-- What the trend line says — see renderSleepTrendNote. -->
|
||||||
|
<p id="sleep-note" class="muted-note" hidden></p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -332,7 +345,9 @@
|
|||||||
<p id="walk-empty" class="empty">No walks yet for this day. Use 🦮 Walk start / 🏁 Walk end to time one.</p>
|
<p id="walk-empty" class="empty">No walks yet for this day. Use 🦮 Walk start / 🏁 Walk end to time one.</p>
|
||||||
<div class="chart walk-chart" id="walk-chart-wrap" hidden>
|
<div class="chart walk-chart" id="walk-chart-wrap" hidden>
|
||||||
<div class="chart-title">Minutes per day <span data-chart-days-label>(last 7 days)</span></div>
|
<div class="chart-title">Minutes per day <span data-chart-days-label>(last 7 days)</span></div>
|
||||||
<svg id="chart-walk" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Minutes walked per day"></svg>
|
<svg id="chart-walk" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Minutes walked per day, with a trend line"></svg>
|
||||||
|
<!-- What the trend line says — see renderTrendNote. -->
|
||||||
|
<p id="walk-note" class="muted-note" hidden></p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -572,6 +587,14 @@
|
|||||||
placeholder="SKK chip or reg. number (optional)" />
|
placeholder="SKK chip or reg. number (optional)" />
|
||||||
</label>
|
</label>
|
||||||
<p class="settings-hint">Set your dog's SKK chip or registration number to unlock the 🌳 pedigree page.</p>
|
<p class="settings-hint">Set your dog's SKK chip or registration number to unlock the 🌳 pedigree page.</p>
|
||||||
|
<!-- Part of the synced profile rather than a device preference: it
|
||||||
|
decides what a guest is asked to log, and the server needs it so
|
||||||
|
reminders stop reading a sleep state nobody is keeping up. -->
|
||||||
|
<label class="toggle-row">
|
||||||
|
<span>Track sleep</span>
|
||||||
|
<input type="checkbox" id="settings-sleep" role="switch" class="switch" />
|
||||||
|
</label>
|
||||||
|
<p class="settings-hint">Off hides the sleep buttons, timer and charts. Sleep already logged is kept, so you can switch it back on for a day whenever you like.</p>
|
||||||
</div>
|
</div>
|
||||||
<label class="toggle-row">
|
<label class="toggle-row">
|
||||||
<span>Dark mode</span>
|
<span>Dark mode</span>
|
||||||
|
|||||||
+34
-1
@@ -17,6 +17,9 @@
|
|||||||
flip with the theme; the brights don't. --sleep itself was doing both
|
flip with the theme; the brights don't. --sleep itself was doing both
|
||||||
jobs and failing the second — 2.6:1 on the timer pill it painted. */
|
jobs and failing the second — 2.6:1 on the timer pill it painted. */
|
||||||
--sleep-ink: #4258cc;
|
--sleep-ink: #4258cc;
|
||||||
|
/* Same idea for walks: the green is a fill, and a line drawn over the
|
||||||
|
green bars needs a shade that stands off them in either theme. */
|
||||||
|
--walk-ink: #22683d;
|
||||||
--wake: #f2b705;
|
--wake: #f2b705;
|
||||||
--wake-ink: #6f4d00;
|
--wake-ink: #6f4d00;
|
||||||
/* The two timers, on the dark theme, take a near-white with a sixth of the
|
/* The two timers, on the dark theme, take a near-white with a sixth of the
|
||||||
@@ -47,6 +50,7 @@
|
|||||||
--accent: #a690ff;
|
--accent: #a690ff;
|
||||||
--accent-soft: #2a2640;
|
--accent-soft: #2a2640;
|
||||||
--sleep-ink: #8ba4ff;
|
--sleep-ink: #8ba4ff;
|
||||||
|
--walk-ink: #7fd49c;
|
||||||
--wake-ink: #f5c451;
|
--wake-ink: #f5c451;
|
||||||
--wake-timer-ink: #fdf4da;
|
--wake-timer-ink: #fdf4da;
|
||||||
--border: #2c2a3a;
|
--border: #2c2a3a;
|
||||||
@@ -61,6 +65,7 @@
|
|||||||
--accent: #a690ff;
|
--accent: #a690ff;
|
||||||
--accent-soft: #2a2640;
|
--accent-soft: #2a2640;
|
||||||
--sleep-ink: #8ba4ff;
|
--sleep-ink: #8ba4ff;
|
||||||
|
--walk-ink: #7fd49c;
|
||||||
--wake-ink: #f5c451;
|
--wake-ink: #f5c451;
|
||||||
--wake-timer-ink: #fdf4da;
|
--wake-timer-ink: #fdf4da;
|
||||||
--border: #2c2a3a;
|
--border: #2c2a3a;
|
||||||
@@ -884,10 +889,26 @@ dialog menu {
|
|||||||
and the buttons sitting on the page background between two cards. */
|
and the buttons sitting on the page background between two cards. */
|
||||||
.chart-window {
|
.chart-window {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap; /* a fourth button leaves no room for the label on a small phone */
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 10px;
|
gap: 8px 10px;
|
||||||
padding: 0 4px;
|
padding: 0 4px;
|
||||||
}
|
}
|
||||||
|
/* Custom dates get a row of their own under the buttons. */
|
||||||
|
.chart-range-fields {
|
||||||
|
flex-basis: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.chart-range-fields input[type="date"] {
|
||||||
|
flex: 1;
|
||||||
|
width: auto; /* the global input rule sets 100%, which would push the row */
|
||||||
|
min-width: 0;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
.chart-range-fields .muted-note { flex: none; white-space: nowrap; }
|
||||||
.chart-window-label {
|
.chart-window-label {
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
@@ -1369,6 +1390,18 @@ input.switch:checked::after { transform: translateX(18px); }
|
|||||||
stroke-linecap: round;
|
stroke-linecap: round;
|
||||||
fill: none;
|
fill: none;
|
||||||
}
|
}
|
||||||
|
/* The sleep and walk bars are filled with --sleep and --walk, so the fit
|
||||||
|
through each takes its ink shade — darker in light mode, lighter in dark —
|
||||||
|
to stay visible where it crosses a bar. */
|
||||||
|
.chart-svg .sleep-trend,
|
||||||
|
.chart-svg .walk-trend-line {
|
||||||
|
stroke: var(--sleep-ink);
|
||||||
|
stroke-width: 2;
|
||||||
|
stroke-dasharray: 5 3;
|
||||||
|
stroke-linecap: round;
|
||||||
|
fill: none;
|
||||||
|
}
|
||||||
|
.chart-svg .walk-trend-line { stroke: var(--walk-ink); }
|
||||||
.legend .sw.food-sw { background: var(--food-color, var(--muted)); }
|
.legend .sw.food-sw { background: var(--food-color, var(--muted)); }
|
||||||
|
|
||||||
.kind-field { margin-bottom: 10px; }
|
.kind-field { margin-bottom: 10px; }
|
||||||
|
|||||||
Reference in new issue
Block a user