mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(cycle): add cycle-tracking API surface + offline sync
Add the `/api/cycle/*` capture, calendar, history, and settings routes
plus the offline-sync delta extension for the v1.15 cycle-tracking
feature, all against the locked iOS contract.
- Enable flag: add nullable `cycleTrackingEnabled` to CycleProfile
(migration 0132). A null toggle derives from gender (FEMALE → on).
`isCycleEnabled()` is the single gate resolver; every `/api/cycle/*`
route 403s `{ errorCode: "cycle.disabled" }` when off. The resolved
flag surfaces additively on GET /api/auth/me.
- Routes (apiHandler + Zod + envelope + gate + annotate + auditLog):
POST/PATCH/DELETE day-logs (single), POST day-logs/bulk (idempotent,
capped 500, rate-limited 60/min, per-entry inserted/updated/duplicate/
skipped), POST period boundary, GET calendar (runs the deterministic
engine, debounced stale-while-revalidate cache, goal-gated fertile
window), GET cycles (history + median/MAD stats), GET profile,
DELETE cycles, PATCH /api/auth/me/cycle-prefs (deep-merge).
- Day-log note encrypts at rest (notesEncrypted); intent fields stay
queryable plaintext. Upsert keys on (userId, source, externalId) when
externalId present, else (userId, date).
- Offline sync: extend GET /api/sync/changes + the cursor with the
`cycleDays` + `cycles` domains (CURSOR_VERSION → 2). cycleDays
tombstones key on externalId else id; cycles on id.
- OpenAPI: register every route + DTO; regenerate the committed spec.
- i18n: cycle prediction disclaimer across all six locales.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
ea0d7681e2
commit
5f485ca780
34 files changed
+4738
-178
No files matched your search
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* v1.15.0 — per-user cycle-tracking preferences.
|
||||
*
|
||||
* GET /api/auth/me/cycle-prefs — current resolved CycleProfileDTO.
|
||||
* PATCH /api/auth/me/cycle-prefs — body `{ enabled?, goal?, rawChartMode?,
|
||||
* predictionEnabled?, discreetNotifications?,
|
||||
* sensitiveCategoryEncryption?,
|
||||
* typicalCycleLength?, typicalPeriodLength?,
|
||||
* lutealPhaseLength? }`. Deep-merges the
|
||||
* supplied fields over the persisted row
|
||||
* (the notification-prefs precedent) and
|
||||
* returns the merged CycleProfileDTO.
|
||||
*
|
||||
* This route does NOT enforce the cycle gate — it is the surface that
|
||||
* FLIPS the gate (`enabled` → `cycleTrackingEnabled`). `enabled` is
|
||||
* idempotent last-writer-wins; the route is otherwise idempotent.
|
||||
*/
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { getOrCreateCycleProfile } from "@/lib/cycle/profile";
|
||||
import { isCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { toCycleProfileDTO } from "@/lib/cycle/dto";
|
||||
import { cyclePrefsSchema } from "@/lib/validations/cycle";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const PATCH_RATE_LIMIT = 60;
|
||||
const PATCH_WINDOW_MS = 60_000;
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "auth.me.cycle-prefs.get" } });
|
||||
|
||||
const profile = await getOrCreateCycleProfile(user.id);
|
||||
const resolved = isCycleEnabled(user.gender, profile);
|
||||
return apiSuccess(toCycleProfileDTO(profile, resolved));
|
||||
});
|
||||
|
||||
export const PATCH = apiHandler(async (req: Request) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`cycle-prefs:patch:${user.id}`,
|
||||
PATCH_RATE_LIMIT,
|
||||
PATCH_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
const response = apiError("Too many requests", 429);
|
||||
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
|
||||
response.headers.set(k, v);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return apiError("Invalid JSON body", 422, {
|
||||
errorCode: "cycle-prefs.body.invalid_json",
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = cyclePrefsSchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "auth.me.cycle-prefs.patch.invalid_shape" },
|
||||
meta: { issues: parsed.error.issues.length },
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "cycle-prefs.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
// Ensure the row exists, then deep-merge: only the supplied fields are
|
||||
// touched; siblings are left untouched (field-by-field, no mass
|
||||
// assignment). `enabled` maps onto the `cycleTrackingEnabled` column.
|
||||
await getOrCreateCycleProfile(user.id);
|
||||
const p = parsed.data;
|
||||
|
||||
const updated = await prisma.cycleProfile.update({
|
||||
where: { userId: user.id },
|
||||
data: {
|
||||
...(p.enabled !== undefined && { cycleTrackingEnabled: p.enabled }),
|
||||
...(p.goal !== undefined && { goal: p.goal }),
|
||||
...(p.rawChartMode !== undefined && { rawChartMode: p.rawChartMode }),
|
||||
...(p.predictionEnabled !== undefined && {
|
||||
predictionEnabled: p.predictionEnabled,
|
||||
}),
|
||||
...(p.discreetNotifications !== undefined && {
|
||||
discreetNotifications: p.discreetNotifications,
|
||||
}),
|
||||
...(p.sensitiveCategoryEncryption !== undefined && {
|
||||
sensitiveCategoryEncryption: p.sensitiveCategoryEncryption,
|
||||
}),
|
||||
...(p.typicalCycleLength !== undefined && {
|
||||
typicalCycleLength: p.typicalCycleLength,
|
||||
}),
|
||||
...(p.typicalPeriodLength !== undefined && {
|
||||
typicalPeriodLength: p.typicalPeriodLength,
|
||||
}),
|
||||
...(p.lutealPhaseLength !== undefined && {
|
||||
lutealPhaseLength: p.lutealPhaseLength,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const resolved = isCycleEnabled(user.gender, updated);
|
||||
|
||||
await auditLog("user.cycle-prefs.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(req),
|
||||
details: { changed: Object.keys(p) },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "user.cycle_prefs.update" },
|
||||
meta: { changed: Object.keys(p), enabled: resolved },
|
||||
});
|
||||
|
||||
return apiSuccess(toCycleProfileDTO(updated, resolved));
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import { annotate } from "@/lib/logging/context";
|
||||
import { setOnboardingPendingCookie } from "@/lib/auth/session";
|
||||
import { buildAvatarUrl } from "@/lib/avatar";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isCycleEnabled } from "@/lib/cycle/gate";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -19,6 +21,15 @@ export const GET = apiHandler(async () => {
|
||||
|
||||
annotate({ action: { name: "auth.me" } });
|
||||
|
||||
// v1.15.0 — resolved cycle-tracking gate. Read the profile without
|
||||
// forcing a row (a NULL toggle derives from gender); the resolver
|
||||
// collapses both gates into the single boolean iOS hides the tab on.
|
||||
const cycleProfile = await prisma.cycleProfile.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: { cycleTrackingEnabled: true },
|
||||
});
|
||||
const cycleTrackingEnabled = isCycleEnabled(user.gender, cycleProfile);
|
||||
|
||||
// v1.7.0 — patient-identity fields for the health-record export. The
|
||||
// KVNR is stored encrypted; decrypt fail-soft so a key-rotation gap on
|
||||
// one row never 500s the whole profile fetch (the field just reads
|
||||
@@ -68,5 +79,8 @@ export const GET = apiHandler(async () => {
|
||||
insurerName: user.insurerName ?? null,
|
||||
insurerIkNumber: user.insurerIkNumber ?? null,
|
||||
insuranceNumber,
|
||||
// v1.15.0 — cycle-tracking feature gate, resolved server-side. iOS
|
||||
// hides the whole cycle tab when this is false.
|
||||
cycleTrackingEnabled,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* `GET /api/cycle/calendar?from&to` — predicted calendar read
|
||||
* (ios-contract §2.D).
|
||||
*
|
||||
* Calls the pure engine (`predictCycle` + per-day phase) to build
|
||||
* `{ profile, prediction, days }`. The synchronous engine call is cheap
|
||||
* (pure stats); the heavy part is the cache persist, which is debounced
|
||||
* stale-while-revalidate and fire-and-forget so it never blocks the GET.
|
||||
* Fertile-window fields are goal-gated (null unless TRYING_TO_CONCEIVE),
|
||||
* suppressed server-side.
|
||||
*
|
||||
* Default range: current cycle − 90d … +180d forward.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { cycleCalendarQuerySchema } from "@/lib/validations/cycle";
|
||||
import {
|
||||
buildCalendar,
|
||||
type CalendarDayLogRow,
|
||||
} from "@/lib/cycle/engine-adapter";
|
||||
import {
|
||||
toCyclePredictionDTO,
|
||||
goalAllowsFertileWindow,
|
||||
} from "@/lib/cycle/dto";
|
||||
import { persistPredictionCache } from "@/lib/cycle/prediction-cache";
|
||||
import { addDays } from "@/lib/cycle/day-math";
|
||||
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { resolveServerLocale } from "@/lib/i18n/server-locale";
|
||||
|
||||
const DEFAULT_PAST_DAYS = 90;
|
||||
const DEFAULT_FORWARD_DAYS = 180;
|
||||
/** Hard cap on the rendered span (days) to bound the day-grid build. */
|
||||
const MAX_SPAN_DAYS = 400;
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
const profile = gate.profile;
|
||||
|
||||
const url = new URL(request.url);
|
||||
const parsed = cycleCalendarQuerySchema.safeParse({
|
||||
from: url.searchParams.get("from") ?? undefined,
|
||||
to: url.searchParams.get("to") ?? undefined,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid calendar query", 422, {
|
||||
errorCode: "cycle.calendar.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const tz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
const today = moodDateKey(new Date(), tz);
|
||||
const from = parsed.data.from ?? addDays(today, -DEFAULT_PAST_DAYS);
|
||||
const to = parsed.data.to ?? addDays(today, DEFAULT_FORWARD_DAYS);
|
||||
|
||||
// Reject an inverted or absurdly wide range up front.
|
||||
const fromMs = Date.parse(`${from}T12:00:00Z`);
|
||||
const toMs = Date.parse(`${to}T12:00:00Z`);
|
||||
if (toMs < fromMs || (toMs - fromMs) / 86_400_000 > MAX_SPAN_DAYS) {
|
||||
return apiError("Calendar range too wide or inverted", 422, {
|
||||
errorCode: "cycle.calendar.range",
|
||||
});
|
||||
}
|
||||
|
||||
const [cycles, dayLogRows, nightlyTemps] = await Promise.all([
|
||||
prisma.menstrualCycle.findMany({
|
||||
where: { userId: user.id, deletedAt: null },
|
||||
orderBy: { startDate: "asc" },
|
||||
}),
|
||||
prisma.cycleDayLog.findMany({
|
||||
where: { userId: user.id, deletedAt: null },
|
||||
orderBy: { date: "asc" },
|
||||
select: {
|
||||
date: true,
|
||||
flow: true,
|
||||
basalBodyTempC: true,
|
||||
ovulationTest: true,
|
||||
cervicalMucus: true,
|
||||
_count: { select: { symptomLinks: true } },
|
||||
},
|
||||
}),
|
||||
// Apple Watch wrist/skin temperature feeds the temperature-trend
|
||||
// ovulation layer. Read the WRIST_TEMPERATURE measurements as nightly
|
||||
// values; the engine derives the trailing-mean deviation itself.
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
deletedAt: null,
|
||||
type: "WRIST_TEMPERATURE",
|
||||
measuredAt: {
|
||||
gte: new Date(Date.parse(`${addDays(today, -90)}T00:00:00Z`)),
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { measuredAt: true, value: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const dayLogs: CalendarDayLogRow[] = dayLogRows.map((l) => ({
|
||||
date: l.date,
|
||||
flow: l.flow,
|
||||
basalBodyTempC: l.basalBodyTempC,
|
||||
ovulationTest: l.ovulationTest,
|
||||
cervicalMucus: l.cervicalMucus,
|
||||
hasSymptoms: l._count.symptomLinks > 0,
|
||||
}));
|
||||
|
||||
const nights = nightlyTemps.map((m) => ({
|
||||
date: moodDateKey(m.measuredAt, tz),
|
||||
valueC: m.value,
|
||||
}));
|
||||
|
||||
const goalAllowsFertile = goalAllowsFertileWindow(profile.goal);
|
||||
|
||||
const { prediction, days } = buildCalendar(
|
||||
profile,
|
||||
cycles,
|
||||
dayLogs,
|
||||
nights,
|
||||
from,
|
||||
to,
|
||||
today,
|
||||
goalAllowsFertile,
|
||||
);
|
||||
|
||||
// Persist the cache fire-and-forget (debounced) — never block the read.
|
||||
let generatedAt = new Date().toISOString();
|
||||
if (prediction) {
|
||||
const now = new Date();
|
||||
generatedAt = now.toISOString();
|
||||
void persistPredictionCache(user.id, prediction, now);
|
||||
}
|
||||
|
||||
const locale = await resolveServerLocale({
|
||||
request,
|
||||
userLocale: user.locale ?? undefined,
|
||||
});
|
||||
const t = getServerTranslator(locale);
|
||||
const disclaimer = t.t("cycle.prediction.disclaimer");
|
||||
|
||||
annotate({
|
||||
action: { name: "cycle.calendar.read" },
|
||||
meta: {
|
||||
days: days.length,
|
||||
cycles_observed: prediction?.cyclesObserved ?? 0,
|
||||
has_prediction: prediction !== null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
profile: {
|
||||
goal: profile.goal,
|
||||
rawChartMode: profile.rawChartMode,
|
||||
predictionEnabled: profile.predictionEnabled,
|
||||
cyclesObserved: prediction?.cyclesObserved ?? cycles.length,
|
||||
},
|
||||
prediction: prediction
|
||||
? toCyclePredictionDTO(prediction, goalAllowsFertile, disclaimer)
|
||||
: null,
|
||||
days,
|
||||
meta: { generatedAt },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* `DELETE /api/cycle/cycles/{id}` — soft-delete a cycle
|
||||
* (ios-contract §2.F): set `deletedAt` + bump `syncVersion`, emit a
|
||||
* tombstone on the next sync page. 204. Idempotent. Owner-scoped + gated.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiError, getClientIp } from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const DELETE = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.menstrualCycle.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Cycle not found", 404);
|
||||
}
|
||||
|
||||
await prisma.menstrualCycle.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
|
||||
await auditLog("cycle.cycle.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { cycleId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "cycle.cycle.delete",
|
||||
entity_type: "menstrual_cycle",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* `GET /api/cycle/cycles?limit=24` — cycle history + summary stats
|
||||
* (ios-contract §2.E).
|
||||
*
|
||||
* Returns the most recent observed cycles (newest first) plus
|
||||
* `{ avgLengthDays, lengthVariabilityDays (MAD), avgPeriodLengthDays,
|
||||
* regularity }`. The median / MAD reuse the engine helpers so the stats
|
||||
* match the prediction's own variability math.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { cycleHistoryQuerySchema } from "@/lib/validations/cycle";
|
||||
import { toMenstrualCycleDTO } from "@/lib/cycle/dto";
|
||||
import { median, mad } from "@/lib/cycle";
|
||||
import { dayDiff } from "@/lib/cycle/day-math";
|
||||
import { MIN_CYCLES_TO_PREDICT } from "@/lib/cycle/types";
|
||||
|
||||
const DEFAULT_LIMIT = 24;
|
||||
|
||||
/**
|
||||
* Regularity gate. < MIN_CYCLES → LEARNING; a length MAD at/under 2 days
|
||||
* (the clinical "regular cycle" rule of thumb) → REGULAR, else IRREGULAR.
|
||||
*/
|
||||
const REGULAR_MAD_THRESHOLD = 2;
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const url = new URL(request.url);
|
||||
const parsed = cycleHistoryQuerySchema.safeParse({
|
||||
limit: url.searchParams.get("limit") ?? undefined,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return apiError("Invalid history query", 422, {
|
||||
errorCode: "cycle.cycles.invalid",
|
||||
});
|
||||
}
|
||||
const limit = parsed.data.limit ?? DEFAULT_LIMIT;
|
||||
|
||||
const rows = await prisma.menstrualCycle.findMany({
|
||||
where: { userId: user.id, deletedAt: null },
|
||||
orderBy: { startDate: "desc" },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
// Completed lengths (non-null lengthDays) drive the length stats.
|
||||
const lengths = rows
|
||||
.map((r) => r.lengthDays)
|
||||
.filter((l): l is number => l != null && l > 0);
|
||||
|
||||
// Period lengths from periodEndDate − startDate + 1.
|
||||
const periodLengths = rows
|
||||
.filter((r) => r.periodEndDate != null)
|
||||
.map((r) => dayDiff(r.periodEndDate as string, r.startDate) + 1)
|
||||
.filter((l) => l > 0);
|
||||
|
||||
let avgLengthDays: number | null = null;
|
||||
let lengthVariabilityDays: number | null = null;
|
||||
let avgPeriodLengthDays: number | null = null;
|
||||
let regularity: "REGULAR" | "IRREGULAR" | "LEARNING" = "LEARNING";
|
||||
|
||||
if (lengths.length > 0) {
|
||||
const med = median(lengths);
|
||||
avgLengthDays = Math.round(med);
|
||||
lengthVariabilityDays = Math.round(mad(lengths, med) * 10) / 10;
|
||||
if (lengths.length < MIN_CYCLES_TO_PREDICT) {
|
||||
regularity = "LEARNING";
|
||||
} else {
|
||||
regularity =
|
||||
lengthVariabilityDays <= REGULAR_MAD_THRESHOLD ? "REGULAR" : "IRREGULAR";
|
||||
}
|
||||
}
|
||||
if (periodLengths.length > 0) {
|
||||
avgPeriodLengthDays = Math.round(median(periodLengths));
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: { name: "cycle.cycles.read" },
|
||||
meta: { returned: rows.length, regularity },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
cycles: rows.map(toMenstrualCycleDTO),
|
||||
stats: {
|
||||
avgLengthDays,
|
||||
lengthVariabilityDays,
|
||||
avgPeriodLengthDays,
|
||||
regularity,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* `PATCH /api/cycle/day-logs/{id}` — edit a single day-log
|
||||
* (ios-contract §2.A).
|
||||
* `DELETE /api/cycle/day-logs/{id}` — soft-delete (ios-contract §2.F):
|
||||
* set `deletedAt` + bump `syncVersion`, emit a tombstone on the next
|
||||
* sync page. 204. Idempotent.
|
||||
*
|
||||
* Both are gated (`cycle.disabled` 403) and owner-scoped (a row owned by
|
||||
* another user 404s).
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiSuccess,
|
||||
apiError,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { cycleDayLogPatchSchema } from "@/lib/validations/cycle";
|
||||
import { toCycleDayLogDTO, dayLogSymptomInclude } from "@/lib/cycle/dto";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
export const PATCH = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.cycleDayLog.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Day-log not found", 404);
|
||||
}
|
||||
|
||||
const { data: rawBody, error: jsonError } = await safeJson(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = cycleDayLogPatchSchema.safeParse(rawBody);
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "cycle.day-log.patch.validation-failed" },
|
||||
meta: { issue_count: parsed.error.issues.length },
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "cycle.day-log.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const body = parsed.data;
|
||||
|
||||
// Field-by-field update (no mass assignment). Every field is
|
||||
// optional; an omitted field is left untouched. `note` re-encrypts;
|
||||
// an explicit null clears it.
|
||||
await prisma.cycleDayLog.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(body.flow !== undefined && { flow: body.flow }),
|
||||
...(body.intermenstrualBleeding !== undefined && {
|
||||
intermenstrualBleeding: body.intermenstrualBleeding,
|
||||
}),
|
||||
...(body.basalBodyTempC !== undefined && {
|
||||
basalBodyTempC: body.basalBodyTempC,
|
||||
}),
|
||||
...(body.ovulationTest !== undefined && {
|
||||
ovulationTest: body.ovulationTest,
|
||||
}),
|
||||
...(body.cervicalMucus !== undefined && {
|
||||
cervicalMucus: body.cervicalMucus,
|
||||
}),
|
||||
...(body.sexualActivity !== undefined && {
|
||||
sexualActivity: body.sexualActivity,
|
||||
}),
|
||||
...(body.protectedSex !== undefined && {
|
||||
protectedSex: body.protectedSex,
|
||||
}),
|
||||
...(body.pregnancyTest !== undefined && {
|
||||
pregnancyTest: body.pregnancyTest,
|
||||
}),
|
||||
...(body.progesteroneTest !== undefined && {
|
||||
progesteroneTest: body.progesteroneTest,
|
||||
}),
|
||||
...(body.contraceptive !== undefined && {
|
||||
contraceptive: body.contraceptive,
|
||||
}),
|
||||
...(body.note !== undefined && {
|
||||
notesEncrypted: body.note ? encrypt(body.note) : null,
|
||||
}),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
// Replace symptom links only when `symptoms` was supplied.
|
||||
if (body.symptoms !== undefined) {
|
||||
const keys = Array.from(new Set(body.symptoms.map((s) => s.key)));
|
||||
const symptoms =
|
||||
keys.length > 0
|
||||
? await prisma.cycleSymptom.findMany({
|
||||
where: {
|
||||
key: { in: keys },
|
||||
isActive: true,
|
||||
OR: [{ userId: null }, { userId: user.id }],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
await prisma.cycleSymptomLink.deleteMany({ where: { dayLogId: id } });
|
||||
if (symptoms.length > 0) {
|
||||
await prisma.cycleSymptomLink.createMany({
|
||||
data: symptoms.map((s) => ({ dayLogId: id, symptomId: s.id })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const row = await prisma.cycleDayLog.findUniqueOrThrow({
|
||||
where: { id },
|
||||
include: dayLogSymptomInclude,
|
||||
});
|
||||
|
||||
await auditLog("cycle.day-log.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { dayLogId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "cycle.day-log.update",
|
||||
entity_type: "cycle_day_log",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(toCycleDayLogDTO(row));
|
||||
},
|
||||
);
|
||||
|
||||
export const DELETE = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await prisma.cycleDayLog.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Day-log not found", 404);
|
||||
}
|
||||
|
||||
// Soft-delete: leave the row in place so the `/api/sync/changes`
|
||||
// delta feed surfaces it as a tombstone. A re-delete re-bumps
|
||||
// `syncVersion` harmlessly (idempotent).
|
||||
await prisma.cycleDayLog.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
|
||||
await auditLog("cycle.day-log.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { dayLogId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "cycle.day-log.delete",
|
||||
entity_type: "cycle_day_log",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* `POST /api/cycle/day-logs/bulk` — Outbox / HealthKit drain
|
||||
* (ios-contract §2.B / §3).
|
||||
*
|
||||
* The route iOS's Outbox flushes to. Per-entry UPSERT keyed on the
|
||||
* NULL-distinct `(userId, source, externalId)` (or `(userId, date)`
|
||||
* when no externalId). Capped at 500, wrapped in `withIdempotency`,
|
||||
* rate-limited `cycle:day-logs:bulk:{userId}` 60/min. Always 200; each
|
||||
* entry carries `{ index, status, id?, externalId?, reason? }` where
|
||||
* status is `inserted` | `duplicate` | `updated` | `skipped`. `updated`
|
||||
* = an externalId re-post that changed a field; `duplicate` = an
|
||||
* unchanged re-post.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiSuccess,
|
||||
apiError,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
sanitiseZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { cycleBulkSchema, MAX_CYCLE_BULK_ENTRIES } from "@/lib/validations/cycle";
|
||||
import { upsertCycleDayLog } from "@/lib/cycle/day-log-write";
|
||||
import { findOwningCycleId } from "@/lib/cycle/cycle-attribution";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
|
||||
const BATCH_RATE_LIMIT_MAX = 60;
|
||||
const BATCH_RATE_LIMIT_WINDOW_MS = 60 * 1000;
|
||||
|
||||
type EntryStatus = "inserted" | "duplicate" | "updated" | "skipped";
|
||||
interface EntryResult {
|
||||
index: number;
|
||||
status: EntryStatus;
|
||||
id?: string;
|
||||
externalId?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postBulk));
|
||||
|
||||
async function postBulk(request: NextRequest): Promise<Response> {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`cycle:day-logs:bulk:${user.id}`,
|
||||
BATCH_RATE_LIMIT_MAX,
|
||||
BATCH_RATE_LIMIT_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Too many bulk submissions, try again later", 429);
|
||||
}
|
||||
|
||||
const { data: rawBody, error: jsonError } = await safeJson(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
if (
|
||||
typeof rawBody === "object" &&
|
||||
rawBody !== null &&
|
||||
"entries" in rawBody &&
|
||||
Array.isArray((rawBody as { entries: unknown }).entries) &&
|
||||
(rawBody as { entries: unknown[] }).entries.length > MAX_CYCLE_BULK_ENTRIES
|
||||
) {
|
||||
return apiError(
|
||||
`Batch exceeds the ${MAX_CYCLE_BULK_ENTRIES}-entry limit`,
|
||||
422,
|
||||
{ errorCode: "cycle.bulk.too_large" },
|
||||
);
|
||||
}
|
||||
|
||||
const parsed = cycleBulkSchema.safeParse(rawBody);
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "cycle.bulk.validation-failed" },
|
||||
meta: { issue_count: sanitiseZodIssues(parsed.error.issues).length },
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "cycle.bulk.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const { entries } = parsed.data;
|
||||
const tz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
|
||||
const results: EntryResult[] = [];
|
||||
let inserted = 0;
|
||||
let updated = 0;
|
||||
let duplicates = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
try {
|
||||
const cycleId = await findOwningCycleId(user.id, entry.date);
|
||||
const r = await upsertCycleDayLog(user.id, entry, tz, cycleId);
|
||||
|
||||
let status: EntryStatus;
|
||||
if (!r.existed) {
|
||||
status = "inserted";
|
||||
inserted += 1;
|
||||
} else if (r.changed) {
|
||||
status = "updated";
|
||||
updated += 1;
|
||||
} else {
|
||||
status = "duplicate";
|
||||
duplicates += 1;
|
||||
}
|
||||
|
||||
results.push({
|
||||
index: i,
|
||||
status,
|
||||
id: r.id,
|
||||
...(entry.externalId ? { externalId: entry.externalId } : {}),
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const reason =
|
||||
err instanceof Error ? err.message.slice(0, 120) : "upsert_failed";
|
||||
skipped += 1;
|
||||
results.push({
|
||||
index: i,
|
||||
status: "skipped",
|
||||
reason,
|
||||
...(entry.externalId ? { externalId: entry.externalId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await auditLog("cycle.bulk.ingest", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
processed: entries.length,
|
||||
inserted,
|
||||
updated,
|
||||
duplicates,
|
||||
skipped,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "cycle.bulk.ingest" },
|
||||
meta: {
|
||||
processed: entries.length,
|
||||
inserted,
|
||||
updated,
|
||||
duplicates,
|
||||
skipped,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
processed: entries.length,
|
||||
inserted,
|
||||
updated,
|
||||
duplicates,
|
||||
skipped,
|
||||
entries: results,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* `POST /api/cycle/day-logs` — single cycle day-log capture
|
||||
* (ios-contract §2.A).
|
||||
*
|
||||
* Upserts on `(userId, source, externalId)` when an `externalId` is
|
||||
* present (the cross-device dedup key), else the canonical `(userId,
|
||||
* date)` key. `note` is encrypted at rest (`notesEncrypted`); the intent
|
||||
* fields stay queryable plaintext (they feed the rollup / correlation
|
||||
* tier). Returns the full `CycleDayLogDTO`: 201 on insert, 200 on update.
|
||||
*
|
||||
* Gated: a disabled / non-FEMALE-without-opt-in account 403s with
|
||||
* `errorCode:"cycle.disabled"` even with a valid Bearer token.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { cycleDayLogInputSchema } from "@/lib/validations/cycle";
|
||||
import { upsertCycleDayLog } from "@/lib/cycle/day-log-write";
|
||||
import { findOwningCycleId } from "@/lib/cycle/cycle-attribution";
|
||||
import { toCycleDayLogDTO, dayLogSymptomInclude } from "@/lib/cycle/dto";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postDayLog));
|
||||
|
||||
async function postDayLog(request: NextRequest): Promise<Response> {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const { data: rawBody, error: jsonError } = await safeJson(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = cycleDayLogInputSchema.safeParse(rawBody);
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "cycle.day-log.validation-failed" },
|
||||
meta: { issue_count: parsed.error.issues.length },
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "cycle.day-log.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const entry = parsed.data;
|
||||
const tz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
|
||||
const cycleId = await findOwningCycleId(user.id, entry.date);
|
||||
const result = await upsertCycleDayLog(user.id, entry, tz, cycleId);
|
||||
|
||||
const row = await prisma.cycleDayLog.findUniqueOrThrow({
|
||||
where: { id: result.id },
|
||||
include: dayLogSymptomInclude,
|
||||
});
|
||||
|
||||
await auditLog("cycle.day-log.upsert", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { dayLogId: result.id, existed: result.existed },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "cycle.day-log.upsert",
|
||||
entity_type: "cycle_day_log",
|
||||
entity_id: result.id,
|
||||
},
|
||||
meta: { existed: result.existed, source: entry.source },
|
||||
});
|
||||
|
||||
return apiSuccess(toCycleDayLogDTO(row), result.existed ? 200 : 201);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* `POST /api/cycle/period` — one-tap period-boundary shortcut
|
||||
* (ios-contract §2.C).
|
||||
*
|
||||
* `action:"start"` opens a new `MenstrualCycle` anchored at `date`,
|
||||
* closes the prior open cycle (endDate = day before, lengthDays set),
|
||||
* and writes the boundary `CycleDayLog(flow=MEDIUM)`. `action:"end"`
|
||||
* stamps the current cycle's `periodEndDate` and writes the boundary
|
||||
* day-log. Convenience over §2.A; returns
|
||||
* `{ cycle: MenstrualCycleDTO, dayLog: CycleDayLogDTO }`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { cyclePeriodSchema } from "@/lib/validations/cycle";
|
||||
import { upsertCycleDayLog } from "@/lib/cycle/day-log-write";
|
||||
import {
|
||||
toCycleDayLogDTO,
|
||||
toMenstrualCycleDTO,
|
||||
dayLogSymptomInclude,
|
||||
} from "@/lib/cycle/dto";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { addDays, dayDiff } from "@/lib/cycle/day-math";
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const { data: rawBody, error: jsonError } = await safeJson(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = cyclePeriodSchema.safeParse(rawBody);
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "cycle.period.validation-failed" },
|
||||
meta: { issue_count: parsed.error.issues.length },
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "cycle.period.invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const { action, date, externalId, loggedAt } = parsed.data;
|
||||
const tz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
|
||||
let cycleId: string;
|
||||
|
||||
if (action === "start") {
|
||||
// Close the prior open cycle (its end is the day before this start)
|
||||
// and record its observed length.
|
||||
const prior = await prisma.menstrualCycle.findFirst({
|
||||
where: { userId: user.id, deletedAt: null, startDate: { lt: date } },
|
||||
orderBy: { startDate: "desc" },
|
||||
select: { id: true, startDate: true },
|
||||
});
|
||||
if (prior) {
|
||||
await prisma.menstrualCycle.update({
|
||||
where: { id: prior.id },
|
||||
data: {
|
||||
endDate: addDays(date, -1),
|
||||
lengthDays: dayDiff(date, prior.startDate),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Upsert the new cycle on the `(userId, startDate)` unique so a
|
||||
// re-tap on the same day is idempotent.
|
||||
const cycle = await prisma.menstrualCycle.upsert({
|
||||
where: { userId_startDate: { userId: user.id, startDate: date } },
|
||||
create: { userId: user.id, startDate: date, tz, isPredicted: false },
|
||||
update: { deletedAt: null, isPredicted: false, syncVersion: { increment: 1 } },
|
||||
});
|
||||
cycleId = cycle.id;
|
||||
} else {
|
||||
// `end`: stamp the current cycle's periodEndDate.
|
||||
const current = await prisma.menstrualCycle.findFirst({
|
||||
where: { userId: user.id, deletedAt: null, startDate: { lte: date } },
|
||||
orderBy: { startDate: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!current) {
|
||||
return apiSuccessNoCycle();
|
||||
}
|
||||
await prisma.menstrualCycle.update({
|
||||
where: { id: current.id },
|
||||
data: { periodEndDate: date, syncVersion: { increment: 1 } },
|
||||
});
|
||||
cycleId = current.id;
|
||||
}
|
||||
|
||||
// Boundary day-log. Start → MEDIUM flow opens the bleed; end → SPOTTING
|
||||
// tail (the last logged bleeding day).
|
||||
await upsertCycleDayLog(
|
||||
user.id,
|
||||
{
|
||||
date,
|
||||
flow: action === "start" ? "MEDIUM" : "SPOTTING",
|
||||
loggedAt,
|
||||
source: "MANUAL",
|
||||
...(externalId ? { externalId } : {}),
|
||||
},
|
||||
tz,
|
||||
cycleId,
|
||||
);
|
||||
|
||||
const [cycleRow, dayLogRow] = await Promise.all([
|
||||
prisma.menstrualCycle.findUniqueOrThrow({ where: { id: cycleId } }),
|
||||
prisma.cycleDayLog.findFirstOrThrow({
|
||||
where: { userId: user.id, date, deletedAt: null },
|
||||
include: dayLogSymptomInclude,
|
||||
}),
|
||||
]);
|
||||
|
||||
await auditLog("cycle.period.boundary", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { action, date, cycleId },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "cycle.period.boundary",
|
||||
entity_type: "menstrual_cycle",
|
||||
entity_id: cycleId,
|
||||
},
|
||||
meta: { boundary: action },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
cycle: toMenstrualCycleDTO(cycleRow),
|
||||
dayLog: toCycleDayLogDTO(dayLogRow),
|
||||
});
|
||||
});
|
||||
|
||||
/** `end` with no preceding cycle is a no-op the client should not hit. */
|
||||
function apiSuccessNoCycle(): Response {
|
||||
return apiSuccess({ cycle: null, dayLog: null });
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* `GET /api/cycle/profile` — full CycleProfileDTO (ios-contract §2.G).
|
||||
*
|
||||
* Gated like every cycle route; returns the lazily-upserted profile with
|
||||
* the resolved `cycleTrackingEnabled`.
|
||||
*/
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { isCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { toCycleProfileDTO } from "@/lib/cycle/dto";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const gate = await requireCycleEnabled(user.id, user.gender);
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const resolved = isCycleEnabled(user.gender, gate.profile);
|
||||
|
||||
annotate({ action: { name: "cycle.profile.read" } });
|
||||
|
||||
return apiSuccess(toCycleProfileDTO(gate.profile, resolved));
|
||||
});
|
||||
@@ -8,7 +8,9 @@
|
||||
* domain now soft-delete (set `deletedAt` + bump `syncVersion`) rather
|
||||
* than hard-delete.
|
||||
*
|
||||
* Domains served: `measurements`, `mood`, `intakes`. The iOS consumer
|
||||
* Domains served: `measurements`, `mood`, `intakes`, `cycleDays`,
|
||||
* `cycles` (the last two added v1.15.0; `cycleDays` tombstones key on
|
||||
* `externalId` when present else `id`, `cycles` on `id`). The iOS consumer
|
||||
* is measurements-only this cycle (iOS-coord
|
||||
* `v1.7.0-ios-offline-sync-answers.md` §7.1); mood + intakes are
|
||||
* forward-prep so the contract is complete + tested before the
|
||||
@@ -57,6 +59,13 @@ import {
|
||||
type SyncCursor,
|
||||
type SyncDomain,
|
||||
} from "@/lib/sync/cursor";
|
||||
import {
|
||||
toCycleDayLogDTO,
|
||||
toMenstrualCycleDTO,
|
||||
dayLogSymptomInclude,
|
||||
type CycleDayLogDTO,
|
||||
type MenstrualCycleDTO,
|
||||
} from "@/lib/cycle/dto";
|
||||
|
||||
const DEFAULT_LIMIT = 200;
|
||||
const MAX_LIMIT = 500;
|
||||
@@ -126,6 +135,25 @@ interface IntakeTombstone {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// v1.15.0 — cycle domains. cycleDays key tombstones on `externalId` when
|
||||
// present (HealthKit-origin rows are externalId-keyed cross-device, like
|
||||
// measurements) else the server `id`; cycles key on the server `id`
|
||||
// (computed rows carry no externalId).
|
||||
interface CycleDayTombstone {
|
||||
id: string;
|
||||
externalId: string | null;
|
||||
syncVersion: number;
|
||||
deletedAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface CycleTombstone {
|
||||
id: string;
|
||||
syncVersion: number;
|
||||
deletedAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `(updatedAt, id)` keyset predicate for a domain's watermark.
|
||||
* Empty object (full scan) when the client has no watermark for it yet.
|
||||
@@ -196,6 +224,8 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
measurements: { upserts: [], tombstones: [] },
|
||||
mood: { upserts: [], tombstones: [] },
|
||||
intakes: { upserts: [], tombstones: [] },
|
||||
cycleDays: { upserts: [], tombstones: [] },
|
||||
cycles: { upserts: [], tombstones: [] },
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -204,7 +234,8 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
// same scan — a soft-delete bumps `updatedAt`, so a tombstone is just a
|
||||
// row whose `deletedAt` is non-null. Fetch limit+1 to detect `hasMore`
|
||||
// without a count query.
|
||||
const [measurementRows, moodRows, intakeRows] = await Promise.all([
|
||||
const [measurementRows, moodRows, intakeRows, cycleDayRows, cycleRows] =
|
||||
await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where: { userId: user.id, ...keysetFilter(cursor.measurements) },
|
||||
orderBy: [{ updatedAt: "asc" }, { id: "asc" }],
|
||||
@@ -257,6 +288,17 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.cycleDayLog.findMany({
|
||||
where: { userId: user.id, ...keysetFilter(cursor.cycleDays) },
|
||||
orderBy: [{ updatedAt: "asc" }, { id: "asc" }],
|
||||
take: limit + 1,
|
||||
include: dayLogSymptomInclude,
|
||||
}),
|
||||
prisma.menstrualCycle.findMany({
|
||||
where: { userId: user.id, ...keysetFilter(cursor.cycles) },
|
||||
orderBy: [{ updatedAt: "asc" }, { id: "asc" }],
|
||||
take: limit + 1,
|
||||
}),
|
||||
]);
|
||||
|
||||
const nextCursor: SyncCursor = { ...cursor };
|
||||
@@ -354,6 +396,49 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
advanceCursor(nextCursor, "intakes", intakePage);
|
||||
hasMore = hasMore || intakeHasMore;
|
||||
|
||||
// ── cycleDays ─────────────────────────────────────────────
|
||||
const cycleDayHasMore = cycleDayRows.length > limit;
|
||||
const cycleDayPage = cycleDayHasMore
|
||||
? cycleDayRows.slice(0, limit)
|
||||
: cycleDayRows;
|
||||
const cycleDayUpserts: CycleDayLogDTO[] = [];
|
||||
const cycleDayTombstones: CycleDayTombstone[] = [];
|
||||
for (const row of cycleDayPage) {
|
||||
if (row.deletedAt) {
|
||||
cycleDayTombstones.push({
|
||||
id: row.id,
|
||||
externalId: row.externalId,
|
||||
syncVersion: row.syncVersion,
|
||||
deletedAt: row.deletedAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
});
|
||||
} else {
|
||||
cycleDayUpserts.push(toCycleDayLogDTO(row));
|
||||
}
|
||||
}
|
||||
advanceCursor(nextCursor, "cycleDays", cycleDayPage);
|
||||
hasMore = hasMore || cycleDayHasMore;
|
||||
|
||||
// ── cycles ────────────────────────────────────────────────
|
||||
const cycleHasMore = cycleRows.length > limit;
|
||||
const cyclePage = cycleHasMore ? cycleRows.slice(0, limit) : cycleRows;
|
||||
const cycleUpserts: MenstrualCycleDTO[] = [];
|
||||
const cycleTombstones: CycleTombstone[] = [];
|
||||
for (const row of cyclePage) {
|
||||
if (row.deletedAt) {
|
||||
cycleTombstones.push({
|
||||
id: row.id,
|
||||
syncVersion: row.syncVersion,
|
||||
deletedAt: row.deletedAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
});
|
||||
} else {
|
||||
cycleUpserts.push(toMenstrualCycleDTO(row));
|
||||
}
|
||||
}
|
||||
advanceCursor(nextCursor, "cycles", cyclePage);
|
||||
hasMore = hasMore || cycleHasMore;
|
||||
|
||||
annotate({
|
||||
action: { name: "sync.changes.pull" },
|
||||
meta: {
|
||||
@@ -363,6 +448,10 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
mood_tombstones: moodTombstones.length,
|
||||
intake_upserts: intakeUpserts.length,
|
||||
intake_tombstones: intakeTombstones.length,
|
||||
cycle_day_upserts: cycleDayUpserts.length,
|
||||
cycle_day_tombstones: cycleDayTombstones.length,
|
||||
cycle_upserts: cycleUpserts.length,
|
||||
cycle_tombstones: cycleTombstones.length,
|
||||
has_more: hasMore,
|
||||
cursor_present: Boolean(parsed.data.cursor),
|
||||
},
|
||||
@@ -380,6 +469,11 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
},
|
||||
mood: { upserts: moodUpserts, tombstones: moodTombstones },
|
||||
intakes: { upserts: intakeUpserts, tombstones: intakeTombstones },
|
||||
cycleDays: {
|
||||
upserts: cycleDayUpserts,
|
||||
tombstones: cycleDayTombstones,
|
||||
},
|
||||
cycles: { upserts: cycleUpserts, tombstones: cycleTombstones },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user