merge: fields management — create field definitions (endpoint + /fields UI)
CI / web (push) Has been cancelled
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>
This commit is contained in:
@@ -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),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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");
|
||||
});
|
||||
@@ -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. */
|
||||
|
||||
Vendored
+75
-1
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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",
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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"
|
||||
>
|
||||
{t(`nav.${key}`)}
|
||||
</button>
|
||||
))}
|
||||
<NavLink
|
||||
to="/fields"
|
||||
className={({ isActive }) =>
|
||||
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
|
||||
}
|
||||
>
|
||||
{t("nav.fields")}
|
||||
</NavLink>
|
||||
</nav>
|
||||
</aside>
|
||||
<div className="flex flex-1 flex-col">
|
||||
|
||||
@@ -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 }),
|
||||
),
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user