Add notification preferences API and screen (1n)
GET/PUT /api/v1/settings/notifications read and replace the event x
{push, chat} matrix for the five events and the reminder time. The PUT
validates every event exactly once and an HH:MM time, refuses unknown
events and fields, and writes the preferences and the household
settings' reminder_time (the one copy) in one transaction, publishing
the new settings to the scheduler as a household settings change does.
/settings/notifications renders mock 1n: the matrix with Toggle
switches, including the next-day "Keep it in rotation?" Rotation check
(D-021); the reminder time edited in a sheet; the push permission row
using pushStatus/subscribePush/unsubscribePush; the iOS InstallHint;
the Google Chat webhook card with the masked URL, "Connected · {space}"
and Send test showing success or the HTTP status; and the preview
bubble. The desktop 2e Notifications & AI tab shows the matrix and
webhook cards in its left column. The settings home row now reads Web
Push on this device and the Google Chat space, and the Household form
takes a reminder time saved elsewhere without undoing it.
Maestro task 308a460d-b22c-4179-acba-d5ea0968ccd5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/auth"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/household"
|
||||
)
|
||||
|
||||
// notificationsBody is the PUT /settings/notifications body: every event's
|
||||
// channels and the reminder time, all required. Unknown fields and null
|
||||
// values are refused.
|
||||
type notificationsBody struct {
|
||||
Prefs *[]notificationPrefBody `json:"prefs"`
|
||||
ReminderTime *string `json:"reminder_time"`
|
||||
}
|
||||
|
||||
type notificationPrefBody struct {
|
||||
Event *string `json:"event"`
|
||||
Push *bool `json:"push"`
|
||||
Chat *bool `json:"chat"`
|
||||
}
|
||||
|
||||
// settings is the body as household notification settings, or why it is
|
||||
// incomplete.
|
||||
func (b notificationsBody) settings() (household.NotificationSettings, error) {
|
||||
if b.Prefs == nil || b.ReminderTime == nil {
|
||||
return household.NotificationSettings{}, errors.New("prefs and reminder_time are required")
|
||||
}
|
||||
prefs := make([]household.NotificationPref, len(*b.Prefs))
|
||||
for i, p := range *b.Prefs {
|
||||
if p.Event == nil || p.Push == nil || p.Chat == nil {
|
||||
return household.NotificationSettings{}, fmt.Errorf("prefs[%d]: event, push and chat are required", i)
|
||||
}
|
||||
prefs[i] = household.NotificationPref{Event: *p.Event, Push: *p.Push, Chat: *p.Chat}
|
||||
}
|
||||
return household.NotificationSettings{Prefs: prefs, ReminderTime: *b.ReminderTime}, nil
|
||||
}
|
||||
|
||||
func getNotificationSettings(logger *slog.Logger, svc *household.SettingsService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := svc.Notifications(r.Context())
|
||||
if err != nil {
|
||||
logger.ErrorContext(r.Context(), "get notification settings", "error", err)
|
||||
writeError(w, r, logger, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, logger, http.StatusOK, settings)
|
||||
}
|
||||
}
|
||||
|
||||
// putNotificationSettings replaces the notification preferences and the
|
||||
// reminder time, recording the session's actor subject as updated_by.
|
||||
func putNotificationSettings(logger *slog.Logger, svc *household.SettingsService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := auth.ActorFrom(r.Context())
|
||||
if !ok {
|
||||
logger.ErrorContext(r.Context(), "PUT /api/v1/settings/notifications without a session")
|
||||
writeError(w, r, logger, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
body, err := decodePatch[notificationsBody](http.MaxBytesReader(w, r.Body, maxSettingsBody))
|
||||
if err != nil {
|
||||
writeError(w, r, logger, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
want, err := body.settings()
|
||||
if err != nil {
|
||||
writeError(w, r, logger, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
settings, err := svc.UpdateNotifications(r.Context(), want, actor.Subject)
|
||||
var invalid *household.ValidationError
|
||||
if errors.As(err, &invalid) {
|
||||
writeError(w, r, logger, http.StatusBadRequest, "invalid_settings", invalid.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
logger.ErrorContext(r.Context(), "update notification settings", "error", err)
|
||||
writeError(w, r, logger, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, r, logger, http.StatusOK, settings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/household"
|
||||
)
|
||||
|
||||
const notificationsPath = "/api/v1/settings/notifications"
|
||||
|
||||
// seedPrefs is the seed notification preferences as GET answers them.
|
||||
var seedPrefs = []any{
|
||||
map[string]any{"event": "plan_ready", "push": true, "chat": true},
|
||||
map[string]any{"event": "list_ready", "push": true, "chat": true},
|
||||
map[string]any{"event": "day_of_reminder", "push": true, "chat": false},
|
||||
map[string]any{"event": "new_suggestions", "push": true, "chat": false},
|
||||
map[string]any{"event": "rotation_review", "push": true, "chat": false},
|
||||
}
|
||||
|
||||
func TestGetNotificationSettings(t *testing.T) {
|
||||
t.Parallel()
|
||||
router := newTestRouterWith(t, "dev", newTestSettings(t), newTestRunner(t))
|
||||
|
||||
rec, body := serve(t, router, signedIn(http.MethodGet, notificationsPath, nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body)
|
||||
}
|
||||
want := map[string]any{"prefs": seedPrefs, "reminder_time": "16:30"}
|
||||
if !reflect.DeepEqual(body, want) {
|
||||
t.Errorf("body = %v, want %v", body, want)
|
||||
}
|
||||
}
|
||||
|
||||
const allChanged = `{"prefs":[
|
||||
{"event":"plan_ready","push":false,"chat":true},
|
||||
{"event":"list_ready","push":true,"chat":false},
|
||||
{"event":"day_of_reminder","push":true,"chat":true},
|
||||
{"event":"new_suggestions","push":false,"chat":false},
|
||||
{"event":"rotation_review","push":false,"chat":true}
|
||||
],"reminder_time":"15:45"}`
|
||||
|
||||
func TestPutNotificationSettings(t *testing.T) {
|
||||
t.Parallel()
|
||||
settings := newTestSettings(t)
|
||||
router := newTestRouterWith(t, "dev", settings, newTestRunner(t))
|
||||
|
||||
var notified []household.Settings
|
||||
settings.Subscribe(func(s household.Settings) { notified = append(notified, s) })
|
||||
|
||||
// The events come in any order and are answered in screen order.
|
||||
rec, body := serve(t, router, signedIn(http.MethodPut, notificationsPath, strings.NewReader(`{"reminder_time":"15:45","prefs":[
|
||||
{"event":"rotation_review","push":false,"chat":true},
|
||||
{"event":"new_suggestions","push":false,"chat":false},
|
||||
{"event":"day_of_reminder","push":true,"chat":true},
|
||||
{"event":"list_ready","push":true,"chat":false},
|
||||
{"event":"plan_ready","push":false,"chat":true}
|
||||
]}`)))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body)
|
||||
}
|
||||
want := map[string]any{
|
||||
"prefs": []any{
|
||||
map[string]any{"event": "plan_ready", "push": false, "chat": true},
|
||||
map[string]any{"event": "list_ready", "push": true, "chat": false},
|
||||
map[string]any{"event": "day_of_reminder", "push": true, "chat": true},
|
||||
map[string]any{"event": "new_suggestions", "push": false, "chat": false},
|
||||
map[string]any{"event": "rotation_review", "push": false, "chat": true},
|
||||
},
|
||||
"reminder_time": "15:45",
|
||||
}
|
||||
if !reflect.DeepEqual(body, want) {
|
||||
t.Errorf("PUT body = %v, want %v", body, want)
|
||||
}
|
||||
if _, got := serve(t, router, signedIn(http.MethodGet, notificationsPath, nil)); !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("GET after PUT = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
// reminder_time is the household setting: there is one copy of it.
|
||||
_, hs := serve(t, router, signedIn(http.MethodGet, settingsPath, nil))
|
||||
if hs["reminder_time"] != "15:45" || hs["updated_by"] != testSession.Subject {
|
||||
t.Errorf("household settings after PUT = %v, want reminder_time 15:45 updated by %s", hs, testSession.Subject)
|
||||
}
|
||||
if len(notified) != 1 || notified[0].ReminderTime != "15:45" {
|
||||
t.Errorf("subscriber notified with %+v, want one change to 15:45", notified)
|
||||
}
|
||||
|
||||
// A household settings change to reminder_time is what GET answers.
|
||||
if rec, _ := serve(t, router, signedIn(http.MethodPatch, settingsPath, strings.NewReader(`{"reminder_time":"17:05"}`))); rec.Code != http.StatusOK {
|
||||
t.Fatalf("PATCH household status = %d: %s", rec.Code, rec.Body)
|
||||
}
|
||||
if _, got := serve(t, router, signedIn(http.MethodGet, notificationsPath, nil)); got["reminder_time"] != "17:05" {
|
||||
t.Errorf("GET reminder_time after PATCH household = %v, want 17:05", got["reminder_time"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutNotificationSettingsRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
settings := newTestSettings(t)
|
||||
router := newTestRouterWith(t, "dev", settings, newTestRunner(t))
|
||||
|
||||
const four = `{"event":"plan_ready","push":true,"chat":true},
|
||||
{"event":"list_ready","push":true,"chat":true},
|
||||
{"event":"day_of_reminder","push":true,"chat":true},
|
||||
{"event":"new_suggestions","push":true,"chat":true}`
|
||||
for _, tc := range []struct {
|
||||
name, body, code, message string
|
||||
}{
|
||||
{"bad time", strings.Replace(allChanged, "15:45", "24:00", 1), "invalid_settings", `reminder_time: invalid time "24:00"`},
|
||||
{"unpadded time", strings.Replace(allChanged, "15:45", "9:00", 1), "invalid_settings", `reminder_time: invalid time "9:00"`},
|
||||
{"missing event", `{"prefs":[` + four + `],"reminder_time":"16:30"}`, "invalid_settings", `prefs: event "rotation_review" is missing`},
|
||||
{"unknown event", `{"prefs":[` + four + `,{"event":"rotation_review","push":true,"chat":true},{"event":"weather","push":true,"chat":true}],"reminder_time":"16:30"}`, "invalid_settings", `prefs: unknown event "weather"`},
|
||||
{"duplicate event", `{"prefs":[` + four + `,{"event":"plan_ready","push":true,"chat":true}],"reminder_time":"16:30"}`, "invalid_settings", `prefs: event "plan_ready" is listed more than once`},
|
||||
{"unknown field", strings.Replace(allChanged, `"reminder_time"`, `"review_time":"09:00","reminder_time"`, 1), "invalid_request", `unknown field "review_time"`},
|
||||
{"unknown pref field", strings.Replace(allChanged, `"chat":true}`, `"chat":true,"email":true}`, 1), "invalid_request", `unknown field "email"`},
|
||||
{"missing reminder_time", `{"prefs":[]}`, "invalid_request", "prefs and reminder_time are required"},
|
||||
{"missing channel", strings.Replace(allChanged, `"push":false,"chat":true}`, `"push":false}`, 1), "invalid_request", "prefs[0]: event, push and chat are required"},
|
||||
{"null channel", strings.Replace(allChanged, `"chat":true}`, `"chat":null}`, 1), "invalid_request", "prefs[0]: event, push and chat are required"},
|
||||
{"null field", `{"prefs":null,"reminder_time":"16:30"}`, "invalid_request", "prefs: must not be null"},
|
||||
{"wrong type", strings.Replace(allChanged, `"push":false`, `"push":"no"`, 1), "invalid_request", "want a JSON bool"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec, body := serve(t, router, signedIn(http.MethodPut, notificationsPath, strings.NewReader(tc.body)))
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", rec.Code, rec.Body)
|
||||
}
|
||||
e, _ := body["error"].(map[string]any)
|
||||
if e["code"] != tc.code || !strings.Contains(e["message"].(string), tc.message) {
|
||||
t.Errorf("error = %v, want code %s with %q", e, tc.code, tc.message)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Nothing was changed.
|
||||
_, got := serve(t, router, signedIn(http.MethodGet, notificationsPath, nil))
|
||||
if want := (map[string]any{"prefs": seedPrefs, "reminder_time": "16:30"}); !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("GET after rejected PUTs = %v, want the seed %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutNotificationSettingsNeedsCSRF(t *testing.T) {
|
||||
t.Parallel()
|
||||
router := newTestRouterWith(t, "dev", newTestSettings(t), newTestRunner(t))
|
||||
|
||||
req := signedIn(http.MethodPut, notificationsPath, strings.NewReader(allChanged))
|
||||
req.Header.Del(CSRFHeader)
|
||||
if rec, _ := serve(t, router, req); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403: %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,8 @@ type RouteMounter interface {
|
||||
// has its client address and scheme resolved, honouring forwarded headers
|
||||
// only from a peer in trusted (see resolveOrigin). version is reported by
|
||||
// GET /health; auth mounts the /auth routes; sessions guards /api/v1 and
|
||||
// /media; settings serves /api/v1/settings/household; search serves
|
||||
// /media; settings serves /api/v1/settings/household and
|
||||
// /api/v1/settings/notifications; search serves
|
||||
// /api/v1/settings/recipe-search and its /test; ai serves
|
||||
// /api/v1/settings/ai, its /api-key, /verify, /models and /reset-prompt;
|
||||
// chatSvc serves GET and PUT /api/v1/settings/chat-webhook and its /test;
|
||||
@@ -130,6 +131,8 @@ func NewRouter(logger *slog.Logger, version string, trusted forwarded.Trusted, a
|
||||
apiV1.Get("/me", me(logger))
|
||||
apiV1.Get("/settings/household", getHouseholdSettings(logger, settings))
|
||||
apiV1.Patch("/settings/household", patchHouseholdSettings(logger, settings))
|
||||
apiV1.Get("/settings/notifications", getNotificationSettings(logger, settings))
|
||||
apiV1.Put("/settings/notifications", putNotificationSettings(logger, settings))
|
||||
apiV1.Get("/settings/recipe-search", getRecipeSearchSettings(logger, search))
|
||||
apiV1.Patch("/settings/recipe-search", patchRecipeSearchSettings(logger, search))
|
||||
apiV1.Post("/settings/recipe-search/test", postRecipeSearchTest(logger, search))
|
||||
|
||||
@@ -107,13 +107,16 @@ func newTestStore(t *testing.T) *store.Store {
|
||||
}
|
||||
|
||||
// newTestSettings returns a settings service over a migrated temp database
|
||||
// seeded with zone America/New_York.
|
||||
// seeded with zone America/New_York and the seed notification preferences.
|
||||
func newTestSettings(t *testing.T) *household.SettingsService {
|
||||
t.Helper()
|
||||
st := newTestStore(t)
|
||||
if err := household.SeedSettings(context.Background(), st, "America/New_York"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := household.SeedNotificationPrefs(context.Background(), st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return household.NewSettingsService(st)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user