b490db13b1
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
923 lines
36 KiB
Markdown
923 lines
36 KiB
Markdown
# 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 `<select>`s and conditional config (vocabulary for `term`, kind for `authority`). Creating a field invalidates `["field-definitions"]`, so it appears in both the list and the object editor.
|
||
|
||
**Tech Stack:** Rust (axum 0.8, utoipa, sqlx 0.8), React 19 + TS, TanStack Query v5, react-router-dom 7, react-i18next (sv/en), Vitest + RTL + MSW.
|
||
|
||
**Spec:** `docs/superpowers/specs/2026-06-04-fields-management-design.md`
|
||
|
||
**Conventions (every task):**
|
||
- Rust fmt with **nightly** (`cargo +nightly fmt`); `cargo clippy`.
|
||
- Frontend: no `any` / `eslint-disable` / `@ts-ignore`; en/sv i18n key parity; codename "biggus"/"dickus" nowhere; native `<select>` 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<Body> {
|
||
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<String>,
|
||
pub authority_kind: Option<String>,
|
||
pub required: bool,
|
||
pub group: Option<String>,
|
||
pub labels: Vec<LabelInput>,
|
||
}
|
||
|
||
#[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<EditCatalogue>,
|
||
State(state): State<AppState>,
|
||
Json(req): Json<NewFieldDefinitionRequest>,
|
||
) -> Result<(StatusCode, Json<CreatedField>), StatusCode> {
|
||
let vocabulary_id = match req.vocabulary_id.as_deref() {
|
||
None | Some("") => None,
|
||
Some(s) => Some(s.parse::<VocabularyId>().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<AuthorityKind>`). `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 <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
|
||
}
|
||
|
||
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 (
|
||
<div className="space-y-2 p-3">
|
||
{Array.from({ length: 6 }).map((_, i) => (
|
||
<Skeleton key={i} className="h-9 w-full" />
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
if (isError) return <p className="p-4 text-sm text-red-600">{t("fields.loadError")}</p>;
|
||
if (!data || data.length === 0)
|
||
return <p className="p-4 text-sm text-neutral-500">{t("fields.empty")}</p>;
|
||
|
||
// Group by `group`; ungrouped (null/empty) collected under the "Other" heading.
|
||
const groups = new Map<string, FieldDefinitionView[]>();
|
||
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 (
|
||
<ul className="overflow-auto">
|
||
{[...groups.entries()].map(([group, defs]) => (
|
||
<li key={group}>
|
||
<div className="border-b bg-neutral-50 px-3 py-1 text-xs font-medium uppercase tracking-wide text-neutral-500">
|
||
{group}
|
||
</div>
|
||
<ul>
|
||
{defs.map((def) => (
|
||
<li key={def.key} className="flex items-center gap-2 border-b px-3 py-2 text-sm">
|
||
<span className="font-medium">{labelText(def.labels, lang)}</span>
|
||
<span className="text-xs text-neutral-400">{def.key}</span>
|
||
<span className="rounded bg-neutral-100 px-1.5 py-0.5 text-xs text-neutral-600">
|
||
{t(`fields.types.${def.data_type}`)}
|
||
</span>
|
||
{def.required && <span className="text-xs text-red-600">*</span>}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 3: Implement `FieldForm`** — create `web/src/fields/field-form.tsx`. Native `<select>`s (matches `web/src/objects/field-input.tsx`). Reuses `LabelEditor` (sv/en, EN-required) and `useVocabularies`.
|
||
|
||
```tsx
|
||
import { useState, type FormEvent } from "react";
|
||
import { useTranslation } from "react-i18next";
|
||
|
||
import type { components } from "../api/schema";
|
||
import { useCreateFieldDefinition, useVocabularies } from "../api/queries";
|
||
import { LabelEditor } from "../components/label-editor";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Label } from "@/components/ui/label";
|
||
import { Checkbox } from "@/components/ui/checkbox";
|
||
|
||
type LabelInput = components["schemas"]["LabelInput"];
|
||
|
||
const TYPES = ["text", "localized_text", "integer", "date", "boolean", "term", "authority"] as const;
|
||
const KINDS = ["person", "organisation", "place"] as const;
|
||
|
||
export function FieldForm() {
|
||
const { t } = useTranslation();
|
||
const create = useCreateFieldDefinition();
|
||
const { data: vocabularies } = useVocabularies();
|
||
|
||
const [key, setKey] = useState("");
|
||
const [labels, setLabels] = useState<LabelInput[]>([]);
|
||
const [dataType, setDataType] = useState<string>("text");
|
||
const [vocabularyId, setVocabularyId] = useState("");
|
||
const [authorityKind, setAuthorityKind] = useState(""); // "" == any
|
||
const [group, setGroup] = useState("");
|
||
const [required, setRequired] = useState(false);
|
||
const [error, setError] = useState(false);
|
||
|
||
const reset = () => {
|
||
setKey("");
|
||
setLabels([]);
|
||
setDataType("text");
|
||
setVocabularyId("");
|
||
setAuthorityKind("");
|
||
setGroup("");
|
||
setRequired(false);
|
||
};
|
||
|
||
const onSubmit = (event: FormEvent) => {
|
||
event.preventDefault();
|
||
|
||
const hasEn = labels.some((l) => l.lang === "en" && l.label);
|
||
const termNeedsVocab = dataType === "term" && !vocabularyId;
|
||
|
||
if (!key.trim() || !hasEn || termNeedsVocab) {
|
||
setError(true);
|
||
return;
|
||
}
|
||
|
||
setError(false);
|
||
create.mutate(
|
||
{
|
||
key: key.trim(),
|
||
data_type: dataType,
|
||
vocabulary_id: dataType === "term" ? vocabularyId : null,
|
||
authority_kind: dataType === "authority" ? authorityKind || null : null,
|
||
required,
|
||
group: group.trim() || null,
|
||
labels,
|
||
},
|
||
{ onSuccess: reset },
|
||
);
|
||
};
|
||
|
||
return (
|
||
<form onSubmit={onSubmit} className="space-y-3 overflow-auto p-4">
|
||
<div className="text-sm font-medium">{t("fields.newField")}</div>
|
||
|
||
<div className="space-y-1">
|
||
<Label htmlFor="field-key">{t("fields.key")}</Label>
|
||
<Input id="field-key" value={key} onChange={(e) => setKey(e.target.value)} />
|
||
</div>
|
||
|
||
<LabelEditor value={labels} onChange={setLabels} />
|
||
|
||
<div className="space-y-1">
|
||
<Label htmlFor="field-type">{t("fields.type")}</Label>
|
||
<select
|
||
id="field-type"
|
||
value={dataType}
|
||
onChange={(e) => setDataType(e.target.value)}
|
||
className="w-full rounded border px-2 py-1 text-sm"
|
||
>
|
||
{TYPES.map((type) => (
|
||
<option key={type} value={type}>
|
||
{t(`fields.types.${type}`)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
|
||
{dataType === "term" && (
|
||
<div className="space-y-1">
|
||
<Label htmlFor="field-vocab">{t("fields.vocabulary")}</Label>
|
||
<select
|
||
id="field-vocab"
|
||
value={vocabularyId}
|
||
onChange={(e) => setVocabularyId(e.target.value)}
|
||
className="w-full rounded border px-2 py-1 text-sm"
|
||
>
|
||
<option value="">{t("form.selectPlaceholder")}</option>
|
||
{vocabularies?.map((vocab) => (
|
||
<option key={vocab.id} value={vocab.id}>
|
||
{vocab.key}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
)}
|
||
|
||
{dataType === "authority" && (
|
||
<div className="space-y-1">
|
||
<Label htmlFor="field-kind">{t("fields.authorityKind")}</Label>
|
||
<select
|
||
id="field-kind"
|
||
value={authorityKind}
|
||
onChange={(e) => setAuthorityKind(e.target.value)}
|
||
className="w-full rounded border px-2 py-1 text-sm"
|
||
>
|
||
<option value="">{t("fields.anyKind")}</option>
|
||
{KINDS.map((kind) => (
|
||
<option key={kind} value={kind}>
|
||
{t(`authorities.${kind}`)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
)}
|
||
|
||
<div className="space-y-1">
|
||
<Label htmlFor="field-group">{t("fields.group")}</Label>
|
||
<Input id="field-group" value={group} onChange={(e) => setGroup(e.target.value)} />
|
||
</div>
|
||
|
||
<label className="flex items-center gap-2 text-sm">
|
||
<Checkbox checked={required} onCheckedChange={(checked) => setRequired(checked === true)} />
|
||
{t("fields.required")}
|
||
</label>
|
||
|
||
{error && <p role="alert" className="text-xs text-red-600">{t("form.required")}</p>}
|
||
{create.isError && <p role="alert" className="text-xs text-red-600">{t("form.rejected")}</p>}
|
||
|
||
<Button type="submit" size="sm" disabled={create.isPending}>
|
||
{t("fields.create")}
|
||
</Button>
|
||
</form>
|
||
);
|
||
}
|
||
```
|
||
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 `<Checkbox>` 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 (
|
||
<div className="grid h-full grid-cols-[20rem_1fr]">
|
||
<div className="overflow-hidden border-r">
|
||
<FieldList />
|
||
</div>
|
||
<div className="overflow-hidden">
|
||
<FieldForm />
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 5: Wire the route** — in `web/src/app.tsx`, import `import { FieldsPage } from "./fields/fields-page";` and add inside the `<AppShell>` group:
|
||
```tsx
|
||
<Route path="/fields" element={<FieldsPage />} />
|
||
```
|
||
|
||
- [ ] **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
|
||
<NavLink
|
||
to="/fields"
|
||
className={({ isActive }) =>
|
||
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
|
||
}
|
||
>
|
||
{t("nav.fields")}
|
||
</NavLink>
|
||
```
|
||
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 (
|
||
<Routes>
|
||
<Route path="/fields" element={<FieldsPage />} />
|
||
</Routes>
|
||
);
|
||
}
|
||
|
||
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" `<Label htmlFor="field-key">`; if not, scope with the field id. The `vocabularies` fixture is the existing one (`v-material`/`material`, `v-technique`/`technique`).
|
||
|
||
- [ ] **Step 8: Update the app-shell test** — open `web/src/shell/app-shell.test.tsx`. It currently asserts `fields` (and/or `search`) is a disabled button. Update so **Fields is now a link** (`getByRole("link", { name: /fields/i })`); there are no disabled nav buttons left — if a test asserted a disabled button exists, remove/replace that assertion. Run `pnpm test src/shell/app-shell.test.tsx` → PASS.
|
||
|
||
- [ ] **Step 9: Full verify** — `pnpm test && pnpm typecheck && pnpm lint && pnpm build && pnpm check:size`. Report the bundle gz number. If `check:size` > 150 KB gz, lazy-load `/fields` in `app.tsx` (mirror the `ObjectNewPage` lazy pattern: `const FieldsPage = lazy(() => import("./fields/fields-page").then((m) => ({ default: m.FieldsPage })))` + wrap the route element in `<Suspense fallback={<FormFallback />}>`), then re-run check:size.
|
||
|
||
- [ ] **Step 10: Commit** —
|
||
|
||
```bash
|
||
cd /Users/olsson/Laboratory/biggus-dickus
|
||
git add web
|
||
git commit -m "feat(web): /fields two-pane screen (grouped list + create form) + nav (no stubs left)"
|
||
```
|
||
|
||
---
|
||
|
||
## Task 4: i18n parity + full verification
|
||
|
||
**Files:** none expected (verification); fix-ups only if a check fails.
|
||
|
||
- [ ] **Step 1: i18n parity** —
|
||
|
||
```bash
|
||
cd web
|
||
node -e "const a=require('./src/i18n/en.json'),b=require('./src/i18n/sv.json');const k=o=>Object.entries(o).flatMap(([K,v])=>typeof v==='object'?k(v).map(s=>K+'.'+s):[K]);const ka=k(a).sort(),kb=k(b).sort();console.log(JSON.stringify(ka)===JSON.stringify(kb)?'PARITY OK':'MISMATCH '+JSON.stringify({onlyEn:ka.filter(x=>!kb.includes(x)),onlySv:kb.filter(x=>!ka.includes(x))}))"
|
||
```
|
||
Expected `PARITY OK`; fix any mismatch.
|
||
|
||
- [ ] **Step 2: Full frontend verification** —
|
||
```bash
|
||
cd web
|
||
pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size
|
||
```
|
||
Expected clean; all tests pass; bundle ≤150 KB gz (report the number).
|
||
|
||
- [ ] **Step 3: Full backend verification** —
|
||
```bash
|
||
cd /Users/olsson/Laboratory/biggus-dickus
|
||
DATABASE_URL=postgres://postgres:postgres@localhost:5433/cms_dev \
|
||
MEILI_URL=http://localhost:7701 MEILI_MASTER_KEY=masterKey \
|
||
cargo test -p api
|
||
cargo clippy --workspace --all-targets
|
||
cargo +nightly fmt --check
|
||
```
|
||
Expected: all pass; clippy clean; fmt clean.
|
||
|
||
- [ ] **Step 4: Commit** — only if Steps 1–2 required a fix:
|
||
```bash
|
||
git add web
|
||
git commit -m "chore(web): fields management verification fix-ups"
|
||
```
|
||
|
||
---
|
||
|
||
## Self-Review (completed)
|
||
|
||
**Spec coverage:**
|
||
- `POST /api/admin/field-definitions`, `EditCatalogue`, `from_parts` validation (422), dup key (409), malformed binding (400), auth → Task 1. ✓
|
||
- OpenAPI registration + regenerated client → Task 1. ✓
|
||
- `useCreateFieldDefinition` invalidating `["field-definitions"]` (shared with M2 editor) → Task 2. ✓
|
||
- Two-pane `/fields`: grouped list (+ "Other"), create form with conditional vocabulary/kind, native selects, LabelEditor reuse, EN-required + term-needs-vocab client validation, `form.rejected` on backend error → Task 3. ✓
|
||
- Nav enabled, `DISABLED_NAV = []` (no stubs) → Task 3. ✓
|
||
- i18n sv/en parity, bundle ≤150 KB, full backend+frontend verification → Task 4. ✓
|
||
- Create + list only (no edit/delete) — respected. ✓
|
||
|
||
**Placeholder scan:** none — every code step is complete; the two "confirm the Checkbox API / Label export" notes are concrete verification instructions against named files.
|
||
|
||
**Type consistency:** `NewFieldDefinitionRequest`/`CreatedField` (api) ↔ `components["schemas"]["NewFieldDefinitionRequest"]` (web `useCreateFieldDefinition` arg) consistent; `FieldDefinitionView` reused for the list; `data_type` string values (`text|localized_text|integer|date|boolean|term|authority`) match the `TYPES` tuple and the `fields.types.*` i18n keys; the `["field-definitions"]` query key matches `useFieldDefinitions`; `AuthorityKind::from_db`, `FieldType::from_parts`, `db::fields::create_field_definition(&mut tx, &new)`, and `VocabularyId` parse usage all match the confirmed backend signatures.
|
||
|
||
## Notes for follow-on
|
||
- Edit/delete field definitions — needs new `db::fields` update/delete + a referential-integrity policy (block/handle deleting a field objects reference or that is required). File a backend follow-up when this lands.
|
||
- Per-field validation rules (min/max/regex) — #11. Field/group reordering and renaming. Immutable `key`/`type` after creation.
|