Skip to content

Commit

Permalink
fix: use format! instead of + putting string
Browse files Browse the repository at this point in the history
  • Loading branch information
7086cmd committed May 3, 2024
1 parent 0428c45 commit 256dea6
Show file tree
Hide file tree
Showing 8 changed files with 177 additions and 13 deletions.
120 changes: 120 additions & 0 deletions src/calc/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,121 @@
use crate::{
models::{activities::Activity, users::User},
routers::users::time::UserActivityTime,
};
use bson::{doc, from_document};
use futures::stream::TryStreamExt;
use mongodb::{Collection, Database};
use polars::{df, frame::DataFrame, prelude::NamedFrom, series::Series};
use std::sync::Arc;
use tokio::sync::Mutex;

async fn export(db: Arc<Mutex<Database>>) -> Result<DataFrame, String> {
let db = db.lock().await;
let mut df = df!(
"_id" => &["".to_string()],
"id" => &["0".to_string()],
"name" => &["Example".to_string()],
"class" => &["".to_string()],
"on_campus" => &[0.0],
"off_campus" => &[0.0],
"social_practice" => &[0.0],
"total" => &[0.0]
)
.unwrap();

let users_collection: Collection<User> = db.collection("users");
let activities_collection: Collection<Activity> = db.collection("activities");

let mut users = users_collection.find(doc! {}, None).await.unwrap();

while let Some(doc) = users.try_next().await.unwrap() {
let pipeline = vec![
doc! {
"$match": {
"$or": [
{ "members._id": doc._id.clone() },
{ "members._id": doc._id.to_hex() }
]
}
},
doc! {
"$unwind": "$members"
},
doc! {
"$match": {
"$or": [
{ "members._id": doc._id.clone() },
{ "members._id": doc._id.to_hex() }
]
}
},
doc! {
"$group": {
"_id": "$members.mode",
"totalDuration": { "$sum": "$members.duration" }
}
},
doc! {
"$group": {
"_id": null,
"on_campus": {
"$sum": {
"$cond": [{ "$eq": ["$_id", "on-campus"] }, "$totalDuration", 0.0]
}
},
"off_campus": {
"$sum": {
"$cond": [{ "$eq": ["$_id", "off-campus"] }, "$totalDuration", 0.0]
}
},
"social_practice": {
"$sum": {
"$cond": [{ "$eq": ["$_id", "social-practice"] }, "$totalDuration", 0.0]
}
},
"total": { "$sum": "$totalDuration" }
}
},
doc! {
"$project": {
"_id": 0,
"on_campus": 1,
"off_campus": 1,
"social_practice": 1,
"total": 1
}
},
];
let cursor = activities_collection.aggregate(pipeline, None).await;
if let Err(_) = cursor {
return Err("Failed to get cursor".to_string());
}
let mut cursor = cursor.unwrap();
let result = cursor.try_next().await;
if let Err(_) = result {
return Err("Failed to get result".to_string());
}
let result = result.unwrap();
if let None = result {
return Err("Failed to get result".to_string());
}
let result = result.unwrap();
let result: UserActivityTime = from_document(result).unwrap();
let extend = DataFrame::new(vec![
Series::new("_id", vec![doc._id.clone().to_hex()]),
Series::new("id", vec![doc.id.clone()]),
Series::new("name", vec![doc.name.clone()]),
Series::new("class", vec!["".to_string()]),
Series::new("on_campus", vec![result.on_campus]),
Series::new("off_campus", vec![result.off_campus]),
Series::new("social_practice", vec![result.social_practice]),
Series::new("total", vec![result.total]),
]);
if let Err(_) = extend {
return Err("Failed to create DataFrame".to_string());
}
let extend = extend.unwrap();
df.extend(&extend).unwrap();
}
Ok(df)
}
2 changes: 1 addition & 1 deletion src/routers/activities/members/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub async fn read_member(
if let Err(e) = same {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Cannot validate user".to_string() + &e,
format!("Failed to validate user: {}", e),
);
}
if !same.unwrap() {
Expand Down
2 changes: 1 addition & 1 deletion src/routers/activities/members/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ pub async fn update_member_impression(
if let Err(e) = activity {
return create_error(
StatusCode::NOT_FOUND,
"Activity not found".to_string() + &e.to_string(),
format!("Activity not found: {}", e.to_string()),
);
}
let member = bson::from_document::<ActivityMember>(activity.unwrap());
Expand Down
10 changes: 5 additions & 5 deletions src/routers/activities/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub async fn read_all(
if let Err(e) = count {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read activity: ".to_string() + &e.to_string(),
format!("Failed to read activity: {}", e.to_string()),
);
}
let pipeline = vec![
Expand Down Expand Up @@ -97,7 +97,7 @@ pub async fn read_all(
if let Err(e) = cursor {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read activity: ".to_string() + &e.to_string(),
format!("Failed to read activity: {}", e.to_string()),
);
}
let mut cursor = cursor.unwrap();
Expand All @@ -107,7 +107,7 @@ pub async fn read_all(
if let Err(e) = doc_result {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read activity: ".to_string() + &e.to_string(),
format!("Failed to read activity: {}", e.to_string()),
);
}
if let Ok(Some(document)) = doc_result {
Expand All @@ -116,7 +116,7 @@ pub async fn read_all(
Err(e) => {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read activity: ".to_string() + &e.to_string(),
format!("Failed to read activity: {}", e.to_string()),
)
}
}
Expand Down Expand Up @@ -163,7 +163,7 @@ pub async fn read_one(
if let Err(e) = result {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read activity: ".to_string() + &e.to_string(),
format!("Failed to read activity: {}", e.to_string()),
);
}
let result: Option<Activity> = result.unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/routers/activities/remove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub async fn remove_activity(
if let Err(e) = activity {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to find activity: ".to_string() + &e.to_string(),
format!("Failed to find activity: {}", e.to_string()),
);
}
let activity = activity.unwrap();
Expand All @@ -54,7 +54,7 @@ pub async fn remove_activity(
if let Err(e) = result {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to delete activity: ".to_string() + &e.to_string(),
format!("Failed to delete activity: {}", e.to_string()),
);
}
let result = result.unwrap();
Expand Down
8 changes: 4 additions & 4 deletions src/routers/activities/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn update_activity_name(
if let Err(e) = activity {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to find activity: ".to_string() + &e.to_string(),
format!("Failed to find activity: {}", e.to_string()),
);
}
let activity = activity.unwrap();
Expand All @@ -58,7 +58,7 @@ pub async fn update_activity_name(
if let Err(e) = result {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to update activity: ".to_string() + &e.to_string(),
format!("Failed to update activity: {}", e.to_string()),
);
}
let response: SuccessResponse<Vec<Activity>, ()> = SuccessResponse {
Expand Down Expand Up @@ -96,7 +96,7 @@ pub async fn update_activity_description(
if let Err(e) = activity {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to find activity: ".to_string() + &e.to_string(),
format!("Failed to find activity: {}", e.to_string()),
);
}
let activity = activity.unwrap();
Expand All @@ -119,7 +119,7 @@ pub async fn update_activity_description(
if let Err(e) = result {
return create_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to update activity: ".to_string() + &e.to_string(),
format!("Failed to update activity: {}", e.to_string()),
);
}
let response: SuccessResponse<Vec<Activity>, ()> = SuccessResponse {
Expand Down
43 changes: 43 additions & 0 deletions src/routers/exports/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use crate::{
models::{groups::GroupPermission, response::create_error},
utils::jwt::UserData,
};
use axum::{
extract::Extension,
http::StatusCode,
response::{IntoResponse, Json},
};
use bson::doc;
use mongodb::Database;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub enum ExportFormat {
CSV,
JSON,
Excel,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExportActivityTimesOptions {
pub start: u64, // Unix timestamp
pub end: u64, // Unix timestamp
pub format: ExportFormat,
}

pub async fn export_activity_times(
Extension(db): Extension<Arc<Mutex<Database>>>,
user: UserData,
Json(options): Json<ExportActivityTimesOptions>,
) -> impl IntoResponse {
if !user.perms.contains(&GroupPermission::Admin)
&& !user.perms.contains(&GroupPermission::Inspector)
{
return create_error(StatusCode::FORBIDDEN, "Permission denied".to_string());
}

(StatusCode::OK, Json("".to_string()))
}
1 change: 1 addition & 0 deletions src/routers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod activities;
pub mod auth;
pub mod exports;
pub mod users;

0 comments on commit 256dea6

Please sign in to comment.