Skip to content

Commit

Permalink
Fix: math corrected with all rabbit suggestion
Browse files Browse the repository at this point in the history
  • Loading branch information
arkanoider committed Dec 23, 2024
1 parent a6bcf1f commit 7b5f670
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
13 changes: 6 additions & 7 deletions src/app/rate_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,21 +141,20 @@ pub async fn update_user_reputation_action(

// Update user reputation
// Going on with calculation
let old_rating = user_to_vote.total_rating;
// increment first
user_to_vote.total_reviews += 1;
// recompute rating
let new_rating = old_rating + (rating as i64 - old_rating) / (user_to_vote.total_reviews);

// Store last rating
user_to_vote.last_rating = rating.into();
// recompute rating
user_to_vote.total_rating =
((user_to_vote.total_rating * (user_to_vote.total_reviews - 1) as f64) + rating as f64)
/ user_to_vote.total_reviews as f64;

// Assign new total rating to review
user_to_vote.total_rating = new_rating;
// Create new rating event
let reputation_event = Rating::new(
user_to_vote.total_reviews as u64,
user_to_vote.total_rating as f64,
rating as u8,
user_to_vote.last_rating as u8,
user_to_vote.min_rating as u8,
user_to_vote.max_rating as u8,
)
Expand Down
4 changes: 2 additions & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ pub async fn update_user_rating(
min_rating: i64,
max_rating: i64,
total_reviews: i64,
total_rating: i64,
total_rating: f64,
) -> anyhow::Result<User> {
// Validate public key format (32-bytes hex)
if !public_key.chars().all(|c| c.is_ascii_hexdigit()) || public_key.len() != 64 {
Expand All @@ -414,7 +414,7 @@ pub async fn update_user_rating(
if total_reviews < 0 {
return Err(anyhow::anyhow!("Invalid total reviews"));
}
if total_rating < 0 || total_rating > total_reviews * 5 {
if total_rating < 0.0 || total_rating > (total_reviews * 5) as f64 {
return Err(anyhow::anyhow!("Invalid total rating"));
}
if let Ok(user) = sqlx::query_as::<_, User>(
Expand Down

0 comments on commit 7b5f670

Please sign in to comment.