feat(api): admin object read surface (paginated list + get, ViewInternal)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ rust-version.workspace = true
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
time.workspace = true
|
||||
tower-sessions.workspace = true
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Admin catalogue-object surface (authenticated). Reads require `ViewInternal`;
|
||||
//! writes require `EditCatalogue` (added in later tasks).
|
||||
|
||||
use auth::{Authorized, ViewInternal};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::get,
|
||||
};
|
||||
use domain::{CatalogueObject, ObjectId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
/// A localized label `{ lang, label }` (shared across admin views).
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub(crate) struct LabelView {
|
||||
pub lang: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// Full admin view of a catalogue object (all fields, all visibility levels).
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub(crate) struct AdminObjectView {
|
||||
pub id: String,
|
||||
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>,
|
||||
/// `YYYY-MM-DD` or null.
|
||||
pub recording_date: Option<String>,
|
||||
/// "draft" | "internal" | "public".
|
||||
pub visibility: String,
|
||||
/// Flexible field values (key -> value).
|
||||
#[schema(value_type = Object)]
|
||||
pub fields: serde_json::Value,
|
||||
}
|
||||
|
||||
impl AdminObjectView {
|
||||
pub(crate) fn from_object(o: &CatalogueObject) -> Self {
|
||||
AdminObjectView {
|
||||
id: o.id.to_string(),
|
||||
object_number: o.object_number.clone(),
|
||||
object_name: o.object_name.clone(),
|
||||
number_of_objects: o.number_of_objects,
|
||||
brief_description: o.brief_description.clone(),
|
||||
current_location: o.current_location.clone(),
|
||||
current_owner: o.current_owner.clone(),
|
||||
recorder: o.recorder.clone(),
|
||||
recording_date: o.recording_date.map(format_date),
|
||||
visibility: o.visibility.as_str().to_owned(),
|
||||
fields: o.fields.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A page of admin objects.
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub(crate) struct AdminObjectPage {
|
||||
pub items: Vec<AdminObjectView>,
|
||||
pub total: i64,
|
||||
pub limit: i64,
|
||||
pub offset: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Pagination {
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT: i64 = 50;
|
||||
const MAX_LIMIT: i64 = 200;
|
||||
|
||||
impl Pagination {
|
||||
fn limit(&self) -> i64 {
|
||||
self.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT)
|
||||
}
|
||||
|
||||
fn offset(&self) -> i64 {
|
||||
self.offset.unwrap_or(0).max(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Format a `time::Date` as `YYYY-MM-DD`.
|
||||
pub(crate) fn format_date(d: time::Date) -> String {
|
||||
let fmt = time::macros::format_description!("[year]-[month]-[day]");
|
||||
|
||||
d.format(&fmt).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 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]");
|
||||
|
||||
time::Date::parse(s, &fmt).map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)
|
||||
}
|
||||
|
||||
/// List objects (paginated, all visibility levels). Requires `ViewInternal`.
|
||||
#[utoipa::path(
|
||||
get, path = "/api/admin/objects",
|
||||
params(
|
||||
("limit" = Option<i64>, Query, description = "1..=200, default 50"),
|
||||
("offset" = Option<i64>, Query, description = "default 0")
|
||||
),
|
||||
responses(
|
||||
(status = 200, body = AdminObjectPage),
|
||||
(status = 401),
|
||||
(status = 403)
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn list_objects(
|
||||
_auth: Authorized<ViewInternal>,
|
||||
State(state): State<AppState>,
|
||||
Query(page): Query<Pagination>,
|
||||
) -> Result<Json<AdminObjectPage>, StatusCode> {
|
||||
let (limit, offset) = (page.limit(), page.offset());
|
||||
|
||||
let objects = db::catalog::list_objects_paged(state.db.pool(), limit, offset)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let total = db::catalog::count_objects(state.db.pool())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(AdminObjectPage {
|
||||
items: objects.iter().map(AdminObjectView::from_object).collect(),
|
||||
total,
|
||||
limit,
|
||||
offset,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Get one object (any visibility). Requires `ViewInternal`. 404 if missing.
|
||||
#[utoipa::path(
|
||||
get, path = "/api/admin/objects/{id}",
|
||||
params(("id" = String, Path, description = "Object id (UUID)")),
|
||||
responses(
|
||||
(status = 200, body = AdminObjectView),
|
||||
(status = 401),
|
||||
(status = 403),
|
||||
(status = 404)
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn get_object(
|
||||
_auth: Authorized<ViewInternal>,
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let Ok(object_id) = id.parse::<ObjectId>() else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
|
||||
match db::catalog::object_by_id(state.db.pool(), object_id).await {
|
||||
Ok(Some(o)) => Json(AdminObjectView::from_object(&o)).into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! HTTP API: router, handlers, and OpenAPI document.
|
||||
|
||||
mod admin;
|
||||
mod admin_objects;
|
||||
mod health;
|
||||
mod openapi;
|
||||
mod public;
|
||||
@@ -40,6 +41,7 @@ pub fn build_app(state: AppState) -> Router {
|
||||
.merge(openapi::routes())
|
||||
.merge(public::routes())
|
||||
.merge(admin::routes())
|
||||
.merge(admin_objects::routes())
|
||||
.layer(session_layer)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use axum::{Json, Router, extract::State, routing::get};
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use crate::{AppState, admin, health, public};
|
||||
use crate::{AppState, admin, admin_objects, health, public};
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
@@ -14,7 +14,9 @@ use crate::{AppState, admin, health, public};
|
||||
admin::logout,
|
||||
admin::me,
|
||||
admin::list_users,
|
||||
admin::set_visibility
|
||||
admin::set_visibility,
|
||||
admin_objects::list_objects,
|
||||
admin_objects::get_object
|
||||
),
|
||||
components(schemas(
|
||||
health::Live,
|
||||
@@ -23,7 +25,10 @@ use crate::{AppState, admin, health, public};
|
||||
public::PublicObjectPage,
|
||||
admin::LoginRequest,
|
||||
admin::UserView,
|
||||
admin::VisibilityRequest
|
||||
admin::VisibilityRequest,
|
||||
admin_objects::AdminObjectView,
|
||||
admin_objects::AdminObjectPage,
|
||||
admin_objects::LabelView
|
||||
)),
|
||||
info(title = "Collection Management System", version = "0.0.0")
|
||||
)]
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
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 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,
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
fn login_request(email: &str, password: &str) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/admin/login")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(format!(
|
||||
r#"{{"email":"{email}","password":"{password}"}}"#
|
||||
)))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn session_cookie(resp: &axum::http::Response<Body>) -> String {
|
||||
resp.headers()
|
||||
.get(header::SET_COOKIE)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
async fn login(app: &axum::Router, email: &str, pw: &str) -> String {
|
||||
let resp = app.clone().oneshot(login_request(email, pw)).await.unwrap();
|
||||
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
|
||||
session_cookie(&resp)
|
||||
}
|
||||
|
||||
fn obj(number: &str, name: &str, v: Visibility) -> ObjectInput {
|
||||
ObjectInput {
|
||||
object_number: number.into(),
|
||||
object_name: name.into(),
|
||||
number_of_objects: 1,
|
||||
brief_description: Some("d".into()),
|
||||
current_location: Some("vault".into()),
|
||||
current_owner: None,
|
||||
recorder: None,
|
||||
recording_date: None,
|
||||
visibility: v,
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn list_and_get_require_auth(pool: PgPool) {
|
||||
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let app = build_app(state(pool));
|
||||
|
||||
let list = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/objects")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(list.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn list_shows_all_visibility_levels(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();
|
||||
|
||||
catalog::create_object(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
&obj("D-1", "draft", Visibility::Draft),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
catalog::create_object(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
&obj("P-1", "pub", Visibility::Public),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
let app = build_app(state(pool));
|
||||
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
|
||||
|
||||
let resp = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/objects")
|
||||
.header(header::COOKIE, &cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
assert_eq!(json["total"], 2);
|
||||
|
||||
let items = json["items"].as_array().unwrap();
|
||||
assert!(items.iter().any(|i| i["object_number"] == "D-1"));
|
||||
assert!(items[0].get("current_location").is_some());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn get_by_id_returns_full_view(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();
|
||||
|
||||
let id = catalog::create_object(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
&obj("D-1", "draft", Visibility::Draft),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
let app = build_app(state(pool));
|
||||
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
|
||||
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/api/admin/objects/{id}"))
|
||||
.header(header::COOKIE, &cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
assert_eq!(json["object_number"], "D-1");
|
||||
assert_eq!(json["visibility"], "draft");
|
||||
|
||||
let missing = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/api/admin/objects/{}", domain::ObjectId::new()))
|
||||
.header(header::COOKIE, &cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
@@ -96,6 +96,39 @@ where
|
||||
rows.into_iter().map(map_object).collect()
|
||||
}
|
||||
|
||||
/// List objects (all visibility levels) ordered by object number, with paging.
|
||||
pub async fn list_objects_paged<'e, E>(
|
||||
executor: E,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<CatalogueObject>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::PgExecutor<'e>,
|
||||
{
|
||||
let sql =
|
||||
format!("SELECT {OBJECT_COLUMNS} FROM object ORDER BY object_number LIMIT $1 OFFSET $2");
|
||||
|
||||
let rows = sqlx::query(&sql)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(executor)
|
||||
.await?;
|
||||
|
||||
rows.into_iter().map(map_object).collect()
|
||||
}
|
||||
|
||||
/// Count all objects (for pagination totals).
|
||||
pub async fn count_objects<'e, E>(executor: E) -> Result<i64, sqlx::Error>
|
||||
where
|
||||
E: sqlx::PgExecutor<'e>,
|
||||
{
|
||||
let row = sqlx::query("SELECT count(*) AS n FROM object")
|
||||
.fetch_one(executor)
|
||||
.await?;
|
||||
|
||||
row.try_get("n")
|
||||
}
|
||||
|
||||
/// Fetch one **public** object by id. Returns `None` if the object is missing **or**
|
||||
/// not public — callers map both to 404 so non-public existence isn't revealed.
|
||||
pub async fn public_object_by_id<'e, E>(
|
||||
|
||||
Reference in New Issue
Block a user