feat(api): admin set flexible fields + field-definition listing

- GET /api/admin/field-definitions (ViewInternal) — lists all registered
  field definitions with key, data_type, vocabulary_id, authority_kind,
  required, group, and localized labels
- PUT /api/admin/objects/{id}/fields (EditCatalogue) — replaces an
  object's flexible-field values with replace semantics; validates every
  key against the registry (UnknownField → 422, TypeMismatch → 422,
  Unresolved → 422, ObjectNotFound → 404, Db → 500)
- FieldDefinitionView DTO added; both handlers registered in OpenAPI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-02 22:09:43 +02:00
parent 34e5754815
commit b6a30c3995
3 changed files with 217 additions and 4 deletions
+109 -1
View File
@@ -7,7 +7,7 @@ use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
routing::get,
routing::{get, put},
};
use domain::{AuditActor, CatalogueObject, ObjectId, ObjectInput, Visibility};
use serde::{Deserialize, Serialize};
@@ -345,6 +345,112 @@ pub(crate) async fn delete_object(
}
}
/// Field-definition descriptor for the UI to render forms.
#[derive(Serialize, ToSchema)]
pub(crate) struct FieldDefinitionView {
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<LabelView>,
}
/// List all field definitions. Requires `ViewInternal`.
#[utoipa::path(
get, path = "/api/admin/field-definitions",
responses(
(status = 200, body = [FieldDefinitionView]),
(status = 401),
(status = 403)
)
)]
pub(crate) async fn list_field_definitions(
_auth: Authorized<ViewInternal>,
State(state): State<AppState>,
) -> Result<Json<Vec<FieldDefinitionView>>, StatusCode> {
let defs = db::fields::list_field_definitions(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(
defs.into_iter()
.map(|d| {
let (data_type, vocabulary_id, authority_kind) = d.field_type.to_parts();
FieldDefinitionView {
key: d.key,
data_type: data_type.to_owned(),
vocabulary_id: vocabulary_id.map(|v| v.to_string()),
authority_kind: authority_kind.map(|k| k.as_str().to_owned()),
required: d.required,
group: d.group_key,
labels: d
.labels
.into_iter()
.map(|l| LabelView {
lang: l.lang,
label: l.label,
})
.collect(),
}
})
.collect(),
))
}
/// Replace an object's flexible-field values (validated against the registry).
///
/// **Replace semantics:** the body is the *complete* desired field set. Omitting a key
/// that was previously set removes it — send every key the caller wants to retain.
///
/// Requires `EditCatalogue`.
#[utoipa::path(
put, path = "/api/admin/objects/{id}/fields",
params(("id" = String, Path, description = "Object id (UUID)")),
request_body = Object,
responses(
(status = 204),
(status = 401),
(status = 403),
(status = 404, description = "Object not found"),
(status = 422, description = "Unknown field, type mismatch, or unresolved reference")
)
)]
pub(crate) async fn set_fields(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Path(id): Path<String>,
Json(values): Json<serde_json::Map<String, serde_json::Value>>,
) -> Result<StatusCode, StatusCode> {
let object_id = id.parse::<ObjectId>().map_err(|_| StatusCode::NOT_FOUND)?;
let mut tx = state
.db
.pool()
.begin()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let result =
db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await;
match result {
Ok(()) => {
tx.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::NO_CONTENT)
}
Err(db::catalog::FieldError::ObjectNotFound) => Err(StatusCode::NOT_FOUND),
Err(db::catalog::FieldError::Db(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR),
Err(_) => Err(StatusCode::UNPROCESSABLE_ENTITY),
}
}
/// Admin object routes, parameterized over [`AppState`].
pub(crate) fn routes() -> Router<AppState> {
Router::new()
@@ -353,4 +459,6 @@ pub(crate) fn routes() -> Router<AppState> {
"/api/admin/objects/{id}",
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))
}
+5 -2
View File
@@ -19,7 +19,9 @@ use crate::{AppState, admin, admin_objects, health, public};
admin_objects::get_object,
admin_objects::create_object,
admin_objects::update_object,
admin_objects::delete_object
admin_objects::delete_object,
admin_objects::list_field_definitions,
admin_objects::set_fields
),
components(schemas(
health::Live,
@@ -34,7 +36,8 @@ use crate::{AppState, admin, admin_objects, health, public};
admin_objects::LabelView,
admin_objects::ObjectCreateRequest,
admin_objects::ObjectUpdateRequest,
admin_objects::CreatedObject
admin_objects::CreatedObject,
admin_objects::FieldDefinitionView
)),
info(title = "Collection Management System", version = "0.0.0")
)]
+103 -1
View File
@@ -2,7 +2,10 @@ use api::{AppState, build_app, migrate_sessions};
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use db::{catalog, users};
use domain::{AuditActor, Email, NewUser, ObjectInput, Role, Visibility};
use domain::{
AuditActor, Email, FieldType, LocalizedLabel, NewFieldDefinition, NewUser, ObjectInput, Role,
Visibility,
};
use http_body_util::BodyExt;
use sqlx::PgPool;
use tower::ServiceExt;
@@ -329,6 +332,105 @@ async fn create_rejects_public_visibility(pool: PgPool) {
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn set_fields_and_list_field_definitions(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 db = db::Db::from_pool(pool.clone());
let mut tx = db.pool().begin().await.unwrap();
db::fields::create_field_definition(
&mut tx,
&NewFieldDefinition {
key: "inscription".into(),
field_type: FieldType::Text,
required: false,
group_key: None,
labels: vec![LocalizedLabel {
lang: "en".into(),
label: "Inscription".into(),
}],
},
)
.await
.unwrap();
let id = catalog::create_object(
&mut tx,
AuditActor::System,
&obj("A-1", "amphora", Visibility::Draft),
)
.await
.unwrap();
tx.commit().await.unwrap();
let app = build_app(state(pool.clone()));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
// field-definitions list
let defs = app
.clone()
.oneshot(
Request::builder()
.uri("/api/admin/field-definitions")
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(defs.status(), StatusCode::OK);
let defs_json: serde_json::Value =
serde_json::from_slice(&defs.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert!(
defs_json
.as_array()
.unwrap()
.iter()
.any(|d| d["key"] == "inscription" && d["data_type"] == "text")
);
// set the field
let set = app
.clone()
.oneshot(
Request::builder()
.method("PUT")
.uri(format!("/api/admin/objects/{id}/fields"))
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"inscription":"To the gods"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(set.status(), StatusCode::NO_CONTENT);
let stored = catalog::object_by_id(db.pool(), id).await.unwrap().unwrap();
assert_eq!(stored.fields["inscription"], "To the gods");
// unknown field → 422
let bad = app
.oneshot(
Request::builder()
.method("PUT")
.uri(format!("/api/admin/objects/{id}/fields"))
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"nope":"x"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn create_requires_auth(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))