diff --git a/bin/library/load-library-metadata.py b/bin/library/load-library-metadata.py index ee12d564..cef6cbba 100644 --- a/bin/library/load-library-metadata.py +++ b/bin/library/load-library-metadata.py @@ -172,6 +172,23 @@ def extract_top_level_inputs( return inputs +def extract_top_level_inputs_from_template( + template_schema: JsonSchema, +) -> dict[str, JsonSchema]: + """ + Extract top-level properties from an x-template-schema. + + The x-template-schema is a self-contained JSON Schema that doesn't + use $ref - all types are already inlined. It also contains richer + metadata like descriptions and template placeholders (e.g., {personId}). + """ + inputs: dict[str, JsonSchema] = {} + if template_schema.get("type") == "object": + for prop_name, prop_schema in template_schema.get("properties", {}).items(): + inputs[prop_name] = prop_schema + return inputs + + # -------------------------------------------- # Convert schema to simple {field: type} # -------------------------------------------- @@ -288,26 +305,46 @@ def extract_check_records(openapi: OpenAPIDocument, version: str) -> list[CheckR entry["inputs"][param_name] = dtype # ---------------------------------------- - # 2. Request body parameters + # 2. Request body - prefer x-template-schema if available # ---------------------------------------- if "requestBody" in details: content: dict[str, Any] = details["requestBody"]["content"] if "application/json" in content: - - schema: JsonSchema = content["application/json"].get("schema", {}) - # Only expand top-level 'parameters' and 'situation' - entry["inputs"].update( - extract_top_level_inputs(schema, components)) + json_content = content["application/json"] + + # Prefer x-template-schema as the source of truth + if "x-template-schema" in json_content: + template_schema: JsonSchema = json_content["x-template-schema"] + entry["inputs"] = extract_top_level_inputs_from_template(template_schema) + else: + # Fall back to regular schema with $ref resolution + schema: JsonSchema = json_content.get("schema", {}) + entry["inputs"].update( + extract_top_level_inputs(schema, components)) output.append(entry) return output -def transform_parameters(properties_obj: dict[str, JsonSchema]) -> list[ParameterDefinition]: - """Convert properties dict to a list of {key, name, type} objects.""" +def transform_parameters( + properties_obj: dict[str, JsonSchema], + required_list: list[str] | None = None +) -> list[ParameterDefinition]: + """ + Convert properties dict to a list of ParameterDefinition objects. + + When using x-template-schema, we have access to richer metadata: + - description: Human-readable description of the parameter + - required: List of required field names from parent schema + + Args: + properties_obj: The properties dict from the schema + required_list: Optional list of required field names + """ transformed: list[ParameterDefinition] = [] + required_set: set[str] = set(required_list) if required_list else set() for key, val in properties_obj.items(): # Determine the property's type @@ -318,10 +355,13 @@ def transform_parameters(properties_obj: dict[str, JsonSchema]) -> list[Paramete if prop_type == "string" and prop_format == "date": prop_type = "date" + # Use description from schema if available, otherwise fall back to key + label: str = val.get("description", key) + transformed.append({ "key": key, - "label": key, - "required": False, + "label": label, + "required": key in required_set, "type": prop_type }) @@ -329,15 +369,16 @@ def transform_parameters(properties_obj: dict[str, JsonSchema]) -> list[Paramete def transform_parameters_format(data: list[CheckRecord]) -> list[CheckRecord]: - """Transform all `inputs.parameters.properties` in the provided list.""" + """Transform all `inputs.parameters` in the provided list to parameterDefinitions.""" for check in data: inputs: dict[str, Any] = check.get("inputs", {}) parameters: dict[str, Any] | None = inputs.get("parameters") - # Only transform objects that follow the original structure + # Only transform objects that follow the expected structure if isinstance(parameters, dict) and "properties" in parameters: properties_obj: dict[str, JsonSchema] = parameters["properties"] - new_parameters = transform_parameters(properties_obj) + required_list: list[str] | None = parameters.get("required") + new_parameters = transform_parameters(properties_obj, required_list) # Replace object with the transformed list check["parameterDefinitions"] = new_parameters @@ -345,9 +386,20 @@ def transform_parameters_format(data: list[CheckRecord]) -> list[CheckRecord]: def transform_situation_format(data: list[CheckRecord]) -> list[CheckRecord]: - """Transform all `inputs.situation` in the provided list.""" + """ + Transform all `inputs.situation` in the provided list to inputDefinition. + + When using x-template-schema as the source, the situation schema contains: + - Rich property descriptions + - Template placeholders like {personId} for dynamic keys + - Proper required field arrays + - Nested type definitions + """ for check in data: - check["inputDefinition"] = check["inputs"]["situation"] + inputs: dict[str, Any] = check.get("inputs", {}) + situation = inputs.get("situation") + if situation is not None: + check["inputDefinition"] = situation return data diff --git a/builder-api/src/main/java/org/acme/controller/DecisionResource.java b/builder-api/src/main/java/org/acme/controller/DecisionResource.java index c50edb56..f175de43 100644 --- a/builder-api/src/main/java/org/acme/controller/DecisionResource.java +++ b/builder-api/src/main/java/org/acme/controller/DecisionResource.java @@ -111,14 +111,14 @@ public Response evaluateScreener( } // Transform form data: convert people object to people array - Map transformedData = FormDataTransformer.transformFormData(formData); + // Map transformedData = FormDataTransformer.transformFormData(formData); try { Map screenerResults = new HashMap(); //TODO: consider ways of processing benefits in parallel for (Benefit benefit : benefits) { // Evaluate benefit - Map benefitResults = evaluateBenefit(benefit, transformedData); + Map benefitResults = evaluateBenefit(benefit, formData); screenerResults.put(benefit.getId(), benefitResults); } return Response.ok().entity(screenerResults).build(); @@ -139,14 +139,14 @@ private Map evaluateBenefit(Benefit benefit, Map if (isLibraryCheck(checkConfig)){ evaluationResult = libraryApi.evaluateCheck(checkConfig, formData); } else { - Map customFormValues = (Map) formData.get("custom"); - if (customFormValues == null) { - customFormValues = new HashMap(); - } + Map data = new HashMap<>(); + data.put("parameters", checkConfig.getParameters()); + data.put("situation", formData); + String sourceCheckId = checkConfig.getSourceCheckId() != null ? checkConfig.getSourceCheckId() : checkConfig.getCheckId(); String dmnFilepath = storageService.getCheckDmnModelPath(sourceCheckId); evaluationResult = dmnService.evaluateDmn( - dmnFilepath, checkConfig.getCheckName(), customFormValues, checkConfig.getParameters() + dmnFilepath, checkConfig.getCheckName(), data, checkConfig.getParameters() ); } resultsList.add(evaluationResult); @@ -210,6 +210,18 @@ public Response evaluateCustomCheck( } EligibilityCheck check = checkOpt.get(); + /* +{ + "situation": { + "people": { + "client": { + "dateOfBirth": "2026-01-01" + } + } + } +} +*/ + try { String dmnFilepath = storageService.getCheckDmnModelPath(check.getId()); diff --git a/builder-api/src/main/java/org/acme/controller/EligibilityCheckResource.java b/builder-api/src/main/java/org/acme/controller/EligibilityCheckResource.java index 5c81f513..9c0012bb 100644 --- a/builder-api/src/main/java/org/acme/controller/EligibilityCheckResource.java +++ b/builder-api/src/main/java/org/acme/controller/EligibilityCheckResource.java @@ -152,6 +152,9 @@ public Response updateCustomCheck(@Context SecurityIdentity identity, if (request.parameterDefinitions() != null) { existingCheck.setParameterDefinitions(request.parameterDefinitions()); } + if (request.inputDefinition() != null) { + existingCheck.setInputDefinition(request.inputDefinition()); + } try { eligibilityCheckRepository.updateWorkingCustomCheck(existingCheck); @@ -267,18 +270,6 @@ public Response publishCustomCheck(@Context SecurityIdentity identity, @PathPara .build(); } - // Extract input schema from DMN - try { - String workingDmn = workingDmnOpt.get(); - HashMap dmnDependenciesMap = new HashMap(); - JsonNode inputSchema = dmnService.extractInputSchema(workingDmn, dmnDependenciesMap, check.getName()); - check.setInputDefinition(inputSchema); - } catch (Exception e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(Map.of("error", "Failed to extract input schema for check " + check.getId())) - .build(); - } - // Update workingCheck so that the incremented version number is saved check.setVersion(incrementMajorVersion(check.getVersion())); try { diff --git a/builder-api/src/main/java/org/acme/model/dto/EligibilityCheck/EditCheckRequest.java b/builder-api/src/main/java/org/acme/model/dto/EligibilityCheck/EditCheckRequest.java index a47303a5..6ae656e1 100644 --- a/builder-api/src/main/java/org/acme/model/dto/EligibilityCheck/EditCheckRequest.java +++ b/builder-api/src/main/java/org/acme/model/dto/EligibilityCheck/EditCheckRequest.java @@ -1,11 +1,14 @@ package org.acme.model.dto.EligibilityCheck; +import com.fasterxml.jackson.databind.JsonNode; import org.acme.api.validation.AtLeastOneProvided; import org.acme.model.domain.ParameterDefinition; import java.util.List; -@AtLeastOneProvided(fields = {"description", "parameterDefinitions"}) +@AtLeastOneProvided(fields = {"description", "parameterDefinitions", "inputDefinition"}) public record EditCheckRequest( - String description, List parameterDefinitions + String description, + List parameterDefinitions, + JsonNode inputDefinition ) {} diff --git a/builder-api/src/main/java/org/acme/persistence/FirestoreUtils.java b/builder-api/src/main/java/org/acme/persistence/FirestoreUtils.java index 4c942c04..f55ee15d 100644 --- a/builder-api/src/main/java/org/acme/persistence/FirestoreUtils.java +++ b/builder-api/src/main/java/org/acme/persistence/FirestoreUtils.java @@ -201,7 +201,7 @@ public static void updateDocument(String collectionName, Map dat try { WriteResult result = db.collection(collectionName) .document(docId) - .set(data, SetOptions.merge()) + .set(data) .get(); Log.info("Document " + docId + " updated at " + result.getUpdateTime()); diff --git a/builder-api/src/main/java/org/acme/service/InputSchemaService.java b/builder-api/src/main/java/org/acme/service/InputSchemaService.java index ad091387..a94f6d8a 100644 --- a/builder-api/src/main/java/org/acme/service/InputSchemaService.java +++ b/builder-api/src/main/java/org/acme/service/InputSchemaService.java @@ -1,8 +1,8 @@ package org.acme.service; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; + +import io.quarkus.logging.Log; import jakarta.enterprise.context.ApplicationScoped; import org.acme.model.domain.Benefit; @@ -12,16 +12,25 @@ import java.util.*; /** - * Service for transforming and extracting paths from JSON Schema input definitions. + * Service for extracting paths from JSON Schema input definitions. + * + *

Uses the x-template-schema from library-api as the source of truth for inputDefinition. + * The inputDefinition contains template placeholders (e.g., {personId}) that are filled + * using the check's configured parameters via SchemaTemplateTransformer.fillTemplate(). */ @ApplicationScoped public class InputSchemaService { - private final ObjectMapper objectMapper = new ObjectMapper(); - /** * Extracts all unique input paths from all benefits in a screener. * + *

For each check in each benefit: + *

    + *
  1. Takes the inputDefinition (x-template-schema from library-api)
  2. + *
  3. Fills template placeholders using the check's parameters
  4. + *
  5. Extracts JSON Schema paths from the filled schema
  6. + *
+ * * @param benefits List of benefits containing checks with inputDefinitions * @return List of unique FormPath objects */ @@ -33,8 +42,18 @@ public List extractUniqueInputPaths(List benefits) { if (checks == null) continue; for (CheckConfig check : checks) { - JsonNode transformedSchema = transformInputDefinitionSchema(check); - List checkFormPaths = extractJsonSchemaPaths(transformedSchema); + JsonNode inputDefinition = check.getInputDefinition(); + if (inputDefinition == null) continue; + + // Fill template placeholders with the check's parameters + Map parameters = check.getParameters(); + JsonNode filledSchema = SchemaTemplateTransformer.fillTemplate( + inputDefinition, + parameters != null ? parameters : Collections.emptyMap() + ); + + // Extract paths from the filled schema + List checkFormPaths = extractJsonSchemaPaths(filledSchema); for (FormPath checkFormPath : checkFormPaths) { // If the same path exists with different types, keep the first one found pathTypeMap.putIfAbsent(checkFormPath.getPath(), checkFormPath.getType()); @@ -48,218 +67,6 @@ public List extractUniqueInputPaths(List benefits) { .toList(); } - /** - * Transforms a CheckConfig's inputDefinition JSON Schema by applying all schema transformations. - * Currently applies: - * 1. People transformation: converts people array to object keyed by personId(s) - * 2. Enrollments transformation: moves enrollments under people.{personId}.enrollments - * - * Supports both single personId (String) and multiple peopleIds (List) parameters. - * - * @param checkConfig The CheckConfig containing inputDefinition and parameters - * @return A new JsonNode with all transformations applied - */ - public JsonNode transformInputDefinitionSchema(CheckConfig checkConfig) { - JsonNode inputDefinition = checkConfig.getInputDefinition(); - - if (inputDefinition == null || !inputDefinition.has("properties")) { - return inputDefinition != null ? inputDefinition.deepCopy() : objectMapper.createObjectNode(); - } - - // Extract personId(s) from parameters - supports both single personId and multiple peopleIds - Map parameters = checkConfig.getParameters(); - List personIds = extractPersonIds(parameters); - - // Apply each transformation in sequence - JsonNode schema = inputDefinition.deepCopy(); - schema = transformPeopleSchema(schema, personIds); - schema = transformEnrollmentsSchema(schema, personIds); - - return schema; - } - - /** - * Extracts person IDs from parameters, supporting both: - * - personId: a single String ID - * - peopleIds: a List of String IDs - * - * @param parameters The parameters map from CheckConfig - * @return List of person IDs (may be empty if neither parameter is set) - */ - private List extractPersonIds(Map parameters) { - if (parameters == null) { - return Collections.emptyList(); - } - - List personIds = new ArrayList<>(); - - // Check for single personId - Object personId = parameters.get("personId"); - if (personId instanceof String && !((String) personId).isEmpty()) { - personIds.add((String) personId); - } - - // Check for multiple peopleIds - Object peopleIds = parameters.get("peopleIds"); - if (peopleIds instanceof List) { - for (Object id : (List) peopleIds) { - if (id instanceof String && !((String) id).isEmpty()) { - personIds.add((String) id); - } - } - } - - return personIds; - } - - /** - * Transforms the `people` array property into an object with personId-keyed properties. - * - * Example (single ID): - * Input: { people: { type: "array", items: { properties: { dateOfBirth: ... } } } } - * Output: { people: { type: "object", properties: { [personId]: { properties: { dateOfBirth: ... } } } } } - * - * Example (multiple IDs): - * Input: { people: { type: "array", items: { properties: { dateOfBirth: ... } } } } - * Output: { people: { type: "object", properties: { [id1]: {...}, [id2]: {...} } } } - * - * @param schema The JSON Schema to transform - * @param personIds List of personIds to use as keys under people - * @return A new JsonNode with `people` transformed, or the original if no transformation needed - */ - public JsonNode transformPeopleSchema(JsonNode schema, List personIds) { - if (schema == null || !schema.has("properties")) { - return schema != null ? schema.deepCopy() : objectMapper.createObjectNode(); - } - - JsonNode properties = schema.get("properties"); - JsonNode peopleProperty = properties.get("people"); - - // If no people property, return a copy of the original schema - if (peopleProperty == null) { - return schema.deepCopy(); - } - - // If people property exists but no personIds, return original (can't transform) - if (personIds == null || personIds.isEmpty()) { - return schema.deepCopy(); - } - - // Deep clone the schema to avoid mutations - ObjectNode transformedSchema = schema.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 personIds as nested properties - ObjectNode newPeopleSchema = objectMapper.createObjectNode(); - newPeopleSchema.put("type", "object"); - ObjectNode newPeopleProperties = objectMapper.createObjectNode(); - if (itemsSchema != null) { - for (String personId : personIds) { - newPeopleProperties.set(personId, itemsSchema.deepCopy()); - } - } - - newPeopleSchema.set("properties", newPeopleProperties); - transformedProperties.set("people", newPeopleSchema); - return transformedSchema; - } - - /** - * Transforms the `enrollments` array property by moving it under people.{personId}.enrollments - * as an array of strings (benefit names). - * - * Example (single ID): - * Input: { enrollments: { type: "array", items: { properties: { personId: ..., benefit: ... } } } } - * Output: { people: { type: "object", properties: { [personId]: { properties: { enrollments: { type: "array", items: { type: "string" } } } } } } } - * - * Example (multiple IDs): - * Input: { enrollments: { type: "array", ... } } - * Output: { people: { type: "object", properties: { [id1]: { properties: { enrollments: ... } }, [id2]: { properties: { enrollments: ... } } } } } - * - * @param schema The JSON Schema to transform - * @param personIds List of personIds to use as keys under people - * @return A new JsonNode with `enrollments` transformed, or the original if no transformation needed - */ - public JsonNode transformEnrollmentsSchema(JsonNode schema, List personIds) { - if (schema == null || !schema.has("properties")) { - return schema != null ? schema.deepCopy() : objectMapper.createObjectNode(); - } - - JsonNode properties = schema.get("properties"); - JsonNode enrollmentsProperty = properties.get("enrollments"); - - // If no enrollments property, return a copy of the original schema - if (enrollmentsProperty == null) { - return schema.deepCopy(); - } - - // If enrollments property exists but no personIds, return original (can't transform) - if (personIds == null || personIds.isEmpty()) { - return schema.deepCopy(); - } - - // Deep clone the schema to avoid mutations - ObjectNode transformedSchema = schema.deepCopy(); - ObjectNode transformedProperties = (ObjectNode) transformedSchema.get("properties"); - - // Remove the top-level enrollments property - transformedProperties.remove("enrollments"); - - // Create enrollments schema as array of strings - ObjectNode enrollmentsSchema = objectMapper.createObjectNode(); - enrollmentsSchema.put("type", "array"); - ObjectNode itemsSchema = objectMapper.createObjectNode(); - itemsSchema.put("type", "string"); - enrollmentsSchema.set("items", itemsSchema); - - // Get or create the people property - JsonNode existingPeople = transformedProperties.get("people"); - ObjectNode peopleSchema; - ObjectNode peopleProps; - - if (existingPeople != null && existingPeople.has("properties")) { - // People already exists (from transformPeopleSchema) - peopleSchema = (ObjectNode) existingPeople; - peopleProps = (ObjectNode) peopleSchema.get("properties"); - } else { - // Create new people structure - peopleSchema = objectMapper.createObjectNode(); - peopleSchema.put("type", "object"); - peopleProps = objectMapper.createObjectNode(); - peopleSchema.set("properties", peopleProps); - transformedProperties.set("people", peopleSchema); - } - - // Add enrollments under each personId - for (String personId : personIds) { - // Get or create the personId property under people - JsonNode existingPersonId = peopleProps.get(personId); - ObjectNode personIdSchema; - ObjectNode personIdProps; - - if (existingPersonId != null && existingPersonId.has("properties")) { - // PersonId already exists - personIdSchema = (ObjectNode) existingPersonId; - personIdProps = (ObjectNode) personIdSchema.get("properties"); - } else { - // Create new personId structure - personIdSchema = objectMapper.createObjectNode(); - personIdSchema.put("type", "object"); - personIdProps = objectMapper.createObjectNode(); - personIdSchema.set("properties", personIdProps); - peopleProps.set(personId, personIdSchema); - } - - // Add enrollments under the personId - personIdProps.set("enrollments", enrollmentsSchema.deepCopy()); - } - - return transformedSchema; - } - /** * Extracts all property paths from a JSON Schema inputDefinition. * Recursively traverses nested objects to build dot-separated paths. @@ -301,7 +108,12 @@ private List traverseSchema(JsonNode schema, String parentPath) { continue; } - String currentPath = parentPath.isEmpty() ? propKey : parentPath + "." + propKey; + String currentPath = ""; + if (propKey.equals("situation")) { + currentPath = parentPath; + } else { + currentPath = parentPath.isEmpty() ? propKey : parentPath + "." + propKey; + } String currentType = getEffectiveType(propValue); // If this property has nested properties, recurse into it diff --git a/builder-api/src/main/java/org/acme/service/KieDmnService.java b/builder-api/src/main/java/org/acme/service/KieDmnService.java index 5e1bcc75..5cec841a 100644 --- a/builder-api/src/main/java/org/acme/service/KieDmnService.java +++ b/builder-api/src/main/java/org/acme/service/KieDmnService.java @@ -195,6 +195,9 @@ public EvaluationResult evaluateDmn( context.set(input.getKey(), input.getValue()); } context.set("parameters", parameters); + Log.info(context.toString()); + + DMNResult dmnResult = dmnRuntime.evaluateAll(dmnModel, context); // Collect and interpret results @@ -208,6 +211,8 @@ public EvaluationResult evaluateDmn( throw new RuntimeException("Multiple decision results from DMN evaluation"); } + Log.info(decisionResults.toString()); + // Assuming single decision result for a Simple DMN DMNDecisionResult decisionResult = decisionResults.get(0); Object result = decisionResult.getResult(); diff --git a/builder-api/src/main/java/org/acme/service/SchemaTemplateTransformer.java b/builder-api/src/main/java/org/acme/service/SchemaTemplateTransformer.java new file mode 100644 index 00000000..83633d52 --- /dev/null +++ b/builder-api/src/main/java/org/acme/service/SchemaTemplateTransformer.java @@ -0,0 +1,157 @@ +package org.acme.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Transforms JSON Schema templates that contain placeholder keys. + * + *

Placeholder keys use the syntax {placeholderName} and can be transformed by + * substituting placeholders with provided values (e.g., {personId} → "client"). + * + *

Example templated schema: + *

+ * {
+ *   "type": "object",
+ *   "properties": {
+ *     "{personId}": {
+ *       "type": "object",
+ *       "properties": {
+ *         "dateOfBirth": { "type": "string" }
+ *       }
+ *     }
+ *   }
+ * }
+ * 
+ * + *

Fill mode with {personId: "client"} produces: + *

+ * {
+ *   "type": "object",
+ *   "properties": {
+ *     "client": { ... }
+ *   }
+ * }
+ * 
+ * + *

Array expansion with {personId: ["client", "spouse"]} produces: + *

+ * {
+ *   "type": "object",
+ *   "properties": {
+ *     "client": { ... },
+ *     "spouse": { ... }
+ *   }
+ * }
+ * 
+ */ +public class SchemaTemplateTransformer { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + // Pattern to match placeholder keys like {placeholderName} + private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("^\\{([^}]+)\\}$"); + + private SchemaTemplateTransformer() { + // Utility class - prevent instantiation + } + + /** + * Fill template placeholders with provided values. + * + *

Walks through the schema and replaces any property key matching {placeholder} + * with the corresponding value from the values map. Values can be: + *

    + *
  • String: replaces the placeholder with a single property
  • + *
  • List<String>: expands the placeholder into multiple properties, one per list item
  • + *
+ * + *

Example with array expansion: + *

+     * Template: { "properties": { "{personId}": { "type": "object" } } }
+     * Values: { "personId": ["alice", "bob"] }
+     * Result: { "properties": { "alice": { "type": "object" }, "bob": { "type": "object" } } }
+     * 
+ * + * @param templateSchema the schema containing placeholder keys + * @param values map of placeholder names to replacement values (String or List<String>) + * @return a new schema with placeholders replaced by actual values + */ + public static JsonNode fillTemplate(JsonNode templateSchema, Map values) { + if (templateSchema == null) { + return null; + } + return fillTemplateRecursive(templateSchema.deepCopy(), values); + } + + @SuppressWarnings("unchecked") + private static JsonNode fillTemplateRecursive(JsonNode node, Map values) { + if (node.isObject()) { + ObjectNode objectNode = (ObjectNode) node; + + // If this object has "properties", process them for placeholder substitution + if (objectNode.has("properties")) { + JsonNode properties = objectNode.get("properties"); + if (properties.isObject()) { + ObjectNode newProperties = MAPPER.createObjectNode(); + + properties.fields().forEachRemaining(entry -> { + String key = entry.getKey(); + JsonNode value = entry.getValue(); + + // Check if key is a placeholder + Matcher matcher = PLACEHOLDER_PATTERN.matcher(key); + if (matcher.matches()) { + String placeholderName = matcher.group(1); + Object replacement = values.get(placeholderName); + if (replacement != null) { + if (replacement instanceof List) { + // Array expansion: create a property for each list item + List replacements = (List) replacement; + for (String r : replacements) { + newProperties.set(r, fillTemplateRecursive(value.deepCopy(), values)); + } + } else { + // Single value replacement + newProperties.set(replacement.toString(), fillTemplateRecursive(value, values)); + } + } else { + // Keep original placeholder if no value provided + newProperties.set(key, fillTemplateRecursive(value, values)); + } + } else { + // Non-placeholder key - keep as is + newProperties.set(key, fillTemplateRecursive(value, values)); + } + }); + + objectNode.set("properties", newProperties); + } + } + + // Recursively process other object fields + objectNode.fields().forEachRemaining(entry -> { + if (!"properties".equals(entry.getKey())) { + JsonNode processed = fillTemplateRecursive(entry.getValue(), values); + objectNode.set(entry.getKey(), processed); + } + }); + + return objectNode; + } else if (node.isArray()) { + ArrayNode arrayNode = (ArrayNode) node; + ArrayNode newArray = MAPPER.createArrayNode(); + for (JsonNode element : arrayNode) { + newArray.add(fillTemplateRecursive(element, values)); + } + return newArray; + } + + return node; + } +} diff --git a/builder-api/src/test/java/org/acme/service/InputSchemaServiceTest.java b/builder-api/src/test/java/org/acme/service/InputSchemaServiceTest.java index f86873e5..b6959efa 100644 --- a/builder-api/src/test/java/org/acme/service/InputSchemaServiceTest.java +++ b/builder-api/src/test/java/org/acme/service/InputSchemaServiceTest.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import org.acme.model.domain.Benefit; import org.acme.model.domain.CheckConfig; import org.acme.model.domain.FormPath; import org.junit.jupiter.api.BeforeEach; @@ -26,20 +27,22 @@ void setUp() { objectMapper = new ObjectMapper(); } - // ==== transformPeopleSchema tests ==== + // ==== extractJsonSchemaPaths tests ==== @Test - void transformPeopleSchema_withPeopleArrayAndSinglePersonId_transformsToObject() throws Exception { + void extractJsonSchemaPaths_withSimpleSchema_extractsCorrectPaths() throws Exception { String schemaJson = """ { "type": "object", "properties": { "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } + "type": "object", + "properties": { + "applicant": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" } + } } } } @@ -48,31 +51,30 @@ void transformPeopleSchema_withPeopleArrayAndSinglePersonId_transformsToObject() """; JsonNode schema = objectMapper.readTree(schemaJson); - JsonNode result = service.transformPeopleSchema(schema, List.of("applicant")); - - // Verify people is now an object with personId key - assertTrue(result.has("properties")); - JsonNode people = result.get("properties").get("people"); - assertEquals("object", people.get("type").asText()); - assertTrue(people.has("properties")); - assertTrue(people.get("properties").has("applicant")); - // Verify the items schema is nested under the personId - assertTrue(people.get("properties").get("applicant").has("properties")); - assertTrue(people.get("properties").get("applicant").get("properties").has("dateOfBirth")); + List paths = service.extractJsonSchemaPaths(schema); + + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertEquals(1, paths.size()); } @Test - void transformPeopleSchema_withMultiplePersonIds_transformsToObjectWithMultipleKeys() throws Exception { + void extractJsonSchemaPaths_withArrayProperty_extractsCorrectPaths() throws Exception { String schemaJson = """ { "type": "object", "properties": { "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } + "type": "object", + "properties": { + "applicant": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" }, + "enrollments": { + "type": "array", + "items": { "type": "string" } + } + } } } } @@ -81,99 +83,33 @@ void transformPeopleSchema_withMultiplePersonIds_transformsToObjectWithMultipleK """; JsonNode schema = objectMapper.readTree(schemaJson); - JsonNode result = service.transformPeopleSchema(schema, List.of("applicant", "spouse", "child")); - - // Verify people is now an object with all personId keys - assertTrue(result.has("properties")); - JsonNode people = result.get("properties").get("people"); - assertEquals("object", people.get("type").asText()); - assertTrue(people.has("properties")); - - // Verify all three personIds are present - assertTrue(people.get("properties").has("applicant")); - assertTrue(people.get("properties").get("applicant").get("properties").has("dateOfBirth")); - assertTrue(people.get("properties").has("spouse")); - assertTrue(people.get("properties").get("spouse").get("properties").has("dateOfBirth")); - assertTrue(people.get("properties").has("child")); - assertTrue(people.get("properties").get("child").get("properties").has("dateOfBirth")); - } - - @Test - void transformPeopleSchema_withoutPersonIds_returnsOriginal() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "people": { - "type": "array", - "items": { "type": "object", "properties": { "dateOfBirth": { "type": "string" } } } - } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformPeopleSchema(schema, Collections.emptyList()); + List paths = service.extractJsonSchemaPaths(schema); - // Should return a copy of the original - assertEquals("array", result.get("properties").get("people").get("type").asText()); + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertTrue(paths.contains(new FormPath("people.applicant.enrollments", "array:string"))); + assertEquals(2, paths.size()); } @Test - void transformPeopleSchema_withNullPersonIds_returnsOriginal() throws Exception { + void extractJsonSchemaPaths_withMultiplePersonIds_extractsPathsForAll() throws Exception { String schemaJson = """ { "type": "object", "properties": { "people": { - "type": "array", - "items": { "type": "object", "properties": { "dateOfBirth": { "type": "string" } } } - } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformPeopleSchema(schema, null); - - // Should return a copy of the original - assertEquals("array", result.get("properties").get("people").get("type").asText()); - } - - @Test - void transformPeopleSchema_withoutPeopleProperty_returnsOriginal() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "income": { "type": "number" } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformPeopleSchema(schema, List.of("applicant")); - - // Should return a copy of the original - assertTrue(result.get("properties").has("income")); - assertFalse(result.get("properties").has("people")); - } - - // ==== transformEnrollmentsSchema tests ==== - - @Test - void transformEnrollmentsSchema_withEnrollmentsAndSinglePersonId_movesUnderPeople() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "enrollments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "personId": { "type": "string" }, - "benefit": { "type": "string" } + "type": "object", + "properties": { + "applicant": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" } + } + }, + "spouse": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" } + } } } } @@ -182,40 +118,28 @@ void transformEnrollmentsSchema_withEnrollmentsAndSinglePersonId_movesUnderPeopl """; JsonNode schema = objectMapper.readTree(schemaJson); - JsonNode result = service.transformEnrollmentsSchema(schema, List.of("applicant")); - - // Verify top-level enrollments is removed - assertFalse(result.get("properties").has("enrollments")); - - // Verify people.applicant.enrollments exists - assertTrue(result.get("properties").has("people")); - JsonNode people = result.get("properties").get("people"); - assertEquals("object", people.get("type").asText()); - assertTrue(people.get("properties").has("applicant")); - - JsonNode applicant = people.get("properties").get("applicant"); - assertTrue(applicant.get("properties").has("enrollments")); - - // Verify enrollments is now array of strings - JsonNode enrollments = applicant.get("properties").get("enrollments"); - assertEquals("array", enrollments.get("type").asText()); - assertEquals("string", enrollments.get("items").get("type").asText()); + List paths = service.extractJsonSchemaPaths(schema); + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertTrue(paths.contains(new FormPath("people.spouse.dateOfBirth", "date"))); + assertEquals(2, paths.size()); } @Test - void transformEnrollmentsSchema_withMultiplePersonIds_movesUnderAllPeople() throws Exception { + void extractJsonSchemaPaths_skipsParametersProperty() throws Exception { String schemaJson = """ { "type": "object", "properties": { - "enrollments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "personId": { "type": "string" }, - "benefit": { "type": "string" } - } + "parameters": { + "type": "object", + "properties": { + "minAge": { "type": "number" } + } + }, + "simpleChecks": { + "type": "object", + "properties": { + "ownerOccupant": { "type": "boolean" } } } } @@ -223,34 +147,16 @@ void transformEnrollmentsSchema_withMultiplePersonIds_movesUnderAllPeople() thro """; JsonNode schema = objectMapper.readTree(schemaJson); - JsonNode result = service.transformEnrollmentsSchema(schema, List.of("applicant", "spouse")); - - // Verify top-level enrollments is removed - assertFalse(result.get("properties").has("enrollments")); - - // Verify people structure exists - assertTrue(result.get("properties").has("people")); - JsonNode people = result.get("properties").get("people"); - assertEquals("object", people.get("type").asText()); - - // Verify both personIds have enrollments - assertTrue(people.get("properties").has("applicant")); - assertTrue(people.get("properties").has("spouse")); - - JsonNode applicant = people.get("properties").get("applicant"); - JsonNode spouse = people.get("properties").get("spouse"); - - assertTrue(applicant.get("properties").has("enrollments")); - assertTrue(spouse.get("properties").has("enrollments")); + List paths = service.extractJsonSchemaPaths(schema); - // Verify enrollments is array of strings for both - assertEquals("array", applicant.get("properties").get("enrollments").get("type").asText()); - assertEquals("array", spouse.get("properties").get("enrollments").get("type").asText()); + // parameters should be skipped + assertFalse(paths.stream().anyMatch(p -> p.getPath().startsWith("parameters"))); + assertTrue(paths.contains(new FormPath("simpleChecks.ownerOccupant", "boolean"))); + assertEquals(1, paths.size()); } @Test - void transformEnrollmentsSchema_withExistingPeopleStructure_mergesEnrollments() throws Exception { - // Simulate a schema that already has people transformed (e.g., from transformPeopleSchema) + void extractJsonSchemaPaths_skipsIdProperties() throws Exception { String schemaJson = """ { "type": "object", @@ -261,122 +167,42 @@ void transformEnrollmentsSchema_withExistingPeopleStructure_mergesEnrollments() "applicant": { "type": "object", "properties": { + "id": { "type": "string" }, "dateOfBirth": { "type": "string", "format": "date" } } } } - }, - "enrollments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "personId": { "type": "string" }, - "benefit": { "type": "string" } - } - } - } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformEnrollmentsSchema(schema, List.of("applicant")); - - // Verify top-level enrollments is removed - assertFalse(result.get("properties").has("enrollments")); - - // Verify people.applicant now has both dateOfBirth and enrollments - JsonNode applicant = result.get("properties").get("people").get("properties").get("applicant"); - assertTrue(applicant.get("properties").has("dateOfBirth")); - assertTrue(applicant.get("properties").has("enrollments")); - } - - @Test - void transformEnrollmentsSchema_withoutPersonIds_returnsOriginal() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "enrollments": { - "type": "array", - "items": { "type": "object", "properties": { "benefit": { "type": "string" } } } - } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformEnrollmentsSchema(schema, Collections.emptyList()); - - // Should return a copy of the original - assertTrue(result.get("properties").has("enrollments")); - } - - @Test - void transformEnrollmentsSchema_withNullPersonIds_returnsOriginal() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "enrollments": { - "type": "array", - "items": { "type": "object", "properties": { "benefit": { "type": "string" } } } } } } """; JsonNode schema = objectMapper.readTree(schemaJson); - JsonNode result = service.transformEnrollmentsSchema(schema, null); - - // Should return a copy of the original - assertTrue(result.get("properties").has("enrollments")); - } - - @Test - void transformEnrollmentsSchema_withoutEnrollmentsProperty_returnsOriginal() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "income": { "type": "number" } - } - } - """; - JsonNode schema = objectMapper.readTree(schemaJson); - - JsonNode result = service.transformEnrollmentsSchema(schema, List.of("applicant")); + List paths = service.extractJsonSchemaPaths(schema); - // Should return a copy of the original - assertTrue(result.get("properties").has("income")); - assertFalse(result.get("properties").has("enrollments")); + // id should be skipped + assertFalse(paths.stream().anyMatch(p -> p.getPath().endsWith(".id"))); + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertEquals(1, paths.size()); } - // ==== transformInputDefinitionSchema composition tests ==== + // ==== extractUniqueInputPaths with fillTemplate tests ==== @Test - void transformInputDefinitionSchema_withPersonId_appliesBothTransforms() throws Exception { + void extractUniqueInputPaths_withTemplateAndPersonId_fillsTemplateAndExtractsPaths() throws Exception { + // x-template-schema style with {personId} placeholder String schemaJson = """ { "type": "object", "properties": { "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } - } - } - }, - "enrollments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "personId": { "type": "string" }, - "benefit": { "type": "string" } + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" } + } } } } @@ -391,40 +217,30 @@ void transformInputDefinitionSchema_withPersonId_appliesBothTransforms() throws params.put("personId", "applicant"); checkConfig.setParameters(params); - JsonNode result = service.transformInputDefinitionSchema(checkConfig); + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); - // Verify top-level enrollments is removed - assertFalse(result.get("properties").has("enrollments")); + List paths = service.extractUniqueInputPaths(List.of(benefit)); - // Verify people.applicant has both dateOfBirth and enrollments - JsonNode applicant = result.get("properties").get("people").get("properties").get("applicant"); - assertTrue(applicant.get("properties").has("dateOfBirth")); - assertTrue(applicant.get("properties").has("enrollments")); - assertEquals("string", applicant.get("properties").get("enrollments").get("items").get("type").asText()); + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertEquals(1, paths.size()); } @Test - void transformInputDefinitionSchema_withPeopleIds_appliesBothTransformsForAllIds() throws Exception { + void extractUniqueInputPaths_withTemplateAndPeopleIds_expandsTemplateForAllIds() throws Exception { + // x-template-schema style with {personId} placeholder String schemaJson = """ { "type": "object", "properties": { "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } - } - } - }, - "enrollments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "personId": { "type": "string" }, - "benefit": { "type": "string" } + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string", "format": "date" } + } } } } @@ -436,37 +252,32 @@ void transformInputDefinitionSchema_withPeopleIds_appliesBothTransformsForAllIds CheckConfig checkConfig = new CheckConfig(); checkConfig.setInputDefinition(inputDefinition); Map params = new HashMap<>(); - params.put("peopleIds", List.of("applicant", "spouse", "child")); + // Using a list of personIds should expand the template for each one + params.put("personId", List.of("applicant", "spouse", "child")); checkConfig.setParameters(params); - JsonNode result = service.transformInputDefinitionSchema(checkConfig); + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); - // Verify top-level enrollments is removed - assertFalse(result.get("properties").has("enrollments")); + List paths = service.extractUniqueInputPaths(List.of(benefit)); - // Verify all three personIds exist under people and have both dateOfBirth and enrollments - JsonNode peopleProps = result.get("properties").get("people").get("properties"); - for (String personId : List.of("applicant", "spouse", "child")) { - assertTrue(peopleProps.has(personId)); - JsonNode person = peopleProps.get(personId); - assertTrue(person.get("properties").has("dateOfBirth"), personId + " should have dateOfBirth"); - assertTrue(person.get("properties").has("enrollments"), personId + " should have enrollments"); - } + assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); + assertTrue(paths.contains(new FormPath("people.spouse.dateOfBirth", "date"))); + assertTrue(paths.contains(new FormPath("people.child.dateOfBirth", "date"))); + assertEquals(3, paths.size()); } @Test - void transformInputDefinitionSchema_withBothPersonIdAndPeopleIds_combinesBoth() throws Exception { + void extractUniqueInputPaths_withNoTemplate_extractsPathsDirectly() throws Exception { + // Schema without any {placeholder} - e.g., simpleChecks String schemaJson = """ { "type": "object", "properties": { - "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } - } + "simpleChecks": { + "type": "object", + "properties": { + "ownerOccupant": { "type": "boolean" } } } } @@ -476,56 +287,20 @@ void transformInputDefinitionSchema_withBothPersonIdAndPeopleIds_combinesBoth() CheckConfig checkConfig = new CheckConfig(); checkConfig.setInputDefinition(inputDefinition); - Map params = new HashMap<>(); - params.put("personId", "applicant"); - params.put("peopleIds", List.of("spouse", "child")); - checkConfig.setParameters(params); - - JsonNode result = service.transformInputDefinitionSchema(checkConfig); - - // Verify all three personIds exist (personId + peopleIds combined) - JsonNode peopleProps = result.get("properties").get("people").get("properties"); - assertTrue(peopleProps.has("applicant")); - assertTrue(peopleProps.has("spouse")); - assertTrue(peopleProps.has("child")); - } + checkConfig.setParameters(Collections.emptyMap()); - @Test - void transformInputDefinitionSchema_withNoPersonParams_returnsOriginalStructure() throws Exception { - String schemaJson = """ - { - "type": "object", - "properties": { - "people": { - "type": "array", - "items": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } - } - } - } - } - } - """; - JsonNode inputDefinition = objectMapper.readTree(schemaJson); - - CheckConfig checkConfig = new CheckConfig(); - checkConfig.setInputDefinition(inputDefinition); - Map params = new HashMap<>(); - params.put("minAge", 65); // Some other parameter, not personId/peopleIds - checkConfig.setParameters(params); + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); - JsonNode result = service.transformInputDefinitionSchema(checkConfig); + List paths = service.extractUniqueInputPaths(List.of(benefit)); - // Should return people as array (no transformation) - assertEquals("array", result.get("properties").get("people").get("type").asText()); + assertTrue(paths.contains(new FormPath("simpleChecks.ownerOccupant", "boolean"))); + assertEquals(1, paths.size()); } - // ==== extractJsonSchemaPaths tests ==== - @Test - void extractJsonSchemaPaths_withTransformedSchema_extractsCorrectPaths() throws Exception { + void extractUniqueInputPaths_withMultipleBenefits_deduplicatesPaths() throws Exception { + // Two benefits with overlapping paths String schemaJson = """ { "type": "object", @@ -533,14 +308,10 @@ void extractJsonSchemaPaths_withTransformedSchema_extractsCorrectPaths() throws "people": { "type": "object", "properties": { - "applicant": { + "{personId}": { "type": "object", "properties": { - "dateOfBirth": { "type": "string", "format": "date" }, - "enrollments": { - "type": "array", - "items": { "type": "string" } - } + "dateOfBirth": { "type": "string", "format": "date" } } } } @@ -548,50 +319,82 @@ void extractJsonSchemaPaths_withTransformedSchema_extractsCorrectPaths() throws } } """; - JsonNode schema = objectMapper.readTree(schemaJson); + JsonNode inputDefinition = objectMapper.readTree(schemaJson); - List paths = service.extractJsonSchemaPaths(schema); + // First benefit with applicant + CheckConfig check1 = new CheckConfig(); + check1.setInputDefinition(inputDefinition); + Map params1 = new HashMap<>(); + params1.put("personId", "applicant"); + check1.setParameters(params1); + + // Second benefit also with applicant (same path) + CheckConfig check2 = new CheckConfig(); + check2.setInputDefinition(inputDefinition); + Map params2 = new HashMap<>(); + params2.put("personId", "applicant"); + check2.setParameters(params2); + + Benefit benefit1 = new Benefit(); + benefit1.setChecks(List.of(check1)); + Benefit benefit2 = new Benefit(); + benefit2.setChecks(List.of(check2)); + + List paths = service.extractUniqueInputPaths(List.of(benefit1, benefit2)); + + // Should only have one path (deduplicated) assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); - assertTrue(paths.contains(new FormPath("people.applicant.enrollments", "array:string"))); - assertEquals(2, paths.size()); + assertEquals(1, paths.size()); } @Test - void extractJsonSchemaPaths_withEnrollmentOnlySchema_extractsCorrectPath() throws Exception { - // This tests the result after transformEnrollmentsSchema is applied to an enrollment-only check + void extractUniqueInputPaths_withNullInputDefinition_skipsCheck() throws Exception { + CheckConfig checkConfig = new CheckConfig(); + checkConfig.setInputDefinition(null); + checkConfig.setParameters(Collections.emptyMap()); + + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); + + List paths = service.extractUniqueInputPaths(List.of(benefit)); + + assertTrue(paths.isEmpty()); + } + + @Test + void extractUniqueInputPaths_withNullParameters_usesEmptyMap() throws Exception { String schemaJson = """ { "type": "object", "properties": { - "people": { + "simpleChecks": { "type": "object", "properties": { - "applicant": { - "type": "object", - "properties": { - "enrollments": { - "type": "array", - "items": { "type": "string" } - } - } - } + "ownerOccupant": { "type": "boolean" } } } } } """; - JsonNode schema = objectMapper.readTree(schemaJson); + JsonNode inputDefinition = objectMapper.readTree(schemaJson); - List paths = service.extractJsonSchemaPaths(schema); + CheckConfig checkConfig = new CheckConfig(); + checkConfig.setInputDefinition(inputDefinition); + checkConfig.setParameters(null); - assertTrue(paths.contains(new FormPath("people.applicant.enrollments", "array:string"))); + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); + + List paths = service.extractUniqueInputPaths(List.of(benefit)); + + assertTrue(paths.contains(new FormPath("simpleChecks.ownerOccupant", "boolean"))); assertEquals(1, paths.size()); } @Test - void extractJsonSchemaPaths_withMultiplePersonIds_extractsPathsForAll() throws Exception { - // This tests the result after transformation with multiple peopleIds + void extractUniqueInputPaths_withUnfilledPlaceholder_keepsPlaceholderInPath() throws Exception { + // If a placeholder isn't filled, it stays as-is in the schema String schemaJson = """ { "type": "object", @@ -599,13 +402,7 @@ void extractJsonSchemaPaths_withMultiplePersonIds_extractsPathsForAll() throws E "people": { "type": "object", "properties": { - "applicant": { - "type": "object", - "properties": { - "dateOfBirth": { "type": "string", "format": "date" } - } - }, - "spouse": { + "{personId}": { "type": "object", "properties": { "dateOfBirth": { "type": "string", "format": "date" } @@ -616,11 +413,20 @@ void extractJsonSchemaPaths_withMultiplePersonIds_extractsPathsForAll() throws E } } """; - JsonNode schema = objectMapper.readTree(schemaJson); + JsonNode inputDefinition = objectMapper.readTree(schemaJson); - List paths = service.extractJsonSchemaPaths(schema); - assertTrue(paths.contains(new FormPath("people.applicant.dateOfBirth", "date"))); - assertTrue(paths.contains(new FormPath("people.spouse.dateOfBirth", "date"))); - assertEquals(2, paths.size()); + CheckConfig checkConfig = new CheckConfig(); + checkConfig.setInputDefinition(inputDefinition); + // No personId parameter provided + checkConfig.setParameters(Collections.emptyMap()); + + Benefit benefit = new Benefit(); + benefit.setChecks(List.of(checkConfig)); + + List paths = service.extractUniqueInputPaths(List.of(benefit)); + + // The placeholder remains unfilled + assertTrue(paths.contains(new FormPath("people.{personId}.dateOfBirth", "date"))); + assertEquals(1, paths.size()); } } diff --git a/builder-api/src/test/java/org/acme/service/SchemaTemplateTransformerTest.java b/builder-api/src/test/java/org/acme/service/SchemaTemplateTransformerTest.java new file mode 100644 index 00000000..5ec1af85 --- /dev/null +++ b/builder-api/src/test/java/org/acme/service/SchemaTemplateTransformerTest.java @@ -0,0 +1,199 @@ +package org.acme.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +public class SchemaTemplateTransformerTest { + + private ObjectMapper objectMapper; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + } + + @Test + void fillTemplate_withStringValue_replacesPlaceholder() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "properties": { + "name": { "type": "string" } + } + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", "applicant"); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, values); + + assertTrue(result.get("properties").has("applicant")); + assertFalse(result.get("properties").has("{personId}")); + assertTrue(result.get("properties").get("applicant").get("properties").has("name")); + } + + @Test + void fillTemplate_withListValue_expandsToMultipleProperties() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", List.of("applicant", "spouse", "child")); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, values); + + assertTrue(result.get("properties").has("applicant")); + assertTrue(result.get("properties").has("spouse")); + assertTrue(result.get("properties").has("child")); + assertFalse(result.get("properties").has("{personId}")); + } + + @Test + void fillTemplate_withNoMatchingValue_keepsPlaceholder() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "{unknownPlaceholder}": { + "type": "string" + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", "applicant"); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, values); + + assertTrue(result.get("properties").has("{unknownPlaceholder}")); + assertFalse(result.get("properties").has("applicant")); + } + + @Test + void fillTemplate_withNestedPlaceholders_replacesAllLevels() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", "client"); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, values); + + assertTrue(result.get("properties").get("people").get("properties").has("client")); + assertFalse(result.get("properties").get("people").get("properties").has("{personId}")); + } + + @Test + void fillTemplate_withEmptyValues_keepsAllPlaceholders() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "{personId}": { + "type": "string" + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, Collections.emptyMap()); + + assertTrue(result.get("properties").has("{personId}")); + } + + @Test + void fillTemplate_withNullTemplate_returnsNull() { + JsonNode result = SchemaTemplateTransformer.fillTemplate(null, Map.of("personId", "test")); + assertNull(result); + } + + @Test + void fillTemplate_withNonPlaceholderKeys_preservesKeys() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "simpleChecks": { + "type": "object", + "properties": { + "ownerOccupant": { "type": "boolean" } + } + }, + "{personId}": { + "type": "string" + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", "applicant"); + + JsonNode result = SchemaTemplateTransformer.fillTemplate(template, values); + + assertTrue(result.get("properties").has("simpleChecks")); + assertTrue(result.get("properties").has("applicant")); + assertFalse(result.get("properties").has("{personId}")); + } + + @Test + void fillTemplate_doesNotMutateOriginal() throws Exception { + String templateJson = """ + { + "type": "object", + "properties": { + "{personId}": { + "type": "string" + } + } + } + """; + JsonNode template = objectMapper.readTree(templateJson); + Map values = Map.of("personId", "applicant"); + + SchemaTemplateTransformer.fillTemplate(template, values); + + // Original should still have the placeholder + assertTrue(template.get("properties").has("{personId}")); + assertFalse(template.get("properties").has("applicant")); + } +} diff --git a/builder-frontend/src/api/check.ts b/builder-frontend/src/api/check.ts index dfd08c82..f4cdb3b7 100644 --- a/builder-frontend/src/api/check.ts +++ b/builder-frontend/src/api/check.ts @@ -85,6 +85,8 @@ export const updateCheck = async ( body.description = updates.description; if (updates.parameterDefinitions !== undefined) body.parameterDefinitions = updates.parameterDefinitions; + if (updates.inputDefinition !== undefined) + body.inputDefinition = updates.inputDefinition; const response = await authPatch(url, body); diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/EligibilityCheckDetail.tsx b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/EligibilityCheckDetail.tsx index 786b6405..536b5e0b 100644 --- a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/EligibilityCheckDetail.tsx +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/EligibilityCheckDetail.tsx @@ -11,19 +11,19 @@ import EligibilityCheckTest from "./checkTesting/EligibilityCheckTest"; import PublishCheck from "./PublishCheck"; import eligibilityCheckDetailResource from "./eligibilityCheckDetailResource"; -import ParametersConfiguration from "./ParametersConfiguration"; +import InputSchemaEditor from "./inputSchemaEditor/InputSchemaEditor"; import ErrorDisplayModal from "@/components/shared/ErrorModal"; import BdtNavbar, { NavbarProps } from "@/components/shared/BdtNavbar"; -type CheckDetailScreenMode = "paramConfig" | "dmnDefinition" | "testing" | "publish"; +type CheckDetailScreenMode = "inputSchema" | "dmnDefinition" | "testing" | "publish"; const EligibilityCheckDetail = () => { const { checkId } = useParams(); const [currentDmnModel, setCurrentDmnModel] = createSignal(""); - const [screenMode, setScreenMode] = createSignal("paramConfig"); + const [screenMode, setScreenMode] = createSignal("inputSchema"); const [validationErrors, setValidationErrors] = createSignal([]); const [showingErrorModal, setShowingErrorModal] = createSignal(false); @@ -48,7 +48,7 @@ const EligibilityCheckDetail = () => { const navbarDefs: Accessor = () => { return { tabDefs: [ - { key: "paramConfig", label: "Parameter Configuration", onClick: () => setScreenMode("paramConfig") }, + { key: "inputSchema", label: "Input Schema", onClick: () => setScreenMode("inputSchema") }, { key: "dmnDefinition", label: "DMN Definition", onClick: () => setScreenMode("dmnDefinition") }, { key: "testing", label: "Testing", onClick: () => setScreenMode("testing") }, { key: "publish", label: "Publish", onClick: () => setScreenMode("publish") }, @@ -68,12 +68,10 @@ const EligibilityCheckDetail = () => { - - + diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/eligibilityCheckDetailResource.ts b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/eligibilityCheckDetailResource.ts index c85591da..712cb86c 100644 --- a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/eligibilityCheckDetailResource.ts +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/eligibilityCheckDetailResource.ts @@ -11,6 +11,7 @@ import { validateCheckDmn, } from "@/api/check"; +import type { JSONSchema7 } from "json-schema"; import type { CheckConfig, EligibilityCheckDetail, @@ -27,6 +28,7 @@ export interface EligibilityCheckDetailResource { parameterDef: ParameterDefinition ) => Promise; removeParameter: (parameterIndex: number) => Promise; + updateInputSchema: (schema: JSONSchema7, parameters: ParameterDefinition[]) => Promise; saveDmnModel: (dmnString: string) => Promise; validateDmnModel: (dmnString: string) => Promise; testEligibility: ( @@ -120,6 +122,22 @@ const eligibilityCheckDetailResource = ( setActionInProgress(false); }; + const updateInputSchema = async (schema: JSONSchema7, parameters: ParameterDefinition[]) => { + setActionInProgress(true); + try { + await updateCheck(eligibilityCheck.id, { + inputDefinition: schema, + parameterDefinitions: parameters + }); + toast.success("Input schema saved successfully."); + await refetch(); + } catch (e) { + console.error("Failed to save input schema", e); + toast.error("Failed to save input schema."); + } + setActionInProgress(false); + }; + const saveDmnModel = async (dmnString: string) => { setActionInProgress(true); try { @@ -185,6 +203,7 @@ const eligibilityCheckDetailResource = ( addParameter, updateParameter, removeParameter, + updateInputSchema, saveDmnModel, validateDmnModel, testEligibility, diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/InputSchemaEditor.tsx b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/InputSchemaEditor.tsx new file mode 100644 index 00000000..7cac8ef9 --- /dev/null +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/InputSchemaEditor.tsx @@ -0,0 +1,165 @@ +import { Accessor, createSignal, createEffect, Show } from "solid-js"; +import { createStore } from "solid-js/store"; +import type { JSONSchema7 } from "json-schema"; + +import SituationSchemaSection from "./SituationSchemaSection"; +import ParametersSchemaSection from "./ParametersSchemaSection"; +import { + getDefaultEditorState, + parseJsonSchemaToEditorState, + convertEditorStateToJsonSchema, + validateEditorState, +} from "./schemaUtils"; + +import type { EligibilityCheck, InputSchemaEditorState, SituationSchemaConfig, ParameterDefinition } from "@/types"; +import Tooltip from "@/components/shared/Tooltip"; + +interface InputSchemaEditorProps { + eligibilityCheck: Accessor; + onSave: (schema: JSONSchema7, parameterDefinitions: ParameterDefinition[]) => Promise; +} + +const InputSchemaEditor = (props: InputSchemaEditorProps) => { + const [editorState, setEditorState] = createStore( + getDefaultEditorState() + ); + const [validationErrors, setValidationErrors] = createSignal([]); + const [showPreview, setShowPreview] = createSignal(false); + const [isSaving, setIsSaving] = createSignal(false); + const [initialLoadComplete, setInitialLoadComplete] = createSignal(false); + + // Load initial state from existing inputDefinition (only once on initial load) + createEffect(() => { + const check = props.eligibilityCheck(); + if (check && check.id && !initialLoadComplete()) { + if (check.inputDefinition) { + const parsed = parseJsonSchemaToEditorState(check.inputDefinition); + setEditorState(parsed); + } + setInitialLoadComplete(true); + } + }); + + const handleSituationChange = (config: SituationSchemaConfig) => { + setEditorState("situation", config); + setValidationErrors([]); + }; + + const handleParametersChange = (parameters: ParameterDefinition[]) => { + setEditorState("parameters", parameters); + setValidationErrors([]); + }; + + const handleSave = async () => { + // Validate + const validation = validateEditorState(editorState); + if (!validation.valid) { + setValidationErrors(validation.errors); + return; + } + + // Convert to JSON Schema + const schema = convertEditorStateToJsonSchema(editorState); + + // Save + setIsSaving(true); + try { + await props.onSave(schema, editorState.parameters); + setValidationErrors([]); + // Allow the effect to reload fresh data from server after save + setInitialLoadComplete(false); + } catch (error) { + console.error("Failed to save schema:", error); + setValidationErrors(["Failed to save schema. Please try again."]); + } finally { + setIsSaving(false); + } + }; + + const getPreviewJson = () => { + const schema = convertEditorStateToJsonSchema(editorState); + return JSON.stringify(schema, null, 2); + }; + + return ( +
+
+

{props.eligibilityCheck().name}

+ +

+ Define the input schema for your custom check. This specifies what + data your DMN will receive in the situation and{" "} + parameters inputs. +

+

+ + Learn more about input schemas + +

+
+
+ + {/* Validation Errors */} + 0}> +
+

Validation Errors

+
    + {validationErrors().map((error) => ( +
  • {error}
  • + ))} +
+
+
+ +
+ {/* Situation Schema Section */} + + + {/* Parameters Schema Section */} + +
+ + {/* Actions */} +
+ + +
+ + {/* JSON Preview */} + +
+

Generated JSON Schema

+
+            {getPreviewJson()}
+          
+
+
+
+ ); +}; + +export default InputSchemaEditor; diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/ParametersSchemaSection.tsx b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/ParametersSchemaSection.tsx new file mode 100644 index 00000000..2bfa4752 --- /dev/null +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/ParametersSchemaSection.tsx @@ -0,0 +1,125 @@ +import { For, Index } from "solid-js"; +import type { ParameterDefinition, ParameterType } from "@/types"; + +interface ParametersSchemaSectionProps { + parameters: ParameterDefinition[]; + onChange: (parameters: ParameterDefinition[]) => void; +} + +const PARAMETER_TYPES: { value: ParameterType; label: string }[] = [ + { value: "string", label: "String" }, + { value: "number", label: "Number" }, + { value: "boolean", label: "Boolean" }, + { value: "date", label: "Date" }, + { value: "array", label: "String List" }, +]; + +const ParametersSchemaSection = (props: ParametersSchemaSectionProps) => { + const handleParameterChange = ( + index: number, + field: keyof ParameterDefinition, + value: string | boolean + ) => { + const newParams = [...props.parameters]; + newParams[index] = { + ...newParams[index], + [field]: value, + }; + props.onChange(newParams); + }; + + const addParameter = () => { + props.onChange([ + ...props.parameters, + { key: "", label: "", type: "string", required: true }, + ]); + }; + + const removeParameter = (index: number) => { + const newParams = props.parameters.filter((_, i) => i !== index); + props.onChange(newParams); + }; + + return ( +
+

Parameters Schema

+

+ Define the parameters your check accepts. These are passed in the parameters input. +

+ + {props.parameters.length > 0 && ( +
+ {/* Header row */} + + + {/* Parameter rows */} +
+ + {(param, index) => ( +
+ + handleParameterChange(index, "key", e.currentTarget.value) + } + placeholder="parameterKey" + class="form-input border border-gray-300 rounded flex-2" + /> + +
+ +
+ +
+ )} +
+
+
+ )} + + {props.parameters.length === 0 && ( +

No parameters defined yet.

+ )} + + +
+ ); +}; + +export default ParametersSchemaSection; diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/SituationSchemaSection.tsx b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/SituationSchemaSection.tsx new file mode 100644 index 00000000..099e941f --- /dev/null +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/SituationSchemaSection.tsx @@ -0,0 +1,250 @@ +import { For, Index, Show } from "solid-js"; +import type { SituationSchemaConfig, PeopleKeyDefinition, ParameterDefinition } from "@/types"; +import { createDefaultPeopleKey } from "./schemaUtils"; + +interface SituationSchemaSectionProps { + config: SituationSchemaConfig; + parameters: ParameterDefinition[]; + onChange: (config: SituationSchemaConfig) => void; +} + +const SituationSchemaSection = (props: SituationSchemaSectionProps) => { + // Get string parameters that can be used as people key references + const stringParameters = () => + props.parameters.filter((p) => p.type === "string").map((p) => p.key); + + const handlePeopleKeyChange = (index: number, updates: Partial) => { + const newKeys = [...props.config.people.keys]; + newKeys[index] = { ...newKeys[index], ...updates }; + props.onChange({ + ...props.config, + people: { + ...props.config.people, + keys: newKeys, + }, + }); + }; + + const addPeopleKey = (isParameterReference: boolean) => { + props.onChange({ + ...props.config, + people: { + ...props.config.people, + keys: [...props.config.people.keys, createDefaultPeopleKey(isParameterReference)], + }, + }); + }; + + const removePeopleKey = (index: number) => { + const newKeys = props.config.people.keys.filter((_, i) => i !== index); + props.onChange({ + ...props.config, + people: { + ...props.config.people, + keys: newKeys, + }, + }); + }; + + const handleSimpleCheckKeyChange = (index: number, value: string) => { + const newKeys = [...props.config.simpleChecks]; + newKeys[index] = value; + props.onChange({ + ...props.config, + simpleChecks: newKeys, + }); + }; + + const addSimpleCheck = () => { + props.onChange({ + ...props.config, + simpleChecks: [...props.config.simpleChecks, ""], + }); + }; + + const removeSimpleCheck = (index: number) => { + const newKeys = props.config.simpleChecks.filter((_, i) => i !== index); + props.onChange({ + ...props.config, + simpleChecks: newKeys, + }); + }; + + return ( +
+

Situation Schema

+

+ Define which parts of the situation data your check needs access to. +

+ + {/* People Section */} +
+

People

+

+ Define person keys under{" "} + situation.people and their properties. +

+ + {/* People Keys */} +
+ + {(keyDef, index) => ( +
+
+ + handlePeopleKeyChange(index, { value: e.currentTarget.value }) + } + placeholder="e.g., client" + class="form-input border border-gray-300 rounded px-3 py-1.5 w-48" + /> + } + > +
+ {"{"} + + {"}"} +
+
+ + {keyDef().isParameterReference ? "(parameter)" : "(static)"} + + +
+ + {/* Properties for this key */} +
+ Properties: +
+ + +
+
+
+ )} +
+ +
+ + +
+
+
+ + {/* Simple Checks */} +
+

Simple Checks

+

+ Define boolean flags your check needs from{" "} + situation.simpleChecks +

+
+ + {(key, index) => ( +
+ + handleSimpleCheckKeyChange(index, e.currentTarget.value) + } + placeholder="e.g., ownerOccupant" + class="form-input border border-gray-300 rounded px-3 py-1.5 w-64" + /> + : boolean + +
+ )} +
+ +
+
+
+ ); +}; + +export default SituationSchemaSection; diff --git a/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/schemaUtils.ts b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/schemaUtils.ts new file mode 100644 index 00000000..195c1108 --- /dev/null +++ b/builder-frontend/src/components/homeScreen/eligibilityCheckList/eligibilityCheckDetail/inputSchemaEditor/schemaUtils.ts @@ -0,0 +1,388 @@ +import type { JSONSchema7 } from "json-schema"; +import type { + InputSchemaEditorState, + SituationSchemaConfig, + ParameterType, + PeopleKeyDefinition, + ParameterDefinition, +} from "@/types"; + +// Default empty state for the editor +export const getDefaultEditorState = (): InputSchemaEditorState => ({ + situation: { + people: { + keys: [], + }, + simpleChecks: [], + }, + parameters: [], +}); + +// Create a new people key with default properties +export const createDefaultPeopleKey = (isParameterReference: boolean): PeopleKeyDefinition => ({ + value: "", + isParameterReference, + includeDateOfBirth: false, + includeEnrollments: false, +}); + +// Convert a ParameterType to JSON Schema type +const parameterTypeToJsonSchemaType = ( + type: ParameterType +): { type: string; format?: string; items?: { type: string } } => { + switch (type) { + case "string": + return { type: "string" }; + case "number": + return { type: "number" }; + case "boolean": + return { type: "boolean" }; + case "date": + return { type: "string", format: "date" }; + case "array": + return { type: "array", items: { type: "string" } }; + default: + return { type: "string" }; + } +}; + +// Convert JSON Schema type back to ParameterType +const jsonSchemaTypeToParameterType = ( + schemaProperty: JSONSchema7 +): ParameterType => { + if (schemaProperty.type === "array") { + return "array"; + } + if (schemaProperty.type === "string" && schemaProperty.format === "date") { + return "date"; + } + if (schemaProperty.type === "number") { + return "number"; + } + if (schemaProperty.type === "boolean") { + return "boolean"; + } + return "string"; +}; + +// Convert editor state to a valid JSON Schema +export const convertEditorStateToJsonSchema = ( + state: InputSchemaEditorState +): JSONSchema7 => { + const schema: JSONSchema7 = { + $schema: "http://json-schema.org/draft-07/schema#", + type: "object", + properties: { + situation: buildSituationSchema(state.situation), + parameters: buildParametersSchema(state.parameters), + }, + required: ["situation", "parameters"], + }; + + return schema; +}; + +// Build the person properties schema for a specific key definition +const buildPersonPropertiesSchema = (keyDef: PeopleKeyDefinition): Record => { + const personProperties: Record = {}; + + if (keyDef.includeDateOfBirth) { + personProperties.dateOfBirth = { + type: "string", + format: "date", + description: "The person's date of birth in ISO 8601 format (YYYY-MM-DD)", + }; + } + + if (keyDef.includeEnrollments) { + personProperties.enrollments = { + type: "array", + description: "List of benefit programs this person is enrolled in", + items: { type: "string" }, + }; + } + + return personProperties; +}; + +// Build the situation portion of the schema +const buildSituationSchema = (config: SituationSchemaConfig): JSONSchema7 => { + const situationProperties: Record = {}; + const situationRequired: string[] = []; + + // Build people schema if any keys are defined with at least one property + const keysWithProperties = config.people.keys.filter( + (k) => k.includeDateOfBirth || k.includeEnrollments + ); + + if (keysWithProperties.length > 0) { + const peopleProperties: Record = {}; + + for (const keyDef of keysWithProperties) { + // Use the key as-is (either static like "client" or template like "{personId}") + const keyName = keyDef.isParameterReference ? `{${keyDef.value}}` : keyDef.value; + const personProperties = buildPersonPropertiesSchema(keyDef); + + peopleProperties[keyName] = { + type: "object", + description: keyDef.isParameterReference + ? `Person identified by the ${keyDef.value} parameter` + : `Person with key "${keyDef.value}"`, + properties: personProperties, + }; + } + + situationProperties.people = { + type: "object", + description: "Household members keyed by person ID", + properties: peopleProperties, + }; + situationRequired.push("people"); + } + + // Build simpleChecks schema if any keys are defined + if (config.simpleChecks.length > 0) { + const simpleChecksProperties: Record = {}; + + for (const key of config.simpleChecks) { + simpleChecksProperties[key] = { + type: "boolean", + description: `Boolean flag for ${key}`, + }; + } + + situationProperties.simpleChecks = { + type: "object", + description: "Pre-computed boolean checks", + properties: simpleChecksProperties, + required: config.simpleChecks, + }; + situationRequired.push("simpleChecks"); + } + + return { + type: "object", + properties: situationProperties, + required: situationRequired.length > 0 ? situationRequired : undefined, + }; +}; + +// Build the parameters portion of the schema +const buildParametersSchema = ( + parameters: ParameterDefinition[] +): JSONSchema7 => { + const properties: Record = {}; + const required: string[] = []; + + for (const param of parameters) { + const typeInfo = parameterTypeToJsonSchemaType(param.type); + properties[param.key] = { + ...typeInfo, + description: param.description, + } as JSONSchema7; + + if (param.required) { + required.push(param.key); + } + } + + return { + type: "object", + description: "Check parameters", + properties, + required: required.length > 0 ? required : undefined, + }; +}; + +// Parse an existing JSON Schema back into editor state +export const parseJsonSchemaToEditorState = ( + schema: JSONSchema7 | undefined | null, +): InputSchemaEditorState => { + if (!schema || typeof schema !== "object") { + return getDefaultEditorState(); + } + + const state = getDefaultEditorState(); + + const properties = schema.properties as Record | undefined; + if (!properties) { + return state; + } + + // Parse situation + const situationSchema = properties.situation as JSONSchema7 | undefined; + if (situationSchema && typeof situationSchema === "object") { + const situationProps = situationSchema.properties as Record | undefined; + + if (situationProps) { + // Parse people + const peopleSchema = situationProps.people as JSONSchema7 | undefined; + if (peopleSchema && typeof peopleSchema === "object") { + // Check for explicit properties (new format with specific keys) + const peopleProps = peopleSchema.properties as Record | undefined; + if (peopleProps) { + // Parse each person key with its individual properties + for (const [key, personSchema] of Object.entries(peopleProps)) { + const isParameterRef = key.startsWith("{") && key.endsWith("}"); + const personProps = (personSchema as JSONSchema7).properties as Record | undefined; + + state.situation.people.keys.push({ + value: isParameterRef ? key.slice(1, -1) : key, + isParameterReference: isParameterRef, + includeDateOfBirth: personProps ? "dateOfBirth" in personProps : false, + includeEnrollments: personProps ? "enrollments" in personProps : false, + }); + } + } + + // Fallback: check for additionalProperties (old format) - create a generic key + if (state.situation.people.keys.length === 0) { + const additionalProps = peopleSchema.additionalProperties as JSONSchema7 | undefined; + if (additionalProps && typeof additionalProps === "object") { + const personProps = additionalProps.properties as Record | undefined; + if (personProps) { + // Old format had shared properties - we can't determine keys, so skip + // User will need to reconfigure + } + } + } + } + + // Parse simpleChecks + const simpleChecksSchema = situationProps.simpleChecks as JSONSchema7 | undefined; + if (simpleChecksSchema && typeof simpleChecksSchema === "object") { + const simpleChecksProps = simpleChecksSchema.properties as Record | undefined; + if (simpleChecksProps) { + state.situation.simpleChecks = Object.keys(simpleChecksProps); + } + } + } + } + + // Parse parameters + const parametersSchema = properties.parameters as JSONSchema7 | undefined; + if (parametersSchema && typeof parametersSchema === "object") { + const paramProps = parametersSchema.properties as Record | undefined; + const requiredParams = (parametersSchema.required as string[]) || []; + + if (paramProps) { + state.parameters = Object.entries(paramProps).map(([key, propSchema]) => ({ + key, + label: key, + type: jsonSchemaTypeToParameterType(propSchema as JSONSchema7), + required: requiredParams.includes(key), + description: (propSchema as JSONSchema7).description, + })); + } + } + + return state; +}; + +// Validation result type +export interface ValidationResult { + valid: boolean; + errors: string[]; +} + +// Validate editor state before converting to schema +export const validateEditorState = ( + state: InputSchemaEditorState +): ValidationResult => { + const errors: string[] = []; + + // Get list of defined string parameters (for validating parameter references) + const stringParameters = new Set( + state.parameters + .filter((p) => p.type === "string") + .map((p) => p.key) + ); + + // Check that at least something is defined + const keysWithProperties = state.situation.people.keys.filter( + (k) => k.includeDateOfBirth || k.includeEnrollments + ); + const hasPeopleConfig = keysWithProperties.length > 0; + const hasSimpleChecks = state.situation.simpleChecks.length > 0; + const hasParameters = state.parameters.length > 0; + + if (!hasPeopleConfig && !hasSimpleChecks && !hasParameters) { + errors.push( + "At least one situation property (people with properties or simpleChecks) or one parameter must be defined." + ); + } + + // Validate people keys + const peopleKeys = new Set(); + for (const keyDef of state.situation.people.keys) { + if (!keyDef.value || keyDef.value.trim() === "") { + errors.push("People keys cannot be empty."); + } else if (keyDef.isParameterReference) { + // Validate that the referenced parameter exists and is a string type + if (!stringParameters.has(keyDef.value)) { + errors.push( + `People key references parameter "${keyDef.value}" but no string parameter with that name exists.` + ); + } + } else { + // Validate static key format + if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(keyDef.value)) { + errors.push( + `People key "${keyDef.value}" is invalid. Keys must start with a letter and contain only letters, numbers, and underscores.` + ); + } + } + + // Validate that each key has at least one property selected + if (keyDef.value && !keyDef.includeDateOfBirth && !keyDef.includeEnrollments) { + const displayKey = keyDef.isParameterReference ? `{${keyDef.value}}` : keyDef.value; + errors.push( + `People key "${displayKey}" must have at least one property selected (dateOfBirth or enrollments).` + ); + } + + const keyForDuplicateCheck = keyDef.isParameterReference ? `{${keyDef.value}}` : keyDef.value; + if (peopleKeys.has(keyForDuplicateCheck)) { + errors.push(`Duplicate people key: "${keyForDuplicateCheck}".`); + } else { + peopleKeys.add(keyForDuplicateCheck); + } + } + + // Validate simpleChecks keys + const simpleCheckKeys = new Set(); + for (const key of state.situation.simpleChecks) { + if (!key || key.trim() === "") { + errors.push("Simple check keys cannot be empty."); + } else if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(key)) { + errors.push( + `Simple check key "${key}" is invalid. Keys must start with a letter and contain only letters, numbers, and underscores.` + ); + } else if (simpleCheckKeys.has(key)) { + errors.push(`Duplicate simple check key: "${key}".`); + } else { + simpleCheckKeys.add(key); + } + } + + // Validate parameter keys + const parameterKeys = new Set(); + for (const param of state.parameters) { + if (!param.key || param.key.trim() === "") { + errors.push("Parameter keys cannot be empty."); + } else if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param.key)) { + errors.push( + `Parameter key "${param.key}" is invalid. Keys must start with a letter and contain only letters, numbers, and underscores.` + ); + } else if (parameterKeys.has(param.key)) { + errors.push(`Duplicate parameter key: "${param.key}".`); + } else { + parameterKeys.add(param.key); + } + } + + return { + valid: errors.length === 0, + errors, + }; +}; diff --git a/builder-frontend/src/types.ts b/builder-frontend/src/types.ts index 5a7c95d1..e806b502 100644 --- a/builder-frontend/src/types.ts +++ b/builder-frontend/src/types.ts @@ -59,6 +59,7 @@ export interface CreateCheckRequest { export interface UpdateCheckRequest { description?: string; parameterDefinitions?: ParameterDefinition[]; + inputDefinition?: JSONSchema7; } // Request types for Custom Benefit API endpoints @@ -92,6 +93,7 @@ interface BaseParameter { key: string; label: string; required: boolean; + description?: string; } export interface StringMultiInputParameter extends BaseParameter { type: "array"; @@ -144,4 +146,30 @@ export interface PublishedScreener { export interface FormPath { path: string; type: string; -} \ No newline at end of file +} + +// Input Schema Editor Types +export interface InputSchemaEditorState { + situation: SituationSchemaConfig; + parameters: ParameterDefinition[]; +} + +export interface SituationSchemaConfig { + people: PeopleSchemaConfig; + simpleChecks: string[]; // List of boolean flag keys the check needs +} + +export interface PeopleSchemaConfig { + // List of person keys with their individual property configurations + keys: PeopleKeyDefinition[]; +} + +export interface PeopleKeyDefinition { + // The key value - either a static string like "client" or a parameter reference like "personId" (without braces) + value: string; + // Whether this references a parameter (true) or is a static string (false) + isParameterReference: boolean; + // Which properties this specific person key requires + includeDateOfBirth: boolean; + includeEnrollments: boolean; +} diff --git a/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNOpenAPIFilter.java b/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNOpenAPIFilter.java index 184ce154..a37e32af 100644 --- a/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNOpenAPIFilter.java +++ b/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNOpenAPIFilter.java @@ -28,6 +28,12 @@ * This creates specific paths like /api/v1/checks/age/PersonMinAge instead of a single * parameterized path, making the API more discoverable and providing proper type examples. * + *

