Wire plan_ready, list_ready, new_suggestions and Send to Google Chat
CI / ci (push) Failing after 5m48s
CI / ci (pull_request) Successful in 6m58s

Connect the features to the notification outbox so real events notify,
each stored by the new notify.EmitTx in the transaction of the change it
is about (Wake after commit):

- plan_ready:{weekStart} (/plan) when a draft job stores the AI's draft;
  a redraft shares the key and a manual swap never emits. The title reads
  "Next week's plan is ready" for the coming week.
- list_ready:{weekStart} (/plan/shopping) when a week's Supply run is
  first created, by generate or after Push to Calendar.
- new_suggestions:{batchId} (/discover) when a scheduled or manual batch
  ends done with cards; replenish batches never notify.
- plan.Service.EmitDayOfReminder(date) emits day_of_reminder:{date} for
  the Feature 20 scheduler.

Add POST /api/v1/shopping/{weekStart}/send-chat: shopping.SendToChat posts
the dinners with needed items and a link through chat.PostSupplyRun,
records sent_to_chat_at, and is idempotent per week unless
{"resend": true}. The Supply run's Send to Google Chat button calls it
("Send again" once sent) and shows failures in an ErrorBanner; the unused
Unavailable placeholder is removed.

Task: f0cd9d50-9c11-41be-a945-7bae9f5f28a4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 15:42:16 -04:00
co-authored by Claude Opus 5.5
parent bbe031ec8d
commit 45c4f8a803
37 changed files with 1477 additions and 252 deletions
+72 -8
View File
@@ -53,6 +53,9 @@ var (
// ErrUnreachable is wrapped by the error of a post Google Chat did not
// answer.
ErrUnreachable = errors.New("chat: Google Chat did not answer")
// ErrRefused is matched by the *RefusedError of a post Google Chat
// answered with a status other than 2xx.
ErrRefused = errors.New("chat: Google Chat refused the message")
// ErrWebhookChanged is returned by Test when the webhook was replaced
// while the test message was being sent; nothing is recorded.
ErrWebhookChanged = errors.New("chat: the Google Chat webhook changed during the test")
@@ -78,6 +81,24 @@ type TestResult struct {
Settings
}
// RefusedError is a post Google Chat answered with Status, not 2xx. It
// matches ErrRefused.
type RefusedError struct {
Status int
}
func (e *RefusedError) Error() string {
return fmt.Sprintf("%v with status %d", ErrRefused, e.Status)
}
func (e *RefusedError) Unwrap() error { return ErrRefused }
// Retryable reports whether posting again may succeed: Google Chat was
// busy (429) or failing (5xx), rather than refusing the message.
func (e *RefusedError) Retryable() bool {
return e.Status == http.StatusTooManyRequests || e.Status >= 500
}
// Problem is one invalid field of a webhook update, named by its JSON key.
type Problem struct {
Field string
@@ -362,22 +383,65 @@ func (s *Service) messageOf(p notify.Payload) (message, error) {
if !carded[p.Event] {
return msg, nil
}
ref, err := url.Parse(p.URL)
if err != nil || ref.Scheme != "" || ref.Host != "" || !strings.HasPrefix(p.URL, "/") {
return message{}, fmt.Errorf("payload url %q is not an app path", p.URL)
c, err := s.openCard(string(p.Event), p.Title, p.Body, p.URL)
if err != nil {
return message{}, err
}
msg.CardsV2 = []cardV2{c}
return msg, nil
}
// openCard is a card headed title and subtitle whose "Open" button links
// to the app path under the public URL.
func (s *Service) openCard(id, title, subtitle, path string) (cardV2, error) {
ref, err := url.Parse(path)
if err != nil || ref.Scheme != "" || ref.Host != "" || !strings.HasPrefix(path, "/") {
return cardV2{}, fmt.Errorf("payload url %q is not an app path", path)
}
link := s.publicURL.ResolveReference(ref)
msg.CardsV2 = []cardV2{{
CardID: string(p.Event),
return cardV2{
CardID: id,
Card: card{
Header: cardHeader{Title: p.Title, Subtitle: p.Body},
Header: cardHeader{Title: title, Subtitle: subtitle},
Sections: []cardSection{{Widgets: []cardWidget{{ButtonList: buttonList{Buttons: []button{{
Text: "Open",
OnClick: onClick{OpenLink: openLink{URL: link.String()}},
}}}}}}},
},
}}
return msg, nil
}, nil
}
// PostSupplyRun posts the Supply run of the week starting on week, named
// name, with groups, to the stored webhook in the week's thread: its
// SupplyRunText and a card whose "Open" button links to that week's Supply
// run. No webhook stored is ErrNotConfigured; a post Google Chat does not
// answer wraps ErrUnreachable, and one it answers with a status other than
// 2xx is a *RefusedError.
func (s *Service) PostSupplyRun(ctx context.Context, week store.LocalDate, name string, groups []SupplyRunGroup) error {
row, err := db.New(s.st.Reader).GetChatSettings(ctx)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotConfigured
}
if err != nil {
return fmt.Errorf("chat: read chat settings: %w", err)
}
hook, err := s.open(row)
if err != nil {
return err
}
path := "/plan/shopping?" + url.Values{"week": {week.String()}}.Encode()
c, err := s.openCard("supply_run", "Supply run · "+name, "", path)
if err != nil {
return err
}
status, err := s.post(ctx, hook, message{Text: SupplyRunText(name, groups), CardsV2: []cardV2{c}}, ThreadKey(week))
if err != nil {
return err
}
if status < 200 || status >= 300 {
return &RefusedError{Status: status}
}
return nil
}
// post sends msg to hook, in thread when it is not empty, and returns the
+61 -3
View File
@@ -304,7 +304,7 @@ func TestSendThreadsByWeek(t *testing.T) {
}
week := mustDate(t, "2026-10-12")
events := []notify.Event{
PlanReady(week, []string{"Tacos", "Bolognese", "Tikka masala", "A", "B", "C", "D"}),
PlanReady(week, week, []string{"Tacos", "Bolognese", "Tikka masala", "A", "B", "C", "D"}),
ListReady(week, 19, 7),
DayOfReminder(mustDate(t, "2026-10-18"), "01J9DINNER", "Tacos"),
NewSuggestions("01J9BATCH", week, []string{"Pho"}),
@@ -383,7 +383,7 @@ func TestSendClassifiesStatus(t *testing.T) {
if _, err := svc.Put(ctx, testHook, "Family"); err != nil {
t.Fatal(err)
}
m := notify.Message{Payload: payloadOf(PlanReady(mustDate(t, "2026-10-12"), []string{"Tacos"}))}
m := notify.Message{Payload: payloadOf(PlanReady(mustDate(t, "2026-10-12"), mustDate(t, "2026-10-12"), []string{"Tacos"}))}
for _, tc := range []struct {
status int
ok, permanent bool
@@ -464,7 +464,7 @@ func TestOutboxRowsFollowClassification(t *testing.T) {
week := mustDate(t, "2026-10-12")
f.setStatus(http.StatusBadRequest)
planned := PlanReady(week, []string{"Tacos"})
planned := PlanReady(week, week, []string{"Tacos"})
if err := notifier.Emit(ctx, planned); err != nil {
t.Fatal(err)
}
@@ -528,3 +528,61 @@ func (b *syncBuffer) String() string {
defer b.mu.Unlock()
return b.buf.String()
}
func TestPostSupplyRun(t *testing.T) {
t.Parallel()
ctx := context.Background()
f := newFakeChat(t)
svc, _ := newTestService(t, f)
week := mustDate(t, "2026-10-12")
groups := []SupplyRunGroup{{Dinner: "Tacos", Items: []SupplyRunItem{{Name: "tortillas"}}}}
if err := svc.PostSupplyRun(ctx, week, "Week 42 · Oct 12 – 18", groups); !errors.Is(err, ErrNotConfigured) {
t.Fatalf("PostSupplyRun without a webhook = %v, want ErrNotConfigured", err)
}
if _, err := svc.Put(ctx, testHook, "Family"); err != nil {
t.Fatal(err)
}
if err := svc.PostSupplyRun(ctx, week, "Week 42 · Oct 12 – 18", groups); err != nil {
t.Fatal(err)
}
reqs := f.requests()
if len(reqs) != 1 {
t.Fatalf("Chat got %d requests, want 1", len(reqs))
}
r := reqs[0]
if r.Query.Get("threadKey") != "mealquest-week-2026-W42" || r.Query.Get("messageReplyOption") != replyOption {
t.Errorf("threading = %v", r.Query)
}
if want := SupplyRunText("Week 42 · Oct 12 – 18", groups); r.Body["text"] != want {
t.Errorf("text = %q, want %q", r.Body["text"], want)
}
data, _ := json.Marshal(r.Body["cardsV2"])
var cards []cardV2
if err := json.Unmarshal(data, &cards); err != nil || len(cards) != 1 {
t.Fatalf("cardsV2 = %s, %v", data, err)
}
buttons := cards[0].Card.Sections[0].Widgets[0].ButtonList.Buttons
if cards[0].Card.Header.Title != "Supply run · Week 42 · Oct 12 – 18" || len(buttons) != 1 ||
buttons[0].OnClick.OpenLink.URL != "https://mealquest.example/plan/shopping?week=2026-10-12" {
t.Errorf("card = %s, want an Open button to the week's Supply run", data)
}
f.setStatus(http.StatusForbidden)
err := svc.PostSupplyRun(ctx, week, "Week 42 · Oct 12 – 18", groups)
if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "403") {
t.Errorf("PostSupplyRun answered 403 = %v, want ErrRefused with the status", err)
}
if err != nil {
assertNoSecret(t, "refused error", err.Error())
}
f.srv.Close()
err = svc.PostSupplyRun(ctx, week, "Week 42 · Oct 12 – 18", groups)
if !errors.Is(err, ErrUnreachable) {
t.Errorf("PostSupplyRun unanswered = %v, want ErrUnreachable", err)
}
if err != nil {
assertNoSecret(t, "unreachable error", err.Error())
}
}
+97
View File
@@ -0,0 +1,97 @@
// Package chattest provides a fake Google Chat incoming webhook for tests
// of the features that post to Google Chat: an httptest server that
// records each post and answers a status the test sets, reached through a
// transport that sends chat.googleapis.com requests to it.
package chattest
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
)
// Webhook is a valid Google Chat incoming webhook URL to store.
const Webhook = "https://chat.googleapis.com/v1/spaces/AAQA1b2C3d4/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=q0Lz3kV9Yw8pXcRtN2bHsJdFgA7uEmKiOlP1nZxQ%3D"
// Post is one message the fake received.
type Post struct {
// Query is the request's query: key, token and any threading.
Query url.Values
// Body is the decoded JSON message.
Body map[string]any
}
// Text is the post's text.
func (p Post) Text() string {
s, _ := p.Body["text"].(string)
return s
}
// Chat is a fake Google Chat endpoint. It answers 200 until SetStatus.
type Chat struct {
srv *httptest.Server
mu sync.Mutex
status int
posts []Post
}
// New starts a fake Google Chat endpoint, closed when the test ends.
func New(t *testing.T) *Chat {
t.Helper()
c := &Chat{status: http.StatusOK}
c.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
var body map[string]any
if err := json.Unmarshal(data, &body); err != nil {
t.Errorf("Google Chat post body %q: %v", data, err)
}
c.mu.Lock()
c.posts = append(c.posts, Post{Query: r.URL.Query(), Body: body})
status := c.status
c.mu.Unlock()
w.WriteHeader(status)
}))
t.Cleanup(c.srv.Close)
return c
}
// Transport sends every request to the fake, as if it were
// chat.googleapis.com.
func (c *Chat) Transport() http.RoundTripper {
return transport{c}
}
type transport struct{ c *Chat }
func (tr transport) RoundTrip(req *http.Request) (*http.Response, error) {
target, err := url.Parse(tr.c.srv.URL)
if err != nil {
return nil, err
}
out := req.Clone(req.Context())
out.URL.Scheme, out.URL.Host = target.Scheme, target.Host
return http.DefaultTransport.RoundTrip(out)
}
// SetStatus makes the fake answer status from now on.
func (c *Chat) SetStatus(status int) {
c.mu.Lock()
defer c.mu.Unlock()
c.status = status
}
// Close stops the fake, so posts get no answer.
func (c *Chat) Close() {
c.srv.Close()
}
// Posts returns the messages received so far, in order.
func (c *Chat) Posts() []Post {
c.mu.Lock()
defer c.mu.Unlock()
return append([]Post(nil), c.posts...)
}
+74 -4
View File
@@ -3,6 +3,7 @@ package chat
import (
"fmt"
"strings"
"time"
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/household"
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify"
@@ -34,13 +35,16 @@ var actions = map[notify.EventType]string{
// button.
var carded = map[notify.EventType]bool{notify.PlanReady: true, notify.ListReady: true}
// PlanReady is the plan_ready event of the week starting on week, naming
// its dinners in plan order.
func PlanReady(week store.LocalDate, dinners []string) notify.Event {
// PlanReady is the plan_ready event of the week starting on week, drafted
// in the week starting on thisWeek, naming its dinners in plan order. Its
// title names the week as seen from thisWeek: "Next week's plan is ready",
// "This week's plan is ready", or "The plan for the week of Oct 26 is
// ready" for any other week.
func PlanReady(week, thisWeek store.LocalDate, dinners []string) notify.Event {
return notify.Event{
Type: notify.PlanReady,
Key: string(notify.PlanReady) + ":" + week.String(),
Title: "This week's plan is ready",
Title: planTitle(week, thisWeek),
Body: nameList(dinners),
URL: "/plan",
Week: week,
@@ -100,6 +104,72 @@ func RotationReview(dinnerID, name string, week store.LocalDate) notify.Event {
}
}
// SupplyRunItem is a Supply run item still needed, as sent to Google Chat;
// Qty is empty when the recipe gives none.
type SupplyRunItem struct {
Name string
Qty string
}
// SupplyRunGroup is one dinner of a Supply run sent to Google Chat, with
// its items still needed.
type SupplyRunGroup struct {
Dinner string
Items []SupplyRunItem
}
// SupplyRunText is the Google Chat message of the Supply run named name
// (its title, or its week label until it has one): each dinner with items
// still needed in bold, its items one per line, and the call to action.
//
// Supply run · Week 42 · Oct 12 – 18
//
// *Tacos*
// • ground beef — 1 lb
// • tortillas
//
// Open the Supply run →
//
// A Supply run with nothing still needed says so.
func SupplyRunText(name string, groups []SupplyRunGroup) string {
var b strings.Builder
b.WriteString("Supply run · " + name)
listed := false
for _, g := range groups {
if len(g.Items) == 0 {
continue
}
listed = true
b.WriteString("\n\n*" + g.Dinner + "*")
for _, it := range g.Items {
b.WriteString("\n• " + it.Name)
if it.Qty != "" {
b.WriteString(" — " + it.Qty)
}
}
}
if !listed {
b.WriteString("\n\nNothing left to buy.")
}
b.WriteString("\n\n" + actions[notify.ListReady] + " →")
return b.String()
}
// planTitle is the plan_ready title of the week starting on week, seen
// from the week starting on thisWeek.
func planTitle(week, thisWeek store.LocalDate) string {
y, m, d := thisWeek.Date()
next := store.LocalDateOf(time.Date(y, m, d+7, 0, 0, 0, 0, time.UTC))
switch week {
case thisWeek:
return "This week's plan is ready"
case next:
return "Next week's plan is ready"
}
_, m, d = week.Date()
return fmt.Sprintf("The plan for the week of %s %d is ready", m.String()[:3], d)
}
// Text is the Google Chat message of p: its title, its body after a colon
// and the event's call to action with an arrow.
func Text(p notify.Payload) string {
+39 -2
View File
@@ -36,7 +36,7 @@ func TestMessages(t *testing.T) {
}{
{
name: "plan ready",
ev: PlanReady(week, []string{"Tacos", "Bolognese", "Tikka masala", "Lemon orzo", "Bibimbap", "Shakshuka", "Chili"}),
ev: PlanReady(week, week, []string{"Tacos", "Bolognese", "Tikka masala", "Lemon orzo", "Bibimbap", "Shakshuka", "Chili"}),
key: "plan_ready:2026-10-12",
url: "/plan",
week: "2026-10-12",
@@ -46,7 +46,7 @@ func TestMessages(t *testing.T) {
},
{
name: "plan ready with three dinners",
ev: PlanReady(week, []string{"Tacos", "Bolognese", "Tikka masala"}),
ev: PlanReady(week, week, []string{"Tacos", "Bolognese", "Tikka masala"}),
key: "plan_ready:2026-10-12",
url: "/plan",
week: "2026-10-12",
@@ -54,6 +54,26 @@ func TestMessages(t *testing.T) {
body: "Tacos, Bolognese, Tikka masala",
chatT: "This week's plan is ready: Tacos, Bolognese, Tikka masala. Open the plan →",
},
{
name: "plan ready for next week",
ev: PlanReady(week, mustDate(t, "2026-10-05"), []string{"Tacos", "Bolognese", "Tikka masala", "Lemon orzo"}),
key: "plan_ready:2026-10-12",
url: "/plan",
week: "2026-10-12",
title: "Next week's plan is ready",
body: "Tacos, Bolognese, Tikka masala + 1 more",
chatT: "Next week's plan is ready: Tacos, Bolognese, Tikka masala + 1 more. Open the plan →",
},
{
name: "plan ready for a later week",
ev: PlanReady(mustDate(t, "2026-10-26"), mustDate(t, "2026-10-05"), []string{"Tacos"}),
key: "plan_ready:2026-10-26",
url: "/plan",
week: "2026-10-26",
title: "The plan for the week of Oct 26 is ready",
body: "Tacos",
chatT: "The plan for the week of Oct 26 is ready: Tacos. Open the plan →",
},
{
name: "list ready",
ev: ListReady(week, 19, 7),
@@ -115,6 +135,23 @@ func TestMessages(t *testing.T) {
}
}
func TestSupplyRunText(t *testing.T) {
t.Parallel()
got := SupplyRunText("Week 42 · Oct 12 – 18", []SupplyRunGroup{
{Dinner: "Tacos", Items: []SupplyRunItem{{Name: "ground beef", Qty: "1 lb"}, {Name: "tortillas"}}},
{Dinner: "Bolognese"},
{Dinner: "Pho", Items: []SupplyRunItem{{Name: "rice noodles", Qty: "200 g"}}},
})
want := "Supply run · Week 42 · Oct 12 – 18\n\n*Tacos*\n• ground beef — 1 lb\n• tortillas\n\n*Pho*\n• rice noodles — 200 g\n\nOpen the Supply run →"
if got != want {
t.Errorf("SupplyRunText =\n%s\nwant\n%s", got, want)
}
got = SupplyRunText("Cozy week", []SupplyRunGroup{{Dinner: "Tacos"}})
if want := "Supply run · Cozy week\n\nNothing left to buy.\n\nOpen the Supply run →"; got != want {
t.Errorf("SupplyRunText with nothing needed = %q, want %q", got, want)
}
}
func TestTextWithoutBody(t *testing.T) {
t.Parallel()
got := Text(notify.Payload{Event: notify.PlanReady, Title: "This week's plan is ready", URL: "/plan"})