//! Module that handles all the logic related to votes within an application. //! //! This module provides the necessary structures and traits to manage events and their corresponding votes. It includes: //! //! - Structs: `Event`, `Vote`, `PendingEvents`, and `OngoingEvents`. //! - Traits: None at this time. //! - Enums: `EventStatus` that represents different states an event can be in. //! //! Note: //! - The types `UserDataType`, `VoteValueType`, and some fields are marked as deprecated and should not be used. //! They are placeholders for the actual data structures which need to be defined correctly. #![allow(deprecated)] use std::{ collections::HashMap, fmt::Display, sync::{LazyLock, Mutex}, }; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{date::date_tools::NaiveDateList, error_handling::IdleError}; // Helper functions, user facing // Helper functions, user facing /// Adds a parsed vote to the list of planned events. /// /// This function will use the `PendingEvents` instance to store the provided event. /// The structure of the input parameter `event` is expected to be a correctly formatted parsed vote. /// /// ## Parameters: /// - `event`: A `ParsedVote` struct representing the details of the event to be scheduled. /// /// ## Example: /// ```rust /// # use idlefox::votes::{add_pending_event, ParsedVote}; /// let parsed_vote = ParsedVote::default(); /// /// let id = add_pending_event(parsed_vote).unwrap(); /// ``` pub fn add_pending_event(event: ParsedVote) -> Result { PENDING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .add_pending_event(event) } /// Launches a pending event by transferring it from the pending to ongoing events list. /// /// This function identifies an event by its UUID and moves it from the planned (pending) events to the ongoing events. If the event is successfully launched, it returns `Ok(())`. Otherwise, it returns an error of type `IdleError`. /// /// ## Parameters: /// - `uuid`: A `Uuid` that uniquely identifies the event to be launched. /// /// ## Example: /// ```rust /// # use idlefox::votes::{add_pending_event, make_into_ongoing_event, ParsedVote}; /// let id = add_pending_event(ParsedVote::default()).unwrap(); /// /// make_into_ongoing_event(id).unwrap() /// ``` pub fn make_into_ongoing_event(uuid: Uuid) -> Result<(), IdleError> { PENDING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .launch(uuid) } /// Manually adds an ongoing event. /// /// This function is intended for internal use and directly adds an event /// to the list of ongoing events. It expects a UUID and a parsed vote as inputs, /// using which it updates the `OngoingEvents` instance. /// /// ## Parameters: /// - `uuid`: A `Uuid` that uniquely identifies the event to be added. /// - `event`: A `ParsedVote` struct representing the details of the ongoing event to be added. /// /// ## Example: /// ```rust /// # use uuid::Uuid; /// # use idlefox::votes::{add_ongoing_event, ParsedVote}; /// let uuid = Uuid::new_v4(); // A new id /// let parsed_vote = ParsedVote::default(); // A very legit event /// /// add_ongoing_event(uuid, parsed_vote).unwrap(); /// ``` pub fn add_ongoing_event(uuid: Uuid, event: ParsedVote) -> Result<(), IdleError> { ONGOING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .add_event(uuid, event)?; Ok(()) } /// Destroy an event without closing it and officially ending it /// /// This function removes an ongoing event from the list of ongoing events. /// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` /// struct representing the details of the removed event or an `IdleError`. /// /// ## Example: /// ```rust /// # use idlefox::votes::{ /// # add_pending_event, del_ongoing_event, make_into_ongoing_event, ParsedVote, /// # }; /// let id = add_pending_event(ParsedVote::default()).unwrap(); /// make_into_ongoing_event(id).unwrap(); /// /// del_ongoing_event(id).unwrap(); /// ``` pub fn del_ongoing_event(uuid: Uuid) -> Result { ONGOING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .del_event(uuid) } /// Destroy a pending event without closing it /// /// This function removes a pending event from the list of pending events. /// It expects a UUID as input and returns a `Result` containing either a `ParsedVote` /// struct representing the details of the removed event or an `IdleError`. /// /// ## Example: /// ```rust /// # use idlefox::votes::{ /// # add_pending_event, del_pending_event, make_into_ongoing_event, ParsedVote, /// # }; /// let id = add_pending_event(ParsedVote::default()).unwrap(); /// del_pending_event(id).unwrap(); /// ``` pub fn del_pending_event(uuid: Uuid) -> Result { PENDING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .del_event(uuid) } /// This function is used to close an ongoing event and return the parsed vote associated with it. If the closure is successful, the owned event is returned for post-treatment. /// # Arguments /// /// * `uuid` - A Uuid representing the identifier of the event that is to be closed. /// /// ## Example: /// ```rust /// # use idlefox::votes::{ /// # add_pending_event, close_ongoing_event, make_into_ongoing_event, ParsedVote, /// # }; /// let id = add_pending_event(ParsedVote::default()).unwrap(); /// make_into_ongoing_event(id).unwrap(); /// close_ongoing_event(id).unwrap(); /// ``` pub fn close_ongoing_event(uuid: Uuid) -> Result { ONGOING_EVENTS .lock() .unwrap() // .map_err(|_| IdleError::MutexError)? .close_event(uuid) } /// Placeholder datatype /// /// Links to an event, active or planned type EventDataType = Uuid; /// Placeholder user data type /// /// Links back to an user #[deprecated(note = "This is an incorrect type to define an user")] type UserDataType = String; /// What an user voted for #[deprecated(note = "This is an incorrect type to define a voting ballot")] type VoteValueType = String; /// A vote, represents a user interraction towards an event #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(test, derive(Clone))] pub(crate) struct Ballot { /// The event the vote refers to linked_event: EventDataType, /// The user casting the vote user_handle: UserDataType, /// What the user voted for vote_value: VoteValueType, } /// The global status of the event #[derive(Serialize, Deserialize, Default, Debug, Clone, Copy)] pub(crate) enum EventStatus { #[default] /// The event exists but wasn't started yet Pending, /// The event was started but the finish date wasn't reached yet Started, /// The event was started and the date finish date was reached without being closed Finished, /// The event was closed and the outcome was made public Closed, /// The event was cancelled Cancelled, } // impl EventStatus { // /// Check if the event isn't closed, remove this abreration when you add another CLOSED_EVENT struct // fn not_closed(&self) -> bool { // matches!(self, EventStatus::Closed) // } // } /// An event, wether ongoing or planned #[derive(Debug, Serialize, Deserialize, Default)] #[cfg_attr(test, derive(Clone))] pub struct ParsedVote { /// The title of the even title: String, /// Description of the event description: String, /// The global status of the vote status: EventStatus, /// Date at which to autostart the vote process launch_date: NaiveDateTime, /// Date at which to autoclose the vote process close_date: NaiveDateTime, /// Date at which to autodelete the vote process auto_delete_date: NaiveDateTime, /// The inner list of votes cast votes: Vec, /// The list of values to vote for, this list all the valid dates to vote for list_candidates: NaiveDateList, // / The vote type } impl ParsedVote { // #[allow(dead_code, unused_variables)] // pub(crate) fn new( // title: String, // description: String, // status: EventStatus, // launch_date: NaiveDateTime, // close_date: NaiveDateTime, // // ballots: Vec, // list_candidates: NaiveDateList, // ) -> Self { // // Have a rather smart close date if not specified // todo!() // } /// All the logic behind a vote becoming live fn launch(&mut self) -> Result<(), IdleError> { // TODO: Define this self.status = EventStatus::Started; // Maybe send a message ? the bot will need the Uuid of the event to be able to add reaction // TODO: This is a vkypoint, as this method will need an IO interaction Ok(()) } /// Close the event fn close(&mut self) { self.status = EventStatus::Closed; } } // impl From for ParsedVote { // fn from(value: VoteContainer) -> Self { // todo!() // } // } impl Display for ParsedVote { /// A display for a vote, it is exactly what the discord bot will send fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // TODO: Complete this (vky) write!(f, "{:?}", self) } } // This split in two differents structs conceptually represents // the fact that very differents actions will be performed for each struct type EventListType = HashMap; // The list of pending events, not yet started /// /// This struct represents the collection of events that have been scheduled but have not yet begun. #[derive(Serialize, Deserialize)] pub struct PendingEvents { /// The list of pending events pending_events: EventListType, } impl PendingEvents { /// Create a new empty list of events, called in case of a first initialization. /// /// However, a deserialization will always be performed if possible. fn new() -> Self { Self { pending_events: EventListType::new(), } } /// Add a new event to the list of upcoming events. /// /// This function generates a new UUID for the event before adding it to the list. fn add_pending_event(&mut self, event: ParsedVote) -> Result { let id = Uuid::new_v4(); self.pending_events.insert(id, event); Ok(id) } /// Process and activate all upcoming events if the auto-launch time has been reached. /// /// Returns an `IdleError` if there's an issue launching any event or adding it to the ongoing list. pub fn process_upcoming(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { self.find_upcoming(current_time) .iter() .try_for_each(|uuid| { self.launch(*uuid)?; Ok(()) }) } /// Launch the specified event by moving it from pending events to ongoing events. /// /// Returns an `IdleError` if the event cannot be found in pending events. fn launch(&mut self, uuid: Uuid) -> Result<(), IdleError> { let event = self .pending_events .remove(&uuid) .ok_or(IdleError::EventLaunch(uuid))?; add_ongoing_event(uuid, event)?; // make_into_ongoing_event(uuid)?; Ok(()) } /// Find all events that are scheduled to start after the given date. /// /// Returns a vector of UUIDs corresponding to the upcoming events. fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec { self.pending_events .iter() .filter(|&(_, e)| e.launch_date <= current_time) .map(|(k, _v)| (*k)) .collect() } /// delete the event without launching it pub fn del_event(&mut self, uuid: Uuid) -> Result { self.pending_events .remove(&uuid) .ok_or(IdleError::DeleteEvent(uuid)) } // TODO: maybe add an update_upcoming(date) ? } /// The list of ongoing events, not yet closed /// /// This struct represents the collection of events that have been initiated but have not yet concluded. #[derive(Serialize, Deserialize)] pub struct OngoingEvents { /// The list of ongoing events ongoing_events: EventListType, } #[allow(dead_code, unused_variables)] impl OngoingEvents { /// Create a new empty list of ongoing events, called in case of a first initialization. /// /// However, a deserialization will always be performed if possible. fn new() -> Self { Self { ongoing_events: EventListType::new(), } } /// Remove all outdated votes for the current user /// /// This function is expected to be called periodically by the watchdog. pub(crate) fn prune_old(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { let mut failure = Vec::new(); for uuid in self.find_old(current_time) { if self.ongoing_events.remove(&uuid).is_none() { failure.push(uuid); } } match failure.is_empty() { true => Ok(()), false => Err(IdleError::EventPrune(failure)), } } /// Remove all outdated votes for the current user /// /// This function is expected to be called periodically by the watchdog. pub(crate) fn autoclose(&mut self, current_time: NaiveDateTime) -> Result<(), IdleError> { let failure = Vec::new(); for uuid in self.find_autoclose(current_time) { self.ongoing_events .get_mut(&uuid) .ok_or(IdleError::EventLaunch(uuid))? .close() } match failure.is_empty() { true => Ok(()), false => Err(IdleError::EventPrune(failure)), } } /// Find all events that are scheduled to be autoclosed. /// /// Returns a vector of UUIDs corresponding to the old events. fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec { self.ongoing_events .iter() // TODO: Remove this when you do the sensible thing and add a CLOSED_EVENT structure .filter(|(_, e)| { e.close_date <= current_time && !matches!(e.status, EventStatus::Closed) }) .map(|(k, _)| *k) .collect() } /// Find all events that are too old and supposed to be pruned. /// /// Returns a vector of UUIDs corresponding to the old events. fn find_old(&mut self, current_time: NaiveDateTime) -> Vec { self.ongoing_events .iter() .filter(|(_, e)| e.auto_delete_date <= current_time) .map(|(k, _)| *k) .collect() } /// Add a new event to the list of ongoing events. /// /// This function also launch the event based and adds a callback with the Uuid of the original caller. pub(crate) fn add_event(&mut self, id: Uuid, mut event: ParsedVote) -> Result<(), IdleError> { event.launch()?; self.ongoing_events.insert(id, event); Ok(()) } /// delete the event without launching it pub fn del_event(&mut self, uuid: Uuid) -> Result { self.ongoing_events .remove(&uuid) .ok_or(IdleError::DeleteEvent(uuid)) } /// Close an event removing it from the ongoing event list pub fn close_event(&mut self, uuid: Uuid) -> Result { // TODO: Another vkypoint, as we cant continue without knowing how to send a message let event = self .ongoing_events .remove(&uuid) .ok_or(IdleError::LaunchingEvent(uuid))?; let str_event = event.to_string(); // TODO: Do something with this string Ok(event) } // TODO: maybe add an update_ongoing(date) ? } /// The thread safe list of pending events pub static PENDING_EVENTS: LazyLock> = LazyLock::new(|| Mutex::new(PendingEvents::new())); /// The thread safe list of ongoing events pub static ONGOING_EVENTS: LazyLock> = LazyLock::new(|| Mutex::new(OngoingEvents::new())); #[cfg(test)] mod tests { use chrono::{Days, Local}; use super::*; macro_rules! gimme { ($ev: ident) => { $ev.lock().unwrap() }; } // Test all structs can be safely initialized #[test] fn init_test() { let _e = PendingEvents::new(); let _o = OngoingEvents::new(); assert!(PENDING_EVENTS.lock().is_ok()); assert!(ONGOING_EVENTS.lock().is_ok()); assert!(gimme!(PENDING_EVENTS) .process_upcoming(Local::now().naive_local()) .is_ok()); assert!(gimme!(ONGOING_EVENTS) .prune_old(Local::now().naive_local()) .is_ok()); } #[test] fn test_base_vote_handling() { // assert!(ParsedVote::default().launch(Uuid::new_v4()).is_ok()); let ev = ParsedVote::default(); // Can we add a vote ? let id = add_pending_event(ev.clone()).unwrap(); assert!(gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // Is the vote present ? del_pending_event(id).unwrap(); assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // Is the vote now deleted let id = add_pending_event(ev.clone()).unwrap(); make_into_ongoing_event(id).unwrap(); // Launching this event assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // Is the vote now not pending assert!(gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // Is the vote now ongoing close_ongoing_event(id).unwrap(); assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // Is the vote now not ongoing let id = add_pending_event(ev.clone()).unwrap(); make_into_ongoing_event(id).unwrap(); // Launching this event del_ongoing_event(id).unwrap(); assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // Is the vote now not ongoing } #[test] fn test_upcomming_events() { let now = Local::now().naive_local(); let later = now.checked_add_days(Days::new(1)).unwrap(); let very_later = now.checked_add_days(Days::new(3)).unwrap(); let very_very_later = now.checked_add_days(Days::new(7)).unwrap(); let event = ParsedVote { launch_date: later, close_date: very_later, auto_delete_date: very_very_later, ..Default::default() }; assert!(now < later); assert!(later < very_later); let id = add_pending_event(event).unwrap(); assert!(gimme!(PENDING_EVENTS).find_upcoming(now).is_empty()); // no upcomming events assert!(gimme!(ONGOING_EVENTS).find_old(now).is_empty()); // no old events assert!(gimme!(ONGOING_EVENTS).find_autoclose(now).is_empty()); // no old events gimme!(PENDING_EVENTS).process_upcoming(now).unwrap(); // nothing should be processed gimme!(ONGOING_EVENTS).prune_old(now).unwrap(); // nothing should be processed gimme!(ONGOING_EVENTS).autoclose(now).unwrap(); // nothing should be processed assert!(gimme!(PENDING_EVENTS).find_upcoming(now).is_empty()); // no upcomming events assert!(gimme!(ONGOING_EVENTS).find_old(now).is_empty()); // no old events assert!(gimme!(ONGOING_EVENTS).find_autoclose(now).is_empty()); // no old events assert!(gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's still here assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it's wasn't processed // Now some time passed assert_eq!(gimme!(PENDING_EVENTS).find_upcoming(later), vec![id]); // one upcomming event assert!(gimme!(ONGOING_EVENTS).find_old(later).is_empty()); // no old events assert!(gimme!(ONGOING_EVENTS).find_autoclose(later).is_empty()); // no old events gimme!(PENDING_EVENTS).process_upcoming(later).unwrap(); // one event should be processed gimme!(ONGOING_EVENTS).prune_old(later).unwrap(); // nothing should be processed gimme!(ONGOING_EVENTS).autoclose(later).unwrap(); // nothing should be processed assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore assert!(gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was processed // More time passed assert!(gimme!(PENDING_EVENTS).find_upcoming(very_later).is_empty()); // one upcomming event assert_eq!(gimme!(ONGOING_EVENTS).find_autoclose(very_later), vec![id]); // one old event assert!(gimme!(ONGOING_EVENTS).find_old(very_later).is_empty()); // no old events gimme!(PENDING_EVENTS).process_upcoming(very_later).unwrap(); // no event should be processed gimme!(ONGOING_EVENTS).prune_old(very_later).unwrap(); // nothing should be processed gimme!(ONGOING_EVENTS).autoclose(very_later).unwrap(); // nothing should be processed assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore assert!(gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was processed // More more time passed assert!(gimme!(PENDING_EVENTS) .find_upcoming(very_very_later) .is_empty()); // one upcomming event assert_eq!(gimme!(ONGOING_EVENTS).find_old(very_very_later), vec![id]); // one old event assert!(gimme!(ONGOING_EVENTS) .find_autoclose(very_very_later) .is_empty()); // no old events gimme!(PENDING_EVENTS) .process_upcoming(very_very_later) .unwrap(); // no event should be processed gimme!(ONGOING_EVENTS).prune_old(very_very_later).unwrap(); // nothing should be processed gimme!(ONGOING_EVENTS).autoclose(very_very_later).unwrap(); // nothing should be processed assert!(!gimme!(PENDING_EVENTS).pending_events.contains_key(&id)); // it's not here anymore assert!(!gimme!(ONGOING_EVENTS).ongoing_events.contains_key(&id)); // it was processed // TODO: Check the status at several points } // #[test] // #[ignore] // fn test_ongoing_events() { // unimplemented!() // } }