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
+188
View File
@@ -0,0 +1,188 @@
package service
import (
"context"
"strings"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// Plant field bounds. Spacing is mature in-row spacing in cm; the ceiling is a
// generous sanity limit (also rejecting NaN/Inf). Name/notes are length-capped so
// untrusted input can't balloon storage; icon holds one emoji (possibly a
// multi-codepoint ZWJ sequence, hence a byte cap rather than length 1).
const (
maxPlantNameLen = 200
maxPlantNotesLen = 10_000
maxPlantIconLen = 32
minPlantSpacingCM = 0.1
maxPlantSpacingCM = 10_000 // 100 m — headroom for large trees/shrubs
maxDaysToMaturity = 3650 // ~10 years
)
// plantCategories is the set of valid category enum values (mirrors the schema
// CHECK constraint in 0001_init.sql).
var plantCategories = map[string]struct{}{
domain.CategoryVegetable: {},
domain.CategoryHerb: {},
domain.CategoryFlower: {},
domain.CategoryFruit: {},
domain.CategoryTreeShrub: {},
domain.CategoryCover: {},
}
// PlantInput is the mutable field set for creating a plant. DaysToMaturity is
// optional (nil = unknown).
type PlantInput struct {
Name string
Category string
SpacingCM float64
Color string
Icon string
DaysToMaturity *int
Notes string
}
// PlantPatch is a partial update: nil fields are left unchanged. DaysToMaturity
// is itself nullable, so SetDays distinguishes "clear to NULL" (SetDays=true,
// value nil) from "leave unchanged" (SetDays=false) — a plain nil can't.
type PlantPatch struct {
Name *string
Category *string
SpacingCM *float64
Color *string
Icon *string
SetDays bool
DaysToMaturity *int
Notes *string
}
// ListPlants returns the plants the actor can see: built-ins plus their own.
func (s *Service) ListPlants(ctx context.Context, actorID int64) ([]domain.Plant, error) {
return s.store.ListPlantsForActor(ctx, actorID)
}
// CreatePlant adds a plant owned by the actor. To "clone" a built-in the client
// simply POSTs a copy — there is no dedicated endpoint, and the copy is owned by
// (and editable by) the actor.
func (s *Service) CreatePlant(ctx context.Context, actorID int64, in PlantInput) (*domain.Plant, error) {
p := &domain.Plant{
Name: strings.TrimSpace(in.Name),
Category: in.Category,
SpacingCM: in.SpacingCM,
Color: in.Color,
Icon: strings.TrimSpace(in.Icon),
DaysToMaturity: in.DaysToMaturity,
Notes: strings.TrimSpace(in.Notes),
}
if err := finalizePlant(p); err != nil {
return nil, err
}
owner := actorID
p.OwnerID = &owner
return s.store.CreatePlant(ctx, p)
}
// writablePlant loads a plant and enforces that the actor may modify it. It is
// THE authorization point for plant mutation. Built-in rows (owner_id nil) are
// visible to everyone but read-only → ErrForbidden. A row owned by someone else
// is invisible → ErrNotFound (masking existence, as gardens/objects do). Only the
// actor's own rows are writable.
func (s *Service) writablePlant(ctx context.Context, actorID, plantID int64) (*domain.Plant, error) {
p, err := s.store.GetPlant(ctx, plantID)
if err != nil {
return nil, err // ErrNotFound
}
if p.OwnerID == nil {
return nil, domain.ErrForbidden // built-in: seeded and read-only
}
if *p.OwnerID != actorID {
return nil, domain.ErrNotFound // another user's plant: not visible
}
return p, nil
}
// UpdatePlant applies a partial, version-guarded patch to the actor's own plant.
// On a version mismatch it returns (current, ErrVersionConflict).
func (s *Service) UpdatePlant(ctx context.Context, actorID, plantID int64, patch PlantPatch, version int64) (*domain.Plant, error) {
p, err := s.writablePlant(ctx, actorID, plantID)
if err != nil {
return nil, err
}
applyPlantPatch(p, patch)
if err := finalizePlant(p); err != nil {
return nil, err
}
p.Version = version
return s.store.UpdatePlant(ctx, p)
}
// DeletePlant removes the actor's own plant. A plant still referenced by any
// planting (even a removed one — the FK is RESTRICT) is refused with
// ErrPlantInUse rather than orphaning history; the client clones-and-edits or
// clears the plantings first.
func (s *Service) DeletePlant(ctx context.Context, actorID, plantID int64) error {
if _, err := s.writablePlant(ctx, actorID, plantID); err != nil {
return err
}
n, err := s.store.CountPlantingsForPlant(ctx, plantID)
if err != nil {
return err
}
if n > 0 {
return domain.ErrPlantInUse
}
return s.store.DeletePlant(ctx, plantID)
}
// applyPlantPatch mutates p with each provided (non-nil) patch field.
func applyPlantPatch(p *domain.Plant, patch PlantPatch) {
if patch.Name != nil {
p.Name = strings.TrimSpace(*patch.Name)
}
if patch.Category != nil {
p.Category = *patch.Category
}
if patch.SpacingCM != nil {
p.SpacingCM = *patch.SpacingCM
}
if patch.Color != nil {
p.Color = *patch.Color
}
if patch.Icon != nil {
p.Icon = strings.TrimSpace(*patch.Icon)
}
if patch.SetDays {
p.DaysToMaturity = patch.DaysToMaturity
}
if patch.Notes != nil {
p.Notes = strings.TrimSpace(*patch.Notes)
}
}
// finalizePlant validates a built/merged plant. Shared by create and update so
// both enforce the same invariants. isFinite/isHexColor live in objects.go.
func finalizePlant(p *domain.Plant) error {
if p.Name == "" || len(p.Name) > maxPlantNameLen {
return domain.ErrInvalidInput
}
if _, ok := plantCategories[p.Category]; !ok {
return domain.ErrInvalidInput
}
if !isFinite(p.SpacingCM) || p.SpacingCM < minPlantSpacingCM || p.SpacingCM > maxPlantSpacingCM {
return domain.ErrInvalidInput
}
if !isHexColor(p.Color) {
return domain.ErrInvalidInput
}
if p.Icon == "" || len(p.Icon) > maxPlantIconLen {
return domain.ErrInvalidInput
}
if p.DaysToMaturity != nil && (*p.DaysToMaturity < 1 || *p.DaysToMaturity > maxDaysToMaturity) {
return domain.ErrInvalidInput
}
if len(p.Notes) > maxPlantNotesLen {
return domain.ErrInvalidInput
}
return nil
}
+239
View File
@@ -0,0 +1,239 @@
package service
import (
"context"
"errors"
"strings"
"testing"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
func intPtr(n int) *int { return &n }
// validPlant is a well-formed PlantInput for tests to tweak.
func validPlant(name string) PlantInput {
return PlantInput{Name: name, Category: domain.CategoryHerb, SpacingCM: 25, Color: "#4a7c3f", Icon: "🌿"}
}
func TestListPlantsIncludesSeededBuiltins(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
plants, err := s.ListPlants(context.Background(), owner)
if err != nil {
t.Fatalf("ListPlants: %v", err)
}
// The 0003 seed ships a catalog; assert it's there and all built-ins.
if len(plants) < 30 {
t.Fatalf("seeded catalog = %d plants, want >= 30", len(plants))
}
for _, p := range plants {
if p.OwnerID != nil {
t.Fatalf("unexpected non-builtin in a fresh catalog: %+v", p)
}
}
// Find a known one.
var found bool
for _, p := range plants {
if p.Name == "Garlic" {
found = true
if p.SpacingCM != 15 || p.Icon != "🧄" {
t.Errorf("Garlic seeded wrong: %+v", p)
}
}
}
if !found {
t.Error("expected seeded Garlic in the catalog")
}
}
func TestCreatePlantIsOwnedAndTrimmed(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
in := validPlant(" Purple basil ")
in.DaysToMaturity = intPtr(60)
p, err := s.CreatePlant(context.Background(), owner, in)
if err != nil {
t.Fatalf("CreatePlant: %v", err)
}
if p.OwnerID == nil || *p.OwnerID != owner {
t.Errorf("owner = %v, want %d", p.OwnerID, owner)
}
if p.Name != "Purple basil" {
t.Errorf("name = %q, want trimmed", p.Name)
}
if p.Version != 1 || p.DaysToMaturity == nil || *p.DaysToMaturity != 60 {
t.Errorf("unexpected plant: %+v", p)
}
}
func TestPlantVisibilityAcrossUsers(t *testing.T) {
s := newTestService(t, openConfig())
alice := seedUser(t, s, "[email protected]")
bob := seedUser(t, s, "[email protected]")
p, err := s.CreatePlant(context.Background(), alice, validPlant("Alice's mint"))
if err != nil {
t.Fatalf("CreatePlant: %v", err)
}
// Bob's catalog: built-ins only, none of Alice's.
bobList, err := s.ListPlants(context.Background(), bob)
if err != nil {
t.Fatalf("ListPlants(bob): %v", err)
}
for _, bp := range bobList {
if bp.ID == p.ID {
t.Fatal("bob can see alice's custom plant")
}
}
// Bob can neither edit nor delete it — invisibility masks it as ErrNotFound.
nm := "hijack"
if _, err := s.UpdatePlant(context.Background(), bob, p.ID, PlantPatch{Name: &nm}, p.Version); !errors.Is(err, domain.ErrNotFound) {
t.Errorf("bob update err = %v, want ErrNotFound", err)
}
if err := s.DeletePlant(context.Background(), bob, p.ID); !errors.Is(err, domain.ErrNotFound) {
t.Errorf("bob delete err = %v, want ErrNotFound", err)
}
}
func TestBuiltinPlantsAreReadOnly(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
plants, _ := s.ListPlants(context.Background(), owner)
builtin := plants[0] // seeded, owner_id nil
if builtin.OwnerID != nil {
t.Fatalf("expected a built-in, got %+v", builtin)
}
nm := "tweaked"
if _, err := s.UpdatePlant(context.Background(), owner, builtin.ID, PlantPatch{Name: &nm}, builtin.Version); !errors.Is(err, domain.ErrForbidden) {
t.Errorf("edit built-in err = %v, want ErrForbidden", err)
}
if err := s.DeletePlant(context.Background(), owner, builtin.ID); !errors.Is(err, domain.ErrForbidden) {
t.Errorf("delete built-in err = %v, want ErrForbidden", err)
}
}
func TestCloneBuiltinThenEdit(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
plants, _ := s.ListPlants(context.Background(), owner)
src := plants[0]
// "Clone" = POST a copy; it's now owned and editable.
clone, err := s.CreatePlant(context.Background(), owner, PlantInput{
Name: src.Name + " (mine)", Category: src.Category, SpacingCM: src.SpacingCM, Color: src.Color, Icon: src.Icon,
})
if err != nil {
t.Fatalf("clone: %v", err)
}
sp := 12.0
updated, err := s.UpdatePlant(context.Background(), owner, clone.ID, PlantPatch{SpacingCM: &sp}, clone.Version)
if err != nil {
t.Fatalf("edit clone: %v", err)
}
if updated.SpacingCM != 12 || updated.Version != clone.Version+1 {
t.Errorf("clone edit didn't apply: %+v", updated)
}
}
func TestUpdatePlantClearsDays(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
in := validPlant("Dill")
in.DaysToMaturity = intPtr(50)
p, _ := s.CreatePlant(context.Background(), owner, in)
// SetDays with nil clears; absent (SetDays=false) would leave it.
cleared, err := s.UpdatePlant(context.Background(), owner, p.ID, PlantPatch{SetDays: true, DaysToMaturity: nil}, p.Version)
if err != nil {
t.Fatalf("clear days: %v", err)
}
if cleared.DaysToMaturity != nil {
t.Errorf("daysToMaturity = %v, want nil", *cleared.DaysToMaturity)
}
}
func TestPlantVersionConflict(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
p, _ := s.CreatePlant(context.Background(), owner, validPlant("Sage"))
sp := 30.0
if _, err := s.UpdatePlant(context.Background(), owner, p.ID, PlantPatch{SpacingCM: &sp}, p.Version); err != nil {
t.Fatalf("first update: %v", err)
}
// Stale version → conflict + current row.
current, err := s.UpdatePlant(context.Background(), owner, p.ID, PlantPatch{SpacingCM: &sp}, p.Version)
if !errors.Is(err, domain.ErrVersionConflict) {
t.Fatalf("stale update err = %v, want ErrVersionConflict", err)
}
if current == nil || current.Version != 2 {
t.Errorf("conflict didn't return current row: %+v", current)
}
}
func TestCreatePlantValidation(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
bad := []PlantInput{
{Name: "", Category: domain.CategoryHerb, SpacingCM: 10, Color: "#4a7c3f", Icon: "🌿"}, // empty name
{Name: "x", Category: "spaceship", SpacingCM: 10, Color: "#4a7c3f", Icon: "🌿"}, // bad category
{Name: "x", Category: domain.CategoryHerb, SpacingCM: 0, Color: "#4a7c3f", Icon: "🌿"}, // zero spacing
{Name: "x", Category: domain.CategoryHerb, SpacingCM: -5, Color: "#4a7c3f", Icon: "🌿"}, // negative spacing
{Name: "x", Category: domain.CategoryHerb, SpacingCM: 10, Color: "nope", Icon: "🌿"}, // bad color
{Name: "x", Category: domain.CategoryHerb, SpacingCM: 10, Color: "#4a7c3f", Icon: ""}, // empty icon
{Name: strings.Repeat("x", maxPlantNameLen+1), Category: domain.CategoryHerb, SpacingCM: 10, Color: "#4a7c3f", Icon: "🌿"}, // name too long
{Name: "x", Category: domain.CategoryHerb, SpacingCM: 10, Color: "#4a7c3f", Icon: "🌿", DaysToMaturity: intPtr(0)}, // days must be >= 1
}
for i, in := range bad {
if _, err := s.CreatePlant(context.Background(), owner, in); !errors.Is(err, domain.ErrInvalidInput) {
t.Errorf("case %d: err = %v, want ErrInvalidInput", i, err)
}
}
// A shorthand hex (#rgb) and a set days value pass.
ok := validPlant("Thyme")
ok.Color = "#0a0"
ok.DaysToMaturity = intPtr(90)
if _, err := s.CreatePlant(context.Background(), owner, ok); err != nil {
t.Errorf("valid plant rejected: %v", err)
}
}
func TestDeletePlantInUseIsBlocked(t *testing.T) {
s := newTestService(t, openConfig())
owner := seedUser(t, s, "[email protected]")
g := seedGarden(t, s, owner)
bed, _ := s.CreateObject(context.Background(), owner, g.ID, ObjectInput{
Kind: domain.KindBed, XCM: 500, YCM: 500, WidthCM: 200, HeightCM: 200,
})
plant, _ := s.CreatePlant(context.Background(), owner, validPlant("Basil"))
// Plantings CRUD is #14; insert a plop directly so the plant is referenced.
if _, err := s.store.SQL().ExecContext(context.Background(),
`INSERT INTO plantings (object_id, plant_id, x_cm, y_cm, radius_cm) VALUES (?, ?, 0, 0, 10)`,
bed.ID, plant.ID,
); err != nil {
t.Fatalf("seed planting: %v", err)
}
if err := s.DeletePlant(context.Background(), owner, plant.ID); !errors.Is(err, domain.ErrPlantInUse) {
t.Fatalf("delete in-use plant err = %v, want ErrPlantInUse", err)
}
// Clearing the reference frees the delete.
if _, err := s.store.SQL().ExecContext(context.Background(), `DELETE FROM plantings WHERE plant_id = ?`, plant.ID); err != nil {
t.Fatalf("clear planting: %v", err)
}
if err := s.DeletePlant(context.Background(), owner, plant.ID); err != nil {
t.Errorf("delete freed plant: %v", err)
}
}