test: cover revision-aware report and cache contracts

This commit is contained in:
jesse-ux
2026-11-17 12:47:18 +08:00
parent 41fc6749fc
commit e64e829b16
9 changed files with 33 additions and 21 deletions
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { readReportBirthInputSection, reportBirthInputReader, REPORT_BIRTH_INPUT_SECTION } from "@/lib/report-birth-revision";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { readReportBirthInputSection, REPORT_BIRTH_INPUT_SECTION } from "@/lib/report-birth-revision";
import { ownedReportBirthInputReader } from "@/lib/report-birth-revision-server";
import { REPORT_STABLE_CODES } from "@/lib/personal-report-codes";
import { resolveAllowedReportOrigins } from "@/lib/personal-report-entitlement";
import {
@@ -140,7 +140,7 @@ export async function GET(request: Request, context: RouteContext) {
}
const owned = userId && persistence ? await persistence.getOwnedById(userId, reportId) : null;
const inputState = (userId && supabase && owned)
? reportBirthInputReader(supabase, createAdminSupabaseClient, userId)
? ownedReportBirthInputReader(supabase, userId)
: async () => "unknown" as const;
const binding = (owned && supabase)
? await readReportBirthInputSection(supabase, owned.userId, owned.requestId, owned.reportType).catch(() => undefined)
@@ -215,7 +215,7 @@ export async function GET(request: Request, context: RouteContext) {
// A waiting report also says where it is in the queue (report queue, 2026-11-05).
if (response.status === 200 && owned?.status === "generating" && jobs && userId && supabase) {
const job = await jobs.getOwnedByRequestId(userId, owned.requestId).catch(() => null);
const queue = job && owned.status === "generating" ? await queueFor(supabase, job.id, owned.reportType) : null;
const queue = job ? await queueFor(supabase, job.id, owned.reportType) : null;
if (queue) return toNextResponse({ ...response, body: { ...response.body, queue } });
}
return toNextResponse(response);
+11 -12
View File
@@ -1,7 +1,8 @@
import { normalizeReportSubjectRequest } from "@/lib/report-subject-request";
import { refuseWhenAccountDeletionPending } from "@/lib/account-deletion-server";
import { NextResponse } from "next/server";
import { bindReportBirthInput, reportBirthInputReader, reportBirthInputSection, REPORT_BIRTH_INPUT_SECTION, storeReportBirthInput, type ReportBirthInput } from "@/lib/report-birth-revision";
import { bindReportBirthInput, reportBirthInputSection, REPORT_BIRTH_INPUT_SECTION, storeReportBirthInput, type ReportBirthInput } from "@/lib/report-birth-revision";
import { ownedReportBirthInputReader } from "@/lib/report-birth-revision-server";
import { LONGFORM_SNAPSHOT_SECTION_ID } from "@/lib/personal-report-longform-snapshot";
import { resolveMissingBirthTimezoneOffset } from "@/lib/birth-profile-timezone";
import { REPORT_BIRTH_INPUT_REVISION_KEY, stampReportBirthFingerprint } from "@/lib/report-birth-binding";
@@ -175,7 +176,7 @@ export async function GET(request: Request) {
if (error) throw error;
const nextCursor = nextReportCursor(Array.isArray(pageRows) ? pageRows : [], limit);
const data = Array.isArray(pageRows) ? pageRows.slice(0, limit) : [];
const reports = data.map((row) => listReportView(row)).filter((report) => report.id);
let reports = data.map((row) => listReportView(row)).filter((report) => report.id);
const failed = reports.filter((report) => report.status === "failed" && report.requestId);
if (failed.length > 0) {
const { data: sections, error: sectionError } = await supabase
@@ -187,7 +188,8 @@ export async function GET(request: Request) {
const grouped = new Map<string, Array<{ status: string; lastErrorCode: string | null }>>();
for (const row of Array.isArray(sections) ? sections : []) {
const requestId = typeof row.request_id === "string" ? row.request_id : "";
if (!requestId || row.section_id === LONGFORM_SNAPSHOT_SECTION_ID || row.section_id === REPORT_BIRTH_INPUT_SECTION) continue;
if (!requestId || row.section_id === LONGFORM_SNAPSHOT_SECTION_ID) continue;
if (row.section_id === REPORT_BIRTH_INPUT_SECTION) continue;
// BUG-1904: synastry gate diagnostics are not report sections.
if (isGateDiagnosticSection(row.section_id)) continue;
const list = grouped.get(requestId) ?? [];
@@ -232,7 +234,8 @@ export async function GET(request: Request) {
for (const row of Array.isArray(sectionRows) ? sectionRows : []) {
const requestId = typeof row.request_id === "string" ? row.request_id : "";
const sectionId = typeof row.section_id === "string" ? row.section_id : "";
if (!requestId || !sectionId || sectionId === LONGFORM_SNAPSHOT_SECTION_ID || sectionId === REPORT_BIRTH_INPUT_SECTION) continue;
if (!requestId || !sectionId || sectionId === LONGFORM_SNAPSHOT_SECTION_ID) continue;
if (sectionId === REPORT_BIRTH_INPUT_SECTION) continue;
const list = sectionsByRequest.get(requestId) ?? [];
list.push({
id: sectionId,
@@ -263,24 +266,20 @@ export async function GET(request: Request) {
console.warn(`[reports] list progress skipped reason=${sanitizedErrorReason(progressError)}`);
}
}
const states = new Map<string, Awaited<ReturnType<ReturnType<typeof reportBirthInputReader>>>>();
if (reports.length) {
const { data: inputs } = await supabase.from("personal_report_sections")
.select("request_id, section_id, payload")
.eq("user_id", user.id)
.in("request_id", reports.map((report) => report.requestId))
.in("section_id", [...new Set(reports.map((report) => reportBirthInputSection(report.reportType)))]);
const revisions = reportBirthInputReader(supabase, createAdminSupabaseClient, user.id);
const revisions = ownedReportBirthInputReader(supabase, user.id);
const byRequest = new Map(((inputs ?? []) as { request_id: string; section_id: string; payload: unknown }[]).map((row) => [`${row.request_id}:${row.section_id}`, row.payload]));
await Promise.all(reports.map(async (report) => {
reports = await Promise.all(reports.map(async (report) => {
const key = `${report.requestId}:${reportBirthInputSection(report.reportType)}`;
states.set(report.requestId, await revisions(byRequest.get(key)));
return { ...report, birthInputState: await revisions(byRequest.get(key)) };
}));
}
return NextResponse.json({
reports: reports.map((report) => ({ ...report, birthInputState: states.get(report.requestId) ?? "unknown" })),
nextCursor,
});
return NextResponse.json({ reports, nextCursor });
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json(
+1 -1
View File
@@ -281,7 +281,7 @@ export async function createAnnualReport(input: Readonly<{
// run). A finished one no longer blocks a new run (BUG-1637, product: 「点击
// 的话是新生成,历史的从过往里看」); the start card says it costs again.
if (existing?.status === "generating") {
return { status: 200, body: { report: { id: existing.id, status: existing.status, reportType: ANNUAL_REPORT_TYPE }, birthInputState: "current", reused: true } };
return { status: 200, body: { report: { id: existing.id, status: existing.status, reportType: ANNUAL_REPORT_TYPE }, reused: true } };
}
const inFlight = await (input.admin as unknown as AdminClient).from("personal_reports").select("id")
.eq("user_id", userId).eq("status", "generating").limit(1).maybeSingle();
@@ -0,0 +1,8 @@
import "server-only";
import { reportBirthInputReader } from "./report-birth-revision.ts";
import { createAdminSupabaseClient } from "./supabase/admin.ts";
/** Read report subjects with owner RLS. Only receipt projection needs the history RPC. */
export function ownedReportBirthInputReader(ownerClient: unknown, userId: string) {
return reportBirthInputReader(ownerClient, createAdminSupabaseClient, userId);
}
+1 -1
View File
@@ -282,7 +282,7 @@ test("the homepage card is engine-backed first, with Agent polish off the reques
assert.match(route, /consumeUserRequestRateLimit\("dailyStarlanguage"/);
assert.doesNotMatch(route, /body\?\.profile/);
assert.doesNotMatch(route, /body\?\.today/);
assert.match(route, /dailyStarlanguageCacheKey\(user\.id, subjectId, JSON\.stringify\(payload\), today\)/);
assert.match(route, /dailyStarlanguageCacheKey\(user\.id, subjectId, JSON\.stringify\(payload\), today, revision\)/);
assert.match(route, /pending\(\)\.get\(key\)/);
assert.match(route, /"\/api\/daily_guidance"/);
assert.doesNotMatch(generateCard, /"\/api\/chart"/);
@@ -98,7 +98,7 @@ test("daily card computes eligibility, calendar and fingerprint from selected pr
assert.equal(existsSync(new URL("../src/components/daily-starlanguage-binder.tsx", import.meta.url)), false);
const route = source("app/api/daily-starlanguage/route.ts");
assert.match(route, /const requestedSubject = subjectIdFromQuery\(body\?\.subjectId\);/);
assert.match(route, /await loadSubjectBirth\(supabase, user\.id, requestedSubject\)/);
assert.match(route, /await loadSubjectBirth\(supabase, user\.id, requestedSubject, \{ historyClient: createAdminSupabaseClient, ownerRead: true \}\)/);
assert.match(route, /calendarDateInTimeZone\(new Date\(\), profile\.timezoneId\)/);
assert.match(route, /dailyStarlanguageCacheKey\(user\.id, subjectId,/);
});
+1 -1
View File
@@ -1444,7 +1444,7 @@ test("GET route imports codes from the pure module, never the generation module"
});
test("generation pipeline re-validates with the canonical server parse after the guard", () => {
assert.match(generationSource, /safeParseServerReportDocument\(guarded\.document\)/);
assert.match(generationSource, /safeParseServerReportDocument\(withReportBirthInputRevision\(guarded\.document, deps\.birthInputRevision\)\)/);
assert.match(generationSource, /assembleReportDocument/);
});
@@ -105,7 +105,7 @@ test("daily and synastry routes share a literal account-birth select string", ()
assert.match(matchService, /function loadSynastrySubjectBirth\([\s\S]*?await loadSubjectBirth\(client, userId, subjectId, \{ historyClient: admin, ownerRead: true \}\)/);
assert.match(matchService, /await loadReportSubjectBirth\(admin, userId, subjectId\)/);
const reportBirth = readFileSync(new URL("../src/lib/report-subject-birth.ts", import.meta.url), "utf8");
assert.match(reportBirth, /return loadSubjectBirth\(reader, userId, subjectId, \{ historyClient: admin, ownerRead \}\)/);
assert.match(reportBirth, /const subject = await loadSubjectBirth\(reader, userId, subjectId, \{ historyClient: admin, ownerRead \}\)/);
assert.doesNotMatch(daily, /accountBirthColumns/);
assert.doesNotMatch(synastry, /accountBirthColumns/);
assert.doesNotMatch(daily, /\.join\(",\"\)/);
@@ -55,6 +55,7 @@ function script(input: { product: boolean; same: boolean; missingOther: boolean;
createSupabasePersonalReportService: () => ({ getOwnedById: async () => null }),
createPersonalReportDataClient: () => ({ from: () => ({}) }),
} });
const { birthInputRevision } = await import(moduleUrl("src/lib/birth-input-revision.ts"));
function query(table) {
const filters = [];
const q = {
@@ -78,6 +79,10 @@ function script(input: { product: boolean; same: boolean; missingOther: boolean;
}
return Promise.resolve({ data: null, error: null });
}
if (table === "personal_report_sections" && filters.some(([column, value]) => column === "request_id" && value === "req-1")) {
const revision = birthInputRevision(selfRow);
return Promise.resolve({ data: { payload: { first: "self", second: otherId, birthInputRevisions: { a: revision, b: revision } } }, error: null });
}
return Promise.resolve({ data: null, error: null });
},
then(resolve, reject) { return Promise.resolve({ data: [], error: null }).then(resolve, reject); },