Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33e048cea9 | ||
|
|
7a6f6963f9 | ||
|
|
3cfa72cb25 | ||
|
|
437c535cd1 | ||
|
|
07d598cffd | ||
|
|
958b90ebc6 | ||
|
|
28af101634 | ||
|
|
70ff970672 | ||
|
|
f8929a19a8 | ||
|
|
3af0d08779 | ||
|
|
45da4b15e2 |
@@ -85,6 +85,12 @@ Frontend: React 19 + Vite + Tailwind 4 + TanStack Router/Query, built into
|
||||
deliberately. `ErrForbidden` means "you can see it but may not do that".
|
||||
- **Plops (plantings) live in their parent object's local frame**, origin at the
|
||||
object's center, `-y` is north. Moving or rotating a bed moves its plants free.
|
||||
- **A plop is a clump, not a plant.** `defaultPlopRadius` is `1.5 × spacing`, so a
|
||||
plop is three spacings across and holds `π·r²/spacing²` plants. Reasoning about
|
||||
fills as if one plop were one plant gets the geometry wrong every time — which
|
||||
is how #75 happened: requiring the whole circle inside the bed inset the outer
|
||||
row by 1.5 spacings when the horticultural rule is *half* a spacing. Spacing is
|
||||
a constraint between neighbouring plants; a bed edge is nobody's neighbour.
|
||||
- **Soft removal**: "clear bed" sets `removed_at`; the editor reads
|
||||
`removed_at IS NULL`. Hard delete is a different operation.
|
||||
- **Migrations** are numbered `.sql` files in `internal/store/migrations/`, run
|
||||
@@ -123,6 +129,22 @@ fix what's real → merge when the pipeline is green. Do not grade Gadfly findin
|
||||
A push to `main` builds the image and deploys to Komodo; the live instance at
|
||||
`pansy.orgrimmar.dudenhoeffer.casa` updates a few minutes later.
|
||||
|
||||
**Gadfly reviews the PR as opened, not as merged.** The workflow triggers on
|
||||
`opened`/`reopened`/`ready_for_review` — deliberately *not* `synchronize` — so
|
||||
every commit you push afterwards, including the ones you push in response to
|
||||
Gadfly itself, is unreviewed unless you ask. Once you've stopped pushing and
|
||||
before you merge, comment **`@gadfly review`** on the PR to re-trigger it. The
|
||||
phrase is required, and this is not hypothetical: on #76 the follow-up commit
|
||||
was the one that contained a real bug.
|
||||
|
||||
**A skipped Gadfly run reports success.** A comment without the trigger phrase
|
||||
still starts the workflow, which logs `comment does not contain trigger phrase`
|
||||
and exits green in ~2 seconds. So "the pipeline is green" does NOT mean "this
|
||||
was reviewed". Confirm a re-review actually ran by its **duration** — a real
|
||||
pass takes ~10 minutes, a skip takes 2 seconds. Don't look for a new consensus
|
||||
comment: Gadfly EDITS its existing status-board and consensus comments in place,
|
||||
so their `created_at` stays at the first review and only `updated_at` moves.
|
||||
|
||||
Workflow- and config-only changes (CI, this file, docs) go straight to `main`
|
||||
without the PR dance.
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ Work is tracked in Gitea issues; the tracking epic links every piece in dependen
|
||||
## Decisions
|
||||
|
||||
- **Placement model:** freeform plops (not a square-foot grid), scaled by real plant spacing. Grid snapping may come later as a toggle.
|
||||
- **Spacing is a plant-to-plant rule, so bed edges get half of it.** A bed edge is not a competitor for soil, light or water, so the outer row owes it half the spacing rather than a full one. `FillRegion` centres its lattice accordingly, and lets a plop — a *clump* three spacings across — cross the edge by up to half a spacing so its outermost plants land at that half-spacing. The rule, the square-foot-chart arithmetic behind it, and the failure mode it prevents are written out once in `hexCenters`; #75 is what getting it wrong looked like.
|
||||
- **Stack:** Go 1.26.x backend, module `gitea.stevedudenhoeffer.com/steve/pansy`; React + TypeScript + Vite + Tailwind frontend, production build embedded via `embed.FS` → one static binary (`CGO_ENABLED=0`).
|
||||
- **Users:** multi-user with ownership. Users own gardens; a garden can be shared with other users as viewer (read) or editor (edit content). Owner additionally shares/deletes.
|
||||
- **Auth:** OIDC-first (Authentik is the primary IdP), local argon2id passwords as an optional fallback.
|
||||
@@ -63,6 +64,8 @@ POST /change-sets/:id/revert ← undo an operation; 201, or 409 + the conflicts
|
||||
POST /gardens/:id/copy ← deep-copy a garden you own (objects + active plops; not shares/link)
|
||||
POST /gardens/:id/objects PATCH,DELETE /objects/:id
|
||||
POST /objects/:id/plantings PATCH,DELETE /plantings/:id
|
||||
POST /objects/:id/fill ← hex-pack a region with one plant; region by compass name or rect
|
||||
POST /objects/:id/clear ← soft-remove every active plop, as ONE change set
|
||||
GET,POST /plants PATCH,DELETE /plants/:id (own plants only)
|
||||
GET,POST /seed-lots GET,PATCH,DELETE /seed-lots/:id (own lots only; private)
|
||||
GET,POST /gardens/:id/journal PATCH,DELETE /journal/:id (editor writes; author edits own)
|
||||
@@ -71,6 +74,8 @@ POST /agent/chat ← SSE: step events, then the finished turn (edit
|
||||
GET,DELETE /gardens/:id/agent/history (the actor's own thread)
|
||||
GET /capabilities ← what this instance can do, so the UI offers only what works
|
||||
GET,POST /gardens/:id/shares PATCH,DELETE /gardens/:id/shares/:userId (invite by email)
|
||||
GET,POST,DELETE /gardens/:id/share-link ← the public read-only token for this garden
|
||||
GET /public/gardens/:token ← UNAUTHENTICATED read-only /full; the token is the capability
|
||||
```
|
||||
|
||||
**Sync:** plain REST + optimistic UI + last-write-wins with a version guard. Every PATCH/DELETE carries the row's `version`; the server increments on write and returns **409 + the current row** on mismatch; the client rolls back and refetches. No websockets/CRDT — the right cost for household-scale co-editing. Drags PATCH once on drop, not per frame.
|
||||
|
||||
@@ -119,6 +119,11 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
|
||||
objects.PATCH("/:id", h.updateObject)
|
||||
objects.DELETE("/:id", h.deleteObject)
|
||||
objects.POST("/:id/plantings", h.createPlanting) // place a plop in this object
|
||||
// Bulk ops. These wrap the same service methods the agent tools call, so an
|
||||
// instance with no model configured still gets the most valuable operation in
|
||||
// the app — and so "clear bed" is ONE change set rather than one per plop.
|
||||
objects.POST("/:id/fill", h.fillObject)
|
||||
objects.POST("/:id/clear", h.clearObject)
|
||||
|
||||
// Plantings ("plops") are addressed by their own id; the service resolves the
|
||||
// owning object/garden for the permission check.
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
|
||||
)
|
||||
|
||||
// Bulk operations on a plantable object (#82): fill a region with one plant, and
|
||||
// clear everything out of it.
|
||||
//
|
||||
// These were reachable only through the agent toolbox until now, which meant the
|
||||
// most valuable bulk operation in a garden planner — and the one carrying the
|
||||
// most carefully reasoned geometry in the codebase — did not exist at all on an
|
||||
// instance with no model configured. They are thin adapters over the same
|
||||
// service methods `internal/agent/tools.go` calls, so the permission checks and
|
||||
// the one-change-set-per-operation guarantee come along unchanged.
|
||||
|
||||
// fillRect is an explicit rectangle in the object's local frame, the alternative
|
||||
// to a compass name. A named type (not an inline anonymous struct) to match the
|
||||
// rest of internal/api and so it can carry its own validity check.
|
||||
type fillRect struct {
|
||||
MinX float64 `json:"minXCm"`
|
||||
MinY float64 `json:"minYCm"`
|
||||
MaxX float64 `json:"maxXCm"`
|
||||
MaxY float64 `json:"maxYCm"`
|
||||
}
|
||||
|
||||
// degenerate reports whether the rect encloses no area. Such a rect (including
|
||||
// the all-zeros an empty `"rect": {}` decodes to) would otherwise slip through
|
||||
// and plant a single plop at the object's centre — a surprising result for what
|
||||
// is really malformed input.
|
||||
func (r fillRect) degenerate() bool {
|
||||
return r.MaxX <= r.MinX || r.MaxY <= r.MinY
|
||||
}
|
||||
|
||||
// objectFillRequest is the body for POST /objects/:id/fill.
|
||||
//
|
||||
// A region is given EITHER by compass name ("ne", "south half", "all") or as an
|
||||
// explicit rect in the object's local frame. The named form is what a person
|
||||
// means and what the agent uses; the rect is for a future drag-a-box affordance.
|
||||
// Exactly one must be supplied — accepting both and silently preferring one
|
||||
// would make a client bug look like a geometry bug.
|
||||
type objectFillRequest struct {
|
||||
PlantID int64 `json:"plantId" binding:"required"`
|
||||
Region string `json:"region"`
|
||||
Rect *fillRect `json:"rect"`
|
||||
// SpacingOverrideCM plants tighter or looser than the plant's mature spacing
|
||||
// without editing the catalog entry.
|
||||
SpacingOverrideCM *float64 `json:"spacingOverrideCm"`
|
||||
}
|
||||
|
||||
func (h *handlers) fillObject(c *gin.Context) {
|
||||
id, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req objectFillRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a plantId and a region are required")
|
||||
return
|
||||
}
|
||||
named, hasRect := req.Region != "", req.Rect != nil
|
||||
if named == hasRect {
|
||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT",
|
||||
`supply exactly one of "region" (e.g. "all", "ne", "south half") or "rect"`)
|
||||
return
|
||||
}
|
||||
|
||||
actor := mustActor(c).ID
|
||||
var (
|
||||
created []domain.Planting
|
||||
err error
|
||||
)
|
||||
if rect := req.Rect; rect != nil {
|
||||
// Reject a zero-area rect here rather than let it plant one stray plop.
|
||||
// (Binding the pointer to `rect` also keeps the deref visibly guarded,
|
||||
// instead of reading req.Rect.MinX under an invariant from a line above.)
|
||||
if rect.degenerate() {
|
||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "rect must enclose a positive area")
|
||||
return
|
||||
}
|
||||
region := service.Region{MinX: rect.MinX, MinY: rect.MinY, MaxX: rect.MaxX, MaxY: rect.MaxY}
|
||||
created, err = h.svc.FillRegion(c.Request.Context(), actor, id, region, req.PlantID, req.SpacingOverrideCM)
|
||||
} else {
|
||||
created, err = h.svc.FillNamedRegion(c.Request.Context(), actor, id, req.Region, req.PlantID, req.SpacingOverrideCM)
|
||||
}
|
||||
if err != nil {
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
// 200, not 201: a fill can legitimately create nothing (the region is already
|
||||
// planted), and there is no single resource to point a Location at.
|
||||
c.JSON(http.StatusOK, gin.H{"plantings": created, "created": len(created)})
|
||||
}
|
||||
|
||||
// clearObject soft-removes every active plop in an object.
|
||||
//
|
||||
// Distinct from deleting the object, and — unlike the client-side loop this
|
||||
// replaces — it lands as ONE change set, so undoing a cleared bed is one click
|
||||
// rather than one per plop.
|
||||
func (h *handlers) clearObject(c *gin.Context) {
|
||||
id, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
n, err := h.svc.ClearObject(c.Request.Context(), mustActor(c).ID, id)
|
||||
if err != nil {
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"cleared": n})
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func fillPath(id int64) string { return objectPath(id) + "/fill" }
|
||||
func clearPath(id int64) string { return objectPath(id) + "/clear" }
|
||||
|
||||
// makeFillPlant creates a custom plant and returns its id. (A near-identical
|
||||
// createPlantAPI landed alongside the seed-lot tests; consolidating the two into
|
||||
// one shared helper is a fine follow-up, kept separate here only to avoid a
|
||||
// merge collision on the shared symbol.)
|
||||
func makeFillPlant(t *testing.T, r *gin.Engine, cookie *http.Cookie, name string, spacing float64) int64 {
|
||||
t.Helper()
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/plants", map[string]any{
|
||||
"name": name, "category": "vegetable", "spacingCm": spacing, "color": "#4a7c3f", "icon": "🌱",
|
||||
}, cookie)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create plant %q: status %d, body %s", name, w.Code, w.Body.String())
|
||||
}
|
||||
return int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||
}
|
||||
|
||||
// seedFillableBed makes a garden with one plantable bed and a custom plant,
|
||||
// returning (gardenID, objectID, plantID).
|
||||
func seedFillableBed(t *testing.T, r *gin.Engine, cookie *http.Cookie, w, h, spacing float64) (int64, int64, int64) {
|
||||
t.Helper()
|
||||
gid := createGardenAPI(t, r, cookie, "G")
|
||||
rec := doJSON(t, r, http.MethodPost, objectsPath(gid), map[string]any{
|
||||
"kind": "bed", "widthCm": w, "heightCm": h, "plantable": true,
|
||||
}, cookie)
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("create bed: status %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
objID := int64(decodeMap(t, rec.Body.Bytes())["id"].(float64))
|
||||
plantID := makeFillPlant(t, r, cookie, "Fillable", spacing)
|
||||
return gid, objID, plantID
|
||||
}
|
||||
|
||||
// countChangeSets reads the history page and reports how many change sets exist.
|
||||
func countChangeSets(t *testing.T, r *gin.Engine, cookie *http.Cookie, gardenID int64) int {
|
||||
t.Helper()
|
||||
w := doJSON(t, r, http.MethodGet, historyPath(gardenID), nil, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("history: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
sets, _ := decodeMap(t, w.Body.Bytes())["changeSets"].([]any)
|
||||
return len(sets)
|
||||
}
|
||||
|
||||
// TestFillAndClearAPI covers the two routes end to end through the router.
|
||||
//
|
||||
// These exist because both operations were previously reachable ONLY through the
|
||||
// agent toolbox, so on an instance with no model configured the most valuable
|
||||
// bulk operation in the app did not exist at all.
|
||||
func TestFillAndClearAPI(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
_, objID, plantID := seedFillableBed(t, r, cookie, 200, 200, 20)
|
||||
|
||||
// Fill by compass name.
|
||||
w := doJSON(t, r, http.MethodPost, fillPath(objID), map[string]any{
|
||||
"plantId": plantID, "region": "all",
|
||||
}, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("fill: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
body := decodeMap(t, w.Body.Bytes())
|
||||
created := int(body["created"].(float64))
|
||||
if created == 0 {
|
||||
t.Fatalf("fill created nothing: %s", w.Body.String())
|
||||
}
|
||||
if plops, _ := body["plantings"].([]any); len(plops) != created {
|
||||
t.Errorf("created=%d but returned %d plantings", created, len(plops))
|
||||
}
|
||||
|
||||
// Clear it: one call, and it reports what it removed.
|
||||
w = doJSON(t, r, http.MethodPost, clearPath(objID), nil, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("clear: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
if n := int(decodeMap(t, w.Body.Bytes())["cleared"].(float64)); n != created {
|
||||
t.Errorf("cleared %d, want %d (everything the fill made)", n, created)
|
||||
}
|
||||
|
||||
// Clearing an already-empty bed is a no-op, not an error.
|
||||
w = doJSON(t, r, http.MethodPost, clearPath(objID), nil, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("second clear: status %d", w.Code)
|
||||
}
|
||||
if n := int(decodeMap(t, w.Body.Bytes())["cleared"].(float64)); n != 0 {
|
||||
t.Errorf("second clear removed %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillRegionSelectionAPI: exactly one of region/rect, and a rect fills only
|
||||
// its own corner of the bed.
|
||||
func TestFillRegionSelectionAPI(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
_, objID, plantID := seedFillableBed(t, r, cookie, 400, 400, 20)
|
||||
|
||||
// Neither → 400. Both → 400. Accepting both and silently preferring one
|
||||
// would make a client bug look like a geometry bug.
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), map[string]any{"plantId": plantID}, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("no region = %d, want 400", w.Code)
|
||||
}
|
||||
both := map[string]any{
|
||||
"plantId": plantID, "region": "all",
|
||||
"rect": map[string]any{"minXCm": -50, "minYCm": -50, "maxXCm": 50, "maxYCm": 50},
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), both, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("both region and rect = %d, want 400", w.Code)
|
||||
}
|
||||
// An unknown compass name is rejected rather than silently filling nothing.
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), map[string]any{
|
||||
"plantId": plantID, "region": "middle-ish",
|
||||
}, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("bad region name = %d, want 400", w.Code)
|
||||
}
|
||||
|
||||
// A zero-area rect is malformed input, not "plant one at the centre". An empty
|
||||
// `"rect": {}` decodes to all-zeros and must be caught the same way.
|
||||
for _, rect := range []map[string]any{
|
||||
{}, // {} → 0,0,0,0
|
||||
{"minXCm": 10, "minYCm": 10, "maxXCm": 10, "maxYCm": 50}, // zero width
|
||||
{"minXCm": 10, "minYCm": 50, "maxXCm": 50, "maxYCm": 50}, // zero height
|
||||
{"minXCm": 50, "minYCm": 50, "maxXCm": 10, "maxYCm": 10}, // inverted
|
||||
} {
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID),
|
||||
map[string]any{"plantId": plantID, "rect": rect}, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("degenerate rect %v = %d, want 400", rect, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// A rect confined to the NE corner produces plops only there. Local frame:
|
||||
// +x east, -y north.
|
||||
w := doJSON(t, r, http.MethodPost, fillPath(objID), map[string]any{
|
||||
"plantId": plantID,
|
||||
"rect": map[string]any{"minXCm": 0, "minYCm": -200, "maxXCm": 200, "maxYCm": 0},
|
||||
}, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("rect fill: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
plops, _ := decodeMap(t, w.Body.Bytes())["plantings"].([]any)
|
||||
if len(plops) == 0 {
|
||||
t.Fatal("rect fill created nothing")
|
||||
}
|
||||
for _, raw := range plops {
|
||||
p := raw.(map[string]any)
|
||||
if x, y := p["xCm"].(float64), p["yCm"].(float64); x < 0 || y > 0 {
|
||||
t.Errorf("plop at (%v,%v) outside the NE rect", x, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClearObjectIsOneChangeSetAPI is the regression test for the behaviour this
|
||||
// endpoint exists to restore.
|
||||
//
|
||||
// The UI used to clear a bed with a loop of PATCHes, and since every service
|
||||
// mutation auto-scopes its own change set, clearing a 40-plop bed wrote 40 of
|
||||
// them — 40 presses of Undo to put the bed back. CLAUDE.md states the rule
|
||||
// directly: multi-row operations record together so they undo as one unit.
|
||||
func TestClearObjectIsOneChangeSetAPI(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
gid, objID, plantID := seedFillableBed(t, r, cookie, 300, 300, 20)
|
||||
|
||||
w := doJSON(t, r, http.MethodPost, fillPath(objID), map[string]any{
|
||||
"plantId": plantID, "region": "all",
|
||||
}, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("fill: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
created := int(decodeMap(t, w.Body.Bytes())["created"].(float64))
|
||||
if created < 4 {
|
||||
t.Fatalf("need several plops to make this meaningful, got %d", created)
|
||||
}
|
||||
|
||||
before := countChangeSets(t, r, cookie, gid)
|
||||
if w := doJSON(t, r, http.MethodPost, clearPath(objID), nil, cookie); w.Code != http.StatusOK {
|
||||
t.Fatalf("clear: status %d", w.Code)
|
||||
}
|
||||
if after := countChangeSets(t, r, cookie, gid); after != before+1 {
|
||||
t.Errorf("clearing %d plops added %d change sets, want exactly 1", created, after-before)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillClearPermissionsAPI: a viewer may look but not fill or clear, and a
|
||||
// stranger gets 404 because existence is masked.
|
||||
func TestFillClearPermissionsAPI(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
owner := registerAndCookie(t, r, "[email protected]")
|
||||
viewer := registerAndCookie(t, r, "[email protected]")
|
||||
stranger := registerAndCookie(t, r, "[email protected]")
|
||||
|
||||
gid, objID, plantID := seedFillableBed(t, r, owner, 200, 200, 20)
|
||||
if w := doJSON(t, r, http.MethodPost, sharesPath(gid),
|
||||
map[string]any{"email": "[email protected]", "role": "viewer"}, owner); w.Code != http.StatusCreated {
|
||||
t.Fatalf("share as viewer: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
fillBody := map[string]any{"plantId": plantID, "region": "all"}
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), fillBody, viewer); w.Code != http.StatusForbidden {
|
||||
t.Errorf("viewer fill = %d, want 403 (they can see it but may not do that)", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, clearPath(objID), nil, viewer); w.Code != http.StatusForbidden {
|
||||
t.Errorf("viewer clear = %d, want 403", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), fillBody, stranger); w.Code != http.StatusNotFound {
|
||||
t.Errorf("stranger fill = %d, want 404 (existence masked)", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, clearPath(objID), nil, stranger); w.Code != http.StatusNotFound {
|
||||
t.Errorf("stranger clear = %d, want 404", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, fillPath(objID), fillBody, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous fill = %d, want 401", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, clearPath(objID), nil, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("anonymous clear = %d, want 401", w.Code)
|
||||
}
|
||||
}
|
||||
+135
-35
@@ -28,13 +28,9 @@ type Region struct {
|
||||
MinX, MinY, MaxX, MaxY float64
|
||||
}
|
||||
|
||||
// contains reports whether a local point lies in the region.
|
||||
func (r Region) contains(x, y float64) bool {
|
||||
return x >= r.MinX && x <= r.MaxX && y >= r.MinY && y <= r.MaxY
|
||||
}
|
||||
|
||||
// clampTo intersects the region with an object's local bounds (±halfW, ±halfH),
|
||||
// so an oversized caller-supplied region can't make hexCenters loop forever.
|
||||
// so a fill can't plant outside the object it was aimed at. A region that misses
|
||||
// the object entirely comes back empty — see empty().
|
||||
func (r Region) clampTo(halfW, halfH float64) Region {
|
||||
return Region{
|
||||
MinX: math.Max(r.MinX, -halfW), MinY: math.Max(r.MinY, -halfH),
|
||||
@@ -42,6 +38,16 @@ func (r Region) clampTo(halfW, halfH float64) Region {
|
||||
}
|
||||
}
|
||||
|
||||
// empty reports whether the region encloses nothing.
|
||||
//
|
||||
// This exists because clampTo expresses "no overlap" by INVERTING the region —
|
||||
// Max clamps below Min — rather than by zeroing it, which is not something a
|
||||
// reader guesses. Naming it once here beats a bare `MaxX < MinX` at each place
|
||||
// that has to care.
|
||||
func (r Region) empty() bool {
|
||||
return r.MaxX < r.MinX || r.MaxY < r.MinY
|
||||
}
|
||||
|
||||
// rect builds a rectangular region.
|
||||
func rect(minX, minY, maxX, maxY float64) Region {
|
||||
return Region{MinX: minX, MinY: minY, MaxX: maxX, MaxY: maxY}
|
||||
@@ -94,9 +100,11 @@ func defaultPlopRadius(spacingCM float64) float64 {
|
||||
// FillRegion lays a hex-packed field of plops of one plant across a region of a
|
||||
// plantable object the actor can edit. Plop radius comes from the plant's spacing
|
||||
// (or spacingOverride) via defaultPlopRadius; centers sit on a hex lattice at 2×
|
||||
// radius pitch, kept where the center is inside the region. A candidate is
|
||||
// skipped when its plop would sit entirely inside an existing active plop (so
|
||||
// re-filling doesn't stack duplicates). Returns the plops it created.
|
||||
// radius pitch, centered in the region, and set in from each edge by the plop's
|
||||
// radius less half a spacing — see hexCenters for why that half-spacing is what
|
||||
// the edge is owed. A candidate is skipped when its plop would sit entirely
|
||||
// inside an existing active plop (so re-filling doesn't stack duplicates).
|
||||
// Returns the plops it created.
|
||||
func (s *Service) FillRegion(ctx context.Context, actorID, objectID int64, region Region, plantID int64, spacingOverride *float64) ([]domain.Planting, error) {
|
||||
o, _, err := s.objectForRole(ctx, actorID, objectID, roleEditor)
|
||||
if err != nil {
|
||||
@@ -106,9 +114,9 @@ func (s *Service) FillRegion(ctx context.Context, actorID, objectID int64, regio
|
||||
}
|
||||
|
||||
// fillLoaded is the shared body of FillRegion/FillNamedRegion given an object
|
||||
// already loaded and authorized (roleEditor). It clamps the region to the
|
||||
// object's bounds, refuses fills over maxFillPlops, and inserts the whole batch
|
||||
// in one transaction rather than one round-trip per plop.
|
||||
// already loaded and authorized (roleEditor). It rejects a non-finite region,
|
||||
// clamps the region to the object's bounds, refuses fills over maxFillPlops, and
|
||||
// inserts the whole batch in one transaction rather than one round-trip per plop.
|
||||
func (s *Service) fillLoaded(ctx context.Context, actorID int64, o *domain.GardenObject, region Region, plantID int64, spacingOverride *float64) ([]domain.Planting, error) {
|
||||
if !o.Plantable {
|
||||
return nil, domain.ErrInvalidInput
|
||||
@@ -129,9 +137,21 @@ func (s *Service) fillLoaded(ctx context.Context, actorID int64, o *domain.Garde
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
// A caller-supplied region is arbitrary floats, and non-finite ones survive
|
||||
// everything downstream: clamping keeps them, the inverted-region guard can't
|
||||
// see NaN (it compares false both ways), and fitAxis centres on them happily.
|
||||
// Nothing corrupt reaches the table — SQLite stores NaN as NULL and the NOT
|
||||
// NULL constraint refuses it — but the caller gets an opaque store error for
|
||||
// NaN, and for +Inf a silent zero-plop success. Both are lies about what went
|
||||
// wrong; say "bad input" here instead.
|
||||
if !isFinite(region.MinX) || !isFinite(region.MinY) ||
|
||||
!isFinite(region.MaxX) || !isFinite(region.MaxY) {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
region = region.clampTo(o.WidthCM/2, o.HeightCM/2)
|
||||
centers := hexCenters(region, radius)
|
||||
if len(centers) > maxFillPlops {
|
||||
centers, total := hexCenters(region, radius, spacing, maxFillPlops)
|
||||
if total > maxFillPlops {
|
||||
return nil, domain.ErrInvalidInput // region too large for this spacing; ask for less
|
||||
}
|
||||
|
||||
@@ -169,32 +189,112 @@ func (s *Service) fillLoaded(ctx context.Context, actorID int64, o *domain.Garde
|
||||
|
||||
type localPoint struct{ x, y float64 }
|
||||
|
||||
// hexCenters returns hex-packed lattice centers whose center lies in the region.
|
||||
// Rows are spaced radius·√3 apart and every other row is offset by radius, the
|
||||
// standard hexagonal packing at a 2×radius pitch. The lattice is anchored one
|
||||
// radius inside the region's min corner so the first plop sits inside it.
|
||||
func hexCenters(r Region, radius float64) []localPoint {
|
||||
// hexCenters returns hex-packed lattice centers filling a region: rows radius·√3
|
||||
// apart, alternate rows offset by half a pitch, at a 2×radius pitch. The lattice
|
||||
// is CENTERED, so the leftover is shared between opposite edges instead of piling
|
||||
// up against the far one.
|
||||
//
|
||||
// # How close to the edge the outer row goes
|
||||
//
|
||||
// Spacing is a constraint BETWEEN NEIGHBOURING PLANTS competing for the same
|
||||
// soil, light and water. A bed edge is not a competitor, so the outer row only
|
||||
// owes it HALF the spacing — the half it would otherwise share with a neighbour.
|
||||
// That is the arithmetic inside every square-foot-gardening chart: 4 per square
|
||||
// is 6" apart and 3" from the square's edge; 9 per square is 4" apart and 2"
|
||||
// from the edge. Garlic at 9 per square goes in 2" from the frame, not 6".
|
||||
//
|
||||
// A plop is a CLUMP, not a plant — defaultPlopRadius makes it 1.5×spacing, so
|
||||
// three spacings across — and its plants sit out to its rim. So keeping the whole
|
||||
// circle inside the bed would inset the outer row by a full 1.5 spacings, three
|
||||
// times what the rule allows. Instead the clump may hang over the edge by up to
|
||||
// half a spacing, which puts its outermost plants exactly the half-spacing from
|
||||
// the edge that the rule asks for. Overhang is capped there and nowhere near the
|
||||
// full radius: a clump mostly outside the bed is a drawing of plants in the path.
|
||||
//
|
||||
// Do not "simplify" this back to anchoring at the region's min corner. That is
|
||||
// what #75 was: staggered rows start a full pitch in, and the leftover all lands
|
||||
// on the far edge, where clumps hang outside a bed that nothing clips them to.
|
||||
//
|
||||
// # Counting before building
|
||||
//
|
||||
// hexCenters returns the total alongside the points, and works that total out
|
||||
// BEFORE building anything: a fill large enough to be refused shouldn't allocate
|
||||
// its whole lattice first just to be counted and thrown away. Over `limit` it
|
||||
// returns (nil, total), so the caller can still refuse with the real number.
|
||||
func hexCenters(r Region, radius, spacing float64, limit int) ([]localPoint, int) {
|
||||
if radius <= 0 {
|
||||
return nil
|
||||
return nil, 0
|
||||
}
|
||||
// An empty region has no inside to plant. The old loop-until-past-MaxX form
|
||||
// got this for free by never entering the loop; counting positions up front
|
||||
// does not, and would site a plop off the bed.
|
||||
if r.empty() {
|
||||
return nil, 0
|
||||
}
|
||||
pitch := 2 * radius
|
||||
rowH := pitch * math.Sqrt(3) / 2
|
||||
const eps = 1e-6
|
||||
var pts []localPoint
|
||||
row := 0
|
||||
for y := r.MinY + radius; y <= r.MaxY+eps; y += rowH {
|
||||
xStart := r.MinX + radius
|
||||
if row%2 == 1 {
|
||||
xStart += radius
|
||||
}
|
||||
for x := xStart; x <= r.MaxX+eps; x += pitch {
|
||||
if r.contains(x, y) {
|
||||
pts = append(pts, localPoint{x, y})
|
||||
}
|
||||
}
|
||||
row++
|
||||
|
||||
// How far a clump's centre must stay inside the edge: its own radius, less the
|
||||
// half-spacing of overhang the rule allows. Never negative, and never past the
|
||||
// centre of the clump.
|
||||
inset := math.Max(0, radius-math.Max(0, spacing)/2)
|
||||
|
||||
rows, y0 := fitAxis(r.MaxY-r.MinY, rowH, inset)
|
||||
cols, x0 := fitAxis(r.MaxX-r.MinX, pitch, inset)
|
||||
|
||||
// Exact, not an upper bound: staggered rows hold one fewer, so rows*cols would
|
||||
// over-reserve by ~12% — and, more to the point, allocating it is the thing we
|
||||
// are trying to avoid when the answer is "too many".
|
||||
staggered := cols
|
||||
if cols > 1 {
|
||||
staggered = cols - 1
|
||||
}
|
||||
return pts
|
||||
total := (rows+1)/2*cols + rows/2*staggered
|
||||
if total > limit {
|
||||
return nil, total
|
||||
}
|
||||
|
||||
pts := make([]localPoint, 0, total)
|
||||
for row := 0; row < rows; row++ {
|
||||
y := r.MinY + y0 + float64(row)*rowH
|
||||
n, x := cols, r.MinX+x0
|
||||
// The stagger falls out of centering: an offset row holds one fewer plop,
|
||||
// and centering THAT run puts it exactly half a pitch off its neighbours.
|
||||
// A single-column region has nothing to stagger against.
|
||||
if row%2 == 1 && cols > 1 {
|
||||
n, x = staggered, r.MinX+x0+pitch/2
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
pts = append(pts, localPoint{x + float64(i)*pitch, y})
|
||||
}
|
||||
}
|
||||
return pts, total
|
||||
}
|
||||
|
||||
// fitAxis returns how many lattice positions fit along a span at `step`, keeping
|
||||
// at least `inset` from each end, and the offset from the span's start that
|
||||
// centers them — so the leftover is split between the two edges rather than all
|
||||
// landing on the far one.
|
||||
//
|
||||
// A span too small to hold even one position at that inset still gets one, in the
|
||||
// middle: filling a bed narrower than a single plop with one plop is a better
|
||||
// answer than refusing to plant it.
|
||||
//
|
||||
// The step<=0 half of that guard is currently unreachable — hexCenters, the only
|
||||
// caller, returns early unless radius > 0, which makes both steps it passes
|
||||
// positive. It stays because dividing by a non-positive step yields ±Inf and then
|
||||
// a garbage int conversion, and a helper this small should not require reading
|
||||
// its caller to know it is safe. Deliberate, not an oversight.
|
||||
func fitAxis(length, step, inset float64) (n int, start float64) {
|
||||
if step <= 0 || length < 2*inset {
|
||||
return 1, length / 2
|
||||
}
|
||||
// The epsilon keeps an exact fit from being lost to floating point — a 60cm
|
||||
// span at a 30cm step should give 2 positions, not 1 because the division
|
||||
// landed on 0.9999999.
|
||||
const eps = 1e-9
|
||||
n = int(math.Floor((length-2*inset)/step+eps)) + 1
|
||||
return n, (length - float64(n-1)*step) / 2
|
||||
}
|
||||
|
||||
// coveredByExisting reports whether a new plop (center, radius) would sit
|
||||
|
||||
@@ -3,6 +3,8 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
@@ -71,6 +73,165 @@ func TestDefaultPlopRadius(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHexCentersEdgeInset pins the spacing rule the packing exists to honour:
|
||||
// spacing is a constraint between neighbouring plants, so a bed edge — which is
|
||||
// nobody's neighbour — is owed half a pitch, not a whole one.
|
||||
//
|
||||
// The bug this guards against was visible to anyone who filled a bed: staggered
|
||||
// rows began a full pitch in, leaving a bare strip a whole plop wide down one
|
||||
// side of every other row, while the far edge had plops hanging off it.
|
||||
func TestHexCentersEdgeInset(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
w, h, radius, spacing float64
|
||||
wantRowStarts []float64 // x of the first plop in rows 0 and 1
|
||||
}{
|
||||
// 4ft × 8ft bed, garlic at 15cm spacing → radius 22.5, pitch 45. Three
|
||||
// columns, the outer ones overhanging by 6.5cm — under the 7.5cm the rule
|
||||
// allows. Anchored at the corner this row started at -38.5 and its
|
||||
// staggered neighbour a full 45 further in still.
|
||||
{"4ft bed of garlic", 122, 244, 22.5, 15, []float64{-45, -22.5}},
|
||||
// An exact fit: 90 wide at pitch 30 → 3 columns, no overhang needed.
|
||||
{"exact fit", 90, 90, 15, 10, []float64{-30, -15}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := rect(-tc.w/2, -tc.h/2, tc.w/2, tc.h/2)
|
||||
pts, total := hexCenters(r, tc.radius, tc.spacing, maxFillPlops)
|
||||
if len(pts) == 0 {
|
||||
t.Fatal("no centers")
|
||||
}
|
||||
// The count is derived up front so an oversized fill is refused without
|
||||
// building its lattice — which only works if it matches what gets built.
|
||||
if total != len(pts) {
|
||||
t.Errorf("reported total %d, built %d", total, len(pts))
|
||||
}
|
||||
|
||||
// A clump may cross the edge, but only by the half-spacing the rule
|
||||
// allows — never enough to be mostly out in the path.
|
||||
budget := tc.spacing / 2
|
||||
for _, p := range pts {
|
||||
over := math.Max(
|
||||
math.Max(r.MinX-(p.x-tc.radius), (p.x+tc.radius)-r.MaxX),
|
||||
math.Max(r.MinY-(p.y-tc.radius), (p.y+tc.radius)-r.MaxY),
|
||||
)
|
||||
if over > budget+1e-6 {
|
||||
t.Errorf("plop at (%.1f,%.1f) overhangs by %.2f, budget %.2f", p.x, p.y, over, budget)
|
||||
}
|
||||
}
|
||||
|
||||
// The margins match on opposite edges: the leftover is shared, not piled
|
||||
// against the far side.
|
||||
minX, maxX, minY, maxY := pts[0].x, pts[0].x, pts[0].y, pts[0].y
|
||||
for _, p := range pts {
|
||||
minX, maxX = math.Min(minX, p.x), math.Max(maxX, p.x)
|
||||
minY, maxY = math.Min(minY, p.y), math.Max(maxY, p.y)
|
||||
}
|
||||
if w, e := minX-r.MinX, r.MaxX-maxX; math.Abs(w-e) > 1e-6 {
|
||||
t.Errorf("lopsided horizontally: west margin %.2f, east %.2f", w, e)
|
||||
}
|
||||
if n, s := minY-r.MinY, r.MaxY-maxY; math.Abs(n-s) > 1e-6 {
|
||||
t.Errorf("lopsided vertically: north margin %.2f, south %.2f", n, s)
|
||||
}
|
||||
|
||||
// The staggered row is offset by HALF a pitch, not a whole one.
|
||||
starts := map[float64]float64{}
|
||||
for _, p := range pts {
|
||||
if x, ok := starts[p.y]; !ok || p.x < x {
|
||||
starts[p.y] = p.x
|
||||
}
|
||||
}
|
||||
ys := make([]float64, 0, len(starts))
|
||||
for y := range starts {
|
||||
ys = append(ys, y)
|
||||
}
|
||||
sort.Float64s(ys)
|
||||
for i, want := range tc.wantRowStarts {
|
||||
if i >= len(ys) {
|
||||
t.Fatalf("only %d rows, want at least %d", len(ys), len(tc.wantRowStarts))
|
||||
}
|
||||
if got := starts[ys[i]]; math.Abs(got-want) > 1e-6 {
|
||||
t.Errorf("row %d starts at x=%.2f, want %.2f", i, got, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHexCentersTinyRegion covers a region too small to hold a plop at the
|
||||
// half-pitch inset: planting one in the middle beats refusing to plant at all.
|
||||
//
|
||||
// The off-centre case earns its place — a region symmetric about the origin
|
||||
// can't tell "the middle of the region" from "the origin", so on its own it
|
||||
// would pass for an implementation that just returned (0,0).
|
||||
func TestHexCentersTinyRegion(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
r Region
|
||||
wantX, wantY float64
|
||||
}{
|
||||
{"centred on the origin", rect(-5, -5, 5, 5), 0, 0},
|
||||
{"off in a corner", rect(20, -40, 30, -30), 25, -35},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pts, _ := hexCenters(tc.r, 15, 10, maxFillPlops)
|
||||
if len(pts) != 1 || pts[0].x != tc.wantX || pts[0].y != tc.wantY {
|
||||
t.Errorf("got %+v, want one plop at (%v,%v)", pts, tc.wantX, tc.wantY)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillRegionRejectsNonFiniteRegion: non-finite bounds survive clamping and
|
||||
// the inverted-region guard (NaN compares false both ways). Without the explicit
|
||||
// check, NaN surfaced as a raw store error ("NOT NULL constraint failed") and
|
||||
// +Inf as a silent success that planted nothing — neither of which tells the
|
||||
// caller what it actually did wrong.
|
||||
func TestFillRegionRejectsNonFiniteRegion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(ctx, owner, GardenInput{Name: "Big", WidthCM: 2000, HeightCM: 2000})
|
||||
bed := seedFillBed(t, s, owner, g.ID, 100, 100)
|
||||
plant := seedOwnPlant(t, s, owner, 10)
|
||||
|
||||
nan := math.NaN()
|
||||
for _, r := range []Region{
|
||||
{MinX: nan, MinY: -50, MaxX: 50, MaxY: 50},
|
||||
{MinX: -50, MinY: -50, MaxX: 50, MaxY: math.Inf(1)},
|
||||
} {
|
||||
created, err := s.FillRegion(ctx, owner, bed.ID, r, plant.ID, nil)
|
||||
if !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("FillRegion(%+v) err = %v, want ErrInvalidInput", r, err)
|
||||
}
|
||||
for _, p := range created {
|
||||
if !isFinite(p.XCM) || !isFinite(p.YCM) {
|
||||
t.Errorf("persisted a plop with non-finite coordinates: %+v", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillRegionOutsideObjectPlantsNothing covers a region that misses the object
|
||||
// entirely. clampTo inverts such a region rather than emptying it, and an
|
||||
// inverted region must plant nothing — not one plop at some point off the bed.
|
||||
func TestFillRegionOutsideObjectPlantsNothing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(ctx, owner, GardenInput{Name: "Big", WidthCM: 2000, HeightCM: 2000})
|
||||
bed := seedFillBed(t, s, owner, g.ID, 100, 100) // local bounds ±50
|
||||
plant := seedOwnPlant(t, s, owner, 10)
|
||||
|
||||
// Wholly east of the bed: clampTo gives MinX=500, MaxX=50.
|
||||
created, err := s.FillRegion(ctx, owner, bed.ID, rect(500, -50, 600, 50), plant.ID, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("FillRegion: %v", err)
|
||||
}
|
||||
if len(created) != 0 {
|
||||
t.Errorf("filled %d plops for a region outside the bed, want 0: %+v", len(created), created)
|
||||
}
|
||||
}
|
||||
|
||||
// seedFillBed makes a plantable bed of the given size centered in a big garden.
|
||||
func seedFillBed(t *testing.T, s *Service, owner, gardenID int64, w, h float64) *domain.GardenObject {
|
||||
t.Helper()
|
||||
@@ -99,16 +260,24 @@ func TestFillRegionDeterministicPacking(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("FillRegion: %v", err)
|
||||
}
|
||||
// Hex lattice on [-30,30]² at pitch 30, rows ~26 apart → 4 plops (2 rows × 2).
|
||||
if len(created) != 4 {
|
||||
t.Fatalf("filled %d plops, want 4 (60×60 bed, radius 15)", len(created))
|
||||
// Hex lattice on [-30,30]² at pitch 30, rows ~26 apart, centered: a row of 2
|
||||
// (x=±15), then a staggered row of 1 (x=0) → 3 plops.
|
||||
//
|
||||
// This was 4 while the lattice was anchored at the min corner, and the fourth
|
||||
// sat at x=30 — centred ON the east edge, so half of it lay outside the bed,
|
||||
// well past the half-spacing (5cm here) the rule allows. Packing one fewer
|
||||
// plop is the point of the fix, not a regression in it.
|
||||
if len(created) != 3 {
|
||||
t.Fatalf("filled %d plops, want 3 (60×60 bed, radius 15)", len(created))
|
||||
}
|
||||
for _, p := range created {
|
||||
if p.RadiusCM != 15 || p.PlantedAt == nil || p.DerivedCount < 1 {
|
||||
t.Errorf("unexpected created plop: %+v", p)
|
||||
}
|
||||
if p.XCM < -30 || p.XCM > 30 || p.YCM < -30 || p.YCM > 30 {
|
||||
t.Errorf("plop center out of bed bounds: %+v", p)
|
||||
// This bed fits its lattice exactly, so nothing should need to overhang.
|
||||
if p.XCM-p.RadiusCM < -30 || p.XCM+p.RadiusCM > 30 ||
|
||||
p.YCM-p.RadiusCM < -30 || p.YCM+p.RadiusCM > 30 {
|
||||
t.Errorf("plop overhangs a bed it fits inside: %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,23 +5,25 @@ import { useClearObject } from '@/lib/objects'
|
||||
/** Confirm clearing every active plop from a focused bed (soft-remove — the rows
|
||||
* are kept with removed_at, so history survives). */
|
||||
export function ClearBedModal({
|
||||
objectId,
|
||||
objectName,
|
||||
plops,
|
||||
plopCount,
|
||||
gardenId,
|
||||
onClose,
|
||||
}: {
|
||||
objectId: number
|
||||
objectName: string
|
||||
plops: { id: number; version: number }[]
|
||||
plopCount: number
|
||||
gardenId: number
|
||||
onClose: () => void
|
||||
}) {
|
||||
const clear = useClearObject(gardenId)
|
||||
const n = plops.length
|
||||
return (
|
||||
<Modal title="Clear bed" onClose={onClose} busy={clear.isPending}>
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-sm text-muted">
|
||||
Remove all <span className="font-medium text-fg">{n}</span> {n === 1 ? 'plant' : 'plants'} from{' '}
|
||||
Remove all <span className="font-medium text-fg">{plopCount}</span>{' '}
|
||||
{plopCount === 1 ? 'plant' : 'plants'} from{' '}
|
||||
<span className="font-medium text-fg">{objectName}</span>? They're marked removed but kept in history.
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
@@ -31,8 +33,8 @@ export function ClearBedModal({
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
disabled={clear.isPending || n === 0}
|
||||
onClick={() => clear.mutate(plops, { onSuccess: onClose })}
|
||||
disabled={clear.isPending || plopCount === 0}
|
||||
onClick={() => clear.mutate(objectId, { onSuccess: onClose })}
|
||||
>
|
||||
{clear.isPending ? 'Clearing…' : 'Clear bed'}
|
||||
</Button>
|
||||
|
||||
+17
-17
@@ -328,28 +328,28 @@ export function useUpdatePlanting(gardenId: number) {
|
||||
})
|
||||
}
|
||||
|
||||
/** Clear a bed: soft-remove every active plop in an object (a loop of PATCHes;
|
||||
* a bulk ClearObject endpoint arrives with the agent seam, #19). Invalidates
|
||||
* once at the end. Pass the object's active plops (id + current version). */
|
||||
const clearResultSchema = z.object({ cleared: z.number() })
|
||||
|
||||
/** Clear a bed: soft-remove every active plop in an object (#82).
|
||||
*
|
||||
* ONE request, and so ONE change set. This used to be a loop of PATCHes, which
|
||||
* meant clearing a 40-plop bed wrote 40 change sets and took 40 presses of Undo
|
||||
* to put back — while the agent's clear_object, for the identical user-facing
|
||||
* action, undid in a single click. The rule it violated is stated in CLAUDE.md:
|
||||
* multi-row operations record all their changes together so they undo as one
|
||||
* unit. Doing it server-side also removes the partial-failure case the old loop
|
||||
* had to reconcile. */
|
||||
export function useClearObject(gardenId: number) {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (plops: { id: number; version: number }[]) => {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
// allSettled, not all: a partial failure still soft-removed some rows
|
||||
// server-side, so we must reconcile the cache rather than roll everything
|
||||
// back. Report how many failed.
|
||||
const results = await Promise.allSettled(
|
||||
plops.map((p) => api.patch(`/plantings/${p.id}`, { removedAt: today, version: p.version })),
|
||||
)
|
||||
const failed = results.filter((r) => r.status === 'rejected').length
|
||||
if (failed > 0) {
|
||||
throw new Error(`${failed} of ${plops.length} plants couldn't be cleared — refresh and try again.`)
|
||||
}
|
||||
mutationFn: async (objectId: number): Promise<number> => {
|
||||
// No body — clear takes none; passing undefined sends none rather than an
|
||||
// empty {}. The response is just a count; validate it rather than cast.
|
||||
const res = clearResultSchema.parse(await api.post(`/objects/${objectId}/clear`))
|
||||
return res.cleared
|
||||
},
|
||||
// Reconcile on success OR partial failure, so the cache matches the server.
|
||||
onSettled: () => qc.invalidateQueries({ queryKey: fullKey(gardenId) }),
|
||||
onError: (err) => toast.error(err instanceof Error ? err.message : 'Could not clear the bed.'),
|
||||
onError: (err) => toast.error(objectErrorMessage(err, 'Could not clear the bed.')),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -526,8 +526,9 @@ export function GardenEditorPage() {
|
||||
|
||||
{clearing && focusedObject && (
|
||||
<ClearBedModal
|
||||
objectId={focusedObject.id}
|
||||
objectName={objectDisplayName(focusedObject)}
|
||||
plops={focusedPlops.map((p) => ({ id: p.id, version: p.version }))}
|
||||
plopCount={focusedPlops.length}
|
||||
gardenId={gid}
|
||||
onClose={() => setClearing(false)}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user