fix(measurements): delete a blood-pressure reading as one

Systolic, diastolic and the cuff's pulse are three rows with no link
column, and the single DELETE tombstoned only the row it was given, so
deleting a reading's systolic left its diastolic and pulse behind as half
a reading. The bulk delete had the same gap.

A reading is the rows with the same owner, the same source and the
identical measuredAt: that is how the entry form, the MCP write, a
Withings measure group and a HealthKit correlation all store one, and how
the FHIR read pairs a diastolic onto its systolic. The looser five-minute
pairing of the chart reads is right for drawing a point and wrong for
taking rows away.

Deleting a systolic or diastolic now tombstones the rest of its reading in
the same transaction with the same deletedAt, each row with its own
syncVersion bump so paired clients see every tombstone. The restore route
brings back the rows deleted together with a named half (identical
deletedAt), so the undo, which names only the row that was tapped, puts
the whole reading back, from the web list and from any client that calls
it the same way. A pulse is still deleted on its own, and a row deleted at
another moment stays deleted. The response shapes do not change; the
OpenAPI descriptions say what the counts now include.
This commit is contained in:
Marc-André Bombeck committed 2026-10-29 08:56:19 +01:00
1 parent d88313e929
commit e2998183c8
9 files changed
+430 -48

No files matched your search

