mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
Rework the per-day location resolution so it can no longer fabricate weather for
days before the home was set. Precedence, first hit wins:
1. an explicit dated location period (a trip, or a corrected stretch of
history) covering the day;
2. DEVICE — a reserved slot for a future client-supplied coarse per-day
location (ranks between the period and home; not produced server-side yet);
3. the home location, but only for days on/after its effective-from date;
4. otherwise the day is skipped.
The home route stamps `homeSince` whenever the home is set/updated and returns
it. The overview exposes it. Backfill bounds are now optional and default to the
conservative `[homeSince .. today]` span instead of a fixed reach onto the
current home; days before `homeSince` still resolve to a skip in the worker, so
even a wider explicit start cannot back-fill weather for the pre-home past. To
reach further back a user adds an explicit location period for that range.
Add unit coverage for the precedence (including the effective-from boundary and
the skip-not-guess rule) and the default backfill range.
74 lines
2.6 KiB
TypeScript
74 lines
2.6 KiB
TypeScript
/**
|
|
* `PUT /api/environment/home` — set the account's coarse home location.
|
|
*
|
|
* The picked city (rounded lat/lon + label + IANA timezone) is stored on the
|
|
* user. Coordinates are rounded to ~city granularity here as a defence-in-depth
|
|
* floor even if a client sends finer values. Setting a home enqueues a
|
|
* lookback fetch so weather appears without waiting for the nightly tick.
|
|
* Module-gated; `userId` is narrowed from auth.
|
|
*/
|
|
import { NextRequest } from "next/server";
|
|
|
|
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
|
import { apiSuccess, returnAllZodIssues, safeJson } from "@/lib/api-response";
|
|
import { annotate } from "@/lib/logging/context";
|
|
import { requireModuleEnabled } from "@/lib/modules/gate";
|
|
import { prisma } from "@/lib/db";
|
|
import { homeLocationSchema } from "@/lib/validations/environment";
|
|
import { roundCoarse } from "@/lib/environment/open-meteo";
|
|
import { enqueueEnvironmentFetch } from "@/lib/jobs/environment-fetch";
|
|
|
|
export const PUT = apiHandler(async (request: NextRequest) => {
|
|
const { user } = await requireAuth();
|
|
|
|
const gate = await requireModuleEnabled(user.id, "environment");
|
|
if (!gate.enabled) return gate.response;
|
|
|
|
const { data: rawBody, error: jsonError } = await safeJson(request, {
|
|
maxBytes: 4 * 1024,
|
|
});
|
|
if (jsonError) return jsonError;
|
|
|
|
const parsed = homeLocationSchema.safeParse(rawBody);
|
|
if (!parsed.success) {
|
|
annotate({
|
|
action: { name: "environment.home.validation-failed" },
|
|
meta: { issue_count: parsed.error.issues.length },
|
|
});
|
|
return returnAllZodIssues(parsed.error, 422, {
|
|
errorCode: "environment.invalid",
|
|
});
|
|
}
|
|
|
|
const { lat, lon, label, timezone } = parsed.data;
|
|
// Stamp the effective-from instant: from now on this home resolves days; days
|
|
// before it stay un-attributed (filled via explicit location periods). Every
|
|
// set/update re-stamps — the home is "effective from the moment it is set".
|
|
const homeSince = new Date();
|
|
const home = {
|
|
homeLat: roundCoarse(lat),
|
|
homeLon: roundCoarse(lon),
|
|
homeLabel: label,
|
|
homeTimezone: timezone,
|
|
homeSince,
|
|
};
|
|
|
|
await prisma.user.update({ where: { id: user.id }, data: home });
|
|
|
|
// Kick a lookback refresh so recent days populate promptly. No-ops cleanly
|
|
// when no worker is bound; the nightly cron still covers it.
|
|
await enqueueEnvironmentFetch({ userId: user.id });
|
|
|
|
annotate({ action: { name: "environment.home.set" } });
|
|
|
|
return apiSuccess({
|
|
home: {
|
|
lat: home.homeLat,
|
|
lon: home.homeLon,
|
|
label: home.homeLabel,
|
|
timezone: home.homeTimezone,
|
|
since: homeSince.toISOString(),
|
|
},
|
|
});
|
|
});
|