diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/CustomBenefitResource.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/CustomBenefitResource.java
index a84a8b3f..b3536463 100644
--- a/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/CustomBenefitResource.java
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/CustomBenefitResource.java
@@ -4,6 +4,7 @@
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
@@ -13,6 +14,7 @@
import org.codeforphilly.bdt.builder.model.dto.custombenefit.AddCheckRequest;
import org.codeforphilly.bdt.builder.model.dto.custombenefit.CreateCustomBenefitRequest;
import org.codeforphilly.bdt.builder.model.dto.custombenefit.UpdateCheckAliasRequest;
+import org.codeforphilly.bdt.builder.model.dto.custombenefit.UpdateCheckExplanationRequest;
import org.codeforphilly.bdt.builder.model.dto.custombenefit.UpdateCheckParametersRequest;
import org.codeforphilly.bdt.builder.model.dto.custombenefit.UpdateCustomBenefitRequest;
import org.codeforphilly.bdt.builder.persistence.EligibilityCheckRepository;
@@ -31,6 +33,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
+import java.util.function.Consumer;
@Path("/api")
public class CustomBenefitResource {
@@ -318,7 +321,6 @@ public Response addCheckToBenefit(
}
EligibilityCheck check = checkOpt.get();
- Benefit benefit = benefitOpt.get();
Map parameters = request.parameters() != null
? new HashMap<>(request.parameters())
: new HashMap<>();
@@ -358,17 +360,16 @@ public Response addCheckToBenefit(
checkConfig.setAliasGenerated(aliasName.isPresent());
// Add the check to the benefit
- List checks = benefit.getChecks();
- if (checks == null) {
- checks = new ArrayList<>();
- } else {
- checks = new ArrayList<>(checks);
+ boolean added = screenerRepository.updateCustomBenefitChecks(screenerId, benefitId, checks -> {
+ List updatedChecks = new ArrayList<>(checks);
+ updatedChecks.add(checkConfig);
+ return updatedChecks;
+ });
+ if (!added) {
+ return Response.status(Response.Status.NOT_FOUND)
+ .entity(Map.of("error", "Benefit not found"))
+ .build();
}
- checks.add(checkConfig);
- benefit.setChecks(checks);
-
- // Save the updated benefit
- screenerRepository.updateCustomBenefit(screenerId, benefit);
return Response.ok(Map.of("aliasGenerated", aliasName.isPresent())).build();
} catch (Exception e) {
@@ -394,39 +395,16 @@ public Response removeCheckFromBenefit(
}
try {
- // Get the benefit
- Optional benefitOpt = screenerRepository.getCustomBenefit(screenerId, benefitId);
- if (benefitOpt.isEmpty()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Benefit not found"))
- .build();
- }
-
- Benefit benefit = benefitOpt.get();
- List checks = benefit.getChecks();
-
- if (checks == null || checks.isEmpty()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
- }
-
// Remove the check with the matching checkId
- List updatedChecks = checks.stream()
- .filter(check -> !check.getCheckId().equals(checkId))
- .toList();
+ boolean removed = screenerRepository.updateCustomBenefitChecks(screenerId, benefitId, checks -> {
+ List updatedChecks = new ArrayList<>(checks);
+ return updatedChecks.removeIf(check -> checkId.equals(check.getCheckId())) ? updatedChecks : null;
+ });
- if (updatedChecks.size() == checks.size()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
+ if (!removed) {
+ return checkOrBenefitNotFound(screenerId, benefitId);
}
- benefit.setChecks(new ArrayList<>(updatedChecks));
-
- // Save the updated benefit
- screenerRepository.updateCustomBenefit(screenerId, benefit);
-
return Response.ok().build();
} catch (Exception e) {
Log.error(e);
@@ -461,49 +439,47 @@ public Response updateCheckParameters(
.build();
}
- Benefit benefit = benefitOpt.get();
- List checks = benefit.getChecks();
-
- if (checks == null || checks.isEmpty()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
- }
-
- // Find and update the check with the matching checkId
- Boolean checkUpdated = false;
- boolean aliasCleared = false;
- List checkListAfterUpdate = new ArrayList<>();
- for (CheckConfig check : checks) {
- if (check.getCheckId().equals(checkId)) {
- Map parameters = request.parameters() != null ? request.parameters() : new HashMap<>();
- boolean parametersChanged = !sameParameterValues(check.getParameters(), parameters);
- check.setParameters(parameters);
- // A generated alias describes the old parameter values, so refresh it.
- // Hand-written aliases are left alone.
- if (parametersChanged && check.isAliasGenerated()) {
- Optional aliasName = eligibilityCheckAliasService.generate(check.getCheckName(), parameters);
- check.setAliasName(aliasName.orElse(null));
- check.setAliasGenerated(aliasName.isPresent());
- aliasCleared = aliasName.isEmpty();
+ List checks = benefitOpt.get().getChecks();
+ Map parameters = request.parameters() != null ? request.parameters() : new HashMap<>();
+
+ // A generated alias describes the old parameter values, so refresh it.
+ // Hand-written aliases are left alone. Generating takes seconds, too long for the
+ // transaction below, which keeps any check edit made in the meantime.
+ Optional staleAlias = (checks == null ? List.of() : checks).stream()
+ .filter(check -> checkId.equals(check.getCheckId()) && check.isAliasGenerated())
+ .filter(check -> !sameParameterValues(check.getParameters(), parameters))
+ .findFirst();
+ Optional aliasName = staleAlias.isPresent()
+ ? eligibilityCheckAliasService.generate(staleAlias.get().getCheckName(), parameters)
+ : Optional.empty();
+
+ boolean[] aliasCleared = { false };
+ boolean checkUpdated = screenerRepository.updateCustomBenefitChecks(screenerId, benefitId, storedChecks -> {
+ // Firestore can rerun this callback; report only the committed attempt.
+ aliasCleared[0] = false;
+ List matching = storedChecks.stream()
+ .filter(check -> checkId.equals(check.getCheckId()))
+ .toList();
+ for (CheckConfig check : matching) {
+ if (check.isAliasGenerated() && !sameParameterValues(check.getParameters(), parameters)) {
+ // An intervening edit may have made an initially unchanged alias stale.
+ // Without a preview for these parameters, use the original name rather
+ // than leave an alias describing a different rule.
+ Optional replacement = staleAlias.isPresent() ? aliasName : Optional.empty();
+ check.setAliasName(replacement.orElse(null));
+ check.setAliasGenerated(replacement.isPresent());
+ aliasCleared[0] |= replacement.isEmpty();
}
- checkUpdated = true;
+ check.setParameters(parameters);
}
- checkListAfterUpdate.add(check);
- }
+ return matching.isEmpty() ? null : storedChecks;
+ });
if (!checkUpdated) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
+ return checkOrBenefitNotFound(screenerId, benefitId);
}
- benefit.setChecks(checkListAfterUpdate);
-
- // Save the updated benefit
- screenerRepository.updateCustomBenefit(screenerId, benefit);
-
- return Response.ok(Map.of("aliasCleared", aliasCleared)).build();
+ return Response.ok(Map.of("aliasCleared", aliasCleared[0])).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
@@ -529,48 +505,18 @@ public Response updateCheckAlias(
}
try {
- // Get the benefit
- Optional benefitOpt = screenerRepository.getCustomBenefit(screenerId, benefitId);
- if (benefitOpt.isEmpty()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Benefit not found"))
- .build();
- }
-
- Benefit benefit = benefitOpt.get();
- List checks = benefit.getChecks();
-
- if (checks == null || checks.isEmpty()) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
- }
-
// Find and update the check with the matching checkId
- Boolean checkUpdated = false;
- List checkListAfterUpdate = new ArrayList<>();
- for (CheckConfig check : checks) {
- if (check.getCheckId().equals(checkId)) {
- check.setAliasName(request.aliasName());
- check.setAliasGenerated(
- request.aliasName() != null && Boolean.TRUE.equals(request.aliasGenerated())
- );
- checkUpdated = true;
- }
- checkListAfterUpdate.add(check);
- }
+ boolean checkUpdated = updateMatchingChecks(screenerId, benefitId, checkId, check -> {
+ check.setAliasName(request.aliasName());
+ check.setAliasGenerated(
+ request.aliasName() != null && Boolean.TRUE.equals(request.aliasGenerated())
+ );
+ });
if (!checkUpdated) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity(Map.of("error", "Check not found in benefit"))
- .build();
+ return checkOrBenefitNotFound(screenerId, benefitId);
}
- benefit.setChecks(checkListAfterUpdate);
-
- // Save the updated benefit
- screenerRepository.updateCustomBenefit(screenerId, benefit);
-
return Response.ok().build();
} catch (Exception e) {
Log.error(e);
@@ -580,6 +526,32 @@ public Response updateCheckAlias(
}
}
+ @PATCH
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Path("/screener/{screenerId}/benefit/{benefitId}/check/{checkId}/explanation")
+ public Response updateCheckExplanation(
+ @Context SecurityIdentity identity,
+ @PathParam("screenerId") String screenerId,
+ @PathParam("benefitId") String benefitId,
+ @PathParam("checkId") String checkId,
+ @NotNull @Valid UpdateCheckExplanationRequest request
+ ) {
+ if (!isUserAuthorizedForScreener(AuthUtils.getUserId(identity), screenerId)) {
+ return Response.status(Response.Status.UNAUTHORIZED).build();
+ }
+ try {
+ boolean checkUpdated = updateMatchingChecks(screenerId, benefitId, checkId,
+ check -> check.setExplanation(request.explanation()));
+ if (!checkUpdated) {
+ return checkOrBenefitNotFound(screenerId, benefitId);
+ }
+ return Response.ok().build();
+ } catch (Exception e) {
+ Log.error(e);
+ return Response.serverError().entity(Map.of("error", "Could not update check explanation")).build();
+ }
+ }
+
@POST
@Path("/screener/{screenerId}/benefit/{benefitId}/check/{checkId}/alias/generate")
public Response generateCheckAlias(
@@ -604,7 +576,7 @@ public Response generateCheckAlias(
List checks = benefitOpt.get().getChecks();
Optional checkOpt = (checks == null ? List.of() : checks).stream()
- .filter(check -> check.getCheckId().equals(checkId))
+ .filter(check -> checkId.equals(check.getCheckId()))
.findFirst();
if (checkOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND)
@@ -630,6 +602,28 @@ public Response generateCheckAlias(
// ========== Private Helper Methods ==========
+ // Updates every config with this ID, since configs can share one. False when there are none.
+ private boolean updateMatchingChecks(String screenerId, String benefitId, String checkId,
+ Consumer update) throws Exception {
+ return screenerRepository.updateCustomBenefitChecks(screenerId, benefitId, checks -> {
+ List matching = checks.stream()
+ .filter(check -> checkId.equals(check.getCheckId()))
+ .toList();
+ matching.forEach(update);
+ return matching.isEmpty() ? null : checks;
+ });
+ }
+
+ // updateCustomBenefitChecks reports both as false, and authors see this message.
+ private Response checkOrBenefitNotFound(String screenerId, String benefitId) throws Exception {
+ String error = screenerRepository.getCustomBenefit(screenerId, benefitId).isPresent()
+ ? "Check not found in benefit"
+ : "Benefit not found";
+ return Response.status(Response.Status.NOT_FOUND)
+ .entity(Map.of("error", error))
+ .build();
+ }
+
private static boolean usesEvaluationDateDefault(EligibilityCheck check, ParameterDefinition parameter) {
return check.getEvaluationUrl() != null
&& parameter.getKey().equals("asOfDate")
diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/DecisionResource.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/DecisionResource.java
index 39bfa917..51f8008a 100644
--- a/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/DecisionResource.java
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/DecisionResource.java
@@ -167,6 +167,7 @@ private Map evaluateBenefit(Benefit benefit, Map
Map checkResultMap = new HashMap<>();
checkResultMap.put("name", checkConfig.getCheckName());
checkResultMap.put("aliasName", checkConfig.getAliasName());
+ checkResultMap.put("explanation", checkConfig.getExplanation());
checkResultMap.put("result", evaluationResult);
checkResultMap.put("module", checkConfig.getCheckModule() != null ? checkConfig.getCheckModule() : "");
checkResultMap.put("version", checkConfig.getCheckVersion() != null ? checkConfig.getCheckVersion() : "");
diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/Benefit.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/Benefit.java
index 93a8408b..c3ff1c7d 100644
--- a/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/Benefit.java
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/Benefit.java
@@ -10,6 +10,7 @@ public class Benefit {
private String id;
private String description;
private String name;
+ @Valid
private List checks;
private String ownerId;
@Valid
diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/CheckConfig.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/CheckConfig.java
index 49e198a7..423e0633 100644
--- a/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/CheckConfig.java
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/domain/CheckConfig.java
@@ -2,6 +2,7 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
+import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.Map;
@@ -21,6 +22,9 @@ public class CheckConfig {
private List parameterDefinitions;
// optional alias name for this check instance
private String aliasName;
+ // Plain-language guidance for the person being screened, per configured check.
+ @Size(max = 2000)
+ private String explanation;
// true when aliasName came from alias generation and hasn't been hand-edited,
// so it can be regenerated when parameters change
private boolean aliasGenerated;
@@ -139,6 +143,14 @@ public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
+ public String getExplanation() {
+ return explanation;
+ }
+
+ public void setExplanation(String explanation) {
+ this.explanation = explanation == null || explanation.isBlank() ? null : explanation.trim();
+ }
+
public boolean isAliasGenerated() {
return aliasGenerated;
}
diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/dto/custombenefit/UpdateCheckExplanationRequest.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/dto/custombenefit/UpdateCheckExplanationRequest.java
new file mode 100644
index 00000000..63e585d2
--- /dev/null
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/model/dto/custombenefit/UpdateCheckExplanationRequest.java
@@ -0,0 +1,5 @@
+package org.codeforphilly.bdt.builder.model.dto.custombenefit;
+
+import jakarta.validation.constraints.Size;
+
+public record UpdateCheckExplanationRequest(@Size(max = 2000) String explanation) {}
diff --git a/builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/FirestoreUtils.java b/builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/FirestoreUtils.java
index 99cdda5f..0a6db5d2 100644
--- a/builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/FirestoreUtils.java
+++ b/builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/FirestoreUtils.java
@@ -10,6 +10,7 @@
import java.util.*;
import java.util.concurrent.ExecutionException;
+import java.util.function.UnaryOperator;
public class FirestoreUtils {
@@ -304,6 +305,30 @@ public static void updateDocument(String collectionName, Map dat
}
}
+ /* Reads a document and writes the fields update returns, in one transaction that reruns update
+ if the document changes before commit. Returns false, writing nothing, when the document is
+ missing or update returns null. */
+ public static boolean updateDocumentFields(String collection, String documentId,
+ UnaryOperator
@@ -62,7 +67,11 @@ function BenefitResult({ benefitResult }: { benefitResult: BenefitResult }) {
- {check.aliasName ? titleCase(check.aliasName) : check.name}
+ {checkDisplayName(check)}
+
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
index 866512da..a2f64cb9 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
@@ -211,7 +211,7 @@ export function NextStepsBody({
${unmet.length > 0 &&
html`Requirements not met
-
+
${unmet.map((name) => html`- ${name}
`)}
`}
<${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 6efb80f6..ad3747d1 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts
@@ -1,5 +1,6 @@
import cloneDeep from "lodash/cloneDeep";
import type { Benefit, BenefitResult, NextSteps } from "@/types";
+import { checkDisplayName } from "@/utils/checkDisplayName";
import { normalizeHttpUrl } from "@/utils/httpUrl";
import type { NextStepsField } from "./NextSteps";
@@ -93,7 +94,7 @@ export function benefitNextSteps(
body: null,
unmetRequirements: Object.values(benefit.check_results ?? {})
.filter((check) => check.result === "FALSE")
- .map((check) => check.aliasName?.trim() || check.name)
+ .map((check) => check.explanation?.trim() || checkDisplayName(check))
// 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/nextSteps.css b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/nextSteps.css
index 6e4b6d7d..37e20f69 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/nextSteps.css
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/nextSteps.css
@@ -42,6 +42,9 @@
.bdt-next-steps ol {
list-style: decimal;
}
+.bdt-next-steps-requirements li {
+ white-space: pre-wrap;
+}
.bdt-next-steps-contacts {
display: flex;
flex-wrap: wrap;
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/ConfigureBenefit.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/ConfigureBenefit.tsx
index a3430392..94d2416c 100644
--- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/ConfigureBenefit.tsx
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/ConfigureBenefit.tsx
@@ -120,6 +120,12 @@ const ConfigureBenefit = ({
aliasGenerated,
);
}}
+ updateCheckConfigExplanation={(explanation) =>
+ actions.updateCheckConfigExplanation(
+ checkConfig.checkId,
+ explanation,
+ )
+ }
generateCheckConfigAlias={() =>
actions.generateCheckConfigAlias(
checkConfig.checkId,
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.test.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.test.tsx
new file mode 100644
index 00000000..dd9c5c92
--- /dev/null
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import { render } from "solid-js/web";
+import { afterEach, expect, it, vi } from "vitest";
+import SelectedEligibilityCheck from "./SelectedEligibilityCheck";
+import type { CheckConfig } from "@/types";
+
+let dispose: () => void;
+afterEach(() => {
+ dispose?.();
+ document.body.replaceChildren();
+});
+
+const buttonNamed = (name: string) =>
+ Array.from(document.querySelectorAll("button")).find(
+ (button) => button.textContent === name,
+ )!;
+
+it("returns focus to the edit button when the explanation modal closes", async () => {
+ dispose = render(
+ () => (
+
+ ({ checkName: "Income", checkVersion: "1.0.0" }) as CheckConfig
+ }
+ updateCheckConfigParams={vi.fn()}
+ updateCheckConfigAlias={null}
+ updateCheckConfigExplanation={vi.fn().mockResolvedValue(undefined)}
+ onRemove={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ const edit = buttonNamed("Edit explanation");
+
+ edit.click();
+ buttonNamed("Cancel").click();
+ expect(document.activeElement).toBe(edit);
+
+ edit.click();
+ document.querySelector("form")!.requestSubmit();
+ await vi.waitFor(() => expect(document.querySelector("form")).toBeNull());
+ expect(document.activeElement).toBe(edit);
+});
+
+it.each([
+ ["Age 18-64", "Age 18-64"],
+ ["PrimaryResidence", "Primary Residence"],
+ [undefined, "Income threshold"],
+])("names a check with the alias %s as %s", (aliasName, name) => {
+ dispose = render(
+ () => (
+
+ ({
+ checkName: "income-threshold",
+ checkVersion: "1.0.0",
+ aliasName,
+ }) as CheckConfig
+ }
+ updateCheckConfigParams={vi.fn()}
+ updateCheckConfigAlias={null}
+ onRemove={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ expect(document.querySelector(".text-xl span")?.textContent).toBe(name);
+});
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.tsx
index 3b93a686..ba4cbc5a 100644
--- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.tsx
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.tsx
@@ -1,8 +1,10 @@
import { Accessor, createSignal, For, Show } from "solid-js";
import ConfigureCheckModal from "./modals/ConfigureCheckModal";
+import EditExplanationModal from "./modals/EditExplanationModal";
import EditAliasModal from "./modals/EditAliasModal";
+import { checkDisplayName } from "@/utils/checkDisplayName";
import { titleCase } from "@/utils/title_case";
import type {
@@ -18,6 +20,7 @@ const SelectedEligibilityCheck = ({
updateCheckConfigParams,
updateCheckConfigAlias,
generateCheckConfigAlias,
+ updateCheckConfigExplanation,
}: {
checkConfig: Accessor;
updateCheckConfigParams: (newCheckData: ParameterValues) => void;
@@ -25,6 +28,7 @@ const SelectedEligibilityCheck = ({
updateCheckConfigAlias:
| ((aliasName: string | null, aliasGenerated: boolean) => void)
| null;
+ updateCheckConfigExplanation?: (explanation: string | null) => Promise;
generateCheckConfigAlias?: () => Promise;
onRemove: () => void | null;
}) => {
@@ -32,7 +36,14 @@ const SelectedEligibilityCheck = ({
createSignal(false);
const [editAliasModalOpen, setEditAliasModalOpen] = createSignal(false);
- const displayName = () => checkConfig().aliasName || checkConfig().checkName;
+ const [editExplanationOpen, setEditExplanationOpen] = createSignal(false);
+ let editExplanationButton: HTMLButtonElement | undefined;
+
+ const displayName = () =>
+ checkDisplayName({
+ aliasName: checkConfig().aliasName,
+ name: titleCase(checkConfig().checkName),
+ });
const isBlankParameterValue = (value: unknown) => {
return value === undefined || value === null || value === "";
@@ -74,7 +85,7 @@ const SelectedEligibilityCheck = ({
-
{titleCase(displayName())}
+
{displayName()}
- {checkConfig().checkVersion}
+
+
+
+
+
+ Explanation: {checkConfig().explanation}
+
+
Original: {checkConfig().checkName}
@@ -139,6 +168,18 @@ const SelectedEligibilityCheck = ({
)}
+
+ {(save) => (
+ {
+ setEditExplanationOpen(false);
+ editExplanationButton?.focus();
+ }}
+ />
+ )}
+
{configuringCheckModalOpen() && (
({
fetchScreenerBenefit: vi.fn(),
@@ -16,6 +17,7 @@ vi.mock("@/api/benefit", () => ({
removeCheckFromBenefit: vi.fn(),
updateCheckParameters: vi.fn(),
updateCheckAlias: vi.fn(),
+ updateCheckExplanation: vi.fn(),
generateCheckAlias: vi.fn(),
}));
@@ -26,12 +28,12 @@ describe("benefit next-steps updates", () => {
vi.clearAllMocks();
});
- function setup() {
+ function setup(checks: CheckConfig[] = []) {
const benefit: Benefit = {
id: "benefit-1",
name: "Benefit",
description: "Description",
- checks: [],
+ checks,
};
vi.mocked(fetchScreenerBenefit).mockImplementation(
async (_screenerId, id) => ({ ...benefit, id }),
@@ -131,4 +133,116 @@ describe("benefit next-steps updates", () => {
await saving;
expect(s.resource.benefit().id).toBe("benefit-2");
});
+
+ const checks = [
+ { checkId: "check-1", checkName: "Income" },
+ { checkId: "check-2", checkName: "Age", explanation: "Be at least 65." },
+ ] as CheckConfig[];
+
+ it("shows a saved explanation without reloading or replacing rows", async () => {
+ const s = setup(structuredClone(checks));
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-1"));
+ vi.mocked(updateCheckExplanation).mockResolvedValue(undefined);
+ const row = s.resource.benefit().checks[0];
+ await s.resource.actions.updateCheckConfigExplanation(
+ "check-1",
+ "Income must be low.",
+ );
+ expect(updateCheckExplanation).toHaveBeenCalledWith(
+ "screener-1",
+ "benefit-1",
+ "check-1",
+ "Income must be low.",
+ );
+ expect(s.resource.benefit().checks[0]).toBe(row);
+ expect(row.explanation).toBe("Income must be low.");
+ expect(s.resource.benefit().checks[1].explanation).toBe("Be at least 65.");
+ expect(fetchScreenerBenefit).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps a saved explanation when an older refetch resolves afterwards", async () => {
+ const s = setup(structuredClone(checks));
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-1"));
+ vi.mocked(addCheckToBenefit).mockResolvedValue({ aliasGenerated: true });
+ vi.mocked(updateCheckExplanation).mockResolvedValue(undefined);
+ let finishFetch!: (benefit: Benefit) => void;
+ vi.mocked(fetchScreenerBenefit).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishFetch = resolve;
+ }),
+ );
+ const adding = s.resource.actions.addCheck("check-3", {});
+ await vi.waitFor(() =>
+ expect(fetchScreenerBenefit).toHaveBeenCalledTimes(2),
+ );
+ await s.resource.actions.updateCheckConfigExplanation("check-1", "Saved");
+ finishFetch({
+ ...s.benefit,
+ name: "Refetched",
+ checks: [
+ ...structuredClone(checks),
+ { checkId: "check-3", checkName: "Added" } as CheckConfig,
+ ],
+ });
+ await adding;
+ expect(s.resource.benefit().name).toBe("Refetched");
+ const saved = s.resource.benefit().checks;
+ expect(saved.map((check) => check.explanation)).toEqual([
+ "Saved",
+ "Be at least 65.",
+ undefined,
+ ]);
+ });
+
+ it("keeps rows in place when a refetch returns new objects", async () => {
+ const s = setup(structuredClone(checks));
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-1"));
+ const [first, second] = s.resource.benefit().checks;
+ vi.mocked(addCheckToBenefit).mockResolvedValue({ aliasGenerated: true });
+ vi.mocked(fetchScreenerBenefit).mockResolvedValueOnce({
+ ...s.benefit,
+ checks: [
+ { checkId: "check-3", checkName: "Added" } as CheckConfig,
+ { ...structuredClone(checks[1]), aliasName: "Age" },
+ structuredClone(checks[0]),
+ ],
+ });
+ await s.resource.actions.addCheck("check-3", {});
+ const refreshed = s.resource.benefit().checks;
+ expect(refreshed[1]).toBe(second);
+ expect(refreshed[2]).toBe(first);
+ expect(second.aliasName).toBe("Age");
+ });
+
+ it("keeps the explanation when saving fails and rejects for the modal", async () => {
+ const s = setup(structuredClone(checks));
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-1"));
+ vi.mocked(updateCheckExplanation).mockRejectedValueOnce(
+ new Error("Offline"),
+ );
+ await expect(
+ s.resource.actions.updateCheckConfigExplanation("check-2", null),
+ ).rejects.toThrow("Offline");
+ expect(s.resource.benefit().checks[1].explanation).toBe("Be at least 65.");
+ });
+
+ it("leaves a different benefit alone when an explanation save finishes", async () => {
+ const s = setup(structuredClone(checks));
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-1"));
+ let finish!: () => void;
+ vi.mocked(updateCheckExplanation).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const saving = s.resource.actions.updateCheckConfigExplanation(
+ "check-1",
+ "Stale",
+ );
+ s.switchBenefit("benefit-2");
+ await vi.waitFor(() => expect(s.resource.benefit()?.id).toBe("benefit-2"));
+ finish();
+ await saving;
+ expect(s.resource.benefit().checks[0].explanation).toBeUndefined();
+ });
});
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts
index 65409e9d..4f6b7905 100644
--- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts
@@ -1,5 +1,5 @@
import { createResource, createEffect, Accessor, createSignal } from "solid-js";
-import { createStore } from "solid-js/store";
+import { createStore, reconcile } from "solid-js/store";
import toast from "solid-toast";
import {
@@ -8,6 +8,7 @@ import {
removeCheckFromBenefit,
updateCheckParameters,
updateCheckAlias,
+ updateCheckExplanation,
generateCheckAlias,
updateScreenerBenefit,
} from "@/api/benefit";
@@ -29,6 +30,10 @@ interface ScreenerBenefitsResource {
aliasName: string | null,
aliasGenerated: boolean,
) => void;
+ updateCheckConfigExplanation: (
+ checkId: string,
+ explanation: string | null,
+ ) => Promise;
generateCheckConfigAlias: (checkId: string) => Promise;
updateNextSteps: (nextSteps: NextSteps) => Promise;
};
@@ -46,16 +51,35 @@ const createScreenerBenefits = (
// Local fine-grained store
const [benefit, setBenefit] = createStore(null);
- // A refetch that started before a next-steps save finished returns the old content.
+ // A refetch that started before a save finished returns the old content.
let nextStepsSaves = 0;
+ let explanationSaves = 0;
const [benefitResource, { refetch }] = createResource(
() => [screenerId(), benefitId()],
async ([sId, bId]) => {
- const savesBefore = nextStepsSaves;
+ const nextStepsBefore = nextStepsSaves;
+ const explanationsBefore = explanationSaves;
const fetched = await fetchScreenerBenefit(sId, bId);
- return nextStepsSaves !== savesBefore && benefit?.id === fetched.id
- ? { ...fetched, nextSteps: benefit.nextSteps }
- : fetched;
+ if (benefit?.id !== fetched.id) return fetched;
+ let checks = fetched.checks;
+ if (explanationSaves !== explanationsBefore) {
+ const explanations = new Map(
+ benefit.checks.map((check) => [check.checkId, check.explanation]),
+ );
+ checks = checks.map((check) =>
+ explanations.has(check.checkId)
+ ? { ...check, explanation: explanations.get(check.checkId) }
+ : check,
+ );
+ }
+ return {
+ ...fetched,
+ nextSteps:
+ nextStepsSaves === nextStepsBefore
+ ? fetched.nextSteps
+ : benefit.nextSteps,
+ checks,
+ };
},
);
@@ -65,7 +89,8 @@ const createScreenerBenefits = (
createEffect(() => {
if (benefitResource()) {
console.log("Benefit resource loaded:", benefitResource());
- setBenefit(benefitResource()!);
+ // Reconciled so rows keep their identity, and any open modal its draft.
+ setBenefit(reconcile(benefitResource()!, { key: "checkId" }));
}
});
@@ -154,6 +179,33 @@ const createScreenerBenefits = (
setActionInProgress(false);
};
+ const updateCheckConfigExplanation = async (
+ checkId: string,
+ explanation: string | null,
+ ) => {
+ const targetScreenerId = screenerId();
+ const targetBenefitId = benefitId();
+ await updateCheckExplanation(
+ targetScreenerId,
+ targetBenefitId,
+ checkId,
+ explanation,
+ );
+ // A reload could report a failed read as a failed save, and would re-render every row.
+ if (
+ screenerId() === targetScreenerId &&
+ benefitId() === targetBenefitId
+ ) {
+ explanationSaves++;
+ setBenefit(
+ "checks",
+ (check) => check.checkId === checkId,
+ "explanation",
+ explanation,
+ );
+ }
+ };
+
const generateCheckConfigAlias = (checkId: string) =>
generateCheckAlias(screenerId(), benefitId(), checkId);
@@ -188,6 +240,7 @@ const createScreenerBenefits = (
updateCheckConfigParams,
updateCheckConfigAlias,
generateCheckConfigAlias,
+ updateCheckConfigExplanation,
updateNextSteps,
},
actionInProgress,
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx
new file mode 100644
index 00000000..4d1581a6
--- /dev/null
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx
@@ -0,0 +1,178 @@
+// @vitest-environment jsdom
+import { render } from "solid-js/web";
+import { afterEach, expect, it, vi } from "vitest";
+import EditExplanationModal from "./EditExplanationModal";
+import { ApiError } from "@/api/check";
+import type { CheckConfig } from "@/types";
+
+let dispose: () => void;
+afterEach(() => {
+ dispose?.();
+ document.body.replaceChildren();
+});
+
+it("keeps a failed save editable, retries, and supports clearing the explanation", async () => {
+ const save = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValue(undefined);
+ const close = vi.fn();
+ dispose = render(
+ () => (
+
+ ({ checkName: "Income", explanation: "Saved text" }) as CheckConfig
+ }
+ save={save}
+ closeModal={close}
+ />
+ ),
+ document.body,
+ );
+ const textarea = document.querySelector("textarea")!;
+ expect(textarea.value).toBe("Saved text");
+ textarea.value = " Your income must be below the limit. ";
+ textarea.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ const submit = () =>
+ document
+ .querySelector("form")!
+ .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ submit();
+ await vi.waitFor(() =>
+ expect(document.querySelector('[role="alert"]')).not.toBeNull(),
+ );
+ expect(close).not.toHaveBeenCalled();
+ expect(textarea.value).toBe(" Your income must be below the limit. ");
+ expect(save).toHaveBeenLastCalledWith("Your income must be below the limit.");
+ textarea.value = " ";
+ textarea.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ submit();
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
+ expect(save).toHaveBeenLastCalledWith(null);
+});
+
+it("moves focus into the explanation when it opens", async () => {
+ dispose = render(
+ () => (
+ ({ checkName: "Income" }) as CheckConfig}
+ save={vi.fn()}
+ closeModal={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ await vi.waitFor(() =>
+ expect(document.activeElement).toBe(document.querySelector("textarea")),
+ );
+});
+
+it("keeps unsaved edits from a backdrop click, but Cancel still discards them", () => {
+ const close = vi.fn();
+ dispose = render(
+ () => (
+
+ ({ checkName: "Income", explanation: "Saved text" }) as CheckConfig
+ }
+ save={vi.fn()}
+ closeModal={close}
+ />
+ ),
+ document.body,
+ );
+ const textarea = document.querySelector("textarea")!;
+ const backdrop = document.querySelector("[data-modal-root]")!;
+ const edit = (value: string) => {
+ textarea.value = value;
+ textarea.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ };
+ edit("Edited text");
+ backdrop.click();
+ expect(close).not.toHaveBeenCalled();
+ [...document.querySelectorAll("button")]
+ .find((button) => button.textContent === "Cancel")!
+ .click();
+ expect(close).toHaveBeenCalledOnce();
+ edit("Saved text");
+ backdrop.click();
+ expect(close).toHaveBeenCalledTimes(2);
+});
+
+it.each([
+ [new ApiError("Check not found in benefit", 404), "Check not found in benefit"],
+ [new ApiError("Could not update check explanation", 500), "Please try again."],
+ [new TypeError("Failed to fetch"), "Please try again."],
+])("explains a failed save: %s", async (failure, message) => {
+ dispose = render(
+ () => (
+ ({ checkName: "Income" }) as CheckConfig}
+ save={vi.fn().mockRejectedValue(failure)}
+ closeModal={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ document
+ .querySelector("form")!
+ .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ await vi.waitFor(() =>
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain(
+ message,
+ ),
+ );
+});
+
+it("locks the draft during a save and refocuses it after a failure", async () => {
+ let failSave!: (reason: Error) => void;
+ dispose = render(
+ () => (
+ ({ checkName: "Income" }) as CheckConfig}
+ save={() =>
+ new Promise((_, reject) => {
+ failSave = reject;
+ })
+ }
+ closeModal={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ const textarea = document.querySelector("textarea")!;
+ const saveButton = document.querySelector(
+ 'button[type="submit"]',
+ )!;
+ saveButton.focus();
+ document
+ .querySelector("form")!
+ .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ expect(textarea.readOnly).toBe(true);
+ saveButton.blur();
+
+ failSave(new Error("offline"));
+ await vi.waitFor(() =>
+ expect(document.querySelector('[role="alert"]')).not.toBeNull(),
+ );
+ expect(document.activeElement).toBe(textarea);
+ expect(textarea.readOnly).toBe(false);
+});
+
+it("names the check the way results do", () => {
+ dispose = render(
+ () => (
+
+ ({ checkName: "Income", aliasName: "IncomeLimit" }) as CheckConfig
+ }
+ save={vi.fn()}
+ closeModal={vi.fn()}
+ />
+ ),
+ document.body,
+ );
+ expect(document.querySelector("label")?.textContent).toBe(
+ "Explanation for Income Limit",
+ );
+});
diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.tsx
new file mode 100644
index 00000000..efffa204
--- /dev/null
+++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.tsx
@@ -0,0 +1,102 @@
+import { Accessor, createSignal, createUniqueId, Show } from "solid-js";
+import { ApiError } from "@/api/check";
+import { Modal } from "@/components/shared/Modal";
+import type { CheckConfig } from "@/types";
+import { checkDisplayName } from "@/utils/checkDisplayName";
+
+export default function EditExplanationModal(props: {
+ checkConfig: Accessor;
+ save: (explanation: string | null) => Promise;
+ closeModal: () => void;
+}) {
+ const id = createUniqueId();
+ const savedExplanation = () => props.checkConfig().explanation ?? "";
+ const [draft, setDraft] = createSignal(savedExplanation());
+ const [saving, setSaving] = createSignal(false);
+ const [error, setError] = createSignal("");
+ let textarea: HTMLTextAreaElement | undefined;
+ const save = async (event: SubmitEvent) => {
+ event.preventDefault();
+ if (saving()) return;
+ setSaving(true);
+ setError("");
+ try {
+ await props.save(draft().trim() || null);
+ props.closeModal();
+ } catch (error) {
+ console.error("Failed to save check explanation", error);
+ // A rejected request fails the same way on a retry, and its message says why.
+ setError(
+ error instanceof ApiError && error.status < 500
+ ? `Could not save the explanation. ${error.message}`
+ : "Could not save the explanation. Your edits are still here. Please try again.",
+ );
+ // The Save button is disabled at this point, which dropped focus to the body.
+ textarea?.focus();
+ } finally {
+ setSaving(false);
+ }
+ };
+ return (
+
+
+
+ );
+}
diff --git a/builder-frontend/src/components/screenerEditor/preview/Results.tsx b/builder-frontend/src/components/screenerEditor/preview/Results.tsx
index 2b115bc6..281659b5 100644
--- a/builder-frontend/src/components/screenerEditor/preview/Results.tsx
+++ b/builder-frontend/src/components/screenerEditor/preview/Results.tsx
@@ -2,7 +2,10 @@ import { Accessor, For, Match, Show, Switch } from "solid-js";
import { PreviewFormData, ScreenerResult } from "./types";
import type { ParameterValues } from "@/types";
-import { titleCase } from "@/utils/title_case";
+import { checkDisplayName } from "@/utils/checkDisplayName";
+import { createReconciledResults } from "@/utils/reconciledResults";
+
+import CheckExplanation from "@/components/shared/CheckExplanation";
import checkIcon from "../../../assets/images/checkIcon.svg";
import questionIcon from "../../../assets/images/questionIcon.svg";
@@ -31,6 +34,8 @@ export default function Results({
results: Accessor;
resultsLoading: Accessor;
}) {
+ const reconciled = createReconciledResults(results);
+ const hasResults = () => Object.keys(reconciled).length > 0;
return (