Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v1.3.0 #47

Merged
merged 2 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/graphql/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use serde::Deserialize;

#[derive(Clone, Debug, Deserialize)]
pub struct StreakWithMemberId {
#[serde(rename = "memberId")]
pub member_id: i32,
#[serde(rename = "currentStreak")]
pub current_streak: i32,
#[serde(rename = "maxStreak")]
pub max_streak: i32,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Streak {
#[serde(rename = "currentStreak")]
Expand All @@ -32,6 +42,19 @@ pub struct Member {
pub name: String,
#[serde(rename = "discordId")]
pub discord_id: String,
#[serde(rename = "groupId")]
pub group_id: i32,
#[serde(default)]
pub streak: Vec<Streak>, // Note that Root will NOT have multiple Streak elements but it may be an empty list which is why we use a vector here
}

#[derive(Debug, Deserialize, Clone)]
pub struct AttendanceRecord {
#[serde(rename = "memberId")]
pub name: String,
pub year: i32,
#[serde(rename = "isPresent")]
pub is_present: bool,
#[serde(rename = "timeIn")]
pub time_in: Option<String>,
}
124 changes: 118 additions & 6 deletions src/graphql/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,13 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use anyhow::{anyhow, Context};
use chrono::Local;
use serde_json::Value;
use tracing::debug;

use crate::graphql::models::{Member, Streak};
use crate::graphql::models::{AttendanceRecord, Member, Streak};

use super::models::StreakWithMemberId;

pub async fn fetch_members() -> anyhow::Result<Vec<Member>> {
let request_url = std::env::var("ROOT_URL").context("ROOT_URL not found in ENV")?;
Expand All @@ -30,6 +34,7 @@ pub async fn fetch_members() -> anyhow::Result<Vec<Member>> {
memberId
name
discordId
groupId
streak {
currentStreak
maxStreak
Expand Down Expand Up @@ -114,22 +119,33 @@ pub async fn increment_streak(member: &mut Member) -> anyhow::Result<()> {
.get("data")
.and_then(|data| data.get("incrementStreak"))
{
let current_streak = data.get("currentStreak").and_then(|v| v.as_i64()).ok_or_else(|| anyhow!("current_streak was parsed as None"))? as i32;
let max_streak = data.get("maxStreak").and_then(|v| v.as_i64()).ok_or_else(|| anyhow!("max_streak was parsed as None"))? as i32;
let current_streak =
data.get("currentStreak")
.and_then(|v| v.as_i64())
.ok_or_else(|| anyhow!("current_streak was parsed as None"))? as i32;
let max_streak =
data.get("maxStreak")
.and_then(|v| v.as_i64())
.ok_or_else(|| anyhow!("max_streak was parsed as None"))? as i32;

if member.streak.is_empty() {
member.streak.push(Streak { current_streak, max_streak });
member.streak.push(Streak {
current_streak,
max_streak,
});
} else {
for streak in &mut member.streak {
streak.current_streak = current_streak;
streak.max_streak = max_streak;
}
}
} else {
return Err(anyhow!("Failed to access data from response: {}", response_json));
return Err(anyhow!(
"Failed to access data from response: {}",
response_json
));
}


Ok(())
}

Expand Down Expand Up @@ -199,3 +215,99 @@ pub async fn reset_streak(member: &mut Member) -> anyhow::Result<()> {

Ok(())
}

pub async fn fetch_attendance() -> anyhow::Result<Vec<AttendanceRecord>> {
let request_url =
std::env::var("ROOT_URL").context("ROOT_URL environment variable not found")?;

debug!("Fetching attendance data from {}", request_url);

let client = reqwest::Client::new();
let today = Local::now().format("%Y-%m-%d").to_string();
let query = format!(
r#"
query {{
attendanceByDate(date: "{}") {{
name,
year,
isPresent,
timeIn,
}}
}}"#,
today
);

let response = client
.post(&request_url)
.json(&serde_json::json!({ "query": query }))
.send()
.await
.context("Failed to send GraphQL request")?;
debug!("Response status: {:?}", response.status());

let json: Value = response
.json()
.await
.context("Failed to parse response as JSON")?;

let attendance_array = json["data"]["attendanceByDate"]
.as_array()
.context("Missing or invalid 'data.attendanceByDate' array in response")?;

let attendance: Vec<AttendanceRecord> = attendance_array
.iter()
.map(|entry| {
serde_json::from_value(entry.clone()).context("Failed to parse attendance record")
})
.collect::<anyhow::Result<Vec<_>>>()?;

debug!(
"Successfully fetched {} attendance records",
attendance.len()
);
Ok(attendance)
}

pub async fn fetch_streaks() -> anyhow::Result<Vec<StreakWithMemberId>> {
let request_url = std::env::var("ROOT_URL").context("ROOT_URL not found in ENV")?;

let client = reqwest::Client::new();
let query = r#"
{
streaks {
memberId
currentStreak
maxStreak
}
}
"#;

debug!("Sending query {}", query);
let response = client
.post(request_url)
.json(&serde_json::json!({"query": query}))
.send()
.await
.context("Failed to successfully post request")?;

if !response.status().is_success() {
return Err(anyhow!(
"Server responded with an error: {:?}",
response.status()
));
}

let response_json: serde_json::Value = response
.json()
.await
.context("Failed to serialize response")?;

debug!("Response: {}", response_json);
let streaks = response_json
.get("data")
.and_then(|data| data.get("streaks"))
.and_then(|streaks| serde_json::from_value::<Vec<StreakWithMemberId>>(streaks.clone()).ok())
.context("Failed to parse streaks data")?;

Ok(streaks)
}
1 change: 1 addition & 0 deletions src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ pub const GROUP_TWO_CHANNEL_ID: u64 = 1225098298935738489;
pub const GROUP_THREE_CHANNEL_ID: u64 = 1225098353378070710;
pub const GROUP_FOUR_CHANNEL_ID: u64 = 1225098407216156712;
pub const STATUS_UPDATE_CHANNEL_ID: u64 = 764575524127244318;
pub const THE_LAB_CHANNEL_ID: u64 = 1208438766893670451;
Loading
Loading