use anyhow::Result;
use sqlx::{PgPool, Row};
use uuid::Uuid;
use backbone_orm::org_scope;
use crate::domain::entity::ServiceLevelPriority;
pub const TABLE_NAME: &str = "support.service_level_priorities";
pub struct ServiceLevelPriorityRepository(
backbone_orm::GenericCrudRepository<ServiceLevelPriority, backbone_orm::SoftDelete>,
);
impl std::ops::Deref for ServiceLevelPriorityRepository {
type Target =
backbone_orm::GenericCrudRepository<ServiceLevelPriority, backbone_orm::SoftDelete>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ServiceLevelPriorityRepository {
pub fn new(pool: PgPool) -> Self {
Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
}
}
pub struct NewSlaPriorityRow<'a> {
pub id: Uuid,
pub sla_id: Uuid,
pub priority: &'a str,
pub response_time_mins: i32,
pub resolution_time_mins: i32,
}
pub struct SlaTargetRow {
pub response_time_mins: i32,
pub resolution_time_mins: i32,
}
impl ServiceLevelPriorityRepository {
pub async fn insert_priority(
&self,
conn: &mut sqlx::PgConnection,
p: &NewSlaPriorityRow<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO support.service_level_priorities
(id, sla_id, priority, response_time_mins, resolution_time_mins)
VALUES ($1,$2,$3::issue_priority,$4,$5)"#,
)
.bind(p.id)
.bind(p.sla_id)
.bind(p.priority)
.bind(p.response_time_mins)
.bind(p.resolution_time_mins)
.execute(conn)
.await?;
Ok(())
}
pub async fn find_target(
&self,
pool: &PgPool,
sla_id: Uuid,
priority: &str,
) -> Result<Option<SlaTargetRow>, sqlx::Error> {
let row = org_scope::fetch_optional_row_scoped(
pool,
sqlx::query(
r#"SELECT response_time_mins, resolution_time_mins FROM support.service_level_priorities
WHERE sla_id=$1 AND priority=$2::issue_priority"#,
)
.bind(sla_id)
.bind(priority),
)
.await?;
Ok(row.map(|r| SlaTargetRow {
response_time_mins: r.get("response_time_mins"),
resolution_time_mins: r.get("resolution_time_mins"),
}))
}
}
backbone_core::impl_crud_repository!(
ServiceLevelPriorityRepository,
ServiceLevelPriority,
soft_delete
);