cdb/src/routes/item/supply.rs
2024-08-28 09:38:10 +02:00

97 lines
2.6 KiB
Rust

use rocket::serde::json::Json;
use rocket::{get, post, State};
use serde::Deserialize;
use serde_json::json;
use crate::{
db::ItemDB,
routes::{api_error, FallibleApiResponse},
};
use super::{item_does_not_exist_error, variant_does_not_exist_error};
#[derive(Deserialize, Debug)]
pub struct SupplyForm {
item: String,
variant: String,
price: String,
origin: Option<String>,
}
/// Route for supply action. Creates a new Transaction for the specified Item Variant.
#[post("/supply", data = "<form>")]
pub async fn supply_route(form: Json<SupplyForm>, itemdb: &State<ItemDB>) -> FallibleApiResponse {
println!("{form:?}");
let variant = itemdb
.get_item(&form.item)
.ok_or_else(item_does_not_exist_error)?
.variant(&form.variant)
.ok_or_else(variant_does_not_exist_error)?;
let transaction_id = variant
.supply(
form.price
.clone()
.try_into()
.map_err(|()| api_error("Price malformed"))?,
form.origin.as_deref(),
)
.await;
Ok(json!({"uuid": transaction_id}))
}
/// Returns a list of Transaction UUIDs for the Item Variant
#[get("/item/<item_id>/<variant_id>/supply")]
pub async fn supply_log_route(
item_id: &str,
variant_id: &str,
itemdb: &State<ItemDB>,
) -> FallibleApiResponse {
let variant = itemdb
.get_item(item_id)
.ok_or_else(item_does_not_exist_error)?
.variant(variant_id)
.ok_or_else(variant_does_not_exist_error)?;
let transactions = variant.supply_log().await;
Ok(json!(transactions))
}
/// Returns current active Transactions for Item Variant
#[get("/item/<item_id>/<variant_id>/inventory")]
pub async fn inventory_route(
item_id: &str,
variant_id: &str,
itemdb: &State<ItemDB>,
) -> FallibleApiResponse {
let variant = itemdb
.get_item(item_id)
.ok_or_else(item_does_not_exist_error)?
.variant(variant_id)
.ok_or_else(variant_does_not_exist_error)?;
let transactions = variant.inventory().await;
Ok(json!(transactions
.into_iter()
.map(|x| x.api_json())
.collect::<Vec<_>>()))
}
/// Returns statistics for the Item Variant
#[get("/item/<item_id>/<variant_id>/stat")]
pub async fn variant_stat_route(
item_id: &str,
variant_id: &str,
itemdb: &State<ItemDB>,
) -> FallibleApiResponse {
let variant = itemdb
.get_item(item_id)
.ok_or_else(item_does_not_exist_error)?
.variant(variant_id)
.ok_or_else(variant_does_not_exist_error)?;
Ok(variant.stat().await)
}