Files
multica/server/internal/handler/property_test.go
Jiayuan Zhang b85bb71a58 feat: custom issue properties — typed workspace-defined fields with list-surface support (MUL-4463) (#5335)
* feat(server): custom issue properties — definitions, typed values, CLI (MUL-4463)

Workspace-level property definitions (issue_property table; 7 types:
text/number/select/multi_select/date/checkbox/url) plus a typed value bag
on each issue (issue.properties JSONB keyed by definition UUID, mirroring
the metadata machinery: single-key atomic writes, 16KB cap, GIN index).

- Definitions: owner/admin only; agent actors rejected (agents propose,
  humans confirm). 20 active per workspace, 50 options per select,
  reserved built-in names blocked, archive instead of delete.
- Values: any member or agent; per-type validation with self-correcting
  error messages that enumerate legal option ids.
- API: /api/properties CRUD + PUT/DELETE /api/issues/{id}/properties/{propertyId};
  issue responses always emit the properties bag.
- CLI: multica property list/get/create/update/archive/unarchive and
  multica issue property list/set/unset with name→id translation.
- Events: property:created/updated, issue_properties:changed.

Co-authored-by: multica-agent <github@multica.ai>

* feat(web): custom properties settings tab + issue sidebar editors (MUL-4463)

- Settings → Properties: definition management mirroring the Labels tab
  (list with type badges/option chips/usage counts, create/edit dialog
  with option editor, archive/restore, 20-cap indicator). Admin-gated;
  members see a read-only catalog.
- Issue detail sidebar: custom properties join the built-in optional
  props' progressive disclosure — set values render as rows with
  type-appropriate editors (select/multi-select pickers, calendar,
  yes/no, inline input for text/number/url), unset ones live in the
  same '+ Add property' menu behind a separator. Archived definitions
  render read-only until cleared.
- Core: property types, zod schemas (lenient type strings for forward
  compat), api client methods, React Query hooks with optimistic
  single-key value writes, ws-updaters + realtime wiring for
  property:created/updated and issue_properties:changed.
- Locales: en/zh-Hans/ja/ko strings; Issue fixtures gain properties: {}.

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): address MUL-4463 review round 1 — mobile CI, option guard, mutation safety, schema tolerance

- mobile: EMPTY_ISSUE_FALLBACK gains the required properties field (mobile
  typecheck was the red CI check).
- server: PATCH /api/properties/{id} rejects config updates that remove
  select options still referenced by issues (409 with a per-option usage
  census via jsonb ?); renames keep ids and pass. Integration test included.
- core: property value mutations are serialized per workspace via mutation
  scope, snapshot the bag from detail OR list caches (board surfaces have no
  detail cache — the old path overwrote whole bags with one key), roll back
  to the snapshot or invalidate on error, and the last settled mutation does
  an authoritative detail+catalog invalidate (usage counts reconcile).
- schemas: unknown-shaped property values (future server types) are dropped
  per-entry in a preprocess step instead of failing the whole IssueSchema
  and blanking lists through parseWithFallback; test updated to lock the
  tolerant behavior.
- realtime: reconnect invalidation covers the property catalog; every
  issue_properties:changed event also refreshes catalog usage counts.
- ui: number editor accepts decimals (step=any); settings usage count
  pluralizes (issue/issues) with CJK-safe plural keys.

Co-authored-by: multica-agent <github@multica.ai>

* fix(migrations): renumber issue properties to 179 and build the GIN index concurrently

main's migration sequence advanced twice under this PR (167 collision, then
an upstream renumber wave that claimed 178), so issue properties now sits at
179 — verified against main's current tip by the prefix-uniqueness lint.

The properties GIN index moves to its own single-statement migration (180)
using CREATE INDEX CONCURRENTLY — a plain CREATE INDEX on the hot issue
table would block writes for the duration of the build. Mirrors the
119_user_created_at_index pattern; full-chain dry-run on a fresh database
passes through 180.

Co-authored-by: multica-agent <github@multica.ai>

* feat(web): custom-property list surfaces — filter, cards, sort, board grouping (MUL-4463 M2)

Brings custom properties to the issue list surfaces on top of the M1
definitions/values core:

- Filter: per-definition sections in the Filter dropdown (select /
  multi_select options with color dots and counts; checkbox as Yes/No
  pseudo-options). OR within a definition, AND across definitions;
  client-side in applyIssueFilters, mirrored into filterAssigneeGroups
  for the assignee-grouped board. Included in active-filter count and
  Clear all.
