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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user