feat(notifications): Phase C — Don't Disturb (quiet hours window)
User задаёт quiet window (e.g. 22:00–08:00 Europe/Moscow) — external channels (email + express) DROP'аются dispatcher'ом. In-app bell badge остаётся (юзер видит при следующем визите UI). Cross-midnight aware. ## Backend - Migration 0026: user_notification_settings table (user_id PK + quiet_hours_start/end LocalTime + tz) - Entity UserNotificationSettings + Repository (stock CRUD) - UserPreferencesGate extended: - Constructor takes settingsRepo - allows() checks isQuiet(userId) первым for external channels (EMAIL/EXPRESS/TELEGRAM) - isQuiet: load settings → if hasEffectiveQuietHours() → check current LocalTime в user's TZ - inWindow() helper: cross-midnight semantics (22:00–08:00 wraps midnight) - Invalid TZ → fallback к DEFAULT_TZ (Europe/Moscow) с WARN log - Test seam: setClockForTesting(Clock) для deterministic tests - MeNotificationsSettingsController: GET/PUT /api/v1/me/notifications/settings - HH:mm input parsing, IANA TZ validation, enabled=false clears window - Auth required (JWT sub claim) ## Frontend - NotificationSettings type в client.ts - useMyNotificationSettings query (60s stale) - useUpdateNotificationSettings mutation - QuietHoursSection в /me/notifications/preferences route: - Switch toggle + 2 time inputs + TZ select (12 RU/UTC zones) - Optimistic local state synced from query - Save button с pending/success/error states - i18n RU + EN ## Tests - 9 new tests UserPreferencesGateQuietHoursTest: - Same-day window match (inclusive start, exclusive end) - Cross-midnight window match (22:00–08:00) - No settings row → не блокирует - Quiet window active → email + express dropped - Outside window → email allowed - start == end → disabled (zero-duration treated as off) - Reviewer pool bypasses (always ON) - Invalid TZ → fallback default - Specific pref ON + quiet ON → quiet wins (drop) - NotificationsDispatcherTest constructor updated к new signature - Total notifications tests: 53 → 62, все green ## Design rationale (drop vs defer) Drop chosen за defer (queue + re-fire scheduler) потому что: - Defer needs persistent queue + scheduled retry — high complexity - Most notifications time-relevant (draft N hours ago less actionable) - Bell badge показывает full feed — ничего не «теряется» - Phase D summary digest можно build later если demand surfaces
This commit is contained in:
+78
-1
@@ -2,12 +2,17 @@ package cloud.nstart.terravault.ordinis.notifications.dispatcher;
|
||||
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationPref;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationPrefRepository;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettings;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettingsRepository;
|
||||
import cloud.nstart.terravault.ordinis.notifications.channel.ChannelKind;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
import static cloud.nstart.terravault.ordinis.domain.notification.UserNotificationPref.ANY_EVENT_TYPE;
|
||||
@@ -39,9 +44,20 @@ public class UserPreferencesGate {
|
||||
public static final String REVIEWER_POOL_USER_ID = "reviewer-pool";
|
||||
|
||||
private final UserNotificationPrefRepository repo;
|
||||
private final UserNotificationSettingsRepository settingsRepo;
|
||||
/** Override clock для tests — null = system. */
|
||||
private java.time.Clock clock = java.time.Clock.systemDefaultZone();
|
||||
|
||||
public UserPreferencesGate(UserNotificationPrefRepository repo) {
|
||||
public UserPreferencesGate(
|
||||
UserNotificationPrefRepository repo,
|
||||
UserNotificationSettingsRepository settingsRepo) {
|
||||
this.repo = repo;
|
||||
this.settingsRepo = settingsRepo;
|
||||
}
|
||||
|
||||
/** Test seam — внутрипакетный setter для clock override. */
|
||||
void setClockForTesting(java.time.Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,6 +82,13 @@ public class UserPreferencesGate {
|
||||
// Pool is a shared inbox — always ON, prefs don't apply.
|
||||
return true;
|
||||
}
|
||||
// Phase C Don't Disturb: пользователь в quiet hours → DROP для external
|
||||
// channels (email/express). Bell badge (in-app) НЕ затронут — он не
|
||||
// проходит через gate (rendered напрямую UI'ем из notification log).
|
||||
if (isExternalChannel(channel) && isQuiet(userId)) {
|
||||
log.debug("Quiet hours active для user={} → dropping channel={}", userId, channel);
|
||||
return false;
|
||||
}
|
||||
String channelWire = channel.wireName();
|
||||
|
||||
// Step 1: specific (user, eventType, channel)
|
||||
@@ -96,4 +119,58 @@ public class UserPreferencesGate {
|
||||
private boolean defaultFor(ChannelKind channel) {
|
||||
return channel == ChannelKind.EMAIL;
|
||||
}
|
||||
|
||||
/**
|
||||
* External = доставляется наружу из приложения (EMAIL/EXPRESS/TELEGRAM).
|
||||
* In-app channels (bell badge) НЕ external — не fired через dispatcher.
|
||||
* Сейчас все ChannelKind external; метод оставлен expansion-safe.
|
||||
*/
|
||||
private static boolean isExternalChannel(ChannelKind channel) {
|
||||
return channel == ChannelKind.EMAIL
|
||||
|| channel == ChannelKind.EXPRESS
|
||||
|| channel == ChannelKind.TELEGRAM;
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase C: current time falls in user's quiet hours window?
|
||||
*
|
||||
* <p>Cross-midnight aware: window {@code 22:00–08:00} → true когда current
|
||||
* local time (in user's TZ) ∈ [22:00, 24:00) ∪ [00:00, 08:00).
|
||||
*
|
||||
* <p>Tolerant: settings row missing → false. start == end → false (treat
|
||||
* as disabled, see {@link UserNotificationSettings#hasEffectiveQuietHours}).
|
||||
* Invalid TZ id → fallback к {@link UserNotificationSettings#DEFAULT_TZ}.
|
||||
*/
|
||||
boolean isQuiet(String userId) {
|
||||
Optional<UserNotificationSettings> optS = settingsRepo.findById(userId);
|
||||
if (optS.isEmpty()) return false;
|
||||
UserNotificationSettings s = optS.get();
|
||||
if (!s.hasEffectiveQuietHours()) return false;
|
||||
|
||||
ZoneId zone;
|
||||
try {
|
||||
zone = ZoneId.of(s.effectiveTz());
|
||||
} catch (Exception e) {
|
||||
log.warn("Invalid TZ '{}' для user={}, falling back к {}",
|
||||
s.effectiveTz(), userId, UserNotificationSettings.DEFAULT_TZ);
|
||||
zone = ZoneId.of(UserNotificationSettings.DEFAULT_TZ);
|
||||
}
|
||||
LocalTime nowLocal = ZonedDateTime.now(clock.withZone(zone)).toLocalTime();
|
||||
return inWindow(nowLocal, s.getQuietHoursStart(), s.getQuietHoursEnd());
|
||||
}
|
||||
|
||||
/**
|
||||
* True если {@code t} ∈ [start, end). Cross-midnight semantics: если
|
||||
* start > end (e.g. 22:00 > 08:00), window wraps midnight → match если
|
||||
* t >= start ИЛИ t < end. Standard "do not disturb" interpretation.
|
||||
*/
|
||||
static boolean inWindow(LocalTime t, LocalTime start, LocalTime end) {
|
||||
if (start.isBefore(end)) {
|
||||
// Same-day window: 09:00–18:00 → t in [09:00, 18:00).
|
||||
return !t.isBefore(start) && t.isBefore(end);
|
||||
} else {
|
||||
// Cross-midnight: 22:00–08:00 → t in [22:00, 24:00) ∪ [00:00, 08:00).
|
||||
return !t.isBefore(start) || t.isBefore(end);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -78,7 +78,8 @@ class NotificationsDispatcherTest {
|
||||
// Phase B: UserPreferencesGate — stub all-allow для existing tests (no
|
||||
// prefs row → defaults apply, email ON). Per-channel skip tested separately.
|
||||
// Phase B-2 signature: allows(userId, eventType, channel)
|
||||
UserPreferencesGate allAllowGate = new UserPreferencesGate(null) {
|
||||
// Phase C extended constructor (settingsRepo too) — stub все all-allow.
|
||||
UserPreferencesGate allAllowGate = new UserPreferencesGate(null, null) {
|
||||
@Override
|
||||
public boolean allows(String userId, String eventType,
|
||||
cloud.nstart.terravault.ordinis.notifications.channel.ChannelKind channel) {
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package cloud.nstart.terravault.ordinis.notifications.dispatcher;
|
||||
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationPref;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationPrefRepository;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettings;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettingsRepository;
|
||||
import cloud.nstart.terravault.ordinis.notifications.channel.ChannelKind;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Phase C Don't Disturb gate tests: quiet hours window calculation +
|
||||
* cross-midnight semantics + dispatcher integration.
|
||||
*/
|
||||
class UserPreferencesGateQuietHoursTest {
|
||||
|
||||
private UserNotificationPrefRepository prefRepo;
|
||||
private UserNotificationSettingsRepository settingsRepo;
|
||||
private UserPreferencesGate gate;
|
||||
|
||||
private static final String USER = "user-123";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
prefRepo = mock(UserNotificationPrefRepository.class);
|
||||
settingsRepo = mock(UserNotificationSettingsRepository.class);
|
||||
// Default: no specific prefs found → fallback к default policy
|
||||
when(prefRepo.findByIdUserIdAndIdEventTypeAndIdChannel(anyString(), anyString(), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
gate = new UserPreferencesGate(prefRepo, settingsRepo);
|
||||
}
|
||||
|
||||
// ─── inWindow pure function ──────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void same_day_window_match() {
|
||||
LocalTime start = LocalTime.of(9, 0);
|
||||
LocalTime end = LocalTime.of(18, 0);
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(12, 0), start, end)).isTrue();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(9, 0), start, end)).isTrue();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(8, 59), start, end)).isFalse();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(18, 0), start, end)).isFalse(); // exclusive
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(23, 30), start, end)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cross_midnight_window_match() {
|
||||
LocalTime start = LocalTime.of(22, 0);
|
||||
LocalTime end = LocalTime.of(8, 0);
|
||||
// Evening side
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(22, 0), start, end)).isTrue();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(23, 59), start, end)).isTrue();
|
||||
// Morning side
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(0, 0), start, end)).isTrue();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(7, 59), start, end)).isTrue();
|
||||
// Outside
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(8, 0), start, end)).isFalse();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(12, 0), start, end)).isFalse();
|
||||
assertThat(UserPreferencesGate.inWindow(LocalTime.of(21, 59), start, end)).isFalse();
|
||||
}
|
||||
|
||||
// ─── allows() с quiet hours ──────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void no_settings_row_means_no_quiet_hours_email_allowed() {
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.empty());
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void quiet_hours_block_email_during_window() {
|
||||
var settings = settingsAt(USER, "22:00", "08:00", "Europe/Moscow");
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.of(settings));
|
||||
// Fix clock at 02:00 Europe/Moscow (cross-midnight window match)
|
||||
gate.setClockForTesting(fixedClockMoscow("2026-05-17T02:00:00"));
|
||||
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isFalse();
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EXPRESS)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void quiet_hours_allow_email_outside_window() {
|
||||
var settings = settingsAt(USER, "22:00", "08:00", "Europe/Moscow");
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.of(settings));
|
||||
// 14:00 Moscow — not in quiet window
|
||||
gate.setClockForTesting(fixedClockMoscow("2026-05-17T14:00:00"));
|
||||
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void quiet_hours_disabled_when_start_equals_end() {
|
||||
var settings = settingsAt(USER, "08:00", "08:00", "Europe/Moscow");
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.of(settings));
|
||||
gate.setClockForTesting(fixedClockMoscow("2026-05-17T08:00:00"));
|
||||
|
||||
// Zero-length window treated as disabled
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reviewer_pool_bypasses_quiet_hours() {
|
||||
var settings = settingsAt(UserPreferencesGate.REVIEWER_POOL_USER_ID, "00:00", "23:59", null);
|
||||
when(settingsRepo.findById(UserPreferencesGate.REVIEWER_POOL_USER_ID))
|
||||
.thenReturn(Optional.of(settings));
|
||||
|
||||
// Pool bypass — early return before quiet check
|
||||
assertThat(gate.allows(
|
||||
UserPreferencesGate.REVIEWER_POOL_USER_ID,
|
||||
"RecordDraftSubmitted",
|
||||
ChannelKind.EMAIL)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalid_tz_falls_back_к_default() {
|
||||
var settings = new UserNotificationSettings(USER);
|
||||
settings.setQuietHoursStart(LocalTime.of(22, 0));
|
||||
settings.setQuietHoursEnd(LocalTime.of(8, 0));
|
||||
settings.setQuietHoursTz("Mars/Olympus_Mons"); // invalid
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.of(settings));
|
||||
// 02:00 default (Europe/Moscow) — should still match quiet window
|
||||
gate.setClockForTesting(fixedClockMoscow("2026-05-17T02:00:00"));
|
||||
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void quiet_hours_respect_specific_pref_disabled() {
|
||||
// Specific pref OFF; quiet hours also active → OFF (both паttерны
|
||||
// disabling, no special order needed — short-circuit на quiet first).
|
||||
var pref = new UserNotificationPref(USER, "RecordDraftSubmitted", "email", true);
|
||||
when(prefRepo.findByIdUserIdAndIdEventTypeAndIdChannel(USER, "RecordDraftSubmitted", "email"))
|
||||
.thenReturn(Optional.of(pref));
|
||||
var settings = settingsAt(USER, "22:00", "08:00", "Europe/Moscow");
|
||||
when(settingsRepo.findById(USER)).thenReturn(Optional.of(settings));
|
||||
gate.setClockForTesting(fixedClockMoscow("2026-05-17T02:00:00"));
|
||||
|
||||
// Even though specific pref ON, quiet hours win
|
||||
assertThat(gate.allows(USER, "RecordDraftSubmitted", ChannelKind.EMAIL)).isFalse();
|
||||
}
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
private static UserNotificationSettings settingsAt(
|
||||
String userId, String start, String end, String tz) {
|
||||
var s = new UserNotificationSettings(userId);
|
||||
s.setQuietHoursStart(LocalTime.parse(start));
|
||||
s.setQuietHoursEnd(LocalTime.parse(end));
|
||||
s.setQuietHoursTz(tz);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static Clock fixedClockMoscow(String localIso) {
|
||||
ZoneId zone = ZoneId.of("Europe/Moscow");
|
||||
var instant = java.time.LocalDateTime.parse(localIso).atZone(zone).toInstant();
|
||||
return Clock.fixed(instant, zone);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user