From b508273a52fda9d2b9a19d2451c0b9351c716851 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:09:08 +0200 Subject: [PATCH 1/6] feat(api): POST /api/admin/field-definitions (create field definition) Co-Authored-By: Claude Sonnet 4.6 --- crates/api/src/admin_objects.rs | 103 +++++++++++++++- crates/api/src/openapi.rs | 3 + crates/api/tests/admin_fields.rs | 196 +++++++++++++++++++++++++++++++ web/src/api/schema.d.ts | 76 +++++++++++- 4 files changed, 374 insertions(+), 4 deletions(-) create mode 100644 crates/api/tests/admin_fields.rs diff --git a/crates/api/src/admin_objects.rs b/crates/api/src/admin_objects.rs index fa9d2a2..ce0b302 100644 --- a/crates/api/src/admin_objects.rs +++ b/crates/api/src/admin_objects.rs @@ -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, } +#[derive(serde::Deserialize, utoipa::ToSchema)] +pub(crate) struct NewFieldDefinitionRequest { + pub key: String, + /// text | localized_text | integer | date | boolean | term | authority + pub data_type: String, + pub vocabulary_id: Option, + pub authority_kind: Option, + pub required: bool, + pub group: Option, + pub labels: Vec, +} + +#[derive(serde::Serialize, utoipa::ToSchema)] +pub(crate) struct CreatedField { + pub key: String, +} + /// List all field definitions. Requires `ViewInternal`. #[utoipa::path( get, path = "/api/admin/field-definitions", @@ -407,6 +428,79 @@ 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, + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json), StatusCode> { + let vocabulary_id = match req.vocabulary_id.as_deref() { + None | Some("") => None, + Some(s) => Some( + s.parse::() + .map_err(|_| StatusCode::BAD_REQUEST)?, + ), + }; + + let authority_kind = match req.authority_kind.as_deref() { + None | Some("") => None, + Some(s) => Some(AuthorityKind::from_db(s).ok_or(StatusCode::BAD_REQUEST)?), + }; + + let field_type = FieldType::from_parts(&req.data_type, vocabulary_id, authority_kind) + .ok_or(StatusCode::UNPROCESSABLE_ENTITY)?; + + let new = NewFieldDefinition { + key: req.key, + field_type, + required: req.required, + group_key: req.group, + labels: req + .labels + .into_iter() + .map(|l| LocalizedLabel { + lang: l.lang, + label: l.label, + }) + .collect(), + }; + + let mut tx = state + .db + .pool() + .begin() + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + match db::fields::create_field_definition(&mut tx, &new).await { + Ok(_) => { + tx.commit() + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok((StatusCode::CREATED, Json(CreatedField { key: new.key }))) + } + 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), + } +} + /// 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 +564,8 @@ pub(crate) fn routes() -> Router { 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), + ) } diff --git a/crates/api/src/openapi.rs b/crates/api/src/openapi.rs index 7d08eae..e40d9ba 100644 --- a/crates/api/src/openapi.rs +++ b/crates/api/src/openapi.rs @@ -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, diff --git a/crates/api/tests/admin_fields.rs b/crates/api/tests/admin_fields.rs new file mode 100644 index 0000000..e7675a1 --- /dev/null +++ b/crates/api/tests/admin_fields.rs @@ -0,0 +1,196 @@ +use api::{AppState, build_app, migrate_sessions}; +use axum::body::Body; +use axum::http::{Request, StatusCode, header}; +use db::users; +use domain::{AuditActor, Email, NewUser, Role}; +use http_body_util::BodyExt; +use sqlx::PgPool; +use tower::ServiceExt; + +fn state(pool: PgPool) -> AppState { + AppState { + db: db::Db::from_pool(pool), + app_name: "Test".into(), + cookie_secure: false, + search: None, + } +} + +async fn seed_user(pool: &PgPool, email: &str, password: &str, role: Role) { + let db = db::Db::from_pool(pool.clone()); + let mut tx = db.pool().begin().await.unwrap(); + + users::create_user( + &mut tx, + AuditActor::System, + &NewUser { + email: Email::parse(email).unwrap(), + password_hash: auth::hash_password(password).unwrap(), + role, + }, + ) + .await + .unwrap(); + + tx.commit().await.unwrap(); +} + +async fn login(app: &axum::Router, email: &str, password: &str) -> String { + let resp = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/admin/login") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(format!( + r#"{{"email":"{email}","password":"{password}"}}"# + ))) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::NO_CONTENT); + + resp.headers() + .get(header::SET_COOKIE) + .unwrap() + .to_str() + .unwrap() + .split(';') + .next() + .unwrap() + .to_owned() +} + +async fn post_field(app: &axum::Router, cookie: &str, body: &str) -> axum::http::Response { + app.clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/admin/field-definitions") + .header(header::COOKIE, cookie) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_owned())) + .unwrap(), + ) + .await + .unwrap() +} + +#[sqlx::test(migrations = "../db/migrations")] +async fn create_requires_auth(pool: PgPool) { + migrate_sessions(&db::Db::from_pool(pool.clone())) + .await + .unwrap(); + + let app = build_app(state(pool)); + + let resp = app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/admin/field-definitions") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from( + r#"{"key":"x","data_type":"text","required":false,"labels":[{"lang":"en","label":"X"}]}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); +} + +#[sqlx::test(migrations = "../db/migrations")] +async fn create_scalar_field_then_lists_it(pool: PgPool) { + migrate_sessions(&db::Db::from_pool(pool.clone())) + .await + .unwrap(); + + seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await; + + let app = build_app(state(pool)); + let cookie = login(&app, "ed@example.com", "pw-editor-123").await; + + let resp = post_field( + &app, + &cookie, + r#"{"key":"height_cm","data_type":"integer","required":true,"group":"Dimensions","labels":[{"lang":"en","label":"Height"},{"lang":"sv","label":"Höjd"}]}"#, + ) + .await; + + assert_eq!(resp.status(), StatusCode::CREATED); + + let body: serde_json::Value = + serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap(); + + assert_eq!(body["key"], "height_cm"); + + 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 + ); +} diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 6959d49..e372e04 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -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; From df8f31d14d4953b752e406696f29137ac6ca1d15 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:15:19 +0200 Subject: [PATCH 2/6] fix(api): map nonexistent-vocabulary FK violation to 422; cover term/authority create paths Co-Authored-By: Claude Sonnet 4.6 --- crates/api/src/admin_objects.rs | 11 ++- crates/api/tests/admin_fields.rs | 114 +++++++++++++++++++++++++++---- 2 files changed, 110 insertions(+), 15 deletions(-) diff --git a/crates/api/src/admin_objects.rs b/crates/api/src/admin_objects.rs index ce0b302..8d3229b 100644 --- a/crates/api/src/admin_objects.rs +++ b/crates/api/src/admin_objects.rs @@ -494,10 +494,15 @@ pub(crate) async fn create_field_definition( Ok((StatusCode::CREATED, Json(CreatedField { key: new.key }))) } - Err(err) if err.as_database_error().and_then(|e| e.code()).as_deref() == Some("23505") => { - Err(StatusCode::CONFLICT) + 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), + _ => Err(StatusCode::INTERNAL_SERVER_ERROR), + } } - Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR), } } diff --git a/crates/api/tests/admin_fields.rs b/crates/api/tests/admin_fields.rs index e7675a1..a6a9fe0 100644 --- a/crates/api/tests/admin_fields.rs +++ b/crates/api/tests/admin_fields.rs @@ -7,6 +7,26 @@ 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 { + 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), @@ -65,18 +85,7 @@ async fn login(app: &axum::Router, email: &str, password: &str) -> String { } async fn post_field(app: &axum::Router, cookie: &str, body: &str) -> axum::http::Response { - app.clone() - .oneshot( - Request::builder() - .method("POST") - .uri("/api/admin/field-definitions") - .header(header::COOKIE, cookie) - .header(header::CONTENT_TYPE, "application/json") - .body(Body::from(body.to_owned())) - .unwrap(), - ) - .await - .unwrap() + post_json(app, cookie, "/api/admin/field-definitions", body).await } #[sqlx::test(migrations = "../db/migrations")] @@ -194,3 +203,84 @@ async fn duplicate_key_is_409(pool: PgPool) { 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); +} From 6ad1304efdad2180c6d3e7f70ce12af54e42ff51 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:16:55 +0200 Subject: [PATCH 3/6] feat(web): useCreateFieldDefinition mutation + MSW handler Co-Authored-By: Claude Sonnet 4.6 --- web/src/api/queries.fields.test.tsx | 40 +++++++++++++++++++++++++++++ web/src/api/queries.ts | 17 ++++++++++++ web/src/test/handlers.ts | 4 +++ 3 files changed, 61 insertions(+) create mode 100644 web/src/api/queries.fields.test.tsx diff --git a/web/src/api/queries.fields.test.tsx b/web/src/api/queries.fields.test.tsx new file mode 100644 index 0000000..6ed0f4c --- /dev/null +++ b/web/src/api/queries.fields.test.tsx @@ -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 {children}; +} + +test("useCreateFieldDefinition POSTs the request body", async () => { + let body: unknown; + + server.use( + http.post("/api/admin/field-definitions", async ({ request }) => { + body = await request.json(); + + return HttpResponse.json({ key: "technique" }, { status: 201 }); + }), + ); + + const { result } = renderHook(() => useCreateFieldDefinition(), { wrapper }); + + result.current.mutate({ + key: "technique", + data_type: "term", + vocabulary_id: "v-technique", + authority_kind: null, + required: false, + group: "Provenance", + labels: [{ lang: "en", label: "Technique" }], + }); + + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect((body as { key: string }).key).toBe("technique"); + expect((body as { data_type: string }).data_type).toBe("term"); +}); diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index 668f6f2..0825ec9 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -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. */ diff --git a/web/src/test/handlers.ts b/web/src/test/handlers.ts index 81d0d89..f6dcfba 100644 --- a/web/src/test/handlers.ts +++ b/web/src/test/handlers.ts @@ -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 }), + ), ]; From 37c80121ede297c23e566f98433bdeef3dcec3bc Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:22:57 +0200 Subject: [PATCH 4/6] feat(web): /fields two-pane screen (grouped list + create form) + nav (no stubs left) Co-Authored-By: Claude Sonnet 4.6 --- web/src/app.tsx | 12 +++ web/src/fields/field-form.tsx | 158 +++++++++++++++++++++++++++++++ web/src/fields/field-list.tsx | 70 ++++++++++++++ web/src/fields/fields-page.tsx | 15 +++ web/src/fields/fields.test.tsx | 72 ++++++++++++++ web/src/i18n/en.json | 16 ++++ web/src/i18n/sv.json | 16 ++++ web/src/shell/app-shell.test.tsx | 4 +- web/src/shell/app-shell.tsx | 20 ++-- 9 files changed, 369 insertions(+), 14 deletions(-) create mode 100644 web/src/fields/field-form.tsx create mode 100644 web/src/fields/field-list.tsx create mode 100644 web/src/fields/fields-page.tsx create mode 100644 web/src/fields/fields.test.tsx diff --git a/web/src/app.tsx b/web/src/app.tsx index 952925d..1eaa60d 100644 --- a/web/src/app.tsx +++ b/web/src/app.tsx @@ -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
Loading…
; } @@ -63,6 +67,14 @@ export function App() { } /> } /> + }> + + + } + /> } /> diff --git a/web/src/fields/field-form.tsx b/web/src/fields/field-form.tsx new file mode 100644 index 0000000..7d16bc0 --- /dev/null +++ b/web/src/fields/field-form.tsx @@ -0,0 +1,158 @@ +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([]); + const [dataType, setDataType] = useState("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); + }; + + 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 ( +
+
{t("fields.newField")}
+ +
+ + setKey(e.target.value)} /> +
+ + + +
+ + +
+ + {dataType === "term" && ( +
+ + +
+ )} + + {dataType === "authority" && ( +
+ + +
+ )} + +
+ + setGroup(e.target.value)} /> +
+ + + + {error && ( +

+ {t("form.required")} +

+ )} + {create.isError && ( +

+ {t("form.rejected")} +

+ )} + + + + ); +} diff --git a/web/src/fields/field-list.tsx b/web/src/fields/field-list.tsx new file mode 100644 index 0000000..6bee9d1 --- /dev/null +++ b/web/src/fields/field-list.tsx @@ -0,0 +1,70 @@ +import { useTranslation } from "react-i18next"; + +import type { components } from "../api/schema"; +import { useFieldDefinitions } from "../api/queries"; +import { Skeleton } from "@/components/ui/skeleton"; + +type FieldDefinitionView = components["schemas"]["FieldDefinitionView"]; + +function labelText(labels: FieldDefinitionView["labels"], lang: string): string { + return ( + labels.find((l) => l.lang === lang)?.label ?? + labels.find((l) => l.lang === "en")?.label ?? + labels[0]?.label ?? + "" + ); +} + +export function FieldList() { + const { t, i18n } = useTranslation(); + const { data, isLoading, isError } = useFieldDefinitions(); + const lang = i18n.language.startsWith("sv") ? "sv" : "en"; + + if (isLoading) { + return ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ ); + } + + if (isError) return