+39 -8
View File
@@ -23,6 +23,7 @@ import {
} from "@/lib/measurements/apple-health-mirror";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { afterMeasurementMutation } from "@/lib/rollups/after-measurement-mutation";
import { bloodPressureSiblings } from "@/lib/measurements/blood-pressure-reading";
import { Prisma, type MeasurementType } from "@/generated/prisma/client";
import { NextRequest } from "next/server";
import { z } from "zod";
@@ -237,18 +238,45 @@ export const DELETE = apiHandler(
// (see `measurements/route.ts:100`), so the row is invisible to
// normal reads from this point on. A row that is already tombstoned
// re-bumps `syncVersion` harmlessly (idempotent re-delete).
await prisma.measurement.update({
where: { id },
data: {
deletedAt: new Date(),
syncVersion: { increment: 1 },
},
//
// A systolic or diastolic takes the rest of its reading with it (the
// other half and the cuff's pulse, `bloodPressureSiblings`), in the same
// transaction and with the same `deletedAt`, which is how the restore
// route knows to bring them back together. Each sibling bumps its own
// `syncVersion`, so a paired client sees every row's tombstone.
const deletedAt = new Date();
const siblings = await prisma.$transaction(async (tx) => {
const found = await bloodPressureSiblings(
tx,
user.id,
[existing],
"live",
);
await tx.measurement.update({
where: { id },
data: { deletedAt, syncVersion: { increment: 1 } },
});
if (found.length > 0) {
await tx.measurement.updateMany({
where: {
id: { in: found.map((s) => s.id) },
userId: user.id,
deletedAt: null,
},
data: { deletedAt, syncVersion: { increment: 1 } },
});
}
return found;
});
await auditLog("measurement.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: { measurementId: id, type: existing.type },
details: {
measurementId: id,
type: existing.type,
readingRows: siblings.length,
},
});
annotate({
@@ -269,7 +297,10 @@ export const DELETE = apiHandler(
// the rollup row when the day's measurement count goes to zero).
await afterMeasurementMutation(
user.id,
[{ type: existing.type, measuredAt: existing.measuredAt }],
[
{ type: existing.type, measuredAt: existing.measuredAt },
...siblings.map((s) => ({ type: s.type, measuredAt: s.measuredAt })),
],
{ source: "manual" },
);
@@ -10,15 +10,19 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
vi.mock("@/lib/db", () => {
const prisma = {
measurement: {
findMany: vi.fn(),
updateMany: vi.fn(),
},
auditLog: { create: vi.fn() },
},
}));
// The read and the write run in one transaction; the stub hands the
// callback the same mocked client.
$transaction: vi.fn(async (fn: (tx: unknown) => unknown) => fn(prisma)),
};
return { prisma };
});
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
@@ -113,8 +117,16 @@ describe("POST /api/measurements/bulk-delete", () => {
it("soft-deletes only owned, non-tombstoned rows and returns that count", async () => {
// Caller asked for 3 ids but only 2 are owned + live.
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T08:00:00Z") },
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T20:00:00Z") },
{
id: "m1",
type: "WEIGHT",
measuredAt: new Date("2026-01-01T08:00:00Z"),
},
{
id: "m2",
type: "WEIGHT",
measuredAt: new Date("2026-01-01T20:00:00Z"),
},
] as never);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({
count: 2,
@@ -129,7 +141,9 @@ describe("POST /api/measurements/bulk-delete", () => {
// never 404s, it's just excluded from the count.
const call = vi.mocked(prisma.measurement.updateMany).mock.calls[0][0];
expect(call.where).toMatchObject({
id: { in: ["m1", "m2", "foreign"] },
// The write names the rows the scoped read found, never the
// forged id the caller sent.
id: { in: ["m1", "m2"] },
userId: "user-1",
deletedAt: null,
});
+23 -10
View File
@@ -7,6 +7,8 @@
*
* Soft-deletes (tombstones) every owned, not-already-deleted row in one
* `updateMany` — matching the single-DELETE iOS tombstone contract. A
* selected blood-pressure half takes the rest of its reading with it, as the
* single DELETE does, and `deleted` counts every row tombstoned. A
* forged / foreign id is a silent no-op (never a 404 existence leak): the
* mutation `where` pins `userId` so it only ever touches the caller's rows.
*
@@ -26,6 +28,7 @@ import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { afterMeasurementMutation } from "@/lib/rollups/after-measurement-mutation";
import { bloodPressureSiblings } from "@/lib/measurements/blood-pressure-reading";
import type { MeasurementType } from "@/generated/prisma/client";
const MAX_IDS_PER_BATCH = 200;
@@ -73,17 +76,27 @@ async function postBulkDelete(request: NextRequest): Promise<Response> {
// a status-insight cache drop. Ownership-scoped + `deletedAt: null` so
// a forged / foreign / already-tombstoned id is excluded here exactly
// as it is from the mutation below — no existence leak.
const affected = await prisma.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: null },
select: { type: true, measuredAt: true },
});
//
// A selected systolic or diastolic brings the rest of its reading (the
// other half and the cuff's pulse, `bloodPressureSiblings`) into the same
// statement, so the shared `deletedAt` lets the restore route bring the
// reading back whole.
const { affected, count } = await prisma.$transaction(async (tx) => {
const selected = await tx.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: null },
select: { id: true, type: true, source: true, measuredAt: true },
});
const siblings = await bloodPressureSiblings(tx, user.id, selected, "live");
const rowIds = [...selected, ...siblings].map((row) => row.id);
// Soft-delete (tombstone) in one statement. The `where` pins `userId`
// so a forged id for another user is silently a no-op; `deletedAt: null`
// keeps the count honest (an already-tombstoned id doesn't re-count).
const { count } = await prisma.measurement.updateMany({
where: { id: { in: ids }, userId: user.id, deletedAt: null },
data: { deletedAt: now, syncVersion: { increment: 1 } },
// Soft-delete (tombstone) in one statement. The `where` pins `userId`
// so a forged id for another user is silently a no-op; `deletedAt: null`
// keeps the count honest (an already-tombstoned id doesn't re-count).
const { count } = await tx.measurement.updateMany({
where: { id: { in: rowIds }, userId: user.id, deletedAt: null },
data: { deletedAt: now, syncVersion: { increment: 1 } },
});
return { affected: [...selected, ...siblings], count };
});
await auditLog("measurement.delete.bulk", {
@@ -10,15 +10,19 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
vi.mock("@/lib/db", () => {
const prisma = {
measurement: {
findMany: vi.fn(),
updateMany: vi.fn(),
},
auditLog: { create: vi.fn() },
},
}));
// The read and the write run in one transaction; the stub hands the
// callback the same mocked client.
$transaction: vi.fn(async (fn: (tx: unknown) => unknown) => fn(prisma)),
};
return { prisma };
});
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
@@ -110,8 +114,16 @@ describe("POST /api/measurements/restore", () => {
it("un-tombstones only owned, tombstoned rows and returns that count", async () => {
// Caller asked for 3 ids but only 2 are owned + tombstoned.
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T08:00:00Z") },
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T20:00:00Z") },
{
id: "m1",
type: "WEIGHT",
measuredAt: new Date("2026-01-01T08:00:00Z"),
},
{
id: "m2",
type: "WEIGHT",
measuredAt: new Date("2026-01-01T20:00:00Z"),
},
] as never);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({
count: 2,
@@ -126,7 +138,9 @@ describe("POST /api/measurements/restore", () => {
// forged / live id never 404s, it's just excluded from the count.
const call = vi.mocked(prisma.measurement.updateMany).mock.calls[0][0];
expect(call.where).toMatchObject({
id: { in: ["m1", "m2", "foreign"] },
// The write names the rows the scoped read found, never the
// forged id the caller sent.
id: { in: ["m1", "m2"] },
userId: "user-1",
deletedAt: { not: null },
});
+33 -10
View File
@@ -28,6 +28,7 @@ import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { afterMeasurementMutation } from "@/lib/rollups/after-measurement-mutation";
import { bloodPressureSiblings } from "@/lib/measurements/blood-pressure-reading";
import type { MeasurementType } from "@/generated/prisma/client";
const MAX_IDS_PER_BATCH = 200;
@@ -73,17 +74,39 @@ async function postRestore(request: NextRequest): Promise<Response> {
// a status-insight cache drop. Ownership-scoped + `deletedAt != null`
// so a forged / foreign / never-deleted id is excluded here exactly as
// it is from the mutation below — no existence leak.
const affected = await prisma.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
select: { type: true, measuredAt: true },
});
//
// A blood-pressure half brings back the rows of its reading that were
// tombstoned in the same statement (identical `deletedAt`,
// `bloodPressureSiblings`), so an undo that names only the row the person
// tapped restores the reading the delete took. A row deleted on its own,
// at another moment, stays deleted.
const { affected, count } = await prisma.$transaction(async (tx) => {
const selected = await tx.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
select: {
id: true,
type: true,
source: true,
measuredAt: true,
deletedAt: true,
},
});
const siblings = await bloodPressureSiblings(
tx,
user.id,
selected,
"deletedWith",
);
const rowIds = [...selected, ...siblings].map((row) => row.id);
// Un-tombstone in one statement. The `where` pins `userId` so a forged
// id for another user is silently a no-op; `deletedAt: { not: null }`
// keeps the count honest (a live row doesn't re-count).
const { count } = await prisma.measurement.updateMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
data: { deletedAt: null, syncVersion: { increment: 1 } },
// Un-tombstone in one statement. The `where` pins `userId` so a forged
// id for another user is silently a no-op; `deletedAt: { not: null }`
// keeps the count honest (a live row doesn't re-count).
const { count } = await tx.measurement.updateMany({
where: { id: { in: rowIds }, userId: user.id, deletedAt: { not: null } },
data: { deletedAt: null, syncVersion: { increment: 1 } },
});
return { affected: [...selected, ...siblings], count };
});
await auditLog("measurement.restore", {