mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
feat(insights): persist correlation patterns
This commit is contained in:
1 parent
8ece6f39cc
commit
666a85d311
53 files changed
+2129
-55
No files matched your search
@@ -0,0 +1,105 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
correlationPattern: { findFirst: vi.fn(), update: vi.fn() },
|
||||
auditLog: { create: vi.fn().mockResolvedValue({}) },
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { PATCH } from "../route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const SESSION = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "owner-1", username: "owner", role: "USER", locale: "en" },
|
||||
};
|
||||
const PATTERN = {
|
||||
id: "pattern-1",
|
||||
userId: "owner-1",
|
||||
canonicalKey: `p1:${"a".repeat(64)}`,
|
||||
evidenceHash: "b".repeat(64),
|
||||
effectSize: 0.34,
|
||||
sampleSize: 42,
|
||||
dismissedAt: null,
|
||||
};
|
||||
const params = { params: Promise.resolve({ id: PATTERN.id }) };
|
||||
|
||||
function request(body: unknown) {
|
||||
return new NextRequest(
|
||||
`http://localhost/api/insights/patterns/${PATTERN.id}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe("PATCH /api/insights/patterns/[id]", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION as never);
|
||||
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
it("stores the current evidence as the account-scoped dismissal baseline", async () => {
|
||||
vi.mocked(prisma.correlationPattern.findFirst).mockResolvedValue(
|
||||
PATTERN as never,
|
||||
);
|
||||
vi.mocked(prisma.correlationPattern.update).mockResolvedValue({
|
||||
...PATTERN,
|
||||
dismissedAt: new Date("2026-07-28T10:00:00.000Z"),
|
||||
} as never);
|
||||
|
||||
const response = await PATCH(request({ dismissed: true }), params);
|
||||
expect(response.status).toBe(200);
|
||||
expect(prisma.correlationPattern.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: PATTERN.id, userId: "owner-1", isCurrent: true },
|
||||
});
|
||||
expect(prisma.correlationPattern.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: PATTERN.id },
|
||||
data: expect.objectContaining({
|
||||
dismissedEvidenceHash: PATTERN.evidenceHash,
|
||||
dismissedEffectSize: PATTERN.effectSize,
|
||||
dismissedSampleSize: PATTERN.sampleSize,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not reveal a pattern outside the authenticated account", async () => {
|
||||
vi.mocked(prisma.correlationPattern.findFirst).mockResolvedValue(null);
|
||||
const response = await PATCH(request({ dismissed: true }), params);
|
||||
expect(response.status).toBe(404);
|
||||
expect(prisma.correlationPattern.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects fields other than the dismissal decision", async () => {
|
||||
const response = await PATCH(
|
||||
request({ dismissed: true, factorKey: "OTHER" }),
|
||||
params,
|
||||
);
|
||||
expect(response.status).toBe(422);
|
||||
expect(prisma.correlationPattern.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { invalidateUserCorrelationPatterns } from "@/lib/cache/invalidate";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { updateCorrelationPatternSchema } from "@/lib/validations/correlation-patterns";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
const patternIdSchema = z.string().min(1).max(128);
|
||||
|
||||
export const PATCH = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
const parsedId = patternIdSchema.safeParse((await params).id);
|
||||
if (!parsedId.success) return returnAllZodIssues(parsedId.error, 422);
|
||||
const id = parsedId.data;
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 1024,
|
||||
});
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = updateCorrelationPatternSchema.safeParse(body);
|
||||
if (!parsed.success) return returnAllZodIssues(parsed.error, 422);
|
||||
|
||||
const pattern = await prisma.correlationPattern.findFirst({
|
||||
where: { id, userId: user.id, isCurrent: true },
|
||||
});
|
||||
if (!pattern) return apiError("Correlation pattern not found", 404);
|
||||
|
||||
const dismissedAt = parsed.data.dismissed ? new Date() : null;
|
||||
const updated = await prisma.correlationPattern.update({
|
||||
where: { id: pattern.id },
|
||||
data: parsed.data.dismissed
|
||||
? {
|
||||
dismissedAt,
|
||||
dismissedEvidenceHash: pattern.evidenceHash,
|
||||
dismissedEffectSize: pattern.effectSize,
|
||||
dismissedSampleSize: pattern.sampleSize,
|
||||
}
|
||||
: {
|
||||
dismissedAt: null,
|
||||
dismissedEvidenceHash: null,
|
||||
dismissedEffectSize: null,
|
||||
dismissedSampleSize: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
canonicalKey: true,
|
||||
dismissedAt: true,
|
||||
evidenceHash: true,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog(
|
||||
parsed.data.dismissed
|
||||
? "correlationPattern.dismiss"
|
||||
: "correlationPattern.restore",
|
||||
{
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { correlationPatternId: pattern.id },
|
||||
},
|
||||
);
|
||||
annotate({
|
||||
action: {
|
||||
name: parsed.data.dismissed
|
||||
? "insights.pattern.dismiss"
|
||||
: "insights.pattern.restore",
|
||||
},
|
||||
meta: { correlationPatternId: pattern.id },
|
||||
});
|
||||
invalidateUserCorrelationPatterns(user.id);
|
||||
|
||||
return apiSuccess({
|
||||
id: updated.id,
|
||||
canonicalKey: updated.canonicalKey,
|
||||
dismissed: updated.dismissedAt != null,
|
||||
dismissedAt: updated.dismissedAt?.toISOString() ?? null,
|
||||
evidenceHash: updated.evidenceHash,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,42 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
const patterns = await prisma.correlationPattern.findMany({
|
||||
where: { userId: user.id, isCurrent: true },
|
||||
orderBy: [{ lastComputedAt: "desc" }, { canonicalKey: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
canonicalKey: true,
|
||||
family: true,
|
||||
factorKey: true,
|
||||
outcomeKey: true,
|
||||
lagDays: true,
|
||||
sampleSize: true,
|
||||
effectSize: true,
|
||||
pValue: true,
|
||||
qValue: true,
|
||||
evidenceHash: true,
|
||||
lastComputedAt: true,
|
||||
dismissedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.pattern.list" },
|
||||
meta: { total: patterns.length },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
patterns: patterns.map((pattern) => ({
|
||||
...pattern,
|
||||
lastComputedAt: pattern.lastComputedAt.toISOString(),
|
||||
dismissedAt: pattern.dismissedAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user