diff --git a/Cargo.toml b/Cargo.toml index 6032968..cfc53ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", uuid = { version = "1", features = ["v4", "serde"] } serde = { version = "1", features = ["derive"] } serde_json = "1" -time = { version = "0.3", features = ["serde"] } +time = { version = "0.3", features = ["serde", "macros", "parsing", "formatting"] } clap = { version = "4", features = ["derive", "env"] } utoipa = { version = "5", features = ["uuid"] } anyhow = "1" diff --git a/crates/api/Cargo.toml b/crates/api/Cargo.toml index 720d7bb..2c107c4 100644 --- a/crates/api/Cargo.toml +++ b/crates/api/Cargo.toml @@ -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 diff --git a/crates/api/src/admin_objects.rs b/crates/api/src/admin_objects.rs new file mode 100644 index 0000000..e0a1bf3 --- /dev/null +++ b/crates/api/src/admin_objects.rs @@ -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, + pub current_location: Option, + pub current_owner: Option, + pub recorder: Option, + /// `YYYY-MM-DD` or null. + pub recording_date: Option, + /// "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, + pub total: i64, + pub limit: i64, + pub offset: i64, +} + +#[derive(Deserialize)] +pub(crate) struct Pagination { + limit: Option, + offset: Option, +} + +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 { + 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, Query, description = "1..=200, default 50"), + ("offset" = Option, Query, description = "default 0") + ), + responses( + (status = 200, body = AdminObjectPage), + (status = 401), + (status = 403) + ) +)] +pub(crate) async fn list_objects( + _auth: Authorized, + State(state): State, + Query(page): Query, +) -> Result, 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, + State(state): State, + Path(id): Path, +) -> impl IntoResponse { + let Ok(object_id) = id.parse::() 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 { + Router::new() + .route("/api/admin/objects", get(list_objects)) + .route("/api/admin/objects/{id}", get(get_object)) +} diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index aeea91b..74b081e 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -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) } diff --git a/crates/api/src/openapi.rs b/crates/api/src/openapi.rs index ae77ae0..cd4e72c 100644 --- a/crates/api/src/openapi.rs +++ b/crates/api/src/openapi.rs @@ -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") )] diff --git a/crates/api/tests/admin_objects.rs b/crates/api/tests/admin_objects.rs new file mode 100644 index 0000000..1dcd6b3 --- /dev/null +++ b/crates/api/tests/admin_objects.rs @@ -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 { + 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) -> 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); +} diff --git a/crates/db/src/catalog.rs b/crates/db/src/catalog.rs index f09d243..e3d67fb 100644 --- a/crates/db/src/catalog.rs +++ b/crates/db/src/catalog.rs @@ -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, 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 +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>(