Phase 6b/7b: per-child decoded periods, separate brief blocks, idempotent calendar (AUD-119)

- Parse each child's own "Today" day widget for the timetable (FR-16); drop the
  school-wide week calendar's lesson grid and clean the leaked routine rows.
- Add the editable codes map (FR-17): subjects, rooms, teachers and period
  labels, seeded, an unknown code falls back to the raw code; `school codes` CLI.
- Brief: Finn's block first, then Harry's, four sections always present (FR-9);
  periods decoded into plain English; the undated tail is one counted line (FR-18).
- Calendar: write periods + work due + work overdue + major events, per child,
  on every pass. Identity is the stable per-item key, so a re-run never re-inserts
  (FR-8). morning-brief.sh now runs scan -> calendar push -> notify.
- Day-widget labels are 12-hour: 1-6 read as PM, fixing afternoon periods.

Proven live on .13: image 0.6.2-phase6b7b; both children's briefs decoded and
separate; 35 events in calendar.school; runs 2 and 3 of the scan added nothing.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-10-16 10:25:55 +11:00
parent 4950755b3d
commit 047af0f31d
40 changed files with 2049 additions and 160 deletions

View File

@@ -125,14 +125,11 @@ func calendarStatus(args []string) {
os.Exit(1)
}
now := time.Now().In(cfg.Location)
candidates, err := st.CalendarCandidates(ctx, nil, nil, calendar.StartOfDay(now), 0)
pendingEvents, err := calendar.Pending(ctx, st, calendar.Options{Now: now})
if err != nil {
fmt.Fprintln(os.Stderr, "school calendar:", err)
os.Exit(1)
}
// Count events, not rows: a school-wide event is stored against each
// child but written once.
pendingEvents := len(calendar.GroupDuplicates(candidates))
if asJSON {
out := struct {
@@ -174,7 +171,7 @@ func calendarStatus(args []string) {
} else {
fmt.Printf("reachable yes\n")
}
fmt.Printf("pending events %d (important, not in the calendar yet)\n", pendingEvents)
fmt.Printf("pending events %d (periods + due work + overdue + school events, not in the calendar yet)\n", pendingEvents)
fmt.Printf("pushes %d (%d failed)\n", summary.Total, summary.Failed)
if summary.Last != nil {
state := "ok"
@@ -272,7 +269,11 @@ func printCalendarResult(res calendar.Result, loc *time.Location) {
if uid == "" {
uid = "-"
}
fmt.Printf(" item %-5d %-6s %-10s %-45s uid=%s\n", ev.ItemID, ev.Child, start, truncate(ev.Title, 45), uid)
kind := string(ev.Kind)
if kind == "" {
kind = "event"
}
fmt.Printf(" item %-5d %-8s %-6s %-10s %-45s uid=%s\n", ev.ItemID, kind, ev.Child, start, truncate(ev.Title, 45), uid)
}
for _, msg := range res.Errors {
fmt.Fprintf(os.Stderr, "FAILED: %s\n", msg)
@@ -285,9 +286,11 @@ func calendarEvents(args []string) {
fs := flag.NewFlagSet("calendar events", flag.ContinueOnError)
var (
days int
past int
asJSON bool
)
fs.IntVar(&days, "days", 14, "how many days ahead to read")
fs.IntVar(&past, "past", 1, "how many days back to read (overdue work sits in the past)")
fs.BoolVar(&asJSON, "json", false, "print the events as JSON")
_ = fs.Parse(args)
@@ -302,8 +305,9 @@ func calendarEvents(args []string) {
defer st.Close()
now := time.Now().In(cfg.Location)
start := now.AddDate(0, 0, -past)
end := now.AddDate(0, 0, days)
events, err := client.Events(ctx, now.Add(-24*time.Hour), end)
events, err := client.Events(ctx, start, end)
if err != nil {
fmt.Fprintln(os.Stderr, "school calendar:", err)
os.Exit(1)
@@ -321,7 +325,7 @@ func calendarEvents(args []string) {
if len(events) == 0 {
fmt.Printf("no events on %s between %s and %s\n",
cfg.Calendar.EntityID,
now.Format("2006-01-02 15:04"),
start.Format("2006-01-02 15:04"),
end.Format("2006-01-02 15:04"))
return
}

160
cmd/school/codes.go Normal file
View File

@@ -0,0 +1,160 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"text/tabwriter"
"gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/config"
"gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/store"
)
// codesCommand is the `school codes` entry point: the editable decode map for
// Compass periods (AGENTS.md §4 FR-17). An unknown code renders as the raw
// code, so a missing entry is safe but unreadable; this is how Sam corrects it.
func codesCommand(args []string) {
if len(args) == 0 {
usage("school codes list [--kind KIND] | set --kind KIND --code CODE --name NAME | delete --kind KIND --code CODE")
}
switch args[0] {
case "list":
codesList(args[1:])
case "set":
codesSet(args[1:])
case "delete":
codesDelete(args[1:])
default:
usage("school codes list | set | delete")
}
}
func openCodes(ctx context.Context) (*store.Store, error) {
cfg, err := config.LoadDB()
if err != nil {
return nil, err
}
st, err := store.Open(cfg.DBPath)
if err != nil {
return nil, err
}
if err := st.Migrate(ctx); err != nil {
_ = st.Close()
return nil, err
}
if err := st.SeedCodes(ctx); err != nil {
_ = st.Close()
return nil, err
}
return st, nil
}
func codesList(args []string) {
fs := flag.NewFlagSet("codes list", flag.ContinueOnError)
var (
kind string
asJSON bool
)
fs.StringVar(&kind, "kind", "", "limit to subject, room, teacher or period")
fs.BoolVar(&asJSON, "json", false, "print as JSON")
_ = fs.Parse(args)
ctx := context.Background()
st, err := openCodes(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
defer st.Close()
codes, err := st.ListCodes(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
if kind != "" {
filtered := codes[:0]
for _, c := range codes {
if c.Kind == kind {
filtered = append(filtered, c)
}
}
codes = filtered
}
if asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(codes); err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
return
}
tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "KIND\tCODE\tREADS AS")
for _, c := range codes {
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Kind, c.Code, c.Name)
}
_ = tw.Flush()
}
func codesSet(args []string) {
fs := flag.NewFlagSet("codes set", flag.ContinueOnError)
var kind, code, name string
fs.StringVar(&kind, "kind", "", "subject, room, teacher or period")
fs.StringVar(&code, "code", "", "the raw Compass code")
fs.StringVar(&name, "name", "", "the plain-English name")
_ = fs.Parse(args)
if kind == "" || code == "" || name == "" {
fmt.Fprintln(os.Stderr, "school codes set: --kind, --code and --name are required")
os.Exit(2)
}
ctx := context.Background()
st, err := openCodes(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
defer st.Close()
c, err := st.SetCode(ctx, kind, code, name)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
fmt.Printf("%s %s reads as %q\n", c.Kind, c.Code, c.Name)
}
func codesDelete(args []string) {
fs := flag.NewFlagSet("codes delete", flag.ContinueOnError)
var kind, code string
fs.StringVar(&kind, "kind", "", "subject, room, teacher or period")
fs.StringVar(&code, "code", "", "the raw Compass code")
_ = fs.Parse(args)
if kind == "" || code == "" {
fmt.Fprintln(os.Stderr, "school codes delete: --kind and --code are required")
os.Exit(2)
}
ctx := context.Background()
st, err := openCodes(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
defer st.Close()
ok, err := st.DeleteCode(ctx, kind, code)
if err != nil {
fmt.Fprintln(os.Stderr, "school codes:", err)
os.Exit(1)
}
if !ok {
fmt.Printf("%s %s was not mapped\n", kind, code)
return
}
fmt.Printf("%s %s now renders as the raw code\n", kind, code)
}

View File

@@ -5,6 +5,7 @@ import (
"flag"
"fmt"
"os"
"strings"
"gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/config"
"gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/store"
@@ -15,31 +16,43 @@ import (
// stored against the wrong child ("nothing may leak between children").
func itemsCommand(args []string) {
if len(args) == 0 || args[0] != "purge" {
fmt.Fprintln(os.Stderr, "usage: school items purge --child NAME [--source compass|teams] [--type message|task|event]")
fmt.Fprintln(os.Stderr, "usage: school items purge --child NAME [--source compass|teams] [--type message|task|event] [--source-page SLUG ...]")
os.Exit(2)
}
fs := flag.NewFlagSet("items purge", flag.ContinueOnError)
var (
child string
source string
typ string
child string
source string
typ string
sourcePages multiFlag
)
fs.StringVar(&child, "child", "", "child name (Harry or Finn)")
fs.StringVar(&source, "source", "", "limit to one source")
fs.StringVar(&typ, "type", "", "limit to one type")
fs.Var(&sourcePages, "source-page", "limit to one stored page slug (repeatable)")
_ = fs.Parse(args[1:])
if child == "" {
fmt.Fprintln(os.Stderr, "school items purge: --child is required")
os.Exit(2)
}
if err := runItemsPurge(child, source, typ); err != nil {
if err := runItemsPurge(child, source, typ, sourcePages); err != nil {
fmt.Fprintln(os.Stderr, "school items:", err)
os.Exit(1)
}
}
func runItemsPurge(child, source, typ string) error {
// multiFlag collects a repeatable string flag.
type multiFlag []string
func (m *multiFlag) String() string { return strings.Join(*m, ",") }
func (m *multiFlag) Set(v string) error {
*m = append(*m, v)
return nil
}
func runItemsPurge(child, source, typ string, sourcePages []string) error {
ctx := context.Background()
cfg, err := config.LoadDB()
@@ -61,10 +74,15 @@ func runItemsPurge(child, source, typ string) error {
if c == nil {
return fmt.Errorf("unknown child %q", child)
}
n, err := st.DeleteItems(ctx, c.ID, source, typ)
var n int64
if len(sourcePages) > 0 {
n, err = st.DeleteItemsFromPages(ctx, c.ID, source, typ, sourcePages...)
} else {
n, err = st.DeleteItems(ctx, c.ID, source, typ)
}
if err != nil {
return err
}
fmt.Printf("child=%s purged=%d source=%q type=%q\n", c.Name, n, source, typ)
fmt.Printf("child=%s purged=%d source=%q type=%q pages=%v\n", c.Name, n, source, typ, sourcePages)
return nil
}

View File

@@ -62,6 +62,9 @@ func main() {
case "calendar":
calendarCommand(os.Args[2:])
return
case "codes":
codesCommand(os.Args[2:])
return
case "version":
fmt.Println(version)
return
@@ -97,6 +100,9 @@ func run() error {
if err := st.SeedChildren(context.Background(), seedChildren...); err != nil {
return err
}
if err := st.SeedCodes(context.Background()); err != nil {
return err
}
am, err := auth.New(cfg.SessionSecret, cfg.SessionTTL, cfg.CookieSecure,
cfg.AdminUsername, cfg.AdminPasswordHash, cfg.AdminPassword)

View File

@@ -118,6 +118,7 @@ func buildOnly(ctx context.Context, svc *brief.Service, st *store.Store, only st
if len(children) == 0 {
return nil, fmt.Errorf("no children on file")
}
children = brief.OrderChildren(children)
var out []brief.Send
if only != "combined" {

View File

@@ -150,6 +150,19 @@ func runParse(f parseFlags) error {
}
}
// The week calendar is school-wide and carries the eldest child's lesson
// grid. Now that this child's own day widget is parsed, drop the leaked
// routine periods; the real school events from that page are kept (FR-16).
// The day-widget rows themselves are not deleted: the same day's period
// upserts onto its own stable reference, so its Home Assistant marker (and
// the calendar write's idempotency) is preserved across passes.
if hasPage(pages, parse.PageChildProfile) || hasPage(pages, parse.PageLearningTasks) {
if _, err := st.DeleteChildRoutineCalendarEvents(ctx, child.ID); err != nil {
_, _ = st.RecordScan(ctx, &child.ID, len(pages), len(items), false, err.Error())
return err
}
}
inserted, updated, err := st.UpsertItems(ctx, child.ID, stored)
if err != nil {
_, _ = st.RecordScan(ctx, &child.ID, len(pages), len(items), false, err.Error())
@@ -326,6 +339,7 @@ func loadRunPages(rawRoot, child, run string) (string, []parse.Page, error) {
type rawPage struct {
htmlBytes, jsonBytes []byte
url, user string
fetchedAt time.Time
}
bySlug := map[string]*rawPage{}
var order []string
@@ -353,13 +367,17 @@ func loadRunPages(rawRoot, child, run string) (string, []parse.Page, error) {
return "", nil, fmt.Errorf("read %s: %w", name, err)
}
var meta struct {
URL string `json:"url"`
UserID string `json:"userId"`
URL string `json:"url"`
UserID string `json:"userId"`
FetchedAt string `json:"fetchedAt"`
}
_ = json.Unmarshal(raw, &meta)
p := get(slug)
p.url = strings.TrimSpace(meta.URL)
p.user = strings.TrimSpace(meta.UserID)
if ts, err := time.Parse(time.RFC3339, strings.TrimSpace(meta.FetchedAt)); err == nil {
p.fetchedAt = ts
}
case strings.HasSuffix(lower, ".json"):
if strings.EqualFold(name, "manifest.json") {
continue
@@ -387,11 +405,12 @@ func loadRunPages(rawRoot, child, run string) (string, []parse.Page, error) {
continue
}
pages = append(pages, parse.Page{
Slug: slug,
URL: rp.url,
HTML: rp.htmlBytes,
JSON: rp.jsonBytes,
UserID: rp.user,
Slug: slug,
URL: rp.url,
HTML: rp.htmlBytes,
JSON: rp.jsonBytes,
UserID: rp.user,
FetchedAt: rp.fetchedAt,
})
}
if len(pages) == 0 {