diff options
| author | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-09-06 18:31:40 +0200 |
|---|---|---|
| committer | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-09-06 18:31:40 +0200 |
| commit | 1c09b0eb5db415985bfefb52786dbe48d757665e (patch) | |
| tree | db1cdbcff8baae9a73fca34e14b52cb8cf7ff230 /crates/rocie-server/src | |
| parent | feat: Provide basic API frame (diff) | |
| download | server-1c09b0eb5db415985bfefb52786dbe48d757665e.zip | |
feat: Provide basic barcode handling support
Diffstat (limited to 'crates/rocie-server/src')
17 files changed, 456 insertions, 38 deletions
diff --git a/crates/rocie-server/src/api/get/mod.rs b/crates/rocie-server/src/api/get/mod.rs new file mode 100644 index 0000000..ce39076 --- /dev/null +++ b/crates/rocie-server/src/api/get/mod.rs @@ -0,0 +1,11 @@ +use actix_web::web; + +pub(crate) mod product; +pub(crate) mod unit; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { + cfg.service(product::product_by_id) + .service(product::products) + .service(unit::units) + .service(unit::unit_by_id); +} diff --git a/crates/rocie-server/src/api/get.rs b/crates/rocie-server/src/api/get/product.rs index 94015cf..c496777 100644 --- a/crates/rocie-server/src/api/get.rs +++ b/crates/rocie-server/src/api/get/product.rs @@ -5,10 +5,6 @@ use crate::{ storage::sql::product::{Product, ProductId}, }; -pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { - cfg.service(product_by_id).service(products); -} - /// Get Product by id #[utoipa::path( responses( diff --git a/crates/rocie-server/src/api/get/unit.rs b/crates/rocie-server/src/api/get/unit.rs new file mode 100644 index 0000000..d006818 --- /dev/null +++ b/crates/rocie-server/src/api/get/unit.rs @@ -0,0 +1,41 @@ +use actix_web::{get, web, HttpResponse, Responder, Result}; + +use crate::{app::App, storage::sql::unit::{Unit, UnitId}}; + +/// Return all registered units +#[utoipa::path( + responses( + (status = OK, description = "All units founds", body = Vec<Unit>), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), +)] +#[get("/units/")] +pub(crate) async fn units(app: web::Data<App>) -> Result<impl Responder> { + let all = Unit::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} + +/// Get Unit by id +#[utoipa::path( + responses( + (status = OK, description = "Unit found from database", body = Unit), + (status = NOT_FOUND, description = "Unit not found in database"), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), + params( + ("id" = UnitId, description = "Unit id" ), + ) +)] +#[get("/unit/{id}")] +pub(crate) async fn unit_by_id( + app: web::Data<App>, + id: web::Path<UnitId>, +) -> Result<impl Responder> { + let id = id.into_inner(); + + match Unit::from_id(&app, id).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + None => Ok(HttpResponse::NotFound().finish()), + } +} diff --git a/crates/rocie-server/src/api/set/mod.rs b/crates/rocie-server/src/api/set/mod.rs new file mode 100644 index 0000000..8a2a1df --- /dev/null +++ b/crates/rocie-server/src/api/set/mod.rs @@ -0,0 +1,10 @@ +use actix_web::web; + +pub(crate) mod product; +pub(crate) mod unit; + +pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { + cfg.service(product::register_product) + .service(product::associate_barcode) + .service(unit::register_unit); +} diff --git a/crates/rocie-server/src/api/set.rs b/crates/rocie-server/src/api/set/product.rs index 0a6af1b..355f09a 100644 --- a/crates/rocie-server/src/api/set.rs +++ b/crates/rocie-server/src/api/set/product.rs @@ -7,6 +7,7 @@ use crate::{ storage::sql::{ insert::Operations, product::{Barcode, Product, ProductId}, + unit::Unit, }, }; @@ -17,10 +18,6 @@ struct ProductStub { parent: Option<ProductId>, } -pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { - cfg.service(register_product).service(associate_barcode); -} - /// Register a product #[utoipa::path( responses( @@ -68,6 +65,11 @@ pub(crate) async fn register_product( description = "Product id not found in database", ), ( + status = FORBIDDEN, + description = "Unit used in request has not been registered yet", + body = String, + ), + ( status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String, @@ -86,6 +88,14 @@ pub(crate) async fn associate_barcode( ) -> Result<impl Responder> { let mut ops = Operations::new("associated barcode with product"); + { + let units = Unit::get_all(&app).await?; + if !units.into_iter().any(|unit| unit.id == barcode.amount.unit) { + return Ok(HttpResponse::Forbidden() + .body("The used unit has not been registered; it cannot be used.\n")); + } + } + match Product::from_id(&app, id.into_inner()).await? { Some(product) => { product.associate_barcode(barcode.into_inner(), &mut ops); diff --git a/crates/rocie-server/src/api/set/unit.rs b/crates/rocie-server/src/api/set/unit.rs new file mode 100644 index 0000000..4281e05 --- /dev/null +++ b/crates/rocie-server/src/api/set/unit.rs @@ -0,0 +1,49 @@ +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{app::App, storage::sql::{insert::Operations, unit::{Unit, UnitId}}}; + +#[derive(Deserialize, ToSchema)] +struct UnitStub { + full_name_plural: String, + full_name_singular: String, + short_name: String, + description: Option<String>, +} + +/// Register an Unit +#[utoipa::path( + responses( + ( + status = 200, + description = "Product successfully registered in database", + body = UnitId, + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = UnitStub, +)] +#[post("/unit/new")] +pub(crate) async fn register_unit( + app: web::Data<App>, + unit: web::Json<UnitStub>, +) -> Result<impl Responder> { + let mut ops = Operations::new("register unit"); + + let unit = Unit::register( + unit.full_name_singular.clone(), + unit.full_name_plural.clone(), + unit.short_name.clone(), + unit.description.clone(), + &mut ops, + ); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(unit.id)) +} diff --git a/crates/rocie-server/src/main.rs b/crates/rocie-server/src/main.rs index 453a2dc..c896c35 100644 --- a/crates/rocie-server/src/main.rs +++ b/crates/rocie-server/src/main.rs @@ -18,10 +18,13 @@ async fn main() -> Result<(), std::io::Error> { #[derive(OpenApi)] #[openapi( paths( - api::get::product_by_id, - api::get::products, - api::set::register_product, - api::set::associate_barcode + api::get::product::product_by_id, + api::get::product::products, + api::get::unit::units, + api::get::unit::unit_by_id, + api::set::product::register_product, + api::set::product::associate_barcode, + api::set::unit::register_unit, ), // security( // (), @@ -49,7 +52,7 @@ async fn main() -> Result<(), std::io::Error> { HttpServer::new(move || { App::new() - .wrap(Logger::default()) + .wrap(Logger::new(r#"%a "%r" -> %s %b ("%{Referer}i" "%{User-Agent}i" %T s)"#)) .app_data(Data::clone(&data)) .configure(api::get::register_paths) .configure(api::set::register_paths) diff --git a/crates/rocie-server/src/storage/migrate/sql/0->1.sql b/crates/rocie-server/src/storage/migrate/sql/0->1.sql index 13bc1cb..5aa497d 100644 --- a/crates/rocie-server/src/storage/migrate/sql/0->1.sql +++ b/crates/rocie-server/src/storage/migrate/sql/0->1.sql @@ -37,11 +37,15 @@ CREATE TABLE barcodes ( amount INTEGER NOT NULL, unit TEXT NOT NULL, FOREIGN KEY(product_id) REFERENCES products(id), - FOREIGN KEY(unit) REFERENCES units(name) + FOREIGN KEY(unit) REFERENCES units(id) ) STRICT; CREATE TABLE units ( - name TEXT UNIQUE NOT NULL PRIMARY KEY + id TEXT UNIQUE NOT NULL PRIMARY KEY, + full_name_singular TEXT UNIQUE NOT NULL, + full_name_plural TEXT UNIQUE NOT NULL, + short_name TEXT UNIQUE NOT NULL, + description TEXT ) STRICT; -- Encodes unit conversions: @@ -51,8 +55,8 @@ CREATE TABLE unit_conversions ( from_unit TEXT NOT NULL, to_unit TEXT NOT NULL, factor REAL NOT NULL, - FOREIGN KEY(from_unit) REFERENCES units(name), - FOREIGN KEY(to_unit) REFERENCES units(name) + FOREIGN KEY(from_unit) REFERENCES units(id), + FOREIGN KEY(to_unit) REFERENCES units(id) ) STRICT; -- Log of all the applied operations to this db. diff --git a/crates/rocie-server/src/storage/sql/get/mod.rs b/crates/rocie-server/src/storage/sql/get/mod.rs index 2268e85..fa22f81 100644 --- a/crates/rocie-server/src/storage/sql/get/mod.rs +++ b/crates/rocie-server/src/storage/sql/get/mod.rs @@ -1 +1,2 @@ pub(crate) mod product; +pub(crate) mod unit; diff --git a/crates/rocie-server/src/storage/sql/get/product/mod.rs b/crates/rocie-server/src/storage/sql/get/product/mod.rs index bcc3e32..d23297a 100644 --- a/crates/rocie-server/src/storage/sql/get/product/mod.rs +++ b/crates/rocie-server/src/storage/sql/get/product/mod.rs @@ -1,6 +1,9 @@ use crate::{ app::App, - storage::sql::product::{Product, ProductId}, + storage::sql::{ + product::{Barcode, Product, ProductId, UnitAmount}, + unit::UnitId, + }, }; use sqlx::query; @@ -40,17 +43,38 @@ impl Product { .fetch_all(&app.db) .await?; - Ok(records - .into_iter() - .map(|record| { - Self { - id: ProductId::from_db(&record.id), - name: record.name, - description: record.description, - associated_bar_codes: vec![], // todo - } - }) - .collect()) + let mut all = Vec::with_capacity(records.len()); + for record in records { + let barcodes = query!( + " + SELECT id, amount, unit + FROM barcodes + WHERE product_id = ? +", + record.id, + ) + .fetch_all(&app.db) + .await?; + + all.push(Self { + id: ProductId::from_db(&record.id), + name: record.name, + description: record.description, + associated_bar_codes: barcodes + .into_iter() + .map(|record| Barcode { + id: u32::try_from(record.id).expect("Should be strictly positive"), + amount: UnitAmount { + value: u32::try_from(record.amount) + .expect("Should be strictly positve"), + unit: UnitId::from_db(&record.unit), + }, + }) + .collect(), + }); + } + + Ok(all) } } @@ -63,8 +87,7 @@ pub(crate) mod from_id { SqlError(#[from] sqlx::Error), } - impl ResponseError for Error { - } + impl ResponseError for Error {} } pub(crate) mod get_all { @@ -76,6 +99,5 @@ pub(crate) mod get_all { SqlError(#[from] sqlx::Error), } - impl ResponseError for Error { - } + impl ResponseError for Error {} } diff --git a/crates/rocie-server/src/storage/sql/get/unit/mod.rs b/crates/rocie-server/src/storage/sql/get/unit/mod.rs new file mode 100644 index 0000000..6c2bbcc --- /dev/null +++ b/crates/rocie-server/src/storage/sql/get/unit/mod.rs @@ -0,0 +1,79 @@ +use crate::{ + app::App, + storage::sql::unit::{Unit, UnitId}, +}; + +use sqlx::query; + +impl Unit { + pub(crate) async fn get_all(app: &App) -> Result<Vec<Self>, get_all::Error> { + let records = query!( + " + SELECT id, full_name_singular, full_name_plural, short_name, description + FROM units +" + ) + .fetch_all(&app.db) + .await?; + + Ok(records + .into_iter() + .map(|record| Self { + id: UnitId::from_db(&record.id), + full_name_singular: record.full_name_singular, + full_name_plural: record.full_name_plural, + short_name: record.short_name, + description: record.description, + }) + .collect()) + } + + pub(crate) async fn from_id(app: &App, id: UnitId) -> Result<Option<Self>, from_id::Error> { + let record = query!( + " + SELECT full_name_singular, full_name_plural, short_name, description + FROM units + WHERE id = ? +", + id + ) + .fetch_optional(&app.db) + .await?; + + if let Some(record) = record { + Ok(Some(Self { + id, + full_name_singular: record.full_name_singular, + full_name_plural: record.full_name_plural, + short_name: record.short_name, + description: record.description, + })) + } else { + Ok(None) + } + } +} + +pub(crate) mod get_all { + use actix_web::ResponseError; + + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute the sql query")] + SqlError(#[from] sqlx::Error), + } + + impl ResponseError for Error {} +} + +pub(crate) mod from_id { + use actix_web::ResponseError; + + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute the sql query")] + SqlError(#[from] sqlx::Error), + } + + impl ResponseError for Error {} +} diff --git a/crates/rocie-server/src/storage/sql/insert/mod.rs b/crates/rocie-server/src/storage/sql/insert/mod.rs index 99f1e71..eec6ad2 100644 --- a/crates/rocie-server/src/storage/sql/insert/mod.rs +++ b/crates/rocie-server/src/storage/sql/insert/mod.rs @@ -8,6 +8,7 @@ use serde::{Serialize, de::DeserializeOwned}; use sqlx::{SqliteConnection, query}; pub(crate) mod product; +pub(crate) mod unit; pub(crate) trait Transactionable: Sized + std::fmt::Debug + Serialize + DeserializeOwned @@ -77,7 +78,8 @@ impl<O: Transactionable> Operations<O> { } pub(crate) mod apply { - use actix_web::ResponseError; + use actix_web::{ResponseError, http::header::HeaderValue}; + use log::error; use crate::storage::sql::insert::{Transactionable, add_operations_to_txn_log}; @@ -94,7 +96,23 @@ pub(crate) mod apply { } impl<O: Transactionable> ResponseError for Error<O> { - // TODO(@bpeetz): Actually do something with this. <2025-09-05> + fn status_code(&self) -> actix_web::http::StatusCode { + actix_web::http::StatusCode::INTERNAL_SERVER_ERROR + } + + fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { + error!("Emmiting `INTERNAL_SERVER_ERROR`: {self}"); + let mut res = + actix_web::HttpResponse::new(self.status_code()).set_body(self.to_string()); + + let mime = actix_web::mime::TEXT_PLAIN_UTF_8; + res.headers_mut().insert( + actix_web::http::header::CONTENT_TYPE, + HeaderValue::from_str(mime.to_string().as_str()).expect("Hard-coded conversion"), + ); + + res.set_body(actix_web::body::BoxBody::new(self.to_string())) + } } } diff --git a/crates/rocie-server/src/storage/sql/insert/product/mod.rs b/crates/rocie-server/src/storage/sql/insert/product/mod.rs index 562e809..b6dd604 100644 --- a/crates/rocie-server/src/storage/sql/insert/product/mod.rs +++ b/crates/rocie-server/src/storage/sql/insert/product/mod.rs @@ -115,14 +115,14 @@ impl Transactionable for Operation { pub(crate) mod undo { #[derive(thiserror::Error, Debug)] pub(crate) enum Error { - #[error("Failed to execute sql statments")] + #[error("Failed to execute undo sql statments: {0}")] SqlError(#[from] sqlx::Error), } } pub(crate) mod apply { #[derive(thiserror::Error, Debug)] pub(crate) enum Error { - #[error("Failed to execute sql statments")] + #[error("Failed to execute apply sql statments: {0}")] SqlError(#[from] sqlx::Error), } } diff --git a/crates/rocie-server/src/storage/sql/insert/unit/mod.rs b/crates/rocie-server/src/storage/sql/insert/unit/mod.rs new file mode 100644 index 0000000..ba08487 --- /dev/null +++ b/crates/rocie-server/src/storage/sql/insert/unit/mod.rs @@ -0,0 +1,110 @@ +use serde::{Deserialize, Serialize}; +use sqlx::query; +use uuid::Uuid; + +use crate::storage::sql::{insert::{Operations, Transactionable}, unit::{Unit, UnitId}}; + +#[derive(Debug, Deserialize, Serialize)] +pub(crate) enum Operation { + RegisterUnit { + id: UnitId, + full_name_singular: String, + full_name_plural: String, + short_name: String, + description: Option<String>, + }, +} + +impl Transactionable for Operation { + type ApplyError = apply::Error; + type UndoError = undo::Error; + + async fn apply(self, txn: &mut sqlx::SqliteConnection) -> Result<(), apply::Error> { + match self { + Operation::RegisterUnit { + id, + full_name_singular, + full_name_plural, + short_name, + description, + } => { + query!( + " + INSERT INTO units (id, full_name_singular, full_name_plural, short_name, description) + VALUES (?,?,?,?,?) +", + id, full_name_singular, full_name_plural, short_name, description, + ) + .execute(txn) + .await?; + } + } + Ok(()) + } + + async fn undo(self, txn: &mut sqlx::SqliteConnection) -> Result<(), undo::Error> { + match self { + Operation::RegisterUnit { + id, + full_name_singular, + full_name_plural, + short_name, + description, + } => { + query!( + " + DELETE FROM units + WHERE id = ? AND full_name_singular = ? AND full_name_plural = ? AND short_name = ? AND description = ?; +", + id, full_name_singular, full_name_plural, short_name, description, + ) + .execute(txn) + .await?; + } + } + Ok(()) + } +} + +pub(crate) mod undo { + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute undo sql statments: {0}")] + SqlError(#[from] sqlx::Error), + } +} +pub(crate) mod apply { + #[derive(thiserror::Error, Debug)] + pub(crate) enum Error { + #[error("Failed to execute apply sql statments: {0}")] + SqlError(#[from] sqlx::Error), + } +} + +impl Unit { + pub(crate) fn register( + full_name_singular: String, + full_name_plural: String, + short_name: String, + description: Option<String>, + ops: &mut Operations<Operation>, + ) -> Self { + let id = UnitId::from(Uuid::new_v4()); + + ops.push(Operation::RegisterUnit { + id, + full_name_singular: full_name_singular.clone(), + full_name_plural: full_name_plural.clone(), + short_name: short_name.clone(), + description: description.clone(), + }); + + Self { + id, + full_name_singular, + full_name_plural, + short_name, + description, + } + } +} diff --git a/crates/rocie-server/src/storage/sql/mod.rs b/crates/rocie-server/src/storage/sql/mod.rs index 871ae3b..f5ad88a 100644 --- a/crates/rocie-server/src/storage/sql/mod.rs +++ b/crates/rocie-server/src/storage/sql/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod insert; // Types pub(crate) mod product; +pub(crate) mod unit; diff --git a/crates/rocie-server/src/storage/sql/product.rs b/crates/rocie-server/src/storage/sql/product.rs index e0216dd..e2a4f0d 100644 --- a/crates/rocie-server/src/storage/sql/product.rs +++ b/crates/rocie-server/src/storage/sql/product.rs @@ -5,6 +5,8 @@ use sqlx::{Database, Encode, Type}; use utoipa::ToSchema; use uuid::Uuid; +use crate::storage::sql::unit::{Unit, UnitId}; + #[derive(Clone, ToSchema, Serialize, Deserialize)] pub(crate) struct Product { pub(crate) id: ProductId, @@ -59,12 +61,14 @@ where #[derive(ToSchema, Debug, Clone, Serialize, Deserialize)] pub(crate) struct Barcode { + #[schema(format = Int64, minimum = 0)] pub(crate) id: u32, pub(crate) amount: UnitAmount, } #[derive(ToSchema, Debug, Clone, Serialize, Deserialize)] pub(crate) struct UnitAmount { + #[schema(format = Int64, minimum = 0)] pub(crate) value: u32, - pub(crate) unit: String, + pub(crate) unit: UnitId, } diff --git a/crates/rocie-server/src/storage/sql/unit.rs b/crates/rocie-server/src/storage/sql/unit.rs new file mode 100644 index 0000000..fe00b1b --- /dev/null +++ b/crates/rocie-server/src/storage/sql/unit.rs @@ -0,0 +1,59 @@ +use std::{fmt::Display, str::FromStr}; + +use serde::{Deserialize, Serialize}; +use sqlx::{Database, Encode, Type}; +use utoipa::ToSchema; +use uuid::Uuid; + +#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)] +pub(crate) struct Unit { + pub(crate) id: UnitId, + pub(crate) full_name_singular: String, + pub(crate) full_name_plural: String, + pub(crate) short_name: String, + pub(crate) description: Option<String>, +} + +#[derive( + Deserialize, Serialize, Debug, Default, ToSchema, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, +)] +pub(crate) struct UnitId(Uuid); + +impl UnitId { + pub(crate) fn from_db(id: &str) -> UnitId { + Self(Uuid::from_str(id).expect("We put an uuid into the db, it should also go out again")) + } +} + +impl Display for UnitId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl From<Uuid> for UnitId { + fn from(value: Uuid) -> Self { + Self(value) + } +} + +impl<'q, DB: Database> Encode<'q, DB> for UnitId +where + String: Encode<'q, DB>, +{ + fn encode_by_ref( + &self, + buf: &mut <DB as Database>::ArgumentBuffer<'q>, + ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { + let inner = self.0.to_string(); + Encode::<DB>::encode_by_ref(&inner, buf) + } +} +impl<DB: Database> Type<DB> for UnitId +where + String: Type<DB>, +{ + fn type_info() -> DB::TypeInfo { + <String as Type<DB>>::type_info() + } +} |
