Compare commits

...

9 Commits

Author SHA1 Message Date
logaritmisk 126f84962a merge: fields management — create field definitions (endpoint + /fields UI)
CI / web (push) Has been cancelled
POST /api/admin/field-definitions (EditCatalogue) over the existing db layer,
validated through FieldType::from_parts (422 on inconsistent type/binding),
dup key -> 409, nonexistent vocabulary / empty key -> 422. /fields two-pane
screen: grouped list + create form with conditional vocabulary/authority-kind
selects, reused LabelEditor; creating a field invalidates the shared
[field-definitions] cache so it appears in the object editor too. Fields nav
enabled — no disabled nav stubs remain.

api tests green (8 admin_fields + suite); web 72 tests; bundle 145.4 KB gz.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:36:14 +02:00
logaritmisk daad9438ba fix(api): map CHECK-constraint violation (empty key) to 422 2026-06-04 14:35:56 +02:00
logaritmisk fd1c22191b polish(web): fields form resets error, shared labelText, drop dead nav.soon, a11y required marker, Other group last
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 14:29:25 +02:00
logaritmisk 37c80121ed feat(web): /fields two-pane screen (grouped list + create form) + nav (no stubs left)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 14:22:57 +02:00
logaritmisk 6ad1304efd feat(web): useCreateFieldDefinition mutation + MSW handler
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 14:16:55 +02:00
logaritmisk df8f31d14d fix(api): map nonexistent-vocabulary FK violation to 422; cover term/authority create paths
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 14:15:19 +02:00
logaritmisk b508273a52 feat(api): POST /api/admin/field-definitions (create field definition)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 14:09:08 +02:00
logaritmisk b490db13b1 docs(plans): fields management — POST endpoint + /fields UI, 4 tasks
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:50:30 +02:00
logaritmisk 19408f6282 docs(specs): fields management — POST field-definitions + /fields two-pane UI
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:35:18 +02:00
18 changed files with 2048 additions and 20 deletions
+107 -3
View File
@@ -9,11 +9,15 @@ use axum::{
response::IntoResponse,
routing::{get, put},
};
use domain::{AuditActor, CatalogueObject, ObjectId, ObjectInput, Visibility};
use domain::{
AuditActor, AuthorityKind, CatalogueObject, FieldType, LocalizedLabel, NewFieldDefinition,
ObjectId, ObjectInput, Visibility, VocabularyId,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{AppState, pagination::Pagination, reindex};
use crate::{AppState, admin_vocab::LabelInput, pagination::Pagination, reindex};
/// A localized label `{ lang, label }` (shared across admin views).
#[derive(Serialize, ToSchema)]
@@ -364,6 +368,23 @@ pub(crate) struct FieldDefinitionView {
pub labels: Vec<LabelView>,
}
#[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,
}
/// List all field definitions. Requires `ViewInternal`.
#[utoipa::path(
get, path = "/api/admin/field-definitions",
@@ -407,6 +428,86 @@ pub(crate) async fn list_field_definitions(
))
}
/// 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 })))
}
Err(err) => {
match err.as_database_error().and_then(|e| e.code()).as_deref() {
// Duplicate `key` violates the unique index.
Some("23505") => Err(StatusCode::CONFLICT),
// Referenced vocabulary doesn't exist — client error, not server fault.
Some("23503") => Err(StatusCode::UNPROCESSABLE_ENTITY),
// CHECK constraint violated (e.g. empty key) — client error.
Some("23514") => Err(StatusCode::UNPROCESSABLE_ENTITY),
_ => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
}
}
/// Replace an object's flexible-field values (validated against the registry).
///
/// **Replace semantics:** the body is the *complete* desired field set. Omitting a key
@@ -470,5 +571,8 @@ pub(crate) fn routes() -> Router<AppState> {
get(get_object).put(update_object).delete(delete_object),
)
.route("/api/admin/objects/{id}/fields", put(set_fields))
.route("/api/admin/field-definitions", get(list_field_definitions))
.route(
"/api/admin/field-definitions",
get(list_field_definitions).post(create_field_definition),
)
}
+3
View File
@@ -23,6 +23,7 @@ use crate::{
admin_objects::update_object,
admin_objects::delete_object,
admin_objects::list_field_definitions,
admin_objects::create_field_definition,
admin_objects::set_fields,
admin_vocab::list_vocabularies,
admin_vocab::create_vocabulary,
@@ -47,6 +48,8 @@ use crate::{
admin_objects::ObjectUpdateRequest,
admin_objects::CreatedObject,
admin_objects::FieldDefinitionView,
admin_objects::NewFieldDefinitionRequest,
admin_objects::CreatedField,
admin_vocab::VocabularyView,
admin_vocab::NewVocabularyRequest,
admin_vocab::NewTermRequest,
+307
View File
@@ -0,0 +1,307 @@
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;
async fn post_json(
app: &axum::Router,
cookie: &str,
uri: &str,
body: &str,
) -> axum::http::Response<Body> {
app.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.header(header::COOKIE, cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body.to_owned()))
.unwrap(),
)
.await
.unwrap()
}
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> {
post_json(app, cookie, "/api/admin/field-definitions", body).await
}
#[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");
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
);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn create_term_field_with_valid_vocabulary(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 vocab_resp = post_json(
&app,
&cookie,
"/api/admin/vocabularies",
r#"{"key":"material"}"#,
)
.await;
assert_eq!(vocab_resp.status(), StatusCode::CREATED);
let vocab_body: serde_json::Value =
serde_json::from_slice(&vocab_resp.into_body().collect().await.unwrap().to_bytes())
.unwrap();
let vocab_id = vocab_body["id"].as_str().unwrap();
let resp = post_field(
&app,
&cookie,
&format!(
r#"{{"key":"material_ref","data_type":"term","vocabulary_id":"{vocab_id}","required":false,"labels":[{{"lang":"en","label":"Material"}}]}}"#
),
)
.await;
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn term_with_nonexistent_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":"bad_ref","data_type":"term","vocabulary_id":"00000000-0000-0000-0000-000000000000","required":false,"labels":[{"lang":"en","label":"Bad"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn create_authority_field(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":"maker_ref","data_type":"authority","authority_kind":"person","required":false,"labels":[{"lang":"en","label":"Maker"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn empty_key_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":"","data_type":"text","required":false,"labels":[{"lang":"en","label":"X"}]}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
@@ -0,0 +1,922 @@
# 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 12 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.
@@ -0,0 +1,196 @@
# Fields Management — Design
**Date:** 2026-06-04
**Status:** Approved (brainstorming) — ready for implementation planning.
## Context
Milestones 15 (merged to `main` at `2d0b76a`) delivered the SPA foundation, object
authoring, publishing, vocabulary/authority management, and search. The app shell has
**one disabled nav stub left: Fields.** This milestone enables it — managing the
*flexible field definitions* that form the catalogue's extensible schema (the fields the
M2 object authoring form renders beyond the fixed core columns).
Like Search (M5), this is **not** a pure-frontend milestone. `GET /api/admin/field-definitions`
exists (read-only), and the db layer has `db::fields::create_field_definition`, but there
is **no HTTP write route**. So Fields is a combined backend + frontend slice.
After this milestone, **every nav item is live** — zero stubs.
## Decisions (settled during brainstorming)
- **Combined backend + frontend, create + list only.** Expose `POST /api/admin/field-definitions`
over the existing `db::fields::create_field_definition`; build the list + create UI.
New field definitions are purely additive (they only add optional schema), so create is
safe and useful standalone. **Edit/delete is deferred** — it needs new db functions and a
referential-integrity policy (a field definition drives existing object data; the same
concern as issue #30). File a follow-up when this lands.
- **Two-pane layout** (consistent with Objects/Vocabularies): grouped list of existing
definitions on the left, a persistent create form on the right. No per-item detail view
or `:id` route (definitions are create+list only and identified by `key`).
- **Create endpoint capability = `EditCatalogue`** (matches other catalogue writes; the
existing GET uses `ViewInternal`).
- **Ungrouped fields** render under a localized "Other" heading.
## Backend contract (to build)
### Domain (already present — reuse, no change)
`FieldType` (`crates/domain/src/field_definition.rs`) is a discriminated union:
`Text | LocalizedText | Integer | Date | Boolean | Term { vocabulary_id } | Authority { kind: Option<AuthorityKind> }`.
- `FieldType::from_parts(data_type: &str, vocabulary_id: Option<VocabularyId>, authority_kind: Option<AuthorityKind>) -> Option<FieldType>`
reconstructs the type from the three stored columns and **returns `None` for any
inconsistent combination** — a scalar carrying a binding, a `term` without a vocabulary
(or with an authority kind), an `authority` carrying a vocabulary. This is the single
validation chokepoint the handler reuses.
- `NewFieldDefinition { key, field_type, required, group_key: Option<String>, labels: Vec<LocalizedLabel> }`.
- `db::fields::create_field_definition(conn: &mut PgConnection, new: &NewFieldDefinition) -> Result<FieldDefinitionId, sqlx::Error>`
(multi-statement — must be passed a transaction connection `&mut *tx`).
### `api` crate — new write handler
`POST /api/admin/field-definitions`, capability **`EditCatalogue`**. Request body:
```
NewFieldDefinitionRequest {
key: String,
data_type: String, // text|localized_text|integer|date|boolean|term|authority
vocabulary_id: Option<String>, // required iff data_type == "term"
authority_kind: Option<String>, // person|organisation|place; only for "authority" (optional)
required: bool,
group: Option<String>,
labels: Vec<LabelInput>, // { lang, label } — reuse the existing LabelInput schema
}
```
Handler logic:
1. Parse `vocabulary_id` (if present) to `VocabularyId` (→ 400 on malformed UUID) and
`authority_kind` (if present) to `AuthorityKind` by matching `person|organisation|place`
(→ 400 otherwise).
2. `FieldType::from_parts(&data_type, vocabulary_id, authority_kind)``None`**422**
(covers "term without vocabulary", "authority with vocabulary", unknown type, stray
binding on a scalar — all in one check).
3. Build `NewFieldDefinition`, run `create_field_definition` inside a transaction, commit.
4. On a unique-violation (duplicate `key`, Postgres SQLSTATE 23505) ⇒ **409**; other db
errors ⇒ 500.
5. Return **`201 { key }`** (a small `CreatedField { key }` view).
Register in `crates/api/src/openapi.rs` (path + the `NewFieldDefinitionRequest` and
`CreatedField` schemas). The route is added to the admin router (likely a new
`crates/api/src/admin_fields.rs`, or alongside the existing field-definition GET in
`admin_objects.rs` — implementer's call, following the module that already owns
`list_field_definitions`).
### Typed client
Regenerate `web/src/api/schema.d.ts` (run the server against the test infra +
`pnpm gen:api`) so the path, `NewFieldDefinitionRequest`, and `CreatedField` appear.
## Frontend architecture
### Routes & navigation
```
/fields → FieldsPage (FieldList left, FieldForm right) — no nested :id route
```
Added under the protected `AppShell`. In `app-shell.tsx`, **Fields** becomes the last
active `NavLink`; `DISABLED_NAV` becomes empty (the disabled-button block renders nothing
/ is removed). All nav items are now live.
### Components / files
```
web/src/fields/
fields-page.tsx two-pane grid (FieldList left, FieldForm right)
field-list.tsx useFieldDefinitions, grouped by `group` (ungrouped → "Other"); rows
show localized label + key + data_type badge + required marker; with
loading / empty / error states
field-form.tsx the create form (key, LabelEditor sv/en, type Select, conditional
Vocabulary/authority-kind, group, required) → useCreateFieldDefinition
web/src/api/queries.ts + useCreateFieldDefinition (POST; invalidates ["field-definitions"])
web/src/app.tsx + the /fields route
web/src/shell/app-shell.tsx enable Fields NavLink; DISABLED_NAV = []
web/src/i18n/{en,sv}.json + fields.* namespace
```
### `FieldForm` — the discriminated-union create form
- `key` — text Input (machine identifier).
- Labels — the **shared `LabelEditor`** (sv/en; EN required), reused from M4.
- `type` — Select over the 7 data types.
- **Conditional:** when type=`term`, reveal a **Vocabulary** Select populated from
`useVocabularies` (reused); when type=`authority`, reveal an **authority-kind** Select
(Any / Person / Organisation / Place). All other types show no extra config.
- `group` — optional text Input.
- `required` — Checkbox.
- Submit → `useCreateFieldDefinition` → on success invalidate `["field-definitions"]` and
clear the form.
### Data layer
`useCreateFieldDefinition()``POST /api/admin/field-definitions` with the request body;
invalidates `["field-definitions"]`. `useFieldDefinitions()` and `useVocabularies()`
already exist and are reused.
## Data flow
`useFieldDefinitions` is the **same cached query the M2 object authoring form consumes**.
Creating a field definition and invalidating `["field-definitions"]` makes the new field
appear both in the Fields list **and** immediately as an available field in the object
editor. That shared-cache effect is the milestone's main payoff.
## Validation & error handling
- **Client:** `key` non-empty (trimmed); EN label required (the `LabelEditor` guard);
if type=`term`, a vocabulary must be chosen — all block submit with inline messages.
- **Backend (source of truth):** key uniqueness (409) and type/binding consistency (422),
surfaced as a form-level `form.rejected` alert.
- The list has loading / empty / error states (reuse the M1 list-state patterns).
## Testing
### Backend (`crates/api/tests/`)
- POST creates a scalar field (e.g. `integer`) → 201; a `term` field with a valid
`vocabulary_id` → 201; `term` without `vocabulary_id` → 422; duplicate `key` → 409;
unauthenticated → 401. (Mirror the existing admin test harness — seed an editor, login,
oneshot requests.)
### Frontend (Vitest + RTL + MSW, `onUnhandledRequest:"error"`)
- New MSW handler `POST /api/admin/field-definitions` (+ a `fieldDefinitions` GET fixture
with at least one grouped and one ungrouped entry).
- Tests: list renders, grouped (incl. the "Other" group); creating a `text` field posts
the expected body and clears the form; selecting **Term** reveals the vocabulary picker
and blocks submit until one is chosen; the EN-required guard blocks submit; create
invalidates `["field-definitions"]`; the Fields nav item is an enabled link (and no
disabled nav buttons remain).
### Project constraints
- en/sv i18n key parity (authority-kind labels reuse existing `authorities.*`).
- No `any` / `eslint-disable` / `@ts-ignore`. Codename ban.
- Bundle ≤150 KB gz (current headroom ~5 KB; lazy-load `/fields` with `React.lazy` +
`Suspense` — as M2 did for the object forms — if it pushes over, then re-verify).
## Acceptance criteria
1. `POST /api/admin/field-definitions` creates definitions of all representative types,
reuses `FieldType::from_parts` for consistency validation (term/authority), is
`EditCatalogue`-gated, returns 409 on duplicate key and 422 on inconsistent type/config.
2. The Fields nav item is enabled and routes to `/fields`; the grouped list renders; the
create form shows the conditional type config (vocabulary for term, kind for authority).
3. A newly created field appears in the Fields list **and** in the M2 object authoring
form (shared `["field-definitions"]` invalidation).
4. EN-required and term-needs-vocabulary client validation; backend 409/422 surfaced as a
form-level error.
5. Web + backend CI green (cargo test; web typecheck/lint/test/build, bundle ≤150 KB gz);
en/sv parity.
6. After this milestone, the app shell has **no disabled nav stubs**.
## Out of scope / follow-ups
- **Edit/delete field definitions** — needs new `db::fields` update/delete functions and a
referential-integrity policy (block/handle deleting a field that objects reference, or
that is `required`). File a backend follow-up when this milestone lands.
- Per-field validation rules (min/max, length, regex) — already tracked as **#11**.
- Field reordering and group management (renaming/reordering groups).
- Changing a field's `key` or `type` after creation (immutable for now).
+40
View File
@@ -0,0 +1,40 @@
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 }).key).toBe("technique");
expect((body as { data_type: string }).data_type).toBe("term");
});
+17
View File
@@ -315,6 +315,23 @@ export function useSearch(q: string, visibility: string | null) {
});
}
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"] }),
});
}
type Visibility = "draft" | "internal" | "public";
/** Error carrying the HTTP status so callers can branch 422-gate vs 409-illegal. */
+75 -1
View File
@@ -30,7 +30,12 @@ export interface paths {
/** List all field definitions. Requires `ViewInternal`. */
get: operations["list_field_definitions"];
put?: never;
post?: never;
/**
* 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.
*/
post: operations["create_field_definition"];
delete?: never;
options?: never;
head?: never;
@@ -339,6 +344,9 @@ export interface components {
kind: string;
labels: components["schemas"]["LabelView"][];
};
CreatedField: {
key: string;
};
CreatedId: {
id: string;
};
@@ -382,6 +390,16 @@ export interface components {
kind: string;
labels: components["schemas"]["LabelInput"][];
};
NewFieldDefinitionRequest: {
authority_kind?: string | null;
/** @description text | localized_text | integer | date | boolean | term | authority */
data_type: string;
group?: string | null;
key: string;
labels: components["schemas"]["LabelInput"][];
required: boolean;
vocabulary_id?: string | null;
};
NewTermRequest: {
external_uri?: string | null;
labels: components["schemas"]["LabelInput"][];
@@ -599,6 +617,62 @@ export interface operations {
};
};
};
create_field_definition: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["NewFieldDefinitionRequest"];
};
};
responses: {
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["CreatedField"];
};
};
/** @description Malformed vocabulary_id or authority_kind */
400: {
headers: {
[name: string]: unknown;
};
content?: never;
};
401: {
headers: {
[name: string]: unknown;
};
content?: never;
};
403: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Duplicate key */
409: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Inconsistent type/binding */
422: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
login: {
parameters: {
query?: never;
+12
View File
@@ -22,6 +22,10 @@ const ObjectEditForm = lazy(() =>
import("./objects/object-edit-form").then((m) => ({ default: m.ObjectEditForm })),
);
const FieldsPage = lazy(() =>
import("./fields/fields-page").then((m) => ({ default: m.FieldsPage })),
);
function FormFallback() {
return <div role="status" className="p-4 text-sm text-neutral-400">Loading</div>;
}
@@ -63,6 +67,14 @@ export function App() {
</Route>
<Route path="/authorities" element={<Navigate to="/authorities/person" replace />} />
<Route path="/authorities/:kind" element={<AuthoritiesPage />} />
<Route
path="/fields"
element={
<Suspense fallback={<FormFallback />}>
<FieldsPage />
</Suspense>
}
/>
<Route path="/" element={<Navigate to="/objects" replace />} />
</Route>
</Route>
+159
View File
@@ -0,0 +1,159 @@
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("");
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);
setError(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>
);
}
+75
View File
@@ -0,0 +1,75 @@
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useFieldDefinitions } from "../api/queries";
import { labelText } from "../lib/labels";
import { Skeleton } from "@/components/ui/skeleton";
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
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>;
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);
}
const otherLabel = t("fields.other");
const entries = [...groups.entries()].sort((a, b) =>
a[0] === otherLabel ? 1 : b[0] === otherLabel ? -1 : 0,
);
return (
<ul className="overflow-auto">
{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"
title={t("fields.required")}
aria-label={t("fields.required")}
>
*
</span>
)}
</li>
))}
</ul>
</li>
))}
</ul>
);
}
+15
View File
@@ -0,0 +1,15 @@
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>
);
}
+72
View File
@@ -0,0 +1,72 @@
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" });
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");
const vocab = await screen.findByLabelText(/^vocabulary$/i);
expect(vocab).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: /create field/i }));
expect(await screen.findByRole("alert")).toBeInTheDocument();
expect(posted).toBe(false);
await userEvent.selectOptions(vocab, "v-material");
await userEvent.click(screen.getByRole("button", { name: /create field/i }));
await waitFor(() => expect(posted).toBe(true));
});
+17 -1
View File
@@ -1,6 +1,6 @@
{
"app": { "name": "Collection" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "soon": "Coming soon" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search" },
"auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" },
"objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object" },
"fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" },
@@ -29,6 +29,22 @@
"resultCount_other": "{{count}} results",
"selectPrompt": "Select a result to see the full record"
},
"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" }
},
"publish": {
"heading": "Visibility",
"advanceInternal": "Advance to internal",
+17 -1
View File
@@ -1,6 +1,6 @@
{
"app": { "name": "Samling" },
"nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "soon": "Kommer snart" },
"nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök" },
"auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" },
"objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål" },
"fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" },
@@ -29,6 +29,22 @@
"resultCount_other": "{{count}} träffar",
"selectPrompt": "Välj en träff för att se hela posten"
},
"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" }
},
"publish": {
"heading": "Synlighet",
"advanceInternal": "Gör intern",
+2 -2
View File
@@ -29,9 +29,9 @@ test("shows active and disabled nav and renders the outlet", async () => {
renderApp(tree(), { route: "/objects" });
expect(await screen.findByText("objects outlet")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /objects/i })).toBeInTheDocument();
// fields is still disabled; search is now a link
// fields and search are now links
expect(screen.getByRole("link", { name: /search/i })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /fields/i })).toBeDisabled();
expect(screen.getByRole("link", { name: /fields/i })).toBeInTheDocument();
});
test("language switch toggles to Swedish", async () => {
+7 -11
View File
@@ -5,8 +5,6 @@ import { useLogout } from "../api/queries";
import { Button } from "@/components/ui/button";
import { LangSwitch } from "./lang-switch";
const DISABLED_NAV = ["fields"] as const;
export function AppShell() {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -54,16 +52,14 @@ export function AppShell() {
>
{t("nav.search")}
</NavLink>
{DISABLED_NAV.map((key) => (
<button
key={key}
disabled
title={t("nav.soon")}
className="block w-full cursor-not-allowed rounded px-2 py-1 text-left text-neutral-400"
<NavLink
to="/fields"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t(`nav.${key}`)}
</button>
))}
{t("nav.fields")}
</NavLink>
</nav>
</aside>
<div className="flex flex-1 flex-col">
+4
View File
@@ -68,4 +68,8 @@ export const handlers = [
http.post("/api/admin/logout", () => new HttpResponse(null, { status: 204 })),
http.post("/api/admin/objects/:id/visibility", () => new HttpResponse(null, { status: 204 })),
http.post("/api/admin/field-definitions", () =>
HttpResponse.json({ key: "new_field" }, { status: 201 }),
),
];