Notification preferences API and screen (1n) (Feature 19) (#166)
CI / ci (push) Successful in 5m53s
CI / ci (push) Successful in 5m53s
Co-authored-by: orchestrator-agent <20+orchestrator-agent@code.cubecraftcreations.com>
This commit was merged in pull request #166.
This commit is contained in:
@@ -133,6 +133,39 @@ func (q *Queries) InsertNotification(ctx context.Context, arg InsertNotification
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const listNotificationPrefs = `-- name: ListNotificationPrefs :many
|
||||
SELECT event, push, chat, created_at, updated_at FROM notification_prefs
|
||||
`
|
||||
|
||||
func (q *Queries) ListNotificationPrefs(ctx context.Context) ([]NotificationPref, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listNotificationPrefs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []NotificationPref
|
||||
for rows.Next() {
|
||||
var i NotificationPref
|
||||
if err := rows.Scan(
|
||||
&i.Event,
|
||||
&i.Push,
|
||||
&i.Chat,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markNotificationSent = `-- name: MarkNotificationSent :execrows
|
||||
UPDATE notification_outbox
|
||||
SET status = 'sent', attempts = attempts + 1, next_attempt_at = NULL, updated_at = ?1
|
||||
@@ -200,3 +233,31 @@ func (q *Queries) RetryNotification(ctx context.Context, arg RetryNotificationPa
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const updateNotificationPref = `-- name: UpdateNotificationPref :execrows
|
||||
UPDATE notification_prefs
|
||||
SET push = ?, chat = ?, updated_at = ?
|
||||
WHERE event = ?
|
||||
`
|
||||
|
||||
type UpdateNotificationPrefParams struct {
|
||||
Push int64
|
||||
Chat int64
|
||||
UpdatedAt string
|
||||
Event string
|
||||
}
|
||||
|
||||
// Sets which channels an event goes to; affects no row when the event has
|
||||
// no preference row.
|
||||
func (q *Queries) UpdateNotificationPref(ctx context.Context, arg UpdateNotificationPrefParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, updateNotificationPref,
|
||||
arg.Push,
|
||||
arg.Chat,
|
||||
arg.UpdatedAt,
|
||||
arg.Event,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
@@ -176,6 +176,7 @@ type Querier interface {
|
||||
// Regular, and every Quest log dinner no other plan for the week starting
|
||||
// from_week_start or later has on any day.
|
||||
ListDraftPool(ctx context.Context, arg ListDraftPoolParams) ([]Dinner, error)
|
||||
ListNotificationPrefs(ctx context.Context) ([]NotificationPref, error)
|
||||
// Every name the household turned down, oldest decision first: the name
|
||||
// each declined suggestion was suggested under, which renaming its dinner
|
||||
// does not change, and the name each dinner a Rotation check dropped
|
||||
@@ -300,6 +301,9 @@ type Querier interface {
|
||||
ToggleDinnerFavorite(ctx context.Context, arg ToggleDinnerFavoriteParams) (Dinner, error)
|
||||
// An unknown id returns sql.ErrNoRows.
|
||||
UpdateDinner(ctx context.Context, arg UpdateDinnerParams) (Dinner, error)
|
||||
// Sets which channels an event goes to; affects no row when the event has
|
||||
// no preference row.
|
||||
UpdateNotificationPref(ctx context.Context, arg UpdateNotificationPrefParams) (int64, error)
|
||||
// Creates the single row (id 1) or replaces every column except id and
|
||||
// created_at.
|
||||
UpsertAISettings(ctx context.Context, arg UpsertAISettingsParams) (AiSetting, error)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package household
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/db"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/store"
|
||||
)
|
||||
|
||||
// NotificationPref is which channels one event's notifications go to.
|
||||
type NotificationPref struct {
|
||||
Event string `json:"event"`
|
||||
Push bool `json:"push"`
|
||||
Chat bool `json:"chat"`
|
||||
}
|
||||
|
||||
// NotificationSettings are the household's notification preferences: one
|
||||
// NotificationPref for every event, in NotificationEvents order, and the
|
||||
// day-of dinner reminder's time, which is the household settings'
|
||||
// reminder_time.
|
||||
type NotificationSettings struct {
|
||||
Prefs []NotificationPref `json:"prefs"`
|
||||
ReminderTime string `json:"reminder_time"`
|
||||
}
|
||||
|
||||
// NotificationEvents are the events notification_prefs holds a row for, in
|
||||
// the order the Notifications screen lists them.
|
||||
var NotificationEvents = func() []string {
|
||||
events := make([]string, len(seedNotificationPrefs))
|
||||
for i, p := range seedNotificationPrefs {
|
||||
events[i] = p.Event
|
||||
}
|
||||
return events
|
||||
}()
|
||||
|
||||
// Notifications returns the notification preferences. A missing event row is
|
||||
// an error: SeedNotificationPrefs creates every one at boot.
|
||||
func (s *SettingsService) Notifications(ctx context.Context) (NotificationSettings, error) {
|
||||
return readNotifications(ctx, db.New(s.st.Reader))
|
||||
}
|
||||
|
||||
// UpdateNotifications validates ns, which must name every event of
|
||||
// NotificationEvents exactly once and a 24-hour HH:MM reminder time, and
|
||||
// replaces the notification preferences and reminder_time with it in one
|
||||
// transaction, recording updatedBy (which must not be empty). The new
|
||||
// household settings are published to every subscriber, as Update does. An
|
||||
// invalid ns is a *ValidationError and changes nothing.
|
||||
func (s *SettingsService) UpdateNotifications(ctx context.Context, ns NotificationSettings, updatedBy string) (NotificationSettings, error) {
|
||||
if updatedBy == "" {
|
||||
return NotificationSettings{}, errors.New("household: update notifications: no member to record as updated_by")
|
||||
}
|
||||
if err := ns.validate(); err != nil {
|
||||
return NotificationSettings{}, err
|
||||
}
|
||||
|
||||
s.updateMu.Lock()
|
||||
defer s.updateMu.Unlock()
|
||||
|
||||
var (
|
||||
row db.HouseholdSetting
|
||||
out NotificationSettings
|
||||
)
|
||||
err := s.st.WithTx(ctx, func(tx *sql.Tx) error {
|
||||
q := db.New(tx)
|
||||
now := store.Now().String()
|
||||
for _, p := range ns.Prefs {
|
||||
n, err := q.UpdateNotificationPref(ctx, db.UpdateNotificationPrefParams{
|
||||
Push: boolInt(p.Push), Chat: boolInt(p.Chat), UpdatedAt: now, Event: p.Event,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("household: update notification preference %s: %w", p.Event, err)
|
||||
}
|
||||
if n != 1 {
|
||||
return fmt.Errorf("household: no notification preference for %s", p.Event)
|
||||
}
|
||||
}
|
||||
var err error
|
||||
row, err = applyPatch(ctx, q, SettingsPatch{ReminderTime: &ns.ReminderTime}, updatedBy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out, err = readNotifications(ctx, q)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return NotificationSettings{}, err
|
||||
}
|
||||
|
||||
s.publish(fromRow(row))
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func readNotifications(ctx context.Context, q *db.Queries) (NotificationSettings, error) {
|
||||
rows, err := q.ListNotificationPrefs(ctx)
|
||||
if err != nil {
|
||||
return NotificationSettings{}, fmt.Errorf("household: read notification preferences: %w", err)
|
||||
}
|
||||
byEvent := make(map[string]db.NotificationPref, len(rows))
|
||||
for _, r := range rows {
|
||||
byEvent[r.Event] = r
|
||||
}
|
||||
prefs := make([]NotificationPref, len(NotificationEvents))
|
||||
for i, event := range NotificationEvents {
|
||||
r, ok := byEvent[event]
|
||||
if !ok {
|
||||
return NotificationSettings{}, fmt.Errorf("household: no notification preference for %s", event)
|
||||
}
|
||||
prefs[i] = NotificationPref{Event: event, Push: r.Push == 1, Chat: r.Chat == 1}
|
||||
}
|
||||
settings, err := q.GetHouseholdSettings(ctx)
|
||||
if err != nil {
|
||||
return NotificationSettings{}, fmt.Errorf("household: read settings: %w", err)
|
||||
}
|
||||
return NotificationSettings{Prefs: prefs, ReminderTime: settings.ReminderTime}, nil
|
||||
}
|
||||
|
||||
func (ns NotificationSettings) validate() error {
|
||||
var problems []Problem
|
||||
fail := func(field, reason string) {
|
||||
problems = append(problems, Problem{Field: field, Reason: reason})
|
||||
}
|
||||
known := make(map[string]bool, len(NotificationEvents))
|
||||
for _, event := range NotificationEvents {
|
||||
known[event] = true
|
||||
}
|
||||
seen := make(map[string]bool, len(ns.Prefs))
|
||||
for _, p := range ns.Prefs {
|
||||
switch {
|
||||
case !known[p.Event]:
|
||||
fail("prefs", fmt.Sprintf("unknown event %q", p.Event))
|
||||
case seen[p.Event]:
|
||||
fail("prefs", fmt.Sprintf("event %q is listed more than once", p.Event))
|
||||
}
|
||||
seen[p.Event] = true
|
||||
}
|
||||
for _, event := range NotificationEvents {
|
||||
if !seen[event] {
|
||||
fail("prefs", fmt.Sprintf("event %q is missing", event))
|
||||
}
|
||||
}
|
||||
if !clockTime.MatchString(ns.ReminderTime) {
|
||||
fail("reminder_time", fmt.Sprintf("invalid time %q (want 24-hour HH:MM, 00:00-23:59)", ns.ReminderTime))
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return &ValidationError{Problems: problems}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func boolInt(b bool) int64 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -187,56 +187,9 @@ func (s *SettingsService) Update(ctx context.Context, patch SettingsPatch, updat
|
||||
|
||||
var row db.HouseholdSetting
|
||||
err := s.st.WithTx(ctx, func(tx *sql.Tx) error {
|
||||
q := db.New(tx)
|
||||
cur, err := q.GetHouseholdSettings(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("household: read settings: %w", err)
|
||||
}
|
||||
p := db.UpsertHouseholdSettingsParams{
|
||||
Timezone: cur.Timezone,
|
||||
DinnerTime: cur.DinnerTime,
|
||||
ReminderTime: cur.ReminderTime,
|
||||
ReviewTime: cur.ReviewTime,
|
||||
PlanDraftDow: cur.PlanDraftDow,
|
||||
PlanDraftTime: cur.PlanDraftTime,
|
||||
SuggestionsDow: cur.SuggestionsDow,
|
||||
SuggestionsTime: cur.SuggestionsTime,
|
||||
ChatAutosendDow: cur.ChatAutosendDow,
|
||||
ChatAutosendTime: cur.ChatAutosendTime,
|
||||
OnboardingCompletedAt: cur.OnboardingCompletedAt,
|
||||
UpdatesSeenAt: cur.UpdatesSeenAt,
|
||||
UpdatedBy: sql.NullString{String: updatedBy, Valid: true},
|
||||
CreatedAt: cur.CreatedAt,
|
||||
UpdatedAt: store.Now().String(),
|
||||
}
|
||||
setString(&p.Timezone, patch.Timezone)
|
||||
setString(&p.DinnerTime, patch.DinnerTime)
|
||||
setString(&p.ReminderTime, patch.ReminderTime)
|
||||
setString(&p.ReviewTime, patch.ReviewTime)
|
||||
setDow(&p.PlanDraftDow, patch.PlanDraftDow)
|
||||
setString(&p.PlanDraftTime, patch.PlanDraftTime)
|
||||
setDow(&p.SuggestionsDow, patch.SuggestionsDow)
|
||||
setString(&p.SuggestionsTime, patch.SuggestionsTime)
|
||||
setDow(&p.ChatAutosendDow, patch.ChatAutosendDow)
|
||||
setString(&p.ChatAutosendTime, patch.ChatAutosendTime)
|
||||
if patch.OnboardingCompleted != nil && !p.OnboardingCompletedAt.Valid {
|
||||
n, err := q.CountRegularDinners(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("household: count Regulars: %w", err)
|
||||
}
|
||||
if n < MinRegulars {
|
||||
return &ValidationError{Problems: []Problem{{
|
||||
Field: "onboarding_completed",
|
||||
Reason: fmt.Sprintf("add at least %d Regulars first (have %d)", MinRegulars, n),
|
||||
}}}
|
||||
}
|
||||
p.OnboardingCompletedAt = sql.NullString{String: p.UpdatedAt, Valid: true}
|
||||
}
|
||||
row, err = q.UpsertHouseholdSettings(ctx, p)
|
||||
if err != nil {
|
||||
return fmt.Errorf("household: update settings: %w", err)
|
||||
}
|
||||
return nil
|
||||
var err error
|
||||
row, err = applyPatch(ctx, db.New(tx), patch, updatedBy)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
@@ -247,8 +200,62 @@ func (s *SettingsService) Update(ctx context.Context, patch SettingsPatch, updat
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
// applyPatch applies a validated patch to the household settings row in q's
|
||||
// transaction, recording updatedBy, and returns the new row.
|
||||
func applyPatch(ctx context.Context, q *db.Queries, patch SettingsPatch, updatedBy string) (db.HouseholdSetting, error) {
|
||||
cur, err := q.GetHouseholdSettings(ctx)
|
||||
if err != nil {
|
||||
return db.HouseholdSetting{}, fmt.Errorf("household: read settings: %w", err)
|
||||
}
|
||||
p := db.UpsertHouseholdSettingsParams{
|
||||
Timezone: cur.Timezone,
|
||||
DinnerTime: cur.DinnerTime,
|
||||
ReminderTime: cur.ReminderTime,
|
||||
ReviewTime: cur.ReviewTime,
|
||||
PlanDraftDow: cur.PlanDraftDow,
|
||||
PlanDraftTime: cur.PlanDraftTime,
|
||||
SuggestionsDow: cur.SuggestionsDow,
|
||||
SuggestionsTime: cur.SuggestionsTime,
|
||||
ChatAutosendDow: cur.ChatAutosendDow,
|
||||
ChatAutosendTime: cur.ChatAutosendTime,
|
||||
OnboardingCompletedAt: cur.OnboardingCompletedAt,
|
||||
UpdatesSeenAt: cur.UpdatesSeenAt,
|
||||
UpdatedBy: sql.NullString{String: updatedBy, Valid: true},
|
||||
CreatedAt: cur.CreatedAt,
|
||||
UpdatedAt: store.Now().String(),
|
||||
}
|
||||
setString(&p.Timezone, patch.Timezone)
|
||||
setString(&p.DinnerTime, patch.DinnerTime)
|
||||
setString(&p.ReminderTime, patch.ReminderTime)
|
||||
setString(&p.ReviewTime, patch.ReviewTime)
|
||||
setDow(&p.PlanDraftDow, patch.PlanDraftDow)
|
||||
setString(&p.PlanDraftTime, patch.PlanDraftTime)
|
||||
setDow(&p.SuggestionsDow, patch.SuggestionsDow)
|
||||
setString(&p.SuggestionsTime, patch.SuggestionsTime)
|
||||
setDow(&p.ChatAutosendDow, patch.ChatAutosendDow)
|
||||
setString(&p.ChatAutosendTime, patch.ChatAutosendTime)
|
||||
if patch.OnboardingCompleted != nil && !p.OnboardingCompletedAt.Valid {
|
||||
n, err := q.CountRegularDinners(ctx)
|
||||
if err != nil {
|
||||
return db.HouseholdSetting{}, fmt.Errorf("household: count Regulars: %w", err)
|
||||
}
|
||||
if n < MinRegulars {
|
||||
return db.HouseholdSetting{}, &ValidationError{Problems: []Problem{{
|
||||
Field: "onboarding_completed",
|
||||
Reason: fmt.Sprintf("add at least %d Regulars first (have %d)", MinRegulars, n),
|
||||
}}}
|
||||
}
|
||||
p.OnboardingCompletedAt = sql.NullString{String: p.UpdatedAt, Valid: true}
|
||||
}
|
||||
row, err := q.UpsertHouseholdSettings(ctx, p)
|
||||
if err != nil {
|
||||
return db.HouseholdSetting{}, fmt.Errorf("household: update settings: %w", err)
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// Subscribe registers fn to receive the new settings after every successful
|
||||
// Update. fn runs synchronously on the updating goroutine, so it must return
|
||||
// Update and UpdateNotifications. fn runs synchronously on the updating goroutine, so it must return
|
||||
// promptly and must not call Update. The returned function unsubscribes fn.
|
||||
func (s *SettingsService) Subscribe(fn func(Settings)) (unsubscribe func()) {
|
||||
s.subsMu.Lock()
|
||||
|
||||
@@ -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