feat(coach,admin): finish the self-context and invite surfaces end to end

Invites move into their own admin section with a real ledger: status
badges, expiry, uses, a redemption history of who joined when (new
redemption table, revocation is now soft so history survives), and an
honest one-time link/QR moment. The assistant self-context grows
structured fields for conditions, allergies and focus — encrypted like
the free text — merges age and gender from the profile into one fenced
prompt block, and asks up to three targeted follow-up questions that
surface as tappable chips above the coach composer. A fourth nudge
trigger gently suggests a check-up when the self-context is stale and
the coach is actually in use.
This commit is contained in:
Marc-André Bombeck committed 2026-06-10 16:18:48 +02:00
1 parent 9fe5673251
commit 5b75184649
32 files changed
+2648 -423

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
/**
* v1.16.0 — invite-token consume-path unit tests.
*
* Pins the gate order against a mocked Prisma client:
* - shape gate (`looksLikeInviteToken`) short-circuits before any DB hit,
* - revoked > expired > exhausted refusal precedence,
* - the guarded-increment WHERE carries `revokedAt: null`,
* - `recordInviteConsumer` writes the `usedBy` stamp AND the
* redemption-ledger row in one transaction.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
const findUnique = vi.fn();
const updateMany = vi.fn();
const update = vi.fn();
const redemptionCreate = vi.fn();
const transaction = vi.fn(async (ops: unknown[]) => ops);
vi.mock("@/lib/db", () => ({
prisma: {
inviteToken: {
findUnique: (...args: unknown[]) => findUnique(...args),
updateMany: (...args: unknown[]) => updateMany(...args),
update: (...args: unknown[]) => update(...args),
},
inviteRedemption: {
create: (...args: unknown[]) => redemptionCreate(...args),
},
$transaction: (...args: unknown[]) => transaction(...(args as [unknown[]])),
},
}));
import {
consumeInviteToken,
generateInviteToken,
looksLikeInviteToken,
recordInviteConsumer,
} from "../invite-token";
const FUTURE = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const PAST = new Date(Date.now() - 60 * 60 * 1000);
function baseInvite(overrides: Record<string, unknown> = {}) {
return {
id: "inv1",
expiresAt: FUTURE,
uses: 0,
maxUses: 1,
revokedAt: null,
...overrides,
};
}
beforeEach(() => {
vi.clearAllMocks();
process.env.API_TOKEN_HMAC_KEY = "0".repeat(64);
});
describe("consumeInviteToken", () => {
it("rejects malformed tokens before touching the DB", async () => {
const result = await consumeInviteToken("not-a-token");
expect(result).toEqual({ ok: false, reason: "not_found" });
expect(findUnique).not.toHaveBeenCalled();
});
it("refuses a revoked invite ahead of every other state", async () => {
findUnique.mockResolvedValue(
baseInvite({ revokedAt: PAST, expiresAt: PAST, uses: 5, maxUses: 1 }),
);
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "revoked" });
expect(updateMany).not.toHaveBeenCalled();
});
it("refuses an expired invite", async () => {
findUnique.mockResolvedValue(baseInvite({ expiresAt: PAST }));
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "expired" });
});
it("refuses an exhausted invite", async () => {
findUnique.mockResolvedValue(baseInvite({ uses: 1, maxUses: 1 }));
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "exhausted" });
});
it("consumes a valid invite with a revocation-guarded increment", async () => {
findUnique.mockResolvedValue(baseInvite());
updateMany.mockResolvedValue({ count: 1 });
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: true, inviteId: "inv1" });
const where = updateMany.mock.calls[0][0].where;
expect(where.revokedAt).toBeNull();
expect(where.uses).toEqual({ lt: 1 });
});
it("treats a lost increment race as exhausted", async () => {
findUnique.mockResolvedValue(baseInvite({ maxUses: 2, uses: 1 }));
updateMany.mockResolvedValue({ count: 0 });
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "exhausted" });
});
});
describe("recordInviteConsumer", () => {
it("stamps usedBy and appends a redemption-ledger row", async () => {
await recordInviteConsumer("inv1", "user1");
expect(transaction).toHaveBeenCalledTimes(1);
expect(update).toHaveBeenCalledWith({
where: { id: "inv1" },
data: { usedBy: "user1" },
});
expect(redemptionCreate).toHaveBeenCalledWith({
data: { inviteId: "inv1", userId: "user1" },
});
});
it("swallows failures — the use is already counted", async () => {
transaction.mockRejectedValueOnce(new Error("boom"));
await expect(recordInviteConsumer("inv1", "user1")).resolves.toBeUndefined();
});
});
describe("looksLikeInviteToken", () => {
it("accepts the generated shape and rejects near-misses", () => {
expect(looksLikeInviteToken(generateInviteToken())).toBe(true);
expect(looksLikeInviteToken("hlk_" + "a".repeat(64))).toBe(false);
expect(looksLikeInviteToken("hlv_" + "a".repeat(63))).toBe(false);
expect(looksLikeInviteToken("hlv_" + "G".repeat(64))).toBe(false);
});
});
+30 -10
View File
@@ -66,7 +66,7 @@ export type InviteConsumeResult =
| { ok: true; inviteId: string }
| {
ok: false;
reason: "not_found" | "expired" | "exhausted";
reason: "not_found" | "expired" | "exhausted" | "revoked";
};
/**
@@ -85,11 +85,22 @@ export async function consumeInviteToken(
const tokenHash = hashToken(rawToken);
const invite = await prisma.inviteToken.findUnique({
where: { tokenHash },
select: { id: true, expiresAt: true, uses: true, maxUses: true },
select: {
id: true,
expiresAt: true,
uses: true,
maxUses: true,
revokedAt: true,
},
});
if (!invite) return { ok: false, reason: "not_found" };
const now = new Date();
// v1.16.0 — a revoked invite is refused like an expired one; the row
// stays so the admin table keeps its redemption history visible.
if (invite.revokedAt !== null) {
return { ok: false, reason: "revoked" };
}
if (invite.expiresAt.getTime() <= now.getTime()) {
return { ok: false, reason: "expired" };
}
@@ -101,6 +112,7 @@ export async function consumeInviteToken(
where: {
id: invite.id,
expiresAt: { gt: now },
revokedAt: null,
// Guarded increment — Postgres evaluates the predicate and the
// UPDATE atomically, so a concurrent consumer of the last use
// makes this a no-op instead of an overshoot.
@@ -119,20 +131,28 @@ export async function consumeInviteToken(
}
/**
* Stamp the consumer account onto the invite after the user row exists.
* Best-effort + last-consumer-wins on multi-use invites; a failure here
* never unwinds the registration.
* Stamp the consumer account onto the invite after the user row exists
* AND append a row to the per-signup redemption ledger (v1.16.0 —
* `usedBy` only ever holds the LAST consumer; the ledger holds them
* all, so multi-use invites keep their full history). Best-effort; a
* failure here never unwinds the registration.
*/
export async function recordInviteConsumer(
inviteId: string,
userId: string,
): Promise<void> {
try {
await prisma.inviteToken.update({
where: { id: inviteId },
data: { usedBy: userId },
});
await prisma.$transaction([
prisma.inviteToken.update({
where: { id: inviteId },
data: { usedBy: userId },
}),
prisma.inviteRedemption.create({
data: { inviteId, userId },
}),
]);
} catch {
// Informational column only — the use itself is already counted.
// Informational rows only — the use itself is already counted by
// the guarded increment in `consumeInviteToken`.
}
}