From 9a4ffe2a83ce5c611c30ebb89c60db523d9af28a Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 00:39:56 +0000 Subject: [PATCH 1/7] test(e2e): feedback-admin helpers and summary and merge sweeps for the product suite --- apps/web/e2e/product/feedback-admin.ts | 176 ++++++++++++++++++ apps/web/e2e/support/sweeps.ts | 3 + .../e2e-harness/__tests__/sweeps.test.ts | 18 ++ apps/web/src/lib/server/e2e-harness/sweeps.ts | 11 ++ 4 files changed, 208 insertions(+) create mode 100644 apps/web/e2e/product/feedback-admin.ts diff --git a/apps/web/e2e/product/feedback-admin.ts b/apps/web/e2e/product/feedback-admin.ts new file mode 100644 index 0000000000..a346fb9148 --- /dev/null +++ b/apps/web/e2e/product/feedback-admin.ts @@ -0,0 +1,176 @@ +/** + * Helpers for the team-side feedback journeys (FBA-*), e2e/tests/feedback/admin-*. + * + * Seeding goes through the product's own server functions as the admin (a + * board, a post, a tag), so the rows look exactly like the ones a person + * makes; the action under test is then driven through the screen or the + * server function the journey names. Every name carries the test's marker. + * + * const api = await personApi(playwright, 'admin') + * const board = await makeBoard(api, marker) + * const post = await makePost(api, { boardId: board.id, title: `${marker} idea` }) + * const admin = await asPerson('admin') + * await openPost(admin, post.id) + * + * Area-specific helpers live in their own files next to this one + * (feedback-admin-*.ts), so the three feedback-admin PRs never edit the same + * file. + */ +import { expect, type APIRequestContext, type Browser, type Page } from '@playwright/test' +import { fromUuid, toUuid } from '@quackback/ids' +import { callServerFn } from '../support/server-fns' +import { supportDb } from '../support/db' +import { mintCustomer, portalContext, type MintedCustomer } from '../support/widget-portal' + +export interface MadeBoard { + id: string + name: string + slug: string +} + +export interface MadePost { + id: string + title: string + boardId: string + statusId: string | null +} + +export interface MadeTag { + id: string + name: string +} + +/** Throw with the server's answer when a seeding call fails. */ +function must(res: { ok: boolean; data: T; raw: string }, what: string): T { + if (!res.ok) throw new Error(`${what} failed: ${res.raw.slice(0, 400)}`) + return res.data +} + +/** A board only this test uses. `preset: 'private'` makes it team-only. */ +export async function makeBoard( + api: APIRequestContext, + marker: string, + opts: { name?: string; description?: string; preset?: 'public' | 'private' } = {} +): Promise { + const res = await callServerFn(api, 'createBoardFn', { + name: opts.name ?? `Board ${marker}`.slice(0, 100), + description: opts.description, + preset: opts.preset ?? 'public', + }) + const board = must(res, 'createBoardFn') + return { id: board.id, name: board.name, slug: board.slug } +} + +/** A post created by whoever `api` is signed in as (a teammate), via createPostFn. */ +export async function makePost( + api: APIRequestContext, + input: { + boardId: string + title: string + content?: string + statusId?: string + tagIds?: string[] + authorPrincipalId?: string + } +): Promise { + const res = await callServerFn(api, 'createPostFn', input) + const post = must(res, 'createPostFn') + return { id: post.id, title: post.title, boardId: post.boardId, statusId: post.statusId } +} + +/** A tag only this test uses. */ +export async function makeTag( + api: APIRequestContext, + name: string, + opts: { color?: string; description?: string; aiPrompt?: string; isPublic?: boolean } = {} +): Promise { + const res = await callServerFn(api, 'createPostTagFn', { + name, + color: opts.color ?? '#6b7280', + ...opts, + }) + const tag = must(res, 'createPostTagFn') + return { id: tag.id, name: tag.name } +} + +export interface PortalCustomer extends MintedCustomer { + /** Requests signed in to the portal as this customer (for callServerFn). */ + api: APIRequestContext + /** Close the customer's browser context. */ + close: () => Promise +} + +/** A fresh identified customer with a portal session. Close it when done. */ +export async function portalCustomer( + browser: Browser, + marker: string, + opts: { name?: string; email?: string } = {} +): Promise { + const customer = await mintCustomer({ + email: opts.email ?? `${marker}-${Math.random().toString(36).slice(2, 7)}@customers.example`, + name: opts.name, + }) + const context = await portalContext(browser, customer) + return { ...customer, api: context.request, close: () => context.close() } +} + +/** A post a customer submits on the portal (createPublicPostFn). */ +export async function customerPost( + customer: Pick, + input: { boardId: string; title: string; content?: string } +): Promise<{ id: string; statusId: string | null }> { + const res = await callServerFn<{ id: string; statusId: string | null }>( + customer.api, + 'createPublicPostFn', + { content: '', ...input } + ) + return must(res, 'createPublicPostFn') +} + +/** A post status's TypeID by slug (the seed has open, under_review, planned, in_progress, complete, closed). */ +export async function statusIdBySlug(slug: string): Promise { + const [row] = await supportDb()` + SELECT id FROM post_statuses WHERE slug = ${slug} AND deleted_at IS NULL LIMIT 1` + if (!row) throw new Error(`No live status with slug ${slug}`) + return fromUuid('post_status', String(row.id)) +} + +/** The raw uuid behind a TypeID, for SQL. */ +export function uuid(typeId: string): string { + return toUuid(typeId as never) +} + +/** The post's row (snake_case columns), or undefined. */ +export async function postRow(postId: string): Promise | undefined> { + const [row] = await supportDb()`SELECT * FROM posts WHERE id = ${uuid(postId)}` + return row +} + +/** + * Open the feedback inbox with these URL search params. Arrays and booleans + * are written the router's way (JSON), so `{ board: [id] }` scopes the list to + * one board: do that in every inbox test, the list is shared. + */ +export async function openInbox( + page: Page, + params: Record = {} +): Promise { + const qs = new URLSearchParams( + Object.entries(params).map(([k, v]) => [k, typeof v === 'string' ? v : JSON.stringify(v)]) + ).toString() + await page.goto(`/admin/feedback${qs ? `?${qs}` : ''}`) +} + +/** Titles of the inbox rows on screen that contain `marker`, top to bottom. */ +export async function inboxTitles(page: Page, marker: string): Promise { + const titles = await page.locator('h3').allInnerTexts() + return titles.map((t) => t.trim()).filter((t) => t.includes(marker)) +} + +/** Open a post's modal straight from its URL and wait for its title. */ +export async function openPost(page: Page, postId: string, title?: string): Promise { + await page.goto(`/admin/feedback?post=${encodeURIComponent(postId)}`) + const dialog = page.getByRole('dialog') + await expect(dialog).toBeVisible({ timeout: 15_000 }) + if (title) await expect(dialog.getByText(title).first()).toBeVisible() +} diff --git a/apps/web/e2e/support/sweeps.ts b/apps/web/e2e/support/sweeps.ts index 32eb95729e..b23bdc1883 100644 --- a/apps/web/e2e/support/sweeps.ts +++ b/apps/web/e2e/support/sweeps.ts @@ -11,6 +11,7 @@ * status-maintenance, status-notify. * email-log-retention, workflow-retention, spam-retention, anon-sweep, * segment-evaluation (every scheduled dynamic segment, once). + * summary-sweep (feedback post summaries), merge-sweep (duplicate checks). */ import { expect, type APIRequestContext } from '@playwright/test' @@ -26,6 +27,8 @@ export type SweepName = | 'status-maintenance' | 'status-notify' | 'segment-evaluation' + | 'summary-sweep' + | 'merge-sweep' export interface SweepRun { ok: true diff --git a/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts b/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts index 146bbca6c4..0d051fcd48 100644 --- a/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts +++ b/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts @@ -30,6 +30,16 @@ vi.mock('@/lib/server/domains/analytics/analytics-queue', () => ({ calls.push({ job: 'analytics-refresh' }) }), })) +vi.mock('@/lib/server/domains/summary/summary.service', () => ({ + refreshStaleSummaries: vi.fn(async () => { + calls.push({ job: 'summary-sweep' }) + }), +})) +vi.mock('@/lib/server/domains/merge-suggestions/merge-check.service', () => ({ + sweepMergeSuggestions: vi.fn(async () => { + calls.push({ job: 'merge-sweep' }) + }), +})) vi.mock('@/lib/server/email/email-log.retention', () => ({ runEmailLogRetention: vi.fn(async () => { calls.push({ job: 'email-log-retention' }) @@ -174,6 +184,14 @@ describe('runE2eSweep', () => { expect(refused).toMatchObject({ ok: false, status: 400 }) }) + it('runs the feedback summary and merge sweeps on the wall clock only', async () => { + for (const job of ['summary-sweep', 'merge-sweep']) { + expect(await runE2eSweep({ job }), job).toMatchObject({ ok: true, job }) + expect(await runE2eSweep({ job, asOf: '2030-01-01T00:00:00Z' }), job).toMatchObject({ + ok: false, + status: 400, + }) + expect(calls).toEqual([{ job: 'summary-sweep' }, { job: 'merge-sweep' }]) it('lists the sweeps it accepts and never the one-shot queues', () => { expect(E2E_SWEEP_NAMES).toContain('sla-breach-sweep') expect(E2E_SWEEP_NAMES).toContain('snooze-sweep') diff --git a/apps/web/src/lib/server/e2e-harness/sweeps.ts b/apps/web/src/lib/server/e2e-harness/sweeps.ts index 4703f3499c..4a9819114f 100644 --- a/apps/web/src/lib/server/e2e-harness/sweeps.ts +++ b/apps/web/src/lib/server/e2e-harness/sweeps.ts @@ -153,6 +153,17 @@ const SWEEPS: Record = { return { evaluated, failed } }, }, + // Feedback: refresh missing and stale post summaries (the hourly cron's pass). + 'summary-sweep': { + const { refreshStaleSummaries } = await import('@/lib/server/domains/summary/summary.service') + await refreshStaleSummaries() + return {} + // Feedback: check posts with an embedding and no recent duplicate check. + 'merge-sweep': { + const { sweepMergeSuggestions } = + await import('@/lib/server/domains/merge-suggestions/merge-check.service') + await sweepMergeSuggestions() + return {} } /** The sweeps the runner accepts, for the refusal message and the tests. */ From 1534b573672213895192029abff125f443e52494 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 00:54:37 +0000 Subject: [PATCH 2/7] test(e2e): FBA-P-01 and FBA-P-07 `@smoke`: create a post and change its status from the post modal --- apps/web/e2e/product/feedback-admin-posts.ts | 140 ++++++++++++++++++ .../tests/feedback/admin-post-actions.spec.ts | 107 +++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 apps/web/e2e/product/feedback-admin-posts.ts create mode 100644 apps/web/e2e/tests/feedback/admin-post-actions.spec.ts diff --git a/apps/web/e2e/product/feedback-admin-posts.ts b/apps/web/e2e/product/feedback-admin-posts.ts new file mode 100644 index 0000000000..11bbfb9e74 --- /dev/null +++ b/apps/web/e2e/product/feedback-admin-posts.ts @@ -0,0 +1,140 @@ +/** + * Helpers for the post-management journeys of the team's feedback inbox + * (e2e/tests/feedback/admin-post-actions, admin-post-comments, admin-votes). + * Read the rows the product promises: activity, domain events, votes, + * subscriptions, comments and bells for one post. + */ +import { expect, type Page } from '@playwright/test' +import { fromUuid } from '@quackback/ids' +import { supportDb, pollFor } from '../support/db' +import { uuid } from './feedback-admin' + +export interface ActivityRow { + type: string + metadata: Record + principal_id: string | null +} + +/** The post's activity rows, oldest first. */ +export async function activityOf(postId: string): Promise { + return supportDb()` + SELECT type, metadata, principal_id FROM post_activity + WHERE post_id = ${uuid(postId)} ORDER BY created_at ASC, id ASC` +} + +export async function activityTypesOf(postId: string): Promise { + return (await activityOf(postId)).map((a) => a.type) +} + +export interface PostEvent { + type: string + payload: Record +} + +/** Domain events whose payload names the post (oldest first). */ +export async function eventsOfPost(postId: string): Promise { + return supportDb()` + SELECT type, payload FROM events + WHERE entity_id = ${postId} OR payload::text LIKE ${'%' + postId + '%'} + ORDER BY id ASC` +} + +export async function eventTypesOfPost(postId: string): Promise { + return (await eventsOfPost(postId)).map((e) => e.type) +} + +/** Wait until the post has an event of `type`; returns all of that type. */ +export async function waitForPostEvent(postId: string, type: string): Promise { + return pollFor( + `${type} event for ${postId}`, + async () => { + const rows = (await eventsOfPost(postId)).filter((e) => e.type === type) + return rows.length > 0 ? rows : undefined + }, + { timeoutMs: 15_000 } + ) +} + +export interface VoteRow { + principal_id: string + source_type: string | null + added_by_principal_id: string | null +} + +export async function votesOf(postId: string): Promise { + return supportDb()` + SELECT principal_id, source_type, added_by_principal_id FROM post_votes + WHERE post_id = ${uuid(postId)} ORDER BY created_at` +} + +export interface SubscriptionRow { + principal_id: string + reason: string + notify_comments: boolean + notify_status_changes: boolean +} + +export async function subscriptionsOf(postId: string): Promise { + return supportDb()` + SELECT principal_id, reason, notify_comments, notify_status_changes FROM post_subscriptions + WHERE post_id = ${uuid(postId)} ORDER BY created_at` +} + +export interface CommentRow { + id: string + content: string + is_team_member: boolean + is_private: boolean + deleted_at: Date | null + status_change_from_id: string | null + status_change_to_id: string | null + parent_id: string | null +} + +export async function commentsOf(postId: string): Promise { + return supportDb()` + SELECT id, content, is_team_member, is_private, deleted_at, status_change_from_id, + status_change_to_id, parent_id + FROM post_comments WHERE post_id = ${uuid(postId)} ORDER BY created_at` +} + +/** Bells about this post, with the recipient's TypeID. */ +export async function bellsOfPost( + postId: string +): Promise<{ type: string; principalId: string }[]> { + const rows = await supportDb()<{ type: string; principal_id: string }[]>` + SELECT type, principal_id FROM in_app_notifications WHERE post_id = ${uuid(postId)}` + return rows.map((r) => ({ type: r.type, principalId: fromUuid('principal', r.principal_id) })) +} + +/** A principal TypeID as the raw uuid stored in rows. */ +export function principalUuid(principalId: string): string { + return uuid(principalId) +} + +/** The modal's sidebar row for a label (Status, Board, Owner, ETA, Tags). */ +export function sidebarRow(page: Page, label: string) { + return page + .getByRole('dialog') + .locator('div.flex.items-center.justify-between', { + has: page.getByText(label, { exact: true }), + }) + .last() +} + +/** Pick another status in the post modal's sidebar. */ +export async function pickStatus(page: Page, current: string, next: string): Promise { + await sidebarRow(page, 'Status').getByRole('button', { name: current }).click() + await popover(page).getByRole('button', { name: next, exact: true }).click() +} + +/** The open popover (base-ui renders it in a portal at the end of the body). */ +export function popover(page: Page) { + return page.locator('[data-side]').filter({ visible: true }).last() +} + +/** Open the modal's Activity tab and wait for a line. */ +export async function openActivity(page: Page, line: string | RegExp): Promise { + await page.getByRole('dialog').getByRole('button', { name: 'Activity', exact: true }).click() + await expect(page.getByRole('dialog').getByText(line).first()).toBeVisible() +} diff --git a/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts new file mode 100644 index 0000000000..5942bb30de --- /dev/null +++ b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts @@ -0,0 +1,107 @@ +/** + * The team's post modal and New post dialog: create, edit, status, owner, ETA, + * tags, board, lock, delete and restore, activity, and a Contributor's limits. + * + * Journeys: FBA-P-01 FBA-P-07 + */ +import { test, expect } from '../../support/fixtures' +import { personApi } from '../../support/server-fns' +import { supportDb, pollFor } from '../../support/db' +import { hooksApi, subscribe, unsubscribe, deliveriesOf, bodyOf } from '../../support/webhooks' +import { makeBoard, makePost, openInbox, openPost, uuid } from '../../product/feedback-admin' +import { + activityOf, + openActivity, + pickStatus, + sidebarRow, + subscriptionsOf, + votesOf, + waitForPostEvent, +} from '../../product/feedback-admin-posts' + +test( + 'FBA-P-01 a teammate creates a post from the inbox: published, authored by them, one vote and one subscription', + { tag: '@smoke' }, + async ({ playwright, baseURL, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const hooks = await hooksApi(playwright, baseURL, people, marker) + const hook = await subscribe(hooks, marker, ['post.created']) + try { + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await admin.getByRole('button', { name: 'New post' }).click() + const dialog = admin.getByRole('dialog') + const title = `${marker} dark mode please` + await dialog.getByPlaceholder("What's the feedback about?").fill(title) + await dialog + .getByRole('combobox') + .filter({ hasText: /Select board|Board/ }) + .first() + .click() + await admin.getByRole('option', { name: board.name }).click() + await dialog.getByRole('button', { name: 'Create post' }).click() + await expect(dialog).toBeHidden() + + const [row] = await pollFor('the new post', async () => { + const rows = await supportDb()`SELECT * FROM posts WHERE title = ${title}` + return rows.length ? rows : undefined + }) + const adminUuid = uuid(people.people.admin.principalId) + expect(row.principal_id).toBe(adminUuid) + expect(row.board_id).toBe(uuid(board.id)) + expect(row.moderation_state).not.toBe('pending') + expect(row.vote_count).toBe(1) + const { fromUuid } = await import('@quackback/ids') + const postId = fromUuid('post', String(row.id)) + expect((await votesOf(postId)).map((v) => v.principal_id)).toEqual([adminUuid]) + expect((await subscriptionsOf(postId)).map((s) => s.principal_id)).toEqual([adminUuid]) + + const [delivery] = await deliveriesOf(marker, 'post.created', postId) + expect(bodyOf<{ post: { id: string; title: string } }>(delivery).data.post).toMatchObject({ + id: postId, + title, + }) + // And it shows in the board's list. + await expect(admin.locator('h3', { hasText: title })).toBeVisible() + } finally { + await unsubscribe(hooks, hook) + await hooks.dispose() + } + } +) + +test( + 'FBA-P-07 changing a post status from the sidebar persists, logs from and to, and fires post.status_changed', + { tag: '@smoke' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} status me` }) + await api.dispose() + + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await pickStatus(admin, 'Open', 'Planned') + await expect(sidebarRow(admin, 'Status').getByRole('button', { name: 'Planned' })).toBeVisible() + + const [event] = await waitForPostEvent(post.id, 'post.status_changed') + expect(JSON.stringify(event.payload)).toContain('Planned') + const status = await pollFor('the stored status', async () => { + const [r] = await supportDb()` + SELECT s.slug FROM posts p JOIN post_statuses s ON s.id = p.status_id + WHERE p.id = ${uuid(post.id)}` + return r?.slug === 'planned' ? r.slug : undefined + }) + expect(status).toBe('planned') + const changed = (await activityOf(post.id)).filter((a) => a.type === 'status.changed') + expect(changed).toHaveLength(1) + expect(changed[0].metadata).toMatchObject({ fromName: 'Open', toName: 'Planned' }) + + await admin.reload() + await expect(admin.getByRole('dialog')).toBeVisible() + await expect(sidebarRow(admin, 'Status').getByRole('button', { name: 'Planned' })).toBeVisible() + await openActivity(admin, /changed status/) + } +) From e1c20dd70e91ba15edf60a3492e4888811393942 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 07:51:51 +0000 Subject: [PATCH 3/7] test(e2e): feedback inbox journeys (FBA-I) for the product suite --- apps/web/e2e/QUARANTINE.md | 23 + apps/web/e2e/product/feedback-admin-inbox.ts | 160 ++++ .../e2e/tests/feedback/admin-inbox.spec.ts | 854 ++++++++++++++++++ 3 files changed, 1037 insertions(+) create mode 100644 apps/web/e2e/product/feedback-admin-inbox.ts create mode 100644 apps/web/e2e/tests/feedback/admin-inbox.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 43bc217e5a..562805b2f6 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -750,3 +750,26 @@ no such part beyond the wrong notification). revisit) is swallowed and the invitee sees "Something went wrong". The invite is accepted all the same. Fix: use the router's `isRedirect(err)`. owner: unassigned, review by: 2026-12-03. + +### Product suite: feedback admin (inbox and posts) + +- `feedback/admin-inbox.spec.ts` › FBA-I-11 Responded lists posts with a public + team reply; a private note is not a response. Product bug: the Team response + filter (and its counts) treats a private internal note as a response, because + `teamResponseExistsSql` (`apps/web/src/lib/server/domains/posts/post.inbox.ts:43`) + matches any live comment with `is_team_member = true`. Fix: add + `AND post_comments.is_private = false` (and `moderation_state <> 'pending'`) + to that EXISTS. owner: unassigned, review by: 2026-12-03. +- `feedback/admin-inbox.spec.ts` › FBA-I-12 Has duplicates lists only posts with a + pending suggestion, and nothing when none has one. Product bug: the filter + runs in the browser (`feedback-table-view.tsx:244`) and is skipped when the + counts map is `undefined`, which `inbox-container.tsx:85` returns whenever no + loaded post has a pending suggestion, so every post is listed. Fix: filter on + the server (`hasDuplicates` in `post.inbox.ts`), or treat a missing map as + "no post has duplicates" when the filter is on. owner: unassigned, review by: +- `feedback/admin-inbox.spec.ts` › FBA-I-32 a failed list read shows Failed to + load feedback, and Try again recovers. Product bug: the error component's Try + again (`apps/web/src/routes/admin/feedback.index.tsx:71`) calls only the error + boundary's `reset`, so the failed loader is never re-run and the alert stays + until a full reload. Fix: `onClick={() => { router.invalidate(); reset() }}` + (or `useQueryErrorResetBoundary`). owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/product/feedback-admin-inbox.ts b/apps/web/e2e/product/feedback-admin-inbox.ts new file mode 100644 index 0000000000..0847512ac7 --- /dev/null +++ b/apps/web/e2e/product/feedback-admin-inbox.ts @@ -0,0 +1,160 @@ +/** + * Helpers for the feedback inbox journeys (FBA-I-*, e2e/tests/feedback/admin-inbox.spec.ts). + * The shared seeding helpers are in ./feedback-admin.ts. + */ +import { expect, type APIRequestContext, type Locator, type Page } from '@playwright/test' +import { fromUuid, generateId, toUuid } from '@quackback/ids' +import { callServerFn } from '../support/server-fns' +import { supportDb } from '../support/db' +import { uuid } from './feedback-admin' + +/** An option in the inbox's filter pane, by its accessible name `Name, count`. */ +export function filterOption(page: Page, name: string, count?: number): Locator { + return page.getByRole('option', { + name: + count === undefined ? new RegExp(`^${escapeRegExp(name)}(, \\d+)?$`) : `${name}, ${count}`, + exact: count !== undefined, + }) +} + +/** A comment on a post by whoever `api` is (a teammate), via createCommentFn. */ +export async function addComment( + api: APIRequestContext, + postId: string, + content: string, + opts: { isPrivate?: boolean } = {} +): Promise { + const res = await callServerFn<{ id: string }>(api, 'createCommentFn', { + postId, + content, + ...opts, + }) + if (!res.ok) throw new Error(`createCommentFn failed: ${res.raw.slice(0, 300)}`) + return res.data.id +} + +/** Set (or clear with null) a post's owner via setPostOwnerFn. */ +export async function setOwner( + api: APIRequestContext, + postId: string, + ownerId: string | null +): Promise { + const res = await callServerFn(api, 'setPostOwnerFn', { id: postId, ownerId }) + if (!res.ok) throw new Error(`setPostOwnerFn failed: ${res.raw.slice(0, 300)}`) +} + +/** Put tags on a post via updatePostTagsFn. */ +export async function setTags( + api: APIRequestContext, + postId: string, + tagIds: string[] +): Promise { + const res = await callServerFn(api, 'updatePostTagsFn', { id: postId, tagIds }) + if (!res.ok) throw new Error(`updatePostTagsFn failed: ${res.raw.slice(0, 300)}`) +} + +/** A pending merge suggestion between two posts (source is the likely duplicate). */ +export async function insertSuggestion( + sourcePostId: string, + targetPostId: string +): Promise { + const id = toUuid(generateId('post_merge_suggestion')) + await supportDb()` + INSERT INTO post_merge_suggestions + (id, source_post_id, target_post_id, status, vector_score, fts_score, hybrid_score, llm_confidence) + VALUES (${id}, ${uuid(sourcePostId)}, ${uuid(targetPostId)}, 'pending', 0.9, 0.5, 0.8, 0.9)` + return id +} + +/** Set a post's timestamps or counters directly (preconditions only). */ +export async function backdatePost( + postId: string, + fields: { createdDaysAgo?: number; deletedDaysAgo?: number; updatedDaysAgo?: number } +): Promise { + const sql = supportDb() + const id = uuid(postId) + if (fields.createdDaysAgo !== undefined) + await sql`UPDATE posts SET created_at = now() - make_interval(days => ${fields.createdDaysAgo}) + WHERE id = ${id}` + if (fields.deletedDaysAgo !== undefined) + await sql`UPDATE posts SET deleted_at = now() - make_interval(days => ${fields.deletedDaysAgo}) + WHERE id = ${id}` + if (fields.updatedDaysAgo !== undefined) + await sql`UPDATE posts SET updated_at = now() - make_interval(days => ${fields.updatedDaysAgo}) + WHERE id = ${id}` +} + +/** The current URL's search param, decoded the router's way (JSON when it parses). */ +export function searchParam(page: Page, key: string): unknown { + const raw = new URL(page.url()).searchParams.get(key) + if (raw === null) return undefined + try { + return JSON.parse(raw) + } catch { + return raw + } +} + +/** Wait until the inbox shows exactly these marker titles, in any order. */ +export async function expectTitlesUnordered( + page: Page, + marker: string, + titles: string[] +): Promise { + await expect + .poll(async () => { + const shown = await page.locator('h3').allInnerTexts() + return shown + .map((t) => t.trim()) + .filter((t) => t.includes(marker)) + .sort() + }) + .toEqual([...titles].sort()) +} + +/** + * One of the post modal's Manage icon buttons, found by its tooltip (the + * buttons carry no accessible name). Throws when no button has that tooltip. + */ +export async function manageButton(page: Page, tooltip: string): Promise { + const buttons = page.getByRole('dialog').getByRole('complementary').getByRole('button') + await expect(buttons.first()).toBeVisible({ timeout: 15_000 }) + for (let i = 0; i < 6; i++) { + await buttons.nth(i).hover() + const shown = await page + .getByText(tooltip, { exact: true }) + .last() + .waitFor({ state: 'visible', timeout: 1_500 }) + .then(() => true) + .catch(() => false) + if (shown) return buttons.nth(i) + } + throw new Error(`No Manage button with the tooltip "${tooltip}"`) +} + +/** A manual segment holding these principals (raw uuids). */ +export async function makeSegment( + name: string, + principalUuids: string[] +): Promise<{ id: string; name: string }> { + const sql = supportDb() + const id = toUuid(generateId('segment')) + const slug = `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${id.slice(0, 6)}` + await sql`INSERT INTO segments (id, name, type, slug) VALUES (${id}, ${name}, 'manual', ${slug})` + for (const principal of principalUuids) { + await sql`INSERT INTO user_segments (principal_id, segment_id) VALUES (${principal}, ${id})` + } + return { id: fromUuid('segment', id), name } +} + +/** A lowercase word no other post contains (letters only, so search reads it whole). */ +export function uniqueWord(): string { + const letters = 'abcdefghijklmnopqrstuvwxyz' + let word = '' + for (let i = 0; i < 10; i++) word += letters[Math.floor(Math.random() * letters.length)] + return `zq${word}` +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} diff --git a/apps/web/e2e/tests/feedback/admin-inbox.spec.ts b/apps/web/e2e/tests/feedback/admin-inbox.spec.ts new file mode 100644 index 0000000000..418ba15dda --- /dev/null +++ b/apps/web/e2e/tests/feedback/admin-inbox.spec.ts @@ -0,0 +1,854 @@ +/** + * The team's feedback inbox: list, filters, search, saved views, keyboard. + * + * Journeys: FBA-I-01 + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { callServerFn, personApi, serverFnId } from '../../support/server-fns' +import { pollFor, supportDb } from '../../support/db' +import { createRole } from '../../support/access' +import { ISOLATED } from '../../support/automation' +import { withSettings } from '../../support/isolated-settings' +import { + customerPost, + inboxTitles, + makeBoard, + makePost, + makeTag, + openInbox, + openPost, + portalCustomer, + statusIdBySlug, + uuid, +} from '../../product/feedback-admin' +import { + addComment, + backdatePost, + expectTitlesUnordered, + filterOption, + insertSuggestion, + makeSegment, + manageButton, + searchParam, + setOwner, + uniqueWord, +} from '../../product/feedback-admin-inbox' + +/** A row of the inbox list (the badge sits beside the card). */ +function rowOf(page: Page, title: string) { + return page + .locator('div.group.relative.flex', { has: page.locator('h3', { hasText: title }) }) + .first() +} + +test( + 'FBA-I-01 the inbox opens on the newest posts, 20 per page, without deleted or merged posts', + { tag: '@smoke' }, + async ({ playwright, asPerson, marker }) => { + test.setTimeout(60_000) + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const titles: string[] = [] + for (let i = 1; i <= 21; i++) { + const title = `${marker} idea ${String(i).padStart(2, '0')}` + await makePost(api, { boardId: board.id, title, content: `Details of ${title}` }) + titles.push(title) + } + // A deleted post and a post merged into another never show. + const gone = await makePost(api, { boardId: board.id, title: `${marker} deleted one` }) + const merged = await makePost(api, { boardId: board.id, title: `${marker} merged one` }) + const sql = supportDb() + const [canonical] = await sql`SELECT id FROM posts WHERE title = ${titles[0]}` + await sql`UPDATE posts SET deleted_at = now() WHERE id = ${uuid(gone.id)}` + await sql`UPDATE posts SET canonical_post_id = ${canonical.id}, merged_at = now() + WHERE id = ${uuid(merged.id)}` + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + const newestFirst = [...titles].reverse() + await expect.poll(() => inboxTitles(admin, marker)).toEqual(newestFirst.slice(0, 20)) + + // A row carries its status, author and snippet. + const row = admin.locator('div', { has: admin.locator('h3', { hasText: titles[20] }) }).last() + await expect(row.getByText('Ada Admin')).toBeVisible() + await expect(row.getByText(`Details of ${titles[20]}`)).toBeVisible() + await expect(row.getByText('Open', { exact: true })).toBeVisible() + + await admin.getByRole('button', { name: 'Load more' }).click() + await expect.poll(() => inboxTitles(admin, marker)).toEqual(newestFirst) + } +) + +test( + 'FBA-I-02 a teammate without post.view_private gets the no-access page and every inbox read refuses', + { tag: '@core' }, + async ({ playwright, browser, newTeammate, marker }) => { + const roleKey = await createRole(marker, ['member.view', 'conversation.view']) + const mate = await newTeammate({ roleKey }) + const page = await mate.newPage(browser) + const listId = serverFnId('fetchInboxPostsForAdmin') + const listReads: string[] = [] + page.on('request', (r) => { + if (r.url().includes(listId)) listReads.push(r.url()) + }) + await page.goto('/admin/feedback') + await expect(page.getByRole('heading', { name: "You don't have access" })).toBeVisible({ + timeout: 15_000, + }) + await expect(page.getByPlaceholder('Search posts…')).toHaveCount(0) + expect(listReads).toEqual([]) + + const api = await mate.api(playwright) + for (const fn of ['fetchInboxPostsForAdmin', 'fetchInboxFilterCounts']) { + const res = await callServerFn(api, fn, {}, { method: 'GET' }) + expect(res.ok, fn).toBe(false) + } + await api.dispose() + } +) + +test( + 'FBA-I-04 the status filter narrows the list, keeps the other counts and takes a hand-typed slug', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const open = await makePost(api, { boardId: board.id, title: `${marker} open one` }) + const planned = await makePost(api, { + boardId: board.id, + title: `${marker} planned one`, + statusId: await statusIdBySlug('planned'), + }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [open.title, planned.title]) + await filterOption(admin, 'Open', 1).click() + await expectTitlesUnordered(admin, marker, [open.title]) + expect(searchParam(admin, 'status')).toEqual(['open']) + // A dimension's counts ignore its own filter: Planned still says 1. + await expect(filterOption(admin, 'Planned', 1)).toBeVisible() + await expect(filterOption(admin, 'Open', 1)).toHaveAttribute('aria-selected', 'true') + + // Removing the chip clears only the status filter. + await admin.getByRole('button', { name: 'Remove Status: Open filter' }).click() + await expectTitlesUnordered(admin, marker, [open.title, planned.title]) + expect(searchParam(admin, 'board')).toEqual([board.id]) + + // A single slug typed by hand is a one-item list. + await admin.goto( + `/admin/feedback?status=planned&board=${encodeURIComponent(JSON.stringify([board.id]))}` + ) + await expectTitlesUnordered(admin, marker, [planned.title]) + } +) + +test( + 'FBA-I-05 selecting two boards lists posts from either, with a count per board', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const one = await makeBoard(api, `${marker}-one`) + const two = await makeBoard(api, `${marker}-two`) + const three = await makeBoard(api, `${marker}-three`) + const a = await makePost(api, { boardId: one.id, title: `${marker} on one` }) + const b = await makePost(api, { boardId: two.id, title: `${marker} on two` }) + const b2 = await makePost(api, { boardId: two.id, title: `${marker} also on two` }) + const c = await makePost(api, { boardId: three.id, title: `${marker} on three` }) + await api.dispose() + + const admin = await asPerson('admin') + // Board counts obey the other filters: a search for the marker scopes them to this test. + await openInbox(admin, { search: marker }) + await expect(filterOption(admin, one.name, 1)).toBeVisible({ timeout: 15_000 }) + await expect(filterOption(admin, two.name, 2)).toBeVisible() + await filterOption(admin, one.name, 1).click() + await expectTitlesUnordered(admin, marker, [a.title]) + await filterOption(admin, two.name, 2).click({ modifiers: ['ControlOrMeta'] }) + await expectTitlesUnordered(admin, marker, [a.title, b.title, b2.title]) + expect((searchParam(admin, 'board') as string[]).sort()).toEqual([one.id, two.id].sort()) + await expect(admin.locator('h3', { hasText: c.title })).toHaveCount(0) + } +) + +test( + 'FBA-I-06 two tags list posts carrying either tag, with a count per tag', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const tagA = await makeTag(api, `A ${marker}`.slice(0, 50)) + const tagB = await makeTag(api, `B ${marker}`.slice(0, 50)) + const onlyA = await makePost(api, { + boardId: board.id, + title: `${marker} only A`, + tagIds: [tagA.id], + }) + const onlyB = await makePost(api, { + boardId: board.id, + title: `${marker} only B`, + tagIds: [tagB.id], + }) + const both = await makePost(api, { + boardId: board.id, + title: `${marker} both`, + tagIds: [tagA.id, tagB.id], + }) + const none = await makePost(api, { boardId: board.id, title: `${marker} untagged` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [onlyA.title, onlyB.title, both.title, none.title]) + await expect(filterOption(admin, tagA.name, 2)).toBeVisible() + await expect(filterOption(admin, tagB.name, 2)).toBeVisible() + await filterOption(admin, tagA.name, 2).click() + await expectTitlesUnordered(admin, marker, [onlyA.title, both.title]) + await filterOption(admin, tagB.name, 2).click() + await expectTitlesUnordered(admin, marker, [onlyA.title, onlyB.title, both.title]) + expect((searchParam(admin, 'tags') as string[]).sort()).toEqual([tagA.id, tagB.id].sort()) + } +) + +test( + 'FBA-I-08 Assigned to lists a teammate’s posts, and Unassigned the posts with no owner', + { tag: '@core' }, + async ({ playwright, asPerson, people, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const owned = await makePost(api, { boardId: board.id, title: `${marker} owned by Ben` }) + const free = await makePost(api, { boardId: board.id, title: `${marker} nobody owns` }) + await setOwner(api, owned.id, people.people.agentB.principalId) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [owned.title, free.title]) + await admin.getByRole('button', { name: 'Filter', exact: true }).click() + await admin.getByRole('button', { name: 'Assigned to' }).click() + await admin.getByRole('button', { name: people.people.agentB.displayName, exact: true }).click() + await expectTitlesUnordered(admin, marker, [owned.title]) + expect(searchParam(admin, 'owner')).toBe(people.people.agentB.principalId) + + await admin.keyboard.press('Escape') + await admin.getByRole('button', { name: 'Filter', exact: true }).click() + await admin.getByRole('button', { name: 'Assigned to' }).click() + await admin.getByRole('button', { name: 'Unassigned', exact: true }).click() + await expectTitlesUnordered(admin, marker, [free.title]) + expect(searchParam(admin, 'owner')).toBe('unassigned') + + // The literal works from the URL too. + await admin.reload() + await expectTitlesUnordered(admin, marker, [free.title]) + } +) + +test( + 'FBA-I-11 Responded lists posts with a public team reply; a private note is not a response', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'post.inbox.ts:44 counts any team comment, including private internal notes (QUARANTINE.md)', + }, + }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const replied = await makePost(api, { boardId: board.id, title: `${marker} replied` }) + const noted = await makePost(api, { boardId: board.id, title: `${marker} noted privately` }) + const quiet = await makePost(api, { boardId: board.id, title: `${marker} quiet` }) + await addComment(api, replied.id, `Public reply ${marker}`) + await addComment(api, noted.id, `Internal note ${marker}`, { isPrivate: true }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [replied.title, noted.title, quiet.title]) + await filterOption(admin, 'Responded').click() + await expect.poll(() => searchParam(admin, 'responded')).toBe('responded') + // The bug: the private note puts "noted privately" under Responded. + await expectTitlesUnordered(admin, marker, [replied.title]) + await expect(filterOption(admin, 'Responded', 1)).toBeVisible() + await filterOption(admin, 'Unresponded', 2).click() + await expectTitlesUnordered(admin, marker, [noted.title, quiet.title]) + } +) + +test( + 'FBA-I-12 Has duplicates lists only posts with a pending suggestion, and nothing when none has one', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'feedback-table-view.tsx:244 filters in the browser and skips the filter when no loaded post has a suggestion (QUARANTINE.md)', + }, + }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const dupe = await makePost(api, { boardId: board.id, title: `${marker} dupe` }) + const original = await makePost(api, { boardId: board.id, title: `${marker} original` }) + const alone = await makePost(api, { boardId: board.id, title: `${marker} alone` }) + const suggestion = await insertSuggestion(dupe.id, original.id) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], hasDuplicates: true }) + await expectTitlesUnordered(admin, marker, [dupe.title, original.title]) + + // Dismissed: no post on the board has a pending suggestion, so nothing matches. + await supportDb()`UPDATE post_merge_suggestions SET status = 'dismissed', resolved_at = now() + WHERE id = ${suggestion}` + await admin.reload() + await expect(admin.getByText('No results for these filters')).toBeVisible({ timeout: 15_000 }) + await expect(admin.locator('h3', { hasText: alone.title })).toHaveCount(0) + } +) + +test( + 'FBA-I-13 a row shows how many pending duplicate suggestions name the post, on either side', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const hub = await makePost(api, { boardId: board.id, title: `${marker} hub` }) + const x = await makePost(api, { boardId: board.id, title: `${marker} x` }) + const y = await makePost(api, { boardId: board.id, title: `${marker} y` }) + const z = await makePost(api, { boardId: board.id, title: `${marker} z` }) + await insertSuggestion(x.id, hub.id) + await insertSuggestion(hub.id, y.id) + const old = await insertSuggestion(z.id, hub.id) + await supportDb()`UPDATE post_merge_suggestions SET status = 'dismissed' WHERE id = ${old}` + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expect(rowOf(admin, hub.title).getByText('2 duplicates')).toBeVisible({ timeout: 15_000 }) + await expect(rowOf(admin, x.title).getByText('1 duplicate', { exact: true })).toBeVisible() + await expect(rowOf(admin, y.title).getByText('1 duplicate', { exact: true })).toBeVisible() + await expect(rowOf(admin, z.title).getByText(/duplicate/)).toHaveCount(0) + } +) + +test( + 'FBA-I-14 Deleted posts lists posts deleted in the last 30 days only', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const live = await makePost(api, { boardId: board.id, title: `${marker} live` }) + const recent = await makePost(api, { boardId: board.id, title: `${marker} deleted lately` }) + const old = await makePost(api, { boardId: board.id, title: `${marker} deleted long ago` }) + expect((await callServerFn(api, 'deletePostFn', { id: recent.id })).ok).toBe(true) + await backdatePost(old.id, { deletedDaysAgo: 31 }) + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [live.title]) + await expect(filterOption(admin, 'Deleted posts', 1)).toBeVisible() + await filterOption(admin, 'Deleted posts', 1).click() + await expectTitlesUnordered(admin, marker, [recent.title]) + expect(searchParam(admin, 'deleted')).toBe(true) + + // The 31-day-old one cannot come back. + const res = await callServerFn(api, 'restorePostFn', { id: old.id }) + expect(res.ok).toBe(false) + expect(res.raw).toMatch(/RESTORE_EXPIRED|30 days/) + await api.dispose() + } +) + +test( + 'FBA-I-15 each sort orders the list as documented, and Newest stays out of the URL', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const old = await makePost(api, { boardId: board.id, title: `${marker} old` }) + const mid = await makePost(api, { boardId: board.id, title: `${marker} mid` }) + const fresh = await makePost(api, { boardId: board.id, title: `${marker} fresh` }) + await api.dispose() + const sql = supportDb() + await backdatePost(old.id, { createdDaysAgo: 40 }) + await backdatePost(mid.id, { createdDaysAgo: 10 }) + await sql`UPDATE posts SET vote_count = 5 WHERE id = ${uuid(old.id)}` + await sql`UPDATE posts SET vote_count = 1, comment_count = 3 WHERE id = ${uuid(mid.id)}` + await sql`UPDATE posts SET vote_count = 2 WHERE id = ${uuid(fresh.id)}` + // Priority = votes*3 + comments*2 + max(0, 30 - age): old 15, mid 29, fresh 36. + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expect.poll(() => inboxTitles(admin, marker)).toEqual([fresh.title, mid.title, old.title]) + expect(searchParam(admin, 'sort')).toBeUndefined() + for (const [label, sort, order] of [ + ['Oldest', 'oldest', [old, mid, fresh]], + ['Top votes', 'votes', [old, fresh, mid]], + ['Priority', 'priority', [fresh, mid, old]], + ] as const) { + await admin.getByRole('button', { name: /^Sort: / }).click() + await admin.getByRole('menuitemradio', { name: label }).click() + await expect.poll(() => inboxTitles(admin, marker)).toEqual(order.map((p) => p.title)) + expect(searchParam(admin, 'sort')).toBe(sort) + } + } +) + +test( + 'FBA-I-03 Feedback cannot be switched off: a stored feedback:false is repaired and the pages stay open', + { tag: ['@nightly', '@isolated'] }, + async ({ asPerson }) => { + test.skip(!ISOLATED, 'runs in product-isolated') + // The portal home is the feedback board, so settings.types.ts resolveFeatureFlags + // forces feedback on at read time; no product switch can turn it off. + const admin = await asPerson('admin') + await withSettings({ feature_flags: { feedback: false } }, async () => { + for (const path of [ + '/admin/feedback', + '/admin/settings/boards', + '/admin/settings/statuses', + '/admin/settings/tags', + '/admin/settings/moderation', + ]) { + const res = await admin.goto(path) + expect(res?.status(), path).toBeLessThan(400) + await expect(admin, path).toHaveURL(new RegExp(`${path}$`)) + } + await expect + .poll(async () => { + const [row] = await supportDb()` + SELECT value->'featureFlags'->>'feedback' AS feedback FROM kv_store + WHERE key = 'settings:workspace'` + return row?.feedback + }) + .toBe('true') + }) + } +) + +test( + 'FBA-I-07 the segment filter lists posts whose author is in the segment, with its count', + { tag: '@nightly' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const inside = await portalCustomer(browser, `${marker}-in`) + const outside = await portalCustomer(browser, `${marker}-out`) + const a = await customerPost(inside, { boardId: board.id, title: `${marker} from a member` }) + await customerPost(outside, { boardId: board.id, title: `${marker} from someone else` }) + await inside.close() + await outside.close() + await api.dispose() + const segment = await makeSegment(`Segment ${marker}`.slice(0, 60), [inside.principalUuid]) + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expect(admin.getByRole('heading', { level: 3, name: a.title })).toBeVisible({ + timeout: 15_000, + }) + const option = admin.getByRole('button', { name: `${segment.name}, 1`, exact: true }) + await expect(option).toBeVisible() + await option.click() + await expectTitlesUnordered(admin, marker, [`${marker} from a member`]) + expect(searchParam(admin, 'segments')).toEqual([segment.id]) + } +) + +test( + 'FBA-I-09 a created-date preset hides older posts and shows its label on the chip', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const fresh = await makePost(api, { boardId: board.id, title: `${marker} this week` }) + const old = await makePost(api, { boardId: board.id, title: `${marker} last month` }) + await api.dispose() + await backdatePost(old.id, { createdDaysAgo: 40 }) + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [fresh.title, old.title]) + await admin.getByRole('button', { name: 'Filter', exact: true }).click() + await admin.getByRole('button', { name: 'Created date' }).click() + await admin.getByRole('button', { name: 'Last 7 days', exact: true }).click() + await expectTitlesUnordered(admin, marker, [fresh.title]) + expect(typeof searchParam(admin, 'dateFrom')).toBe('string') + await expect( + admin.getByRole('button', { name: 'Remove Date: Last 7 days filter' }) + ).toBeVisible() + } +) + +test( + 'FBA-I-10 the comment and vote thresholds keep only posts at or above them', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + test.setTimeout(60_000) + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const none = await makePost(api, { boardId: board.id, title: `${marker} no comments` }) + const one = await makePost(api, { boardId: board.id, title: `${marker} one comment` }) + const five = await makePost(api, { boardId: board.id, title: `${marker} five comments` }) + await addComment(api, one.id, `Reply ${marker}`) + for (let i = 0; i < 5; i++) await addComment(api, five.id, `Reply ${i} ${marker}`) + // A private note does not count toward the comment count. + await addComment(api, one.id, `Note ${marker}`, { isPrivate: true }) + await api.dispose() + await supportDb()`UPDATE posts SET vote_count = 12 WHERE id = ${uuid(none.id)}` + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [none.title, one.title, five.title]) + await admin.getByRole('button', { name: 'Filter', exact: true }).click() + await admin.getByRole('button', { name: 'Comment count' }).click() + await admin.getByRole('button', { name: '5+ comments', exact: true }).click() + await expectTitlesUnordered(admin, marker, [five.title]) + expect(searchParam(admin, 'minComments')).toBe('5') + + await openInbox(admin, { board: [board.id], minComments: JSON.stringify('1') }) + await expectTitlesUnordered(admin, marker, [one.title, five.title]) + + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [none.title, one.title, five.title]) + await admin.getByRole('button', { name: 'Filter', exact: true }).click() + await admin.getByRole('button', { name: 'Vote count' }).click() + await admin.getByRole('button', { name: '10+ votes', exact: true }).click() + await expectTitlesUnordered(admin, marker, [none.title]) + } +) + +test( + 'FBA-I-16 typing the start of a word finds the post, switches to Best match, and clearing goes back', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const word = uniqueWord() + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const hit = await makePost(api, { boardId: board.id, title: `${marker} ${word} request` }) + const body = await makePost(api, { + boardId: board.id, + title: `${marker} body match`, + content: `Mentions ${word} in the details`, + }) + const miss = await makePost(api, { boardId: board.id, title: `${marker} unrelated` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expectTitlesUnordered(admin, marker, [hit.title, body.title, miss.title]) + await admin.getByPlaceholder('Search posts…').fill(word.slice(0, 7)) + await expect.poll(() => searchParam(admin, 'search')).toBe(word.slice(0, 7)) + // Title matches rank above body matches. + await expect.poll(() => inboxTitles(admin, marker)).toEqual([hit.title, body.title]) + await expect(admin.getByRole('button', { name: 'Sort: Best match' })).toBeVisible() + + await admin.getByPlaceholder('Search posts…').fill('') + await expect.poll(() => searchParam(admin, 'search')).toBeUndefined() + await expectTitlesUnordered(admin, marker, [hit.title, body.title, miss.title]) + await expect(admin.getByRole('button', { name: 'Sort: Newest' })).toBeVisible() + } +) + +test( + 'FBA-I-17 a search no post fully matches widens to posts with most of the words and says so', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const [a, b, c] = [uniqueWord(), uniqueWord(), uniqueWord()] + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} ${a} ${b}` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], search: `${a} ${b} ${c}` }) + await expect( + admin.getByText('No post has all your words. Showing posts with most of them.') + ).toBeVisible({ timeout: 15_000 }) + await expectTitlesUnordered(admin, marker, [post.title]) + + // One word never widens. + await openInbox(admin, { board: [board.id], search: c }) + await expect(admin.getByText('No results for these filters')).toBeVisible({ timeout: 15_000 }) + } +) + +test( + 'FBA-I-18 a close misspelling finds the title and says the match is by spelling', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const word = `integration${uniqueWord()}` + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} ${word}` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], search: word.replace('integration', 'integraton') }) + await expect( + admin.getByText('No exact matches. Showing posts with a similar spelling.') + ).toBeVisible({ timeout: 15_000 }) + await expectTitlesUnordered(admin, marker, [post.title]) + } +) + +test( + 'FBA-I-20 filters that match nothing show the no-results state, and Clear all filters resets them', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await makePost(api, { boardId: board.id, title: `${marker} lonely post` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], search: uniqueWord(), sort: 'oldest' }) + await expect(admin.getByText('No results for these filters')).toBeVisible({ timeout: 15_000 }) + await expect(admin.getByText('Try adjusting your search or filter criteria.')).toBeVisible() + await admin.getByRole('button', { name: 'Clear all filters' }).click() + await expect.poll(() => searchParam(admin, 'board')).toBeUndefined() + expect(searchParam(admin, 'search')).toBeUndefined() + expect(searchParam(admin, 'sort')).toBe('oldest') + await expect(admin.getByText('No results for these filters')).toHaveCount(0) + } +) + +test( + 'FBA-I-21 filters live in the URL: they survive a reload, a chip removes one, and a bad sort is dropped', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const word = uniqueWord() + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const match = await makePost(api, { + boardId: board.id, + title: `${marker} ${word} planned`, + statusId: await statusIdBySlug('planned'), + }) + const openOne = await makePost(api, { boardId: board.id, title: `${marker} ${word} open` }) + await makePost(api, { boardId: board.id, title: `${marker} other planned` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], status: ['planned'], search: word, sort: 'oldest' }) + await expectTitlesUnordered(admin, marker, [match.title]) + await admin.reload() + await expectTitlesUnordered(admin, marker, [match.title]) + await expect(admin.getByRole('button', { name: 'Sort: Oldest' })).toBeVisible() + + await admin.getByRole('button', { name: 'Remove Status: Planned filter' }).click() + await expectTitlesUnordered(admin, marker, [match.title, openOne.title]) + expect(searchParam(admin, 'board')).toEqual([board.id]) + expect(searchParam(admin, 'search')).toBe(word) + + // A leftover portal sort is dropped, not an error. + const res = await admin.goto( + `/admin/feedback?sort=trending&board=${encodeURIComponent(JSON.stringify([board.id]))}` + ) + expect(res?.status()).toBeLessThan(400) + await expect(admin.getByRole('button', { name: 'Sort: Newest' })).toBeVisible() + } +) + +test( + 'FBA-I-24 a row opens the modal with ?post=, j and k step through the rows, Escape closes it', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const first = await makePost(api, { boardId: board.id, title: `${marker} first` }) + const second = await makePost(api, { boardId: board.id, title: `${marker} second` }) + const third = await makePost(api, { boardId: board.id, title: `${marker} third` }) + await api.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expect + .poll(() => inboxTitles(admin, marker)) + .toEqual([third.title, second.title, first.title]) + await admin.getByRole('heading', { level: 3, name: second.title }).click() + await expect.poll(() => searchParam(admin, 'post')).toBe(second.id) + const dialog = admin.getByRole('dialog') + await expect(dialog.getByText('2 / 3')).toBeVisible() + const popup = admin.waitForEvent('popup') + await dialog.getByRole('button', { name: 'View', exact: true }).click() + await expect(await popup).toHaveURL(new RegExp(`/b/${board.slug}/posts/${second.id}$`)) + await (await popup).close() + await admin.bringToFront() + + await admin.keyboard.press('j') + await expect.poll(() => searchParam(admin, 'post')).toBe(first.id) + await expect(dialog.getByText('3 / 3')).toBeVisible() + await admin.keyboard.press('k') + await admin.keyboard.press('k') + await expect.poll(() => searchParam(admin, 'post')).toBe(third.id) + await expect(dialog.getByText('1 / 3')).toBeVisible() + + await admin.keyboard.press('Escape') + await expect(dialog).toHaveCount(0) + expect(searchParam(admin, 'post')).toBeUndefined() + expect(searchParam(admin, 'board')).toEqual([board.id]) + } +) + +test( + 'FBA-I-25 ?post= with a malformed id opens nothing; a deleted post offers Restore; a merged one says where it went', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const deleted = await makePost(api, { boardId: board.id, title: `${marker} deleted` }) + const canonical = await makePost(api, { boardId: board.id, title: `${marker} canonical` }) + const merged = await makePost(api, { boardId: board.id, title: `${marker} merged` }) + expect((await callServerFn(api, 'deletePostFn', { id: deleted.id })).ok).toBe(true) + await supportDb()`UPDATE posts SET canonical_post_id = ${uuid(canonical.id)}, merged_at = now() + WHERE id = ${uuid(merged.id)}` + await api.dispose() + + const admin = await asPerson('admin') + await admin.goto('/admin/feedback?post=abc') + await expect(admin.getByPlaceholder('Search posts…')).toBeVisible({ timeout: 15_000 }) + await expect(admin.getByRole('dialog').getByRole('heading')).toHaveCount(0) + + await openPost(admin, deleted.id, deleted.title) + await expect(await manageButton(admin, 'Restore post')).toBeVisible() + + await openPost(admin, merged.id, merged.title) + await expect( + admin.getByRole('dialog').getByText('This feedback has been merged into') + ).toBeVisible() + await expect(admin.getByRole('dialog').getByText(canonical.title).first()).toBeVisible() + } +) + +test( + 'FBA-I-26 a saved view stores the filters but not the search, applies by replacing the filters, and deletes', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const planned = await makePost(api, { + boardId: board.id, + title: `${marker} planned`, + statusId: await statusIdBySlug('planned'), + }) + await makePost(api, { boardId: board.id, title: `${marker} open` }) + await api.dispose() + const viewName = `View ${marker}`.slice(0, 80) + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], status: ['planned'], search: 'planned' }) + await expectTitlesUnordered(admin, marker, [planned.title]) + await admin.getByRole('button', { name: 'Views' }).click() + await admin.getByRole('menuitem', { name: 'Save current filters' }).click() + const dialog = admin.getByRole('dialog', { name: 'Save current filters as a view' }) + await dialog.getByPlaceholder('View name').fill(viewName) + await dialog.getByRole('button', { name: 'Save view' }).click() + await expect(dialog).toHaveCount(0) + + const row = await pollFor('the saved view row', async () => { + const rows = await supportDb()`SELECT filters, is_shared FROM post_views + WHERE name = ${viewName} AND deleted_at IS NULL` + return rows[0] + }) + const stored = typeof row.filters === 'string' ? JSON.parse(row.filters) : row.filters + expect(stored).not.toHaveProperty('search') + expect(stored).toMatchObject({ status: ['planned'], board: [board.id] }) + expect(row.is_shared).toBe(true) + + // Applying replaces the current filters (the owner filter goes away). + await openInbox(admin, { owner: 'unassigned', minVotes: '50' }) + await admin.getByRole('button', { name: 'Views' }).click() + await admin.getByRole('menuitem', { name: viewName }).click() + await expectTitlesUnordered(admin, marker, [planned.title]) + expect(searchParam(admin, 'owner')).toBeUndefined() + expect(searchParam(admin, 'minVotes')).toBeUndefined() + + await admin.getByRole('button', { name: 'Views' }).click() + await admin.getByRole('button', { name: `Delete view ${viewName}` }).click() + await expect + .poll( + async () => + ( + await supportDb()`SELECT 1 FROM post_views WHERE name = ${viewName} + AND deleted_at IS NULL` + ).length + ) + .toBe(0) + await admin.keyboard.press('Escape') + await admin.getByRole('button', { name: 'Views' }).click() + await expect(admin.getByRole('menuitem', { name: viewName })).toHaveCount(0) + } +) + +test( + 'FBA-I-28 slash focuses the search box and Escape blurs it', + { tag: '@nightly' }, + async ({ asPerson }) => { + const admin = await asPerson('admin') + await openInbox(admin) + const search = admin.getByPlaceholder('Search posts…') + await expect(search).toBeVisible({ timeout: 15_000 }) + // Retried until the page has hydrated and its key handler is listening. + await expect(async () => { + await admin.keyboard.press('/') + await expect(search).toBeFocused({ timeout: 1_000 }) + }).toPass({ timeout: 15_000 }) + await admin.keyboard.type('ab') + await expect(search).toHaveValue('ab') + await admin.keyboard.press('Escape') + await expect(search).not.toBeFocused() + } +) + +test( + 'FBA-I-30 the filter pane shows a Moderation row to reviewers only, linking to the queue', + { tag: '@nightly' }, + async ({ asPerson, browser, newTeammate, marker }) => { + const admin = await asPerson('admin') + await openInbox(admin) + const row = admin.getByRole('link', { name: /^Moderation\s*\d+$/ }) + await expect(row).toBeVisible({ timeout: 15_000 }) + await expect(row).toHaveAttribute('href', '/admin/feedback/moderation') + await row.click() + await expect(admin).toHaveURL(/\/admin\/feedback\/moderation/) + + const roleKey = await createRole(marker, ['post.view_private', 'status.view', 'tag.view']) + const viewer = await (await newTeammate({ roleKey })).newPage(browser) + await openInbox(viewer) + await expect(viewer.getByPlaceholder('Search posts…')).toBeVisible({ timeout: 15_000 }) + await expect(viewer.getByRole('link', { name: /^Moderation\s*\d+$/ })).toHaveCount(0) + } +) + +test( + 'FBA-I-32 a failed list read shows Failed to load feedback, and Try again recovers', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'feedback.index.tsx:62 Try again only resets the error boundary; the failed loader is not re-run, so the alert stays (QUARANTINE.md)', + }, + }, + async ({ asPerson }) => { + const admin = await asPerson('admin') + await admin.goto('/admin/roadmap') + await expect(admin.getByRole('heading', { name: /roadmap/i }).first()).toBeVisible({ + timeout: 15_000, + }) + const listUrl = `**/_serverFn/${serverFnId('fetchInboxPostsForAdmin')}**` + await admin.route(listUrl, (route) => + route.fulfill({ status: 500, contentType: 'text/plain', body: 'Inbox is down' }) + ) + await admin.getByRole('link', { name: 'Feedback', exact: true }).first().click() + await expect(admin.getByText('Failed to load feedback')).toBeVisible({ timeout: 15_000 }) + await admin.unroute(listUrl) + await admin.getByRole('button', { name: 'Try again' }).click() + await expect(admin.getByPlaceholder('Search posts…')).toBeVisible({ timeout: 15_000 }) + } +) From c8a6e4b14c61b9075d2b4274e9f547da3e75ec03 Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 07:31:03 +0000 Subject: [PATCH 4/7] test(e2e): feedback admin post actions, comments and votes (FBA-P), with six product bugs quarantined --- apps/web/e2e/QUARANTINE.md | 45 + apps/web/e2e/product/feedback-admin-posts.ts | 36 +- .../tests/feedback/admin-post-actions.spec.ts | 893 +++++++++++++++++- .../feedback/admin-post-comments.spec.ts | 386 ++++++++ .../e2e/tests/feedback/admin-votes.spec.ts | 251 +++++ 5 files changed, 1604 insertions(+), 7 deletions(-) create mode 100644 apps/web/e2e/tests/feedback/admin-post-comments.spec.ts create mode 100644 apps/web/e2e/tests/feedback/admin-votes.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 562805b2f6..1d250c2ea7 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -773,3 +773,48 @@ no such part beyond the wrong notification). boundary's `reset`, so the failed loader is never re-run and the alert stays until a full reload. Fix: `onClick={() => { router.invalidate(); reset() }}` (or `useQueryErrorResetBoundary`). owner: unassigned, review by: 2026-12-03. +- `feedback/admin-post-actions.spec.ts` › FBA-P-04 a post created over REST + without a status gets the workspace default status (`@isolated`). Product + bug: `createPost` falls back to the status slugged `open` + (`apps/web/src/lib/server/domains/posts/post.service.ts:145`), not the one + marked default, so REST, MCP and Track as feedback ignore a changed default + while the portal and admin dialog follow it. Fix: look up + `is_default = true` there (falling back to `open`). owner: unassigned, + review by: 2026-12-03. +- `feedback/admin-post-actions.spec.ts` › FBA-P-08 choosing the status a post + already has changes nothing. Product bug: `changeStatus` + (`apps/web/src/lib/server/domains/posts/post.status.ts:72`) has no + same-status guard, so re-picking the current status writes a + `status.changed` activity, fires `post.status_changed` (Open to Open) and + emails subscribers. Fix: return early when the post already has `statusId`. + owner: unassigned, review by: 2026-12-03. +- `feedback/admin-post-actions.spec.ts` › FBA-P-11 a post owner must be a + teammate. Product bug: `setPostOwnerFn` + (`apps/web/src/lib/server/functions/posts.ts:497`) accepts any principal + id, so a customer can be made owner (and gets the owner bell). Fix: load the + principal and refuse unless its role is admin or member. owner: unassigned, + review by: 2026-12-03. +- `feedback/admin-post-actions.spec.ts` › FBA-P-17 post.deleted from the post + modal names who deleted it. Product bug: `softDeletePost` builds the event + actor from principal and user ids only + (`apps/web/src/lib/server/domains/posts/post.user-actions.ts:332`), so + `dispatchPostDeleted` (`apps/web/src/lib/server/events/dispatch.ts:265`) + finds no email or name and the webhook carries no `deletedBy`. Fix: pass the + actor's email and display name into `buildEventActor`. owner: unassigned, + review by: 2026-12-03. +- `feedback/admin-post-actions.spec.ts` › FBA-P-21 deleting a canonical post + does not hide its merged duplicates. Product bug: `softDeletePost` + (`apps/web/src/lib/server/domains/posts/post.user-actions.ts:243`) only + recounts when the deleted post is itself a duplicate; the duplicates of a + deleted canonical keep `canonical_post_id`, and the inbox hides every such + post (`apps/web/src/lib/server/domains/posts/post.inbox.ts:100`). Fix: + unmerge (or re-point) the duplicates when a canonical is deleted. owner: + unassigned, review by: 2026-12-03. +- `feedback/admin-post-comments.spec.ts` › FBA-P-30 a teammate without + post.set_status cannot change status through a comment. Product bug: + `createComment` applies `statusId` for any team author + (`apps/web/src/lib/server/domains/comments/comment.service.ts:146`) and + `createCommentFn` checks no status permission, so a role without + post.set_status changes status through the comment box. Fix: require + post.set_status for `shouldChangeStatus`. owner: unassigned, review by: + 2026-12-03. diff --git a/apps/web/e2e/product/feedback-admin-posts.ts b/apps/web/e2e/product/feedback-admin-posts.ts index 11bbfb9e74..bdf80d59b5 100644 --- a/apps/web/e2e/product/feedback-admin-posts.ts +++ b/apps/web/e2e/product/feedback-admin-posts.ts @@ -116,10 +116,10 @@ export function principalUuid(principalId: string): string { export function sidebarRow(page: Page, label: string) { return page .getByRole('dialog') - .locator('div.flex.items-center.justify-between', { - has: page.getByText(label, { exact: true }), - }) - .last() + .getByRole('complementary') + .getByText(label, { exact: true }) + .locator('xpath=ancestor::div[contains(@class, "justify-between")][1]') + .first() } /** Pick another status in the post modal's sidebar. */ @@ -138,3 +138,31 @@ export async function openActivity(page: Page, line: string | RegExp): Promise { + const buttons = page + .getByRole('dialog') + .getByText('Manage', { exact: true }) + .locator('xpath=..') + .locator('button') + .filter({ visible: true }) + await expect(buttons.last()).toBeVisible() + const count = await buttons.count() + await buttons.nth(label.endsWith('post') ? count - 1 : count - 2).click() +} + +/** The post's status slug as stored. */ +export async function statusSlugOf(postId: string): Promise { + const [r] = await supportDb()` + SELECT s.slug FROM posts p LEFT JOIN post_statuses s ON s.id = p.status_id + WHERE p.id = ${uuid(postId)}` + return (r?.slug as string | null) ?? null +} diff --git a/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts index 5942bb30de..f943fcf715 100644 --- a/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts +++ b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts @@ -2,23 +2,59 @@ * The team's post modal and New post dialog: create, edit, status, owner, ETA, * tags, board, lock, delete and restore, activity, and a Contributor's limits. * - * Journeys: FBA-P-01 FBA-P-07 + * Journeys: FBA-P-01 FBA-P-02 FBA-P-04 FBA-P-05 FBA-P-07 FBA-P-08 FBA-P-09 + * FBA-P-11 FBA-P-12 FBA-P-13 FBA-P-14 FBA-P-15 FBA-P-17 FBA-P-18 FBA-P-19 + * FBA-P-20 FBA-P-21 FBA-P-35 FBA-P-36 FBA-P-37 FBA-P-41, and the lower rows + * FBA-P-03 FBA-P-06 FBA-P-10 FBA-P-24 FBA-P-31 at the server-function boundary. */ +import { fromUuid } from '@quackback/ids' import { test, expect } from '../../support/fixtures' -import { personApi } from '../../support/server-fns' +import { callServerFn, personApi } from '../../support/server-fns' import { supportDb, pollFor } from '../../support/db' import { hooksApi, subscribe, unsubscribe, deliveriesOf, bodyOf } from '../../support/webhooks' -import { makeBoard, makePost, openInbox, openPost, uuid } from '../../product/feedback-admin' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { mintCustomer } from '../../support/widget-portal' +import { createSupportApiKey } from '../../utils/db-helpers' +import { + customerPost, + makeBoard, + makePost, + makeTag, + openInbox, + openPost, + portalCustomer, + postRow, + statusIdBySlug, + uuid, +} from '../../product/feedback-admin' import { activityOf, + activityTypesOf, + bellsOfPost, + commentsOf, + eventsOfPost, openActivity, pickStatus, + popover, + pressManage, sidebarRow, + statusSlugOf, subscriptionsOf, votesOf, waitForPostEvent, } from '../../product/feedback-admin-posts' +// Well-formed ids nothing has. +const NOBODY = '01900000-0000-7000-8000-000000000000' +const UNKNOWN_POST = fromUuid('post', NOBODY) +const UNKNOWN_BOARD = fromUuid('board', NOBODY) +const UNKNOWN_STATUS = fromUuid('post_status', NOBODY) + +/** Make one status the workspace default (isolated tests only). */ +async function setDefaultStatus(statusId: string): Promise { + await supportDb()`UPDATE post_statuses SET is_default = (id = ${uuid(statusId)})` +} + test( 'FBA-P-01 a teammate creates a post from the inbox: published, authored by them, one vote and one subscription', { tag: '@smoke' }, @@ -105,3 +141,854 @@ test( await openActivity(admin, /changed status/) } ) + +test( + 'FBA-P-02 New post on behalf of a person makes them the author with the vote and subscription; without post.set_author the caller is the author', + { tag: '@core' }, + async ({ playwright, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const person = await mintCustomer({ + email: `${marker}@customers.example`, + name: `Author ${marker.slice(-12)}`, + }) + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await admin.getByRole('button', { name: 'New post' }).click() + const dialog = admin.getByRole('dialog') + const title = `${marker} on behalf` + await dialog.getByPlaceholder("What's the feedback about?").fill(title) + await dialog + .getByRole('combobox') + .filter({ hasText: /Select board|Board/ }) + .first() + .click() + await admin.getByRole('option', { name: board.name }).click() + await dialog + .getByRole('button', { name: /Ada Admin/ }) + .first() + .click() + await popover(admin).getByPlaceholder('Search members...').fill(person.name) + await popover(admin) + .getByRole('button', { name: new RegExp(person.name) }) + .first() + .click() + await dialog.getByRole('button', { name: 'Create post' }).click() + await expect(admin.getByRole('button', { name: 'Create post' })).toBeHidden() + + const [row] = await pollFor('the new post', async () => { + const rows = await supportDb()`SELECT id, principal_id FROM posts WHERE title = ${title}` + return rows.length ? rows : undefined + }) + expect(row.principal_id).toBe(person.principalUuid) + const postId = fromUuid('post', String(row.id)) + expect((await votesOf(postId)).map((v) => v.principal_id)).toEqual([person.principalUuid]) + expect((await subscriptionsOf(postId)).map((s) => s.principal_id)).toEqual([ + person.principalUuid, + ]) + + // The Contributor preset has no post.set_author: the chosen author is ignored. + const contributor = await personApi(playwright, 'contributor') + const res = await callServerFn<{ id: string }>(contributor, 'createPostFn', { + boardId: board.id, + title: `${marker} by contributor`, + authorPrincipalId: fromUuid('principal', person.principalUuid), + }) + await contributor.dispose() + expect(res.ok, res.raw).toBe(true) + expect((await postRow(res.data.id))?.principal_id).toBe( + uuid(people.people.contributor.principalId) + ) + } +) + +test( + 'FBA-P-04 a post created over REST without a status gets the workspace default status', + { + tag: ['@nightly', '@isolated', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-04: post.service.ts createPost falls back to the status slugged "open", not the default status', + }, + }, + async ({ playwright, people, baseURL, marker }) => { + test.skip(!ISOLATED, ISOLATED_SKIP) + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const planned = await statusIdBySlug('planned') + const open = await statusIdBySlug('open') + const key = createSupportApiKey(people.people.admin.email, 'personal') + const rest = await playwright.request.newContext({ + baseURL, + extraHTTPHeaders: { authorization: `Bearer ${key}` }, + }) + try { + // Seeded in SQL: updateStatusFn with only isDefault answers 500 ("No values + // to set", status.service.ts updateStatus) after it has moved the default. + await setDefaultStatus(planned) + const res = await rest.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} via rest` }, + }) + expect(res.status(), await res.text()).toBe(201) + const body = (await res.json()) as { data: { id: string } } + expect(await statusSlugOf(body.data.id)).toBe('planned') + } finally { + await setDefaultStatus(open) + await rest.dispose() + await api.dispose() + } + } +) + +test( + 'FBA-P-05 editing the title in the modal saves it, closes the modal and fires post.updated with the changed field', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} old title` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + const dialog = admin.getByRole('dialog') + const save = dialog.getByRole('button', { name: 'Save changes' }) + await expect(save).toBeDisabled() + const newTitle = `${marker} new title` + await dialog.getByPlaceholder("What's the feedback about?").fill(newTitle) + await save.click() + await expect(admin.getByText('Post updated')).toBeVisible() + await expect(dialog).toBeHidden() + expect((await postRow(post.id))?.title).toBe(newTitle) + await expect(admin.locator('h3', { hasText: newTitle })).toBeVisible() + const [event] = await waitForPostEvent(post.id, 'post.updated') + expect(JSON.stringify(event.payload)).toContain('"title"') + // A title edit writes no activity row (only the creation's). + expect( + (await activityTypesOf(post.id)).filter((t) => t !== 'post.created' && t !== 'vote.cast') + ).toEqual([]) + } +) + +test( + 'FBA-P-08 choosing the status a post already has changes nothing', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-08: post.status.ts changeStatus has no same-status guard; re-picking the status re-sends the whole fan-out', + }, + }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} same status` }) + const same = await callServerFn(api, 'changePostStatusFn', { + id: post.id, + statusId: await statusIdBySlug('open'), + }) + expect(same.ok, same.raw).toBe(true) + // A real change afterwards is the barrier: once its event is in, any + // event from the first call would be too. + await callServerFn(api, 'changePostStatusFn', { + id: post.id, + statusId: await statusIdBySlug('planned'), + }) + await api.dispose() + await waitForPostEvent(post.id, 'post.status_changed') + const events = (await eventsOfPost(post.id)).filter((e) => e.type === 'post.status_changed') + expect(events).toHaveLength(1) + expect((await activityOf(post.id)).filter((a) => a.type === 'status.changed')).toHaveLength(1) + } +) + +test( + 'FBA-P-09 entering a complete status announces the ship moment once; moving between complete statuses does not', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} ship it` }) + await api.dispose() + const admin = await asPerson('admin') + await admin.addInitScript(() => { + ;(window as unknown as { __ships: number }).__ships = 0 + window.addEventListener('quackback:ship-moment', () => { + ;(window as unknown as { __ships: number }).__ships++ + }) + }) + await openPost(admin, post.id, post.title) + const ships = () => admin.evaluate(() => (window as unknown as { __ships: number }).__ships) + await pickStatus(admin, 'Open', 'Complete') + await expect.poll(ships).toBe(1) + await expect( + sidebarRow(admin, 'Status').getByRole('button', { name: 'Complete' }) + ).toBeVisible() + await pickStatus(admin, 'Complete', 'Closed') + await expect.poll(() => statusSlugOf(post.id)).toBe('closed') + expect(await ships()).toBe(1) + } +) + +test( + 'FBA-P-11 assigning an owner logs it, bells the new owner and fires post.owner_assigned; clearing logs the removal', + { tag: '@core' }, + async ({ playwright, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} own me` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await sidebarRow(admin, 'Owner').getByRole('button', { name: 'Unassigned' }).click() + await popover(admin) + .getByRole('button', { name: /Ben Agent/ }) + .click() + await expect(admin.getByText('Owner assigned')).toBeVisible() + const agentB = people.people.agentB.principalId + expect((await postRow(post.id))?.owner_principal_id).toBe(uuid(agentB)) + const [event] = await waitForPostEvent(post.id, 'post.owner_assigned') + expect(JSON.stringify(event.payload)).toContain(agentB) + await pollFor('the owner bell', async () => + (await bellsOfPost(post.id)).find( + (b) => b.type === 'post_owner_assigned' && b.principalId === agentB + ) + ) + // The assigner gets no bell. + expect( + (await bellsOfPost(post.id)).filter((b) => b.principalId === people.people.admin.principalId) + ).toEqual([]) + + await sidebarRow(admin, 'Owner') + .getByRole('button', { name: /Ben Agent/ }) + .click() + await popover(admin).getByRole('button', { name: 'Unassigned' }).click() + await expect(admin.getByText('Owner unassigned')).toBeVisible() + expect((await postRow(post.id))?.owner_principal_id).toBeNull() + await expect.poll(() => activityTypesOf(post.id)).toContain('owner.unassigned') + expect(await activityTypesOf(post.id)).toContain('owner.assigned') + await openActivity(admin, /assigned Ben Agent/) + await expect(admin.getByRole('dialog').getByText(/removed assignee/)).toBeVisible() + } +) + +test( + 'FBA-P-11 a post owner must be a teammate', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-11: setPostOwnerFn (functions/posts.ts) accepts any principal id; a customer can be made owner', + }, + }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} customer owner` }) + const customer = await mintCustomer({ email: `${marker}@customers.example` }) + const res = await callServerFn(api, 'setPostOwnerFn', { + id: post.id, + ownerId: customer.principalId, + }) + await api.dispose() + expect(res.ok).toBe(false) + expect((await postRow(post.id))?.owner_principal_id).toBeNull() + } +) + +test( + 'FBA-P-12 a month ETA is stored as the first of that UTC month and can be cleared, without activity', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} when` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await sidebarRow(admin, 'ETA').getByRole('button', { name: 'Set ETA' }).click() + await popover(admin).getByLabel('ETA').fill('2027-03') + await expect(admin.getByText('ETA updated')).toBeVisible() + await expect + .poll(async () => ((await postRow(post.id))?.eta as Date | null)?.toISOString()) + .toBe('2027-03-01T00:00:00.000Z') + await sidebarRow(admin, 'ETA').getByRole('button').click() + await popover(admin).getByRole('button', { name: 'Clear ETA' }).click() + await expect(admin.getByText('ETA cleared')).toBeVisible() + await expect.poll(async () => (await postRow(post.id))?.eta ?? null).toBeNull() + expect((await activityTypesOf(post.id)).filter((t) => t.includes('eta'))).toEqual([]) + } +) + +test( + 'FBA-P-13 adding and removing tags logs the names; resubmitting the same set logs nothing', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const red = await makeTag(api, `${marker}-red`) + const blue = await makeTag(api, `${marker}-blue`) + const post = await makePost(api, { boardId: board.id, title: `${marker} tag me` }) + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + for (const tag of [red, blue]) { + await sidebarRow(admin, 'Tags').getByRole('button', { name: 'Add', exact: true }).click() + await popover(admin).getByRole('button', { name: tag.name }).click() + await expect(sidebarRow(admin, 'Tags').getByRole('button', { name: tag.name })).toBeVisible() + } + // Clicking a chip removes the tag. + await sidebarRow(admin, 'Tags').getByRole('button', { name: red.name }).click() + await expect(sidebarRow(admin, 'Tags').getByRole('button', { name: red.name })).toBeHidden() + const tagRows = async () => + (await activityOf(post.id)).filter((a) => a.type.startsWith('tags.')) + await expect.poll(async () => (await tagRows()).length).toBe(3) + const rows = await tagRows() + expect(rows.map((r) => [r.type, r.metadata.tagNames])).toEqual([ + ['tags.added', [red.name]], + ['tags.added', [blue.name]], + ['tags.removed', [red.name]], + ]) + const same = await callServerFn(api, 'updatePostTagsFn', { id: post.id, tagIds: [blue.id] }) + expect(same.ok, same.raw).toBe(true) + expect(await tagRows()).toHaveLength(3) + const [assigned] = await supportDb()` + SELECT count(*)::int AS n FROM post_tag_assignments WHERE post_id = ${uuid(post.id)}` + expect(assigned.n).toBe(1) + await api.dispose() + } +) + +test( + 'FBA-P-14 moving a post to another board keeps its votes and logs from and to', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const from = await makeBoard(api, `${marker}-a`) + const to = await makeBoard(api, `${marker}-b`) + const post = await makePost(api, { boardId: from.id, title: `${marker} move me` }) + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await sidebarRow(admin, 'Board').getByRole('button', { name: from.name }).click() + await popover(admin).getByRole('button', { name: to.name }).click() + await expect(admin.getByText('Board updated')).toBeVisible() + expect((await postRow(post.id))?.board_id).toBe(uuid(to.id)) + expect(await votesOf(post.id)).toHaveLength(1) + const moved = await pollFor('post.board_changed', async () => + (await activityOf(post.id)).find((a) => a.type === 'post.board_changed') + ) + expect(moved.metadata).toMatchObject({ fromBoardName: from.name, toBoardName: to.name }) + await openActivity(admin, /moved to a different board/) + + // The same board again is a no-op; a read-only board refuses the move. + await callServerFn(api, 'changePostBoardFn', { id: post.id, boardId: to.id }) + expect((await activityOf(post.id)).filter((a) => a.type === 'post.board_changed')).toHaveLength( + 1 + ) + await callServerFn(api, 'updateBoardFn', { id: from.id, readOnly: true }) + const refused = await callServerFn(api, 'changePostBoardFn', { id: post.id, boardId: from.id }) + expect(refused.code).toBe('BOARD_READ_ONLY') + await api.dispose() + } +) + +test( + 'FBA-P-15 locking comments stops customers but not the team; unlocking lets customers back in', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} lock me` }) + const customer = await portalCustomer(browser, marker) + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await pressManage(admin, 'Lock comments') + await expect.poll(async () => (await postRow(post.id))?.is_comments_locked).toBe(true) + const refused = await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} let me in`, + }) + expect(refused.ok).toBe(false) + expect(refused.error).toContain('Comments are locked on this post') + const team = await callServerFn(api, 'createCommentFn', { + postId: post.id, + content: `${marker} team still talks`, + }) + expect(team.ok, team.raw).toBe(true) + + await pressManage(admin, 'Unlock comments') + await expect.poll(async () => (await postRow(post.id))?.is_comments_locked).toBe(false) + const allowed = await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} thanks`, + }) + expect(allowed.ok, allowed.raw).toBe(true) + const types = await activityTypesOf(post.id) + expect(types).toContain('comments.locked') + expect(types).toContain('comments.unlocked') + await customer.close() + await api.dispose() + } +) + +test( + 'FBA-P-17 deleting a post soft-deletes it, logs it, fires post.deleted and takes it off the list', + { tag: '@core' }, + async ({ playwright, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} delete me` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await pressManage(admin, 'Delete post') + const confirm = admin.getByRole('alertdialog') + await confirm + .getByRole('button', { name: /Delete/ }) + .last() + .click() + await expect(admin.getByText('Post deleted')).toBeVisible() + const row = await postRow(post.id) + expect(row?.deleted_at).not.toBeNull() + expect(row?.deleted_by_principal_id).toBe(uuid(people.people.admin.principalId)) + await waitForPostEvent(post.id, 'post.deleted') + await expect.poll(() => activityTypesOf(post.id)).toContain('post.deleted') + await openInbox(admin, { board: [board.id] }) + await expect(admin.getByRole('button', { name: 'New post' })).toBeVisible() + await expect(admin.locator('h3', { hasText: post.title })).toHaveCount(0) + await openInbox(admin, { board: [board.id], deleted: true }) + await expect(admin.locator('h3', { hasText: post.title })).toBeVisible() + } +) + +test( + 'FBA-P-17 post.deleted from the post modal names who deleted it', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-17: post.user-actions.ts builds the event actor from principalId and userId only, so dispatchPostDeleted has no email or name for deletedBy', + }, + }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} who deleted` }) + expect((await callServerFn(api, 'deletePostFn', { id: post.id })).ok).toBe(true) + await api.dispose() + const [event] = await waitForPostEvent(post.id, 'post.deleted') + expect(event.payload).toMatchObject({ deletedBy: 'e2e-support-admin@example.com' }) + } +) + +test( + 'FBA-P-18 deleting twice, an unknown post, or as a Contributor is refused', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} twice` }) + const contributor = await personApi(playwright, 'contributor') + const denied = await callServerFn(contributor, 'deletePostFn', { id: post.id }) + await contributor.dispose() + expect(denied.ok).toBe(false) + expect((await postRow(post.id))?.deleted_at).toBeNull() + expect((await callServerFn(api, 'deletePostFn', { id: post.id })).ok).toBe(true) + const again = await callServerFn(api, 'deletePostFn', { id: post.id }) + expect(again.code).toBe('DELETE_NOT_ALLOWED') + const unknown = await callServerFn(api, 'deletePostFn', { id: UNKNOWN_POST }) + expect(unknown.code).toBe('POST_NOT_FOUND') + await api.dispose() + } +) + +test( + 'FBA-P-19 restoring from the Deleted posts view brings the post back with its votes and logs it', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} bring back` }) + expect((await callServerFn(api, 'deletePostFn', { id: post.id })).ok).toBe(true) + await api.dispose() + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id], deleted: true }) + await admin.locator('h3', { hasText: post.title }).click() + await pressManage(admin, 'Restore post') + await expect(admin.getByText('Post restored')).toBeVisible() + expect((await postRow(post.id))?.deleted_at).toBeNull() + expect(await votesOf(post.id)).toHaveLength(1) + await waitForPostEvent(post.id, 'post.restored') + expect(await activityTypesOf(post.id)).toContain('post.restored') + await openInbox(admin, { board: [board.id] }) + await expect(admin.locator('h3', { hasText: post.title })).toBeVisible() + } +) + +test( + 'FBA-P-20 restoring a live post or one deleted over 30 days ago is refused', + { tag: '@core' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} too late` }) + const live = await callServerFn(api, 'restorePostFn', { id: post.id }) + expect(live.ok).toBe(false) + expect(live.error).toContain('Post is not deleted') + await callServerFn(api, 'deletePostFn', { id: post.id }) + await supportDb()`UPDATE posts SET deleted_at = now() - interval '31 days' + WHERE id = ${uuid(post.id)}` + const late = await callServerFn(api, 'restorePostFn', { id: post.id }) + expect(late.code).toBe('RESTORE_EXPIRED') + expect((await postRow(post.id))?.deleted_at).not.toBeNull() + await api.dispose() + } +) + +test( + 'FBA-P-21 deleting a canonical post does not hide its merged duplicates', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-21: post.user-actions.ts softDeletePost never releases the duplicates of a deleted canonical; the inbox hides every post with canonical_post_id', + }, + }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const canonical = await makePost(api, { boardId: board.id, title: `${marker} canonical` }) + const duplicate = await makePost(api, { boardId: board.id, title: `${marker} duplicate` }) + const merged = await callServerFn(api, 'mergePostFn', { + duplicatePostId: duplicate.id, + canonicalPostId: canonical.id, + }) + expect(merged.ok, merged.raw).toBe(true) + expect((await callServerFn(api, 'deletePostFn', { id: canonical.id })).ok).toBe(true) + await api.dispose() + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await expect(admin.locator('h3', { hasText: duplicate.title })).toBeVisible() + } +) + +test( + 'FBA-P-35 the Activity tab lists what the team did, newest first', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const other = await makeBoard(api, `${marker}-to`) + const tag = await makeTag(api, `${marker}-t`) + const post = await makePost(api, { boardId: board.id, title: `${marker} history` }) + const steps: [string, unknown][] = [ + ['changePostStatusFn', { id: post.id, statusId: await statusIdBySlug('planned') }], + ['updatePostTagsFn', { id: post.id, tagIds: [tag.id] }], + ['changePostBoardFn', { id: post.id, boardId: other.id }], + ['toggleCommentsLockFn', { id: post.id, locked: true }], + ] + const before = (await activityOf(post.id)).length + for (const [i, [fn, data]] of steps.entries()) { + const res = await callServerFn(api, fn, data) + expect(res.ok, `${fn}: ${res.raw}`).toBe(true) + // Activity is written after the response; wait so the order is strict. + await expect.poll(async () => (await activityOf(post.id)).length).toBe(before + i + 1) + } + await api.dispose() + + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await openActivity(admin, /locked comments/) + const lines = admin + .getByRole('dialog') + .getByText( + /(created this post|changed status|added tags|moved to a different board|locked comments)$/ + ) + await expect(lines).toHaveText([ + /locked comments/, + /moved to a different board/, + /added tags/, + /changed status/, + /created this post/, + ]) + } +) + +test( + 'FBA-P-36 the retry-sync control answers that there is no sync work for a post with no links', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} sync` }) + const res = await callServerFn<{ queued?: number }>(api, 'retryPostIntegrationSyncFn', { + id: post.id, + }) + expect(res.ok, res.raw).toBe(true) + const unknown = await callServerFn(api, 'retryPostIntegrationSyncFn', { id: UNKNOWN_POST }) + expect(unknown.code).toBe('POST_NOT_FOUND') + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + const buttons = admin + .getByRole('dialog') + .getByText('Manage', { exact: true }) + .locator('xpath=..') + .locator('button') + .filter({ visible: true }) + await buttons.first().hover() + await expect(admin.getByText('Sync integrations').filter({ visible: true })).toBeVisible() + await buttons.first().click() + await expect(admin.getByText('No new sync work to queue')).toBeVisible() + } +) + +test( + 'FBA-P-37 a Contributor can change status and tags but is refused edit, delete, ETA and lock', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const tag = await makeTag(api, `${marker}-c`) + const post = await makePost(api, { boardId: board.id, title: `${marker} contributor` }) + await api.dispose() + + const page = await asPerson('contributor') + await openPost(page, post.id, post.title) + await pickStatus(page, 'Open', 'Planned') + await expect.poll(() => statusSlugOf(post.id)).toBe('planned') + + const contributor = await personApi(playwright, 'contributor') + const tags = await callServerFn(contributor, 'updatePostTagsFn', { + id: post.id, + tagIds: [tag.id], + }) + expect(tags.ok, tags.raw).toBe(true) + for (const [fn, data] of [ + ['updatePostFn', { id: post.id, title: `${marker} renamed` }], + ['deletePostFn', { id: post.id }], + ['setPostEtaFn', { id: post.id, eta: '2027-01-01T00:00:00.000Z' }], + ['toggleCommentsLockFn', { id: post.id, locked: true }], + ] as const) { + const res = await callServerFn(contributor, fn, data) + expect(res.ok, fn).toBe(false) + } + await contributor.dispose() + const row = await postRow(post.id) + expect(row).toMatchObject({ + title: post.title, + deleted_at: null, + eta: null, + is_comments_locked: false, + }) + + // The title field is still offered; saving it ends in the permission error. + await page.getByRole('dialog').getByPlaceholder("What's the feedback about?").fill('x') + await page.getByRole('dialog').getByRole('button', { name: 'Save changes' }).click() + await expect(page.getByRole('dialog')).toBeVisible() + expect((await postRow(post.id))?.title).toBe(post.title) + } +) + +test( + 'FBA-P-41 the post modal shows the post it was opened for', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const tag = await makeTag(api, `${marker}-d`) + await api.dispose() + const customer = await portalCustomer(browser, marker, { name: `Det ${marker.slice(-12)}` }) + const post = await customerPost(customer, { + boardId: board.id, + title: `${marker} the details`, + content: `${marker} body text`, + }) + // A second post on the same board must not bleed into the modal. + await customerPost(customer, { boardId: board.id, title: `${marker} another one` }) + for (const n of ['one', 'two']) { + await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} comment ${n}`, + }) + } + await customer.close() + const adminApi = await personApi(playwright, 'admin') + await callServerFn(adminApi, 'updatePostTagsFn', { id: post.id, tagIds: [tag.id] }) + await adminApi.dispose() + + const admin = await asPerson('admin') + await openInbox(admin, { board: [board.id] }) + await admin.locator('h3', { hasText: post.title }).click() + const dialog = admin.getByRole('dialog') + await expect(dialog.getByPlaceholder("What's the feedback about?")).toHaveValue(post.title) + await expect(dialog.getByText(`${marker} body text`)).toBeVisible() + await expect(sidebarRow(admin, 'Author')).toContainText(customer.name) + await expect(sidebarRow(admin, 'Board')).toContainText(board.name) + await expect(sidebarRow(admin, 'Status')).toContainText('Open') + await expect(sidebarRow(admin, 'Tags')).toContainText(tag.name) + await expect(dialog.getByText('2 comments', { exact: false })).toBeVisible() + const [view] = await Promise.all([ + admin.waitForEvent('popup'), + dialog.getByRole('button', { name: 'View' }).click(), + ]) + expect(view.url()).toMatch(new RegExp(`/b/${board.slug}/posts/${post.id}$`)) + await view.close() + await expect(dialog.getByText(`${marker} another one`)).toHaveCount(0) + } +) + +// Lower rows, proved at the server-function boundary (the named unit files +// mock the database and do not cover these refusals end to end). + +test( + 'FBA-P-03 New post refusals: empty or long title, long body, unknown board or status, read-only board', + { tag: '@core' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const create = (data: Record) => + callServerFn(api, 'createPostFn', { boardId: board.id, title: `${marker} ok`, ...data }) + expect((await create({ title: '' })).ok).toBe(false) + expect((await create({ title: 'x'.repeat(201) })).ok).toBe(false) + expect((await create({ content: 'x'.repeat(10_001) })).ok).toBe(false) + expect((await create({ boardId: UNKNOWN_BOARD })).code).toBe('BOARD_NOT_FOUND') + expect((await create({ statusId: UNKNOWN_STATUS })).code).toBe('STATUS_NOT_FOUND') + await callServerFn(api, 'updateBoardFn', { id: board.id, readOnly: true }) + const closed = await create({}) + expect(closed.code).toBe('BOARD_READ_ONLY') + expect(closed.error).toContain("This board isn't taking new feedback right now.") + const [n] = + await supportDb()`SELECT count(*)::int AS n FROM posts WHERE board_id = ${uuid(board.id)}` + expect(n.n).toBe(0) + await api.dispose() + } +) + +test( + 'FBA-P-06 edit refusals: an empty title toasts in the modal; blank, long title and long body are refused', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} keep title` }) + for (const data of [ + { title: '' }, + { title: ' ' }, + { title: 'x'.repeat(201) }, + { content: 'x'.repeat(10_001) }, + ]) { + const res = await callServerFn(api, 'updatePostFn', { id: post.id, ...data }) + expect(res.ok, JSON.stringify(data).slice(0, 40)).toBe(false) + } + await api.dispose() + expect((await postRow(post.id))?.title).toBe(post.title) + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await admin.getByRole('dialog').getByPlaceholder("What's the feedback about?").fill('') + await admin.getByRole('dialog').getByRole('button', { name: 'Save changes' }).click() + await expect(admin.getByText('Title is required')).toBeVisible() + } +) + +test( + 'FBA-P-10 status change refusals: unknown status or post; a deleted post can still be re-statused', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} statuses` }) + const planned = await statusIdBySlug('planned') + expect( + (await callServerFn(api, 'changePostStatusFn', { id: post.id, statusId: UNKNOWN_STATUS })) + .code + ).toBe('STATUS_NOT_FOUND') + expect( + (await callServerFn(api, 'changePostStatusFn', { id: UNKNOWN_POST, statusId: planned })).code + ).toBe('POST_NOT_FOUND') + await callServerFn(api, 'deletePostFn', { id: post.id }) + const deleted = await callServerFn(api, 'changePostStatusFn', { + id: post.id, + statusId: planned, + }) + expect(deleted.ok, deleted.raw).toBe(true) + expect(await statusSlugOf(post.id)).toBe('planned') + await api.dispose() + } +) + +test( + 'FBA-P-24 proxy vote refusals: read-only board, unknown or deleted post; a duplicate votes on its canonical', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const canonical = await makePost(api, { boardId: board.id, title: `${marker} canon` }) + const duplicate = await makePost(api, { boardId: board.id, title: `${marker} dup` }) + const gone = await makePost(api, { boardId: board.id, title: `${marker} gone` }) + await callServerFn(api, 'mergePostFn', { + duplicatePostId: duplicate.id, + canonicalPostId: canonical.id, + }) + await callServerFn(api, 'deletePostFn', { id: gone.id }) + const voter = await mintCustomer({ email: `${marker}@customers.example` }) + const vote = (postId: string) => + callServerFn(api, 'proxyVoteFn', { postId, voterPrincipalId: voter.principalId }) + + expect((await vote(UNKNOWN_POST)).code).toBe('POST_NOT_FOUND') + expect((await vote(gone.id)).code).toBe('POST_NOT_FOUND') + const onDup = await vote(duplicate.id) + expect(onDup.ok, onDup.raw).toBe(true) + expect((await votesOf(canonical.id)).map((v) => v.principal_id)).toContain(voter.principalUuid) + expect((await votesOf(duplicate.id)).map((v) => v.principal_id)).not.toContain( + voter.principalUuid + ) + + const closedBoard = await makeBoard(api, `${marker}-ro`) + const closedPost = await makePost(api, { boardId: closedBoard.id, title: `${marker} ro` }) + await callServerFn(api, 'updateBoardFn', { id: closedBoard.id, readOnly: true }) + expect((await vote(closedPost.id)).code).toBe('BOARD_READ_ONLY') + expect(await votesOf(closedPost.id)).toHaveLength(1) + await api.dispose() + } +) + +test( + 'FBA-P-31 comment refusals: a parent from another post, a read-only board, a deleted board', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const a = await makePost(api, { boardId: board.id, title: `${marker} a` }) + const b = await makePost(api, { boardId: board.id, title: `${marker} b` }) + await callServerFn(api, 'createCommentFn', { postId: a.id, content: `${marker} on a` }) + const [parent] = await commentsOf(a.id) + const mismatch = await callServerFn(api, 'createCommentFn', { + postId: b.id, + content: `${marker} wrong parent`, + parentId: fromUuid('post_comment', parent.id), + }) + expect(mismatch.code).toBe('VALIDATION_ERROR') + expect(mismatch.error).toContain('Parent comment belongs to a different post') + + await callServerFn(api, 'updateBoardFn', { id: board.id, readOnly: true }) + expect( + (await callServerFn(api, 'createCommentFn', { postId: a.id, content: `${marker} ro` })).code + ).toBe('BOARD_READ_ONLY') + + const doomed = await makeBoard(api, `${marker}-del`) + const onDoomed = await makePost(api, { boardId: doomed.id, title: `${marker} doomed` }) + expect((await callServerFn(api, 'deleteBoardFn', { id: doomed.id })).ok).toBe(true) + expect( + (await callServerFn(api, 'createCommentFn', { postId: onDoomed.id, content: `${marker} x` })) + .code + ).toBe('POST_NOT_FOUND') + expect(await commentsOf(b.id)).toHaveLength(0) + await api.dispose() + } +) diff --git a/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts b/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts new file mode 100644 index 0000000000..992ca466b0 --- /dev/null +++ b/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts @@ -0,0 +1,386 @@ +/** + * The team's comments in the post modal: public and private comments, + * Comment & mark a status, pin, delete, restore and edit. + * + * Journeys: FBA-P-28 FBA-P-29 FBA-P-30 FBA-P-32 FBA-P-33 FBA-P-34 FBA-P-40 + */ +import { test, expect } from '../../support/fixtures' +import { callServerFn, personApi } from '../../support/server-fns' +import { supportDb, pollFor } from '../../support/db' +import { + customerPost, + makeBoard, + makePost, + openPost, + portalCustomer, + postRow, + statusIdBySlug, + uuid, +} from '../../product/feedback-admin' +import { + activityOf, + commentsOf, + eventsOfPost, + openActivity, + principalUuid, + subscriptionsOf, + waitForPostEvent, +} from '../../product/feedback-admin-posts' +import type { Page } from '@playwright/test' + +/** Type a comment into the modal's composer and submit it with `button`. */ +async function writeComment(page: Page, text: string, button: string | RegExp = 'Comment') { + const dialog = page.getByRole('dialog') + // The composer is a stand-in until pressed; the press mounts the editor focused. + await dialog.getByRole('textbox', { name: 'Write a comment...' }).click() + await expect(page.locator('[contenteditable="true"]:focus')).toBeVisible() + await page.keyboard.type(text) + await dialog.getByRole('button', { name: button, exact: typeof button === 'string' }).click() +} + +function commentEl(page: Page, commentId: string) { + return page.locator(`[id="comment-${commentId}"]`) +} + +async function commentIdOf(postId: string, content: string): Promise { + const { fromUuid } = await import('@quackback/ids') + const row = await pollFor(`comment "${content}"`, async () => + (await commentsOf(postId)).find((c) => c.content.includes(content)) + ) + return fromUuid('post_comment', row.id) +} + +test( + 'FBA-P-28 a team comment shows with the team marker, counts, and subscribes the commenter', + { tag: '@core' }, + async ({ playwright, browser, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const customer = await portalCustomer(browser, marker) + const post = await customerPost(customer, { + boardId: board.id, + title: `${marker} needs a reply`, + }) + + const agentB = await asPerson('agentB') + await openPost(agentB, post.id) + const text = `${marker} thanks, looking into it` + await writeComment(agentB, text) + const commentId = await commentIdOf(post.id, text) + await expect(commentEl(agentB, commentId).getByText('Team').first()).toBeVisible() + + const [row] = (await commentsOf(post.id)).filter((c) => c.content.includes(text)) + expect(row).toMatchObject({ is_team_member: true, is_private: false }) + expect((await postRow(post.id))?.comment_count).toBe(1) + const subs = await subscriptionsOf(post.id) + expect( + subs.find((s) => s.principal_id === principalUuid(people.people.agentB.principalId)) + ).toMatchObject({ reason: 'comment' }) + await waitForPostEvent(post.id, 'comment.created') + await customer.close() + } +) + +test( + 'FBA-P-29 a private comment is stored private, not counted, and replies to it are forced private', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} internal` }) + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + + const dialog = admin.getByRole('dialog') + await dialog.getByRole('button', { name: 'Private', exact: true }).click() + const text = `${marker} internal note only` + await writeComment(admin, text) + const commentId = await commentIdOf(post.id, text) + const [row] = (await commentsOf(post.id)).filter((c) => c.content.includes(text)) + expect(row.is_private).toBe(true) + expect((await postRow(post.id))?.comment_count).toBe(0) + const [event] = await waitForPostEvent(post.id, 'comment.created') + expect(JSON.stringify(event.payload)).toContain('"isPrivate":true') + + // A reply to the private comment is private even when not asked to be. + const reply = await callServerFn(api, 'createCommentFn', { + postId: post.id, + content: `${marker} reply`, + parentId: commentId, + isPrivate: false, + }) + expect(reply.ok, reply.raw).toBe(true) + const replyRow = (await commentsOf(post.id)).find((c) => c.content === `${marker} reply`) + expect(replyRow?.is_private).toBe(true) + expect((await postRow(post.id))?.comment_count).toBe(0) + + // A customer cannot post a private comment. + const customer = await portalCustomer(browser, marker) + const refused = await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} sneaky`, + isPrivate: true, + }) + expect(refused.ok).toBe(false) + expect(refused.code).toBe('PRIVATE_COMMENT_FORBIDDEN') + await customer.close() + await api.dispose() + } +) + +test( + 'FBA-P-30 Comment & mark posts the comment and changes the status in one action', + { tag: '@core' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} mark me` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + const dialog = admin.getByRole('dialog') + // The composer's status picker shows the current status. + await dialog + .locator('form, div') + .filter({ has: admin.getByRole('button', { name: 'Comment', exact: true }) }) + .last() + .getByRole('button', { name: 'Open', exact: true }) + .click() + await admin + .getByRole('button', { name: /^Planned/ }) + .last() + .click() + const text = `${marker} shipping this next` + await writeComment(admin, text, 'Comment & mark Planned') + + const planned = await statusIdBySlug('planned') + const open = await statusIdBySlug('open') + await pollFor('the new status', async () => + (await postRow(post.id))?.status_id === uuid(planned) ? true : undefined + ) + const row = (await commentsOf(post.id)).find((c) => c.content.includes(text)) + expect(row).toMatchObject({ + status_change_from_id: uuid(open), + status_change_to_id: uuid(planned), + }) + expect((await activityOf(post.id)).filter((a) => a.type === 'status.changed')).toHaveLength(1) + await waitForPostEvent(post.id, 'post.status_changed') + const types = (await eventsOfPost(post.id)).map((e) => e.type) + expect(types.indexOf('comment.created')).toBeLessThan(types.indexOf('post.status_changed')) + } +) + +test( + 'FBA-P-30 a teammate without post.set_status cannot change status through a comment', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'FBA-P-30: comment.service.ts applies statusId for any team author with no post.set_status check', + }, + }, + async ({ playwright, marker }) => { + const admin = await personApi(playwright, 'admin') + const board = await makeBoard(admin, marker) + const post = await makePost(admin, { boardId: board.id, title: `${marker} no status right` }) + await admin.dispose() + // noAccess holds post.view_private but not post.set_status. + const api = await personApi(playwright, 'noAccess') + await callServerFn(api, 'createCommentFn', { + postId: post.id, + content: `${marker} sneaking a status`, + statusId: await statusIdBySlug('complete'), + }) + await api.dispose() + expect((await postRow(post.id))?.status_id).toBe(uuid(await statusIdBySlug('open'))) + } +) + +test( + 'FBA-P-32 pinning a team comment makes it the response; pinning another replaces it; unpin clears it', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} pin it` }) + const ids: string[] = [] + for (const n of ['first', 'second']) { + const res = await callServerFn<{ comment?: { id: string }; id?: string }>( + api, + 'createCommentFn', + { postId: post.id, content: `${marker} ${n} answer` } + ) + expect(res.ok, res.raw).toBe(true) + ids.push(await commentIdOf(post.id, `${marker} ${n} answer`)) + } + // Refusals: a customer comment and a private comment cannot be pinned. + const customer = await portalCustomer(browser, marker) + await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} customer says`, + }) + await customer.close() + const customerComment = await commentIdOf(post.id, `${marker} customer says`) + const notTeam = await callServerFn(api, 'pinCommentFn', { commentId: customerComment }) + expect(notTeam.ok).toBe(false) + expect(notTeam.error).toContain('Only team member comments can be pinned') + + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await commentEl(admin, ids[0]).getByRole('button', { name: 'Pin', exact: true }).first().click() + await pollFor('pinned first', async () => + (await postRow(post.id))?.pinned_comment_id === uuid(ids[0]) ? true : undefined + ) + await commentEl(admin, ids[1]).getByRole('button', { name: 'Pin', exact: true }).first().click() + await pollFor('pinned second', async () => + (await postRow(post.id))?.pinned_comment_id === uuid(ids[1]) ? true : undefined + ) + await commentEl(admin, ids[1]) + .getByRole('button', { name: 'Unpin', exact: true }) + .first() + .click() + await pollFor('unpinned', async () => + (await postRow(post.id))?.pinned_comment_id === null ? true : undefined + ) + const types = (await activityOf(post.id)).map((a) => a.type) + expect(types.filter((t) => t === 'comment.pinned')).toHaveLength(2) + expect(types.filter((t) => t === 'comment.unpinned')).toHaveLength(1) + await openActivity(admin, /pinned a response/) + await api.dispose() + } +) + +test( + 'FBA-P-33 the team deletes a customer comment: placeholder, count drops, comment.removed; a Contributor is refused', + { tag: '@core' }, + async ({ playwright, browser, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const customer = await portalCustomer(browser, marker) + const post = await customerPost(customer, { boardId: board.id, title: `${marker} spammy` }) + for (const n of ['one', 'two']) { + const res = await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} comment ${n}`, + }) + expect(res.ok, res.raw).toBe(true) + } + await customer.close() + const one = await commentIdOf(post.id, `${marker} comment one`) + const two = await commentIdOf(post.id, `${marker} comment two`) + expect((await postRow(post.id))?.comment_count).toBe(2) + + // A Contributor (no comment.edit) is refused by the server. + const contributor = await personApi(playwright, 'contributor') + const refused = await callServerFn(contributor, 'userDeleteCommentFn', { commentId: two }) + expect(refused.ok).toBe(false) + await contributor.dispose() + + const admin = await asPerson('admin') + await openPost(admin, post.id) + await commentEl(admin, one).getByRole('button', { name: 'Delete', exact: true }).first().click() + await admin + .getByRole('alertdialog') + .getByRole('button', { name: 'Delete', exact: true }) + .click() + await pollFor('soft delete', async () => + (await commentsOf(post.id)).find((c) => c.content.includes('comment one'))?.deleted_at + ? true + : undefined + ) + const [deleted] = await supportDb()` + SELECT deleted_by_principal_id FROM post_comments WHERE id = ${uuid(one)}` + expect(deleted.deleted_by_principal_id).toBe(principalUuid(people.people.admin.principalId)) + expect((await postRow(post.id))?.comment_count).toBe(1) + expect( + (await commentsOf(post.id)).find((c) => c.content.includes('comment two'))?.deleted_at + ).toBeNull() + await pollFor('comment.removed activity', async () => + (await activityOf(post.id)).find((a) => a.type === 'comment.removed') + ) + await expect(commentEl(admin, one).getByRole('button', { name: 'Restore' })).toBeVisible() + } +) + +test( + 'FBA-P-34 restoring a deleted comment re-counts it; restoring a live comment is refused', + { tag: '@nightly' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const customer = await portalCustomer(browser, marker) + const post = await customerPost(customer, { boardId: board.id, title: `${marker} restore c` }) + await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} keep me`, + }) + await customer.close() + const id = await commentIdOf(post.id, `${marker} keep me`) + const live = await callServerFn(api, 'restoreCommentFn', { commentId: id }) + expect(live.ok).toBe(false) + expect(live.code).toBe('NOT_DELETED') + const del = await callServerFn(api, 'userDeleteCommentFn', { commentId: id }) + expect(del.ok, del.raw).toBe(true) + expect((await postRow(post.id))?.comment_count).toBe(0) + + const admin = await asPerson('admin') + await openPost(admin, post.id) + await commentEl(admin, id).getByRole('button', { name: 'Restore', exact: true }).click() + await pollFor('restored', async () => + (await commentsOf(post.id))[0]?.deleted_at === null ? true : undefined + ) + expect((await postRow(post.id))?.comment_count).toBe(1) + await pollFor('comment.restored activity', async () => + (await activityOf(post.id)).find((a) => a.type === 'comment.restored') + ) + await api.dispose() + } +) + +test( + 'FBA-P-40 an admin edits a customer comment: content changes, history kept, comment.updated fired; a deleted comment cannot be edited', + { tag: '@nightly' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const customer = await portalCustomer(browser, marker) + const post = await customerPost(customer, { boardId: board.id, title: `${marker} typo` }) + await callServerFn(customer.api, 'createCommentFn', { + postId: post.id, + content: `${marker} teh typo`, + }) + await customer.close() + const id = await commentIdOf(post.id, `${marker} teh typo`) + + const admin = await asPerson('admin') + await openPost(admin, post.id) + await commentEl(admin, id).getByRole('button', { name: 'Edit', exact: true }).first().click() + const editor = admin.getByTestId('edit-comment-editor').locator('[contenteditable="true"]') + await editor.click() + await admin.keyboard.press('ControlOrMeta+a') + await editor.pressSequentially(`${marker} the typo`) + await commentEl(admin, id).getByRole('button', { name: 'Save', exact: true }).click() + await pollFor('edited content', async () => + (await commentsOf(post.id))[0]?.content === `${marker} the typo` ? true : undefined + ) + const history = await supportDb()` + SELECT previous_content FROM post_comment_edit_history WHERE comment_id = ${uuid(id)}` + expect(history.map((h) => String(h.previous_content))).toContain(`${marker} teh typo`) + await waitForPostEvent(post.id, 'comment.updated') + + // Editing a deleted comment is refused. + const adminApi = await personApi(playwright, 'admin') + await callServerFn(adminApi, 'userDeleteCommentFn', { commentId: id }) + const refused = await callServerFn(adminApi, 'userEditCommentFn', { + commentId: id, + content: `${marker} again`, + }) + expect(refused.ok).toBe(false) + expect(refused.code).toBe('COMMENT_NOT_FOUND') + await adminApi.dispose() + } +) diff --git a/apps/web/e2e/tests/feedback/admin-votes.spec.ts b/apps/web/e2e/tests/feedback/admin-votes.spec.ts new file mode 100644 index 0000000000..4d662b2892 --- /dev/null +++ b/apps/web/e2e/tests/feedback/admin-votes.spec.ts @@ -0,0 +1,251 @@ +/** + * Votes the team manages from the post modal: add a voter on someone's + * behalf, create a person and vote for them, remove a vote, the voters list + * and a voter's notification level. + * + * Journeys: FBA-P-22 FBA-P-23 FBA-P-25 FBA-P-26 FBA-P-27 + */ +import type { Page } from '@playwright/test' +import { fromUuid } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { callServerFn, personApi } from '../../support/server-fns' +import { supportDb, pollFor } from '../../support/db' +import { mintCustomer } from '../../support/widget-portal' +import { + customerPost, + makeBoard, + makePost, + openPost, + portalCustomer, + postRow, + uuid, +} from '../../product/feedback-admin' +import { + activityOf, + popover, + principalUuid, + subscriptionsOf, + votesOf, +} from '../../product/feedback-admin-posts' + +/** Open the Voters dialog from the sidebar's avatar stack. */ +async function openVoters(page: Page, count: number) { + await page.getByRole('dialog').first().locator('button[class*="-space-x-2"]').click() + const voters = page.getByRole('dialog', { name: `Voters (${count})` }) + await expect(voters).toBeVisible() + return voters +} + +function voterRow(voters: ReturnType, name: string) { + return voters.locator('div.group').filter({ hasText: name }) +} + +/** The X shows on hover only. */ +async function removeVoteOf(voters: ReturnType, name: string) { + const row = voterRow(voters, name) + await row.hover() + await row.getByRole('button', { name: 'Remove vote' }).click() +} + +test( + 'FBA-P-22 Add voter casts a proxy vote, subscribes the person and labels it Added by the teammate', + { tag: '@core' }, + async ({ playwright, people, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} proxy me` }) + await api.dispose() + const person = await mintCustomer({ + email: `${marker}@customers.example`, + name: `Voter ${marker.slice(-12)}`, + }) + + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await admin.getByRole('dialog').getByRole('button', { name: 'Add voter' }).click() + await popover(admin).getByPlaceholder('Search members...').fill(person.name) + await popover(admin) + .getByRole('button', { name: new RegExp(person.name) }) + .first() + .click() + + const vote = await pollFor('the proxy vote', async () => + (await votesOf(post.id)).find((v) => v.principal_id === person.principalUuid) + ) + expect(vote).toMatchObject({ + source_type: 'proxy', + added_by_principal_id: principalUuid(people.people.admin.principalId), + }) + expect((await postRow(post.id))?.vote_count).toBe(2) + const proxy = (await activityOf(post.id)).find((a) => a.type === 'vote.proxy') + expect(proxy?.metadata).toMatchObject({ voterName: person.name }) + const sub = (await subscriptionsOf(post.id)).find( + (s) => s.principal_id === person.principalUuid + ) + expect(sub).toMatchObject({ + reason: 'vote', + notify_comments: true, + notify_status_changes: true, + }) + + const voters = await openVoters(admin, 2) + await expect(voterRow(voters, person.name)).toContainText('Added by Ada Admin') + } +) + +test( + 'FBA-P-23 Add voter can create a new person and vote for them; a bad email is refused', + { tag: '@nightly' }, + async ({ playwright, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const post = await makePost(api, { boardId: board.id, title: `${marker} new voter` }) + await api.dispose() + const admin = await asPerson('admin') + await openPost(admin, post.id, post.title) + await admin.getByRole('dialog').getByRole('button', { name: 'Add voter' }).click() + const pop = popover(admin) + await pop.getByRole('button', { name: /New user|Create new user/ }).click() + const name = `New ${marker.slice(-14)}` + await pop.getByPlaceholder('Name').fill(name) + await pop.getByPlaceholder('Email (optional)').fill('not-an-email') + await pop.getByRole('button', { name: 'Create & add vote' }).click() + await expect(admin.getByText('Invalid email address').first()).toBeVisible() + expect(await votesOf(post.id)).toHaveLength(1) + + await pop.getByPlaceholder('Email (optional)').fill(`${marker}-new@customers.example`) + await pop.getByRole('button', { name: 'Create & add vote' }).click() + const [created] = await pollFor('the new person', async () => { + const rows = await supportDb()` + SELECT p.id FROM principal p JOIN "user" u ON u.id = p.user_id + WHERE u.email = ${`${marker}-new@customers.example`}` + return rows.length ? rows : undefined + }) + const vote = await pollFor('their vote', async () => + (await votesOf(post.id)).find((v) => v.principal_id === created.id) + ) + expect(vote.source_type).toBe('proxy') + } +) + +test( + 'FBA-P-25 removing a vote in the Voters dialog drops the count, logs it and keeps the subscription', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + await api.dispose() + const customer = await portalCustomer(browser, marker, { name: `Cust ${marker.slice(-12)}` }) + const post = await customerPost(customer, { boardId: board.id, title: `${marker} unvote` }) + await customer.close() + // The author's own vote is the only one. + expect((await postRow(post.id))?.vote_count).toBe(1) + + const admin = await asPerson('admin') + await openPost(admin, post.id) + const voters = await openVoters(admin, 1) + await removeVoteOf(voters, customer.name) + await pollFor('the vote removed', async () => + (await votesOf(post.id)).length === 0 ? true : undefined + ) + expect((await postRow(post.id))?.vote_count).toBe(0) + const removed = await pollFor('vote.removed', async () => + (await activityOf(post.id)).find((a) => a.type === 'vote.removed') + ) + expect(removed.metadata).toMatchObject({ voterName: customer.name }) + expect((await subscriptionsOf(post.id)).map((s) => s.principal_id)).toContain( + customer.principalUuid + ) + } +) + +test( + 'FBA-P-26 the voters list joins the merged thread and shows each source', + { tag: '@nightly' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const canonical = await makePost(api, { boardId: board.id, title: `${marker} canonical` }) + // A customer votes on a duplicate that is then merged into the canonical. + const customer = await portalCustomer(browser, marker, { name: `Dup ${marker.slice(-12)}` }) + const duplicate = await customerPost(customer, { boardId: board.id, title: `${marker} dupe` }) + await customer.close() + const merged = await callServerFn(api, 'mergePostFn', { + duplicatePostId: duplicate.id, + canonicalPostId: canonical.id, + }) + expect(merged.ok, merged.raw).toBe(true) + // An integration vote with a link, and an anonymous voter. + const viaSlack = await mintCustomer({ + email: `${marker}-slack@customers.example`, + name: `Slack ${marker.slice(-12)}`, + }) + // An anonymous visitor as the anonymous plugin makes one (temp-@anon.quackback.io). + const anon = await mintCustomer({ + email: `temp-${marker}@anon.quackback.io`, + name: 'Anonymous visitor', + }) + const sql = supportDb() + await sql`UPDATE principal SET type = 'anonymous' WHERE id = ${anon.principalUuid}` + await sql`INSERT INTO post_votes (id, post_id, principal_id, source_type, source_external_url, created_at, updated_at) + VALUES (gen_random_uuid(), ${uuid(canonical.id)}, ${viaSlack.principalUuid}, 'slack', + 'https://slack.example/msg/1', now(), now()), + (gen_random_uuid(), ${uuid(canonical.id)}, ${anon.principalUuid}, NULL, NULL, now(), now())` + await api.dispose() + + const admin = await asPerson('admin') + await openPost(admin, canonical.id) + const count = Number((await postRow(canonical.id))?.vote_count) + const voters = await openVoters(admin, count) + await expect(voters.getByText(customer.name)).toBeVisible() + await expect(voters.getByText('Ada Admin')).toBeVisible() + await expect(voters.getByRole('link', { name: /via Slack/ })).toHaveAttribute( + 'href', + 'https://slack.example/msg/1' + ) + await expect(voters.getByText('Anonymous')).toBeVisible() + await expect(voters.getByText(/@anon\.quackback\.io/)).toHaveCount(0) + await expect(voters.getByText('Anonymous visitor')).toHaveCount(0) + } +) + +test( + 'FBA-P-27 a voter notification level is changed from the Voters dialog; a non-voter is refused', + { tag: '@core' }, + async ({ playwright, browser, asPerson, marker }) => { + const api = await personApi(playwright, 'admin') + const board = await makeBoard(api, marker) + const customer = await portalCustomer(browser, marker, { name: `Lvl ${marker.slice(-12)}` }) + const post = await customerPost(customer, { boardId: board.id, title: `${marker} levels` }) + await customer.close() + + const admin = await asPerson('admin') + await openPost(admin, post.id) + const voters = await openVoters(admin, 1) + await voterRow(voters, customer.name).getByRole('button', { name: 'All activity' }).click() + await admin.getByRole('menuitemradio', { name: 'Status only' }).click() + await pollFor('status only', async () => { + const sub = (await subscriptionsOf(post.id)).find( + (s) => s.principal_id === customer.principalUuid + ) + return sub && !sub.notify_comments && sub.notify_status_changes ? sub : undefined + }) + await voterRow(voters, customer.name).getByRole('button', { name: 'Status only' }).click() + await admin.getByRole('menuitemradio', { name: 'Not subscribed' }).click() + await pollFor('unsubscribed', async () => + (await subscriptionsOf(post.id)).some((s) => s.principal_id === customer.principalUuid) + ? undefined + : true + ) + + const stranger = await mintCustomer({ email: `${marker}-x@customers.example` }) + const refused = await callServerFn(api, 'adminUpdateVoterSubscriptionFn', { + postId: post.id, + principalId: fromUuid('principal', stranger.principalUuid), + level: 'all', + }) + expect(refused.ok).toBe(false) + expect(refused.code).toBe('NOT_A_VOTER') + await api.dispose() + } +) From 582e54756ab8874d0c3975436a194fb92700d02a Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 08:20:48 +0000 Subject: [PATCH 5/7] test(e2e): wait for FBA-P activity rows and the hydrated New post button --- apps/web/e2e/product/feedback-admin-posts.ts | 15 +++++++ .../tests/feedback/admin-post-actions.spec.ts | 43 +++++++++++++------ .../feedback/admin-post-comments.spec.ts | 7 ++- .../e2e/tests/feedback/admin-votes.spec.ts | 3 +- 4 files changed, 53 insertions(+), 15 deletions(-) diff --git a/apps/web/e2e/product/feedback-admin-posts.ts b/apps/web/e2e/product/feedback-admin-posts.ts index bdf80d59b5..212b5fe91b 100644 --- a/apps/web/e2e/product/feedback-admin-posts.ts +++ b/apps/web/e2e/product/feedback-admin-posts.ts @@ -26,6 +26,21 @@ export async function activityTypesOf(postId: string): Promise { return (await activityOf(postId)).map((a) => a.type) } +/** + * Activity rows are written after the action answers: wait until the post + * has at least `count` rows of `type`, then return them all. + */ +export async function waitForActivity( + postId: string, + type: string, + count = 1 +): Promise { + return pollFor(`${count} ${type} activity row(s) on ${postId}`, async () => { + const rows = (await activityOf(postId)).filter((a) => a.type === type) + return rows.length >= count ? rows : undefined + }) +} + export interface PostEvent { type: string payload: Record diff --git a/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts index f943fcf715..effd3cdbf5 100644 --- a/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts +++ b/apps/web/e2e/tests/feedback/admin-post-actions.spec.ts @@ -7,6 +7,7 @@ * FBA-P-20 FBA-P-21 FBA-P-35 FBA-P-36 FBA-P-37 FBA-P-41, and the lower rows * FBA-P-03 FBA-P-06 FBA-P-10 FBA-P-24 FBA-P-31 at the server-function boundary. */ +import type { Page } from '@playwright/test' import { fromUuid } from '@quackback/ids' import { test, expect } from '../../support/fixtures' import { callServerFn, personApi } from '../../support/server-fns' @@ -42,6 +43,7 @@ import { subscriptionsOf, votesOf, waitForPostEvent, + waitForActivity, } from '../../product/feedback-admin-posts' // Well-formed ids nothing has. @@ -50,6 +52,19 @@ const UNKNOWN_POST = fromUuid('post', NOBODY) const UNKNOWN_BOARD = fromUuid('board', NOBODY) const UNKNOWN_STATUS = fromUuid('post_status', NOBODY) +/** + * Open the New post dialog. A press that lands before the inbox has + * hydrated does nothing, so press again until the form is there. + */ +async function openNewPost(page: Page): Promise { + await expect(async () => { + await page.getByRole('button', { name: 'New post' }).click() + await expect(page.getByPlaceholder("What's the feedback about?")).toBeVisible({ + timeout: 3_000, + }) + }).toPass({ timeout: 20_000 }) +} + /** Make one status the workspace default (isolated tests only). */ async function setDefaultStatus(statusId: string): Promise { await supportDb()`UPDATE post_statuses SET is_default = (id = ${uuid(statusId)})` @@ -67,7 +82,7 @@ test( try { const admin = await asPerson('admin') await openInbox(admin, { board: [board.id] }) - await admin.getByRole('button', { name: 'New post' }).click() + await openNewPost(admin) const dialog = admin.getByRole('dialog') const title = `${marker} dark mode please` await dialog.getByPlaceholder("What's the feedback about?").fill(title) @@ -92,7 +107,9 @@ test( const { fromUuid } = await import('@quackback/ids') const postId = fromUuid('post', String(row.id)) expect((await votesOf(postId)).map((v) => v.principal_id)).toEqual([adminUuid]) - expect((await subscriptionsOf(postId)).map((s) => s.principal_id)).toEqual([adminUuid]) + await expect + .poll(async () => (await subscriptionsOf(postId)).map((s) => s.principal_id)) + .toEqual([adminUuid]) const [delivery] = await deliveriesOf(marker, 'post.created', postId) expect(bodyOf<{ post: { id: string; title: string } }>(delivery).data.post).toMatchObject({ @@ -131,7 +148,7 @@ test( return r?.slug === 'planned' ? r.slug : undefined }) expect(status).toBe('planned') - const changed = (await activityOf(post.id)).filter((a) => a.type === 'status.changed') + const changed = await waitForActivity(post.id, 'status.changed') expect(changed).toHaveLength(1) expect(changed[0].metadata).toMatchObject({ fromName: 'Open', toName: 'Planned' }) @@ -156,7 +173,7 @@ test( const admin = await asPerson('admin') await openInbox(admin, { board: [board.id] }) - await admin.getByRole('button', { name: 'New post' }).click() + await openNewPost(admin) const dialog = admin.getByRole('dialog') const title = `${marker} on behalf` await dialog.getByPlaceholder("What's the feedback about?").fill(title) @@ -185,9 +202,9 @@ test( expect(row.principal_id).toBe(person.principalUuid) const postId = fromUuid('post', String(row.id)) expect((await votesOf(postId)).map((v) => v.principal_id)).toEqual([person.principalUuid]) - expect((await subscriptionsOf(postId)).map((s) => s.principal_id)).toEqual([ - person.principalUuid, - ]) + await expect + .poll(async () => (await subscriptionsOf(postId)).map((s) => s.principal_id)) + .toEqual([person.principalUuid]) // The Contributor preset has no post.set_author: the chosen author is ignored. const contributor = await personApi(playwright, 'contributor') @@ -369,7 +386,7 @@ test( await expect(admin.getByText('Owner unassigned')).toBeVisible() expect((await postRow(post.id))?.owner_principal_id).toBeNull() await expect.poll(() => activityTypesOf(post.id)).toContain('owner.unassigned') - expect(await activityTypesOf(post.id)).toContain('owner.assigned') + await waitForActivity(post.id, 'owner.assigned') await openActivity(admin, /assigned Ben Agent/) await expect(admin.getByRole('dialog').getByText(/removed assignee/)).toBeVisible() } @@ -526,9 +543,8 @@ test( content: `${marker} thanks`, }) expect(allowed.ok, allowed.raw).toBe(true) - const types = await activityTypesOf(post.id) - expect(types).toContain('comments.locked') - expect(types).toContain('comments.unlocked') + await waitForActivity(post.id, 'comments.locked') + await waitForActivity(post.id, 'comments.unlocked') await customer.close() await api.dispose() } @@ -623,7 +639,7 @@ test( expect((await postRow(post.id))?.deleted_at).toBeNull() expect(await votesOf(post.id)).toHaveLength(1) await waitForPostEvent(post.id, 'post.restored') - expect(await activityTypesOf(post.id)).toContain('post.restored') + await waitForActivity(post.id, 'post.restored') await openInbox(admin, { board: [board.id] }) await expect(admin.locator('h3', { hasText: post.title })).toBeVisible() } @@ -761,7 +777,8 @@ test( const page = await asPerson('contributor') await openPost(page, post.id, post.title) await pickStatus(page, 'Open', 'Planned') - await expect.poll(() => statusSlugOf(post.id)).toBe('planned') + await expect(sidebarRow(page, 'Status').getByRole('button', { name: 'Planned' })).toBeVisible() + await expect.poll(() => statusSlugOf(post.id), { timeout: 15_000 }).toBe('planned') const contributor = await personApi(playwright, 'contributor') const tags = await callServerFn(contributor, 'updatePostTagsFn', { diff --git a/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts b/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts index 992ca466b0..3697a9ade5 100644 --- a/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts +++ b/apps/web/e2e/tests/feedback/admin-post-comments.spec.ts @@ -25,6 +25,7 @@ import { principalUuid, subscriptionsOf, waitForPostEvent, + waitForActivity, } from '../../product/feedback-admin-posts' import type { Page } from '@playwright/test' @@ -73,6 +74,9 @@ test( const [row] = (await commentsOf(post.id)).filter((c) => c.content.includes(text)) expect(row).toMatchObject({ is_team_member: true, is_private: false }) expect((await postRow(post.id))?.comment_count).toBe(1) + await pollFor('the commenter subscription', async () => + (await subscriptionsOf(post.id)).length > 1 ? true : undefined + ) const subs = await subscriptionsOf(post.id) expect( subs.find((s) => s.principal_id === principalUuid(people.people.agentB.principalId)) @@ -164,7 +168,7 @@ test( status_change_from_id: uuid(open), status_change_to_id: uuid(planned), }) - expect((await activityOf(post.id)).filter((a) => a.type === 'status.changed')).toHaveLength(1) + expect(await waitForActivity(post.id, 'status.changed')).toHaveLength(1) await waitForPostEvent(post.id, 'post.status_changed') const types = (await eventsOfPost(post.id)).map((e) => e.type) expect(types.indexOf('comment.created')).toBeLessThan(types.indexOf('post.status_changed')) @@ -244,6 +248,7 @@ test( await pollFor('unpinned', async () => (await postRow(post.id))?.pinned_comment_id === null ? true : undefined ) + await waitForActivity(post.id, 'comment.unpinned') const types = (await activityOf(post.id)).map((a) => a.type) expect(types.filter((t) => t === 'comment.pinned')).toHaveLength(2) expect(types.filter((t) => t === 'comment.unpinned')).toHaveLength(1) diff --git a/apps/web/e2e/tests/feedback/admin-votes.spec.ts b/apps/web/e2e/tests/feedback/admin-votes.spec.ts index 4d662b2892..b5fd838fff 100644 --- a/apps/web/e2e/tests/feedback/admin-votes.spec.ts +++ b/apps/web/e2e/tests/feedback/admin-votes.spec.ts @@ -26,6 +26,7 @@ import { principalUuid, subscriptionsOf, votesOf, + waitForActivity, } from '../../product/feedback-admin-posts' /** Open the Voters dialog from the sidebar's avatar stack. */ @@ -77,7 +78,7 @@ test( added_by_principal_id: principalUuid(people.people.admin.principalId), }) expect((await postRow(post.id))?.vote_count).toBe(2) - const proxy = (await activityOf(post.id)).find((a) => a.type === 'vote.proxy') + const [proxy] = await waitForActivity(post.id, 'vote.proxy') expect(proxy?.metadata).toMatchObject({ voterName: person.name }) const sub = (await subscriptionsOf(post.id)).find( (s) => s.principal_id === person.principalUuid From a252294764bda9e0d82fa87c8740b6052c62cb8f Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 08:20:28 +0000 Subject: [PATCH 6/7] test(e2e): FBA-I-27 saved view delete rule and inbox DB tests for merged, facet and updatedBefore --- apps/web/e2e/QUARANTINE.md | 8 +++ .../e2e/tests/feedback/admin-inbox.spec.ts | 48 ++++++++++++- .../posts/__tests__/post.inbox.db.test.ts | 68 +++++++++++++++++++ 3 files changed, 123 insertions(+), 1 deletion(-) diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 1d250c2ea7..123dd24357 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -818,3 +818,11 @@ no such part beyond the wrong notification). post.set_status changes status through the comment box. Fix: require post.set_status for `shouldChangeStatus`. owner: unassigned, review by: 2026-12-03. +- `feedback/admin-inbox.spec.ts` › FBA-I-27 a teammate cannot delete a colleague’s + private saved view. Product bug: `deletePostViewFn` checks only post.edit and + `deleteView` (`apps/web/src/lib/server/domains/post-views/post-views.service.ts:76`) + updates by id with no owner or shared check, so any post.edit holder deletes + a private view they cannot even list (or anyone's shared view). Fix: pass the + caller and add `created_by_principal_id = caller OR (is_shared AND caller is +admin)` to the update; refuse when no row matched. owner: unassigned, review + by: 2026-12-03. diff --git a/apps/web/e2e/tests/feedback/admin-inbox.spec.ts b/apps/web/e2e/tests/feedback/admin-inbox.spec.ts index 418ba15dda..83cadbbc93 100644 --- a/apps/web/e2e/tests/feedback/admin-inbox.spec.ts +++ b/apps/web/e2e/tests/feedback/admin-inbox.spec.ts @@ -1,7 +1,9 @@ /** * The team's feedback inbox: list, filters, search, saved views, keyboard. * - * Journeys: FBA-I-01 + * Journeys: FBA-I-01 I-02 I-03 I-04 I-05 I-06 I-07 I-08 I-09 I-10 I-11 I-12 I-13 I-14 + * I-15 I-16 I-17 I-18 I-20 I-21 I-24 I-25 I-26 I-27 I-28 I-30 I-32. Lower rows I-22, + * I-29 and I-31 are in post.inbox.db.test.ts; I-19 in post.search.test.ts. */ import type { Page } from '@playwright/test' import { test, expect } from '../../support/fixtures' @@ -852,3 +854,47 @@ test( await expect(admin.getByPlaceholder('Search posts…')).toBeVisible({ timeout: 15_000 }) } ) + +test( + 'FBA-I-27 a teammate cannot delete a colleague’s private saved view', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'post-views.service.ts:76 deletes by id only: any post.edit holder deletes any view (QUARANTINE.md)', + }, + }, + async ({ playwright, newTeammate, marker }) => { + const admin = await personApi(playwright, 'admin') + const name = `Private ${marker}`.slice(0, 80) + const created = await callServerFn<{ id: string }>(admin, 'createPostViewFn', { + name, + filters: { owner: 'unassigned' }, + isShared: false, + }) + expect(created.ok, created.raw).toBe(true) + const viewId = created.data.id + await admin.dispose() + + const roleKey = await createRole(marker, ['post.view_private', 'post.edit']) + const colleague = await (await newTeammate({ roleKey })).api(playwright) + // The view is not even listed to them... + const listed = await callServerFn>( + colleague, + 'listPostViewsFn', + undefined, + { + method: 'GET', + } + ) + expect(listed.ok).toBe(true) + expect(listed.data.map((v) => v.id)).not.toContain(viewId) + // ...so deleting it by id must be refused, and the view must survive. + const res = await callServerFn(colleague, 'deletePostViewFn', { viewId }) + await colleague.dispose() + const [row] = await supportDb()`SELECT deleted_at FROM post_views WHERE id = ${uuid(viewId)}` + expect(row.deleted_at).toBeNull() + expect(res.ok).toBe(false) + } +) diff --git a/apps/web/src/lib/server/domains/posts/__tests__/post.inbox.db.test.ts b/apps/web/src/lib/server/domains/posts/__tests__/post.inbox.db.test.ts index 2cfd2460f8..5c93d6f74e 100644 --- a/apps/web/src/lib/server/domains/posts/__tests__/post.inbox.db.test.ts +++ b/apps/web/src/lib/server/domains/posts/__tests__/post.inbox.db.test.ts @@ -13,6 +13,7 @@ * Only real SQL shows either, so this suite runs against Postgres. */ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { eq } from 'drizzle-orm' import { createId, type BoardId, type PostId, type PrincipalId, type UserId } from '@quackback/ids' import { createDbTestFixture, testDb } from '@/lib/server/__tests__/db-test-fixture' import { boards, postComments, posts, principal, user } from '@/lib/server/db' @@ -24,6 +25,7 @@ vi.mock('@/lib/server/db', async (importOriginal) => ({ })) import { countInboxFilterFacets, listInboxPosts } from '../post.inbox' +import { listBoardsWithDetails } from '../../boards/board.service' const fixture = await createDbTestFixture({ probe: async (db) => { @@ -107,4 +109,70 @@ describe.skipIf(!fixture.available)('inbox correlated predicates (real DB)', () expect(list.items.map((p) => p.title)).toEqual(['By Ada']) }) + + // FBA-I-22 + it('leaves a merged duplicate out of the list, the facet counts and the board count until unmerged', async () => { + const author = await seedPrincipal('Author') + const boardId = await seedBoard() + const canonical = await seedPost(boardId, author, 'Canonical') + const duplicate = await seedPost(boardId, author, 'Duplicate') + await testDb + .update(posts) + .set({ canonicalPostId: canonical, mergedAt: new Date() }) + .where(eq(posts.id, duplicate)) + + const titles = async () => + (await listInboxPosts({ boardIds: [boardId] })).items.map((p) => p.title).sort() + const boardCount = async () => + (await listBoardsWithDetails()).find((b) => b.id === boardId)?.postCount + expect(await titles()).toEqual(['Canonical']) + expect((await countInboxFilterFacets({ boardIds: [boardId] })).boards[boardId]).toBe(1) + expect(await boardCount()).toBe(1) + + await testDb + .update(posts) + .set({ canonicalPostId: null, mergedAt: null }) + .where(eq(posts.id, duplicate)) + expect(await titles()).toEqual(['Canonical', 'Duplicate']) + expect((await countInboxFilterFacets({ boardIds: [boardId] })).boards[boardId]).toBe(2) + expect(await boardCount()).toBe(2) + }) + + // FBA-I-29 + it('counts each facet over every other active filter but not its own', async () => { + const author = await seedPrincipal('Author') + const boardA = await seedBoard() + const boardB = await seedBoard() + const answeredA = await seedPost(boardA, author, 'Answered on A') + await seedPost(boardA, author, 'Silent on A') + const answeredB = await seedPost(boardB, author, 'Answered on B') + const goneA = await seedPost(boardA, author, 'Deleted answered on A') + const goneB = await seedPost(boardB, author, 'Deleted answered on B') + for (const id of [answeredA, answeredB, goneA, goneB]) await seedComment(id, author, true) + await testDb.update(posts).set({ deletedAt: new Date() }).where(eq(posts.id, goneA)) + await testDb.update(posts).set({ deletedAt: new Date() }).where(eq(posts.id, goneB)) + + const counts = await countInboxFilterFacets({ boardIds: [boardA], responded: 'responded' }) + // Board counts ignore the board filter but keep "responded". + expect(counts.boards[boardA]).toBe(1) + expect(counts.boards[boardB]).toBe(1) + // Responded counts ignore their own filter but keep the board. + expect(counts.responded).toEqual({ responded: 1, unresponded: 1 }) + // Deleted counts keep both: only the restorable answered post on board A. + expect(counts.deleted).toBe(1) + }) + + // FBA-I-31 + it('updatedBefore keeps only posts not updated since the date', async () => { + const author = await seedPrincipal('Author') + const boardId = await seedBoard() + const stale = await seedPost(boardId, author, 'Stale') + await seedPost(boardId, author, 'Fresh') + const tenDaysAgo = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000) + await testDb.update(posts).set({ updatedAt: tenDaysAgo }).where(eq(posts.id, stale)) + + const fiveDaysAgo = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000) + const list = await listInboxPosts({ boardIds: [boardId], updatedBefore: fiveDaysAgo }) + expect(list.items.map((p) => p.title)).toEqual(['Stale']) + }) }) From 25b55f071a1cb44376d3913af4d6912f6d34a1bc Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 14:22:57 +0000 Subject: [PATCH 7/7] test(e2e): repair the summary and merge sweep entries after a bad rebase --- .../server/e2e-harness/__tests__/sweeps.test.ts | 14 ++++++++++++++ apps/web/src/lib/server/e2e-harness/sweeps.ts | 8 ++++++++ 2 files changed, 22 insertions(+) diff --git a/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts b/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts index 0d051fcd48..8d22132d52 100644 --- a/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts +++ b/apps/web/src/lib/server/e2e-harness/__tests__/sweeps.test.ts @@ -76,6 +76,17 @@ beforeEach(() => { calls.length = 0 }) +vi.mock('@/lib/server/domains/summary/summary.service', () => ({ + refreshStaleSummaries: vi.fn(async () => { + calls.push({ job: 'summary-sweep' }) + }), +})) +vi.mock('@/lib/server/domains/merge-suggestions/merge-check.service', () => ({ + sweepMergeSuggestions: vi.fn(async () => { + calls.push({ job: 'merge-sweep' }) + }), +})) + describe('runE2eSweep', () => { it('passes asOf through to the sweep as its clock', async () => { const outcome = await runE2eSweep({ job: 'snooze-sweep', asOf: '2030-05-01T10:00:00.000Z' }) @@ -191,7 +202,10 @@ describe('runE2eSweep', () => { ok: false, status: 400, }) + } expect(calls).toEqual([{ job: 'summary-sweep' }, { job: 'merge-sweep' }]) + }) + it('lists the sweeps it accepts and never the one-shot queues', () => { expect(E2E_SWEEP_NAMES).toContain('sla-breach-sweep') expect(E2E_SWEEP_NAMES).toContain('snooze-sweep') diff --git a/apps/web/src/lib/server/e2e-harness/sweeps.ts b/apps/web/src/lib/server/e2e-harness/sweeps.ts index 4a9819114f..61c22d7c31 100644 --- a/apps/web/src/lib/server/e2e-harness/sweeps.ts +++ b/apps/web/src/lib/server/e2e-harness/sweeps.ts @@ -155,15 +155,23 @@ const SWEEPS: Record = { }, // Feedback: refresh missing and stale post summaries (the hourly cron's pass). 'summary-sweep': { + asOf: false, + run: async () => { const { refreshStaleSummaries } = await import('@/lib/server/domains/summary/summary.service') await refreshStaleSummaries() return {} + }, + }, // Feedback: check posts with an embedding and no recent duplicate check. 'merge-sweep': { + asOf: false, + run: async () => { const { sweepMergeSuggestions } = await import('@/lib/server/domains/merge-suggestions/merge-check.service') await sweepMergeSuggestions() return {} + }, + }, } /** The sweeps the runner accepts, for the refusal message and the tests. */