Add garden objects backend: polymorphic CRUD + /full (#10)
Garden objects (beds, bags, containers, in-ground, trees, paths, structures) in one polymorphic table, following the #7 service conventions. - store/objects.go: scanObject + Create (RETURNING), Get, ListForGarden (z_index order), version-guarded Update (RETURNING, returns current row on conflict), Delete (plantings cascade via FK). - store/plantings.go + plants.go: the read side /full needs now — ListActivePlantingsForGarden (removed_at IS NULL) and ListReferencedPlants (distinct plants used by active plantings). Both return empty until #14 adds plantings; #12/#14 extend these files. - service/objects.go: Create/Update(partial patch)/Delete/GardenFull, all (ctx, actorID, ...) through requireGardenRole(editor for mutations, viewer for /full). finalizeObject validates kind + shape (rect/circle; polygon reserved), finite dims in [1cm,100m], NaN/Inf rejection, loose bbox-overlaps-garden placement (partial overhang OK), hex color, valid JSON props, name/notes caps; normalizes rotation to [0,360). Plantable defaults by kind, overridable. - api/objects.go: POST /gardens/:id/objects, PATCH/DELETE /objects/:id, GET /gardens/:id/full ({garden,objects,plantings,plants}). props is any JSON value stored as text; PATCH is partial + required version, 409 returns the current row. Tests: service (defaults, plantable-by-kind, rotation normalize, validation rejects incl. off-field/polygon/bad-color/bad-props, partial patch + version conflict, cross-user ErrNotFound, delete, /full shape) and api (CRUD + /full, 409 envelope, cross-user 404, polygon/no-kind 400, props round-trip). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -81,6 +81,14 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
|
||||
gardens.GET("/:id", h.getGarden)
|
||||
gardens.PATCH("/:id", h.updateGarden)
|
||||
gardens.DELETE("/:id", h.deleteGarden)
|
||||
gardens.GET("/:id/full", h.gardenFull) // one-shot editor load
|
||||
gardens.POST("/:id/objects", h.createObject)
|
||||
|
||||
// Objects are addressed by their own id; the service resolves the owning
|
||||
// garden for the permission check.
|
||||
objects := v1.Group("/objects", h.requireAuth())
|
||||
objects.PATCH("/:id", h.updateObject)
|
||||
objects.DELETE("/:id", h.deleteObject)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
|
||||
)
|
||||
|
||||
// objectCreateRequest is the body for POST /gardens/:id/objects. Dimensions are
|
||||
// centimeters; the object is positioned by its center. Plantable/color/props are
|
||||
// optional (plantable defaults by kind). props is any JSON value, stored as-is.
|
||||
type objectCreateRequest struct {
|
||||
Kind string `json:"kind" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
Shape string `json:"shape"`
|
||||
XCM float64 `json:"xCm"`
|
||||
YCM float64 `json:"yCm"`
|
||||
WidthCM float64 `json:"widthCm"`
|
||||
HeightCM float64 `json:"heightCm"`
|
||||
RotationDeg float64 `json:"rotationDeg"`
|
||||
ZIndex int `json:"zIndex"`
|
||||
Plantable *bool `json:"plantable"`
|
||||
Color *string `json:"color"`
|
||||
Props json.RawMessage `json:"props"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
// objectUpdateRequest is the body for PATCH /objects/:id: every field optional
|
||||
// (absent = unchanged), plus the required current version. Kind and shape are
|
||||
// immutable and not accepted.
|
||||
type objectUpdateRequest struct {
|
||||
Name *string `json:"name"`
|
||||
XCM *float64 `json:"xCm"`
|
||||
YCM *float64 `json:"yCm"`
|
||||
WidthCM *float64 `json:"widthCm"`
|
||||
HeightCM *float64 `json:"heightCm"`
|
||||
RotationDeg *float64 `json:"rotationDeg"`
|
||||
ZIndex *int `json:"zIndex"`
|
||||
Plantable *bool `json:"plantable"`
|
||||
Color *string `json:"color"`
|
||||
Props json.RawMessage `json:"props"`
|
||||
Notes *string `json:"notes"`
|
||||
Version int64 `json:"version" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// propsFromRaw maps a JSON props value to the stored *string: a present, non-null
|
||||
// value becomes its JSON text; absent or null becomes nil (leave/none).
|
||||
func propsFromRaw(raw json.RawMessage) *string {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
s := string(raw)
|
||||
return &s
|
||||
}
|
||||
|
||||
func (h *handlers) createObject(c *gin.Context) {
|
||||
gardenID, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req objectCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "kind is required")
|
||||
return
|
||||
}
|
||||
o, err := h.svc.CreateObject(c.Request.Context(), mustActor(c).ID, gardenID, service.ObjectInput{
|
||||
Kind: req.Kind,
|
||||
Name: req.Name,
|
||||
Shape: req.Shape,
|
||||
XCM: req.XCM,
|
||||
YCM: req.YCM,
|
||||
WidthCM: req.WidthCM,
|
||||
HeightCM: req.HeightCM,
|
||||
RotationDeg: req.RotationDeg,
|
||||
ZIndex: req.ZIndex,
|
||||
Plantable: req.Plantable,
|
||||
Color: req.Color,
|
||||
Props: propsFromRaw(req.Props),
|
||||
Notes: req.Notes,
|
||||
})
|
||||
if err != nil {
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, o)
|
||||
}
|
||||
|
||||
func (h *handlers) updateObject(c *gin.Context) {
|
||||
id, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req objectUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a current version is required")
|
||||
return
|
||||
}
|
||||
o, err := h.svc.UpdateObject(c.Request.Context(), mustActor(c).ID, id, service.ObjectPatch{
|
||||
Name: req.Name,
|
||||
XCM: req.XCM,
|
||||
YCM: req.YCM,
|
||||
WidthCM: req.WidthCM,
|
||||
HeightCM: req.HeightCM,
|
||||
RotationDeg: req.RotationDeg,
|
||||
ZIndex: req.ZIndex,
|
||||
Plantable: req.Plantable,
|
||||
Color: req.Color,
|
||||
Props: propsFromRaw(req.Props),
|
||||
Notes: req.Notes,
|
||||
}, req.Version)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrVersionConflict) {
|
||||
writeVersionConflict(c, o)
|
||||
return
|
||||
}
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, o)
|
||||
}
|
||||
|
||||
func (h *handlers) deleteObject(c *gin.Context) {
|
||||
id, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteObject(c.Request.Context(), mustActor(c).ID, id); err != nil {
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *handlers) gardenFull(c *gin.Context) {
|
||||
gardenID, ok := parseIDParam(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
full, err := h.svc.GardenFull(c.Request.Context(), mustActor(c).ID, gardenID)
|
||||
if err != nil {
|
||||
writeServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, full)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// createGardenAPI creates a garden via the API and returns its id.
|
||||
func createGardenAPI(t *testing.T, r *gin.Engine, cookie *http.Cookie, name string) int64 {
|
||||
t.Helper()
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": name}, cookie)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create garden: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
return int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
||||
}
|
||||
|
||||
func objectPath(id int64) string { return "/api/v1/objects/" + strconv.FormatInt(id, 10) }
|
||||
func fullPath(id int64) string { return "/api/v1/gardens/" + strconv.FormatInt(id, 10) + "/full" }
|
||||
func objectsPath(id int64) string {
|
||||
return "/api/v1/gardens/" + strconv.FormatInt(id, 10) + "/objects"
|
||||
}
|
||||
|
||||
func TestObjectCRUDAndFull(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
gid := createGardenAPI(t, r, cookie, "Yard")
|
||||
|
||||
// Create a bed.
|
||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||
map[string]any{"kind": "bed", "name": "Bed 1", "xCm": 300, "yCm": 300, "widthCm": 200, "heightCm": 100}, cookie)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create object: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
obj := decodeGarden(t, w.Body.Bytes())
|
||||
oid := int64(obj["id"].(float64))
|
||||
if obj["plantable"].(bool) != true {
|
||||
t.Error("bed should default plantable=true")
|
||||
}
|
||||
|
||||
// /full includes it, with empty plantings/plants.
|
||||
w = doJSON(t, r, http.MethodGet, fullPath(gid), nil, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("full: status %d", w.Code)
|
||||
}
|
||||
var full struct {
|
||||
Garden map[string]any `json:"garden"`
|
||||
Objects []map[string]any `json:"objects"`
|
||||
Plantings []map[string]any `json:"plantings"`
|
||||
Plants []map[string]any `json:"plants"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &full); err != nil {
|
||||
t.Fatalf("decode full: %v (body %s)", err, w.Body.String())
|
||||
}
|
||||
if full.Garden == nil || len(full.Objects) != 1 {
|
||||
t.Errorf("full shape wrong: %+v", full)
|
||||
}
|
||||
if full.Plantings == nil || full.Plants == nil || len(full.Plantings) != 0 || len(full.Plants) != 0 {
|
||||
t.Errorf("plantings/plants should be present + empty: %+v %+v", full.Plantings, full.Plants)
|
||||
}
|
||||
|
||||
// Move it (PATCH with version).
|
||||
w = doJSON(t, r, http.MethodPatch, objectPath(oid), map[string]any{"xCm": 500, "yCm": 500, "version": 1}, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch: status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
patched := decodeGarden(t, w.Body.Bytes())
|
||||
if patched["xCm"].(float64) != 500 || patched["version"].(float64) != 2 {
|
||||
t.Errorf("patch didn't apply/bump: %+v", patched)
|
||||
}
|
||||
|
||||
// Delete → 204, then /full has none.
|
||||
if w := doJSON(t, r, http.MethodDelete, objectPath(oid), nil, cookie); w.Code != http.StatusNoContent {
|
||||
t.Fatalf("delete: status %d", w.Code)
|
||||
}
|
||||
w = doJSON(t, r, http.MethodGet, fullPath(gid), nil, cookie)
|
||||
json.Unmarshal(w.Body.Bytes(), &full)
|
||||
if len(full.Objects) != 0 {
|
||||
t.Errorf("object still in /full after delete: %d", len(full.Objects))
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectVersionConflict(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
gid := createGardenAPI(t, r, cookie, "Yard")
|
||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, cookie)
|
||||
oid := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
||||
|
||||
body := map[string]any{"xCm": 400, "version": 1}
|
||||
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), body, cookie); w.Code != http.StatusOK {
|
||||
t.Fatalf("first patch: %d", w.Code)
|
||||
}
|
||||
w = doJSON(t, r, http.MethodPatch, objectPath(oid), body, cookie) // stale version 1
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("stale patch: status %d, want 409", w.Code)
|
||||
}
|
||||
var env struct {
|
||||
Error struct{ Code string } `json:"error"`
|
||||
Current map[string]any `json:"current"`
|
||||
}
|
||||
json.Unmarshal(w.Body.Bytes(), &env)
|
||||
if env.Error.Code != "VERSION_CONFLICT" || env.Current["version"].(float64) != 2 {
|
||||
t.Errorf("conflict envelope wrong: %+v", env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectCrossUserIsNotFound(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
alice := registerAndCookie(t, r, "[email protected]")
|
||||
bob := registerAndCookie(t, r, "[email protected]")
|
||||
gid := createGardenAPI(t, r, alice, "Alice's")
|
||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, alice)
|
||||
oid := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
||||
|
||||
// Bob can't see the garden or its objects — all 404.
|
||||
if w := doJSON(t, r, http.MethodGet, fullPath(gid), nil, bob); w.Code != http.StatusNotFound {
|
||||
t.Errorf("bob full = %d, want 404", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPost, objectsPath(gid), map[string]any{"kind": "bed", "xCm": 1, "yCm": 1, "widthCm": 10, "heightCm": 10}, bob); w.Code != http.StatusNotFound {
|
||||
t.Errorf("bob create object = %d, want 404", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), map[string]any{"xCm": 1, "version": 1}, bob); w.Code != http.StatusNotFound {
|
||||
t.Errorf("bob patch = %d, want 404", w.Code)
|
||||
}
|
||||
if w := doJSON(t, r, http.MethodDelete, objectPath(oid), nil, bob); w.Code != http.StatusNotFound {
|
||||
t.Errorf("bob delete = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectValidationRejects(t *testing.T) {
|
||||
r := authEngine(t, localCfg())
|
||||
cookie := registerAndCookie(t, r, "[email protected]")
|
||||
gid := createGardenAPI(t, r, cookie, "Yard")
|
||||
|
||||
// Polygon shape is reserved → 400.
|
||||
if w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||
map[string]any{"kind": "bed", "shape": "polygon", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("polygon create = %d, want 400", w.Code)
|
||||
}
|
||||
// Missing kind → 400.
|
||||
if w := doJSON(t, r, http.MethodPost, objectsPath(gid), map[string]any{"xCm": 1, "yCm": 1, "widthCm": 10, "heightCm": 10}, cookie); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("no-kind create = %d, want 400", w.Code)
|
||||
}
|
||||
// props accepts a JSON object and round-trips.
|
||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||
map[string]any{"kind": "tree", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100, "props": map[string]any{"species": "oak"}}, cookie)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("props create = %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
if props, _ := decodeGarden(t, w.Body.Bytes())["props"].(string); props == "" {
|
||||
t.Error("props should be stored and returned as a JSON string")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user