feat(api): admin object create/update/delete (EditCatalogue, audited as user)

POST /api/admin/objects (draft|internal only; public rejected 422),
PUT /api/admin/objects/{id} (preserves visibility; 204/404),
DELETE /api/admin/objects/{id} (204/404). Every write records
AuditActor::User(<session-user-uuid>). Tests: lifecycle, public-rejection,
unauthenticated-rejection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-02 21:59:14 +02:00
parent 1888e185f7
commit 3f4da46b78
3 changed files with 349 additions and 10 deletions
+208 -8
View File
@@ -1,7 +1,7 @@
//! Admin catalogue-object surface (authenticated). Reads require `ViewInternal`;
//! writes require `EditCatalogue` (added in later tasks).
//! writes require `EditCatalogue`.
use auth::{Authorized, ViewInternal};
use auth::{AuthUser, Authorized, EditCatalogue, ViewInternal};
use axum::{
Json, Router,
extract::{Path, Query, State},
@@ -9,8 +9,8 @@ use axum::{
response::IntoResponse,
routing::get,
};
use domain::{CatalogueObject, ObjectId};
use serde::Serialize;
use domain::{AuditActor, CatalogueObject, ObjectId, ObjectInput, Visibility};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{AppState, pagination::Pagination};
@@ -77,8 +77,6 @@ pub(crate) fn format_date(d: time::Date) -> String {
}
/// Parse a `YYYY-MM-DD` string into a `time::Date`, returning 422 on failure.
// Used by write handlers added in later tasks.
#[allow(dead_code)]
pub(crate) fn parse_date(s: &str) -> Result<time::Date, StatusCode> {
let fmt = time::macros::format_description!("[year]-[month]-[day]");
@@ -148,9 +146,211 @@ pub(crate) async fn get_object(
}
}
/// Inventory-minimum fields for create. `recording_date` is `YYYY-MM-DD`.
#[derive(Deserialize, ToSchema)]
pub(crate) struct ObjectCreateRequest {
pub object_number: String,
pub object_name: String,
pub number_of_objects: i32,
pub brief_description: Option<String>,
pub current_location: Option<String>,
pub current_owner: Option<String>,
pub recorder: Option<String>,
pub recording_date: Option<String>,
/// "draft" | "internal" (public is rejected — publish via the visibility endpoint).
#[schema(value_type = String)]
pub visibility: Visibility,
}
/// Inventory-minimum fields for update. Visibility is intentionally absent — it changes
/// only through the stepwise publish endpoint.
#[derive(Deserialize, ToSchema)]
pub(crate) struct ObjectUpdateRequest {
pub object_number: String,
pub object_name: String,
pub number_of_objects: i32,
pub brief_description: Option<String>,
pub current_location: Option<String>,
pub current_owner: Option<String>,
pub recorder: Option<String>,
pub recording_date: Option<String>,
}
/// The id of a newly created object.
#[derive(Serialize, ToSchema)]
pub(crate) struct CreatedObject {
pub id: String,
}
fn actor(user: &AuthUser) -> AuditActor {
AuditActor::User(user.id.to_uuid())
}
/// Create an object (initial visibility Draft or Internal). Requires `EditCatalogue`.
#[utoipa::path(
post, path = "/api/admin/objects", request_body = ObjectCreateRequest,
responses(
(status = 201, body = CreatedObject),
(status = 401),
(status = 403),
(status = 422, description = "Invalid input (e.g. visibility=public or bad date)")
)
)]
pub(crate) async fn create_object(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Json(req): Json<ObjectCreateRequest>,
) -> Result<(StatusCode, Json<CreatedObject>), StatusCode> {
if req.visibility == Visibility::Public {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let recording_date = req.recording_date.as_deref().map(parse_date).transpose()?;
let input = ObjectInput {
object_number: req.object_number,
object_name: req.object_name,
number_of_objects: req.number_of_objects,
brief_description: req.brief_description,
current_location: req.current_location,
current_owner: req.current_owner,
recorder: req.recorder,
recording_date,
visibility: req.visibility,
};
let mut tx = state
.db
.pool()
.begin()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let id = db::catalog::create_object(&mut tx, actor(&auth.user), &input)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
tx.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok((
StatusCode::CREATED,
Json(CreatedObject { id: id.to_string() }),
))
}
/// Update an object's inventory-minimum fields (NOT visibility). Requires `EditCatalogue`.
#[utoipa::path(
put, path = "/api/admin/objects/{id}", request_body = ObjectUpdateRequest,
params(("id" = String, Path, description = "Object id (UUID)")),
responses(
(status = 204),
(status = 401),
(status = 403),
(status = 404),
(status = 422)
)
)]
pub(crate) async fn update_object(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Path(id): Path<String>,
Json(req): Json<ObjectUpdateRequest>,
) -> Result<StatusCode, StatusCode> {
let object_id = id.parse::<ObjectId>().map_err(|_| StatusCode::NOT_FOUND)?;
let recording_date = req.recording_date.as_deref().map(parse_date).transpose()?;
// Read current visibility so the update preserves it — visibility changes only
// through the stepwise publish endpoint.
let Some(current) = db::catalog::object_by_id(state.db.pool(), object_id)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
else {
return Err(StatusCode::NOT_FOUND);
};
let input = ObjectInput {
object_number: req.object_number,
object_name: req.object_name,
number_of_objects: req.number_of_objects,
brief_description: req.brief_description,
current_location: req.current_location,
current_owner: req.current_owner,
recorder: req.recorder,
recording_date,
visibility: current.visibility,
};
let mut tx = state
.db
.pool()
.begin()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let existed = db::catalog::update_object(&mut tx, actor(&auth.user), object_id, &input)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
tx.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if existed {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
/// Delete an object. Requires `EditCatalogue`. 404 if it did not exist.
#[utoipa::path(
delete, path = "/api/admin/objects/{id}",
params(("id" = String, Path, description = "Object id (UUID)")),
responses(
(status = 204),
(status = 401),
(status = 403),
(status = 404)
)
)]
pub(crate) async fn delete_object(
auth: Authorized<EditCatalogue>,
State(state): State<AppState>,
Path(id): Path<String>,
) -> 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 existed = db::catalog::delete_object(&mut tx, actor(&auth.user), object_id)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
tx.commit()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if existed {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
/// Admin object routes, parameterized over [`AppState`].
pub(crate) fn routes() -> Router<AppState> {
Router::new()
.route("/api/admin/objects", get(list_objects))
.route("/api/admin/objects/{id}", get(get_object))
.route("/api/admin/objects", get(list_objects).post(create_object))
.route(
"/api/admin/objects/{id}",
get(get_object).put(update_object).delete(delete_object),
)
}