- Cards: per-property Display toggles (cardPropertyIds) render value
  chips on board cards and list rows via CustomPropertyValueDisplay.
- Sort: SortField gains property:<id> for number/date definitions.
  Server keeps position order (fixed sort enum); the surface controller
  re-sorts client-side, swimlane/gantt reuse the same comparator.
  Date-only strings compare lexically; missing values sort last.
- Board grouping: IssueGrouping gains property:<id> for select
  definitions — one column per option (definition order) plus a
  trailing No-value column, option-colored headings. Drag-drop moves
  position via UpdateIssue and applies the value through
  useSetIssueProperty/useUnsetIssueProperty (properties are not part
  of UpdateIssueRequest). Stale persisted property groupings fall back
  to status columns.

View-store: propertyFilters + cardPropertyIds persisted via the
partialize allowlist; clearFilters resets property filters; new fields
deep-merge cleanly into pre-existing persisted snapshots.

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): address MUL-4463 review round 2 — desc sort, option bucketing, archived-state reconciliation

- sort: direction now applies to value comparison only; issues without a
  value sort last in BOTH directions (the whole-array reverse flipped them
  to the front on desc). Test covers the desc+missing case.
- board: values referencing an option removed from the definition bucket
  into the No-value column instead of vanishing (unmatched column ids
  dropped the issue entirely). Defense-in-depth behind the new server-side
  in-use guard; drag-utils test locks both behaviors.
- controller: persisted propertyFilters keyed by archived/deleted
  definitions are stripped before reaching the filter predicates, and a
  persisted property sort on a non-active definition degrades to manual
  order — previously both kept silently applying while the header claimed
  otherwise. The filter badge counts only active-definition filters.

Co-authored-by: multica-agent <github@multica.ai>

* feat(properties): server-side property filtering and sorting on list endpoints

Property filter/sort now execute in the database, so results are correct
across the full issue set — not just the loaded 50-per-status window
(closes MUL-4493 item 1's filter/sort half; requested on MUL-4463).

- New `properties` query param on ListIssues and ListGroupedIssues:
  JSON {definitionId: [values]} compiled to an AND-of-ORs containment
  check (double NOT EXISTS over jsonb_array_elements). One value expands
  to every storage shape it could match — string (select), array element
  (multi_select), boolean (checkbox) — so the handler stays type-agnostic.
  Guarded at 20 definitions / 50 values.
- `sort=property:<definitionId>` resolves the definition and orders by a
  typed expression (numeric CASE cast for number, NULLIF text for
  date/text/url); missing values sort last in both directions. Malformed
  ids 400; unknown/archived definitions degrade to position order instead
  of breaking stale clients.
- Frontend: the property filter and property sort ride the IssueSortParam
  window bag, so every surface (workspace + my-issues variants), query
  key, and per-status load-more page carries them automatically. The
  client-side re-sort layer is gone; applyIssueFilters keeps its property
  predicate as an optimistic-update backstop.
- Regression test seeds 55 issues and proves a match at position 55 is
  returned by a filtered 50-row page, plus sort order/missing-last,
  AND-across-definitions, and the 400/fallback sort paths.

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): address review round 3 — cache reconcile, merged-scope order, GIN-indexable filter, pool loader

- Cache reconciliation: property value writes (mutation settle + WS event)
  now invalidate every issue window whose server-side shape depends on
  property values — queries filtered by `properties` or sorted by
  `property:<id>` (detected via query-key predicate), covering flat lists,
  assignee groups, and my-issues variants. Windows without property params
  keep the cheap in-place patch. Fixes stale ordering/membership/counts
  under staleTime:Infinity.
- My Issues "All" scope: merged assigned/created/involves results are
  re-sorted with a comparator mirroring the server ORDER BY semantics
  (including property sorts and missing-last, created_at DESC tiebreak) in
  both the flat and assignee-grouped merge paths — relation concatenation
  no longer overrides the user's sort.
- Filter predicate rebuilt as plain bind-parameter containment ORs
  (AND across definitions): EXPLAIN now shows BitmapOr over
  idx_issue_properties_gin (the correlated jsonb_array_elements form
  defeated the index). Alternatives capped at 256 bind params.
- Property-grouped board gains a pool loader strip: one sentinel per
  status that still has server rows, keeping every issue reachable until
  per-column pagination lands (MUL-4493).
