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:
Zimin A.N.
2026-05-17 11:11:21 +03:00
parent 6ed0b459de
commit 74704dbf5b
13 changed files with 804 additions and 4 deletions
@@ -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) {
@@ -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);
}
}