feat: create managed profiles from shared access

- add a managed-profile card to Settings -> Shared access, between the
  invitation card and the standing-state cards
- collect exactly the four fields the create route accepts, with the date
  of birth genuinely optional and never derived from a year
- refresh the account payload on success, so the new record reaches the
  switcher and the banner without a reload
- assert the section is reachable for an owner and refused for a Guardian
  inside a profile and for an adult manager
This commit is contained in:
Marc-André Bombeck committed 2026-08-07 01:53:26 +02:00
1 parent 466c9c906f
commit 110511ff31
14 files changed
+1188 -3

No files matched your search

@@ -0,0 +1,156 @@
/**
* A created managed profile reaches the switcher.
*
* ## The claim, and why it is not "the mutation calls invalidate"
*
* The list of profiles somebody looks after is not a read of its own. It is
* `accountAccess.accounts` on `GET /api/auth/me`, filtered to the managed
* entries — the same block that paints the account switcher and the shared-
* record banner. So "the new profile appears without a reload" is exactly one
* property: the account payload comes back invalidated when the creation
* succeeds. A mutation that refreshed the sharing panel and not the payload
* would leave the profile invisible in the card, in the switcher and in the
* banner at once, and nothing on screen would say a read was stale.
*
* That claim can only be answered by a real `QueryClient` with the reads in
* it, so the hook's success handler is driven against one. `@tanstack/react-
* query` is mocked down to the two functions the hook body calls, which is
* what lets the body run outside React: the unit environment is `node`, there
* is no jsdom and no testing-library in this repo.
*
* Mutation check, run: point `invalidateManagedProfileReads` at the grant list
* alone and "refreshes the account payload" goes red while every other leg
* here stays green.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient } from "@tanstack/react-query";
import { QUERY_CLIENT_DEFAULT_OPTIONS } from "@/lib/pwa/query-client-options";
import { queryKeys } from "@/lib/query-keys";
import { __resetRecordScopeForTests } from "@/lib/query-keys/record-scope";
/** The client the mocked `useQueryClient` hands back. Reassigned per case. */
const clientRef: { value: QueryClient } = { value: seeded() };
vi.mock("@tanstack/react-query", async (importOriginal) => {
const actual = await importOriginal<typeof import("@tanstack/react-query")>();
return {
...actual,
// The hook body is what is under test, so the two hooks it calls are
// replaced by the smallest things that let it run: one that records the
// options object, one that hands over a real client.
useMutation: (options: unknown) => options,
useQueryClient: () => clientRef.value,
};
});
import {
invalidateManagedProfileReads,
useCreateManagedProfile,
} from "@/lib/queries/use-managed-profiles";
function seeded(): QueryClient {
const client = new QueryClient({
defaultOptions: QUERY_CLIENT_DEFAULT_OPTIONS,
});
client.setQueryData(queryKeys.accountGrants(), {
given: [],
received: [],
retentionDays: 365,
});
client.setQueryData(queryKeys.accountActivity(), {
entries: [],
retentionDays: 365,
truncated: false,
});
client.setQueryData(queryKeys.authMe(), { id: "guardian" });
client.setQueryData(queryKeys.managedProfileGuardians("p1"), []);
return client;
}
function invalidated(client: QueryClient, key: readonly unknown[]): boolean {
return (
client.getQueryCache().find({ queryKey: key })?.state.isInvalidated === true
);
}
beforeEach(() => {
__resetRecordScopeForTests();
clientRef.value = seeded();
});
describe("what a managed-profile change refreshes", () => {
it("starts from four live, valid entries", () => {
// Non-zero proof. Without it a client that failed to seed and a client
// whose entries were all invalidated read identically below: every
// `find()` returns undefined and each assertion becomes a quiet
// `undefined !== true`.
const all = clientRef.value.getQueryCache().getAll();
expect(all).toHaveLength(4);
expect(all.every((q) => q.state.isInvalidated)).toBe(false);
});
it("refreshes the account payload, which carries the switcher", () => {
invalidateManagedProfileReads(clientRef.value);
expect(invalidated(clientRef.value, queryKeys.authMe())).toBe(true);
});
it("refreshes the grant list and the record-activity feed", () => {
invalidateManagedProfileReads(clientRef.value);
expect(invalidated(clientRef.value, queryKeys.accountGrants())).toBe(true);
expect(invalidated(clientRef.value, queryKeys.accountActivity())).toBe(
true,
);
});
it("refreshes a profile's guardian roster through the family prefix", () => {
// Accepting a Guardian invitation is an ordinary grant accept, and it
// moves a row on a roster that endpoint knows nothing about. The prefix is
// what keeps the two in step.
invalidateManagedProfileReads(clientRef.value);
expect(
invalidated(clientRef.value, queryKeys.managedProfileGuardians("p1")),
).toBe(true);
});
});
describe("the creation hook, driven for real", () => {
it("posts the four fields the strict schema accepts, and no others", async () => {
const options = useCreateManagedProfile() as unknown as {
mutationFn: (input: unknown) => Promise<unknown>;
onSuccess: () => void;
};
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ data: { id: "p9" }, error: null }), {
status: 201,
headers: { "content-type": "application/json" },
}),
);
await options.mutationFn({
displayName: "Managed record",
dateOfBirth: null,
locale: "en",
timezone: "Europe/Berlin",
});
const [path, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
expect(path).toBe("/api/managed-profiles");
expect(init.method).toBe("POST");
expect(Object.keys(JSON.parse(String(init.body))).sort()).toEqual([
"dateOfBirth",
"displayName",
"locale",
"timezone",
]);
fetchSpy.mockRestore();
});
it("puts the new profile in the switcher by refreshing the payload", () => {
const options = useCreateManagedProfile() as unknown as {
onSuccess: () => void;
};
options.onSuccess();
expect(invalidated(clientRef.value, queryKeys.authMe())).toBe(true);
});
});
+98
View File
@@ -0,0 +1,98 @@
"use client";
/**
* v1.37.0 — the reads and writes behind the managed-profile surface.
*
* A managed profile is a record with no login of its own. It is created by the
* person who will look after it, and from that moment it exists only through
* its Guardians — which is why every call here refreshes the ACCOUNT payload
* and not merely the panel it was fired from.
*
* That is the one property worth stating up front. The list of profiles a
* Guardian looks after is not a read of its own: it is `accountAccess.accounts`
* on `GET /api/auth/me`, filtered to the managed entries, because the Guardian's
* relationship to the profile IS a MANAGE grant. So a creation that refreshed
* the sharing panel and not the payload would leave the new profile invisible —
* in the switcher, in the banner, and in this card — until the next boot. Every
* mutation below therefore goes through `invalidateGrantReads`, the one entry
* `use-account-grants.ts` already publishes for exactly this fan-out; the
* managed-profile family rides it as a key prefix rather than as a second
* invalidation path (`grantDependentKeys`).
*/
import {
useMutation,
useQueryClient,
type QueryClient,
} from "@tanstack/react-query";
import { apiPost } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
import { invalidateGrantReads } from "@/lib/queries/use-account-grants";
import type { Locale } from "@/lib/i18n/config";
/**
* Exactly the body `POST /api/managed-profiles` accepts.
*
* The route's schema is `.strict()`, so an extra key is a 422 with nothing
* useful in it — a form that helpfully posted an empty `heightCm` would be
* refused for a field the person never saw. Naming the four fields as a type
* rather than passing the form state through is what stops that: a fifth field
* added to the form cannot reach the wire without somebody deciding it should.
*/
export interface CreateManagedProfileInput {
displayName: string;
/** ISO `yyyy-MM-dd`, or null. Never synthesised from a year. */
dateOfBirth: string | null;
locale: Locale;
/** IANA zone name. */
timezone: string;
}
/** What the create route answers with. */
export interface ManagedProfileCreated {
id: string;
displayName: string;
dateOfBirth: string | null;
locale: string;
timezone: string;
recordKind: "managed";
}
/**
* Everything a managed-profile lifecycle change makes stale.
*
* Exported as a plain function over a `QueryClient` for the same reason
* `invalidateGrantReads` is: a test can hand it a real client, seed the reads
* and check they came back invalidated. "The mutation calls invalidate" is a
* claim about the source; "the account payload comes back invalidated" is the
* claim that decides whether the new profile appears in the switcher.
*/
export function invalidateManagedProfileReads(queryClient: QueryClient): void {
invalidateGrantReads(queryClient);
}
/** The same refresh, bound to the mounted client. */
function useInvalidateManagedProfiles() {
const queryClient = useQueryClient();
return () => invalidateManagedProfileReads(queryClient);
}
/**
* Create a record somebody looks after.
*
* `requireFreshMfa` guards the route, so a 401 carrying
* `meta.errorCode: auth.stepup.required` is the EXPECTED first answer for
* anybody who has a second factor and has not proved it recently. The form
* routes that into the app's re-verification path rather than into a generic
* failure — see `managed-profile-create-form.tsx`.
*/
export function useCreateManagedProfile() {
const invalidate = useInvalidateManagedProfiles();
return useMutation({
mutationKey: queryKeys.managedProfileCreate(),
mutationFn: (input: CreateManagedProfileInput) =>
apiPost<ManagedProfileCreated>("/api/managed-profiles", input),
onSuccess: invalidate,
});
}
+9
View File
@@ -81,11 +81,20 @@ export { recordSettingsKeys } from "./record-settings";
* and the banner. A revoke that refreshed the panel but not the payload would
* leave a switcher entry pointing at a record the server had just closed: the
* affordance still on screen, the click already refused.
*
* v1.37.0 — the managed-profile family joins the bundle as a prefix. A
* Guardian invitation is accepted through the ordinary
* `POST /api/account/grants/{id}/accept`, and that acceptance moves a row on a
* roster the accept route knows nothing about: the invitee stops being PENDING
* and starts counting toward the last-Guardian floor. Listing the prefix here
* keeps the roster in step with the act that changed it, rather than asking
* every future grant transition to remember one more read.
*/
export const grantDependentKeys = [
queryKeys.accountGrants(),
queryKeys.accountActivity(),
queryKeys.authMe(),
queryKeys.managedProfiles(),
];
/**
+28
View File
@@ -28,10 +28,38 @@ export const sharingKeys = {
*/
accountActivity: () => ["account", "activity"] as const,
/**
* v1.37.0 — the managed-profile family, as one prefix.
*
* Present so a grant transition can invalidate the whole family at once:
* accepting a Guardian invitation is an ordinary `POST
* /api/account/grants/{id}/accept`, and it moves a row on a roster that
* endpoint knows nothing about. Listing this prefix in `grantDependentKeys`
* is what keeps the two in step without the accept path having to know a
* managed profile exists.
*/
managedProfiles: () => ["managed-profiles"] as const,
/**
* Who looks after one managed profile (`GET
* /api/managed-profiles/{id}/guardians`). Keyed by profile because a
* Guardian may look after more than one, and a single key for all of them
* would be the same-key-different-shape collision the factory exists to
* prevent.
*/
managedProfileGuardians: (profileId: string) =>
["managed-profiles", profileId, "guardians"] as const,
/** Mutation keys — kept in the factory so no bare array reaches a call site. */
accountGrantInvite: () => ["account", "grants", "invite"] as const,
accountGrantAccept: () => ["account", "grants", "accept"] as const,
accountGrantRevoke: () => ["account", "grants", "revoke"] as const,
accountGrantRenounce: () => ["account", "grants", "renounce"] as const,
accountSwitchMutation: () => ["account", "switch"] as const,
managedProfileCreate: () => ["managed-profiles", "create"] as const,
managedProfileDelete: () => ["managed-profiles", "delete"] as const,
managedProfileGuardianInvite: () =>
["managed-profiles", "guardian", "invite"] as const,
managedProfileGuardianRemove: () =>
["managed-profiles", "guardian", "remove"] as const,
};