about summary refs log tree commit diff stats
path: root/crates/rocie-server/src/storage
diff options
context:
space:
mode:
Diffstat (limited to 'crates/rocie-server/src/storage')
-rw-r--r--crates/rocie-server/src/storage/migrate/sql/0->1.sql12
-rw-r--r--crates/rocie-server/src/storage/sql/get/mod.rs1
-rw-r--r--crates/rocie-server/src/storage/sql/get/product/mod.rs54
-rw-r--r--crates/rocie-server/src/storage/sql/get/unit/mod.rs79
-rw-r--r--crates/rocie-server/src/storage/sql/insert/mod.rs22
-rw-r--r--crates/rocie-server/src/storage/sql/insert/product/mod.rs4
-rw-r--r--crates/rocie-server/src/storage/sql/insert/unit/mod.rs110
-rw-r--r--crates/rocie-server/src/storage/sql/mod.rs1
-rw-r--r--crates/rocie-server/src/storage/sql/product.rs6
-rw-r--r--crates/rocie-server/src/storage/sql/unit.rs59
10 files changed, 323 insertions, 25 deletions
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()
+    }
+}