diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 971b8bdb9d..d9d8a48608 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -164,3 +164,53 @@ id IN (SELECT post_id FROM post_votes WHERE principal_id = $1)`. owner: just stays open. Same component backs user attributes (PPL-U-51). Fix: catch in `handleCreate` (and the edit/delete handlers) and toast the error message. owner: unassigned, review by: 2026-12-03. +### Product suite: help center +Each test asserts the right behaviour and fails on the product bug named. +owner: unassigned, review by: 2026-12-03 for every entry. +- `help-center/admin-articles.spec.ts` › HC-A-15 emptying the description in + the editor clears it (HC-B12). `article-modal.tsx` sends + `description: data.description?.trim() || undefined`, and `updateArticle` + (`help-center.article.service.ts`) treats `undefined` as "leave unchanged", + so the old description stays. Fix: send `''` (or `null`) for an emptied + field; the service already stores `'' || null` as null. +- `help-center/admin-articles.spec.ts` › HC-A-20 an unknown article id in the + URL says the article was not found (HC-B18). `use-url-modal.ts` opens the + dialog whenever `?article=` is set and `article-modal.tsx` renders a spinner + until the article loads, so a missing or deleted id spins forever. Fix: when + the detail query errors (ARTICLE_NOT_FOUND), show a not-found state or close + the modal and drop the param. +- `help-center/api-rest.spec.ts` › HC-A-16 a whitespace-only title or + category name is refused on update (HC-B13). `updateArticleSchema` and + `updateCategorySchema` (`lib/shared/schemas/help-center.ts`, and the REST + bodies) check `min(1)` before trimming; `updateArticle` / `updateCategory` + then store the trimmed empty string. Fix: `.trim().min(1)` in the update + schemas, or refuse an empty trimmed value in the services as create does. +- `help-center/api-rest.spec.ts` › HC-A-76 a key without help_center.manage + cannot read drafts or private categories (HC-B3). The GET handlers in + `routes/api/v1/help-center/articles/index.ts`, `articles/$articleId.ts`, + `categories/index.ts` and `categories/$categoryId.ts` call + `withApiKeyAuth(request)` with no permission and read at team scope, so a + Contributor's key gets drafts and private categories. Fix: pass + `{ permission: PERMISSIONS.HELP_CENTER_MANAGE }` (as MCP does), or read with + the public visibility rules for keys without it. +- `help-center/admin-trash.spec.ts` › HC-A-26 the delete dialogs say a + deleted article or category can be restored (HC-B5). The article confirm + (`components/admin/help-center/help-center-list.tsx`, ConfirmDialog + description) says "This action cannot be undone. The article will be + permanently deleted." and the category confirm says "the UI provides no + restore flow", but both are soft deletes that Other › Deleted items restores + for 30 days. Fix: reword both to point at Deleted items. +- `help-center/admin-settings.spec.ts` › HC-A-67 a protocol-relative header + link is refused (HC-B20; `@isolated`). `helpCenterHeaderLinkUrl` + (`lib/shared/schemas/help-center.ts`) accepts any value starting with `/`, + so `//example.com` is stored, and `components/public/portal-header.tsx` + decides "external" by `!startsWith('/')`, rendering it as an in-tab internal + link to another host. Fix: require `startsWith('/') && !startsWith('//')` + in the schema (and treat `//` as external in the header). +- `help-center/translations.spec.ts` › HC-A-53 Save draft on a published + translation does not change the live page (HC-B9; `@isolated`). The + dialog's Save draft (`components/admin/help-center/article-translations-dialog.tsx`) + calls `upsertArticleTranslationFn`, which never touches `status`, so a + published translation's live text changes at once. Fix: either set + `status: 'draft'` on that save, or label the button "Save" when the + translation is published. diff --git a/apps/web/e2e/product/help-center.ts b/apps/web/e2e/product/help-center.ts new file mode 100644 index 0000000000..588bafdfdf --- /dev/null +++ b/apps/web/e2e/product/help-center.ts @@ -0,0 +1,229 @@ +/** + * Help center helpers for the product suite (e2e/tests/help-center/). + * + * const hc = await hcApi(playwright) // REST as the admin (personal key) + * const cat = await hcCategory(hc, `Guides ${marker}`) + * const art = await hcArticle(hc, { categoryId: cat.id, title: `... ${word}`, publish: true }) + * await page.goto(articlePath(art)) // /hc/en/articles/- + * + * Seeding goes through the product's REST API (markdown in, the editor JSON + * and the search vector built by the app), so a seeded article looks exactly + * like one an admin wrote. Rows are found by the marker in their names. + * + * Search note: the fake AI's embeddings are hash vectors, so only keyword + * matching finds anything. Put a single alphanumeric `searchWord()` in a title + * and search for it; the hyphenated marker is split by the text parser. + */ +import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' +import type { APIRequestContext, PlaywrightWorkerArgs } from '@playwright/test' +import { expect } from '@playwright/test' +import { fromUuid, generateId, toUuid } from '@quackback/ids' +import { apiFor, createKey, expectJson, type Wire } from '../support/api-client' +import { supportDb } from '../support/db' +import { supportEnv } from '../support/env' +import { SEEDED_PEOPLE_FILE, SUPPORT_PEOPLE, type SeededPeople } from '../support/people' + +/** One admin personal key per worker (minting one runs a script). */ +let adminKey: string | null = null + +export function hcAdminKey(): string { + adminKey ??= createKey({ creatorEmail: SUPPORT_PEOPLE.admin.email, kind: 'personal' }).key + return adminKey +} + +/** The seeded admin's principal TypeID (the default article author). */ +export function adminPrincipalId(): string { + const seeded = JSON.parse(readFileSync(SEEDED_PEOPLE_FILE, 'utf8')) as SeededPeople + return seeded.people.admin.principalId +} + +/** A REST context authenticated as the admin, with its own client address. */ +export function hcApi(playwright: PlaywrightWorkerArgs['playwright']): Promise { + return apiFor(playwright, supportEnv().baseUrl, hcAdminKey()) +} + +/** A token the search parser keeps whole: `zq` and hex, no hyphen. */ +export function searchWord(): string { + return `zq${randomBytes(5).toString('hex')}` +} + +export interface HcCategory { + /** TypeID, kb_category_... */ + id: string + uuid: string + slug: string + name: string + urlId: number +} + +export interface HcArticle { + /** TypeID, article_... */ + id: string + uuid: string + slug: string + title: string + urlId: number + categoryId: string + categorySlug: string +} + +/** A category through REST (public unless `isPublic: false`). */ +export async function hcCategory( + api: APIRequestContext, + name: string, + opts: { + parentId?: string | null + isPublic?: boolean + description?: string + icon?: string + position?: number + } = {} +): Promise { + const res = await api.post('/api/v1/help-center/categories', { data: { name, ...opts } }) + const { data } = await expectJson<{ data: Wire }>(res, 201) + const [row] = + await supportDb()`SELECT id, url_id FROM kb_categories WHERE id = ${uuidOfTypeId(data.id)}` + return { + id: data.id as string, + uuid: row.id as string, + slug: data.slug as string, + name: data.name as string, + urlId: row.url_id as number, + } +} + +/** An article through REST; `publish: true` publishes it after the create. */ +export async function hcArticle( + api: APIRequestContext, + input: { + categoryId: string + title: string + content?: string + description?: string + slug?: string + publish?: boolean + } +): Promise { + const { publish, ...body } = input + // API keys act as service principals, which need an explicit byline. + const res = await api.post('/api/v1/help-center/articles', { + data: { content: `Body of ${input.title}.`, authorId: adminPrincipalId(), ...body }, + }) + const { data } = await expectJson<{ data: Wire }>(res, 201) + if (publish) { + const pub = await api.patch(`/api/v1/help-center/articles/${data.id}`, { + data: { publishedAt: new Date().toISOString() }, + }) + await expectJson(pub, 200) + } + const [row] = + await supportDb()`SELECT id, url_id FROM kb_articles WHERE id = ${uuidOfTypeId(data.id)}` + return { + id: data.id as string, + uuid: row.id as string, + slug: data.slug as string, + title: data.title as string, + urlId: row.url_id as number, + categoryId: data.category.id as string, + categorySlug: data.category.slug as string, + } +} + +/** A category with one published article in it, both carrying `word`. */ +export async function hcPublishedArticle( + api: APIRequestContext, + marker: string, + opts: { word?: string; content?: string; isPublic?: boolean } = {} +): Promise<{ category: HcCategory; article: HcArticle; word: string }> { + const word = opts.word ?? searchWord() + const category = await hcCategory(api, `Guides ${marker}`, { isPublic: opts.isPublic }) + const article = await hcArticle(api, { + categoryId: category.id, + title: `Setting up the ${word} gadget`, + content: opts.content ?? `Hold the ${word} button for five seconds. ${marker}`, + publish: true, + }) + return { category, article, word } +} + +/** The canonical public article path, /hc//articles/-. */ +export function articlePath(a: Pick, locale = 'en'): string { + return `/hc/${locale}/articles/${a.urlId}-${a.slug}` +} + +/** The canonical public collection path, /hc//collections/-. */ +export function collectionPath(c: Pick, locale = 'en'): string { + return `/hc/${locale}/collections/${c.urlId}-${c.slug}` +} + +/** The admin editor deep link for an article. */ +export function editorPath(a: Pick): string { + return `/admin/help-center?article=${a.id}` +} + +/** The uuid behind a TypeID (`article_...`, `kb_category_...`). */ +export function uuidOfTypeId(typeId: string): string { + return toUuid(typeId as Parameters[0]) +} + +/** The stored article row (snake_case columns), or undefined. */ +export async function articleRow(uuid: string): Promise | undefined> { + const [row] = await supportDb()`SELECT * FROM kb_articles WHERE id = ${uuid}` + return row +} + +/** The stored category row, or undefined. */ +export async function categoryRow(uuid: string): Promise | undefined> { + const [row] = await supportDb()`SELECT * FROM kb_categories WHERE id = ${uuid}` + return row +} + +/** + * A manual segment of this test's own (SQL), with `members` (principal + * uuids) in it. Gates store the segment's TypeID. + */ +export async function hcSegment( + marker: string, + members: string[] = [] +): Promise<{ id: string; uuid: string; name: string }> { + const sql = supportDb() + const uuid = toUuid(generateId('segment')) + const name = `Segment ${marker} ${randomBytes(2).toString('hex')}` + await sql`INSERT INTO segments (id, name, slug, type, created_at, updated_at) + VALUES (${uuid}, ${name}, ${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}, 'manual', NOW(), NOW())` + for (const principalUuid of members) { + await sql`INSERT INTO user_segments (principal_id, segment_id, added_by) + VALUES (${principalUuid}, ${uuid}, 'manual')` + } + return { id: fromUuid('segment', uuid), uuid, name } +} + +/** Gate a category or an article to segments (SQL; the admin UI is tested on its own). */ +export async function gateToSegments( + target: { kind: 'category' | 'article'; uuid: string }, + segmentIds: string[] +): Promise { + const sql = supportDb() + const json = sql.json(segmentIds) + if (target.kind === 'category') { + await sql`UPDATE kb_categories SET segment_ids = ${json} WHERE id = ${target.uuid}` + } else { + await sql`UPDATE kb_articles SET segment_ids = ${json} WHERE id = ${target.uuid}` + } + const table = target.kind === 'category' ? 'kb_categories' : 'kb_articles' + const [row] = + await sql`SELECT jsonb_typeof(segment_ids) AS t FROM ${sql(table)} WHERE id = ${target.uuid}` + if (row?.t !== 'array') throw new Error(`segment_ids stored as ${row?.t}`) +} + +/** Fetch a public page as a signed-out visitor, bypassing the shared cache. */ +export async function publicGet( + request: APIRequestContext, + path: string +): Promise<{ status: number; text: string }> { + const res = await request.get(path, { maxRedirects: 0, headers: { 'cache-control': 'no-cache' } }) + return { status: res.status(), text: await res.text() } +} + +export { expect } diff --git a/apps/web/e2e/tests/help-center/admin-access.spec.ts b/apps/web/e2e/tests/help-center/admin-access.spec.ts new file mode 100644 index 0000000000..30db70f030 --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-access.spec.ts @@ -0,0 +1,41 @@ +/** + * Help center admin access: the permission and the product switch. + * + * Journeys: HC-A-01. + */ +import { test, expect } from '../../support/fixtures' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { withSettings } from '../../support/isolated-settings' + +test( + 'HC-A-01 the admin sees the help center; a role without help_center.manage gets no access', + { tag: '@core' }, + async ({ asPerson }) => { + const admin = await asPerson('admin') + await admin.goto('/admin/help-center') + await expect(admin.getByRole('button', { name: 'New category' })).toBeVisible() + await expect(admin.getByRole('button', { name: 'New article' }).first()).toBeVisible() + await expect(admin.getByRole('option', { name: 'Draft', exact: true })).toBeVisible() + + const contributor = await asPerson('contributor') + await contributor.goto('/admin/help-center') + await expect(contributor.getByText(/You don.t have access/)).toBeVisible() + await expect(contributor.getByRole('button', { name: 'New category' })).toBeHidden() + await expect(contributor.getByRole('link', { name: 'Help center', exact: true })).toBeHidden() + } +) + +test( + 'HC-A-01 with the product off the help center admin page redirects elsewhere', + { tag: ['@core', '@isolated'] }, + async ({ asPerson }) => { + test.skip(!ISOLATED, ISOLATED_SKIP) + await withSettings({ feature_flags: { helpCenter: false } }, async () => { + const admin = await asPerson('admin') + await admin.goto('/admin/help-center') + await expect(admin).not.toHaveURL(/\/admin\/help-center/) + await expect(admin).toHaveURL(/\/admin\//) + await expect(admin.getByRole('link', { name: 'Help center', exact: true })).toBeHidden() + }) + } +) diff --git a/apps/web/e2e/tests/help-center/admin-articles.spec.ts b/apps/web/e2e/tests/help-center/admin-articles.spec.ts new file mode 100644 index 0000000000..8e12f8e4f9 --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-articles.spec.ts @@ -0,0 +1,356 @@ +/** + * Help center admin: writing and editing articles in the create dialog and the + * editor modal. + * + * Journeys: HC-A-04, HC-A-05, HC-A-06, HC-A-08, HC-A-13, HC-A-15, HC-A-17, + * HC-A-19, HC-A-20. + */ +import type { Page } from '@playwright/test' +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { waitForHydration } from '../../utils/helpers' +import { + articlePath, + articleRow, + editorPath, + hcApi, + hcArticle, + hcCategory, + uuidOfTypeId, +} from '../../product/help-center' + +/** + * The editor modal over the list (/admin/help-center?article=). Found by + * its header's Copy Link, which stays put while a save is pending (the Save + * changes label turns into "Saving…"). + */ +function editorModal(page: Page) { + return page.getByRole('dialog').filter({ has: page.getByRole('button', { name: 'Copy Link' }) }) +} + +/** Open the create dialog from the list's New article button. */ +async function openCreateDialog(page: Page) { + await page.goto('/admin/help-center') + const button = page.getByRole('button', { name: 'New article' }).first() + await waitForHydration(button) + await button.click() + const dialog = page.getByRole('dialog', { name: 'Create help article' }) + await expect(dialog.getByPlaceholder('Article title')).toBeVisible() + return dialog +} + +/** Type into the dialog's rich text body. */ +async function typeBody(page: Page, scope: ReturnType, text: string) { + await scope.locator('.ProseMirror[contenteditable="true"]').click() + await page.keyboard.type(text) +} + +/** The article id the URL's ?article= names, once it is there. */ +async function articleIdInUrl(page: Page): Promise { + await expect(page).toHaveURL(/[?&]article=article_/, { timeout: 15_000 }) + return new URL(page.url()).searchParams.get('article')! +} + +test.describe('creating articles', () => { + test( + 'HC-A-04 a draft saved with no category is filed under General and opens in the editor', + { tag: '@smoke' }, + async ({ asPerson, people, marker, request }) => { + const admin = await asPerson('admin') + const dialog = await openCreateDialog(admin) + const title = `Draft ${marker}` + await dialog.getByPlaceholder('Article title').fill(title) + await typeBody(admin, dialog, `First words of ${marker}`) + await dialog.getByRole('button', { name: 'Save draft' }).click() + + const id = await articleIdInUrl(admin) + await expect(editorModal(admin).getByPlaceholder('Article title')).toHaveValue(title) + + const row = await articleRow(uuidOfTypeId(id)) + expect(row?.title).toBe(title) + expect(row?.published_at).toBeNull() + expect(String(row?.content)).toContain(`First words of ${marker}`) + expect(row?.principal_id).toBe(uuidOfTypeId(people.people.admin.principalId)) + const [category] = await supportDb()`SELECT slug, deleted_at FROM kb_categories + WHERE id = ${row?.category_id as string}` + expect(category.slug).toMatch(/^general(-\d+)?$/) + expect(category.deleted_at).toBeNull() + + // A draft is not on the public site. + const [{ url_id: urlId, slug }] = await supportDb()`SELECT url_id, slug FROM kb_articles + WHERE id = ${uuidOfTypeId(id)}` + expect((await request.get(articlePath({ urlId, slug }), { maxRedirects: 0 })).status()).toBe( + 404 + ) + } + ) + + test( + 'HC-A-05 the create dialog refuses an empty title or an empty body and saves nothing', + { tag: '@core' }, + async ({ asPerson, marker }) => { + const admin = await asPerson('admin') + const dialog = await openCreateDialog(admin) + const save = dialog.getByRole('button', { name: 'Save draft' }) + + await save.click() + await expect(dialog.getByText('Title is required')).toBeVisible() + + await dialog.getByPlaceholder('Article title').fill(`Title only ${marker}`) + await save.click() + await expect(dialog.getByText('Content is required')).toBeVisible() + await expect(dialog.getByText('Title is required')).toBeHidden() + + await dialog.getByPlaceholder('Article title').fill('') + await typeBody(admin, dialog, `Body only ${marker}`) + await save.click() + await expect(dialog.getByText('Title is required')).toBeVisible() + + // The dialog stays open and no row was written. + await expect(dialog).toBeVisible() + expect(admin.url()).not.toContain('article=') + const rows = await supportDb()`SELECT id FROM kb_articles + WHERE title LIKE ${`%${marker}%`} OR content LIKE ${`%${marker}%`}` + expect(rows).toHaveLength(0) + } + ) + + test( + 'HC-A-06 Publish creates the article live in one step', + { tag: '@core' }, + async ({ asPerson, marker, request }) => { + const admin = await asPerson('admin') + const dialog = await openCreateDialog(admin) + const title = `Published at once ${marker}` + await dialog.getByPlaceholder('Article title').fill(title) + await typeBody(admin, dialog, `Live words ${marker}`) + // Publish is the main action, with Save draft beside it. + await expect(dialog.getByRole('button', { name: 'Save draft' })).toBeVisible() + await dialog.getByRole('button', { name: 'Publish', exact: true }).click() + + const id = await articleIdInUrl(admin) + const modal = editorModal(admin) + await expect(modal.getByPlaceholder('Article title')).toHaveValue(title) + await expect(modal.getByRole('button', { name: 'Published', exact: true })).toBeVisible() + + const row = await articleRow(uuidOfTypeId(id)) + expect(row?.published_at).not.toBeNull() + const res = await request.get( + articlePath({ urlId: row!.url_id as number, slug: row!.slug as string }) + ) + expect(res.status()).toBe(200) + expect(await res.text()).toContain(title) + } + ) + + test( + 'HC-A-08 an article is filed under a picked category, or one created from the sidebar', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const existing = await hcCategory(hc, `Picked ${marker}`) + const admin = await asPerson('admin') + + // 1. Pick an existing category. + let dialog = await openCreateDialog(admin) + await dialog.getByPlaceholder('Article title').fill(`In picked ${marker}`) + await typeBody(admin, dialog, 'Body') + await dialog.getByRole('combobox').click() + await admin.getByRole('option', { name: existing.name }).click() + await dialog.getByRole('button', { name: 'Save draft' }).click() + const first = await articleIdInUrl(admin) + expect((await articleRow(uuidOfTypeId(first)))?.category_id).toBe(existing.uuid) + + // 2. Create a category from the plus button; it is selected for the article. + dialog = await openCreateDialog(admin) + await dialog.getByPlaceholder('Article title').fill(`In new ${marker}`) + await typeBody(admin, dialog, 'Body') + await dialog.getByTitle('Create new category').click() + const newCategory = admin.getByRole('dialog', { name: 'New category' }) + const name = `Made inline ${marker}` + await newCategory.getByLabel('Name').fill(name) + await newCategory.getByRole('button', { name: 'Create' }).click() + await expect(newCategory).toBeHidden() + await dialog.getByRole('button', { name: 'Save draft' }).click() + const second = await articleIdInUrl(admin) + const row = await articleRow(uuidOfTypeId(second)) + const [category] = + await supportDb()`SELECT name FROM kb_categories WHERE id = ${row?.category_id as string}` + expect(category.name).toBe(name) + } + ) +}) + +test.describe('editing articles', () => { + test( + 'HC-A-13 the editor opens from a row or a deep link and saves title, description, body and category', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const from = await hcCategory(hc, `From ${marker}`) + const to = await hcCategory(hc, `To ${marker}`) + const article = await hcArticle(hc, { + categoryId: from.id, + title: `Before ${marker}`, + content: 'Old body text.', + }) + const admin = await asPerson('admin') + + // From the list row (the list filtered to the article's category). + await admin.goto(`/admin/help-center?category=${from.id}`) + const modal = editorModal(admin) + // The list is server-rendered: a click before hydration does nothing. + await expect(async () => { + await admin.getByRole('heading', { name: article.title }).click() + await expect(modal.getByPlaceholder('Article title')).toHaveValue(article.title, { + timeout: 2_000, + }) + }).toPass({ timeout: 15_000 }) + await expect(admin).toHaveURL(new RegExp(`article=${article.id}`)) + // Nothing changed yet: nothing to save. Cancel closes without saving. + await expect(modal.getByRole('button', { name: 'Save changes' })).toBeDisabled() + await modal.getByRole('button', { name: 'Cancel' }).click() + await expect(modal).toBeHidden() + + // From a deep link. + await admin.goto(editorPath(article)) + await expect(modal.getByPlaceholder('Article title')).toHaveValue(article.title) + const before = await articleRow(article.uuid) + const newTitle = `After ${marker}` + await modal.getByPlaceholder('Article title').fill(` ${newTitle} `) + await modal.getByLabel('Page description').fill(` Summary ${marker} `) + await modal.locator('.ProseMirror[contenteditable="true"]').click() + await admin.keyboard.press('ControlOrMeta+a') + await admin.keyboard.type(`New body ${marker}`) + await modal.getByRole('combobox').first().click() + await admin.getByRole('option', { name: to.name }).click() + await modal.getByRole('button', { name: 'Save changes' }).click() + await expect(modal).toBeHidden() + + const row = await articleRow(article.uuid) + expect(row?.title).toBe(newTitle) + expect(row?.description).toBe(`Summary ${marker}`) + expect(String(row?.content)).toContain(`New body ${marker}`) + expect(String(row?.content)).not.toContain('Old body text') + expect(row?.category_id).toBe(to.uuid) + expect((row?.updated_at as Date).getTime()).toBeGreaterThan( + (before?.updated_at as Date).getTime() + ) + + // The list row shows the new title and the description preview. + await admin.goto(`/admin/help-center?category=${to.id}`) + await expect(admin.getByRole('heading', { name: newTitle })).toBeVisible() + await expect(admin.getByText(`Summary ${marker}`)).toBeVisible() + } + ) + + test( + 'HC-A-15 emptying the description in the editor clears it', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B12: article-modal.tsx sends description undefined for an empty field, which updateArticle reads as unchanged', + }, + }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Desc ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Described ${marker}`, + description: `Old summary ${marker}`, + }) + const admin = await asPerson('admin') + await admin.goto(editorPath(article)) + const modal = editorModal(admin) + const description = modal.getByLabel('Page description') + await expect(description).toHaveValue(`Old summary ${marker}`) + await description.fill('') + await modal.getByRole('button', { name: 'Save changes' }).click() + await expect(modal).toBeHidden() + + await expect.poll(async () => (await articleRow(article.uuid))?.description).toBeNull() + await admin.goto(editorPath(article)) + await expect(modal.getByLabel('Page description')).toHaveValue('') + } + ) + + test( + 'HC-A-17 the status button publishes and unpublishes the article', + { tag: '@smoke' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Toggle ${marker}`) + const article = await hcArticle(hc, { categoryId: category.id, title: `Toggled ${marker}` }) + const admin = await asPerson('admin') + await admin.goto(editorPath(article)) + const modal = editorModal(admin) + await expect(modal.getByRole('button', { name: 'View', exact: true })).toBeHidden() + + await modal.getByRole('button', { name: 'Draft', exact: true }).click() + await expect(modal.getByRole('button', { name: 'Published', exact: true })).toBeVisible() + await expect(modal.getByRole('button', { name: 'View', exact: true })).toBeVisible() + expect((await articleRow(article.uuid))?.published_at).not.toBeNull() + const live = await request.get(articlePath(article)) + expect(live.status()).toBe(200) + expect(await live.text()).toContain(article.title) + + await modal.getByRole('button', { name: 'Published', exact: true }).click() + await expect(modal.getByRole('button', { name: 'Draft', exact: true })).toBeVisible() + await expect(modal.getByRole('button', { name: 'View', exact: true })).toBeHidden() + const row = await articleRow(article.uuid) + expect(row?.published_at).toBeNull() + expect(row?.deleted_at).toBeNull() + expect((await request.get(articlePath(article), { maxRedirects: 0 })).status()).toBe(404) + } + ) + + test( + 'HC-A-19 View in the editor opens the public article', + { tag: '@nightly' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `View ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Viewed ${marker}`, + publish: true, + }) + const admin = await asPerson('admin') + await admin.goto(editorPath(article)) + const modal = editorModal(admin) + const [tab] = await Promise.all([ + admin.context().waitForEvent('page'), + modal.getByRole('button', { name: 'View', exact: true }).click(), + ]) + await tab.waitForLoadState() + expect(new URL(tab.url()).pathname).toBe(articlePath(article)) + await expect(tab.getByRole('heading', { level: 1, name: article.title })).toBeVisible() + } + ) + + test( + 'HC-A-20 an unknown article id in the URL says the article was not found', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B18: use-url-modal.ts opens the dialog for any ?article= value and article-modal.tsx waits for the article forever (spinner, no not-found state)', + }, + }, + async ({ asPerson }) => { + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?article=${generateId('article')}`) + const dialog = admin.getByRole('dialog') + await expect(dialog).toBeVisible() + await expect(dialog.getByText(/not found|no longer exists|deleted/i)).toBeVisible({ + timeout: 10_000, + }) + await expect(dialog.locator('.animate-spin')).toHaveCount(0) + } + ) +}) diff --git a/apps/web/e2e/tests/help-center/admin-categories.spec.ts b/apps/web/e2e/tests/help-center/admin-categories.spec.ts new file mode 100644 index 0000000000..0b2b40f06c --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-categories.spec.ts @@ -0,0 +1,205 @@ +/** + * Help center admin: categories in the tree pane (create, edit, visibility, + * segment gate, delete). + * + * Journeys: HC-A-31, HC-A-33, HC-A-34, HC-A-36. + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { waitForHydration } from '../../utils/helpers' +import { + categoryRow, + collectionPath, + articleRow, + gateToSegments, + hcApi, + hcArticle, + hcCategory, + hcSegment, +} from '../../product/help-center' + +/** The tree row of a category. */ +function treeRow(page: Page, name: string) { + return page.getByRole('treeitem').filter({ hasText: name }) +} + +/** Hover a tree row and press one of its actions. */ +async function rowAction(page: Page, name: string, action: string) { + const row = treeRow(page, name) + await waitForHydration(row.getByRole('button').first()) + await row.hover() + await row.getByRole('button', { name: action }).click() +} + +test( + 'HC-A-31 a new top-level category is stored trimmed with its icon and shows in the tree', + { tag: '@core' }, + async ({ asPerson, marker, request }) => { + const admin = await asPerson('admin') + await admin.goto('/admin/help-center') + const add = admin.getByRole('button', { name: 'New category' }) + await waitForHydration(add) + await add.click() + const dialog = admin.getByRole('dialog', { name: 'New category' }) + const create = dialog.getByRole('button', { name: 'Create' }) + await expect(create).toBeDisabled() + await dialog.getByLabel('Name').fill(' ') + await expect(create).toBeDisabled() + + const name = `Getting started ${marker}` + await dialog.getByLabel('Name').fill(` ${name} `) + await dialog.getByLabel('Description').fill(` Where to begin ${marker} `) + // The icon picker is the button beside the name. + await dialog.locator('#category-name').locator('xpath=preceding-sibling::*[1]').click() + await admin.getByPlaceholder('Search icons…').fill('rocket') + await admin + .getByTitle(/^rocket/) + .first() + .click() + await create.click() + await expect(dialog).toBeHidden() + + await expect(treeRow(admin, name)).toBeVisible() + await expect(treeRow(admin, name).getByTitle('0 articles')).toBeVisible() + const [row] = await supportDb()`SELECT * FROM kb_categories WHERE name = ${name}` + expect(row).toMatchObject({ + name, + description: `Where to begin ${marker}`, + is_public: true, + position: 0, + parent_id: null, + deleted_at: null, + }) + expect(row.slug).toBe(`getting-started-${marker}`) + expect(row.icon).toMatch(/^Rocket/) + + // No published article in it yet, so the public landing leaves it out. + expect(await (await request.get('/hc')).text()).not.toContain(name) + } +) + +test( + 'HC-A-33 editing a category renames and re-parents it; its public URL keeps working', + { tag: '@core' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const parent = await hcCategory(hc, `New parent ${marker}`) + const category = await hcCategory(hc, `Old name ${marker}`) + await hcArticle(hc, { categoryId: category.id, title: `Inside ${marker}`, publish: true }) + const before = await categoryRow(category.uuid) + + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + await rowAction(admin, category.name, 'Edit category') + const dialog = admin.getByRole('dialog', { name: 'Edit category' }) + await expect(dialog.getByLabel('Name')).toHaveValue(category.name) + const name = `Renamed ${marker}` + await dialog.getByLabel('Name').fill(name) + await dialog.getByLabel('Description').fill(`Now described ${marker}`) + await dialog.getByRole('combobox').click() + await admin.getByRole('option', { name: parent.name }).click() + await dialog.getByRole('button', { name: 'Save' }).click() + await expect(dialog).toBeHidden() + + await expect.poll(async () => (await categoryRow(category.uuid))?.name).toBe(name) + const row = await categoryRow(category.uuid) + expect(row?.parent_id).toBe(parent.uuid) + expect(row?.description).toBe(`Now described ${marker}`) + expect((row?.updated_at as Date).getTime()).toBeGreaterThan( + (before?.updated_at as Date).getTime() + ) + // The tree nests the row under its new parent. + await expect(treeRow(admin, name)).toHaveAttribute('aria-level', '2') + + // A rename keeps the slug; the public page shows the new name. Public + // URLs are keyed by urlId, so a stale slug 301s to the canonical one. + const page = await request.get(collectionPath(category)) + expect(page.status()).toBe(200) + expect(await page.text()).toContain(name) + const stale = await request.get(`/hc/en/collections/${category.urlId}-stale-slug`, { + maxRedirects: 0, + }) + expect(stale.status()).toBe(301) + expect(new URL(stale.headers()['location'] ?? '', 'http://x').pathname).toBe( + collectionPath(category) + ) + } +) + +test( + 'HC-A-34 making a gated category private clears its segment gate for good', + { tag: '@core' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const segment = await hcSegment(marker) + const category = await hcCategory(hc, `Gated ${marker}`) + await hcArticle(hc, { categoryId: category.id, title: `Gated doc ${marker}`, publish: true }) + await gateToSegments({ kind: 'category', uuid: category.uuid }, [segment.id]) + // Gated: a signed-out visitor gets the 404 a missing page gets. + expect((await request.get(collectionPath(category), { maxRedirects: 0 })).status()).toBe(404) + + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + await rowAction(admin, category.name, 'Edit category') + const dialog = admin.getByRole('dialog', { name: 'Edit category' }) + const gate = dialog.getByLabel('Category segment gate') + await expect(gate).toBeVisible() + await expect(gate).toContainText(segment.name) + await dialog.getByRole('switch').click() + await expect(gate).toBeHidden() + await dialog.getByRole('button', { name: 'Save' }).click() + await expect(dialog).toBeHidden() + + await expect.poll(async () => (await categoryRow(category.uuid))?.is_public).toBe(false) + expect((await categoryRow(category.uuid))?.segment_ids).toEqual([]) + expect((await request.get(collectionPath(category), { maxRedirects: 0 })).status()).toBe(404) + + // Public again: the old restriction does not come back, so everyone sees it. + await rowAction(admin, category.name, 'Edit category') + await dialog.getByRole('switch').click() + await dialog.getByRole('button', { name: 'Save' }).click() + await expect(dialog).toBeHidden() + await expect.poll(async () => (await categoryRow(category.uuid))?.is_public).toBe(true) + expect((await categoryRow(category.uuid))?.segment_ids).toEqual([]) + expect((await request.get(collectionPath(category))).status()).toBe(200) + } +) + +test( + 'HC-A-36 deleting a category deletes its sub-categories and articles together', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const root = await hcCategory(hc, `Root ${marker}`) + const doomed = await hcCategory(hc, `Doomed ${marker}`, { parentId: root.id }) + const child = await hcCategory(hc, `Doomed child ${marker}`, { parentId: doomed.id }) + const a1 = await hcArticle(hc, { categoryId: doomed.id, title: `In doomed ${marker}` }) + const a2 = await hcArticle(hc, { categoryId: child.id, title: `In child ${marker}` }) + const survivor = await hcArticle(hc, { categoryId: root.id, title: `In root ${marker}` }) + + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${doomed.id}`) + await rowAction(admin, doomed.name, 'Delete category') + const confirm = admin.getByRole('alertdialog') + await expect(confirm).toContainText(`"${doomed.name}" along with 1 sub-category and 2 articles`) + await confirm.getByRole('button', { name: 'Delete' }).click() + await expect(confirm).toBeHidden() + + // The selection falls back to the parent. + await expect(admin).toHaveURL(new RegExp(`category=${root.id}`)) + await expect(treeRow(admin, doomed.name)).toBeHidden() + + const rows = await Promise.all([ + categoryRow(doomed.uuid), + categoryRow(child.uuid), + articleRow(a1.uuid), + articleRow(a2.uuid), + ]) + const stamps = rows.map((r) => (r?.deleted_at as Date | null)?.getTime()) + expect(stamps.every((t) => typeof t === 'number')).toBe(true) + expect(new Set(stamps).size).toBe(1) + expect((await articleRow(survivor.uuid))?.deleted_at).toBeNull() + expect((await categoryRow(root.uuid))?.deleted_at).toBeNull() + } +) diff --git a/apps/web/e2e/tests/help-center/admin-list.spec.ts b/apps/web/e2e/tests/help-center/admin-list.spec.ts new file mode 100644 index 0000000000..41cf7d841a --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-list.spec.ts @@ -0,0 +1,116 @@ +/** + * Help center admin: the article list (status and category filters, search, + * sort and paging). + * + * Journeys: HC-A-39, HC-A-40, HC-A-41. + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { waitForHydration } from '../../utils/helpers' +import { hcApi, hcArticle, hcCategory, searchWord } from '../../product/help-center' + +/** The titles the list shows, in order. */ +function listTitles(page: Page) { + return page.locator('h3').allInnerTexts() +} + +test( + 'HC-A-39 the status and category filters change the list and Clear all resets them', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Filters ${marker}`) + const draft = await hcArticle(hc, { categoryId: category.id, title: `Draft row ${marker}` }) + const live = await hcArticle(hc, { + categoryId: category.id, + title: `Live row ${marker}`, + publish: true, + }) + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + await expect(admin.getByText('2 articles', { exact: true })).toBeVisible() + await expect(admin.getByRole('heading', { name: draft.title })).toBeVisible() + await expect(admin.getByRole('heading', { name: live.title })).toBeVisible() + // The category shows as a chip. + await expect( + admin.getByRole('button', { name: `Remove Category ${category.name} filter` }) + ).toBeVisible() + + const draftOption = admin.getByRole('option', { name: 'Draft', exact: true }) + await waitForHydration(draftOption) + await draftOption.click() + await expect(admin).toHaveURL(/status=draft/) + await expect(admin.getByRole('heading', { name: live.title })).toBeHidden() + await expect(admin.getByRole('heading', { name: draft.title })).toBeVisible() + await expect(admin.getByText('1 article', { exact: true })).toBeVisible() + + await admin.getByRole('option', { name: 'Published', exact: true }).click() + await expect(admin).toHaveURL(/status=published/) + await expect(admin.getByRole('heading', { name: draft.title })).toBeHidden() + await expect(admin.getByRole('heading', { name: live.title })).toBeVisible() + + // Removing the status chip keeps the category. + await admin.getByRole('button', { name: 'Remove Status Published filter' }).click() + await expect(admin).not.toHaveURL(/status=/) + await expect(admin.getByRole('heading', { name: draft.title })).toBeVisible() + + await admin.getByRole('option', { name: 'Draft', exact: true }).click() + await admin.getByRole('button', { name: 'Clear all' }).click() + await expect(admin).not.toHaveURL(/status=|category=/) + } +) + +test( + 'HC-A-40 the admin search finds drafts and private articles by a title word', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const hidden = await hcCategory(hc, `Private ${marker}`, { isPublic: false }) + const draft = await hcArticle(hc, { categoryId: hidden.id, title: `Find ${word} draft` }) + const other = await hcArticle(hc, { categoryId: hidden.id, title: `Other ${marker}` }) + const admin = await asPerson('admin') + await admin.goto('/admin/help-center') + + const search = admin.getByPlaceholder('Search articles…') + await waitForHydration(search) + await search.fill(word) + await expect(admin).toHaveURL(new RegExp(`search=${word}`)) + await expect(admin.getByRole('heading', { name: draft.title })).toBeVisible() + await expect(admin.getByRole('heading', { name: other.title })).toBeHidden() + expect(await listTitles(admin)).toEqual([draft.title]) + + await search.fill(searchWord()) + await expect(admin.getByText('No articles match your search')).toBeVisible() + } +) + +test( + 'HC-A-41 a category with more than a page loads the rest, and Oldest sorts by creation', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + test.setTimeout(60_000) + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Paging ${marker}`) + const titles: string[] = [] + for (let i = 1; i <= 23; i++) { + const title = `Page item ${String(i).padStart(2, '0')} ${marker}` + await hcArticle(hc, { categoryId: category.id, title }) + titles.push(title) + } + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + // Newest first, 20 to a page, with a plus while more exist. + await expect(admin.getByText('20+ articles', { exact: true })).toBeVisible() + expect((await listTitles(admin))[0]).toBe(titles[22]) + + const more = admin.getByRole('button', { name: 'Load more articles' }) + await more.scrollIntoViewIfNeeded() + await expect(admin.getByText('23 articles', { exact: true })).toBeVisible({ timeout: 15_000 }) + expect(new Set(await listTitles(admin))).toEqual(new Set(titles)) + + await admin.goto(`/admin/help-center?category=${category.id}&sort=oldest`) + await expect(admin.getByText('20+ articles', { exact: true })).toBeVisible() + expect((await listTitles(admin)).slice(0, 3)).toEqual(titles.slice(0, 3)) + } +) diff --git a/apps/web/e2e/tests/help-center/admin-settings.spec.ts b/apps/web/e2e/tests/help-center/admin-settings.spec.ts new file mode 100644 index 0000000000..e09b19c2b3 --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-settings.spec.ts @@ -0,0 +1,217 @@ +/** + * Help center settings: redirect rules, homepage texts and header links. + * + * Journeys: HC-A-62, HC-A-63, HC-A-64, HC-A-66, HC-A-67. + */ +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { supportDb } from '../../support/db' +import { withSettings } from '../../support/isolated-settings' +import { callServerFn, personApi } from '../../support/server-fns' +import { waitForHydration } from '../../utils/helpers' +import { articlePath, hcApi, hcArticle, hcCategory } from '../../product/help-center' + +const SETTINGS = '/admin/settings/help-center' + +test( + 'HC-A-62 a redirect rule sends an old /hc path to a published article', + { tag: '@core' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Redirected ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Redirect target ${marker}`, + publish: true, + }) + const admin = await asPerson('admin') + await admin.goto(`${SETTINGS}?tab=domains-languages`) + const pathInput = admin.getByRole('textbox', { name: 'Redirect path' }) + await waitForHydration(pathInput) + const add = admin.getByRole('button', { name: 'Add rule' }) + // The path must start with / before Add rule is offered. + await pathInput.fill(`hc/old/${marker}`) + await expect(add).toBeDisabled() + // Messy but valid: normalised to /hc/old/. + await pathInput.fill(`/hc//old/${marker}/`) + const card = admin.locator('div').filter({ has: pathInput }).last() + await card.getByRole('combobox').last().click() + await admin.getByRole('option', { name: article.title }).click() + await add.click() + const path = `/hc/old/${marker}` + await expect(admin.getByText(path, { exact: true })).toBeVisible() + await expect(admin.getByText(`→ article "${article.title}"`)).toBeVisible() + + // First hop: the rule (legacy article form); second hop: the canonical URL. + const first = await request.get(path, { maxRedirects: 0 }) + expect(first.status()).toBe(301) + const legacy = new URL(first.headers()['location'], 'http://x').pathname + expect(legacy).toBe(`/hc/articles/${category.slug}/${article.slug}`) + const second = await request.get(legacy, { maxRedirects: 0 }) + expect(second.status()).toBe(301) + expect(new URL(second.headers()['location'], 'http://x').pathname).toBe(articlePath(article)) + } +) + +test( + 'HC-A-63 redirect rules refuse a taken path and dead targets, and stop redirecting to a dead page', + { tag: '@core' }, + async ({ marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Rules ${marker}`) + const privateCat = await hcCategory(hc, `Private rules ${marker}`, { isPublic: false }) + const live = await hcArticle(hc, { + categoryId: category.id, + title: `Rule live ${marker}`, + publish: true, + }) + const draft = await hcArticle(hc, { categoryId: category.id, title: `Rule draft ${marker}` }) + const api = await personApi(playwright, 'admin') + const create = (path: string, targetType: 'article' | 'category', targetId: string) => + callServerFn(api, 'createRedirectRuleFn', { path, targetType, targetId }) + + const path = `/hc/rules/${marker}` + const ok = await create(path, 'category', category.id) + expect(ok.ok, ok.error).toBe(true) + const taken = await create(`${path}/`, 'article', live.id) + expect(taken.code).toBe('HC_REDIRECT_PATH_TAKEN') + expect(taken.error).toContain('A redirect rule for') + expect(taken.error).toContain(path) + expect(taken.error).toContain('already exists') + + const unpublished = await create(`${path}-a`, 'article', draft.id) + expect(unpublished.code).toBe('HC_REDIRECT_TARGET_NOT_PUBLISHED') + expect(unpublished.error).toContain('Redirect target must be a published article') + const hidden = await create(`${path}-b`, 'category', privateCat.id) + expect(hidden.code).toBe('HC_REDIRECT_TARGET_NOT_PUBLISHED') + expect(hidden.error).toContain('Redirect target must be a public category') + const missing = await create(`${path}-c`, 'article', generateId('article')) + expect(missing.code).toBe('HC_REDIRECT_TARGET_NOT_FOUND') + const rows = await supportDb()`SELECT path FROM hc_redirect_rules WHERE path LIKE ${`${path}%`}` + expect(rows.map((r) => r.path)).toEqual([path]) + + // The category rule redirects; once the category is private it is a 404, + // and public again it redirects again with no re-entry. + const articleRule = await create(`${path}-live`, 'article', live.id) + expect(articleRule.ok, articleRule.error).toBe(true) + expect((await request.get(path, { maxRedirects: 0 })).status()).toBe(301) + expect( + ( + await hc.patch(`/api/v1/help-center/categories/${category.id}`, { + data: { isPublic: false }, + }) + ).status() + ).toBe(200) + expect((await request.get(path, { maxRedirects: 0 })).status()).toBe(404) + expect( + ( + await hc.patch(`/api/v1/help-center/categories/${category.id}`, { + data: { isPublic: true }, + }) + ).status() + ).toBe(200) + expect((await request.get(path, { maxRedirects: 0 })).status()).toBe(301) + + // Same for an article rule when its target is unpublished. + expect((await request.get(`${path}-live`, { maxRedirects: 0 })).status()).toBe(301) + await hc.patch(`/api/v1/help-center/articles/${live.id}`, { data: { publishedAt: null } }) + expect((await request.get(`${path}-live`, { maxRedirects: 0 })).status()).toBe(404) + } +) + +test( + 'HC-A-64 deleting a redirect rule asks first and the path stops redirecting', + { tag: '@nightly' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Rule delete ${marker}`) + await hcArticle(hc, { categoryId: category.id, title: `In ${marker}`, publish: true }) + const api = await personApi(playwright, 'admin') + const path = `/hc/gone/${marker}` + const made = await callServerFn(api, 'createRedirectRuleFn', { + path, + targetType: 'category', + targetId: category.id, + }) + expect(made.ok, made.error).toBe(true) + expect((await request.get(path, { maxRedirects: 0 })).status()).toBe(301) + + const admin = await asPerson('admin') + await admin.goto(`${SETTINGS}?tab=domains-languages`) + const row = admin.getByRole('listitem').filter({ hasText: path }) + const del = row.getByRole('button', { name: 'Delete redirect rule' }) + await waitForHydration(del) + await del.click() + const confirm = admin.getByRole('alertdialog') + await expect(confirm).toContainText('Visitors to the old path will get a not found page') + await confirm.getByRole('button', { name: 'Delete redirect rule' }).click() + await expect(row).toBeHidden() + expect((await request.get(path, { maxRedirects: 0 })).status()).toBe(404) + } +) + +test.describe('workspace-wide help center texts', { tag: '@isolated' }, () => { + test.beforeEach(() => { + test.skip(!ISOLATED, ISOLATED_SKIP) + }) + + test( + 'HC-A-66 the homepage title and description show on the landing page', + { tag: '@core' }, + async ({ asPerson, marker, request }) => { + await withSettings({ help_center_config: {} }, async () => { + const admin = await asPerson('admin') + await admin.goto(SETTINGS) + const title = admin.locator('#homepage-title') + await waitForHydration(title) + const description = admin.locator('#homepage-description') + await title.fill(`Help for ${marker}`) + await description.fill(`Answers about ${marker}`) + await expect + .poll(async () => { + const [row] = await supportDb()`SELECT help_center_config FROM settings LIMIT 1` + const cfg = JSON.parse(String(row.help_center_config)) as Record + return [cfg.homepageTitle, cfg.homepageDescription] + }) + .toEqual([`Help for ${marker}`, `Answers about ${marker}`]) + + const landing = await (await request.get('/hc', { headers: { cookie: 'e2e=1' } })).text() + expect(landing).toContain(`Help for ${marker}`) + expect(landing).toContain(`Answers about ${marker}`) + expect(landing).toMatch(new RegExp(`[^<]*Help for ${marker}`)) + + // A cleared title is not saved; the old one stays after a reload. + await title.fill('') + await admin.waitForTimeout(1_500) + await admin.reload() + await expect(admin.locator('#homepage-title')).toHaveValue(`Help for ${marker}`) + }) + } + ) + + test( + 'HC-A-67 a protocol-relative header link is refused', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B20: helpCenterHeaderLinkUrl accepts anything starting with "/", so //example.com is stored and portal-header.tsx renders it as an internal link', + }, + }, + async ({ playwright, marker }) => { + await withSettings({ help_center_config: {} }, async () => { + const api = await personApi(playwright, 'admin') + const good = await callServerFn(api, 'updateHelpCenterConfigFn', { + headerLinks: [{ label: `Docs ${marker}`, url: '/docs' }], + }) + expect(good.ok, good.error).toBe(true) + const bad = await callServerFn(api, 'updateHelpCenterConfigFn', { + headerLinks: [{ label: `Evil ${marker}`, url: '//example.com' }], + }) + expect(bad.ok).toBe(false) + }) + } + ) +}) diff --git a/apps/web/e2e/tests/help-center/admin-trash.spec.ts b/apps/web/e2e/tests/help-center/admin-trash.spec.ts new file mode 100644 index 0000000000..0b405f8556 --- /dev/null +++ b/apps/web/e2e/tests/help-center/admin-trash.spec.ts @@ -0,0 +1,176 @@ +/** + * Help center admin: deleting articles and categories, the Deleted items view + * and restore. + * + * Journeys: HC-A-26, HC-A-27, HC-A-28. + */ +import type { Page } from '@playwright/test' +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { callServerFn, personApi } from '../../support/server-fns' +import { waitForHydration } from '../../utils/helpers' +import { articlePath, articleRow, hcApi, hcArticle, hcCategory } from '../../product/help-center' + +/** Open a list row's menu (it shows on hover) and choose Delete. */ +async function deleteFromRow(page: Page, title: string) { + const heading = page.getByRole('heading', { name: title }) + await waitForHydration(heading) + await heading.hover() + const row = page.locator('div.group').filter({ has: heading }) + await row.getByRole('button').last().click() + await page.getByRole('menuitem', { name: 'Delete' }).click() +} + +/** A row of the Deleted items view, by the text it shows. */ +function deletedRow(page: Page, name: string) { + return page + .locator('div') + .filter({ hasText: name }) + .filter({ has: page.getByRole('button', { name: 'Restore' }) }) + .last() +} + +test( + 'HC-A-26 deleting an article from the list soft-deletes it and takes it off the public site', + { tag: '@core' }, + async ({ asPerson, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Trash ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Bin me ${marker}`, + publish: true, + }) + const keep = await hcArticle(hc, { categoryId: category.id, title: `Keep me ${marker}` }) + expect((await request.get(articlePath(article))).status()).toBe(200) + + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + await deleteFromRow(admin, article.title) + const confirm = admin.getByRole('alertdialog') + await confirm.getByRole('button', { name: 'Delete' }).click() + await expect(confirm).toBeHidden() + + await expect(admin.getByRole('heading', { name: article.title })).toBeHidden() + await expect(admin.getByRole('heading', { name: keep.title })).toBeVisible() + const row = await articleRow(article.uuid) + expect(row?.deleted_at).not.toBeNull() + expect((await request.get(articlePath(article), { maxRedirects: 0 })).status()).toBe(404) + + // A second delete of the same id is refused. + const api = await personApi(playwright, 'admin') + const again = await callServerFn(api, 'deleteArticleFn', { id: article.id }) + expect(again.ok).toBe(false) + expect(again.code).toBe('ARTICLE_NOT_FOUND') + } +) + +test( + 'HC-A-26 the delete dialogs say a deleted article or category can be restored', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B5: help-center-list.tsx says "permanently deleted" / "the UI provides no restore flow", but both are soft deletes restorable from Deleted items for 30 days', + }, + }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Copy ${marker}`) + const article = await hcArticle(hc, { categoryId: category.id, title: `Copy ${marker}` }) + const admin = await asPerson('admin') + await admin.goto(`/admin/help-center?category=${category.id}`) + + await deleteFromRow(admin, article.title) + const articleConfirm = admin.getByRole('alertdialog') + await expect(articleConfirm).toBeVisible() + await expect(articleConfirm).not.toContainText(/permanently|cannot be undone/i) + await expect(articleConfirm).toContainText(/restore/i) + await articleConfirm.getByRole('button', { name: 'Cancel' }).click() + + const treeRow = admin.getByRole('treeitem').filter({ hasText: category.name }) + await treeRow.hover() + await treeRow.getByRole('button', { name: 'Delete category' }).click() + const categoryConfirm = admin.getByRole('alertdialog') + await expect(categoryConfirm).not.toContainText(/no restore flow|cannot be undone/i) + await expect(categoryConfirm).toContainText(/Deleted items/i) + } +) + +test( + 'HC-A-27 Deleted items lists a deleted article and a deleted category with Restore', + { tag: '@core' }, + async ({ asPerson, marker, playwright }) => { + const hc = await hcApi(playwright) + const gone = await hcCategory(hc, `Gone category ${marker}`) + const home = await hcCategory(hc, `Home ${marker}`) + const article = await hcArticle(hc, { categoryId: home.id, title: `Gone article ${marker}` }) + expect((await hc.delete(`/api/v1/help-center/articles/${article.id}`)).status()).toBe(204) + expect((await hc.delete(`/api/v1/help-center/categories/${gone.id}`)).status()).toBe(204) + + const admin = await asPerson('admin') + // Article performance is on; Deleted items replaces it (one view at a time). + await admin.goto('/admin/help-center?performance=true') + const deletedItems = admin.getByRole('option', { name: 'Deleted items' }) + await waitForHydration(deletedItems) + await deletedItems.click() + await expect(admin.getByRole('heading', { name: 'Deleted items', level: 1 })).toBeVisible() + await expect(admin).toHaveURL(/deleted=true/) + expect(admin.url()).not.toContain('performance=true') + + const categoryRow = deletedRow(admin, gone.name) + await expect(categoryRow).toContainText(/Deleted .*ago|Deleted just now|Deleted now/i) + const articleRowEl = deletedRow(admin, article.title) + await expect(articleRowEl).toBeVisible() + + // Restore from the view brings the article back. + await articleRowEl.getByRole('button', { name: 'Restore' }).click() + await expect.poll(async () => (await articleRow(article.uuid))?.deleted_at).toBeNull() + await expect(admin.getByText(article.title)).toBeHidden() + } +) + +test( + 'HC-A-28 restore brings an article back as it was, within 30 days only', + { tag: '@core' }, + async ({ marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Restore ${marker}`) + const live = await hcArticle(hc, { + categoryId: category.id, + title: `Comes back ${marker}`, + publish: true, + }) + const old = await hcArticle(hc, { categoryId: category.id, title: `Too old ${marker}` }) + const never = await hcArticle(hc, { categoryId: category.id, title: `Never deleted ${marker}` }) + for (const a of [live, old]) { + expect((await hc.delete(`/api/v1/help-center/articles/${a.id}`)).status()).toBe(204) + } + await supportDb()`UPDATE kb_articles SET deleted_at = NOW() - interval '31 days' + WHERE id = ${old.uuid}` + + const api = await personApi(playwright, 'admin') + const restored = await callServerFn<{ publishedAt: string | null }>(api, 'restoreArticleFn', { + id: live.id, + }) + expect(restored.ok, restored.error).toBe(true) + expect(restored.data.publishedAt).not.toBeNull() + expect((await articleRow(live.uuid))?.deleted_at).toBeNull() + // Published before, so public again at once. + expect((await request.get(articlePath(live))).status()).toBe(200) + + const expired = await callServerFn(api, 'restoreArticleFn', { id: old.id }) + expect(expired.code).toBe('RESTORE_EXPIRED') + expect(expired.error).toContain('Articles can only be restored within 30 days of deletion') + expect((await articleRow(old.uuid))?.deleted_at).not.toBeNull() + + const notDeleted = await callServerFn(api, 'restoreArticleFn', { id: never.id }) + expect(notDeleted.code).toBe('VALIDATION_ERROR') + expect(notDeleted.error).toContain('Article is not deleted') + + const unknown = await callServerFn(api, 'restoreArticleFn', { id: generateId('article') }) + expect(unknown.code).toBe('ARTICLE_NOT_FOUND') + } +) diff --git a/apps/web/e2e/tests/help-center/api-rest.spec.ts b/apps/web/e2e/tests/help-center/api-rest.spec.ts new file mode 100644 index 0000000000..006fc507b6 --- /dev/null +++ b/apps/web/e2e/tests/help-center/api-rest.spec.ts @@ -0,0 +1,463 @@ +/** + * Help center REST API (/api/v1/help-center/...): articles, categories, + * authors, permissions and the article feedback endpoint. + * + * Journeys: HC-A-11, HC-A-16, HC-A-70, HC-A-71, HC-A-72, HC-A-73, HC-A-74, + * HC-A-75, HC-A-76, HC-F-07. + */ +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { apiFor, createKey, expectJson, type Wire } from '../../support/api-client' +import { supportEnv } from '../../support/env' +import { SUPPORT_PEOPLE } from '../../support/people' +import { supportDb } from '../../support/db' +import { + adminPrincipalId, + articlePath, + articleRow, + categoryRow, + hcApi, + hcArticle, + hcCategory, + searchWord, + uuidOfTypeId, +} from '../../product/help-center' + +const baseURL = supportEnv().baseUrl +const ARTICLES = '/api/v1/help-center/articles' +const CATEGORIES = '/api/v1/help-center/categories' + +/** Every item of a paginated article list, following the cursor. */ +async function listAll( + api: Awaited<ReturnType<typeof hcApi>>, + query: Record<string, string> +): Promise<{ items: Wire[]; pages: number }> { + const items: Wire[] = [] + let cursor: string | null = null + let pages = 0 + do { + const params = new URLSearchParams({ ...query, ...(cursor ? { cursor } : {}) }) + const body = await expectJson<{ data: Wire[]; meta: Wire }>( + await api.get(`${ARTICLES}?${params}`), + 200 + ) + items.push(...body.data) + pages++ + cursor = body.meta.pagination.hasMore ? body.meta.pagination.cursor : null + } while (cursor && pages < 20) + return { items, pages } +} + +test.describe('articles over REST', () => { + test( + 'HC-A-70 the article list filters by status, category and search and pages by cursor', + { tag: '@core' }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `Listed ${marker}`, { isPublic: false }) + const draftA = await hcArticle(hc, { categoryId: category.id, title: `Draft A ${marker}` }) + const draftB = await hcArticle(hc, { + categoryId: category.id, + title: `Draft B ${word} ${marker}`, + content: '# Heading\n\nSome **bold** text.', + }) + const live = await hcArticle(hc, { + categoryId: category.id, + title: `Live ${marker}`, + publish: true, + }) + + // Drafts only, in this (private) category, one per page. + const drafts = await listAll(hc, { categoryId: category.id, status: 'draft', limit: '1' }) + expect(drafts.items.map((a) => a.id).sort()).toEqual([draftA.id, draftB.id].sort()) + expect(drafts.pages).toBe(2) + + const published = await listAll(hc, { categoryId: category.id, status: 'published' }) + expect(published.items.map((a) => a.id)).toEqual([live.id]) + const all = await listAll(hc, { categoryId: category.id }) + expect(all.items).toHaveLength(3) + + // Each item carries markdown content, counters, category and author. + const b = all.items.find((a) => a.id === draftB.id) + expect(b).toMatchObject({ + title: draftB.title, + publishedAt: null, + viewCount: 0, + helpfulCount: 0, + notHelpfulCount: 0, + category: { id: category.id, slug: category.slug }, + author: { name: SUPPORT_PEOPLE.admin.name }, + }) + expect(b.content).toContain('**bold**') + + // Search ranks within the filters. + const found = await listAll(hc, { categoryId: category.id, search: word }) + expect(found.items.map((a) => a.id)).toEqual([draftB.id]) + + // No key, no list. + const anon = await apiFor(playwright, baseURL, null) + expect((await anon.get(ARTICLES)).status()).toBe(401) + } + ) + + test( + 'HC-A-71 one article by id: drafts are returned, a malformed id is 400, unknown or deleted 404', + { tag: '@core' }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `One ${marker}`) + const draft = await hcArticle(hc, { categoryId: category.id, title: `Got ${marker}` }) + + const got = await expectJson<{ data: Wire }>(await hc.get(`${ARTICLES}/${draft.id}`), 200) + expect(got.data).toMatchObject({ + id: draft.id, + title: draft.title, + publishedAt: null, + category: { id: category.id }, + author: { name: SUPPORT_PEOPLE.admin.name }, + }) + // The retired kb_article_ prefix still resolves. + const alias = draft.id.replace(/^article_/, 'kb_article_') + expect((await hc.get(`${ARTICLES}/${alias}`)).status()).toBe(200) + + expect((await hc.get(`${ARTICLES}/not-an-id`)).status()).toBe(400) + const unknown = await hc.get(`${ARTICLES}/${generateId('article')}`) + expect(unknown.status()).toBe(404) + + expect((await hc.delete(`${ARTICLES}/${draft.id}`)).status()).toBe(204) + expect((await hc.get(`${ARTICLES}/${draft.id}`)).status()).toBe(404) + } + ) + + test( + 'HC-A-72 create: a draft with editor JSON from markdown; field errors; permission', + { tag: '@core' }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Create ${marker}`) + const res = await hc.post(ARTICLES, { + data: { + categoryId: category.id, + title: ` Created ${marker} `, + content: '## Steps\n\n1. One\n2. Two', + description: `About ${marker}`, + slug: `custom-${marker}`, + authorId: adminPrincipalId(), + }, + }) + const { data } = await expectJson<{ data: Wire }>(res, 201) + expect(data).toMatchObject({ + title: `Created ${marker}`, + slug: `custom-${marker}`, + description: `About ${marker}`, + publishedAt: null, + }) + const row = await articleRow(uuidOfTypeId(data.id)) + const json = JSON.stringify(row?.content_json) + expect(json).toContain('"type":"heading"') + expect(json).toContain('"type":"orderedList"') + + // Field errors: no category, empty title or content, long title or description. + const bad = async (body: Record<string, unknown>, field: string) => { + const r = await expectJson<{ error: Wire }>( + await hc.post(ARTICLES, { + data: { categoryId: category.id, title: 'T', content: 'C', ...body }, + }), + 400 + ) + expect(Object.keys(r.error.details?.errors ?? {}), JSON.stringify(r)).toContain(field) + } + await bad({ categoryId: undefined }, 'categoryId') + await bad({ title: '' }, 'title') + await bad({ content: '' }, 'content') + await bad({ title: 'x'.repeat(201) }, 'title') + await bad({ description: 'x'.repeat(301) }, 'description') + + // A key whose person cannot manage the help center cannot create. + const contributor = await apiFor( + playwright, + baseURL, + createKey({ creatorEmail: SUPPORT_PEOPLE.contributor.email }).key + ) + const refused = await contributor.post(ARTICLES, { + data: { categoryId: category.id, title: `Refused ${marker}`, content: 'C' }, + }) + expect(refused.status()).toBe(403) + } + ) + + test( + 'HC-A-11 authors: a key needs an explicit team author; others are refused', + { tag: '@core' }, + async ({ playwright, marker, people }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Authors ${marker}`) + const base = { categoryId: category.id, content: 'C' } + + const noAuthor = await expectJson<{ error: Wire }>( + await hc.post(ARTICLES, { data: { ...base, title: `No author ${marker}` } }), + 400 + ) + expect(noAuthor.error.message).toBe('Service principals must provide an explicit authorId') + + const customer = await expectJson<{ error: Wire }>( + await hc.post(ARTICLES, { + data: { + ...base, + title: `Customer ${marker}`, + authorId: people.people.customer.principalId, + }, + }), + 400 + ) + expect(customer.error.message).toBe('Author must be a team member') + + const unknown = await expectJson<{ error: Wire }>( + await hc.post(ARTICLES, { + data: { + ...base, + title: `Unknown ${marker}`, + authorId: generateId('principal'), + }, + }), + 400 + ) + expect(unknown.error.message).toBe('Author not found') + + const teammate = await expectJson<{ data: Wire }>( + await hc.post(ARTICLES, { + data: { ...base, title: `By Ben ${marker}`, authorId: people.people.agentB.principalId }, + }), + 201 + ) + expect(teammate.data.author).toMatchObject({ + id: people.people.agentB.principalId, + name: SUPPORT_PEOPLE.agentB.name, + }) + const rows = + await supportDb()`SELECT title FROM kb_articles WHERE title LIKE ${`%${marker}%`}` + expect(rows.map((r) => r.title)).toEqual([`By Ben ${marker}`]) + } + ) + + test( + 'HC-A-73 update: fields, an emptied description, author, category and publish state', + { tag: '@core' }, + async ({ playwright, marker, people }) => { + const hc = await hcApi(playwright) + const from = await hcCategory(hc, `Patch from ${marker}`) + const to = await hcCategory(hc, `Patch to ${marker}`) + const article = await hcArticle(hc, { + categoryId: from.id, + title: `Patched ${marker}`, + description: `Was described ${marker}`, + }) + const patch = (data: Record<string, unknown>) => + hc.patch(`${ARTICLES}/${article.id}`, { data }) + + // A bad author refuses the whole update: the title does not change. + const refused = await patch({ + title: `Never ${marker}`, + authorId: people.people.customer.principalId, + }) + expect(refused.status()).toBe(400) + expect((await articleRow(article.uuid))?.title).toBe(article.title) + + const updated = await expectJson<{ data: Wire }>( + await patch({ + title: `Renamed ${marker}`, + description: '', + categoryId: to.id, + authorId: people.people.agentB.principalId, + publishedAt: '2001-01-01T00:00:00.000Z', + }), + 200 + ) + expect(updated.data).toMatchObject({ + title: `Renamed ${marker}`, + description: null, + category: { id: to.id }, + author: { id: people.people.agentB.principalId }, + }) + // Any datetime publishes now; the value sent is not stored. + const publishedAt = new Date(updated.data.publishedAt as string).getTime() + expect(Math.abs(publishedAt - Date.now())).toBeLessThan(60_000) + + const unpublished = await expectJson<{ data: Wire }>(await patch({ publishedAt: null }), 200) + expect(unpublished.data.publishedAt).toBeNull() + expect((await articleRow(article.uuid))?.published_at).toBeNull() + + // An empty body changes nothing. + const same = await expectJson<{ data: Wire }>(await patch({}), 200) + expect(same.data).toMatchObject({ title: `Renamed ${marker}`, publishedAt: null }) + } + ) + + test( + 'HC-A-74 delete: 204 and a soft delete, then 404', + { tag: '@core' }, + async ({ playwright, marker, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Delete ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Deleted ${marker}`, + publish: true, + }) + expect((await request.get(articlePath(article))).status()).toBe(200) + + expect((await hc.delete(`${ARTICLES}/${article.id}`)).status()).toBe(204) + expect((await articleRow(article.uuid))?.deleted_at).not.toBeNull() + expect((await request.get(articlePath(article), { maxRedirects: 0 })).status()).toBe(404) + const listed = await listAll(hc, { categoryId: category.id }) + expect(listed.items).toEqual([]) + + expect((await hc.delete(`${ARTICLES}/${article.id}`)).status()).toBe(404) + } + ) + + test( + 'HC-A-16 a whitespace-only title or category name is refused on update', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B13: updateArticleSchema / updateCategorySchema check min(1) before trimming; the services store an empty string', + }, + }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Blank ${marker}`) + const article = await hcArticle(hc, { categoryId: category.id, title: `Blank ${marker}` }) + + const title = await hc.patch(`${ARTICLES}/${article.id}`, { data: { title: ' ' } }) + const name = await hc.patch(`${CATEGORIES}/${category.id}`, { data: { name: ' ' } }) + // Whatever the answers, nothing may be stored blank. + expect((await articleRow(article.uuid))?.title).toBe(article.title) + expect((await categoryRow(category.uuid))?.name).toBe(category.name) + expect(title.status()).toBe(400) + expect(name.status()).toBe(400) + } + ) +}) + +test.describe('categories over REST', () => { + test( + 'HC-A-75 categories: create, read, update, list with counts, delete cascades', + { tag: '@core' }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const created = await expectJson<{ data: Wire }>( + await hc.post(CATEGORIES, { + data: { + name: `Parent ${marker}`, + description: 'Top', + isPublic: false, + icon: 'book', + position: 3, + }, + }), + 201 + ) + expect(created.data).toMatchObject({ + name: `Parent ${marker}`, + description: 'Top', + isPublic: false, + icon: 'book', + position: 3, + parentId: null, + }) + const parentId = created.data.id as string + const child = await hcCategory(hc, `Child ${marker}`, { parentId }) + const article = await hcArticle(hc, { categoryId: child.id, title: `Under child ${marker}` }) + + const got = await expectJson<{ data: Wire }>(await hc.get(`${CATEGORIES}/${parentId}`), 200) + expect(got.data.name).toBe(`Parent ${marker}`) + + const patched = await expectJson<{ data: Wire }>( + await hc.patch(`${CATEGORIES}/${parentId}`, { + data: { name: `Renamed parent ${marker}`, description: null }, + }), + 200 + ) + expect(patched.data).toMatchObject({ name: `Renamed parent ${marker}`, description: null }) + + // The list includes private categories, with article counts. + const list = await expectJson<{ data: Wire[] }>(await hc.get(CATEGORIES), 200) + const listedChild = list.data.find((c) => c.id === child.id) + expect(list.data.some((c) => c.id === parentId)).toBe(true) + expect(listedChild?.articleCount).toBe(1) + + // A category cannot be its own descendant's child. + const cycle = await hc.patch(`${CATEGORIES}/${parentId}`, { data: { parentId: child.id } }) + expect(cycle.status()).toBe(400) + + // Delete cascades to the sub-category and its article. + expect((await hc.delete(`${CATEGORIES}/${parentId}`)).status()).toBe(204) + expect((await categoryRow(child.uuid))?.deleted_at).not.toBeNull() + expect((await articleRow(article.uuid))?.deleted_at).not.toBeNull() + expect((await hc.get(`${CATEGORIES}/${parentId}`)).status()).toBe(404) + } + ) + + test( + 'HC-A-76 a key without help_center.manage cannot read drafts or private categories', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B3: REST GET article list, article, category list and category call withApiKeyAuth(request) with no permission and read at team scope', + }, + }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const hidden = await hcCategory(hc, `Hidden ${marker}`, { isPublic: false }) + const draft = await hcArticle(hc, { categoryId: hidden.id, title: `Secret ${marker}` }) + const contributor = await apiFor( + playwright, + baseURL, + createKey({ creatorEmail: SUPPORT_PEOPLE.contributor.email }).key + ) + + const one = await contributor.get(`${ARTICLES}/${draft.id}`) + const list = await contributor.get(`${ARTICLES}?status=draft&categoryId=${hidden.id}`) + const cat = await contributor.get(`${CATEGORIES}/${hidden.id}`) + const cats = await contributor.get(CATEGORIES) + const text = [await one.text(), await list.text(), await cat.text(), await cats.text()] + for (const body of text) { + expect(body).not.toContain(`Secret ${marker}`) + expect(body).not.toContain(`Hidden ${marker}`) + } + expect(one.status()).toBe(403) + } + ) +}) + +test.describe('feedback over REST', () => { + test( + 'HC-F-07 the feedback endpoint records a vote and moves the counters', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Votes ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Voted ${marker}`, + publish: true, + }) + const res = await hc.post(`${ARTICLES}/${article.id}/feedback`, { data: { helpful: true } }) + expect(res.status()).toBeLessThan(300) + await expect.poll(async () => (await articleRow(article.uuid))?.helpful_count).toBe(1) + const bad = await hc.post(`${ARTICLES}/${article.id}/feedback`, { data: { helpful: 'yes' } }) + expect(bad.status()).toBe(400) + const anon = await apiFor(playwright, baseURL, null) + const refused = await anon.post(`${ARTICLES}/${article.id}/feedback`, { + data: { helpful: true }, + }) + expect(refused.status()).toBe(401) + } + ) +}) diff --git a/apps/web/e2e/tests/help-center/translations.spec.ts b/apps/web/e2e/tests/help-center/translations.spec.ts new file mode 100644 index 0000000000..ca4f1ac98a --- /dev/null +++ b/apps/web/e2e/tests/help-center/translations.spec.ts @@ -0,0 +1,238 @@ +/** + * Help center languages and article translations. The enabled language list + * is workspace-wide (help_center_config.locales), so every test here is + * `@isolated` and sets it with withSettings. + * + * Journeys: HC-A-48, HC-A-49, HC-A-51, HC-A-52, HC-A-53. + */ +import type { Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { supportDb } from '../../support/db' +import { withSettings } from '../../support/isolated-settings' +import { waitForHydration } from '../../utils/helpers' +import { + articlePath, + editorPath, + hcApi, + hcArticle, + hcCategory, + type HcArticle, +} from '../../product/help-center' + +const FRENCH = { + help_center_config: { + 'locales.additional': ['fr'], + 'locales.chrome.fr': { + homepageTitle: 'Comment pouvons-nous aider ?', + homepageDescription: '', + searchPlaceholder: '', + }, + }, +} + +/** What a signed-out visitor gets (a cookie skips the shared cache). */ +async function visit(page: Page, path: string) { + const res = await page.request.get(path, { maxRedirects: 0, headers: { cookie: 'e2e=1' } }) + return { status: res.status(), text: await res.text() } +} + +async function translationRow(article: HcArticle, locale: string) { + const [row] = await supportDb()`SELECT * FROM kb_article_translations + WHERE article_id = ${article.uuid} AND locale = ${locale}` + return row +} + +/** Open an article's Translations dialog on French. */ +async function openFrench(admin: Page, article: HcArticle) { + await admin.goto(editorPath(article)) + const manage = admin.getByRole('button', { name: 'Manage' }) + await waitForHydration(manage) + await manage.click() + const dialog = admin.getByRole('dialog', { name: 'Translations' }) + await dialog.getByRole('combobox').click() + await admin.getByRole('option', { name: 'Français' }).click() + await expect(dialog.locator('#translation-title')).not.toHaveValue('') + return dialog +} + +test.describe('help center languages', { tag: '@isolated' }, () => { + test.beforeEach(() => { + test.skip(!ISOLATED, ISOLATED_SKIP) + }) + + test( + 'HC-A-48 adding a language stores it with default texts and opens /hc/<locale>', + { tag: '@core' }, + async ({ asPerson, page }) => { + await withSettings({ help_center_config: { 'locales.additional': [] } }, async () => { + expect((await visit(page, '/hc/de')).status).toBe(404) + const admin = await asPerson('admin') + await admin.goto('/admin/settings/help-center?tab=domains-languages') + const add = admin.getByRole('combobox').filter({ hasText: 'Add a language…' }) + await waitForHydration(add) + await add.click() + await admin.getByRole('option', { name: 'Deutsch' }).click() + await admin.getByRole('button', { name: 'Add', exact: true }).click() + await expect(admin.getByRole('button', { name: 'Remove Deutsch' })).toBeVisible() + + const [row] = await supportDb()`SELECT help_center_config FROM settings LIMIT 1` + const locales = ( + JSON.parse(String(row.help_center_config)) as { + locales: { additional: string[]; chrome: Record<string, unknown> } + } + ).locales + expect(locales.additional).toEqual(['de']) + expect(locales.chrome.de).toMatchObject({ homepageTitle: 'How can we help?' }) + expect((await visit(page, '/hc/de')).status).toBe(200) + }) + } + ) + + test( + 'HC-A-49 removing a language takes its pages offline but keeps its translations', + { tag: '@core' }, + async ({ asPerson, marker, page, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Langs ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Language off ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + await supportDb()`INSERT INTO kb_article_translations + (id, article_id, locale, title, content, status, created_at, updated_at) + VALUES (gen_random_uuid(), ${article.uuid}, 'fr', ${`Langue ${marker}`}, 'Texte.', + 'published', NOW(), NOW())` + const fr = articlePath(article, 'fr') + expect((await visit(page, fr)).status).toBe(200) + + const admin = await asPerson('admin') + await admin.goto('/admin/settings/help-center?tab=domains-languages') + const remove = admin.getByRole('button', { name: 'Remove Français' }) + await waitForHydration(remove) + await remove.click() + await expect(remove).toBeHidden() + + expect((await visit(page, fr)).status).toBe(404) + expect((await visit(page, '/hc/fr')).status).toBe(404) + expect((await translationRow(article, 'fr'))?.title).toBe(`Langue ${marker}`) + }) + } + ) + + test( + 'HC-A-51 a translation opens seeded with the article and saves as a draft', + { tag: '@core' }, + async ({ asPerson, marker, page, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Translate ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Original ${marker}`, + description: `Original summary ${marker}`, + content: `Original body ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + const admin = await asPerson('admin') + const dialog = await openFrench(admin, article) + await expect(dialog).toContainText('Untranslated') + await expect(dialog.locator('#translation-title')).toHaveValue(article.title) + await expect(dialog.locator('#translation-description')).toHaveValue( + `Original summary ${marker}` + ) + await expect(dialog.locator('#translation-content')).toHaveValue( + new RegExp(`Original body ${marker}`) + ) + + await dialog.locator('#translation-title').fill(`Traduit ${marker}`) + await dialog.locator('#translation-content').fill(`Corps traduit ${marker}`) + await dialog.getByRole('button', { name: 'Save draft' }).click() + await expect(dialog).toContainText('Draft') + await expect.poll(async () => (await translationRow(article, 'fr'))?.status).toBe('draft') + expect((await translationRow(article, 'fr'))?.title).toBe(`Traduit ${marker}`) + // A draft translation is not public: the French URL is a 404. + expect((await visit(page, articlePath(article, 'fr'))).status).toBe(404) + }) + } + ) + + test( + 'HC-A-52 publish, unpublish and delete a translation', + { tag: '@core' }, + async ({ asPerson, marker, page, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Publish fr ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Base ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + const admin = await asPerson('admin') + const dialog = await openFrench(admin, article) + await dialog.locator('#translation-title').fill(`Publié ${marker}`) + await dialog.getByRole('button', { name: 'Save draft' }).click() + await expect.poll(async () => (await translationRow(article, 'fr'))?.status).toBe('draft') + + await dialog.getByRole('button', { name: 'Publish' }).click() + await expect + .poll(async () => (await translationRow(article, 'fr'))?.status) + .toBe('published') + const live = await visit(page, articlePath(article, 'fr')) + expect(live.status).toBe(200) + expect(live.text).toContain(`Publié ${marker}`) + + await dialog.getByRole('button', { name: 'Unpublish' }).click() + await expect.poll(async () => (await translationRow(article, 'fr'))?.status).toBe('draft') + expect((await visit(page, articlePath(article, 'fr'))).status).toBe(404) + + await dialog.getByRole('button', { name: 'Delete translation' }).click() + await expect.poll(async () => (await translationRow(article, 'fr')) ?? null).toBeNull() + await expect(dialog).toContainText('Untranslated') + }) + } + ) + + test( + 'HC-A-53 Save draft on a published translation does not change the live page', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B9: upsertArticleTranslation never touches status, so "Save draft" on a published translation publishes the edit at once', + }, + }, + async ({ asPerson, marker, page, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Quirk ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Quirk ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + await supportDb()`INSERT INTO kb_article_translations + (id, article_id, locale, title, content, status, created_at, updated_at) + VALUES (gen_random_uuid(), ${article.uuid}, 'fr', ${`En ligne ${marker}`}, 'Texte.', + 'published', NOW(), NOW())` + const admin = await asPerson('admin') + const dialog = await openFrench(admin, article) + await expect(dialog.locator('#translation-title')).toHaveValue(`En ligne ${marker}`) + await dialog.locator('#translation-title').fill(`Brouillon ${marker}`) + await dialog.getByRole('button', { name: 'Save draft' }).click() + await expect + .poll(async () => { + const row = await translationRow(article, 'fr') + return row?.title === `Brouillon ${marker}` || row?.status === 'draft' + }) + .toBe(true) + const live = await visit(page, articlePath(article, 'fr')) + expect(live.text).not.toContain(`Brouillon ${marker}`) + }) + } + ) +})