From b8fed0591824b27b5dce62c6f0d5fca90433ec06 Mon Sep 17 00:00:00 2001 From: Preston Cabe Date: Tue, 27 Oct 2026 16:46:55 -0400 Subject: [PATCH 01/12] Send visible copied next steps to CRM hosts and saved examples --- builder-frontend/public/integrations/host.js | 6 +- .../components/screener/FormRenderer.test.tsx | 50 +++++++ .../src/components/screener/FormRenderer.tsx | 22 +++ .../src/components/screener/Screener.test.tsx | 9 +- .../src/components/screener/Screener.tsx | 9 +- .../formJsExtensions/nextSteps/selection.ts | 14 ++ .../printSummary/PrintSummary.ts | 17 +-- .../src/integrations/nextSteps.test.ts | 99 ++++++++++++++ .../src/integrations/nextSteps.ts | 71 ++++++++++ .../src/integrations/screenerBridge.test.ts | 45 +++++++ .../src/integrations/screenerBridge.ts | 10 +- docs/src/content/docs/dev/crm-integrations.md | 46 ++++++- e2e/tests/crmIntegration.spec.ts | 126 +++++++++++++++++- examples/crm/browser/README.md | 12 ++ examples/crm/browser/demo.html | 7 + examples/crm/browser/demo.js | 71 ++++++++++ examples/crm/salesforce/README.md | 12 ++ .../salesforce/bdtScreening/bdtScreening.js | 1 + .../bdtScreeningResults.css | 16 +++ .../bdtScreeningResults.html | 35 +++++ .../bdtScreeningResults/formatResults.js | 59 ++++++++ .../salesforce/tests/formatResults.test.mjs | 64 +++++++++ 22 files changed, 780 insertions(+), 21 deletions(-) create mode 100644 builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts create mode 100644 builder-frontend/src/integrations/nextSteps.test.ts create mode 100644 builder-frontend/src/integrations/nextSteps.ts create mode 100644 examples/crm/salesforce/tests/formatResults.test.mjs diff --git a/builder-frontend/public/integrations/host.js b/builder-frontend/public/integrations/host.js index 91094259..1caa3857 100644 --- a/builder-frontend/public/integrations/host.js +++ b/builder-frontend/public/integrations/host.js @@ -143,7 +143,11 @@ export function createCrmIntegration({ message.inputData && typeof message.inputData === "object" && !Array.isArray(message.inputData) && - typeof message.evaluatedAt === "string" + typeof message.evaluatedAt === "string" && + (message.nextSteps === undefined || + (message.nextSteps !== null && + typeof message.nextSteps === "object" && + !Array.isArray(message.nextSteps))) ) { onResult(message); } else if ( diff --git a/builder-frontend/src/components/screener/FormRenderer.test.tsx b/builder-frontend/src/components/screener/FormRenderer.test.tsx index c56d6132..a01cc098 100644 --- a/builder-frontend/src/components/screener/FormRenderer.test.tsx +++ b/builder-frontend/src/components/screener/FormRenderer.test.tsx @@ -31,6 +31,56 @@ describe("FormRenderer host prefill", () => { document.body.innerHTML = ""; }); + it("exports only the currently visible saved content and unregisters on unmount", async () => { + const register = vi.fn(); + const container = document.body.appendChild(document.createElement("div")); + dispose = render( + () => ( + ({ show: true })} + hiddenQuestionPaths={() => []} + submitForm={() => {}} + registerNextStepsProvider={register} + /> + ), + container, + ); + await vi.waitFor(() => expect(register).toHaveBeenCalledOnce()); + const results = { + benefit: { name: "Benefit", result: "TRUE" as const, check_results: {} }, + }; + const provider = register.mock.calls[0][0]; + expect(provider(results).benefit.body.text).toBe("Saved instructions"); + container + .querySelector('input[type="checkbox"]')! + .click(); + await vi.waitFor(() => expect(provider(results)).toBeUndefined()); + dispose(); + dispose = undefined; + expect(register).toHaveBeenLastCalledWith(undefined); + }); + it("evaluates unknown host answers as null until the user answers them", async () => { const submitForm = vi.fn(); const container = document.body.appendChild(document.createElement("div")); diff --git a/builder-frontend/src/components/screener/FormRenderer.tsx b/builder-frontend/src/components/screener/FormRenderer.tsx index aa42ddaa..6554ad63 100644 --- a/builder-frontend/src/components/screener/FormRenderer.tsx +++ b/builder-frontend/src/components/screener/FormRenderer.tsx @@ -11,6 +11,12 @@ import { connectScreeningResults, screeningResultsModule, } from "../screenerEditor/formJsExtensions/screeningResults/screeningResults"; +import { firstVisibleNextSteps } from "../screenerEditor/formJsExtensions/nextSteps/selection"; +import { + projectNextSteps, + type NextStepsProvider, +} from "@/integrations/nextSteps"; +import type { ScreeningResultsService } from "../screenerEditor/formJsExtensions/screeningResults/screeningResults"; import type { ScreenerResult } from "@/types"; import { hideQuestions } from "@/utils/questionVotes"; import { normalizeArrayFieldData } from "@/utils/arrayFieldData"; @@ -34,7 +40,9 @@ function FormRenderer({ failed = () => false, onNextStepsShownChange, screenerName, + registerNextStepsProvider, }: { + registerNextStepsProvider?: (provider: NextStepsProvider | undefined) => void; schema: { [key: string]: any }; formData: Accessor; hiddenQuestionPaths: Accessor; @@ -53,6 +61,7 @@ function FormRenderer({ let form: Form | undefined; let currentData: any = {}; let importing = false; + let disposed = false; let unknownPaths: string[][] = []; const evaluationData = (data: any) => normalizeArrayFieldData(schema, restoreUnknownAnswers(data, unknownPaths)); @@ -98,6 +107,17 @@ function FormRenderer({ form .importSchema(hideQuestions(schema, hiddenQuestionPaths()), formData()) .then(() => { + if (disposed) return; + registerNextStepsProvider?.((results) => { + const service = + form!.get("screeningResults"); + const fields = + (form!.get("formFieldRegistry") as any).getForm()?.components ?? []; + return projectNextSteps( + results, + firstVisibleNextSteps(fields, service.isNextStepsFieldShown), + ); + }); currentData = cloneDeep(form?._getState().data || formData()); if (evaluateInitialData) { unknownPaths = findFilledUnknownPaths(formData(), currentData); @@ -115,6 +135,8 @@ function FormRenderer({ .catch(console.error); onCleanup(() => { + disposed = true; + registerNextStepsProvider?.(undefined); debouncedSubmit.cancel(); form?.destroy(); }); diff --git a/builder-frontend/src/components/screener/Screener.test.tsx b/builder-frontend/src/components/screener/Screener.test.tsx index 2f819619..a7f8db4c 100644 --- a/builder-frontend/src/components/screener/Screener.test.tsx +++ b/builder-frontend/src/components/screener/Screener.test.tsx @@ -55,11 +55,15 @@ vi.mock("./FormRenderer", () => ({ return ( <> - + ); }, @@ -115,6 +119,7 @@ describe("published screener integration lifecycle", () => { expect(integration.result).toHaveBeenLastCalledWith( { custom: { householdIncome: 50000 } }, result("FALSE"), + undefined, ); old.resolve(result("TRUE")); await old.promise; diff --git a/builder-frontend/src/components/screener/Screener.tsx b/builder-frontend/src/components/screener/Screener.tsx index e589b013..9c6fa0c4 100644 --- a/builder-frontend/src/components/screener/Screener.tsx +++ b/builder-frontend/src/components/screener/Screener.tsx @@ -25,6 +25,7 @@ import { getUnneededQuestionPaths, haveSameQuestionPaths, } from "@/utils/questionVotes"; +import type { NextStepsProvider } from "@/integrations/nextSteps"; import { createScreeningBridge } from "@/integrations/screenerBridge"; export default function Screener() { @@ -51,6 +52,7 @@ export default function Screener() { }); const [integrationReady, setIntegrationReady] = createSignal(!bridge); let evaluationSequence = 0; + let nextStepsProvider: NextStepsProvider | undefined; // Start once the screener loads, so the host's origin can be checked against // the origins its builder allowed. Only an allowed host gets answers. let bridgeStarted = false; @@ -100,10 +102,12 @@ export default function Screener() { data, ); if (sequence !== evaluationSequence) return; + // Read visible content before setting results can re-import the form to hide questions. + const nextSteps = nextStepsProvider?.(evaluationResult); setScreenerResult(evaluationResult); setResultsStale(false); setEvaluationFailed(false); - bridge?.result(data, evaluationResult); + bridge?.result(data, evaluationResult, nextSteps); } catch (err) { if (sequence !== evaluationSequence) return; setEvaluationFailed(true); @@ -144,6 +148,9 @@ export default function Screener() {
{ + nextStepsProvider = provider; + }} screenerName={() => screener()?.screenerName ?? ""} schema={screener()?.formSchema || {}} formData={formData} diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts new file mode 100644 index 00000000..5579de5c --- /dev/null +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts @@ -0,0 +1,14 @@ +import type { NextStepsField } from "./NextSteps"; +import { NEXT_STEPS_TYPE } from "./content"; + +/** Shared by print and CRM exports: use the first rendered component in schema order. */ +export function firstVisibleNextSteps( + fields: any[], + isShown: (id: string) => boolean, +): NextStepsField | undefined { + for (const field of fields) { + if (field.type === NEXT_STEPS_TYPE && isShown(field.id)) return field; + const nested = firstVisibleNextSteps(field.components ?? [], isShown); + if (nested) return nested; + } +} diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts index 48c3d046..f003e180 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts @@ -3,7 +3,8 @@ import { render } from "preact"; import { useContext, useLayoutEffect, useRef, useState } from "preact/hooks"; import { FormContext, iconsByType, Text } from "@bpmn-io/form-js-viewer"; import { NextStepsBody, type NextStepsField } from "../nextSteps/NextSteps"; -import { NEXT_STEPS_TYPE, webLink } from "../nextSteps/content"; +import { webLink } from "../nextSteps/content"; +import { firstVisibleNextSteps } from "../nextSteps/selection"; import type { ScreeningResultsService } from "../screeningResults/screeningResults"; import { useScreeningResults } from "../screeningResults/useScreeningResults"; import "./printSummary.css"; @@ -74,20 +75,10 @@ export function PrintSummary() { const benefits = Object.entries(current.results ?? {}); setError(""); // Print what the person sees: skip Next steps hidden by a condition. - const firstNextSteps = (fields: any[]): NextStepsField | undefined => { - for (const field of fields) { - if ( - field.type === NEXT_STEPS_TYPE && - service.isNextStepsFieldShown(field.id) - ) - return field; - const nested = firstNextSteps(field.components ?? []); - if (nested) return nested; - } - }; const source: NextStepsField = - firstNextSteps( + firstVisibleNextSteps( context.getService("formFieldRegistry").getForm()?.components ?? [], + service.isNextStepsFieldShown, ) ?? {}; const root = document.createElement("article"); root.className = "bdt-print-root"; diff --git a/builder-frontend/src/integrations/nextSteps.test.ts b/builder-frontend/src/integrations/nextSteps.test.ts new file mode 100644 index 00000000..6ba5f5ab --- /dev/null +++ b/builder-frontend/src/integrations/nextSteps.test.ts @@ -0,0 +1,99 @@ +import { expect, it } from "vitest"; +import { projectNextSteps } from "./nextSteps"; +import type { ScreenerResult } from "@/types"; + +const results: ScreenerResult = { + housing: { name: "Housing", result: "TRUE", check_results: {} }, + food: { + name: "Food", + result: "FALSE", + check_results: { + a: { result: "FALSE", name: "Income", aliasName: "Income limit" } as any, + b: { result: "FALSE", name: "Residence", aliasName: " " } as any, + c: { result: "TRUE", name: "Other requirement" } as any, + }, + }, + utility: { + name: "Utilities", + result: "UNABLE_TO_DETERMINE", + check_results: {}, + }, +}; +const field = { + benefitContent: { + housing: { + eligible: { + applyUrl: "https://example.org/apply", + helpUrl: "https://example.org/help", + helpPhone: " 215-555-0100 ", + body: "Bring **ID**.", + }, + ineligible: { note: "Not for eligible" }, + }, + food: { + eligible: { applyUrl: "https://example.org/wrong" }, + ineligible: { note: "Ask about **other help**." }, + }, + removed: { eligible: { body: "Removed instructions" } }, + }, +}; + +it("exports only decided benefits and the content matching each outcome", () => { + const copy = structuredClone(field); + expect(projectNextSteps(results, field)).toEqual({ + housing: { + status: "eligible", + applyUrl: "https://example.org/apply", + help: { url: "https://example.org/help", phone: "215-555-0100" }, + body: { format: "markdown", text: "Bring **ID**." }, + unmetRequirements: [], + note: null, + }, + food: { + status: "ineligible", + applyUrl: null, + help: { url: null, phone: null }, + body: null, + unmetRequirements: ["Income limit", "Residence"], + note: { format: "markdown", text: "Ask about **other help**." }, + }, + }); + expect(field).toEqual(copy); +}); + +it("omits the extension without a visible field and respects whenComplete", () => { + expect(projectNextSteps(results)).toBeUndefined(); + expect( + projectNextSteps(results, { ...field, showWhen: "whenComplete" }), + ).toEqual({}); + expect( + Object.keys( + projectNextSteps( + { housing: results.housing }, + { ...field, showWhen: "whenComplete" }, + )!, + ), + ).toEqual(["housing"]); +}); + +it("does not invent missing content or pass unsafe application links", () => { + const exported = projectNextSteps(results, { + benefitContent: { + housing: { + eligible: { + applyUrl: "javascript:alert(1)", + helpUrl: "https://user:secret@example.org/", + }, + }, + }, + })!; + expect(exported.housing).toEqual({ + status: "eligible", + applyUrl: null, + help: { url: null, phone: null }, + body: null, + unmetRequirements: [], + note: null, + }); + expect(exported.food.note).toBeNull(); +}); diff --git a/builder-frontend/src/integrations/nextSteps.ts b/builder-frontend/src/integrations/nextSteps.ts new file mode 100644 index 00000000..f04c4d41 --- /dev/null +++ b/builder-frontend/src/integrations/nextSteps.ts @@ -0,0 +1,71 @@ +import type { ScreenerResult } from "@/types"; +import type { NextStepsField } from "@/components/screenerEditor/formJsExtensions/nextSteps/NextSteps"; +import { webLink } from "@/components/screenerEditor/formJsExtensions/nextSteps/content"; + +type Markdown = { format: "markdown"; text: string }; +export type CrmNextSteps = Record< + string, + { + status: "eligible" | "ineligible"; + applyUrl: string | null; + help: { url: string | null; phone: string | null }; + body: Markdown | null; + unmetRequirements: string[]; + note: Markdown | null; + } +>; +export type NextStepsProvider = ( + results: ScreenerResult, +) => CrmNextSteps | undefined; + +const text = (value?: string | null) => + typeof value === "string" && value.trim() ? value : null; +const markdown = (value?: string | null): Markdown | null => + text(value) ? { format: "markdown", text: value! } : null; + +/** Project the saved screener copy, never evaluation-provider content or generated HTML. */ +export function projectNextSteps( + results: ScreenerResult, + field?: NextStepsField, +): CrmNextSteps | undefined { + if (!field) return; + const benefits = Object.entries(results); + if ( + field.showWhen === "whenComplete" && + benefits.some(([, benefit]) => !["TRUE", "FALSE"].includes(benefit.result)) + ) + return {}; + return Object.fromEntries( + benefits.flatMap(([id, benefit]) => { + if (!["TRUE", "FALSE"].includes(benefit.result)) return []; + const content = field.benefitContent?.[id]; + const eligible = benefit.result === "TRUE"; + return [ + [ + id, + { + status: eligible ? "eligible" : "ineligible", + applyUrl: eligible + ? (webLink(content?.eligible?.applyUrl) ?? null) + : null, + help: { + url: eligible + ? (webLink(content?.eligible?.helpUrl) ?? null) + : null, + phone: eligible + ? (text(content?.eligible?.helpPhone)?.trim() ?? null) + : null, + }, + body: eligible ? markdown(content?.eligible?.body) : null, + unmetRequirements: eligible + ? [] + : Object.values(benefit.check_results ?? {}) + .filter((check) => check.result === "FALSE") + .map((check) => check.aliasName?.trim() || check.name), + note: eligible ? null : markdown(content?.ineligible?.note), + }, + ], + ]; + }), + ); +} diff --git a/builder-frontend/src/integrations/screenerBridge.test.ts b/builder-frontend/src/integrations/screenerBridge.test.ts index f599f422..5690c9df 100644 --- a/builder-frontend/src/integrations/screenerBridge.test.ts +++ b/builder-frontend/src/integrations/screenerBridge.test.ts @@ -79,6 +79,51 @@ afterEach(() => { }); describe("published screener CRM bridge", () => { + it.each([false, true])( + "round-trips optional next steps without changing protocol version (JSON=%s)", + (serializeMessages) => { + const s = setup(); + const onResult = vi.fn(); + const host = createCrmIntegration({ + screenerUrl: "https://bdt.example/screener/published-id", + getTargetWindow: () => s.child as any, + initialData: {}, + requestId: "request-1", + serializeMessages, + onResult, + hostWindow: s.host as any, + }); + s.bridge.start(); + s.receive(s.hostPost.mock.calls[0][0]); + s.send(s.childPost.mock.calls[0][0]); + s.receive(s.hostPost.mock.calls[1][0]); + const nextSteps = { + benefit: { + status: "eligible" as const, + applyUrl: null, + help: { url: null, phone: null }, + body: { format: "markdown" as const, text: "Bring **ID**." }, + unmetRequirements: [], + note: null, + }, + }; + s.bridge.result({}, results, nextSteps); + s.receive(s.hostPost.mock.lastCall![0]); + expect(onResult).toHaveBeenLastCalledWith( + expect.objectContaining({ version: 1, nextSteps }), + ); + const last = serializeMessages + ? JSON.parse(s.hostPost.mock.lastCall![0]) + : s.hostPost.mock.lastCall![0]; + s.receive({ ...last, nextSteps: [] }); + expect(onResult).toHaveBeenCalledOnce(); + s.bridge.result({}, results); + s.receive(s.hostPost.mock.lastCall![0]); + expect(onResult.mock.lastCall![0]).not.toHaveProperty("nextSteps"); + host.dispose(); + s.bridge.dispose(); + }, + ); it("repeats ready until a host initializes it", () => { const s = setup(); s.bridge.start(); diff --git a/builder-frontend/src/integrations/screenerBridge.ts b/builder-frontend/src/integrations/screenerBridge.ts index 574620fd..a6d80f1a 100644 --- a/builder-frontend/src/integrations/screenerBridge.ts +++ b/builder-frontend/src/integrations/screenerBridge.ts @@ -1,5 +1,6 @@ import type { ScreenerResult } from "@/types"; import { isUnsafeObjectKey } from "@/utils/unsafeObjectKeys"; +import type { CrmNextSteps } from "./nextSteps"; const CHANNEL = "bdt.crm"; const VERSION = 1; @@ -28,7 +29,11 @@ export interface ScreeningBridge { readonly origin: string; start(): void; dispose(): void; - result(inputData: Record, results: ScreenerResult): void; + result( + inputData: Record, + results: ScreenerResult, + nextSteps?: CrmNextSteps, + ): void; error(): void; /** Call before start(): answer the host's initialize with this error, then stop. */ fail(code: ConnectionFailure): void; @@ -169,11 +174,12 @@ export function createScreeningBridge( }, CONNECT_TIMEOUT_MS); }, dispose, - result(inputData, results) { + result(inputData, results, nextSteps) { if (requestId) send("result", { inputData, results, + ...(nextSteps === undefined ? {} : { nextSteps }), evaluatedAt: new Date().toISOString(), }); }, diff --git a/docs/src/content/docs/dev/crm-integrations.md b/docs/src/content/docs/dev/crm-integrations.md index 299aa779..f8418bdc 100644 --- a/docs/src/content/docs/dev/crm-integrations.md +++ b/docs/src/content/docs/dev/crm-integrations.md @@ -101,6 +101,7 @@ const connection = createCrmIntegration({ screenerId: message.screenerId, evaluatedAt: message.evaluatedAt, results: message.results, + nextSteps: message.nextSteps, }); }, onError: () => showEvaluationError(), @@ -181,10 +182,53 @@ Every message is a plain object with these envelope fields: | Screener → host | `ready` | Repeated until initialized; send prefill for this `sessionId` | | Host → screener | `initialize` | `inputData`: a JSON form-data object; use `{}` for no prefill | | Screener → host | `initialized` | Prefill accepted; form loads and evaluates | -| Screener → host | `result` | `inputData`, `results`, `evaluatedAt` (ISO 8601 timestamp) | +| Screener → host | `result` | `inputData`, `results`, `evaluatedAt` (ISO 8601 timestamp), optional `nextSteps` | | Screener → host | `error` | `code`: see below | | Host → screener | `disconnect` | Host closed the connection; screener stops and says so | +### Next steps in result messages + +Version 1 includes an optional, additive `nextSteps` field. Existing hosts may +ignore it; no protocol version change or new handshake is required. The host +adapter forwards the field unchanged in both object and JSON message modes. + +```json +{ + "nextSteps": { + "benefit-id": { + "status": "eligible", + "applyUrl": "https://example.org/apply", + "help": { "url": "https://example.org/help", "phone": "215-555-0100" }, + "body": { "format": "markdown", "text": "Bring **proof of residence**." }, + "unmetRequirements": [], + "note": null + } + } +} +``` + +Only decided benefits are included, keyed by their evaluation benefit IDs. +Eligible entries contain application/help contacts and `body`; ineligible entries +have `status: "ineligible"`, `unmetRequirements` (the failed checks' display names), +and `note` with the same `{ format: "markdown", text }` structure. Unused contacts +and text fields are `null`; unused requirements are an empty array. Missing +instructions remain empty rather than being invented. + +Content comes from the first **visible** Next steps component in schema order, +including nested groups, just like printing. It uses the screener's saved copy, +not current benefit defaults or content in an evaluation response. Hidden +components are skipped. If none is visible, `nextSteps` is omitted. If the +component uses `whenComplete`, `nextSteps` is `{}` until every benefit is decided. +As with `results`, each new message replaces the previous snapshot: an omitted +field or empty object must clear any previous instructions in the host. + +The payload contains structured data, never rendered HTML. Treat Markdown as +untrusted content: display it as plain text (as the examples do), or use a +sanitizing Markdown renderer. Validate links before making them clickable. The +screener emits only HTTP(S) application/help URLs, but hosts must still validate +any saved snapshot they read. Save `nextSteps` alongside `results` only when the +user chooses to save; the protocol does not change persistence authorization. + The screener repeats `ready` about every 500 ms until it's initialized, so a host that starts listening late still connects. Ignore repeated `ready` messages for a session you've already initialized. If nothing initializes the screener diff --git a/e2e/tests/crmIntegration.spec.ts b/e2e/tests/crmIntegration.spec.ts index bad4d2e1..fb147a14 100644 --- a/e2e/tests/crmIntegration.spec.ts +++ b/e2e/tests/crmIntegration.spec.ts @@ -6,6 +6,9 @@ let demoServer: ChildProcess | undefined; let demoUrl: string; // Origins the mocked published screener allows; the demo's by default. let integrationOrigins: string[]; +let includeNextSteps: boolean; +let hideNextSteps: boolean; +let showWhen: string; // Only this spec needs the CRM host example, so it starts its own server on a // free port instead of making every Playwright project reserve one. @@ -40,6 +43,9 @@ test.afterAll(() => { // Public browser integration tests use intercepted API responses, not Firebase. test.beforeEach(async ({ context }) => { integrationOrigins = [new URL(demoUrl).origin]; + includeNextSteps = true; + hideNextSteps = false; + showWhen = "whenDecided"; await context.route("**/api/published/**", async (route) => { const request = route.request(); const headers = { @@ -84,6 +90,31 @@ test.beforeEach(async ({ context }) => { key: "custom.wantsExtraCash", label: "Interested in cash assistance", }, + ...(includeNextSteps + ? [ + { + id: "next", + type: "next_steps", + showWhen, + conditional: { + hide: hideNextSteps + ? "=true" + : "=not(custom.wantsExtraCash)", + }, + benefitContent: { + benefit: { + eligible: { + applyUrl: "https://example.org/apply", + helpUrl: "https://example.org/help", + helpPhone: "215-555-0100", + body: "Screener-specific application instructions.", + }, + ineligible: { note: "Ask about other assistance." }, + }, + }, + }, + ] + : []), ], }, }, @@ -96,7 +127,18 @@ test.beforeEach(async ({ context }) => { benefit: { name: "Example benefit", result: input.custom.householdIncome <= 40000 ? "TRUE" : "FALSE", - check_results: {}, + check_results: + input.custom.householdIncome <= 40000 + ? {} + : { + income: { + name: "Income", + aliasName: "Income must be below $40,000", + result: "FALSE", + inputPaths: [], + parameters: {}, + }, + }, }, }, }); @@ -208,6 +250,15 @@ for (const serializeMessages of [false, true]) { await expect( record.getByText("Ineligible", { exact: true }), ).toBeVisible(); + await expect( + record.getByText("Ask about other assistance.", { exact: true }), + ).toBeVisible(); + await expect( + record.getByText("Income must be below $40,000", { exact: true }), + ).toBeVisible(); + await expect( + record.getByRole("link", { name: "Apply for this benefit" }), + ).toHaveCount(0); await expect(record.locator("#saved-screener")).toHaveText("crm-test"); await expect(record.locator("#saved-at")).toHaveAttribute( "datetime", @@ -246,6 +297,29 @@ for (const serializeMessages of [false, true]) { ).toBeVisible(); await page.locator("#save").click(); await expect(record.getByText("Eligible", { exact: true })).toBeVisible(); + await expect( + record.getByText("Screener-specific application instructions.", { + exact: true, + }), + ).toBeVisible(); + await expect( + record.getByRole("link", { name: "Apply for this benefit" }), + ).toHaveAttribute("href", "https://example.org/apply"); + // Hiding the component omits the extension; explicitly saving replaces old instructions. + await screener.getByLabel("Interested in cash assistance").uncheck(); + await expect(page.locator("#save")).toBeEnabled(); + await page.locator("#save").click(); + await expect( + record.getByText("Screener-specific application instructions.", { + exact: true, + }), + ).toHaveCount(0); + const stored = await page.evaluate( + () => + JSON.parse(localStorage.getItem("bdt.crm.browser-demo.record.v1")!) + .screening, + ); + expect(stored).not.toHaveProperty("nextSteps"); const savedAt = await record .locator("#saved-at") .getAttribute("datetime"); @@ -316,3 +390,53 @@ test("standalone screener still evaluates edited answers", async ({ page }) => { await page.getByLabel("Household income").fill("30000"); await expect(page.getByText("Eligible", { exact: true })).toBeVisible(); }); + +for (const scenario of ["absent", "hidden", "whenComplete"] as const) { + test(`CRM next steps are omitted or empty when ${scenario}`, async ({ + page, + baseURL, + context, + }) => { + includeNextSteps = scenario !== "absent"; + hideNextSteps = scenario === "hidden"; + showWhen = scenario === "whenComplete" ? "whenComplete" : "whenDecided"; + if (scenario === "whenComplete") + await context.route( + "**/api/published/crm-test/evaluate", + async (route) => { + if (route.request().method() !== "POST") return route.fallback(); + await route.fulfill({ + headers: { "Access-Control-Allow-Origin": "*" }, + json: { + benefit: { + name: "Example benefit", + result: "TRUE", + check_results: {}, + }, + utility: { + name: "Utility help", + result: "UNABLE_TO_DETERMINE", + check_results: {}, + }, + }, + }); + }, + ); + await page.goto(demoUrl); + await page + .locator("#screener-url") + .fill(new URL("/screener/crm-test", baseURL).href); + await page.locator("#monthly-income").fill("2000"); + await page.locator("#cash-interest").selectOption("requested"); + await page.locator("#embed").click(); + await expect(page.locator("#save")).toBeEnabled({ timeout: 15000 }); + await page.locator("#save").click(); + const stored = await page.evaluate( + () => + JSON.parse(localStorage.getItem("bdt.crm.browser-demo.record.v1")!) + .screening, + ); + if (scenario === "whenComplete") expect(stored.nextSteps).toEqual({}); + else expect(stored).not.toHaveProperty("nextSteps"); + }); +} diff --git a/examples/crm/browser/README.md b/examples/crm/browser/README.md index 937efbde..74592720 100644 --- a/examples/crm/browser/README.md +++ b/examples/crm/browser/README.md @@ -81,3 +81,15 @@ already running. Restart a manually running example server after adding assets. The tests verify that flat client fields reach the screener as mapped nested data, including monthly-to-annual income conversion. They intercept published API responses, so they require no Firebase emulators, login, published screener, or CRM account. + +## Saved next steps + +New result messages may include `nextSteps` alongside `results`. The example +saves both on the user's explicit Save action and shows application/help links, +contact numbers, instructions, and unmet requirements from that snapshot. +Markdown is displayed as plain text rather than inserted as HTML. Links accept +only HTTP(S) destinations without embedded credentials. Older saved records +without `nextSteps` continue to display their benefit decisions. + +Only visible screener content is sent. A missing `nextSteps` field or `{}` in a +new snapshot clears previous instructions; it does not mean to keep stale ones. diff --git a/examples/crm/browser/demo.html b/examples/crm/browser/demo.html index f67f6a81..f1ffe3b7 100644 --- a/examples/crm/browser/demo.html +++ b/examples/crm/browser/demo.html @@ -156,6 +156,13 @@ border: 1px solid #dce2ed; border-radius: 8px; } + .instructions { + white-space: pre-wrap; + overflow-wrap: anywhere; + } + .benefit a { + overflow-wrap: anywhere; + } .benefit h3 { font-size: 1rem; margin-bottom: 0.75rem; diff --git a/examples/crm/browser/demo.js b/examples/crm/browser/demo.js index 05986fee..0cb6d09a 100644 --- a/examples/crm/browser/demo.js +++ b/examples/crm/browser/demo.js @@ -76,6 +76,67 @@ function renderTime(id, value) { } } +// Render Markdown as plain text in this dependency-free demo; never inject HTML. +function appendNextSteps(item, steps, outcome) { + if ( + !steps || + !["eligible", "ineligible"].includes(outcome) || + steps.status !== outcome + ) + return; + const section = document.createElement("section"); + section.setAttribute("aria-label", "Saved next steps"); + const paragraph = (value) => { + if (typeof value !== "string" || !value.trim()) return; + const p = document.createElement("p"); + p.className = "instructions"; + p.textContent = value; + section.append(p); + }; + const link = (value, label) => { + if (typeof value !== "string") return; + try { + const url = new URL(value); + if ( + !["http:", "https:"].includes(url.protocol) || + url.username || + url.password + ) + return; + const a = document.createElement("a"); + a.href = url.href; + a.textContent = label; + a.target = "_blank"; + a.rel = "noopener noreferrer"; + const p = document.createElement("p"); + p.append(a); + section.append(p); + } catch { + /* Ignore invalid saved URLs. */ + } + }; + if (outcome === "eligible") { + link(steps.applyUrl, "Apply for this benefit"); + link(steps.help?.url, "Get help"); + if (typeof steps.help?.phone === "string") + paragraph(`Help phone: ${steps.help.phone}`); + if (steps.body?.format === "markdown") paragraph(steps.body.text); + } else { + if (Array.isArray(steps.unmetRequirements)) { + const list = document.createElement("ul"); + for (const requirement of steps.unmetRequirements) { + if (typeof requirement !== "string") continue; + const li = document.createElement("li"); + li.textContent = requirement; + list.append(li); + } + section.append(list); + } + if (steps.note?.format === "markdown") paragraph(steps.note.text); + } + item.append(section); +} + function renderRecord() { // Read the stored record, rather than displaying the latest unsaved message. const snapshot = readRecord().screening; @@ -106,6 +167,15 @@ function renderRecord() { status.className = `outcome ${outcome.style}`; status.textContent = outcome.label; item.append(name, status); + appendNextSteps( + item, + snapshot.nextSteps?.[id], + benefit.result === "TRUE" + ? "eligible" + : benefit.result === "FALSE" + ? "ineligible" + : "unknown", + ); element("saved-results").append(item); } } @@ -182,6 +252,7 @@ element("save").addEventListener("click", () => { evaluatedAt: latest.evaluatedAt, savedAt: new Date().toISOString(), results: latest.results, + nextSteps: latest.nextSteps, }, }), ); diff --git a/examples/crm/salesforce/README.md b/examples/crm/salesforce/README.md index 3e94bc71..ace8f8c1 100644 --- a/examples/crm/salesforce/README.md +++ b/examples/crm/salesforce/README.md @@ -120,3 +120,15 @@ Salesforce references: - [Objects proxied by Lightning Web Security](https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-proxies.html) - [Iframe access with Lightning Web Security](https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-iframes.html) - [Trusted URLs and third-party JavaScript](https://developer.salesforce.com/docs/platform/lwc/guide/js-api-calls) + +## Saved next steps + +New result messages may include `nextSteps` alongside `results`. The example +saves both on the user's explicit Save action and shows application/help links, +contact numbers, instructions, and unmet requirements from that snapshot. +Markdown is displayed as plain text rather than inserted as HTML. Links accept +only HTTP(S) destinations without embedded credentials. Older saved records +without `nextSteps` continue to display their benefit decisions. + +Only visible screener content is sent. A missing `nextSteps` field or `{}` in a +new snapshot clears previous instructions; it does not mean to keep stale ones. diff --git a/examples/crm/salesforce/bdtScreening/bdtScreening.js b/examples/crm/salesforce/bdtScreening/bdtScreening.js index 65f6331c..640b16e2 100644 --- a/examples/crm/salesforce/bdtScreening/bdtScreening.js +++ b/examples/crm/salesforce/bdtScreening/bdtScreening.js @@ -146,6 +146,7 @@ export default class BdtScreening extends LightningElement { requestId: message.requestId, evaluatedAt: message.evaluatedAt, results: message.results, + nextSteps: message.nextSteps, }); if (snapshot.length > 131072) { this.status = diff --git a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css index 4a1fae69..70dc3831 100644 --- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css +++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css @@ -124,3 +124,19 @@ font-size: 0.75rem; overflow-wrap: anywhere; } + +.next-steps { + margin-top: 0.75rem; + overflow-wrap: anywhere; +} +.next-steps h4 { + font-weight: 600; +} +.next-steps p { + margin-top: 0.5rem; + white-space: pre-wrap; +} +.next-steps ul { + list-style: disc; + padding-left: 1.25rem; +} diff --git a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html index 17745c92..d0fef037 100644 --- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html +++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html @@ -32,6 +32,41 @@

{benefit.name}

{benefit.status}
+ -
    - -
+