mostro_core/
user.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3#[cfg(feature = "sqlx")]
4use sqlx::FromRow;
5
6/// Database representation of an user
7#[cfg_attr(feature = "sqlx", derive(FromRow))]
8#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
9pub struct User {
10    pub pubkey: String,
11    pub is_admin: i64,
12    pub is_solver: i64,
13    pub is_banned: i64,
14    pub category: i64,
15    /// We have to be sure that when a user creates a new order (or takes an order),
16    /// the trade_index is greater than the one we have in database
17    pub last_trade_index: i64,
18    pub total_reviews: i64,
19    pub total_rating: f64,
20    pub last_rating: i64,
21    pub max_rating: i64,
22    pub min_rating: i64,
23    pub created_at: i64,
24}
25
26impl User {
27    pub fn new(
28        pubkey: String,
29        is_admin: i64,
30        is_solver: i64,
31        is_banned: i64,
32        category: i64,
33        trade_index: i64,
34    ) -> Self {
35        Self {
36            pubkey,
37            is_admin,
38            is_solver,
39            is_banned,
40            category,
41            last_trade_index: trade_index,
42            total_reviews: 0,
43            total_rating: 0.0,
44            last_rating: 0,
45            max_rating: 0,
46            min_rating: 0,
47            created_at: Utc::now().timestamp(),
48        }
49    }
50
51    /// Update user rating
52    pub fn update_rating(&mut self, rating: u8) {
53        // Update user reputation
54        // increment first
55        self.total_reviews += 1;
56        let old_rating = self.total_rating;
57        // recompute new rating
58        if self.total_reviews <= 1 {
59            self.total_rating = rating.into();
60            self.max_rating = rating.into();
61            self.min_rating = rating.into();
62        } else {
63            self.total_rating =
64                old_rating + ((self.last_rating as f64) - old_rating) / (self.total_reviews as f64);
65            if self.max_rating < rating.into() {
66                self.max_rating = rating.into();
67            }
68            if self.min_rating > rating.into() {
69                self.min_rating = rating.into();
70            }
71        }
72        // Store last rating
73        self.last_rating = rating.into();
74    }
75}