- Windowing regression test hardened: explicit positions + an assertion
  that the unfiltered first page excludes the target (the old fixture tied
  at position 0 and the created_at DESC tiebreak put the target on page
  one, proving nothing).
- Rollback safety: /api/properties 404 (old server) degrades to an empty
  catalog instead of a query error, which also keeps property params from
  ever being sent to pre-property servers; migration 179's CHECK
  constraints switch to NOT VALID + VALIDATE so the exclusive lock is
  instantaneous.

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): harden concurrency and cache coordination from clean-room review

Backend (MUL-4762 F1/F4/F5):
- withPropertyLock: pg_advisory_xact_lock helper; definition create/update
  and value writes now serialize config-vs-value and cap-vs-insert races
  (workspace-level 'props:' lock + per-definition 'prop:' lock, ordered).
- propertySortExpr degrades archived definitions to position sort.

Frontend (F2/F3/F6):
- onIssuePropertiesChanged invalidates plain assignee-group caches too.
- Property value mutations cancel list refetches in onMutate and roll back
  only the touched key against the current bag (concurrent WS writes to
  other keys survive a failed write).
- useUpdateIssue reconcile drops the stale properties bag from the server
  snapshot; the property pipeline owns that field.
- Surface controller passes persisted property filters/sorts through
  until the catalog query settles (cold cache no longer strips them).

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): open_only branch honors the properties filter

ListOpenIssues takes the parsed AND-of-ORs containment groups as a single
jsonb properties_filter param and unrolls them with a static double
NOT EXISTS; previously the open_only path parsed the properties param and
silently dropped it (clean-room review F7a).

Co-authored-by: multica-agent <github@multica.ai>

* fix(properties): toast on failed board drag to a property column

Property-column drags rolled the card back silently on failure; mirror
the status/assignee drag path (use-issue-surface-actions) so the
snap-back is explained (clean-room review F3, drag half).

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Lambda <lambda@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
2026-07-15 12:00:28 +08:00

564 lines
23 KiB
Go

