use axum::extract::{Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::{Deserialize, Serialize};
use super::{ok_seq, require_admin, require_user, Shared};
use crate::catalog::{self, Effective};
use crate::db::CategoryChange;
use crate::model::{AttributeDef, Category};
use crate::Error;
#[derive(Debug, Serialize)]
pub struct CategoryView {
#[serde(flatten)]
pub category: Category,
pub path: String,
pub depth: usize,
pub parts: usize,
pub parts_within: usize,
}
pub async fn list(
State(db): State<Shared>,
headers: HeaderMap,
) -> Result<Response, Error> {
require_user(&db, &headers)?;
db.read(|state| {
let etag = format!("\"categories-{}\"", state.seq);
if headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok())
.is_some_and(|value| value.split(',').any(|tag| tag.trim() == etag || tag.trim() == "*"))
{
return Ok((StatusCode::NOT_MODIFIED, [(header::ETAG, etag),
(header::CACHE_CONTROL, "private, no-cache".to_string())]).into_response());
}
let mut counts = std::collections::BTreeMap::<String, usize>::new();
for part in &state.parts {
*counts.entry(part.category.to_ascii_lowercase()).or_default() += 1;
}
let categories = &state.categories;
let mut out = Vec::with_capacity(categories.len());
let mut roots: Vec<&Category> = categories
.iter()
.filter(|c| c.parent.is_empty() || catalog::find(categories, &c.parent).is_none())
.collect();
roots.sort_by_key(|c| c.name.to_ascii_lowercase());
let mut stack: Vec<(&Category, usize)> = roots.into_iter().rev().map(|c| (c, 0)).collect();
let mut seen = std::collections::BTreeSet::new();
while let Some((category, depth)) = stack.pop() {
if !seen.insert(category.id.clone()) {
continue;
}
let own = counts.get(&category.id.to_ascii_lowercase()).copied().unwrap_or(0);
out.push(CategoryView {
category: category.clone(),
path: catalog::path_name(categories, &category.id),
depth,
parts: own,
parts_within: own,
});
let mut children: Vec<&Category> = categories
.iter()
.filter(|c| c.parent.eq_ignore_ascii_case(&category.id))
.collect();
children.sort_by_key(|c| c.name.to_ascii_lowercase());
stack.extend(children.into_iter().rev().map(|c| (c, depth + 1)));
}
let positions: std::collections::BTreeMap<String, usize> = out.iter().enumerate()
.map(|(i, row)| (row.category.id.to_ascii_lowercase(), i)).collect();
for i in (0..out.len()).rev() {
if let Some(&parent) = positions.get(&out[i].category.parent.to_ascii_lowercase()) {
let total = out[i].parts_within;
out[parent].parts_within += total;
}
}
Ok(([(header::ETAG, etag), (header::CACHE_CONTROL, "private, no-cache".to_string())],
Json(out)).into_response())
})
}
#[derive(Debug, Deserialize)]
pub struct NewCategory {
pub id: String,
pub name: String,
#[serde(default)]
pub parent: String,
#[serde(default)]
pub attributes: Vec<AttributeDef>,
}
pub async fn create(
State(db): State<Shared>,
headers: HeaderMap,
Json(body): Json<NewCategory>,
) -> Result<Json<Category>, Error> {
require_admin(&db, &headers)?;
Ok(Json(db.create_category(
&body.id,
CategoryChange {
name: Some(body.name),
parent: Some(body.parent),
attributes: Some(body.attributes),
},
)?))
}
#[derive(Debug, Deserialize)]
pub struct Change {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub parent: Option<String>,
#[serde(default)]
pub attributes: Option<Vec<AttributeDef>>,
}
pub async fn update(
State(db): State<Shared>,
headers: HeaderMap,
Path(id): Path<String>,
Json(body): Json<Change>,
) -> Result<Json<Category>, Error> {
require_admin(&db, &headers)?;
Ok(Json(db.update_category(
&id,
CategoryChange { name: body.name, parent: body.parent, attributes: body.attributes },
)?))
}
pub async fn remove(
State(db): State<Shared>,
headers: HeaderMap,
Path(id): Path<String>,
) -> Result<Response, Error> {
require_admin(&db, &headers)?;
db.delete_category(&id)?;
Ok(ok_seq(&db))
}
#[derive(Debug, Serialize)]
pub struct Schema {
pub category: String,
pub path: String,
pub attributes: Vec<Effective>,
}
pub async fn schema(
State(db): State<Shared>,
headers: HeaderMap,
Path(id): Path<String>,
) -> Result<Json<Schema>, Error> {
require_user(&db, &headers)?;
db.read(|state| {
let category = catalog::find(&state.categories, &id)
.ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
Ok(Json(Schema {
category: category.id.clone(),
path: catalog::path_name(&state.categories, &category.id),
attributes: catalog::schema(&state.categories, &category.id)?,
}))
})
}