{t("fields.loadError")}

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

{t("fields.empty")}

; + + const groups = new Map(); + + for (const def of data) { + const key = def.group?.trim() ? def.group : t("fields.other"); + const bucket = groups.get(key) ?? []; + + bucket.push(def); + groups.set(key, bucket); + } + + return ( +
    + {[...groups.entries()].map(([group, defs]) => ( +
  • +
    + {group} +
    +
      + {defs.map((def) => ( +
    • + {labelText(def.labels, lang)} + {def.key} + + {t(`fields.types.${def.data_type}`)} + + {def.required && *} +
    • + ))} +
    +
  • + ))} +
+ ); +} diff --git a/web/src/fields/fields-page.tsx b/web/src/fields/fields-page.tsx new file mode 100644 index 0000000..f845bf9 --- /dev/null +++ b/web/src/fields/fields-page.tsx @@ -0,0 +1,15 @@ +import { FieldList } from "./field-list"; +import { FieldForm } from "./field-form"; + +export function FieldsPage() { + return ( +
+
+ +
+
+ +
+
+ ); +} diff --git a/web/src/fields/fields.test.tsx b/web/src/fields/fields.test.tsx new file mode 100644 index 0000000..87fdceb --- /dev/null +++ b/web/src/fields/fields.test.tsx @@ -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 ( + + } /> + + ); +} + +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)); +}); diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index bafe24b..a23cc69 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -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", diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index 2477583..e33f294 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -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", diff --git a/web/src/shell/app-shell.test.tsx b/web/src/shell/app-shell.test.tsx index 9cc1ca2..5e60cd2 100644 --- a/web/src/shell/app-shell.test.tsx +++ b/web/src/shell/app-shell.test.tsx @@ -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 () => { diff --git a/web/src/shell/app-shell.tsx b/web/src/shell/app-shell.tsx index 4a1aa13..43fb481 100644 --- a/web/src/shell/app-shell.tsx +++ b/web/src/shell/app-shell.tsx @@ -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")} - {DISABLED_NAV.map((key) => ( - - ))} + + `block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}` + } + > + {t("nav.fields")} +
From fd1c22191b6a34a342c826762b685011a29e9605 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:29:25 +0200 Subject: [PATCH 5/6] 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 --- web/src/fields/field-form.tsx | 1 + web/src/fields/field-list.tsx | 27 ++++++++++++++++----------- web/src/i18n/en.json | 2 +- web/src/i18n/sv.json | 2 +- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/web/src/fields/field-form.tsx b/web/src/fields/field-form.tsx index 7d16bc0..d7c77da 100644 --- a/web/src/fields/field-form.tsx +++ b/web/src/fields/field-form.tsx @@ -36,6 +36,7 @@ export function FieldForm() { setAuthorityKind(""); setGroup(""); setRequired(false); + setError(false); }; const onSubmit = (event: FormEvent) => { diff --git a/web/src/fields/field-list.tsx b/web/src/fields/field-list.tsx index 6bee9d1..341f846 100644 --- a/web/src/fields/field-list.tsx +++ b/web/src/fields/field-list.tsx @@ -2,19 +2,11 @@ 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"]; -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(); @@ -44,9 +36,14 @@ export function FieldList() { 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 (
    - {[...groups.entries()].map(([group, defs]) => ( + {entries.map(([group, defs]) => (
  • {group} @@ -59,7 +56,15 @@ export function FieldList() { {t(`fields.types.${def.data_type}`)} - {def.required && *} + {def.required && ( + + * + + )}
  • ))}
diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index a23cc69..9c27be1 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -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" }, diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index e33f294..833b5ff 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -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" }, From daad9438baec61ba07db7ba4bae0ae844cc30755 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Thu, 4 Jun 2026 14:35:56 +0200 Subject: [PATCH 6/6] fix(api): map CHECK-constraint violation (empty key) to 422 --- crates/api/src/admin_objects.rs | 2 ++ crates/api/tests/admin_fields.rs | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/api/src/admin_objects.rs b/crates/api/src/admin_objects.rs index 8d3229b..1b2d1b6 100644 --- a/crates/api/src/admin_objects.rs +++ b/crates/api/src/admin_objects.rs @@ -500,6 +500,8 @@ pub(crate) async fn create_field_definition( 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), } } diff --git a/crates/api/tests/admin_fields.rs b/crates/api/tests/admin_fields.rs index a6a9fe0..f4408d3 100644 --- a/crates/api/tests/admin_fields.rs +++ b/crates/api/tests/admin_fields.rs @@ -284,3 +284,24 @@ async fn create_authority_field(pool: PgPool) { 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); +}