Schema sources (in order of preference): + *

    + *
  1. .schema.json files alongside DMN files (flattened via SchemaTemplateTransformer)
  2. + *
  3. Auto-generated dmnDefinitions.json from Kogito
  4. + *
+ * * Note: This is registered via mp.openapi.filter in application.properties, not as a CDI bean. */ public class DynamicDMNOpenAPIFilter implements OASFilter { @@ -36,6 +42,7 @@ public class DynamicDMNOpenAPIFilter implements OASFilter { private ModelRegistry modelRegistry; private DMNSchemaResolver schemaResolver; + private SchemaFileLoader schemaFileLoader; @Override public void filterOpenAPI(OpenAPI openAPI) { @@ -48,6 +55,9 @@ public void filterOpenAPI(OpenAPI openAPI) { if (schemaResolver == null) { schemaResolver = CDI.current().select(DMNSchemaResolver.class).get(); } + if (schemaFileLoader == null) { + schemaFileLoader = CDI.current().select(SchemaFileLoader.class).get(); + } // Ensure components exist if (openAPI.getComponents() == null) { @@ -225,6 +235,18 @@ private Schema convertJsonNodeToSchema(com.fasterxml.jackson.databind.JsonNode n schema.items(convertJsonNodeToSchema(node.get("items"))); } + // Handle additionalProperties (for dynamic keys like {personId}) + if (node.has("additionalProperties")) { + com.fasterxml.jackson.databind.JsonNode additionalProps = node.get("additionalProperties"); + if (additionalProps.isBoolean()) { + // additionalProperties: true/false + schema.additionalPropertiesBoolean(additionalProps.asBoolean()); + } else if (additionalProps.isObject()) { + // additionalProperties: { type: "object", properties: {...} } + schema.additionalPropertiesSchema(convertJsonNodeToSchema(additionalProps)); + } + } + // Handle required fields if (node.has("required")) { com.fasterxml.jackson.databind.JsonNode required = node.get("required"); @@ -291,8 +313,37 @@ private RequestBody createRequestBody(ModelInfo model, String serviceName, Strin Content content = OASFactory.createContent(); MediaType mediaType = OASFactory.createMediaType(); - // Set schema reference if available - if (inputRef != null) { + // Prefer .schema.json file if it exists + com.fasterxml.jackson.databind.JsonNode schemaJsonFile = schemaFileLoader.loadFlattenedSchema(model.getPath()); + com.fasterxml.jackson.databind.JsonNode originalSchema = schemaFileLoader.loadOriginalSchema(model.getPath()); + + if (schemaJsonFile != null) { + // Use the flattened schema from .schema.json file + Schema schema = convertJsonNodeToSchema(schemaJsonFile); + mediaType.schema(schema); + + // Generate example from the schema file + Map exampleData = schemaFileLoader.generateExample(model.getPath()); + if (!exampleData.isEmpty()) { + Example example = OASFactory.createExample(); + example.value(convertToOpenAPIValue(exampleData)); + mediaType.addExample("Example request", example); + } + + // Add the original templated schema as x-template-schema extension + if (originalSchema != null) { + try { + // Convert JsonNode to a Map for the extension + Object templateSchemaMap = OBJECT_MAPPER.convertValue(originalSchema, Object.class); + mediaType.addExtension("x-template-schema", templateSchemaMap); + } catch (Exception e) { + LOG.warning("Failed to add x-template-schema extension: " + e.getMessage()); + } + } + + LOG.fine("Using .schema.json for request body: " + model.getPath()); + } else if (inputRef != null) { + // Fall back to dmnDefinitions.json schema Schema schema = OASFactory.createSchema(); schema.ref(inputRef); mediaType.schema(schema); diff --git a/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNResource.java b/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNResource.java index 2f0aa776..8cb4eedb 100644 --- a/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNResource.java +++ b/library-api/src/main/java/org/codeforphilly/bdt/api/DynamicDMNResource.java @@ -108,6 +108,8 @@ public Response evaluateDecisionService( .build(); } + log.warn("made it far"); + // 4. Evaluate the decision service DMNResult dmnResult; try { @@ -115,6 +117,7 @@ public Response evaluateDecisionService( DMNJSONUtils.ctx(decision, variables, serviceName), serviceName ); + log.warn(dmnResult.toString()); } catch (Exception e) { log.error("Error evaluating decision service: {}/{}", modelName, serviceName, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) diff --git a/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaFileLoader.java b/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaFileLoader.java new file mode 100644 index 00000000..de4e338b --- /dev/null +++ b/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaFileLoader.java @@ -0,0 +1,280 @@ +package org.codeforphilly.bdt.api; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.arc.Unremovable; + +import javax.enterprise.context.ApplicationScoped; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.logging.Logger; + +/** + * Loads .schema.json files from the classpath and provides flattened schemas + * for use in OpenAPI documentation. + * + *

Schema files are expected to be named {dmn-file-name}.schema.json and located + * alongside their corresponding .dmn files. For example: + *

    + *
  • checks/age/person-min-age.dmn
  • + *
  • checks/age/person-min-age.schema.json
  • + *
+ * + *

These schema files use placeholder keys like {personId} which are transformed + * using {@link SchemaTemplateTransformer#flattenTemplate(JsonNode)} to create + * OpenAPI-compatible schemas with additionalProperties. + */ +@ApplicationScoped +@Unremovable +public class SchemaFileLoader { + private static final Logger LOG = Logger.getLogger(SchemaFileLoader.class.getName()); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + // Cache of path -> flattened schema + private final Map flattenedSchemas = new HashMap<>(); + + // Cache of path -> original schema (for example generation) + private final Map originalSchemas = new HashMap<>(); + + /** + * Load and flatten the schema.json file for a given DMN path. + * + * @param dmnPath the path to the DMN file (without .dmn extension), e.g., "checks/age/person-min-age" + * @return the flattened schema, or null if no schema file exists + */ + public JsonNode loadFlattenedSchema(String dmnPath) { + // Check cache first + if (flattenedSchemas.containsKey(dmnPath)) { + return flattenedSchemas.get(dmnPath); + } + + JsonNode originalSchema = loadOriginalSchema(dmnPath); + if (originalSchema == null) { + return null; + } + + // Flatten the schema using SchemaTemplateTransformer + JsonNode flattened = SchemaTemplateTransformer.flattenTemplate(originalSchema); + flattenedSchemas.put(dmnPath, flattened); + + LOG.fine("Loaded and flattened schema for: " + dmnPath); + return flattened; + } + + /** + * Load the original (non-flattened) schema.json file for a given DMN path. + * + * @param dmnPath the path to the DMN file (without .dmn extension) + * @return the original schema with placeholders, or null if no schema file exists + */ + public JsonNode loadOriginalSchema(String dmnPath) { + // Check cache first + if (originalSchemas.containsKey(dmnPath)) { + return originalSchemas.get(dmnPath); + } + + String schemaPath = dmnPath + ".schema.json"; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + + try (InputStream is = classLoader.getResourceAsStream(schemaPath)) { + if (is == null) { + LOG.fine("No schema.json file found for: " + dmnPath); + originalSchemas.put(dmnPath, null); + return null; + } + + JsonNode schema = MAPPER.readTree(is); + originalSchemas.put(dmnPath, schema); + LOG.fine("Loaded original schema for: " + dmnPath); + return schema; + } catch (IOException e) { + LOG.warning("Failed to load schema.json for " + dmnPath + ": " + e.getMessage()); + originalSchemas.put(dmnPath, null); + return null; + } + } + + /** + * Check if a schema.json file exists for the given DMN path. + * + * @param dmnPath the path to the DMN file (without .dmn extension) + * @return true if a schema file exists + */ + public boolean hasSchemaFile(String dmnPath) { + return loadOriginalSchema(dmnPath) != null; + } + + /** + * Generate an example request body from the flattened schema. + * + *

This walks the schema and generates realistic example values based on: + *

    + *
  • Field types and formats (e.g., date format gets ISO date string)
  • + *
  • Field names (e.g., "personId" gets "person1")
  • + *
  • additionalProperties (generates example keys like "person1")
  • + *
+ * + * @param dmnPath the path to the DMN file + * @return an example object, or empty map if no schema exists + */ + public Map generateExample(String dmnPath) { + JsonNode flattened = loadFlattenedSchema(dmnPath); + if (flattened == null) { + return Collections.emptyMap(); + } + + return generateExampleFromNode(flattened, ""); + } + + private Map generateExampleFromNode(JsonNode schema, String context) { + Map example = new LinkedHashMap<>(); + + if (!schema.has("properties") && !schema.has("additionalProperties")) { + return example; + } + + // Process defined properties + if (schema.has("properties")) { + JsonNode properties = schema.get("properties"); + properties.fields().forEachRemaining(entry -> { + String fieldName = entry.getKey(); + JsonNode fieldSchema = entry.getValue(); + Object value = generateFieldExample(fieldName, fieldSchema, context); + if (value != null) { + example.put(fieldName, value); + } + }); + } + + // Process additionalProperties (from flattened placeholders) + if (schema.has("additionalProperties")) { + JsonNode additionalProps = schema.get("additionalProperties"); + // Generate an example key based on the context + String exampleKey = generateExampleKey(context); + Object value = generateFieldExample(exampleKey, additionalProps, context + "." + exampleKey); + if (value != null) { + example.put(exampleKey, value); + } + } + + return example; + } + + private Object generateFieldExample(String fieldName, JsonNode fieldSchema, String context) { + String type = fieldSchema.has("type") ? fieldSchema.get("type").asText() : "object"; + String format = fieldSchema.has("format") ? fieldSchema.get("format").asText() : null; + + switch (type) { + case "object": + return generateExampleFromNode(fieldSchema, context + "." + fieldName); + + case "array": + if (fieldSchema.has("items")) { + Object itemExample = generateFieldExample(fieldName + "_item", fieldSchema.get("items"), context); + return Collections.singletonList(itemExample); + } + return Collections.emptyList(); + + case "string": + return generateStringExample(fieldName, format); + + case "number": + case "integer": + return generateNumberExample(fieldName); + + case "boolean": + return generateBooleanExample(fieldName); + + default: + return null; + } + } + + private String generateExampleKey(String context) { + // Generate contextual example keys + if (context.contains("people")) { + return "client"; + } + return "example1"; + } + + private String generateStringExample(String fieldName, String format) { + // Handle date format + if ("date".equals(format)) { + return "1960-05-15"; + } + if ("date-time".equals(format)) { + return "1960-05-15T00:00:00Z"; + } + + // Generate contextual examples based on field name + String lowerName = fieldName.toLowerCase(); + + if (lowerName.contains("personid") || lowerName.equals("id")) { + return "client"; + } + if (lowerName.contains("benefit")) { + return "PhlHomesteadExemption"; + } + + return "example-" + fieldName; + } + + private Object generateNumberExample(String fieldName) { + String lowerName = fieldName.toLowerCase(); + + if (lowerName.contains("age")) { + return 65; + } + if (lowerName.contains("min")) { + return 65; + } + if (lowerName.contains("max")) { + return 100; + } + + return 42; + } + + private boolean generateBooleanExample(String fieldName) { + // Fields containing "not" or negative prefixes should default to false + String lowerName = fieldName.toLowerCase(); + if (lowerName.startsWith("not") || lowerName.contains("abatement")) { + return false; + } + return true; + } + + /** + * Convert the flattened schema to OpenAPI Schema format. + * + *

This converts the JSON Schema to OpenAPI-compatible format by: + *

    + *
  • Converting $ref from #/definitions/ to #/components/schemas/
  • + *
  • Preserving type, format, description, properties, additionalProperties
  • + *
  • Handling required arrays
  • + *
+ * + * @param dmnPath the path to the DMN file + * @return the schema as a JsonNode suitable for OpenAPI, or null if no schema exists + */ + public JsonNode getOpenAPISchema(String dmnPath) { + JsonNode flattened = loadFlattenedSchema(dmnPath); + if (flattened == null) { + return null; + } + + // The flattened schema is already in a format close to OpenAPI + // Just need to ensure proper structure + return flattened; + } + + /** + * Clear cached schemas. Useful for testing. + */ + public void clearCache() { + flattenedSchemas.clear(); + originalSchemas.clear(); + } +} diff --git a/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaTemplateTransformer.java b/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaTemplateTransformer.java new file mode 100644 index 00000000..cffe0a84 --- /dev/null +++ b/library-api/src/main/java/org/codeforphilly/bdt/api/SchemaTemplateTransformer.java @@ -0,0 +1,427 @@ +package org.codeforphilly.bdt.api; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Transforms JSON Schema templates that contain placeholder keys. + * + *

Placeholder keys use the syntax {placeholderName} and can be transformed in two ways: + *

    + *
  • Fill mode: Substitutes placeholders with provided values (e.g., {person1} → "client")
  • + *
  • Flatten mode: Merges all placeholder properties into additionalProperties
  • + *
+ * + *

Example templated schema: + *

+ * {
+ *   "type": "object",
+ *   "properties": {
+ *     "{person1}": {
+ *       "type": "object",
+ *       "properties": {
+ *         "dateOfBirth": { "type": "string" }
+ *       }
+ *     },
+ *     "{person2}": {
+ *       "type": "object",
+ *       "properties": {
+ *         "dateOfBirth": { "type": "string" }
+ *       }
+ *     }
+ *   }
+ * }
+ * 
+ * + *

Fill mode with {person1: "client", person2: "spouse"} produces: + *

+ * {
+ *   "type": "object",
+ *   "properties": {
+ *     "client": { ... },
+ *     "spouse": { ... }
+ *   }
+ * }
+ * 
+ * + *

Flatten mode produces: + *

+ * {
+ *   "type": "object",
+ *   "additionalProperties": {
+ *     "type": "object",
+ *     "properties": {
+ *       "dateOfBirth": { "type": "string" }
+ *     }
+ *   }
+ * }
+ * 
+ */ +public class SchemaTemplateTransformer { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + // Pattern to match placeholder keys like {placeholderName} + private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("^\\{([^}]+)\\}$"); + + private SchemaTemplateTransformer() { + // Utility class - prevent instantiation + } + + /** + * Fill template placeholders with provided values. + * + *

Walks through the schema and replaces any property key matching {placeholder} + * with the corresponding value from the values map. Values can be: + *

    + *
  • String: replaces the placeholder with a single property
  • + *
  • List<String>: expands the placeholder into multiple properties, one per list item
  • + *
+ * + *

Example with array expansion: + *

+     * Template: { "properties": { "{peopleIds}": { "type": "object" } } }
+     * Values: { "peopleIds": ["alice", "bob"] }
+     * Result: { "properties": { "alice": { "type": "object" }, "bob": { "type": "object" } } }
+     * 
+ * + * @param templateSchema the schema containing placeholder keys + * @param values map of placeholder names to replacement values (String or List<String>) + * @return a new schema with placeholders replaced by actual values + */ + public static JsonNode fillTemplate(JsonNode templateSchema, Map values) { + if (templateSchema == null) { + return null; + } + return fillTemplateRecursive(templateSchema.deepCopy(), values); + } + + @SuppressWarnings("unchecked") + private static JsonNode fillTemplateRecursive(JsonNode node, Map values) { + if (node.isObject()) { + ObjectNode objectNode = (ObjectNode) node; + + // If this object has "properties", process them for placeholder substitution + if (objectNode.has("properties")) { + JsonNode properties = objectNode.get("properties"); + if (properties.isObject()) { + ObjectNode newProperties = MAPPER.createObjectNode(); + + properties.fields().forEachRemaining(entry -> { + String key = entry.getKey(); + JsonNode value = entry.getValue(); + + // Check if key is a placeholder + Matcher matcher = PLACEHOLDER_PATTERN.matcher(key); + if (matcher.matches()) { + String placeholderName = matcher.group(1); + Object replacement = values.get(placeholderName); + if (replacement != null) { + if (replacement instanceof List) { + // Array expansion: create a property for each list item + List replacements = (List) replacement; + for (String r : replacements) { + newProperties.set(r, fillTemplateRecursive(value.deepCopy(), values)); + } + } else { + // Single value replacement + newProperties.set(replacement.toString(), fillTemplateRecursive(value, values)); + } + } else { + // Keep original placeholder if no value provided + newProperties.set(key, fillTemplateRecursive(value, values)); + } + } else { + // Non-placeholder key - keep as is + newProperties.set(key, fillTemplateRecursive(value, values)); + } + }); + + objectNode.set("properties", newProperties); + } + } + + // Recursively process other object fields + objectNode.fields().forEachRemaining(entry -> { + if (!"properties".equals(entry.getKey())) { + JsonNode processed = fillTemplateRecursive(entry.getValue(), values); + objectNode.set(entry.getKey(), processed); + } + }); + + return objectNode; + } else if (node.isArray()) { + ArrayNode arrayNode = (ArrayNode) node; + ArrayNode newArray = MAPPER.createArrayNode(); + for (JsonNode element : arrayNode) { + newArray.add(fillTemplateRecursive(element, values)); + } + return newArray; + } + + return node; + } + + /** + * Flatten template by merging all placeholder properties into additionalProperties. + * + *

This mode creates a schema that accepts any property name by: + *

    + *
  1. Finding all properties with placeholder keys ({...})
  2. + *
  3. Merging their schemas into a union (combining all properties)
  4. + *
  5. Replacing the placeholder properties with additionalProperties
  6. + *
+ * + *

Non-placeholder properties are preserved as-is. + * + * @param templateSchema the schema containing placeholder keys + * @return a new schema with placeholders converted to additionalProperties + */ + public static JsonNode flattenTemplate(JsonNode templateSchema) { + if (templateSchema == null) { + return null; + } + return flattenTemplateRecursive(templateSchema.deepCopy()); + } + + private static JsonNode flattenTemplateRecursive(JsonNode node) { + if (!node.isObject()) { + if (node.isArray()) { + ArrayNode arrayNode = (ArrayNode) node; + ArrayNode newArray = MAPPER.createArrayNode(); + for (JsonNode element : arrayNode) { + newArray.add(flattenTemplateRecursive(element)); + } + return newArray; + } + return node; + } + + ObjectNode objectNode = (ObjectNode) node; + + if (!objectNode.has("properties")) { + // Recursively process other fields + ObjectNode result = MAPPER.createObjectNode(); + objectNode.fields().forEachRemaining(entry -> { + result.set(entry.getKey(), flattenTemplateRecursive(entry.getValue())); + }); + return result; + } + + JsonNode properties = objectNode.get("properties"); + if (!properties.isObject()) { + return objectNode; + } + + // Separate placeholder and non-placeholder properties + List placeholderSchemas = new ArrayList<>(); + ObjectNode nonPlaceholderProperties = MAPPER.createObjectNode(); + + properties.fields().forEachRemaining(entry -> { + String key = entry.getKey(); + JsonNode value = entry.getValue(); + + Matcher matcher = PLACEHOLDER_PATTERN.matcher(key); + if (matcher.matches()) { + // Collect placeholder schemas for merging + placeholderSchemas.add(flattenTemplateRecursive(value)); + } else { + // Keep non-placeholder properties + nonPlaceholderProperties.set(key, flattenTemplateRecursive(value)); + } + }); + + ObjectNode result = MAPPER.createObjectNode(); + + // Copy all fields except "properties" + objectNode.fields().forEachRemaining(entry -> { + if (!"properties".equals(entry.getKey())) { + result.set(entry.getKey(), flattenTemplateRecursive(entry.getValue())); + } + }); + + // If there are non-placeholder properties, keep them + if (nonPlaceholderProperties.size() > 0) { + result.set("properties", nonPlaceholderProperties); + } + + // If there were placeholder schemas, merge them into additionalProperties + if (!placeholderSchemas.isEmpty()) { + JsonNode mergedSchema = mergeSchemas(placeholderSchemas); + result.set("additionalProperties", mergedSchema); + } + + return result; + } + + /** + * Merge multiple schemas into one by combining their properties. + * + *

This performs a union merge - all properties from all schemas are included. + * If the same property appears in multiple schemas with different definitions, + * the later definition wins. + * + * @param schemas list of schemas to merge + * @return merged schema containing all properties from all input schemas + */ + private static JsonNode mergeSchemas(List schemas) { + if (schemas.isEmpty()) { + return MAPPER.createObjectNode(); + } + + if (schemas.size() == 1) { + return schemas.get(0); + } + + // Start with a copy of the first schema + ObjectNode merged = schemas.get(0).deepCopy().isObject() + ? (ObjectNode) schemas.get(0).deepCopy() + : MAPPER.createObjectNode(); + + // Merge properties from all other schemas + for (int i = 1; i < schemas.size(); i++) { + JsonNode schema = schemas.get(i); + if (!schema.isObject()) { + continue; + } + + // Merge type (should be the same, but handle mismatch) + if (schema.has("type") && !merged.has("type")) { + merged.set("type", schema.get("type")); + } + + // Merge properties + if (schema.has("properties")) { + ObjectNode mergedProps = merged.has("properties") + ? (ObjectNode) merged.get("properties") + : MAPPER.createObjectNode(); + + schema.get("properties").fields().forEachRemaining(entry -> { + mergedProps.set(entry.getKey(), entry.getValue().deepCopy()); + }); + + merged.set("properties", mergedProps); + } + + // Merge required arrays + if (schema.has("required")) { + Set requiredSet = new LinkedHashSet<>(); + if (merged.has("required") && merged.get("required").isArray()) { + for (JsonNode req : merged.get("required")) { + requiredSet.add(req.asText()); + } + } + for (JsonNode req : schema.get("required")) { + requiredSet.add(req.asText()); + } + if (!requiredSet.isEmpty()) { + ArrayNode requiredArray = MAPPER.createArrayNode(); + requiredSet.forEach(requiredArray::add); + merged.set("required", requiredArray); + } + } + } + + return merged; + } + + /** + * Extract all placeholder names from a schema template. + * + * @param templateSchema the schema to scan for placeholders + * @return set of placeholder names (without braces) + */ + public static Set extractPlaceholders(JsonNode templateSchema) { + Set placeholders = new LinkedHashSet<>(); + extractPlaceholdersRecursive(templateSchema, placeholders); + return placeholders; + } + + private static void extractPlaceholdersRecursive(JsonNode node, Set placeholders) { + if (node == null) { + return; + } + + if (node.isObject()) { + ObjectNode objectNode = (ObjectNode) node; + + if (objectNode.has("properties")) { + JsonNode properties = objectNode.get("properties"); + if (properties.isObject()) { + properties.fieldNames().forEachRemaining(key -> { + Matcher matcher = PLACEHOLDER_PATTERN.matcher(key); + if (matcher.matches()) { + placeholders.add(matcher.group(1)); + } + }); + + // Recursively check nested properties + properties.fields().forEachRemaining(entry -> { + extractPlaceholdersRecursive(entry.getValue(), placeholders); + }); + } + } + + // Check other object fields + objectNode.fields().forEachRemaining(entry -> { + if (!"properties".equals(entry.getKey())) { + extractPlaceholdersRecursive(entry.getValue(), placeholders); + } + }); + } else if (node.isArray()) { + for (JsonNode element : node) { + extractPlaceholdersRecursive(element, placeholders); + } + } + } + + /** + * Check if a schema contains any placeholder keys. + * + * @param schema the schema to check + * @return true if the schema contains at least one placeholder + */ + public static boolean hasPlaceholders(JsonNode schema) { + return !extractPlaceholders(schema).isEmpty(); + } + + /** + * Parse a JSON schema template from a string. + * + * @param json the JSON string to parse + * @return parsed JsonNode + * @throws IOException if parsing fails + */ + public static JsonNode parseSchema(String json) throws IOException { + return MAPPER.readTree(json); + } + + /** + * Parse a JSON schema template from an input stream. + * + * @param inputStream the input stream to read from + * @return parsed JsonNode + * @throws IOException if parsing fails + */ + public static JsonNode parseSchema(InputStream inputStream) throws IOException { + return MAPPER.readTree(inputStream); + } + + /** + * Convert a JsonNode to a pretty-printed JSON string. + * + * @param node the node to convert + * @return formatted JSON string + * @throws IOException if conversion fails + */ + public static String toJsonString(JsonNode node) throws IOException { + return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(node); + } +} diff --git a/library-api/src/main/resources/BDT.dmn b/library-api/src/main/resources/BDT.dmn index 99b977aa..e7741ce8 100644 --- a/library-api/src/main/resources/BDT.dmn +++ b/library-api/src/main/resources/BDT.dmn @@ -1,17 +1,16 @@ - - Enrollment.tEnrollmentList + Any string - tPersonList + Any tRelationshipList @@ -106,9 +105,6 @@ Age.as of date(date of birth, comparison date) - - - @@ -240,15 +236,6 @@ - - - - - - - - - @@ -267,10 +254,6 @@ - - - - \ No newline at end of file diff --git a/library-api/src/main/resources/benefits/Benefits.dmn b/library-api/src/main/resources/benefits/Benefits.dmn deleted file mode 100644 index f5d8dbbc..00000000 --- a/library-api/src/main/resources/benefits/Benefits.dmn +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - Any - - - boolean - - - - Add a "calculate benefit" BKM - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.dmn b/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.dmn deleted file mode 100644 index c28524c0..00000000 --- a/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.dmn +++ /dev/null @@ -1,360 +0,0 @@ - - - - - - - - - - - - - string - - - Enrollment.tEnrollmentList - - - tSimpleChecks - - - - - boolean - - - boolean - - - boolean - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PersonNotEnrolledInBenefit.PersonNotEnrolledInBenefitService - - - - - situation - - - - - - - - - situation.primaryPersonId - - - - - - "PhlHomesteadExemption" - - - - - - - - - - - NoTenYearTaxAbatement.NoTenYearTaxAbatementService - - - - - situation - - - - - - - - - OwnerOccupant.OwnerOccupantService - - - - - situation - - - - - - - - - LivesInPhiladelphiaPa.LivesInPhiladelphiaPaService - - - - - situation - - - - - - - - - - - - - - - - - - - - - // e.g. [true, false, true, null, ...] -for check in (get entries(checks)) -return - check.value - - - - - - // true if all checks are true -// null if there are any null checks -// false if any check is false -all(checksAsList) - - - - - result - - - - - - - - - - 50 - 376 - 599 - - - 50 - 239 - 290 - - - - 290 - - - 50 - 120 - 100 - - - 100 - - - 100 - - - 50 - 239 - 290 - - - - 290 - - - 50 - 239 - 290 - - - - 290 - - - 50 - 239 - 290 - - - - 290 - - - 50 - 222 - 504 - - - 504 - - - 504 - - - 504 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.schema.json b/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.schema.json new file mode 100644 index 00000000..89d1ee73 --- /dev/null +++ b/library-api/src/main/resources/benefits/pa/phl/homestead-exemption.schema.json @@ -0,0 +1,69 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema for Philadelphia Homestead Exemption benefit eligibility check.", + "properties": { + "situation": { + "type": "object", + "description": "The household situation to evaluate", + "properties": { + "people": { + "type": "object", + "description": "Household members keyed by person ID", + "properties": { + "{personId}": { + "type": "object", + "description": "A person in the household", + "properties": { + "dateOfBirth": { + "type": "string", + "format": "date", + "description": "The person's date of birth in ISO 8601 format (YYYY-MM-DD)" + }, + "enrollments": { + "type": "array", + "description": "Benefits this person is enrolled in", + "items": { + "type": "string" + } + } + } + } + } + }, + "simpleChecks": { + "type": "object", + "description": "Pre-computed boolean checks", + "properties": { + "ownerOccupant": { + "type": "boolean", + "description": "Whether the person owns and occupies their primary residence" + }, + "livesInPhiladelphiaPa": { + "type": "boolean", + "description": "Whether the person lives in Philadelphia, PA" + }, + "tenYearTaxAbatement": { + "type": "boolean", + "description": "Whether the property has a 10-year tax abatement" + } + }, + "required": ["ownerOccupant", "livesInPhiladelphiaPa", "tenYearTaxAbatement"] + } + }, + "required": ["people", "simpleChecks"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the primary person to evaluate for eligibility" + } + }, + "required": ["personId"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.dmn b/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.dmn deleted file mode 100644 index 951dc12b..00000000 --- a/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.dmn +++ /dev/null @@ -1,506 +0,0 @@ - - - - - - - - - - - Enrollment.tEnrollmentList - - - tSimpleChecks - - - string - - - tPeople - - - BDT.tRelationshipList - - - - - string - - - date - - - - tPerson - - - - boolean - - - boolean - - - boolean - - - - - - - - - - - - - - - - - - - - - - - - - - - PersonNotEnrolledInBenefit.PersonNotEnrolledInBenefitService - - - - - situation - - - - - - - - - situation.primaryPersonId - - - - - - "PhlSeniorCitizenTaxFreeze" - - - - - - - - - - situation.simpleChecks.ownerOccupant - - - - - - situation.simpleChecks.livesInPhiladelphiaPa - - - - - - SctfAgeRequirement(situation) - - - - - - - - - - - - - - - // e.g. [true, false, true, null, ...] -for check in (get entries(checks)) -return - check.value - - - - - - // true if all checks are true -// null if there are any null checks -// false if any check is false -all(checksAsList) - - - - - result - - - - - - - - - - - - - - - - - - PersonMinAge.PersonMinAgeService( - situation: situation, - parameters: { - personId: situation.primaryPersonId, - minAge: 65, - asOfDate: date(today().year, 12, 31) - } -) - - - - - - - - PersonMinAge.PersonMinAgeService - - - - - situation - - - - - - - - - situation.primaryPersonId - - - - - - 50 - - - - - - date(today().year, 12, 31) - - - - - - - - - - - PersonMinAge.PersonMinAgeService - - - - - situation - - - - - - - - - BDT.spouse id(situation.relationships, situation.primaryPersonId) - - - - - - 65 - - - - - - date(today().year, 12, 31) - - - - - - - - - - situation.simpleChecks.lateSpouseWasAtLeast65 - - - - - - PrimaryPerson65PlusThisYear or PrimarySpouse65PlusThisYear or (PrimaryPerson50PlusThisYear and LateSpouseWasAtLeast65) - - - - - result - - - - - - - - - - - - - - - - - 50 - 327 - 480 - - - 50 - 120 - 290 - - - - 290 - - - 50 - 120 - 100 - - - 100 - - - 100 - - - 480 - - - 480 - - - 480 - - - 50 - 120 - 500 - - - 500 - - - 500 - - - 500 - - - 50 - 282 - 560 - - - 560 - - - 50 - 172 - 318 - - - - 318 - - - 50 - 120 - 128 - - - 128 - - - 128 - - - 128 - - - 50 - 200 - 290 - - - - 290 - - - 50 - 120 - 100 - - - 100 - - - 100 - - - 100 - - - 560 - - - 560 - - - 560 - - - 50 - 912 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.schema.json b/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.schema.json new file mode 100644 index 00000000..8595c878 --- /dev/null +++ b/library-api/src/main/resources/benefits/pa/phl/senior-citizen-tax-freeze.schema.json @@ -0,0 +1,90 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema for Philadelphia Senior Citizen Tax Freeze benefit eligibility check.", + "properties": { + "situation": { + "type": "object", + "description": "The household situation to evaluate", + "properties": { + "people": { + "type": "object", + "description": "Household members keyed by person ID", + "properties": { + "{personId}": { + "type": "object", + "description": "A person in the household", + "properties": { + "dateOfBirth": { + "type": "string", + "format": "date", + "description": "The person's date of birth in ISO 8601 format (YYYY-MM-DD)" + }, + "enrollments": { + "type": "array", + "description": "Benefits this person is enrolled in", + "items": { + "type": "string" + } + } + } + } + } + }, + "simpleChecks": { + "type": "object", + "description": "Pre-computed boolean checks", + "properties": { + "ownerOccupant": { + "type": "boolean", + "description": "Whether the person owns and occupies their primary residence" + }, + "livesInPhiladelphiaPa": { + "type": "boolean", + "description": "Whether the person lives in Philadelphia, PA" + }, + "lateSpouseWasAtLeast65": { + "type": "boolean", + "description": "Whether the late spouse was at least 65 years old (for surviving spouse eligibility)" + } + }, + "required": ["ownerOccupant", "livesInPhiladelphiaPa"] + }, + "relationships": { + "type": "array", + "description": "Relationships between household members", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The type of relationship (e.g., 'spouse')" + }, + "personId": { + "type": "string", + "description": "The person in the relationship" + }, + "relatedPersonId": { + "type": "string", + "description": "The related person" + } + } + } + } + }, + "required": ["people", "simpleChecks"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the primary person to evaluate for eligibility" + } + }, + "required": ["personId"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/age/person-max-age.dmn b/library-api/src/main/resources/checks/age/person-max-age.dmn index 9b53d866..216bf6cb 100644 --- a/library-api/src/main/resources/checks/age/person-max-age.dmn +++ b/library-api/src/main/resources/checks/age/person-max-age.dmn @@ -14,20 +14,9 @@ number - - - string - - - date - - - - tPerson - - tPersonList + Any @@ -49,11 +38,14 @@ - + - situation.people[id = parameters.personId].dateOfBirth[1] + if parameters.personId != null then + get value(situation.people, parameters.personId).dateOfBirth +else + null @@ -155,7 +147,7 @@ else - + @@ -167,7 +159,7 @@ else - + diff --git a/library-api/src/main/resources/checks/age/person-max-age.schema.json b/library-api/src/main/resources/checks/age/person-max-age.schema.json new file mode 100644 index 00000000..3c74daec --- /dev/null +++ b/library-api/src/main/resources/checks/age/person-max-age.schema.json @@ -0,0 +1,51 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for person-max-age check. Verifies a person's age is at or below a maximum threshold.", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "description": "A person whose age will be checked", + "properties": { + "dateOfBirth": { + "type": "string", + "format": "date", + "description": "The person's date of birth in ISO 8601 format (YYYY-MM-DD)" + } + }, + "required": ["dateOfBirth"] + } + } + } + }, + "required": ["people"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the person to check (must match a key in situation.people)" + }, + "maxAge": { + "type": "number", + "description": "The maximum age allowed (in years, inclusive)" + }, + "asOfDate": { + "type": "string", + "format": "date", + "description": "The date to calculate age as of (defaults to today if not provided)" + } + }, + "required": ["personId", "maxAge"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/age/person-min-age.dmn b/library-api/src/main/resources/checks/age/person-min-age.dmn index 1b2de111..305ebf28 100644 --- a/library-api/src/main/resources/checks/age/person-min-age.dmn +++ b/library-api/src/main/resources/checks/age/person-min-age.dmn @@ -2,7 +2,7 @@ Ensure a specified person's age meets a minimum number as of a specified date. - + @@ -17,20 +17,9 @@ - tPersonList + Any - - - string - - - date - - - - tPerson - @@ -50,11 +39,14 @@ - + - situation.people[id = parameters.personId].dateOfBirth[1] + if parameters.personId != null then + get value(situation.people, parameters.personId).dateOfBirth +else + null @@ -93,20 +85,20 @@ else 50 - 120 - 453 + 211 + 555 - 453 + 555 - 453 + 555 - 453 + 555 - 453 + 555 @@ -156,7 +148,7 @@ else - + @@ -168,7 +160,7 @@ else - + diff --git a/library-api/src/main/resources/checks/age/person-min-age.schema.json b/library-api/src/main/resources/checks/age/person-min-age.schema.json new file mode 100644 index 00000000..ec7da25c --- /dev/null +++ b/library-api/src/main/resources/checks/age/person-min-age.schema.json @@ -0,0 +1,51 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for person-min-age check. Verifies a person's age meets a minimum threshold.", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "description": "A person whose age will be checked", + "properties": { + "dateOfBirth": { + "type": "string", + "format": "date", + "description": "The person's date of birth in ISO 8601 format (YYYY-MM-DD)" + } + }, + "required": ["dateOfBirth"] + } + } + } + }, + "required": ["people"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the person to check (must match a key in situation.people)" + }, + "minAge": { + "type": "number", + "description": "The minimum age required (in years)" + }, + "asOfDate": { + "type": "string", + "format": "date", + "description": "The date to calculate age as of (defaults to today if not provided)" + } + }, + "required": ["personId", "minAge"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/age/someone-min-age.dmn b/library-api/src/main/resources/checks/age/someone-min-age.dmn deleted file mode 100644 index 0a7b4268..00000000 --- a/library-api/src/main/resources/checks/age/someone-min-age.dmn +++ /dev/null @@ -1,185 +0,0 @@ - - - Ensure at least one person from a specified list meets a minimum age requirement as of a specified date. - - - - - - BDT.tStringList - - - date - - - number - - - - - tPersonList - - - - - string - - - date - - - - tPerson - - - - - - - - - - - - - - - - - - - - - - - - - situation.people[id in parameters.peopleIds].dateOfBirth - - - - - - for dob in DOBs return Age.as of date(dob, parameters.asOfDate) - - - - - - if DOBs = null or count(DOBs) = 0 then null else count(ages[item >= parameters.minAge]) > 0 - - - - - result - - - - - - - - - - - - - - peopleIds, asOfDate, minimumAge - - - - - - - 50 - 120 - 630 - - - 630 - - - 630 - - - 630 - - - 630 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/library-api/src/main/resources/checks/age/someone-min-age.schema.json b/library-api/src/main/resources/checks/age/someone-min-age.schema.json new file mode 100644 index 00000000..11c1ac4a --- /dev/null +++ b/library-api/src/main/resources/checks/age/someone-min-age.schema.json @@ -0,0 +1,54 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for someone-min-age check. Verifies at least one person from a list meets a minimum age requirement.", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{peopleIds}": { + "type": "object", + "description": "A person who may be checked for the minimum age requirement. Each entry in the peopleIds array creates a key here.", + "properties": { + "dateOfBirth": { + "type": "string", + "format": "date", + "description": "The person's date of birth in ISO 8601 format (YYYY-MM-DD)" + } + }, + "required": ["dateOfBirth"] + } + } + } + }, + "required": ["people"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "peopleIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "List of person IDs to check (at least one must meet the age requirement). Each ID corresponds to a key under situation.people." + }, + "minAge": { + "type": "number", + "description": "The minimum age required (in years)" + }, + "asOfDate": { + "type": "string", + "format": "date", + "description": "The date to calculate age as of (defaults to today if not provided)" + } + }, + "required": ["peopleIds", "minAge"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/enrollment/Enrollment.dmn b/library-api/src/main/resources/checks/enrollment/Enrollment.dmn index 6ab01020..d2bb2b5e 100644 --- a/library-api/src/main/resources/checks/enrollment/Enrollment.dmn +++ b/library-api/src/main/resources/checks/enrollment/Enrollment.dmn @@ -1,16 +1,8 @@ - - - string - - - string - - - tEnrollment + string diff --git a/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.dmn b/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.dmn index c0b2d5b6..d246019c 100644 --- a/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.dmn +++ b/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.dmn @@ -1,8 +1,7 @@ - + Verify that a specified person is enrolled in a specified benefit program. - @@ -13,33 +12,17 @@ - - Enrollment.tEnrollmentList + + Any - + - - - - - - - - - - - if situation.enrollments != null and count(situation.enrollments) > 0 and parameters.personId != null and parameters.benefit != null then - some enrollment in situation.enrollments satisfies enrollment.personId = parameters.personId and enrollment.benefit = parameters.benefit -else - null - - @@ -48,12 +31,49 @@ else + + + + + + + + + + + + + + if parameters.personId != null then + get value(situation.people, parameters.personId).enrollments +else + null + + + + + if enrollments != null and count(enrollments) != 0 then + some benefit in enrollments satisfies benefit = parameters.benefit +else + null + + + + - - 917 + + 50 + 267 + 698 + + + 698 + + + 698 @@ -70,40 +90,40 @@ else - + - + - + - + - + - + - - - - - + - + + + + + diff --git a/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.schema.json b/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.schema.json new file mode 100644 index 00000000..287f0d80 --- /dev/null +++ b/library-api/src/main/resources/checks/enrollment/person-enrolled-in-benefit.schema.json @@ -0,0 +1,47 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for person-enrolled-in-benefit check. Verifies a person is currently enrolled in a specified benefit program.", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "description": "A person whose benefit enrollment will be checked", + "properties": { + "enrollments": { + "type": "array", + "description": "List of benefit programs this person is enrolled in", + "items": { + "type": "string" + } + } + } + } + } + } + }, + "required": ["people"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the person to check enrollment for" + }, + "benefit": { + "type": "string", + "description": "The benefit program ID to check enrollment for" + } + }, + "required": ["personId", "benefit"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.dmn b/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.dmn index c5508471..b54f09fc 100644 --- a/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.dmn +++ b/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.dmn @@ -1,10 +1,9 @@ - + Verify that a specified person is not currently enrolled in a specified benefit program. - string @@ -14,8 +13,8 @@ - - Enrollment.tEnrollmentList + + Any @@ -54,7 +53,7 @@ - 553 + 510 diff --git a/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.schema.json b/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.schema.json new file mode 100644 index 00000000..643af698 --- /dev/null +++ b/library-api/src/main/resources/checks/enrollment/person-not-enrolled-in-benefit.schema.json @@ -0,0 +1,47 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for person-not-enrolled-in-benefit check. Verifies a person is NOT currently enrolled in a specified benefit program.", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{personId}": { + "type": "object", + "description": "A person whose benefit enrollment will be checked", + "properties": { + "enrollments": { + "type": "array", + "description": "List of benefit programs this person is enrolled in", + "items": { + "type": "string" + } + } + } + } + } + } + }, + "required": ["people"] + }, + "parameters": { + "type": "object", + "description": "Check parameters", + "properties": { + "personId": { + "type": "string", + "description": "ID of the person to check enrollment for" + }, + "benefit": { + "type": "string", + "description": "The benefit program ID to verify non-enrollment" + } + }, + "required": ["personId", "benefit"] + } + }, + "required": ["situation", "parameters"] +} diff --git a/library-api/src/main/resources/checks/residence/lives-in-philadelphia-pa.schema.json b/library-api/src/main/resources/checks/residence/lives-in-philadelphia-pa.schema.json new file mode 100644 index 00000000..bde10a23 --- /dev/null +++ b/library-api/src/main/resources/checks/residence/lives-in-philadelphia-pa.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for lives-in-philadelphia-pa check. Verifies a person lives in Philadelphia, PA.", + "properties": { + "situation": { + "type": "object", + "properties": { + "simpleChecks": { + "type": "object", + "description": "Pre-computed simple boolean checks", + "properties": { + "livesInPhiladelphiaPa": { + "type": "boolean", + "description": "Whether the person lives in Philadelphia, PA" + } + }, + "required": ["livesInPhiladelphiaPa"] + } + }, + "required": ["simpleChecks"] + } + }, + "required": ["situation"] +} diff --git a/library-api/src/main/resources/checks/residence/no-ten-year-tax-abatement.schema.json b/library-api/src/main/resources/checks/residence/no-ten-year-tax-abatement.schema.json new file mode 100644 index 00000000..490a29a4 --- /dev/null +++ b/library-api/src/main/resources/checks/residence/no-ten-year-tax-abatement.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for no-ten-year-tax-abatement check. Verifies a property does NOT have an active 10-year tax abatement.", + "properties": { + "situation": { + "type": "object", + "properties": { + "simpleChecks": { + "type": "object", + "description": "Pre-computed simple boolean checks", + "properties": { + "tenYearTaxAbatement": { + "type": "boolean", + "description": "Whether the property has an active 10-year tax abatement (check passes if false)" + } + }, + "required": ["tenYearTaxAbatement"] + } + }, + "required": ["simpleChecks"] + } + }, + "required": ["situation"] +} diff --git a/library-api/src/main/resources/checks/residence/owner-occupant.schema.json b/library-api/src/main/resources/checks/residence/owner-occupant.schema.json new file mode 100644 index 00000000..26e96622 --- /dev/null +++ b/library-api/src/main/resources/checks/residence/owner-occupant.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for owner-occupant check. Verifies a person owns and occupies their primary residence.", + "properties": { + "situation": { + "type": "object", + "properties": { + "simpleChecks": { + "type": "object", + "description": "Pre-computed simple boolean checks", + "properties": { + "ownerOccupant": { + "type": "boolean", + "description": "Whether the person owns and occupies their primary residence" + } + }, + "required": ["ownerOccupant"] + } + }, + "required": ["simpleChecks"] + } + }, + "required": ["situation"] +} diff --git a/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.dmn b/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.dmn index 05fbdd92..7f60a9f1 100644 --- a/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.dmn +++ b/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.dmn @@ -1,28 +1,9 @@ - + Checks that a property has an active 10-year tax abatement. - - + + boolean @@ -65,7 +46,6 @@ else - @@ -79,7 +59,6 @@ else - @@ -89,7 +68,6 @@ else - @@ -99,11 +77,10 @@ else - - + \ No newline at end of file diff --git a/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.schema.json b/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.schema.json new file mode 100644 index 00000000..c4a1138a --- /dev/null +++ b/library-api/src/main/resources/checks/residence/ten-year-tax-abatement.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "description": "Input schema template for ten-year-tax-abatement check. Verifies a property has an active 10-year tax abatement.", + "properties": { + "situation": { + "type": "object", + "properties": { + "simpleChecks": { + "type": "object", + "description": "Pre-computed simple boolean checks", + "properties": { + "tenYearTaxAbatement": { + "type": "boolean", + "description": "Whether the property has an active 10-year tax abatement" + } + }, + "required": ["tenYearTaxAbatement"] + } + }, + "required": ["simpleChecks"] + } + }, + "required": ["situation"] +} diff --git a/library-api/src/test/java/org/codeforphilly/bdt/api/DynamicEndpointPatternTest.java b/library-api/src/test/java/org/codeforphilly/bdt/api/DynamicEndpointPatternTest.java deleted file mode 100644 index 22e26d8d..00000000 --- a/library-api/src/test/java/org/codeforphilly/bdt/api/DynamicEndpointPatternTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.codeforphilly.bdt.api; - -import io.quarkus.test.junit.QuarkusTest; -import io.restassured.common.mapper.TypeRef; -import io.restassured.http.ContentType; -import io.restassured.path.json.JsonPath; -import io.restassured.response.Response; -import org.junit.jupiter.api.Test; - -import javax.inject.Inject; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.jupiter.api.Assertions.*; - -@QuarkusTest -public class DynamicEndpointPatternTest { - - @Inject - ModelRegistry modelRegistry; - - @Inject - DMNSchemaResolver schemaResolver; - - @Test - public void testAllCheckEndpointsReturnCheckResult() { - Map allModels = modelRegistry.getAllModels(); - - List checkModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(checkModels.size() > 0, "Should have at least one check model"); - - for (ModelInfo model : checkModels) { - String serviceName = model.getModelName() + "Service"; - String inputRef = schemaResolver.findInputSchemaRef(model.getModelName(), serviceName); - assertNotNull(inputRef, "Should find input schema for " + serviceName); - - // Generate example request - Map exampleRequest = schemaResolver.generateExample(inputRef); - - String path = "/api/v1/" + model.getPath(); - - given() - .contentType(ContentType.JSON) - .body(exampleRequest) - .when() - .post(path) - .then() - .statusCode(200) - .body("checkResult", notNullValue()) - .body("situation", notNullValue()); - // 'parameters' is only echoed back for checks that declare a parameters input - } - } - - @Test - public void testAllCheckEndpointsReturnNullWithEmptyInputs() { - Map allModels = modelRegistry.getAllModels(); - - List checkModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(checkModels.size() > 0, "Should have at least one check model"); - - for (ModelInfo model : checkModels) { - String path = "/api/v1/" + model.getPath(); - - String checkResult = given() - .contentType(ContentType.JSON) - .body(Map.of("situation", Map.of())) - .when() - .post(path) - .then() - .statusCode(200) - .extract() - .jsonPath() - .getString("checkResult"); - - assertNull(checkResult, path + " should return null checkResult with empty situation"); - } - } - - @Test - public void testAllBenefitEndpointsReturnExpectedStructure() { - Map allModels = modelRegistry.getAllModels(); - - List benefitModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("benefits/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(benefitModels.size() > 0, "Should have at least one benefit model"); - - for (ModelInfo model : benefitModels) { - String serviceName = model.getModelName() + "Service"; - String inputRef = schemaResolver.findInputSchemaRef(model.getModelName(), serviceName); - - if (inputRef != null) { - Map exampleRequest = schemaResolver.generateExample(inputRef); - String path = "/api/v1/" + model.getPath(); - - given() - .contentType(ContentType.JSON) - .body(exampleRequest) - .when() - .post(path) - .then() - .statusCode(200) - .body("checks", notNullValue()) - .body("isEligible", notNullValue()) - .body("situation", notNullValue()); - } - } - } - - @Test - public void testActualResponsesMatchOpenAPIExamples() { - // For each endpoint, verify actual response structure matches OpenAPI example structure - Map allModels = modelRegistry.getAllModels(); - - List exposedModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/") || model.getPath().startsWith("benefits/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - JsonPath openApiSpec = given() - .queryParam("format", "JSON") - .when() - .get("/q/openapi") - .then() - .extract() - .jsonPath(); - - for (ModelInfo model : exposedModels) { - String serviceName = model.getModelName() + "Service"; - String inputRef = schemaResolver.findInputSchemaRef(model.getModelName(), serviceName); - - if (inputRef != null) { - Map exampleRequest = schemaResolver.generateExample(inputRef); - String path = "/api/v1/" + model.getPath(); - - // Get actual response - Response response = given() - .contentType(ContentType.JSON) - .body(exampleRequest) - .when() - .post(path) - .then() - .extract() - .response(); - - assertEquals(200, response.statusCode(), path + " should return 200"); - - Map actualResponse = response.as(new TypeRef>() {}); - - // Get OpenAPI example - String examplePath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.examples.'Example response'.value"; - Map openApiExample = openApiSpec.getMap(examplePath); - - if (openApiExample != null) { - // Verify same keys - assertEquals(openApiExample.keySet(), actualResponse.keySet(), - path + ": actual response keys should match OpenAPI example keys"); - } - } - } - } -} diff --git a/library-api/src/test/java/org/codeforphilly/bdt/api/ModelDiscoveryTest.java b/library-api/src/test/java/org/codeforphilly/bdt/api/ModelDiscoveryTest.java deleted file mode 100644 index f8c61773..00000000 --- a/library-api/src/test/java/org/codeforphilly/bdt/api/ModelDiscoveryTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.codeforphilly.bdt.api; - -import io.quarkus.test.junit.QuarkusTest; -import org.junit.jupiter.api.Test; - -import javax.inject.Inject; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.hasKey; -import static org.junit.jupiter.api.Assertions.*; - -@QuarkusTest -public class ModelDiscoveryTest { - - @Inject - ModelRegistry modelRegistry; - - @Test - public void testAllDMNModelsAreDiscovered() { - Map models = modelRegistry.getAllModels(); - assertNotNull(models); - assertTrue(models.size() > 0, "Should discover at least one DMN model"); - - // Log discovered models for debugging - models.values().forEach(model -> { - System.out.println("Discovered: " + model.getModelName() + - " at " + model.getPath() + - " with services: " + model.getDecisionServices()); - }); - } - - @Test - public void testAllModelsFollowNamingConvention() { - Map allModels = modelRegistry.getAllModels(); - - for (ModelInfo model : allModels.values()) { - // Models that are exposed via API should have {ModelName}Service - String expectedService = model.getModelName() + "Service"; - - if (model.getDecisionServices().contains(expectedService)) { - // This model should appear in OpenAPI - String path = "/api/v1/" + model.getPath(); - - given() - .queryParam("format", "JSON") - .when() - .get("/q/openapi") - .then() - .statusCode(200) - .body("paths", hasKey(path)); - } - } - } - - @Test - public void testCheckModelsHaveCorrectCategory() { - Map allModels = modelRegistry.getAllModels(); - - List checkModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/")) - .collect(Collectors.toList()); - - for (ModelInfo model : checkModels) { - String category = model.getCategory(); - assertTrue(category.endsWith("Checks"), - "Check model " + model.getModelName() + - " should have category ending with 'Checks', got: " + category); - } - } - - @Test - public void testBenefitModelsHaveCorrectCategory() { - Map allModels = modelRegistry.getAllModels(); - - List benefitModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("benefits/")) - .collect(Collectors.toList()); - - for (ModelInfo model : benefitModels) { - String category = model.getCategory(); - assertEquals("Benefits", category, - "Benefit model " + model.getModelName() + " should have 'Benefits' category"); - } - } -} diff --git a/library-api/src/test/java/org/codeforphilly/bdt/api/OpenAPISchemaPatternTest.java b/library-api/src/test/java/org/codeforphilly/bdt/api/OpenAPISchemaPatternTest.java deleted file mode 100644 index beb33ab0..00000000 --- a/library-api/src/test/java/org/codeforphilly/bdt/api/OpenAPISchemaPatternTest.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.codeforphilly.bdt.api; - -import io.quarkus.test.junit.QuarkusTest; -import io.restassured.path.json.JsonPath; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import javax.inject.Inject; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.*; - -@QuarkusTest -public class OpenAPISchemaPatternTest { - - @Inject - ModelRegistry modelRegistry; - - private JsonPath openApiSpec; - - @BeforeEach - public void loadOpenAPISpec() { - openApiSpec = given() - .queryParam("format", "JSON") - .when() - .get("/q/openapi") - .then() - .statusCode(200) - .extract() - .jsonPath(); - } - - @Test - public void testAllCheckEndpointsHaveCheckResultInSchema() { - // Discover all check models dynamically - Map allModels = modelRegistry.getAllModels(); - - List checkModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(checkModels.size() > 0, "Should have at least one check model"); - - for (ModelInfo model : checkModels) { - String path = "/api/v1/" + model.getPath(); - String schemaPath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.schema.properties"; - - // Verify response schema has required fields - Map properties = openApiSpec.getMap(schemaPath); - assertNotNull(properties, "Schema properties should exist for " + path); - assertTrue(properties.containsKey("checkResult"), - path + " should have 'checkResult' in response schema, not 'result'"); - assertTrue(properties.containsKey("situation"), - path + " should have 'situation' in response schema"); - // 'parameters' is only present for checks that declare a parameters input in their DMN model - } - } - - @Test - public void testAllBenefitEndpointsHaveExpectedFields() { - Map allModels = modelRegistry.getAllModels(); - - List benefitModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("benefits/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(benefitModels.size() > 0, "Should have at least one benefit model"); - - for (ModelInfo model : benefitModels) { - String path = "/api/v1/" + model.getPath(); - String schemaPath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.schema.properties"; - - Map properties = openApiSpec.getMap(schemaPath); - assertNotNull(properties, "Schema properties should exist for " + path); - - // Benefits should have checks and isEligible - assertTrue(properties.containsKey("checks"), - path + " should have 'checks' in response schema"); - assertTrue(properties.containsKey("isEligible"), - path + " should have 'isEligible' in response schema"); - - // Benefits should also echo back input - assertTrue(properties.containsKey("situation"), - path + " should have 'situation' in response schema"); - } - } - - @Test - public void testAllCheckEndpointsHaveCheckResultInExamples() { - Map allModels = modelRegistry.getAllModels(); - - List checkModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - for (ModelInfo model : checkModels) { - String path = "/api/v1/" + model.getPath(); - String examplePath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.examples.'Example response'.value"; - - Map exampleValue = openApiSpec.getMap(examplePath); - assertNotNull(exampleValue, "Example should exist for " + path); - assertTrue(exampleValue.containsKey("checkResult"), - path + " example should have 'checkResult', not 'result'"); - assertTrue(exampleValue.containsKey("situation"), - path + " example should have 'situation'"); - // 'parameters' is only present for checks that declare a parameters input in their DMN model - } - } - - @Test - public void testExampleKeysMatchSchemaKeys() { - // For ALL endpoints, verify example keys match schema properties - Map allModels = modelRegistry.getAllModels(); - - List exposedModels = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/") || model.getPath().startsWith("benefits/")) - .filter(model -> model.getDecisionServices().contains(model.getModelName() + "Service")) - .collect(Collectors.toList()); - - assertTrue(exposedModels.size() > 0, "Should have at least one exposed model"); - - for (ModelInfo model : exposedModels) { - String path = "/api/v1/" + model.getPath(); - String schemaPath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.schema.properties"; - String examplePath = "paths.'" + path + "'.post.responses.'200'.content.'application/json'.examples.'Example response'.value"; - - Map schemaProperties = openApiSpec.getMap(schemaPath); - Map exampleValue = openApiSpec.getMap(examplePath); - - if (schemaProperties != null && exampleValue != null) { - // Every key in schema should exist in example - for (String schemaKey : schemaProperties.keySet()) { - assertTrue(exampleValue.containsKey(schemaKey), - path + ": example missing schema key '" + schemaKey + "'"); - } - - // Every key in example should exist in schema - for (String exampleKey : exampleValue.keySet()) { - assertTrue(schemaProperties.containsKey(exampleKey), - path + ": schema missing example key '" + exampleKey + "'"); - } - } - } - } -} diff --git a/library-api/src/test/java/org/codeforphilly/bdt/api/SchemaTemplateTransformerTest.java b/library-api/src/test/java/org/codeforphilly/bdt/api/SchemaTemplateTransformerTest.java new file mode 100644 index 00000000..1b8ad6bf --- /dev/null +++ b/library-api/src/test/java/org/codeforphilly/bdt/api/SchemaTemplateTransformerTest.java @@ -0,0 +1,529 @@ +package org.codeforphilly.bdt.api; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests for SchemaTemplateTransformer utility class. + */ +public class SchemaTemplateTransformerTest { + + @Test + public void testFillTemplateSinglePlaceholder() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, Map.of("person", "client")); + + assertTrue(filled.has("properties")); + assertTrue(filled.get("properties").has("client")); + assertFalse(filled.get("properties").has("{person}")); + + JsonNode clientNode = filled.get("properties").get("client"); + assertTrue(clientNode.has("properties")); + assertTrue(clientNode.get("properties").has("dateOfBirth")); + } + + @Test + public void testFillTemplateMultiplePlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person1}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" }, + "enrollments": { "type": "array", "items": { "type": "string" } } + } + }, + "{person2}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, + Map.of("person1", "applicant", "person2", "spouse")); + + JsonNode properties = filled.get("properties"); + assertTrue(properties.has("applicant")); + assertTrue(properties.has("spouse")); + assertFalse(properties.has("{person1}")); + assertFalse(properties.has("{person2}")); + + // Verify applicant has both dateOfBirth and enrollments + assertTrue(properties.get("applicant").get("properties").has("dateOfBirth")); + assertTrue(properties.get("applicant").get("properties").has("enrollments")); + + // Verify spouse has only dateOfBirth + assertTrue(properties.get("spouse").get("properties").has("dateOfBirth")); + assertFalse(properties.get("spouse").get("properties").has("enrollments")); + } + + @Test + public void testFillTemplatePreservesNonPlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "name": { "type": "string" } + } + }, + "parameters": { + "type": "object", + "properties": { + "minAge": { "type": "number" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, Map.of("person", "client")); + + JsonNode properties = filled.get("properties"); + assertTrue(properties.has("client")); + assertTrue(properties.has("parameters")); + assertTrue(properties.get("parameters").get("properties").has("minAge")); + } + + @Test + public void testFillTemplateWithMissingValue() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "name": { "type": "string" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + // Pass empty map - placeholder should remain unchanged + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, Map.of()); + + assertTrue(filled.get("properties").has("{person}")); + } + + @Test + public void testFlattenTemplateSinglePlaceholder() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" }, + "enrollments": { "type": "array", "items": { "type": "string" } } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode flattened = SchemaTemplateTransformer.flattenTemplate(templateNode); + + // Should not have properties with placeholders + assertFalse(flattened.has("properties")); + + // Should have additionalProperties + assertTrue(flattened.has("additionalProperties")); + JsonNode additionalProps = flattened.get("additionalProperties"); + assertEquals("object", additionalProps.get("type").asText()); + assertTrue(additionalProps.get("properties").has("dateOfBirth")); + assertTrue(additionalProps.get("properties").has("enrollments")); + } + + @Test + public void testFlattenTemplateMultiplePlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person1}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" }, + "enrollments": { "type": "array", "items": { "type": "string" } } + } + }, + "{person2}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode flattened = SchemaTemplateTransformer.flattenTemplate(templateNode); + + assertTrue(flattened.has("additionalProperties")); + JsonNode additionalProps = flattened.get("additionalProperties"); + + // Should have merged properties from both placeholders + assertTrue(additionalProps.get("properties").has("dateOfBirth")); + assertTrue(additionalProps.get("properties").has("enrollments")); + } + + @Test + public void testFlattenTemplatePreservesNonPlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "name": { "type": "string" } + } + }, + "parameters": { + "type": "object", + "properties": { + "minAge": { "type": "number" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode flattened = SchemaTemplateTransformer.flattenTemplate(templateNode); + + // Non-placeholder properties should be preserved + assertTrue(flattened.has("properties")); + assertTrue(flattened.get("properties").has("parameters")); + + // Placeholder should be converted to additionalProperties + assertTrue(flattened.has("additionalProperties")); + } + + @Test + public void testExtractPlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person1}": { + "type": "object", + "properties": { + "nested": { + "type": "object", + "properties": { + "{nestedPlaceholder}": { "type": "string" } + } + } + } + }, + "{person2}": { "type": "object" }, + "regularProp": { "type": "string" } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + Set placeholders = SchemaTemplateTransformer.extractPlaceholders(templateNode); + + assertTrue(placeholders.contains("person1")); + assertTrue(placeholders.contains("person2")); + assertTrue(placeholders.contains("nestedPlaceholder")); + assertEquals(3, placeholders.size()); + } + + @Test + public void testHasPlaceholders() throws IOException { + String withPlaceholders = """ + { + "type": "object", + "properties": { + "{person}": { "type": "object" } + } + } + """; + + String withoutPlaceholders = """ + { + "type": "object", + "properties": { + "person": { "type": "object" } + } + } + """; + + assertTrue(SchemaTemplateTransformer.hasPlaceholders( + SchemaTemplateTransformer.parseSchema(withPlaceholders))); + assertFalse(SchemaTemplateTransformer.hasPlaceholders( + SchemaTemplateTransformer.parseSchema(withoutPlaceholders))); + } + + @Test + public void testNestedFillTemplate() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "household": { + "type": "object", + "properties": { + "{member}": { + "type": "object", + "properties": { + "age": { "type": "number" } + } + } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, Map.of("member", "parent")); + + JsonNode householdProps = filled.get("properties").get("household").get("properties"); + assertTrue(householdProps.has("parent")); + assertFalse(householdProps.has("{member}")); + } + + @Test + public void testFlattenNestedPlaceholders() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "household": { + "type": "object", + "properties": { + "{member1}": { + "type": "object", + "properties": { + "age": { "type": "number" }, + "income": { "type": "number" } + } + }, + "{member2}": { + "type": "object", + "properties": { + "age": { "type": "number" } + } + } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode flattened = SchemaTemplateTransformer.flattenTemplate(templateNode); + + JsonNode household = flattened.get("properties").get("household"); + assertTrue(household.has("additionalProperties")); + + JsonNode additionalProps = household.get("additionalProperties"); + // Should have merged properties from both placeholders + assertTrue(additionalProps.get("properties").has("age")); + assertTrue(additionalProps.get("properties").has("income")); + } + + @Test + public void testLoadSchemaTemplateFromFile() throws IOException { + // Test loading the actual schema template file we created + try (InputStream is = getClass().getResourceAsStream( + "/checks/age/person-min-age.schema.json")) { + assertNotNull(is, "Schema template file should exist"); + JsonNode schema = SchemaTemplateTransformer.parseSchema(is); + + assertTrue(SchemaTemplateTransformer.hasPlaceholders(schema)); + + Set placeholders = SchemaTemplateTransformer.extractPlaceholders(schema); + assertTrue(placeholders.contains("personId")); + } + } + + @Test + public void testNullHandling() { + assertNull(SchemaTemplateTransformer.fillTemplate(null, Map.of())); + assertNull(SchemaTemplateTransformer.flattenTemplate(null)); + assertTrue(SchemaTemplateTransformer.extractPlaceholders(null).isEmpty()); + assertFalse(SchemaTemplateTransformer.hasPlaceholders(null)); + } + + @Test + public void testToJsonString() throws IOException { + String template = """ + {"type":"object","properties":{"{person}":{"type":"string"}}} + """; + + JsonNode node = SchemaTemplateTransformer.parseSchema(template); + String json = SchemaTemplateTransformer.toJsonString(node); + + assertNotNull(json); + assertTrue(json.contains("\"type\"")); + assertTrue(json.contains("\"properties\"")); + } + + @Test + public void testFillTemplateWithArrayExpansion() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "situation": { + "type": "object", + "properties": { + "people": { + "type": "object", + "properties": { + "{peopleIds}": { + "type": "object", + "properties": { + "dateOfBirth": { "type": "string" } + } + } + } + } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + + // When value is a List, each element becomes a separate property + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, + Map.of("peopleIds", List.of("alice", "bob", "charlie"))); + + JsonNode people = filled.get("properties").get("situation") + .get("properties").get("people").get("properties"); + + // Should have expanded into three separate properties + assertTrue(people.has("alice")); + assertTrue(people.has("bob")); + assertTrue(people.has("charlie")); + assertFalse(people.has("{peopleIds}")); + + // Each should have the same schema + assertTrue(people.get("alice").get("properties").has("dateOfBirth")); + assertTrue(people.get("bob").get("properties").has("dateOfBirth")); + assertTrue(people.get("charlie").get("properties").has("dateOfBirth")); + } + + @Test + public void testFillTemplateWithEmptyArray() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{items}": { "type": "object" } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, + Map.of("items", List.of())); + + // Empty array should result in no properties from that placeholder + assertEquals(0, filled.get("properties").size()); + } + + @Test + public void testFillTemplateMixedStringAndArray() throws IOException { + String template = """ + { + "type": "object", + "properties": { + "{person}": { + "type": "object", + "properties": { + "name": { "type": "string" } + } + }, + "{items}": { + "type": "object", + "properties": { + "value": { "type": "number" } + } + } + } + } + """; + + JsonNode templateNode = SchemaTemplateTransformer.parseSchema(template); + + // Mix of single string and array values + Map values = Map.of( + "person", "client", + "items", List.of("item1", "item2") + ); + JsonNode filled = SchemaTemplateTransformer.fillTemplate(templateNode, values); + + JsonNode props = filled.get("properties"); + + // Single replacement + assertTrue(props.has("client")); + assertTrue(props.get("client").get("properties").has("name")); + + // Array expansion + assertTrue(props.has("item1")); + assertTrue(props.has("item2")); + assertTrue(props.get("item1").get("properties").has("value")); + assertTrue(props.get("item2").get("properties").has("value")); + } + + @Test + public void testLoadSomeoneMinAgeSchemaTemplate() throws IOException { + // Test the someone-min-age schema which uses {peopleIds} placeholder + try (InputStream is = getClass().getResourceAsStream( + "/checks/age/someone-min-age.schema.json")) { + assertNotNull(is, "Schema template file should exist"); + JsonNode schema = SchemaTemplateTransformer.parseSchema(is); + + assertTrue(SchemaTemplateTransformer.hasPlaceholders(schema)); + + Set placeholders = SchemaTemplateTransformer.extractPlaceholders(schema); + assertTrue(placeholders.contains("peopleIds")); + } + } +} diff --git a/library-api/src/test/java/org/codeforphilly/bdt/api/SituationTypeValidationTest.java b/library-api/src/test/java/org/codeforphilly/bdt/api/SituationTypeValidationTest.java deleted file mode 100644 index ab2d9ad9..00000000 --- a/library-api/src/test/java/org/codeforphilly/bdt/api/SituationTypeValidationTest.java +++ /dev/null @@ -1,357 +0,0 @@ -package org.codeforphilly.bdt.api; - -import com.fasterxml.jackson.databind.JsonNode; -import io.quarkus.test.junit.QuarkusTest; -import org.junit.jupiter.api.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -import javax.inject.Inject; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.InputStream; -import java.util.*; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * Validates that all "situation" inputs in DMN models are proper subtypes of BDT.tSituation. - * - * This test ensures: - * 1. BDT.dmn exists and defines tSituation with all expected fields (recursively) - * 2. All DMN models with decision services that accept a "situation" parameter either: - * a) Reference BDT.tSituation directly (typeRef="BDT.tSituation"), OR - * b) Define a local tSituation type that is a valid subset of BDT.tSituation - * (all fields/nested fields exist in BDT.tSituation) - * - * Uses JSON schema comparison via DMNSchemaResolver to recursively validate nested types. - */ -@QuarkusTest -public class SituationTypeValidationTest { - - @Inject - ModelRegistry modelRegistry; - - @Inject - DMNSchemaResolver schemaResolver; - - private static final String DMN_NAMESPACE = "http://www.omg.org/spec/DMN/20180521/MODEL/"; - private static final String BDT_NAMESPACE = "https://kie.apache.org/dmn/_1B91A885-130A-4E0B-A762-E12AA6DD5C79"; - - @Test - public void testBdtDefinesTSituation() { - // Find BDT tSituation schema in dmnDefinitions.json - String bdtSchemaKey = findBdtTSituationSchemaKey(); - assertNotNull(bdtSchemaKey, "BDT.tSituation schema should exist in dmnDefinitions.json"); - - JsonNode bdtSchema = schemaResolver.getSchema(bdtSchemaKey); - assertNotNull(bdtSchema, "BDT.tSituation schema should be loadable"); - - // Generate example to verify structure - Map bdtExample = schemaResolver.generateExampleFromSchema(bdtSchema); - assertFalse(bdtExample.isEmpty(), "BDT.tSituation should have fields"); - - // Verify expected core fields exist - assertTrue(bdtExample.containsKey("people"), - "BDT.tSituation should define 'people' field"); - assertTrue(bdtExample.containsKey("primaryPersonId"), - "BDT.tSituation should define 'primaryPersonId' field"); - - System.out.println("BDT.tSituation schema key: " + bdtSchemaKey); - System.out.println("BDT.tSituation example fields: " + bdtExample.keySet()); - } - - /** - * Find the schema key for BDT.tSituation in dmnDefinitions.json. - * Pattern: looks for a schema with x-dmn-type containing BDT namespace and tSituation. - */ - private String findBdtTSituationSchemaKey() { - Set allKeys = schemaResolver.getAllSchemaKeys(); - for (String key : allKeys) { - JsonNode schema = schemaResolver.getSchema(key); - if (schema != null && schema.has("x-dmn-type")) { - String dmnType = schema.get("x-dmn-type").asText(); - if (dmnType.contains(BDT_NAMESPACE) && dmnType.contains("tSituation")) { - return key; - } - } - } - return null; - } - - @Test - public void testAllSituationInputsAreValidSubtypes() throws Exception { - Map allModels = modelRegistry.getAllModels(); - - // Get all models with decision services (both benefits and checks) - List modelsToValidate = allModels.values().stream() - .filter(model -> model.getPath().startsWith("checks/") || model.getPath().startsWith("benefits/")) - .filter(model -> !model.getDecisionServices().isEmpty()) - .collect(Collectors.toList()); - - assertTrue(modelsToValidate.size() > 0, - "Should have at least one model to validate"); - - for (ModelInfo model : modelsToValidate) { - validateSituationInput(model); - } - } - - private void validateSituationInput(ModelInfo model) throws Exception { - // Load and parse the DMN file (add .dmn extension to path) - String dmnPath = model.getPath() + ".dmn"; - InputStream dmnStream = getClass().getClassLoader() - .getResourceAsStream(dmnPath); - assertNotNull(dmnStream, - "DMN file should exist at " + dmnPath); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(dmnStream); - - // Find inputData elements with name="situation" - NodeList inputDataElements = doc.getElementsByTagNameNS(DMN_NAMESPACE, "inputData"); - Element situationInput = null; - - for (int i = 0; i < inputDataElements.getLength(); i++) { - Element inputData = (Element) inputDataElements.item(i); - if ("situation".equals(inputData.getAttribute("name"))) { - situationInput = inputData; - break; - } - } - - // Not all models have a situation input (e.g., utility models like Age.dmn) - if (situationInput == null) { - System.out.println("Skipping " + model.getPath() + " - no 'situation' input found"); - return; - } - - // Find the variable element within inputData - NodeList variables = situationInput.getElementsByTagNameNS(DMN_NAMESPACE, "variable"); - assertTrue(variables.getLength() > 0, - model.getPath() + ": situation input must have a variable element"); - - Element variable = (Element) variables.item(0); - String typeRef = variable.getAttribute("typeRef"); - - assertNotNull(typeRef, - model.getPath() + ": situation variable must have a typeRef"); - assertFalse(typeRef.isEmpty(), - model.getPath() + ": situation variable typeRef must not be empty"); - - // Case 1: Direct reference to BDT.tSituation - this is always valid - if ("BDT.tSituation".equals(typeRef)) { - System.out.println("✓ " + model.getPath() + " uses BDT.tSituation directly"); - return; - } - - // Case 2: Local tSituation reference - must validate it's a proper subset - if ("tSituation".equals(typeRef)) { - validateLocalTSituationType(model, doc); - return; - } - - // Any other typeRef is invalid - fail(model.getPath() + ": situation variable has unexpected typeRef '" + typeRef + - "'. Expected 'BDT.tSituation' or 'tSituation'"); - } - - private void validateLocalTSituationType(ModelInfo model, Document doc) { - // Find BDT tSituation schema - String bdtSchemaKey = findBdtTSituationSchemaKey(); - assertNotNull(bdtSchemaKey, "BDT.tSituation schema must exist"); - - // Find local tSituation schema from dmnDefinitions.json - String localSchemaKey = findLocalTSituationSchemaKey(model); - if (localSchemaKey == null) { - fail(model.getPath() + ": uses typeRef='tSituation' but schema not found in dmnDefinitions.json"); - } - - // Get schemas - JsonNode bdtSchema = schemaResolver.getSchema(bdtSchemaKey); - JsonNode localSchema = schemaResolver.getSchema(localSchemaKey); - - assertNotNull(bdtSchema, "BDT schema should exist"); - assertNotNull(localSchema, "Local schema should exist for " + model.getPath()); - - // Check that local schema has properties (not empty/Any-only) - if (!localSchema.has("properties") || !localSchema.get("properties").fields().hasNext()) { - fail(model.getPath() + ": local tSituation must define at least one field from BDT.tSituation. " + - "It currently has no fields (may just be typeRef='Any')."); - } - - // Recursively validate that local schema is subset of BDT schema - List invalidPaths = new ArrayList<>(); - validateSchemaSubset(bdtSchema, localSchema, "", invalidPaths); - - if (!invalidPaths.isEmpty()) { - // Generate examples for error message - Map bdtExample = schemaResolver.generateExampleFromSchema(bdtSchema); - Map localExample = schemaResolver.generateExampleFromSchema(localSchema); - - fail(model.getPath() + ": local tSituation defines structure not compatible with BDT.tSituation.\n" + - "Invalid paths: " + invalidPaths + "\n" + - "Local example: " + localExample + "\n" + - "BDT example: " + bdtExample); - } - - // Generate example for success message - Map localExample = schemaResolver.generateExampleFromSchema(localSchema); - System.out.println("✓ " + model.getPath() + " uses valid local tSituation subset with fields: " + - localExample.keySet()); - } - - /** - * Find the schema key for a model's local tSituation type. - * Pattern: {nsN}tSituation where N is the namespace number for the model. - */ - private String findLocalTSituationSchemaKey(ModelInfo model) { - String modelNamespace = model.getNamespace(); - Set allKeys = schemaResolver.getAllSchemaKeys(); - - for (String key : allKeys) { - JsonNode schema = schemaResolver.getSchema(key); - if (schema != null && schema.has("x-dmn-type")) { - String dmnType = schema.get("x-dmn-type").asText(); - // Check if this is tSituation from the model's namespace - if (dmnType.contains(modelNamespace) && dmnType.contains("tSituation")) { - return key; - } - } - } - return null; - } - - /** - * Recursively validate that local schema is a structural and type-compatible subset of BDT schema. - * All fields/paths in local schema must exist in BDT schema with compatible types and formats. - * - * @param bdtSchema The canonical BDT schema node - * @param localSchema The local schema node to validate - * @param currentPath The current path in dot notation (for error reporting) - * @param invalidPaths List to accumulate invalid paths found - */ - private void validateSchemaSubset(JsonNode bdtSchema, JsonNode localSchema, String currentPath, List invalidPaths) { - // Resolve any $ref references - JsonNode resolvedBdt = resolveSchemaRef(bdtSchema); - JsonNode resolvedLocal = resolveSchemaRef(localSchema); - - // If local schema is null or missing, it's valid (no constraint) - if (resolvedLocal == null || resolvedLocal.isNull()) { - return; - } - - // Check if local is unstructured (only x-dmn-type, no type/properties/items/$ref) - boolean localHasStructure = resolvedLocal.has("type") || - resolvedLocal.has("properties") || - resolvedLocal.has("items") || - resolvedLocal.has("$ref"); - - boolean bdtHasStructure = resolvedBdt.has("type") || - resolvedBdt.has("properties") || - resolvedBdt.has("items") || - resolvedBdt.has("$ref"); - - // If BDT has structure but local doesn't, that's invalid - if (bdtHasStructure && !localHasStructure) { - String localType = resolvedLocal.has("x-dmn-type") ? - resolvedLocal.get("x-dmn-type").asText() : "unknown"; - invalidPaths.add(currentPath + - " [local uses unstructured type '" + localType + - "' but BDT has structured type]"); - return; - } - - // Handle object types (have "properties") - if (resolvedLocal.has("properties")) { - if (!resolvedBdt.has("properties")) { - invalidPaths.add(currentPath + " [BDT is not an object but local is]"); - return; - } - - JsonNode localProps = resolvedLocal.get("properties"); - JsonNode bdtProps = resolvedBdt.get("properties"); - - // Check each local property - localProps.fields().forEachRemaining(entry -> { - String fieldName = entry.getKey(); - String newPath = currentPath.isEmpty() ? fieldName : currentPath + "." + fieldName; - - // Check if field exists in BDT - if (!bdtProps.has(fieldName)) { - invalidPaths.add(newPath + " [field does not exist in BDT]"); - return; - } - - // Recursively validate the field's schema - validateSchemaSubset(bdtProps.get(fieldName), entry.getValue(), newPath, invalidPaths); - }); - return; - } - - // Handle array types (have "items") - if (resolvedLocal.has("items")) { - if (!resolvedBdt.has("items")) { - invalidPaths.add(currentPath + " [BDT is not an array but local is]"); - return; - } - - String newPath = currentPath + "[]"; - validateSchemaSubset(resolvedBdt.get("items"), resolvedLocal.get("items"), newPath, invalidPaths); - return; - } - - // Handle primitive types - check type and format compatibility - String localType = resolvedLocal.has("type") ? resolvedLocal.get("type").asText() : null; - String bdtType = resolvedBdt.has("type") ? resolvedBdt.get("type").asText() : null; - - if (localType != null && bdtType != null && !localType.equals(bdtType)) { - invalidPaths.add(currentPath + " [type mismatch: BDT has " + bdtType + ", local has " + localType + "]"); - return; - } - - // Check format (important for date vs string distinction) - String localFormat = resolvedLocal.has("format") ? resolvedLocal.get("format").asText() : null; - String bdtFormat = resolvedBdt.has("format") ? resolvedBdt.get("format").asText() : null; - - // Both should have same format, or both should have no format - if (!Objects.equals(localFormat, bdtFormat)) { - String localDesc = localFormat != null ? localFormat : "no format"; - String bdtDesc = bdtFormat != null ? bdtFormat : "no format"; - invalidPaths.add(currentPath + " [format mismatch: BDT has " + bdtDesc + ", local has " + localDesc + "]"); - } - } - - /** - * Resolve a JSON Schema $ref to get the actual schema definition. - * Uses DMNSchemaResolver's schema cache. - */ - private JsonNode resolveSchemaRef(JsonNode schema) { - if (schema == null || !schema.has("$ref")) { - return schema; - } - - String ref = schema.get("$ref").asText(); - String refKey = null; - - if (ref.startsWith("#/components/schemas/")) { - refKey = ref.substring("#/components/schemas/".length()); - } else if (ref.startsWith("#/definitions/")) { - refKey = ref.substring("#/definitions/".length()); - } - - if (refKey != null) { - JsonNode refSchema = schemaResolver.getSchema(refKey); - if (refSchema != null) { - // Recursively resolve in case the referenced schema is also a reference - return resolveSchemaRef(refSchema); - } - } - - return schema; - } -} diff --git a/library-api/test/bdt/benefits/folder.bru b/library-api/test/bdt/benefits/folder.bru deleted file mode 100644 index 9f575392..00000000 --- a/library-api/test/bdt/benefits/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: benefits - seq: 2 -} - -auth { - mode: inherit -} diff --git a/library-api/test/bdt/benefits/pa/folder.bru b/library-api/test/bdt/benefits/pa/folder.bru deleted file mode 100644 index 2b72b0c3..00000000 --- a/library-api/test/bdt/benefits/pa/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: pa - seq: 1 -} - -auth { - mode: inherit -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Eligible.bru b/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Eligible.bru deleted file mode 100644 index 090fe5de..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Eligible.bru +++ /dev/null @@ -1,39 +0,0 @@ -meta { - name: Eligible - type: http - seq: 2 -} - -post { - url: {{host}}/benefits/pa/phl/homestead-exemption - body: json - auth: inherit -} - -body:json { - { - "situation": { - "primaryPersonId": "p1", - "enrollments": [ - { - "personId": "p2", - "benefit": "PhlHomesteadExemption" - } - ], - "simpleChecks": { - "tenYearTaxAbatement": false, - "ownerOccupant": true, - "livesInPhiladelphiaPa": true - } - } - } -} - -assert { - res.body.isEligible: eq true -} - -settings { - encodeUrl: true - timeout: 0 -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Ineligible.bru b/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Ineligible.bru deleted file mode 100644 index d676eb0b..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Ineligible.bru +++ /dev/null @@ -1,39 +0,0 @@ -meta { - name: Ineligible - type: http - seq: 3 -} - -post { - url: {{host}}/benefits/pa/phl/homestead-exemption - body: json - auth: inherit -} - -body:json { - { - "situation": { - "primaryPersonId": "p1", - "enrollments": [ - { - "personId": "p2", - "benefit": "PhlHomesteadExemption" - } - ], - "simpleChecks": { - "tenYearTaxAbatement": true, - "ownerOccupant": true, - "livesInPhiladelphiaPa": true - } - } - } -} - -assert { - res.body.isEligible: eq false -} - -settings { - encodeUrl: true - timeout: 0 -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Smoke Test.bru b/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Smoke Test.bru deleted file mode 100644 index 354b63f4..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/Smoke Test.bru +++ /dev/null @@ -1,37 +0,0 @@ -meta { - name: Smoke Test - type: http - seq: 1 -} - -post { - url: {{host}}/benefits/pa/phl/homestead-exemption - body: json - auth: inherit -} - -body:json { - { - "situation": { - "primaryPersonId": "p1", - "enrollments": [ - { - "personId": "p2", - "benefit": "PhlHomesteadExemption" - } - ], - "simpleChecks": { - "tenYearTaxAbatement": false - } - } - } -} - -assert { - res.body.isEligible: eq null -} - -settings { - encodeUrl: true - timeout: 0 -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/folder.bru b/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/folder.bru deleted file mode 100644 index 4f6786ff..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlHomesteadExemption/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: PhlHomesteadExemption - seq: 1 -} - -auth { - mode: inherit -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/Smoke Test.bru b/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/Smoke Test.bru deleted file mode 100644 index 70e7021c..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/Smoke Test.bru +++ /dev/null @@ -1,55 +0,0 @@ -meta { - name: Smoke Test - type: http - seq: 1 -} - -post { - url: {{host}}/benefits/pa/phl/senior-citizen-tax-freeze - body: json - auth: inherit -} - -body:json { - { - "situation": { - "simpleChecks": { - "phillyHomeownerOccupant": true - }, - "primaryPersonId": "p1", - "people": [ - { - "id": "p1", - "dateOfBirth": "1970-08-01" - }, - { - "id": "p2", - "dateOfBirth": "1960-12-30" - } - ], - "enrollments": [ - { - "personId": "p2", - "benefit": "PhlHomesteadExemption" - } - ], - "relationships": [ - { - "type": "spouse", - "personId": "p1", - "relatedPersonId": "p2" - }, - { - "type": "spouse", - "personId": "p2", - "relatedPersonId": "p1" - } - ] - } - } -} - -settings { - encodeUrl: true - timeout: 0 -} diff --git a/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/folder.bru b/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/folder.bru deleted file mode 100644 index 03805897..00000000 --- a/library-api/test/bdt/benefits/pa/phl/PhlSeniorCitizenTaxFreeze/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: PhlSeniorCitizenTaxFreeze - seq: 1 -} - -auth { - mode: inherit -} diff --git a/library-api/test/bdt/benefits/pa/phl/folder.bru b/library-api/test/bdt/benefits/pa/phl/folder.bru deleted file mode 100644 index 5bafa61d..00000000 --- a/library-api/test/bdt/benefits/pa/phl/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: phl - seq: 1 -} - -auth { - mode: inherit -} diff --git a/library-api/test/bdt/checks/age/PersonMaxAge/DOB is null.bru b/library-api/test/bdt/checks/age/PersonMaxAge/DOB is null.bru index 3c5edf00..343195d7 100644 --- a/library-api/test/bdt/checks/age/PersonMaxAge/DOB is null.bru +++ b/library-api/test/bdt/checks/age/PersonMaxAge/DOB is null.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1", + "people": { + "p1": { "dateOfBirth": null } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/age/PersonMaxAge/age is below max age.bru b/library-api/test/bdt/checks/age/PersonMaxAge/age is below max age.bru index e7954cd8..c6b044a6 100644 --- a/library-api/test/bdt/checks/age/PersonMaxAge/age is below max age.bru +++ b/library-api/test/bdt/checks/age/PersonMaxAge/age is below max age.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1", + "people": { + "p1": { "dateOfBirth": "2025-01-01" } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/age/PersonMinAge/Person At Min Age.bru b/library-api/test/bdt/checks/age/PersonMinAge/Person At Min Age.bru index ee111e96..370b75a7 100644 --- a/library-api/test/bdt/checks/age/PersonMinAge/Person At Min Age.bru +++ b/library-api/test/bdt/checks/age/PersonMinAge/Person At Min Age.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1", + "people": { + "p1": { "dateOfBirth": "2020-01-01" } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/age/PersonMinAge/Person with Null DOB.bru b/library-api/test/bdt/checks/age/PersonMinAge/Person with Null DOB.bru index 01b57731..c4d0534a 100644 --- a/library-api/test/bdt/checks/age/PersonMinAge/Person with Null DOB.bru +++ b/library-api/test/bdt/checks/age/PersonMinAge/Person with Null DOB.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1", + "people": { + "p1": { "dateOfBirth": null } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrolled in Bogus Benefit.bru b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrolled in Bogus Benefit.bru index 73aba57f..945bb6f3 100644 --- a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrolled in Bogus Benefit.bru +++ b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrolled in Bogus Benefit.bru @@ -13,17 +13,13 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": [ + "bogus" + ] } - ], - "enrollments": [ - { - "personId": "p1", - "benefit": "bogus" - } - ] + } }, "parameters": { "personId": "p1", @@ -32,6 +28,10 @@ body:json { } } +assert { + res.body.checkResult: eq true +} + settings { encodeUrl: true timeout: 0 diff --git a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments empty.bru b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments empty.bru index 7eff128e..e0039fb5 100644 --- a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments empty.bru +++ b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments empty.bru @@ -13,13 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": [] } - ], - "enrollments": [ - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments null.bru b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments null.bru index 2e158d2e..a767b442 100644 --- a/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments null.bru +++ b/library-api/test/bdt/checks/enrollment/PersonEnrolledInBenefit/Enrollments null.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": null } - ], - "enrollments": null + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrolled.bru b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrolled.bru index 4099930a..524571f2 100644 --- a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrolled.bru +++ b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrolled.bru @@ -13,17 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": ["bogus"] } - ], - "enrollments": [ - { - "personId": "p1", - "benefit": "bogus" - } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments empty.bru b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments empty.bru index 11c4b173..b625db66 100644 --- a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments empty.bru +++ b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments empty.bru @@ -13,13 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": [] } - ], - "enrollments": [ - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments null.bru b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments null.bru index 107d7abc..a0608aa9 100644 --- a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments null.bru +++ b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/Enrollments null.bru @@ -13,12 +13,11 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": null } - ], - "enrollments": null + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/NOT Enrolled in Bogus Benefit.bru b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/NOT Enrolled in Bogus Benefit.bru index 20368af5..3a3a7443 100644 --- a/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/NOT Enrolled in Bogus Benefit.bru +++ b/library-api/test/bdt/checks/enrollment/PersonNotEnrolledInBenefit/NOT Enrolled in Bogus Benefit.bru @@ -13,17 +13,14 @@ post { body:json { { "situation": { - "people": [ - { - "id": "p1" + "people": { + "p1": { + "enrollments": ["different_benefit"] + }, + "p2": { + "enrollments": ["bogus"] } - ], - "enrollments": [ - { - "personId": "p2", - "benefit": "bogus" - } - ] + } }, "parameters": { "personId": "p1", diff --git a/library-api/test/bdt/checks/enrollment/folder.bru b/library-api/test/bdt/checks/enrollment/folder.bru deleted file mode 100644 index 7bb6a730..00000000 --- a/library-api/test/bdt/checks/enrollment/folder.bru +++ /dev/null @@ -1,8 +0,0 @@ -meta { - name: enrollment - seq: 2 -} - -auth { - mode: inherit -}