Compare commits

..
Author SHA1 Message Date
CircleCI a4116b3c75 Bump version to 0.1.0-RC.10 [skip ci] 2026-10-14 23:08:43 +00:00
james.maesandClaude Opus 5.5 6c3fb450eb Merge develop into release/0.1 for 0.1.0-RC.10 (#33 duplicate notifications, #32, #35 indexes and FKs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:03:54 -05:00
CircleCI 7f51d8ee93 Bump version to 0.1.0-RC.9 [skip ci] 2026-10-14 22:38:07 +00:00
james.maesandClaude Opus 5.5 cc297f649a Merge develop into release/0.1 for 0.1.0-RC.9 (#36 seeds, Setup card, coverage wiring)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:33:42 -05:00
CircleCI 289acee3cc Bump version to 0.1.0-RC.8 [skip ci] 2026-10-14 21:49:55 +00:00
james.maesandClaude Opus 5.5 8ca9fff6a1 Merge develop into release/0.1 for 0.1.0-RC.8 (#18 Notifications preferences section, QQQ RC.7)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:45:03 -05:00
CircleCI c67e1a343d Bump version to 0.1.0-RC.7 [skip ci] 2026-10-14 21:24:49 +00:00
james.maesandClaude Opus 5.5 4fe1db3462 Merge develop into release/0.1 for 0.1.0-RC.7 (#34 child lists JSON serialization fix)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:20:57 -05:00
CircleCI 27d471a8e1 Bump version to 0.1.0-RC.6 [skip ci] 2026-10-14 20:24:26 +00:00
james.maesandClaude Opus 5.5 ee54fc4ba5 Merge develop into release/0.1 for 0.1.0-RC.6 (per-user Slack delivery)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:21:06 -05:00
CircleCI bba86368d9 Bump version to 0.1.0-RC.5 [skip ci] 2026-10-14 16:22:13 +00:00
james.maesandClaude Opus 5.5 fb88168107 Merge develop into release/0.1 for 0.1.0-RC.5 (#23 #26 #28 #29 #30)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:17:45 -05:00
CircleCI 6d4b80793b Bump version to 0.1.0-RC.4 [skip ci] 2026-10-14 12:51:58 +00:00
james.maesandClaude Opus 5.5 da5aba1f39 Merge develop into release/0.1 for 0.1.0-RC.4 (#19 #21 #24)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:48:10 -05:00
CircleCI dbbcb97baf Bump version to 0.1.0-RC.3 [skip ci] 2026-10-14 00:51:41 +00:00
james.maesandClaude Opus 5.5 a84a10a4cd Merge develop into release/0.1 for 0.1.0-RC.3 (core QAlerts sink and WebhookSigner, #17)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:49:04 -05:00
CircleCI dae98dae82 Bump version to 0.1.0-RC.2 [skip ci] 2026-10-13 16:33:36 +00:00
james.maesandClaude Opus 5.5 aede554b25 Merge develop into release/0.1 for 0.1.0-RC.2
User notifications: spec (#8), tables, admin, audiences and bell API
(#9), job-failure notices (#10), security/share/release notices, email
digest and link hardening (#11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:31:35 -05:00
CircleCI 567b4833fc Bump version to 0.1.0-RC.1 [skip ci] 2026-10-12 22:57:11 +00:00
10 changed files with 267 additions and 1854 deletions

No files matched your search

+1 -3
View File
@@ -8,9 +8,8 @@ All notable changes to this project are documented here. The format follows Keep
- Record-view child lists (e.g. a notification's Recipients) failed with "Error in JSON Serialization": the child table's meta-data includes the qbit config, and `AlertsQBitConfig.getRuntime()` points at a runtime that points back at the config, so Jackson recursed to its 1000-level nesting limit. `getRuntime()` and `getAudienceResolver()` are now `@JsonIgnore`, as in the other qbits' configs. A regression test renders and serializes every child-list widget.
### Added
- Ship the full host-neutral Alerts help bundle through QQQ 4.1.0-RC.7 core registration, replacing the temporary loader. Cover owned tables, fields, actions, jobs, widgets and possible-value sources with a bundle coverage gate; support HOST overrides and hosts without help tables.
- Starter defaults changelog `alerts-defaults.changelog.sql` (insert-only, guarded): the `in-app` and `email` channels and the `alerts` and `other` groups, equal to what the runtime creates on first use. Tested through real Liquibase on H2.
- Help for the Alerts app and every `alerts_*` table (`help/qbit-alerts.yaml`): what the table is for and how its rows get created, shown when it is empty.
- Help for the Alerts app and every `alerts_*` table (`help/qbit-alerts.yaml`, STAND-IN core#1198): what the table is for and how its rows get created, shown when it is empty.
- A Setup card first on the Alerts home (alerts admins): each configuration table, its state and the next step.
- `AlertsTablesGuardrailTest`: every table is used by runtime code, seeded or listed as starting empty with a reason, and has help.
@@ -48,7 +47,6 @@ All notable changes to this project are documented here. The format follows Keep
- Apply reminders and escalation (#27, part 2): a minute-based hidden job sends due reminders, advances ordered USER/TEAM/CHANNEL escalation steps, and caps final-step repeats. Acknowledgement, snooze, resolution and mutes stop both; reopening restarts escalation. Delivery, events and progress commit together, with a persisted same-minute checkpoint.
- Add admin escalation policy and step tables, child step lists, and type/group policy links in guarded Liquibase changesets 23–26. Type policies override group policies. CRITICAL reminders default to 60 minutes; explicit zero turns them off.
- Keep EXPIRED reserved and remove it from selectable resolution values because the design specifies no expiration rule.
- Per-notification email opt-in via recipient email status `REQUESTED`: immediate delivery without a standing category preference. It still honours the category email minimum severity, the user pause (SECURITY bypasses) and quiet hours (held until they end, for up to a day), is skipped when no address is known, and is never emailed for ALERT notifications.
- Optional external channels:
- Slack (an Incoming Webhook, Block Kit)
- Microsoft Teams (a Workflows webhook, an Adaptive Card)
-17
View File
@@ -280,23 +280,6 @@ assigned automatically. The Resolve action continues to record MANUAL.
- **Alertmanager sink:** open alerts are sent with an `endsAt` a week out, not re-posted.
- **Not built yet:** Micrometer metrics, mirrored lock columns and a configurable table namespace. These are the rest of design phases P4 to P6.
## In-app help
The producer registers [`help/qbit-alerts.yaml`](src/main/resources/help/qbit-alerts.yaml)
with QQQ's help-bundle registry. It covers the Alerts app, tables and fields,
actions, scheduled jobs, widgets and possible-value sources. QQQ syncs the bundle
when the host installs the help-content tables; registration is harmless without them.
Hosts can override individual entries by registering their own bundle with
`layer: HOST`, using the same entry `key` and `role` (default `ALL_SCREENS`).
Register it with `HelpBundles.register(qInstance, "help/my-host.yaml")`. Host
bundles take precedence over this `QBIT` bundle, and edits made by users remain protected.
`AlertsTablesGuardrailTest` runs `HelpBundleAssertions` against the produced instance
to check owned-object coverage, summary length and live references. It also requires
widget and possible-value-source help and preserves the table empty-state guidance.
When releasing, keep the bundle's literal version aligned with the POM's revision.
## Build
```bash
+2 -29
View File
@@ -18,7 +18,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<revision>0.1.0-SNAPSHOT</revision>
<revision>0.1.0-RC.10</revision>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<jacoco.version>0.8.15</jacoco.version>
@@ -153,34 +153,7 @@
</dependencies>
<build>
<resources>
<!-- help bundles carry the artifact version (QQQ help bundle provenance) -->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>help/*.yaml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>help/*.yaml</exclude>
</excludes>
</resource>
</resources>
<plugins>
<!-- the artifact version, for the help bundle version test -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables combine.children="append">
<qbit.artifactVersion>${project.version}</qbit.artifactVersion>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
@@ -258,7 +231,7 @@
<profiles>
<!-- Built against qqq 4.1 (QBitMetaDataProducer). Until qbit-build-parent -->
<!-- imports the released 4.1 BOM, this profile is active by default and -->
<!-- imports qqq-bom-pom 4.1.0-RC.7 ahead of the parent's 4.0.0 BOM. -->
<!-- imports qqq-bom-pom 4.1.0-RC.6 ahead of the parent's 4.0.0 BOM. -->
<profile>
<id>qqq-snapshot</id>
<activation>
@@ -24,6 +24,7 @@ import com.kingsrook.qbits.alerts.engine.AlertsProcessListener;
import com.kingsrook.qbits.alerts.engine.AlertsSinkAdapter;
import com.kingsrook.qbits.alerts.engine.MonitorEvaluator;
import com.kingsrook.qbits.alerts.engine.QbitAlertsSink;
import com.kingsrook.qbits.alerts.metadata.AlertsHelp;
import com.kingsrook.qbits.alerts.metadata.AlertsTableMetaDataHelper;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
@@ -37,7 +38,6 @@ import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
@@ -174,8 +174,7 @@ public class AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig
MetaDataProducerMultiOutput output = QBitMetaDataProducer.super.produce(qInstance);
output.addSelfToInstance(qInstance);
// Registration is metadata-only; core guards startup sync when helpContent is absent.
HelpBundles.register(qInstance, "help/qbit-alerts.yaml");
AlertsHelp.apply(qInstance);
return (new MetaDataProducerMultiOutput());
}
@@ -0,0 +1,127 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Applies help/qbit-alerts.yaml (the QQQ help-bundle format) to the
** Alerts app and its alerts_* tables: what each table is for and how
** its rows get created, shown on the table screen and when it is empty.
** STAND-IN(core=QRun-IO/qqq#1198, removeBy=4.1.0-RC.8): replace with HelpBundles.register once the pinned
** QQQ release includes it; the bundle file stays the same.
*******************************************************************************/
public final class AlertsHelp
{
public static final String RESOURCE = "/help/qbit-alerts.yaml";
public static final String SLOT = "help";
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AlertsHelp()
{
}
/*******************************************************************************
** The bundle's entries by key, validated (fails startup if malformed).
*******************************************************************************/
public static Map<String, JsonNode> entries() throws QException
{
try(InputStream stream = AlertsHelp.class.getResourceAsStream(RESOURCE))
{
if(stream == null)
{
throw (new IOException("missing resource"));
}
JsonNode bundle = new ObjectMapper(new YAMLFactory()).readTree(stream);
if(!"qbit-alerts".equals(bundle.path("bundle").asText()) || !"QBIT".equals(bundle.path("layer").asText()))
{
throw (new IOException("invalid bundle header"));
}
Map<String, JsonNode> entries = new LinkedHashMap<>();
for(JsonNode entry : bundle.path("entries"))
{
String key = entry.path("key").asText();
String summary = entry.path("summary").asText();
if(key.isBlank() || summary.isBlank() || summary.length() > 120 || entry.path("content").asText().isBlank() || entries.put(key, entry) != null)
{
throw (new IOException("invalid or duplicate entry: " + key));
}
}
return (entries);
}
catch(IOException | RuntimeException e)
{
throw (new QException("Could not load " + RESOURCE, e));
}
}
/*******************************************************************************
** Apply the help to the app and every alerts_* table in the instance.
** A host's own help on a table is kept (the bundle only fills the slot).
*******************************************************************************/
public static void apply(QInstance qInstance) throws QException
{
Map<String, JsonNode> entries = entries();
for(QTableMetaData table : qInstance.getTables().values())
{
JsonNode entry = entries.get("table:" + table.getName() + ";slot:" + SLOT);
if(entry != null && (table.getHelpContent() == null || !table.getHelpContent().containsKey(SLOT)))
{
table.withHelpContent(SLOT, content(entry));
}
}
QAppMetaData app = qInstance.getApp(AlertsQBitConfig.APP_NAME);
JsonNode appEntry = entries.get("app:" + AlertsQBitConfig.APP_NAME + ";slot:" + SLOT);
if(app != null && appEntry != null && (app.getHelpContent() == null || !app.getHelpContent().containsKey(SLOT)))
{
app.withHelpContent(SLOT, content(appEntry));
}
}
/*******************************************************************************
** Summary as the first paragraph, then the content, as markdown.
*******************************************************************************/
static QHelpContent content(JsonNode entry)
{
return (new QHelpContent().withContentAsMarkdown(entry.path("summary").asText().strip() + "\n\n" + entry.path("content").asText().strip()));
}
}
@@ -290,7 +290,7 @@ public final class AlertsPossibleValues
*******************************************************************************/
public enum EmailStatus
{
NONE, PENDING, REQUESTED, SENT, DIGESTED, SKIPPED, FAILED
NONE, PENDING, SENT, DIGESTED, SKIPPED, FAILED
}
@@ -29,14 +29,11 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.delivery.AlertRedactor;
import com.kingsrook.qbits.alerts.email.AlertsEmail;
import com.kingsrook.qbits.alerts.email.AlertsEmailSender;
import com.kingsrook.qbits.alerts.engine.AlertTiming;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.metadata.AlertsProcessesMetaDataProducer;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
@@ -46,7 +43,6 @@ import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EmailMode;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EmailStatus;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.actions.messaging.SendMessageAction;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.NotificationCategory;
import com.kingsrook.qqq.backend.core.alerts.NotificationSeverity;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@@ -71,11 +67,6 @@ import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
** - IMMEDIATE: one email per notification at or above the minimum severity;
** - DAILY_DIGEST: one email at the user's digest hour (in their time zone,
** from My Alert Settings) listing the day's unread notifications.
** A recipient with email status REQUESTED (a per-notification opt-in, e.g. by
** a job) is emailed immediately without a standing category preference. It
** still honours the category's email minimum severity when one is set, the
** user's pause (SECURITY bypasses) and quiet hours (held, not dropped), is
** skipped without a known address, and is only eligible for a day.
** Sent through qbit-email when it is produced in the instance (one message
** per recipient; templates alerts_notification and alerts_digest,
** NOTIFICATION), else through core SendMessageAction. Inert without either
@@ -146,19 +137,12 @@ public class NotificationEmailer
{
preferences.computeIfAbsent(preference.getValueString("userId"), k -> new HashMap<>()).put(preference.getValueString("category"), preference);
}
QQueryFilter eligible = new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR)
.withSubFilter(new QQueryFilter()
.withCriteria("emailStatus", QCriteriaOperator.EQUALS, EmailStatus.REQUESTED.name())
.withCriteria("deliveredAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, now.minus(1, ChronoUnit.DAYS)));
if(!preferences.isEmpty())
if(preferences.isEmpty())
{
eligible.withSubFilter(new QQueryFilter()
.withCriteria("userId", QCriteriaOperator.IN, new ArrayList<>(preferences.keySet()))
.withCriteria("emailStatus", QCriteriaOperator.IN, List.of(EmailStatus.NONE.name(), EmailStatus.PENDING.name())));
return (new Result(0, 0, 0, 0));
}
Map<String, QRecord> settings = new HashMap<>();
Map<String, QRecord> settings = userSettings(preferences.keySet());
int sent = 0;
int skipped = 0;
int failed = 0;
@@ -167,7 +151,8 @@ public class NotificationEmailer
while(true)
{
List<QRecord> recipients = AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, new QQueryFilter()
.withSubFilter(eligible)
.withCriteria("userId", QCriteriaOperator.IN, new ArrayList<>(preferences.keySet()))
.withCriteria("emailStatus", QCriteriaOperator.IN, List.of(EmailStatus.NONE.name(), EmailStatus.PENDING.name()))
.withCriteria("id", QCriteriaOperator.GREATER_THAN, afterId)
.withOrderBy(new QFilterOrderBy("id", true)).withLimit(SCAN));
if(recipients.isEmpty())
@@ -176,43 +161,25 @@ public class NotificationEmailer
}
afterId = recipients.get(recipients.size() - 1).getValueInteger("id");
Map<Integer, QRecord> notifications = notifications(recipients, now);
Set<String> pageUsers = recipients.stream().map(recipient -> recipient.getValueString("userId")).collect(Collectors.toSet());
settings.putAll(userSettings(pageUsers));
Map<String, Map<String, QRecord>> requestedPreferences = new HashMap<>();
for(QRecord preference : AlertsDb.query(AlertsNotificationPreference.TABLE_NAME, new QQueryFilter()
.withCriteria("userId", QCriteriaOperator.IN, new ArrayList<>(pageUsers))))
{
requestedPreferences.computeIfAbsent(preference.getValueString("userId"), k -> new HashMap<>()).put(preference.getValueString("category"), preference);
}
for(QRecord recipient : recipients)
{
QRecord notification = notifications.get(recipient.getValueInteger("notificationId"));
String userId = recipient.getValueString("userId");
boolean requested = EmailStatus.REQUESTED.name().equals(recipient.getValueString("emailStatus"));
String category = notification == null ? null : notification.getValueString("category");
QRecord preference = category == null ? null : (requested ? requestedPreferences : preferences).getOrDefault(userId, Map.of()).get(category);
QRecord setting = settings.get(userId);
if(notification == null || NotificationCategory.ALERT.name().equals(category)
|| (requested ? (!StringUtils.hasContent(address(setting)) || (preference != null && StringUtils.hasContent(preference.getValueString("emailMinSeverity"))
&& !atLeast(notification.getValueString("severity"), preference.getValueString("emailMinSeverity"))))
: (preference == null || !atLeast(notification.getValueString("severity"), preference.getValueString("emailMinSeverity")))))
QRecord preference = notification == null ? null : preferences.get(userId).get(notification.getValueString("category"));
if(notification == null || preference == null || NotificationCategory.ALERT.name().equals(notification.getValueString("category"))
|| !atLeast(notification.getValueString("severity"), preference.getValueString("emailMinSeverity")))
{
mark(recipient, EmailStatus.SKIPPED, null);
skipped++;
}
else if(!NotificationCategory.SECURITY.name().equals(category)
&& setting != null && setting.getValueInstant("pausedUntil") != null
&& setting.getValueInstant("pausedUntil").isAfter(now))
else if(!NotificationCategory.SECURITY.name().equals(notification.getValueString("category"))
&& settings.get(userId) != null && settings.get(userId).getValueInstant("pausedUntil") != null
&& settings.get(userId).getValueInstant("pausedUntil").isAfter(now))
{
// Leave the recipient pending so a later run can deliver it.
skipped++;
}
else if(requested && AlertTiming.isQuiet(setting, AlertSeverity.fromLabel(notification.getValueString("severity"), AlertSeverity.WARNING), now))
{
// Quiet hours hold a requested email; it stays REQUESTED until the window ends or it ages out.
skipped++;
}
else if(requested || EmailMode.IMMEDIATE.name().equals(preference.getValueString("emailMode")))
else if(EmailMode.IMMEDIATE.name().equals(preference.getValueString("emailMode")))
{
EmailStatus status = sendImmediate(address(settings.get(userId)), notification);
mark(recipient, status, status == EmailStatus.SENT ? now : null);
File diff suppressed because it is too large. Load diff
@@ -26,10 +26,9 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import com.kingsrook.qbits.alerts.metadata.AlertsProcessesMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
import com.kingsrook.qbits.alerts.metadata.AlertsHelp;
import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.testing.HelpBundleAssertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -59,7 +58,7 @@ class AlertsTablesGuardrailTest extends BaseAlertsTest
Map.entry("alerts_event", "runtime: the alert timeline"),
Map.entry("alerts_subscription", "people's own choices; the first alerts admin gets one by the bootstrap rule (AlertsPreferences)"),
Map.entry("alerts_user_preference", "user content: created per person on their first visit (AlertsPreferences)"),
Map.entry("alerts_team", "the host's own people"),
Map.entry("alerts_team", "the host's own people (kof22 seeds its team)"),
Map.entry("alerts_team_member", "the host's own people"),
Map.entry("alerts_mute", "user content: maintenance windows and mutes people create"),
Map.entry("alerts_delivery", "runtime log: every delivery attempt"),
@@ -123,44 +122,31 @@ class AlertsTablesGuardrailTest extends BaseAlertsTest
@Test
void everyTableHasEmptyStateHelp() throws Exception
{
// Core adds bulk CRUD processes during validation; the qbit owns its declared actions and jobs.
var processes = AlertsProcessesMetaDataProducer.buildProcesses(config).stream().map(process -> process.getName()).toList();
HelpBundleAssertions.forInstance(qInstance)
.bundles("help/qbit-alerts.yaml")
.owning(target -> "process".equals(target.kind()) ? processes.contains(target.name()) : target.name().startsWith("alerts"))
.assertComplete();
var entries = HelpBundles.of(qInstance).getBundles().get(0).getEntries();
// Core's gate does not yet require widget and possible-value-source help.
var keys = entries.stream().map(entry -> entry.getKey()).toList();
qInstance.getWidgets().keySet().stream().filter(name -> name.startsWith("alerts"))
.forEach(name -> assertThat(keys).contains("widget:" + name + ";slot:help"));
qInstance.getPossibleValueSources().keySet().stream().filter(name -> name.startsWith("alerts"))
.forEach(name -> assertThat(keys).contains("possibleValueSource:" + name + ";slot:help"));
assertThat(AlertsHelp.entries()).allSatisfy((key, entry) -> assertThat(entry.path("summary").asText().length()).as(key).isLessThanOrEqualTo(120));
for(String table : alertsTables())
{
assertThat(entries).anySatisfy(entry ->
{
assertThat(entry.getKey()).isEqualTo("table:" + table + ";slot:help");
assertThat(entry.getContent()).contains("How rows get created");
});
List<QHelpContent> help = qInstance.getTable(table).getHelpContent() == null ? null : qInstance.getTable(table).getHelpContent().get(AlertsHelp.SLOT);
assertThat(help).as(table + " table help").isNotEmpty();
assertThat(help.get(0).getContent()).as(table + " help says how rows get created").contains("How rows get created");
}
assertThat(qInstance.getApp(AlertsQBitConfig.APP_NAME).getHelpContent()).containsKey(AlertsHelp.SLOT);
assertThat(AlertsHelp.entries().keySet()).allMatch(key -> !key.startsWith("table:") || qInstance.getTable(key.substring(6, key.indexOf(';'))) != null,
"help names only real tables");
}
/*******************************************************************************
** Bundle registration needs no help table; core safely skips startup sync.
** A host's own help on a table is kept; the bundle fills only empty slots.
*******************************************************************************/
@Test
void hostWithoutHelpTableIsSupported()
void hostHelpIsNotOverridden() throws Exception
{
assertThat(qInstance.getTable("helpContent")).isNull();
assertThat(HelpBundles.of(qInstance).getBundles()).singleElement().satisfies(bundle ->
{
assertThat(bundle.getId()).isEqualTo("qbit-alerts");
assertThat(bundle.getVersion()).as("the help bundle carries the artifact version").isEqualTo(System.getProperty("qbit.artifactVersion"));
});
HelpBundles.syncOnStartup(qInstance);
QTableMetaData table = qInstance.getTable("alerts_channel");
table.getHelpContent().remove(AlertsHelp.SLOT);
table.withHelpContent(AlertsHelp.SLOT, new QHelpContent().withContentAsMarkdown("host text"));
AlertsHelp.apply(qInstance);
assertThat(table.getHelpContent().get(AlertsHelp.SLOT)).singleElement().matches(c -> "host text".equals(c.getContent()));
}
@@ -172,232 +172,6 @@ class NotificationEmailAndNoticesTest extends BaseAlertsTest
/*******************************************************************************
** A requested email does not require a standing category preference.
*******************************************************************************/
@Test
void testRequestedWithoutPreference() throws Exception
{
addressOnly();
requested("JOB");
assertThat(new NotificationEmailer(runtime).run().sent()).isEqualTo(1);
assertThat(emailStatus("viewer-1")).isEqualTo("SENT");
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(SENT).hasSize(1);
}
/*******************************************************************************
** An explicit request and an immediate preference still send only once.
*******************************************************************************/
@Test
void testRequestedWithImmediatePreference() throws Exception
{
emailSettings("viewer-1", "JOB", "IMMEDIATE", "INFO");
requested("JOB");
assertThat(new NotificationEmailer(runtime).run().sent()).isEqualTo(1);
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(SENT).hasSize(1);
}
/*******************************************************************************
** A request overrides digest timing (not the category's minimum severity).
*******************************************************************************/
@Test
void testRequestedWithDigestPreference() throws Exception
{
emailSettings("viewer-1", "JOB", "DAILY_DIGEST", "INFO");
requested("JOB");
NotificationEmailer.Result result = new NotificationEmailer(runtime).run();
assertThat(result.sent()).isEqualTo(1);
assertThat(result.digests()).isZero();
assertThat(SENT).hasSize(1);
}
/*******************************************************************************
** Knowing an address alone does not opt a notification into email.
*******************************************************************************/
@Test
void testNotRequestedWithoutPreference() throws Exception
{
addressOnly();
runtime.getNotifications().notify(new NotificationSignal("Done").withCategory(NotificationCategory.JOB)
.withAudience(NotificationAudience.user("viewer-1")));
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(emailStatus("viewer-1")).isEqualTo("NONE");
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** Missing addresses are skipped rather than counted as delivery failures.
*******************************************************************************/
@Test
void testRequestedWithoutAddress() throws Exception
{
requested("JOB");
NotificationEmailer.Result result = new NotificationEmailer(runtime).run();
assertThat(result.skipped()).isEqualTo(1);
assertThat(result.failed()).isZero();
assertThat(emailStatus("viewer-1")).isEqualTo("SKIPPED");
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** Alert subscriptions own alert emails, even with an explicit request.
*******************************************************************************/
@Test
void testRequestedAlertNeverEmailed() throws Exception
{
emailSettings("viewer-1", "ALERT", "IMMEDIATE", "INFO");
requested("ALERT");
assertThat(new NotificationEmailer(runtime).run().skipped()).isEqualTo(1);
assertThat(emailStatus("viewer-1")).isEqualTo("SKIPPED");
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** Requests older than the delivery window are not emailed.
*******************************************************************************/
@Test
void testRequestedOutsideDeliveryWindow() throws Exception
{
addressOnly();
requested("JOB");
clock.set(clock.instant().plusSeconds(86401));
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(emailStatus("viewer-1")).isEqualTo("REQUESTED");
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** Provider failures remain terminal and do not cause repeated sends.
*******************************************************************************/
@Test
void testRequestedDeliveryFailure() throws Exception
{
addressOnly();
requested("JOB");
runtime.getConfig().withMessagingProviderName("missing-provider");
NotificationEmailer.Result result = new NotificationEmailer(runtime).run();
assertThat(result.failed()).isEqualTo(1);
assertThat(emailStatus("viewer-1")).isEqualTo("FAILED");
assertThat(new NotificationEmailer(runtime).run().failed()).isZero();
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** A request still honours the category's email minimum severity.
*******************************************************************************/
@Test
void testRequestedBelowMinSeverity() throws Exception
{
emailSettings("viewer-1", "JOB", "OFF", "ERROR");
requested("JOB");
NotificationEmailer.Result result = new NotificationEmailer(runtime).run();
assertThat(result.skipped()).isEqualTo(1);
assertThat(emailStatus("viewer-1")).isEqualTo("SKIPPED");
assertThat(SENT).isEmpty();
}
/*******************************************************************************
** A user's pause or quiet hours hold a requested email until they end.
*******************************************************************************/
@Test
void testRequestedHeldByPauseAndQuietHours() throws Exception
{
clock.set(Instant.parse("2026-10-12T12:00:00Z"));
addressOnly();
requested("JOB");
setUserPreference(new QRecord().withValue("pausedUntil", clock.instant().plusSeconds(3600)));
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(emailStatus("viewer-1")).isEqualTo("REQUESTED");
clock.set(Instant.parse("2026-10-12T13:30:00Z"));
setUserPreference(new QRecord().withValue("timeZone", "UTC").withValue("quietHoursStart", "13:00").withValue("quietHoursEnd", "14:00"));
assertThat(new NotificationEmailer(runtime).run().sent()).isZero();
assertThat(emailStatus("viewer-1")).isEqualTo("REQUESTED");
clock.set(Instant.parse("2026-10-12T14:00:00Z"));
assertThat(new NotificationEmailer(runtime).run().sent()).isEqualTo(1);
assertThat(emailStatus("viewer-1")).isEqualTo("SENT");
assertThat(SENT).hasSize(1);
}
/*******************************************************************************
** A pause does not hold a requested SECURITY email.
*******************************************************************************/
@Test
void testRequestedSecurityBypassesPause() throws Exception
{
addressOnly();
requested("SECURITY");
setUserPreference(new QRecord().withValue("pausedUntil", clock.instant().plusSeconds(3600)));
assertThat(new NotificationEmailer(runtime).run().sent()).isEqualTo(1);
}
/*******************************************************************************
** Update the user's alert settings row.
*******************************************************************************/
private void setUserPreference(QRecord values) throws QException
{
runtime.asSystem(() ->
{
QRecord setting = AlertsDb.first(AlertsUserPreference.TABLE_NAME, AlertsDb.eq("userId", "viewer-1"));
return (AlertsDb.update(AlertsUserPreference.TABLE_NAME, values.withValue("id", setting.getValue("id"))));
});
}
/*******************************************************************************
** Store an address without opting into any category.
*******************************************************************************/
private void addressOnly() throws QException
{
runtime.asSystem(() -> AlertsDb.insert(AlertsUserPreference.TABLE_NAME,
new QRecord().withValue("userId", "viewer-1").withValue("emailAddress", "viewer-1@example.com")));
}
/*******************************************************************************
** Set up a recipient explicitly requesting email for worker tests.
*******************************************************************************/
private void requested(String category) throws QException
{
Integer id = runtime.getNotifications().notify(new NotificationSignal("Done").withCategory(NotificationCategory.valueOf(category))
.withAudience(NotificationAudience.user("viewer-1")));
runtime.asSystem(() ->
{
QRecord recipient = AlertsDb.first(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", id));
return (AlertsDb.update(AlertsNotificationRecipient.TABLE_NAME,
new QRecord().withValue("id", recipient.getValue("id")).withValue("emailStatus", "REQUESTED")));
});
}
/*******************************************************************************
** The daily digest waits for the user's hour, then lists the unread ones.
*******************************************************************************/