Add plant catalog backend: CRUD + seeded built-ins (#12)
Build image / build-and-push (push) Successful in 5s
Gadfly review (reusable) / review (pull_request) Successful in 10m32s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m32s

Extends the plants store (which had only the /full read side) with full
catalog CRUD, adds a service layer with visibility/immutability rules, REST
endpoints, and a seed migration of ~32 built-ins.

- 0003_seed_plants.sql: 32 built-in plants (owner_id NULL, read-only), seeded
  once by the version-tracked migration runner.
- store: ListPlantsForActor (built-ins + own), Get/Create/Update/Delete +
  CountPlantingsForPlant; isForeignKeyViolation backstop for the RESTRICT FK.
- service: built-ins are read-only (ErrForbidden); another user's plants are
  invisible (ErrNotFound); delete of a referenced plant → ErrPlantInUse (409);
  validation mirrors the schema (category enum, spacing>0, hex color, icon).
- api: GET,POST /plants and PATCH,DELETE /plants/:id with the version guard.
- Made the migration-count store tests derive their expectation from the files
  so future migrations don't break them.

Service + API tests cover visibility, built-in immutability, validation,
version conflict, and delete-in-use.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
2026-07-18 21:33:12 -04:00
co-authored by Claude Opus 4.8
parent b79bfcf7a9
commit 78dbadf95c
11 changed files with 871 additions and 4 deletions
+7
View File
@@ -90,6 +90,13 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
objects.PATCH("/:id", h.updateObject)
objects.DELETE("/:id", h.deleteObject)
// Plant catalog: built-ins (seeded, read-only) plus the actor's own rows.
plants := v1.Group("/plants", h.requireAuth())
plants.GET("", h.listPlants)
plants.POST("", h.createPlant)
plants.PATCH("/:id", h.updatePlant)
plants.DELETE("/:id", h.deletePlant)
return r
}
+2
View File
@@ -28,6 +28,8 @@ func writeServiceError(c *gin.Context, err error) {
writeAPIError(c, http.StatusForbidden, "FORBIDDEN", "you don't have access")
case errors.Is(err, domain.ErrVersionConflict):
writeAPIError(c, http.StatusConflict, "VERSION_CONFLICT", "the resource was modified; refetch and retry")
case errors.Is(err, domain.ErrPlantInUse):
writeAPIError(c, http.StatusConflict, "PLANT_IN_USE", "this plant is used by plantings and can't be deleted")
case errors.Is(err, domain.ErrInvalidCredentials):
writeAPIError(c, http.StatusUnauthorized, "INVALID_CREDENTIALS", "invalid email or password")
case errors.Is(err, domain.ErrEmailTaken):
+133
View File
@@ -0,0 +1,133 @@
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"
)
// plantCreateRequest is the body for POST /plants. spacingCm is centimeters;
// color is a hex string; icon is an emoji. daysToMaturity is optional.
type plantCreateRequest struct {
Name string `json:"name" binding:"required"`
Category string `json:"category" binding:"required"`
SpacingCM float64 `json:"spacingCm"`
Color string `json:"color" binding:"required"`
Icon string `json:"icon" binding:"required"`
DaysToMaturity *int `json:"daysToMaturity"`
Notes string `json:"notes"`
}
func (r plantCreateRequest) toInput() service.PlantInput {
return service.PlantInput{
Name: r.Name, Category: r.Category, SpacingCM: r.SpacingCM,
Color: r.Color, Icon: r.Icon, DaysToMaturity: r.DaysToMaturity, Notes: r.Notes,
}
}
// plantUpdateRequest is the body for PATCH /plants/:id: every field optional
// (absent = unchanged), plus the required current version. daysToMaturity is
// json.RawMessage so an explicit null (clear it) is distinct from an absent
// field (unchanged).
type plantUpdateRequest struct {
Name *string `json:"name"`
Category *string `json:"category"`
SpacingCM *float64 `json:"spacingCm"`
Color *string `json:"color"`
Icon *string `json:"icon"`
DaysToMaturity json.RawMessage `json:"daysToMaturity"`
Notes *string `json:"notes"`
Version int64 `json:"version" binding:"required,min=1"`
}
func (r plantUpdateRequest) toPatch() (service.PlantPatch, error) {
days, setDays, err := parseNullableInt(r.DaysToMaturity)
if err != nil {
return service.PlantPatch{}, err
}
return service.PlantPatch{
Name: r.Name, Category: r.Category, SpacingCM: r.SpacingCM,
Color: r.Color, Icon: r.Icon,
SetDays: setDays, DaysToMaturity: days, Notes: r.Notes,
}, nil
}
// parseNullableInt decodes a JSON number|null field into (value, present).
// Absent → (nil, false); null → (nil, true); 42 → (&42, true). A non-integer
// value is an error.
func parseNullableInt(raw json.RawMessage) (value *int, present bool, err error) {
if len(raw) == 0 {
return nil, false, nil
}
if err := json.Unmarshal(raw, &value); err != nil {
return nil, false, err
}
return value, true, nil
}
func (h *handlers) listPlants(c *gin.Context) {
plants, err := h.svc.ListPlants(c.Request.Context(), mustActor(c).ID)
if err != nil {
writeServiceError(c, err)
return
}
c.JSON(http.StatusOK, plants)
}
func (h *handlers) createPlant(c *gin.Context) {
var req plantCreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "name, category, color and icon are required")
return
}
p, err := h.svc.CreatePlant(c.Request.Context(), mustActor(c).ID, req.toInput())
if err != nil {
writeServiceError(c, err)
return
}
c.JSON(http.StatusCreated, p)
}
func (h *handlers) updatePlant(c *gin.Context) {
id, ok := parseIDParam(c, "id")
if !ok {
return
}
var req plantUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a current version is required")
return
}
patch, err := req.toPatch()
if err != nil {
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid update payload")
return
}
p, err := h.svc.UpdatePlant(c.Request.Context(), mustActor(c).ID, id, patch, req.Version)
if err != nil {
if errors.Is(err, domain.ErrVersionConflict) {
writeVersionConflict(c, p)
return
}
writeServiceError(c, err)
return
}
c.JSON(http.StatusOK, p)
}
func (h *handlers) deletePlant(c *gin.Context) {
id, ok := parseIDParam(c, "id")
if !ok {
return
}
if err := h.svc.DeletePlant(c.Request.Context(), mustActor(c).ID, id); err != nil {
writeServiceError(c, err)
return
}
c.Status(http.StatusNoContent)
}
+100
View File
@@ -0,0 +1,100 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"testing"
)
func plantPath(id int64) string {
return "/api/v1/plants/" + strconv.FormatInt(id, 10)
}
// firstBuiltinID returns the id of a seeded built-in (no ownerId key) from a
// /plants list response, plus the total count.
func firstBuiltinID(t *testing.T, body []byte) (int64, int) {
t.Helper()
var list []map[string]any
if err := json.Unmarshal(body, &list); err != nil {
t.Fatalf("decode plants list: %v (body %s)", err, body)
}
for _, p := range list {
if _, owned := p["ownerId"]; !owned {
return int64(p["id"].(float64)), len(list)
}
}
t.Fatal("no built-in plant in list")
return 0, 0
}
func TestPlantCatalogFlow(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
// List → seeded built-ins present.
w := doJSON(t, r, http.MethodGet, "/api/v1/plants", nil, cookie)
if w.Code != http.StatusOK {
t.Fatalf("list status = %d, body %s", w.Code, w.Body.String())
}
builtinID, count := firstBuiltinID(t, w.Body.Bytes())
if count < 30 {
t.Errorf("catalog = %d plants, want >= 30 seeded", count)
}
// Create a custom plant → 201.
w = doJSON(t, r, http.MethodPost, "/api/v1/plants",
map[string]any{"name": "My tomato", "category": "vegetable", "spacingCm": 55, "color": "#e53935", "icon": "🍅"}, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
}
created := decodeMap(t, w.Body.Bytes())
id := int64(created["id"].(float64))
if created["ownerId"] == nil {
t.Error("custom plant should carry ownerId")
}
// Patch the custom plant with its version → 200, bumped.
w = doJSON(t, r, http.MethodPatch, plantPath(id), map[string]any{"spacingCm": 50, "version": 1}, cookie)
if w.Code != http.StatusOK {
t.Fatalf("patch status = %d, body %s", w.Code, w.Body.String())
}
if decodeMap(t, w.Body.Bytes())["version"].(float64) != 2 {
t.Error("patch didn't bump version")
}
// A built-in is read-only: patch and delete both → 403.
if w := doJSON(t, r, http.MethodPatch, plantPath(builtinID), map[string]any{"spacingCm": 99, "version": 1}, cookie); w.Code != http.StatusForbidden {
t.Errorf("patch built-in = %d, want 403", w.Code)
}
if w := doJSON(t, r, http.MethodDelete, plantPath(builtinID), nil, cookie); w.Code != http.StatusForbidden {
t.Errorf("delete built-in = %d, want 403", w.Code)
}
// Delete the custom plant → 204.
if w := doJSON(t, r, http.MethodDelete, plantPath(id), nil, cookie); w.Code != http.StatusNoContent {
t.Errorf("delete custom = %d, want 204", w.Code)
}
}
func TestPlantVisibilityAcrossUsersAPI(t *testing.T) {
r := authEngine(t, localCfg())
alice := registerAndCookie(t, r, "[email protected]")
bob := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/plants",
map[string]any{"name": "Alice mint", "category": "herb", "spacingCm": 30, "color": "#66bb6a", "icon": "🌿"}, alice)
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
// Bob can't see it → editing masks as 404, not 403.
if w := doJSON(t, r, http.MethodPatch, plantPath(id), map[string]any{"name": "x", "version": 1}, bob); w.Code != http.StatusNotFound {
t.Errorf("bob patch alice's plant = %d, want 404", w.Code)
}
}
func TestPlantsRequireAuth(t *testing.T) {
r := authEngine(t, localCfg())
if w := doJSON(t, r, http.MethodGet, "/api/v1/plants", nil, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated list = %d, want 401", w.Code)
}
}