4.0 KiB · text History 2264215
//! Discourse-style trust levels.
//!
//! 0 New · 1 Basic · 2 Member · 3 Regular · 4 Leader. Levels 1–3 are earned
//! automatically from activity; level 4 is granted manually by staff. This is a
//! pragmatic approximation of Discourse's engine using the signals we track
//! (posts, topics, account age, reactions received) rather than reading time.
//! Promotion only ever raises a user's level, never lowers it.

use crate::entities::{posts, topics, users};
use chrono::Utc;
use sea_orm::{DatabaseBackend, FromQueryResult, Statement};
use sea_orm::*;
use uuid::Uuid;

pub const TIER_NAMES: [&str; 5] = ["New", "Basic", "Member", "Regular", "Leader"];

/// Human name for a trust level.
pub fn tier_name(level: i32) -> &'static str {
    TIER_NAMES
        .get(level.clamp(0, 4) as usize)
        .copied()
        .unwrap_or("New")
}

struct Stats {
    posts: i64,
    topics: i64,
    age_days: i64,
    reactions_received: i64,
}

async fn user_stats(
    db: &DatabaseConnection,
    user_id: Uuid,
    created_at: chrono::DateTime<chrono::FixedOffset>,
) -> Result<Stats, DbErr> {
    let posts = posts::Entity::find()
        .filter(posts::Column::UserId.eq(user_id))
        .filter(posts::Column::DeletedAt.is_null())
        .count(db)
        .await? as i64;
    let topics = topics::Entity::find()
        .filter(topics::Column::UserId.eq(user_id))
        .filter(topics::Column::DeletedAt.is_null())
        .count(db)
        .await? as i64;
    #[derive(FromQueryResult)]
    struct Cnt {
        c: i64,
    }
    let reactions_received = Cnt::find_by_statement(Statement::from_sql_and_values(
        DatabaseBackend::Postgres,
        "SELECT count(*)::bigint AS c FROM post_reactions pr JOIN posts p ON p.id = pr.post_id WHERE p.user_id = $1",
        [user_id.into()],
    ))
    .one(db)
    .await?
    .map(|x| x.c)
    .unwrap_or(0);
    let age_days = (Utc::now() - created_at.with_timezone(&Utc)).num_days();
    Ok(Stats {
        posts,
        topics,
        age_days,
        reactions_received,
    })
}

/// Highest level earnable from activity (capped at 3; 4 is manual). Thresholds
/// are intentionally simple and easy to tune.
fn earned_level(s: &Stats) -> i32 {
    let mut tl = 0;
    if s.posts >= 3 {
        tl = 1;
    }
    if s.posts >= 15 && s.topics >= 2 && s.age_days >= 7 {
        tl = 2;
    }
    if s.posts >= 50 && s.topics >= 5 && s.age_days >= 30 && s.reactions_received >= 10 {
        tl = 3;
    }
    tl
}

/// Recompute a user's earned level and promote them if they now qualify for a
/// higher one. Returns the (possibly unchanged) level. Best-effort: callers log
/// errors but don't fail the triggering action.
pub async fn recompute(db: &DatabaseConnection, user: &users::Model) -> Result<i32, DbErr> {
    let stats = user_stats(db, user.id, user.created_at).await?;
    let earned = earned_level(&stats);
    if earned > user.trust_level {
        let mut am: users::ActiveModel = user.clone().into();
        am.trust_level = Set(earned);
        am.updated_at = Set(Utc::now().into());
        am.update(db).await?;
        Ok(earned)
    } else {
        Ok(user.trust_level)
    }
}

/// Whether a user may mint brand-new tags.
pub fn can_create_tags(user: &users::Model, min_trust: i32) -> bool {
    user.is_staff || user.trust_level >= min_trust
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tiers() {
        assert_eq!(tier_name(0), "New");
        assert_eq!(tier_name(3), "Regular");
        assert_eq!(tier_name(4), "Leader");
        assert_eq!(tier_name(99), "Leader"); // clamped
    }

    #[test]
    fn earned_thresholds() {
        let mk = |posts, topics, age_days, rx| Stats {
            posts,
            topics,
            age_days,
            reactions_received: rx,
        };
        assert_eq!(earned_level(&mk(0, 0, 0, 0)), 0);
        assert_eq!(earned_level(&mk(3, 0, 0, 0)), 1);
        assert_eq!(earned_level(&mk(15, 2, 7, 0)), 2);
        assert_eq!(earned_level(&mk(50, 5, 30, 10)), 3);
        assert_eq!(earned_level(&mk(50, 5, 30, 9)), 2); // not enough reactions
    }
}