Phase 6: write important school events to the Home Assistant calendar
Add the Home Assistant REST calendar client and the idempotent sync that writes important school events to Sam's Home Assistant calendar (FR-8). The school stays read-only; the only write is to the calendar (rule 7). - internal/calendar: HA REST client (states, create_event, get_events, delete_event) and the sync that selects important future events, adopts an existing event by its description marker, records the HA event id on the item, and records every attempt. - internal/store: migration 003 (items.ha_event_uid, items.ha_pushed_at and the append-only calendar_pushes table), candidates, mark-synced and the push log. - internal/parse: a school event is important; a routine class period is not. - cmd/school: `school calendar entities|status|push|events`. - web: an "Add to calendar" item action and a fail-loud calendar banner, so a failed write is never swallowed (FR-12). - scripts/calendar-push.sh, Makefile target, env example, docs and tests. The target is configurable (SCHOOL_HA_CALENDAR_ENTITY). Home Assistant has no non-Google writable calendar today, so the entity is asked on AUD-110. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
@@ -2,6 +2,7 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -31,6 +32,11 @@ var csrfRe = regexp.MustCompile(`name="csrf" value="([^"]+)"`)
|
||||
|
||||
// newTestServer builds the web handler against a fresh SQLite database.
|
||||
func newTestServer(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
return newTestServerCalendar(t, config.CalendarConfig{})
|
||||
}
|
||||
|
||||
// newTestServerCalendar is newTestServer with a Home Assistant calendar target.
|
||||
func newTestServerCalendar(t *testing.T, cal config.CalendarConfig) (*httptest.Server, *store.Store) {
|
||||
t.Helper()
|
||||
loc, err := time.LoadLocation("Australia/Sydney")
|
||||
if err != nil {
|
||||
@@ -58,6 +64,7 @@ func newTestServer(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
AppEnv: "test",
|
||||
Version: "test",
|
||||
Location: loc,
|
||||
Calendar: cal,
|
||||
}
|
||||
am, err := auth.New(cfg.SessionSecret, cfg.SessionTTL, false, cfg.AdminUsername, "", cfg.AdminPassword)
|
||||
if err != nil {
|
||||
@@ -307,3 +314,187 @@ func snippet(s string) string {
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// fakeHACalendar is a minimal Home Assistant calendar for the item-screen test.
|
||||
// It records created events so a read-back can prove the write.
|
||||
func fakeHACalendar(t *testing.T, failCreate bool) *httptest.Server {
|
||||
t.Helper()
|
||||
var events []map[string]any
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/services/calendar/create_event", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if failCreate {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"error": map[string]any{"code": "unknown_error", "message": "calendar is busy"},
|
||||
})
|
||||
return
|
||||
}
|
||||
events = append(events, map[string]any{
|
||||
"uid": "uid-1", "summary": body["summary"], "description": body["description"],
|
||||
"start_date_time": body["start_date_time"],
|
||||
})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"service_response": map[string]any{"calendar.school": map[string]any{"uid": "uid-1"}},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /api/services/calendar/get_events", func(w http.ResponseWriter, r *http.Request) {
|
||||
if events == nil {
|
||||
events = []map[string]any{}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"service_response": map[string]any{"calendar.school": map[string]any{"events": events}},
|
||||
})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// TestDashboardWarnsWhenTheCalendarIsNotConfigured proves the calendar half of
|
||||
// FR-12: an unconfigured target is stated, never silently skipped.
|
||||
func TestDashboardWarnsWhenTheCalendarIsNotConfigured(t *testing.T) {
|
||||
ts, _ := newTestServer(t)
|
||||
client := login(t, ts)
|
||||
body := getBody(t, client, ts.URL+"/")
|
||||
if !strings.Contains(body, "CALENDAR NOT CONFIGURED") {
|
||||
t.Errorf("dashboard does not warn about the calendar: %s", snippet(body))
|
||||
}
|
||||
if !strings.Contains(body, "SCHOOL_HA_URL") {
|
||||
t.Error("warning does not name the missing configuration")
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemCalendarPush proves the item screen writes one event and records it.
|
||||
func TestItemCalendarPush(t *testing.T) {
|
||||
ha := fakeHACalendar(t, false)
|
||||
ts, st := newTestServerCalendar(t, config.CalendarConfig{
|
||||
BaseURL: ha.URL, Token: "test-token", EntityID: "calendar.school", Timeout: 5 * time.Second,
|
||||
})
|
||||
ctx := context.Background()
|
||||
harry, _ := st.ChildByName(ctx, "Harry")
|
||||
due := time.Now().Add(4 * time.Hour).UTC().Truncate(time.Second)
|
||||
if _, _, err := st.UpsertItems(ctx, harry.ID, []store.Item{{
|
||||
Source: "compass", Type: "event", Title: "End of Year Senior Music Concert - HALL",
|
||||
Body: "End of Year Senior Music Concert - HALL - KSH", DueAt: &due,
|
||||
Importance: "high", ExternalRef: "e1",
|
||||
}}); err != nil {
|
||||
t.Fatalf("upsert: %v", err)
|
||||
}
|
||||
items, _ := st.ItemsForChild(ctx, harry.ID)
|
||||
id := items[0].ID
|
||||
|
||||
client := login(t, ts)
|
||||
detail := getBody(t, client, ts.URL+"/items/"+itoa(id))
|
||||
if !strings.Contains(detail, "Add to calendar") {
|
||||
t.Fatalf("item screen has no calendar action: %s", snippet(detail))
|
||||
}
|
||||
|
||||
resp, err := client.PostForm(ts.URL+"/items/"+itoa(id)+"/calendar",
|
||||
url.Values{"csrf": {csrfToken(t, detail)}})
|
||||
if err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
page, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("push status = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
if !strings.Contains(string(page), "Added to calendar.school") {
|
||||
t.Errorf("push page has no confirmation: %s", snippet(string(page)))
|
||||
}
|
||||
if !strings.Contains(string(page), "in the calendar") {
|
||||
t.Errorf("item screen does not show the calendar state: %s", snippet(string(page)))
|
||||
}
|
||||
|
||||
summary, err := st.CalendarPushSummary(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("summary: %v", err)
|
||||
}
|
||||
if summary.Total != 1 || summary.Failed != 0 {
|
||||
t.Fatalf("push log = %+v", summary)
|
||||
}
|
||||
ci, _ := st.CalendarItemByID(ctx, id)
|
||||
if ci == nil || ci.HAEventUID != "uid-1" {
|
||||
t.Fatalf("item does not carry the event id: %+v", ci)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemCalendarPushFailureIsLoud proves a failed write is shown and recorded.
|
||||
func TestItemCalendarPushFailureIsLoud(t *testing.T) {
|
||||
ha := fakeHACalendar(t, true)
|
||||
ts, st := newTestServerCalendar(t, config.CalendarConfig{
|
||||
BaseURL: ha.URL, Token: "test-token", EntityID: "calendar.school", Timeout: 5 * time.Second,
|
||||
})
|
||||
ctx := context.Background()
|
||||
harry, _ := st.ChildByName(ctx, "Harry")
|
||||
due := time.Now().Add(4 * time.Hour).UTC().Truncate(time.Second)
|
||||
if _, _, err := st.UpsertItems(ctx, harry.ID, []store.Item{{
|
||||
Source: "compass", Type: "event", Title: "Year 11 Assembly - HALL",
|
||||
DueAt: &due, Importance: "high", ExternalRef: "e1",
|
||||
}}); err != nil {
|
||||
t.Fatalf("upsert: %v", err)
|
||||
}
|
||||
items, _ := st.ItemsForChild(ctx, harry.ID)
|
||||
id := items[0].ID
|
||||
|
||||
client := login(t, ts)
|
||||
detail := getBody(t, client, ts.URL+"/items/"+itoa(id))
|
||||
resp, err := client.PostForm(ts.URL+"/items/"+itoa(id)+"/calendar",
|
||||
url.Values{"csrf": {csrfToken(t, detail)}})
|
||||
if err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
page, _ := io.ReadAll(resp.Body)
|
||||
if !strings.Contains(string(page), "Calendar write failed") {
|
||||
t.Errorf("failure is not shown on the page: %s", snippet(string(page)))
|
||||
}
|
||||
if !strings.Contains(string(page), "calendar is busy") {
|
||||
t.Errorf("failure loses the reason: %s", snippet(string(page)))
|
||||
}
|
||||
|
||||
summary, _ := st.CalendarPushSummary(ctx)
|
||||
if summary.Failed != 1 {
|
||||
t.Fatalf("failed write was not recorded: %+v", summary)
|
||||
}
|
||||
|
||||
// The dashboard repeats the failure, so it is visible without the item page.
|
||||
body := getBody(t, client, ts.URL+"/")
|
||||
if !strings.Contains(body, "CALENDAR WRITE FAILED") {
|
||||
t.Errorf("dashboard does not show the failed write: %s", snippet(body))
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemCalendarPushNeedsCSRF proves the write is not open to a forged post.
|
||||
func TestItemCalendarPushNeedsCSRF(t *testing.T) {
|
||||
ha := fakeHACalendar(t, false)
|
||||
ts, st := newTestServerCalendar(t, config.CalendarConfig{
|
||||
BaseURL: ha.URL, Token: "test-token", EntityID: "calendar.school", Timeout: 5 * time.Second,
|
||||
})
|
||||
ctx := context.Background()
|
||||
harry, _ := st.ChildByName(ctx, "Harry")
|
||||
due := time.Now().Add(4 * time.Hour).UTC()
|
||||
if _, _, err := st.UpsertItems(ctx, harry.ID, []store.Item{{
|
||||
Source: "compass", Type: "event", Title: "Concert", DueAt: &due,
|
||||
Importance: "high", ExternalRef: "e1",
|
||||
}}); err != nil {
|
||||
t.Fatalf("upsert: %v", err)
|
||||
}
|
||||
items, _ := st.ItemsForChild(ctx, harry.ID)
|
||||
|
||||
client := login(t, ts)
|
||||
resp, err := client.PostForm(ts.URL+"/items/"+itoa(items[0].ID)+"/calendar", url.Values{})
|
||||
if err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("tokenless push = %d, want 403", resp.StatusCode)
|
||||
}
|
||||
summary, _ := st.CalendarPushSummary(ctx)
|
||||
if summary.Total != 0 {
|
||||
t.Errorf("a tokenless push recorded a write: %+v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user