Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app/api/profile/ensure-tool-report/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
isOnDemandToolSlug,
storedReportMatchesHash,
} from '@/lib/onDemandToolReports';
import { isCommittedProfileHash } from '@/lib/profileHashCommit';
import { hasToolReportExtraInputs, sanitizeToolReportExtraInputs } from '@/lib/toolReportExtraInputs';

export const dynamic = 'force-dynamic';
Expand Down Expand Up @@ -83,6 +84,15 @@ export async function POST(request: NextRequest) {
}

const profileHash = calculateProfileDataHash(userProfile);
if (!isCommittedProfileHash(userProfile.profileDataHash, profileHash)) {
return NextResponse.json(
{
error: 'Birth details changed. Click Generate to rebuild natal charts before opening this tool.',
code: 'profile_hash_changed',
},
{ status: 409 },
);
}
const stored = ((await getDocument('comprehensiveMysticalProfiles', uid)) || {}) as Record<string, unknown>;
const existing = stored[toolSlug];
const forceRefresh = hasToolReportExtraInputs(extraInputs);
Expand Down
11 changes: 11 additions & 0 deletions app/api/profile/generate-catalog-batch/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { checkRateLimitWithOptionalFirestore } from '@/lib/rateLimitFirestore';
import { logServerError } from '@/lib/serverErrorLogging';
import { devLog } from '@/lib/devLogger';
import { generateAndPersistToolReports } from '@/lib/onDemandToolReports';
import { isCommittedProfileHash } from '@/lib/profileHashCommit';
import type { PersistedToolStatusMap } from '@/lib/mysticalStageB';

export const dynamic = 'force-dynamic';
Expand Down Expand Up @@ -104,6 +105,16 @@ export async function POST(request: NextRequest) {
}

