Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Add alarms feature (#1244)

NinaBianca11c4a9a60c2f
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
index fce0be427..218bc00a7 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -40,6 +40,8 @@ import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.EntityClassProvider;
import org.openremote.model.PersistenceEvent;
+import org.openremote.model.alarm.AlarmAssetLink;
+import org.openremote.model.alarm.SentAlarm;
import org.openremote.model.apps.ConsoleAppConfig;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
@@ -360,6 +362,8 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
entityClasses.add(Dashboard.class.getName());
entityClasses.add(ProvisioningConfig.class.getName());
entityClasses.add(X509ProvisioningConfig.class.getName());
+ entityClasses.add(SentAlarm.class.getName());
+ entityClasses.add(AlarmAssetLink.class.getName());
// Add packages with package-info (don't think this is JPA spec but hibernate specific)
entityClasses.add("org.openremote.container.util");
diff --git a/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
new file mode 100644
index 000000000..b923b03fa
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2024, 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.manager.alarm;
+
+import jakarta.persistence.EntityNotFoundException;
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.ForbiddenException;
+import jakarta.ws.rs.NotFoundException;
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebResource;
+import org.openremote.model.alarm.Alarm;
+import org.openremote.model.alarm.AlarmResource;
+import org.openremote.model.alarm.SentAlarm;
+import org.openremote.model.alarm.AlarmAssetLink;
+import org.openremote.model.http.RequestParams;
+
+import org.openremote.model.util.TextUtil;
+
+import java.util.List;
+import java.util.function.Supplier;
+
+import static org.openremote.model.alarm.Alarm.Source.CLIENT;
+import static org.openremote.model.alarm.Alarm.Source.MANUAL;
+
+public class AlarmResourceImpl extends ManagerWebResource implements AlarmResource {
+
+ private final AlarmService alarmService;
+
+ public AlarmResourceImpl(TimerService timerService,
+ ManagerIdentityService identityService,
+ AlarmService alarmService) {
+ super(timerService, identityService);
+ this.alarmService = alarmService;
+ }
+
+ private <T> T mapExceptions(Supplier<T> supplier) {
+ try {
+ return supplier.get();
+ } catch (IllegalArgumentException | NullPointerException e) {
+ throw new BadRequestException(e.getMessage(), e);
+ } catch (EntityNotFoundException e) {
+ throw new NotFoundException(e.getMessage(), e);
+ } catch (SecurityException e) {
+ throw new ForbiddenException(e.getMessage(), e);
+ }
+ }
+
+ private void mapExceptions(Runnable runnable) {
+ try {
+ runnable.run();
+ } catch (IllegalArgumentException | NullPointerException e) {
+ throw new BadRequestException(e.getMessage(), e);
+ } catch (EntityNotFoundException e) {
+ throw new NotFoundException(e.getMessage(), e);
+ } catch (SecurityException e) {
+ throw new ForbiddenException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public SentAlarm[] getAlarms(RequestParams requestParams, String realm, Alarm.Status status, String assetId, String assigneeId) {
+ String filterRealm = TextUtil.isNullOrEmpty(realm) ? getAuthenticatedRealm().getName() : realm;
+ if (!isRealmActiveAndAccessible(filterRealm)) {
+ throw new ForbiddenException("Realm '" + filterRealm + "' is not active or inaccessible");
+ }
+ return mapExceptions(() -> alarmService.getAlarms(filterRealm, status, assetId, assigneeId).toArray(new SentAlarm[0]));
+ }
+
+ @Override
+ public void removeAlarms(RequestParams requestParams, List<Long> alarmIds) {
+ mapExceptions(() -> alarmService.removeAlarms(alarmIds, getUserId()));
+ }
+
+ @Override
+ public SentAlarm getAlarm(RequestParams requestParams, Long alarmId) {
+ return mapExceptions(() -> alarmService.getAlarm(alarmId, getUserId()));
+ }
+
+ @Override
+ public void removeAlarm(RequestParams requestParams, Long alarmId) {
+ mapExceptions(() -> alarmService.removeAlarm(alarmId, getUserId()));
+ }
+
+ @Override
+ public SentAlarm createAlarm(RequestParams requestParams, Alarm alarm, List<String> assetIds) {
+ if (getUserId() != null) {
+ alarm.setSource(MANUAL);
+ alarm.setSourceId(getUserId());
+ } else if (getClientId() != null) {
+ alarm.setSource(CLIENT);
+ alarm.setSourceId(getClientId());
+ }
+ return mapExceptions(() -> alarmService.sendAlarm(alarm, assetIds, getUserId()));
+ }
+
+ @Override
+ public void updateAlarm(RequestParams requestParams, Long alarmId, SentAlarm alarm) {
+ mapExceptions(() -> alarmService.updateAlarm(alarmId, getUserId(), alarm));
+ }
+
+ @Override
+ public List<AlarmAssetLink> getAssetLinks(RequestParams requestParams, Long alarmId, String realm) {
+ return mapExceptions(() -> alarmService.getAssetLinks(alarmId, getUserId(), realm));
+ }
+
+ @Override
+ public void setAssetLinks(RequestParams requestParams, List<AlarmAssetLink> links) {
+ mapExceptions(() -> alarmService.linkAssets(links, getUserId()));
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
new file mode 100644
index 000000000..ba77f314c
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
@@ -0,0 +1,546 @@
+/*
+ * Copyright 2024, 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.manager.alarm;
+
+import jakarta.persistence.EntityNotFoundException;
+import jakarta.persistence.PersistenceException;
+import jakarta.persistence.TypedQuery;
+import org.apache.camel.builder.RouteBuilder;
+import org.hibernate.Session;
+import org.openremote.manager.notification.NotificationService;
+import org.openremote.manager.security.ManagerIdentityProvider;
+import org.openremote.model.Constants;
+import org.openremote.model.PersistenceEvent;
+import org.openremote.model.alarm.*;
+import org.openremote.model.Container;
+import org.openremote.model.ContainerService;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.persistence.PersistenceService;
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebService;
+import org.openremote.manager.event.ClientEventService;
+
+import org.openremote.model.event.shared.EventSubscription;
+import org.openremote.model.event.shared.RealmFilter;
+import org.openremote.model.notification.*;
+import org.openremote.model.query.UserQuery;
+import org.openremote.model.query.filter.RealmPredicate;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.security.User;
+import org.openremote.model.util.TextUtil;
+
+import java.sql.PreparedStatement;
+import java.sql.Timestamp;
+import java.text.DateFormat;
+import java.util.*;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.Constants.OR_HOSTNAME;
+import static org.openremote.model.alarm.Alarm.Source.*;
+
+/**
+ * A service for managing {@link SentAlarm}s. It also provides functionality for managing links between {@link SentAlarm}s
+ * and {@link org.openremote.model.asset.Asset}s using {@link AlarmAssetLink}s.
+ */
+public class AlarmService extends RouteBuilder implements ContainerService {
+
+ public static final Logger LOG = Logger.getLogger(AlarmService.class.getName());
+
+ private Container container;
+ private ClientEventService clientEventService;
+ private ManagerIdentityService identityService;
+ private NotificationService notificationService;
+ private PersistenceService persistenceService;
+ private TimerService timerService;
+
+ @Override
+ public int getPriority() {
+ return ContainerService.DEFAULT_PRIORITY;
+ }
+
+ @Override
+ public void init(Container container) throws Exception {
+ this.container = container;
+ this.clientEventService = container.getService(ClientEventService.class);
+ this.identityService = container.getService(ManagerIdentityService.class);
+ this.notificationService = container.getService(NotificationService.class);
+ this.persistenceService = container.getService(PersistenceService.class);
+ this.timerService = container.getService(TimerService.class);
+ container.getService(MessageBrokerService.class).getContext().addRoutes(this);
+ container.getService(ManagerWebService.class).addApiSingleton(
+ new AlarmResourceImpl(timerService, identityService, this)
+ );
+ clientEventService.addSubscriptionAuthorizer((realm, authContext, eventSubscription) -> {
+ if (!eventSubscription.isEventType(AlarmEvent.class) || authContext == null) {
+ return false;
+ }
+
+ // If not a superuser force a filter for the users realm
+ if (!authContext.isSuperUser()) {
+ @SuppressWarnings("unchecked")
+ EventSubscription<AlarmEvent> subscription = (EventSubscription<AlarmEvent>) eventSubscription;
+ subscription.setFilter(new RealmFilter<>(authContext.getAuthenticatedRealmName()));
+ }
+
+ return true;
+ });
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void configure() throws Exception {
+
+ }
+
+ /**
+ * Returns a set of all realms of the given alarms.
+ */
+ protected Set<String> getAlarmRealms(List<SentAlarm> alarms) {
+ return alarms == null ? Set.of() : alarms.stream().map(SentAlarm::getRealm).collect(Collectors.toSet());
+ }
+
+ /**
+ * Throws an {@link IllegalArgumentException} if {@code alarmId} is null or negative.
+ */
+ protected void validateAlarmId(Long alarmId) {
+ if (alarmId == null) {
+ throw new IllegalArgumentException("Missing alarm ID");
+ }
+ if (alarmId < 0) {
+ throw new IllegalArgumentException("Alarm ID cannot be negative");
+ }
+ }
+
+ /**
+ * Throws an {@link IllegalArgumentException} if the given {@code alarmIds} are null, empty or negative.
+ */
+ protected void validateAlarmIds(Collection<Long> alarmIds) {
+ if (alarmIds == null || alarmIds.isEmpty()) {
+ throw new IllegalArgumentException("Missing alarm IDs");
+ }
+ alarmIds.forEach(this::validateAlarmId);
+ }
+
+ /**
+ * Validates if the {@code alarm} is non-null and the user can access to the alarm realm.
+ */
+ protected void validateAlarmExistsAndAccessible(SentAlarm alarm, String userId) {
+ if (alarm == null) {
+ throw new EntityNotFoundException("Alarm does not exist");
+ }
+ validateRealmAccessibleToUser(userId, alarm.getRealm());
+ }
+
+ /**
+ * Validates if the {@code alarms} are non-null, match the alarmIds length and the user has access to all alarm realms.
+ */
+ protected void validateAlarmsExistAndAccessible(List<Long> alarmIds, List<SentAlarm> alarms, String userId) {
+ if (alarms == null || alarmIds.size() != alarms.size()) {
+ throw new EntityNotFoundException("One or more alarms do not exist");
+ }
+ validateRealmsAccessibleToUser(userId, getAlarmRealms(alarms));
+ }
+
+ /**
+ * Throws an {@link IllegalArgumentException} if the given {@code assetIds} are null or empty.
+ */
+ protected void validateAssetIds(Collection<String> assetIds) {
+ if (assetIds == null || assetIds.isEmpty()) {
+ throw new IllegalArgumentException("Missing asset IDs");
+ }
+ assetIds.forEach(assetId -> {
+ if (TextUtil.isNullOrEmpty(assetId)) {
+ throw new IllegalArgumentException("Missing asset ID");
+ }
+ });
+ }
+
+ /**
+ * Validates if the user has access to the given realm.
+ */
+ protected void validateRealmAccessibleToUser(String userId, String realm) {
+ validateRealmsAccessibleToUser(userId, Set.of(realm));
+ }
+
+ /**
+ * Validates if the user has access to all given realms.
+ */
+ protected void validateRealmsAccessibleToUser(String userId, Set<String> realms) {
+ if (userId == null) {
+ return;
+ }
+ ManagerIdentityProvider identityProvider = identityService.getIdentityProvider();
+ User user = identityProvider.getUser(userId);
+ if (user == null) {
+ throw new IllegalStateException("User does not exist");
+ }
+
+ if (!identityProvider.isMasterRealmAdmin(userId) &&
+ (realms.size() > 1 || !identityProvider.isUserInRealm(userId, realms.stream().findFirst().orElse(null)))) {
+ throw new SecurityException("Realm is not active or inaccessible");
+ }
+ }
+
+ /**
+ * Sends an alarm if the given user has access to the alarm realm.
+ */
+ public SentAlarm sendAlarm(Alarm alarm, List<String> assetIds, String userId) {
+ Objects.requireNonNull(alarm, "Alarm cannot be null");
+ Objects.requireNonNull(alarm.getRealm(), "Alarm realm cannot be null");
+ Objects.requireNonNull(alarm.getTitle(), "Alarm title cannot be null");
+ Objects.requireNonNull(alarm.getSeverity(), "Alarm severity cannot be null");
+ Objects.requireNonNull(alarm.getSource(), "Source cannot be null");
+ Objects.requireNonNull(alarm.getSourceId(), "Source ID cannot be null");
+
+ validateRealmAccessibleToUser(userId, alarm.getRealm());
+
+ Date timestamp = new Date(timerService.getCurrentTimeMillis());
+ SentAlarm sentAlarm = persistenceService.doReturningTransaction(entityManager -> entityManager.merge(new SentAlarm()
+ .setAssigneeId(alarm.getAssigneeId())
+ .setRealm(alarm.getRealm())
+ .setTitle(alarm.getTitle())
+ .setContent(alarm.getContent())
+ .setSeverity(alarm.getSeverity())
+ .setStatus(alarm.getStatus())
+ .setSource(alarm.getSource())
+ .setSourceId(alarm.getSourceId())
+ .setCreatedOn(timestamp)
+ .setLastModified(timestamp)));
+
+ if (assetIds != null && !assetIds.isEmpty()) {
+ linkAssets(assetIds, sentAlarm.getRealm(), sentAlarm.getId());
+ }
+
+ clientEventService.publishEvent(new AlarmEvent(alarm.getRealm(), PersistenceEvent.Cause.CREATE));
+ if (alarm.getSeverity() == Alarm.Severity.HIGH) {
+ Set<String> excludeUserIds = alarm.getSource() == MANUAL ? Set.of(alarm.getSourceId()) : Set.of();
+ sendAssigneeNotification(sentAlarm, excludeUserIds);
+ }
+
+ return sentAlarm;
+ }
+
+ /**
+ * Sends e-mail and push notifications for an alarm to the alarm assignee. If an assignee is not set all users having
+ * the {@link Constants#READ_ADMIN_ROLE} or {@link Constants#WRITE_ALARMS_ROLE} are notified.
+ *
+ * @param alarm the alarm to send e-mail and push notifications for
+ * @param excludeUserIds users matching these user IDs will are excluded from the notifications
+ */
+ protected void sendAssigneeNotification(SentAlarm alarm, Set<String> excludeUserIds) {
+ List<User> users = getAlarmNotificationUsers(alarm);
+ users.removeIf(user -> excludeUserIds.contains(user.getId()));
+ if (users.isEmpty()) {
+ LOG.fine("No matching users to send alarm notification");
+ return;
+ }
+
+ LOG.fine("Sending alarm notification to " + users.size() + " matching user(s)");
+
+ String title = String.format("Alarm: %s - %s", alarm.getSeverity(), alarm.getTitle());
+ String url = getAlarmNotificationUrl(alarm);
+ Map<String, String> content = getAlarmNotificationContent(alarm, url);
+
+ Notification email = new Notification()
+ .setName("New Alarm")
+ .setMessage(new EmailNotificationMessage()
+ .setHtml(getAlarmNotificationHtml(content))
+ .setSubject(title)
+ .setTo(users.stream()
+ .filter(user -> user.getEmail() != null && !user.getEmail().isBlank())
+ .map(user -> new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail())).toList()));
+
+ Notification push = new Notification();
+ push.setName("New Alarm")
+ .setMessage(
+ new PushNotificationMessage()
+ .setTitle(title)
+ .setBody(getAlarmNotificationText(content))
+ .setAction(url == null ? null : new PushNotificationAction(url))
+ )
+ .setTargets(users.stream().map(user -> new Notification.Target(Notification.TargetType.USER, user.getId())).toList());
+
+ notificationService.sendNotificationAsync(push, Notification.Source.INTERNAL, "alarms");
+ notificationService.sendNotificationAsync(email, Notification.Source.INTERNAL, "alarms");
+ }
+
+ private List<User> getAlarmNotificationUsers(SentAlarm alarm) {
+ ManagerIdentityProvider identityProvider = identityService.getIdentityProvider();
+ List<User> users = new ArrayList<>();
+ if (alarm.getAssigneeId() == null) {
+ UserQuery userQuery = new UserQuery()
+ .realm(new RealmPredicate(alarm.getRealm()))
+ .clientRoles(new StringPredicate(Constants.WRITE_ALARMS_ROLE))
+ .realmRoles(new StringPredicate(Constants.REALM_ADMIN_ROLE))
+ .serviceUsers(false);
+ users.addAll(Arrays.asList(identityProvider.queryUsers(userQuery)));
+ } else {
+ users.add(identityProvider.getUser(alarm.getAssigneeId()));
+ }
+ return users;
+ }
+
+ private String getAlarmNotificationUrl(SentAlarm alarm) {
+ String defaultHostname = getString(container.getConfig(), OR_HOSTNAME, null);
+ return defaultHostname == null ? null : String.format("https://%s/manager/#/alarms/%s?realm=%s", defaultHostname, alarm.getId(), alarm.getRealm());
+ }
+
+ private Map<String, String> getAlarmNotificationContent(SentAlarm alarm, String url) {
+ Map<String, String> result = new LinkedHashMap<>();
+ result.put("Title", alarm.getTitle());
+ result.put("Content", alarm.getContent());
+ result.put("Created", DateFormat.getDateTimeInstance().format(alarm.getCreatedOn()));
+ result.put("Source", alarm.getSource().name());
+ result.put("Severity", alarm.getSeverity().name());
+ result.put("Status", alarm.getStatus().name());
+
+ List<String> assetLinks = getAssetLinks(alarm.getId(), null, alarm.getRealm()).stream().map(AlarmAssetLink::getAssetName).toList();
+ result.put("Linked assets", assetLinks.isEmpty() ? "None" : String.join(", ", assetLinks));
+
+ result.put("Assignee", TextUtil.isNullOrEmpty(alarm.getAssigneeUsername()) ? "None" : alarm.getAssigneeUsername());
+
+ if (url != null) {
+ result.put("URL", url);
+ }
+
+ return result;
+ }
+
+ private String getAlarmNotificationHtml(Map<String, String> content) {
+ StringBuilder sb = new StringBuilder("<html><head><style>td {vertical-align: top;}</style></head><body><table>");
+ content.forEach((key, value) -> sb.append(String.format("<tr><td><b>%s</b></td><td>%s</td></tr>", key, value.replaceAll("\n", "<br>"))));
+ sb.append("</table><body></html>");
+ return sb.toString();
+ }
+
+ private String getAlarmNotificationText(Map<String, String> content) {
+ StringBuilder sb = new StringBuilder();
+ content.forEach((key, value) -> sb.append(String.format("%s: %s\n", key, value)));
+ return sb.toString();
+ }
+
+ /**
+ * Updates an existing alarm if the given user has access to the alarm realm.
+ */
+ public void updateAlarm(Long alarmId, String userId, SentAlarm alarm) {
+ SentAlarm oldAlarm = getAlarm(alarmId, userId);
+ String oldAssigneeId = oldAlarm.getAssigneeId();
+ String newAssigneeId = alarm.getAssigneeId();
+
+ if (newAssigneeId != null) {
+ validateRealmAccessibleToUser(newAssigneeId, alarm.getRealm());
+ }
+
+ persistenceService.doTransaction(entityManager -> entityManager.createQuery("""
+ update SentAlarm set title=:title, content=:content, severity=:severity, status=:status, lastModified=:lastModified, assigneeId=:assigneeId
+ where id =:id
+ """)
+ .setParameter("id", alarmId)
+ .setParameter("title", alarm.getTitle())
+ .setParameter("content", alarm.getContent())
+ .setParameter("severity", alarm.getSeverity())
+ .setParameter("status", alarm.getStatus())
+ .setParameter("lastModified", new Timestamp(timerService.getCurrentTimeMillis()))
+ .setParameter("assigneeId", newAssigneeId)
+ .executeUpdate());
+
+ clientEventService.publishEvent(new AlarmEvent(alarm.getRealm(), PersistenceEvent.Cause.UPDATE));
+
+ if (alarm.getSeverity() == Alarm.Severity.HIGH) {
+ Set<String> excludeUserIds = Stream.of(userId, oldAssigneeId).filter(Objects::nonNull).collect(Collectors.toSet());
+ sendAssigneeNotification(getAlarm(alarmId, userId), excludeUserIds);
+ }
+ }
+
+ /**
+ * Links one asset to an existing alarm.
+ */
+ public void linkAsset(String assetId, String realm, Long alarmId) {
+ linkAssets(List.of(assetId), realm, alarmId);
+ }
+
+ /**
+ * Links multiple assets to an existing alarm.
+ */
+ public void linkAssets(List<String> assetIds, String realm, Long alarmId) {
+ linkAssets(assetIds.stream().map(assetId -> new AlarmAssetLink(realm, alarmId, assetId)).toList(), null);
+ }
+
+ /**
+ * Links multiple assets to existing alarms if the given user has access to the alarm realms.
+ */
+ public void linkAssets(List<AlarmAssetLink> links, String userId) {
+ if (links == null || links.isEmpty()) {
+ throw new IllegalArgumentException("Missing links");
+ }
+
+ Set<Long> alarmIds = links.stream().map(link -> link.getId().getAlarmId()).collect(Collectors.toSet());
+ validateAlarmIds(alarmIds);
+
+ Set<String> assetIds = links.stream().map(link -> link.getId().getAssetId()).collect(Collectors.toSet());
+ validateAssetIds(assetIds);
+
+ if (userId != null) {
+ Set<String> realms = links.stream().map(link -> link.getId().getRealm()).collect(Collectors.toSet());
+ validateRealmsAccessibleToUser(userId, realms);
+ }
+
+ persistenceService.doTransaction(entityManager -> entityManager.unwrap(Session.class).doWork(connection -> {
+ PreparedStatement st = connection.prepareStatement("""
+ insert into ALARM_ASSET_LINK (sentalarm_id, realm, asset_id, created_on) values (?, ?, ?, ?)
+ on conflict (sentalarm_id, realm, asset_id) do nothing
+ """);
+ for (AlarmAssetLink link : links) {
+ st.setLong(1, link.getId().getAlarmId());
+ st.setString(2, link.getId().getRealm());
+ st.setString(3, link.getId().getAssetId());
+ st.setTimestamp(4, new Timestamp(timerService.getCurrentTimeMillis()));
+ st.addBatch();
+ }
+ st.executeBatch();
+ }));
+ }
+
+ /**
+ * Returns the assets linked to an alarm if the given user has access to the alarm realm.
+ */
+ public List<AlarmAssetLink> getAssetLinks(Long alarmId, String userId, String realm) throws IllegalArgumentException {
+ getAlarm(alarmId, userId);
+ return persistenceService.doReturningTransaction(entityManager ->
+ entityManager.createQuery("""
+ select aal from AlarmAssetLink aal
+ where aal.id.realm = :realm and aal.id.sentalarmId = :alarmId
+ order by aal.createdOn desc
+ """, AlarmAssetLink.class)
+ .setParameter("realm", realm)
+ .setParameter("alarmId", alarmId)
+ .getResultList()
+ );
+ }
+
+ /**
+ * Retrieves the details of an existing alarm if the given user has access to the alarm realm.
+ */
+ public SentAlarm getAlarm(Long alarmId, String userId) throws IllegalArgumentException {
+ validateAlarmId(alarmId);
+ SentAlarm alarm;
+ try {
+ alarm = persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery("select sa from SentAlarm sa where sa.id = :id", SentAlarm.class)
+ .setParameter("id", alarmId)
+ .getSingleResult());
+ } catch (PersistenceException e) {
+ alarm = null;
+ }
+ validateAlarmExistsAndAccessible(alarm, userId);
+ return alarm;
+ }
+
+ /**
+ * Retrieves the details of existing alarms if the given user has access to the alarm realms.
+ */
+ public List<SentAlarm> getAlarms(List<Long> alarmIds, String userId) throws IllegalArgumentException {
+ validateAlarmIds(alarmIds);
+ List<SentAlarm> alarms;
+ try {
+ alarms = persistenceService.doReturningTransaction(entityManager ->
+ entityManager.createQuery("select sa from SentAlarm sa where sa.id in :ids", SentAlarm.class)
+ .setParameter("ids", alarmIds)
+ .getResultList()
+ );
+ } catch (PersistenceException e) {
+ alarms = null;
+ }
+ validateAlarmsExistAndAccessible(alarmIds, alarms, userId);
+ return alarms;
+ }
+
+ /**
+ * Retrieves all existing alarms in a realm. The {@code status}, {@code assetId} and {@code assigneeId} parameters
+ * are optional and if non-null are used for filtering the alarms.
+ */
+ public List<SentAlarm> getAlarms(String realm, Alarm.Status status, String assetId, String assigneeId) throws IllegalArgumentException {
+ Map<String, Object> parameters = new HashMap<>();
+ StringBuilder sb = new StringBuilder("select sa from SentAlarm sa ");
+
+ if (assetId != null) {
+ sb.append("join AlarmAssetLink aal on sa.id = aal.id.sentalarmId where sa.realm = :realm and aal.id.assetId = :assetId ");
+ parameters.put("assetId", assetId);
+ } else {
+ sb.append("where sa.realm = :realm ");
+ }
+ parameters.put("realm", realm);
+
+ if (status != null) {
+ sb.append("and sa.status = :status ");
+ parameters.put("status", status);
+ }
+ if (assigneeId != null) {
+ sb.append("and sa.assigneeId = :assigneeId ");
+ parameters.put("assigneeId", assigneeId);
+ }
+ sb.append("order by sa.createdOn desc");
+
+ return persistenceService.doReturningTransaction(entityManager -> {
+ TypedQuery<SentAlarm> query = entityManager.createQuery(sb.toString(), SentAlarm.class);
+ parameters.forEach(query::setParameter);
+ return query.getResultList();
+ });
+ }
+
+ /**
+ * Removes an existing alarm if the given user has access to the alarm realm.
+ */
+ public void removeAlarm(Long alarmId, String userId) {
+ SentAlarm alarm = getAlarm(alarmId, userId);
+ persistenceService.doTransaction(entityManager -> entityManager
+ .createQuery("delete SentAlarm where id = :id")
+ .setParameter("id", alarmId)
+ .executeUpdate()
+ );
+ clientEventService.publishEvent(new AlarmEvent(alarm.getRealm(), PersistenceEvent.Cause.DELETE));
+ }
+
+ /**
+ * Removes existing alarms if the given user has access to the alarm realms.
+ */
+ public void removeAlarms(List<Long> alarmIds, String userId) throws IllegalArgumentException {
+ List<SentAlarm> alarms = getAlarms(alarmIds, userId);
+ persistenceService.doTransaction(entityManager ->
+ entityManager.createQuery("delete from SentAlarm sa where sa.id in :ids")
+ .setParameter("ids", alarmIds)
+ .executeUpdate()
+ );
+
+ getAlarmRealms(alarms).forEach(realm -> clientEventService.publishEvent(new AlarmEvent(realm, PersistenceEvent.Cause.DELETE)));
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
index 692e3061f..40aad99c0 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
@@ -42,7 +42,7 @@ public class NotificationProcessingException extends RuntimeException {
/**
* Missing {@link AbstractNotificationMessage}.
*/
- MISSING_MESSAGE,
+ MISSING_CONTENT,
/**
* Missing {@link Notification.Target}.
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
index 7b71aab1f..86dea7df1 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -54,6 +54,7 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.time.temporal.ChronoUnit.*;
+import static java.util.Map.entry;
import static org.openremote.manager.notification.NotificationProcessingException.Reason.*;
import static org.openremote.model.notification.Notification.HEADER_SOURCE;
import static org.openremote.model.notification.Notification.Source.*;
@@ -119,7 +120,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
LOG.finest("Processing: " + notification.getName());
if (notification.getMessage() == null) {
- throw new NotificationProcessingException(MISSING_MESSAGE, "Notification message must be set");
+ throw new NotificationProcessingException(MISSING_CONTENT, "Notification message must be set");
}
Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Notification.Source.class);
@@ -273,16 +274,16 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
public void sendNotificationAsync(Notification notification, Notification.Source source, String sourceId) {
- Map<String, Object> headers = new HashMap<>();
- headers.put(Notification.HEADER_SOURCE, source);
- headers.put(Notification.HEADER_SOURCE_ID, sourceId);
+ Map<String, Object> headers = Map.ofEntries(
+ entry(Notification.HEADER_SOURCE, source),
+ entry(Notification.HEADER_SOURCE_ID, sourceId));
messageBrokerService.getFluentProducerTemplate().withBody(notification).withHeaders(headers).to(NotificationService.NOTIFICATION_QUEUE).send();
}
public boolean sendNotification(Notification notification, Notification.Source source, String sourceId) {
- Map<String, Object> headers = new HashMap<>();
- headers.put(Notification.HEADER_SOURCE, source);
- headers.put(Notification.HEADER_SOURCE_ID, sourceId);
+ Map<String, Object> headers = Map.ofEntries(
+ entry(Notification.HEADER_SOURCE, source),
+ entry(Notification.HEADER_SOURCE_ID, sourceId));
return messageBrokerService.getFluentProducerTemplate().withBody(notification).withHeaders(headers).to(NotificationService.NOTIFICATION_QUEUE).request(Boolean.class);
}
@@ -328,6 +329,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
IntStream.rangeClosed(1, parameters.size())
.forEach(i -> query.setParameter(i, parameters.get(i-1)));
return query.getResultList();
+
});
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 225a237f6..78f8e41e2 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -19,10 +19,11 @@
*/
package org.openremote.manager.rules;
+import org.openremote.model.PersistenceEvent;
import jakarta.ws.rs.core.MediaType;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
-import org.openremote.model.PersistenceEvent;
+import org.openremote.model.alarm.Alarm;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.UserAssetLink;
import org.openremote.model.attribute.AttributeEvent;
@@ -79,6 +80,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
}
+
/**
* Stores all state for a given {@link RuleCondition} and calculates which {@link AttributeInfo}s match and don't
* match the condition.
@@ -271,8 +273,8 @@ public class JsonRulesBuilder extends RulesBuilder {
} else {
Map<Boolean, List<AttributeInfo>> results = new HashMap<>();
- ArrayList<AttributeInfo> matched = new ArrayList<>();
- ArrayList<AttributeInfo> unmatched = new ArrayList<>();
+ List<AttributeInfo> matched = new ArrayList<>();
+ List<AttributeInfo> unmatched = new ArrayList<>();
results.put(true, matched);
results.put(false, unmatched);
@@ -534,6 +536,7 @@ public class JsonRulesBuilder extends RulesBuilder {
final protected Users usersFacade;
final protected Notifications notificationsFacade;
final protected Webhooks webhooksFacade;
+ final protected Alarms alarmsFacade;
final protected HistoricDatapoints historicDatapointsFacade;
final protected PredictedDatapoints predictedDatapointsFacade;
final protected ScheduledExecutorService executorService;
@@ -546,7 +549,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public JsonRulesBuilder(Logger logger, Ruleset ruleset, TimerService timerService,
AssetStorageService assetStorageService, ScheduledExecutorService executorService,
Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,
- HistoricDatapoints historicDatapoints, PredictedDatapoints predictedDatapoints,
+ Alarms alarmsFacade, HistoricDatapoints historicDatapoints, PredictedDatapoints predictedDatapoints,
BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {
this.timerService = timerService;
this.assetStorageService = assetStorageService;
@@ -555,6 +558,7 @@ public class JsonRulesBuilder extends RulesBuilder {
this.usersFacade = usersFacade;
this.notificationsFacade = notificationsFacade;
this.webhooksFacade = webhooksFacade;
+ this.alarmsFacade = alarmsFacade;
this.historicDatapointsFacade= historicDatapoints;
this.predictedDatapointsFacade = predictedDatapoints;
this.scheduledActionConsumer = scheduledActionConsumer;
@@ -580,7 +584,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public void stop(RulesFacts facts) {
Arrays.stream(jsonRules).forEach(jsonRule ->
- executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
+ executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, alarmsFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
// Remove temporal fact for timer rule evaluation
String tempFactName = TIMER_TEMPORAL_FACT_NAME_PREFIX + jsonRuleset.getId();
@@ -590,7 +594,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public void start(RulesFacts facts) {
Arrays.stream(jsonRules).forEach(jsonRule -> {
- executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, this.scheduledActionConsumer);
+ executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, alarmsFacade, predictedDatapointsFacade, this.scheduledActionConsumer);
});
// Initialise asset states
@@ -669,12 +673,12 @@ public class JsonRulesBuilder extends RulesBuilder {
try {
if (ruleState.thenMatched()) {
log(Level.FINEST, "Triggered rule so executing 'then' actions for rule: " + rule.name);
- executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, scheduledActionConsumer);
+ executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, alarmsFacade, predictedDatapointsFacade, scheduledActionConsumer);
}
if (rule.otherwise != null && ruleState.otherwiseMatched()) {
log(Level.FINEST, "Triggered rule so executing 'otherwise' actions for rule: " + rule.name);
- executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, predictedDatapointsFacade, scheduledActionConsumer);
+ executeRuleActions(rule, rule.otherwise, "otherwise", true, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, alarmsFacade, predictedDatapointsFacade, scheduledActionConsumer);
}
} catch (Exception e) {
log(Level.SEVERE, "Exception thrown during rule RHS execution", e);
@@ -716,7 +720,7 @@ public class JsonRulesBuilder extends RulesBuilder {
};
}
- public void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, PredictedDatapoints predictedDatapointsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {
+ public void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, Alarms alarmsFacade, PredictedDatapoints predictedDatapointsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {
if (ruleActions != null && ruleActions.length > 0) {
@@ -737,6 +741,7 @@ public class JsonRulesBuilder extends RulesBuilder {
usersFacade,
notificationsFacade,
webhooksFacade,
+ alarmsFacade,
predictedDatapointsFacade
);
@@ -765,7 +770,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
@SuppressWarnings({"rawtypes", "unchecked"})
- protected RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, PredictedDatapoints predictedDatapointsFacade) {
+ protected RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, Alarms alarmsFacade, PredictedDatapoints predictedDatapointsFacade) {
if (ruleAction instanceof RuleActionNotification notificationAction) {
@@ -934,6 +939,38 @@ public class JsonRulesBuilder extends RulesBuilder {
return new RuleActionExecution(() -> webhooksFacade.send(webhook, webhookAction.mediaType, webhookAction.target), 0);
}
+ if (ruleAction instanceof RuleActionAlarm alarmAction && (alarmAction.alarm != null)) {
+ Alarm alarm = alarmAction.alarm;
+ List<String> assetIds = new ArrayList<>(getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts));
+ if (alarm.getContent() != null) {
+ String content = alarm.getContent();
+ if (!TextUtil.isNullOrEmpty(content) && (content.contains(PLACEHOLDER_TRIGGER_ASSETS))) {
+ // Need to clone the alarm
+ alarm = ValueUtil.clone(alarm);
+ Map<String, Set<AttributeInfo>> assetStates = getMatchedAssetStates(ruleState, useUnmatched, null, null);
+ alarm.setContent(getAlarmContent(content, assetStates));
+ }
+ }
+ else {
+ log(Level.WARNING, "Alarm content is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
+ }
+ if (alarm.getSeverity() == null) {
+ log(Level.WARNING, "Alarm severity is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
+ }
+ if (alarm.getTitle() == null) {
+ log(Level.WARNING, "Alarm title is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
+ }
+
+ alarm.setAssigneeId(alarmAction.assigneeId);
+ alarm.setSourceId(Long.toString(jsonRuleset.getId()));
+
+ Alarm finalAlarm = alarm;
+ return new RuleActionExecution(() -> alarmsFacade.create(finalAlarm, assetIds), 0);
+ }
+
if (ruleAction instanceof RuleActionWriteAttribute attributeAction) {
if (targetIsNotAssets(ruleAction.target)) {
@@ -1122,6 +1159,19 @@ public class JsonRulesBuilder extends RulesBuilder {
return realm;
}
+ protected String getAlarmContent(String sourceText, Map<String, Set<AttributeInfo>> assetStates) {
+ StringBuilder sb = new StringBuilder();
+
+ assetStates.forEach((key, value) -> value.forEach(assetState -> {
+ sb.append("ID: ").append(assetState.getId()).append("\n");
+ sb.append("Asset name: ").append(assetState.getAssetName()).append("\n");
+ sb.append("Attribute name: ").append(assetState.getName()).append("\n");
+ sb.append("Value: ").append(assetState.getValue().flatMap(ValueUtil::asJSON).orElse("")).append("\n");
+ }));
+
+ return sourceText.replace(PLACEHOLDER_TRIGGER_ASSETS, sb.toString());
+ }
+
protected String insertTriggeredAssetInfo(String sourceText, Map<String, Set<AttributeInfo>> assetStates, boolean isHtml, boolean isJson) {
StringBuilder sb = new StringBuilder();
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index ced5cc15b..675327a72 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -29,6 +29,7 @@ import org.jeasy.rules.api.RulesEngineParameters;
import org.jeasy.rules.core.AbstractRulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.openremote.container.timer.TimerService;
+import org.openremote.manager.alarm.AlarmService;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.datapoint.AssetDatapointService;
@@ -109,6 +110,7 @@ public class RulesEngine<T extends Ruleset> {
final protected Users usersFacade;
final protected Notifications notificationFacade;
final protected Webhooks webhooksFacade;
+ final protected Alarms alarmsFacade;
final protected PredictedDatapoints predictedFacade;
final protected HistoricDatapoints historicFacade;
final protected AssetLocationPredicateProcessor assetLocationPredicatesConsumer;
@@ -136,6 +138,7 @@ public class RulesEngine<T extends Ruleset> {
AssetProcessingService assetProcessingService,
NotificationService notificationService,
WebhookService webhookService,
+ AlarmService alarmService,
ClientEventService clientEventService,
AssetDatapointService assetDatapointService,
AssetPredictedDatapointService assetPredictedDatapointService,
@@ -163,6 +166,7 @@ public class RulesEngine<T extends Ruleset> {
this.usersFacade = new UsersFacade<>(id, assetStorageService, notificationService, identityService);
this.notificationFacade = new NotificationsFacade<>(id, notificationService);
this.webhooksFacade = new WebhooksFacade<>(id, webhookService);
+ this.alarmsFacade = new AlarmFacade<>(id, alarmService);
this.historicFacade = new HistoricFacade<>(id, assetDatapointService);
this.predictedFacade = new PredictedFacade<>(id, assetPredictedDatapointService);
this.assetLocationPredicatesConsumer = assetLocationPredicatesConsumer;
@@ -271,7 +275,7 @@ public class RulesEngine<T extends Ruleset> {
removeRuleset(deployment.ruleset);
}
- deployment = new RulesetDeployment(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationFacade, webhooksFacade, historicFacade, predictedFacade);
+ deployment = new RulesetDeployment(ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationFacade, webhooksFacade, alarmsFacade, historicFacade, predictedFacade);
deployment.init();
deployments.put(ruleset.getId(), deployment);
publishRulesetStatus(deployment);
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 87746c0c0..7916f7368 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -35,6 +35,7 @@ import org.openremote.manager.event.AttributeEventInterceptor;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.notification.NotificationService;
+import org.openremote.manager.alarm.AlarmService;
import org.openremote.manager.rules.flow.FlowResourceImpl;
import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;
import org.openremote.manager.security.ManagerIdentityService;
@@ -128,6 +129,7 @@ public class RulesService extends RouteBuilder implements ContainerService {
protected AssetStorageService assetStorageService;
protected NotificationService notificationService;
protected WebhookService webhookService;
+ protected AlarmService alarmService;
protected AssetProcessingService assetProcessingService;
protected AssetDatapointService assetDatapointService;
protected AssetPredictedDatapointService assetPredictedDatapointService;
@@ -164,6 +166,7 @@ public class RulesService extends RouteBuilder implements ContainerService {
identityService = container.getService(ManagerIdentityService.class);
notificationService = container.getService(NotificationService.class);
webhookService = container.getService(WebhookService.class);
+ alarmService = container.getService(AlarmService.class);
assetStorageService = container.getService(AssetStorageService.class);
assetProcessingService = container.getService(AssetProcessingService.class);
assetDatapointService = container.getService(AssetDatapointService.class);
@@ -644,6 +647,7 @@ public class RulesService extends RouteBuilder implements ContainerService {
assetProcessingService,
notificationService,
webhookService,
+ alarmService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
@@ -685,6 +689,7 @@ public class RulesService extends RouteBuilder implements ContainerService {
assetProcessingService,
notificationService,
webhookService,
+ alarmService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
@@ -754,6 +759,7 @@ public class RulesService extends RouteBuilder implements ContainerService {
assetProcessingService,
notificationService,
webhookService,
+ alarmService,
clientEventService,
assetDatapointService,
assetPredictedDatapointService,
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index 48d868394..74ad3e399 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -95,6 +95,7 @@ public class RulesetDeployment {
final protected Users usersFacade;
final protected Notifications notificationsFacade;
final protected Webhooks webhooksFacade;
+ final protected Alarms alarmsFacade;
final protected HistoricDatapoints historicDatapointsFacade;
final protected PredictedDatapoints predictedDatapointsFacade;
final protected List<ScheduledFuture<?>> scheduledRuleActions = Collections.synchronizedList(new ArrayList<>());
@@ -110,7 +111,7 @@ public class RulesetDeployment {
public RulesetDeployment(Ruleset ruleset, TimerService timerService,
AssetStorageService assetStorageService, ScheduledExecutorService executorService,
Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade,
- HistoricDatapoints historicDatapointsFacade, PredictedDatapoints predictedDatapointsFacade) {
+ Alarms alarmsFacade, HistoricDatapoints historicDatapointsFacade, PredictedDatapoints predictedDatapointsFacade) {
this.ruleset = ruleset;
this.timerService = timerService;
this.assetStorageService = assetStorageService;
@@ -119,6 +120,7 @@ public class RulesetDeployment {
this.usersFacade = usersFacade;
this.notificationsFacade = notificationsFacade;
this.webhooksFacade = webhooksFacade;
+ this.alarmsFacade = alarmsFacade;
this.historicDatapointsFacade = historicDatapointsFacade;
this.predictedDatapointsFacade = predictedDatapointsFacade;
@@ -286,7 +288,7 @@ public class RulesetDeployment {
protected boolean compileRulesJson(Ruleset ruleset) {
try {
- jsonRulesBuilder = new JsonRulesBuilder(LOG, ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, historicDatapointsFacade, predictedDatapointsFacade, this::scheduleRuleAction);
+ jsonRulesBuilder = new JsonRulesBuilder(LOG, ruleset, timerService, assetStorageService, executorService, assetsFacade, usersFacade, notificationsFacade, webhooksFacade, alarmsFacade, historicDatapointsFacade, predictedDatapointsFacade, this::scheduleRuleAction);
for (Rule rule : jsonRulesBuilder.build()) {
LOG.finest("Registering JSON rule: " + rule.getName());
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java
new file mode 100644
index 000000000..6e544f5dc
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2024, 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.manager.rules.facade;
+
+import java.util.List;
+
+import org.openremote.manager.alarm.AlarmService;
+import org.openremote.manager.rules.RulesEngineId;
+import org.openremote.model.rules.GlobalRuleset;
+import org.openremote.model.rules.RealmRuleset;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.alarm.Alarm;
+import org.openremote.model.alarm.Alarm.Source;
+import org.openremote.model.rules.Alarms;
+
+public class AlarmFacade<T extends Ruleset> extends Alarms {
+ protected final RulesEngineId<T> rulesEngineId;
+ protected final AlarmService alarmService;
+
+ public AlarmFacade(RulesEngineId<T> rulesEngineId, AlarmService alarmService) {
+ this.rulesEngineId = rulesEngineId;
+ this.alarmService = alarmService;
+ }
+
+ public Long create(Alarm alarm, List<String> assetIds) {
+ Alarm.Source source;
+
+ if (rulesEngineId.getScope() == GlobalRuleset.class) {
+ source = Source.GLOBAL_RULESET;
+ } else if (rulesEngineId.getScope() == RealmRuleset.class) {
+ source = Source.REALM_RULESET;
+ } else {
+ source = Source.ASSET_RULESET;
+ }
+
+ alarm.setRealm(rulesEngineId.getRealm().orElseThrow());
+ alarm.setSource(source);
+
+ return alarmService.sendAlarm(alarm, assetIds, null).getId();
+ }
+
+ public void linkAssets(List<String> assetIds, Long alarmId) {
+ if (assetIds != null && !assetIds.isEmpty()) {
+ String realmId = rulesEngineId.getRealm().orElseThrow(() -> new IllegalStateException("Realm ruleset must have a realm ID"));
+ alarmService.linkAssets(assetIds, realmId, alarmId);
+ }
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index 1078b3e1e..a0adddaff 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -33,6 +33,7 @@ import org.openremote.model.util.TextUtil;
import jakarta.persistence.Tuple;
import java.util.*;
+import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -40,6 +41,7 @@ import static org.openremote.model.query.filter.StringPredicate.toSQLParameter;
import static org.openremote.model.Constants.MASTER_REALM;
// TODO: Normalise interface for Basic and Keycloak providers and add client CRUD
+
/**
* SPI for implementations used by {@link ManagerIdentityService}, provides CRUD of
* {@link User} and {@link Realm}.
@@ -68,9 +70,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
Role[] getUserRealmRoles(String realm, String userId);
- void updateUserRoles(String realm, String userId, String client, String...roles);
+ void updateUserRoles(String realm, String userId, String client, String... roles);
- void updateUserRealmRoles(String realm, String userId, String...roles);
+ void updateUserRealmRoles(String realm, String userId, String... roles);
boolean isMasterRealmAdmin(String userId);
@@ -111,7 +113,7 @@ public interface ManagerIdentityProvider extends IdentityProvider {
* BELOW ARE STATIC HELPER METHODS
*/
- default String[] addRealmRoles(String realm, String userId, String...roles) {
+ default String[] addRealmRoles(String realm, String userId, String... roles) {
Set<String> realmRoles = Arrays.stream(getUserRealmRoles(realm, userId)).filter(role -> role.isAssigned() || Arrays.stream(roles).anyMatch(r -> role.getName().equals(r))).map(Role::getName).collect(Collectors.toCollection(LinkedHashSet::new));
realmRoles.addAll(Arrays.asList(roles));
return realmRoles.toArray(new String[0]);
@@ -130,8 +132,8 @@ public interface ManagerIdentityProvider extends IdentityProvider {
userQuery.usernames = new StringPredicate[1];
userQuery.usernames(new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(!userQuery.serviceUsers));
} else {
- userQuery.usernames = Arrays.copyOf(userQuery.usernames, userQuery.usernames.length+1);
- userQuery.usernames[userQuery.usernames.length-1] = new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(!userQuery.serviceUsers);
+ userQuery.usernames = Arrays.copyOf(userQuery.usernames, userQuery.usernames.length + 1);
+ userQuery.usernames[userQuery.usernames.length - 1] = new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(!userQuery.serviceUsers);
}
}
@@ -175,24 +177,39 @@ public interface ManagerIdentityProvider extends IdentityProvider {
}
sb.append(")");
}
- if (userQuery.realmRoles != null && userQuery.realmRoles.length > 0) {
- sb.append(" and (FALSE");
-
- Arrays.stream(userQuery.realmRoles).forEach(realmPredicate -> {
- sb.append(" OR ");
- if (realmPredicate.negate) {
- // Negation implies does not contain this match so use a sub query in the where clause with not
- // exists otherwise it will just match any other row
- sb.append("NOT ");
- }
- sb.append("EXISTS (SELECT urm.user_id from public.user_role_mapping urm join public.keycloak_role kr on urm.role_id = kr.id where urm.user_id = u.id and not kr.client_role and");
- sb.append(realmPredicate.caseSensitive ? " kr.name" : " upper(kr.name)");
- sb.append(StringPredicate.toSQLParameter(realmPredicate, parameters.size() + 1, realmPredicate.negate));
- parameters.add(realmPredicate.prepareValue());
+ boolean hasClientRoles = userQuery.clientRoles != null && userQuery.clientRoles.length > 0;
+ boolean hasRealmRoles = userQuery.realmRoles != null && userQuery.realmRoles.length > 0;
+ if (hasClientRoles || hasRealmRoles) {
+ sb.append(" and (FALSE");
- sb.append(")");
- });
+ BiConsumer<StringPredicate[], Boolean> appendRolePredicates = (rolePredicates, clientRolePredicates) -> {
+ Arrays.stream(rolePredicates).forEach(rolePredicate -> {
+ sb.append(" OR ");
+ if (rolePredicate.negate) {
+ // Negation implies does not contain this match so use a sub query in the where clause with not
+ // exists otherwise it will just match any other row
+ sb.append("NOT ");
+ }
+ sb.append("EXISTS (SELECT urm.user_id from public.user_role_mapping urm join public.keycloak_role kr on urm.role_id = kr.id where urm.user_id = u.id and ");
+ if (!clientRolePredicates) {
+ sb.append("not ");
+ }
+ sb.append("kr.client_role and");
+ sb.append(rolePredicate.caseSensitive ? " kr.name" : " upper(kr.name)");
+ sb.append(StringPredicate.toSQLParameter(rolePredicate, parameters.size() + 1, rolePredicate.negate));
+ parameters.add(rolePredicate.prepareValue());
+
+ sb.append(")");
+ });
+ };
+
+ if (hasClientRoles) {
+ appendRolePredicates.accept(userQuery.clientRoles, true);
+ }
+ if (hasRealmRoles) {
+ appendRolePredicates.accept(userQuery.realmRoles, false);
+ }
sb.append(")");
}
@@ -229,7 +246,7 @@ public interface ManagerIdentityProvider extends IdentityProvider {
if (userQuery.orderBy != null) {
if (userQuery.orderBy.property != null) {
sb.append(" ORDER BY");
- switch(userQuery.orderBy.property) {
+ switch (userQuery.orderBy.property) {
case CREATED_ON:
sb.append(" u.created_on");
break;
@@ -257,7 +274,7 @@ public interface ManagerIdentityProvider extends IdentityProvider {
List<User> users = persistenceService.doReturningTransaction(entityManager -> {
Query sqlQuery = entityManager.createNativeQuery(sb.toString(), User.class);
- IntStream.rangeClosed(1, parameters.size()).forEach(i -> sqlQuery.setParameter(i, parameters.get(i-1)));
+ IntStream.rangeClosed(1, parameters.size()).forEach(i -> sqlQuery.setParameter(i, parameters.get(i - 1)));
if (userQuery.limit != null && userQuery.limit > 0) {
sqlQuery.setMaxResults(userQuery.limit);
@@ -286,10 +303,10 @@ public interface ManagerIdentityProvider extends IdentityProvider {
static User getUserByUsernameFromDb(PersistenceService persistenceService, String realm, String username) {
return persistenceService.doReturningTransaction(em -> {
List<User> result =
- em.createQuery("select u from User u where u.realm = :realm and u.username = :username", User.class)
- .setParameter("realm", realm)
- .setParameter("username", username)
- .getResultList();
+ em.createQuery("select u from User u where u.realm = :realm and u.username = :username", User.class)
+ .setParameter("realm", realm)
+ .setParameter("username", username)
+ .getResultList();
return result.size() > 0 ? result.get(0) : null;
});
}
@@ -297,9 +314,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
static User getUserByIdFromDb(PersistenceService persistenceService, String userId) {
return persistenceService.doReturningTransaction(em -> {
List<User> result =
- em.createQuery("select u from User u where u.id = :userId", User.class)
- .setParameter("userId", userId)
- .getResultList();
+ em.createQuery("select u from User u where u.id = :userId", User.class)
+ .setParameter("userId", userId)
+ .getResultList();
return result.size() > 0 ? result.get(0) : null;
});
}
@@ -309,16 +326,16 @@ public interface ManagerIdentityProvider extends IdentityProvider {
return persistenceService.doReturningTransaction(em -> {
Map<String, String> usernameIdMap = em.createQuery(
- "select u.username, u.id from User u join Realm r on r.id = u.realmId where u.username in :usernames and r.name = :realm", Tuple.class)
+ "select u.username, u.id from User u join Realm r on r.id = u.realmId where u.username in :usernames and r.name = :realm", Tuple.class)
.setParameter("usernames", CIUsernames)
.setParameter("realm", realm)
.getResultList()
.stream()
.collect(
- Collectors.toMap(
- tuple -> (String) tuple.get(0),
- tuple -> (String) tuple.get(1)
- )
+ Collectors.toMap(
+ tuple -> (String) tuple.get(0),
+ tuple -> (String) tuple.get(1)
+ )
);
return CIUsernames.stream().map(usernameIdMap::get).collect(Collectors.toList());
@@ -328,9 +345,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
@SuppressWarnings("unchecked")
static Realm[] getRealmsFromDb(PersistenceService persistenceService) {
return persistenceService.doReturningTransaction(entityManager -> {
- List<Realm> realms = (List<Realm>)entityManager.createNativeQuery(
- "select *, (select ra.VALUE from PUBLIC.REALM_ATTRIBUTE ra where ra.REALM_ID = r.ID and ra.name = 'displayName') as displayName from public.realm r where r.not_before is null or r.not_before = 0 or r.not_before <= extract('epoch' from now())"
- , Realm.class).getResultList();
+ List<Realm> realms = (List<Realm>) entityManager.createNativeQuery(
+ "select *, (select ra.VALUE from PUBLIC.REALM_ATTRIBUTE ra where ra.REALM_ID = r.ID and ra.name = 'displayName') as displayName from public.realm r where r.not_before is null or r.not_before = 0 or r.not_before <= extract('epoch' from now())"
+ , Realm.class).getResultList();
// Make sure the master realm is always on top
realms.sort((o1, o2) -> {
@@ -350,23 +367,23 @@ public interface ManagerIdentityProvider extends IdentityProvider {
static Realm getRealmFromDb(PersistenceService persistenceService, String realm) {
return persistenceService.doReturningTransaction(em -> {
- List<Realm> realms = em.createQuery("select r from Realm r where r.name = :realm", Realm.class)
- .setParameter("realm", realm).getResultList();
+ List<Realm> realms = em.createQuery("select r from Realm r where r.name = :realm", Realm.class)
+ .setParameter("realm", realm).getResultList();
- // TODO: Remove this once migrated to hibernate 6.2.x+
- realms.forEach(r -> r.getRealmRoles().size());
+ // TODO: Remove this once migrated to hibernate 6.2.x+
+ realms.forEach(r -> r.getRealmRoles().size());
- return realms.size() == 1 ? realms.get(0) : null;
- }
+ return realms.size() == 1 ? realms.get(0) : null;
+ }
);
}
static boolean realmExistsFromDb(PersistenceService persistenceService, String realm) {
return persistenceService.doReturningTransaction(em -> {
- long count = (long)em.createNativeQuery(
- "select count(*) from public.realm r where r.name = :realm and r.enabled = true and (r.not_before is null or r.not_before = 0 or r.not_before <= extract('epoch' from now()))",
- Long.class).setParameter("realm", realm).getSingleResult();
+ long count = (long) em.createNativeQuery(
+ "select count(*) from public.realm r where r.name = :realm and r.enabled = true and (r.not_before is null or r.not_before = 0 or r.not_before <= extract('epoch' from now()))",
+ Long.class).setParameter("realm", realm).getSingleResult();
return count > 0;
});
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
index b8b651839..84aaed08b 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
@@ -51,10 +51,12 @@ public abstract class AbstractKeycloakSetup implements Setup {
ClientRole.READ_USERS,
ClientRole.READ_RULES,
ClientRole.READ_INSIGHTS,
+ ClientRole.READ_ALARMS,
ClientRole.WRITE_ASSETS,
ClientRole.WRITE_ATTRIBUTES,
ClientRole.WRITE_RULES,
- ClientRole.WRITE_INSIGHTS
+ ClientRole.WRITE_INSIGHTS,
+ ClientRole.WRITE_ALARMS
};
final protected Container container;
@@ -73,7 +75,7 @@ public abstract class AbstractKeycloakSetup implements Setup {
return keycloakProvider;
}
- protected Realm createRealm(String realmName, String displayName, boolean rememberMe) {
+ public Realm createRealm(String realmName, String displayName, boolean rememberMe) {
Realm realm = new Realm();
realm.setName(realmName);
realm.setDisplayName(displayName);
@@ -84,11 +86,11 @@ public abstract class AbstractKeycloakSetup implements Setup {
return realm;
}
- protected User createUser(String realm, String username, String password, String firstName, String lastName, String email, boolean enabled, ClientRole[] roles) {
+ public User createUser(String realm, String username, String password, String firstName, String lastName, String email, boolean enabled, ClientRole[] roles) {
return createUser(realm, username, password, firstName, lastName, email, enabled, false, false, roles);
}
- protected User createUser(String realm, String username, String password, String firstName, String lastName, String email, boolean enabled, boolean emailNotificationsDisabled, boolean pushNotificationsDisabled, ClientRole[] roles) {
+ public User createUser(String realm, String username, String password, String firstName, String lastName, String email, boolean enabled, boolean emailNotificationsDisabled, boolean pushNotificationsDisabled, ClientRole[] roles) {
User user = new User();
user.setUsername(username);
user.setFirstName(firstName);
@@ -115,7 +117,7 @@ public abstract class AbstractKeycloakSetup implements Setup {
* Default realm roles will assign manage-account role to account client so we have to remove this role from the composite default roles
* This is a temporary thing and when/if we move to groups we should look at explicit default roles on realm creation
*/
- protected void removeManageAccount(String realm) {
+ public void removeManageAccount(String realm) {
keycloakProvider.<Void>getRealms(
realmsResource -> {
RealmResource realmResource = realmsResource.realm(realm);
diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
index ed76c9c6a..6c09fd7bd 100644
--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
@@ -34,4 +34,5 @@ org.openremote.manager.security.AuthorisationService
org.openremote.manager.app.ConfigurationService
org.openremote.manager.asset.ForecastService
org.openremote.manager.setup.KeycloakInitService
+org.openremote.manager.alarm.AlarmService
org.openremote.manager.security.KeyStoreServiceImpl
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20240813_01__Alarms.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20240813_01__Alarms.sql
new file mode 100644
index 000000000..2e14a14b4
--- /dev/null
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20240813_01__Alarms.sql
@@ -0,0 +1,35 @@
+create table ALARM (
+ ID int8 not null,
+ REALM varchar(255) not null,
+ TITLE varchar(255) not null,
+ CONTENT varchar(4096),
+ SEVERITY varchar(15) not null,
+ STATUS varchar(15) not null,
+ SOURCE varchar(50) not null,
+ SOURCE_ID varchar(43) not null,
+ CREATED_ON timestamp with time zone not null,
+ ACKNOWLEDGED_ON timestamp with time zone,
+ LAST_MODIFIED timestamp with time zone not null,
+ ASSIGNEE_ID varchar(255),
+ primary key (ID)
+);
+
+create table ALARM_ASSET_LINK (
+ SENTALARM_ID int8 not null,
+ REALM varchar(255) not null,
+ ASSET_ID varchar(22) not null,
+ CREATED_ON timestamp with time zone not null,
+ primary key (ASSET_ID, REALM, SENTALARM_ID)
+);
+
+alter table ALARM
+ add foreign key (ASSIGNEE_ID) references PUBLIC.USER_ENTITY (ID) on delete cascade;
+
+alter table ALARM_ASSET_LINK
+ add foreign key (SENTALARM_ID) references ALARM (ID) on delete cascade;
+
+alter table ALARM_ASSET_LINK
+ add foreign key (ASSET_ID) references ASSET (ID) on delete cascade;
+
+alter table ALARM_ASSET_LINK
+ add foreign key (REALM) references PUBLIC.REALM (NAME) on delete cascade;
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 4fc301da6..cbc3f453f 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -776,5 +776,53 @@
"withInterval": "With interval",
"AVG": "Average (mean)",
"MIN": "Minimum",
- "MAX": "Maximum"
+ "MAX": "Maximum",
+ "alarm": {
+ "": "Alarm",
+ "alarm_plural": "Alarms",
+ "add": "Add Alarm",
+ "inactive_plural": "Inactive alarms",
+ "active_plural" : "Active alarms",
+ "title": "Title",
+ "content": "Description",
+ "severity": "Severity",
+ "status": "Status",
+ "status_CLOSED": "Closed",
+ "status_RESOLVED": "Resolved",
+ "status_ACKNOWLEDGED": "Acknowledged",
+ "status_IN_PROGRESS": "In Progress",
+ "status_OPEN": "Open",
+ "severity_LOW": "Low",
+ "severity_MEDIUM": "Medium",
+ "severity_HIGH": "High",
+ "source_GLOBAL_RULESET": "Global ruleset",
+ "source_REALM_RULESET": "Realm ruleset",
+ "source_ASSET_RULESET": "Asset ruleset",
+ "source_CLIENT": "Client",
+ "source_AGENT": "Agent",
+ "source_MANUAL": "Manual",
+ "all": "All",
+ "allActive": "All active",
+ "linkedAssets": "Linked asset(s)",
+ "linkedUsers": "Linked user(s)",
+ "linkedAlarms": "Linked alarms",
+ "saveAlarmSucceeded": "Saved alarm successfully!",
+ "saveAlarmFailed": "Save alarm failed",
+ "creatingAlarm": "Creating a new alarm",
+ "createAlarmFailed": "Create alarm failed",
+ "alarmAlreadyExists": "Error occurred! This alarm already exists.",
+ "deleteAlarm": "Delete alarm",
+ "deleteAlarmConfirm": "Are you sure you want to delete this alarm?",
+ "deleteAlarms": "Delete alarms",
+ "deleteAlarmsConfirm": "Are you sure you want to delete {{count}} selected alarm(s)?",
+ "assignUser": "Assign user",
+ "hideControls": "Hide controls",
+ "filter": "Content filter",
+ "lastModified": "Last modified",
+ "sort": "Sort",
+ "assignee": "Assignee",
+ "assignedToMe": "Assigned to me",
+ "noData": "No alarms found.",
+ "source": "Source"
+ }
}
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 10c299d52..bc3472b49 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -774,5 +774,53 @@
"withInterval": "Met interval",
"AVG": "Gemiddelde",
"MIN": "Minimum",
- "MAX": "Maximum"
+ "MAX": "Maximum",
+ "alarm": {
+ "": "Alarm",
+ "alarm_plural": "Alarmen",
+ "add": "Alarm Toevoegen",
+ "inactive_plural": "Inactieve alarmen",
+ "active_plural": "Actieve alarmen",
+ "title": "Titel",
+ "content": "Beschrijving",
+ "severity": "Ernst",
+ "status": "Status",
+ "status_CLOSED": "Gesloten",
+ "status_RESOLVED": "Opgelost",
+ "status_ACKNOWLEDGED": "Erkend",
+ "status_IN_PROGRESS": "In Uitvoering",
+ "status_OPEN": "Open",
+ "severity_LOW": "Laag",
+ "severity_MEDIUM": "Gemiddeld",
+ "severity_HIGH": "Hoog",
+ "source_GLOBAL_RULESET": "Globale regels",
+ "source_REALM_RULESET": "Realm regels",
+ "source_ASSET_RULESET": "Asset regels",
+ "source_CLIENT": "Client",
+ "source_AGENT": "Agent",
+ "source_MANUAL": "Handmatig",
+ "all": "Alles",
+ "allActive": "Alle actieve",
+ "linkedAssets": "Gekoppelde asset(s)",
+ "linkedUsers": "Gekoppelde gebruiker(s)",
+ "linkedAlarms": "Gekoppelde alarmen",
+ "saveAlarmSucceeded": "Alarm succesvol opgeslagen!",
+ "saveAlarmFailed": "Opslaan van alarm mislukt",
+ "creatingAlarm": "Een nieuw alarm creëren",
+ "createAlarmFailed": "Alarm maken mislukt",
+ "alarmAlreadyExists": "Fout opgetreden! Dit alarm bestaat al.",
+ "deleteAlarm": "Alarm verwijderen",
+ "deleteAlarmConfirm": "Weet u zeker dat u dit alarm wilt verwijderen?",
+ "deleteAlarms": "Alarmen verwijderen",
+ "deleteAlarmsConfirm": "Weet u zeker dat u {{count}} geselecteerde alarmen wilt verwijderen?",
+ "assignUser": "Gebruiker toewijzen",
+ "hideControls": "Bedieningselementen verbergen",
+ "filter": "Inhoud filteren",
+ "lastModified": "Laatst gewijzigd",
+ "sort": "Sorteren",
+ "assignee": "Toegewezen aan",
+ "assignedToMe": "Aan mij toegewezen",
+ "noData": "Geen alarmen gevonden.",
+ "source": "Bron"
+ }
}
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index 5c0904602..f7b9abaf8 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -36,6 +36,7 @@ public interface Constants {
String READ_ASSETS_ROLE = "read:assets";
String READ_RULES_ROLE = "read:rules";
String READ_INSIGHTS_ROLE = "read:insights";
+ String READ_ALARMS_ROLE = "read:alarms";
String WRITE_USER_ROLE = "write:user";
String WRITE_ADMIN_ROLE = "write:admin";
String WRITE_LOGS_ROLE = "write:logs";
@@ -43,6 +44,7 @@ public interface Constants {
String WRITE_ATTRIBUTES_ROLE = "write:attributes";
String WRITE_RULES_ROLE = "write:rules";
String WRITE_INSIGHTS_ROLE = "write:insights";
+ String WRITE_ALARMS_ROLE = "write:alarms";
String RESTRICTED_USER_REALM_ROLE = "restricted_user";
String AUTH_CONTEXT = "AUTH_CONTEXT";
String SESSION_TERMINATOR = "connection.sessionTerminator";
diff --git a/model/src/main/java/org/openremote/model/alarm/Alarm.java b/model/src/main/java/org/openremote/model/alarm/Alarm.java
new file mode 100644
index 000000000..83cc74532
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/alarm/Alarm.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2024, 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.alarm;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import jakarta.validation.constraints.NotNull;
+
+public class Alarm {
+ public enum Source {
+ MANUAL,
+ CLIENT,
+ GLOBAL_RULESET,
+ REALM_RULESET,
+ ASSET_RULESET,
+ AGENT
+ }
+
+ public enum Status {
+ OPEN,
+ ACKNOWLEDGED,
+ IN_PROGRESS,
+ RESOLVED,
+ CLOSED
+ }
+
+ public enum Severity {
+ LOW,
+ MEDIUM,
+ HIGH
+ }
+
+ public static final String HEADER_SOURCE = Alarm.class.getName() + ".SOURCE";
+ public static final String HEADER_SOURCE_ID = Alarm.class.getName() + ".SOURCEID";
+
+ @NotNull
+ protected String title;
+
+ protected String content;
+
+ @NotNull
+ protected Severity severity;
+
+ @NotNull
+ protected Status status;
+
+ protected String assigneeId;
+
+ @NotNull
+ protected String realm;
+
+ @NotNull
+ protected String sourceId;
+
+ @NotNull
+ protected Source source;
+
+ @JsonCreator
+ public Alarm(String title, String content, Severity severity, String assigneeId, String realm) {
+ this.title = title;
+ this.content = content;
+ this.severity = severity;
+ this.status = Status.OPEN;
+ this.assigneeId = assigneeId;
+ this.realm = realm;
+ }
+
+ @JsonCreator
+ public Alarm() {
+
+ }
+
+ public String getTitle() {
+ return this.title;
+ }
+
+ public Alarm setTitle(@NotNull String title) {
+ this.title = title;
+ return this;
+ }
+
+ public String getContent() {
+ return this.content;
+ }
+
+ public Alarm setContent(String content) {
+ this.content = content;
+ return this;
+ }
+
+ public Severity getSeverity() {
+ return this.severity;
+ }
+
+ public Alarm setSeverity(@NotNull Severity severity) {
+ this.severity = severity;
+ return this;
+ }
+
+ public Status getStatus() {
+ return this.status;
+ }
+
+ public Alarm setStatus(@NotNull Status status) {
+ this.status = status;
+ return this;
+ }
+
+ public String getAssigneeId() {
+ return this.assigneeId;
+ }
+
+ public Alarm setAssigneeId(String assigneeId) {
+ this.assigneeId = assigneeId;
+ return this;
+ }
+
+ public String getRealm() {
+ return this.realm;
+ }
+
+ public Alarm setRealm(@NotNull String realm) {
+ this.realm = realm;
+ return this;
+ }
+
+ public Source getSource() {
+ return source;
+ }
+
+ public Alarm setSource(@NotNull Source source) {
+ this.source = source;
+ return this;
+ }
+
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ public Alarm setSourceId(@NotNull String sourceId) {
+ this.sourceId = sourceId;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "title='" + title + '\'' +
+ ", content='" + content + '\'' +
+ ", severity=" + severity +
+ ", status=" + status +
+ ", assigneeId='" + assigneeId + '\'' +
+ ", realm='" + realm + '\'' +
+ ", sourceId='" + sourceId + '\'' +
+ ", source=" + source +
+ '}';
+ }
+
+}
diff --git a/model/src/main/java/org/openremote/model/alarm/AlarmAssetLink.java b/model/src/main/java/org/openremote/model/alarm/AlarmAssetLink.java
new file mode 100644
index 000000000..5a28a2b28
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/alarm/AlarmAssetLink.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2024, 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.alarm;
+
+import org.hibernate.annotations.Formula;
+
+
+import jakarta.persistence.*;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Objects;
+
+@Entity
+@Table(name = "ALARM_ASSET_LINK")
+public class AlarmAssetLink {
+ public static class Id implements Serializable {
+ @Column(name = "REALM", nullable = false, length = 36)
+ protected String realm;
+
+ @Column(name = "SENTALARM_ID", nullable = false)
+ protected Long sentalarmId;
+
+
+ @Column(name = "ASSET_ID", nullable = false)
+ protected String assetId;
+
+ protected Id() {
+ }
+
+ public Id(String realm, Long alarmId, String assetId) {
+ this.realm = realm;
+ this.sentalarmId = alarmId;
+ this.assetId = assetId;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public Long getAlarmId() {
+ return sentalarmId;
+ }
+
+ public String getAssetId() {
+ return assetId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Id id = (Id) o;
+
+ if (!realm.equals(id.realm)) return false;
+ if (!sentalarmId.equals(id.sentalarmId)) return false;
+ return assetId.equals(id.assetId);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(realm, sentalarmId, assetId);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "realm='" + realm + '\'' +
+ ", alarmId='" + sentalarmId + '\'' +
+ ", assetId='" + assetId + '\'' +
+ '}';
+ }
+ }
+
+ @EmbeddedId
+ protected Id id;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date createdOn;
+
+ @Formula("(select a.NAME from ASSET a where a.ID = ASSET_ID)")
+ protected String assetName;
+
+ @Formula("(select pa.NAME from ASSET a left outer join ASSET pa on a.PARENT_ID = pa.ID where a.ID = ASSET_ID)")
+ protected String parentAssetName;
+
+ protected AlarmAssetLink() {
+ }
+
+ public AlarmAssetLink(Id id) {
+ this.id = id;
+ }
+
+ public AlarmAssetLink(String realm, Long alarmId, String assetId) {
+ this(new AlarmAssetLink.Id(realm, alarmId, assetId));
+ }
+
+ public Id getId() {
+ return id;
+ }
+
+ public String getAssetName() {
+ return assetName;
+ }
+
+ public String getParentAssetName() {
+ return parentAssetName;
+ }
+
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public void setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ AlarmAssetLink that = (AlarmAssetLink) o;
+ return id.equals(that.id);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id=" + id +
+ ", createdOn=" + createdOn +
+ ", assetName='" + assetName + '\'' +
+ ", parentAssetName='" + parentAssetName + '\'' +
+ '}';
+ }
+
+}
diff --git a/model/src/main/java/org/openremote/model/alarm/AlarmEvent.java b/model/src/main/java/org/openremote/model/alarm/AlarmEvent.java
new file mode 100644
index 000000000..d01551b36
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/alarm/AlarmEvent.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2024, 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.alarm;
+
+import org.openremote.model.PersistenceEvent;
+import org.openremote.model.event.shared.RealmScopedEvent;
+
+public class AlarmEvent extends RealmScopedEvent {
+ protected String realm;
+ protected PersistenceEvent.Cause cause;
+
+ public AlarmEvent(String realm, PersistenceEvent.Cause cause) {
+ this.realm = realm;
+ this.cause = cause;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "realm=" + realm +
+ ", cause=" + cause +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/alarm/AlarmResource.java b/model/src/main/java/org/openremote/model/alarm/AlarmResource.java
new file mode 100644
index 000000000..c32881254
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/alarm/AlarmResource.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2024, 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.alarm;
+
+import io.swagger.v3.oas.annotations.parameters.RequestBody;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.openremote.model.Constants;
+import org.openremote.model.http.RequestParams;
+
+import jakarta.annotation.security.RolesAllowed;
+import jakarta.ws.rs.*;
+
+import java.util.List;
+
+import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
+
+@Tag(name = "Alarm")
+@Path("alarm")
+public interface AlarmResource {
+
+ @GET
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({Constants.READ_ALARMS_ROLE})
+ SentAlarm[] getAlarms(@BeanParam RequestParams requestParams, @QueryParam("realm") String realm,
+ @QueryParam("status") Alarm.Status status, @QueryParam("assetId") String assetId,
+ @QueryParam("assigneeId") String assigneeId);
+
+ @POST
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({Constants.WRITE_ALARMS_ROLE})
+ SentAlarm createAlarm(@BeanParam RequestParams requestParams, @RequestBody Alarm alarm, @QueryParam("assetIds") List<String> assetIds);
+
+ @DELETE
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({Constants.WRITE_ALARMS_ROLE})
+ void removeAlarms(@BeanParam RequestParams requestParams, @RequestBody List<Long> ids);
+
+ @GET
+ @Path("{alarmId}")
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({Constants.READ_ALARMS_ROLE})
+ SentAlarm getAlarm(@BeanParam RequestParams requestParams, @PathParam("alarmId") Long alarmId);
+
+ @PUT
+ @Path("{alarmId}")
+ @Consumes(APPLICATION_JSON)
+ @RolesAllowed({Constants.WRITE_ALARMS_ROLE})
+ void updateAlarm(@BeanParam RequestParams requestParams, @PathParam("alarmId") Long alarmId, @RequestBody SentAlarm alarm);
+
+ @DELETE
+ @Path("{alarmId}")
+ @RolesAllowed({Constants.WRITE_ALARMS_ROLE})
+ void removeAlarm(@BeanParam RequestParams requestParams, @PathParam("alarmId") Long alarmId);
+
+ @GET
+ @Path("{alarmId}/assets")
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({Constants.READ_ALARMS_ROLE})
+ List<AlarmAssetLink> getAssetLinks(@BeanParam RequestParams requestParams, @PathParam("alarmId") Long alarmId,
+ @QueryParam("realm") String realm);
+
+ @PUT
+ @Path("assets")
+ @Consumes(APPLICATION_JSON)
+ @RolesAllowed({Constants.WRITE_ALARMS_ROLE})
+ void setAssetLinks(@BeanParam RequestParams requestParams, @RequestBody List<AlarmAssetLink> links);
+}
diff --git a/model/src/main/java/org/openremote/model/alarm/SentAlarm.java b/model/src/main/java/org/openremote/model/alarm/SentAlarm.java
new file mode 100644
index 000000000..b5fea2734
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/alarm/SentAlarm.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2024, 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.alarm;
+
+import jakarta.persistence.*;
+import jakarta.validation.constraints.NotNull;
+import org.hibernate.annotations.Formula;
+import org.openremote.model.asset.Asset;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
+
+@Entity
+@Table(name = "ALARM")
+public class SentAlarm {
+ @Id
+ @Column(name = "ID")
+ @GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)
+ protected Long id;
+
+ @NotNull
+ @Column(name = "REALM", nullable = false, updatable = false)
+ protected String realm;
+
+ @Column(name = "TITLE", nullable = false)
+ protected String title;
+
+ @Column(name = "CONTENT", length = 4096)
+ protected String content;
+
+ @NotNull
+ @Column(name = "SEVERITY", nullable = false, length = 15)
+ @Enumerated(EnumType.STRING)
+ protected Alarm.Severity severity;
+
+ @NotNull
+ @Column(name = "STATUS", nullable = false, length = 15)
+ @Enumerated(EnumType.STRING)
+ protected Alarm.Status status;
+
+ @NotNull()
+ @Column(name = "SOURCE", nullable = false, length = 50)
+ @Enumerated(EnumType.STRING)
+ protected Alarm.Source source;
+
+ @Column(name = "SOURCE_ID", nullable = false, length = 43)
+ protected String sourceId;
+
+ @Formula("(select u.USERNAME from PUBLIC.USER_ENTITY u where u.ID = SOURCE_ID)")
+ protected String sourceUsername;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date createdOn;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "ACKNOWLEDGED_ON", columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date acknowledgedOn;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "LAST_MODIFIED", nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date lastModified;
+
+ @Column(name = "ASSIGNEE_ID")
+ protected String assigneeId;
+
+ @Formula("(select u.USERNAME from PUBLIC.USER_ENTITY u where u.ID = ASSIGNEE_ID)")
+ protected String assigneeUsername;
+
+ @ManyToMany(fetch = FetchType.EAGER)
+ @JoinTable(name = "ALARM_ASSET_LINK")
+ protected List<Asset<?>> asset = new ArrayList<>();
+
+ public Long getId() {
+ return id;
+ }
+
+ public SentAlarm setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public SentAlarm setRealm(String realm) {
+ this.realm = realm;
+ return this;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public SentAlarm setTitle(String title) {
+ this.title = title;
+ return this;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public SentAlarm setContent(String content) {
+ this.content = content;
+ return this;
+ }
+
+ public Alarm.Severity getSeverity() {
+ return severity;
+ }
+
+ public SentAlarm setSeverity(Alarm.Severity severity) {
+ this.severity = severity;
+ return this;
+ }
+
+ public Alarm.Status getStatus() {
+ return status;
+ }
+
+ public SentAlarm setStatus(Alarm.Status status) {
+ this.status = status;
+ return this;
+ }
+
+ public Alarm.Source getSource() {
+ return source;
+ }
+
+ public SentAlarm setSource(Alarm.Source source) {
+ this.source = source;
+ return this;
+ }
+
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ public SentAlarm setSourceId(String sourceId) {
+ this.sourceId = sourceId;
+ return this;
+ }
+
+ public String getSourceUsername() {
+ return sourceUsername;
+ }
+
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public SentAlarm setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ return this;
+ }
+
+ public Date getAcknowledgedOn() {
+ return acknowledgedOn;
+ }
+
+ public SentAlarm setAcknowledgedOn(Date acknowledgedOn) {
+ this.acknowledgedOn = acknowledgedOn;
+ return this;
+ }
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ public SentAlarm setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ return this;
+ }
+
+ public String getAssigneeId() {
+ return assigneeId;
+ }
+
+ public SentAlarm setAssigneeId(String assigneeId) {
+ this.assigneeId = assigneeId;
+ return this;
+ }
+
+ public String getAssigneeUsername() {
+ return assigneeUsername;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id=" + id +
+ ", title='" + title + '\'' +
+ ", content='" + content + '\'' +
+ ", severity=" + severity + '\'' +
+ ", status='" + status + '\'' +
+ ", source=" + source +
+ ", sourceId='" + sourceId + '\'' +
+ ", createdOn=" + createdOn + '\'' +
+ ", acknowledgedOn=" + acknowledgedOn + '\'' +
+ ", lastModified=" + lastModified + '\'' +
+ ", assigneeId=" + assigneeId + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index b81d7027e..b88765678 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -30,12 +30,14 @@ import org.openremote.model.rules.RulesetChangedEvent;
import org.openremote.model.simulator.RequestSimulatorState;
import org.openremote.model.simulator.SimulatorState;
import org.openremote.model.syslog.SyslogEvent;
+import org.openremote.model.alarm.AlarmEvent;
/**
* An event that can be serialized and shared between client and server.
*/
@JsonSubTypes({
// Events used on client and server (serializable)
+ @JsonSubTypes.Type(value = AlarmEvent.class, name = "alarm"),
@JsonSubTypes.Type(value = SyslogEvent.class, name = "syslog"),
@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),
@JsonSubTypes.Type(value = AssetEvent.class, name = "asset"),
diff --git a/model/src/main/java/org/openremote/model/query/UserQuery.java b/model/src/main/java/org/openremote/model/query/UserQuery.java
index 49bca3b7a..513bc8421 100644
--- a/model/src/main/java/org/openremote/model/query/UserQuery.java
+++ b/model/src/main/java/org/openremote/model/query/UserQuery.java
@@ -137,6 +137,7 @@ public class UserQuery {
/**
* OR condition is assumed between values (AND filtering can be applied by the caller on the results)
*/
+ public StringPredicate[] clientRoles;
public StringPredicate[] realmRoles;
public Boolean serviceUsers;
public Integer limit;
@@ -176,6 +177,11 @@ public class UserQuery {
return this;
}
+ public UserQuery clientRoles(StringPredicate...clientRoles) {
+ this.clientRoles = clientRoles;
+ return this;
+ }
+
public UserQuery realmRoles(StringPredicate...realmRoles) {
this.realmRoles = realmRoles;
return this;
@@ -216,6 +222,7 @@ public class UserQuery {
", usernames=" + (usernames != null ? Arrays.toString(usernames) : "null") +
", serviceUsers=" + serviceUsers +
", attributes=" + (attributes != null ? Arrays.toString(attributes) : "null") +
+ ", clientRoles=" + (clientRoles != null ? Arrays.toString(clientRoles) : "null") +
", realmRoles=" + (realmRoles != null ? Arrays.toString(realmRoles) : "null") +
", limit=" + limit +
", offset=" + offset +
diff --git a/model/src/main/java/org/openremote/model/rules/Alarms.java b/model/src/main/java/org/openremote/model/rules/Alarms.java
new file mode 100644
index 000000000..5fa73cc8b
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/Alarms.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2024, 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;
+
+import java.util.List;
+
+import org.openremote.model.alarm.Alarm;
+import org.openremote.model.util.TsIgnore;
+
+/**
+ * Facade for sending {@link Alarm}s from rules RHS.
+ */
+@TsIgnore
+public abstract class Alarms {
+ public abstract Long create(Alarm alarm, List<String> assetIds);
+ public abstract void linkAssets(List<String> assetIds, Long alarmId);
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
index 88ca29fa1..02d8f3655 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
@@ -30,7 +30,8 @@ import java.util.function.Function;
@JsonSubTypes.Type(value = RuleActionWriteAttribute.class, name = "write-attribute"),
@JsonSubTypes.Type(value = RuleActionNotification.class, name = "notification"),
@JsonSubTypes.Type(value = RuleActionUpdateAttribute.class, name = "update-attribute"),
- @JsonSubTypes.Type(value = RuleActionWebhook.class, name = "webhook")
+ @JsonSubTypes.Type(value = RuleActionWebhook.class, name = "webhook"),
+ @JsonSubTypes.Type(value = RuleActionAlarm.class, name = "alarm")
})
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionAlarm.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionAlarm.java
new file mode 100644
index 000000000..08fe09629
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionAlarm.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2024, 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;
+
+import org.openremote.model.alarm.Alarm;
+
+public class RuleActionAlarm extends RuleAction {
+ public Alarm alarm;
+ public String assigneeId;
+}
diff --git a/model/src/main/java/org/openremote/model/security/ClientRole.java b/model/src/main/java/org/openremote/model/security/ClientRole.java
index 44d1f7d4a..26b06a819 100644
--- a/model/src/main/java/org/openremote/model/security/ClientRole.java
+++ b/model/src/main/java/org/openremote/model/security/ClientRole.java
@@ -38,6 +38,7 @@ public enum ClientRole {
READ_ASSETS(Constants.READ_ASSETS_ROLE, "Read asset data"),
READ_RULES(Constants.READ_RULES_ROLE, "Read rulesets"),
READ_INSIGHTS(Constants.READ_INSIGHTS_ROLE, "Read dashboards"),
+ READ_ALARMS(Constants.READ_ALARMS_ROLE, "Read alarms"),
WRITE_USER(Constants.WRITE_USER_ROLE, "Write data of the authenticated user"),
WRITE_ADMIN(Constants.WRITE_ADMIN_ROLE, "Write system settings, realms, and users"),
@@ -46,6 +47,7 @@ public enum ClientRole {
WRITE_ATTRIBUTES(Constants.WRITE_ATTRIBUTES_ROLE, "Write attribute data"),
WRITE_RULES(Constants.WRITE_RULES_ROLE, "Write rulesets (NOTE: effectively super-user access!)"),
WRITE_INSIGHTS(Constants.WRITE_INSIGHTS_ROLE, "Write dashboard data"),
+ WRITE_ALARMS(Constants.WRITE_ALARMS_ROLE, "Write alarm data"),
READ("read", "Read all data", new ClientRole[]{
READ_ADMIN,
@@ -54,7 +56,8 @@ public enum ClientRole {
READ_MAP,
READ_ASSETS,
READ_RULES,
- READ_INSIGHTS
+ READ_INSIGHTS,
+ READ_ALARMS
}),
WRITE("write", "Write all data", new ClientRole[]{
@@ -65,13 +68,15 @@ public enum ClientRole {
READ_ASSETS,
READ_RULES,
READ_INSIGHTS,
+ READ_ALARMS,
WRITE_USER,
WRITE_ADMIN,
WRITE_LOGS,
WRITE_ASSETS,
WRITE_ATTRIBUTES,
WRITE_RULES,
- WRITE_INSIGHTS
+ WRITE_INSIGHTS,
+ WRITE_ALARMS
});
// Only individual roles, not composites
diff --git a/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java b/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java
index 947263494..56a67334e 100644
--- a/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java
+++ b/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java
@@ -42,6 +42,11 @@ public enum SyslogCategory {
"NotificationService",
"FCMDeliveryService"
),
+ ALARM(
+ "ALARM",
+ false,
+ "AlarmService"
+ ),
RULES(
"Rules",
true,
diff --git a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
index 55c27254e..bf85bedb9 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
@@ -63,6 +63,11 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
public Realm realmBuilding;
public Realm realmEnergy;
public Realm realmCity;
+ public User testuser1;
+ public User testuser2;
+ public User testuser3;
+ public User buildingUser;
+ public User smartCityUser;
public User serviceUser;
public User serviceUser2;
@@ -95,27 +100,27 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
// Users
- User testuser1 = createUser(MASTER_REALM, "testuser1", "testuser1", "DemoMaster", "DemoLast", null, true, REGULAR_USER_ROLES);
+ testuser1 = createUser(MASTER_REALM, "testuser1", "testuser1", "DemoMaster", "DemoLast", null, true, REGULAR_USER_ROLES);
this.testuser1Id = testuser1.getId();
keycloakProvider.updateUserRoles(MASTER_REALM, testuser1Id, "account"); // Remove all roles for account client
- User testuser2 = createUser(realmBuilding.getName(), "testuser2", "testuser2", "DemoA2", "DemoLast", "[email protected]", true, false, true, new ClientRole[] {
+ testuser2 = createUser(realmBuilding.getName(), "testuser2", "testuser2", "DemoA2", "DemoLast", "[email protected]", true, false, true, new ClientRole[] {
ClientRole.WRITE_USER,
ClientRole.READ_MAP,
ClientRole.READ_ASSETS
});
this.testuser2Id = testuser2.getId();
keycloakProvider.updateUserRoles(realmBuilding.getName(), testuser2Id, "account"); // Remove all roles for account client
- User testuser3 = createUser(realmBuilding.getName(), "testuser3", "testuser3", "DemoA3", "DemoLast", "[email protected]", true, true, false, REGULAR_USER_ROLES);
+ testuser3 = createUser(realmBuilding.getName(), "testuser3", "testuser3", "DemoA3", "DemoLast", "[email protected]", true, true, false, REGULAR_USER_ROLES);
this.testuser3Id = testuser3.getId();
keycloakProvider.updateUserRoles(realmBuilding.getName(), testuser3Id, "account"); // Remove all roles for account client
// Add realm role
keycloakProvider.updateUserRealmRoles(realmBuilding.getName(), testuser3Id, keycloakProvider.addRealmRoles(realmBuilding.getName(), testuser3Id, REALM_ROLE_TEST));
- User buildingUser = createUser(realmBuilding.getName(), "building", "building", "Building", "User", "[email protected]", true, noWriteAccess);
+ buildingUser = createUser(realmBuilding.getName(), "building", "building", "Building", "User", "[email protected]", true, noWriteAccess);
this.buildingUserId = buildingUser.getId();
keycloakProvider.updateUserRoles(realmBuilding.getName(), buildingUserId, "account"); // Remove all roles for account client
// Add realm role
keycloakProvider.updateUserRealmRoles(realmBuilding.getName(), buildingUserId, keycloakProvider.addRealmRoles(realmBuilding.getName(), buildingUserId, REALM_ROLE_TEST2));
- User smartCityUser = createUser(realmCity.getName(), "smartcity", "smartcity", "Smart", "City", null, true, noWriteAccess);
+ smartCityUser = createUser(realmCity.getName(), "smartcity", "smartcity", "Smart", "City", null, true, noWriteAccess);
this.smartCityUserId = smartCityUser.getId();
keycloakProvider.updateUserRoles(realmCity.getName(), smartCityUserId, "account"); // Remove all roles for account client
diff --git a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
new file mode 100644
index 000000000..adf101e5d
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
@@ -0,0 +1,525 @@
+/*
+ * Copyright 2024, 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.test.alarm
+
+import jakarta.mail.Message
+import org.openremote.manager.notification.EmailNotificationHandler
+import org.openremote.manager.notification.NotificationService
+import org.openremote.model.alarm.Alarm
+import org.openremote.model.alarm.Alarm.Severity
+import org.openremote.model.alarm.AlarmAssetLink
+import org.openremote.model.alarm.SentAlarm
+import org.openremote.model.alarm.AlarmResource
+import org.openremote.manager.setup.SetupService
+import org.openremote.model.notification.AbstractNotificationMessage
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.security.User
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.lang.Unroll
+import spock.lang.Shared
+import spock.util.concurrent.PollingConditions
+
+import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
+import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
+import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
+import static org.openremote.model.Constants.MASTER_REALM
+import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
+import jakarta.ws.rs.WebApplicationException
+
+class AlarmResourceTest extends Specification implements ManagerContainerTrait {
+ @Shared
+ static AlarmResource adminResource
+
+ @Shared
+ static AlarmResource regularUserResource
+
+ @Shared
+ static KeycloakTestSetup keycloakTestSetup
+
+ @Shared
+ static ManagerTestSetup managerTestSetup
+
+ @Shared
+ static String alarmsReadWriteUserId
+
+ @Shared
+ static NotificationService notificationService
+
+ @Shared
+ static List<AbstractNotificationMessage> notificationMessages = []
+
+ def setupSpec() {
+ def container = startContainer(defaultConfig(), defaultServices())
+ keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+ managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+ notificationService = container.getService(NotificationService.class)
+
+ def adminAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
+ ).token
+
+ regularUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM).proxy(AlarmResource.class)
+ adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(AlarmResource.class)
+
+ User alarmsReadWriteUser = keycloakTestSetup.createUser(MASTER_REALM, "alarmsrwuser1", "alarmsrwuser1", "Alarms R/W", "User", "[email protected]", true, KeycloakTestSetup.REGULAR_USER_ROLES)
+ alarmsReadWriteUserId = alarmsReadWriteUser.getId()
+
+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)
+ def throwPushHandlerException = false
+ EmailNotificationHandler mockPushNotificationHandler = Spy(emailNotificationHandler)
+ mockPushNotificationHandler.isValid() >> true
+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
+ if (throwPushHandlerException) {
+ throw new Exception("Failed to send notification")
+ }
+ notificationMessages << message
+ callRealMethod()
+ }
+ mockPushNotificationHandler.sendMessage(_ as Message) >> {
+ message -> return NotificationSendResult.success()
+ }
+
+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockPushNotificationHandler)
+ }
+
+ def cleanup() {
+ // Remove all alarms
+ def alarms = adminResource.getAlarms(null, MASTER_REALM, null, null, null)
+ if (alarms.length > 0) {
+ adminResource.removeAlarms(null, (List<Long>) alarms.collect { it.id })
+ }
+
+ // Clear notifications
+ notificationMessages.clear()
+ }
+
+ // Create alarm as admin
+ @Unroll
+ def "should create an alarm with title '#title', content '#content', severity '#severity', assigneeId '#assigneeId' and '#emailNotifications' emailNotifications"() {
+ when: "an alarm is created"
+ def input = new Alarm(title, content, severity, assigneeId, MASTER_REALM)
+ def alarm = adminResource.createAlarm(null, input, null)
+
+ then:
+ alarm != null
+ alarm.title == title
+ alarm.content == content
+ alarm.severity == severity
+ alarm.assigneeId == assigneeId
+ alarm.status == Alarm.Status.OPEN
+
+ and:
+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 0.2)
+ conditions.eventually {
+ assert notificationMessages.size() == emailNotifications
+ }
+
+ where:
+ title | content | severity | assigneeId | emailNotifications
+ "Low Alarm" | "Test Description" | Severity.LOW | null | 0
+ "Low Assigned 1 Alarm" | "Test Description" | Severity.LOW | keycloakTestSetup.testuser1Id | 0
+ "Low Assigned 2 Alarm" | "Test Description" | Severity.LOW | alarmsReadWriteUserId | 0
+ "Medium Unassigned Alarm" | "Another Description" | Severity.MEDIUM | null | 0
+ "Medium Assigned 1 Alarm" | "Assigned Description" | Severity.MEDIUM | keycloakTestSetup.testuser1Id | 0
+ "Medium Assigned 2 Alarm" | "Assigned Description" | Severity.MEDIUM | alarmsReadWriteUserId | 0
+ "High Unassigned Alarm" | "Critical Description" | Severity.HIGH | null | 1
+ "High Assigned 1 Alarm" | "Critical Description" | Severity.HIGH | keycloakTestSetup.testuser1Id | 0
+ "High Assigned 2 Alarm" | "Critical Description" | Severity.HIGH | alarmsReadWriteUserId | 1
+ }
+
+ @Unroll
+ def "should create an alarm with title '#title', content '#content', severity '#severity', and source '#source'"() {
+ when: "an alarm is created"
+ def input = new Alarm().setTitle(title).setContent(content).setSeverity(severity).setStatus(Alarm.Status.OPEN).setRealm(MASTER_REALM)
+ def alarm = adminResource.createAlarm(null, input, null)
+
+ then:
+ alarm != null
+ alarm.title == title
+ alarm.content == content
+ alarm.severity == severity
+ alarm.status == Alarm.Status.OPEN
+ alarm.source == source
+
+ where:
+ title | content | severity | source
+ "Test Alarm" | "Test Description" | Severity.LOW | Alarm.Source.MANUAL
+ "Another Alarm" | "Another Description" | Severity.MEDIUM | Alarm.Source.MANUAL
+ "Critical Alarm" | "Critical Description" | Severity.HIGH | Alarm.Source.MANUAL
+ }
+
+ @Unroll
+ def "should not create an alarm with title '#title', content '#content', severity '#severity', and status '#status'"() {
+ when:
+ adminResource.createAlarm(null, new Alarm().setTitle(title).setContent(content).setSeverity(severity).setStatus(status).setRealm(MASTER_REALM), null)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 400
+
+ where:
+ title | content | severity | status
+ null | "Test Description" | Severity.LOW | Alarm.Status.OPEN
+ "Another Test Alarm" | "Another Description" | null | Alarm.Status.RESOLVED
+ }
+
+ // Create alarm without write:alarm role
+ def "should not create an alarm as regular user"() {
+ when:
+ regularUserResource.createAlarm(null, new Alarm().setTitle("title").setContent("content").setSeverity(Severity.MEDIUM).setStatus(Alarm.Status.ACKNOWLEDGED).setRealm(MASTER_REALM), null)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+ }
+
+ // Get alarms as admin
+ def "should return created alarms"() {
+ when: "five alarms are added"
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 2').setContent('content').setStatus(Alarm.Status.ACKNOWLEDGED).setSeverity(Severity.MEDIUM).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 3').setContent('content').setStatus(Alarm.Status.CLOSED).setSeverity(Severity.HIGH).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 4').setContent('content').setStatus(Alarm.Status.IN_PROGRESS).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 5').setContent('content').setStatus(Alarm.Status.RESOLVED).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ def alarms = adminResource.getAlarms(null, MASTER_REALM, null, null, null)
+
+ then: "five alarm can be retrieved"
+ alarms != null
+ alarms.size() == 5
+
+ and: "each single alarm can also be retrieved"
+ for (alarm in alarms) {
+ assert adminResource.getAlarm(null, alarm.id) != null
+ }
+ }
+
+ // Get alarms without read:alarm role
+ def "should not return alarms"() {
+ when:
+ regularUserResource.getAlarms(null, MASTER_REALM, null, null, null)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+
+ when:
+ regularUserResource.getAlarm(null, 1L)
+
+ then:
+ ex = thrown()
+ ex.response.status == 403
+ }
+
+ // Update alarm as admin
+ @Unroll
+ def "should update an alarm with title '#title', content '#content', severity '#severity', status '#status' and assigneeId '#assigneeId'"() {
+ when:
+ def alarm = adminResource.createAlarm(null, new Alarm().setTitle('Updatable alarm').setContent('Updatable content').setStatus(Alarm.Status.CLOSED).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.updateAlarm(null, alarm.id, new SentAlarm().setTitle(title).setContent(content).setRealm(MASTER_REALM).setSeverity(severity).setStatus(status).setAssigneeId(assigneeId))
+ def updated = adminResource.getAlarms(null, MASTER_REALM, null, null, null)[0]
+
+ then:
+ updated != null
+ updated.title == title
+ updated.content == content
+ updated.severity == severity
+ updated.status == status
+ updated.assigneeId == assigneeId
+
+ where:
+ title | content | severity | status | assigneeId
+ "Updated Alarm" | "Test Description" | Severity.HIGH | Alarm.Status.OPEN | null
+ "Another Alarm" | "Updated Description" | Severity.MEDIUM | Alarm.Status.CLOSED | keycloakTestSetup.testuser1Id
+ }
+
+ @Unroll
+ def "should not update an alarm with id 'null'"() {
+ when:
+ adminResource.updateAlarm(null, null, new SentAlarm().setTitle('title').setContent('content').setSeverity(Severity.LOW).setStatus(Alarm.Status.OPEN))
+
+ then:
+ NullPointerException ex = thrown()
+ }
+
+ // Update alarm without write:alarm role
+ @Unroll
+ def "should not update an alarm with title '#title', content '#content', severity '#severity', and status '#status'"() {
+ when:
+ def alarm = adminResource.createAlarm(null, new Alarm().setTitle('Some alarm').setContent('Some content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ regularUserResource.updateAlarm(null, alarm.id, new SentAlarm().setTitle(title).setContent(content).setSeverity(severity).setStatus(status))
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+
+ where:
+ title | content | severity | status
+ "Updated Alarm" | "Test Description" | Severity.HIGH | Alarm.Status.OPEN
+ "Another Alarm" | "Updated Description" | Severity.MEDIUM | Alarm.Status.CLOSED
+ }
+
+ // Delete alarm without write:alarm role
+ def "should not delete alarm without proper permissions"() {
+ when:
+ adminResource.createAlarm(null, new Alarm().setTitle('Some alarm').setContent('Some content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ def alarm = adminResource.getAlarms(null, MASTER_REALM, null, null, null)[0]
+ regularUserResource.removeAlarm(null, alarm.id)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+ }
+
+ // Delete alarms without write:alarm role
+ def "should not delete alarms without proper permissions"() {
+ when:
+ adminResource.createAlarm(null, new Alarm().setTitle('Some alarm').setContent('Some content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('Another alarm').setContent('More content').setStatus(Alarm.Status.IN_PROGRESS).setSeverity(Severity.MEDIUM).setRealm(MASTER_REALM), null)
+ def alarms = adminResource.getAlarms(null, MASTER_REALM, null, null, null)
+ regularUserResource.removeAlarms(null, (List<Long>) alarms.collect { it.id })
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+ }
+
+ // Delete empty or null alarms
+ def "should not delete null or empty alarms"() {
+ when:
+ adminResource.removeAlarm(null, null)
+
+ then:
+ NullPointerException npe = thrown()
+
+ when:
+ adminResource.removeAlarms(null, [])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.removeAlarms(null, [null])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+ }
+
+ // Delete invalid alarms
+ def "should not delete alarms with invalid ID"() {
+ when:
+ adminResource.removeAlarm(null, -1L)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.removeAlarms(null, [-1L, 0L, 1L])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+ }
+
+ // Delete non-exising alarms
+ def "should not delete non-existing alarms"() {
+ when:
+ adminResource.removeAlarm(null, 1L)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 404
+
+ when:
+ adminResource.removeAlarms(null, [1L, 2L, 3L])
+
+ then:
+ ex = thrown()
+ ex.response.status == 404
+ }
+
+ // Delete one alarm as admin
+ def "should delete one alarm as admin"() {
+ when:
+ for (int i = 0; i < 2; i++) {
+ adminResource.createAlarm(null, new Alarm("Alarm " + i, "Content " + i, Severity.MEDIUM, null, MASTER_REALM), null)
+ }
+ def delete = adminResource.getAlarms(null, MASTER_REALM, null, null, null)[0]
+ adminResource.removeAlarm(null, delete.id)
+
+ then: "returns some alarms but not the deleted alarm"
+ def alarms = adminResource.getAlarms(null, MASTER_REALM, null, null, null)
+ alarms.find { it.id == delete.id } == null
+ alarms.length > 0
+ }
+
+ // Delete multiple alarms as admin
+ def "should delete multiple alarms as admin"() {
+ when:
+ for (int i = 0; i < 2; i++) {
+ adminResource.createAlarm(null, new Alarm("Alarm " + i, "Content " + i, Severity.MEDIUM, null, MASTER_REALM), null)
+ }
+ def alarms = adminResource.getAlarms(null, MASTER_REALM, null, null, null)
+ adminResource.removeAlarms(null, (List<Long>) alarms.collect { it.id })
+
+ then: "returns no alarms"
+ adminResource.getAlarms(null, MASTER_REALM, null, null, null).length == 0
+ }
+
+ // Get open alarms
+ def "should get open alarms"() {
+ when: "two open and one closed alarms are added"
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 2').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.createAlarm(null, new Alarm().setTitle('alarm 3').setContent('content').setStatus(Alarm.Status.CLOSED).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ def openAlarms = adminResource.getAlarms(null, MASTER_REALM, Alarm.Status.OPEN, null, null)
+
+ then: "returns 2 open alarms"
+ openAlarms.size() == 2
+ }
+
+ // Linking alarms as admin
+ def "should be able to link alarms to assets as admin"() {
+ when: "two alarms are added"
+ def alarm1 = adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ def alarm2 = adminResource.createAlarm(null, new Alarm().setTitle('alarm 2').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+
+ then: "both can be linked to an asset"
+ adminResource.setAssetLinks(null, [
+ new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.smartOfficeId),
+ new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.smartOfficeId)
+ ])
+
+ when: "the alarm asset links are retrieved"
+ def alarm1Links = adminResource.getAssetLinks(null, alarm1.id, MASTER_REALM)
+ def alarm2Links = adminResource.getAssetLinks(null, alarm2.id, MASTER_REALM)
+
+ then: "the alarm asset links match"
+ alarm1Links.size() == 1
+ alarm1Links.get(0).id.alarmId == alarm1.id
+ alarm1Links.get(0).id.assetId == managerTestSetup.smartOfficeId
+ alarm1Links.get(0).id.realm == MASTER_REALM
+ alarm2Links.size() == 1
+ alarm2Links.get(0).id.alarmId == alarm2.id
+ alarm2Links.get(0).id.assetId == managerTestSetup.smartOfficeId
+ alarm2Links.get(0).id.realm == MASTER_REALM
+
+ when: "more alarm asset links are added"
+ adminResource.setAssetLinks(null, [
+ new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.lobbyId),
+ new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.lobbyId)
+ ])
+ alarm1Links = adminResource.getAssetLinks(null, alarm1.id, MASTER_REALM)
+ alarm2Links = adminResource.getAssetLinks(null, alarm2.id, MASTER_REALM)
+
+ then: "these alarm asset links also match"
+ alarm1Links.size() == 2
+ alarm1Links.get(0).id.alarmId == alarm1.id
+ alarm1Links.get(0).id.assetId == managerTestSetup.lobbyId
+ alarm1Links.get(0).id.realm == MASTER_REALM
+ alarm1Links.get(1).id.alarmId == alarm1.id
+ alarm1Links.get(1).id.assetId == managerTestSetup.smartOfficeId
+ alarm1Links.get(1).id.realm == MASTER_REALM
+ alarm2Links.size() == 2
+ alarm2Links.get(0).id.alarmId == alarm2.id
+ alarm2Links.get(0).id.assetId == managerTestSetup.lobbyId
+ alarm2Links.get(0).id.realm == MASTER_REALM
+ alarm2Links.get(1).id.alarmId == alarm2.id
+ alarm2Links.get(1).id.assetId == managerTestSetup.smartOfficeId
+ alarm2Links.get(1).id.realm == MASTER_REALM
+ }
+
+ // Linking alarms without permissions
+ def "should not be able to link alarms without proper permissions"() {
+ when:
+ def alarm = adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ regularUserResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm.id, managerTestSetup.smartOfficeId)])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+ }
+
+ // Creating invalid alarm links
+ def "should not create invalid alarm links"() {
+ when:
+ def alarm = adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ adminResource.setAssetLinks(null, [])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.setAssetLinks(null, [null])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(null, null, null)])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+
+
+ when:
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, null, null)])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, -1L, null)])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm.id, null)])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+
+ when:
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm.id, "")])
+
+ then:
+ ex = thrown()
+ ex.response.status == 400
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy b/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy
new file mode 100644
index 000000000..1c32c507a
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy
@@ -0,0 +1,197 @@
+package org.openremote.test.rules
+
+import jakarta.mail.Message
+import org.openremote.manager.alarm.AlarmService
+import org.openremote.manager.asset.AssetProcessingService
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.notification.EmailNotificationHandler
+import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.rules.RulesService
+import org.openremote.manager.rules.RulesetStorageService
+import org.openremote.manager.setup.SetupService
+import org.openremote.model.alarm.Alarm
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.notification.AbstractNotificationMessage
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.query.RulesetQuery
+import org.openremote.model.rules.json.JsonRulesetDefinition
+import org.openremote.model.rules.json.RuleActionAlarm
+import org.openremote.model.security.User
+import org.openremote.model.util.ValueUtil
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
+import org.openremote.model.rules.*
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Shared
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import java.time.Instant
+
+class AlarmRuleTest extends Specification implements ManagerContainerTrait {
+
+ @Shared
+ static KeycloakTestSetup keycloakTestSetup
+
+ @Shared
+ static ManagerTestSetup managerTestSetup
+
+ @Shared
+ static String alarmsReadWriteUserId
+
+ @Shared
+ static AssetProcessingService assetProcessingService
+
+ @Shared
+ static AlarmService alarmService
+
+ @Shared
+ static AssetStorageService assetStorageService
+
+ @Shared
+ static NotificationService notificationService
+
+ @Shared
+ static RulesService rulesService
+
+ @Shared
+ static RulesetStorageService rulesetStorageService
+
+ @Shared
+ static List<AbstractNotificationMessage> notificationMessages = []
+
+ def setupSpec() {
+ def container = startContainer(defaultConfig(), defaultServices())
+
+ keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+ managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+
+ User alarmsReadWriteUser = keycloakTestSetup.createUser(managerTestSetup.realmBuildingName, "alarmsrwuser1", "alarmsrwuser1", "Alarms R/W", "User", "[email protected]", true, KeycloakTestSetup.REGULAR_USER_ROLES)
+ alarmsReadWriteUserId = alarmsReadWriteUser.getId()
+
+ alarmService = container.getService(AlarmService.class)
+ assetProcessingService = container.getService(AssetProcessingService.class)
+ assetStorageService = container.getService(AssetStorageService.class)
+ notificationService = container.getService(NotificationService.class)
+ rulesetStorageService = container.getService(RulesetStorageService.class)
+ rulesService = container.getService(RulesService.class)
+
+
+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)
+ def throwPushHandlerException = false
+ EmailNotificationHandler mockPushNotificationHandler = Spy(emailNotificationHandler)
+ mockPushNotificationHandler.isValid() >> true
+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
+ if (throwPushHandlerException) {
+ throw new Exception("Failed to send notification")
+ }
+ notificationMessages << message
+ callRealMethod()
+ }
+ mockPushNotificationHandler.sendMessage(_ as Message) >> {
+ message -> return NotificationSendResult.success()
+ }
+
+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockPushNotificationHandler)
+ }
+
+ def cleanup() {
+ // Remove all alarms
+ def alarms = alarmService.getAlarms(managerTestSetup.realmBuildingName, null, null, null)
+ if (alarms.size() > 0) {
+ alarmService.removeAlarms((List<Long>) alarms.collect { it.id }, null)
+ }
+
+ // Remove all rulesets
+ List<RealmRuleset> rulesets = rulesetStorageService.findAll(RealmRuleset.class, new RulesetQuery().setRealm(managerTestSetup.realmBuildingName).setLanguages(Ruleset.Lang.JSON))
+ rulesets.forEach { ruleset -> rulesetStorageService.delete(RealmRuleset.class, ruleset.id) }
+
+ // Clear notifications
+ notificationMessages.clear()
+ }
+
+ def "rule in realm with alarm action creates an alarm with severity '#severity', assignee '#assigneeId' and '#emailNotifications' emailNotifications based on attribute event"() {
+ when: "a ruleset with a notification action is created in the building realm"
+ def rulesStr = getClass().getResource("/org/openremote/test/rules/CO2AlarmRule.json").text
+ JsonRulesetDefinition rulesetDef = ValueUtil.JSON.readValue(rulesStr, JsonRulesetDefinition.class)
+ rulesetDef.rules[0].when.groups.get(0).items.get(0).assets.ids(managerTestSetup.apartment2LivingroomId)
+ ((RuleActionAlarm) rulesetDef.rules[0].then[0]).alarm.setSeverity(severity)
+ ((RuleActionAlarm) rulesetDef.rules[0].then[0]).assigneeId = assigneeId
+ rulesStr = ValueUtil.JSON.writeValueAsString(rulesetDef)
+ def realmRuleset = new RealmRuleset(managerTestSetup.realmBuildingName, "CO2 Alarm Rule", Ruleset.Lang.JSON, rulesStr)
+ rulesetStorageService.merge(realmRuleset)
+
+ then: "the ruleset should reach the engine"
+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)
+ conditions.eventually {
+ def deployment = rulesService.realmEngines.get(managerTestSetup.realmBuildingName).deployments.get(realmRuleset.id)
+ assert deployment != null
+ assert deployment.ruleset.version == realmRuleset.version
+ }
+
+ when: "the room linked attribute is updated"
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment2LivingroomId, "co2Level", 6000))
+
+ then: "the linked co2Level attribute should equal the event value"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerTestSetup.apartment2LivingroomId, true)
+ assert asset.getAttribute("co2Level").flatMap { it.getValue() }.orElse(null) == 6000
+ }
+
+ and: "one alarm is created"
+ def alarms = null
+ conditions.eventually {
+ alarms = alarmService.getAlarms(managerTestSetup.realmBuildingName, null, null, null)
+ assert alarms.size() == 1
+ }
+
+ and: "the created alarm matches the rule action configuration"
+ def alarm = alarms.get(0)
+ alarm.id >= 0L
+ alarm.realm == managerTestSetup.realmBuildingName
+ alarm.title == "CO2 Alarm Rule"
+ alarm.content == String.format("""\
+ID: ${managerTestSetup.apartment2LivingroomId}
+Asset name: Living Room 2
+Attribute name: co2Level
+Value: 6000
+""")
+ alarm.severity == severity
+ alarm.status == Alarm.Status.OPEN
+ alarm.source == Alarm.Source.REALM_RULESET
+ alarm.sourceId == Long.toString(realmRuleset.id)
+ alarm.createdOn.toInstant().isAfter(Instant.now().minusSeconds(30))
+ alarm.createdOn.toInstant().isBefore(Instant.now())
+ alarm.acknowledgedOn == null
+ alarm.createdOn == alarm.lastModified
+ alarm.assigneeId == assigneeId
+
+ and: "the asset is linked to the alarm"
+ def assetLinks = alarmService.getAssetLinks(alarm.id, null, managerTestSetup.realmBuildingName)
+ assetLinks.size() == 1
+ def assetLink = assetLinks.get(0)
+ assetLink.id.alarmId == alarm.id
+ assetLink.id.realm == managerTestSetup.realmBuildingName
+ assetLink.id.assetId == managerTestSetup.apartment2LivingroomId
+ assetLink.createdOn.toInstant().isAfter(Instant.now().minusSeconds(30))
+ assetLink.createdOn.toInstant().isBefore(Instant.now())
+ assetLink.assetName == "Living Room 2"
+ assetLink.parentAssetName == "Apartment 2"
+
+ and: "the expected number e-mail notifications matches"
+ notificationMessages.size() == emailNotifications
+
+ where:
+ severity | assigneeId | emailNotifications
+ Alarm.Severity.LOW | null | 0
+ Alarm.Severity.LOW | keycloakTestSetup.testuser1Id | 0
+ Alarm.Severity.MEDIUM | null | 0
+ Alarm.Severity.MEDIUM | keycloakTestSetup.testuser2Id | 0
+ Alarm.Severity.HIGH | null | 1
+ Alarm.Severity.HIGH | keycloakTestSetup.testuser3Id | 1
+ Alarm.Severity.HIGH | alarmsReadWriteUserId | 1
+ }
+
+}
diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
index 960e0cfa0..9f7883d8d 100644
--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
@@ -125,19 +125,19 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "only non system users of the users realm should be returned in username order"
users.size() == 5
- users[0].username == "building"
+ users[0].username == keycloakTestSetup.buildingUser.username
users[1].username == keycloakTestSetup.serviceUser.username
users[2].username == keycloakTestSetup.serviceUser2.username
- users[3].username == "testuser2"
- users[4].username == "testuser3"
+ users[3].username == keycloakTestSetup.testuser2.username
+ users[4].username == keycloakTestSetup.testuser3.username
when: "a request is made for subset of users ordered by username descending"
users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2))
then: "the correct users should be returned"
users.size() == 2
- users[0].username == "testuser3"
- users[1].username == "testuser2"
+ users[0].username == keycloakTestSetup.testuser3.username
+ users[1].username == keycloakTestSetup.testuser2.username
when: "a request is made for another subset of users ordered by username descending"
users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2).offset(3))
@@ -145,7 +145,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "the correct users should be returned"
users.size() == 2
users[0].username == keycloakTestSetup.serviceUser.username
- users[1].username == "building"
+ users[1].username == keycloakTestSetup.buildingUser.username
when: "a request is made for only service users (users with a secret)"
users = adminUserResource.query(null, new UserQuery().serviceUsers(true).realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name)))
@@ -166,9 +166,9 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "only restricted users of this realm should be returned"
users.size() == 3
- users[0].username == "building"
+ users[0].username == keycloakTestSetup.buildingUser.username
users[1].username == keycloakTestSetup.serviceUser2.username
- users[2].username == "testuser3"
+ users[2].username == keycloakTestSetup.testuser3.username
when: "a request is made for non restricted users"
users = regularUserBuildingResource.query(null,
@@ -180,7 +180,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "only non restricted users of this realm should be returned"
users.size() == 2
users[0].username == keycloakTestSetup.serviceUser.username
- users[1].username == "testuser2"
+ users[1].username == keycloakTestSetup.testuser2.username
when: "a request is made based on user attributes"
users = regularUserBuildingResource.query(null,
@@ -193,10 +193,22 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "only matching users of this realm should be returned"
users.size() == 4
- users[0].username == "building"
+ users[0].username == keycloakTestSetup.buildingUser.username
users[1].username == keycloakTestSetup.serviceUser.username
users[2].username == keycloakTestSetup.serviceUser2.username
- users[3].username == "testuser2"
+ users[3].username == keycloakTestSetup.testuser2.username
+
+ when: "a request is made for users with the write:alarms client role"
+ users = regularUserBuildingResource.query(null,
+ new UserQuery()
+ .realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name))
+ .clientRoles(new StringPredicate(Constants.WRITE_ALARMS_ROLE))
+ .orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
+
+ then: "only users of this realm with the write:alarms client role should be returned"
+ users.size() == 2
+ users[0].username == keycloakTestSetup.buildingUser.username
+ users[1].username == keycloakTestSetup.testuser3.username
}
def "Get and update roles"() {
@@ -276,7 +288,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
user.attributes.get(0).getValue() == "true"
user.id == keycloakTestSetup.testuser3Id
user.realm == keycloakTestSetup.realmBuilding.name
- user.username == "testuser3"
+ user.username == keycloakTestSetup.testuser3.username
when: "a new attribute is added to the user"
user.setAttribute("test", "testvalue")
diff --git a/test/src/test/resources/org/openremote/test/rules/CO2AlarmRule.json b/test/src/test/resources/org/openremote/test/rules/CO2AlarmRule.json
new file mode 100644
index 000000000..1f5be6234
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/CO2AlarmRule.json
@@ -0,0 +1,57 @@
+{
+ "rules": [
+ {
+ "recurrence": {
+ "mins": 0
+ },
+ "when": {
+ "operator": "OR",
+ "groups": [
+ {
+ "operator": "AND",
+ "items": [
+ {
+ "assets": {
+ "types": [
+ "RoomAsset"
+ ],
+ "attributes": {
+ "items": [
+ {
+ "name": {
+ "predicateType": "string",
+ "match": "EXACT",
+ "value": "co2Level"
+ },
+ "value": {
+ "predicateType": "number",
+ "operator": "GREATER_THAN",
+ "value": 5000
+ }
+ }
+ ]
+ },
+ "ids": [
+ "7BQS4awDpktKayW0HrngTR"
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "then": [
+ {
+ "action": "alarm",
+ "alarm": {
+ "title": "%RULESET_NAME%",
+ "content": "%TRIGGER_ASSETS%",
+ "severity": "HIGH",
+ "status": "OPEN"
+ }
+ }
+ ],
+ "name": "CO2 Alarm Rule"
+ }
+ ]
+}
diff --git a/ui/app/manager/src/components/alarms/or-alarms-table.ts b/ui/app/manager/src/components/alarms/or-alarms-table.ts
new file mode 100644
index 000000000..9eb165f89
--- /dev/null
+++ b/ui/app/manager/src/components/alarms/or-alarms-table.ts
@@ -0,0 +1,268 @@
+/*
+ * Copyright 2024, 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/>.
+ */
+import {css, html, TemplateResult} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {OrMwcTable, TableColumn, TableConfig, TableContent, TableRow} from "@openremote/or-mwc-components/or-mwc-table";
+import {AlarmSeverity, AlarmStatus, Asset, SentAlarm} from "@openremote/model";
+import {i18next} from "@openremote/or-translate";
+import {classMap} from "lit/directives/class-map.js";
+
+/**
+ * ## AlarmTableColumn
+ * Custom model that inherits on {@link TableColumn}, and adds {@link widthWeight},
+ * which impacts the column width; higher numbers are 'more important' and get wider, others get smaller.
+ * */
+export interface AlarmTableColumn extends TableColumn {
+ widthWeight?: number;
+}
+
+const styling = css`
+ .alarm-text {
+ padding: 4px 6px;
+ border-radius: 5px;
+ }
+
+ .alarm-status-text__closed {
+ color: var(--or-alarm-status-color__closed, grey);
+ background-color: var(--or-alarm-status-background__closed);
+ border: var(--or-alarm-status-border__closed, 1px #8590A2 solid);
+ }
+
+ .alarm-status-text__resolved {
+ color: var(--or-alarm-status-color__resolved, white);
+ background-color: var(--or-alarm-status-background__resolved, #22A06B);
+ border: var(--or-alarm-status-border__resolved);
+ }
+
+ .alarm-status-text__acknowledged {
+ color: var(--or-alarm-status-color__acknowledged);
+ background-color: var(--or-alarm-status-background__acknowledged);
+ border: var(--or-alarm-status-border__acknowledged, 1px #8F7EE7 solid);
+ }
+
+ .alarm-status-text__in-progress {
+ color: var(--or-alarm-status-color__in-progress, white);
+ background-color: var(--or-alarm-status-background__in-progress, #388BFF);
+ border: var(--or-alarm-status-border__in-progress);
+ }
+
+ .alarm-status-text__open {
+ color: var(--or-alarm-status-color__open, white);
+ background-color: var(--or-alarm-status-background__open, #8F7EE7);
+ border: var(--or-alarm-status-border__open);
+ }
+
+ .alarm-severity-text__low {
+ color: white;
+ background-color: #388BFF;
+ }
+
+ .alarm-severity-text__medium {
+ color: white;
+ background-color: #ffab00;
+ }
+
+ .alarm-severity-text__high {
+ color: white;
+ background-color: #ff5630;
+ }
+`;
+
+/**
+ * ## or-alarms-table
+ * <p>
+ * It extends on {@link OrMwcTable}, and applies both additional styling and helper functions to it.
+ * </p>
+ * Usage;
+ * <pre>
+ * <or-alarms-table .alarms="${alarms}"></or-alarms-table>
+ * </pre>
+ * */
+@customElement("or-alarms-table")
+export class OrAlarmsTable extends OrMwcTable {
+
+ @property()
+ public alarms: SentAlarm[] = [];
+
+ @property({type: Boolean})
+ public readonly = true;
+
+ // Setup columns
+ public columns: AlarmTableColumn[] = [
+ {title: i18next.t("alarm.severity"), widthWeight: 3, isSortable: true},
+ {title: i18next.t("alarm.title"), widthWeight: 25, isSortable: true},
+ {title: i18next.t("alarm.status"), widthWeight: 3, isSortable: true},
+ {title: i18next.t("alarm.linkedAssets"), widthWeight: 6, hideMobile: true},
+ {title: i18next.t("alarm.assignee"), widthWeight: 4, isSortable: true},
+ {title: i18next.t("alarm.lastModified"), widthWeight: 6, isSortable: true}
+ ];
+
+ // Config override
+ protected config: TableConfig = {
+ columnFilter: [],
+ stickyFirstColumn: false,
+ pagination: {
+ enable: true
+ },
+ multiSelect: !this.readonly
+ };
+
+ protected sortIndex = 5;
+ protected sortDirection: "ASC" | "DESC" = "DESC";
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected willUpdate(changedProps: Map<string, any>): any {
+
+ // If alarms changes, update content of the table accordingly
+ if (changedProps.has("alarms") && this.alarms) {
+ this.selectedRows = [];
+ this.rows = this.getTableRows(this.alarms);
+ }
+
+ // If readonly state changes, update multi select
+ if (changedProps.has("readonly")) {
+ this.config.multiSelect = !this.readonly;
+ }
+
+ return super.willUpdate(changedProps);
+ }
+
+
+ protected getTableRows(alarms: SentAlarm[]): TableRow[] | undefined {
+ return alarms?.map(a => {
+ return {
+ content: [
+ this.getSeverityContent(a.severity),
+ this.getDisplayNameContent(a.title),
+ this.getAlarmStatusContent(a.status),
+ this.getLinkedAssetsContent(a.asset),
+ this.getAssigneeContent(a.assigneeUsername),
+ this.getLastModifiedContent(a.lastModified)
+ ],
+ clickable: true
+ } as TableRow;
+ });
+ }
+
+ /* --------------------------------------- */
+
+ /* TEMPLATING FUNCTIONS */
+
+ protected getSeverityContent(severity?: AlarmSeverity): TemplateResult | string | number {
+ const classes = {
+ "alarm-text": true,
+ "alarm-severity-text__low": severity === AlarmSeverity.LOW,
+ "alarm-severity-text__medium": severity === AlarmSeverity.MEDIUM,
+ "alarm-severity-text__high": severity === AlarmSeverity.HIGH
+ };
+ return html`
+ <or-translate class=${classMap(classes)}
+ value="${severity ? `alarm.severity_${severity}` : "error"}"></or-translate>
+ `;
+ }
+
+ protected getDisplayNameContent(title?: string): TableContent {
+ return title;
+ }
+
+ protected getAlarmStatusContent(status?: AlarmStatus): TableContent {
+ const classes = {
+ "alarm-text": true,
+ "alarm-status-text__closed": status === AlarmStatus.CLOSED,
+ "alarm-status-text__resolved": status === AlarmStatus.RESOLVED,
+ "alarm-status-text__acknowledged": status === AlarmStatus.ACKNOWLEDGED,
+ "alarm-status-text__in-progress": status === AlarmStatus.IN_PROGRESS,
+ "alarm-status-text__open": status === AlarmStatus.OPEN
+ };
+ return html`
+ <or-translate class=${classMap(classes)}
+ value="${status ? `alarm.status_${status}` : "error"}"></or-translate>
+ `;
+ }
+
+ protected getLinkedAssetsContent(assets?: Asset[]): TableContent {
+ return html`${assets?.map(a => a.name).join(', ')}`;
+ }
+
+ protected getAssigneeContent(assigneeName?: string): TableContent {
+ return assigneeName;
+ }
+
+ protected getLastModifiedContent(lastModified?: number): TableContent {
+ return new Date(lastModified);
+ }
+
+ protected sortTemplateRows(cellA: any, cellB: any, cIndex: number, sortDirection: 'ASC' | 'DESC'): number {
+ const valueA: string | undefined = (cellA.values as any[]).filter(v => typeof v === 'string' || typeof v === 'number').map(v => v.toString())?.[0];
+ const valueB: string | undefined = (cellB.values as any[]).filter(v => typeof v === 'string' || typeof v === 'number').map(v => v.toString())?.[0];
+ if (valueA !== undefined && valueB !== undefined) {
+ if (valueA.includes("alarm.status") && valueB.includes("alarm.status")) {
+ const sortingArr = ["alarm.status_OPEN", "alarm.status_ACKNOWLEDGED", "alarm.status_IN_PROGRESS", "alarm.status_RESOLVED", "alarm.status_CLOSED"];
+ if (sortDirection === 'DESC') {
+ return sortingArr.indexOf(valueB) - sortingArr.indexOf(valueA);
+ } else {
+ return sortingArr.indexOf(valueA) - sortingArr.indexOf(valueB);
+ }
+ }
+ if (valueA.includes("alarm.severity") && valueB.includes("alarm.severity")) {
+ const sortingArr = ["alarm.severity_LOW", "alarm.severity_MEDIUM", "alarm.severity_HIGH"];
+ if (sortDirection === 'DESC') {
+ return sortingArr.indexOf(valueB) - sortingArr.indexOf(valueA);
+ } else {
+ return sortingArr.indexOf(valueA) - sortingArr.indexOf(valueB);
+ }
+ }
+
+ return this.sortPrimitiveRows([valueA], [valueB], 0, sortDirection);
+ } else {
+ return 1;
+ }
+ }
+
+
+ /* --------------------------------------- */
+
+ /* STYLING MODIFICATIONS */
+
+ /** Applies the custom 'weighted width' field of AlarmTableColumn, to make columns wider/smaller relative to others. */
+ protected getColumnWidth(index: number, columns?: string[] | TableColumn[], tableWidthPx?: number): string | undefined {
+ const column = columns[index];
+ const totalWeight = this.getTotalColumnWidthWeight(columns);
+ if (typeof column !== "string" && totalWeight && (column as AlarmTableColumn).widthWeight) {
+ return `${(column as AlarmTableColumn).widthWeight / totalWeight * 100}%`;
+ }
+ return super.getColumnWidth(index, columns, tableWidthPx);
+ }
+
+ /** In AlarmTableColumn, columns can have a 'weighted width' which makes them wider/smaller relative to others.
+ * This function calculates the total of these values. */
+ protected getTotalColumnWidthWeight(columns?: string[] | TableColumn[]): number | undefined {
+ let totalWeight = 0;
+ columns.forEach(c => {
+ if (typeof c !== "string") {
+ totalWeight = totalWeight + (c as AlarmTableColumn).widthWeight;
+ }
+ });
+ return totalWeight;
+ }
+}
diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.ts
index dd102a9da..aab2f92f3 100644
--- a/ui/app/manager/src/index.ts
+++ b/ui/app/manager/src/index.ts
@@ -43,6 +43,7 @@ import "./pages/page-realms";
import {pageRealmsProvider} from "./pages/page-realms";
import {pageExportProvider} from "./pages/page-export";
import { pageConfigurationProvider } from "./pages/page-configuration";
+import {pageAlarmsProvider} from "./pages/page-alarms";
import { ManagerAppConfig } from "@openremote/model";
import {pageGatewayTunnelProvider} from "./pages/page-gateway-tunnel";
@@ -76,7 +77,8 @@ export const DefaultPagesConfig: PageProvider<any>[] = [
pageRealmsProvider(store),
pageExportProvider(store),
pageProvisioningProvider(store),
- pageConfigurationProvider(store)
+ pageConfigurationProvider(store),
+ pageAlarmsProvider(store)
];
export const DefaultHeaderMainMenu: {[name: string]: HeaderItem} = {
diff --git a/ui/app/manager/src/pages/page-alarms.ts b/ui/app/manager/src/pages/page-alarms.ts
new file mode 100644
index 000000000..1e3578c1d
--- /dev/null
+++ b/ui/app/manager/src/pages/page-alarms.ts
@@ -0,0 +1,1059 @@
+import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";
+import {customElement, property, query, state} from "lit/decorators.js";
+import {AppStateKeyed, Page, PageProvider, router} from "@openremote/or-app";
+import {Store} from "@reduxjs/toolkit";
+import {
+ AlarmAssetLink,
+ AlarmSeverity,
+ AlarmSource,
+ AlarmStatus,
+ Asset,
+ SentAlarm,
+ User,
+ UserQuery
+} from "@openremote/model";
+import manager, {DefaultColor3, DefaultColor4} from "@openremote/core";
+import i18next from "i18next";
+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {GenericAxiosResponse, isAxiosError} from "@openremote/rest";
+import {getAlarmsRoute} from "../routes";
+import {when} from "lit/directives/when.js";
+import {until} from "lit/directives/until.js";
+import {guard} from "lit/directives/guard.js";
+import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
+import {OrMwcDialog, showDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrAssetTreeRequestSelectionEvent, OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";
+import {
+ OrMwcTable,
+ OrMwcTableRowClickEvent,
+ OrMwcTableRowSelectEvent
+} from "@openremote/or-mwc-components/or-mwc-table";
+import "../components/alarms/or-alarms-table";
+
+export interface PageAlarmsConfig {
+ initialFilter?: string;
+ initialSeverity?: AlarmSeverity;
+ assignOnly?: boolean;
+}
+
+export function pageAlarmsProvider(store: Store<AppStateKeyed>, config?: PageAlarmsConfig): PageProvider<AppStateKeyed> {
+ return {
+ name: "alarms",
+ routes: ["alarms", "alarms/:id"],
+ pageCreator: () => {
+ return new PageAlarms(store);
+ }
+ };
+}
+
+interface AlarmModel extends SentAlarm {
+ loaded?: boolean;
+ loading?: boolean;
+ alarmAssetLinks?: AlarmAssetLink[];
+ previousAssetLinks?: AlarmAssetLink[];
+}
+
+@customElement("page-alarms")
+export class PageAlarms extends Page<AppStateKeyed> {
+ static get styles() {
+ // language=CSS
+ return [
+ css`
+ :host {
+ flex: 1;
+ width: 100%;
+ }
+
+ #wrapper {
+ height: 100%;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ overflow: auto;
+ }
+
+ #title {
+ padding: 0 20px;
+ font-size: 18px;
+ font-weight: bold;
+ margin: 10px 0;
+ display: flex;
+ align-items: center;
+ color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});
+ justify-content: space-between;
+ }
+
+ #title-alarm {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ width: calc(100% - 52px);
+ max-width: 1000px;
+ margin: 20px auto;
+ font-size: 18px;
+ font-weight: bold;
+ }
+
+ .breadcrumb-container {
+ width: calc(100% - 52px);
+ max-width: 1000px;
+ margin: 10px 20px 0 34px;
+ display: flex;
+ align-items: center;
+ }
+
+ .breadcrumb-clickable {
+ cursor: pointer;
+ color: var(--or-app-color4, ${unsafeCSS(DefaultColor4)});
+ }
+
+ .breadcrumb-arrow {
+ margin: 0 5px -3px 5px;
+ --or-icon-width: 16px;
+ --or-icon-height: 16px;
+ }
+
+ .panel {
+ width: calc(100% - 100px);
+ max-width: 1000px;
+ background-color: white;
+ border: 1px solid #e5e5e5;
+ border-radius: 5px;
+ position: relative;
+ margin: auto;
+ padding: 12px 24px 24px;
+ }
+
+ .panel-title {
+ text-transform: uppercase;
+ font-weight: bolder;
+ color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});
+ line-height: 1em;
+ /*margin-bottom: 10px;*/
+ margin-top: 0;
+ flex: 0 0 auto;
+ letter-spacing: 0.025em;
+ display: flex;
+ align-items: center;
+ min-height: 36px;
+ }
+
+ .alarm-input {
+ margin-bottom: 12px;
+ }
+
+ #status-select, #severity-select {
+ width: 180px;
+ }
+
+ #controls {
+ flex: 0;
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ }
+
+ .controls-left {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ }
+
+ .controls-left > * {
+ padding-right: 20px;
+ }
+
+ h5 {
+ margin-top: 12px;
+ margin-bottom: 6px;
+ }
+
+ or-icon {
+ vertical-align: middle;
+ --or-icon-width: 20px;
+ --or-icon-height: 20px;
+ }
+
+ #table-container {
+ margin-left: 20px;
+ margin-right: 20px;
+ }
+
+ .row {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ margin: auto;
+ flex: 1 1 0;
+ gap: 16px;
+ width: 100%;
+ }
+
+ .column {
+ display: flex;
+ flex-direction: column;
+ margin: 0px;
+ flex: 1 1 0;
+ }
+
+ #details-panel {
+ min-width: 66%;
+ height: max-content;
+ }
+
+ #prop-panel {
+ min-width: 32%;
+ height: fit-content;
+ }
+
+ .hidden {
+ display: none;
+ margin: 0 !important;
+ }
+
+ #title.hidden {
+ display: none;
+ margin: 0 !important;
+ }
+ `];
+ }
+
+ @property()
+ public config?: PageAlarmsConfig;
+
+ @property()
+ public realm?: string;
+ @state()
+ public alarm?: AlarmModel;
+ @state()
+ public creationState?: {
+ alarmModel: AlarmModel;
+ };
+
+ @state()
+ protected _alarms: AlarmModel[] = [];
+ @state()
+ protected _linkedAssets: Asset[] = [];
+ @state()
+ protected _linkedUsers: User[] = [];
+ @state()
+ protected _loadedUsers: User[] = [];
+
+ protected _loading: boolean = false;
+
+ @state()
+ public severity?: AlarmSeverity;
+
+ @state()
+ public status?: AlarmStatus;
+
+ @state()
+ public assign: boolean = false;
+
+ @state()
+ public allActive: boolean = true;
+
+ @state()
+ protected _data?: SentAlarm[];
+
+ @state()
+ protected _loadAlarmsPromise?: Promise<any>;
+
+ @state()
+ protected _saveAlarmPromise?: Promise<any>;
+
+ @state()
+ protected _loadUsersPromise?: Promise<any>;
+
+ @query("#table")
+ protected _tableElem!: HTMLDivElement;
+ protected _table?: OrMwcTable;
+ protected _refresh?: number;
+ @state()
+ protected _selectedIds?: number[];
+
+ get statusValue() {
+ const statusOptions = this._getStatusOptions();
+ const matchingOption = statusOptions.find(option =>
+ option.value === this.status ||
+ (this.allActive && option.value === 'All-active') ||
+ (!this.status && option.value === 'All')
+ );
+ return matchingOption ? matchingOption.label : '';
+ }
+
+ get severityValue() {
+ const severityOptions = this._getSeverityOptions();
+ const matchingOption = severityOptions.find(option =>
+ option.value === this.severity ||
+ (!this.severity && option.value === 'All')
+ );
+ return matchingOption ? matchingOption.label : '';
+ }
+
+ get name(): string {
+ return "alarm.alarm_plural";
+ }
+
+ constructor(store: Store<AppStateKeyed>) {
+ super(store);
+ }
+
+ public connectedCallback() {
+ super.connectedCallback();
+ this.realm = this.getState().app.realm;
+ this._loadData();
+ }
+
+ public shouldUpdate(changedProperties: PropertyValues): boolean {
+ if (changedProperties.has("realm") && changedProperties.get("realm") != undefined) {
+ this.reset();
+ }
+ if (changedProperties.has("alarm")) {
+ this._updateRoute();
+ }
+ if (changedProperties.has("severity")
+ || changedProperties.has("status")
+ || changedProperties.has("allActive")) {
+ this._data = undefined;
+ }
+
+ if (!this._data) {
+ this._loadData();
+ }
+
+ return super.shouldUpdate(changedProperties);
+ }
+
+ protected responseAndStateOK(
+ stateChecker: () => boolean,
+ response: GenericAxiosResponse<any>,
+ errorMsg: string
+ ): boolean {
+ if (!stateChecker()) {
+ return false;
+ }
+
+ if (!response.data) {
+ showSnackbar(undefined, errorMsg, i18next.t("dismiss"));
+ console.error(errorMsg + ": response = " + response.statusText);
+ return false;
+ }
+
+ return true;
+ }
+
+ protected async _createUpdateAlarm(alarm: AlarmModel, action: "update" | "create") {
+ if (!alarm.title || alarm.title === "") {
+ return;
+ }
+
+ const isUpdate = !!alarm.id;
+ let assetsIds: string[];
+
+ if (!isUpdate) {
+ alarm.realm = manager.displayRealm;
+ assetsIds = alarm.alarmAssetLinks.map(l => l.id.assetId)
+ }
+
+ try {
+ action == "update"
+ ? await manager.rest.api.AlarmResource.updateAlarm(alarm.id, alarm)
+ : await manager.rest.api.AlarmResource.createAlarm(alarm, {assetIds: assetsIds}).then(async (response) => {
+ if (alarm.alarmAssetLinks.length > 0) {
+ alarm.alarmAssetLinks.forEach((link) => {
+ link.id.sentalarmId = response.data.id;
+ link.id.realm = response.data.realm;
+ })
+ await manager.rest.api.AlarmResource.setAssetLinks(alarm.alarmAssetLinks);
+ }
+ });
+ } catch (e) {
+ if (isAxiosError(e)) {
+ console.error(
+ (isUpdate ? "alarm.saveAlarmFailed" : "alarm.createAlarmFailed") + ": response = " + e.response.statusText
+ );
+
+ if (e.response.status === 400) {
+ showSnackbar(
+ undefined,
+ i18next.t(isUpdate ? "alarm.saveAlarmFailed" : "alarm.createAlarmFailed"),
+ i18next.t("dismiss")
+ );
+ } else if (e.response.status === 403) {
+ showSnackbar(undefined, i18next.t("alarm.alarmAlreadyExists"));
+ }
+ }
+ throw e; // Throw exception anyhow to handle individual cases
+ } finally {
+ this.reset();
+ await this._loadData();
+ }
+ }
+
+ protected render() {
+ if (!manager.authenticated) {
+ return html`
+ <or-translate value="notAuthenticated"/>`;
+ }
+
+ const disabled = false;
+ const readAlarms = manager.hasRole("read:alarms");
+ const writeAlarms = manager.hasRole("write:alarms");
+
+ const readonly = readAlarms && !writeAlarms;
+ const assignOnly = !readAlarms && !writeAlarms;
+ this.config = {assignOnly: assignOnly};
+ return html`
+ <div id="wrapper">
+ <!-- Alarm Specific page -->
+ <div id="title" class="${this.creationState || this.alarm ? "hidden" : ""}">
+ <div class="${this.creationState || this.alarm ? "hidden" : ""}"
+ style="display: flex; align-items: center;">
+ <or-icon icon="bell-outline" style="padding: 0 10px 0 4px;"></or-icon>
+ <span>${this.alarm != undefined ? this.alarm.title : html`
+ <or-translate value="alarm.alarm_plural"/>`}</span>
+ </div>
+ <div>
+ <div id="controls">
+ <div class="${this.creationState || this.alarm || assignOnly || readonly ? "hidden" : "panel-title"}"
+ style="justify-content: flex-end;">
+ <or-mwc-input
+ outlined
+ class="${this._selectedIds?.length > 0 ? "" : "hidden"}"
+ style="margin: 0;"
+ type="${InputType.BUTTON}"
+ icon="delete"
+ @or-mwc-input-changed="${() => (this._deleteAlarms())}"
+ ></or-mwc-input>
+ </div>
+ <div class="${this._selectedIds?.length > 0 ? "" : "hidden"}"
+ style="height:40px; border-right: 1px solid #e0e0e0; margin-right: 4px;"></div>
+ <div class="${this.creationState || this.alarm ? "hidden" : "controls-left"}">
+ <or-mwc-input .type="${InputType.CHECKBOX}" id="assign-check"
+ ?disabled="${disabled}" .label="${i18next.t("alarm.assignedToMe")}"
+ @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._onAssignCheckChanged(evt.detail.value)}"
+ .value="${this.assign}"></or-mwc-input>
+ <or-mwc-input .type="${InputType.SELECT}" id="severity-select" comfortable
+ ?disabled="${disabled}" .label="${i18next.t("alarm.severity")}"
+ @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._onSeverityChanged(evt.detail.value)}"
+ .value="${this.severityValue}"
+ .options="${this._getSeverityOptions().map(s => s.label)}"></or-mwc-input>
+ <or-mwc-input .type="${InputType.SELECT}" id="status-select" comfortable
+ ?disabled="${disabled}" .label="${i18next.t("alarm.status")}"
+ @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._onStatusChanged(evt.detail.value)}"
+ .value="${this.statusValue}"
+ .options="${this._getStatusOptions().map(s => s.label)}"></or-mwc-input>
+
+ </div>
+ <div class="${this.creationState || this.alarm || assignOnly || readonly ? "hidden" : "panel-title"}"
+ style="justify-content: flex-end;">
+ <or-mwc-input
+ type="${InputType.BUTTON}"
+ icon="plus"
+ label="${i18next.t("alarm.add")}"
+ @or-mwc-input-changed="${() => (this.creationState = {alarmModel: this.getNewAlarmModel()})}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </div>
+ </div>
+ ${when(this.alarm || this.creationState, () => {
+ const alarm: AlarmModel = this.alarm ?? this.creationState.alarmModel;
+ return this.getSingleAlarmView(alarm, readonly);
+ }, () => {
+ return html`
+ <!-- List of Alarms page -->
+ <div id="container">
+ ${disabled ? html`
+ <div id="msg">
+ <or-translate value="loading"/>
+ </div>
+ ` : html`
+ <div id="table-container">
+ ${when(this._data, () => guard([this._data], () => this.getAlarmsTable(writeAlarms)))}
+ </div>
+ `}
+ </div>
+ `;
+ })}
+ </div>
+ `;
+ }
+
+ protected getNewAlarmModel(): AlarmModel {
+ return {
+ alarmAssetLinks: [],
+ previousAssetLinks: [],
+ loaded: true,
+ source: AlarmSource.MANUAL,
+ severity: AlarmSeverity.MEDIUM,
+ status: AlarmStatus.OPEN,
+ realm: manager.displayRealm
+ };
+ }
+
+ protected async loadAlarm(alarm: AlarmModel) {
+ if (alarm.loaded) {
+ return;
+ }
+ const stateChecker = () => {
+ return this.getState().app.realm === this.realm && this.isConnected;
+ };
+
+ const alarmAssetLinksResponse = await manager.rest.api.AlarmResource.getAssetLinks(alarm.id, {realm: alarm.realm});
+
+ if (!this.responseAndStateOK(stateChecker, alarmAssetLinksResponse, i18next.t("loadFailedUsers"))) {
+ return;
+ }
+
+ if (manager.hasRole("read:users") || manager.hasRole("read:admin")) {
+ const usersResponse = await manager.rest.api.UserResource.query({
+ realmPredicate: {name: manager.displayRealm},
+ } as UserQuery);
+
+ if (!this.responseAndStateOK(stateChecker, usersResponse, i18next.t("loadFailedUsers"))) {
+ return;
+ }
+
+ this._loadedUsers = usersResponse.data.filter((user) => user.enabled && !user.serviceAccount);
+ }
+ this.alarm.alarmAssetLinks = alarmAssetLinksResponse.data;
+
+ this.alarm.loaded = true;
+ this.alarm.loading = false;
+
+ // Update the dom
+ this.requestUpdate();
+ }
+
+ protected getAlarmsTable(writeAlarms: boolean) {
+ return html`
+ <or-alarms-table .alarms=${this._data} .readonly=${!writeAlarms}
+ @or-mwc-table-row-select="${(e: OrMwcTableRowSelectEvent) => this._onRowSelect(e)}"
+ @or-mwc-table-row-click="${(e: OrMwcTableRowClickEvent) => this._onRowClick(e)}"
+ ></or-alarms-table>
+ `;
+ }
+
+ protected async _loadData() {
+ if (this._loading || (!manager.hasRole("read:alarms") && !manager.hasRole("write:alarms"))) {
+ return;
+ }
+
+ this._loading = true;
+ const response = await manager.rest.api.AlarmResource.getAlarms({realm: manager.displayRealm});
+ if (manager.hasRole("read:users") || manager.hasRole("read:admin")) {
+ const usersResponse = await manager.rest.api.UserResource.query({
+ realmPredicate: {name: manager.displayRealm},
+ } as UserQuery);
+
+ if (usersResponse.status === 200) {
+ this._loadedUsers = usersResponse.data.filter((user) => user.enabled && !user.serviceAccount);
+ }
+ }
+
+ if (response.status === 200) {
+ // Get page count
+ this._data = response.data;
+ this._data = this._data.filter((e) => e.realm === manager.displayRealm);
+ this._selectedIds = [];
+
+ if (this.config?.assignOnly) {
+ const userResponse = await manager.rest.api.UserResource.getCurrent();
+ if (userResponse.status === 200) {
+ this._data = this._data.filter((e) => e.assigneeId === userResponse.data.id);
+ }
+ }
+ if (this.severity) {
+ this._data = this._data.filter((e) => e.severity === this.severity);
+ }
+ if (this.status) {
+ this._data = this._data.filter((e) => e.status === this.status);
+ }
+ if (!this.status && this.allActive) {
+ this._data = this._data.filter((e) => e.status !== AlarmStatus.RESOLVED && e.status !== AlarmStatus.CLOSED);
+ }
+ if (this.assign) {
+ await this._onAssignCheckChanged(this.assign);
+ }
+ }
+ this._loading = false;
+ }
+
+ private _deleteAlarm(alarm: SentAlarm) {
+ showOkCancelDialog(i18next.t("alarm.deleteAlarm"), i18next.t("alarm.deleteAlarmConfirm", {alarm: alarm.title}), i18next.t("delete"))
+ .then((ok) => {
+ if (ok) {
+ this.doDelete(alarm.id);
+ }
+ });
+ }
+
+ private _deleteAlarms() {
+ showOkCancelDialog(i18next.t("alarm.deleteAlarms"), i18next.t("alarm.deleteAlarmsConfirm", {count: this._selectedIds.length}), i18next.t("delete"))
+ .then((ok) => {
+ if (ok) {
+ this.doMultipleDelete(this._selectedIds);
+ }
+ });
+ }
+
+ private doDelete(alarmId: any) {
+ manager.rest.api.AlarmResource.removeAlarm(alarmId).then(response => {
+ this.reset();
+ })
+ }
+
+ private doMultipleDelete(alarmIds: any[]) {
+ manager.rest.api.AlarmResource.removeAlarms(alarmIds).then(response => {
+ this.reset();
+ })
+ }
+
+ protected getSingleAlarmView(alarm: AlarmModel, readonly: boolean = true): TemplateResult {
+ return html`
+ ${when(
+ alarm.loaded,
+ () => {
+ return this.getSingleAlarmTemplate(alarm, readonly);
+ },
+ () => {
+ const getTemplate = async () => {
+ await this.loadAlarm(alarm);
+ return this.getSingleAlarmTemplate(alarm, readonly);
+ };
+ const content: Promise<TemplateResult> = getTemplate();
+ return html`${until(content, html`
+ <or-translate value="loading"/>`)} `;
+ }
+ )}
+ `;
+ }
+
+ protected getSingleAlarmTemplate(alarm: AlarmModel, readonly: boolean = true): TemplateResult {
+ const write = manager.hasRole("write:alarms");
+ return html`
+ <!-- Breadcrumb on top of the page-->
+ <div style="margin: 0 auto auto auto;
+ width: calc(100% - 100px);
+ max-width: 1000px;">
+ <div class="breadcrumb-container">
+ <span class="breadcrumb-clickable" @click="${() => this.reset()}"
+ ><or-translate value="alarm.alarm_plural"/></span>
+ <or-icon class="breadcrumb-arrow" icon="chevron-right"></or-icon>
+ <span style="margin-left: 2px;"
+ >${this.alarm != undefined ? this.alarm.id : html`
+ <or-translate value="alarm.creatingAlarm"/>`}</span>
+ </div>
+ <div id="title-alarm">
+ <or-icon icon="bell-outline" style="margin-right: 10px; margin-left: 14px;"></or-icon>
+ <span>${this.alarm != undefined ? this.alarm.title : html`
+ <or-translate value="alarm.alarm_plural"/>`}</span>
+ </div>
+
+ <div class="panel" style="margin-top: 0">
+ <div class="row">
+ <div class="column" id="details-panel">
+ <h5>
+ <or-translate value="details"/>
+ </h5>
+ <!-- alarm details -->
+ <or-mwc-input class="alarm-input" ?disabled="${!write}"
+ .label="${i18next.t("alarm.title")}" required
+ .type="${InputType.TEXT}"
+ .value="${alarm.title}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ alarm.title = e.detail.value;
+ this.onAlarmChanged(e);
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input class="alarm-input" ?disabled="${!write}"
+ .label="${i18next.t("alarm.content")}"
+ .type="${InputType.TEXTAREA}"
+ .value="${alarm.content}"
+ rows="12"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ alarm.content = e.detail.value;
+ this.onAlarmChanged(e);
+ }}"
+ ></or-mwc-input>
+ </div>
+ <div class="column" id="prop-panel">
+ <h5>
+ <or-translate value="properties"/>
+ </h5>
+ <or-mwc-input class="alarm-input hidden" ?disabled="${true}"
+ ?comfortable=${!this.creationState}
+ .label="${i18next.t("createdOn")}"
+ .type="${InputType.DATETIME}"
+ .value="${new Date(alarm.createdOn)}"
+ ></or-mwc-input>
+ <or-mwc-input class="${this.creationState ? "hidden" : "alarm-input"}" ?disabled="${true}"
+ .label="${i18next.t("alarm.lastModified")}"
+ .type="${InputType.DATETIME}"
+ .value="${new Date(alarm.lastModified)}"
+ ></or-mwc-input>
+ <or-mwc-input class="alarm-input" ?disabled="${!write || this.creationState || this.alarm}"
+ .label="${i18next.t("alarm.source")}"
+ .type="${InputType.TEXT}"
+ .value="${this._getSourceText()}"
+ ></or-mwc-input>
+ <or-mwc-input class="alarm-input" ?disabled="${!write}"
+ .label="${i18next.t("alarm.severity")}"
+ .type="${InputType.SELECT}"
+ .options="${this._getAddSeverityOptions().map(s => s.label)}"
+ .value="${this._getAddSeverityOptions().filter((obj) => obj.value === alarm.severity).map((obj) => obj.label)[0]}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ alarm.severity = this._getAddSeverityOptions().filter((obj) => obj.label === e.detail.value).map((obj) => obj.value)[0];
+ this.onAlarmChanged(e);
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input class="alarm-input" ?disabled="${!write}"
+ .label="${i18next.t("alarm.status")}"
+ .type="${InputType.SELECT}"
+ .options="${this._getAddStatusOptions().map(s => s.label)}"
+ .value="${this._getAddStatusOptions().filter((obj) => obj.value === alarm.status).map((obj) => obj.label)[0]}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ alarm.status = this._getAddStatusOptions().filter((obj) => obj.label === e.detail.value).map((obj) => obj.value)[0];
+ this.onAlarmChanged(e);
+ }}"
+ ></or-mwc-input>
+ <or-mwc-input class="alarm-input"
+ ?disabled="${!manager.hasRole("read:users") && !manager.hasRole("read:admin")}"
+ .label="${i18next.t("alarm.assignee")}"
+ .type="${InputType.SELECT}"
+ .options="${this._getUsers().map((obj) => obj.label)}"
+ .value="${this._getUsers().filter((obj) => obj.label === alarm.assigneeUsername).map((obj) => obj.label)[0]}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ alarm.assigneeId = this._getUsers().filter((obj) => obj.label === e.detail.value).map((obj) => obj.value)[0];
+ this.onAlarmChanged(e);
+ }}"
+ ></or-mwc-input>
+ <div>
+ <span style="margin: 0px auto 10px;"><or-translate value="linkedAssets"/>:</span>
+ <or-mwc-input outlined ?disabled="${!manager.hasRole("write:alarms")}"
+ style="margin-left: 4px;"
+ .type="${InputType.BUTTON}"
+ .label="${i18next.t("selectRestrictedAssets", {
+ number: alarm.alarmAssetLinks?.length,
+ })}"
+ @or-mwc-input-changed="${(ev: MouseEvent) =>
+ this._openAssetSelector(ev, alarm, readonly)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </div>
+ <!-- Bottom controls (save/update and delete button) -->
+ ${when(!(readonly && !this._saveAlarmPromise), () => html`
+ <div class="row" style="justify-content: space-between; margin-top: 10px;">
+ ${when((manager.hasRole("write:alarms")), () => html`
+ <or-mwc-input class="alarm-input" style="margin: 0;" outlined
+ ?disabled="${!manager.hasRole("write:alarms") || !alarm.id}"
+ .label="${i18next.t("delete")}"
+ .type="${InputType.BUTTON}"
+ @or-mwc-input-changed="${() => this._deleteAlarm(this.alarm)}"
+ ></or-mwc-input>
+ `)}
+ <div>
+ <or-mwc-input class="alarm-input" style="margin: 0;" outlined
+ .label="${i18next.t("cancel")}"
+ .type="${InputType.BUTTON}"
+ @or-mwc-input-changed="${() => this.reset()}"
+ ></or-mwc-input>
+ <or-mwc-input id="savebtn"
+ style="margin: 0;"
+ raised class="alarm-input" disabled
+ .label="${i18next.t(alarm.id ? "save" : "create")}"
+ .type="${InputType.BUTTON}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ let error: { status?: number; text: string };
+ this._saveAlarmPromise = this._createUpdateAlarm(alarm, alarm.id ? "update" : "create")
+ .then(() => {
+ showSnackbar(undefined, i18next.t("alarm.saveAlarmSucceeded"));
+ this.reset();
+ }).catch((ex) => {
+ if (isAxiosError(ex)) {
+ error = {
+ status: ex.response.status,
+ text: ex.response.status === 403 ? i18next.t("alarm.alarmAlreadyExists") : i18next.t("errorOccurred"),
+ };
+ }
+ }).finally(() => {
+ this._saveAlarmPromise = undefined;
+ });
+ }}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ `)}
+ </div>
+ </div>
+ </div>`;
+ }
+
+ protected _getStatusOptions() {
+ return [{label: 'alarm.allActive', value: 'All-active'}, {
+ label: 'alarm.all',
+ value: 'All'
+ }].concat(this._getAddStatusOptions());
+ }
+
+ protected _getSeverityOptions() {
+ return [{label: 'alarm.all', value: 'All'}].concat(this._getAddSeverityOptions());
+ }
+
+ protected _getAddStatusOptions() {
+ const statuses = [AlarmStatus.OPEN, AlarmStatus.ACKNOWLEDGED, AlarmStatus.IN_PROGRESS, AlarmStatus.RESOLVED, AlarmStatus.CLOSED];
+ return statuses.map(status => ({label: 'alarm.status_' + status, value: status}));
+ }
+
+ protected _getAddSeverityOptions() {
+ const severities = [AlarmSeverity.LOW, AlarmSeverity.MEDIUM, AlarmSeverity.HIGH];
+ return severities.map(status => ({label: 'alarm.severity_' + status, value: status}));
+ }
+
+ protected _getSourceText(): string {
+ const alarm: AlarmModel = this.alarm ?? this.creationState.alarmModel
+ const alarmSource = alarm.source;
+ const alarmSourceId = alarm.sourceId;
+ const sourceText = i18next.t('alarm.source_' + alarmSource);
+
+ if (alarmSourceId) {
+ let sourceIdText: string;
+ if ([AlarmSource.REALM_RULESET, AlarmSource.ASSET_RULESET, AlarmSource.GLOBAL_RULESET].includes(alarmSource)) {
+ sourceIdText = "ID: " + alarmSourceId;
+ } else if (alarmSource === AlarmSource.MANUAL) {
+ sourceIdText = alarm.sourceUsername;
+ }
+ return sourceIdText ? sourceText + " (" + sourceIdText + ")" : sourceText;
+ }
+ return sourceText;
+ }
+
+ protected _onSeverityChanged(severity: any) {
+ if (severity == 'alarm.all') {
+ this.severity = undefined;
+ this._loadData();
+ return;
+ }
+
+ this.severity = this._getSeverityOptions().filter((obj) => obj.label === severity).map((obj) => obj.value)[0] as AlarmSeverity;
+
+ if (!this.severity) {
+ return;
+ }
+ this._data = this._data!.filter((e) => e.severity === this.severity);
+ }
+
+ protected async _onAssignCheckChanged(assign: boolean) {
+ this.assign = assign;
+
+ if (this.assign === undefined) {
+ return;
+ }
+ const response = await manager.rest.api.UserResource.getCurrent();
+ if (response.status === 200 && this.assign) {
+ this._data = this._data!.filter((e) => e.assigneeId === response.data.id);
+ } else if (!this.assign) {
+ this._loadData();
+ }
+ }
+
+ protected _onStatusChanged(status: any) {
+ if (status == 'alarm.all') {
+ this.status = undefined;
+ this.allActive = undefined;
+ this.requestUpdate();
+ return;
+ }
+
+ if (status == 'alarm.allActive') {
+ this.status = undefined;
+ this.allActive = true;
+ this.requestUpdate();
+ return;
+ }
+ this.allActive = undefined;
+ this.status = this._getStatusOptions().filter((obj) => obj.label === status).map((obj) => obj.value)[0] as AlarmStatus;
+ if (!this.status) {
+ return;
+ }
+
+ this._data = this._data!.filter((e) => e.status === this.status);
+ }
+
+ protected _onRowSelect(ev: OrMwcTableRowSelectEvent) {
+ const alarm = this._data[ev.detail.index];
+ if (alarm) {
+ if (ev.detail.state) {
+ if (this._selectedIds === undefined) {
+ this._selectedIds = [alarm.id];
+ } else {
+ this._selectedIds.push(alarm.id);
+ this.requestUpdate('_selectedIds');
+ }
+ } else {
+ this._selectedIds = this._selectedIds.filter(id => id !== alarm.id);
+ }
+ } else {
+ console.warn("Tried selecting an alarm that does not exist?")
+ }
+ }
+
+ protected _onRowClick(ev: OrMwcTableRowClickEvent) {
+ if (!ev.detail.index && ev.detail.index != 0) {
+ return;
+ }
+ this.alarm = this._data[ev.detail.index] as AlarmModel;
+ this.alarm.loaded = false;
+ this.alarm.loading = false;
+ this.alarm.alarmAssetLinks = [];
+ this.loadAlarm(this.alarm);
+ this.requestUpdate();
+ }
+
+
+ protected _getUsers() {
+ let options = this._loadedUsers.filter((u) => u.username != 'manager-keycloak').map((u) => {
+ return {value: u.id, label: u.username};
+ });
+ options.unshift({value: null, label: i18next.t("none")})
+ return options;
+ }
+
+ protected _openAssetSelector(ev: MouseEvent, alarm: AlarmModel, readonly: boolean) {
+ const openBtn = ev.target as OrMwcInput;
+ openBtn.disabled = true;
+ alarm.previousAssetLinks = alarm.alarmAssetLinks ? [...alarm.alarmAssetLinks] : [];
+
+ const onAssetSelectionChanged = (e: OrAssetTreeSelectionEvent) => {
+ alarm.alarmAssetLinks = e.detail.newNodes.map(node => {
+ const alarmAssetLink: AlarmAssetLink = {
+ id: {
+ sentalarmId: alarm.id,
+ realm: alarm.realm,
+ assetId: node.asset.id
+ }
+ };
+ return alarmAssetLink;
+ })
+ };
+
+ const dialog = showDialog(
+ new OrMwcDialog()
+ .setHeading(i18next.t("linkedAssets"))
+ .setContent(
+ html`
+ <or-asset-tree
+ id="chart-asset-tree"
+ readonly="true"
+ .selectedIds="${alarm.alarmAssetLinks?.map((al) => al.id.assetId)}"
+ .showSortBtn="${false}"
+ expandNodes
+ checkboxes
+ @or-asset-tree-request-selection="${(e: OrAssetTreeRequestSelectionEvent) => {
+ this.creationState ? e.detail.allow = true : e.detail.allow = false;
+ }}"
+ @or-asset-tree-selection="${(e: OrAssetTreeSelectionEvent) => {
+ if (!readonly) {
+ onAssetSelectionChanged(e);
+ }
+ }}"
+ ></or-asset-tree>
+ `
+ )
+ .setActions([
+ {
+ default: true,
+ actionName: "cancel",
+ content: i18next.t("cancel"),
+ action: () => {
+ openBtn.disabled = false;
+ },
+ },
+ {
+ actionName: "ok",
+ content: "ok",
+ action: () => {
+ openBtn.disabled = false;
+ this.onAlarmChanged(this.shadowRoot.querySelector('or-mwc-input') as OrMwcInput);
+ this.requestUpdate();
+ }
+ }
+ ])
+ .setDismissAction({
+ actionName: "cancel",
+ action: () => {
+ openBtn.disabled = false;
+ },
+ })
+ );
+ }
+
+ // Reset selected alarm and go back to the alarm overview
+ protected reset() {
+ this._selectedIds = [];
+ this.alarm = undefined;
+ this.creationState = undefined;
+ this._data = undefined;
+ this._selectedIds = undefined;
+ this.assign = false;
+ if (this._table) {
+ this._table = undefined;
+ }
+ if (this._refresh) {
+ window.clearTimeout(this._refresh);
+ }
+ }
+
+ public stateChanged(state: AppStateKeyed) {
+ if (state.app.page == "alarms") {
+ if (this.realm === undefined || this.realm == state.app.realm) {
+ if (state.app.params && state.app.params.id) {
+ const parsedId = Number(state.app.params.id);
+ manager.rest.api.AlarmResource.getAlarm(parsedId).then((alarm: any) => {
+ this.alarm = alarm.data as AlarmModel;
+ this.alarm.loaded = false;
+ this.alarm.loading = false;
+ this.alarm.alarmAssetLinks = [];
+ this.loadAlarm(this.alarm);
+ this.requestUpdate();
+ }).catch((ex) => {
+ if (isAxiosError(ex)) {
+ this.reset();
+ }
+ })
+ } else if (!this.creationState) {
+ this.reset();
+ }
+ } else {
+ this.realm = state.app.realm;
+ this.requestUpdate('realm');
+ }
+ }
+ }
+
+ protected _updateRoute(silent: boolean = false) {
+ router.navigate(getAlarmsRoute(this.alarm?.id.toString()), {
+ callHooks: !silent,
+ callHandler: !silent,
+ });
+ }
+
+ protected onAlarmChanged(e: OrInputChangedEvent | OrMwcInput) {
+ const formElement = e instanceof OrInputChangedEvent ? (e.target as HTMLElement).parentElement : e.parentElement;
+ const saveBtn = this.shadowRoot.getElementById("savebtn") as OrMwcInput;
+
+ if (formElement) {
+ saveBtn.disabled = Array.from(formElement.children)
+ .filter((e) => e instanceof OrMwcInput)
+ .some((input) => !(input as OrMwcInput).valid);
+ }
+
+ if (this.alarm && !this.alarm.title) {
+ saveBtn.disabled = true;
+ }
+ }
+}
diff --git a/ui/app/manager/src/pages/page-assets.ts b/ui/app/manager/src/pages/page-assets.ts
index 53deb9883..93fdfcdbb 100644
--- a/ui/app/manager/src/pages/page-assets.ts
+++ b/ui/app/manager/src/pages/page-assets.ts
@@ -10,7 +10,7 @@ import {
OrAssetViewerLoadUserEvent,
saveAsset,
SaveResult,
- ViewerConfig
+ ViewerConfig, OrAssetViewerLoadAlarmEvent
} from "@openremote/or-asset-viewer";
import {
AssetTreeConfig,
@@ -29,7 +29,7 @@ import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import i18next from "i18next";
import {AssetEventCause, WellknownAssets} from "@openremote/model";
import "@openremote/or-json-forms";
-import {getAssetsRoute, getUsersRoute} from "../routes";
+import {getAlarmsRoute, getAssetsRoute, getUsersRoute} from "../routes";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
export interface PageAssetsConfig {
@@ -191,6 +191,7 @@ export class PageAssets extends Page<AssetsStateKeyed> {
this.addEventListener(OrAssetTreeChangeParentEvent.NAME, (ev) => this._onAssetParentChange(ev.detail));
this.addEventListener(OrAssetTreeToggleExpandEvent.NAME, this._onAssetExpandToggle);
this.addEventListener(OrAssetViewerLoadUserEvent.NAME, this._onLoadUserEvent);
+ this.addEventListener(OrAssetViewerLoadAlarmEvent.NAME,(ev) => this._onLoadAlarmEvent(ev));
}
public connectedCallback() {
@@ -362,4 +363,11 @@ export class PageAssets extends Page<AssetsStateKeyed> {
callHandler: !silent
});
}
+
+ protected _onLoadAlarmEvent(event: OrAssetViewerLoadAlarmEvent, silent: boolean = false) {
+ router.navigate(getAlarmsRoute(event.detail.toString()), {
+ callHooks: !silent,
+ callHandler: !silent
+ });
+ }
}
diff --git a/ui/app/manager/src/pages/page-users.ts b/ui/app/manager/src/pages/page-users.ts
index 9a82cba3f..7c6729929 100644
--- a/ui/app/manager/src/pages/page-users.ts
+++ b/ui/app/manager/src/pages/page-users.ts
@@ -148,7 +148,7 @@ export class PageUsers extends Page<AppStateKeyed> {
.breadcrumb-clickable {
cursor: pointer;
- color: ${unsafeCSS(DefaultColor4)}
+ color: var(--or-app-color4, ${unsafeCSS(DefaultColor4)});
}
.breadcrumb-arrow {
diff --git a/ui/app/manager/src/routes.ts b/ui/app/manager/src/routes.ts
index da6996501..44f4fd953 100644
--- a/ui/app/manager/src/routes.ts
+++ b/ui/app/manager/src/routes.ts
@@ -40,3 +40,11 @@ export function getNewUserRoute(serviceAccount?: boolean) {
}
return route
}
+
+export function getAlarmsRoute(alarmId?: string) {
+ let route = "alarms";
+ if(alarmId) {
+ route += "/" + alarmId;
+ }
+ return route;
+}
diff --git a/ui/component/or-app/src/or-header.ts b/ui/component/or-app/src/or-header.ts
index 019fff371..a09c2a035 100644
--- a/ui/component/or-app/src/or-header.ts
+++ b/ui/component/or-app/src/or-header.ts
@@ -16,9 +16,11 @@ import "@openremote/or-mwc-components/or-mwc-dialog";
import "@openremote/or-icon";
import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
-import {Realm} from "@openremote/model";
+import {Alarm, AlarmEvent, AlarmStatus, PersistenceEvent, Realm} from "@openremote/model";
import {AppStateKeyed, router, updateRealm} from "./index";
import {AnyAction, Store} from "@reduxjs/toolkit";
+import * as Model from "@openremote/model";
+
export {DEFAULT_LANGUAGES, Languages}
@@ -349,6 +351,14 @@ export class OrHeader extends LitElement {
@state()
private _drawerOpened = false;
+ @state()
+ private alarmButton = 'bell-outline';
+
+ @state()
+ private alarmColor = '--or-app-color3, ${unsafeCSS(DefaultColor3)}';
+
+ private _eventSubscriptionId?: string;
+
public _onRealmSelect(realm: string) {
this.store.dispatch(updateRealm(realm));
}
@@ -357,9 +367,41 @@ export class OrHeader extends LitElement {
if (changedProperties.has("config")) {
this.activeMenu = getCurrentMenuItemRef(this.config && this.config.mainMenu && this.config.mainMenu.length > 0 ? this.config.mainMenu[0].href : undefined);
}
+ if (changedProperties.has("realm")) {
+ this._getAlarmButton();
+ }
return super.shouldUpdate(changedProperties);
}
+ firstUpdated() {
+ this._getAlarmButton();
+ }
+
+ connectedCallback() {
+ super.connectedCallback();
+ this._subscribeEvents();
+ }
+
+ disconnectedCallback() {
+ super.disconnectedCallback();
+ this._unsubscribeEvents();
+ }
+
+ protected async _subscribeEvents() {
+ if (manager.events) {
+ this._eventSubscriptionId = await manager.events.subscribe<AlarmEvent>({
+ eventType: "alarm"
+ }, (ev) => this._getAlarmButton());
+ }
+ }
+
+ protected _unsubscribeEvents() {
+ if (this._eventSubscriptionId) {
+ manager.events!.unsubscribe(this._eventSubscriptionId);
+ this._eventSubscriptionId = undefined;
+ }
+ }
+
protected render() {
if (!this.config) {
@@ -386,6 +428,11 @@ export class OrHeader extends LitElement {
</div>
</nav>
<div id="desktop-right">
+ <div id="alarm-btn">
+ <a class="menu-item" @click="${(e: MouseEvent) => router.navigate('alarms')}">
+ <or-icon icon="${this.alarmButton}" style="color:var(${this.alarmColor})"></or-icon>
+ </a>
+ </div>
${this._getRealmMenu((value: string) => this._onRealmSelect(value))}
${secondaryItems ? getContentWithMenuTemplate(html`
<button id="menu-btn-desktop" class="menu-btn" title="Menu"><or-icon icon="dots-vertical"></or-icon></button>
@@ -458,6 +505,16 @@ export class OrHeader extends LitElement {
return realmTemplate;
}
+ protected async _getAlarmButton() {
+ let newAlarms = false;
+ if (manager.hasRole("read:alarms") || manager.hasRole("read:admin")) {
+ const response = await manager.rest.api.AlarmResource.getAlarms({realm: manager.displayRealm, status: Model.AlarmStatus.OPEN});
+ newAlarms = response.data.length > 0;
+ }
+ this.alarmButton = newAlarms ? 'bell-badge-outline' : 'bell-outline';
+ this.alarmColor = newAlarms ? '--or-app-color4, ${unsafeCSS(DefaultColor4)}' : '--or-app-color3, ${unsafeCSS(DefaultColor3)}';
+ }
+
protected _onSecondaryMenuSelect(value: string) {
const headerItem = this.config!.secondaryMenu!.find((item) => item.value === value);
if (headerItem) {
diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.ts
index 6967316f6..722afcff3 100644
--- a/ui/component/or-asset-viewer/src/index.ts
+++ b/ui/component/or-asset-viewer/src/index.ts
@@ -28,6 +28,7 @@ import {
AttributeEvent,
ClientRole,
FileInfo,
+ SentAlarm,
SharedEvent,
UserAssetLink,
WellknownAssets,
@@ -47,7 +48,7 @@ import { progressCircular } from "@openremote/or-mwc-components/style";
import { OrAssetTree } from "@openremote/or-asset-tree";
export interface PanelConfig {
- type: "info" | "setup" | "history" | "group" | "survey" | "survey-results" | "linkedUsers";
+ type: "info" | "setup" | "history" | "group" | "survey" | "survey-results" | "linkedUsers" | "alarm.linkedAlarms";
title?: string;
hide?: boolean;
column?: number;
@@ -134,6 +135,7 @@ interface UserAssetLinkInfo {
interface AssetInfo {
asset: Asset;
userAssetLinks?: UserAssetLinkInfo[];
+ alarmAssetLinks?: SentAlarm[];
childAssets?: Asset[];
viewerConfig: AssetViewerConfig;
modified: boolean;
@@ -268,6 +270,19 @@ export class OrAssetViewerLoadUserEvent extends CustomEvent<string> {
}
}
+export class OrAssetViewerLoadAlarmEvent extends CustomEvent<number> {
+
+ public static readonly NAME = "or-asset-viewer-load-alarm-event";
+
+ constructor(alarmId: number) {
+ super(OrAssetViewerLoadAlarmEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: alarmId
+ });
+ }
+}
+
declare global {
export interface HTMLElementEventMap {
[OrAssetViewerComputeGridEvent.NAME]: OrAssetViewerComputeGridEvent;
@@ -277,6 +292,7 @@ declare global {
[OrAssetViewerEditToggleEvent.NAME]: OrAssetViewerEditToggleEvent;
[OrAssetViewerChangeParentEvent.NAME]: OrAssetViewerChangeParentEvent;
[OrAssetViewerLoadUserEvent.NAME]: OrAssetViewerLoadUserEvent;
+ [OrAssetViewerLoadAlarmEvent.NAME]: OrAssetViewerLoadAlarmEvent;
}
}
@@ -807,6 +823,34 @@ function getPanelContent(id: string, assetInfo: AssetInfo, hostElement: LitEleme
}}">
</or-mwc-table>`;
}
+
+ if (panelConfig.type === "alarm.linkedAlarms") {
+
+ const hasReadAlarmsRole = manager.hasRole(ClientRole.READ_ALARMS);
+ const linkedAlarms = assetInfo.alarmAssetLinks
+
+ if (!hasReadAlarmsRole) {
+ return;
+ }
+
+ if (!linkedAlarms || linkedAlarms.length === 0) {
+ return;
+ }
+
+ const cols = [i18next.t("alarm.title"), i18next.t("alarm.severity"), i18next.t("status")];
+ const rows = linkedAlarms.sort().map(linkedAlarm => {
+ return [
+ linkedAlarm.title,
+ linkedAlarm.severity,
+ linkedAlarm.status
+ ];
+ });
+ return html`<or-mwc-table .rows="${rows}" .config="${{stickyFirstColumn:false}}" .columns="${cols}"
+ @or-mwc-table-row-click="${(ev: OrMwcTableRowClickEvent) => {
+ hostElement.dispatchEvent(new OrAssetViewerLoadAlarmEvent(linkedAlarms[ev.detail.index].id!));
+ }}">
+ </or-mwc-table>`;
+ }
}
export function getAttributeTemplate(asset: Asset, attribute: Attribute<any>, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfig, itemConfig: InfoPanelItemConfig): TemplateResult {
@@ -981,6 +1025,21 @@ async function getLinkedUsers(asset: Asset): Promise<UserAssetLinkInfo[]> {
}
}
+async function getLinkedAlarms(asset: Asset): Promise<SentAlarm[]> {
+ try {
+ return await manager.rest.api.AlarmResource.getAlarms(
+ {realm: manager.displayRealm, assetId: asset.id}
+ ).then((response) => {
+ const alarmAssetLinks = response.data;
+ return Promise.all(alarmAssetLinks);
+ });
+
+ } catch (e) {
+ console.log("Failed to get child assets: " + e);
+ return [];
+ }
+}
+
export async function saveAsset(asset: Asset): Promise<SaveResult> {
const isUpdate = !!asset.id && asset.version !== undefined;
@@ -1081,6 +1140,11 @@ export const DEFAULT_VIEWER_CONFIG: AssetViewerConfig = {
{
type: "linkedUsers",
column: 1
+ },
+ {
+ type: "alarm.linkedAlarms",
+ column: 1,
+ hideOnMobile: true
}
]
};
@@ -1224,6 +1288,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
}
const links = await getLinkedUsers(asset);
+ const alarms = await getLinkedAlarms(asset);
// Check this asset is still the correct one
if (!this.ids || this.ids.length != 1 || this.ids[0] !== asset.id) {
@@ -1247,6 +1312,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
viewerConfig: viewerConfig,
childAssets: childAssets,
userAssetLinks: links,
+ alarmAssetLinks: alarms,
attributeTemplateMap: {}
};
}
diff --git a/ui/component/or-mwc-components/src/or-mwc-table.ts b/ui/component/or-mwc-components/src/or-mwc-table.ts
index 3f35b4c05..93be8a9d7 100644
--- a/ui/component/or-mwc-components/src/or-mwc-table.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-table.ts
@@ -1,14 +1,14 @@
-import {css, html, LitElement, TemplateResult, unsafeCSS, PropertyValues} from "lit";
+import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";
import {customElement, property, state} from "lit/decorators.js";
import {classMap} from "lit/directives/class-map.js";
import {until} from 'lit/directives/until.js';
import {MDCDataTable} from "@material/data-table";
-import {MDCCheckbox} from "@material/checkbox";
import {when} from 'lit/directives/when.js';
-import {DefaultColor3, DefaultColor2, DefaultColor1, manager} from "@openremote/core";
+import {DefaultColor3, DefaultColor2, DefaultColor1} from "@openremote/core";
import {i18next} from "@openremote/or-translate";
import {InputType, OrInputChangedEvent} from "./or-mwc-input";
import { styleMap } from "lit/directives/style-map.js";
+import moment from "moment";
const dataTableStyle = require("@material/data-table/dist/mdc.data-table.css");
@@ -180,8 +180,10 @@ export interface TableColumn {
isSortable?: boolean
}
+export type TableContent = string | number | Date | TemplateResult
+
export interface TableRow {
- content?: (string | number | TemplateResult)[]
+ content?: TableContent[]
clickable?: boolean
}
@@ -189,6 +191,10 @@ export interface OrMwcTableRowClickDetail {
index: number
}
+export interface OrMwcTableRowSelectDetail extends OrMwcTableRowClickDetail {
+ state: boolean
+}
+
export class OrMwcTableRowClickEvent extends CustomEvent<OrMwcTableRowClickDetail> {
public static readonly NAME = "or-mwc-table-row-click";
@@ -204,6 +210,22 @@ export class OrMwcTableRowClickEvent extends CustomEvent<OrMwcTableRowClickDetai
}
}
+export class OrMwcTableRowSelectEvent extends CustomEvent<OrMwcTableRowSelectDetail> {
+
+ public static readonly NAME = "or-mwc-table-row-select";
+
+ constructor(index: number, state: boolean) {
+ super(OrMwcTableRowSelectEvent.NAME, {
+ detail: {
+ index: index,
+ state: state
+ },
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
@customElement("or-mwc-table")
export class OrMwcTable extends LitElement {
@@ -240,13 +262,13 @@ export class OrMwcTable extends LitElement {
protected paginationIndex: number = 0;
@property({type: Number})
- protected paginationSize: number = 10;
+ public paginationSize: number = 10;
@state()
protected _dataTable?: MDCDataTable;
@property({ type: String })
- protected sortDirection?: 'ASC' | 'DESC' = 'ASC';
+ protected sortDirection: 'ASC' | 'DESC' = 'ASC';
@property({type: Number})
protected sortIndex?: number = -1;
@@ -254,11 +276,6 @@ export class OrMwcTable extends LitElement {
@property({type: Array})
public selectedRows?: TableRow[] | string[][] | any[] = [];
- @property()
- protected indeterminate?: boolean = false;
-
- @property()
- protected allSelected?: boolean = false;
/* ------------------- */
@@ -280,8 +297,6 @@ export class OrMwcTable extends LitElement {
// Reset selected rows properties
this.selectedRows = [];
- this.indeterminate = false;
- this.allSelected = false;
}
}
@@ -306,24 +321,41 @@ export class OrMwcTable extends LitElement {
<tr class="mdc-data-table__header-row">
${this.columns.map((column: TableColumn | string, index: number) => {
const styles = {
- maxWidth: tableWidth ? `${tableWidth / (this.columns!.length / 2)}px` : undefined
+ width: this.getColumnWidth(index, this.columns, tableWidth),
+ maxWidth: this.getMaxColumnWidth(index, this.columns, tableWidth),
} as any;
- if(index == 0 && this.config.multiSelect){
- return html`
- <th class="mdc-data-table__header-cell mdc-data-table__header-cell--checkbox"
- role="columnheader" scope="col">
- <div class="">
- <or-mwc-input type="${InputType.CHECKBOX}" id="checkbox-${index}"
- class="${classMap({'mdi-checkbox-intermediate': this.indeterminate!})}"
- .indeterminate="${this.indeterminate}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCheckChanged(ev.detail.value, "all")}" .value="${this.allSelected}">
+ if(index === 0 && this.config.multiSelect){
+ const allSelected = this.rows && this.rows.length > 0 && this.selectedRows?.length === this.rows?.length;
+ const indeterminate = !allSelected && this.selectedRows && this.selectedRows.length > 0;
+ return html`
+ <th class="mdc-data-table__header-cell mdc-data-table__header-cell--checkbox"
+ role="columnheader" scope="col">
+ <or-mwc-input type="${InputType.CHECKBOX}" id="checkbox"
+ .indeterminate="${indeterminate}" .value="${allSelected}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCheckChanged(ev, ev.detail.value, "all")}">
</or-mwc-input>
- </div>
- </th>
- `
+ </th>
+ ${(typeof column === "string") ? html`
+ <th class="mdc-data-table__header-cell ${this.config.multiSelect ? "mdc-data-table__header-cell" : ''}" id="column-${index + 1}"
+ role="columnheader" scope="col"
+ title="${column}">
+ column
+ </th>
+ ` : html`
+ <th class="mdc-data-table__header-cell ${classMap({
+ 'mdc-data-table__cell--numeric': !!column.isNumeric,
+ 'hide-mobile': !!column.hideMobile,
+ 'mdc-data-table__header-cell--with-sort': !!column.isSortable,
+ })}"
+ role="columnheader" scope="col" title="${column.title}" data-column-id="${column.title}"
+ @click="${(ev: MouseEvent) => column.isSortable! ? this.onColumnSort(ev, index, this.sortDirection!) : ''}">
+ ${(!column.isSortable ? column.title : until(this.getSortHeader(index, column.title!, this.sortDirection!), html`${i18next.t('loading')}`))}
+ </th>
+ `
+ }`
}
return (typeof column == "string") ? html`
- <th class="mdc-data-table__header-cell ${!!this.config.multiSelect ? "mdc-data-table__header-cell mdc-data-table__header-cell--checkbox" : ''}" id="column-${index+1}" role="columnheader" scope="col"
+ <th class="mdc-data-table__header-cell ${!!this.config.multiSelect ? "mdc-data-table__header-cell" : ''}" id="column-${index+1}" role="columnheader" scope="col"
title="${column}">
${column}
</th>
@@ -335,7 +367,7 @@ export class OrMwcTable extends LitElement {
})}"
style="${styleMap(styles)}"
role="columnheader" scope="col" title="${column.title}" data-column-id="${column.title}"
- @click="${(ev: MouseEvent) => !!column.isSortable ? this.sortRows(ev, index, this.sortDirection!) : ''}">
+ @click="${(ev: MouseEvent) => column.isSortable! ? this.onColumnSort(ev, index, this.sortDirection ? this.sortDirection : 'ASC') : ''}">
${(!column.isSortable ? column.title : until(this.getSortHeader(index, column.title!, this.sortDirection!, !!column.isNumeric), html`${i18next.t('loading')}`))}
</th>
`
@@ -362,35 +394,34 @@ export class OrMwcTable extends LitElement {
return this.rows ? (this.rows as any[])
.filter((row, index) => !this.config.pagination?.enable || (index >= (this.paginationIndex * this.paginationSize)) && (index < (this.paginationIndex * this.paginationSize + this.paginationSize)))
.map((item: TableRow | string[]) => {
- const content: (string | number | TemplateResult)[] | undefined = (Array.isArray(item) ? item : (item as TableRow).content);
- const styles = {
- maxWidth: tableWidth ? `${tableWidth / (this.columns!.length / 2)}px` : undefined
- } as any;
+ const content: TableContent[] | undefined = (Array.isArray(item) ? item : (item as TableRow).content);
return html`
<tr class="mdc-data-table__row" @click="${(ev: MouseEvent) => this.onRowClick(ev, item)}">
- ${content?.map((cell: string | number | TemplateResult, index: number) => {
+ ${content?.map((cell: TableContent, index: number) => {
const classes = {
"mdc-data-table__cell": true,
"mdc-data-table__cell--numeric": typeof cell === "number",
"mdc-data-table__cell--clickable": (!Array.isArray(item) && (item as TableRow).clickable)!,
"hide-mobile": (this.columns && typeof this.columns[index] != "string" && (this.columns[index] as TableColumn).hideMobile)!
}
- if(index == 0 && this.config.multiSelect){
- return html`
+ const styles = {
+ maxWidth: this.getMaxColumnWidth(index, this.columns, tableWidth),
+ } as any;
+ return html`
+ ${when(index === 0 && this.config.multiSelect, () => html`
<td class="mdc-data-table__cell mdc-data-table__cell--checkbox" >
<div class="">
<or-mwc-input type="${InputType.CHECKBOX}" id="checkbox-${index}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCheckChanged(ev.detail.value,"single",item)}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCheckChanged(ev,ev.detail.value,"single",item)}"
.value="${this.selectedRows?.includes(item)}"
></or-mwc-input>
</div>
- </td> `
- }
- return html`
- <td class="${classMap(classes)}" title="${cell}" style="${styleMap(styles)}">
- <span>${cell}</span>
+ </td>
+ `)}
+ <td class="${classMap(classes)}" title="${typeof cell === 'object' ? "" : cell}" style="${styleMap(styles)}">
+ ${until(this.getTableContent(cell))}
</td>
- `
+ `;
})}
</tr>
`
@@ -428,6 +459,23 @@ export class OrMwcTable extends LitElement {
`;
}
+ /**
+ * Function that is responsible for formatting the table content.
+ * For example; dates should be formatted differently than strings, numbers and HTML templates.
+ */
+ protected getTableContent(content: TableContent): TemplateResult | string {
+ if (typeof content === 'string' || typeof content === 'number') {
+ return content as string;
+ } else if (content instanceof Date) {
+ return moment(content).format("lll");
+ } else {
+ return content;
+ }
+ }
+
+ /**
+ * "When user clicks on a row", it dispatches an {@link OrMwcTableRowClickEvent} to the parent component / listeners.
+ */
protected onRowClick(ev: MouseEvent, item: TableRow | string[]) {
if(this.config.multiSelect) {
const elem = ev.target as HTMLElement;
@@ -438,104 +486,163 @@ export class OrMwcTable extends LitElement {
this.dispatchEvent(new OrMwcTableRowClickEvent((this.rows as any[]).indexOf(item)))
}
-
- async getSortHeader(index: number, title: string, sortDirection: 'ASC' | 'DESC', arrowOnLeft = false): Promise<TemplateResult> {
- this.sortIndex === -1 ? this.sortIndex = index : '';
- return html`
- <div class="mdc-data-table__header-cell-wrapper ${arrowOnLeft ? 'sortable-reverse' : 'sortable'}">
- <div class="mdc-data-table__header-cell-label">
- ${title}
- </div>
- <button class="mdc-icon-button material-icons ${arrowOnLeft ? 'sort-button-reverse' : 'sort-button'} ${this.sortIndex === index ? '' : 'hidden'}"
- aria-label="Sort by ${title}" aria-describedby="${title}-status-label" aria-hidden="${!(this.sortIndex === index)}">
- <or-icon icon="${ sortDirection == 'ASC' ? "arrow-up" : "arrow-down"}"></or-icon>
- </button>
- <div class="mdc-data-table__sort-status-label" aria-hidden="true" id="${title}-status-label">
- </div>
- </div>
- `;
+ /**
+ * "When user clicks on a checkbox" when multiselect is enabled,
+ * it dispatches an {@link OrMwcTableRowSelectEvent} to the parent component / listeners.
+ */
+ protected onCheckChanged(event: Event, checked: boolean, type: "all" | "single", item?: any) {
+ event.stopPropagation();
+ if (type === "all") {
+ if (checked) {
+ this.selectedRows = this.rows;
+ } else {
+ this.selectedRows = [];
+ }
+ // Dispatch events to parent component
+ this.rows?.forEach((_, index) => this.dispatchEvent(new OrMwcTableRowSelectEvent(index, checked)));
+
+ } else {
+ if (checked) {
+ if (this.selectedRows === undefined) {
+ this.selectedRows = [item];
+ } else if (this.selectedRows.indexOf(item) === -1) {
+ this.selectedRows.push(item);
+ this.requestUpdate('selectedRows');
+ }
+ } else {
+ this.selectedRows = this.selectedRows?.filter((e: TableRow) => e !== item);
+ }
+ // Dispatch events to parent component
+ const index = this.rows?.indexOf(item);
+ if (index !== undefined && index > -1) {
+ this.dispatchEvent(new OrMwcTableRowSelectEvent(index, checked));
+ }
+ }
}
- async sortRows(ev: MouseEvent, index: number, sortDirection: 'ASC' | 'DESC'){
- if(this.config.multiSelect) {
+ /**
+ * Event handling function for when users try to sort the rows within a column.
+ */
+ async onColumnSort(ev: MouseEvent, index: number, sortDirection: 'ASC' | 'DESC') {
+ if (this.config.multiSelect) {
const elem = ev.target as HTMLElement;
- if(elem.nodeName === "OR-MWC-INPUT" && elem.id.includes('checkbox')) {
+ if (elem.nodeName === "OR-MWC-INPUT" && elem.id.includes('checkbox')) {
return; // if checkbox is clicked, sort should not trigger.
}
}
- sortDirection == 'ASC' ? this.sortDirection = 'DESC' : this.sortDirection = 'ASC';
- sortDirection = this.sortDirection;
+ const newDirection = (sortDirection == 'ASC') ? 'DESC' : 'ASC';
+ this.sortDirection = newDirection;
this.sortIndex = index;
- if(this.rows!){
- if('content' in this.rows[0]) {
- (this.rows as TableRow[]).sort((a : TableRow, b : TableRow) => {
- return this.customSort(a.content, b.content, index, sortDirection);
- });
+ if (this.rows && this.rows.length > 0) {
- } else {
- (this.rows as string[][]).sort((a : string[], b : string[]) => {
- return this.customSort(a, b, index, sortDirection);
+ // If string array of rows,
+ if (Array.isArray(this.rows[0])) {
+ (this.rows as string[][]).sort((a: string[], b: string[]) => {
+ return this.sortPrimitiveRows(a, b, index, newDirection);
+ });
+ }
+ // Else if row is TableRow
+ else {
+ (this.rows as TableRow[]).sort((a: TableRow, b: TableRow) => {
+ return this.sortObjectRows(a, b, index, newDirection);
});
}
- return;
}
- return;
}
- protected customSort(a: any, b: any, index: number, sortDirection: 'ASC' | 'DESC'): number{
- if (!a[index] && !b[index]) {
+ /**
+ * Sorts either numbers incrementally or strings alphabetically depending on the sorting direction.
+ */
+ protected sortPrimitiveRows(rowA: string[] | number[], rowB: string[] | number[], cIndex: number, sortDirection: 'ASC' | 'DESC'): number {
+ const cellA = rowA[cIndex];
+ const cellB = rowB[cIndex];
+ if (!cellA && !cellB) {
return 0;
+ } else if (!cellA || cellA.toString().length === 0) {
+ return sortDirection === 'DESC' ? 1 : -1;
+ } else if (!cellB || cellB.toString().length === 0) {
+ return sortDirection === 'DESC' ? -1 : 1;
+ } else {
+ if (typeof cellA === 'string' && typeof cellB === 'string') {
+ if (sortDirection === 'DESC') {
+ return (cellB as string).localeCompare(cellA as string, 'en', {numeric: true});
+ } else {
+ return (cellA as string).localeCompare(cellB as string, 'en', {numeric: true});
+ }
+ } else if (typeof cellA === 'number' && typeof cellB === 'number') {
+ if (sortDirection === 'DESC') {
+ return cellA > cellB ? -1 : 1;
+ } else {
+ return cellA > cellB ? 1 : -1;
+ }
+ } else {
+ console.warn("sortPrimitiveRows() was called using neither a number nor a string.")
+ return 1;
+ }
}
+ }
- if (!a[index]) {
- return 1;
- }
+ /**
+ * Function that handles several sorts of table content; from dates to HTML templates.
+ * */
+ protected sortObjectRows(rowA: TableRow, rowB: TableRow, cIndex: number, sortDirection: 'ASC' | 'DESC'): number {
+ const cellA = rowA.content?.[cIndex];
+ const cellB = rowB.content?.[cIndex];
+ const isSortable = (content: any) => (typeof content === 'string' || typeof content === 'number');
+ const isTemplate = (content: any) => (content.strings !== undefined && content.values !== undefined);
- if (!b[index]) {
- return -1;
- }
- if(typeof a[index] === 'string' && typeof b[index] === 'string'){
- return sortDirection == 'DESC' ? b[index].localeCompare(a[index], 'en', {numeric: true}) : a[index].localeCompare(b[index], 'en', {numeric: true});
- }
- else {
- return sortDirection == 'DESC' ? (a[index] > b[index] ? -1 : 1) : (a[index] < b[index] ? -1 : 1);
+ if (!cellA || !cellB || isSortable(cellA) || isSortable(cellB)) {
+ return this.sortPrimitiveRows([cellA as string], [cellB as string], 0, sortDirection);
+
+ } else if (cellA instanceof Date && cellB instanceof Date) {
+ return this.sortDateRows(cellA, cellB, 0, sortDirection);
+
+ } else if (isTemplate(cellA) || isTemplate(cellB)) {
+ return this.sortTemplateRows(cellA, cellB, 0, sortDirection);
}
+ return 1;
}
- protected onCheckChanged(checked: boolean, type: "all" | "single", item?: any) {
- let rowCount = (this.config.pagination?.enable && this.rows!.length > this.paginationSize ? this.paginationSize : this.rows!.length);
- if (type === "all") {
- if(checked) {
- this.selectedRows! = this.rows ? (this.rows as any[])
- .filter((row, index) => (index >= (this.paginationIndex * this.paginationSize)) && (index < (this.paginationIndex * this.paginationSize + this.paginationSize))) : [];
- this.indeterminate = false;
- this.allSelected = true;
-
- }
- else {
- this.selectedRows! = [];
- this.allSelected = false;
- this.indeterminate = false;
- }
+ protected sortDateRows(dateA: Date, dateB: Date, cIndex: number, sortDirection: 'ASC' | 'DESC'): number {
+ if (sortDirection === 'DESC') {
+ return dateA > dateB ? -1 : 1;
+ } else {
+ return dateA > dateB ? 1 : -1;
}
- else {
- if(checked) {
- if(this.selectedRows!.indexOf(item) === -1) {
- this.selectedRows!.push(item);
- this.indeterminate = (this.selectedRows!.length < (this.config.pagination?.enable ? rowCount : this.rows!.length) && this.selectedRows!.length > 0);
- this.allSelected = (this.selectedRows!.length === (this.config.pagination?.enable ? rowCount : this.rows!.length) && this.selectedRows!.length > 0);
- this.requestUpdate("selectedRows");
- }
- }
- else {
- this.selectedRows! = this.selectedRows!.filter((e: TableRow) => e !== item);
- }
+ }
- this.indeterminate = (this.selectedRows!.length < (this.config.pagination?.enable ? rowCount : this.rows!.length) && this.selectedRows!.length > 0);
- this.allSelected = (this.selectedRows!.length === (this.config.pagination?.enable ? rowCount : this.rows!.length) && this.selectedRows!.length > 0);
+ /**
+ * Uses the {@link TemplateResult} content to identify and analyze the content.
+ * See the documentation here; https://lit.dev/docs/v2/api/templates/#TemplateResult
+ * Sometimes it cannot analyze the HTML; if so, it will retain the same order.
+ */
+ protected sortTemplateRows(cellA: any, cellB: any, cIndex: number, sortDirection: 'ASC' | 'DESC'): number {
+ const valueA: string | undefined = (cellA.values as any[]).filter(v => typeof v === 'string' || typeof v === 'number').map(v => v.toString())?.[0];
+ const valueB: string | undefined = (cellB.values as any[]).filter(v => typeof v === 'string' || typeof v === 'number').map(v => v.toString())?.[0];
+ if (valueA !== undefined && valueB !== undefined) {
+ return this.sortPrimitiveRows([valueA], [valueB], 0, sortDirection);
+ } else {
+ return 1;
}
}
+ // HTML for the sort header, that adds click functionality and a up/down arrow.
+ async getSortHeader(index: number, title: string, sortDirection: 'ASC' | 'DESC', arrowOnLeft = false): Promise<TemplateResult> {
+ this.sortIndex === -1 ? this.sortIndex = index : '';
+ return html`
+ <div class="mdc-data-table__header-cell-wrapper ${arrowOnLeft ? 'sortable-reverse' : 'sortable'}">
+ <div class="mdc-data-table__header-cell-label">
+ ${title}
+ </div>
+ <button class="mdc-icon-button material-icons ${arrowOnLeft ? 'sort-button-reverse' : 'sort-button'} ${this.sortIndex === index ? '' : 'hidden'}"
+ aria-label="Sort by ${title}" aria-describedby="${title}-status-label" aria-hidden="${!(this.sortIndex === index)}">
+ <or-icon icon="${sortDirection == 'ASC' ? "arrow-up" : "arrow-down"}"></or-icon>
+ </button>
+ <div class="mdc-data-table__sort-status-label" aria-hidden="true" id="${title}-status-label">
+ </div>
+ </div>
+ `;
+ }
// HTML for the controls on the bottom of the table.
@@ -595,4 +702,12 @@ export class OrMwcTable extends LitElement {
return this._dataTable ? (this._dataTable.root as HTMLElement) : (this.shadowRoot!.querySelector('.mdc-data-table') as HTMLElement);
}
+ protected getColumnWidth(index: number, columns?: string[] | TableColumn[], tableWidthPx?: number): string | undefined {
+ return undefined;
+ }
+
+ protected getMaxColumnWidth(index: number, columns?: string[] | TableColumn[], tableWidthPx?: number): string | undefined {
+ return tableWidthPx ? (`${tableWidthPx / (columns?.length || 2)}px`) : undefined;
+ }
+
}
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index b74845996..524007776 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -53,6 +53,7 @@ export const enum ConditionType {
export const enum ActionType {
WAIT = "wait",
+ ALARM = "alarm",
EMAIL = "email",
PUSH_NOTIFICATION = "push",
ATTRIBUTE = "attribute",
diff --git a/ui/component/or-rules/src/json-viewer/forms/or-rule-form-alarm.ts b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-alarm.ts
new file mode 100644
index 000000000..54b52486b
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/forms/or-rule-form-alarm.ts
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2024, 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/>.
+ */
+import {html, LitElement, css} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {
+ RuleActionAlarm,
+ Alarm,
+ User
+} from "@openremote/model";
+import { OrRulesJsonRuleChangedEvent } from "../or-rule-json-viewer";
+import {i18next} from "@openremote/or-translate";
+
+@customElement("or-rule-form-alarm")
+export class OrRuleFormAlarm extends LitElement {
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionAlarm;
+
+ @property()
+ public users: User[] = [];
+
+ static get styles() {
+ return css`
+ or-mwc-input {
+ margin-bottom: 20px;
+ min-width: 420px;
+ width: 100%;
+ }
+ `
+ }
+
+ protected render() {
+ const alarm: Alarm | undefined = this.action.alarm as Alarm;
+ const options: {value: string | undefined | null, label: string | undefined}[] = this.users.filter((u) => u.username != 'manager-keycloak').map((u) => {
+ return { value: u.id, label: u.username };
+ });
+ options.unshift({value: null, label: i18next.t("none")})
+
+ return html`
+ <form style="display:grid">
+ <or-mwc-input value="${alarm && alarm.title ? alarm.title : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionAlarmName(e.detail.value, "title")}" .label="title" type="${InputType.TEXT}" required placeholder=" "></or-mwc-input>
+ <or-mwc-input value="${alarm && alarm.content ? alarm.content : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionAlarmName(e.detail.value, "content")}" .label=content" type="${InputType.TEXTAREA}" required placeholder=" " ></or-mwc-input>
+ <or-mwc-input .label="${i18next.t("alarm.assignee")}"
+ .type="${InputType.SELECT}"
+ .options="${options.map((obj) => obj.label)}"
+ .value="${this.action.assigneeId ? options.filter((obj) => obj.value === this.action.assigneeId).map((obj) => obj.label)[0] : ""}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ this.action.assigneeId = options.filter((obj) => obj.label === e.detail.value).map((obj) => obj.value)[0];
+ this.setActionAlarmName(e.detail.value, undefined);
+ }}"
+ ></or-mwc-input>
+ </form>
+ `
+ }
+
+ protected setActionAlarmName(value: string | undefined, key?: string) {
+ if(key && this.action.alarm){
+ const alarm:any = this.action.alarm;
+ alarm[key] = value;
+ this.action.alarm = {...alarm};
+ }
+ if(!key) {
+ this.action.assigneeId = this.users.filter((obj) => obj.username === value).map((obj) => obj.id)[0];
+ }
+
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+}
diff --git a/ui/component/or-rules/src/json-viewer/modals/or-rule-alarm-modal.ts b/ui/component/or-rules/src/json-viewer/modals/or-rule-alarm-modal.ts
new file mode 100644
index 000000000..a41a8ceb4
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/modals/or-rule-alarm-modal.ts
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2024, 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/>.
+ */
+import {html, LitElement, PropertyValues} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {
+ RuleActionAlarm,
+ AssetQuery,
+ AlarmSeverity
+} from "@openremote/model";
+
+import "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import i18next from "i18next";
+import {translate} from "@openremote/or-translate";
+
+import {DialogAction, OrMwcDialog, OrMwcDialogOpenedEvent} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrRulesJsonRuleChangedEvent} from "../or-rule-json-viewer";
+const checkValidity = (form:HTMLElement | null, dialog:OrMwcDialog) => {
+ if(form) {
+ const inputs = form.querySelectorAll('or-mwc-input');
+ const elements = Array.prototype.slice.call(inputs);
+
+ const valid = elements.every((element) => {
+ if(element.shadowRoot) {
+ const input = element.shadowRoot.querySelector('input, textarea') as any
+
+ if(element.type === InputType.SELECT) {
+ return true;
+ }
+
+ if(input && input.checkValidity()) {
+ return true
+ } else {
+ element._mdcComponent.valid = false;
+ element._mdcComponent.helperTextContent = 'required';
+
+ return false;
+ }
+ } else {
+ return false;
+ }
+ })
+ if(valid) {
+ dialog.close();
+ }
+ }
+}
+@customElement("or-rule-alarm-modal")
+export class OrRuleAlarmModal extends translate(i18next)(LitElement) {
+
+ @property({type: Object, attribute: false})
+ public action!: RuleActionAlarm;
+
+ @property({type: String})
+ public title = "settings";
+
+ @property({type: Object})
+ public query?: AssetQuery;
+
+ constructor() {
+ super();
+ this.addEventListener(OrMwcDialogOpenedEvent.NAME, this.initDialog)
+ }
+
+ initDialog() {
+ const modal = this.shadowRoot!.getElementById('alarm-modal');
+ if(!modal) return;
+ }
+
+ renderDialogHTML(action:RuleActionAlarm) {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("alarm-modal") as OrMwcDialog;
+ if(!this.shadowRoot) return
+
+ const slot:HTMLSlotElement|null = this.shadowRoot.querySelector('.alarm-form-slot');
+ if (dialog && slot) {
+ let container = document.createElement("div");
+ slot.assignedNodes({flatten: true}).forEach((child) => {
+ if (child instanceof HTMLElement) {
+ container.appendChild(child);
+ }
+ });
+ dialog.content = html`${container}`;
+ dialog.dismissAction = null;
+ this.requestUpdate();
+ }
+ }
+
+ firstUpdated(changedProperties: PropertyValues){
+ if(changedProperties.has("action")){
+ this.renderDialogHTML(this.action);
+ }
+ }
+
+ checkForm() {
+ const dialog: OrMwcDialog = this.shadowRoot!.host as OrMwcDialog;
+
+ if (this.shadowRoot) {
+ const alarmConfig = this.shadowRoot.querySelector('or-rule-form-alarm');
+
+ if(alarmConfig && alarmConfig.shadowRoot) {
+ const form = alarmConfig.shadowRoot.querySelector('form');
+ return checkValidity(form, dialog);
+ }
+ }
+ }
+
+ protected render() {
+ if(!this.action) return html``;
+
+ const alarmPickerModalActions: DialogAction[] = [
+ {
+ actionName: "cancel",
+ content: html`<or-mwc-input class="button" .type="${InputType.BUTTON}" .label="${i18next.t("cancel")}"></or-mwc-input>`,
+ action: (dialog) => {
+
+ }
+ },
+ {
+ actionName: "",
+ content: html`<or-mwc-input class="button" .type="${InputType.BUTTON}" .label="${i18next.t("ok")}" @or-mwc-input-changed="${this.checkForm}"></or-mwc-input>`
+ }
+ ];
+
+
+ const alarmPickerModalOpen = () => {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("alarm-modal") as OrMwcDialog;
+ if (dialog) {
+ dialog.open();
+ }
+ };
+
+ return html`
+ <or-mwc-input style="width: 200px" .type="${InputType.SELECT}" .value="${this.action.alarm?.severity}" .label="${i18next.t("alarm.severity")}" .options="${[AlarmSeverity.LOW, AlarmSeverity.MEDIUM, AlarmSeverity.HIGH]}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionAlarmSeverity(e.detail.value)}"></or-mwc-input>
+ <or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t("settings")}" @or-mwc-input-changed="${alarmPickerModalOpen}"></or-mwc-input>
+ <or-mwc-dialog id="alarm-modal" heading="${this.title}" .actions="${alarmPickerModalActions}"></or-mwc-dialog>
+ <slot class="alarm-form-slot"></slot>
+ `
+ }
+
+ protected setActionAlarmSeverity(value: string | undefined) {
+ if(value && this.action.alarm){
+ const alarm:any = this.action.alarm;
+ alarm.severity = value;
+ this.action.alarm = {...alarm};
+ }
+
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-alarm.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-alarm.ts
new file mode 100644
index 000000000..ff9c87921
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-alarm.ts
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2024, 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/>.
+ */
+import { css, html, LitElement, TemplateResult } from "lit";
+import { customElement, property } from "lit/decorators.js";
+import { ActionType, RulesConfig } from "../index";
+import {
+ JsonRule,
+ RuleActionAlarm,
+ User,
+ UserQuery,
+} from "@openremote/model";
+import "./modals/or-rule-alarm-modal";
+import "./forms/or-rule-form-alarm";
+import manager from "@openremote/core";
+
+
+// language=CSS
+const style = css`
+ :host {
+ display: flex;
+ align-items: center;
+ }
+ :host > * {
+ margin: 0 3px 6px;
+ }
+ .min-width {
+ min-width: 200px;
+ }
+`;
+
+@customElement("or-rule-action-alarm")
+export class OrRuleActionAlarm extends LitElement {
+
+ static get styles() {
+ return style;
+ }
+
+ @property({ type: Object, attribute: false })
+ public rule!: JsonRule;
+
+ @property({ type: Object, attribute: false })
+ public action!: RuleActionAlarm;
+
+ @property({ type: String, attribute: false })
+ public actionType!: ActionType;
+
+ public readonly?: boolean;
+
+ @property({ type: Object })
+ public config?: RulesConfig;
+
+ protected _loadedUsers: User[] = [];
+
+ async connectedCallback(): Promise<void> {
+ await this.loadUsers();
+ super.connectedCallback();
+ }
+
+ protected async loadUsers() {
+ const usersResponse = await manager.rest.api.UserResource.query({
+ realmPredicate: { name: manager.displayRealm },
+ } as UserQuery);
+
+ if (usersResponse.status !== 200) {
+ return;
+ }
+
+ this._loadedUsers = usersResponse.data.filter((user) => user.enabled && !user.serviceAccount);
+ }
+
+
+ protected render() {
+ if (!this.action.alarm || !this.action.alarm.title) {
+ return html``;
+ }
+
+ const alarm = this.action.alarm;
+
+ let modalTemplate: TemplateResult | string = ``;
+
+ if (alarm) {
+ modalTemplate = html`
+ <div style="display: flex;">
+ <or-rule-alarm-modal title="alarm." .action="${this.action}">
+ <or-rule-form-alarm .users="${this._loadedUsers}" .action="${this.action}"></or-rule-form-alarm>
+ </or-rule-alarm-modal>
+ </div>
+ `;
+ }
+
+ return html`${modalTemplate}`;
+ }
+}
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.ts
index a02dd4f54..8297555cc 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
@@ -350,6 +350,9 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
case "notification":
// TODO: validate notification rule action
break;
+ case "alarm":
+ // TODO: validate alarm rule action
+ break;
case "webhook":
if(!action.webhook?.url || !action.webhook.httpMethod) {
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.ts
index 0df306b2b..87e87166e 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
@@ -5,11 +5,14 @@ import "./or-rule-asset-query";
import {ActionType, getAssetTypeFromQuery, RulesConfig} from "../index";
import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
import {
+ AlarmSeverity,
+ AlarmStatus,
Asset,
AssetModelUtil,
AssetTypeInfo,
HTTPMethod,
JsonRule,
+ RuleActionAlarm,
RuleActionNotification,
RuleActionUnion,
RuleActionWebhook,
@@ -24,15 +27,18 @@ import {Util} from "@openremote/core";
import "./or-rule-action-attribute";
import "./or-rule-action-notification";
import "./or-rule-action-webhook";
+import "./or-rule-action-alarm";
import {translate} from "@openremote/or-translate";
const NOTIFICATION_COLOR = "4B87EA";
const WAIT_COLOR = "EACC54";
+const ALARM_COLOR = "FC2D2D";
function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]): (ListItem | null)[] {
let addAssetTypes = true;
let addWait = true;
+ let addAlarm = true;
let addNotification = true;
let addPushNotification = true;
let addWebhook = true;
@@ -40,6 +46,7 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):
if (config && config.controls && config.controls.allowedActionTypes) {
addAssetTypes = config.controls.allowedActionTypes.indexOf(ActionType.ATTRIBUTE) >= 0;
addWait = config.controls.allowedActionTypes.indexOf(ActionType.WAIT) >= 0;
+ addAlarm = config.controls.allowedActionTypes.indexOf(ActionType.ALARM) >= 0;
addNotification = config.controls.allowedActionTypes.indexOf(ActionType.EMAIL) >= 0;
addPushNotification = config.controls.allowedActionTypes.indexOf(ActionType.PUSH_NOTIFICATION) >= 0;
addWebhook = config.controls.allowedActionTypes.indexOf(ActionType.WEBHOOK) >= 0;
@@ -94,6 +101,15 @@ function getActionTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInfo[]):
} as ListItem);
}
+ if (addAlarm) {
+ menu.push({
+ text: i18next.t("alarm."),
+ icon: "bell-outline",
+ value: ActionType.ALARM,
+ styleMap: {"--or-icon-fill": "#" + ALARM_COLOR}
+ } as ListItem);
+ }
+
if (addWebhook) {
menu.push({
text: i18next.t("webhook"),
@@ -315,6 +331,10 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
buttonColor = NOTIFICATION_COLOR;
}
break;
+ case ActionType.ALARM:
+ buttonIcon = "bell-outline";
+ buttonColor = ALARM_COLOR;
+ break;
default:
const ad = AssetModelUtil.getAssetDescriptor(type);
buttonIcon = AssetModelUtil.getAssetDescriptorIcon(ad);
@@ -356,6 +376,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case ActionType.WEBHOOK:
template = html`<or-rule-action-webhook .rule="${this.rule}" .action="${action}" .actionType="${ActionType.WEBHOOK}"></or-rule-action-webhook>`;
break;
+ case ActionType.ALARM:
+ template = html`<or-rule-action-alarm .rule="${this.rule}" .action="${action}" .actionType="${ActionType.ALARM}"></or-rule-action-alarm>`;
+ break;
default:
template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetInfos="${this.assetInfos}" .assetProvider="${this.assetProvider}" .readonly="${this.readonly}"></or-rule-action-attribute>`;
break;
@@ -410,6 +433,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
const type = action.notification && action.notification.message && action.notification.message.type ? action.notification.message.type : action.action;
return type;
break;
+ case "alarm":
+ return action.action;
+ break;
case "write-attribute":
case "update-attribute":
if (!action.target) {
@@ -466,6 +492,10 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case "notification":
action.notification = undefined;
break;
+ case "alarm":
+ action.alarm = undefined;
+ action.assigneeId = undefined;
+ break;
case "update-attribute":
action.value = undefined;
action.attributeName = undefined;
@@ -477,6 +507,16 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
if (value === ActionType.WAIT) {
action.action = "wait";
+ } else if (value == ActionType.ALARM){
+ action = action as RuleActionAlarm;
+ action.action = "alarm";
+ action.alarm = {
+ title: "%RULESET_NAME%",
+ content: "%TRIGGER_ASSETS%",
+ severity: AlarmSeverity.LOW,
+ status: AlarmStatus.OPEN
+ };
+ action.assigneeId = undefined;
} else if (value == ActionType.WEBHOOK) {
action = action as RuleActionWebhook;
action.action = "webhook";