package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func makePropertyDef(propType string, options []PropertyOption) db.IssueProperty {
cfg, _ := json.Marshal(PropertyConfig{Options: options})
return db.IssueProperty{Type: propType, Config: cfg}
}
// withIssuePropertyParams sets both chi URL params in one route context —
// withURLParam builds a fresh context per call, so chaining it would drop
// the first param.
func withIssuePropertyParams(req *http.Request, issueID, propertyID string) *http.Request {
rctx := chi.NewRouteContext()
rctx.URLParams.Add("id", issueID)
rctx.URLParams.Add("propertyId", propertyID)
return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
}
func createTestProperty(t *testing.T, body map[string]any) PropertyResponse {
t.Helper()
w := httptest.NewRecorder()
req := newRequest("POST", "/api/properties", body)
testHandler.CreateProperty(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("CreateProperty: expected 201, got %d: %s", w.Code, w.Body.String())
}
var created PropertyResponse
json.NewDecoder(w.Body).Decode(&created)
t.Cleanup(func() { deleteTestProperty(t, created.ID) })
return created
}
// deleteTestProperty removes the row directly — the API only archives, but
// tests must not leak definitions into the shared workspace fixture (the
// 20-active cap and list assertions would couple unrelated tests).
func deleteTestProperty(t *testing.T, id string) {
t.Helper()
if _, err := testPool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, id); err != nil {
t.Fatalf("cleanup property %s: %v", id, err)
}
}
func createPropertyTestIssue(t *testing.T, title string) string {
t.Helper()
var issueID string
if err := testPool.QueryRow(context.Background(), `
INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)
VALUES ($1, $2, 'todo', 'none', 'member', $3,
COALESCE((SELECT MAX(number) FROM issue WHERE workspace_id = $1), 0) + 1)
RETURNING id
`, testWorkspaceID, title, testUserID).Scan(&issueID); err != nil {
t.Fatalf("create test issue: %v", err)
}
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
})
return issueID
}
func setIssuePropertyRaw(t *testing.T, issueID, propertyID string, value any) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
req := newRequest("PUT", "/api/issues/"+issueID+"/properties/"+propertyID, map[string]any{"value": value})
req = withIssuePropertyParams(req, issueID, propertyID)
testHandler.SetIssueProperty(w, req)
return w
}
func TestPropertyDefinitionCRUD(t *testing.T) {
created := createTestProperty(t, map[string]any{
"name": "Severity",
"type": "select",
"description": "How bad it is",
"config": map[string]any{"options": []map[string]any{
{"name": "Critical", "color": "EF4444"},
{"name": "Minor", "color": "#6b7280"},
}},
})
if created.Type != "select" || len(created.Config.Options) != 2 {
t.Fatalf("unexpected created property: %+v", created)
}
// Server assigns option ids and normalizes colors to lowercase #rrggbb.
if created.Config.Options[0].ID == "" {
t.Fatalf("option id not assigned: %+v", created.Config.Options[0])
}
if created.Config.Options[0].Color != "#ef4444" {
t.Fatalf("color not normalized: %q", created.Config.Options[0].Color)
}
// Duplicate name (case-insensitive) → 409.
w := httptest.NewRecorder()
req := newRequest("POST", "/api/properties", map[string]any{
"name": "severity", "type": "text",
})
testHandler.CreateProperty(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("duplicate name: expected 409, got %d: %s", w.Code, w.Body.String())
}
// Rename + replace options, keeping the first option's id: values that
// reference it must survive option-list edits.
keepID := created.Config.Options[0].ID
w = httptest.NewRecorder()
req = newRequest("PATCH", "/api/properties/"+created.ID, map[string]any{
"name": "Sev",
"config": map[string]any{"options": []map[string]any{
{"id": keepID, "name": "Blocker", "color": "#ef4444"},
{"name": "Trivial", "color": "#a1a1aa"},
}},
})
req = withURLParam(req, "id", created.ID)
testHandler.UpdateProperty(w, req)
if w.Code != http.StatusOK {
t.Fatalf("UpdateProperty: expected 200, got %d: %s", w.Code, w.Body.String())
}
var updated PropertyResponse
json.NewDecoder(w.Body).Decode(&updated)
if updated.Name != "Sev" || updated.Config.Options[0].ID != keepID || updated.Config.Options[0].Name != "Blocker" {
t.Fatalf("option id not preserved on update: %+v", updated.Config.Options)
}
// Archive → default list hides it, include_archived shows it.
w = httptest.NewRecorder()
req = newRequest("PATCH", "/api/properties/"+created.ID, map[string]any{"archived": true})
req = withURLParam(req, "id", created.ID)
testHandler.UpdateProperty(w, req)
if w.Code != http.StatusOK {
t.Fatalf("archive: expected 200, got %d: %s", w.Code, w.Body.String())
}
listProperties := func(query string) []PropertyResponse {
w := httptest.NewRecorder()
testHandler.ListProperties(w, newRequest("GET", "/api/properties"+query, nil))
if w.Code != http.StatusOK {
t.Fatalf("ListProperties%s: expected 200, got %d: %s", query, w.Code, w.Body.String())
}
var resp struct {
Properties []PropertyResponse `json:"properties"`
}
json.NewDecoder(w.Body).Decode(&resp)
return resp.Properties
}
contains := func(list []PropertyResponse, id string) bool {
for _, p := range list {
if p.ID == id {
return true
}
}
return false
}
if contains(listProperties(""), created.ID) {
t.Fatalf("archived property still in default list")
}
if !contains(listProperties("?include_archived=true"), created.ID) {
t.Fatalf("archived property missing from include_archived list")
}
}
func TestPropertyDefinitionValidation(t *testing.T) {
cases := []struct {
name string
body map[string]any
want string
}{
{"reserved name", map[string]any{"name": "Due Date", "type": "text"}, "reserved"},
{"invalid type", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "formula"}, "invalid type"},
{"options on text", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "text",
"config": map[string]any{"options": []map[string]any{{"name": "a", "color": "#000000"}}}}, "does not accept options"},
{"select without options", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "select"}, "at least one option"},
{"duplicate option names", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "select",
"config": map[string]any{"options": []map[string]any{
{"name": "One", "color": "#000000"}, {"name": "one", "color": "#111111"},
}}}, "duplicate option name"},
}
for _, tc := range cases {
w := httptest.NewRecorder()
testHandler.CreateProperty(w, newRequest("POST", "/api/properties", tc.body))
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), tc.want) {
t.Fatalf("%s: expected 400 containing %q, got %d: %s", tc.name, tc.want, w.Code, w.Body.String())
}
}
}
// TestPropertyAdminGate verifies the two definition-management gates: agent
// actors are rejected outright (even though the fixture user is the workspace
// owner), while value writes from the same agent context succeed.
func TestPropertyAdminGate(t *testing.T) {
// Agent actor (task_token path is trusted directly by resolveActor).
w := httptest.NewRecorder()
req := newRequest("POST", "/api/properties", map[string]any{"name": "AgentMade", "type": "text"})
req.Header.Set("X-Actor-Source", "task_token")
req.Header.Set("X-Agent-ID", uuid.NewString())
testHandler.CreateProperty(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("agent CreateProperty: expected 403, got %d: %s", w.Code, w.Body.String())
}
property := createTestProperty(t, map[string]any{"name": "AgentWritable" + uuid.NewString()[:8], "type": "text"})
issueID := createPropertyTestIssue(t, "agent value write")
w = httptest.NewRecorder()
req = newRequest("PUT", "/api/issues/"+issueID+"/properties/"+property.ID, map[string]any{"value": "set by agent"})
req.Header.Set("X-Actor-Source", "task_token")
req.Header.Set("X-Agent-ID", uuid.NewString())
req = withIssuePropertyParams(req, issueID, property.ID)
testHandler.SetIssueProperty(w, req)
if w.Code != http.StatusOK {
t.Fatalf("agent SetIssueProperty: expected 200, got %d: %s", w.Code, w.Body.String())
}
}
func TestIssuePropertyValues(t *testing.T) {
sel := createTestProperty(t, map[string]any{
"name": "Env" + uuid.NewString()[:8], "type": "select",
"config": map[string]any{"options": []map[string]any{
{"name": "Staging", "color": "#22c55e"},
{"name": "Production", "color": "#ef4444"},
}},
})
multi := createTestProperty(t, map[string]any{
"name": "Platforms" + uuid.NewString()[:8], "type": "multi_select",
"config": map[string]any{"options": []map[string]any{
{"name": "iOS", "color": "#3b82f6"},
{"name": "Android", "color": "#22c55e"},
{"name": "Web", "color": "#f59e0b"},
}},
})
date := createTestProperty(t, map[string]any{"name": "Reviewed" + uuid.NewString()[:8], "type": "date"})
link := createTestProperty(t, map[string]any{"name": "Spec" + uuid.NewString()[:8], "type": "url"})
num := createTestProperty(t, map[string]any{"name": "Effort" + uuid.NewString()[:8], "type": "number"})
issueID := createPropertyTestIssue(t, "property value matrix")
// select: valid option id.
if w := setIssuePropertyRaw(t, issueID, sel.ID, sel.Config.Options[0].ID); w.Code != http.StatusOK {
t.Fatalf("select set: expected 200, got %d: %s", w.Code, w.Body.String())
}
// select: unknown option → 400 listing legal ids (agents self-correct on this).
if w := setIssuePropertyRaw(t, issueID, sel.ID, "nope"); w.Code != http.StatusBadRequest ||
!strings.Contains(w.Body.String(), sel.Config.Options[0].ID) {
t.Fatalf("select invalid: expected 400 listing option ids, got %d: %s", w.Code, w.Body.String())
}
// multi_select: duplicates dropped, order canonicalized to config order.
webID, iosID := multi.Config.Options[2].ID, multi.Config.Options[0].ID
w := setIssuePropertyRaw(t, issueID, multi.ID, []string{webID, iosID, webID})
if w.Code != http.StatusOK {
t.Fatalf("multi_select set: expected 200, got %d: %s", w.Code, w.Body.String())
}
var resp struct {
Properties map[string]any `json:"properties"`
}
json.NewDecoder(w.Body).Decode(&resp)
stored, _ := resp.Properties[multi.ID].([]any)
if len(stored) != 2 || stored[0] != iosID || stored[1] != webID {
t.Fatalf("multi_select not canonicalized to config order: %v", stored)
}
// date / url / number validation.
if w := setIssuePropertyRaw(t, issueID, date.ID, "13/07/2026"); w.Code != http.StatusBadRequest {
t.Fatalf("bad date: expected 400, got %d", w.Code)
}
if w := setIssuePropertyRaw(t, issueID, date.ID, "2026-07-13"); w.Code != http.StatusOK {
t.Fatalf("good date: expected 200, got %d: %s", w.Code, w.Body.String())
}
if w := setIssuePropertyRaw(t, issueID, link.ID, "javascript:alert(1)"); w.Code != http.StatusBadRequest {
t.Fatalf("bad url: expected 400, got %d", w.Code)
}
if w := setIssuePropertyRaw(t, issueID, link.ID, "https://example.com/spec"); w.Code != http.StatusOK {
t.Fatalf("good url: expected 200, got %d: %s", w.Code, w.Body.String())
}
if w := setIssuePropertyRaw(t, issueID, num.ID, "3"); w.Code != http.StatusBadRequest {
t.Fatalf("string into number: expected 400, got %d", w.Code)
}
if w := setIssuePropertyRaw(t, issueID, num.ID, 3.5); w.Code != http.StatusOK {
t.Fatalf("good number: expected 200, got %d: %s", w.Code, w.Body.String())
}
// Archived definitions reject new values but allow unset.
warch := httptest.NewRecorder()
req := newRequest("PATCH", "/api/properties/"+sel.ID, map[string]any{"archived": true})
req = withURLParam(req, "id", sel.ID)
testHandler.UpdateProperty(warch, req)
if warch.Code != http.StatusOK {
t.Fatalf("archive: expected 200, got %d: %s", warch.Code, warch.Body.String())
}
if w := setIssuePropertyRaw(t, issueID, sel.ID, sel.Config.Options[1].ID); w.Code != http.StatusBadRequest {
t.Fatalf("set on archived: expected 400, got %d: %s", w.Code, w.Body.String())
}
wdel := httptest.NewRecorder()
req = newRequest("DELETE", "/api/issues/"+issueID+"/properties/"+sel.ID, nil)
req = withIssuePropertyParams(req, issueID, sel.ID)
testHandler.DeleteIssueProperty(wdel, req)
if wdel.Code != http.StatusOK {
t.Fatalf("unset on archived: expected 200, got %d: %s", wdel.Code, wdel.Body.String())
}
// Fresh struct: json.Decode merges into a pre-populated map, which would
// leave the earlier bag contents (including sel.ID) in place.
var afterDelete struct {
Properties map[string]any `json:"properties"`
}
json.NewDecoder(wdel.Body).Decode(&afterDelete)
if _, present := afterDelete.Properties[sel.ID]; present {
t.Fatalf("value not removed: %v", afterDelete.Properties)
}
}
func TestValidatePropertyValueUnit(t *testing.T) {
textDef := makePropertyDef("text", nil)
if _, err := validatePropertyValue(textDef, json.RawMessage(`" "`)); err == nil {
t.Fatalf("blank text accepted")
}
if _, err := validatePropertyValue(textDef, json.RawMessage(`"`+strings.Repeat("x", 2001)+`"`)); err == nil {
t.Fatalf("overlong text accepted")
}
if _, err := validatePropertyValue(textDef, json.RawMessage(`null`)); err == nil {
t.Fatalf("null accepted")
}
boolDef := makePropertyDef("checkbox", nil)
if _, err := validatePropertyValue(boolDef, json.RawMessage(`"true"`)); err == nil {
t.Fatalf("string into checkbox accepted")
}
if _, err := validatePropertyValue(boolDef, json.RawMessage(`false`)); err != nil {
t.Fatalf("false rejected: %v", err)
}
}
func TestValidatePropertyNameReserved(t *testing.T) {
for _, name := range []string{"status", "Priority", "due date", "Due_Date", "START DATE", "labels"} {
if _, err := validatePropertyName(name); err == nil {
t.Fatalf("reserved name %q accepted", name)
}
}
if _, err := validatePropertyName("Severity"); err != nil {
t.Fatalf("legit name rejected: %v", err)
}
}
// TestPropertyOptionRemovalGuard: removing a select option still referenced
// by issues is rejected with a usage census; renames (same id) and removal
// of unused options pass.
func TestPropertyOptionRemovalGuard(t *testing.T) {
property := createTestProperty(t, map[string]any{
"name": "Guard" + uuid.NewString()[:8], "type": "select",
"config": map[string]any{"options": []map[string]any{
{"name": "Used", "color": "#ef4444"},
{"name": "Unused", "color": "#6b7280"},
}},
})
usedID := property.Config.Options[0].ID
unusedID := property.Config.Options[1].ID
issueID := createPropertyTestIssue(t, "option removal guard")
if w := setIssuePropertyRaw(t, issueID, property.ID, usedID); w.Code != http.StatusOK {
t.Fatalf("seed value: expected 200, got %d: %s", w.Code, w.Body.String())
}
patchConfig := func(options []map[string]any) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
req := newRequest("PATCH", "/api/properties/"+property.ID, map[string]any{
"config": map[string]any{"options": options},
})
req = withURLParam(req, "id", property.ID)
testHandler.UpdateProperty(w, req)
return w
}
// Dropping the in-use option → 409 naming it with the census.
w := patchConfig([]map[string]any{{"id": unusedID, "name": "Unused", "color": "#6b7280"}})
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "Used") || !strings.Contains(w.Body.String(), "1 issues") {
t.Fatalf("in-use removal: expected 409 with census, got %d: %s", w.Code, w.Body.String())
}
// Renaming the in-use option (id preserved) → 200.
w = patchConfig([]map[string]any{
{"id": usedID, "name": "Used (renamed)", "color": "#ef4444"},
{"id": unusedID, "name": "Unused", "color": "#6b7280"},
})
if w.Code != http.StatusOK {
t.Fatalf("rename: expected 200, got %d: %s", w.Code, w.Body.String())
}
// Dropping only the unused option → 200.
w = patchConfig([]map[string]any{{"id": usedID, "name": "Used (renamed)", "color": "#ef4444"}})
if w.Code != http.StatusOK {
t.Fatalf("unused removal: expected 200, got %d: %s", w.Code, w.Body.String())
}
}
// TestListIssuesPropertyFilterAndSort covers the server-side list support:
// containment filtering (select / multi_select / checkbox) beyond the first
// page window, and typed property sort expressions with missing-last
// semantics. The shared workspace fixture may hold foreign issues, so
// assertions check relative order / membership rather than exact lists.
func TestListIssuesPropertyFilterAndSort(t *testing.T) {
sel := createTestProperty(t, map[string]any{
"name": "FS" + uuid.NewString()[:8], "type": "select",
"config": map[string]any{"options": []map[string]any{
{"name": "Hit", "color": "#ef4444"},
{"name": "Miss", "color": "#6b7280"},
}},
})
hitID := sel.Config.Options[0].ID
multi := createTestProperty(t, map[string]any{
"name": "FM" + uuid.NewString()[:8], "type": "multi_select",
"config": map[string]any{"options": []map[string]any{
{"name": "A", "color": "#3b82f6"},
{"name": "B", "color": "#22c55e"},
}},
})
multiB := multi.Config.Options[1].ID
box := createTestProperty(t, map[string]any{"name": "FB" + uuid.NewString()[:8], "type": "checkbox"})
num := createTestProperty(t, map[string]any{"name": "FN" + uuid.NewString()[:8], "type": "number"})
// 54 padding issues at explicit ascending positions, then the matching
// issue at the highest position — genuinely beyond the 50-row first page
// (review round 3: without explicit positions everything ties at 0 and
// the created_at DESC tie-breaker put the target on page one).
setPosition := func(issueID string, position float64) {
t.Helper()
if _, err := testPool.Exec(context.Background(),
`UPDATE issue SET position = $1 WHERE id = $2`, position, issueID); err != nil {
t.Fatalf("set position: %v", err)
}
}
for i := 0; i < 54; i++ {
setPosition(createPropertyTestIssue(t, fmt.Sprintf("filter pad %02d", i)), float64(i))
}
target := createPropertyTestIssue(t, "filter target beyond page one")
setPosition(target, 1000)
if w := setIssuePropertyRaw(t, target, sel.ID, hitID); w.Code != http.StatusOK {
t.Fatalf("seed select: %d %s", w.Code, w.Body.String())
}
if w := setIssuePropertyRaw(t, target, multi.ID, []string{multiB}); w.Code != http.StatusOK {
t.Fatalf("seed multi: %d %s", w.Code, w.Body.String())
}
if w := setIssuePropertyRaw(t, target, box.ID, true); w.Code != http.StatusOK {
t.Fatalf("seed checkbox: %d %s", w.Code, w.Body.String())
}
numLow := createPropertyTestIssue(t, "sort low")
numHigh := createPropertyTestIssue(t, "sort high")
if w := setIssuePropertyRaw(t, numLow, num.ID, 1); w.Code != http.StatusOK {
t.Fatalf("seed low: %d %s", w.Code, w.Body.String())
}
if w := setIssuePropertyRaw(t, numHigh, num.ID, 9.5); w.Code != http.StatusOK {
t.Fatalf("seed high: %d %s", w.Code, w.Body.String())
}
listIssues := func(query string) []IssueResponse {
t.Helper()
w := httptest.NewRecorder()
testHandler.ListIssues(w, newRequest("GET", "/api/issues"+query, nil))
if w.Code != http.StatusOK {
t.Fatalf("ListIssues%s: expected 200, got %d: %s", query, w.Code, w.Body.String())
}
var resp struct {
Issues []IssueResponse `json:"issues"`
}
json.NewDecoder(w.Body).Decode(&resp)
return resp.Issues
}
ids := func(list []IssueResponse) map[string]int {
out := make(map[string]int, len(list))
for i, issue := range list {
out[issue.ID] = i
}
return out
}
filterQuery := func(defID string, values ...string) string {
buf, _ := json.Marshal(map[string][]string{defID: values})
return "?limit=50&properties=" + url.QueryEscape(string(buf))
}
// Preconditions: the UNFILTERED first page must not contain the target
// (otherwise the assertions below prove nothing about windowing).
if _, present := ids(listIssues("?limit=50&sort=position&status=todo"))[target]; present {
t.Fatalf("windowing precondition broken: target already on the unfiltered first page")
}
// Select filter finds the issue past the 50-row window.
got := listIssues(filterQuery(sel.ID, hitID))
if _, present := ids(got)[target]; !present {
t.Fatalf("select filter missed the issue beyond page one")
}
for _, issue := range got {
if issue.Properties[sel.ID] != hitID {
t.Fatalf("select filter returned non-matching issue %s", issue.ID)
}
}
// Multi and checkbox containment forms.
if _, present := ids(listIssues(filterQuery(multi.ID, multiB)))[target]; !present {
t.Fatalf("multi_select filter missed the issue")
}
if _, present := ids(listIssues(filterQuery(box.ID, "true")))[target]; !present {
t.Fatalf("checkbox filter missed the issue")
}
// AND across definitions: matching select + non-matching checkbox → empty of target.
buf, _ := json.Marshal(map[string][]string{sel.ID: {hitID}, box.ID: {"false"}})
if _, present := ids(listIssues("?limit=50&properties=" + url.QueryEscape(string(buf))))[target]; present {
t.Fatalf("AND semantics failed: target matched with contradictory checkbox filter")
}
// The open_only branch honors the same filter via the static
// properties_filter param in ListOpenIssues (clean-room review: it used
// to be parsed and then silently dropped on this path).
openGot := listIssues(filterQuery(sel.ID, hitID) + "&open_only=true")
if _, present := ids(openGot)[target]; !present {
t.Fatalf("open_only ignored the properties filter: target missing")
}
for _, issue := range openGot {
if issue.Properties[sel.ID] != hitID {
t.Fatalf("open_only properties filter returned non-matching issue %s", issue.ID)
}
}
openBuf, _ := json.Marshal(map[string][]string{sel.ID: {hitID}, box.ID: {"false"}})
if _, present := ids(listIssues("?open_only=true&properties=" + url.QueryEscape(string(openBuf))))[target]; present {
t.Fatalf("open_only AND semantics failed: target matched contradictory filter")
}
// Property sort: asc = low before high, valueless after both (missing last).
sorted := listIssues("?limit=200&sort=property:" + num.ID + "&direction=asc")
pos := ids(sorted)
lowIdx, lowOK := pos[numLow]
highIdx, highOK := pos[numHigh]
padIdx, padOK := pos[target]
if !lowOK || !highOK || !padOK {
t.Fatalf("sorted list missing seeded issues (low=%v high=%v pad=%v)", lowOK, highOK, padOK)
}
if !(lowIdx < highIdx && highIdx < padIdx) {
t.Fatalf("asc property sort order wrong: low=%d high=%d valueless=%d", lowIdx, highIdx, padIdx)
}
sorted = listIssues("?limit=200&sort=property:" + num.ID + "&direction=desc")
pos = ids(sorted)
if !(pos[numHigh] < pos[numLow] && pos[numLow] < pos[target]) {
t.Fatalf("desc property sort order wrong: high=%d low=%d valueless=%d", pos[numHigh], pos[numLow], pos[target])
}
// Malformed property sort id → 400; unknown definition → 200 position order.
w := httptest.NewRecorder()
testHandler.ListIssues(w, newRequest("GET", "/api/issues?sort=property:nope", nil))
if w.Code != http.StatusBadRequest {
t.Fatalf("malformed property sort: expected 400, got %d", w.Code)
}
if got := listIssues("?limit=5&sort=property:" + uuid.NewString()); len(got) == 0 {
t.Fatalf("unknown-definition sort should fall back to position order, got empty")
}
}