tetratto-core 12.0.0

The core behind Tetratto
Documentation
use crate::model::{
    auth::User,
    permissions::{FinePermission, SecondaryPermission},
    products::{Product, ProductPrice},
    Error, Result,
};
use crate::{auto_method, DataManager};
use oiseau::{cache::Cache, execute, get, params, query_rows, PostgresRow};

impl DataManager {
    /// Get a [`Product`] from an SQL row.
    pub(crate) fn get_product_from_row(x: &PostgresRow) -> Product {
        Product {
            id: get!(x->0(i64)) as usize,
            created: get!(x->1(i64)) as usize,
            owner: get!(x->2(i64)) as usize,
            name: get!(x->3(String)),
            description: get!(x->4(String)),
            likes: get!(x->5(i32)) as isize,
            dislikes: get!(x->6(i32)) as isize,
            product_type: serde_json::from_str(&get!(x->7(String))).unwrap(),
            price: serde_json::from_str(&get!(x->8(String))).unwrap(),
            uploads: serde_json::from_str(&get!(x->9(String))).unwrap(),
        }
    }

    auto_method!(get_product_by_id(usize as i64)@get_product_from_row -> "SELECT * FROM products WHERE id = $1" --name="product" --returns=Product --cache-key-tmpl="atto.product:{}");

    /// Get all products by user.
    ///
    /// # Arguments
    /// * `id` - the ID of the user to fetch products for
    /// * `batch`
    /// * `page`
    pub async fn get_products_by_user(
        &self,
        id: usize,
        batch: usize,
        page: usize,
    ) -> Result<Vec<Product>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM products WHERE owner = $1 ORDER BY created DESC LIMIT {} OFFSET {}",
            &[&(id as i64), &(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_product_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("product".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Get all products by user.
    ///
    /// # Arguments
    /// * `id` - the ID of the user to fetch products for
    pub async fn get_products_by_user_all(&self, id: usize) -> Result<Vec<Product>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM products WHERE owner = $1 ORDER BY created DESC",
            &[&(id as i64)],
            |x| { Self::get_product_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("product".to_string()));
        }

        Ok(res.unwrap())
    }

    const MAXIMUM_FREE_PRODUCTS: usize = 15;

    /// Create a new product in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Product`] object to insert
    pub async fn create_product(&self, data: Product) -> Result<Product> {
        // check values
        if data.name.len() < 2 {
            return Err(Error::DataTooShort("name".to_string()));
        } else if data.name.len() > 128 {
            return Err(Error::DataTooLong("name".to_string()));
        }

        // check number of products
        let owner = self.get_user_by_id(data.owner).await?;

        if !owner.permissions.check(FinePermission::SUPPORTER) {
            let products = self
                .get_table_row_count_where("products", &format!("owner = {}", owner.id))
                .await? as usize;

            if products >= Self::MAXIMUM_FREE_PRODUCTS {
                return Err(Error::MiscError(
                    "You already have the maximum number of products you can have".to_string(),
                ));
            }
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "INSERT INTO products VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
            params![
                &(data.id as i64),
                &(data.created as i64),
                &(data.owner as i64),
                &data.name,
                &data.description,
                &0_i32,
                &0_i32,
                &serde_json::to_string(&data.product_type).unwrap(),
                &serde_json::to_string(&data.price).unwrap(),
                &serde_json::to_string(&data.uploads).unwrap(),
            ]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        Ok(data)
    }

    pub async fn delete_product(&self, id: usize, user: &User) -> Result<()> {
        let product = self.get_product_by_id(id).await?;

        // check user permission
        if user.id != product.owner
            && !user
                .secondary_permissions
                .check(SecondaryPermission::MANAGE_PRODUCTS)
        {
            return Err(Error::NotAllowed);
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(&conn, "DELETE FROM products WHERE id = $1", &[&(id as i64)]);

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // ...
        self.0.1.remove(format!("atto.product:{}", id)).await;
        Ok(())
    }

    auto_method!(update_product_name(&str)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET name = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
    auto_method!(update_product_description(&str)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET description = $1 WHERE id = $2" --cache-key-tmpl="atto.product:{}");
    auto_method!(update_product_price(ProductPrice)@get_product_by_id:FinePermission::MANAGE_USERS; -> "UPDATE products SET price = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.product:{}");
}