# Fields Management Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Let admins create flexible field definitions — expose `POST /api/admin/field-definitions` over the existing db layer, and build a `/fields` two-pane screen (grouped list + create form) that enables the last nav stub. **Architecture:** A thin axum write handler reuses `FieldType::from_parts` as the single type/binding validation chokepoint and `db::fields::create_field_definition`. The frontend reuses the Objects/Vocabularies two-pane idiom: a grouped read-only list (`useFieldDefinitions`, already cached and shared with the M2 object editor) plus a create form with native `` for dropdowns (matches `web/src/objects/field-input.tsx` — a deliberate bundle-lean choice). - Test infra (running docker containers; start if down): `DATABASE_URL=postgres://postgres:postgres@localhost:5433/cms_dev`, `MEILI_URL=http://localhost:7701`, `MEILI_MASTER_KEY=masterKey`. (Field-definition tests need only Postgres; `#[sqlx::test]` provisions its own DB.) - Run web commands from `web/`; cargo from repo root. --- ## Task 1: Backend — `POST /api/admin/field-definitions` The GET handler already lives in `crates/api/src/admin_objects.rs` and its route is registered there. **axum panics if the same path is declared in two merged routers**, so the POST handler goes in `admin_objects.rs` too and chains `.post(...)` onto the existing `.route("/api/admin/field-definitions", get(list_field_definitions))`. No domain or db changes — `FieldType::from_parts` and `db::fields::create_field_definition` already exist. **Files:** - Modify: `crates/api/src/admin_objects.rs` (add request/response structs, handler, chain `.post`) - Modify: `crates/api/src/openapi.rs` (register path + schemas) - Test: `crates/api/tests/admin_fields.rs` (new) - Regenerate: `web/src/api/schema.d.ts` - [ ] **Step 1: Write the failing API test** — create `crates/api/tests/admin_fields.rs`: ```rust use api::{AppState, build_app, migrate_sessions}; use axum::body::Body; use axum::http::{Request, StatusCode, header}; use db::users; use domain::{AuditActor, Email, NewUser, Role}; use http_body_util::BodyExt; use sqlx::PgPool; use tower::ServiceExt; fn state(pool: PgPool) -> AppState { AppState { db: db::Db::from_pool(pool), app_name: "Test".into(), cookie_secure: false, search: None, } } async fn seed_user(pool: &PgPool, email: &str, password: &str, role: Role) { let db = db::Db::from_pool(pool.clone()); let mut tx = db.pool().begin().await.unwrap(); users::create_user( &mut tx, AuditActor::System, &NewUser { email: Email::parse(email).unwrap(), password_hash: auth::hash_password(password).unwrap(), role, }, ) .await .unwrap(); tx.commit().await.unwrap(); } async fn login(app: &axum::Router, email: &str, password: &str) -> String { let resp = app .clone() .oneshot( Request::builder() .method("POST") .uri("/api/admin/login") .header(header::CONTENT_TYPE, "application/json") .body(Body::from(format!( r#"{{"email":"{email}","password":"{password}"}}"# ))) .unwrap(), ) .await .unwrap(); assert_eq!(resp.status(), StatusCode::NO_CONTENT); resp.headers() .get(header::SET_COOKIE) .unwrap() .to_str() .unwrap() .split(';') .next() .unwrap() .to_owned() } async fn post_field(app: &axum::Router, cookie: &str, body: &str) -> axum::http::Response { app.clone() .oneshot( Request::builder() .method("POST") .uri("/api/admin/field-definitions") .header(header::COOKIE, cookie) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(body.to_owned())) .unwrap(), ) .await .unwrap() } #[sqlx::test(migrations = "../db/migrations")] async fn create_requires_auth(pool: PgPool) { migrate_sessions(&db::Db::from_pool(pool.clone())).await.unwrap(); let app = build_app(state(pool)); let resp = app .oneshot( Request::builder() .method("POST") .uri("/api/admin/field-definitions") .header(header::CONTENT_TYPE, "application/json") .body(Body::from( r#"{"key":"x","data_type":"text","required":false,"labels":[{"lang":"en","label":"X"}]}"#, )) .unwrap(), ) .await .unwrap(); assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); } #[sqlx::test(migrations = "../db/migrations")] async fn create_scalar_field_then_lists_it(pool: PgPool) { migrate_sessions(&db::Db::from_pool(pool.clone())).await.unwrap(); seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await; let app = build_app(state(pool)); let cookie = login(&app, "ed@example.com", "pw-editor-123").await; let resp = post_field( &app, &cookie, r#"{"key":"height_cm","data_type":"integer","required":true,"group":"Dimensions","labels":[{"lang":"en","label":"Height"},{"lang":"sv","label":"Höjd"}]}"#, ) .await; assert_eq!(resp.status(), StatusCode::CREATED); let body: serde_json::Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap(); assert_eq!(body["key"], "height_cm"); // It appears in the GET listing. let list = app .oneshot( Request::builder() .uri("/api/admin/field-definitions") .header(header::COOKIE, &cookie) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let defs: serde_json::Value = serde_json::from_slice(&list.into_body().collect().await.unwrap().to_bytes()).unwrap(); assert!(defs.as_array().unwrap().iter().any(|d| d["key"] == "height_cm")); } #[sqlx::test(migrations = "../db/migrations")] async fn term_without_vocabulary_is_422(pool: PgPool) { migrate_sessions(&db::Db::from_pool(pool.clone())).await.unwrap(); seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await; let app = build_app(state(pool)); let cookie = login(&app, "ed@example.com", "pw-editor-123").await; let resp = post_field( &app, &cookie, r#"{"key":"material","data_type":"term","required":false,"labels":[{"lang":"en","label":"Material"}]}"#, ) .await; assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY); } #[sqlx::test(migrations = "../db/migrations")] async fn duplicate_key_is_409(pool: PgPool) { migrate_sessions(&db::Db::from_pool(pool.clone())).await.unwrap(); seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await; let app = build_app(state(pool)); let cookie = login(&app, "ed@example.com", "pw-editor-123").await; let body = r#"{"key":"dup","data_type":"text","required":false,"labels":[{"lang":"en","label":"Dup"}]}"#; assert_eq!(post_field(&app, &cookie, body).await.status(), StatusCode::CREATED); assert_eq!(post_field(&app, &cookie, body).await.status(), StatusCode::CONFLICT); } ``` - [ ] **Step 2: Run it to confirm it fails** — ```bash cargo test -p api --test admin_fields ``` Expected: 401-test may pass incidentally, but the create tests fail (route has no POST → 405/404). - [ ] **Step 3: Add the request/response structs + handler** — in `crates/api/src/admin_objects.rs`. First ensure the imports at the top include what's needed (the file already imports axum bits, `State`, `StatusCode`, `Json`, `db`, `auth::{Authorized, ViewInternal}`; add `EditCatalogue` and the domain types). Add to the `use auth::...` line: `EditCatalogue`. Add `use domain::{AuthorityKind, FieldType, LocalizedLabel, NewFieldDefinition, VocabularyId};` if not already present (the file may already import some domain types — merge, don't duplicate). Reuse `LabelInput` — it is defined in `admin_vocab`; import it: `use crate::admin_vocab::LabelInput;` (the file already imports from `crate`; add this). Then add the structs (near `FieldDefinitionView`): ```rust #[derive(serde::Deserialize, utoipa::ToSchema)] pub(crate) struct NewFieldDefinitionRequest { pub key: String, /// text | localized_text | integer | date | boolean | term | authority pub data_type: String, pub vocabulary_id: Option, pub authority_kind: Option, pub required: bool, pub group: Option, pub labels: Vec, } #[derive(serde::Serialize, utoipa::ToSchema)] pub(crate) struct CreatedField { pub key: String, } ``` (If `serde::{Deserialize, Serialize}` and `utoipa::ToSchema` are already imported in this file, use the bare derive names to match the file's style.) And the handler: ```rust /// Create a field definition. Requires `EditCatalogue`. All type/binding consistency /// (term needs a vocabulary, authority takes no vocabulary, scalars take no binding) is /// validated by `FieldType::from_parts`, which returns `None` for any bad combination. #[utoipa::path( post, path = "/api/admin/field-definitions", request_body = NewFieldDefinitionRequest, responses( (status = 201, body = CreatedField), (status = 400, description = "Malformed vocabulary_id or authority_kind"), (status = 401), (status = 403), (status = 409, description = "Duplicate key"), (status = 422, description = "Inconsistent type/binding") ) )] pub(crate) async fn create_field_definition( _auth: Authorized, State(state): State, Json(req): Json, ) -> Result<(StatusCode, Json), StatusCode> { let vocabulary_id = match req.vocabulary_id.as_deref() { None | Some("") => None, Some(s) => Some(s.parse::().map_err(|_| StatusCode::BAD_REQUEST)?), }; let authority_kind = match req.authority_kind.as_deref() { None | Some("") => None, Some(s) => Some(AuthorityKind::from_db(s).ok_or(StatusCode::BAD_REQUEST)?), }; let field_type = FieldType::from_parts(&req.data_type, vocabulary_id, authority_kind) .ok_or(StatusCode::UNPROCESSABLE_ENTITY)?; let new = NewFieldDefinition { key: req.key, field_type, required: req.required, group_key: req.group, labels: req .labels .into_iter() .map(|l| LocalizedLabel { lang: l.lang, label: l.label, }) .collect(), }; let mut tx = state .db .pool() .begin() .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; match db::fields::create_field_definition(&mut tx, &new).await { Ok(_) => { tx.commit() .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok((StatusCode::CREATED, Json(CreatedField { key: new.key }))) } // Duplicate `key` violates the unique index (SQLSTATE 23505). Err(err) if err .as_database_error() .and_then(|e| e.code()) .as_deref() == Some("23505") => { Err(StatusCode::CONFLICT) } Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR), } } ``` Note: `AuthorityKind::from_db` is the existing parser (`crates/domain/src/authority.rs`); confirm the method name there (it is `from_db`, returning `Option`). `VocabularyId: FromStr` is used the same way `admin_vocab` parses ids. - [ ] **Step 4: Chain `.post` onto the existing route** — in `admin_objects.rs` `routes()`, change: ```rust .route("/api/admin/field-definitions", get(list_field_definitions)) ``` to ```rust .route( "/api/admin/field-definitions", get(list_field_definitions).post(create_field_definition), ) ``` - [ ] **Step 5: Register in OpenAPI** — in `crates/api/src/openapi.rs`: add `admin_objects::create_field_definition` to `paths(...)`; add `admin_objects::NewFieldDefinitionRequest` and `admin_objects::CreatedField` to `components(schemas(...))`. - [ ] **Step 6: Run the API tests** — `cargo test -p api --test admin_fields` → 4 pass. - [ ] **Step 7: Regenerate the typed web client** — ```bash cargo build -p server DATABASE_URL=postgres://postgres:postgres@localhost:5433/cms_dev \ MEILI_URL=http://localhost:7701 MEILI_MASTER_KEY=masterKey \ ./target/debug/server & SERVER_PID=$! sleep 2 ( cd web && pnpm gen:api ) kill "$SERVER_PID" grep -n "NewFieldDefinitionRequest\|CreatedField" web/src/api/schema.d.ts ``` The grep must show both schemas. Then `cd web && pnpm typecheck` to confirm the regenerated file is well-formed (the diff should be purely additive — the existing `/api/admin/field-definitions` GET path gains a `post` operation; no existing paths removed). If a stale server occupies :8080, kill it first (`lsof -ti :8080 | xargs kill`). - [ ] **Step 8: Format, lint, commit** — ```bash cargo +nightly fmt cargo clippy -p api --all-targets cd /Users/olsson/Laboratory/biggus-dickus git add crates/api web/src/api/schema.d.ts git commit -m "feat(api): POST /api/admin/field-definitions (create field definition)" ``` --- ## Task 2: Frontend data layer — `useCreateFieldDefinition` + MSW handler **Files:** - Modify: `web/src/api/queries.ts`, `web/src/test/handlers.ts` - Test: `web/src/api/queries.fields.test.tsx` (new) The `fieldDefinitions` GET fixture already exists (`web/src/test/fixtures.ts`) with a grouped entry (`inscription`, group "Description") and ungrouped entries, and the GET handler is already wired. Only the mutation + POST handler are new. - [ ] **Step 1: Add the MSW POST handler** — in `web/src/test/handlers.ts`, add to the `handlers` array: ```ts http.post("/api/admin/field-definitions", () => HttpResponse.json({ key: "new_field" }, { status: 201 }), ), ``` - [ ] **Step 2: Write the failing hook test** — create `web/src/api/queries.fields.test.tsx`: ```tsx import { expect, test } from "vitest"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { renderHook, waitFor } from "@testing-library/react"; import { http, HttpResponse } from "msw"; import { server } from "../test/server"; import { useCreateFieldDefinition } from "./queries"; function wrapper({ children }: { children: React.ReactNode }) { const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); return {children}; } test("useCreateFieldDefinition POSTs the request body", async () => { let body: unknown; server.use( http.post("/api/admin/field-definitions", async ({ request }) => { body = await request.json(); return HttpResponse.json({ key: "technique" }, { status: 201 }); }), ); const { result } = renderHook(() => useCreateFieldDefinition(), { wrapper }); result.current.mutate({ key: "technique", data_type: "term", vocabulary_id: "v-technique", authority_kind: null, required: false, group: "Provenance", labels: [{ lang: "en", label: "Technique" }], }); await waitFor(() => expect(result.current.isSuccess).toBe(true)); expect((body as { key: string; data_type: string }).key).toBe("technique"); expect((body as { data_type: string }).data_type).toBe("term"); }); ``` - [ ] **Step 3: Run it to confirm it fails** — `cd web && pnpm test src/api/queries.fields.test.tsx` → FAIL (no `useCreateFieldDefinition`). - [ ] **Step 4: Implement the hook** — in `web/src/api/queries.ts`, append (it uses the already-imported `useMutation`, `useQueryClient`, `api`, and `components`): ```ts type NewFieldDefinitionRequest = components["schemas"]["NewFieldDefinitionRequest"]; export function useCreateFieldDefinition() { const qc = useQueryClient(); return useMutation({ mutationFn: async (body: NewFieldDefinitionRequest) => { const { data, response } = await api.POST("/api/admin/field-definitions", { body }); if (response.status !== 201 || !data) throw new Error("failed to create field definition"); return data; }, onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), }); } ``` - [ ] **Step 5: Run it to confirm it passes** — `pnpm test src/api/queries.fields.test.tsx` → PASS. - [ ] **Step 6: Commit** — ```bash cd /Users/olsson/Laboratory/biggus-dickus git add web git commit -m "feat(web): useCreateFieldDefinition mutation + MSW handler" ``` --- ## Task 3: Frontend — `/fields` two-pane screen, route, nav, i18n **Files:** - Create: `web/src/fields/fields-page.tsx`, `web/src/fields/field-list.tsx`, `web/src/fields/field-form.tsx`, `web/src/fields/fields.test.tsx` - Modify: `web/src/app.tsx`, `web/src/shell/app-shell.tsx`, `web/src/i18n/{en,sv}.json` - [ ] **Step 1: i18n** — add a `fields` namespace to BOTH `web/src/i18n/en.json` and `sv.json` (keep parity; authority-kind option labels reuse the existing `authorities.{person,organisation,place}` keys). `en.json`: ```json "fields": { "title": "Fields", "newField": "New field definition", "key": "Key", "type": "Type", "vocabulary": "Vocabulary", "authorityKind": "Authority kind", "anyKind": "Any", "group": "Group", "required": "Required", "create": "Create field", "empty": "No field definitions yet", "loadError": "Could not load", "other": "Other", "types": { "text": "Text", "localized_text": "Localized text", "integer": "Integer", "date": "Date", "boolean": "Boolean", "term": "Term", "authority": "Authority" } } ``` `sv.json`: ```json "fields": { "title": "Fält", "newField": "Nytt fältdefinition", "key": "Nyckel", "type": "Typ", "vocabulary": "Vokabulär", "authorityKind": "Auktoritetstyp", "anyKind": "Alla", "group": "Grupp", "required": "Obligatoriskt", "create": "Skapa fält", "empty": "Inga fältdefinitioner ännu", "loadError": "Kunde inte ladda", "other": "Övrigt", "types": { "text": "Text", "localized_text": "Lokaliserad text", "integer": "Heltal", "date": "Datum", "boolean": "Boolesk", "term": "Term", "authority": "Auktoritet" } } ``` - [ ] **Step 2: Implement `FieldList`** — create `web/src/fields/field-list.tsx`: ```tsx import { useTranslation } from "react-i18next"; import type { components } from "../api/schema"; import { useFieldDefinitions } from "../api/queries"; import { Skeleton } from "@/components/ui/skeleton"; type FieldDefinitionView = components["schemas"]["FieldDefinitionView"]; function labelText(labels: FieldDefinitionView["labels"], lang: string): string { return ( labels.find((l) => l.lang === lang)?.label ?? labels.find((l) => l.lang === "en")?.label ?? labels[0]?.label ?? "" ); } export function FieldList() { const { t, i18n } = useTranslation(); const { data, isLoading, isError } = useFieldDefinitions(); const lang = i18n.language.startsWith("sv") ? "sv" : "en"; if (isLoading) { return (
{Array.from({ length: 6 }).map((_, i) => ( ))}
); } if (isError) return

