diff options
Diffstat (limited to 'crates')
44 files changed, 1409 insertions, 130 deletions
diff --git a/crates/rocie-cli/src/cli.rs b/crates/rocie-cli/src/cli.rs index ac220d5..3f2662b 100644 --- a/crates/rocie-cli/src/cli.rs +++ b/crates/rocie-cli/src/cli.rs @@ -14,21 +14,62 @@ pub(crate) enum Command { #[command(subcommand)] command: ProductCommand, }, + + /// Deal with products + Unit { + #[command(subcommand)] + command: UnitCommand, + }, +} + +#[derive(Subcommand)] +pub(crate) enum UnitCommand { + /// Register a new unit + Register { + /// The full singular name of the new unit + /// E.g.: 1 kilogram + #[arg(short = 's', long)] + full_name_singular: String, + + /// The full plural name of the new unit + /// E.g.: 5 kilograms + #[arg(short = 'p', long)] + full_name_plural: String, + + /// The short name of the new unit (short names have no plural) + /// E.g.: 1 kg or 5 kg + #[arg(short = 'n', long)] + short_name: String, + + /// Optional description of the new unit + #[arg(short, long)] + description: Option<String>, + }, + + /// Fetch an unit based on id + GetById { + /// The id of the unit + #[arg(short, long)] + id: Uuid, + }, + + /// List all available units + List {}, } #[derive(Subcommand)] pub(crate) enum ProductCommand { /// Register a new product Register { - /// The name of new the product + /// The name of the new product #[arg(short, long)] name: String, - /// Optional description of the new the product + /// Optional description of the new product #[arg(short, long)] description: Option<String>, - /// Optional parent of the new the product + /// Optional parent of the new product #[arg(short, long)] parent: Option<Uuid>, }, @@ -48,7 +89,7 @@ pub(crate) enum ProductCommand { /// The unit the amount value is in #[arg(short = 'u', long)] - amount_unit: String, + amount_unit_id: Uuid, }, /// Get a already registered product by id diff --git a/crates/rocie-cli/src/handle/mod.rs b/crates/rocie-cli/src/handle/mod.rs new file mode 100644 index 0000000..1d322f8 --- /dev/null +++ b/crates/rocie-cli/src/handle/mod.rs @@ -0,0 +1,148 @@ +use crate::cli::{ProductCommand, UnitCommand}; + +use anyhow::{Context, Result}; +use rocie_client::{ + apis::{ + api_get_product_api::{product_by_id, products}, + api_get_unit_api::{unit_by_id, units}, + api_set_product_api::{associate_barcode, register_product}, + api_set_unit_api::register_unit, + configuration::Configuration, + }, + models::{Barcode, UnitAmount, UnitStub}, +}; + +pub(crate) async fn product(config: &Configuration, command: ProductCommand) -> Result<()> { + match command { + ProductCommand::Register { + name, + description, + parent, + } => { + let new_id = register_product( + config, + rocie_client::models::ProductStub { + description: Some(description), // TODO: Fix the duplicate option + name, + parent, + }, + ) + .await + .context("Failed to register new product")?; + + println!("Registered new product with id: {new_id}"); + } + + ProductCommand::Get { id } => { + let product = product_by_id(config, id.to_string().as_str()) + .await + .with_context(|| format!("Failed to get product with id: {id}"))?; + + println!("{product:#?}"); + } + + ProductCommand::AssociateBarcode { + product_id, + barcode_number, + amount_value, + amount_unit_id, + } => associate_barcode( + config, + product_id.to_string().as_str(), + Barcode { + id: i64::from(barcode_number), + amount: Box::new(UnitAmount { + unit: amount_unit_id, + value: i64::from(amount_value), + }), + }, + ) + .await + .context("Failed to associated barcode")?, + + ProductCommand::List {} => { + let all = products(config) + .await + .context("Failed to get all products")?; + + for product in all { + print!("{}: {}", product.name, product.id); + + if let Some(description) = product + .description + .expect("Superflous Option wrapping in api") + { + println!(" ({description})"); + } else { + println!(); + } + + for barcode in product.associated_bar_codes { + let unit = unit_by_id(config, barcode.amount.unit.to_string().as_str()).await?; + + println!( + " - {}: {} {}", + barcode.id, + barcode.amount.value, + if barcode.amount.value == 1 { + unit.full_name_singular + } else { + unit.full_name_plural + } + ); + } + } + } + } + Ok(()) +} + +pub(crate) async fn unit(config: &Configuration, command: UnitCommand) -> Result<()> { + match command { + UnitCommand::Register { + full_name_singular, + full_name_plural, + short_name, + description, + } => { + let new_id = register_unit( + config, + UnitStub { + description: Some(description), + full_name_plural, + full_name_singular, + short_name, + }, + ) + .await + .context("Failed to register unit")?; + println!("Registered new unit with id: {new_id}"); + } + UnitCommand::List {} => { + let all = units(config).await.context("Failed to get all products")?; + + for unit in all { + print!("{}: {}", unit.full_name_singular, unit.id); + + if let Some(description) = + unit.description.expect("Superflous Option wrapping in api") + { + println!(" ({description})"); + } else { + println!(); + } + } + } + UnitCommand::GetById { id } => { + let unit = unit_by_id(config, id.to_string().as_str()) + .await + .context("Failed to find unit")?; + println!( + "Unit: {} ({},{},{})", + unit.id, unit.full_name_singular, unit.full_name_plural, unit.short_name + ); + } + } + + Ok(()) +} diff --git a/crates/rocie-cli/src/main.rs b/crates/rocie-cli/src/main.rs index f0192d4..ef81ad9 100644 --- a/crates/rocie-cli/src/main.rs +++ b/crates/rocie-cli/src/main.rs @@ -1,17 +1,11 @@ -use anyhow::{Context, Result}; +use anyhow::Result; use clap::Parser; -use rocie_client::{ - apis::{ - api_get_api::{product_by_id, products}, - api_set_api::{associate_barcode, register_product}, - configuration::Configuration, - }, - models::{Barcode, UnitAmount}, -}; +use rocie_client::apis::configuration::Configuration; -use crate::cli::{CliArgs, Command, ProductCommand}; +use crate::cli::{CliArgs, Command}; mod cli; +mod handle; #[tokio::main] async fn main() -> Result<()> { @@ -21,62 +15,8 @@ async fn main() -> Result<()> { "http://127.0.0.1:8080".clone_into(&mut config.base_path); match args.command { - Command::Product { command } => { - match command { - ProductCommand::Register { - name, - description, - parent, - } => { - let new_id = register_product( - &config, - rocie_client::models::ProductStub { - description: Some(description), // TODO: Fix - name, - parent, - }, - ) - .await - .context("Failed to register new product")?; - - println!("Registered new product with id: {new_id}"); - } - ProductCommand::Get { id } => { - let product = product_by_id(&config, id.to_string().as_str()) - .await - .with_context(|| format!("Failed to get product with id: {id}"))?; - - println!("{product:#?}"); - } - ProductCommand::AssociateBarcode { - product_id, - barcode_number, - amount_value, - amount_unit, - } => associate_barcode( - &config, - product_id.to_string().as_str(), - Barcode { - amount: Box::new(UnitAmount { - unit: amount_unit, - value: amount_value as i32, - }), - id: barcode_number as i32, - }, - ) - .await - .context("Failed to associated barcode")?, - ProductCommand::List {} => { - let all = products(&config) - .await - .context("Failed to get all products")?; - - for product in all { - println!("{}: {}", product.name, product.id); - } - } - } - } + Command::Product { command } => handle::product(&config, command).await?, + Command::Unit { command } => handle::unit(&config, command).await?, } Ok(()) diff --git a/crates/rocie-client/.openapi-generator/FILES b/crates/rocie-client/.openapi-generator/FILES index f9b70e6..01b279c 100644 --- a/crates/rocie-client/.openapi-generator/FILES +++ b/crates/rocie-client/.openapi-generator/FILES @@ -1,15 +1,21 @@ .gitignore .travis.yml README.md -docs/ApiGetApi.md -docs/ApiSetApi.md +docs/ApiGetProductApi.md +docs/ApiGetUnitApi.md +docs/ApiSetProductApi.md +docs/ApiSetUnitApi.md docs/Barcode.md docs/Product.md docs/ProductStub.md +docs/Unit.md docs/UnitAmount.md +docs/UnitStub.md git_push.sh -src/apis/api_get_api.rs -src/apis/api_set_api.rs +src/apis/api_get_product_api.rs +src/apis/api_get_unit_api.rs +src/apis/api_set_product_api.rs +src/apis/api_set_unit_api.rs src/apis/configuration.rs src/apis/mod.rs src/lib.rs @@ -17,4 +23,6 @@ src/models/barcode.rs src/models/mod.rs src/models/product.rs src/models/product_stub.rs +src/models/unit.rs src/models/unit_amount.rs +src/models/unit_stub.rs diff --git a/crates/rocie-client/README.md b/crates/rocie-client/README.md index 7649325..26bacb1 100644 --- a/crates/rocie-client/README.md +++ b/crates/rocie-client/README.md @@ -26,10 +26,13 @@ All URIs are relative to *http://localhost* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*ApiGetApi* | [**product_by_id**](docs/ApiGetApi.md#product_by_id) | **GET** /product/{id} | Get Product by id -*ApiGetApi* | [**products**](docs/ApiGetApi.md#products) | **GET** /products/ | Return all registered products -*ApiSetApi* | [**associate_barcode**](docs/ApiSetApi.md#associate_barcode) | **POST** /product/{id}/associate | Associate a barcode with a product -*ApiSetApi* | [**register_product**](docs/ApiSetApi.md#register_product) | **POST** /product/new | Register a product +*ApiGetProductApi* | [**product_by_id**](docs/ApiGetProductApi.md#product_by_id) | **GET** /product/{id} | Get Product by id +*ApiGetProductApi* | [**products**](docs/ApiGetProductApi.md#products) | **GET** /products/ | Return all registered products +*ApiGetUnitApi* | [**unit_by_id**](docs/ApiGetUnitApi.md#unit_by_id) | **GET** /unit/{id} | Get Unit by id +*ApiGetUnitApi* | [**units**](docs/ApiGetUnitApi.md#units) | **GET** /units/ | Return all registered units +*ApiSetProductApi* | [**associate_barcode**](docs/ApiSetProductApi.md#associate_barcode) | **POST** /product/{id}/associate | Associate a barcode with a product +*ApiSetProductApi* | [**register_product**](docs/ApiSetProductApi.md#register_product) | **POST** /product/new | Register a product +*ApiSetUnitApi* | [**register_unit**](docs/ApiSetUnitApi.md#register_unit) | **POST** /unit/new | Register an Unit ## Documentation For Models @@ -37,7 +40,9 @@ Class | Method | HTTP request | Description - [Barcode](docs/Barcode.md) - [Product](docs/Product.md) - [ProductStub](docs/ProductStub.md) + - [Unit](docs/Unit.md) - [UnitAmount](docs/UnitAmount.md) + - [UnitStub](docs/UnitStub.md) To get access to the crate's generated documentation, use: diff --git a/crates/rocie-client/docs/ApiGetApi.md b/crates/rocie-client/docs/ApiGetApi.md index f2df94c..1ecfb75 100644 --- a/crates/rocie-client/docs/ApiGetApi.md +++ b/crates/rocie-client/docs/ApiGetApi.md @@ -32,7 +32,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined -- **Accept**: application/json +- **Accept**: application/json, text/plain [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -57,7 +57,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined -- **Accept**: application/json +- **Accept**: application/json, text/plain [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/crates/rocie-client/docs/ApiGetProductApi.md b/crates/rocie-client/docs/ApiGetProductApi.md new file mode 100644 index 0000000..58955c6 --- /dev/null +++ b/crates/rocie-client/docs/ApiGetProductApi.md @@ -0,0 +1,63 @@ +# \ApiGetProductApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**product_by_id**](ApiGetProductApi.md#product_by_id) | **GET** /product/{id} | Get Product by id +[**products**](ApiGetProductApi.md#products) | **GET** /products/ | Return all registered products + + + +## product_by_id + +> models::Product product_by_id(id) +Get Product by id + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **uuid::Uuid** | Product id | [required] | + +### Return type + +[**models::Product**](Product.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## products + +> Vec<models::Product> products() +Return all registered products + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec<models::Product>**](Product.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/crates/rocie-client/docs/ApiGetUnitApi.md b/crates/rocie-client/docs/ApiGetUnitApi.md new file mode 100644 index 0000000..3ac44c0 --- /dev/null +++ b/crates/rocie-client/docs/ApiGetUnitApi.md @@ -0,0 +1,63 @@ +# \ApiGetUnitApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**unit_by_id**](ApiGetUnitApi.md#unit_by_id) | **GET** /unit/{id} | Get Unit by id +[**units**](ApiGetUnitApi.md#units) | **GET** /units/ | Return all registered units + + + +## unit_by_id + +> models::Unit unit_by_id(id) +Get Unit by id + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **uuid::Uuid** | Unit id | [required] | + +### Return type + +[**models::Unit**](Unit.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## units + +> Vec<models::Unit> units() +Return all registered units + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec<models::Unit>**](Unit.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/crates/rocie-client/docs/ApiSetApi.md b/crates/rocie-client/docs/ApiSetApi.md index 87f88b8..6129e50 100644 --- a/crates/rocie-client/docs/ApiSetApi.md +++ b/crates/rocie-client/docs/ApiSetApi.md @@ -33,7 +33,7 @@ No authorization required ### HTTP request headers - **Content-Type**: application/json -- **Accept**: Not defined +- **Accept**: text/plain [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -61,7 +61,7 @@ No authorization required ### HTTP request headers - **Content-Type**: application/json -- **Accept**: application/json +- **Accept**: application/json, text/plain [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/crates/rocie-client/docs/ApiSetProductApi.md b/crates/rocie-client/docs/ApiSetProductApi.md new file mode 100644 index 0000000..6166887 --- /dev/null +++ b/crates/rocie-client/docs/ApiSetProductApi.md @@ -0,0 +1,67 @@ +# \ApiSetProductApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**associate_barcode**](ApiSetProductApi.md#associate_barcode) | **POST** /product/{id}/associate | Associate a barcode with a product +[**register_product**](ApiSetProductApi.md#register_product) | **POST** /product/new | Register a product + + + +## associate_barcode + +> associate_barcode(id, barcode) +Associate a barcode with a product + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **uuid::Uuid** | The id of the product to associated the barcode with | [required] | +**barcode** | [**Barcode**](Barcode.md) | | [required] | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## register_product + +> uuid::Uuid register_product(product_stub) +Register a product + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**product_stub** | [**ProductStub**](ProductStub.md) | | [required] | + +### Return type + +[**uuid::Uuid**](uuid::Uuid.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/crates/rocie-client/docs/ApiSetUnitApi.md b/crates/rocie-client/docs/ApiSetUnitApi.md new file mode 100644 index 0000000..6d6d397 --- /dev/null +++ b/crates/rocie-client/docs/ApiSetUnitApi.md @@ -0,0 +1,37 @@ +# \ApiSetUnitApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**register_unit**](ApiSetUnitApi.md#register_unit) | **POST** /unit/new | Register an Unit + + + +## register_unit + +> uuid::Uuid register_unit(unit_stub) +Register an Unit + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**unit_stub** | [**UnitStub**](UnitStub.md) | | [required] | + +### Return type + +[**uuid::Uuid**](uuid::Uuid.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/crates/rocie-client/docs/Barcode.md b/crates/rocie-client/docs/Barcode.md index 7e6f4fb..d9734fa 100644 --- a/crates/rocie-client/docs/Barcode.md +++ b/crates/rocie-client/docs/Barcode.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **amount** | [**models::UnitAmount**](UnitAmount.md) | | -**id** | **i32** | | +**id** | **i64** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/crates/rocie-client/docs/Unit.md b/crates/rocie-client/docs/Unit.md new file mode 100644 index 0000000..9fb95a5 --- /dev/null +++ b/crates/rocie-client/docs/Unit.md @@ -0,0 +1,15 @@ +# Unit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**description** | Option<**String**> | | [optional] +**full_name_plural** | **String** | | +**full_name_singular** | **String** | | +**id** | [**uuid::Uuid**](uuid::Uuid.md) | | +**short_name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/crates/rocie-client/docs/UnitAmount.md b/crates/rocie-client/docs/UnitAmount.md index 39b2264..f0c1b5f 100644 --- a/crates/rocie-client/docs/UnitAmount.md +++ b/crates/rocie-client/docs/UnitAmount.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**unit** | **String** | | -**value** | **i32** | | +**unit** | [**uuid::Uuid**](uuid::Uuid.md) | | +**value** | **i64** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/crates/rocie-client/docs/UnitStub.md b/crates/rocie-client/docs/UnitStub.md new file mode 100644 index 0000000..62ab220 --- /dev/null +++ b/crates/rocie-client/docs/UnitStub.md @@ -0,0 +1,14 @@ +# UnitStub + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**description** | Option<**String**> | | [optional] +**full_name_plural** | **String** | | +**full_name_singular** | **String** | | +**short_name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/crates/rocie-client/src/apis/api_get_api.rs b/crates/rocie-client/src/apis/api_get_api.rs index 3217717..a8f4c17 100644 --- a/crates/rocie-client/src/apis/api_get_api.rs +++ b/crates/rocie-client/src/apis/api_get_api.rs @@ -20,6 +20,7 @@ use super::{Error, configuration, ContentType}; #[serde(untagged)] pub enum ProductByIdError { Status404(), + Status500(String), UnknownValue(serde_json::Value), } @@ -27,6 +28,7 @@ pub enum ProductByIdError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ProductsError { + Status500(String), UnknownValue(serde_json::Value), } diff --git a/crates/rocie-client/src/apis/api_get_product_api.rs b/crates/rocie-client/src/apis/api_get_product_api.rs new file mode 100644 index 0000000..a8f4c17 --- /dev/null +++ b/crates/rocie-client/src/apis/api_get_product_api.rs @@ -0,0 +1,105 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`product_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProductByIdError { + Status404(), + Status500(String), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`products`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProductsError { + Status500(String), + UnknownValue(serde_json::Value), +} + + +pub async fn product_by_id(configuration: &configuration::Configuration, id: &str) -> Result<models::Product, Error<ProductByIdError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_id = id; + + let uri_str = format!("{}/product/{id}", configuration.base_path, id=crate::apis::urlencode(p_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Product`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Product`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<ProductByIdError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn products(configuration: &configuration::Configuration, ) -> Result<Vec<models::Product>, Error<ProductsError>> { + + let uri_str = format!("{}/products/", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::Product>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::Product>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<ProductsError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/crates/rocie-client/src/apis/api_get_unit_api.rs b/crates/rocie-client/src/apis/api_get_unit_api.rs new file mode 100644 index 0000000..5895652 --- /dev/null +++ b/crates/rocie-client/src/apis/api_get_unit_api.rs @@ -0,0 +1,105 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`unit_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UnitByIdError { + Status404(), + Status500(String), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`units`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UnitsError { + Status500(String), + UnknownValue(serde_json::Value), +} + + +pub async fn unit_by_id(configuration: &configuration::Configuration, id: &str) -> Result<models::Unit, Error<UnitByIdError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_id = id; + + let uri_str = format!("{}/unit/{id}", configuration.base_path, id=crate::apis::urlencode(p_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Unit`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Unit`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<UnitByIdError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn units(configuration: &configuration::Configuration, ) -> Result<Vec<models::Unit>, Error<UnitsError>> { + + let uri_str = format!("{}/units/", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::Unit>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::Unit>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<UnitsError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/crates/rocie-client/src/apis/api_set_api.rs b/crates/rocie-client/src/apis/api_set_api.rs index 7c0c414..81f029e 100644 --- a/crates/rocie-client/src/apis/api_set_api.rs +++ b/crates/rocie-client/src/apis/api_set_api.rs @@ -19,6 +19,9 @@ use super::{Error, configuration, ContentType}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum AssociateBarcodeError { + Status403(), + Status404(), + Status500(String), UnknownValue(serde_json::Value), } @@ -26,6 +29,7 @@ pub enum AssociateBarcodeError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RegisterProductError { + Status500(String), UnknownValue(serde_json::Value), } diff --git a/crates/rocie-client/src/apis/api_set_product_api.rs b/crates/rocie-client/src/apis/api_set_product_api.rs new file mode 100644 index 0000000..0d2679b --- /dev/null +++ b/crates/rocie-client/src/apis/api_set_product_api.rs @@ -0,0 +1,100 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`associate_barcode`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AssociateBarcodeError { + Status403(String), + Status404(), + Status500(String), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`register_product`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RegisterProductError { + Status500(String), + UnknownValue(serde_json::Value), +} + + +pub async fn associate_barcode(configuration: &configuration::Configuration, id: &str, barcode: models::Barcode) -> Result<(), Error<AssociateBarcodeError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_id = id; + let p_barcode = barcode; + + let uri_str = format!("{}/product/{id}/associate", configuration.base_path, id=crate::apis::urlencode(p_id)); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + req_builder = req_builder.json(&p_barcode); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + + if !status.is_client_error() && !status.is_server_error() { + Ok(()) + } else { + let content = resp.text().await?; + let entity: Option<AssociateBarcodeError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn register_product(configuration: &configuration::Configuration, product_stub: models::ProductStub) -> Result<uuid::Uuid, Error<RegisterProductError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_product_stub = product_stub; + + let uri_str = format!("{}/product/new", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + req_builder = req_builder.json(&p_product_stub); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `uuid::Uuid`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `uuid::Uuid`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<RegisterProductError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/crates/rocie-client/src/apis/api_set_unit_api.rs b/crates/rocie-client/src/apis/api_set_unit_api.rs new file mode 100644 index 0000000..e894fc3 --- /dev/null +++ b/crates/rocie-client/src/apis/api_set_unit_api.rs @@ -0,0 +1,63 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`register_unit`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RegisterUnitError { + Status500(String), + UnknownValue(serde_json::Value), +} + + +pub async fn register_unit(configuration: &configuration::Configuration, unit_stub: models::UnitStub) -> Result<uuid::Uuid, Error<RegisterUnitError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_unit_stub = unit_stub; + + let uri_str = format!("{}/unit/new", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + req_builder = req_builder.json(&p_unit_stub); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `uuid::Uuid`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `uuid::Uuid`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<RegisterUnitError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/crates/rocie-client/src/apis/mod.rs b/crates/rocie-client/src/apis/mod.rs index c3f990f..7daca17 100644 --- a/crates/rocie-client/src/apis/mod.rs +++ b/crates/rocie-client/src/apis/mod.rs @@ -111,7 +111,9 @@ impl From<&str> for ContentType { } } -pub mod api_get_api; -pub mod api_set_api; +pub mod api_get_product_api; +pub mod api_get_unit_api; +pub mod api_set_product_api; +pub mod api_set_unit_api; pub mod configuration; diff --git a/crates/rocie-client/src/models/barcode.rs b/crates/rocie-client/src/models/barcode.rs index 7690be2..2b1759a 100644 --- a/crates/rocie-client/src/models/barcode.rs +++ b/crates/rocie-client/src/models/barcode.rs @@ -16,11 +16,11 @@ pub struct Barcode { #[serde(rename = "amount")] pub amount: Box<models::UnitAmount>, #[serde(rename = "id")] - pub id: i32, + pub id: i64, } impl Barcode { - pub fn new(amount: models::UnitAmount, id: i32) -> Barcode { + pub fn new(amount: models::UnitAmount, id: i64) -> Barcode { Barcode { amount: Box::new(amount), id, diff --git a/crates/rocie-client/src/models/mod.rs b/crates/rocie-client/src/models/mod.rs index 6c96c01..42fecc5 100644 --- a/crates/rocie-client/src/models/mod.rs +++ b/crates/rocie-client/src/models/mod.rs @@ -4,5 +4,9 @@ pub mod product; pub use self::product::Product; pub mod product_stub; pub use self::product_stub::ProductStub; +pub mod unit; +pub use self::unit::Unit; pub mod unit_amount; pub use self::unit_amount::UnitAmount; +pub mod unit_stub; +pub use self::unit_stub::UnitStub; diff --git a/crates/rocie-client/src/models/unit.rs b/crates/rocie-client/src/models/unit.rs new file mode 100644 index 0000000..95ec588 --- /dev/null +++ b/crates/rocie-client/src/models/unit.rs @@ -0,0 +1,39 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Unit { + #[serde(rename = "description", default, with = "::serde_with::rust::double_option", skip_serializing_if = "Option::is_none")] + pub description: Option<Option<String>>, + #[serde(rename = "full_name_plural")] + pub full_name_plural: String, + #[serde(rename = "full_name_singular")] + pub full_name_singular: String, + #[serde(rename = "id")] + pub id: uuid::Uuid, + #[serde(rename = "short_name")] + pub short_name: String, +} + +impl Unit { + pub fn new(full_name_plural: String, full_name_singular: String, id: uuid::Uuid, short_name: String) -> Unit { + Unit { + description: None, + full_name_plural, + full_name_singular, + id, + short_name, + } + } +} + diff --git a/crates/rocie-client/src/models/unit_amount.rs b/crates/rocie-client/src/models/unit_amount.rs index 038adb0..3ab482c 100644 --- a/crates/rocie-client/src/models/unit_amount.rs +++ b/crates/rocie-client/src/models/unit_amount.rs @@ -14,13 +14,13 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UnitAmount { #[serde(rename = "unit")] - pub unit: String, + pub unit: uuid::Uuid, #[serde(rename = "value")] - pub value: i32, + pub value: i64, } impl UnitAmount { - pub fn new(unit: String, value: i32) -> UnitAmount { + pub fn new(unit: uuid::Uuid, value: i64) -> UnitAmount { UnitAmount { unit, value, diff --git a/crates/rocie-client/src/models/unit_stub.rs b/crates/rocie-client/src/models/unit_stub.rs new file mode 100644 index 0000000..03f81fd --- /dev/null +++ b/crates/rocie-client/src/models/unit_stub.rs @@ -0,0 +1,36 @@ +/* + * rocie-server + * + * An enterprise grocery management system + * + * The version of the OpenAPI document: 0.1.0 + * Contact: benedikt.peetz@b-peetz.de + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct UnitStub { + #[serde(rename = "description", default, with = "::serde_with::rust::double_option", skip_serializing_if = "Option::is_none")] + pub description: Option<Option<String>>, + #[serde(rename = "full_name_plural")] + pub full_name_plural: String, + #[serde(rename = "full_name_singular")] + pub full_name_singular: String, + #[serde(rename = "short_name")] + pub short_name: String, +} + +impl UnitStub { + pub fn new(full_name_plural: String, full_name_singular: String, short_name: String) -> UnitStub { + UnitStub { + description: None, + full_name_plural, + full_name_singular, + short_name, + } + } +} + 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() + } +} |
