//! # Forez Presence helper //! //! @author Pierre Hubert use crate::constants::database_tables_names::FOREZ_PRESENCE_TABLE; use crate::data::error::Res; use crate::data::group_id::GroupID; use crate::data::presence::Presence; use crate::data::user::UserID; use crate::helpers::database; /// Get the list of presence contained in the database pub fn get_list(group_id: &GroupID) -> Res> { database::QueryInfo::new(FOREZ_PRESENCE_TABLE) .cond_group_id("group_id", group_id) .exec(db_to_presence) } /// Get the list of presences of a specific user pub fn get_user_presences(group_id: &GroupID, user_id: &UserID) -> Res> { database::QueryInfo::new(FOREZ_PRESENCE_TABLE) .cond_user_id("user_id", user_id) .cond_group_id("group_id", group_id) .exec(db_to_presence) } /// Update the presences of a user pub fn update(group_id: &GroupID, user_id: &UserID, list: Vec) -> Res { let previous_presences = get_user_presences(group_id, user_id)?; for presence in &list { if !previous_presences.contains(presence) { database::InsertQuery::new(FOREZ_PRESENCE_TABLE) .add_user_id("user_id", user_id) .add_group_id("group_id", group_id) .add_u32("year", presence.year) .add_u16("month", presence.month) .add_u16("day", presence.day) .insert()?; } } for prev in &previous_presences { if !list.contains(prev) { database::DeleteQuery::new(FOREZ_PRESENCE_TABLE) .cond_u64("id", prev.id) .exec()?; } } Ok(()) } /// Turn a database entry into a presence entry fn db_to_presence(row: &database::RowResult) -> Res { Ok(Presence { id: row.get_u64("id")?, user_id: row.get_user_id("user_id")?, year: row.get_u32("year")?, month: row.get_u16("month")?, day: row.get_u16("day")?, }) }