swarm / companies/starter/work/project/src/sync/api/data_quality.rs

raw file 1173 bytes
use actix_web::{web, HttpResponse};
use sqlx::PgPool;
use serde::Serialize;

#[derive(Serialize)]
pub struct CustomerStats {
    pub customer_id: String,
    pub table_name: String,
    pub row_count: i64,
    pub drift_score: f64,
    pub last_sync_at: Option<String>,
    pub last_error: Option<String>,
}

pub async fn get_data_quality(
    pool: web::Data<PgPool>,
) -> Result<HttpResponse, actix_web::Error> {
    let rows: Vec<(String, String, i64, f64, Option<chrono::DateTime<chrono::Utc>>, Option<String>)> = sqlx::query_as(
        "SELECT customer_id::text, table_name, row_count, drift_score, last_sync_at, last_error \
         FROM data_quality_stats ORDER BY customer_id, table_name"
    )
    .fetch_all(&pool)
    .await
    .map_err(|e| actix_web::Error::Json(e))?;

    let stats: Vec<CustomerStats> = rows
        .into_iter()
        .map(|(cid, tn, rc, ds, ls, le)| CustomerStats {
            customer_id: cid,
            table_name: tn,
            row_count: rc,
            drift_score: ds,
            last_sync_at: ls.map(|t| t.to_rfc3339()),
            last_error: le,
        })
        .collect();

    Ok(HttpResponse::Ok().json(&stats))
}