Template based rule

In case we want to generate a rule using a template.groovy file:

package groovyRules

import static com.stibo.leap.datastandard.extractor.sdk.businessrules.BusinessRuleUtils.*;
import com.stibo.leap.datastandard.extractor.sdk.businessrules.GroovyExecutionScope;

def product = GroovyExecutionScope.CHANNEL_PRODUCT?.getProduct();
def attributeA = product?.getAttribute("{attribute A}");
def attributeB = product?.getAttribute("{attribute B}");

if (nullSafeEquals(attributeA?.getValue(), attributeB?.getValue())) {
    GroovyExecutionScope.errors.put("{attribute A}", "{name A} and {name B} cannot be the same");
    GroovyExecutionScope.errors.put("{attribute B}", "{name A} and {name B} cannot be the same");
};

return !GroovyExecutionScope.errors.isEmpty();

we can do this by adding code that processes the lines of the template and does the replacements like for instance:

ar groovyTemplate = new File("template.groovy");
var replacements = Map.of(
    "{attribute A}", "SIZE_OF_PRODUCT",
    "{attribute B}", "SIZE_OF_PACK",
    "{name A}", "Product Size",
    "{name B}", "Package Size"
);
var templateLines = IOUtils.readLines(new FileInputStream(groovyTemplate), Charsets.UTF_8);
List<String> lines = new ArrayList<>();

for (String templateLine : templateLines) {
    String line = templateLine;

    for (var key : replacements.keySet()) {
        line = line.replace(key, replacements.get(key));
    }

    lines.add(line);
}

and feeds those lines into rule as a list of strings like this:

BusinessRule rule = BusinessRuleBuilder.groovyRule("ID")
    .withGroovyLines(lines)
    .build();

This produces the following JSON output when rule is serialized:

{
  "id": "ID",
  "templateId": "groovyRule",
  "namedAttributes": {},
  "parameters": {
    "customFunction": "def product = context.get(\"CHANNEL_PRODUCT\")?.getProduct();def attributeA = product?.getAttribute(\"SIZE_OF_PRODUCT\");def attributeB = product?.getAttribute(\"SIZE_OF_PACK\");if (nullSafeEquals(attributeA?.getValue(), attributeB?.getValue())) {errors.put(\"SIZE_OF_PRODUCT\", \"Product Size and Package Size cannot be the same\");errors.put(\"SIZE_OF_PACK\", \"Product Size and Package Size cannot be the same\");};return !errors.isEmpty();"
  },
  "requiredContexts": [
    "CHANNEL_PRODUCT"
  ],
  "execution": "CONTINUOUS",
  "businessRuleScopes": [],
  "staticProperties": {}
}