From 1c09b0eb5db415985bfefb52786dbe48d757665e Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Sat, 6 Sep 2025 18:31:40 +0200 Subject: feat: Provide basic barcode handling support --- crates/rocie-server/src/api/get.rs | 48 --------- crates/rocie-server/src/api/get/mod.rs | 11 +++ crates/rocie-server/src/api/get/product.rs | 44 +++++++++ crates/rocie-server/src/api/get/unit.rs | 41 ++++++++ crates/rocie-server/src/api/set.rs | 99 ------------------- crates/rocie-server/src/api/set/mod.rs | 10 ++ crates/rocie-server/src/api/set/product.rs | 109 ++++++++++++++++++++ crates/rocie-server/src/api/set/unit.rs | 49 +++++++++ crates/rocie-server/src/main.rs | 13 ++- .../rocie-server/src/storage/migrate/sql/0->1.sql | 12 ++- crates/rocie-server/src/storage/sql/get/mod.rs | 1 + .../src/storage/sql/get/product/mod.rs | 54 +++++++--- .../rocie-server/src/storage/sql/get/unit/mod.rs | 79 +++++++++++++++ crates/rocie-server/src/storage/sql/insert/mod.rs | 22 ++++- .../src/storage/sql/insert/product/mod.rs | 4 +- .../src/storage/sql/insert/unit/mod.rs | 110 +++++++++++++++++++++ crates/rocie-server/src/storage/sql/mod.rs | 1 + crates/rocie-server/src/storage/sql/product.rs | 6 +- crates/rocie-server/src/storage/sql/unit.rs | 59 +++++++++++ 19 files changed, 595 insertions(+), 177 deletions(-) delete mode 100644 crates/rocie-server/src/api/get.rs create mode 100644 crates/rocie-server/src/api/get/mod.rs create mode 100644 crates/rocie-server/src/api/get/product.rs create mode 100644 crates/rocie-server/src/api/get/unit.rs delete mode 100644 crates/rocie-server/src/api/set.rs create mode 100644 crates/rocie-server/src/api/set/mod.rs create mode 100644 crates/rocie-server/src/api/set/product.rs create mode 100644 crates/rocie-server/src/api/set/unit.rs create mode 100644 crates/rocie-server/src/storage/sql/get/unit/mod.rs create mode 100644 crates/rocie-server/src/storage/sql/insert/unit/mod.rs create mode 100644 crates/rocie-server/src/storage/sql/unit.rs (limited to 'crates/rocie-server/src') diff --git a/crates/rocie-server/src/api/get.rs b/crates/rocie-server/src/api/get.rs deleted file mode 100644 index 94015cf..0000000 --- a/crates/rocie-server/src/api/get.rs +++ /dev/null @@ -1,48 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, get, web}; - -use crate::{ - app::App, - 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( - (status = OK, description = "Product found from database", body = Product), - (status = NOT_FOUND, description = "Product not found in database"), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), - params( - ("id" = ProductId, description = "Product id" ), - ) -)] -#[get("/product/{id}")] -pub(crate) async fn product_by_id( - app: web::Data, - id: web::Path, -) -> Result { - let id = id.into_inner(); - - match Product::from_id(&app, id).await? { - Some(product) => Ok(HttpResponse::Ok().json(product)), - None => Ok(HttpResponse::NotFound().finish()), - } -} - -/// Return all registered products -#[utoipa::path( - responses( - (status = OK, description = "All products founds", body = Vec), - (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) - ), -)] -#[get("/products/")] -pub(crate) async fn products(app: web::Data) -> Result { - let all = Product::get_all(&app).await?; - - Ok(HttpResponse::Ok().json(all)) -} 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/product.rs b/crates/rocie-server/src/api/get/product.rs new file mode 100644 index 0000000..c496777 --- /dev/null +++ b/crates/rocie-server/src/api/get/product.rs @@ -0,0 +1,44 @@ +use actix_web::{HttpResponse, Responder, Result, get, web}; + +use crate::{ + app::App, + storage::sql::product::{Product, ProductId}, +}; + +/// Get Product by id +#[utoipa::path( + responses( + (status = OK, description = "Product found from database", body = Product), + (status = NOT_FOUND, description = "Product not found in database"), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), + params( + ("id" = ProductId, description = "Product id" ), + ) +)] +#[get("/product/{id}")] +pub(crate) async fn product_by_id( + app: web::Data, + id: web::Path, +) -> Result { + let id = id.into_inner(); + + match Product::from_id(&app, id).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Return all registered products +#[utoipa::path( + responses( + (status = OK, description = "All products founds", body = Vec), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), +)] +#[get("/products/")] +pub(crate) async fn products(app: web::Data) -> Result { + let all = Product::get_all(&app).await?; + + Ok(HttpResponse::Ok().json(all)) +} 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), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), +)] +#[get("/units/")] +pub(crate) async fn units(app: web::Data) -> Result { + 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, + id: web::Path, +) -> Result { + 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.rs b/crates/rocie-server/src/api/set.rs deleted file mode 100644 index 0a6af1b..0000000 --- a/crates/rocie-server/src/api/set.rs +++ /dev/null @@ -1,99 +0,0 @@ -use actix_web::{HttpResponse, Responder, Result, post, web}; -use serde::Deserialize; -use utoipa::ToSchema; - -use crate::{ - app::App, - storage::sql::{ - insert::Operations, - product::{Barcode, Product, ProductId}, - }, -}; - -#[derive(Deserialize, ToSchema)] -struct ProductStub { - name: String, - description: Option, - parent: Option, -} - -pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { - cfg.service(register_product).service(associate_barcode); -} - -/// Register a product -#[utoipa::path( - responses( - ( - status = 200, - description = "Product successfully registered in database", - body = ProductId, - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - request_body = ProductStub, -)] -#[post("/product/new")] -pub(crate) async fn register_product( - app: web::Data, - product_stub: web::Json, -) -> Result { - let mut ops = Operations::new("register product"); - - let product = Product::register( - product_stub.name.clone(), - product_stub.description.clone(), - product_stub.parent, - &mut ops, - ); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().json(product.id)) -} - -/// Associate a barcode with a product -#[utoipa::path( - responses( - ( - status = OK, - description = "Barcode successfully associated with product", - ), - ( - status = NOT_FOUND, - description = "Product id not found in database", - ), - ( - status = INTERNAL_SERVER_ERROR, - description = "Server encountered error", - body = String, - ) - ), - params ( - ("id" = ProductId, description = "The id of the product to associated the barcode with"), - ), - request_body = Barcode, -)] -#[post("/product/{id}/associate")] -pub(crate) async fn associate_barcode( - app: web::Data, - id: web::Path, - barcode: web::Json, -) -> Result { - let mut ops = Operations::new("associated barcode with product"); - - match Product::from_id(&app, id.into_inner()).await? { - Some(product) => { - product.associate_barcode(barcode.into_inner(), &mut ops); - - ops.apply(&app).await?; - - Ok(HttpResponse::Ok().finish()) - } - 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/product.rs b/crates/rocie-server/src/api/set/product.rs new file mode 100644 index 0000000..355f09a --- /dev/null +++ b/crates/rocie-server/src/api/set/product.rs @@ -0,0 +1,109 @@ +use actix_web::{HttpResponse, Responder, Result, post, web}; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::{ + app::App, + storage::sql::{ + insert::Operations, + product::{Barcode, Product, ProductId}, + unit::Unit, + }, +}; + +#[derive(Deserialize, ToSchema)] +struct ProductStub { + name: String, + description: Option, + parent: Option, +} + +/// Register a product +#[utoipa::path( + responses( + ( + status = 200, + description = "Product successfully registered in database", + body = ProductId, + ), + ( + status = INTERNAL_SERVER_ERROR, + description = "Server encountered error", + body = String, + ) + ), + request_body = ProductStub, +)] +#[post("/product/new")] +pub(crate) async fn register_product( + app: web::Data, + product_stub: web::Json, +) -> Result { + let mut ops = Operations::new("register product"); + + let product = Product::register( + product_stub.name.clone(), + product_stub.description.clone(), + product_stub.parent, + &mut ops, + ); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().json(product.id)) +} + +/// Associate a barcode with a product +#[utoipa::path( + responses( + ( + status = OK, + description = "Barcode successfully associated with product", + ), + ( + status = NOT_FOUND, + 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, + ) + ), + params ( + ("id" = ProductId, description = "The id of the product to associated the barcode with"), + ), + request_body = Barcode, +)] +#[post("/product/{id}/associate")] +pub(crate) async fn associate_barcode( + app: web::Data, + id: web::Path, + barcode: web::Json, +) -> Result { + 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); + + ops.apply(&app).await?; + + Ok(HttpResponse::Ok().finish()) + } + None => Ok(HttpResponse::NotFound().finish()), + } +} 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, +} + +/// 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, + unit: web::Json, +) -> Result { + 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, 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, 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 Operations { } 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 ResponseError for Error { - // 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 { + 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, + }, +} + +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, + ops: &mut Operations, + ) -> 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, +} + +#[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 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 ::ArgumentBuffer<'q>, + ) -> Result { + let inner = self.0.to_string(); + Encode::::encode_by_ref(&inner, buf) + } +} +impl Type for UnitId +where + String: Type, +{ + fn type_info() -> DB::TypeInfo { + >::type_info() + } +} -- cgit 1.4.1