use crate::{
DataManager,
model::{Error, Result, User, UserPermission, properties::Property},
};
use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_rows};
use tetratto_core2::{auto_method, model::id::Id};
impl DataManager {
pub(crate) fn get_property_from_row(x: &PostgresRow) -> Property {
Property {
id: Id::deserialize(&get!(x->0(String))),
created: get!(x->1(i64)) as u128,
owner: Id::Legacy(get!(x->2(i64)) as usize),
name: get!(x->3(String)),
product: serde_json::from_str(&get!(x->4(String))).unwrap(),
custom_domain: get!(x->5(String)),
}
}
auto_method!(get_property_by_id()@get_property_from_row -> "SELECT * FROM a_properties WHERE id = $1" --name="property" --returns=Property --cache-key-tmpl="srmp.property:{}");
pub async fn get_properties_by_user(&self, user: &Id) -> Result<Vec<Property>> {
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 a_properties WHERE owner = $1 ORDER BY created",
&[&(user.as_usize() as i64)],
|x| { Self::get_property_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("property".to_string()));
}
Ok(res.unwrap())
}
pub async fn create_property(&self, data: Property) -> Result<()> {
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 a_properties VALUES ($1, $2, $3, $4, $5, $6)",
params![
&data.id.printable(),
&(data.created as i64),
&(data.owner.as_usize() as i64),
&data.name,
&serde_json::to_string(&data.product).unwrap(),
&data.custom_domain
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(())
}
pub async fn delete_property(&self, id: &Id, user: User) -> Result<()> {
let property = self.get_property_by_id(&id).await?;
if user.id != property.owner
&& !user.permissions.contains(&UserPermission::ManageProperties)
{
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 a_properties WHERE id = $1",
&[&id.printable()]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("srmp.property:{}", id)).await;
Ok(())
}
auto_method!(update_property_custom_domain(&str) -> "UPDATE a_properties SET custom_domain = $1 WHERE id = $2" --cache-key-tmpl="srmp.property:{}");
auto_method!(update_property_name(&str) -> "UPDATE a_properties SET name = $1 WHERE id = $2" --cache-key-tmpl="srmp.property:{}");
}