const profileHash = calculateProfileDataHash(userProfile);
if (!isCommittedProfileHash(userProfile.profileDataHash, profileHash)) {
return NextResponse.json(
{
error:
'Birth details changed. Click Generate to rebuild natal charts before filling remaining reports.',
code: 'profile_hash_changed',
},
{ status: 409 },
);
}
const result = await generateAndPersistToolReports({
uid,
profile: { ...userProfile, uid },
Expand Down
27 changes: 22 additions & 5 deletions lib/onDemandToolReports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ import type { PersistedToolStatusMap } from '@/lib/mysticalStageB';
import { collapseDuplicateReportFields } from '@/lib/reportDedup';
import type { ToolReportExtraInputs } from '@/lib/toolReportExtraInputs';
import { clearCachedDivinationData } from '@/lib/universalDataAggregator';
import {
NATAL_CHART_SLUGS,
natalReportsMatchProfileHash,
} from '@/lib/profileHashCommit';

export const NATAL_CHART_SLUGS = ['vedic', 'western'] as const;
export { NATAL_CHART_SLUGS };

export type OnDemandToolSlug = (typeof ALL_TOOL_SLUGS)[number];

Expand Down Expand Up @@ -66,10 +70,20 @@ export async function persistOnDemandToolReports(params: {
const existingProfile = ((await getDocument('comprehensiveMysticalProfiles', uid)) ||
{}) as Record<string, unknown>;
let toolStatus = (existingProfile.toolStatus as PersistedToolStatusMap | undefined) ?? {};
const rewritingSlugs = Object.entries(toolReports)
.filter(([, entry]) => entry.status === 'success')
.map(([slug]) => slug);
const writeCommittedHash = natalReportsMatchProfileHash(
existingProfile,
profileHash,
rewritingSlugs,
);
const profilePatch: Record<string, unknown> = {
lastProgressAt: now,
profileDataHash: profileHash,
};
if (writeCommittedHash) {
profilePatch.profileDataHash = profileHash;
}
const readySlugs: string[] = [];
const failedSlugs: string[] = [];

Expand All @@ -91,17 +105,20 @@ export async function persistOnDemandToolReports(params: {
const mergedProfile = { ...existingProfile, ...profilePatch };
const readiness = summarizeToolReadiness(mergedProfile, ALL_TOOL_SLUGS);
await setDocument('comprehensiveMysticalProfiles', uid, profilePatch);
await setDocument('users', uid, {
const userPatch: Record<string, unknown> = {
mysticalProfileGenerated: true,
mysticalProfileGeneratedAt: now,
profileDataHash: profileHash,
profileStatus: readiness.allReportsReady ? 'completed' : 'running',
allReportsReady: readiness.allReportsReady,
pendingToolSlugs: readiness.pendingToolSlugs,
toolStatus,
lastProgressAt: now,
updatedAt: now,
});
};
if (writeCommittedHash) {
userPatch.profileDataHash = profileHash;
}
await setDocument('users', uid, userPatch);
const lockPatch: Record<string, unknown> = {
status: readiness.allReportsReady ? 'completed' : 'running',
phase: readiness.allReportsReady ? 'completed' : 'catalog',
Expand Down
42 changes: 42 additions & 0 deletions lib/profileHashCommit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Catalog / on-demand persist may only advance profileDataHash when the
* committed hash still matches live birth fields. Otherwise natal charts stay
* on the previous hash while the stale banner disappears.
*/

export const NATAL_CHART_SLUGS = ['vedic', 'western'] as const;

export function isCommittedProfileHash(
committedHash: unknown,
liveHash: string,
): boolean {
if (typeof committedHash !== 'string' || committedHash.length === 0) {
return true;
}
return committedHash === liveHash;
}

function reportGenerationKey(report: unknown): string | null {
if (!report || typeof report !== 'object') return null;
const key = (report as Record<string, unknown>).generationIdempotencyKey;
if (typeof key !== 'string' || key.length === 0) return null;
return key;
}

/**
* True when existing natal reports are either missing (legacy), have no key
* (legacy), match profileHash, or are being rewritten in this persist.
*/
export function natalReportsMatchProfileHash(
profile: Record<string, unknown>,
profileHash: string,
rewritingSlugs: readonly string[] = [],
): boolean {
for (const slug of NATAL_CHART_SLUGS) {
if (rewritingSlugs.includes(slug)) continue;
const key = reportGenerationKey(profile[slug]);
if (key == null) continue;
if (key !== profileHash) return false;
}
return true;
}
28 changes: 27 additions & 1 deletion tests/integration/ensure-tool-report.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,16 @@ jest.mock('@/lib/onDemandToolReports', () => ({
}));

jest.mock('@/lib/firebase', () => ({
calculateProfileDataHash: () => 'hash-1',
calculateProfileDataHash: jest.fn(() => 'hash-1'),
}));

import { calculateProfileDataHash } from '@/lib/firebase';
import { POST } from '@/app/api/profile/ensure-tool-report/route';

const mockCalculateProfileDataHash = calculateProfileDataHash as jest.MockedFunction<
typeof calculateProfileDataHash
>;

describe('ensure-tool-report API', () => {
const uid = 'user-1';

Expand All @@ -53,6 +58,7 @@ describe('ensure-tool-report API', () => {
failedSlugs: [],
toolReports: { tarot: { status: 'success', data: { cards: [{ name: 'The Fool' }] } } },
});
mockCalculateProfileDataHash.mockReturnValue('hash-1');
});

async function callEnsure(body: Record<string, unknown>): Promise<Response> {
Expand Down Expand Up @@ -136,4 +142,24 @@ describe('ensure-tool-report API', () => {
}),
);
});

it('returns 409 and does not persist when birth details changed after the last Generate', async () => {
mockCalculateProfileDataHash.mockReturnValue('hash-2');
mockGetDocument.mockImplementation((collection: string) => {
if (collection === 'users') {
return Promise.resolve({
uid,
mysticalProfileGenerated: true,
profileDataHash: 'hash-1',
});
}
if (collection === 'comprehensiveMysticalProfiles') return Promise.resolve({});
return Promise.resolve({});
});
const res = await callEnsure({ toolSlug: 'tarot' });
const data = await res.json();
expect(res.status).toBe(409);
expect(data.code).toBe('profile_hash_changed');
expect(mockGenerateAndPersistToolReports).not.toHaveBeenCalled();
});
});
33 changes: 32 additions & 1 deletion tests/integration/generate-catalog-batch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,16 @@ jest.mock('@/lib/onDemandToolReports', () => ({
}));

jest.mock('@/lib/firebase', () => ({
calculateProfileDataHash: () => 'hash-1',
calculateProfileDataHash: jest.fn(() => 'hash-1'),
}));

import { calculateProfileDataHash } from '@/lib/firebase';
import { POST } from '@/app/api/profile/generate-catalog-batch/route';

const mockCalculateProfileDataHash = calculateProfileDataHash as jest.MockedFunction<
typeof calculateProfileDataHash
>;

describe('generate-catalog-batch API', () => {
const uid = 'user-1';

Expand All @@ -79,6 +84,7 @@ describe('generate-catalog-batch API', () => {
failedSlugs: [],
toolReports: {},
});
mockCalculateProfileDataHash.mockReturnValue('hash-1');
});

async function callBatch(): Promise<Response> {
Expand Down Expand Up @@ -169,4 +175,29 @@ describe('generate-catalog-batch API', () => {
);
expect(data.generatedSlugs).toEqual(['esotericAstrology', 'kabbalisticAstrology']);
});

it('returns 409 and does not persist when birth details changed after the last Generate', async () => {
mockCalculateProfileDataHash.mockReturnValue('hash-2');
mockGetDocument.mockImplementation((collection: string) => {
if (collection === 'users') {
return Promise.resolve({
uid,
mysticalProfileGenerated: true,
profileDataHash: 'hash-1',
});
}
if (collection === 'comprehensiveMysticalProfiles') {
return Promise.resolve({
vedic: displayableReportForSlug('vedic'),
western: displayableReportForSlug('western'),
});
}
return Promise.resolve({});
});
const res = await callBatch();
const data = await res.json();
expect(res.status).toBe(409);
expect(data.code).toBe('profile_hash_changed');
expect(mockGenerateAndPersistToolReports).not.toHaveBeenCalled();
});
});
57 changes: 57 additions & 0 deletions tests/unit/profileHashCommit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
isCommittedProfileHash,
natalReportsMatchProfileHash,
} from '@/lib/profileHashCommit';

