diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 2f858ce9..6ef7423e 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [builder-frontend, builder-api, library-api, e2e] + suite: [builder-frontend, builder-api, library-api, examples, e2e] steps: - name: Checkout uses: actions/checkout@v4 @@ -25,7 +25,7 @@ jobs: uses: ./.github/actions/devbox-setup - name: Cache Maven dependencies - if: matrix.suite != 'builder-frontend' + if: matrix.suite != 'builder-frontend' && matrix.suite != 'examples' uses: actions/cache@v4 with: path: ~/.m2/repository diff --git a/AGENTS.md b/AGENTS.md index 80b9ba7a..15b9c1a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ This is a monorepo for building and publishing benefit eligibility screeners. Ke - Preferred one-time setup: `bin/install-devbox && devbox run setup` - In worktrees, agents may create the ignored root `.env` from `.env.example` when needed to run Devbox commands. The preferred setup command above does this automatically. - Start the development stack: `devbox services up` -- All tests: `devbox run test` (wrapper: `bin/run-all-tests`; accepts `--fail-fast` and suite names `builder-frontend`, `builder-api`, `library-api`, `e2e`) +- All tests: `devbox run test` (wrapper: `bin/run-all-tests`; accepts `--fail-fast` and suite names `builder-frontend`, `builder-api`, `library-api`, `examples`, `e2e`) - Backend tests: `(cd builder-api && mvn test)` - Library tests: `(cd library-api && mvn test)`; DMN API tests require a running library service, then `(cd library-api/test/bdt && bru run)` - Frontend tests: `(cd builder-frontend && npm test)`; frontend build: `(cd builder-frontend && npm run build)` diff --git a/bin/run-all-tests b/bin/run-all-tests index 7ceb053a..91d4e7b3 100755 --- a/bin/run-all-tests +++ b/bin/run-all-tests @@ -6,11 +6,12 @@ # 1. builder-frontend - Vitest unit tests (npm test) # 2. builder-api - JVM unit/integration tests (mvn test) # 3. library-api - JVM unit/integration tests (mvn test) -# 4. e2e - bin/run-e2e-tests, which boots the full dev stack with +# 4. examples - Node tests for the CRM examples (node --test) +# 5. e2e - bin/run-e2e-tests, which boots the full dev stack with # devbox services and then runs the library-api Bruno # collection followed by the Playwright suite. # -# The unit suites run first because they need nothing but npm and Maven, while +# The unit suites run first because they need nothing but Node and Maven, while # the e2e suite takes exclusive ownership of the local service ports and swaps # the root emulator-data directory for the e2e fixtures. # @@ -27,7 +28,7 @@ source "$SCRIPT_DIR/functions" cd "$PROJECT_ROOT" -ALL_SUITES=(builder-frontend builder-api library-api e2e) +ALL_SUITES=(builder-frontend builder-api library-api examples e2e) FAIL_FAST=0 usage() { @@ -42,6 +43,7 @@ Suites: builder-frontend builder-frontend Vitest tests (npm test) builder-api builder-api JVM tests (mvn test) library-api library-api JVM tests (mvn test) + examples CRM example Node tests (node --test) e2e full dev stack, library-api Bruno collection, Playwright suite With no suite arguments, all suites run in the order listed above. @@ -154,6 +156,10 @@ if suite_selected builder-api || suite_selected library-api; then require_command mvn fi +if suite_selected examples; then + require_command node +fi + # The JVM suites read component .env files directly, and bin/run-e2e-tests needs # the root .env for the Devbox service graph. Create any that are missing from # the checked-in examples before the first suite runs. @@ -195,6 +201,10 @@ run_library_api_suite() { ) } +run_examples_suite() { + node --test examples/crm/*/tests/*.test.mjs +} + run_e2e_suite() { bin/run-e2e-tests } @@ -266,6 +276,10 @@ if suite_selected library-api; then run_suite "library-api" run_library_api_suite fi +if suite_selected examples; then + run_suite "examples" run_examples_suite +fi + if suite_selected e2e; then run_suite "e2e" run_e2e_suite fi diff --git a/builder-frontend/public/integrations/host.js b/builder-frontend/public/integrations/host.js index 91094259..4c12aaa7 100644 --- a/builder-frontend/public/integrations/host.js +++ b/builder-frontend/public/integrations/host.js @@ -6,6 +6,30 @@ function randomId() { ).join(""); } +/** + * Returns a saved next-steps link if it's one the screener would send: HTTP(S) + * with a hostname (no underscores) and no credentials. Otherwise returns null. + * Validate saved snapshots with this before making a link clickable. + * @param {unknown} value + * @returns {string | null} + */ +export function safeHttpUrl(value) { + if (typeof value !== "string") return null; + let url; + try { + url = new URL(value); + } catch { + return null; + } + return ["http:", "https:"].includes(url.protocol) && + url.hostname && + !url.hostname.includes("_") && + !url.username && + !url.password + ? url.href + : null; +} + /** * BDT CRM host adapter. Install the listener before navigating the iframe/popup. * Copy this module into your CRM's source tree if remote modules are restricted. @@ -145,7 +169,16 @@ export function createCrmIntegration({ !Array.isArray(message.inputData) && typeof message.evaluatedAt === "string" ) { - onResult(message); + // nextSteps is optional: drop a malformed one, never the results. + const { nextSteps, ...rest } = message; + onResult( + nextSteps === undefined || + (nextSteps && + typeof nextSteps === "object" && + !Array.isArray(nextSteps)) + ? message + : rest, + ); } else if ( message.type === "error" && ["SCREENER_UNAVAILABLE", "ORIGIN_NOT_ALLOWED"].includes(message.code) diff --git a/builder-frontend/src/components/screener/FormRenderer.test.tsx b/builder-frontend/src/components/screener/FormRenderer.test.tsx index c56d6132..4533a1ef 100644 --- a/builder-frontend/src/components/screener/FormRenderer.test.tsx +++ b/builder-frontend/src/components/screener/FormRenderer.test.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { createSignal } from "solid-js"; import { render } from "solid-js/web"; import { afterEach, describe, expect, it, vi } from "vitest"; import FormRenderer from "./FormRenderer"; @@ -31,6 +32,222 @@ 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(); + // Follows the answers at once, without waiting for form-js to repaint. + expect(provider(results)).toBeUndefined(); + dispose(); + dispose = undefined; + expect(register).toHaveBeenLastCalledWith(undefined); + }); + + it("reads visibility from conditions, including groups, while the form re-imports", async () => { + const register = vi.fn(); + const [hidden, setHidden] = createSignal([]); + const content = (body: string) => ({ + benefit: { eligible: { body } }, + }); + dispose = render( + () => ( + ({})} + hiddenQuestionPaths={hidden} + submitForm={() => {}} + registerNextStepsProvider={register} + /> + ), + document.body.appendChild(document.createElement("div")), + ); + 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("Shown group"); + // Hiding a question re-imports the form; the export must not see a gap. + setHidden(["city"]); + expect(provider(results).benefit.body.text).toBe("Shown group"); + }); + + it("exports visible instructions from a dynamic list with repetition disabled", async () => { + const register = vi.fn(); + const container = document.body.appendChild(document.createElement("div")); + dispose = render( + () => ( + ({ person: { show: true } })} + hiddenQuestionPaths={() => []} + submitForm={() => {}} + registerNextStepsProvider={register} + /> + ), + container, + ); + await vi.waitFor(() => expect(register).toHaveBeenCalledOnce()); + const exported = register.mock.calls[0][0]({ + benefit: { name: "Benefit", result: "TRUE", check_results: {} }, + }); + expect(exported.benefit.body.text).toBe("Single-person instructions"); + }); + + it.each([ + [[{ show: false }, { show: true }], "Per item"], + [[{ show: false }], undefined], + ])( + "checks Next steps in a repeated group against each item (%j)", + async (people, body) => { + const register = vi.fn(); + dispose = render( + () => ( + ({ people })} + hiddenQuestionPaths={() => []} + submitForm={() => {}} + registerNextStepsProvider={register} + /> + ), + document.body.appendChild(document.createElement("div")), + ); + await vi.waitFor(() => expect(register).toHaveBeenCalledOnce()); + const exported = register.mock.calls[0][0]({ + benefit: { name: "Benefit", result: "TRUE", check_results: {} }, + }); + expect(exported?.benefit.body?.text).toBe(body); + }, + ); + 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..c77f83cc 100644 --- a/builder-frontend/src/components/screener/FormRenderer.tsx +++ b/builder-frontend/src/components/screener/FormRenderer.tsx @@ -11,6 +11,11 @@ import { connectScreeningResults, screeningResultsModule, } from "../screenerEditor/formJsExtensions/screeningResults/screeningResults"; +import { firstVisibleNextSteps } from "../screenerEditor/formJsExtensions/nextSteps/selection"; +import { + projectNextSteps, + type NextStepsProvider, +} from "@/integrations/nextSteps"; import type { ScreenerResult } from "@/types"; import { hideQuestions } from "@/utils/questionVotes"; import { normalizeArrayFieldData } from "@/utils/arrayFieldData"; @@ -34,7 +39,9 @@ function FormRenderer({ failed = () => false, onNextStepsShownChange, screenerName, + registerNextStepsProvider, }: { + registerNextStepsProvider?: (provider: NextStepsProvider | undefined) => void; schema: { [key: string]: any }; formData: Accessor; hiddenQuestionPaths: Accessor; @@ -53,6 +60,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 +106,13 @@ function FormRenderer({ form .importSchema(hideQuestions(schema, hiddenQuestionPaths()), formData()) .then(() => { + if (disposed) return; + registerNextStepsProvider?.((results) => + projectNextSteps( + results, + firstVisibleNextSteps((name) => form!.get(name)), + ), + ); currentData = cloneDeep(form?._getState().data || formData()); if (evaluateInitialData) { unknownPaths = findFilledUnknownPaths(formData(), currentData); @@ -115,6 +130,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..f20adaa2 100644 --- a/builder-frontend/src/components/screener/Screener.test.tsx +++ b/builder-frontend/src/components/screener/Screener.test.tsx @@ -21,6 +21,7 @@ const integration = vi.hoisted(() => ({ error: vi.fn(), fail: vi.fn(), origin: "https://crm.example", + registerNextStepsProvider: undefined as unknown, })); vi.mock("@solidjs/router", () => ({ @@ -49,17 +50,22 @@ vi.mock("@/integrations/screenerBridge", () => ({ })); vi.mock("./FormRenderer", () => ({ default: (props: any) => { + integration.registerNextStepsProvider = props.registerNextStepsProvider; onMount(() => { if (props.evaluateInitialData) props.submitForm(props.formData()); }); return ( <> - + ); }, @@ -110,11 +116,13 @@ describe("published screener integration lifecycle", () => { initialData, ), ); + expect(integration.registerNextStepsProvider).toBeTypeOf("function"); container.querySelector("button")!.click(); await vi.waitFor(() => expect(integration.result).toHaveBeenCalledOnce()); expect(integration.result).toHaveBeenLastCalledWith( { custom: { householdIncome: 50000 } }, result("FALSE"), + undefined, ); old.resolve(result("TRUE")); await old.promise; @@ -256,5 +264,6 @@ describe("published screener integration lifecycle", () => { container.querySelector("button")!.click(); await vi.waitFor(() => expect(container.textContent).toContain("Eligible")); expect(integration.result).not.toHaveBeenCalled(); + expect(integration.registerNextStepsProvider).toBeUndefined(); }); }); diff --git a/builder-frontend/src/components/screener/Screener.tsx b/builder-frontend/src/components/screener/Screener.tsx index e589b013..0b386788 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; @@ -103,7 +105,11 @@ export default function Screener() { setScreenerResult(evaluationResult); setResultsStale(false); setEvaluationFailed(false); - bridge?.result(data, evaluationResult); + bridge?.result( + data, + evaluationResult, + nextStepsProvider?.(evaluationResult), + ); } catch (err) { if (sequence !== evaluationSequence) return; setEvaluationFailed(true); @@ -144,6 +150,13 @@ export default function Screener() {
{ + nextStepsProvider = provider; + }) + } screenerName={() => screener()?.screenerName ?? ""} schema={screener()?.formSchema || {}} formData={formData} diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts index 42d91a96..71860c8f 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts @@ -6,13 +6,17 @@ import { sanitizeHTML, Text, } from "@bpmn-io/form-js-viewer"; -import type { BenefitResult, NextSteps as Content } from "@/types"; +import type { BenefitResult } from "@/types"; import { useScreeningResults } from "../screeningResults/useScreeningResults"; import { NEXT_STEPS_TYPE, + benefitNextSteps, contactLink, + isDecided, + showsDecided, webLink, type BenefitContent, + type BenefitNextSteps, } from "./content"; import "./nextSteps.css"; @@ -56,15 +60,15 @@ function Markdown({ } function Eligible({ - content, + steps, forPrint, }: { - content?: Content; + steps: BenefitNextSteps; forPrint?: boolean; }) { - const apply = webLink(content?.eligible?.applyUrl); - const help = webLink(content?.eligible?.helpUrl); - const phone = content?.eligible?.helpPhone?.trim(); + const apply = steps.applyUrl; + const help = steps.help.url; + const phone = steps.help.phone; const dial = phone && /^[+\d\s().-]+$/.test(phone) ? phone.replace(/[^+\d]/g, "") @@ -86,7 +90,7 @@ function Eligible({ ${dial ? html`${phone}` : phone}`}
- <${Markdown} text=${content?.eligible?.body} forPrint=${forPrint} /> + <${Markdown} text=${steps.body?.text} forPrint=${forPrint} /> `; } @@ -105,8 +109,7 @@ export function NextSteps({ field }: { field: NextStepsField }) { const { results, pending, failed, mode } = useScreeningResults(); const benefits = Object.entries(results ?? {}); const complete = - benefits.length > 0 && - benefits.every(([, benefit]) => ["TRUE", "FALSE"].includes(benefit.result)); + benefits.length > 0 && benefits.every(([, benefit]) => isDecided(benefit)); // Stays in the DOM so screen readers announce completion, as the page's message did. return html`

@@ -158,7 +161,10 @@ export function NextStepsBody({ Next steps will appear after screening.

` : null; - const hideDecided = field.showWhen === "whenComplete" && !complete; + const hideDecided = !showsDecided( + field, + benefits.map(([, benefit]) => benefit), + ); return html`
Answer the remaining questions to see your next steps.

`} ${benefits.map(([id, benefit]) => { - const content = field.benefitContent?.[id]; - if (benefit.result === "UNABLE_TO_DETERMINE") + const steps = benefitNextSteps(benefit, field.benefitContent?.[id]); + if (!steps) return html`

${benefit.name}

Still needs more information.

`; if (hideDecided) return null; - const unmet = Object.values(benefit.check_results ?? {}).filter( - (check) => check.result === "FALSE", - ); + const unmet = steps.unmetRequirements; return html`

${benefit.name}

- ${benefit.result === "TRUE" - ? html`<${Eligible} content=${content} forPrint=${forPrint} />` + ${steps.status === "eligible" + ? html`<${Eligible} steps=${steps} forPrint=${forPrint} />` : html`

You do not appear to be eligible. @@ -196,15 +200,9 @@ export function NextStepsBody({ ${unmet.length > 0 && html`

Requirements not met

    - ${unmet.map( - (check) => - html`
  • ${check.aliasName?.trim() || check.name}
  • `, - )} + ${unmet.map((name) => html`
  • ${name}
  • `)}
`} - <${Markdown} - text=${content?.ineligible?.note} - forPrint=${forPrint} - /> + <${Markdown} text=${steps.note?.text} forPrint=${forPrint} /> `}
`; })} diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts index e9b998cc..6efb80f6 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts @@ -1,6 +1,7 @@ import cloneDeep from "lodash/cloneDeep"; -import type { Benefit, NextSteps } from "@/types"; +import type { Benefit, BenefitResult, NextSteps } from "@/types"; import { normalizeHttpUrl } from "@/utils/httpUrl"; +import type { NextStepsField } from "./NextSteps"; export const NEXT_STEPS_TYPE = "next_steps"; export type BenefitContent = Record; @@ -41,3 +42,60 @@ export function contactLink(value?: string | null): string | undefined { /* An invalid contact is omitted. */ } } + +export type Markdown = { format: "markdown"; text: string }; +/** A decided benefit's Next steps, as the field shows them and CRM hosts receive them. */ +export type BenefitNextSteps = { + status: "eligible" | "ineligible"; + applyUrl: string | null; + help: { url: string | null; phone: string | null }; + body: Markdown | null; + unmetRequirements: string[]; + note: Markdown | null; +}; + +export const isDecided = (benefit: BenefitResult) => + benefit.result === "TRUE" || benefit.result === "FALSE"; + +/** A whenComplete field shows decided benefits only once every benefit is decided. */ +export const showsDecided = ( + field: NextStepsField, + benefits: BenefitResult[], +) => field.showWhen !== "whenComplete" || benefits.every(isDecided); + +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; + +/** Only the saved copy for the benefit's outcome; undefined while undecided. */ +export function benefitNextSteps( + benefit: BenefitResult, + content?: NextSteps, +): BenefitNextSteps | undefined { + if (!isDecided(benefit)) return; + if (benefit.result === "TRUE") + return { + status: "eligible", + applyUrl: webLink(content?.eligible?.applyUrl) ?? null, + help: { + url: webLink(content?.eligible?.helpUrl) ?? null, + phone: text(content?.eligible?.helpPhone)?.trim() ?? null, + }, + body: markdown(content?.eligible?.body), + unmetRequirements: [], + note: null, + }; + return { + status: "ineligible", + applyUrl: null, + help: { url: null, phone: null }, + body: null, + unmetRequirements: Object.values(benefit.check_results ?? {}) + .filter((check) => check.result === "FALSE") + .map((check) => check.aliasName?.trim() || check.name) + // An unnamed check has nothing to show. + .filter((name): name is string => !!name?.trim()), + note: markdown(content?.ineligible?.note), + }; +} 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..348769b3 --- /dev/null +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts @@ -0,0 +1,72 @@ +import get from "lodash/get"; +import { buildExpressionContext } from "@bpmn-io/form-js-viewer"; +import type { NextStepsField } from "./NextSteps"; +import { NEXT_STEPS_TYPE } from "./content"; + +type ExpressionContext = { data: any; this: any; parent: any; i: number[] }; + +/** + * Shared by print and CRM exports: the first component in schema order that form-js shows, + * judged by its and its groups' hide conditions against the current answers, as form-js + * judges them. Reading conditions rather than mounted fields keeps a re-import from + * briefly hiding every Next steps component. + */ +export function firstVisibleNextSteps( + getService: (name: string) => any, +): NextStepsField | undefined { + const form = getService("formFieldRegistry").getForm(); + if (!form) return; + const conditionChecker = getService("conditionChecker"); + const pathRegistry = getService("pathRegistry"); + const formFields = getService("formFields"); + const { data, initialData } = getService("form")._getState(); + // The root context form-js renders with: answers minus those hidden by conditions. + const filtered = { + ...initialData, + ...conditionChecker.applyConditions(data, data), + }; + const find = ( + fields: any[] | undefined, + context: ExpressionContext, + indexes: Record, + ): NextStepsField | undefined => { + for (const field of fields ?? []) { + const hide = field.conditional?.hide; + if ( + hide && + conditionChecker.check(hide, buildExpressionContext(context)) === true + ) + continue; + if (field.type === NEXT_STEPS_TYPE) return field; + if ( + !formFields.get(field.type)?.config.repeatable || + !field.isRepeating + ) { + const nested = find(field.components, context, indexes); + if (nested) return nested; + continue; + } + // A repeated group renders its components once per item, each in its own scope. + const items = get(data, pathRegistry.getValuePath(field, { indexes })); + const rows: unknown[] = Array.isArray(items) ? items : []; + for (const [index, item] of rows.entries()) { + const nested = find( + field.components, + { + data: context.data, + this: item, + parent: buildExpressionContext({ ...context, data: context.this }), + i: [...context.i, index + 1], + }, + { ...indexes, [field.id]: index }, + ); + if (nested) return nested; + } + } + }; + return find( + form.components, + { data: filtered, this: filtered, parent: null, i: [] }, + {}, + ); +} diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts index 48c3d046..2a7bc7d9 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 { isDecided, webLink } from "../nextSteps/content"; +import { firstVisibleNextSteps } from "../nextSteps/selection"; import type { ScreeningResultsService } from "../screeningResults/screeningResults"; import { useScreeningResults } from "../screeningResults/useScreeningResults"; import "./printSummary.css"; @@ -74,21 +75,8 @@ 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( - context.getService("formFieldRegistry").getForm()?.components ?? [], - ) ?? {}; + firstVisibleNextSteps(context.getService) ?? {}; const root = document.createElement("article"); root.className = "bdt-print-root"; const printMedia = window.matchMedia?.("print"); @@ -118,9 +106,7 @@ export function PrintSummary() { <${NextStepsBody} field=${source} benefits=${benefits} - complete=${benefits.every(([, benefit]) => - ["TRUE", "FALSE"].includes(benefit.result), - )} + complete=${benefits.every(([, benefit]) => isDecided(benefit))} pending=${false} failed=${false} mode="live" diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts index 6a682a49..bc35b2f6 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts @@ -68,10 +68,6 @@ export class ScreeningResultsService { isNextStepsShown = (): boolean => this.reportedNextStepsShown; - /** Whether this Next steps field is rendered, so not hidden by a condition. */ - isNextStepsFieldShown = (fieldId: string): boolean => - this.nextStepsShown.includes(fieldId); - private reportNextStepsShown(): void { const shown = this.nextStepsShown.length > 0; if (shown === this.reportedNextStepsShown) return; diff --git a/builder-frontend/src/integrations/nextSteps.test.ts b/builder-frontend/src/integrations/nextSteps.test.ts new file mode 100644 index 00000000..dcfb4659 --- /dev/null +++ b/builder-frontend/src/integrations/nextSteps.test.ts @@ -0,0 +1,100 @@ +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, + d: { result: "FALSE", aliasName: " " } 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..86edfde5 --- /dev/null +++ b/builder-frontend/src/integrations/nextSteps.ts @@ -0,0 +1,27 @@ +import type { ScreenerResult } from "@/types"; +import type { NextStepsField } from "@/components/screenerEditor/formJsExtensions/nextSteps/NextSteps"; +import { + benefitNextSteps, + showsDecided, + type BenefitNextSteps, +} from "@/components/screenerEditor/formJsExtensions/nextSteps/content"; + +export type CrmNextSteps = Record; +export type NextStepsProvider = ( + results: ScreenerResult, +) => CrmNextSteps | undefined; + +/** Project the saved screener copy, never evaluation-provider content or generated HTML. */ +export function projectNextSteps( + results: ScreenerResult, + field?: NextStepsField, +): CrmNextSteps | undefined { + if (!field) return; + if (!showsDecided(field, Object.values(results))) return {}; + return Object.fromEntries( + Object.entries(results).flatMap(([id, benefit]) => { + const steps = benefitNextSteps(benefit, field.benefitContent?.[id]); + return steps ? [[id, steps]] : []; + }), + ); +} diff --git a/builder-frontend/src/integrations/screenerBridge.test.ts b/builder-frontend/src/integrations/screenerBridge.test.ts index f599f422..0519930d 100644 --- a/builder-frontend/src/integrations/screenerBridge.test.ts +++ b/builder-frontend/src/integrations/screenerBridge.test.ts @@ -1,6 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CONNECT_TIMEOUT_MS, createScreeningBridge } from "./screenerBridge"; -import { createCrmIntegration } from "../../public/integrations/host.js"; +import { + createCrmIntegration, + safeHttpUrl, +} from "../../public/integrations/host.js"; +import { normalizeHttpUrl } from "@/utils/httpUrl"; const results = { benefit: { name: "Benefit", result: "TRUE" as const, check_results: {} }, @@ -79,6 +83,69 @@ afterEach(() => { }); describe("published screener CRM bridge", () => { + it.each([ + "https://example.org/apply", + "http://example.org/a b", + "javascript:alert(1)", + "https://user:secret@example.org/", + "http://under_score/", + "file:///etc/passwd", + "not a url", + ])("checks saved links as the screener does (%s)", (value) => { + expect(safeHttpUrl(value) !== null).toBe(normalizeHttpUrl(value) !== null); + }); + 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]; + for (const malformed of [[], null, "Bring ID"]) { + s.receive( + serializeMessages + ? JSON.stringify({ ...last, nextSteps: malformed }) + : { ...last, nextSteps: malformed }, + ); + expect(onResult.mock.lastCall![0]).toMatchObject({ results }); + expect(onResult.mock.lastCall![0]).not.toHaveProperty("nextSteps"); + } + 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..35026fa8 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,55 @@ 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. If +`nextSteps` isn't an object, the adapter drops that field and still delivers the +result. + +```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; `host.js` exports `safeHttpUrl` for this. 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..4c7463da 100644 --- a/examples/crm/browser/README.md +++ b/examples/crm/browser/README.md @@ -81,3 +81,16 @@ 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 pass +through the adapter's `safeHttpUrl`, which accepts only the HTTP(S) links the +screener sends. 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..cd6148bd 100644 --- a/examples/crm/browser/demo.js +++ b/examples/crm/browser/demo.js @@ -1,4 +1,4 @@ -import { createCrmIntegration } from "./host.js"; +import { createCrmIntegration, safeHttpUrl } from "./host.js"; import { clientToScreenerData } from "./clientMapping.mjs"; const element = (id) => document.getElementById(id); @@ -76,6 +76,58 @@ 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) => { + const href = safeHttpUrl(value); + if (!href) return; + const a = document.createElement("a"); + a.href = href; + a.textContent = label; + a.target = "_blank"; + a.rel = "noopener noreferrer"; + const p = document.createElement("p"); + p.append(a); + section.append(p); + }; + 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 { + const list = document.createElement("ul"); + for (const requirement of Array.isArray(steps.unmetRequirements) + ? steps.unmetRequirements + : []) { + if (typeof requirement !== "string") continue; + const li = document.createElement("li"); + li.textContent = requirement; + list.append(li); + } + if (list.childElementCount) section.append(list); + if (steps.note?.format === "markdown") paragraph(steps.note.text); + } + // Leave out a benefit with no usable saved content, rather than an empty region. + if (section.childElementCount) item.append(section); +} + function renderRecord() { // Read the stored record, rather than displaying the latest unsaved message. const snapshot = readRecord().screening; @@ -106,6 +158,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 +243,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..8ddf9994 100644 --- a/examples/crm/salesforce/README.md +++ b/examples/crm/salesforce/README.md @@ -120,3 +120,18 @@ 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 pass +through the adapter's `safeHttpUrl`, which accepts only the HTTP(S) links the +screener sends. Older saved records +without `nextSteps` continue to display their benefit decisions. If the +snapshot with `nextSteps` exceeds the field size, the example saves the +decisions without `nextSteps` and says so. + +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..4c696fb3 100644 --- a/examples/crm/salesforce/bdtScreening/bdtScreening.js +++ b/examples/crm/salesforce/bdtScreening/bdtScreening.js @@ -141,12 +141,20 @@ export default class BdtScreening extends LightningElement { async save() { if (this.cannotSave) return; const { recordId, message } = this.latest; - const snapshot = JSON.stringify({ + const decisions = { screenerId: message.screenerId, requestId: message.requestId, evaluatedAt: message.evaluatedAt, results: message.results, + }; + let snapshot = JSON.stringify({ + ...decisions, + nextSteps: message.nextSteps, }); + // Keep the decisions when instructions push the snapshot past the field size. + const droppedNextSteps = + snapshot.length > 131072 && message.nextSteps !== undefined; + if (droppedNextSteps) snapshot = JSON.stringify(decisions); if (snapshot.length > 131072) { this.status = "Results exceed the configured field size; use a related screening object."; @@ -158,7 +166,9 @@ export default class BdtScreening extends LightningElement { fields: { Id: recordId, [SCREENING.fieldApiName]: snapshot }, }); if (this.recordId === recordId) - this.status = "Screening results saved to the client record."; + this.status = droppedNextSteps + ? "Screening results saved without next steps, which exceed the configured field size." + : "Screening results saved to the client record."; } catch { if (this.recordId === recordId) this.status = "Could not save. Check field permissions and try again."; 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..29a01759 100644 --- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html +++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html @@ -32,6 +32,43 @@

{benefit.name}

{benefit.status} +