{t("fields.loadError")}

; if (!data || data.length === 0) return

{t("fields.empty")}

; // Group by `group`; ungrouped (null/empty) collected under the "Other" heading. const groups = new Map(); for (const def of data) { const key = def.group?.trim() ? def.group : t("fields.other"); const bucket = groups.get(key) ?? []; bucket.push(def); groups.set(key, bucket); } return (
    {[...groups.entries()].map(([group, defs]) => (
  • {group}
      {defs.map((def) => (
    • {labelText(def.labels, lang)} {def.key} {t(`fields.types.${def.data_type}`)} {def.required && *}
    • ))}
  • ))}
); } ``` - [ ] **Step 3: Implement `FieldForm`** — create `web/src/fields/field-form.tsx`. Native ` setKey(e.target.value)} />
{dataType === "term" && (
)} {dataType === "authority" && (
)}
setGroup(e.target.value)} />
{error &&

{t("form.required")}

} {create.isError &&

{t("form.rejected")}

} ); } ``` Before finishing: open `web/src/components/ui/checkbox.tsx` and confirm the controlled API is `checked` + `onCheckedChange(checked: boolean)` (base-ui). If the signature differs, adapt the `` usage (no `any`). Also confirm `@/components/ui/label` exports `Label` (the vocab/object forms use it). - [ ] **Step 4: Implement `FieldsPage`** — create `web/src/fields/fields-page.tsx`: ```tsx import { FieldList } from "./field-list"; import { FieldForm } from "./field-form"; export function FieldsPage() { return (
); } ``` - [ ] **Step 5: Wire the route** — in `web/src/app.tsx`, import `import { FieldsPage } from "./fields/fields-page";` and add inside the `` group: ```tsx } /> ``` - [ ] **Step 6: Enable the Fields nav** — in `web/src/shell/app-shell.tsx`: - change `const DISABLED_NAV = ["fields"] as const;` to `const DISABLED_NAV = [] as const;` - add a Fields `NavLink` after the Search NavLink (before the `DISABLED_NAV.map(...)`): ```tsx `block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}` } > {t("nav.fields")} ``` The `DISABLED_NAV.map(...)` block now renders nothing (empty array) — that is fine; leave it, or remove it if eslint flags an unused `nav.soon`. (`nav.soon` may become unused — if `pnpm lint`/parity complains, leave the key in both i18n files; an unused i18n key is harmless and keeps parity.) - [ ] **Step 7: Write the integration test** — create `web/src/fields/fields.test.tsx`: ```tsx import { expect, test } from "vitest"; import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { http, HttpResponse } from "msw"; import { Route, Routes } from "react-router-dom"; import { server } from "../test/server"; import { renderApp } from "../test/render"; import { FieldsPage } from "./fields-page"; function tree() { return ( } /> ); } test("lists field definitions grouped, with an Other heading for ungrouped", async () => { renderApp(tree(), { route: "/fields" }); // grouped fixture entry (group "Description") and an ungrouped one ("Other") expect(await screen.findByText("Inscription")).toBeInTheDocument(); expect(screen.getByText(/^Description$/i)).toBeInTheDocument(); expect(screen.getByText(/^Other$/i)).toBeInTheDocument(); }); test("creates a text field — posts the body and clears the key input", async () => { let body: { key: string; data_type: string } | undefined; server.use( http.post("/api/admin/field-definitions", async ({ request }) => { body = (await request.json()) as { key: string; data_type: string }; return HttpResponse.json({ key: "notes" }, { status: 201 }); }), ); renderApp(tree(), { route: "/fields" }); await userEvent.type(screen.getByLabelText(/^key$/i), "notes"); await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Notes"); await userEvent.click(screen.getByRole("button", { name: /create field/i })); await waitFor(() => expect(body?.key).toBe("notes")); expect(body?.data_type).toBe("text"); await waitFor(() => expect(screen.getByLabelText(/^key$/i)).toHaveValue("")); }); test("selecting Term reveals the vocabulary picker and blocks submit until chosen", async () => { let posted = false; server.use( http.post("/api/admin/field-definitions", () => { posted = true; return HttpResponse.json({ key: "x" }, { status: 201 }); }), ); renderApp(tree(), { route: "/fields" }); await userEvent.type(screen.getByLabelText(/^key$/i), "material"); await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Material"); await userEvent.selectOptions(screen.getByLabelText(/^type$/i), "term"); // Vocabulary select now present. const vocab = await screen.findByLabelText(/^vocabulary$/i); expect(vocab).toBeInTheDocument(); // Submit without choosing a vocabulary → blocked, alert shown, no POST. await userEvent.click(screen.getByRole("button", { name: /create field/i })); expect(await screen.findByRole("alert")).toBeInTheDocument(); expect(posted).toBe(false); // Choose one (fixture vocabularies: v-material/material, v-technique/technique) → posts. await userEvent.selectOptions(vocab, "v-material"); await userEvent.click(screen.getByRole("button", { name: /create field/i })); await waitFor(() => expect(posted).toBe(true)); }); ``` Run `pnpm test src/fields/fields.test.tsx`. If `getByLabelText(/^key$/i)` is ambiguous (the EN/SV label inputs from `LabelEditor` use `labels.en`/`labels.sv` text), the anchored `/^key$/i` should match only the "Key" `