100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
JSON rules refactor
Rich Turner3c872f8d78d2
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.javaindex 27833d9b3..e800ac078 100644--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java@@ -1,5 +1,6 @@package org.openremote.agent.protocol.knx;+import org.apache.commons.io.IOUtils;import org.openremote.agent.protocol.AbstractProtocol;import org.openremote.model.asset.AssetTreeNode;import org.openremote.agent.protocol.ProtocolLinkedAttributeImport;@@ -33,9 +34,9 @@ import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.stream.StreamResult;import javax.xml.transform.stream.StreamSource;-import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;-import java.io.IOException;+import java.io.*;+import java.nio.charset.Charset;+import java.nio.charset.StandardCharsets;import java.util.*;import java.util.function.Consumer;import java.util.logging.Logger;@@ -446,23 +447,30 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttri}// Create a transform factory instance.- System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");- TransformerFactory tfactory = TransformerFactory.newInstance();+ TransformerFactory tfactory = new net.sf.saxon.TransformerFactoryImpl();// Create a transformer for the stylesheet.- Transformer transformer = tfactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream("/org/openremote/agent/protocol/knx/ets_calimero_group_name.xsl")));+ InputStream inputStream = KNXProtocol.class.getResourceAsStream("/org/openremote/agent/protocol/knx/ets_calimero_group_name.xsl");+ String xsd = IOUtils.toString(inputStream, StandardCharsets.UTF_8);+ xsd = xsd.trim().replaceFirst("^([\\W]+)<","<"); // Get weird behaviour sometimes without this+ LOG.warning(xsd);+ Transformer transformer = tfactory.newTransformer(new StreamSource(new StringReader(xsd)));// Set the URIResolvertransformer.setURIResolver(new EtsFileUriResolver(data));- // Transform the source XML into byte array- ByteArrayOutputStream bos = new ByteArrayOutputStream();- transformer.transform(new StreamSource(zin), new StreamResult(bos));- byte[] result = bos.toByteArray();+ // Transform the source XML+ String xml = IOUtils.toString(zin, StandardCharsets.UTF_8);+ xml = xml.trim().replaceFirst("^([\\W]+)<","<"); // Get weird behaviour sometimes without this+ LOG.warning(xml);+ StringWriter writer = new StringWriter();+ StringReader reader = new StringReader(xml);+ transformer.transform(new StreamSource(reader), new StreamResult(writer));+ xml = writer.toString();- // we use a map of state-based datapoints and read from the transformed xml+ // we use a map of state-based data points and read from the transformed xmlfinal DatapointMap<StateDP> datapoints = new DatapointMap<>();- try (final XmlReader r = XmlInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(result))) {+ try (final XmlReader r = XmlInputFactory.newInstance().createXMLStreamReader(new StringReader(xml))) {datapoints.load(r);} catch (final KNXMLException e) {String msg = "Error loading parsed ETS file: " + e.getMessage();diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.jsonindex a40b8933c..b0a915371 100644--- a/deployment/manager/shared/locales/en/or.json+++ b/deployment/manager/shared/locales/en/or.json@@ -160,11 +160,18 @@"message": "Message","warn": "Warning","error": "Error",- "frequency": "Frequency",- "everyTime": "Every time",- "onlyOnce": "Only once",- "oncePerHour": "Max. once per hour",- "oncePerDay": "Max. once per day",- "oncePerWeek": "Max. once per week",- "oncePerMonth": "Max. once per month"+ "recurrence": "Recurrence",+ "always": "Always",+ "once": "Once",+ "oncePerAsset": "Once per asset",+ "oncePerHour": "Once per hour",+ "oncePerHourPerAsset": "Once per hour per asset",+ "oncePerDay": "Once per day",+ "oncePerDayPerAsset": "Once per day per asset",+ "oncePerWeek": "Once per week",+ "oncePerWeekPerAsset": "Once per week per asset",+ "oncePerMonth": "Once per month",+ "oncePerMonthPerAsset": "Once per month per asset",+ "reset": "Reset",+ "noLongerMatches": "No longer matches"}diff --git a/deployment/manager/shared/locales/nl/or.json b/deployment/manager/shared/locales/nl/or.jsonindex eb954761f..ed13a7f1e 100644--- a/deployment/manager/shared/locales/nl/or.json+++ b/deployment/manager/shared/locales/nl/or.json@@ -150,11 +150,18 @@"operator": "Operator","area": "Gebied","timestamp": "Tijdsaanduiding",- "frequency": "Frequentie",- "everyTime": "Iedere keer",- "onlyOnce": "Eenmalig",- "oncePerHour": "Max. 1x per uur",- "oncePerDay": "Max. 1x per dag",- "oncePerWeek": "Max. 1x per week",- "oncePerMonth": "Max. 1x per maand"+ "recurrence": "Recurrence",+ "always": "Iedere keer",+ "once": "Eenmalig",+ "oncePerAsset": "Eenmalig per asset",+ "oncePerHour": "1x per uur",+ "oncePerHourPerAsset": "1x per uur per asset",+ "oncePerDay": "1x per dag",+ "oncePerDayPerAsset": "1x per dag per asset",+ "oncePerWeek": "1x per week",+ "oncePerWeekPerAsset": "1x per week per asset",+ "oncePerMonth": "1x per maand",+ "oncePerMonthPerAsset": "1x per maand per asset",+ "reset": "Reset",+ "noLongerMatches": "No longer matches"}diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex 58273f683..788ae2c89 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -20,6 +20,7 @@package org.openremote.manager.rules;import com.fasterxml.jackson.core.JsonProcessingException;+import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.concurrent.ManagerExecutorService;@@ -32,7 +33,6 @@ import org.openremote.model.query.AssetQuery;import org.openremote.model.query.LogicGroup;import org.openremote.model.query.UserQuery;import org.openremote.model.query.filter.AttributePredicate;-import org.openremote.model.query.filter.DateTimePredicate;import org.openremote.model.rules.AssetState;import org.openremote.model.rules.Assets;import org.openremote.model.rules.Ruleset;@@ -45,6 +45,7 @@ import org.openremote.model.value.*;import org.quartz.CronExpression;import java.util.*;+import java.util.concurrent.atomic.AtomicLong;import java.util.function.BiConsumer;import java.util.function.Predicate;import java.util.logging.Level;@@ -59,16 +60,6 @@ import static org.openremote.model.query.filter.LocationAttributePredicate.getLopublic class JsonRulesBuilder extends RulesBuilder {- static class Targets {- public TargetType type;- public List<String> ids;-- public Targets(TargetType type, List<String> ids) {- this.type = type;- this.ids = ids;- }- }-static class RuleActionExecution {Runnable runnable;long delay;@@ -80,29 +71,25 @@ public class JsonRulesBuilder extends RulesBuilder {}/**- * This stores all state for a given {@link RuleCondition} and calculates which {@link AssetState}s match and don't+ * Stores all state for a given {@link RuleCondition} and calculates which {@link AssetState}s match and don't* match the condition.*/static class RuleConditionState {+ RuleCondition ruleCondition;final TimerService timerService;boolean trackUnmatched;AssetQuery.OrderBy orderBy;int limit;LogicGroup<AttributePredicate> attributePredicates = null;- Collection<Predicate<AssetState>> attributeAndedPredicates = null;- RuleCondition ruleCondition;+ Predicate<AssetState> assetStatePredicate = null;Set<AssetState> unfilteredAssetStates = new HashSet<>();Set<AssetState> previouslyMatchedAssetStates = new HashSet<>();Set<AssetState> previouslyUnmatchedAssetStates;- Map<AssetState, Long> previouslyMatchedExpiryTimes;- long nextExecuteMillis;- long resetDurationMillis;- Runnable updateNextExecuteTime;- CronExpression timerExpression;- RuleConditionTriggerResult lastTriggerResult;-- public RuleConditionState(RuleCondition ruleCondition, boolean trackUnmatched, TimerService timerService) {+ Predicate<Long> timePredicate;+ RuleConditionEvaluationResult lastEvaluationResult;++ public RuleConditionState(RuleCondition ruleCondition, boolean trackUnmatched, TimerService timerService) throws Exception {this.timerService = timerService;this.ruleCondition = ruleCondition;this.trackUnmatched = trackUnmatched;@@ -111,98 +98,106 @@ public class JsonRulesBuilder extends RulesBuilder {previouslyUnmatchedAssetStates = new HashSet<>();}- if (ruleConditionResetHasTimer(ruleCondition.reset)) {- previouslyMatchedExpiryTimes = new HashMap<>();- if (!TextUtil.isNullOrEmpty(ruleCondition.reset.timer) && TimeUtil.isTimeDuration(ruleCondition.reset.timer)) {- resetDurationMillis = TimeUtil.parseTimeDuration(ruleCondition.reset.timer);- }- }-if (!TextUtil.isNullOrEmpty(ruleCondition.timer)) {+try {if (TimeUtil.isTimeDuration(ruleCondition.timer)) {- nextExecuteMillis = timerService.getCurrentTimeMillis();- long duration = TimeUtil.parseTimeDuration(ruleCondition.timer);- updateNextExecuteTime = () -> nextExecuteMillis += duration;++ final long duration = TimeUtil.parseTimeDuration(ruleCondition.timer);+ AtomicLong nextExecuteMillis = new AtomicLong(timerService.getCurrentTimeMillis());++ timePredicate = (time) -> {+ long nextExecute = nextExecuteMillis.get();+ if (time >= nextExecute) {+ nextExecuteMillis.set(nextExecute + duration);+ return true;+ }+ return false;+ };}+if (CronExpression.isValidExpression(ruleCondition.timer)) {- timerExpression = new CronExpression(ruleCondition.timer);- nextExecuteMillis = timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime();- updateNextExecuteTime = () ->- nextExecuteMillis = timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecuteMillis))).getTime();++ CronExpression timerExpression = new CronExpression(ruleCondition.timer);+ AtomicLong nextExecuteMillis = new AtomicLong(timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime());++ timePredicate = (time) -> {+ long nextExecute = nextExecuteMillis.get();+ if (time >= nextExecute) {+ nextExecuteMillis.set(timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecute))).getTime());+ return true;+ }+ return false;+ };}} catch (Exception e) {- log(Level.SEVERE, "Failed to parse rule trigger timer expression: " + ruleCondition.timer, e);+ log(Level.SEVERE, "Failed to parse rule condition timer expression: " + ruleCondition.timer, e);+ throw e;}- }+ } else if (ruleCondition.assets != null) {- // Pull out order, limit and attribute predicates so they can be applied at required times- if (ruleCondition.assets != null) {+ // Pull out order, limit and attribute predicates so they can be applied at required timesorderBy = ruleCondition.assets.orderBy;limit = ruleCondition.assets.limit;attributePredicates = ruleCondition.assets.attributes;if (attributePredicates != null && attributePredicates.items != null) {- // Note only supports a single level or logic group for attributes (i.e. cannot nest groups)+ // Only supports a single level or logic group for attributes (i.e. cannot nest groups in the UI so+ // don't support it here either)attributePredicates.groups = null;- if (attributePredicates.operator == null || attributePredicates.operator == LogicGroup.Operator.AND) {- attributeAndedPredicates = attributePredicates.items.stream()- .map(attributePredicate -> AssetQueryPredicate.asPredicate(timerService::getCurrentTimeMillis, attributePredicate))- .collect(Collectors.toList());- }+ assetStatePredicate = AssetQueryPredicate.asPredicate(timerService::getCurrentTimeMillis, attributePredicates);}ruleCondition.assets.orderBy = null;ruleCondition.assets.limit = 0;ruleCondition.assets.attributes = null;+ } else {+ throw new IllegalStateException("Invalid rule condition either timer or asset query must be set");}}- void updateUnfilteredAssetStates(RulesFacts facts) {- // Clear last trigger to ensure update runs again- lastTriggerResult = null;+ void updateUnfilteredAssetStates(RulesFacts facts, RulesEngine.AssetStateChangeEvent event) {- if (ruleCondition.timer != null) {- unfilteredAssetStates = new HashSet<>(facts.getAssetStates());- } else if (ruleCondition.assets != null) {- AssetQuery query = ruleCondition.assets;- unfilteredAssetStates = facts.matchAssetState(query).collect(Collectors.toSet());+ // Only interested in this when condition is of type asset query+ if (ruleCondition.assets != null) {+ // Clear last trigger to ensure update runs again+ lastEvaluationResult = null;- // Use this opportunity to notify RulesFacts about any location predicates- if (facts.trackLocationRules) {- boolean isValid = true;- if (ruleCondition.datetime != null) {- //Check if rule is still valid- isValid = checkRuleValidity(timerService.getCurrentTimeMillis(), ruleCondition.datetime);- }- if (isValid) {- facts.storeLocationPredicates(getLocationPredicates(attributePredicates));+ if (event == null || event.cause == PersistenceEvent.Cause.CREATE) {+ // Do a complete refresh of unfiltered asset states based on the asset query (without attribute predicates)+ unfilteredAssetStates = facts.matchAssetState(ruleCondition.assets).collect(Collectors.toSet());+ } else {+ // Replace or remove asset state as required+ switch (event.cause) {+ case UPDATE:+ unfilteredAssetStates.remove(event.assetState);+ unfilteredAssetStates.add(event.assetState);+ break;+ case DELETE:+ unfilteredAssetStates.remove(event.assetState);+ break;}}++ // During startup notify RulesFacts about any location predicates+ if (facts.trackLocationRules) {+ facts.storeLocationPredicates(getLocationPredicates(attributePredicates));+ }}}- void update() {+ void update(Map<String, Long> nextRecurAssetIdMap) {- // Last trigger is cleared by rule RHS execution- if (lastTriggerResult != null && lastTriggerResult.matches) {+ // Last trigger is cleared by rule RHS execution if a match is already found then skip the update+ if (lastEvaluationResult != null && lastEvaluationResult.matches) {return;}- //Check if rule is still valid- if (ruleCondition.datetime != null) {- if (!checkRuleValidity(timerService.getCurrentTimeMillis(), ruleCondition.datetime)) {- log(Level.FINEST, "Rule trigger is no longer valid so no match");- lastTriggerResult = new RuleConditionTriggerResult(false, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());- return;- }- }+ // Apply time condition if it exists+ if (timePredicate != null) {+ lastEvaluationResult = null;- if (!TextUtil.isNullOrEmpty(ruleCondition.timer)) {- lastTriggerResult = null;-- if (updateNextExecuteTime != null && nextExecuteMillis < timerService.getCurrentTimeMillis()) {- updateNextExecuteTime.run();- lastTriggerResult = new RuleConditionTriggerResult(true, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());+ if (timePredicate.test(timerService.getCurrentTimeMillis())) {+ lastEvaluationResult = new RuleConditionEvaluationResult(true, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());}return;@@ -215,7 +210,7 @@ public class JsonRulesBuilder extends RulesBuilder {previouslyUnmatchedAssetStates.clear();}log(Level.FINEST, "Rule trigger has no unfiltered asset states so no match");- lastTriggerResult = new RuleConditionTriggerResult(false, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());+ lastEvaluationResult = new RuleConditionEvaluationResult(false, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());return;}@@ -226,9 +221,12 @@ public class JsonRulesBuilder extends RulesBuilder {if (attributePredicates == null) {matchedAssetStates = new ArrayList<>(unfilteredAssetStates);} else {+Map<Boolean, List<AssetState>> results;+ boolean isAndGroup = attributePredicates.operator == null || attributePredicates.operator == LogicGroup.Operator.AND;++ if (isAndGroup) {- if (attributeAndedPredicates != null) {// ANDs need to be applied in the context of an entire asset as don't make any sense otherwiseresults = new HashMap<>();ArrayList<AssetState> matched = new ArrayList<>();@@ -237,26 +235,16 @@ public class JsonRulesBuilder extends RulesBuilder {results.put(false, unmatched);unfilteredAssetStates.stream().collect(Collectors.groupingBy(AssetState::getId)).forEach((id, states) -> {- Set<AssetState> assetMatched = new HashSet<>();-- for (Predicate<AssetState> attributePredicate : attributeAndedPredicates) {- Collection<AssetState> assetPredicateMatched = states.stream().filter(attributePredicate).collect(Collectors.toList());-- if (assetPredicateMatched.isEmpty()) {- assetMatched.clear();- break;- }-- assetMatched.addAll(assetPredicateMatched);- }- matched.addAll(assetMatched);- unmatched.addAll(states.stream().filter(as -> !assetMatched.contains(as)).collect(Collectors.toList()));+ Map<Boolean, List<AssetState>> assetResults = unfilteredAssetStates.stream().collect(Collectors.groupingBy(assetStatePredicate::test));+ matched.addAll(assetResults.getOrDefault(true, Collections.emptyList()));+ unmatched.addAll(assetResults.getOrDefault(false, Collections.emptyList()));});} else {- Predicate<AssetState> predicate = AssetQueryPredicate.asPredicate(timerService::getCurrentTimeMillis, attributePredicates);- results = unfilteredAssetStates.stream().collect(Collectors.groupingBy(predicate::test));++ results = unfilteredAssetStates.stream().collect(Collectors.groupingBy(assetStatePredicate::test));+}matchedAssetStates = results.getOrDefault(true, Collections.emptyList());@@ -269,66 +257,42 @@ public class JsonRulesBuilder extends RulesBuilder {// Filter out previous un-matches to avoid re-triggeringunmatchedAssetStates.removeIf(previouslyUnmatchedAssetStates::contains);+}}- // Apply reset logic to make previously matched asset states eligible for matching again- if (ruleCondition.reset == null || ruleCondition.reset.noLongerMatches) {- previouslyMatchedAssetStates.removeIf(assetState -> {- boolean noLongerMatches = !matchedAssetStates.contains(assetState);- if (noLongerMatches) {- log(Level.FINER, "Rule trigger previously matched asset state no longer matches so resetting: " + assetState);- }- return noLongerMatches;- });- }+ // Remove previous matches where a recurrence timer doesn't exist for the asset+ // And also depending on reset option whether the asset state no longer matches or the value has changed+ previouslyMatchedAssetStates.removeIf(previousAssetState -> {- if (ruleConditionResetHasTimer(ruleCondition.reset)) {- previouslyMatchedAssetStates.removeIf(assetState -> {- Long timestamp = previouslyMatchedExpiryTimes.get(assetState);- boolean expired = timestamp != null && timerService.getCurrentTimeMillis() > timestamp;- if (expired) {- previouslyMatchedExpiryTimes.remove(assetState);- log(Level.FINER, "Rule trigger previously matched asset state timer has expired or timestamp has changed so resetting: " + assetState);- }- return expired;- });- }+ boolean hasActiveRecurTimer = nextRecurAssetIdMap.containsKey(previousAssetState.getId())+ && nextRecurAssetIdMap.get(previousAssetState.getId()) > timerService.getCurrentTimeMillis();- if (ruleCondition.reset != null && ruleCondition.reset.timestampChanges) {- previouslyMatchedAssetStates.removeIf(previousAssetState -> {- int index = matchedAssetStates.indexOf(previousAssetState);- if (index < 0) {- return false;- }+ if (hasActiveRecurTimer) {+ return false;+ }- boolean timestampChanged = previousAssetState.getTimestamp() != matchedAssetStates.get(index).getTimestamp();- if (timestampChanged) {- log(Level.FINER, "Rule trigger previously matched asset state timestamp has changed so resetting: " + previousAssetState);- }- return timestampChanged;- });- }+ int matchIndex = matchedAssetStates.indexOf(previousAssetState);+ boolean valueChangedOrNoLongerMatches = matchIndex < 0;- if (ruleCondition.reset != null && ruleCondition.reset.valueChanges) {- previouslyMatchedAssetStates.removeIf(previousAssetState -> {- int index = matchedAssetStates.indexOf(previousAssetState);- if (index < 0) {- return false;- }+ // If reset on value change and still matches check to see if the value has changed+ if (!valueChangedOrNoLongerMatches && ruleCondition.resetOnValueChange) {+ valueChangedOrNoLongerMatches = !Objects.equals(previousAssetState.getValue().orElse(null), matchedAssetStates.get(matchIndex).getValue().orElse(null));+ }- boolean valueChanged = !Objects.equals(previousAssetState.getValue().orElse(null), matchedAssetStates.get(index).getValue().orElse(null));- if (valueChanged) {- log(Level.FINER, "Rule trigger previously matched asset state value has changed so resetting: " + previousAssetState);- }- return valueChanged;- });- }+ if (valueChangedOrNoLongerMatches) {+ log(Level.FINER, "Rule trigger previously matched asset state value has changed or no longer matches so resetting: " + previousAssetState);+ }++ return valueChangedOrNoLongerMatches;+ });// Filter out previous matches to avoid re-triggeringmatchedAssetStates.removeIf(previouslyMatchedAssetStates::contains);+// Select unique asset states based on asset idStream<AssetState> matchedAssetStateStream = matchedAssetStates.stream().filter(distinctByKey(AssetState::getId));+// Order asset states before applying limitif (orderBy != null) {matchedAssetStateStream = matchedAssetStateStream.sorted(RulesFacts.asComparator(orderBy));@@ -336,8 +300,8 @@ public class JsonRulesBuilder extends RulesBuilder {if (limit > 0) {matchedAssetStateStream = matchedAssetStateStream.limit(limit);}- Collection<String> matchedAssetIds = matchedAssetStateStream.map(AssetState::getId).collect(Collectors.toList());+ Collection<String> matchedAssetIds = matchedAssetStateStream.map(AssetState::getId).collect(Collectors.toList());if (trackUnmatched) {// Select unique asset states based on asset id@@ -350,35 +314,38 @@ public class JsonRulesBuilder extends RulesBuilder {.collect(Collectors.toList());}- lastTriggerResult = new RuleConditionTriggerResult((!matchedAssetIds.isEmpty() || (trackUnmatched && !unmatchedAssetIds.isEmpty())), matchedAssetStates, matchedAssetIds, unmatchedAssetStates, unmatchedAssetIds);- log(Level.FINEST, "Rule trigger result: " + lastTriggerResult);+ lastEvaluationResult = new RuleConditionEvaluationResult((!matchedAssetIds.isEmpty() || (trackUnmatched && !unmatchedAssetIds.isEmpty())), matchedAssetStates, matchedAssetIds, unmatchedAssetStates, unmatchedAssetIds);+ log(Level.FINEST, "Rule evaluation result: " + lastEvaluationResult);}Collection<String> getMatchedAssetIds() {- if (lastTriggerResult == null) {+ if (lastEvaluationResult == null) {return Collections.emptyList();}- return lastTriggerResult.matchedAssetIds;+ return lastEvaluationResult.matchedAssetIds;}Collection<String> getUnmatchedAssetIds() {- if (lastTriggerResult == null) {+ if (lastEvaluationResult == null) {return Collections.emptyList();}- return lastTriggerResult.unmatchedAssetIds;+ return lastEvaluationResult.unmatchedAssetIds;}}- static class RuleConditionTriggerResult {+ /**+ * This contains the results of a rule condition trigger evaluation.+ */+ static class RuleConditionEvaluationResult {boolean matches;Collection<AssetState> matchedAssetStates;Collection<AssetState> unmatchedAssetStates;Collection<String> matchedAssetIds;Collection<String> unmatchedAssetIds;- public RuleConditionTriggerResult(boolean matches, Collection<AssetState> matchedAssetStates, Collection<String> matchedAssetIds, Collection<AssetState> unmatchedAssetStates, Collection<String> unmatchedAssetIds) {+ public RuleConditionEvaluationResult(boolean matches, Collection<AssetState> matchedAssetStates, Collection<String> matchedAssetIds, Collection<AssetState> unmatchedAssetStates, Collection<String> unmatchedAssetIds) {this.matches = matches;this.matchedAssetStates = matchedAssetStates;this.matchedAssetIds = matchedAssetIds;@@ -388,7 +355,7 @@ public class JsonRulesBuilder extends RulesBuilder {@Overridepublic String toString() {- return RuleConditionTriggerResult.class.getSimpleName() + "{" ++ return RuleConditionEvaluationResult.class.getSimpleName() + "{" +"matches=" + matches +", matchedAssetStates=" + matchedAssetStates.size() +", unmatchedAssetStates=" + unmatchedAssetStates.size() +@@ -398,13 +365,18 @@ public class JsonRulesBuilder extends RulesBuilder {}}- static class RuleEvaluationResult {+ /**+ * Stores the state of the overall rule and each {@link RuleCondition}.+ */+ static class RuleState {protected Map<String, RuleConditionState> conditionStateMap;protected List<String> thenMatchedAssetIds = new ArrayList<>();protected List<String> otherwiseMatchedAssetIds = new ArrayList<>();+ protected long nextRecur;+ protected Map<String, Long> nextRecurAssetIdMap = new HashMap<>();- public RuleEvaluationResult(Map<String, RuleConditionState> conditionStateMap) {+ public RuleState(Map<String, RuleConditionState> conditionStateMap) {this.conditionStateMap = conditionStateMap;}@@ -417,11 +389,6 @@ public class JsonRulesBuilder extends RulesBuilder {}}- enum TargetType {- ASSET,- USER- }-public static final String PLACEHOLDER_RULESET_ID = "%RULESET_ID%";public static final String PLACEHOLDER_RULESET_NAME = "%RULESET_NAME%";public static final String PLACEHOLDER_TRIGGER_ASSETS = "%TRIGGER_ASSETS%";@@ -430,13 +397,13 @@ public class JsonRulesBuilder extends RulesBuilder {final protected TimerService timerService;final protected Assets assetsFacade;final protected Users usersFacade;- final protected NotificationsFacade notificationsFacade;+ final protected NotificationsFacade<?> notificationsFacade;final protected ManagerExecutorService executorService;final protected BiConsumer<Runnable, Long> scheduledActionConsumer;- final protected Map<String, RuleEvaluationResult> ruleEvaluationMap = new HashMap<>();+ final protected Map<String, RuleState> ruleEvaluationMap = new HashMap<>();final protected JsonRule[] jsonRules;- public JsonRulesBuilder(Ruleset ruleset, TimerService timerService, AssetStorageService assetStorageService, ManagerExecutorService executorService, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {+ public JsonRulesBuilder(Ruleset ruleset, TimerService timerService, AssetStorageService assetStorageService, ManagerExecutorService executorService, Assets assetsFacade, Users usersFacade, NotificationsFacade<?> notificationsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {this.timerService = timerService;this.assetStorageService = assetStorageService;this.executorService = executorService;@@ -455,42 +422,39 @@ public class JsonRulesBuilder extends RulesBuilder {throw new IllegalArgumentException("No rules within ruleset so nothing to start: " + ruleset);}- this.jsonRules = jsonRulesetDefinition.rules;- Arrays.stream(jsonRules).forEach(this::add);+ jsonRules = jsonRulesetDefinition.rules;++ for (JsonRule jsonRule : jsonRules) {+ add(jsonRule);+ }}public void stop(RulesFacts facts) {Arrays.stream(jsonRules).forEach(jsonRule ->- executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, timerService, assetStorageService, this.scheduledActionConsumer));+ executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, this.scheduledActionConsumer));}public void start(RulesFacts facts) {Arrays.stream(jsonRules).forEach(jsonRule ->- executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, timerService, assetStorageService, this.scheduledActionConsumer));+ executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, this.scheduledActionConsumer));// Initialise asset states- onAssetStatesChanged(facts);-- // Initialise trigger state - prevents rules firing based on initial asset states- Arrays.stream(jsonRules).forEach(jsonRule -> {- log(Level.FINEST, "Initialising rule trigger states for rule: " + jsonRule.name);- ruleEvaluationMap.get(jsonRule.name).conditionStateMap.values().forEach(RuleConditionState::update);- });+ onAssetStatesChanged(facts, null);}- public void onAssetStatesChanged(RulesFacts facts) {- ruleEvaluationMap.values().forEach(triggerStateMap -> triggerStateMap.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts)));+ public void onAssetStatesChanged(RulesFacts facts, RulesEngine.AssetStateChangeEvent event) {+ ruleEvaluationMap.values().forEach(triggerStateMap -> triggerStateMap.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts, event)));}- protected JsonRulesBuilder add(JsonRule rule) {+ protected JsonRulesBuilder add(JsonRule rule) throws Exception {if (ruleEvaluationMap.containsKey(rule.name)) {throw new IllegalArgumentException("Rules must have a unique name within a ruleset, rule name '" + rule.name + "' already used");}- RuleEvaluationResult ruleEvaluationResult = new RuleEvaluationResult(new HashMap<>());+ RuleState ruleEvaluationResult = new RuleState(new HashMap<>());ruleEvaluationMap.put(rule.name, ruleEvaluationResult);- addRuleTriggerStates(rule.when, rule.otherwise != null, 0, ruleEvaluationResult.conditionStateMap, rule.reset);+ addRuleConditionStates(rule.when, rule.otherwise != null, 0, ruleEvaluationResult.conditionStateMap);Condition condition = buildLhsCondition(rule, ruleEvaluationResult);Action action = buildRhsAction(rule, ruleEvaluationResult);@@ -520,49 +484,51 @@ public class JsonRulesBuilder extends RulesBuilder {return this;}- protected void addRuleTriggerStates(LogicGroup<RuleCondition> ruleConditionGroup, boolean trackUnmatched, int index, Map<String, RuleConditionState> triggerStateMap, RuleConditionReset defaultReset) {+ protected void addRuleConditionStates(LogicGroup<RuleCondition> ruleConditionGroup, boolean trackUnmatched, int index, Map<String, RuleConditionState> triggerStateMap) throws Exception {if (ruleConditionGroup != null) {if (ruleConditionGroup.getItems().size() > 0) {for (RuleCondition ruleCondition : ruleConditionGroup.getItems()) {if (TextUtil.isNullOrEmpty(ruleCondition.tag)) {ruleCondition.tag = Integer.toString(index);}- if (ruleCondition.reset == null) {- ruleCondition.reset = defaultReset;- }triggerStateMap.put(ruleCondition.tag, new RuleConditionState(ruleCondition, trackUnmatched, timerService));index++;}}if (ruleConditionGroup.groups != null && ruleConditionGroup.groups.size() > 0) {for (LogicGroup<RuleCondition> childRuleTriggerCondition : ruleConditionGroup.groups) {- addRuleTriggerStates(childRuleTriggerCondition, trackUnmatched, index, triggerStateMap, defaultReset);+ addRuleConditionStates(childRuleTriggerCondition, trackUnmatched, index, triggerStateMap);}}}}- protected Condition buildLhsCondition(JsonRule rule, RuleEvaluationResult ruleEvaluationResult) {+ protected Condition buildLhsCondition(JsonRule rule, RuleState ruleState) {if (rule.when == null) {return null;}return facts -> {+ // Check if next recurrence in the future+ if (ruleState.nextRecur > timerService.getCurrentTimeMillis()) {+ return false;+ }+// Update each trigger state- log(Level.FINEST, "Updating rule trigger states for rule: " + rule.name);- ruleEvaluationResult.conditionStateMap.values().forEach(RuleConditionState::update);+ log(Level.FINEST, "Updating rule condition states for rule: " + rule.name);+ ruleState.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.update(ruleState.nextRecurAssetIdMap));// Apply group operator and extract resulting matched asset IDs- Pair<List<String>, List<String>> matchedUnmatchedGroupResults = getGroupLastTriggerResults(rule.when, ruleEvaluationResult.conditionStateMap, rule.otherwise != null);- ruleEvaluationResult.thenMatchedAssetIds = matchedUnmatchedGroupResults.key;- ruleEvaluationResult.otherwiseMatchedAssetIds = matchedUnmatchedGroupResults.value;+ Pair<List<String>, List<String>> matchedUnmatchedGroupResults = getGroupLastTriggerResults(rule.when, ruleState.conditionStateMap, rule.otherwise != null);+ ruleState.thenMatchedAssetIds = matchedUnmatchedGroupResults.key;+ ruleState.otherwiseMatchedAssetIds = matchedUnmatchedGroupResults.value;- return ruleEvaluationResult.thenMatched() || ruleEvaluationResult.otherwiseMatched();+ return ruleState.thenMatched() || ruleState.otherwiseMatched();};}- protected Action buildRhsAction(JsonRule rule, RuleEvaluationResult ruleEvaluationResult) {+ protected Action buildRhsAction(JsonRule rule, RuleState ruleState) {if (rule.then == null) {return null;@@ -572,54 +538,58 @@ public class JsonRulesBuilder extends RulesBuilder {try {log(Level.FINER, "Triggered rule so executing 'then' actions for rule: " + rule.name);- if (ruleEvaluationResult.thenMatched()) {- executeRuleActions(rule, rule.then, "then", false, facts, ruleEvaluationResult, assetsFacade, usersFacade, notificationsFacade, timerService, assetStorageService, scheduledActionConsumer);+ if (ruleState.thenMatched()) {+ executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, scheduledActionConsumer);}- if (rule.otherwise != null && ruleEvaluationResult.otherwiseMatched()) {+ if (rule.otherwise != null && ruleState.otherwiseMatched()) {log(Level.FINER, "Triggered rule so executing 'otherwise' actions for rule: " + rule.name);- executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleEvaluationResult, assetsFacade, usersFacade, notificationsFacade, timerService, assetStorageService, scheduledActionConsumer);+ executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, scheduledActionConsumer);}} catch (Exception e) {log(Level.SEVERE, "Exception thrown during rule RHS execution", e);throw e;} finally {- ruleEvaluationResult.conditionStateMap.values().forEach(triggerState -> triggerState.lastTriggerResult = null);++ // Clear out expired recurrence timers+ ruleState.nextRecurAssetIdMap.entrySet().removeIf(entry -> entry.getValue() <= timerService.getCurrentTimeMillis());++ // Store recurrence times as required+ boolean recurPerAsset = rule.recurrence == null || rule.recurrence.scope != RuleRecurrence.Scope.GLOBAL;+ long currentTime = timerService.getCurrentTimeMillis();+ long nextRecur = rule.recurrence == null || rule.recurrence.mins == null ? Long.MAX_VALUE : currentTime + rule.recurrence.mins;++ if (nextRecur > currentTime) {+ if (recurPerAsset) {+ ruleState.thenMatchedAssetIds.forEach(assetId -> ruleState.nextRecurAssetIdMap.put(assetId, nextRecur));+ } else {+ ruleState.nextRecur = nextRecur;+ }+ }++ // Store last evaluation results in state+ ruleState.conditionStateMap.values().forEach(ruleConditionState -> {+ if (ruleConditionState.lastEvaluationResult != null) {++ // Replace any stale matched asset states (values may have changed equality is by asset ID and attribute name)+ // only need up to date values in the previously matched asset states previously unmatched asset states is only+ // used to compare asset ID and attribute name.+ ruleConditionState.previouslyMatchedAssetStates.removeAll(ruleConditionState.lastEvaluationResult.matchedAssetStates);+ ruleConditionState.previouslyMatchedAssetStates.addAll(ruleConditionState.lastEvaluationResult.matchedAssetStates);++ if (ruleConditionState.trackUnmatched) {+ ruleConditionState.previouslyUnmatchedAssetStates.addAll(ruleConditionState.lastEvaluationResult.unmatchedAssetStates);+ }+ }+ });++ // Clear last results+ ruleState.conditionStateMap.values().forEach(triggerState -> triggerState.lastEvaluationResult = null);}};}- public static void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleEvaluationResult ruleEvaluationResult, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, TimerService timerService, AssetStorageService assetStorageService, BiConsumer<Runnable, Long> scheduledActionConsumer) {-- // Push rule trigger results into the trigger state for future runs and store timestamps where required- if (ruleEvaluationResult != null && ruleEvaluationResult.conditionStateMap != null) {- ruleEvaluationResult.conditionStateMap.values().forEach(ruleConditionState -> {- if (ruleConditionState.lastTriggerResult != null) {-- // Replace any stale matched asset states (values may have changed equality is by asset ID and attribute name)- // only need up to date values in the previously matched asset states previously unmatched asset states is only- // used to compare asset ID and attribute name.- ruleConditionState.previouslyMatchedAssetStates.removeAll(ruleConditionState.lastTriggerResult.matchedAssetStates);- ruleConditionState.previouslyMatchedAssetStates.addAll(ruleConditionState.lastTriggerResult.matchedAssetStates);-- RuleConditionReset reset = ruleConditionState.ruleCondition.reset;- if (ruleConditionResetHasTimer(reset)) {- if (ruleConditionState.resetDurationMillis > 0) {- if (ruleConditionState.resetDurationMillis == Long.MAX_VALUE) {- ruleConditionState.lastTriggerResult.matchedAssetStates.forEach(assetState ->- ruleConditionState.previouslyMatchedExpiryTimes.put(assetState, ruleConditionState.resetDurationMillis));- } else {- ruleConditionState.lastTriggerResult.matchedAssetStates.forEach(assetState ->- ruleConditionState.previouslyMatchedExpiryTimes.put(assetState, timerService.getCurrentTimeMillis() + ruleConditionState.resetDurationMillis));- }- }- }- if (ruleConditionState.trackUnmatched) {- ruleConditionState.previouslyUnmatchedAssetStates.addAll(ruleConditionState.lastTriggerResult.unmatchedAssetStates);- }- }- });- }+ public static void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, NotificationsFacade<?> notificationsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {if (ruleActions != null && ruleActions.length > 0) {@@ -635,11 +605,11 @@ public class JsonRulesBuilder extends RulesBuilder {i,useUnmatched,facts,- ruleEvaluationResult,+ ruleState,assetsFacade,usersFacade,- notificationsFacade,- assetStorageService);+ notificationsFacade+ );if (actionExecution != null) {delay += actionExecution.delay;@@ -665,7 +635,7 @@ public class JsonRulesBuilder extends RulesBuilder {.collect(Collectors.toList());}- protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleEvaluationResult ruleEvaluationResult, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, AssetStorageService assetStorageService) {+ protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, NotificationsFacade<?> notificationsFacade) {if (ruleAction instanceof RuleActionNotification) {RuleActionNotification notificationAction = (RuleActionNotification) ruleAction;@@ -689,7 +659,7 @@ public class JsonRulesBuilder extends RulesBuilder {try {notification = JSON.readValue(JSON.writeValueAsString(notification), Notification.class);email = (EmailNotificationMessage) notification.getMessage();- String triggeredAssetInfo = buildTriggeredAssetInfo(useUnmatched, ruleEvaluationResult, isHtml);+ String triggeredAssetInfo = buildTriggeredAssetInfo(useUnmatched, ruleState, isHtml);body = body.replace(PLACEHOLDER_TRIGGER_ASSETS, triggeredAssetInfo);if (isHtml) {email.setHtml(body);@@ -705,7 +675,7 @@ public class JsonRulesBuilder extends RulesBuilder {// Override the notification targets if set in the ruleNotification.TargetType targetType = targetIsNotAssets(ruleAction.target) ? Notification.TargetType.USER : Notification.TargetType.ASSET;- Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleEvaluationResult, assetsFacade, usersFacade, facts);+ Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts);if (ids != null && !ids.isEmpty()) {notification.setTargets(ids.stream().map(id -> new Notification.Target(targetType, id)).collect(Collectors.toList()));@@ -730,7 +700,7 @@ public class JsonRulesBuilder extends RulesBuilder {return null;}- Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleEvaluationResult, assetsFacade, usersFacade, facts);+ Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts);if (ids == null || ids.isEmpty()) {log(Level.FINEST, "No targets for write attribute rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);@@ -771,7 +741,7 @@ public class JsonRulesBuilder extends RulesBuilder {if (ruleAction.target != null && ruleAction.target.users != null) {throw new IllegalStateException("Cannot use action type '" + RuleActionUpdateAttribute.class.getSimpleName() + "' with user target");}- matchingAssetIds = new ArrayList<>(getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleEvaluationResult, assetsFacade, usersFacade, facts));+ matchingAssetIds = new ArrayList<>(getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts));} else {matchingAssetIds = facts.matchAssetState(ruleAction.target.assets)@@ -876,7 +846,7 @@ public class JsonRulesBuilder extends RulesBuilder {return null;}- private static String buildTriggeredAssetInfo(boolean useUnmatched, RuleEvaluationResult ruleEvaluationResult, boolean isHtml) {+ private static String buildTriggeredAssetInfo(boolean useUnmatched, RuleState ruleEvaluationResult, boolean isHtml) {List<String> assetIds = useUnmatched ? ruleEvaluationResult.otherwiseMatchedAssetIds : ruleEvaluationResult.thenMatchedAssetIds;@@ -886,11 +856,11 @@ public class JsonRulesBuilder extends RulesBuilder {// Extract asset states for matched asset IDsMap<String, Set<AssetState>> assetStates = ruleEvaluationResult.conditionStateMap.values().stream()- .filter(conditionState -> conditionState.lastTriggerResult.matches)+ .filter(conditionState -> conditionState.lastEvaluationResult.matches).flatMap(conditionState -> {Collection<AssetState> as = useUnmatched- ? conditionState.lastTriggerResult.unmatchedAssetStates- : conditionState.lastTriggerResult.matchedAssetStates;+ ? conditionState.lastEvaluationResult.unmatchedAssetStates+ : conditionState.lastEvaluationResult.matchedAssetStates;return as.stream();}).filter(assetState -> assetIds.contains(assetState.getId()))@@ -928,9 +898,9 @@ public class JsonRulesBuilder extends RulesBuilder {return sb.toString();}- protected static Collection<String> getRuleActionTargetIds(RuleActionTarget target, boolean useUnmatched, RuleEvaluationResult ruleEvaluationResult, Assets assetsFacade, Users usersFacade, RulesFacts facts) {+ protected static Collection<String> getRuleActionTargetIds(RuleActionTarget target, boolean useUnmatched, RuleState ruleState, Assets assetsFacade, Users usersFacade, RulesFacts facts) {- Map<String, RuleConditionState> conditionStateMap = ruleEvaluationResult.conditionStateMap;+ Map<String, RuleConditionState> conditionStateMap = ruleState.conditionStateMap;if (target != null) {if (!TextUtil.isNullOrEmpty(target.ruleConditionTag) && conditionStateMap != null) {@@ -942,7 +912,7 @@ public class JsonRulesBuilder extends RulesBuilder {return triggerState != null ? triggerState.getUnmatchedAssetIds() : Collections.emptyList();}- if (target.matchedAssets != null) {+ if (conditionStateMap != null && target.matchedAssets != null) {List<String> compareAssetIds = conditionStateMap.values().stream().flatMap(triggerState ->useUnmatched ? triggerState.getUnmatchedAssetIds().stream() : triggerState.getMatchedAssetIds().stream())@@ -996,7 +966,7 @@ public class JsonRulesBuilder extends RulesBuilder {// Find asset IDs that are matched in all rule conditionsmatchedAssetIds.addAll(ruleConditionGroup.getItems().stream().map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.lastTriggerResult != null && ruleConditionState.lastTriggerResult.matches) //Only trigger results which matches+ .filter(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches) //Only trigger results which matches.map(RuleConditionState::getMatchedAssetIds)//Get all matched assetIds.flatMap(Collection::stream).collect(Collectors.groupingBy(assetId -> assetId, Collectors.counting())) // Group them and count the number of times appearing in the rule conditions@@ -1010,7 +980,7 @@ public class JsonRulesBuilder extends RulesBuilder {matchedAssetIds.addAll(ruleConditionGroup.getItems().stream().map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.lastTriggerResult != null && ruleConditionState.lastTriggerResult.matches)+ .filter(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches).map(RuleConditionState::getMatchedAssetIds)//Get all unmatched assetIds.flatMap(Collection::stream).distinct()@@ -1022,7 +992,7 @@ public class JsonRulesBuilder extends RulesBuilder {// Unmatched we don't apply group AND/OR just collate them allunmatchedAssetIds.addAll(ruleConditionGroup.getItems().stream().map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.trackUnmatched && ruleConditionState.lastTriggerResult != null && ruleConditionState.lastTriggerResult.matches)+ .filter(ruleConditionState -> ruleConditionState.trackUnmatched && ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches).map(RuleConditionState::getUnmatchedAssetIds)//Get all unmatched assetIds.flatMap(Collection::stream).distinct()@@ -1041,40 +1011,10 @@ public class JsonRulesBuilder extends RulesBuilder {return new Pair<>(matchedAssetIds, unmatchedAssetIds);}- protected static boolean ruleConditionResetHasTimer(RuleConditionReset reset) {- return reset != null && (!TextUtil.isNullOrEmpty(reset.timer));- }-protected static boolean targetIsNotAssets(RuleActionTarget target) {return target != null && target.users != null;}- protected static boolean checkRuleValidity(long currentMillis, DateTimePredicate dateTimePredicate) {- Pair<Long, Long> fromAndTo = AssetQueryPredicate.asFromAndTo(currentMillis, dateTimePredicate);- boolean isValid = false;- switch (dateTimePredicate.operator) {- case BETWEEN:- isValid = currentMillis >= fromAndTo.key && currentMillis < fromAndTo.value;- break;- case EQUALS:- isValid = currentMillis == fromAndTo.key;- break;- case LESS_THAN:- isValid = currentMillis < fromAndTo.key;- break;- case LESS_EQUALS:- isValid = currentMillis <= fromAndTo.key;- break;- case GREATER_THAN:- isValid = currentMillis > fromAndTo.key;- break;- case GREATER_EQUALS:- isValid = currentMillis >= fromAndTo.key;- break;- }- return isValid;- }-protected static void log(Level level, String message) {RulesEngine.RULES_LOG.log(level, LOG_PREFIX + message);}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 1f51cb760..3e866f622 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -21,6 +21,7 @@ package org.openremote.manager.rules;import org.jeasy.rules.core.InferenceRulesEngine;import org.jeasy.rules.core.RulesEngineParameters;+import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetProcessingService;import org.openremote.manager.asset.AssetStorageService;@@ -52,6 +53,19 @@ import static org.openremote.model.rules.RulesetStatus.*;public class RulesEngine<T extends Ruleset> {+ /**+ * Allows rule deployments to track changes to the {@link AssetState}s in scope+ */+ public static final class AssetStateChangeEvent {+ public PersistenceEvent.Cause cause;+ public AssetState assetState;++ public AssetStateChangeEvent(PersistenceEvent.Cause cause, AssetState assetState) {+ this.cause = cause;+ this.assetState = assetState;+ }+ }+/*** Identifies a set of {@link LocationAttributePredicate}s associated with a particular {@link Asset}*/@@ -86,8 +100,8 @@ public class RulesEngine<T extends Ruleset> {public static final Logger STATS_LOG = Logger.getLogger("org.openremote.rules.RulesEngineStats");// Here to facilitate testing- protected static BiConsumer<RulesEngine, RulesetDeployment> PAUSE_SCHEDULER = RulesEngine::schedulePause;- protected static BiConsumer<RulesEngine, RulesetDeployment> UNPAUSE_SCHEDULER = RulesEngine::scheduleUnpause;+ protected static BiConsumer<RulesEngine<?>, RulesetDeployment> PAUSE_SCHEDULER = RulesEngine::schedulePause;+ protected static BiConsumer<RulesEngine<?>, RulesetDeployment> UNPAUSE_SCHEDULER = RulesEngine::scheduleUnpause;final protected TimerService timerService;final protected ManagerExecutorService executorService;@@ -97,7 +111,7 @@ public class RulesEngine<T extends Ruleset> {final protected RulesEngineId<T> id;final protected Assets assetsFacade;final protected Users usersFacade;- final protected NotificationsFacade notificationFacade;+ final protected NotificationsFacade<T> notificationFacade;final protected AssetLocationPredicateProcessor assetLocationPredicatesConsumer;final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();@@ -107,11 +121,10 @@ public class RulesEngine<T extends Ruleset> {protected boolean running;protected long lastFireTimestamp;protected boolean trackLocationPredicates;- protected ScheduledFuture fireTimer;- protected ScheduledFuture statsTimer;- protected Map<Long, ScheduledFuture> pauseTimers = new HashMap<>();- protected Map<Long, ScheduledFuture> unpauseTimers = new HashMap<>();- protected boolean assetStatesChanged = false;+ protected ScheduledFuture<?> fireTimer;+ protected ScheduledFuture<?> statsTimer;+ protected Map<Long, ScheduledFuture<?>> pauseTimers = new HashMap<>();+ protected Map<Long, ScheduledFuture<?>> unpauseTimers = new HashMap<>();// Only used to optimize toString(), contains the details of this engineprotected String deploymentInfo;@@ -276,7 +289,7 @@ public class RulesEngine<T extends Ruleset> {publishRulesetStatus(deployment);deployments.remove(ruleset.getId());- ScheduledFuture timer = pauseTimers.remove(ruleset.getId());+ ScheduledFuture<?> timer = pauseTimers.remove(ruleset.getId());if (timer != null) timer.cancel(true);timer = unpauseTimers.remove(ruleset.getId());if (timer != null) timer.cancel(true);@@ -304,13 +317,13 @@ public class RulesEngine<T extends Ruleset> {LOG.info("Starting: " + this);running = true;- trackLocationPredicates = true;+ trackLocationPredicates(true);deployments.values().forEach(this::startRuleset);updateDeploymentInfo();publishRulesEngineStatus();- fire();+ scheduleFire();// Start a background stats printer if INFO level logging is enabledif (STATS_LOG.isLoggable(Level.INFO) || STATS_LOG.isLoggable(Level.FINEST)) {@@ -323,7 +336,20 @@ public class RulesEngine<T extends Ruleset> {}}+ protected void trackLocationPredicates(boolean track) {+ if (trackLocationPredicates == track) {+ return;+ }+ trackLocationPredicates = track;+ if (track) {+ facts.startTrackingLocationRules();+ } else {+ if (assetLocationPredicatesConsumer != null) {+ processLocationRules(facts.stopTrackingLocationRules());+ }+ }+ }public void stop() {stop(false);}@@ -400,7 +426,7 @@ public class RulesEngine<T extends Ruleset> {}}- public void fire() {+ public void scheduleFire() {withLock(toString() + "::scheduleFire", () -> {// Schedule a firing within the guaranteed expiration time (so not immediately), and// only if the last firing is done. This effectively limits how often the rules engine@@ -422,7 +448,7 @@ public class RulesEngine<T extends Ruleset> {if ((facts.hasTemporaryFacts() || (hadTemporaryFactsBefore && !facts.hasTemporaryFacts()))&& !disableTemporaryFactExpiration) {LOG.fine("Temporary facts require firing rules on: " + this);- executorService.schedule(this::fire, 0);+ executorService.schedule(this::scheduleFire, 0);} else if (!disableTemporaryFactExpiration) {LOG.fine("No temporary facts present/changed when firing rules on: " + this);}@@ -450,10 +476,6 @@ public class RulesEngine<T extends Ruleset> {// Remove any expired temporary factsfacts.removeExpiredTemporaryFacts();- // Notify rulesets if assetstates changed- boolean notifyAssetStatesChanged = assetStatesChanged;- assetStatesChanged = false;-for (RulesetDeployment deployment : deployments.values()) {try {@@ -470,10 +492,6 @@ public class RulesEngine<T extends Ruleset> {// Reset facts for this firing (loop detection etc.)facts.reset();- if (notifyAssetStatesChanged) {- deployment.onAssetStatesChanged(facts);- }-long startTimestamp = System.currentTimeMillis();lastFireTimestamp = startTimestamp;engine.fire(deployment.getRules(), facts);@@ -498,38 +516,41 @@ public class RulesEngine<T extends Ruleset> {}}- if (trackLocationPredicates) {- trackLocationPredicates = false;- if (assetLocationPredicatesConsumer != null) {- processLocationRules(facts.stopTrackingLocationRules());+ trackLocationPredicates(false);+ }++ protected void notifyAssetStatesChanged(AssetStateChangeEvent event) {+ for (RulesetDeployment deployment : deployments.values()) {+ if (!deployment.isError()) {+ deployment.onAssetStatesChanged(facts, event);}}}- public void updateFact(AssetState assetState, boolean fireImmediately) {- assetStatesChanged = true;+ public void updateOrInsertAssetState(AssetState assetState, boolean insert) {facts.putAssetState(assetState);- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getAttributeName());- if (running && fireImmediately) {- fire();+ // Make sure location predicate tracking is activated before notifying the deployments otherwise they won't report location predicates+ trackLocationPredicates(trackLocationPredicates || (insert && assetState.getAttributeName().equals(AttributeType.LOCATION.getAttributeName())));+ notifyAssetStatesChanged(new AssetStateChangeEvent(insert ? PersistenceEvent.Cause.CREATE : PersistenceEvent.Cause.UPDATE, assetState));+ if (running) {+ scheduleFire();}}- public void removeFact(AssetState assetState) {- assetStatesChanged = true;+ public void removeAssetState(AssetState assetState) {facts.removeAssetState(assetState);- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getAttributeName());+ // Make sure location predicate tracking is activated before notifying the deployments otherwise they won't report location predicates+ trackLocationPredicates(trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getAttributeName()));+ notifyAssetStatesChanged(new AssetStateChangeEvent(PersistenceEvent.Cause.DELETE, assetState));if (running) {- fire();+ scheduleFire();}}- public void insertFact(String expires, AssetState assetState) {- assetStatesChanged = true;+ public void insertAssetEvent(String expires, AssetState assetState) {facts.insertAssetEvent(expires, assetState);- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getAttributeName());if (running) {- fire();+ scheduleFire();}}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex b1befb046..5b92050b8 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -114,7 +114,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected RulesEngine<GlobalRuleset> globalEngine;protected Tenant[] tenants;protected AssetLocationPredicateProcessor locationPredicateRulesConsumer;- protected Map<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();+ protected Map<RulesEngine<?>, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();protected Set<String> assetsWithModifiedLocationPredicates = new HashSet<>();// Keep global list of asset states that have been pushed to any engines// The objects are already in memory inside the rule engines but keeping them@@ -254,19 +254,25 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.setFullyPopulate(true)));LOG.info("Loading all assets with fact attributes to initialize state of rules engines");- Stream<Pair<Asset, Stream<AssetAttribute>>> assetRuleAttributes = findRuleStateAttributes();+ Stream<Pair<Asset, Stream<AssetAttribute>>> stateAttributes = findRuleStateAttributes();- // Push each rule attribute as an asset update through the rule engine chain+ // Push each attribute as an asset update through the rule engine chain// that will ensure the insert only happens to the engines in scope- assetRuleAttributes+ stateAttributes.forEach(pair -> {Asset asset = pair.key;pair.value.forEach(ruleAttribute -> {AssetState assetState = new AssetState(asset, ruleAttribute, Source.INTERNAL);- updateAssetState(assetState, true, true);+ updateAssetState(assetState);});});+ // Start the engines+ if (globalEngine != null) {+ globalEngine.start();+ }+ tenantEngines.values().forEach(RulesEngine::start);+ assetEngines.values().forEach(RulesEngine::start);}@Override@@ -302,11 +308,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// First as asset stateif (attribute.isRuleState()) {- updateAssetState(- new AssetState(asset, attribute, source),- false, // Don't skip the error check on the rules engines- !attribute.isRuleEvent() // If it's not a rule event, fire immediately- );+ updateAssetState(new AssetState(asset, attribute, source));}// Then as asset event (if there wasn't an error), this will also fire the rules engines@@ -375,7 +377,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.setRealm(tenant.getRealm()).setFullyPopulate(true).setEnabledOnly(true))- .forEach(this::deployTenantRuleset);+ .stream()+ .map(this::deployTenantRuleset)+ .filter(Objects::nonNull)+ .forEach(RulesEngine::start);// Create any asset rules engines for assets in this realm that have rulesetsdeployAssetRulesets(@@ -384,7 +389,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Assenew RulesetQuery().setRealm(tenant.getRealm()).setEnabledOnly(true)- .setFullyPopulate(true)));+ .setFullyPopulate(true)))+ .forEach(RulesEngine::start);}});}@@ -416,7 +422,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseAssetState assetState = buildAssetState.apply(loadedAsset, attribute);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + assetState);- updateAssetState(assetState, true, true);+ updateAssetState(assetState);});break;}@@ -461,7 +467,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.forEach(newFactAttribute -> {AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);- updateAssetState(assetState, true, true);+ updateAssetState(assetState);});break;}@@ -470,9 +476,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseasset.getAttributesStream().filter(AssetAttribute::isRuleState).forEach(attribute -> {- // We can't load the asset again (it was deleted), so don't use buildAssetState() and- // hope that the path of the event asset has been loaded before deletion, although it is- // "unlikely" anybody will access it during retraction...AssetState assetState = new AssetState(asset, attribute, Source.INTERNAL);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);retractAssetState(assetState);@@ -495,21 +498,21 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse} else {if (ruleset instanceof GlobalRuleset) {- RulesEngine newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);+ RulesEngine<GlobalRuleset> newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);if (newEngine != null) {- // Push all existing facts into the engine, this is an initial import of state so fire delayed- assetStates.forEach(assetState -> newEngine.updateFact(assetState, false));+ // Push all existing facts into the engine+ assetStates.forEach(assetState -> newEngine.updateOrInsertAssetState(assetState, true));newEngine.start();}} else if (ruleset instanceof TenantRuleset) {- RulesEngine newEngine = deployTenantRuleset((TenantRuleset) ruleset);+ RulesEngine<TenantRuleset> newEngine = deployTenantRuleset((TenantRuleset) ruleset);if (newEngine != null) {- // Push all existing facts into the engine, this is an initial import of state so fire delayed+ // Push all existing facts into the engineassetStates.forEach(assetState -> {if (assetState.getRealm().equals(((TenantRuleset) ruleset).getRealm())) {- newEngine.updateFact(assetState, false);+ newEngine.updateOrInsertAssetState(assetState, true);}});newEngine.start();@@ -519,13 +522,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// Must reload from the database, the ruleset might not be completely hydrated on CREATE or UPDATEAssetRuleset assetRuleset = rulesetStorageService.find(AssetRuleset.class, ruleset.getId());- RulesEngine newEngine = deployAssetRuleset(assetRuleset);+ RulesEngine<AssetRuleset> newEngine = deployAssetRuleset(assetRuleset);if (newEngine != null) {- // Push all existing facts for this asset (and it's children into the engine), this is an- // initial import of state so fire delayed+ // Push all existing facts for this asset (and it's children into the engine)getAssetStatesInScope(((AssetRuleset) ruleset).getAssetId())- .forEach(assetState -> newEngine.updateFact(assetState, false));-+ .forEach(assetState -> newEngine.updateOrInsertAssetState(assetState, true));newEngine.start();}}@@ -558,10 +559,6 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseglobalEngine.addRuleset(ruleset);- if (created) {- globalEngine.start();- }-return created ? globalEngine : null;});}@@ -602,10 +599,6 @@ public class RulesService extends RouteBuilder implements ContainerService, AssetenantRulesEngine.addRuleset(ruleset);- if (created.get()) {- tenantRulesEngine.start();- }-return created.get() ? tenantRulesEngine : null;});}@@ -624,8 +617,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse});}- protected void deployAssetRulesets(List<AssetRuleset> rulesets) {- rulesets+ protected Stream<RulesEngine<AssetRuleset>> deployAssetRulesets(List<AssetRuleset> rulesets) {+ return rulesets.stream().collect(Collectors.groupingBy(AssetRuleset::getAssetId)).entrySet()@@ -640,15 +633,16 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.filter(es -> Arrays.stream(tenants).anyMatch(at -> es.getKey().equals(at.getRealm())))- .forEach(es -> {+ .flatMap(es -> {List<Pair<Asset, List<AssetRuleset>>> tenantAssetAndRules = es.getValue();// RT: Not sure we need ordering here for starting engines so removing it// Order rulesets by asset hierarchy within this tenant- tenantAssetAndRules.stream()+ return tenantAssetAndRules.stream()//.sorted(Comparator.comparingInt(item -> item.key.getPath().length)).flatMap(assetAndRules -> assetAndRules.value.stream())- .forEach(this::deployAssetRuleset);+ .map(this::deployAssetRuleset)+ .filter(Objects::nonNull);});}@@ -675,10 +669,6 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseassetRulesEngine.addRuleset(ruleset);- if (created.get()) {- assetRulesEngine.start();- }-return created.get() ? assetRulesEngine : null;});}@@ -700,13 +690,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected void insertAssetEvent(AssetState assetState, String expires) {withLock(getClass().getSimpleName() + "::insertAssetEvent", () -> {// Get the chain of rule engines that we need to pass through- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());+ List<RulesEngine<?>> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());// Check that all engines in the scope are availableif (rulesEngines.stream().anyMatch(RulesEngine::isError)) {LOG.severe("At least one rules engine is in an error state, skipping: " + assetState);if (LOG.isLoggable(FINEST)) {- for (RulesEngine rulesEngine : rulesEngines) {+ for (RulesEngine<?> rulesEngine : rulesEngines) {if (rulesEngine.isError()) {LOG.log(FINEST, "Rules engine error state: " + rulesEngine, rulesEngine.getError());}@@ -716,46 +706,35 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse}// Pass through each engine- for (RulesEngine rulesEngine : rulesEngines) {- rulesEngine.insertFact(expires, assetState);+ for (RulesEngine<?> rulesEngine : rulesEngines) {+ rulesEngine.insertAssetEvent(expires, assetState);}});}- protected void updateAssetState(AssetState assetState, boolean skipStatusCheck, boolean fireImmediately) {+ protected void updateAssetState(AssetState assetState) {withLock(getClass().getSimpleName() + "::updateAssetState", () -> {// TODO: implement rules processing error state handlingLOG.fine("Updating asset state: " + assetState);// Get the chain of rule engines that we need to pass through- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());-- if (!skipStatusCheck) {- // Check that all engines in the scope are available- // TODO This is not very useful without locking the engines until we are done with the update- for (RulesEngine rulesEngine : rulesEngines) {- if (rulesEngine.isError()) {- LOG.severe("Cannot update asset state as one or more rule engines in scope are in an error state");- throw rulesEngine.getError();- }- }- }+ List<RulesEngine<?>> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());// Remove asset state with same attribute ref as new state, add new state- assetStates.remove(assetState);+ boolean inserted = !assetStates.remove(assetState);assetStates.add(assetState);// Pass through each rules engine- for (RulesEngine rulesEngine : rulesEngines) {- rulesEngine.updateFact(assetState, fireImmediately);+ for (RulesEngine<?> rulesEngine : rulesEngines) {+ rulesEngine.updateOrInsertAssetState(assetState, inserted);}});}protected void retractAssetState(AssetState assetState) {// Get the chain of rule engines that we need to pass through- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());+ List<RulesEngine<?>> rulesEngines = getEnginesInScope(assetState.getRealm(), assetState.getPath());// Remove asset state with same attribute refassetStates.remove(assetState);@@ -765,8 +744,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse}// Pass through each rules engine- for (RulesEngine rulesEngine : rulesEngines) {- rulesEngine.removeFact(assetState);+ for (RulesEngine<?> rulesEngine : rulesEngines) {+ rulesEngine.removeAssetState(assetState);}}@@ -777,8 +756,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.collect(Collectors.toList());}- protected List<RulesEngine> getEnginesInScope(String realm, String[] assetPath) {- List<RulesEngine> rulesEngines = new ArrayList<>();+ protected List<RulesEngine<?>> getEnginesInScope(String realm, String[] assetPath) {+ List<RulesEngine<?>> rulesEngines = new ArrayList<>();// Add global engine (if it exists)if (globalEngine != null) {@@ -786,7 +765,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse}// Add tenant engine (if it exists)- RulesEngine tenantRulesEngine = tenantEngines.get(realm);+ RulesEngine<?> tenantRulesEngine = tenantEngines.get(realm);if (tenantRulesEngine != null) {rulesEngines.add(tenantRulesEngine);@@ -794,7 +773,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// Add asset engines, iterate through asset hierarchy using asset IDs from asset pathfor (String assetId : assetPath) {- RulesEngine assetRulesEngine = assetEngines.get(assetId);+ RulesEngine<?> assetRulesEngine = assetEngines.get(assetId);if (assetRulesEngine != null) {rulesEngines.add(assetRulesEngine);}@@ -824,7 +803,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse* identify the asset's (via {@link AssetState}) that have modified {@link LocationAttributePredicate}s and to* notify the {@link GeofenceAssetAdapter}s.*/- protected void onEngineLocationRulesChanged(RulesEngine rulesEngine, List<RulesEngine.AssetStateLocationPredicates> newEngineAssetStateLocationPredicates) {+ protected void onEngineLocationRulesChanged(RulesEngine<?> rulesEngine, List<RulesEngine.AssetStateLocationPredicates> newEngineAssetStateLocationPredicates) {withLock(getClass().getSimpleName() + "::onEngineLocationRulesChanged", () -> {int initialModifiedCount = assetsWithModifiedLocationPredicates.size();diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.javaindex a523f7957..9140bba9b 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java@@ -244,9 +244,9 @@ public class RulesetDeployment {}}- public void onAssetStatesChanged(RulesFacts facts) {+ public void onAssetStatesChanged(RulesFacts facts, RulesEngine.AssetStateChangeEvent event) {if (jsonRulesBuilder != null) {- jsonRulesBuilder.onAssetStatesChanged(facts);+ jsonRulesBuilder.onAssetStatesChanged(facts, event);}}diff --git a/model/src/main/java/org/openremote/model/rules/json/JsonRule.java b/model/src/main/java/org/openremote/model/rules/json/JsonRule.javaindex 9d9bbe2ce..584d65254 100644--- a/model/src/main/java/org/openremote/model/rules/json/JsonRule.java+++ b/model/src/main/java/org/openremote/model/rules/json/JsonRule.java@@ -48,11 +48,9 @@ import org.openremote.model.query.LogicGroup;* {@link JsonRule#when} but excluding the {@link AssetQuery#attributes} predicates and excluding any assets that match* the entire {@link JsonRule#when}. If the number of these assets is greater than 0 then these {@link RuleAction}s will be* executed.- * <h2>Reset</h2>+ * <h2>Recurrence</h2>* <p>- * {@link #reset} - Optional logic used to reset the rule, this is applied to each- * {@link org.openremote.model.rules.AssetState} that was returned by the {@link #when}. If no reset is specified then- * it is assumed that the rule is fire once only per matched {@link org.openremote.model.rules.AssetState}.+ * {@link #recurrence} - Optional logic used to control when rule firing can recur.* <b>NOTE: Rule trigger history is not persisted so on system restart this information is lost and a rule will be* able to fire again.</b>*/@@ -64,7 +62,7 @@ public class JsonRule {public LogicGroup<RuleCondition> when;public RuleAction[] then;public RuleAction[] otherwise;- public RuleConditionReset reset;+ public RuleRecurrence recurrence;public RuleAction[] onStart;public RuleAction[] onStop;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.javaindex 550b44daf..c403662eb 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java@@ -20,16 +20,22 @@package org.openremote.model.rules.json;import org.openremote.model.query.AssetQuery;-import org.openremote.model.query.filter.DateTimePredicate;/**- * Consists of a timer expression (interval, absolute, CRON etc.) or query for filtering- * {@link org.openremote.model.rules.AssetState}s, if both are specified then the timer is used.+ * Consists of one of the following triggers in order of precedence:+ * <ol>+ * <li>{@link #timer} - Timer expression (interval e.g. '1h' or CRON expression) which means the condition becomes+ * true when the interval duration passes or the cron expression matches the current time - note the firing of the+ * rule will not be precise</li>+ * <li>{@link #assets} - {@link AssetQuery} to be applied to the {@link org.openremote.model.rules.AssetState}s+ * available within the rule engine this rule is loaded into. Evaluates to true when one or more+ * {@link org.openremote.model.rules.AssetState}s (referencing unique {@link org.openremote.model.asset.Asset}s) are+ * returned after applying the query.</li>+ * </ol>* <p>- * For timer based trigger it evaluates to true if the timer expression matches the current time. For query based trigger- * it evaluates to true when one or more {@link org.openremote.model.rules.AssetState}s (referencing unique- * {@link org.openremote.model.asset.Asset}s) are returned after applying the query to the- * {@link org.openremote.model.rules.AssetState}s in the RuleEngine that this rule is loaded into.+ * The {@link #resetOnValueChange} is used to indicate that an {@link org.openremote.model.rules.AssetState} is+ * re-eligible for triggering the rule again when its' value changes (the default behaviour is that it only becomes+ * re-eligible when it no longer matches the condition).* <p>* The {@link #tag} is used to name the {@link org.openremote.model.asset.Asset}s that are filtered by the query and can* be used in the rule RHS to perform actions on these specific assets.@@ -37,8 +43,7 @@ import org.openremote.model.query.filter.DateTimePredicate;public class RuleCondition {public String timer;- public DateTimePredicate datetime;public AssetQuery assets;+ public boolean resetOnValueChange;public String tag;- public RuleConditionReset reset;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.java b/model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.javadeleted file mode 100644index ecce26f65..000000000--- a/model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.java+++ /dev/null@@ -1,56 +0,0 @@-/*- * Copyright 2018, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.rules.json;--/**- * This defines when an {@link org.openremote.model.rules.AssetState} becomes eligible for triggering the rule again once- * if has triggered a rule. If a reset is not specified then {@link #noLongerMatches} is assumed.- * <p>- * There is an implicit OR condition between each option.- */-public class RuleConditionReset {-- /**- * Never reset i.e. fire once only for a given {@link org.openremote.model.rules.AssetState}.- */- public boolean never;-- /**- * Simple timer expression e.g. '1h' that is started when the condition is matched.- */- public String timer;-- /**- * When the {@link org.openremote.model.rules.AssetState} no longer evaluates to true.- */- public boolean noLongerMatches;-- /**- * When the timestamp of the {@link org.openremote.model.rules.AssetState} changes in comparison to the timestamp- * at the time when it matched.- */- public boolean timestampChanges;-- /**- * When the value of the {@link org.openremote.model.rules.AssetState} changes in comparison to the value at the- * time when it matched.- */- public boolean valueChanges;-}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleRecurrence.java b/model/src/main/java/org/openremote/model/rules/json/RuleRecurrence.javanew file mode 100644index 000000000..29a419bef--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/json/RuleRecurrence.java@@ -0,0 +1,54 @@+/*+ * Copyright 2018, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.rules.json;++/**+ * Controls if/when a rule can be eligible for firing again;+ */+public class RuleRecurrence {++ /**+ * Defines the scope of the recurrence+ */+ public enum Scope {++ /**+ * Recurrence applies to each asset individually (i.e. timer starts from when rule triggered, each asset that+ * triggered the rule will have their own timer based on {@link #mins} value)+ */+ PER_ASSET,++ /**+ * Recurrence applies globally (i.e. timer starts from when rule triggered, there is a single timer based on+ * {@link #mins} value, this rule will not fire again until timer expires)+ */+ GLOBAL+ }++ /**+ * If not defined defaults to {@link Scope#PER_ASSET}+ */+ public Scope scope;++ /**+ * How many mins until firing is allowed to recur; null=NEVER, 0=ALWAYS, >0=N mins from last firing.+ */+ public Long mins;+}\ No newline at end of filediff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovyindex 6b62d619a..55c98cf5c 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy@@ -146,7 +146,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the apartment rules engine should be removed"conditions.eventually {- assert rulesService.assetEngines.size() == 2+ assert rulesService.assetEngines.size() == 1def apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)def apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)assert apartment2Engine == null@@ -204,7 +204,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerand: "other rule engines should be unaffected"conditions.eventually {assert rulesService.tenantEngines.size() == 2- assert rulesService.assetEngines.size() == 1+ assert rulesService.assetEngines.size() == 0def masterEngine = rulesService.tenantEngines.get(keycloakDemoSetup.masterTenant.realm)def tenantCity = rulesService.tenantEngines.get(keycloakDemoSetup.tenantCity.realm)assert masterEngine != null@@ -222,7 +222,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainertenantBuildingEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantBuilding.realm)apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)assert rulesService.tenantEngines.size() == 3- assert rulesService.assetEngines.size() == 2+ assert rulesService.assetEngines.size() == 1assert tenantBuildingEngine != nullassert tenantBuildingEngine.isRunning()assert tenantBuildingEngine.deployments.size() == 2diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovyindex 0d82a4e74..132f12f3e 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy@@ -122,7 +122,7 @@ class BasicRulesImport {def tenantCityEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantCity.realm)assert tenantCityEngine == null- assert rulesService.assetEngines.size() == 3+ assert rulesService.assetEngines.size() == 2apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)assert apartment1Engine == nullapartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex 59c296beb..50ded5f06 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -398,13 +398,6 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesImport.apartment3Engine.lastFireTimestamp > apartment3LastFireTimestamp}- then: "the broken rules engine should prevent a database update"- conditions.eventually {- def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().isPresent()- assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()- }-cleanup: "the server should be stopped"stopContainer(container)}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovyindex be2698f59..8e8ff53ef 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy@@ -2,6 +2,7 @@ package org.openremote.test.rules.residenceimport com.google.common.collect.Listsimport com.google.firebase.messaging.Message+import org.openremote.container.Containerimport org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService@@ -28,7 +29,9 @@ import org.openremote.model.notification.NotificationSendResultimport org.openremote.model.notification.PushNotificationMessageimport org.openremote.model.rules.Rulesetimport org.openremote.model.rules.RulesetStatus+import org.openremote.model.rules.TemporaryFactimport org.openremote.model.rules.TenantRuleset+import org.openremote.model.rules.json.JsonRulesetDefinitionimport org.openremote.model.value.ObjectValueimport org.openremote.test.ManagerContainerTraitimport org.simplejavamail.email.Email@@ -91,6 +94,9 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {and: "the geofence notifier debounce is set to a small value for testing"ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100+ and: "the rule firing delay time is set to a small value for testing"+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = 100+and: "the container environment is started with the mock handler"def conditions = new PollingConditions(timeout: 15, delay: 1)def serverPort = findEphemeralPort()@@ -237,7 +243,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}and: "after a few seconds the rule should not have fired again"- new PollingConditions(initialDelay: 3).eventually {+ new PollingConditions(initialDelay: 1).eventually {assert notificationMessages.findAll {it.title == "Test title"}.size() == 1}@@ -259,25 +265,27 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {assert targets[1].id == consoleRegistration.id}- when: "the console sends a location update with the same location but a newer timestamp"- advancePseudoClock(35, MINUTES, container)- assetProcessingService.sendAttributeEvent(new AttributeEvent(consoleRegistration.id, LOCATION.attributeName, new GeoJSONPoint(0d, 0d).toValue()), AttributeEvent.Source.CLIENT)-- then: "another notification should have been sent to the console (because the reset condition includes reset on timestampChanges)"- conditions.eventually {- assert notificationMessages.findAll {it.title == "Test title"}.size() == 3- assert targets[2].id == consoleRegistration.id- }-when: "the console sends a location update with a new location but still outside the geofence"def timestamp = assetStorageService.find(consoleRegistration.id, true).getAttribute(LOCATION).flatMap{it.getValueTimestamp()}.orElse(timerService.getCurrentTimeMillis())def attributeEvent = new AttributeEvent(consoleRegistration.id, LOCATION.attributeName, new GeoJSONPoint(10d, 10d).toValue(), timestamp)assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.CLIENT)- then: "another notification should have been sent to the console (because the reset condition includes reset on valueChanges)"+ then: "after a few seconds the rule should not have fired again"+ new PollingConditions(initialDelay: 1).eventually {+ assert notificationMessages.findAll {it.title == "Test title"}.size() == 2+ }++ when: "the ruleset is modified to add a 4hr recurrence per asset"+ def version = ruleset.version+ JsonRulesetDefinition jsonRules = Container.JSON.readValue(ruleset.rules, JsonRulesetDefinition.class)+ jsonRules.rules[0].recurrence.mins = 240+ ruleset.rules = Container.JSON.writeValueAsString(jsonRules)+ ruleset = rulesetStorageService.merge(ruleset)++ then: "the ruleset to be redeployed"conditions.eventually {- assert notificationMessages.findAll {it.title == "Test title"}.size() == 4- assert targets[3].id == consoleRegistration.id+ assert tenantBuildingEngine.deployments.find{it.key == ruleset.id}.value.version == version+1+ assert tenantBuildingEngine.deployments.find{it.key == ruleset.id}.value.status == RulesetStatus.DEPLOYED}when: "when time advances 5 hours"@@ -286,10 +294,10 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {and: "the same AttributeEvent is sent"assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.CLIENT)- then: "another notification should have been sent to the console (because the reset condition includes reset on timer)"+ then: "another notification should have been sent to the console"conditions.eventually {- assert notificationMessages.findAll {it.title == "Test title"}.size() == 5- assert targets[4].id == consoleRegistration.id+ assert notificationMessages.findAll {it.title == "Test title"}.size() == 3+ assert targets[2].id == consoleRegistration.id}when: "the Rules PAUSE_SCHEDULER is overridden to facilitate testing"@@ -314,7 +322,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}and: "a validity period is added to the ruleset (fictional times to ensure firing in sensible time within test)"- def version = ruleset.version+ version = ruleset.versiondef validityStart = Instant.ofEpochMilli(getClockTimeOf(container)).plus(2000, ChronoUnit.MILLIS)def validityEnd = Instant.ofEpochMilli(getClockTimeOf(container)).plus(4000, ChronoUnit.MILLIS)def calendarEvent = new CalendarEvent(@@ -341,7 +349,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}and: "no notification should have been sent as outside the validity period"- assert notificationMessages.findAll {it.title == "Test title"}.size() == 5+ assert notificationMessages.findAll {it.title == "Test title"}.size() == 3when: "the pause elapses"engine.unPauseRuleset(deployment)@@ -364,8 +372,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {and: "another notification should have been sent as inside the validity period"conditions.eventually {- assert notificationMessages.findAll {it.title == "Test title"}.size() == 6- assert targets[5].id == consoleRegistration.id+ assert notificationMessages.findAll {it.title == "Test title"}.size() == 4+ assert targets[3].id == consoleRegistration.id}when: "the un-pause elapses"@@ -388,7 +396,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}and: "no notification should have been sent as outside the validity period"- assert notificationMessages.findAll {it.title == "Test title"}.size() == 6+ assert notificationMessages.findAll {it.title == "Test title"}.size() == 4when: "the pause elapses"engine.unPauseRuleset(deployment)diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.jsonindex c6e914cdd..8dc3d8157 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json@@ -28,8 +28,8 @@"value": {"predicateType": "radial","radius": 50,- "lat": 51.438000,- "lng": 5.470945,+ "lat": 51.446308,+ "lng": 5.454027,"negated": true}}@@ -155,11 +155,8 @@"updateAction": "REPLACE"}],- "reset": {- "noLongerMatches": true,- "valueChanges": true,- "timestampChanges": true,- "timer": "4h"+ "recurrence": {+ "mins": 0}}]diff --git a/ui/app/main/src/components/pages/page-rules.ts b/ui/app/main/src/components/pages/page-rules.tsindex 0c6e2988c..5f8b1a5b1 100644--- a/ui/app/main/src/components/pages/page-rules.ts+++ b/ui/app/main/src/components/pages/page-rules.ts@@ -29,11 +29,7 @@ const rulesConfig: RulesConfig = {}},json: {- rule: {- reset: {- timer: "1h"- }- }+}};diff --git a/ui/component/or-rules/package.json b/ui/component/or-rules/package.jsonindex ff3a7a3cd..4f75a3da0 100644--- a/ui/component/or-rules/package.json+++ b/ui/component/or-rules/package.json@@ -13,6 +13,8 @@"license": "AGPL-3.0-or-later","dependencies": {"@openremote/core": "^1.1.0",+ "@openremote/model": "^1.1.0",+ "@openremote/or-asset-viewer": "^1.1.0","@openremote/or-attribute-input": "^1.1.0","@openremote/or-icon": "^1.1.0","@openremote/or-input": "^1.1.0",@@ -21,20 +23,19 @@"@openremote/or-select": "^1.1.0","@openremote/or-translate": "^1.1.0","@openremote/rest": "^1.1.0",- "@openremote/model": "^1.1.0",- "@openremote/or-asset-viewer": "^1.1.0","ace-builds": "^1.4.7",- "lit-element": "^2.2.1","linqts": "^1.12.6",+ "lit-element": "^2.2.1",+ "moment": "^2.24.0","resize-observer": "^1.0.0",- "shortid": "^2.2.15",- "moment": "^2.24.0"+ "rrule": "^2.6.4",+ "shortid": "^2.2.15"},"devDependencies": {+ "@types/shortid": "^0.0.29","tslint": ">=5.11.0","typescript": ">=3.4.5","webpack": "^4.41.2",- "webpack-cli": "^3.3.9",- "@types/shortid": "^0.0.29"+ "webpack-cli": "^3.3.9"}}diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.tsindex cc8de5558..b918934c9 100644--- a/ui/component/or-rules/src/index.ts+++ b/ui/component/or-rules/src/index.ts@@ -38,10 +38,10 @@ import "./or-rule-viewer";import "./flow-viewer/flow-viewer";import {OrRuleList} from "./or-rule-list";import {OrRuleViewer} from "./or-rule-viewer";+import {RecurrenceOption} from "./json-viewer/or-rule-then-otherwise";export const enum ConditionType {ASSET_QUERY = "assetQuery",- DATE_TIME = "datetime",TIMER = "timer"}@@ -81,8 +81,7 @@ export enum AssetQueryOperator {WITHIN_RADIUS = "withinRadius",OUTSIDE_RADIUS = "outsideRadius",WITHIN_RECTANGLE = "withinRectangle",- OUTSIDE_RECTANGLE = "outsideRectangle",- VALUE_CHANGES = "valueChanges"+ OUTSIDE_RECTANGLE = "outsideRectangle"}export interface AssetTypeAttributeName {@@ -96,6 +95,7 @@ export interface RulesConfig {allowedConditionTypes?: ConditionType[];allowedActionTypes?: ActionType[];allowedAssetQueryOperators?: Map<AssetTypeAttributeName | AttributeDescriptor | AttributeValueDescriptor | ValueType, AssetQueryOperator[]>;+ allowedRecurrenceOptions?: RecurrenceOption[];hideActionTypeOptions?: boolean;hideActionTargetOptions?: boolean;hideActionUpdateOptions?: boolean;diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.tsindex 7993a7493..cd8da7d2c 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts@@ -80,8 +80,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {AssetQueryOperator.WITHIN_RECTANGLE,AssetQueryOperator.OUTSIDE_RECTANGLE,AssetQueryOperator.VALUE_EMPTY,- AssetQueryOperator.VALUE_NOT_EMPTY,- AssetQueryOperator.VALUE_CHANGES]+ AssetQueryOperator.VALUE_NOT_EMPTY]],[ValueType.STRING, [AssetQueryOperator.EQUALS,@@ -105,15 +104,13 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {AssetQueryOperator.BETWEEN,AssetQueryOperator.NOT_BETWEEN,AssetQueryOperator.VALUE_EMPTY,- AssetQueryOperator.VALUE_NOT_EMPTY,- AssetQueryOperator.VALUE_CHANGES]+ AssetQueryOperator.VALUE_NOT_EMPTY]],[ValueType.BOOLEAN, [AssetQueryOperator.IS_TRUE,AssetQueryOperator.IS_FALSE,AssetQueryOperator.VALUE_EMPTY,- AssetQueryOperator.VALUE_NOT_EMPTY,- AssetQueryOperator.VALUE_CHANGES]+ AssetQueryOperator.VALUE_NOT_EMPTY]],[ValueType.ARRAY, [AssetQueryOperator.CONTAINS,@@ -125,15 +122,13 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {AssetQueryOperator.LENGTH_LESS_THAN,AssetQueryOperator.LENGTH_GREATER_THAN,AssetQueryOperator.VALUE_EMPTY,- AssetQueryOperator.VALUE_NOT_EMPTY,- AssetQueryOperator.VALUE_CHANGES]+ AssetQueryOperator.VALUE_NOT_EMPTY]],[ValueType.OBJECT, [AssetQueryOperator.CONTAINS_KEY,AssetQueryOperator.NOT_CONTAINS_KEY,AssetQueryOperator.VALUE_EMPTY,- AssetQueryOperator.VALUE_NOT_EMPTY,- AssetQueryOperator.VALUE_CHANGES]+ AssetQueryOperator.VALUE_NOT_EMPTY]]]);@@ -450,7 +445,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {case "value-empty":return AssetQueryOperator.VALUE_EMPTY;case "value-not-empty":- return this.condition.reset ? AssetQueryOperator.VALUE_CHANGES : AssetQueryOperator.VALUE_NOT_EMPTY;+ return AssetQueryOperator.VALUE_NOT_EMPTY;}}@@ -463,8 +458,6 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {return;}- this.condition.reset = undefined;-if (!operator) {attributePredicate.value = undefined;this.dispatchEvent(new OrRulesJsonRuleChangedEvent());@@ -641,15 +634,9 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {};break;case AssetQueryOperator.VALUE_NOT_EMPTY:- case AssetQueryOperator.VALUE_CHANGES:predicate = {predicateType: "value-not-empty"};- if (value === AssetQueryOperator.VALUE_CHANGES) {- this.condition.reset = {- valueChanges: true- };- }break;case AssetQueryOperator.CONTAINS:case AssetQueryOperator.NOT_CONTAINS:diff --git a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts b/ui/component/or-rules/src/json-viewer/or-rule-condition.tsindex c29b1dcb2..c42ac0f42 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts@@ -25,12 +25,10 @@ const DATE_TIME_COLOR = "6AEAA4";export function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriptor[]): MenuItem[] {let addAssetTypes = true;- let addDatetime = true;let addTimer = true;if (config && config.controls && config.controls.allowedConditionTypes) {addAssetTypes = config.controls.allowedConditionTypes.indexOf(ConditionType.ASSET_QUERY) >= 0;- addDatetime = config.controls.allowedConditionTypes.indexOf(ConditionType.DATE_TIME) >= 0;addTimer = config.controls.allowedConditionTypes.indexOf(ConditionType.TIMER) >= 0;}@@ -52,15 +50,6 @@ export function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetD}));}- if (addDatetime) {- menu.push({- text: i18next.t("datetime"),- icon: "clock",- value: ConditionType.DATE_TIME,- styleMap: {"--or-icon-fill": "#" + DATE_TIME_COLOR}- } as MenuItem);- }-if (addTimer) {menu.push({text: i18next.t("timer"),@@ -73,25 +62,16 @@ export function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDreturn menu;}-export function updateRuleConditionType(ruleCondition: RuleCondition, value: string | undefined, config?: RulesConfig) {+export function updateRuleConditionType(ruleCondition: RuleCondition, value: string | ConditionType | undefined, config?: RulesConfig) {- if (!value || value === "") {+ if (!value) {ruleCondition.assets = undefined;ruleCondition.timer = undefined;- ruleCondition.datetime = undefined;} else if (value === ConditionType.TIMER) {ruleCondition.assets = undefined;- ruleCondition.datetime = undefined;ruleCondition.timer = "1h";- } else if (value === ConditionType.DATE_TIME) {- ruleCondition.assets = undefined;- ruleCondition.timer = undefined;- ruleCondition.datetime = {- predicateType: "datetime"- };} else {ruleCondition.timer = undefined;- ruleCondition.datetime = undefined;if (config && config.json && config.json.whenAssetQuery) {ruleCondition.assets = JSON.parse(JSON.stringify(config.json.whenAssetQuery));@@ -165,10 +145,6 @@ class OrRuleCondition extends translate(i18next)(LitElement) {if (type) {switch (type) {- case ConditionType.DATE_TIME:- buttonIcon = "clock";- buttonColor = DATE_TIME_COLOR;- break;case ConditionType.TIMER:buttonIcon = "timer";buttonColor = TIMER_COLOR;@@ -187,16 +163,13 @@ class OrRuleCondition extends translate(i18next)(LitElement) {html`<or-input type="${InputType.BUTTON}" .icon="${buttonIcon || ""}"></or-input>`,getWhenTypesMenu(this.config, this.assetDescriptors),type,- (values: string[] | string) => this.type = values as string)}+ (values: string[] | string) => this.type = values as ConditionType)}</div>`;}if (type) {switch (type) {- case ConditionType.DATE_TIME:- template = html`<span>DATE TIME NOT IMPLEMENTED</span>`;- break;case ConditionType.TIMER:template = html`<span>TIMER NOT IMPLEMENTED</span>`;break;@@ -212,7 +185,7 @@ class OrRuleCondition extends translate(i18next)(LitElement) {`;}- protected get type(): string | undefined {+ protected get type(): string | ConditionType | undefined {const assetType = getAssetTypeFromQuery(this.ruleCondition.assets);if (assetType) {@@ -222,13 +195,9 @@ class OrRuleCondition extends translate(i18next)(LitElement) {if (this.ruleCondition.timer) {return ConditionType.TIMER;}-- if (this.ruleCondition.datetime) {- return ConditionType.DATE_TIME;- }}- protected set type(value: string | undefined) {+ protected set type(value: string | ConditionType | undefined) {updateRuleConditionType(this.ruleCondition, value, this.config);if (this._assetQuery) {this._assetQuery.refresh();diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.tsindex af9e83963..b5b41b7cb 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts@@ -267,7 +267,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsif (group.items) {for (const condition of group.items) {- if (!condition.assets && !condition.datetime && !condition.timer) {+ if (!condition.assets && !condition.timer) {return false;}@@ -275,10 +275,6 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn false;}- if (condition.datetime && !this._validateValuePredicate(condition.datetime)) {- return false;- }-if (condition.timer && !Util.isTimeDuration(condition.timer)) {return false;}diff --git a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.tsindex 56926dcfe..04896d44a 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts@@ -1,24 +1,23 @@import {css, customElement, html, LitElement, property, TemplateResult} from "lit-element";import {buttonStyle} from "../style";import "./or-rule-asset-query";+import {ActionType, getAssetTypeFromQuery, RulesConfig} from "../index";+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import {- ActionType,- getAssetTypeFromQuery,- RulesConfig-} from "../index";-import {- OrRulesJsonRuleChangedEvent-} from "./or-rule-json-viewer";-import {AssetDescriptor, JsonRule, RuleActionUnion, RuleConditionReset, RuleActionNotification, AssetType} from "@openremote/model";+ AssetDescriptor,+ AssetType,+ JsonRule,+ RuleActionUnion,+ RuleRecurrence,+ RuleRecurrenceScope+} from "@openremote/model";import i18next from "i18next";import {InputType} from "@openremote/or-input";-import {MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";-import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";+import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";import {AssetModelUtil} from "@openremote/core";import "./or-rule-action-attribute";import "./or-rule-action-notification";-import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";-import { translate } from "@openremote/or-translate";+import {translate} from "@openremote/or-translate";const NOTIFICATION_COLOR = "4B87EA";const WAIT_COLOR = "EACC54";@@ -75,24 +74,38 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri}interface ResetOptions {- [key: string]: string;+ [key: string]: (jsonRule: JsonRule) => void;+}++export enum RecurrenceOption {+ ALWAYS = "always",+ ONCE = "once",+ ONCE_PER_ASSET = "oncePerAsset",+ ONCE_PER_HOUR = "oncePerHour",+ ONCE_PER_HOUR_PER_ASSET = "oncePerHourPerAsset",+ ONCE_PER_DAY = "oncePerDay",+ ONCE_PER_DAY_PER_ASSET = "oncePerDayPerAsset",+ ONCE_PER_WEEK = "oncePerWeek",+ ONCE_PER_WEEK_PER_ASSET = "oncePerWeekPerAsset",+ ONCE_PER_MONTH = "oncePerMonth",+ ONCE_PER_MONTH_PER_ASSET = "oncePerMonthPerAsset"}-const resetOptions: ResetOptions = {- "everyTime": "everyTime",- "onlyOnce": "onlyOnce",- "1h": "oncePerHour",- "1d": "oncePerDay",- "1w": "oncePerWeek",- "1mn": "oncePerMonth"-};+function getRecurrenceMenu(config?: RulesConfig): MenuItem[] {-function getResetMenu(config?: RulesConfig): MenuItem[] {+ if (config && config.controls && config.controls.allowedRecurrenceOptions) {+ return config.controls.allowedRecurrenceOptions.map((value) => {+ return {+ text: i18next.t(value),+ value: value+ };+ });+ }- return Object.entries(resetOptions).map(([key, value]) => {+ return Object.values(RecurrenceOption).map((value) => {return {text: i18next.t(value),- value: key+ value: value};});}@@ -159,7 +172,7 @@ const style = css`text-transform: capitalize;}- .rule-reset {+ .rule-recurrence {position: absolute;top: 5px;right: 0;@@ -187,38 +200,43 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {return !this.config || !this.config.controls || this.config.controls.hideThenAddAction !== true;}- protected ruleResetTemplate(reset: RuleConditionReset) {- let resetTemplate: TemplateResult | string = ``;+ protected ruleRecurrenceTemplate(reset: RuleRecurrence | undefined) {+ let recurrenceTemplate: TemplateResult | string = ``;const buttonColor = "inherit";-- let value;-- if (!reset) {- value = "onlyOnce";- } else if (reset.valueChanges && reset.timestampChanges) {- value = "everyTime";- } else if (reset.timer) {- value = reset.timer;- } else if (this.config && this.config.json && this.config.json.rule && this.config.json.rule.reset) {- value = this.config.json.rule.reset.timer;+ let value = RecurrenceOption.ONCE_PER_ASSET;++ if (reset) {+ let isGlobal = reset.scope === RuleRecurrenceScope.GLOBAL;+ if (reset.mins === undefined || reset.mins === null) {+ value = isGlobal ? RecurrenceOption.ONCE : RecurrenceOption.ONCE_PER_ASSET;+ } else if (reset.mins === 0) {+ value = RecurrenceOption.ALWAYS;+ } else if (reset.mins === 60) {+ value = isGlobal ? RecurrenceOption.ONCE_PER_HOUR : RecurrenceOption.ONCE_PER_HOUR_PER_ASSET;+ } else if (reset.mins === 1440) {+ value = isGlobal ? RecurrenceOption.ONCE_PER_DAY : RecurrenceOption.ONCE_PER_DAY_PER_ASSET;+ } else if (reset.mins === 10080) {+ value = isGlobal ? RecurrenceOption.ONCE_PER_WEEK : RecurrenceOption.ONCE_PER_WEEK_PER_ASSET;+ } else if (reset.mins === 43200) {+ value = isGlobal ? RecurrenceOption.ONCE_PER_MONTH : RecurrenceOption.ONCE_PER_MONTH_PER_ASSET;+ }}- resetTemplate = html`- <div style="color: #${buttonColor}; margin-right: 6px;">+ recurrenceTemplate = html`+ <div style="color: #${buttonColor}; margin-right: 6px;"><span><or-translate value="recurrence"></or-translate>:</span>${getContentWithMenuTemplate(- html`<or-input type="${InputType.BUTTON}" label="${value ? i18next.t(resetOptions[value]) : i18next.t("frequency") }"></or-input>`,- getResetMenu(this.config),+ html`<or-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}"></or-input>`,+ getRecurrenceMenu(this.config),value,- (values: string | string[]) => this.setResetOption(values as string))}+ (value) => this.setRecurrenceOption(value as RecurrenceOption))}</div>`;return html`- <div class="rule-reset">- ${resetTemplate}+ <div class="rule-recurrence">+ ${recurrenceTemplate}</div>`;-}protected ruleActionTemplate(actions: RuleActionUnion[], action: RuleActionUnion) {@@ -300,7 +318,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {return html`<div><or-panel .heading="${i18next.t("then")}...">- ${this.ruleResetTemplate(this.rule.reset!)}+ ${this.ruleRecurrenceTemplate(this.rule.recurrence)}${!this.rule.then ? `` : this.rule.then.map((action: RuleActionUnion) => this.ruleActionTemplate(this.rule.then!, action))}${this.thenAllowAdd ? html`@@ -341,35 +359,45 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {}}- protected setResetOption(value: string) {+ protected setRecurrenceOption(value: RecurrenceOption) {switch (value) {- case "onlyOnce":- delete this.rule.reset;+ case RecurrenceOption.ALWAYS:+ this.rule.recurrence = {mins: 0};break;- case "everyTime":- if (this.rule.reset) {- delete this.rule.reset.timer;- }- this.rule.reset = {- valueChanges: true,- timestampChanges: true- };+ case RecurrenceOption.ONCE:+ this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL};break;+ case RecurrenceOption.ONCE_PER_HOUR:+ this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 60};+ break;+ case RecurrenceOption.ONCE_PER_HOUR_PER_ASSET:+ this.rule.recurrence = {mins: 60};+ break;+ case RecurrenceOption.ONCE_PER_DAY:+ this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 1440};+ break;+ case RecurrenceOption.ONCE_PER_DAY_PER_ASSET:+ this.rule.recurrence = {mins: 1440};+ break;+ case RecurrenceOption.ONCE_PER_WEEK:+ this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 10080};+ break;+ case RecurrenceOption.ONCE_PER_WEEK_PER_ASSET:+ this.rule.recurrence = {mins: 10080};+ break;+ case RecurrenceOption.ONCE_PER_MONTH:+ this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 43200};+ break;+ case RecurrenceOption.ONCE_PER_MONTH_PER_ASSET:+ this.rule.recurrence = {mins: 43200};+ break;+ case RecurrenceOption.ONCE_PER_ASSET:default:- if (this.rule.reset) {- if (this.rule.reset.valueChanges) {- delete this.rule.reset.valueChanges;- }- if (this.rule.reset.timestampChanges) {- delete this.rule.reset.timestampChanges;- }- this.rule.reset.timer = value;- } else {- this.rule.reset = {timer: value};- }+ delete this.rule.recurrence;break;}+this.dispatchEvent(new OrRulesJsonRuleChangedEvent());this.requestUpdate();}diff --git a/ui/component/or-rules/src/json-viewer/or-rule-when.ts b/ui/component/or-rules/src/json-viewer/or-rule-when.tsindex b5ed54fe0..64962fc15 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-when.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-when.ts@@ -7,9 +7,14 @@ import i18next from "i18next";import {InputType} from "@openremote/or-input";import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import {getWhenTypesMenu, updateRuleConditionType} from "./or-rule-condition";-import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";+import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";import { translate } from "@openremote/or-translate";+enum ResetOption {+ NO_LONGER_MATCHES = "noLongerMatches",+ VALUE_CHANGES = "valueChanges"+}+// language=CSSconst style = css`@@ -89,6 +94,12 @@ const style = css`.add-button-wrapper or-mwc-menu {text-transform: capitalize;}++ .rule-reset {+ position: absolute;+ top: 5px;+ right: 0;+ }`;@customElement("or-rule-when")@@ -107,6 +118,33 @@ class OrRuleWhen extends translate(i18next)(LitElement) {public assetDescriptors?: AssetDescriptor[];+ protected conditionResetTemplate(condition: RuleCondition): TemplateResult | string {++ if (!condition.assets) {+ return ``;+ }++ const buttonColor = "inherit";+ let value = condition.resetOnValueChange ? ResetOption.VALUE_CHANGES : ResetOption.NO_LONGER_MATCHES;+ let menuItems: MenuItem[] = Object.values(ResetOption).map((resetOption) => {+ return {+ text: i18next.t(resetOption),+ value: resetOption+ } as MenuItem;+ });++ return html`+ <div class="rule-reset">+ <div style="color: #${buttonColor}; margin-right: 6px;"><span><or-translate value="reset"></or-translate>:</span>+ ${getContentWithMenuTemplate(+ html`<or-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}"></or-input>`,+ menuItems,+ value,+ (value) => this.setResetOption(condition, value as ResetOption))}+ </div>+ </div>`;+ }+protected ruleGroupTemplate(group: LogicGroup<RuleCondition>, parentGroup?: LogicGroup<RuleCondition>): TemplateResult | undefined {if (!group) {@@ -123,6 +161,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {if (isTopLevel) {wrapper = (content, item, parent, isGroup, isFirst) => {return html`+<or-panel .heading="${i18next.t(isFirst ? "when": "orWhen")}...">${showRemoveGroup ? html`<button class="button-clear remove-button" @click="${() => this.removeItem(item, parent, isGroup)}">@@ -134,7 +173,13 @@ class OrRuleWhen extends translate(i18next)(LitElement) {};} else {wrapper = (content, item, parent, isGroup, isFirst) => {++ let isCondition = (item as LogicGroup<RuleCondition>).items === undefined;+return html`++ ${isCondition ? this.conditionResetTemplate(item as RuleCondition) : ``}+${!isFirst ? html`<or-icon class="small" icon="ampersand"></or-icon>` : ``}@@ -373,4 +418,14 @@ class OrRuleWhen extends translate(i18next)(LitElement) {this.requestUpdate();}}++ private setResetOption(condition: RuleCondition, value: ResetOption) {+ if (value === ResetOption.NO_LONGER_MATCHES) {+ delete condition.resetOnValueChange;+ } else {+ condition.resetOnValueChange = true;+ }+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());+ this.requestUpdate();+ }}diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.tsindex eb3794efa..53f9458b9 100644--- a/ui/component/or-rules/src/or-rule-list.ts+++ b/ui/component/or-rules/src/or-rule-list.ts@@ -1,10 +1,11 @@import {css, customElement, html, LitElement, property, PropertyValues, query, TemplateResult} from "lit-element";-import {JsonRule, RuleCondition, RulesetLang, Tenant, TenantRuleset, ClientRole} from "@openremote/model";+import {JsonRule, RuleCondition, RulesetLang, TenantRuleset, ClientRole, CalendarEvent} from "@openremote/model";import "@openremote/or-translate";import manager, {EventCallback, OREvent} from "@openremote/core";import moment from "moment";+import { RRule, RRuleSet, rrulestr } from "rrule";import "@openremote/or-input";-import {InputType, OrInputChangedEvent} from "@openremote/or-input";+import {InputType} from "@openremote/or-input";import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";import {OrRulesRequestAddEvent,@@ -277,32 +278,24 @@ export class OrRuleList extends translate(i18next)(LitElement) {protected static _getNodeStatusClasses(ruleset: TenantRuleset): string {let status = ruleset.enabled ? "bg-green" : "bg-red";- if (ruleset.rules && ruleset.enabled) {- switch (ruleset.lang) {- case RulesetLang.JSON:- const rule: JsonRule = JSON.parse(ruleset.rules).rules[0];-- // HACK/WIP: the status of a rule should be better thought over see issue #95- // currently only checks the date of the first whenCondition- if (rule && rule.when && rule.when.items && rule.when.items.length > 0) {- const ruleCondition: RuleCondition = rule.when.items[0];- if (ruleCondition.datetime) {- const today = moment();- const startDate = ruleCondition.datetime.value;- const endDate = ruleCondition.datetime.rangeValue;-- if (today.diff(startDate) < 0) {- // before startDate, show blue- status = "bg-blue";- } else if (today.diff(endDate) > 0) {- // after endDate, show grey- status = "bg-grey";- }- }+ if (ruleset.enabled) {++ // Look at validity meta+ if (ruleset.meta && ruleset.meta.hasOwnProperty("urn:openremote:rule:meta:validity")) {+ let calendarEvent = ruleset.meta["urn:openremote:rule:meta:validity"] as CalendarEvent;+ let now = new Date().getTime();++ if (calendarEvent.start) {+ if (now < calendarEvent.start) {+ // before startDate, show blue+ status = "bg-blue";+ } else if (calendarEvent.end && now > calendarEvent.end) {+ // after endDate, show grey+ status = "bg-grey";+ } else if (calendarEvent.recurrence) {+ // TODO: Implement RRule support}- break;- default:- break;+ }}}diff --git a/yarn.lock b/yarn.lockindex af6d12f71..203aacdcb 100644--- a/yarn.lock+++ b/yarn.lock@@ -1546,6 +1546,25 @@resolved "https://registry.yarnpkg.com/@material/density/-/density-4.0.0.tgz#5bc4bba6c1232f6e075c88295357e6ebdee4353f"integrity sha512-PuOCPCXlWjimTq+OuCS8biAb1JE9aXCZwT1dRG9REAIAK7bN8KeeTzkeJp6jTj+ggZjWphwKF0lKeX6Gv+e/lw==+"@material/dialog@^4.0.0":+ version "4.0.0"+ resolved "https://registry.yarnpkg.com/@material/dialog/-/dialog-4.0.0.tgz#09861315b80c217acf2a8a9f9ea6201e2cf2d2a7"+ integrity sha512-ATfmcRKjPUuhpjKuCCtYrbuRfx1vZ9r0ZkMI2eLBxWbYbTbKOH+oM5Z24uVO38bX7SvOItPWsAQZYkoiyPUdPQ==+ dependencies:+ "@material/animation" "^4.0.0"+ "@material/base" "^4.0.0"+ "@material/dom" "^4.0.0"+ "@material/elevation" "^4.0.0"+ "@material/feature-targeting" "^4.0.0"+ "@material/ripple" "^4.0.0"+ "@material/rtl" "^4.0.0"+ "@material/shape" "^4.0.0"+ "@material/theme" "^4.0.0"+ "@material/touch-target" "^4.0.0"+ "@material/typography" "^4.0.0"+ focus-trap "^5.0.0"+ tslib "^1.9.3"+"@material/dom@^4.0.0":version "4.0.0"resolved "https://registry.yarnpkg.com/@material/dom/-/dom-4.0.0.tgz#f0e68c4429e555040304c958bb3e11614276fdfa"@@ -1553,6 +1572,24 @@dependencies:tslib "^1.9.3"+"@material/drawer@^4.0.0":+ version "4.0.0"+ resolved "https://registry.yarnpkg.com/@material/drawer/-/drawer-4.0.0.tgz#07d66e4170f6b802ef902248dbddb1693ead55f2"+ integrity sha512-HjhE4KnP+bGC56AdD8H1FqMT5PjEuz0RvvEzsMrQC86CERsE9eu35+JdSHFsLT2qi8m8c8v9NicOVIP1QHNH+Q==+ dependencies:+ "@material/animation" "^4.0.0"+ "@material/base" "^4.0.0"+ "@material/elevation" "^4.0.0"+ "@material/feature-targeting" "^4.0.0"+ "@material/list" "^4.0.0"+ "@material/ripple" "^4.0.0"+ "@material/rtl" "^4.0.0"+ "@material/shape" "^4.0.0"+ "@material/theme" "^4.0.0"+ "@material/typography" "^4.0.0"+ focus-trap "^5.0.0"+ tslib "^1.9.3"+"@material/elevation@^4.0.0":version "4.0.0"resolved "https://registry.yarnpkg.com/@material/elevation/-/elevation-4.0.0.tgz#58ba81c8c9efd0b5d3bfed7fa915d4930d814b97"@@ -5810,6 +5847,11 @@ lerna@^3.18.1:import-local "^2.0.0"npmlog "^4.1.2"+linqts@^1.12.6:+ version "1.12.6"+ resolved "https://registry.yarnpkg.com/linqts/-/linqts-1.12.6.tgz#8556e7d013a23dd2cc7201d460117b1cdfa2b6be"+ integrity sha512-fqVBvHkATzGrkTbct1jLJ50Tb76KTI/nWAsUzkmnkA75i5mmj5T4YHo4nywx+Sej9WoCpE7Udc8jAZXRfEf/QQ==+lit-element@^2.1.0, lit-element@^2.2.1:version "2.2.1"resolved "https://registry.yarnpkg.com/lit-element/-/lit-element-2.2.1.tgz#79c94d8cfdc2d73b245656e37991bd1e4811d96f"@@ -6016,6 +6058,11 @@ lru-cache@^5.1.1:dependencies:yallist "^3.0.2"+luxon@^1.21.3:+ version "1.22.0"+ resolved "https://registry.yarnpkg.com/luxon/-/luxon-1.22.0.tgz#639525c7c69e594953c7b142794466b8ea85b868"+ integrity sha512-3sLvlfbFo+AxVEY3IqxymbumtnlgBwjDExxK60W3d+trrUzErNAz/PfvPT+mva+vEUrdIodeCOs7fB6zHtRSrw==+macos-release@^2.2.0:version "2.3.0"resolved "https://registry.yarnpkg.com/macos-release/-/macos-release-2.3.0.tgz#eb1930b036c0800adebccd5f17bc4c12de8bb71f"@@ -8037,6 +8084,15 @@ ripemd160@^2.0.0, ripemd160@^2.0.1:hash-base "^3.0.0"inherits "^2.0.1"+rrule@^2.6.4:+ version "2.6.4"+ resolved "https://registry.yarnpkg.com/rrule/-/rrule-2.6.4.tgz#7f4f31fda12bc7249bb176c891109a9bc448e035"+ integrity sha512-sLdnh4lmjUqq8liFiOUXD5kWp/FcnbDLPwq5YAc/RrN6120XOPb86Ae5zxF7ttBVq8O3LxjjORMEit1baluahA==+ dependencies:+ tslib "^1.10.0"+ optionalDependencies:+ luxon "^1.21.3"+run-async@^2.2.0:version "2.3.0"resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.3.0.tgz#0371ab4ae0bdd720d4166d7dfda64ff7a445a6c0"