Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package org.acme.constants;

import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;

public enum CheckStatus {
WORKING('W'),
PUBLISHED('P');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.acme.persistence.ScreenerRepository;
import org.acme.persistence.StorageService;
import org.acme.service.DmnService;
import org.acme.service.FormDataTransformer;
import org.acme.service.LibraryApiService;

import java.util.*;
Expand Down Expand Up @@ -66,11 +67,14 @@ public Response evaluatePublishedScreener(
return Response.status(Response.Status.NOT_FOUND).build();
}

// Transform form data: convert people object to people array
Map<String, Object> transformedData = FormDataTransformer.transformFormData(inputData);

try {
Map<String, Object> screenerResults = new HashMap<String, Object>();
for (Benefit benefit : benefits) {
// Evaluate benefit
Map<String, Object> benefitResults = evaluateBenefit(benefit, inputData);
Map<String, Object> benefitResults = evaluateBenefit(benefit, transformedData);
screenerResults.put(benefit.getId(), benefitResults);
}
return Response.ok().entity(screenerResults).build();
Expand Down Expand Up @@ -106,12 +110,15 @@ public Response evaluateScreener(
return Response.status(Response.Status.NOT_FOUND).build();
}

// Transform form data: convert people object to people array
Map<String, Object> transformedData = FormDataTransformer.transformFormData(formData);

try {
Map<String, Object> screenerResults = new HashMap<String, Object>();
//TODO: consider ways of processing benefits in parallel
for (Benefit benefit : benefits) {
// Evaluate benefit
Map<String, Object> benefitResults = evaluateBenefit(benefit, formData);
Map<String, Object> benefitResults = evaluateBenefit(benefit, transformedData);
screenerResults.put(benefit.getId(), benefitResults);
}
return Response.ok().entity(screenerResults).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
import jakarta.ws.rs.core.Response;
import org.acme.auth.AuthUtils;
import org.acme.model.domain.*;
import org.acme.model.dto.FormPathsResponse;
import org.acme.model.dto.PublishScreenerRequest;
import org.acme.model.dto.SaveSchemaRequest;
import org.acme.persistence.EligibilityCheckRepository;
import org.acme.persistence.ScreenerRepository;
import org.acme.persistence.PublishedScreenerRepository;
import org.acme.persistence.StorageService;
import org.acme.service.DmnService;
import org.acme.service.InputSchemaService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
Expand All @@ -42,6 +45,9 @@ public class ScreenerResource {
@Inject
DmnService dmnService;

@Inject
InputSchemaService inputSchemaService;

@GET
@Path("/screeners")
public Response getScreeners(@Context SecurityIdentity identity) {
Expand Down Expand Up @@ -252,6 +258,40 @@ public Response getScreenerBenefits(@Context SecurityIdentity identity,
}
}

/**
* Returns the list of unique input paths required by all checks in a screener.
* This endpoint transforms inputDefinition schemas and extracts paths,
* replacing the frontend's transformInputDefinitionSchema and extractJsonSchemaPaths logic.
*/
@GET
@Path("/screener/{screenerId}/form-paths")
public Response getScreenerFormPaths(@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId) {
String userId = AuthUtils.getUserId(identity);

Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
throw new NotFoundException();
}
Screener screener = screenerOpt.get();

if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}

try {
List<Benefit> benefits = screenerRepository.getBenefitsInScreener(screener);
List<String> paths = new ArrayList<>(inputSchemaService.extractAllInputPaths(benefits));
Collections.sort(paths);
return Response.ok().entity(new FormPathsResponse(paths)).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not extract form paths"))
.build();
}
}

@GET
@Path("/screener/{screenerId}/benefit/{benefitId}")
public Response getScreenerBenefit(@Context SecurityIdentity identity,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package org.acme.enums;

import java.util.Optional;

public enum EvaluationResult {
TRUE("TRUE"),
FALSE("FALSE"),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.acme.model.dto;

import java.util.List;

/**
* Response DTO for the form paths endpoint.
* Contains the list of unique input paths required by all checks in a screener.
*/
public class FormPathsResponse {
private List<String> paths;

public FormPathsResponse() {
}

public FormPathsResponse(List<String> paths) {
this.paths = paths;
}

public List<String> getPaths() {
return paths;
}

public void setPaths(List<String> paths) {
this.paths = paths;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.quarkus.logging.Log;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package org.acme.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Utility class for transforming form data between different formats.
*
* The Form-JS editor uses a "people" object with personId keys (e.g., {applicant: {...}, spouse: {...}}),
* while DMN models expect a "people" array with id fields (e.g., [{id: "applicant", ...}, {id: "spouse", ...}]).
*/
public class FormDataTransformer {

/**
* Transforms form data by converting a "people" object (with personId keys) into a "people" array
* (with id fields). This is the reverse of the frontend's transformInputDefinitionSchema function.
*
* @param formData The form data from the user, potentially containing a "people" object
* @return A new Map with the "people" object converted to an array, or the original data if no transformation needed
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> transformFormData(Map<String, Object> formData) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it might be over-engineering to do this now. But if we add additional transformations, I think it would be great if this function iterated through a list of transformations. Or somehow setup up so that we could easily add new transformations while changing as little code as possible.

if (formData == null) {
return new HashMap<>();
}

Object peopleValue = formData.get("people");

// If no people key, or it's already a List (array), return a copy of the original
if (peopleValue == null || peopleValue instanceof List) {
return new HashMap<>(formData);
}

// If people is not a Map (object), return a copy of the original
if (!(peopleValue instanceof Map)) {
return new HashMap<>(formData);
}

Map<String, Object> peopleObject = (Map<String, Object>) peopleValue;
List<Map<String, Object>> peopleArray = new ArrayList<>();

// Convert each entry in the people object to an array element with an "id" field
for (Map.Entry<String, Object> entry : peopleObject.entrySet()) {
String personId = entry.getKey();
Object personValue = entry.getValue();

if (personValue instanceof Map) {
Map<String, Object> personData = new HashMap<>((Map<String, Object>) personValue);
personData.put("id", personId);
peopleArray.add(personData);
} else {
// If the value is not a Map, create a simple object with just the id
Map<String, Object> personData = new HashMap<>();
personData.put("id", personId);
peopleArray.add(personData);
}
}

// Create the result with the transformed people array
Map<String, Object> result = new HashMap<>(formData);
result.put("people", peopleArray);

return result;
}
}
170 changes: 170 additions & 0 deletions builder-api/src/main/java/org/acme/service/InputSchemaService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package org.acme.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;

import org.acme.model.domain.Benefit;
import org.acme.model.domain.CheckConfig;

import java.util.*;

/**
* Service for transforming and extracting paths from JSON Schema input definitions.
*/
@ApplicationScoped
public class InputSchemaService {

private final ObjectMapper objectMapper = new ObjectMapper();

/**
* Extracts all unique input paths from all benefits in a screener.
*
* @param benefits List of benefits containing checks with inputDefinitions
* @return Set of unique dot-separated paths (e.g., "people.applicant.dateOfBirth")
*/
public Set<String> extractAllInputPaths(List<Benefit> benefits) {
Set<String> pathSet = new HashSet<>();

for (Benefit benefit : benefits) {
List<CheckConfig> checks = benefit.getChecks();
if (checks == null) continue;

for (CheckConfig check : checks) {
JsonNode transformedSchema = transformInputDefinitionSchema(check);
List<String> paths = extractJsonSchemaPaths(transformedSchema);
pathSet.addAll(paths);
}
}

return pathSet;
}

/**
* Transforms a CheckConfig's inputDefinition JSON Schema by converting the `people`
* array property into an object with personId-keyed properties nested under it.
*
* Example:
* Input: { people: { type: "array", items: { properties: { dateOfBirth: ... } } } }
* Output: { people: { type: "object", properties: { [personId]: { properties: { dateOfBirth: ... } } } } }
*
* @param checkConfig The CheckConfig containing inputDefinition and parameters
* @return A new JsonNode with `people` transformed to an object with personId-keyed properties
*/
public JsonNode transformInputDefinitionSchema(CheckConfig checkConfig) {
JsonNode inputDefinition = checkConfig.getInputDefinition();

if (inputDefinition == null || !inputDefinition.has("properties")) {
return inputDefinition != null ? inputDefinition.deepCopy() : objectMapper.createObjectNode();
}

JsonNode properties = inputDefinition.get("properties");
JsonNode peopleProperty = properties.get("people");
boolean hasPeopleProperty = peopleProperty != null;

// Extract personId from parameters
Map<String, Object> parameters = checkConfig.getParameters();
String personId = parameters != null ? (String) parameters.get("personId") : null;

// If people property exists but no personId, return original (can't transform)
if (hasPeopleProperty && (personId == null || personId.isEmpty())) {
return inputDefinition.deepCopy();
}

// If no people property, return a copy of the original schema
if (!hasPeopleProperty) {
return inputDefinition.deepCopy();
}

// Deep clone the schema to avoid mutations
ObjectNode transformedSchema = inputDefinition.deepCopy();
ObjectNode transformedProperties = (ObjectNode) transformedSchema.get("properties");

// Get the items schema from the people array
JsonNode itemsSchema = peopleProperty.get("items");

// Transform people from array to object with personId as a nested property
ObjectNode newPeopleSchema = objectMapper.createObjectNode();
newPeopleSchema.put("type", "object");
ObjectNode newPeopleProperties = objectMapper.createObjectNode();
if (itemsSchema != null) {
newPeopleProperties.set(personId, itemsSchema.deepCopy());
}

newPeopleSchema.set("properties", newPeopleProperties);
transformedProperties.set("people", newPeopleSchema);
return transformedSchema;
}

/**
* Extracts all property paths from a JSON Schema inputDefinition.
* Recursively traverses nested objects to build dot-separated paths.
* Excludes the top-level "parameters" property and "id" properties.
*
* @param jsonSchema The JSON Schema to parse
* @return List of dot-separated paths (e.g., ["people.applicant.dateOfBirth", "income"])
*/
public List<String> extractJsonSchemaPaths(JsonNode jsonSchema) {
if (jsonSchema == null || !jsonSchema.has("properties")) {
return new ArrayList<>();
}

return traverseSchema(jsonSchema, "");
}

private List<String> traverseSchema(JsonNode schema, String parentPath) {
List<String> paths = new ArrayList<>();

if (schema == null || !schema.has("properties")) {
return paths;
}

JsonNode propertiesJsonNode = schema.get("properties");
Iterator<Map.Entry<String, JsonNode>> nestedProperties = propertiesJsonNode.properties().iterator();

while (nestedProperties.hasNext()) {
Map.Entry<String, JsonNode> currentProperty = nestedProperties.next();
String propKey = currentProperty.getKey();
JsonNode propValue = currentProperty.getValue();

// Skip top-level "parameters" property
if (parentPath.isEmpty() && "parameters".equals(propKey)) {
continue;
}

// Skip "id" properties
if ("id".equals(propKey)) {
continue;
}

String currentPath = parentPath.isEmpty() ? propKey : parentPath + "." + propKey;

// If this property has nested properties, recurse into it
if (propValue.has("properties")) {
paths.addAll(traverseSchema(propValue, currentPath));
} else if ("array".equals(getType(propValue)) && propValue.has("items")) {
// Handle arrays - recurse into items schema with the current path
JsonNode itemsSchema = propValue.get("items");
if (itemsSchema.has("properties")) {
paths.addAll(traverseSchema(itemsSchema, currentPath));
} else {
// Array of primitives - add the path
paths.add(currentPath);
}
} else {
// Leaf property - add the path
paths.add(currentPath);
}
}

return paths;
}

private String getType(JsonNode schema) {
if (schema == null || !schema.has("type")) {
return null;
}
return schema.get("type").asText();
}
}
Loading
Loading