describe('isCommittedProfileHash', () => {
it('allows persist when no committed hash exists yet', () => {
expect(isCommittedProfileHash(undefined, 'h2')).toBe(true);
expect(isCommittedProfileHash('', 'h2')).toBe(true);
expect(isCommittedProfileHash(null, 'h2')).toBe(true);
});

it('allows persist when live hash matches the committed hash', () => {
expect(isCommittedProfileHash('h1', 'h1')).toBe(true);
});

it('refuses persist after birth fields change without Generate', () => {
expect(isCommittedProfileHash('h1', 'h2')).toBe(false);
});
});

describe('natalReportsMatchProfileHash', () => {
it('treats missing or legacy natal reports as compatible', () => {
expect(natalReportsMatchProfileHash({}, 'h2')).toBe(true);
expect(
natalReportsMatchProfileHash(
{ vedic: { planets: [{ name: 'Sun' }] }, western: { planets: [{ name: 'Moon' }] } },
'h2',
),
).toBe(true);
});

it('rejects when stored natal keys belong to a previous hash', () => {
expect(
natalReportsMatchProfileHash(
{
vedic: { planets: [{ name: 'Sun' }], generationIdempotencyKey: 'h1' },
western: { planets: [{ name: 'Moon' }], generationIdempotencyKey: 'h1' },
},
'h2',
),
).toBe(false);
});

it('allows a persist that is rewriting the mismatched natal slugs', () => {
expect(
natalReportsMatchProfileHash(
{
vedic: { planets: [{ name: 'Sun' }], generationIdempotencyKey: 'h1' },
western: { planets: [{ name: 'Moon' }], generationIdempotencyKey: 'h1' },
},
'h2',
['vedic', 'western'],
),
).toBe(true);
});
});
Loading