use anyhow::Result;
use rust_decimal::Decimal;
use sqlx::{PgPool, Row};
use uuid::Uuid;
use crate::domain::entity::PosProfile;
pub const TABLE_NAME: &str = "pos.pos_profiles";
pub struct PosProfileRepository(
backbone_orm::GenericCrudRepository<PosProfile, backbone_orm::SoftDelete>,
);
impl std::ops::Deref for PosProfileRepository {
type Target = backbone_orm::GenericCrudRepository<PosProfile, backbone_orm::SoftDelete>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl PosProfileRepository {
pub fn new(pool: PgPool) -> Self {
Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
}
}
pub struct TaxConfigRow {
pub tax_template_ids: Option<serde_json::Value>,
pub rounding_strategy: String,
pub rounding_unit: Decimal,
pub allow_discount: bool,
}
impl PosProfileRepository {
pub async fn fetch_tax_config(
&self,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
pos_profile_id: Uuid,
) -> Result<Option<TaxConfigRow>, sqlx::Error> {
let row = sqlx::query(
r#"SELECT tax_template_ids, cash_rounding_strategy::text AS strategy, cash_rounding_unit, allow_discount
FROM pos.pos_profiles WHERE id=$1 AND (metadata->>'deleted_at') IS NULL"#,
)
.bind(pos_profile_id)
.fetch_optional(exec)
.await?;
Ok(row.map(|r| TaxConfigRow {
tax_template_ids: r.get("tax_template_ids"),
rounding_strategy: r.get("strategy"),
rounding_unit: r.get("cash_rounding_unit"),
allow_discount: r.get("allow_discount"),
}))
}
pub async fn exists(
&self,
conn: &mut sqlx::PgConnection,
pos_profile_id: Uuid,
) -> Result<bool, sqlx::Error> {
let found: Option<i32> = sqlx::query_scalar(
"SELECT 1 FROM pos.pos_profiles WHERE id=$1 AND (metadata->>'deleted_at') IS NULL",
)
.bind(pos_profile_id)
.fetch_optional(conn)
.await?;
Ok(found.is_some())
}
}
backbone_core::impl_crud_repository!(PosProfileRepository, PosProfile, soft_delete);