feat: relation field and picker

This commit is contained in:
Florian Sylvain committed 2026-10-23 00:13:42 +02:00
1 parent b45c99be3b
commit 37a77c9c22
92 files changed
+6826 -80

No files matched your search

+380
View File
@@ -0,0 +1,380 @@
Feature: Relation field in the SPA
As an owner or admin building a content type, and as a verified user filling an entry
I want a Relation field that links an entry to entries of another content type
So that structured content can point at other structured content
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/relation_field_type.feature is done
And the design is docs/design/screens/schema-later.md section 7 (3 states) and the board group "7 Relations" of "RenewCMS Screens Schema.dc.html" with SchemaFrame.dc.html; the frame markup wins over prose for layout
And the registry is lib/fieldTypes with lib/entryEditors, the single source for the builder, the list cells and the entry form; no screen branches on the type name "relation" where a registry property can say it
And the tags "Later" and "Relation columns: later" / "Relation field: later" drawn on the board are not rendered; the feature ships
And a relation value is an id (uint32 of at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50) for many_to_many
And a field loaded from the API has "relation": {"content_type","kind"} with kind "one_to_one", "one_to_many" or "many_to_many"
And every entry answer (POST 201, PUT 200, GET one, each list item) carries a top-level "relations" object keyed by relation field key: {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true}; an array of these for many_to_many; the label of a target is its first_field formatted by the same rule as the entry list, and "Entry N" when null
And the API refuses with 422 "invalid_entry: <key>: required", "invalid_entry: <key>: type", 409 "invalid_entry: <key>: unique", 409 "schema_incompatible" for a new required relation on a type with entries, 422 "invalid_field" for a bad definition, and 409 "content_type_referenced" when deleting a target type
And the picker searches GET /v1/content-type/{target}/entry?q=&page=&size= and reads total from the answer
And the inverse side is shown in the builder preview only; the target type's form, list and API are unchanged
And sentence case, buttons are verbs, every string goes through t() and has a French entry in i18n/messages.ts
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
And the sample data is the board's: Event with Venue (one_to_many) and Speakers (many_to_many); venues "Rue Verte hall" (Lyon · 120 seats), "Rue Verte yard" (Lyon · outdoor), "Rue du Port studio" (Nantes · 24 seats); speakers "Ines Duarte" and "Jonas Pereira"; entries 42 "Lime plaster workshop", 41 "Heat pumps: what the numbers say", 40 "Open day at the Rue Verte site"
Scenario Outline: Relation in the registry
Given the registry entry for "relation"
Then <property> is <value>
Examples:
| property | value |
| type name in the API | relation (the eighth entry, after media) |
| label | Relation |
| description | Links to another type's entries (proposed copy) |
| icon | lucide:link |
| control | RelationField |
| pairs with a neighbour | no, full width |
| empty value | null for one_to_one and one_to_many, [] for many_to_many |
| initial on create | the empty value; a relation has no default, so no "Default" tag ever shows |
| initial on edit | the stored id or ids |
| supports unique | no |
| supports limits | no |
| supports default | no |
| supports choices | no |
| counter | none |
| list cell | chips: one chip, two chips and "+N", or "–"; not sortable |
| sample in the API preview | null for a single kind, [] for many_to_many |
Scenario: A loaded relation field is not shown as Text
Given GET /v1/content-type/events returns a field {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
Then the builder, the entry form and the list resolve it to the relation entry of the registry, never to the fallback type "text"
Scenario Outline: Client validation of a relation value
Given a <kind> relation "Venue" that is <required>
When the value is <value>
Then the rule is <rule>
Examples:
| kind | required | value | rule |
| single | required | null | required |
| single | optional | null | none |
| single | required | 3 | none |
| single | optional | 0 | type |
| single | optional | "3" | type |
| single | optional | [3] | type |
| many_to_many | required | [] | required |
| many_to_many | optional | [] | none |
| many_to_many | optional | [11, 12] | none |
| many_to_many | optional | [11, 11] | type |
| many_to_many | optional | 11 | type |
| many_to_many | optional | 51 ids | type |
Scenario Outline: Messages of a relation field
Given a relation field labelled "Venue" whose related type is named "Venues"
Then the message of the rule <rule> reads <message>
Examples:
| rule | message |
| required | Choose a Venue. (proposed copy) |
| type | Venue must point to an existing entry. (proposed copy) |
| unique | That Venue is already used by another entry. (proposed copy) |
| min | not produced for relation |
| max | not produced for relation |
| options | not produced for relation |
Scenario: The type gallery gains Relation
Given the inspector of a field that can still change type
Then the tile "Relation" with the link icon is the last tile, selectable like the others
And on a saved field the other tiles are dimmed to 40 % and not selectable, as for any locked type
Scenario: Adding a relation field
Given Events and a second content type Venues exist
When the user activates "Add field", types the label "Venue" and chooses the tile "Relation"
Then the new row shows the badge "New", the key "venue" (Auto, editable) and the chip reads "Unsaved changes"
And the inspector reads "Field: Venue" and shows, after the Type tiles and in this order, the select "Related content type" with the help "Choose the content type this field points to." and the group "How are they connected?"
And no related type is chosen yet and "Save" cannot send a relation without one (proposed copy for the message: "Choose a related content type.")
Scenario: The related content type select
Given the user is editing Events
Then the select lists the other content types by name, and Events itself, each with its key as a hint (proposed)
And choosing Venues sets the sentences of the preview to "Venue" and "Events"
Scenario: Three shape cards (design "Relation in the builder")
Given the related type is Venues, the owner Events
Then three cards are shown in a row (one column on mobile), each with a diagram of squares and a line, a title and a sentence
| card | sentence |
| One to one | Each Event has one Venue, and each Venue has one Event. |
| One to many | Each Event has one Venue. A Venue has many Events. |
| Many to many | Each Event has many Venues, and each Venue has many Events. |
And the selected card has the primary border and the sand fill with --rc-on-sand text, the others the accented border
And the cards are a radio group, one is selected at a time, and a new relation starts with "One to many" selected (proposed default)
Scenario: The preview of both sides
Given "One to many" is selected with Event and Venue
Then a block with the elevated background reads "Each Event has [one] Venue" and "Each Venue has [many] Events" followed by the muted text `· shown on Venue as the field "Events"`
And the bracketed words are drawn as selects showing the chosen kind and follow the selected card
And below it two cards "Event" (Venue: chip "Rue Verte hall") and "Venue" (Events: chips "Open day", "Lime plaster workshop" and "+1") illustrate both sides, side by side on desktop and stacked on mobile
And the inverse field is not stored anywhere and nothing about it is sent
Scenario Outline: The preview follows the kind
Given the owner Event and the related type Venue
When the user selects <card>
Then the sentences read <owner side> and <inverse side>
Examples:
| card | owner side | inverse side |
| One to one | Each Event has one Venue | Each Venue has one Event |
| One to many | Each Event has one Venue | Each Venue has many Events |
| Many to many | Each Event has many Venues| Each Venue has many Events |
Scenario: Plural and names come from the types
Given the owner "Events" and the related type "Venues"
Then "Event"/"Events" and "Venue"/"Venues" in the sentences are the singular and plural forms drawn from the type names (proposed rule: singular is the name without a final "s"; the field label is used for the singular of the related side)
Scenario: The PUT and POST body of a relation field
Given a relation "Venue" to "venues", kind "One to many", Required off
When the type is saved
Then the field is sent as {"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venues","kind":"one_to_many"}}
And every other field is sent with "relation": null
And a round trip of the loaded field to the payload produces no change
Scenario: The inspector of a saved relation (locked) (state not drawn; proposed copy)
Given Events with a saved relation "Venue" as its field
When the user selects its row
Then the Label input and the Required switch are editable
And the Key is locked with "Used in the API, so it can't change."
And the legend of the tiles reads "Type" with a lock and "Can't change after saving", Relation is selected and the other tiles are dimmed to 40 %
And "Related content type" and the three cards are shown disabled with the selected card kept, under the note "The related type and the connection can't change after saving. (proposed copy)"
Scenario: A required relation added to a type with entries is refused first
Given Events with 12 entries and a new relation "Venue" that is required
When the user activates Save
Then no PUT is sent and the dialog "Review changes to Events" opens
And the row "Add Venue" has the warning badge "Can't be applied" and the text "Relation, required. A relation can't have a default, so the 12 existing entries would have no Venue. Make Venue optional to add it. (proposed copy)"
And "Back to editing" is enabled and "Apply changes" is disabled, so pressing it sends nothing
And an optional relation shows the clean row "Relation, optional. 12 entries are unaffected. (proposed copy)" with "Apply changes" enabled
Scenario: The server answers on the builder
Given the user applies a type with a relation
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 409 | schema_incompatible | the existing "Nothing was changed" refusal flow runs unchanged |
| 422 | invalid_field | the existing invalid-field failure of the builder is shown, the edits stay |
Scenario: Deleting a type that another type points at (proposed copy)
Given Venues is the target of the relation on Events and Venues has no entries
When the user confirms the delete of Venues
Then the API answers 409 "content_type_referenced"
And the existing delete failure surface shows the title "You can't delete Venues yet" and the text "Events has a field that points to Venues. Remove that field first. (proposed copy)"
And the type is still listed
Scenario: The builder is for owners and admins
Given a verified user who is neither owner nor admin
Then the builder keeps its existing "You don't have access to Schema" state and no relation control is rendered
Scenario: Where the controls sit
Given Events with the fields Title, Venue and Speakers
Then the controls follow the schema order, full width in the 760 px column, each with its label ("Venue", "Speakers") in weight 500
Scenario: Single relation, empty, focused search (design "Venue")
Given /content/events/42 whose venue is null
When the user focuses the "Venue" control and types "rue"
Then the input shows the search icon, the typed text and "Search to add"
And a popover list under the input shows rows of at least 40 px (48 on mobile) with the title in weight 500 and a second muted 12/18 line, each row a button
| title | second line |
| Rue Verte hall | Lyon · 120 seats |
| Rue Verte yard | Lyon · outdoor |
| Rue du Port studio | Nantes · 24 seats|
And the first row has the elevated background
And the title is the first field of the related type and the second line is the next fields formatted as the entry list does, joined by " · " (up to 2 fields, proposed rule)
Scenario: Picking a single target
When the user activates the row "Rue Verte hall"
Then the list closes, the control shows one chip "Rue Verte hall" with an x, the value becomes 3, and the chip of the page reads "Unsaved changes"
And the live region says "Venue set to Rue Verte hall. (proposed copy)" and the focus stays in the control
And the chip's x removes it, sets the value to null, and says "Venue cleared. (proposed copy)"
Scenario: Many relation (design "Speakers")
Given Events with speakers [11, 12]
Then the control is a bordered box (1 px accented, min height 40, 44 on mobile) holding the chips "Ines Duarte" and "Jonas Pereira", each 24 px high (32 on mobile) with an x, then the muted text "Search to add"
And the help line under it reads "An event can have many speakers."
And a chip is a sand chip with --rc-on-sand text, weight 500
Scenario: Adding and removing in a many relation
When the user types "ines" in the control and activates the row "Ines Duarte"
Then the chip is added at the end in the chosen order and the row no longer appears in later results
When the user activates the x of a chip, or presses Backspace in the empty input
Then that chip is removed and the live region says "Ines Duarte removed from Speakers. (proposed copy)"
And a 51st target cannot be added: the search shows "You can add up to 50. (proposed copy)" and no row is selectable
Scenario: One to one targets already used (proposed copy)
Given a one_to_one relation
When the server answers 409 "invalid_entry: room: unique"
Then "That Venue is already used by another entry." shows under the control with a circle-alert icon, the error border applies, the chip reads "Not saved" and the focus moves to the control
Scenario: The search request
When the user types "rue"
Then the input is trimmed and debounced, and only GET /v1/content-type/venues/entry?q=rue&page=1&size=<page size> is sent
And the response replaces the list and a stale answer never overwrites a newer one
And with an empty input the first page of the type is listed without q (proposed)
Scenario: Picker loading (not drawn; proposed copy)
Given the search has not answered
Then after 150 ms the list shows three skeleton rows of the same height, with "Searching… (proposed copy)" announced politely, and no row is selectable
Scenario: No match (not drawn; proposed copy)
Given the search answers total 0 for "zzz"
Then the list shows `No Venues match "zzz"` (proposed copy) and the action "Clear search" that empties the input
And when the related type has no entries at all the list reads "No Venues yet. Add one in Content, then come back. (proposed copy)"
Scenario Outline: Search failures (not drawn; proposed copy)
Given the search answers <outcome>
Then <result>
Examples:
| outcome | result |
| 500 | the list shows "Couldn't load Venues" / "Check your connection and try again." with "Try again" (proposed copy) |
| a network error | the same |
| 429 | the existing rate-limit countdown alert |
| 401 | the global redirect, no local copy |
| 404 | "Couldn't load Venues" as for 500, since the related type may have been deleted (proposed copy) |
Scenario: Load more in the list
Given the search has more results than one page
When the user scrolls to the end of the list or activates "Load more" (proposed copy)
Then the next page is appended and the focus stays on the active row
Scenario: Keyboard
Given the control is focused and the list is open
Then ArrowDown and ArrowUp move the active row, Enter picks it, Esc closes the list and keeps the typed text, Tab leaves the control
And in a many relation Backspace on an empty input removes the last chip and chips are reachable with ArrowLeft
Scenario: A missing target (not drawn; proposed copy)
Given relations.venue is {"id":3,"missing":true}
Then the control shows a dashed chip "Entry no longer exists (proposed copy)" with an x and the help "You can still save. The entry keeps the link until you change it. (proposed copy)" when the field is optional
And when the field is required the help reads "Venue is required. Choose another to save. (proposed copy)", and saving with the missing target sends no request, shows the required message and focuses the control
And saving an optional field with the missing target sends the same id
Scenario: Required and empty
Given a required relation with no target
When the user activates "Save"
Then no request is sent, the error "Choose a Venue." replaces the help line, the border is --ui-error, the chip reads "Not saved" and the focus goes to the control
And only the first field in schema order with an error takes the focus
When the user picks a target
Then the error goes and the chip reads "Unsaved changes"
Scenario: Saving
Given the PUT has not answered
Then the form is dimmed to 70 %, the chips and the input are not operable and the list cannot open
And Save reads "Saving…"
Scenario Outline: What the control shows and sends
Given the loaded value <loaded> with relations <relations>
When the user <action> and activates "Save"
Then the control shows <shown>
And the data holds <sent>
Examples:
| loaded | relations | action | shown | sent |
| null | none | saves with nothing changed | no chip | "venue": null |
| 3 | existing venue 3 | saves with nothing changed | the chip "Rue Verte hall"| "venue": 3 |
| 3 | missing venue 3 | saves with nothing changed | the missing chip | "venue": 3 |
| 3 | existing venue 3 | picks "Rue Verte yard" | the chip "Rue Verte yard"| "venue": 4 |
| 3 | existing venue 3 | activates the x | no chip | "venue": null |
| [11] | speaker 11 | adds Jonas Pereira | two chips | "speakers": [11, 12] |
| [11,12] | speakers 11, 12 | removes both | no chip | "speakers": [] |
Scenario: Create payload with relations
Given /content/events/new with Title "Open day", Venue left empty and Speakers left empty
When the user activates "Save"
Then POST /v1/content-type/events/entry is sent once with "venue": null and "speakers": [] among the other keys, never absent
And with Rue Verte hall picked it holds "venue": 3, a JSON number
Scenario: Right after a pick the control uses the picked row
Given the user picks "Rue Verte yard" from the results
Then before any save the chip shows its title from the result and no extra request is made
When the PUT answers 200 with relations.venue
Then the control is rebuilt from the answered relations object
Scenario: Dirty tracking of a relation value
Given an entry whose venue is 3
When the user picks 4 then picks 3 again
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
And for a many relation the same ids in another order count as changed
Scenario Outline: Server answers for a relation field
Given the client found no error and the PUT or POST is sent
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 422 | invalid_entry: venue: required | "Choose a Venue." under the control, error border, chip "Not saved", focus on the control |
| 422 | invalid_entry: venue: type | "Venue must point to an existing entry." (proposed copy) under the control, chip "Not saved" |
| 409 | invalid_entry: venue: unique | the one to one copy above |
| 422 | invalid_entry: venue: unknown_field | the read-only reload alert of features/content_entry_editor.feature, same as for media |
Scenario: Layout of the generated form with a relation
Given a boolean, a number or a date field before the relation
Then the relation never pairs and is full width at every viewport
Scenario: Mobile form
Given a 390 px viewport
Then chips are 32 px high, rows are 48 px high, the input is 44 px high, and the list opens as a bottom sheet (proposed) or under the input as drawn
Scenario Outline: The relation cell (design "Relation in the list")
Given the entry list of Events with the columns Title, Starts on, Venue and Speakers
And the item's relations <relations>
Then the cell shows <cell>
Examples:
| relations | cell |
| venue 3 "Rue Verte hall" | one chip "Rue Verte hall" (20 px high, 6 px padding) |
| speakers 11, 12 | two chips "Ines Duarte" and "Jonas Pereira" |
| speakers 11, 12 and two more | two chips and the muted 12 px text "+2" |
| no venue | the muted "–" |
| an empty speakers list | the muted "–" |
| a missing venue | a dashed chip "Entry no longer exists" (proposed copy) |
Scenario: Columns of the board (desktop)
Given the items 42, 41 and 40
Then the grid reads ID, Title, Starts on, Venue, Speakers with the columns 48 px, 1.4fr, 110 px, 200 px, 200 px
And row 42 shows "Rue Verte hall" and "Ines Duarte", "Jonas Pereira", "+2"; row 41 shows "–" and "Jonas Pereira"; row 40 shows "Rue Verte yard" and "–"
And rows stay 48 px high and the header is 36 px high on the elevated background
And the note "One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash." is a design annotation and is not rendered
Scenario: The mobile card
Given a 390 px viewport and Venue and Speakers among the columns
Then each card lists the title, then a line "Venue" (12 px muted) followed by its chips, then a line "Speakers" followed by its chips (wrapping), and "–" for none
And the card keeps its minimum height
Scenario: Columns menu
When the user opens "Columns"
Then "Venue" and "Speakers" are listed with the link icon, their keys, and a checkbox like other fields
And the cap of 6, Reset and the stored choice work as for any field
And a relation column is not sortable and has no sort icon and no aria-sort
Scenario: Cell data comes from the item
Then the chips are read from each item's own "relations" object with no extra request
And the plain text of a relation cell (card title, page title) reads the labels joined by ", " or "–", never the numeric id
Scenario: Relation as the first column
Given a type whose first field is a relation
Then the first column still links to the editor and the chips are the link content
And the page title and breadcrumb of such an entry read "Entry 42"
Scenario: Accessibility of the control
Then the control is a combobox with role="combobox", aria-expanded, aria-controls and aria-activedescendant on the input, labelled by the field label
And the list is role="listbox" with role="option" rows
And chips are a group labelled by the field label, each x is a button named "Remove Ines Duarte from Speakers"
And required adds aria-required, the error text has an id and aria-invalid and aria-describedby point at it then at the help
And one polite live region announces added, removed and cleared values and the result count ("3 results" / "No results", proposed copy)
And mobile targets are 44 px
Scenario: Accessibility of the builder
Then the shape cards are a radio group with a visible selected state that is not only a colour, the disabled locked controls are announced as disabled, and "Can't be applied" is a text badge
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: relation field in the SPA
Two parts. Part 1 is automated (Vitest component tests, `task test:web`). Part 2 is the visual gate (`task visual:check`). Part 3 is manual. The Go side is in `relation_field_type.qa.md`. Until `task test:web` exists, SPA tests are reported NOT RUN, never passing.
## Part 1: automated (Vitest + Vue Test Utils)
Mock `/v1` per test with the shapes below; no live server. A field is `{"key","label","type":"relation","required","unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type","kind"}}` and every other field carries `"relation": null`.
Registry
1. `lib/fieldTypes`: the relation entry has the properties of the registry outline (label, icon `lucide:link`, control `RelationField`, no unique/limits/default/choices, empty value per kind, sample null or []). An unknown type still falls back to text; a relation never does.
2. Client validation table (single and many, required/optional, 0, "3", [3], duplicates, 51 ids) and the message map including the "not produced" rules.
Builder (one test per state)
3. Type gallery: Relation is the last tile; locked on a saved field with the other tiles dimmed.
4. New relation: the related-type select lists the other types (mock `GET /v1/content-type`), the help text, the three cards with the exact sentences, default "One to many" (proposed); choosing a type updates the sentences.
5. Preview outline: the kind change updates both sentences and the line `· shown on Venue as the field "Events"`; the example cards "Event" and "Venue" show the board's chips (Rue Verte hall, Open day, Lime plaster workshop, +1). Nothing about the inverse is in any request.
6. Save body: relation sent as `{"content_type","kind"}`, others `"relation": null`; a loaded field round-trips unchanged; no related type chosen blocks Save with the proposed message.
7. Saved relation: key, tiles, related type and cards are disabled; Label and Required editable; the proposed lock note shows.
8. Review: required relation + entries > 0 shows the flagged row and disabled "Apply changes" with no PUT; optional shows the clean row; required with 0 entries sends at once; making an optional relation required shows "Entries may not fit" with Apply enabled.
9. Server answers: 409 `schema_incompatible` and 422 `invalid_field` map to the existing flows.
10. Delete refused: 409 `content_type_referenced` shows the proposed copy and the type stays listed.
11. A non-owner/admin sees no builder.
Entry form (one test per state)
12. Single control: type "rue" -> only `GET /v1/content-type/venues/entry?q=rue&page=1&size=...` is sent (debounced, trimmed, stale answers ignored); rows show title and second line; pick sets the value to 3, one chip, "Unsaved changes", live message.
13. Many control: chips for [11, 12], "Search to add", the help line; add keeps order; x and Backspace remove; picked ids are not offered again; the 51st is blocked with the proposed message.
14. States: loading (skeleton after 150 ms), no match with "Clear search", empty type, 500, network error, 429 countdown, 401 redirect, 404 (all with the proposed copy where tagged), "Try again" re-sends only the search.
15. Missing target (optional and required), saving, keyboard (arrows, Enter, Esc, Tab, Backspace), required-empty error and focus order (first invalid field only).
16. Outline "What the control shows and sends" (all 7 rows) and the create payload with `venue: null`, `speakers: []` and with a picked number.
17. Dirty tracking: back to the original value gives "Saved"; reordered many ids count as changed.
18. Server answers table: `required`, `type`, `unique`, `unknown_field` (reload alert), each with the right copy, chip and focus.
19. Layout: a relation after boolean/number/date never pairs.
List
20. Cell outline (one chip, two chips, two chips + "+2", dash for null, dash for [], missing chip) from each item's `relations` with no extra request; relation columns are not sortable (no sort icon, no `aria-sort`).
21. Desktop grid for items 42/41/40 matches the board texts; the mobile card shows the labelled lines; the Columns menu lists Venue and Speakers with the link icon and the cap of 6.
22. Plain text of a relation cell never shows the numeric id; a first-field relation keeps the link and the "Entry N" title.
Accessibility
23. Combobox/listbox roles and attributes, chip group label, "Remove X from Y" button names, required/invalid/describedby wiring, the live region texts.
## Part 2: visual (`task visual:check -- <screen>`)
Hard gate: each capture within 10 % at 1440x900 and 390x844, light and dark. Add setups in `web/visual/states.ts` with the board's own sample data; no clock-sensitive state exists in this group.
| Screen | State | Board sample data the mock must reuse |
| --- | --- | --- |
| schema | Relation in the builder | Events with Venue (label), key `venue`, related type Venue, "One to many" selected, preview sentences, example cards with chips "Rue Verte hall", "Open day", "Lime plaster workshop", "+1" |
| entry (content/events/42) | Relation in the entry form | Title "Lime plaster workshop" (21 / 80); Venue search "rue" with rows "Rue Verte hall / Lyon · 120 seats", "Rue Verte yard / Lyon · outdoor", "Rue du Port studio / Nantes · 24 seats"; Speakers chips "Ines Duarte", "Jonas Pereira"; help "An event can have many speakers." |
| content (events) | Relation in the list | Items 42 "Lime plaster workshop" 21 Nov 2026 (Rue Verte hall; Ines Duarte, Jonas Pereira, +2), 41 "Heat pumps: what the numbers say" 3 Nov 2026 (–; Jonas Pereira), 40 "Open day at the Rue Verte site" 12 Nov 2026 (Rue Verte yard; –) |
Notes:
- The board's states are drawn with a "Later" badge; the SPA does not render it. Expect a pixel difference at the badge. If the 10 % gate fails because of it, the user decides on a documented `exception` (`approvedBy`); the QA never adds one.
- The board's builder shows a four-tile gallery plus Relation; the SPA shows the full gallery. The mismatch is reported to the user, not worked around.
- States tagged "(proposed copy)" (loading, no match, error, missing chip, locked inspector, review refusal, delete refusal) are not on the board and get Vitest tests only, no visual capture.
## Part 3: manual (screenshots can't cover)
- Keyboard and focus order across the combobox, chips and list; screen reader announcements of the live region.
- Hover and motion of the popover and of the chips' x; the mobile bottom-sheet versus under-input choice.
- Real SQLite end to end with the built binary: build the type pair, pick, save, reload, delete a target and see the missing chip.
- `bunx playwright install chromium` the first time on a machine.
+235
View File
@@ -0,0 +1,235 @@
Feature: Relation field type for custom content types
As a site owner or admin
I want a content type field that links an entry to entries of another content type
So that structured content can refer to other structured content
Background:
Given internal/domain/contenttype adds the field type "relation" next to text, richtext, number, boolean, date, select and media
And a relation field carries "relation": {"content_type": <key of an existing type>, "kind": "one_to_one" | "one_to_many" | "many_to_many"}
And "one_to_many" reads from the owner: each owner entry has one target, a target has many owner entries
And every field response gains the key "relation", null for the other types, so a field has exactly ten keys
And a relation field accepts only label, key, required and relation; unique, default, min, max and options are refused with ErrInvalidField
And the target type must exist, else ErrInvalidField; a self relation is allowed for one_to_many and many_to_many and refused for one_to_one
And the connection is stored once, on the owner field; the inverse side is derived, never stored, never added to the target schema, and the target type's schema, entry responses, list and routes are unchanged
And the owner value is an id (uint32, at least 1) or null for one_to_one and one_to_many, and an array of ids ([] when empty, at most 50, no duplicates, order kept) for many_to_many
And entry.Validate stays pure; the existence of target entries is checked by CreateEntry and UpdateEntry through entry.Repository
And a changed value means an id not equal to the one in the stored document for that key; on POST every id is changed; on PUT an unchanged id is not checked for existence unless the field is required
And a changed id must be an existing entry of the target type, else 422 "invalid_entry: <key>: type"
And a required relation is never saved empty: null, absent or [] give 422 "invalid_entry: <key>: required", and so does an unchanged id whose entry is gone
And a one_to_one id already held by another entry of the owner type is refused with 409 "invalid_entry: <key>: unique" (entry.ErrUniqueViolation)
And rules are checked in field order for Validate, then target existence in field order, then unique, and the body names one field per answer
And an entry response keeps its eight keys and adds "relations", always present ({} when no relation is set)
And "relations"[key] is {"id","content_type","first_field":{"key","type","value"}} for an existing target, or {"id","missing":true} when it is gone; for many_to_many it is an array of these in stored order
And first_field is the first field of the target type in schema order with its raw stored value, never formatted by the server
And the same "relations" object is on POST 201, PUT 200, GET one and every item of the list
And GET /v1/content-type/{key}/entry accepts ?q=, a trimmed case-insensitive substring of the display text of the first field, filtered in Go on the unpaged list before pagination, so total counts the matches; an empty q means no filter
And deleting an entry that other entries reference is allowed and leaves them untouched
And DELETE /v1/content-type/{key} on a type that is the target of a relation field is refused with 409 "content_type_referenced" (contenttype.ErrReferenced, new apperr string), even with no entries
And a saved relation field's type, target and kind never change: a change is refused with 422 "invalid_field"
And a new required relation on a type with entries gives 409 "schema_incompatible"
And no repository method is added; the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And the key-set assertions of the earlier custom content type, entry and media features and tests are amended (field 9 to 10 keys, entry 8 to 9 keys)
And types: "venue" has title (text, required) and city (text); "event" has title (text, required) then venue (relation to venue, one_to_many, label "Venue") then speakers (relation to speaker, many_to_many); "speaker" has name (text, required)
And entries: venue 3 "Rue Verte hall", venue 4 "Rue Verte yard"; speaker 11 "Ines Duarte", speaker 12 "Jonas Pereira"
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a relation field
Given a valid jwt cookie for admin 2 and the type "venue"
When the client sends POST /v1/content-type with fields title (text, required) and
{"key":"venue","label":"Venue","type":"relation","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[],"relation":{"content_type":"venue","kind":"one_to_many"}}
Then the response status is 201
And the venue field comes back with that relation object and the other fields have "relation": null
Scenario Outline: A relation field with a bad definition is refused
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a relation field that has <defect>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| defect |
| relation null |
| content_type "nope" (unknown type) |
| content_type "" or missing |
| kind "many_to_one" |
| kind missing |
| a relation object on a text field |
| unique true |
| default 3 |
| min 1 |
| max 5 |
| options ["a"] |
| a one_to_one self relation |
Scenario: The shape of a saved relation never changes
Given the type "event" has a saved relation "venue" (one_to_many to venue) and at least one entry
When admin 2 sends PUT /v1/content-type/event changing its kind to many_to_many
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT changing its target to speaker
Then the response is 422 invalid_field and the schema is unchanged
When admin 2 sends PUT turning it into a text field
Then the response is 422 invalid_field and the schema is unchanged
Scenario Outline: Adding a relation field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT adding a relation field "venue" that is <required>
Then the response status is <status> and the body is <message>
Examples:
| required | status | message |
| required | 409 | schema_incompatible |
| optional | 200 | |
Scenario: Deleting a type that another type points at
Given the type "venue" has no entries and "event" has a relation to it
When admin 2 sends DELETE /v1/content-type/venue
Then the response status is 409 with "content_type_referenced" and venue still exists
When the relation field is removed from "event" and DELETE is sent again
Then the response status is 204
Scenario: Creating an entry with a single target
When a verified user sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","venue":3}}
Then the response status is 201 and data.venue is 3
And relations is {"venue":{"id":3,"content_type":"venue","first_field":{"key":"title","type":"text","value":"Rue Verte hall"}}}
Scenario: Creating an entry with many targets
When the client sends POST with {"data":{"title":"A","speakers":[12,11]}}
Then data.speakers is [12,11] and relations.speakers lists speaker 12 then speaker 11
Scenario Outline: Empty optional relations
When the client sends POST with <data>
Then the response status is 201, <stored>, and relations is {}
Examples:
| data | stored |
| {"data":{"title":"A","venue":null}} | data.venue is null |
| {"data":{"title":"A"}} | data.venue is absent |
| {"data":{"title":"A","speakers":[]}} | data.speakers is [] |
Scenario Outline: Values that break a relation are refused and store nothing
Given "venue" is <required> and "speakers" is many_to_many
When the client sends POST with the data <data>
Then the response status is <status> and the body is <message>
And no entry exists
Examples:
| required | data | status | message |
| required | {"title":"A"} | 422 | invalid_entry: venue: required |
| required | {"title":"A","venue":null} | 422 | invalid_entry: venue: required |
| optional | {"title":"A","venue":999} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":"3"} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":0} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":3.5} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","venue":[3]} | 422 | invalid_entry: venue: type |
| optional | {"title":"A","speakers":11} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,11]} | 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[11,999]}| 422 | invalid_entry: speakers: type |
| optional | {"title":"A","speakers":[3]} | 422 | invalid_entry: speakers: type |
| optional | speakers with 51 ids | 422 | invalid_entry: speakers: type |
Scenario: A required many relation is never empty
Given "speakers" is required
When the client sends POST with speakers [] or with the key absent
Then the response is 422 invalid_entry: speakers: required
Scenario: One to one keeps targets exclusive
Given the type "talk" has a one_to_one relation "room" to "venue" and a talk already holds venue 3
When the client sends POST with room 3
Then the response is 409 "invalid_entry: room: unique" and nothing is stored
When the holder is updated with room 3 unchanged
Then the response is 200
When the holder is deleted and the POST is sent again
Then the response is 201
Scenario: Replacing and clearing targets
Given the entry 5 holds venue 3 and speakers [11]
When a verified user sends PUT with venue 4 and speakers [11,12]
Then data and relations reflect venue 4 and speakers 11, 12
When the user sends PUT with venue null and speakers []
Then relations is {}
Scenario: A target deleted after the entry was saved
Given the entry 5 holds venue 3 and speakers [11,12]
When entry 3 of venue and entry 12 of speaker are deleted (both answer 204)
And the client sends GET /v1/content-type/event/entry/5
Then data is unchanged
And relations.venue is {"id":3,"missing":true}
And relations.speakers is [{"id":11,"content_type":"speaker","first_field":{"key":"name","type":"text","value":"Ines Duarte"}},{"id":12,"missing":true}]
And the entry 5 was not modified (updated_at and updated_by unchanged)
Scenario Outline: Unchanged and changed ids when the target is gone
Given the entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 3 | 200 | |
| 999 | 422 | invalid_entry: venue: type |
| 4 | 200 | |
| null | 200 | |
Scenario Outline: A required relation with a missing target can't be saved as is
Given venue is required, entry 5 holds venue 3 and venue 3 was deleted
When the user sends PUT with venue <value>
Then the status is <status>, the body is <message> and the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 3 | 422 | invalid_entry: venue: required | unchanged |
| null | 422 | invalid_entry: venue: required | unchanged |
| 4 | 200 | | updated |
Scenario: A create always treats the id as changed
Given venue 3 was deleted
When the client sends POST with venue 3
Then the response is 422 invalid_entry: venue: type
Scenario: Two broken fields name only one
Given a body with a required text left empty and a relation to a missing target
Then the answer names one field: Validate rules first in field order, then existence, then unique
Scenario: Entry list responses carry relations per item
Given 3 events: one with a venue and two speakers, one with a deleted venue, one with nothing
When the client sends GET /v1/content-type/event/entry
Then each item keeps its eight keys and adds "relations"
And items, total, page and size are unchanged
And a type without a relation field returns "relations": {} and makes no target repository call
Scenario Outline: Searching the entries of a type
Given the type "venue" has entries titled "Rue Verte hall", "Rue Verte yard", "Rue du Port studio"
When the client sends GET /v1/content-type/venue/entry?q=<q>
Then total is <total>
Examples:
| q | total |
| rue | 3 |
| RUE VERTE | 2 |
| yard | 1 |
| nothing | 0 |
| | 3 |
Scenario: Search is paginated after filtering
Given 30 venues match "rue"
When the client sends GET /v1/content-type/venue/entry?q=rue&page=2&size=10
Then total is 30, page is 2, size is 10 and items holds the second ten matches in the requested sort
Scenario: Deleting an entry that is referenced
Given 4 events hold venue 3
When a verified user sends DELETE /v1/content-type/venue/entry/3
Then the response status is 204 and the 4 events are not modified
Scenario: The target type, entries and API are unchanged
Given "event" has a one_to_many relation to "venue"
When the client sends GET /v1/content-type/venue and GET /v1/content-type/venue/entry/3
Then neither response carries the inverse field "Events" and the venue field list is the one saved
Scenario: Use case level
Given fake contenttype and entry repositories
Then contenttype.ValidateFields returns ErrInvalidField for each refused definition
And entry.Validate returns errors.Is(err, entry.ErrInvalidEntry) with Key and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing target and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required relation and ErrInvalidField for a changed shape
And DeleteContentType returns contenttype.ErrReferenced for a target type
+48
View File
@@ -0,0 +1,48 @@
# QA procedure: relation field type (API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse `mockContentTypeRepo` and `mockEntryRepo` of the custom content type and media pairs. Fake names stay unique across the package. The entry fake needs `createCalls`, `updateCalls`, a `getCalls` counter per content type and a `deleteEntry(contentTypeID, id)` helper. No repository method is added.
3. Build `NewHandler(...)` for the content type and entry handlers over use cases wired to the fakes. Mount them on a fresh `chi.NewRouter()` mirroring api/router.go under `/v1/content-type`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`, and `RequireOwnerOrAdmin` on the type write routes. Prefer `api.InitBackendRoutes` with a partial `*api.UseCases` if it works.
4. Seed admin 2 and a plain verified user. Seed the types venue, speaker, event and talk, and the entries venue 3, 4 and speaker 11, 12 from the feature.
5. Inject a fake clock so `updated_at` > `created_at`. Decode bodies into `map[string]any` and compare numbers as `float64`.
## Schema
6. POST a valid relation field -> 201; `relation` is the object sent; every other field has `"relation": null`; every field has exactly ten keys.
7. Refusal table (null relation, unknown target, empty target, bad kind, missing kind, relation on a text field, unique/default/min/max/options, one_to_one self) -> 422 `invalid_field`, repo empty.
8. Locking: kind, target and type changes on a saved relation -> 422 `invalid_field`, schema byte-identical. A type with no entries keeps today's free type change for non-saved shapes.
9. Type with 12 entries: add required relation -> 409 `schema_incompatible`, unchanged; add optional -> 200 and the old entries read with `relations` `{}`.
10. DELETE a target type with no entries -> 409 `content_type_referenced` (plain text); after removing the relation field -> 204. A type with entries is still 409 `content_type_has_entries`.
## Entry writes
11. Single and many targets -> 201, `data` as sent (array order kept), `relations` as in the feature. The target object has exactly `id`, `content_type`, `first_field`; `first_field` has exactly `key`, `type`, `value`, with the raw stored value.
12. Empty optional (null, absent, []) -> 201, `relations` is `{}` (assert JSON `{}`, not null). A required many field with [] or absent -> 422 required.
13. Refusal table -> exact status and body, `createCalls == 0`. The 51-id case is built in the test.
14. A venue id in a speaker field -> 422 type.
15. One-to-one exclusivity: 409 `invalid_entry: room: unique`, nothing stored; PUT of the holder unchanged -> 200; after deleting the holder, POST -> 201.
16. PUT replace/clear -> 200 with updated `relations`.
17. Dangling targets: `deleteEntry` venue 3 and speaker 12 -> GET entry 5 shows `{"id":3,"missing":true}` and the mixed array; `updated_at`/`updated_by` unchanged. PUT unchanged id -> 200; 999 -> 422 type; other id or null -> 200.
18. Required relation with a gone target: PUT same id -> 422 required; null -> 422 required; other id -> 200. POST with a deleted id -> 422 type.
19. Ordering: two bad fields name one only (Validate in field order, then existence, then unique).
## Reads
20. List with 3 events (full, dangling, empty) -> every item has the 8 old keys plus `relations`; `total`, `page`, `size` unchanged; `items` is `[]` for an empty type.
21. A type without a relation field -> `relations` `{}` and zero Get calls on target types. 100 entries pointing at one target call Get at most once for that id.
22. `?q=` table (case-insensitive, trimmed, empty = all, none = 0); `total` counts matches; page 2 size 10 of 30 matches returns the second ten; invalid `page`/`size`/`sort` keep their existing errors.
23. GET venue and GET a venue entry after the relation exists on event -> no inverse field, same keys as before.
## Delete
24. DELETE a referenced venue entry -> 204; the referencing events are byte-identical and no Update is recorded.
## Use case level (no HTTP)
25. `ValidateFields`, `entry.Validate`, `CreateEntry`/`UpdateEntry`, `UpdateContentType`, `DeleteContentType` as in the last scenario (`errors.Is`).
## Existing tests to amend
26. Key-set assertions in the custom content type, entry and media specs and tests: field 9 -> 10 keys, entry 8 -> 9 keys. The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create venue and event with a relation, save entries, delete the venue entry, reload the event and confirm the dangling id and `missing`.
- Time `GET .../entry?q=` against a type with 1,000 entries (the filter loads the whole type).
- The SPA is the second pair and is not checked here.