From 224daeb6569a798ef5a44fc59d331cda4cbb830e Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 00:36:51 +0000 Subject: [PATCH 1/5] test(e2e): people users journeys, first slice (remove, REST list/get/delete) --- apps/web/e2e/QUARANTINE.md | 25 ++ apps/web/e2e/product/people.ts | 258 ++++++++++++++++++++ apps/web/e2e/tests/people/users-api.spec.ts | 207 ++++++++++++++++ apps/web/e2e/tests/people/users.spec.ts | 117 +++++++++ 4 files changed, 607 insertions(+) create mode 100644 apps/web/e2e/product/people.ts create mode 100644 apps/web/e2e/tests/people/users-api.spec.ts create mode 100644 apps/web/e2e/tests/people/users.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 4527677f15..0c18a203d2 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -97,3 +97,28 @@ by a separate test that is not quarantined. checks on both single-column paths. owner: unassigned, review by: 2026-12-03. +### Product suite: people (users and companies) +- `people/users.spec.ts` › removing a person › PPL-U-43 removing a voter + withdraws their vote from the post count. Product bug: `removePortalUser` + deletes the principal and lets `post_votes` cascade + (`apps/web/src/lib/server/domains/users/user.service.ts:514`), but nothing + decrements `posts.vote_count`, so every post the person voted on keeps a + count one too high on the portal and the admin, although the remove dialog + promises "their votes are withdrawn". Fix: in the same transaction, before + the delete, `UPDATE posts SET vote_count = greatest(vote_count - 1, 0) WHERE +id IN (SELECT post_id FROM post_votes WHERE principal_id = $1)`. owner: + unassigned, review by: 2026-12-03. +- `people/users-api.spec.ts` › REST /api/v1/users › PPL-U-59 a teammate id + answers a plain "Portal user not found". Product bug: the route passes a + full sentence to `notFoundResponse`, which appends " not found" again, so + the answer reads "Portal user not found not found" + (`apps/web/src/routes/api/v1/users/$principalId.ts:46`). Fix: pass + `'Portal user'`. owner: unassigned, review by: 2026-12-03. +- `people/users-api.spec.ts` › REST /api/v1/users › PPL-U-64 an unknown or + teammate id is refused as a missing user, not a "Member". Product bug: + `removePortalUser` throws `MEMBER_NOT_FOUND`, which `handleDomainError` maps + to "Member not found" (`apps/web/src/lib/server/domains/api/responses.ts:182`), + so DELETE /api/v1/users/:id on an unknown portal user talks about a member. + Fix: throw a `USER_NOT_FOUND` (or a portal-user code) from + `removePortalUser` (`user.service.ts:476`), or map the error in the route. + owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/product/people.ts b/apps/web/e2e/product/people.ts new file mode 100644 index 0000000000..7646acfb0a --- /dev/null +++ b/apps/web/e2e/product/people.ts @@ -0,0 +1,258 @@ +/** + * Helpers for the people specs (e2e/tests/people/users*, companies, + * user-attributes): portal users with their own activity, boards, posts, + * votes and comments made the way the portal makes them, REST keys, and the + * admin's server functions. + * + * const board = await seedBoard(marker) + * const cass = await portalUser(browser, marker) // signed-in portal user + * const post = await postAs(cass.api, board.id, `Idea ${marker}`) + * await voteAs(cass.api, post.id) + * const admin = await personApi(playwright, 'admin') + * await adminCall(admin, 'deletePortalUserFn', { principalId: cass.principalId }) + * + * Every row a test makes carries its marker, so tests find their own rows by + * search and never by position or count. + */ +import { randomBytes } from 'node:crypto' +import { + expect, + type APIRequestContext, + type Browser, + type BrowserContext, + type PlaywrightWorkerArgs, +} from '@playwright/test' +import { fromUuid, generateId, toUuid } from '@quackback/ids' +import { supportDb } from '../support/db' +import { supportEnv } from '../support/env' +import { apiFor, createKey, type CreatedKey } from '../support/api-client' +import { callServerFn, type ServerFnResult } from '../support/server-fns' +import { mintCustomer, portalContext, type MintedCustomer } from '../support/widget-portal' + +export { personApi, callServerFn } from '../support/server-fns' + +/** The fixed placeholder principal removed people's content is re-pointed to. */ +export const DELETED_USER_PRINCIPAL = 'principal_00000000000000000000000000' + +function suffix(): string { + return randomBytes(3).toString('hex') +} + +/** A public board only this test uses. */ +export async function seedBoard( + marker: string +): Promise<{ id: string; slug: string; name: string }> { + const uuid = toUuid(generateId('board')) + const slug = `${marker}-${suffix()}`.slice(0, 60) + const name = `Board ${marker}`.slice(0, 90) + await supportDb()`INSERT INTO boards (id, slug, name, description) + VALUES (${uuid}, ${slug}, ${name}, 'people e2e board')` + return { id: fromUuid('board', uuid), slug, name } +} + +export interface PortalUser extends MintedCustomer { + /** A browser context signed in to the portal as them. */ + context: BrowserContext + /** That context's request client (cookie-authed server functions). */ + api: APIRequestContext +} + +/** + * A fresh identified portal user, signed in. `name` defaults to one carrying + * the marker so a directory search for the marker finds them. + */ +export async function portalUser( + browser: Browser, + marker: string, + opts: { name?: string; email?: string } = {} +): Promise { + const s = suffix() + const customer = await mintCustomer({ + email: opts.email ?? `${marker}-${s}@customers.example`, + name: opts.name ?? `Person ${marker} ${s}`, + }) + const context = await portalContext(browser, customer) + return { ...customer, context, api: context.request } +} + +/** A portal user with no session (only rows). */ +export async function portalUserRow( + marker: string, + opts: { name?: string; email?: string; verified?: boolean } = {} +): Promise { + const s = suffix() + const customer = await mintCustomer({ + email: opts.email ?? `${marker}-${s}@customers.example`, + name: opts.name ?? `Person ${marker} ${s}`, + }) + if (opts.verified === false) { + await supportDb()`UPDATE "user" SET email_verified = false WHERE id = ${customer.userUuid}` + } + return customer +} + +/** + * An anonymous "lead": an anonymous principal shaped like the anonymous auth + * plugin makes one (placeholder email on the reserved domain), optionally + * with a captured contact email. + */ +export async function seedLead( + marker: string, + opts: { contactEmail?: string | null; name?: string } = {} +): Promise { + const sql = supportDb() + const userUuid = toUuid(generateId('user')) + const principalUuid = toUuid(generateId('principal')) + const email = `temp-${userUuid}@anon.quackback.io` + const name = opts.name ?? `Lead ${marker} ${suffix()}` + await sql`INSERT INTO "user" (id, name, email, email_verified, is_anonymous, created_at, updated_at) + VALUES (${userUuid}, ${name}, ${email}, false, true, NOW(), NOW())` + await sql`INSERT INTO principal (id, user_id, role, type, display_name, contact_email, created_at) + VALUES (${principalUuid}, ${userUuid}, 'user', 'anonymous', ${name}, + ${opts.contactEmail ?? null}, NOW())` + return { + email, + name, + userId: fromUuid('user', userUuid), + principalId: fromUuid('principal', principalUuid), + userUuid, + principalUuid, + } +} + +/** Call a server function and fail the test when it throws. */ +export async function mustCall( + api: APIRequestContext, + name: string, + data?: unknown, + opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} +): Promise { + const res = await callServerFn(api, name, data, opts) + expect(res.ok, `${name}: ${res.raw.slice(0, 400)}`).toBe(true) + return res.data +} + +/** Call a server function expecting a refusal; returns the result. */ +export async function refusedCall( + api: APIRequestContext, + name: string, + data?: unknown, + opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} +): Promise { + const res = await callServerFn(api, name, data, opts) + expect(res.ok, `${name} should be refused: ${res.raw.slice(0, 300)}`).toBe(false) + return res +} + +/** The portal user files a post on a board (createPublicPostFn). */ +export async function postAs( + api: APIRequestContext, + boardId: string, + title: string +): Promise<{ id: string }> { + const post = await mustCall<{ id: string }>(api, 'createPublicPostFn', { + boardId, + title, + content: `Body of ${title}`, + }) + return { id: post.id } +} + +/** The portal user toggles their vote on a post. */ +export async function voteAs( + api: APIRequestContext, + postId: string +): Promise<{ voted: boolean; voteCount: number }> { + return mustCall(api, 'toggleVoteFn', { postId }) +} + +/** The portal user comments on a post. */ +export async function commentAs( + api: APIRequestContext, + postId: string, + content: string +): Promise<{ id: string }> { + const res = await mustCall<{ comment?: { id: string }; id?: string }>(api, 'createCommentFn', { + postId, + content, + }) + const id = res.comment?.id ?? res.id + if (!id) throw new Error(`createCommentFn answered without an id: ${JSON.stringify(res)}`) + return { id } +} + +/** posts.vote_count for a post. */ +export async function voteCountOf(postId: string): Promise { + const [row] = + await supportDb()`SELECT vote_count FROM posts WHERE id = ${toUuid(postId as `post_${string}`)}` + if (!row) throw new Error(`no post ${postId}`) + return Number(row.vote_count) +} + +/** Live post_votes rows for a post. */ +export async function voteRowsOf(postId: string): Promise { + const [row] = await supportDb()`SELECT count(*)::int AS n FROM post_votes + WHERE post_id = ${toUuid(postId as `post_${string}`)}` + return Number(row.n) +} + +export function uuid(typeId: string): string { + return toUuid(typeId as `principal_${string}`) +} + +// --------------------------------------------------------------------------- +// REST keys +// --------------------------------------------------------------------------- + +let adminKey: CreatedKey | null = null + +/** + * A workspace key holding the admin role (every permission), made once per + * worker. For tests that need a narrower key, call createKey directly. + */ +export function adminWorkspaceKey(): CreatedKey { + adminKey ??= createKey({ + creatorEmail: 'e2e-support-admin@example.com', + kind: 'workspace', + roleKey: 'admin', + }) + return adminKey +} + +/** A REST client with the per-worker admin workspace key. */ +export async function restAdmin( + playwright: PlaywrightWorkerArgs['playwright'] +): Promise { + return apiFor(playwright, supportEnv().baseUrl, adminWorkspaceKey().key) +} + +/** A REST client with a workspace key holding `roleKey`. */ +export async function restAs( + playwright: PlaywrightWorkerArgs['playwright'], + roleKey: string +): Promise { + const { key } = createKey({ + creatorEmail: 'e2e-support-admin@example.com', + kind: 'workspace', + roleKey, + }) + return apiFor(playwright, supportEnv().baseUrl, key) +} + +// --------------------------------------------------------------------------- +// Admin UI +// --------------------------------------------------------------------------- + +/** The People directory, searched for `search`, with a profile open. */ +export function usersUrl(opts: { + search?: string + selected?: string + lifecycle?: 'leads' +}): string { + const q = new URLSearchParams() + if (opts.search) q.set('search', opts.search) + if (opts.selected) q.set('selected', opts.selected) + if (opts.lifecycle) q.set('lifecycle', opts.lifecycle) + const s = q.toString() + return `/admin/users${s ? `?${s}` : ''}` +} diff --git a/apps/web/e2e/tests/people/users-api.spec.ts b/apps/web/e2e/tests/people/users-api.spec.ts new file mode 100644 index 0000000000..650b003235 --- /dev/null +++ b/apps/web/e2e/tests/people/users-api.spec.ts @@ -0,0 +1,207 @@ +/** + * People over the REST API (/api/v1/users), the people server functions' + * refusals and permission gates. + * + * Journeys: PPL-U-45, PPL-U-57, PPL-U-59, PPL-U-64 + */ +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { expectJson } from '../../support/api-client' +import { + DELETED_USER_PRINCIPAL, + mustCall, + personApi, + portalUserRow, + refusedCall, + restAdmin, + seedLead, +} from '../../product/people' + +test.describe('removing people: refusals', () => { + test( + 'PPL-U-45 remove is refused for a teammate, the placeholder, an unknown id and a repeat', + { tag: '@core' }, + async ({ playwright, people, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const sql = supportDb() + const mate = await newTeammate({ roleKey: 'contributor' }) + const person = await portalUserRow(marker) + + const refusals = [ + mate.principalId, + people.people.agentB.principalId, + DELETED_USER_PRINCIPAL, + generateId('principal'), + ] + for (const principalId of refusals) { + const res = await refusedCall(admin, 'deletePortalUserFn', { principalId }) + expect(res.code, principalId).toBe('MEMBER_NOT_FOUND') + } + const [mateRow] = await sql`SELECT role FROM principal WHERE user_id = + (SELECT id FROM "user" WHERE email = ${mate.email})` + expect(mateRow?.role).toBe('member') + + // A real removal, then the repeat is refused. + await mustCall(admin, 'deletePortalUserFn', { principalId: person.principalId }) + const again = await refusedCall(admin, 'deletePortalUserFn', { + principalId: person.principalId, + }) + expect(again.code).toBe('MEMBER_NOT_FOUND') + + // An anonymous lead can be removed; its synthetic user row stays. + const lead = await seedLead(marker, { contactEmail: `${marker}-lead@customers.example` }) + await mustCall(admin, 'deletePortalUserFn', { principalId: lead.principalId }) + const [leadPrincipal] = await sql`SELECT id FROM principal WHERE id = ${lead.principalUuid}` + expect(leadPrincipal).toBeUndefined() + const [leadUser] = await sql`SELECT id FROM "user" WHERE id = ${lead.userUuid}` + expect(leadUser).toBeDefined() + await admin.dispose() + } + ) +}) + +test.describe('REST /api/v1/users', () => { + test( + 'PPL-U-57 list users returns identified portal users only, with counts and paging', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const rest = await restAdmin(playwright) + const a = await portalUserRow(marker) + const b = await portalUserRow(marker) + await supportDb()`UPDATE "user" SET metadata = ${JSON.stringify({ plan: 'pro', _secret: 'x' })} + WHERE id = ${a.userUuid}` + // Not listed: a lead and a teammate carrying the marker. + const lead = await seedLead(marker, { name: `Lead ${marker}` }) + const mate = await newTeammate({ roleKey: 'contributor', name: `Mate ${marker}` }) + + const body = await expectJson( + await rest.get(`/api/v1/users?search=${encodeURIComponent(marker)}&limit=1`), + 200 + ) + expect(body.data).toHaveLength(1) + expect(body.meta.pagination.hasMore).toBe(true) + expect(body.meta.pagination.total).toBe(2) + const next = await expectJson( + await rest.get( + `/api/v1/users?search=${encodeURIComponent(marker)}&limit=1&cursor=${body.meta.pagination.cursor}` + ), + 200 + ) + expect(next.data).toHaveLength(1) + expect(next.meta.pagination.hasMore).toBe(false) + + const all = [...body.data, ...next.data] + const ids = all.map((u: { principalId: string }) => u.principalId).sort() + expect(ids).toEqual([a.principalId, b.principalId].sort()) + expect(ids).not.toContain(lead.principalId) + expect(ids).not.toContain(mate.principalId) + + const rowA = all.find((u: { principalId: string }) => u.principalId === a.principalId) + expect(rowA).toMatchObject({ + userId: a.userId, + name: a.name, + email: a.email, + emailVerified: true, + attributes: { plan: 'pro' }, + postCount: 0, + commentCount: 0, + voteCount: 0, + }) + expect(rowA.attributes).not.toHaveProperty('_secret') + expect(typeof rowA.joinedAt).toBe('string') + await rest.dispose() + } + ) + + test( + 'PPL-U-59 get one user: profile fields, a lead without an email, refusals', + { tag: '@core' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const person = await portalUserRow(marker) + const lead = await seedLead(marker) + + const one = await expectJson(await rest.get(`/api/v1/users/${person.principalId}`), 200) + expect(one.data).toMatchObject({ + principalId: person.principalId, + userId: person.userId, + name: person.name, + email: person.email, + emailVerified: true, + postCount: 0, + commentCount: 0, + voteCount: 0, + engagedPosts: [], + }) + expect(typeof one.data.createdAt).toBe('string') + + const leadBody = await expectJson(await rest.get(`/api/v1/users/${lead.principalId}`), 200) + expect(leadBody.data.email).toBeNull() + + const bad = await expectJson(await rest.get('/api/v1/users/not-a-principal'), 400) + expect(bad.error.code).toBe('VALIDATION_ERROR') + expect(bad.error.message).toContain('Invalid principal ID format') + await rest.dispose() + } + ) + + test( + 'PPL-U-59 a teammate id answers a plain "Portal user not found"', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'GET /api/v1/users/:id passes a full sentence to notFoundResponse, which appends "not found" again; see QUARANTINE.md', + }, + }, + async ({ playwright, people }) => { + const rest = await restAdmin(playwright) + const res = await expectJson( + await rest.get(`/api/v1/users/${people.people.agentB.principalId}`), + 404 + ) + expect(res.error.code).toBe('NOT_FOUND') + expect(res.error.message).toBe('Portal user not found') + await rest.dispose() + } + ) + + test( + 'PPL-U-64 delete a user over REST, then the repeat is a 404', + { tag: '@core' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const person = await portalUserRow(marker) + const res = await rest.delete(`/api/v1/users/${person.principalId}`) + expect(res.status(), await res.text()).toBe(204) + const [row] = await supportDb()`SELECT id FROM principal WHERE id = ${person.principalUuid}` + expect(row).toBeUndefined() + const again = await expectJson(await rest.delete(`/api/v1/users/${person.principalId}`), 404) + expect(again.error.code).toBe('NOT_FOUND') + await rest.dispose() + } + ) + + test( + 'PPL-U-64 an unknown or teammate id is refused as a missing user, not a "Member"', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'removePortalUser throws MEMBER_NOT_FOUND, which handleDomainError names "Member not found" on the users endpoint; see QUARANTINE.md', + }, + }, + async ({ playwright, people }) => { + const rest = await restAdmin(playwright) + for (const id of [generateId('principal'), people.people.agentB.principalId]) { + const res = await expectJson(await rest.delete(`/api/v1/users/${id}`), 404) + expect(res.error.message, id).not.toContain('Member') + expect(res.error.message, id).toMatch(/user not found/i) + } + await rest.dispose() + } + ) +}) diff --git a/apps/web/e2e/tests/people/users.spec.ts b/apps/web/e2e/tests/people/users.spec.ts new file mode 100644 index 0000000000..5c3b7267d0 --- /dev/null +++ b/apps/web/e2e/tests/people/users.spec.ts @@ -0,0 +1,117 @@ +/** + * People directory and profiles in the admin (/admin/users), and the portal + * users' own rows they change. + * + * Journeys: PPL-U-42 (smoke), PPL-U-43 + */ +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { + DELETED_USER_PRINCIPAL, + commentAs, + mustCall, + personApi, + portalUser, + postAs, + seedBoard, + usersUrl, + uuid, + voteAs, + voteCountOf, + voteRowsOf, +} from '../../product/people' + +test.describe('removing a person', () => { + test( + 'PPL-U-42 removing a portal user takes them off the portal and re-points their content', + { tag: '@smoke' }, + async ({ asPerson, browser, marker }) => { + const board = await seedBoard(marker) + const author = await portalUser(browser, marker) + const post = await postAs(author.api, board.id, `Idea ${marker}`) + const comment = await commentAs(author.api, post.id, `Comment ${marker}`) + // The vote lands on someone else's post, so it is the voter's own row. + const other = await portalUser(browser, marker, { name: `Other voter ${marker}` }) + const otherPost = await postAs(other.api, board.id, `Other ${marker}`) + await voteAs(author.api, otherPost.id) + + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker, selected: author.principalId })) + const profile = admin.getByRole('heading', { name: author.name, exact: true }) + await expect(profile).toBeVisible({ timeout: 15_000 }) + + await admin.getByRole('button', { name: 'More actions' }).click() + await admin.getByRole('menuitem', { name: 'Remove from portal' }).click() + const dialog = admin.getByRole('alertdialog') + await expect(dialog.getByText(`Remove ${author.name}?`)).toBeVisible() + await expect(dialog).toContainText('their votes are withdrawn') + await expect(dialog).toContainText('reattributed to “Deleted user”') + await dialog.getByRole('button', { name: 'Remove', exact: true }).click() + + // The pane closes; the person is gone from the list after a fresh load. + await expect(profile).toHaveCount(0) + await admin.goto(usersUrl({ search: marker })) + await expect(admin.getByRole('heading', { level: 3, name: other.name })).toBeVisible({ + timeout: 15_000, + }) + await expect(admin.getByRole('heading', { level: 3, name: author.name })).toHaveCount(0) + + const sql = supportDb() + const [principal] = await sql`SELECT id FROM principal WHERE id = ${author.principalUuid}` + expect(principal, 'principal row deleted').toBeUndefined() + const [account] = await sql`SELECT id FROM "user" WHERE id = ${author.userUuid}` + expect(account, 'global user row kept').toBeDefined() + const sessions = await sql`SELECT id FROM session WHERE user_id = ${author.userUuid}` + expect(sessions, 'every session ended').toHaveLength(0) + + const deletedUser = uuid(DELETED_USER_PRINCIPAL) + const [postRow] = await sql`SELECT principal_id FROM posts WHERE id = ${uuid(post.id)}` + expect(postRow.principal_id).toBe(deletedUser) + const [commentRow] = + await sql`SELECT principal_id FROM post_comments WHERE id = ${uuid(comment.id)}` + expect(commentRow.principal_id).toBe(deletedUser) + const votes = + await sql`SELECT id FROM post_votes WHERE principal_id = ${author.principalUuid}` + expect(votes, 'their votes are gone').toHaveLength(0) + const subs = + await sql`SELECT id FROM post_subscriptions WHERE principal_id = ${author.principalUuid}` + expect(subs, 'their post subscriptions are gone').toHaveLength(0) + + // The portal shows the post under "Deleted user". + const visitor = await browser.newPage() + await visitor.goto(`/b/${board.slug}/posts/${post.id}`) + await expect(visitor.getByRole('heading', { name: `Idea ${marker}` })).toBeVisible() + await expect(visitor.getByText('Deleted user').first()).toBeVisible() + await visitor.close() + } + ) + + test( + 'PPL-U-43 removing a voter withdraws their vote from the post count', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'removePortalUser lets post_votes cascade without decrementing posts.vote_count (user.service.ts removePortalUser); see QUARANTINE.md', + }, + }, + async ({ browser, playwright, marker }) => { + const board = await seedBoard(marker) + const author = await portalUser(browser, `${marker}-a`) + const post = await postAs(author.api, board.id, `Idea ${marker}`) + const voter = await portalUser(browser, marker) + const before = await voteCountOf(post.id) + const voted = await voteAs(voter.api, post.id) + expect(voted.voted).toBe(true) + expect(await voteCountOf(post.id)).toBe(before + 1) + + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'deletePortalUserFn', { principalId: voter.principalId }) + await admin.dispose() + + expect(await voteRowsOf(post.id)).toBe(before) + expect(await voteCountOf(post.id), 'the count drops with the withdrawn vote').toBe(before) + } + ) +}) From 730543c2575921b85926413d63c352002256ed31 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 01:18:23 +0000 Subject: [PATCH 2/5] test(e2e): people users server-function and REST journeys --- apps/web/e2e/QUARANTINE.md | 24 + apps/web/e2e/product/people.ts | 138 ++++- apps/web/e2e/tests/people/users-api.spec.ts | 547 +++++++++++++++++++- apps/web/e2e/tests/people/users.spec.ts | 281 +++++++++- 4 files changed, 984 insertions(+), 6 deletions(-) diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 0c18a203d2..3dae1b8392 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -122,3 +122,27 @@ id IN (SELECT post_id FROM post_votes WHERE principal_id = $1)`. owner: Fix: throw a `USER_NOT_FOUND` (or a portal-user code) from `removePortalUser` (`user.service.ts:476`), or map the error in the route. owner: unassigned, review by: 2026-12-03. +- `people/users.spec.ts` › merging a lead › PPL-U-31 merging a lead that + voted the same post as the user leaves one vote counted. Product bug: the + `post_votes` step of the re-point registry is a `collisionRepoint` that + drops the lead's colliding vote (the user's vote wins) + (`apps/web/src/lib/server/domains/principals/principal-repoint.ts:220`) + without decrementing `posts.vote_count`, so the post keeps one vote too + many. Fix: in that step, decrement `posts.vote_count` for every dropped + vote row (or recompute the count for the affected posts). owner: + unassigned, review by: 2026-12-03. +- `people/users-api.spec.ts` › REST /api/v1/users › PPL-U-60 PATCH merges + coerced attributes, unsets null keys and sets the external id; PPL-U-61 + boolean and date attributes accept their valid spellings; PPL-U-66 + identify merges an attribute into an existing user, keeping the others. + Product bug: every attribute or `externalId` write on an EXISTING user over + REST (PATCH /api/v1/users/:id and identify of a known email) answers 500. + `user.identify.ts:81` and `:257` build + `... ::jsonb - ${metadataRemovals}::text[]`; drizzle expands a JS array in + a `sql` template into a parameter list, so the SQL is `- ()::text[]` + (syntax error) with no removals and `- ($4)::text[]` (malformed array + literal) with one. Creating a user through identify is unaffected. Fix: + bind the array as one parameter, e.g. + `- ${sql.param(metadataRemovals)}::text[]` or + `- ARRAY[${sql.join(metadataRemovals.map((k) => sql`${k}`), sql`, `)}]::text[]` + with a guard for the empty case. owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/product/people.ts b/apps/web/e2e/product/people.ts index 7646acfb0a..2da2bdac5b 100644 --- a/apps/web/e2e/product/people.ts +++ b/apps/web/e2e/product/people.ts @@ -29,7 +29,7 @@ import { apiFor, createKey, type CreatedKey } from '../support/api-client' import { callServerFn, type ServerFnResult } from '../support/server-fns' import { mintCustomer, portalContext, type MintedCustomer } from '../support/widget-portal' -export { personApi, callServerFn } from '../support/server-fns' +export { personApi } from '../support/server-fns' /** The fixed placeholder principal removed people's content is re-pointed to. */ export const DELETED_USER_PRINCIPAL = 'principal_00000000000000000000000000' @@ -120,6 +120,37 @@ export async function seedLead( } } +/** Server functions the people specs call that are GETs. */ +const GET_FNS = new Set([ + 'listPortalUsersFn', + 'getPortalUserFn', + 'listDuplicateUsersFn', + 'listUserTagsFn', + 'listUserTagsForPrincipalFn', + 'getPersonBlockStatusFn', + 'getChangelogSubscriptionStatusFn', + 'getProfileTeamContextFn', + 'searchPeopleFn', + 'listCompaniesFn', + 'getCompanyFn', + 'listCompanyAttributesFn', + 'listUserAttributesFn', +]) + +function methodOf(name: string, method?: 'POST' | 'GET'): 'POST' | 'GET' { + return method ?? (GET_FNS.has(name) ? 'GET' : 'POST') +} + +/** Call a server function by name; GETs are known by name (GET_FNS). */ +export function call( + api: APIRequestContext, + name: string, + data?: unknown, + opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} +): Promise> { + return callServerFn(api, name, data, { ...opts, method: methodOf(name, opts.method) }) +} + /** Call a server function and fail the test when it throws. */ export async function mustCall( api: APIRequestContext, @@ -127,7 +158,7 @@ export async function mustCall( data?: unknown, opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} ): Promise { - const res = await callServerFn(api, name, data, opts) + const res = await call(api, name, data, opts) expect(res.ok, `${name}: ${res.raw.slice(0, 400)}`).toBe(true) return res.data } @@ -139,7 +170,7 @@ export async function refusedCall( data?: unknown, opts: { sourceFile?: string; method?: 'POST' | 'GET' } = {} ): Promise { - const res = await callServerFn(api, name, data, opts) + const res = await call(api, name, data, opts) expect(res.ok, `${name} should be refused: ${res.raw.slice(0, 300)}`).toBe(false) return res } @@ -256,3 +287,104 @@ export function usersUrl(opts: { const s = q.toString() return `/admin/users${s ? `?${s}` : ''}` } + +/** A teammate's or portal user's name/email/verified straight from the rows. */ +export async function userRow( + userUuid: string +): Promise<{ + name: string + email: string | null + email_verified: boolean + metadata: string | null +}> { + const [row] = await supportDb()`SELECT name, email, email_verified, metadata FROM "user" + WHERE id = ${userUuid}` + if (!row) throw new Error(`no user ${userUuid}`) + return row as never +} + +/** The workspace's post status id by slug (open, planned, complete, ...). */ +export async function postStatusId(slug: string): Promise { + const [row] = await supportDb()`SELECT id FROM post_statuses WHERE slug = ${slug} LIMIT 1` + if (!row) throw new Error(`no post status ${slug}`) + return fromUuid('post_status', row.id as string) +} + +/** + * Activity a lead left while anonymous interaction was on (the suite's + * workspace has it off, so leads cannot act through the portal here). Each + * row is written as the vote, post and comment paths write it, counters + * included. + */ +export async function seedLeadActivity( + leadPrincipalUuid: string, + act: + | { vote: string } + | { post: { boardId: string; title: string } } + | { comment: { postId: string; content: string } } +): Promise { + const sql = supportDb() + if ('vote' in act) { + const id = toUuid(generateId('vote')) + await sql.begin(async (tx) => { + await tx`INSERT INTO post_votes (id, post_id, principal_id) + VALUES (${id}, ${uuid(act.vote)}, ${leadPrincipalUuid})` + await tx`UPDATE posts SET vote_count = vote_count + 1 WHERE id = ${uuid(act.vote)}` + }) + return fromUuid('vote', id) + } + if ('post' in act) { + const id = toUuid(generateId('post')) + await sql`INSERT INTO posts (id, board_id, title, content, principal_id) + VALUES (${id}, ${uuid(act.post.boardId)}, ${act.post.title}, '', ${leadPrincipalUuid})` + return fromUuid('post', id) + } + const id = toUuid(generateId('comment')) + await sql.begin(async (tx) => { + await tx`INSERT INTO post_comments (id, post_id, principal_id, content) + VALUES (${id}, ${uuid(act.comment.postId)}, ${leadPrincipalUuid}, ${act.comment.content})` + await tx`UPDATE posts SET comment_count = comment_count + 1 + WHERE id = ${uuid(act.comment.postId)}` + }) + return fromUuid('comment', id) +} + +/** A browser context signed in as a lead (anonymous principal with a session). */ +export async function leadContext( + browser: Browser, + lead: Pick +): Promise { + return portalContext(browser, lead) +} + +/** A user attribute definition with a fresh key; returns the key. */ +export async function seedUserAttribute( + type: 'string' | 'number' | 'boolean' | 'date' | 'currency', + opts: { label?: string; currencyCode?: string } = {} +): Promise { + const key = `e2e_${type}_${suffix()}${suffix()}` + await supportDb()`INSERT INTO user_attribute_definitions (id, key, label, type, currency_code) + VALUES (${toUuid(generateId('user_attr'))}, ${key}, ${opts.label ?? key}, ${type}, + ${opts.currencyCode ?? (type === 'currency' ? 'USD' : null)})` + return key +} + +/** A user's metadata JSON (attributes live here). */ +export async function metadataOf(userUuid: string): Promise> { + const [row] = await supportDb()`SELECT metadata FROM "user" WHERE id = ${userUuid}` + return row?.metadata ? (JSON.parse(row.metadata as string) as Record) : {} +} + +export interface AuditRow { + event_type: string + before_value: Record | null + after_value: Record | null + metadata: Record | null +} + +/** Audit rows of one event type for a target id, oldest first. */ +export async function auditRows(eventType: string, targetId: string): Promise { + return supportDb()`SELECT event_type, before_value, after_value, metadata + FROM audit_log WHERE event_type = ${eventType} AND target_id = ${targetId} + ORDER BY occurred_at` +} diff --git a/apps/web/e2e/tests/people/users-api.spec.ts b/apps/web/e2e/tests/people/users-api.spec.ts index 650b003235..2bd871ba5f 100644 --- a/apps/web/e2e/tests/people/users-api.spec.ts +++ b/apps/web/e2e/tests/people/users-api.spec.ts @@ -2,22 +2,163 @@ * People over the REST API (/api/v1/users), the people server functions' * refusals and permission gates. * - * Journeys: PPL-U-45, PPL-U-57, PPL-U-59, PPL-U-64 + * Journeys: PPL-U-39, PPL-U-45, PPL-U-46, PPL-U-47, PPL-U-57, PPL-U-59, + * PPL-U-60, PPL-U-61, PPL-U-64, PPL-U-65, PPL-U-66, PPL-U-69, PPL-U-70, + * PPL-U-72 */ import { generateId } from '@quackback/ids' import { test, expect } from '../../support/fixtures' import { supportDb } from '../../support/db' -import { expectJson } from '../../support/api-client' +import { createRole } from '../../support/access' +import { apiFor, createKey, expectJson } from '../../support/api-client' +import { supportEnv } from '../../support/env' import { DELETED_USER_PRINCIPAL, + auditRows, + call, + metadataOf, mustCall, personApi, portalUserRow, refusedCall, restAdmin, seedLead, + seedUserAttribute, + userRow, + uuid, } from '../../product/people' +/** User attribute writes on an existing user fail in user.identify.ts (QUARANTINE.md). */ +const QUARANTINE_ATTR_WRITE = { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'user.identify.ts builds the metadata update with ${metadataRemovals}::text[], which drizzle expands to () or ($n), so every attribute or externalId write on an existing user is a 500; see QUARANTINE.md', + }, +} as const + +test.describe('blocking: refusals', () => { + test( + 'PPL-U-39 block is refused for a teammate, a service principal and an unknown id; a lead can be blocked', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const sql = supportDb() + const mate = await newTeammate({ roleKey: 'contributor' }) + const service = createKey({ + creatorEmail: 'e2e-support-admin@example.com', + kind: 'workspace', + roleKey: 'contributor', + }) + const cases: Array<[string, string[]]> = [ + [mate.principalId, ['CANNOT_BLOCK_TEAM']], + // A workspace key's principal holds a team role, so the team guard + // answers before the service guard (blocking.ts assertBlockable). + [service.principalId, ['CANNOT_BLOCK_TEAM', 'CANNOT_BLOCK_SERVICE']], + [generateId('principal'), ['PRINCIPAL_NOT_FOUND']], + ] + for (const [principalId, codes] of cases) { + const res = await refusedCall(admin, 'blockPersonFn', { principalId }) + expect(codes, principalId).toContain(res.code) + } + const blocked = await sql`SELECT id FROM principal WHERE blocked_at IS NOT NULL + AND id IN ${sql([uuid(mate.principalId), uuid(service.principalId)])}` + expect(blocked).toHaveLength(0) + + const lead = await seedLead(marker) + await mustCall(admin, 'blockPersonFn', { principalId: lead.principalId }) + const [row] = await sql`SELECT blocked_at FROM principal WHERE id = ${lead.principalUuid}` + expect(row.blocked_at).not.toBeNull() + await admin.dispose() + } + ) +}) + +test.describe('people permissions', () => { + test( + 'PPL-U-46 a people.view-only teammate reads people but every people write is refused', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const mate = await newTeammate({ roleKey: 'contributor' }) + const api = await mate.api(playwright) + const person = await portalUserRow(marker) + const lead = await seedLead(marker, { contactEmail: person.email }) + const target = { principalId: person.principalId } + + for (const [name, data] of [ + ['listPortalUsersFn', { search: marker }], + ['getPortalUserFn', target], + ['listDuplicateUsersFn', target], + ['listUserTagsFn', undefined], + ['getPersonBlockStatusFn', target], + ['getChangelogSubscriptionStatusFn', target], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name}: ${res.raw.slice(0, 200)}`).toBe(true) + } + + for (const [name, data] of [ + ['updatePortalUserFn', { ...target, name: `Hijack ${marker}` }], + ['createPortalUserFn', { name: `New ${marker}`, email: `${marker}-new@customers.example` }], + ['findPortalUsersByEmailFn', { email: person.email }], + ['deletePortalUserFn', target], + [ + 'mergeLeadIntoUserFn', + { principalId: lead.principalId, targetPrincipalId: person.principalId }, + ], + ['assignUserTagFn', { ...target, name: `tag-${marker}` }], + ['removeUserTagFn', { ...target, tagId: generateId('user_tag') }], + ['blockPersonFn', target], + ['unblockPersonFn', target], + ['setChangelogSubscriptionFn', { ...target, subscribed: true }], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name} must be refused`).toBe(false) + } + + const row = await userRow(person.userUuid) + expect(row.name).toBe(person.name) + const sql = supportDb() + const [principal] = + await sql`SELECT blocked_at FROM principal WHERE id = ${person.principalUuid}` + expect(principal.blocked_at).toBeNull() + const [leadRow] = await sql`SELECT id FROM principal WHERE id = ${lead.principalUuid}` + expect(leadRow, 'the lead was not merged').toBeDefined() + const created = + await sql`SELECT id FROM "user" WHERE email = ${`${marker}-new@customers.example`}` + expect(created).toHaveLength(0) + const tagged = await sql`SELECT t.id FROM user_tags t WHERE t.name = ${`tag-${marker}`}` + expect(tagged).toHaveLength(0) + await api.dispose() + } + ) + + test( + 'PPL-U-47 a teammate without people.view gets nothing from people reads', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const roleKey = await createRole(marker, ['conversation.view', 'member.view']) + const mate = await newTeammate({ roleKey }) + const api = await mate.api(playwright) + const person = await portalUserRow(marker) + const target = { principalId: person.principalId } + for (const [name, data] of [ + ['listPortalUsersFn', { search: marker }], + ['getPortalUserFn', target], + ['getPersonBlockStatusFn', target], + ['getProfileTeamContextFn', target], + ['searchPeopleFn', { search: marker }], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name} must be refused: ${res.raw.slice(0, 200)}`).toBe(false) + expect(res.raw, name).not.toContain(person.email) + } + await api.dispose() + } + ) +}) + test.describe('removing people: refusals', () => { test( 'PPL-U-45 remove is refused for a teammate, the placeholder, an unknown id and a repeat', @@ -204,4 +345,406 @@ test.describe('REST /api/v1/users', () => { await rest.dispose() } ) + + test( + 'PPL-U-60 PATCH a user name and image; a teammate id is refused', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const rest = await restAdmin(playwright) + const person = await portalUserRow(marker) + const body = await expectJson( + await rest.patch(`/api/v1/users/${person.principalId}`, { + data: { name: `Patched ${marker}`, image: 'https://images.example/avatar.png' }, + }), + 200 + ) + expect(body.data).toMatchObject({ + principalId: person.principalId, + name: `Patched ${marker}`, + image: 'https://images.example/avatar.png', + email: person.email, + }) + expect((await userRow(person.userUuid)).name).toBe(`Patched ${marker}`) + const [principal] = await supportDb()`SELECT display_name, avatar_url FROM principal + WHERE id = ${person.principalUuid}` + expect(principal.display_name).toBe(`Patched ${marker}`) + + const mate = await expectJson( + await rest.patch(`/api/v1/users/${people.people.agentB.principalId}`, { + data: { name: `Hijack ${marker}` }, + }), + 404 + ) + expect(mate.error.message).toBe('Member not found') + await rest.dispose() + } + ) + + test( + 'PPL-U-60 PATCH merges coerced attributes, unsets null keys and sets the external id', + QUARANTINE_ATTR_WRITE, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const plan = await seedUserAttribute('string') + const seats = await seedUserAttribute('number') + const old = await seedUserAttribute('string') + const person = await portalUserRow(marker) + await supportDb()`UPDATE "user" SET metadata = ${JSON.stringify({ [old]: 'gone soon' })} + WHERE id = ${person.userUuid}` + + const body = await expectJson( + await rest.patch(`/api/v1/users/${person.principalId}`, { + data: { + externalId: `ext-${marker}`, + attributes: { [plan]: 'pro', [seats]: '5', [old]: null }, + }, + }), + 200 + ) + expect(body.data.externalId).toBe(`ext-${marker}`) + const meta = await metadataOf(person.userUuid) + expect(meta[plan]).toBe('pro') + expect(meta[seats]).toBe(5) + expect(meta).not.toHaveProperty(old) + expect(meta._externalUserId).toBe(`ext-${marker}`) + + await expectJson( + await rest.patch(`/api/v1/users/${person.principalId}`, { data: { externalId: null } }), + 200 + ) + expect(await metadataOf(person.userUuid)).not.toHaveProperty('_externalUserId') + await rest.dispose() + } + ) + + test( + 'PPL-U-61 attribute and body validation refuses the whole request and writes nothing', + { tag: '@core' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const num = await seedUserAttribute('number') + const bool = await seedUserAttribute('boolean') + const date = await seedUserAttribute('date') + const text = await seedUserAttribute('string') + const person = await portalUserRow(marker) + const patch = (data: unknown) => rest.patch(`/api/v1/users/${person.principalId}`, { data }) + + const unknown = await expectJson( + await patch({ attributes: { [text]: 'kept?', nope_not_defined: 'x' } }), + 400 + ) + expect(unknown.error.code).toBe('VALIDATION_ERROR') + expect(unknown.error.message).toBe('One or more user attributes are invalid') + expect(JSON.stringify(unknown.error.details)).toContain( + "No attribute definition found for key 'nope_not_defined'" + ) + + const badNumber = await expectJson(await patch({ attributes: { [num]: 'abc' } }), 400) + expect(JSON.stringify(badNumber.error.details)).toContain( + "Value 'abc' cannot be coerced to type 'number'" + ) + await expectJson(await patch({ attributes: { [bool]: 'yes' } }), 400) + await expectJson(await patch({ attributes: { [date]: 'not a date' } }), 400) + expect(await metadataOf(person.userUuid), 'no partial write').toEqual({}) + + const schema = await expectJson( + await patch({ name: 'x'.repeat(201), image: 'not a url' }), + 400 + ) + expect(schema.error.code).toBe('BAD_REQUEST') + expect(schema.error.message).toBe('Invalid request body') + expect(Object.keys(schema.error.details.errors).sort()).toEqual(['image', 'name']) + expect((await userRow(person.userUuid)).name).toBe(person.name) + await rest.dispose() + } + ) + + test( + 'PPL-U-61 boolean and date attributes accept their valid spellings', + QUARANTINE_ATTR_WRITE, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const bool = await seedUserAttribute('boolean') + const date = await seedUserAttribute('date') + const person = await portalUserRow(marker) + const patch = (data: unknown) => rest.patch(`/api/v1/users/${person.principalId}`, { data }) + for (const value of ['true', '1', 'false', '0']) { + await expectJson(await patch({ attributes: { [bool]: value } }), 200) + } + expect((await metadataOf(person.userUuid))[bool]).toBe(false) + await expectJson(await patch({ attributes: { [date]: '2026-01-02' } }), 200) + expect((await metadataOf(person.userUuid))[date]).toBe('2026-01-02T00:00:00.000Z') + await rest.dispose() + } + ) + + test( + 'PPL-U-65 identify creates a portal user, auditing only an asserted verification', + { tag: '@core' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const plan = await seedUserAttribute('string') + const email = `${marker}-New@Customers.Example` + + const created = await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email, attributes: { [plan]: 'team' }, externalId: `ext-${marker}` }, + }), + 201 + ) + expect(created.data).toMatchObject({ + name: `${marker}-new`, + email: email.toLowerCase(), + emailVerified: false, + externalId: `ext-${marker}`, + attributes: { [plan]: 'team' }, + created: true, + }) + const [principal] = await supportDb()`SELECT role FROM principal + WHERE id = ${uuid(created.data.principalId)}` + expect(principal.role).toBe('user') + expect(await auditRows('user.email_verified.asserted', created.data.userId)).toEqual([]) + + const verified = await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email: `${marker}-v@customers.example`, emailVerified: true }, + }), + 201 + ) + expect(verified.data.emailVerified).toBe(true) + const [audit] = await auditRows('user.email_verified.asserted', verified.data.userId) + expect(audit.before_value).toBeNull() + expect(audit.after_value).toEqual({ emailVerified: true }) + expect(audit.metadata).toMatchObject({ + source: 'api.users.identify', + apiKeyId: expect.any(String), + created: true, + }) + await rest.dispose() + } + ) + + test( + 'PPL-U-66 identify updates an existing user and audits only a true-over-false flip', + { tag: '@core' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const person = await portalUserRow(marker, { verified: false }) + + const res = await expectJson( + await rest.post('/api/v1/users/identify', { + data: { + email: person.email, + name: `Identified ${marker}`, + image: 'https://images.example/i.png', + }, + }), + 200 + ) + expect(res.data).toMatchObject({ created: false, name: `Identified ${marker}` }) + expect((await userRow(person.userUuid)).email_verified).toBe(false) + const [principal] = await supportDb()`SELECT display_name FROM principal + WHERE id = ${person.principalUuid}` + expect(principal.display_name).toBe(`Identified ${marker}`) + + await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email: person.email, emailVerified: true }, + }), + 200 + ) + const audits = await auditRows('user.email_verified.asserted', person.userId) + expect(audits).toHaveLength(1) + expect(audits[0].before_value).toEqual({ emailVerified: false }) + + await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email: person.email, emailVerified: false }, + }), + 200 + ) + expect((await userRow(person.userUuid)).email_verified).toBe(false) + expect(await auditRows('user.email_verified.asserted', person.userId)).toHaveLength(1) + await rest.dispose() + } + ) + + test( + 'PPL-U-66 identify merges an attribute into an existing user, keeping the others', + QUARANTINE_ATTR_WRITE, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const plan = await seedUserAttribute('string') + const tier = await seedUserAttribute('string') + const person = await portalUserRow(marker) + await supportDb()`UPDATE "user" SET metadata = ${JSON.stringify({ [tier]: 'gold' })} + WHERE id = ${person.userUuid}` + await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email: person.email, attributes: { [plan]: 'pro' } }, + }), + 200 + ) + expect(await metadataOf(person.userUuid)).toMatchObject({ [plan]: 'pro', [tier]: 'gold' }) + await rest.dispose() + } + ) + + test( + 'PPL-U-69 identify refuses bad bodies and creates nobody', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const rest = await restAdmin(playwright) + const missing = await expectJson( + await rest.post('/api/v1/users/identify', { data: { email: 'nope' } }), + 400 + ) + expect(missing.error.code).toBe('BAD_REQUEST') + expect(missing.error.details.errors.email).toEqual(['Valid email is required']) + const email = `${marker}@customers.example` + await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email, externalId: 'x'.repeat(256) }, + }), + 400 + ) + await expectJson( + await rest.post('/api/v1/users/identify', { data: { email, image: 'not a url' } }), + 400 + ) + const unknown = await expectJson( + await rest.post('/api/v1/users/identify', { + data: { email, attributes: { not_defined_anywhere: 1 } }, + }), + 400 + ) + expect(unknown.error.code).toBe('VALIDATION_ERROR') + const made = await supportDb()`SELECT id FROM "user" WHERE email = ${email}` + expect(made).toHaveLength(0) + await rest.dispose() + } + ) + + test( + 'PPL-U-69 a body that is not JSON is a 400, not a server error', + { tag: '@nightly' }, + async ({ playwright }) => { + const rest = await restAdmin(playwright) + const res = await rest.post('/api/v1/users/identify', { + headers: { 'content-type': 'application/json' }, + data: '{not json', + }) + expect(res.status(), await res.text()).toBe(400) + await rest.dispose() + } + ) + + test( + 'PPL-U-70 API key authority on the users endpoints', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const base = supportEnv().baseUrl + const keyed = (key: string | null) => apiFor(playwright, base, key) + const contributorKey = createKey({ creatorEmail: people.people.contributor.email }) + const readOnly = createKey({ + creatorEmail: people.people.admin.email, + scopes: ['read:feedback'], + }) + const legacy = createKey({ creatorEmail: people.people.admin.email, legacy: true }) + const adminKey = createKey({ creatorEmail: people.people.admin.email }) + + for (const [key, writeMessage] of [ + [contributorKey.key, "Requires the 'people.manage' permission"], + [ + readOnly.key, + "This API key is missing the 'write:feedback' scope required by 'people.manage'", + ], + ] as const) { + const api = await keyed(key) + await expectJson(await api.get(`/api/v1/users?search=${marker}`), 200) + const person = await portalUserRow(marker) + const patch = await expectJson( + await api.patch(`/api/v1/users/${person.principalId}`, { data: { name: 'x' } }), + 403 + ) + expect(patch.error.code).toBe('FORBIDDEN') + expect(patch.error.message).toBe(writeMessage) + await expectJson(await api.delete(`/api/v1/users/${person.principalId}`), 403) + await expectJson( + await api.post('/api/v1/users/identify', { + data: { email: `${marker}-${Date.now()}@customers.example` }, + }), + 403 + ) + expect((await userRow(person.userUuid)).name).toBe(person.name) + await api.dispose() + } + + for (const key of [adminKey.key, legacy.key]) { + const api = await keyed(key) + const person = await portalUserRow(marker) + await expectJson( + await api.patch(`/api/v1/users/${person.principalId}`, { + data: { name: `By key ${marker}` }, + }), + 200 + ) + const del = await api.delete(`/api/v1/users/${person.principalId}`) + expect(del.status()).toBe(204) + await api.dispose() + } + + for (const key of [null, 'qb_' + '0'.repeat(48)]) { + const api = await keyed(key) + const res = await api.get('/api/v1/users') + expect(res.status()).toBe(401) + expect(res.headers()['www-authenticate']).toBe('Bearer realm="Quackback API"') + expect((await res.json()).error.code).toBe('UNAUTHORIZED') + await api.dispose() + } + } + ) +}) + +test.describe('CSV export', () => { + test( + 'PPL-U-72 the users export carries the filtered directory; no people.view, no file', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const person = await portalUserRow(marker) + const lead = await seedLead(marker, { contactEmail: `${marker}-lead@customers.example` }) + + const res = await admin.get(`/api/export/users?search=${encodeURIComponent(marker)}`) + expect(res.status()).toBe(200) + expect(res.headers()['content-type']).toContain('text/csv') + expect(res.headers()['content-disposition']).toMatch( + /^attachment; filename="users-export-[a-z0-9-]+-\d+\.csv"$/ + ) + const lines = (await res.text()).trim().split('\n') + expect(lines[0]).toBe( + 'name,email,verified,lifecycle,segments,joined_at,last_seen_at,post_count,comment_count,vote_count' + ) + expect(lines).toHaveLength(2) + expect(lines[1]).toContain(person.email) + + const leads = await admin.get( + `/api/export/users?search=${encodeURIComponent(marker)}&lifecycle=leads` + ) + const leadLines = (await leads.text()).trim().split('\n') + expect(leadLines).toHaveLength(2) + expect(leadLines[1]).toContain(`${marker}-lead@customers.example`) + expect(leadLines[1]).toContain(',lead,') + expect(leadLines[1]).not.toContain(lead.email) + await admin.dispose() + + const roleKey = await createRole(marker, ['conversation.view']) + const mate = await newTeammate({ roleKey }) + const api = await mate.api(playwright) + const denied = await api.get(`/api/export/users?search=${encodeURIComponent(marker)}`) + expect(denied.status()).toBe(403) + expect(await denied.json()).toEqual({ error: 'Access denied' }) + await api.dispose() + } + ) }) diff --git a/apps/web/e2e/tests/people/users.spec.ts b/apps/web/e2e/tests/people/users.spec.ts index 5c3b7267d0..43d744357c 100644 --- a/apps/web/e2e/tests/people/users.spec.ts +++ b/apps/web/e2e/tests/people/users.spec.ts @@ -2,18 +2,30 @@ * People directory and profiles in the admin (/admin/users), and the portal * users' own rows they change. * - * Journeys: PPL-U-42 (smoke), PPL-U-43 + * Journeys: PPL-U-02, PPL-U-11, PPL-U-20, PPL-U-21, PPL-U-23, PPL-U-31, + * PPL-U-32, PPL-U-41, PPL-U-42 (smoke), PPL-U-43 */ +import type { APIRequestContext } from '@playwright/test' +import { generateId } from '@quackback/ids' import { test, expect } from '../../support/fixtures' import { supportDb } from '../../support/db' +import { emailLogFor, waitForEmailLog } from '../../support/mailpit' import { DELETED_USER_PRINCIPAL, commentAs, + leadContext, mustCall, personApi, portalUser, + portalUserRow, postAs, + postStatusId, + refusedCall, + restAdmin, seedBoard, + seedLead, + seedLeadActivity, + userRow, usersUrl, uuid, voteAs, @@ -21,6 +33,273 @@ import { voteRowsOf, } from '../../product/people' +interface ListedUser { + principalId: string + name: string | null + email: string | null + contactEmail: string | null + isLead: boolean +} + +async function listIds( + admin: APIRequestContext, + filters: Record +): Promise { + const res = await mustCall<{ items: ListedUser[] }>(admin, 'listPortalUsersFn', { + limit: 100, + ...filters, + }) + return res.items.map((u) => u.principalId) +} + +test.describe('directory search and leads', () => { + test( + 'PPL-U-02 search matches name, account email and a lead contact email, ignoring case', + { tag: '@core' }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const byName = await portalUserRow(marker, { + name: `Zelda ${marker.toUpperCase()}`, + email: `zz-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}@other.example`, + }) + const byEmail = await portalUserRow(marker, { name: 'Plain Name' }) + const lead = await seedLead('anon', { + name: 'Anonymous visitor', + contactEmail: `${marker}-lead@customers.example`, + }) + + const found = await listIds(admin, { search: marker.toUpperCase() }) + expect(found).toContain(byName.principalId) + expect(found).toContain(byEmail.principalId) + expect(found, 'leads stay on the Leads tab').not.toContain(lead.principalId) + + const leads = await listIds(admin, { search: `${marker}-LEAD`, lifecycle: 'leads' }) + expect(leads).toEqual([lead.principalId]) + await admin.dispose() + } + ) + + test( + 'PPL-U-11 the Leads tab lists engaged anonymous people only', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const board = await seedBoard(marker) + const author = await portalUser(browser, `${marker}-a`) + const post = await postAs(author.api, board.id, `Idea ${marker}`) + + const withEmail = await seedLead(marker, { contactEmail: `${marker}-c@customers.example` }) + const voter = await seedLead(marker) + const poster = await seedLead(marker) + const commenter = await seedLead(marker) + const idle = await seedLead(marker) + await seedLeadActivity(voter.principalUuid, { vote: post.id }) + await seedLeadActivity(poster.principalUuid, { + post: { boardId: board.id, title: `Lead idea ${marker}` }, + }) + await seedLeadActivity(commenter.principalUuid, { + comment: { postId: post.id, content: `Lead ${marker}` }, + }) + // A session alone does not make a lead. + await (await leadContext(browser, idle)).close() + + const res = await mustCall<{ items: ListedUser[] }>(admin, 'listPortalUsersFn', { + search: marker, + lifecycle: 'leads', + limit: 100, + }) + const ids = res.items.map((u) => u.principalId) + expect(ids.sort()).toEqual( + [withEmail, voter, poster, commenter].map((l) => l.principalId).sort() + ) + for (const item of res.items) { + expect(item.isLead).toBe(true) + expect(item.email ?? '').not.toContain('@anon') + } + const emailed = res.items.find((u) => u.principalId === withEmail.principalId) + expect(emailed?.contactEmail).toBe(`${marker}-c@customers.example`) + // Users and leads never mix. + expect(await listIds(admin, { search: marker })).toEqual([author.principalId]) + await admin.dispose() + } + ) +}) + +test.describe('editing a person', () => { + test( + 'PPL-U-20 changing an identified person email lowercases it and resets verification', + { tag: '@core' }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const person = await portalUserRow(marker) + const next = `New-${marker}@Example.com` + + await mustCall(admin, 'updatePortalUserFn', { principalId: person.principalId, email: next }) + let row = await userRow(person.userUuid) + expect(row.email).toBe(next.toLowerCase()) + expect(row.email_verified).toBe(false) + + // Re-saving the unchanged address with a new name keeps verification. + await supportDb()`UPDATE "user" SET email_verified = true WHERE id = ${person.userUuid}` + await mustCall(admin, 'updatePortalUserFn', { + principalId: person.principalId, + name: `Renamed ${marker}`, + email: next.toLowerCase(), + }) + row = await userRow(person.userUuid) + expect(row.name).toBe(`Renamed ${marker}`) + expect(row.email_verified).toBe(true) + expect(await emailLogFor(next.toLowerCase()), 'no email is sent').toEqual([]) + await admin.dispose() + } + ) + + test( + 'PPL-U-21 an address held by another account is refused; clearing an email is allowed', + { tag: '@core' }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const person = await portalUserRow(marker) + const other = await portalUserRow(marker) + + const taken = await refusedCall(admin, 'updatePortalUserFn', { + principalId: person.principalId, + email: other.email.toUpperCase(), + }) + expect(taken.code).toBe('EMAIL_IN_USE') + expect((await userRow(person.userUuid)).email).toBe(person.email) + + await mustCall(admin, 'updatePortalUserFn', { principalId: person.principalId, email: null }) + const row = await userRow(person.userUuid) + expect(row.email).toBeNull() + expect(row.email_verified).toBe(false) + await admin.dispose() + } + ) + + test( + 'PPL-U-23 editing a teammate or an unknown person is refused', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const mate = await newTeammate({ roleKey: 'contributor' }) + for (const principalId of [mate.principalId, generateId('principal')]) { + const res = await refusedCall(admin, 'updatePortalUserFn', { + principalId, + name: `Hijack ${marker}`, + }) + expect(res.code, principalId).toBe('USER_NOT_FOUND') + } + const [row] = await supportDb()`SELECT name FROM "user" WHERE email = ${mate.email}` + expect(row.name).toBe(mate.name) + await admin.dispose() + } + ) +}) + +test.describe('merging a lead', () => { + test( + 'PPL-U-31 merging a lead that voted the same post as the user leaves one vote counted', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'mergeLeadIntoUser deletes the colliding lead vote without decrementing posts.vote_count (principal-repoint.ts); see QUARANTINE.md', + }, + }, + async ({ browser, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const board = await seedBoard(marker) + const author = await portalUser(browser, `${marker}-a`) + const post = await postAs(author.api, board.id, `Idea ${marker}`) + const before = await voteCountOf(post.id) + const user = await portalUser(browser, marker) + const lead = await seedLead(marker, { contactEmail: user.email }) + await seedLeadActivity(lead.principalUuid, { vote: post.id }) + await voteAs(user.api, post.id) + expect(await voteCountOf(post.id)).toBe(before + 2) + + await mustCall(admin, 'mergeLeadIntoUserFn', { + principalId: lead.principalId, + targetPrincipalId: user.principalId, + }) + expect(await voteRowsOf(post.id)).toBe(before + 1) + expect(await voteCountOf(post.id), 'the count matches the vote rows').toBe(before + 1) + await admin.dispose() + } + ) + + test( + 'PPL-U-32 merge refusals move nothing', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const lead = await seedLead(marker, { contactEmail: `${marker}-l@customers.example` }) + const otherLead = await seedLead(marker) + const user = await portalUserRow(marker) + const otherUser = await portalUserRow(marker) + const mate = await newTeammate({ roleKey: 'contributor' }) + + const pairs: Array<[string, string]> = [ + [lead.principalId, lead.principalId], + [user.principalId, otherUser.principalId], + [lead.principalId, otherLead.principalId], + [lead.principalId, mate.principalId], + [lead.principalId, generateId('principal')], + ] + for (const [source, target] of pairs) { + const res = await refusedCall(admin, 'mergeLeadIntoUserFn', { + principalId: source, + targetPrincipalId: target, + }) + expect(res.code, `${source} -> ${target}`).toBe('MEMBER_NOT_FOUND') + } + const sql = supportDb() + const kept = [lead.principalUuid, user.principalUuid, otherLead.principalUuid] + const rows = await sql`SELECT id FROM principal WHERE id IN ${sql(kept)}` + expect(rows).toHaveLength(3) + await admin.dispose() + } + ) +}) + +test.describe('blocking', () => { + test( + 'PPL-U-41 a blocked subscriber gets no status-change email; the other subscriber does', + { tag: '@core' }, + async ({ browser, playwright, marker }) => { + const board = await seedBoard(marker) + const blocked = await portalUser(browser, marker) + const post = await postAs(blocked.api, board.id, `Idea ${marker}`) + const other = await portalUser(browser, marker) + await commentAs(other.api, post.id, `Me too ${marker}`) + const subs = await supportDb()`SELECT principal_id FROM post_subscriptions + WHERE post_id = ${uuid(post.id)}` + expect(subs.map((r) => r.principal_id as string).sort()).toEqual( + [blocked.principalUuid, other.principalUuid].sort() + ) + + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'blockPersonFn', { principalId: blocked.principalId }) + await admin.dispose() + + const rest = await restAdmin(playwright) + const res = await rest.patch(`/api/v1/posts/${post.id}`, { + data: { statusId: await postStatusId('planned') }, + }) + expect(res.status(), await res.text()).toBe(200) + await rest.dispose() + + await waitForEmailLog(other.email, { direction: 'outbound' }, 30_000) + // The blocked person's delivery runs in the same fan-out; give it a + // moment more before reading its absence. + await new Promise((r) => setTimeout(r, 3_000)) + expect(await emailLogFor(blocked.email)).toEqual([]) + } + ) +}) + test.describe('removing a person', () => { test( 'PPL-U-42 removing a portal user takes them off the portal and re-points their content', From d43ad18a8093ca5e8cddf1a14004dbaa268d649d Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 01:36:45 +0000 Subject: [PATCH 3/5] test(e2e): people directory, profile and attribute journeys in the admin --- apps/web/e2e/product/people.ts | 17 +- .../e2e/tests/people/user-attributes.spec.ts | 153 ++++++++++ apps/web/e2e/tests/people/users.spec.ts | 271 +++++++++++++++++- 3 files changed, 432 insertions(+), 9 deletions(-) create mode 100644 apps/web/e2e/tests/people/user-attributes.spec.ts diff --git a/apps/web/e2e/product/people.ts b/apps/web/e2e/product/people.ts index 2da2bdac5b..8cb01df99e 100644 --- a/apps/web/e2e/product/people.ts +++ b/apps/web/e2e/product/people.ts @@ -40,13 +40,20 @@ function suffix(): string { /** A public board only this test uses. */ export async function seedBoard( - marker: string + marker: string, + opts: { teamOnly?: boolean } = {} ): Promise<{ id: string; slug: string; name: string }> { const uuid = toUuid(generateId('board')) const slug = `${marker}-${suffix()}`.slice(0, 60) const name = `Board ${marker}`.slice(0, 90) - await supportDb()`INSERT INTO boards (id, slug, name, description) - VALUES (${uuid}, ${slug}, ${name}, 'people e2e board')` + const sql = supportDb() + await sql`INSERT INTO boards (id, slug, name, description) + VALUES (${uuid}, ${slug}, ${name}, 'people e2e board')` + if (opts.teamOnly) { + // A private board: every action limited to the team. + await sql`UPDATE boards SET access = access || '{"view":"team","vote":"team","comment":"team","submit":"team"}'::jsonb + WHERE id = ${uuid}` + } return { id: fromUuid('board', uuid), slug, name } } @@ -289,9 +296,7 @@ export function usersUrl(opts: { } /** A teammate's or portal user's name/email/verified straight from the rows. */ -export async function userRow( - userUuid: string -): Promise<{ +export async function userRow(userUuid: string): Promise<{ name: string email: string | null email_verified: boolean diff --git a/apps/web/e2e/tests/people/user-attributes.spec.ts b/apps/web/e2e/tests/people/user-attributes.spec.ts new file mode 100644 index 0000000000..db95280bf2 --- /dev/null +++ b/apps/web/e2e/tests/people/user-attributes.spec.ts @@ -0,0 +1,153 @@ +/** + * User attribute definitions (/admin/settings/people) and how they gate + * attribute writes. + * + * Journeys: PPL-U-50, PPL-U-55, PPL-U-56 + */ +import { randomBytes } from 'node:crypto' +import { fromUuid } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { createRole } from '../../support/access' +import { expectJson } from '../../support/api-client' +import { + call, + metadataOf, + mustCall, + personApi, + portalUserRow, + restAdmin, + seedUserAttribute, +} from '../../product/people' + +const fromDefinition = (id: string) => fromUuid('user_attr', id) + +async function definitionByKey(key: string) { + const [row] = await supportDb()`SELECT id, key, label, type, description, external_key + FROM user_attribute_definitions WHERE key = ${key}` + return row +} + +test( + 'PPL-U-50 creating an attribute normalises its key and lists it after a reload', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const hex = randomBytes(4).toString('hex') + const admin = await asPerson('admin') + await admin.goto('/admin/settings/people') + await admin.getByRole('button', { name: 'New attribute' }).click() + const dialog = admin.getByRole('dialog') + const create = dialog.getByRole('button', { name: 'Create attribute' }) + await expect(create).toBeDisabled() + // The field rewrites what is typed as it goes: lowercase, anything but + // letters, digits and underscores becomes an underscore. + const keyBox = dialog.getByLabel(/^Key/) + await keyBox.fill(`Plan Tier ${hex}`) + await expect(keyBox).toHaveValue(`plan_tier_${hex}`) + await expect(create).toBeDisabled() + await dialog.getByLabel('Display label').fill(` Plan ${marker} `) + await expect(create).toBeEnabled() + await create.click() + await expect(dialog).toHaveCount(0) + + const key = `plan_tier_${hex}` + const row = await definitionByKey(key) + expect(row).toMatchObject({ + key, + label: `Plan ${marker}`, + type: 'string', + description: null, + external_key: null, + }) + await admin.reload() + await expect(admin.getByText(`Plan ${marker}`, { exact: true })).toBeVisible({ + timeout: 15_000, + }) + await expect(admin.getByText(key, { exact: true })).toBeVisible() + + // The server normalises a key that reaches it untrimmed. + const api = await personApi(playwright, 'admin') + await mustCall(api, 'createUserAttributeFn', { + key: ` Plan Tier ${hex}b `, + label: ` Plan ${marker} b `, + type: 'string', + }) + await api.dispose() + expect(await definitionByKey(`plan_tier_${hex}b`)).toMatchObject({ label: `Plan ${marker} b` }) + } +) + +test( + 'PPL-U-55 deleting an attribute keeps stored values but refuses new writes', + { tag: '@core' }, + async ({ playwright, marker }) => { + const key = await seedUserAttribute('string') + const person = await portalUserRow(marker) + // The value as an earlier write stored it. + await supportDb()`UPDATE "user" SET metadata = ${JSON.stringify({ [key]: 'pro' })} + WHERE id = ${person.userUuid}` + const def = await definitionByKey(key) + + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'deleteUserAttributeFn', { id: fromDefinition(def.id as string) }) + await admin.dispose() + expect(await definitionByKey(key)).toBeUndefined() + expect(await metadataOf(person.userUuid)).toMatchObject({ [key]: 'pro' }) + + const rest = await restAdmin(playwright) + const shown = await expectJson(await rest.get(`/api/v1/users/${person.principalId}`), 200) + expect(shown.data.attributes).toMatchObject({ [key]: 'pro' }) + const refused = await expectJson( + await rest.patch(`/api/v1/users/${person.principalId}`, { + data: { attributes: { [key]: 'team' } }, + }), + 400 + ) + expect(refused.error.code).toBe('VALIDATION_ERROR') + expect(refused.error.details.invalidAttributes).toEqual([ + { key, reason: `No attribute definition found for key '${key}'` }, + ]) + expect(await metadataOf(person.userUuid)).toMatchObject({ [key]: 'pro' }) + await rest.dispose() + } +) + +test( + 'PPL-U-56 attribute definitions need user_attribute.view to read and .manage to change', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const create = (k: string) => ({ key: k, label: `Label ${k}`, type: 'string' }) + const viewOnly = await newTeammate({ + roleKey: await createRole(marker, ['user_attribute.view']), + }) + const contributor = await newTeammate({ roleKey: 'contributor' }) + const manager = await newTeammate({ roleKey: 'manager' }) + const existing = await seedUserAttribute('string') + const id = fromDefinition((await definitionByKey(existing)).id as string) + + const c = await contributor.api(playwright) + expect((await call(c, 'listUserAttributesFn')).ok).toBe(false) + expect((await call(c, 'createUserAttributeFn', create(`c_${marker.slice(-8)}`))).ok).toBe(false) + await c.dispose() + + const v = await viewOnly.api(playwright) + expect((await call(v, 'listUserAttributesFn')).ok).toBe(true) + const vKey = `v_${randomBytes(4).toString('hex')}` + expect((await call(v, 'createUserAttributeFn', create(vKey))).ok).toBe(false) + expect((await call(v, 'updateUserAttributeFn', { id, label: 'Changed' })).ok).toBe(false) + expect((await call(v, 'deleteUserAttributeFn', { id })).ok).toBe(false) + expect(await definitionByKey(vKey)).toBeUndefined() + expect((await definitionByKey(existing)).label).toBe(existing) + await v.dispose() + + const m = await manager.api(playwright) + const mKey = `m_${randomBytes(4).toString('hex')}` + await mustCall(m, 'createUserAttributeFn', create(mKey)) + await mustCall(m, 'updateUserAttributeFn', { id, label: `Changed ${marker}` }) + expect((await definitionByKey(existing)).label).toBe(`Changed ${marker}`) + await mustCall(m, 'deleteUserAttributeFn', { id }) + expect(await definitionByKey(existing)).toBeUndefined() + expect(await definitionByKey(mKey)).toBeDefined() + await m.dispose() + } +) diff --git a/apps/web/e2e/tests/people/users.spec.ts b/apps/web/e2e/tests/people/users.spec.ts index 43d744357c..310686b6ee 100644 --- a/apps/web/e2e/tests/people/users.spec.ts +++ b/apps/web/e2e/tests/people/users.spec.ts @@ -2,11 +2,12 @@ * People directory and profiles in the admin (/admin/users), and the portal * users' own rows they change. * - * Journeys: PPL-U-02, PPL-U-11, PPL-U-20, PPL-U-21, PPL-U-23, PPL-U-31, - * PPL-U-32, PPL-U-41, PPL-U-42 (smoke), PPL-U-43 + * Journeys: PPL-U-01, PPL-U-02, PPL-U-11, PPL-U-14, PPL-U-19, PPL-U-20, + * PPL-U-21, PPL-U-23, PPL-U-24, PPL-U-26, PPL-U-29, PPL-U-31, PPL-U-32, + * PPL-U-36, PPL-U-41, PPL-U-42 (smoke), PPL-U-43, PPL-U-75 */ import type { APIRequestContext } from '@playwright/test' -import { generateId } from '@quackback/ids' +import { fromUuid, generateId } from '@quackback/ids' import { test, expect } from '../../support/fixtures' import { supportDb } from '../../support/db' import { emailLogFor, waitForEmailLog } from '../../support/mailpit' @@ -300,6 +301,270 @@ test.describe('blocking', () => { ) }) +test.describe('directory and profile in the admin', () => { + test( + 'PPL-U-01 the Users tab lists identified portal users only, with a matching count', + { tag: '@core' }, + async ({ asPerson, people, marker, newTeammate }) => { + const a = await portalUserRow(marker, { name: `Alpha ${marker}` }) + const b = await portalUserRow(marker, { name: `Bravo ${marker}`, verified: false }) + await newTeammate({ roleKey: 'contributor', name: `Mate ${marker}` }) + const lead = await seedLead(marker, { name: `Lead ${marker}` }) + await supportDb()`UPDATE principal SET contact_email = ${`${marker}-l@customers.example`} + WHERE id = ${lead.principalUuid}` + const testCustomer = await portalUserRow(marker, { name: `Tester ${marker}` }) + await supportDb()`UPDATE principal SET test_owner_principal_id = ${uuid(people.people.admin.principalId)} + WHERE id = ${testCustomer.principalUuid}` + + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker })) + const rows = admin.getByRole('heading', { level: 3 }) + await expect(rows).toHaveText([`Alpha ${marker}`, `Bravo ${marker}`].reverse(), { + timeout: 15_000, + }) + await expect(admin.getByText('2 users', { exact: true })).toBeVisible() + await expect(admin.getByText(a.email)).toBeVisible() + await expect(admin.getByText(b.email)).toBeVisible() + } + ) + + test( + 'PPL-U-14 a profile shows its header, badges, email and fact strip', + { tag: '@core' }, + async ({ asPerson, browser, marker }) => { + const board = await seedBoard(marker) + const person = await portalUser(browser, marker) + const post = await postAs(person.api, board.id, `Idea ${marker}`) + await commentAs(person.api, post.id, `Comment ${marker}`) + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker, selected: person.principalId })) + + await expect(admin.getByRole('heading', { name: person.name, exact: true })).toBeVisible({ + timeout: 15_000, + }) + await expect(admin.getByText('User', { exact: true })).toBeVisible() + await expect(admin.getByText(person.email, { exact: true })).toBeVisible() + for (const [value, label] of [ + ['1', 'Posts'], + ['1', 'Comments'], + ['1', 'Votes'], + ]) { + const cell = admin.getByText(label, { exact: true }).locator('..') + await expect(cell, label).toHaveText(`${value}${label}`) + } + await expect(admin.getByText('Joined', { exact: true })).toBeVisible() + await expect(admin.getByText('Country', { exact: true })).toBeVisible() + await expect(admin.getByRole('link', { name: 'View public profile' })).toHaveAttribute( + 'href', + `/u/${person.principalId}` + ) + await admin.getByText('Back to users').click() + await expect(admin.getByText('Back to users')).toHaveCount(0) + await expect(admin.getByRole('heading', { level: 3, name: person.name })).toBeVisible() + } + ) + + test( + 'PPL-U-19 the admin renames a person from the profile', + { tag: '@core' }, + async ({ asPerson, browser, marker }) => { + const board = await seedBoard(marker) + const person = await portalUser(browser, marker) + const post = await postAs(person.api, board.id, `Idea ${marker}`) + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker, selected: person.principalId })) + await admin.getByTitle('Edit user details').click() + const nameBox = admin.getByPlaceholder('Name') + await nameBox.fill(` Renamed ${marker} `) + await admin.getByRole('button', { name: 'Save' }).click() + await expect(admin.getByText('User updated')).toBeVisible() + await expect( + admin.getByRole('heading', { name: `Renamed ${marker}`, exact: true }) + ).toBeVisible() + + expect((await userRow(person.userUuid)).name).toBe(`Renamed ${marker}`) + const [principal] = await supportDb()`SELECT display_name FROM principal + WHERE id = ${person.principalUuid}` + expect(principal.display_name).toBe(`Renamed ${marker}`) + + const visitor = await browser.newPage() + await visitor.goto(`/b/${board.slug}/posts/${post.id}`) + await expect(visitor.getByText(`Renamed ${marker}`).first()).toBeVisible() + await visitor.close() + } + ) + + test( + 'PPL-U-24 a new user with an email is created verified and audited', + { tag: '@core' }, + async ({ asPerson, people, marker }) => { + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker })) + await admin.getByRole('button', { name: 'New user', exact: true }).click() + const dialog = admin.getByRole('dialog') + await dialog.getByLabel('Name').fill(`Created ${marker}`) + const email = `${marker}-Created@Customers.Example` + await dialog.getByRole('textbox', { name: 'Email (optional)' }).fill(email) + await expect(dialog.getByRole('checkbox', { name: 'Email is verified' })).toBeChecked() + await dialog.getByRole('button', { name: 'Create user' }).click() + + await expect( + admin.getByRole('heading', { name: `Created ${marker}`, exact: true }) + ).toBeVisible({ timeout: 15_000 }) + const [row] = await supportDb()`SELECT u.id, u.email, u.email_verified, p.role FROM "user" u + JOIN principal p ON p.user_id = u.id WHERE u.email = ${email.toLowerCase()}` + expect(row).toMatchObject({ email_verified: true, role: 'user' }) + const userId = fromUuid('user', row.id as string) + const [audit] = await supportDb()`SELECT actor_email, after_value, metadata FROM audit_log + WHERE event_type = 'user.email_verified.asserted' AND target_id = ${userId}` + expect(audit.after_value).toEqual({ emailVerified: true }) + expect(audit.metadata).toMatchObject({ source: 'admin.create_portal_user' }) + expect(audit.actor_email).toBe(people.people.admin.email) + } + ) + + test( + 'PPL-U-26 new user dedup: an existing user blocks; leads offer Create anyway', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const existing = await portalUserRow(marker) + const shared = `${marker}-shared@customers.example` + await seedLead(marker, { contactEmail: shared }) + await seedLead(marker, { contactEmail: shared }) + + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker })) + await admin.getByRole('button', { name: 'New user', exact: true }).click() + const dialog = admin.getByRole('dialog') + await dialog.getByLabel('Name').fill(`Dup ${marker}`) + await dialog + .getByRole('textbox', { name: 'Email (optional)' }) + .fill(existing.email.toUpperCase()) + await dialog.getByRole('button', { name: 'Create user' }).click() + await expect(dialog.getByText('A user with this email already exists.')).toBeVisible() + await expect(dialog.getByRole('button', { name: 'View user' })).toBeVisible() + await expect(dialog.getByRole('button', { name: 'Create user' })).toBeDisabled() + + await dialog.getByRole('textbox', { name: 'Email (optional)' }).fill(shared) + await dialog.getByRole('button', { name: 'Create user' }).click() + await expect(dialog.getByText('Possible existing matches')).toBeVisible() + await expect(dialog.getByText('Lead', { exact: true })).toHaveCount(2) + await dialog.getByRole('button', { name: 'Create anyway' }).click() + await expect(admin.getByRole('heading', { name: `Dup ${marker}`, exact: true })).toBeVisible({ + timeout: 15_000, + }) + const made = await supportDb()`SELECT id FROM "user" WHERE email = ${shared}` + expect(made).toHaveLength(1) + } + ) + + test( + 'PPL-U-29 merging a lead into a user from the lead profile moves its activity', + { tag: '@core' }, + async ({ asPerson, browser, marker }) => { + const board = await seedBoard(marker) + const author = await portalUser(browser, `${marker}-a`) + const post = await postAs(author.api, board.id, `Idea ${marker}`) + const user = await portalUserRow(marker, { name: `Target ${marker}` }) + const lead = await seedLead(marker, { + name: `Lead ${marker}`, + contactEmail: `${marker}-l@customers.example`, + }) + await seedLeadActivity(lead.principalUuid, { vote: post.id }) + const comment = await seedLeadActivity(lead.principalUuid, { + comment: { postId: post.id, content: `Lead said ${marker}` }, + }) + + const admin = await asPerson('admin') + await admin.goto(usersUrl({ lifecycle: 'leads', search: marker, selected: lead.principalId })) + await expect(admin.getByRole('heading', { name: `Lead ${marker}`, exact: true })).toBeVisible( + { timeout: 15_000 } + ) + await admin.getByRole('button', { name: 'More actions' }).click() + await admin.getByRole('menuitem', { name: 'Merge' }).click() + const dialog = admin.getByRole('dialog') + await dialog.getByPlaceholder('Search users by name or email…').fill(`Target ${marker}`) + await dialog.getByText(`Target ${marker}`).click() + await dialog.getByRole('button', { name: 'Merge', exact: true }).click() + await expect(admin.getByText('Lead merged into user')).toBeVisible() + + const sql = supportDb() + expect(await sql`SELECT id FROM principal WHERE id = ${lead.principalUuid}`).toHaveLength(0) + expect(await sql`SELECT id FROM "user" WHERE id = ${lead.userUuid}`).toHaveLength(0) + const [vote] = await sql`SELECT principal_id FROM post_votes + WHERE post_id = ${uuid(post.id)} AND principal_id = ${user.principalUuid}` + expect(vote, 'the vote moved to the user').toBeDefined() + const [moved] = await sql`SELECT principal_id FROM post_comments WHERE id = ${uuid(comment)}` + expect(moved.principal_id).toBe(user.principalUuid) + const [target] = + await sql`SELECT contact_email FROM principal WHERE id = ${user.principalUuid}` + expect(target.contact_email).toBe(`${marker}-l@customers.example`) + + await admin.goto(usersUrl({ search: marker, selected: user.principalId })) + await expect(admin.getByRole('heading', { name: `Idea ${marker}` })).toBeVisible({ + timeout: 15_000, + }) + } + ) + + test( + 'PPL-U-36 blocking a portal user from the profile', + { tag: '@core' }, + async ({ asPerson, people, marker }) => { + const person = await portalUserRow(marker) + const admin = await asPerson('admin') + await admin.goto(usersUrl({ search: marker, selected: person.principalId })) + await admin.getByRole('button', { name: 'More actions' }).click() + await admin.getByRole('menuitem', { name: 'Block' }).click() + const dialog = admin.getByRole('alertdialog') + await expect(dialog.getByText(`Block ${person.name}?`)).toBeVisible() + await expect(dialog).toContainText( + 'They will not be able to send new messages or sign in again, and automatic emails to them stop.' + ) + await dialog.getByRole('button', { name: 'Block', exact: true }).click() + await expect(admin.getByText('User blocked')).toBeVisible() + await expect(admin.getByText('Blocked', { exact: true })).toBeVisible() + await admin.getByRole('button', { name: 'More actions' }).click() + await expect(admin.getByRole('menuitem', { name: 'Unblock' })).toBeVisible() + await admin.keyboard.press('Escape') + + const [row] = await supportDb()`SELECT blocked_at, blocked_by_principal_id FROM principal + WHERE id = ${person.principalUuid}` + expect(row.blocked_at).not.toBeNull() + expect(row.blocked_by_principal_id).toBe(uuid(people.people.admin.principalId)) + } + ) + + test( + 'PPL-U-75 the public profile shows only what the viewer can see; misses are not found', + { tag: '@core' }, + async ({ browser, marker }) => { + const open = await seedBoard(marker) + const closed = await seedBoard(`${marker}-p`, { teamOnly: true }) + const person = await portalUser(browser, marker) + await postAs(person.api, open.id, `Public ${marker}`) + await seedLeadActivity(person.principalUuid, { + post: { boardId: closed.id, title: `Private ${marker}` }, + }) + const lead = await seedLead(marker) + + const visitor = await browser.newPage() + const res = await visitor.goto(`/u/${person.principalId}`) + expect(res?.status()).toBe(200) + await expect(visitor.getByText(person.name).first()).toBeVisible() + await expect(visitor.getByText(`Public ${marker}`)).toBeVisible() + await expect(visitor.getByText(`Private ${marker}`)).toHaveCount(0) + await expect(visitor.getByText(person.email)).toHaveCount(0) + + for (const id of [lead.principalId, generateId('principal'), 'not-an-id']) { + await visitor.goto(`/u/${id}`) + await expect(visitor.getByText('Profile not found'), id).toBeVisible() + } + await visitor.close() + } + ) +}) + test.describe('removing a person', () => { test( 'PPL-U-42 removing a portal user takes them off the portal and re-points their content', From c052a32848e4a9e84aa02ca74d4de200d0232444 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 07:25:44 +0000 Subject: [PATCH 4/5] test(e2e): people companies journeys --- apps/web/e2e/QUARANTINE.md | 18 + apps/web/e2e/product/people.ts | 5 + apps/web/e2e/tests/people/companies.spec.ts | 640 ++++++++++++++++++++ 3 files changed, 663 insertions(+) create mode 100644 apps/web/e2e/tests/people/companies.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 3dae1b8392..971b8bdb9d 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -146,3 +146,21 @@ id IN (SELECT post_id FROM post_votes WHERE principal_id = $1)`. owner: `- ${sql.param(metadataRemovals)}::text[]` or `- ARRAY[${sql.join(metadataRemovals.map((k) => sql`${k}`), sql`, `)}]::text[]` with a guard for the empty case. owner: unassigned, review by: 2026-12-03. +- `people/companies.spec.ts` › PPL-C-03 a company the admin creates is not + labelled as API-sourced. Product bug: `createCompanyFn`'s schema has no + `source` and the admin UI sends none, so `createCompany` falls back to + `source: input.source ?? 'api'` + (`apps/web/src/lib/server/domains/companies/company.service.ts:94`) and + every company made in the admin (directory "New company", a person's + Company card "Create") shows the "API" badge. Fix: have `createCompanyFn` + (`apps/web/src/lib/server/functions/companies.ts`) pass `source: 'manual'`. + owner: unassigned, review by: 2026-12-03. +- `people/companies.spec.ts` › PPL-C-31 a duplicate company attribute key is + refused and the dialog says so. Product bug: `handleCreate` awaits + `onCreate` with no catch + (`apps/web/src/components/admin/settings/scalar-attribute-list.tsx:299`) and + the mutation hook has no `onError`, so the server's 409 `DUPLICATE_KEY` + "An attribute with that key already exists" never surfaces: the dialog + just stays open. Same component backs user attributes (PPL-U-51). Fix: + catch in `handleCreate` (and the edit/delete handlers) and toast the + error message. owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/product/people.ts b/apps/web/e2e/product/people.ts index 8cb01df99e..fd5e1c6822 100644 --- a/apps/web/e2e/product/people.ts +++ b/apps/web/e2e/product/people.ts @@ -139,6 +139,11 @@ const GET_FNS = new Set([ 'getProfileTeamContextFn', 'searchPeopleFn', 'listCompaniesFn', + 'listCompaniesPageFn', + 'countCompaniesFn', + 'listCompanyMembersFn', + 'getCompanyActivityFn', + 'getCompanyForPrincipalFn', 'getCompanyFn', 'listCompanyAttributesFn', 'listUserAttributesFn', diff --git a/apps/web/e2e/tests/people/companies.spec.ts b/apps/web/e2e/tests/people/companies.spec.ts new file mode 100644 index 0000000000..eab83847d4 --- /dev/null +++ b/apps/web/e2e/tests/people/companies.spec.ts @@ -0,0 +1,640 @@ +/** + * Companies: the directory and company profile in the admin, the person's + * Company card, company attributes (/admin/settings/companies), REST and the + * permission gates. + * + * Journeys: PPL-C-01, PPL-C-02, PPL-C-03, PPL-C-04, PPL-C-07, PPL-C-08, + * PPL-C-10, PPL-C-12, PPL-C-14, PPL-C-15, PPL-C-23, PPL-C-25, PPL-C-26, + * PPL-C-29, PPL-C-30, PPL-C-31, PPL-C-36, PPL-C-37 + */ +import { randomBytes } from 'node:crypto' +import type { APIRequestContext, Page } from '@playwright/test' +import { fromUuid, generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { pollFor, supportDb } from '../../support/db' +import { createRole } from '../../support/access' +import { apiFor, createKey, expectJson } from '../../support/api-client' +import { supportEnv } from '../../support/env' +import { + call, + mustCall, + personApi, + portalUserRow, + restAdmin, + usersUrl, + uuid, +} from '../../product/people' + +interface Company { + id: string + name: string +} + +async function newCompany( + admin: APIRequestContext, + name: string, + extra: Record = {} +): Promise { + return mustCall(admin, 'createCompanyFn', { name, ...extra }) +} + +async function companyRow(id: string) { + const [row] = await supportDb()`SELECT * FROM companies WHERE id = ${uuid(id)}` + return row +} + +function companyUrl(search: string, companyId?: string): string { + const q = new URLSearchParams({ lifecycle: 'companies', search }) + if (companyId) q.set('company', companyId) + return `/admin/users?${q.toString()}` +} + +async function openCompany(page: Page, search: string, company: Company): Promise { + await page.goto(companyUrl(search, company.id)) + await expect(page.getByRole('heading', { name: company.name, exact: true })).toBeVisible({ + timeout: 15_000, + }) +} + +function hex(): string { + return randomBytes(4).toString('hex') +} + +test.describe('companies directory and profile', () => { + test( + 'PPL-C-01 the directory lists companies with domain, plan, spend and member counts', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const a = await newCompany(admin, `Alpha ${marker}`, { + domain: `alpha-${marker}.example`, + plan: 'Scale', + mrrCents: 49900, + }) + await newCompany(admin, `Bravo ${marker}`) + for (const _ of [1, 2]) { + const p = await portalUserRow(marker) + await mustCall(admin, 'attachPrincipalToCompanyFn', { + companyId: a.id, + principalId: p.principalId, + }) + } + await admin.dispose() + + const page = await asPerson('admin') + await page.goto(companyUrl(marker)) + // The count line is the directory-wide total by design + // (companies-view.tsx), so only the rows are scoped to this test. + const alpha = page.getByRole('button', { name: new RegExp(`Alpha ${marker}`) }) + await expect(alpha).toContainText(`alpha-${marker}.example`, { timeout: 15_000 }) + await expect(alpha).toContainText('Scale') + await expect(alpha).toContainText('$499') + await expect(alpha).toContainText('2') + const bravo = page.getByRole('button', { name: new RegExp(`Bravo ${marker}`) }) + await expect(bravo).toContainText('No domain') + + // The nav entry opens the directory. + await page.goto(usersUrl({ search: marker })) + await expect(async () => { + await page.getByRole('button', { name: /All companies/ }).click() + await expect(page).toHaveURL(/lifecycle=companies/, { timeout: 1_000 }) + }).toPass({ timeout: 15_000 }) + } + ) + + test( + 'PPL-C-02 creating a company from the directory opens its profile and audits it', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const page = await asPerson('admin') + await page.goto(companyUrl(marker)) + const dialog = page.getByRole('dialog') + await expect(async () => { + await page.getByRole('button', { name: 'New company' }).click() + await expect(dialog).toBeVisible({ timeout: 1_000 }) + }).toPass({ timeout: 15_000 }) + const create = dialog.getByRole('button', { name: 'Create company' }) + const nameBox = dialog.locator('#company-name') + await nameBox.fill(' ') + await expect(create).toBeDisabled() + await nameBox.fill(` Made ${marker} `) + await dialog.locator('#company-domain').fill(`made-${marker}.example`) + await create.click() + await expect(dialog).toHaveCount(0) + await expect(page.getByRole('heading', { name: `Made ${marker}`, exact: true })).toBeVisible() + + const [row] = await supportDb()`SELECT id, name, domain, custom_attributes FROM companies + WHERE name = ${`Made ${marker}`}` + expect(row.domain).toBe(`made-${marker}.example`) + expect(row.custom_attributes).toEqual({}) + const companyId = fromUuid('company', row.id as string) + const audit = await pollFor('company.created audit row', async () => { + const [r] = await supportDb()`SELECT actor_type, target_type, after_value FROM audit_log + WHERE event_type = 'company.created' AND target_id = ${companyId}` + return r ?? null + }) + expect(audit).toMatchObject({ + target_type: 'company', + after_value: { companyId, name: `Made ${marker}` }, + }) + } + ) + + test( + 'PPL-C-03 a company the admin creates is not labelled as API-sourced', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'createCompanyFn passes no source and company.service.ts defaults to api; see QUARANTINE.md', + }, + }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Manual ${marker}`) + await admin.dispose() + expect((await companyRow(company.id)).source).toBe('manual') + } + ) + + test( + 'PPL-C-04 a duplicate domain is refused whatever its case', + { tag: '@core' }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const domain = `acme-${marker}.com` + const first = await newCompany(admin, `First ${marker}`, { domain }) + const dup = await call(admin, 'createCompanyFn', { + name: `Second ${marker}`, + domain: domain.toUpperCase(), + }) + expect(dup.ok).toBe(false) + expect(dup.code).toBe('COMPANY_DOMAIN_EXISTS') + const other = await newCompany(admin, `Third ${marker}`) + const edit = await call(admin, 'updateCompanyFn', { + id: other.id, + domain: domain.toUpperCase(), + }) + expect(edit.code).toBe('COMPANY_DOMAIN_EXISTS') + const rows = await supportDb()`SELECT id FROM companies WHERE lower(domain) = ${domain}` + expect(rows.map((r) => r.id)).toEqual([uuid(first.id)]) + await admin.dispose() + } + ) + + test( + 'PPL-C-07 editing a company standard fields stores spend in cents and blanks as null', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Edit ${marker}`, { industry: 'Old industry' }) + await admin.dispose() + const page = await asPerson('admin') + await openCompany(page, marker, company) + await page.getByRole('button', { name: 'Edit', exact: true }).first().click() + await page.getByPlaceholder('acme.com', { exact: true }).fill(`edit-${marker}.example`) + await page.getByPlaceholder('crm-123').fill(`crm-${marker}`) + await page.getByPlaceholder('Scale').fill('Enterprise') + await page.getByPlaceholder('499').fill('499.5') + await page.getByPlaceholder('11-50').fill('51-200') + await page.getByPlaceholder('https://acme.com').fill('https://edit.example') + await page.getByPlaceholder('SaaS').fill('') + await page.getByRole('button', { name: 'Save', exact: true }).click() + await expect(page.getByText('Company updated')).toBeVisible() + + expect(await companyRow(company.id)).toMatchObject({ + domain: `edit-${marker}.example`, + external_id: `crm-${marker}`, + plan: 'Enterprise', + mrr_cents: 49950, + size: '51-200', + website: 'https://edit.example', + industry: null, + }) + } + ) + + test( + 'PPL-C-08 editing custom attribute values types them and blank removes the key', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const seats = `seats_${hex()}` + const flag = `flag_${hex()}` + const note = `note_${hex()}` + await mustCall(admin, 'createCompanyAttributeFn', { + key: seats, + label: `Seats ${marker}`, + type: 'number', + }) + await mustCall(admin, 'createCompanyAttributeFn', { + key: flag, + label: `Flag ${marker}`, + type: 'boolean', + }) + await mustCall(admin, 'createCompanyAttributeFn', { + key: note, + label: `Note ${marker}`, + type: 'string', + }) + const company = await newCompany(admin, `Attrs ${marker}`, { + customAttributes: { [note]: 'remove me' }, + }) + await admin.dispose() + + const page = await asPerson('admin') + await openCompany(page, marker, company) + await page.getByRole('button', { name: 'Edit', exact: true }).last().click() + const field = (label: string) => + page + .locator('div') + .filter({ has: page.getByText(label, { exact: true }) }) + .filter({ has: page.locator('input, [role="combobox"]') }) + .last() + await field(`Seats ${marker}`).locator('input').fill('12') + await field(`Flag ${marker}`).getByRole('combobox').click() + await page.getByRole('option', { name: 'True' }).click() + await field(`Note ${marker}`).locator('input').fill('') + await page.getByRole('button', { name: 'Save', exact: true }).click() + await expect(page.getByText('Attributes updated')).toBeVisible() + + const attrs = (await companyRow(company.id)).custom_attributes as Record + expect(attrs).toEqual({ [seats]: 12, [flag]: true }) + } + ) + + test( + 'PPL-C-10 deleting a company detaches its people and audits it', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Doomed ${marker}`) + const people = [await portalUserRow(marker), await portalUserRow(marker)] + for (const p of people) { + await mustCall(admin, 'attachPrincipalToCompanyFn', { + companyId: company.id, + principalId: p.principalId, + }) + } + await admin.dispose() + + const page = await asPerson('admin') + await openCompany(page, marker, company) + await page + .getByRole('button', { name: 'Edit', exact: true }) + .first() + .locator('xpath=following-sibling::button[1]') + .click() + const dialog = page.getByRole('alertdialog') + await expect(dialog.getByText(`Delete "Doomed ${marker}"?`)).toBeVisible() + await expect(dialog).toContainText( + 'Users linked to this company will be detached. This cannot be undone.' + ) + await dialog.getByRole('button', { name: 'Delete', exact: true }).click() + await expect(page.getByText('Company deleted')).toBeVisible() + await expect( + page.getByRole('heading', { name: `Doomed ${marker}`, exact: true }) + ).toHaveCount(0) + + expect(await companyRow(company.id)).toBeUndefined() + const sql = supportDb() + const rows = await sql`SELECT company_id FROM principal + WHERE id IN ${sql(people.map((p) => p.principalUuid))}` + expect(rows.map((r) => r.company_id)).toEqual([null, null]) + const audit = await pollFor('company.deleted audit row', async () => { + const [r] = await sql`SELECT after_value FROM audit_log + WHERE event_type = 'company.deleted' AND target_id = ${company.id}` + return r ?? null + }) + expect(audit.after_value).toEqual({ companyId: company.id }) + } + ) + + test( + 'PPL-C-12 PPL-C-14 adding a person to a company from its profile, then removing them', + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Roster ${marker}`) + await admin.dispose() + const person = await portalUserRow(marker, { name: `Member ${marker}` }) + + const page = await asPerson('admin') + await openCompany(page, marker, company) + await expect(page.getByText('No users linked yet')).toBeVisible() + await page.getByRole('button', { name: 'Add user' }).click() + const search = page.getByPlaceholder('Search users…') + await search.fill(`nobody-${marker}`) + await expect(page.getByText('No users found')).toBeVisible() + await search.fill(`Member ${marker}`) + await page.getByRole('button', { name: new RegExp(`Member ${marker}`) }).click() + await expect(page.getByText(person.email)).toBeVisible() + await pollFor('company link', async () => { + const [r] = await supportDb()`SELECT company_id FROM principal + WHERE id = ${person.principalUuid}` + return r?.company_id === uuid(company.id) ? true : null + }) + + await page.getByTitle('Remove from company').click() + await expect(page.getByText('No users linked yet')).toBeVisible() + const [row] = await supportDb()`SELECT company_id FROM principal + WHERE id = ${person.principalUuid}` + expect(row.company_id).toBeNull() + } + ) + + test( + "PPL-C-15 set, create and clear a person's company from their profile", + { tag: '@core' }, + async ({ asPerson, playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const existing = await newCompany(admin, `Existing ${marker}`, { + plan: 'Pro', + mrrCents: 10000, + }) + await admin.dispose() + const person = await portalUserRow(marker) + const companyOf = async () => { + const [r] = await supportDb()`SELECT company_id FROM principal + WHERE id = ${person.principalUuid}` + return r.company_id as string | null + } + + const page = await asPerson('admin') + await page.goto(usersUrl({ search: marker, selected: person.principalId })) + await expect(page.getByText('No company')).toBeVisible({ timeout: 15_000 }) + await page.getByRole('button', { name: '+ Add' }).click() + await page.getByPlaceholder('Search or create…').fill(`Existing ${marker}`) + await page.getByRole('button', { name: `Existing ${marker}`, exact: true }).click() + await expect(page.getByText('Pro · $100/mo')).toBeVisible() + await expect(page.getByRole('link', { name: 'View company →' })).toHaveAttribute( + 'href', + new RegExp(`company=${existing.id}`) + ) + await expect.poll(companyOf).toBe(uuid(existing.id)) + + const trigger = (name: string) => + page.locator('[data-slot="popover-trigger"]', { hasText: name }) + await trigger(`Existing ${marker}`).click() + await page.getByPlaceholder('Search or create…').fill(`Fresh ${marker}`) + await page.getByRole('button', { name: `Create “Fresh ${marker}”` }).click() + await expect(page.getByText('Pro · $100/mo')).toHaveCount(0) + const [fresh] = await supportDb()`SELECT id FROM companies WHERE name = ${`Fresh ${marker}`}` + await expect.poll(companyOf).toBe(fresh.id) + + await trigger(`Fresh ${marker}`).click() + await page.getByRole('button', { name: 'Remove from company' }).click() + await expect(page.getByText('No company')).toBeVisible() + await expect.poll(companyOf).toBeNull() + } + ) +}) + +test.describe('company attributes settings', () => { + test( + 'PPL-C-29 PPL-C-30 the settings page lists built-ins, then a new attribute with a normalised key', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const key = `contract_value_${hex()}` + const page = await asPerson('admin') + await page.goto('/admin/settings/companies') + for (const builtIn of ['Name', 'Email domain', 'Plan', 'Monthly spend', 'Size', 'Website']) { + await expect(page.getByText(builtIn, { exact: true }).first(), builtIn).toBeVisible({ + timeout: 15_000, + }) + } + await page.getByRole('button', { name: 'New attribute' }).click() + const dialog = page.getByRole('dialog') + await expect(dialog.getByText('New company attribute')).toBeVisible() + const create = dialog.getByRole('button', { name: 'Create attribute' }) + await expect(create).toBeDisabled() + await dialog + .getByLabel(/^Key/) + .fill(key.replace(/_/g, ' ').replace('contract value', 'Contract Value')) + await dialog.getByLabel('Display label').fill(`Contract ${marker}`) + await dialog.getByRole('combobox').first().click() + await page.getByRole('option', { name: 'Currency' }).click() + await create.click() + await expect(dialog).toHaveCount(0) + + const [row] = + await supportDb()`SELECT key, label, type, currency_code, description, external_key + FROM company_attribute_definitions WHERE key = ${key}` + expect(row).toMatchObject({ + label: `Contract ${marker}`, + type: 'currency', + currency_code: 'USD', + description: null, + external_key: null, + }) + await page.reload() + await expect(page.getByText(`Contract ${marker}`, { exact: true })).toBeVisible({ + timeout: 15_000, + }) + } + ) + + test( + 'PPL-C-31 a duplicate company attribute key is refused and the dialog says so', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'scalar-attribute-list.tsx handleCreate awaits onCreate with no catch; the DUPLICATE_KEY refusal shows nothing; see QUARANTINE.md', + }, + }, + async ({ asPerson, playwright, marker }) => { + const key = `dup_${hex()}` + const admin = await personApi(playwright, 'admin') + await mustCall(admin, 'createCompanyAttributeFn', { key, label: 'First', type: 'string' }) + const refused = await call(admin, 'createCompanyAttributeFn', { + key, + label: 'Second', + type: 'string', + }) + expect(refused.code).toBe('DUPLICATE_KEY') + await admin.dispose() + + const page = await asPerson('admin') + await page.goto('/admin/settings/companies') + await page.getByRole('button', { name: 'New attribute' }).click() + const dialog = page.getByRole('dialog') + await dialog.getByLabel(/^Key/).fill(key) + await dialog.getByLabel('Display label').fill(`Again ${marker}`) + await dialog.getByRole('button', { name: 'Create attribute' }).click() + await expect(page.getByText('An attribute with that key already exists')).toBeVisible() + } + ) +}) + +test.describe('companies over REST', () => { + test( + 'PPL-C-23 PPL-C-25 list companies with a cursor and get one', + { tag: '@core' }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const made = [ + await newCompany(admin, `C ${marker}`), + await newCompany(admin, `A ${marker}`, { plan: 'Scale', mrrCents: 100 }), + await newCompany(admin, `B ${marker}`), + ] + const p = await portalUserRow(marker) + await mustCall(admin, 'attachPrincipalToCompanyFn', { + companyId: made[1].id, + principalId: p.principalId, + }) + await admin.dispose() + + const rest = await restAdmin(playwright) + const first = await expectJson( + await rest.get(`/api/v1/companies?search=${encodeURIComponent(marker)}&limit=2`), + 200 + ) + expect(first.data.map((c: { name: string }) => c.name)).toEqual([ + `A ${marker}`, + `B ${marker}`, + ]) + expect(first.meta.pagination.hasMore).toBe(true) + const second = await expectJson( + await rest.get( + `/api/v1/companies?search=${encodeURIComponent(marker)}&limit=2&cursor=${first.meta.pagination.cursor}` + ), + 200 + ) + expect(second.data.map((c: { name: string }) => c.name)).toEqual([`C ${marker}`]) + expect(second.meta.pagination.hasMore).toBe(false) + expect(first.data[0]).toMatchObject({ + id: made[1].id, + plan: 'Scale', + mrrCents: 100, + memberCount: 1, + customAttributes: {}, + }) + + const one = await expectJson(await rest.get(`/api/v1/companies/${made[1].id}`), 200) + expect(one.data).toMatchObject({ id: made[1].id, name: `A ${marker}`, memberCount: 1 }) + const bad = await expectJson(await rest.get('/api/v1/companies/nope'), 400) + expect(bad.error).toMatchObject({ + code: 'VALIDATION_ERROR', + message: 'Invalid company ID format', + }) + const unknownId = generateId('company') + const missing = await expectJson(await rest.get(`/api/v1/companies/${unknownId}`), 404) + expect(missing.error).toMatchObject({ + code: 'NOT_FOUND', + message: `Company with ID ${unknownId} not found`, + }) + await rest.dispose() + } + ) + + test( + 'PPL-C-26 REST refuses a key without company.view, and no key at all', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const roleKey = await createRole(marker, ['people.view']) + const mate = await newTeammate({ roleKey }) + const { key } = createKey({ creatorEmail: mate.email }) + const rest = await apiFor(playwright, supportEnv().baseUrl, key) + for (const path of ['/api/v1/companies', `/api/v1/companies/${generateId('company')}`]) { + const res = await expectJson(await rest.get(path), 403) + expect(res.error).toEqual( + expect.objectContaining({ + code: 'FORBIDDEN', + message: "Requires the 'company.view' permission", + }) + ) + } + await rest.dispose() + const anon = await apiFor(playwright, supportEnv().baseUrl, null) + const res = await anon.get('/api/v1/companies') + expect(res.status()).toBe(401) + expect(res.headers()['www-authenticate']).toBe('Bearer realm="Quackback API"') + await anon.dispose() + } + ) +}) + +test.describe('company permissions', () => { + test( + 'PPL-C-36 every company write is refused without company.manage; reads still work', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Guarded ${marker}`) + const attrKey = `guard_${hex()}` + const attr = await mustCall<{ id: string }>(admin, 'createCompanyAttributeFn', { + key: attrKey, + label: 'Guard', + type: 'string', + }) + await admin.dispose() + const person = await portalUserRow(marker) + const mate = await newTeammate({ roleKey: 'contributor' }) + const api = await mate.api(playwright) + + for (const [name, data] of [ + ['createCompanyFn', { name: `Nope ${marker}` }], + ['updateCompanyFn', { id: company.id, name: `Renamed ${marker}` }], + ['deleteCompanyFn', { id: company.id }], + ['attachPrincipalToCompanyFn', { companyId: company.id, principalId: person.principalId }], + ['detachPrincipalFromCompanyFn', { principalId: person.principalId }], + ['createCompanyAttributeFn', { key: `x_${hex()}`, label: 'X', type: 'string' }], + ['updateCompanyAttributeFn', { id: attr.id, label: 'Changed' }], + ['deleteCompanyAttributeFn', { id: attr.id }], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name} must be refused`).toBe(false) + } + expect((await companyRow(company.id)).name).toBe(`Guarded ${marker}`) + const [p] = + await supportDb()`SELECT company_id FROM principal WHERE id = ${person.principalUuid}` + expect(p.company_id).toBeNull() + expect( + await supportDb()`SELECT id FROM companies WHERE name = ${`Nope ${marker}`}` + ).toHaveLength(0) + const [def] = await supportDb()`SELECT label FROM company_attribute_definitions + WHERE key = ${attrKey}` + expect(def.label).toBe('Guard') + + for (const [name, data] of [ + ['listCompaniesPageFn', { search: marker }], + ['getCompanyFn', { id: company.id }], + ['listCompanyAttributesFn', undefined], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name}: ${res.raw.slice(0, 200)}`).toBe(true) + } + await api.dispose() + } + ) + + test( + 'PPL-C-37 company reads are refused without company.view', + { tag: '@core' }, + async ({ playwright, marker, newTeammate }) => { + const admin = await personApi(playwright, 'admin') + const company = await newCompany(admin, `Hidden ${marker}`) + await admin.dispose() + const person = await portalUserRow(marker) + const roleKey = await createRole(marker, ['people.view']) + const mate = await newTeammate({ roleKey }) + const api = await mate.api(playwright) + for (const [name, data] of [ + ['listCompaniesPageFn', { search: marker }], + ['countCompaniesFn', undefined], + ['getCompanyFn', { id: company.id }], + ['getCompanyForPrincipalFn', { principalId: person.principalId }], + ['listCompanyMembersFn', { companyId: company.id }], + ['listCompanyAttributesFn', undefined], + ] as const) { + const res = await call(api, name, data) + expect(res.ok, `${name} must be refused`).toBe(false) + expect(res.raw, name).not.toContain(`Hidden ${marker}`) + } + await api.dispose() + } + ) +}) From 7d4425e413a3415126844b7295bfdcb32b58e87f Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 07:32:03 +0000 Subject: [PATCH 5/5] test(e2e): PPL-U-01 owns the test customer's teammate --- apps/web/e2e/tests/people/users.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/e2e/tests/people/users.spec.ts b/apps/web/e2e/tests/people/users.spec.ts index 310686b6ee..8af083d80e 100644 --- a/apps/web/e2e/tests/people/users.spec.ts +++ b/apps/web/e2e/tests/people/users.spec.ts @@ -305,15 +305,15 @@ test.describe('directory and profile in the admin', () => { test( 'PPL-U-01 the Users tab lists identified portal users only, with a matching count', { tag: '@core' }, - async ({ asPerson, people, marker, newTeammate }) => { + async ({ asPerson, marker, newTeammate }) => { const a = await portalUserRow(marker, { name: `Alpha ${marker}` }) const b = await portalUserRow(marker, { name: `Bravo ${marker}`, verified: false }) - await newTeammate({ roleKey: 'contributor', name: `Mate ${marker}` }) + const mate = await newTeammate({ roleKey: 'contributor', name: `Mate ${marker}` }) const lead = await seedLead(marker, { name: `Lead ${marker}` }) await supportDb()`UPDATE principal SET contact_email = ${`${marker}-l@customers.example`} WHERE id = ${lead.principalUuid}` const testCustomer = await portalUserRow(marker, { name: `Tester ${marker}` }) - await supportDb()`UPDATE principal SET test_owner_principal_id = ${uuid(people.people.admin.principalId)} + await supportDb()`UPDATE principal SET test_owner_principal_id = ${uuid(mate.principalId)} WHERE id = ${testCustomer.principalUuid}` const admin = await asPerson('admin')