use anyhow::Result;
use sqlx::{PgPool, Row};
use uuid::Uuid;
use backbone_orm::org_scope;
use crate::domain::entity::ServiceLevelAgreement;
pub const TABLE_NAME: &str = "support.service_level_agreements";
pub struct ServiceLevelAgreementRepository(
backbone_orm::GenericCrudRepository<ServiceLevelAgreement, backbone_orm::SoftDelete>,
);
impl std::ops::Deref for ServiceLevelAgreementRepository {
type Target =
backbone_orm::GenericCrudRepository<ServiceLevelAgreement, backbone_orm::SoftDelete>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ServiceLevelAgreementRepository {
pub fn new(pool: PgPool) -> Self {
Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
}
}
pub struct NewSlaRow<'a> {
pub id: Uuid,
pub name: &'a str,
pub is_default: bool,
}
impl ServiceLevelAgreementRepository {
pub async fn insert_sla(
&self,
conn: &mut sqlx::PgConnection,
s: &NewSlaRow<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO support.service_level_agreements (id, name, is_default, status)
VALUES ($1,$2,$3,'active')"#,
)
.bind(s.id)
.bind(s.name)
.bind(s.is_default)
.execute(conn)
.await?;
Ok(())
}
pub async fn find_default_id(&self, pool: &PgPool) -> Result<Option<Uuid>, sqlx::Error> {
let row = org_scope::fetch_optional_row_scoped(
pool,
sqlx::query(
r#"SELECT id FROM support.service_level_agreements
WHERE is_default=true AND status='active'
AND (metadata->>'deleted_at') IS NULL LIMIT 1"#,
),
)
.await?;
Ok(row.map(|r| r.get::<Uuid, _>("id")))
}
}
backbone_core::impl_crud_repository!(
ServiceLevelAgreementRepository,
ServiceLevelAgreement,
soft_delete
);