use crate::{
DataManager,
model::{AuditLogEntry, Error, Notification, Result, User, UserPermission, UserWarning},
};
use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_rows};
use tetratto_core2::{auto_method, model::id::Id};
impl DataManager {
pub(crate) fn get_user_warning_from_row(x: &PostgresRow) -> UserWarning {
UserWarning {
id: Id::deserialize(&get!(x->0(String))),
created: get!(x->1(i64)) as u128,
receiver: Id::Legacy(get!(x->2(i64)) as usize),
moderator: Id::Legacy(get!(x->3(i64)) as usize),
content: get!(x->4(String)),
}
}
auto_method!(get_user_warning_by_id()@get_user_warning_from_row -> "SELECT * FROM a_user_warnings WHERE id = $1" --name="user warning" --returns=UserWarning --cache-key-tmpl="srmp.user_warning:{}");
pub async fn get_user_warnings_by_user(
&self,
user: &Id,
batch: usize,
page: usize,
) -> Result<Vec<UserWarning>> {
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_user_warnings WHERE receiver = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[
&(user.as_usize() as i64),
&(batch as i64),
&((page * batch) as i64)
],
|x| { Self::get_user_warning_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("user warning".to_string()));
}
Ok(res.unwrap())
}
pub async fn create_user_warning(&self, data: UserWarning) -> Result<()> {
let user = self.get_user_by_id(&data.moderator).await?;
if !user.permissions.contains(&UserPermission::ManageWarnings) {
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,
"INSERT INTO a_user_warnings VALUES ($1, $2, $3, $4, $5)",
params![
&data.id.printable(),
&(data.created as i64),
&(data.receiver.as_usize() as i64),
&(data.moderator.as_usize() as i64),
&data.content
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!(
"invoked `create_user_warning` with x value `{}`",
data.receiver
),
))
.await?;
self.create_notification(Notification::new(
"You have received a new account warning.".to_string(),
data.content,
data.receiver,
))
.await?;
Ok(())
}
pub async fn delete_user_warning(&self, id: &Id, user: User) -> Result<()> {
if !user.permissions.contains(&UserPermission::ManageWarnings) {
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_user_warnings WHERE id = $1",
&[&id.printable()]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("srmp.user_warning:{}", id)).await;
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!("invoked `delete_user_warning` with x value `{id}`"),
))
.await?;
Ok(())
}
}