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:
+153
@@ -0,0 +1,153 @@
|
||||
package cloud.nstart.terravault.ordinis.restapi.web;
|
||||
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettings;
|
||||
import cloud.nstart.terravault.ordinis.domain.notification.UserNotificationSettingsRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeParseException;
|
||||
|
||||
/**
|
||||
* Phase C Don't Disturb — per-user notification settings (quiet hours window).
|
||||
*
|
||||
* <p>{@code GET /api/v1/me/notifications/settings}:
|
||||
* <pre>
|
||||
* {
|
||||
* "quietHoursEnabled": true,
|
||||
* "quietHoursStart": "22:00",
|
||||
* "quietHoursEnd": "08:00",
|
||||
* "quietHoursTz": "Europe/Moscow"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>{@code PUT /api/v1/me/notifications/settings} — same shape.
|
||||
* {@code quietHoursEnabled=false} clears window (start/end → null).
|
||||
*
|
||||
* <p>Когда window active (current local time ∈ window в указанной TZ),
|
||||
* external channels (email + express) DROPPED dispatcher'ом. Bell badge
|
||||
* (in-app) НЕ затронут.
|
||||
*
|
||||
* <p>Auth required — anonymous → 401.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/me/notifications/settings")
|
||||
public class MeNotificationsSettingsController {
|
||||
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(MeNotificationsSettingsController.class);
|
||||
|
||||
private final UserNotificationSettingsRepository repo;
|
||||
|
||||
public MeNotificationsSettingsController(UserNotificationSettingsRepository repo) {
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public SettingsResponse get() {
|
||||
String sub = requireSub();
|
||||
UserNotificationSettings s = repo.findById(sub).orElse(null);
|
||||
if (s == null) {
|
||||
return new SettingsResponse(false, null, null, UserNotificationSettings.DEFAULT_TZ);
|
||||
}
|
||||
return new SettingsResponse(
|
||||
s.hasEffectiveQuietHours(),
|
||||
s.getQuietHoursStart() == null ? null : s.getQuietHoursStart().toString(),
|
||||
s.getQuietHoursEnd() == null ? null : s.getQuietHoursEnd().toString(),
|
||||
s.effectiveTz());
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
@Transactional
|
||||
public SettingsResponse update(@RequestBody SettingsRequest req) {
|
||||
String sub = requireSub();
|
||||
if (req == null) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "body required");
|
||||
}
|
||||
|
||||
UserNotificationSettings s = repo.findById(sub)
|
||||
.orElseGet(() -> new UserNotificationSettings(sub));
|
||||
|
||||
if (Boolean.FALSE.equals(req.quietHoursEnabled)) {
|
||||
s.setQuietHoursStart(null);
|
||||
s.setQuietHoursEnd(null);
|
||||
} else {
|
||||
LocalTime start = parseTime(req.quietHoursStart, "quietHoursStart");
|
||||
LocalTime end = parseTime(req.quietHoursEnd, "quietHoursEnd");
|
||||
if (start == null || end == null) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"quietHoursStart и quietHoursEnd обязательны когда quietHoursEnabled=true");
|
||||
}
|
||||
s.setQuietHoursStart(start);
|
||||
s.setQuietHoursEnd(end);
|
||||
}
|
||||
|
||||
if (req.quietHoursTz != null && !req.quietHoursTz.isBlank()) {
|
||||
try {
|
||||
ZoneId.of(req.quietHoursTz); // validate IANA id
|
||||
s.setQuietHoursTz(req.quietHoursTz);
|
||||
} catch (Exception e) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST, "Неизвестная timezone: " + req.quietHoursTz);
|
||||
}
|
||||
} else {
|
||||
s.setQuietHoursTz(null);
|
||||
}
|
||||
|
||||
repo.save(s);
|
||||
log.info("Quiet hours updated: user={} start={} end={} tz={}",
|
||||
sub, s.getQuietHoursStart(), s.getQuietHoursEnd(), s.effectiveTz());
|
||||
return get();
|
||||
}
|
||||
|
||||
private LocalTime parseTime(String raw, String field) {
|
||||
if (raw == null || raw.isBlank()) return null;
|
||||
try {
|
||||
// Accept "HH:mm" or "HH:mm:ss" both. LocalTime.parse handles both.
|
||||
return LocalTime.parse(raw);
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
field + ": ожидается формат HH:mm, got '" + raw + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private String requireSub() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (!(auth instanceof JwtAuthenticationToken jwt)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "JWT required");
|
||||
}
|
||||
String sub = jwt.getToken().getSubject();
|
||||
if (sub == null || sub.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "JWT sub claim missing");
|
||||
}
|
||||
return sub;
|
||||
}
|
||||
|
||||
/** Request body. {@code quietHoursEnabled=false} clears window. */
|
||||
public static class SettingsRequest {
|
||||
public Boolean quietHoursEnabled;
|
||||
public String quietHoursStart; // "HH:mm" or "HH:mm:ss"
|
||||
public String quietHoursEnd;
|
||||
public String quietHoursTz; // IANA TZ id, e.g. "Europe/Moscow"
|
||||
}
|
||||
|
||||
public record SettingsResponse(
|
||||
boolean quietHoursEnabled,
|
||||
String quietHoursStart,
|
||||
String quietHoursEnd,
|
||||
String quietHoursTz) {}
|
||||
}
|
||||
Reference in New Issue
Block a user