diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index d9d8a48608..015c373943 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -214,3 +214,46 @@ owner: unassigned, review by: 2026-12-03 for every entry. 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. +- `help-center/public-pages.spec.ts` › HC-P-33 reading the canonical article + page counts a view (HC-B1). `view_count` is incremented only in + `getPublicArticleBySlug` (`domains/help-center/help-center.article.service.ts`), + which serves the legacy URLs, the widget's slug opens, embed cards and the + admin View button. The canonical `/hc//articles/-` page + uses `getPublicArticleByUrlId`, which never counts, so the list "N views", + the performance table and Popular articles miss real reads. Fix: count in + the canonical page's loader (and decide whether previews/embeds count). +- `help-center/feedback.spec.ts` › HC-F-05 a signed-out visitor who flips Yes + to No is counted once (HC-B2). `recordArticleFeedback` + (`domains/help-center/help-center.article-feedback.service.ts`) looks up an + existing vote only when there is a principal; with none it always inserts + (null principals never collide on the unique index), so Yes then No adds + one helpful and one not-helpful vote, and every request adds another. Fix: + have the portal mint an anonymous session before voting (as the widget + does), or accept the previous `feedbackId` from the client and flip that + row; add a rate limit either way. +- `help-center/public-access.spec.ts` › HC-P-04 the landing card counts only + articles the visitor can open (HC-B14). `listPublicCategories` + (`domains/help-center/help-center.category.service.ts`) rolls + `recursivePublishedArticleCount` up through every descendant without + checking that the descendant category is public or that article audiences + admit the viewer, so a card shows "5 articles" where one can be opened (and + a category with only hidden content is listed at all). Fix: compute the + roll-up with the same visibility predicate the collection page uses + (`helpCenterVisibilityConditions` for the viewer). +- `help-center/widget.spec.ts` › HC-W-10 the first widget vote of a fresh + visitor confirms it (new bug, `@isolated`). The vote is stored against the + freshly minted session, but the footer + (`components/widget/widget-article-footer.tsx`) still says "Was this + helpful?" and no button is pressed. `cast` calls `ensureSession()` before + the write; minting the session changes the widget identity, which appears + to remount the article view (session-keyed queries) and drop the local + `vote` state. Root cause unconfirmed. Fix: keep the vote state above the + remount (or key it by article), or mint the session without remounting. +- `help-center/public-locales.spec.ts` › HC-P-27 an untranslated article has + no French page, and related links on a French page work (HC-B26; + `@isolated`). `getPublicArticlePageFn` (`lib/server/functions/help-center.ts`) + loads related articles without the page language, so a French article page + lists English titles linking to `/hc/fr/articles/-`, which 404 + when that article has no published French translation. Fix: load related + articles for the locale (translated only), or link untranslated ones to the + default-language URL. diff --git a/apps/web/e2e/tests/help-center/ask-ai.spec.ts b/apps/web/e2e/tests/help-center/ask-ai.spec.ts new file mode 100644 index 0000000000..d82664c366 --- /dev/null +++ b/apps/web/e2e/tests/help-center/ask-ai.spec.ts @@ -0,0 +1,160 @@ +/** + * Ask AI on the public help center (/api/widget/kb-ask): grounded answers, + * misses that never reach the model, and what the model is shown. + * + * Journeys: HC-S-10, HC-S-11, HC-S-12, HC-S-17. + * + * Current code skips the model when retrieval finds no article (HC-S-11); + * these tests pin that. Rules for the fake AI are keyed on the marker, which + * reaches the prompt through the retrieved article's body. + */ +import type { APIRequestContext } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { clientIp } from '../../support/api-client' +import { fakeAi } from '../../support/fake-ai-client' +import { waitForHydration } from '../../utils/helpers' +import { articlePath, hcApi, hcArticle, hcCategory, searchWord } from '../../product/help-center' + +const MISS = "I couldn't find a reliable answer to that in the help articles" + +/** Ask kb-ask one question as a signed-out visitor; returns the raw stream text. */ +async function ask(request: APIRequestContext, question: string): Promise { + const res = await request.post('/api/widget/kb-ask', { + headers: { 'x-e2e-client-ip': clientIp() }, + data: { + threadId: `t-${Date.now()}`, + runId: `r-${Date.now()}`, + messages: [{ id: 'm1', role: 'user', content: question }], + tools: [], + context: [], + state: {}, + forwardedProps: {}, + }, + }) + const text = await res.text() + expect(res.status(), text.slice(0, 300)).toBe(200) + return text +} + +test.afterEach(async ({ marker }) => { + await fakeAi.clear(marker) +}) + +test( + 'HC-S-10 Ask AI on /hc streams a grounded answer citing the article', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `Ask ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Pairing the ${word} remote`, + content: `To pair the ${word} remote, hold the blue button for five seconds. ${marker}`, + publish: true, + }) + const answer = `${marker} hold the blue button for five seconds` + await fakeAi.script({ + marker, + json: { kind: 'grounded', answer: `${answer} [1].`, sources: [{ articleId: '1' }] }, + }) + await page.context().setExtraHTTPHeaders({ 'x-e2e-client-ip': clientIp() }) + await page.goto('/hc') + const box = page.locator('#hc-search') + await waitForHydration(box) + await expect(box).toHaveAttribute('placeholder', /Ask AI/) + await box.fill(`How do I pair the ${word} remote?`) + await page.getByRole('button', { name: 'Use AI to answer your question in seconds' }).click() + await expect(page.getByText(answer, { exact: false })).toBeVisible({ timeout: 20_000 }) + const source = page.getByRole('button', { name: `1. ${article.title}` }) + await expect(source).toBeVisible() + await source.click() + await expect(page).toHaveURL(new RegExp(`${articlePath(article)}$`)) + } +) + +test( + 'HC-S-11 a question nothing in the help center matches never reaches the model', + { tag: '@core' }, + async ({ request }) => { + const nonsense = `${searchWord()} ${searchWord()}` + const text = await ask(request, nonsense) + expect(text).toContain(MISS) + expect(await fakeAi.requests({ contains: nonsense, endpoint: 'chat' })).toEqual([]) + } +) + +test( + 'HC-S-12 a declared miss keeps its words; a grounded answer citing nothing valid becomes the miss', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `No answer ${marker}`) + await hcArticle(hc, { + categoryId: category.id, + title: `Billing ${word} cycles`, + content: `Invoices go out monthly. ${marker}`, + publish: true, + }) + await fakeAi.script({ + marker, + json: { kind: 'no_answer', answer: `Nothing on that ${marker}`, sources: [] }, + }) + const declined = await ask(request, `Billing ${word} cycles`) + // A declared miss keeps the model's own words and cites nothing. + expect(declined).toContain(`Nothing on that ${marker}`) + expect(declined).toContain('no_answer') + expect(await fakeAi.requests({ contains: marker, endpoint: 'chat' })).not.toEqual([]) + + await fakeAi.clear(marker) + await fakeAi.script({ + marker, + json: { kind: 'grounded', answer: `Made up ${marker} [7].`, sources: [{ articleId: '7' }] }, + }) + const uncited = await ask(request, `Billing ${word} cycles`) + expect(uncited).toContain(MISS) + } +) + +test( + 'HC-S-17 the model is shown only articles the visitor may read', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const secret = searchWord() + const open = await hcCategory(hc, `Readable ${marker}`) + const closed = await hcCategory(hc, `Unreadable ${marker}`, { isPublic: false }) + await hcArticle(hc, { + categoryId: open.id, + title: `Resetting the ${word} hub`, + content: `Press reset on the ${word} hub. ${marker}`, + publish: true, + }) + await hcArticle(hc, { + categoryId: closed.id, + title: `Resetting the ${word} hub internally`, + content: `Internal only ${secret}. ${marker}`, + publish: true, + }) + await hcArticle(hc, { + categoryId: open.id, + title: `Resetting the ${word} hub draft`, + content: `Draft only ${secret}. ${marker}`, + }) + await fakeAi.script({ + marker, + json: { + kind: 'grounded', + answer: `Press reset ${marker} [1].`, + sources: [{ articleId: '1' }], + }, + }) + const text = await ask(request, `How do I reset the ${word} hub?`) + expect(text).toContain(`Press reset ${marker}`) + const prompts = await fakeAi.requests({ contains: marker, endpoint: 'chat' }) + expect(prompts.length).toBeGreaterThan(0) + expect(await fakeAi.requests({ contains: secret, endpoint: 'chat' })).toEqual([]) + } +) diff --git a/apps/web/e2e/tests/help-center/feedback.spec.ts b/apps/web/e2e/tests/help-center/feedback.spec.ts new file mode 100644 index 0000000000..f75f750c50 --- /dev/null +++ b/apps/web/e2e/tests/help-center/feedback.spec.ts @@ -0,0 +1,186 @@ +/** + * Article feedback on the public help center: helpful and unhelpful votes, + * reasons, signed-in vote changes and signed-out de-duplication. + * + * Journeys: HC-F-01, HC-F-02, HC-F-03, HC-F-04, HC-F-05. + */ +import type { Page } from '@playwright/test' +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { supportEnv } from '../../support/env' +import { callServerFn } from '../../support/server-fns' +import { mintCustomer, portalContext } from '../../support/widget-portal' +import { waitForHydration } from '../../utils/helpers' +import { + articlePath, + articleRow, + hcApi, + hcArticle, + hcCategory, + type HcArticle, +} from '../../product/help-center' + +async function seed(playwright: Parameters[0], marker: string): Promise { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Feedback ${marker}`) + return hcArticle(hc, { categoryId: category.id, title: `Rated ${marker}`, publish: true }) +} + +async function counts(article: HcArticle) { + const row = await articleRow(article.uuid) + return { helpful: row?.helpful_count, notHelpful: row?.not_helpful_count } +} + +async function feedbackRows(article: HcArticle) { + return supportDb()`SELECT id, principal_id, helpful, reason FROM kb_article_feedback + WHERE article_id = ${article.uuid} ORDER BY created_at` +} + +/** The feedback card's Yes/No, once the page has hydrated. */ +async function vote(page: Page, answer: 'Yes' | 'No') { + const button = page.getByRole('button', { name: answer, exact: true }) + await waitForHydration(button) + await button.click() +} + +test( + 'HC-F-01 a visitor marks an article helpful once', + { tag: '@smoke' }, + async ({ page, marker, playwright }) => { + const article = await seed(playwright, marker) + await page.goto(articlePath(article)) + await expect(page.getByText('Your feedback shapes what we write next.')).toBeVisible() + const recorded = page.waitForResponse((r) => r.url().includes('/_serverFn/')) + await vote(page, 'Yes') + await recorded + await expect(page.getByText('Thanks, glad it landed.')).toBeVisible() + await expect.poll(() => counts(article)).toEqual({ helpful: 1, notHelpful: 0 }) + const rows = await feedbackRows(article) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ helpful: true, principal_id: null }) + + // Pressing Yes again sends nothing. + await page.getByRole('button', { name: 'Yes', exact: true }).click() + await page.waitForTimeout(500) + expect(await feedbackRows(article)).toHaveLength(1) + } +) + +test( + 'HC-F-02 Not helpful asks for an optional reason and sends it once', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const article = await seed(playwright, marker) + await page.goto(articlePath(article)) + await vote(page, 'No') + await expect(page.getByText("Noted. We'll revisit this article.")).toBeVisible() + await expect.poll(() => counts(article)).toEqual({ helpful: 0, notHelpful: 1 }) + + const box = page.getByPlaceholder('Optional, but it tells us what to fix.') + const send = page.getByRole('button', { name: 'Send' }) + await expect(send).toBeDisabled() + await box.fill(' ') + await expect(send).toBeDisabled() + await expect(box).toHaveAttribute('maxlength', '1000') + await box.fill(`Missing the export steps ${marker}`) + await send.click() + await expect( + page.getByText('Thanks. That goes to whoever maintains this article.') + ).toBeVisible() + await expect(box).toBeHidden() + await expect + .poll(async () => (await feedbackRows(article))[0]?.reason) + .toBe(`Missing the export steps ${marker}`) + } +) + +test( + 'HC-F-03 a reason is refused when blank, too long, second, on a helpful vote or unknown', + { tag: '@core' }, + async ({ marker, playwright }) => { + const article = await seed(playwright, marker) + const anon = await playwright.request.newContext({ baseURL: supportEnv().baseUrl }) + const voteFn = (helpful: boolean) => + callServerFn<{ feedbackId: string }>(anon, 'recordArticleFeedbackFn', { + articleId: article.id, + helpful, + }) + const reason = (feedbackId: string, text: string) => + callServerFn(anon, 'submitArticleFeedbackReasonFn', { feedbackId, reason: text }) + + const no = await voteFn(false) + expect(no.ok, no.error).toBe(true) + const yes = await voteFn(true) + expect(yes.ok, yes.error).toBe(true) + + expect((await reason(no.data.feedbackId, ' ')).ok).toBe(false) + expect((await reason(no.data.feedbackId, 'x'.repeat(1001))).ok).toBe(false) + const first = await reason(no.data.feedbackId, `First ${marker}`) + expect(first.ok, first.error).toBe(true) + const second = await reason(no.data.feedbackId, `Second ${marker}`) + expect(second.code).toBe('FEEDBACK_REASON_UNAVAILABLE') + expect((await reason(yes.data.feedbackId, `On yes ${marker}`)).code).toBe( + 'FEEDBACK_REASON_UNAVAILABLE' + ) + expect((await reason(generateId('kb_article_feedback'), 'x')).code).toBe( + 'FEEDBACK_REASON_UNAVAILABLE' + ) + const reasons = (await feedbackRows(article)).map((r) => r.reason).filter(Boolean) + expect(reasons).toEqual([`First ${marker}`]) + } +) + +test( + 'HC-F-04 a signed-in user has one vote that moves between the counters', + { tag: '@core' }, + async ({ browser, marker, playwright, customerEmail }) => { + const article = await seed(playwright, marker) + const customer = await mintCustomer({ email: customerEmail }) + const context = await portalContext(browser, customer) + const page = await context.newPage() + await page.goto(articlePath(article)) + await vote(page, 'Yes') + await expect.poll(() => counts(article)).toEqual({ helpful: 1, notHelpful: 0 }) + await page.getByRole('button', { name: 'No', exact: true }).click() + await expect.poll(() => counts(article)).toEqual({ helpful: 0, notHelpful: 1 }) + + // After a reload the page forgets the vote, but the server still keeps one. + await page.reload() + await vote(page, 'No') + await expect(page.getByText("Noted. We'll revisit this article.")).toBeVisible() + const again = await callServerFn(context.request, 'recordArticleFeedbackFn', { + articleId: article.id, + helpful: true, + }) + expect(again.ok, again.error).toBe(true) + await expect.poll(() => counts(article)).toEqual({ helpful: 1, notHelpful: 0 }) + const rows = await feedbackRows(article) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ helpful: true, principal_id: customer.principalUuid }) + await context.close() + } +) + +test( + 'HC-F-05 a signed-out visitor who flips Yes to No is counted once', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B2: recordArticleFeedback skips the existing-vote lookup when there is no principal and always inserts, so a flip adds one helpful and one not-helpful vote', + }, + }, + async ({ page, marker, playwright }) => { + const article = await seed(playwright, marker) + await page.goto(articlePath(article)) + await vote(page, 'Yes') + await expect.poll(() => counts(article)).toEqual({ helpful: 1, notHelpful: 0 }) + await page.getByRole('button', { name: 'No', exact: true }).click() + await expect(page.getByText("Noted. We'll revisit this article.")).toBeVisible() + await page.waitForTimeout(1_000) + const c = await counts(article) + expect((c.helpful as number) + (c.notHelpful as number)).toBe(1) + } +) diff --git a/apps/web/e2e/tests/help-center/public-access.spec.ts b/apps/web/e2e/tests/help-center/public-access.spec.ts new file mode 100644 index 0000000000..54a758f11b --- /dev/null +++ b/apps/web/e2e/tests/help-center/public-access.spec.ts @@ -0,0 +1,218 @@ +/** + * Who sees what on the public help center: hidden content, segment gates on + * articles and categories, and the counts on the landing page. + * + * Journeys: HC-P-04, HC-P-14, HC-P-16, HC-A-22, HC-A-35. + */ +import type { Browser, Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { mintCustomer, portalPage } from '../../support/widget-portal' +import { + articlePath, + collectionPath, + gateToSegments, + hcApi, + hcArticle, + hcCategory, + hcSegment, +} from '../../product/help-center' + +const FRESH = { headers: { cookie: 'e2e=1' }, maxRedirects: 0 } + +/** A signed-in portal customer of this test, optionally in a segment of its own. */ +async function member(browser: Browser, marker: string, email: string, inSegment: boolean) { + const customer = await mintCustomer({ email }) + const segment = await hcSegment(marker, inSegment ? [customer.principalUuid] : []) + const page = await portalPage(browser, customer) + return { customer, segment, page } +} + +async function statusFor(page: Page, path: string) { + return (await page.request.get(path, { maxRedirects: 0 })).status() +} + +test( + 'HC-P-14 hidden articles and collections are the same 404 as a missing page', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const open = await hcCategory(hc, `Open ${marker}`) + const closed = await hcCategory(hc, `Closed ${marker}`, { isPublic: false }) + const draft = await hcArticle(hc, { categoryId: open.id, title: `Draft ${marker}` }) + const deleted = await hcArticle(hc, { + categoryId: open.id, + title: `Deleted ${marker}`, + publish: true, + }) + await hc.delete(`/api/v1/help-center/articles/${deleted.id}`) + const privateDoc = await hcArticle(hc, { + categoryId: closed.id, + title: `Private ${marker}`, + publish: true, + }) + const gated = await hcArticle(hc, { + categoryId: open.id, + title: `Gated ${marker}`, + publish: true, + }) + await gateToSegments({ kind: 'article', uuid: gated.uuid }, [(await hcSegment(marker)).id]) + await hcArticle(hc, { categoryId: open.id, title: `Visible ${marker}`, publish: true }) + + const missing = await request.get('/hc/en/articles/987654321-missing', FRESH) + expect(missing.status()).toBe(404) + const missingTitle = (await missing.text()).match(/([^<]*)<\/title>/)?.[1] + for (const a of [draft, deleted, privateDoc, gated]) { + const res = await request.get(articlePath(a), FRESH) + const html = await res.text() + expect(res.status(), a.title).toBe(404) + // The URL (and so the slug) is echoed back; the title and body are not. + expect(html, a.title).not.toContain(a.title) + expect(html, a.title).not.toContain(`Body of ${a.title}`) + expect(html.match(/<title>([^<]*)<\/title>/)?.[1], a.title).toBe(missingTitle) + } + const closedPage = await request.get(collectionPath(closed), FRESH) + expect(closedPage.status()).toBe(404) + expect(await closedPage.text()).not.toContain(closed.name) + } +) + +test( + 'HC-A-35 a segment-gated category is open only to signed-in members of the segment', + { tag: '@core' }, + async ({ browser, asPerson, request, marker, playwright, customerEmail }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Members ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Members only ${marker}`, + publish: true, + }) + const inside = await member(browser, marker, customerEmail, true) + const outside = await member(browser, `${marker}-o`, `out-${customerEmail}`, false) + await gateToSegments({ kind: 'category', uuid: category.uuid }, [inside.segment.id]) + + expect((await request.get(collectionPath(category), FRESH)).status()).toBe(404) + expect((await request.get(articlePath(article), FRESH)).status()).toBe(404) + expect(await statusFor(outside.page, articlePath(article))).toBe(404) + + await inside.page.goto(collectionPath(category)) + await expect(inside.page.getByRole('heading', { level: 1, name: category.name })).toBeVisible() + await inside.page.goto(articlePath(article)) + await expect(inside.page.getByRole('heading', { level: 1, name: article.title })).toBeVisible() + + // Team members bypass the segment gate. + const admin = await asPerson('admin') + expect(await statusFor(admin, articlePath(article))).toBe(200) + } +) + +test( + 'HC-A-22 an article restricted to a segment is hidden from everyone else, its category stays open', + { tag: '@core' }, + async ({ browser, request, marker, playwright, customerEmail }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Audience ${marker}`) + const restricted = await hcArticle(hc, { + categoryId: category.id, + title: `Restricted ${marker}`, + publish: true, + }) + const open = await hcArticle(hc, { + categoryId: category.id, + title: `Everyone ${marker}`, + publish: true, + }) + const inside = await member(browser, marker, customerEmail, true) + await gateToSegments({ kind: 'article', uuid: restricted.uuid }, [inside.segment.id]) + + expect((await request.get(articlePath(restricted), FRESH)).status()).toBe(404) + const collection = await request.get(collectionPath(category), FRESH) + expect(collection.status()).toBe(200) + const html = await collection.text() + expect(html).toContain(open.title) + expect(html).not.toContain(restricted.title) + + await inside.page.goto(collectionPath(category)) + await expect( + inside.page.getByRole('link', { name: new RegExp(restricted.title) }) + ).toBeVisible() + expect(await statusFor(inside.page, articlePath(restricted))).toBe(200) + } +) + +test( + 'HC-P-16 a gated article is left out of the landing, collection, related and prev/next lists', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Lists ${marker}`) + const first = await hcArticle(hc, { + categoryId: category.id, + title: `First ${marker}`, + publish: true, + }) + const gated = await hcArticle(hc, { + categoryId: category.id, + title: `Hidden ${marker}`, + publish: true, + }) + const last = await hcArticle(hc, { + categoryId: category.id, + title: `Last ${marker}`, + publish: true, + }) + await gateToSegments({ kind: 'article', uuid: gated.uuid }, [(await hcSegment(marker)).id]) + + for (const path of [articlePath(first), articlePath(last), collectionPath(category), '/hc']) { + await page.goto(path) + await expect(page.getByRole('heading', { level: 1 })).toBeVisible() + await expect(page.getByText(gated.title), path).toHaveCount(0) + expect(await page.content(), path).not.toContain(gated.title) + } + } +) + +test( + 'HC-P-04 the landing card counts only articles the visitor can open', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B14: listPublicCategories rolls recursivePublishedArticleCount up through private and gated descendants and article audiences', + }, + }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const parent = await hcCategory(hc, `Counted ${marker}`) + await hcArticle(hc, { categoryId: parent.id, title: `Open doc ${marker}`, publish: true }) + const hidden = await hcCategory(hc, `Hidden child ${marker}`, { + parentId: parent.id, + isPublic: false, + }) + for (let i = 0; i < 3; i++) { + await hcArticle(hc, { categoryId: hidden.id, title: `Hidden ${i} ${marker}`, publish: true }) + } + const gated = await hcArticle(hc, { + categoryId: parent.id, + title: `Gated ${marker}`, + publish: true, + }) + await gateToSegments({ kind: 'article', uuid: gated.uuid }, [(await hcSegment(marker)).id]) + expect( + ( + await supportDb()`SELECT count(*)::int AS n FROM kb_articles WHERE title LIKE ${`%${marker}`}` + )[0].n + ).toBe(5) + + await page.goto('/hc') + const card = page + .getByRole('region', { name: 'Browse by topic' }) + .getByRole('link') + .filter({ hasText: parent.name }) + await expect(card).toBeVisible() + await expect(card).toContainText('1 article') + await expect(card).not.toContainText(/[2-9] articles/) + } +) diff --git a/apps/web/e2e/tests/help-center/public-locales.spec.ts b/apps/web/e2e/tests/help-center/public-locales.spec.ts new file mode 100644 index 0000000000..3182bb2f1e --- /dev/null +++ b/apps/web/e2e/tests/help-center/public-locales.spec.ts @@ -0,0 +1,114 @@ +/** + * The public help center in another language (/hc/<locale>/...). The enabled + * languages are workspace-wide, so every test here is `@isolated`. + * + * Journeys: HC-P-24, HC-P-27. + */ +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 { + articlePath, + hcApi, + hcArticle, + hcCategory, + type HcArticle, +} from '../../product/help-center' + +const FRENCH = { + help_center_config: { + 'locales.additional': ['fr'], + 'locales.chrome.fr': { + homepageTitle: 'Comment pouvons-nous vous aider ?', + homepageDescription: 'Cherchez dans nos articles', + searchPlaceholder: '', + }, + }, +} + +async function translate(article: HcArticle, title: string) { + 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', ${title}, ${`Texte de ${title}.`}, + 'published', NOW(), NOW())` +} + +test.describe('the help center in French', { tag: '@isolated' }, () => { + test.beforeEach(() => { + test.skip(!ISOLATED, ISOLATED_SKIP) + }) + + test( + 'HC-P-24 /hc/fr shows the French homepage texts and only translated content', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Localised ${marker}`) + const translated = await hcArticle(hc, { + categoryId: category.id, + title: `English only? no ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + await translate(translated, `Traduit ${marker}`) + await page.goto('/hc/fr') + await expect( + page.getByRole('heading', { level: 1, name: 'Comment pouvons-nous vous aider ?' }) + ).toBeVisible() + await expect(page.getByText('Cherchez dans nos articles')).toBeVisible() + await page.goto(articlePath(translated, 'fr')) + await expect( + page.getByRole('heading', { level: 1, name: `Traduit ${marker}` }) + ).toBeVisible() + }) + } + ) + + test( + 'HC-P-27 an untranslated article has no French page, and related links on a French page work', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B26: related articles on a localised article page are loaded without the language, so they show English titles and link to /hc/<locale>/articles/... that 404 when untranslated', + }, + }, + async ({ page, request, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Related fr ${marker}`) + const main = await hcArticle(hc, { + categoryId: category.id, + title: `Router setup guide ${marker}`, + content: `Router setup steps. ${marker}`, + publish: true, + }) + const sibling = await hcArticle(hc, { + categoryId: category.id, + title: `Router setup advanced ${marker}`, + content: `Router setup advanced steps. ${marker}`, + publish: true, + }) + await withSettings(FRENCH, async () => { + await translate(main, `Guide du routeur ${marker}`) + // Strict: no English fallback on portal URLs. + const untranslated = await request.get(articlePath(sibling, 'fr'), { + headers: { cookie: 'e2e=1' }, + maxRedirects: 0, + }) + expect(untranslated.status()).toBe(404) + + await page.goto(articlePath(main, 'fr')) + await expect( + page.getByRole('heading', { level: 1, name: `Guide du routeur ${marker}` }) + ).toBeVisible() + const related = page.getByRole('link', { name: new RegExp(sibling.title) }) + await expect(related).toBeVisible() + const href = (await related.getAttribute('href')) ?? '' + const res = await request.get(href, { headers: { cookie: 'e2e=1' } }) + expect(res.status(), href).toBe(200) + }) + } + ) +}) diff --git a/apps/web/e2e/tests/help-center/public-pages.spec.ts b/apps/web/e2e/tests/help-center/public-pages.spec.ts new file mode 100644 index 0000000000..9b6e8685fd --- /dev/null +++ b/apps/web/e2e/tests/help-center/public-pages.spec.ts @@ -0,0 +1,275 @@ +/** + * The public help center: landing, collection and article pages, canonical + * and legacy URLs, and view counts. + * + * Journeys: HC-P-02, HC-P-03, HC-P-05, HC-P-07, HC-P-11, HC-P-12, HC-P-33. + */ +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { SUPPORT_PEOPLE } from '../../support/people' +import { + articlePath, + articleRow, + collectionPath, + hcApi, + hcArticle, + hcCategory, +} from '../../product/help-center' + +/** A request with a cookie: the app skips the shared-cache path for it. */ +const FRESH = { headers: { cookie: 'e2e=1' }, maxRedirects: 0 } + +test( + 'HC-P-07 a signed-out visitor reads an article with its author, body and feedback card', + { tag: '@smoke' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Read ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Reading ${marker}`, + description: `What this covers ${marker}`, + content: `## First step\n\nDo the first thing ${marker}.\n\n## Second step\n\nThen the next.`, + publish: true, + }) + const res = await page.goto(articlePath(article)) + expect(res?.status()).toBe(200) + await expect(page.getByRole('heading', { level: 1, name: article.title })).toBeVisible() + await expect(page.getByText(`What this covers ${marker}`).first()).toBeVisible() + await expect(page.getByText(SUPPORT_PEOPLE.admin.name).first()).toBeVisible() + await expect(page.getByText(/Last updated/)).toBeVisible() + await expect(page.getByRole('heading', { name: 'First step' })).toBeVisible() + await expect(page.getByText(`Do the first thing ${marker}.`)).toBeVisible() + await expect(page.getByText('Was this helpful?')).toBeVisible() + // Counters are not in the public payload. + expect(await page.content()).not.toMatch(/helpfulCount|notHelpfulCount/) + } +) + +test( + 'HC-P-02 the landing lists a public category as a card linking to its collection', + { tag: '@core' }, + async ({ page, marker, playwright, request }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Topic ${marker}`, { + description: `About the topic ${marker}`, + }) + await hcArticle(hc, { categoryId: category.id, title: `One ${marker}`, publish: true }) + await hcArticle(hc, { categoryId: category.id, title: `Two ${marker}`, publish: true }) + + await page.goto('/hc') + await expect(page.getByRole('heading', { level: 1 })).toBeVisible() + await expect(page.getByRole('searchbox').or(page.getByRole('textbox')).first()).toBeVisible() + const card = page + .getByRole('region', { name: 'Browse by topic' }) + .getByRole('link') + .filter({ hasText: category.name }) + await expect(card).toHaveAttribute('href', collectionPath(category)) + await expect(card).toContainText(`About the topic ${marker}`) + await expect(card).toContainText('2 articles') + expect(await page.title()).toMatch(/ - /) + + // A cookie-less request is cacheable by a shared cache. + const anon = await request.get('/hc', { headers: { cookie: '' } }) + expect(anon.headers()['cache-control']).toBe('public, s-maxage=60, stale-while-revalidate=600') + } +) + +test( + 'HC-P-03 the landing shows only live public categories with a published article', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const shown = await hcCategory(hc, `Shown ${marker}`) + await hcArticle(hc, { categoryId: shown.id, title: `Shown doc ${marker}`, publish: true }) + const empty = await hcCategory(hc, `Empty ${marker}`) + const drafts = await hcCategory(hc, `Drafts only ${marker}`) + await hcArticle(hc, { categoryId: drafts.id, title: `Draft doc ${marker}` }) + const hidden = await hcCategory(hc, `Private ${marker}`, { isPublic: false }) + await hcArticle(hc, { categoryId: hidden.id, title: `Private doc ${marker}`, publish: true }) + const parent = await hcCategory(hc, `Parent ${marker}`) + const child = await hcCategory(hc, `Child ${marker}`, { parentId: parent.id }) + await hcArticle(hc, { categoryId: child.id, title: `Child doc ${marker}`, publish: true }) + const future = await hcCategory(hc, `Future ${marker}`) + const later = await hcArticle(hc, { + categoryId: future.id, + title: `Later ${marker}`, + publish: true, + }) + await supportDb()`UPDATE kb_articles SET published_at = NOW() + interval '1 day' + WHERE id = ${later.uuid}` + + await page.goto('/hc') + const card = (name: string) => + page + .getByRole('region', { name: 'Browse by topic' }) + .getByRole('link') + .filter({ hasText: name }) + await expect(card(shown.name)).toBeVisible() + // A parent is a card because of its child's article; the child is not. + await expect(card(parent.name)).toBeVisible() + for (const c of [empty, drafts, hidden, child, future]) { + await expect(card(c.name), c.name).toHaveCount(0) + } + } +) + +test( + 'HC-P-05 a collection page shows its own articles and its sub-categories', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Collection ${marker}`, { + description: `Collection about ${marker}`, + }) + const own = await hcArticle(hc, { + categoryId: category.id, + title: `Own ${marker}`, + description: `Own summary ${marker}`, + publish: true, + }) + const sub = await hcCategory(hc, `Sub ${marker}`, { parentId: category.id }) + const subTitles: string[] = [] + for (let i = 1; i <= 9; i++) { + const a = await hcArticle(hc, { + categoryId: sub.id, + title: `Sub item ${i} ${marker}`, + publish: true, + }) + subTitles.push(a.title) + } + const emptySub = await hcCategory(hc, `Empty sub ${marker}`, { parentId: category.id }) + + await page.goto(collectionPath(category)) + await expect(page.getByRole('heading', { level: 1, name: category.name })).toBeVisible() + await expect(page.getByText(`Collection about ${marker}`).first()).toBeVisible() + await expect(page.getByRole('link', { name: new RegExp(own.title) })).toBeVisible() + await expect(page.getByText(`Own summary ${marker}`)).toBeVisible() + await expect(page.getByText(/1 min read/).first()).toBeVisible() + // The sub-category section shows its first 8 and a link to the rest. + await expect(page.getByRole('heading', { name: sub.name })).toBeVisible() + let visible = 0 + for (const t of subTitles) visible += await page.getByRole('link', { name: t }).count() + expect(visible).toBe(8) + await expect(page.getByRole('link', { name: 'View all 9 articles' })).toHaveAttribute( + 'href', + collectionPath(sub) + ) + // An empty sub-category says so (it may be left out of the page instead). + expect(await page.getByRole('heading', { name: emptySub.name }).count()).toBeLessThanOrEqual(1) + } +) + +test( + 'HC-P-11 the numeric id is the key: a wrong slug or a bare id 301s to the canonical URL', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Canon ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Canonical ${marker}`, + publish: true, + }) + const canonical = articlePath(article) + const ok = await request.get(canonical, FRESH) + expect(ok.status()).toBe(200) + const html = await ok.text() + expect(html).toContain(`rel="canonical" href="`) + expect(html).toMatch(new RegExp(`rel="canonical" href="[^"]*${canonical}"`)) + + for (const variant of [ + `/hc/en/articles/${article.urlId}-wrong-slug`, + `/hc/en/articles/${article.urlId}`, + ]) { + const res = await request.get(variant, FRESH) + expect(res.status(), variant).toBe(301) + expect(new URL(res.headers()['location'], 'http://x').pathname).toBe(canonical) + } + expect((await request.get('/hc/en/articles/not-a-number', FRESH)).status()).toBe(404) + expect((await request.get('/hc/en/articles/999999999-nope', FRESH)).status()).toBe(404) + + // A slug change keeps old links working. + await hc.patch(`/api/v1/help-center/articles/${article.id}`, { + data: { slug: `renamed-${marker}` }, + }) + const old = await request.get(canonical, FRESH) + expect(old.status()).toBe(301) + expect(new URL(old.headers()['location'], 'http://x').pathname).toBe( + `/hc/en/articles/${article.urlId}-renamed-${marker}` + ) + } +) + +test( + 'HC-P-12 legacy article, category and /help URLs redirect to the canonical form', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Legacy ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Legacy doc ${marker}`, + publish: true, + }) + const hop = async (path: string) => { + const res = await request.get(path, FRESH) + expect(res.status(), path).toBe(301) + return new URL(res.headers()['location'], 'http://x').pathname + } + /** Follow 301s to the end. */ + const settle = async (path: string) => { + let current = path + for (let i = 0; i < 5; i++) { + const res = await request.get(current, FRESH) + if (res.status() !== 301) return { path: current, status: res.status() } + current = new URL(res.headers()['location'], 'http://x').pathname + } + throw new Error(`redirect loop from ${path}`) + } + + expect(await hop(`/hc/articles/${category.slug}/${article.slug}`)).toBe(articlePath(article)) + // Only the article slug is checked, not the category segment. + expect(await hop(`/hc/articles/anything/${article.slug}`)).toBe(articlePath(article)) + expect(await settle(`/hc/${category.slug}/${article.slug}`)).toEqual({ + path: articlePath(article), + status: 200, + }) + expect(await settle(`/hc/categories/${category.slug}`)).toEqual({ + path: collectionPath(category), + status: 200, + }) + // `/hc/<slug>` (one segment) is left out: it 404s today, and which route + // should win there (language, legacy category, redirect rule) is an + // open owner question. + const help = await request.get('/help', FRESH) + expect([301, 302, 307, 308]).toContain(help.status()) + expect(new URL(help.headers()['location'], 'http://x').pathname).toBe('/hc') + expect((await settle(`/hc/articles/${category.slug}/no-such-${marker}`)).status).toBe(404) + } +) + +test( + 'HC-P-33 reading the canonical article page counts a view', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'HC-B1: view_count is incremented only in getPublicArticleBySlug (legacy URLs, widget by slug, embeds, admin View); the canonical page uses getPublicArticleByUrlId, which never counts', + }, + }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Views ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Viewed ${marker}`, + publish: true, + }) + expect((await articleRow(article.uuid))?.view_count).toBe(0) + await page.goto(articlePath(article)) + await expect(page.getByRole('heading', { level: 1, name: article.title })).toBeVisible() + await expect.poll(async () => (await articleRow(article.uuid))?.view_count).toBe(1) + } +) diff --git a/apps/web/e2e/tests/help-center/public-seo.spec.ts b/apps/web/e2e/tests/help-center/public-seo.spec.ts new file mode 100644 index 0000000000..8e56463a30 --- /dev/null +++ b/apps/web/e2e/tests/help-center/public-seo.spec.ts @@ -0,0 +1,57 @@ +/** + * The help center sitemap. + * + * Journeys: HC-P-20. + */ +import { test, expect } from '../../support/fixtures' +import { supportDb } from '../../support/db' +import { + articlePath, + collectionPath, + gateToSegments, + hcApi, + hcArticle, + hcCategory, + hcSegment, +} from '../../product/help-center' + +test( + 'HC-P-20 /hc/sitemap.xml lists public collections and published articles only', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const open = await hcCategory(hc, `Mapped ${marker}`) + const closed = await hcCategory(hc, `Unmapped ${marker}`, { isPublic: false }) + const live = await hcArticle(hc, { + categoryId: open.id, + title: `Live ${marker}`, + publish: true, + }) + const hidden = [ + await hcArticle(hc, { categoryId: open.id, title: `Draft ${marker}` }), + await hcArticle(hc, { categoryId: closed.id, title: `Private ${marker}`, publish: true }), + await hcArticle(hc, { categoryId: open.id, title: `Gated ${marker}`, publish: true }), + await hcArticle(hc, { categoryId: open.id, title: `Deleted ${marker}`, publish: true }), + await hcArticle(hc, { categoryId: open.id, title: `Future ${marker}`, publish: true }), + ] + await gateToSegments({ kind: 'article', uuid: hidden[2].uuid }, [(await hcSegment(marker)).id]) + await hc.delete(`/api/v1/help-center/articles/${hidden[3].id}`) + await supportDb()`UPDATE kb_articles SET published_at = NOW() + interval '1 day' + WHERE id = ${hidden[4].uuid}` + + const res = await request.get('/hc/sitemap.xml') + expect(res.status()).toBe(200) + expect(res.headers()['content-type']).toContain('application/xml') + expect(res.headers()['cache-control']).toBe('public, max-age=3600') + expect(res.headers()['vary']).toMatch(/Host/i) + const xml = await res.text() + const locs = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname) + expect(locs).toContain('/hc') + expect(locs).toContain(articlePath(live)) + expect(locs).toContain(collectionPath(open)) + expect(locs).not.toContain(collectionPath(closed)) + for (const a of hidden) expect(locs, a.title).not.toContain(articlePath(a)) + const entry = xml.split('<url>').find((u) => u.includes(articlePath(live))) + expect(entry).toMatch(/<lastmod>\d{4}-\d{2}-\d{2}<\/lastmod>/) + } +) diff --git a/apps/web/e2e/tests/help-center/search.spec.ts b/apps/web/e2e/tests/help-center/search.spec.ts new file mode 100644 index 0000000000..5c6cd68049 --- /dev/null +++ b/apps/web/e2e/tests/help-center/search.spec.ts @@ -0,0 +1,122 @@ +/** + * Help center search: the hero search on /hc and the kb-search endpoint it + * calls. + * + * Journeys: HC-S-01, HC-S-02, HC-S-04. + * + * The fake AI's embeddings are hash vectors, so only the keyword arm can + * match: every article carries a unique `searchWord()` in its title. + */ +import type { APIRequestContext } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { clientIp } from '../../support/api-client' +import { supportDb } from '../../support/db' +import { waitForHydration } from '../../utils/helpers' +import { + articlePath, + gateToSegments, + hcApi, + hcArticle, + hcCategory, + hcSegment, + searchWord, +} from '../../product/help-center' + +interface Hit { + id: string + title: string +} + +/** kb-search as a signed-out visitor from an address of its own. */ +async function kbSearch(request: APIRequestContext, q: string): Promise<Hit[]> { + const res = await request.get(`/api/widget/kb-search?q=${encodeURIComponent(q)}`, { + headers: { 'x-e2e-client-ip': clientIp() }, + }) + expect(res.status(), await res.text()).toBe(200) + return ((await res.json()) as { data: { articles: Hit[] } }).data.articles +} + +test( + 'HC-S-01 the hero search finds a published article by a title word and opens it', + { tag: '@smoke' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `Search ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Configuring the ${word} relay`, + content: `Turn the relay on. ${marker}`, + publish: true, + }) + await page.context().setExtraHTTPHeaders({ 'x-e2e-client-ip': clientIp() }) + await page.goto('/hc') + const box = page.locator('#hc-search') + await waitForHydration(box) + const searched = page.waitForResponse((r) => r.url().includes('/api/widget/kb-search')) + await box.fill(word) + const res = await searched + expect(new URL(res.url()).searchParams.get('limit')).toBe('8') + const result = page.getByRole('button').filter({ hasText: article.title }) + await expect(result).toBeVisible() + await expect(result).toContainText(category.name) + await result.click() + await expect(page).toHaveURL(new RegExp(`${articlePath(article)}$`)) + await expect(page.getByRole('heading', { level: 1, name: article.title })).toBeVisible() + } +) + +test( + 'HC-S-02 a title word matches, stopwords alone do not, and matching ignores case and stems', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `Match ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Exporting ${word} reports`, + publish: true, + }) + const ids = async (q: string) => (await kbSearch(request, q)).map((h) => h.title) + + expect(await ids(word)).toEqual([article.title]) + expect(await ids(word.toUpperCase())).toEqual([article.title]) + // Any one word of several can match (an OR of terms). + expect(await ids(`${word} ${searchWord()}`)).toEqual([article.title]) + // "how do I" is all stopwords: an empty query, no results. + expect(await kbSearch(request, 'how do I')).toEqual([]) + // A word in no article finds nothing. + expect(await kbSearch(request, searchWord())).toEqual([]) + } +) + +test( + 'HC-S-04 search never returns drafts, deleted, private, gated or future articles', + { tag: '@core' }, + async ({ request, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const open = await hcCategory(hc, `Open ${marker}`) + const closed = await hcCategory(hc, `Closed ${marker}`, { isPublic: false }) + const make = (title: string, categoryId = open.id, publish = true) => + hcArticle(hc, { categoryId, title: `${title} ${word}`, publish }) + + const visible = await make('Visible') + await make('Draft', open.id, false) + const deleted = await make('Deleted') + await hc.delete(`/api/v1/help-center/articles/${deleted.id}`) + await make('Private', closed.id) + const gated = await make('Gated') + await gateToSegments({ kind: 'article', uuid: gated.uuid }, [(await hcSegment(marker)).id]) + const future = await make('Future') + await supportDb()`UPDATE kb_articles SET published_at = NOW() + interval '1 day' + WHERE id = ${future.uuid}` + const unpublished = await make('Unpublished') + await hc.patch(`/api/v1/help-center/articles/${unpublished.id}`, { + data: { publishedAt: null }, + }) + + expect((await kbSearch(request, word)).map((h) => h.title)).toEqual([visible.title]) + } +) diff --git a/apps/web/e2e/tests/help-center/widget.spec.ts b/apps/web/e2e/tests/help-center/widget.spec.ts new file mode 100644 index 0000000000..1284e20311 --- /dev/null +++ b/apps/web/e2e/tests/help-center/widget.spec.ts @@ -0,0 +1,229 @@ +/** + * The help center inside the widget (the Help tab). The tab switch is + * workspace-wide (widget_config.tabs.help), so these are `@isolated`. + * + * Journeys: HC-W-01, HC-W-02, HC-W-03, HC-W-04, HC-W-06, HC-W-10. + */ +import type { FrameLocator, Page } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { supportDb } from '../../support/db' +import { SUPPORT_FLAGS_ON, WIDGET_BASELINE, withSettings } from '../../support/isolated-settings' +import { openWidget } from '../../support/widget-portal' +import { articleRow, hcApi, hcArticle, hcCategory, searchWord } from '../../product/help-center' + +const HELP_ON = { + feature_flags: { ...SUPPORT_FLAGS_ON, helpCenter: true }, + widget_config: { ...WIDGET_BASELINE, 'tabs.help': true }, +} + +function helpTab(widget: FrameLocator) { + return widget.getByRole('button', { name: 'Help', exact: true }) +} + +async function openHelp(page: Page) { + const widget = await openWidget(page) + await helpTab(widget).click() + await expect(widget.getByRole('textbox', { name: 'Search help articles' })).toBeVisible() + return widget +} + +test.describe('the widget Help tab', { tag: '@isolated' }, () => { + test.beforeEach(() => { + test.skip(!ISOLATED, ISOLATED_SKIP) + }) + + test( + 'HC-W-01 the Help tab shows only with the tab setting and the product both on', + { tag: '@core' }, + async ({ browser }) => { + for (const [patch, shown] of [ + [HELP_ON, true], + [{ ...HELP_ON, widget_config: { ...WIDGET_BASELINE, 'tabs.help': false } }, false], + [{ ...HELP_ON, feature_flags: { ...SUPPORT_FLAGS_ON, helpCenter: false } }, false], + ] as const) { + await withSettings(patch, async () => { + const context = await browser.newContext() + const page = await context.newPage() + const widget = await openWidget(page) + await expect(widget.getByRole('button', { name: 'Messages', exact: true })).toBeVisible() + await expect(helpTab(widget)).toHaveCount(shown ? 1 : 0) + await context.close() + }) + } + } + ) + + test( + 'HC-W-02 HC-W-03 the Help tab lists collections; a collection lists its articles; an article opens', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Widget guides ${marker}`, { + description: `Guides for ${marker}`, + }) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Widget doc ${marker}`, + description: `Widget summary ${marker}`, + content: `Widget body text ${marker}.`, + publish: true, + }) + await withSettings(HELP_ON, async () => { + const widget = await openHelp(page) + await expect(widget.getByText('Browse collections')).toBeVisible() + const collection = widget.getByRole('button').filter({ hasText: category.name }) + await expect(collection).toContainText(`Guides for ${marker}`) + await expect(collection).toContainText('1 article') + await collection.click() + + await expect(widget.getByText(category.name).first()).toBeVisible() + const row = widget.getByRole('button').filter({ hasText: article.title }) + await expect(row).toContainText(`Widget summary ${marker}`) + await row.click() + await expect(widget.getByRole('heading', { name: article.title })).toBeVisible() + await expect(widget.getByText(`Widget body text ${marker}.`)).toBeVisible() + await expect(widget.getByText('Was this helpful?')).toBeVisible() + }) + } + ) + + test( + 'HC-W-04 the host page opens an article by id or slug; a draft is not found', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Opened ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Opened doc ${marker}`, + publish: true, + }) + const draft = await hcArticle(hc, { categoryId: category.id, title: `Draft doc ${marker}` }) + await withSettings(HELP_ON, async () => { + const widget = await openWidget(page) + const open = (articleId: string) => + page.evaluate((id) => { + const q = (window as unknown as { Quackback: (...a: unknown[]) => void }).Quackback + q('open', { articleId: id }) + }, articleId) + for (const ref of [ + article.id, + article.id.replace(/^article_/, 'kb_article_'), + article.slug, + ]) { + await open(ref) + await expect(widget.getByRole('heading', { name: article.title }), ref).toBeVisible() + await expect(widget.getByText(category.name).first()).toBeVisible() + } + await open(draft.id) + await expect(widget.getByText('Article not found')).toBeVisible() + await expect(widget.getByRole('heading', { name: draft.title })).toHaveCount(0) + }) + } + ) + + test( + 'HC-W-06 widget search finds an article, keeps the query on the way back, and says when nothing matches', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const word = searchWord() + const category = await hcCategory(hc, `Searchable ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Calibrating the ${word} sensor`, + publish: true, + }) + await withSettings(HELP_ON, async () => { + const widget = await openHelp(page) + const box = widget.getByRole('textbox', { name: 'Search help articles' }) + await box.fill(word) + const result = widget.getByRole('button').filter({ hasText: article.title }) + await expect(result).toContainText(category.name) + await result.click() + await expect(widget.getByRole('heading', { name: article.title })).toBeVisible() + await widget.getByRole('button', { name: /back/i }).first().click() + await expect(box).toHaveValue(word) + await expect(result).toBeVisible() + + await box.fill(searchWord()) + await expect(widget.getByText('No results found')).toBeVisible() + await expect(widget.getByText('Try different keywords or browse categories.')).toBeVisible() + await widget.getByRole('button', { name: 'Clear search' }).click() + await expect(box).toHaveValue('') + await expect(widget.getByText('Browse collections')).toBeVisible() + }) + } + ) + + test( + 'HC-W-10 a widget vote is stored against the visitor session and flips without adding rows', + { tag: '@core' }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Widget votes ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Widget voted ${marker}`, + publish: true, + }) + await withSettings(HELP_ON, async () => { + const widget = await openWidget(page) + await page.evaluate((id) => { + const q = (window as unknown as { Quackback: (...a: unknown[]) => void }).Quackback + q('open', { articleId: id }) + }, article.id) + await expect(widget.getByRole('heading', { name: article.title })).toBeVisible() + const yes = widget.getByRole('button', { name: 'Yes, this helped' }) + await yes.click() + await expect.poll(async () => (await articleRow(article.uuid))?.helpful_count).toBe(1) + await widget.getByRole('button', { name: "No, this didn't help" }).click() + await expect + .poll(async () => { + const row = await articleRow(article.uuid) + return [row?.helpful_count, row?.not_helpful_count] + }) + .toEqual([0, 1]) + const rows = await supportDb()`SELECT principal_id, helpful FROM kb_article_feedback + WHERE article_id = ${article.uuid}` + expect(rows).toHaveLength(1) + expect(rows[0].principal_id).not.toBeNull() + expect(rows[0].helpful).toBe(false) + }) + } + ) + + test( + 'HC-W-10 the first widget vote of a fresh visitor confirms it', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'New (HC-W-10): the vote is stored, but the footer keeps "Was this helpful?" after a fresh visitor\'s first vote; the session minted by ensureSession appears to remount the article view and drop the vote state', + }, + }, + async ({ page, marker, playwright }) => { + const hc = await hcApi(playwright) + const category = await hcCategory(hc, `Widget thanks ${marker}`) + const article = await hcArticle(hc, { + categoryId: category.id, + title: `Widget thanks ${marker}`, + publish: true, + }) + await withSettings(HELP_ON, async () => { + const widget = await openWidget(page) + await page.evaluate((id) => { + const q = (window as unknown as { Quackback: (...a: unknown[]) => void }).Quackback + q('open', { articleId: id }) + }, article.id) + const yes = widget.getByRole('button', { name: 'Yes, this helped' }) + await yes.click() + await expect.poll(async () => (await articleRow(article.uuid))?.helpful_count).toBe(1) + await expect(widget.getByText('Thanks, glad it helped.')).toBeVisible() + await expect(yes).toHaveAttribute('aria-pressed', 'true') + }) + } + ) +})