From b4a3998ae49ad5f67e02883fe92bb3ae86118799 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 9 Nov 2024 19:24:27 +0100 Subject: [PATCH] Refactors votes into four files --- badges/coverage.svg | 2 +- src/date/mod.rs | 3 + src/votes/ballots.rs | 22 ++ src/votes/events.rs | 116 ++++++++++ src/votes/helper_functions.rs | 194 ++++++++++++++++ src/{votes.rs => votes/holders.rs} | 349 ++--------------------------- src/votes/mod.rs | 50 +++++ 7 files changed, 409 insertions(+), 327 deletions(-) create mode 100644 src/votes/ballots.rs create mode 100644 src/votes/events.rs create mode 100644 src/votes/helper_functions.rs rename src/{votes.rs => votes/holders.rs} (51%) create mode 100644 src/votes/mod.rs diff --git a/badges/coverage.svg b/badges/coverage.svg index 5db7502..dd3016a 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 91%test-coverage91% +test-coverage: 89%test-coverage89% diff --git a/src/date/mod.rs b/src/date/mod.rs index 77062f2..6e481f4 100644 --- a/src/date/mod.rs +++ b/src/date/mod.rs @@ -54,5 +54,8 @@ pub mod date_tools; // Republishing important functions pub use date_parse::parse_str_into_date; pub use date_tools::parse_date_list; + +pub use date_tools::NaiveDateList; +pub use date_tools::NaiveDateObject; // pub use date_tools::naivelistfromstr; // pub use date_tools::naivedayfromstr; diff --git a/src/votes/ballots.rs b/src/votes/ballots.rs new file mode 100644 index 0000000..41b7980 --- /dev/null +++ b/src/votes/ballots.rs @@ -0,0 +1,22 @@ +//! The ballot submodule provides functionality for managing user ballots, which include casting votes towards events. +//! +//! # Important Structures +//! +//! * `Ballot`: Represents a single vote cast by a user towards an event. It includes fields for the event ID, user handle, +//! and the value or option voted for. +use serde::{Deserialize, Serialize}; + +use super::{BallotValueType, EventIdType, UserDataType}; + +/// A `Ballot` represents a user interaction towards an event. This struct is used to record the details of a vote, +/// including which user casted it, which event it pertains to, and what value or option was voted for. +#[derive(Serialize, Deserialize, Debug)] +#[cfg_attr(test, derive(Clone))] +pub struct Ballot { + /// The event the vote refers to + linked_event: EventIdType, + /// The user casting the vote + user_handle: UserDataType, + /// What the user voted for + vote_value: BallotValueType, +} diff --git a/src/votes/events.rs b/src/votes/events.rs new file mode 100644 index 0000000..9a60be7 --- /dev/null +++ b/src/votes/events.rs @@ -0,0 +1,116 @@ +//! The `voting_events` submodule is dedicated to managing the lifecycle and +//! functionality of voting events +//! +//! * `ParsedVote`: A comprehensive structure that represents a single vote, +//! encapsulating both ongoing and planned votes. It stores information +//! about the event's title, description, status, start and end dates, +//! auto-delete date, votes cast by users, list of valid options (candidates) +//! for the vote, and type of vote being conducted. +//! * `EventStatus`: An enumeration that defines various states a voting event +//! can be in, such as planned, ongoing, closed, and cancelled. This helps +//! to track and manage the progression of each voting event according to +//! predefined rules and conditions. + +use std::fmt::Display; + +use chrono::NaiveDateTime; +use serde::{Deserialize, Serialize}; + +use crate::{date::NaiveDateList, io::VoteContainer, IdleError}; + +use super::Ballot; + +/// An enumeration representing the global status of an event +/// +/// This enum is used to track the progress of an event from its creation to completion, +/// including various states that can be transitioned through. It is primarily intended +/// for internal use within the application. +#[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, +} + +/// A `ParsedVote` represents a voting event that has been parsed and validated. It +/// contains all necessary information about the voting process itself. +/// +/// This structure is specifically used within the application to encapsulate both +/// ongoing and planned voting events, providing a clear and organized way to manage their +/// data throughout their lifecycle. +#[derive(Debug, Serialize, Deserialize, Default)] +#[cfg_attr(test, derive(Clone))] +pub struct ParsedVote { + /// The title of the even + pub(super) title: String, + /// Description of the event + pub(super) description: String, + /// The global status of the vote + pub(super) status: EventStatus, + /// Date at which to autostart the vote process + pub(super) launch_date: NaiveDateTime, + /// Date at which to autoclose the vote process + pub(super) close_date: NaiveDateTime, + /// Date at which to autodelete the vote process + pub(super) auto_delete_date: NaiveDateTime, + /// The inner list of votes cast + pub(super) votes: Vec, + /// The list of values to vote for, this list all the valid dates to vote for + pub(super) 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 + pub(super) 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 + pub(super) fn close(&mut self) { + self.status = EventStatus::Closed; + } +} + +impl TryFrom for ParsedVote { + type Error = IdleError; + + fn try_from(value: VoteContainer) -> Result { + let _ = value; + 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) + } +} diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs new file mode 100644 index 0000000..1ad4349 --- /dev/null +++ b/src/votes/helper_functions.rs @@ -0,0 +1,194 @@ +//! Submodule including all helper functions to handle vote creation and evolution +//! +use std::sync::{Arc, Mutex}; + +use chrono::NaiveDate; +use uuid::Uuid; + +use crate::IdleError; + +use super::{OngoingEvents, ParsedVote, PendingEvents}; + +/// 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, EventHolder, ParsedVote}; +/// let ev_ctx = EventHolder::default(); +/// let parsed_vote = ParsedVote::default(); +/// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap(); +/// ``` +pub fn add_pending_event(event: ParsedVote, ev_ctx: &EventHolder) -> Result { + ev_ctx + .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, EventHolder}; +/// let ev_ctx = EventHolder::default(); +/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); +/// +/// make_into_ongoing_event(id, &ev_ctx).unwrap() +/// ``` +pub fn make_into_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { + ev_ctx + .pending_events + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .launch(uuid, ev_ctx) +} + +/// 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, EventHolder}; +/// let ev_ctx = EventHolder::default(); +/// let uuid = Uuid::new_v4(); // A new id +/// let parsed_vote = ParsedVote::default(); // A very legit event +/// +/// add_ongoing_event(uuid, parsed_vote, &ev_ctx).unwrap(); +/// ``` +pub fn add_ongoing_event( + uuid: Uuid, + event: ParsedVote, + ev_ctx: &EventHolder, +) -> Result<(), IdleError> { + ev_ctx + .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, EventHolder +/// # }; +/// let ev_ctx = EventHolder::default(); +/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); +/// make_into_ongoing_event(id, &ev_ctx).unwrap(); +/// +/// del_ongoing_event(id, &ev_ctx).unwrap(); +/// ``` +pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { + ev_ctx + .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, EventHolder +/// # }; +/// let ev_ctx = EventHolder::default(); +/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); +/// del_pending_event(id, &ev_ctx).unwrap(); +/// ``` +pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { + ev_ctx + .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, EventHolder, +/// # }; +/// let ev_ctx = EventHolder::default(); +/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); +/// make_into_ongoing_event(id, &ev_ctx).unwrap(); +/// close_ongoing_event(id, &ev_ctx).unwrap(); +/// ``` +pub fn close_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { + ev_ctx + .ongoing_events + .lock() + .unwrap() + // .map_err(|_| IdleError::MutexError)? + .close_event(uuid) +} + +/// A link to all events, to be shared between threads related to this event pool. +/// +/// This struct serves as a central hub for managing and accessing different states of events within the +/// system. It provides access to pending, ongoing, and potentially closed events. +/// The use of `Arc>` ensures that the events can be safely shared and modified across multiple +/// threads without running into race conditions or other concurrency issues. +#[derive(Clone, Default)] +pub struct EventHolder { + /// A reference-counted pointer to a mutex-protected `PendingEvents` instance, managing all pending events. + /// + /// Pending events are those that have been scheduled but not yet started + pub pending_events: Arc>, + /// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all ongoing events. + /// + /// Ongoing events are currently running but not yet closed. + pub ongoing_events: Arc>, + // /// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all closed events. + // /// + // /// Closed events have been voted up but havent been deleted and can therefore be watched or opened again. + // /// These events will be autodeleted after a while + // pub closed_events: Mutex, + /// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated. + pub old_date: Arc>, + + /// The newly created discord context + pub discord_ctx: Arc>>, +} diff --git a/src/votes.rs b/src/votes/holders.rs similarity index 51% rename from src/votes.rs rename to src/votes/holders.rs index 3a94efd..cb22f21 100644 --- a/src/votes.rs +++ b/src/votes/holders.rs @@ -1,325 +1,23 @@ -//! Module that handles all the logic related to votes within an application. +//! This module is responsible for managing events in an application. It includes +//! functionality to handle both pending and ongoing events, with support for categorizing +//! them based on their status. //! -//! 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. +//! *Important Structures:* +//! - `PendingEvents`: Manages pending events +//! - `OngoingEvents`: Manages ongoing events +//! - `ClosedEvents`: Represents closed events (TODO: Implementation needed) //! //! 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::{Arc, Mutex}, -}; - -use chrono::{NaiveDate, NaiveDateTime}; +//! The module aims to provide a robust framework for managing event lifecycles within an +//! application, ensuring separation between pending and ongoing events and supporting +//! actions such as adding, launching, processing, and autoclosing events. +use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::{date::date_tools::NaiveDateList, error_handling::IdleError}; +use crate::IdleError; -/// A link to all events, to be shared between threads related to this event pool. -/// -/// This struct serves as a central hub for managing and accessing different states of events within the -/// system. It provides access to pending, ongoing, and potentially closed events. -/// The use of `Arc>` ensures that the events can be safely shared and modified across multiple -/// threads without running into race conditions or other concurrency issues. -#[derive(Clone, Default)] -pub struct EventHolder { - /// A reference-counted pointer to a mutex-protected `PendingEvents` instance, managing all pending events. - /// - /// Pending events are those that have been scheduled but not yet started - pub pending_events: Arc>, - /// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all ongoing events. - /// - /// Ongoing events are currently running but not yet closed. - pub ongoing_events: Arc>, - // /// A reference-counted pointer to a mutex-protected `OngoingEvents` instance, managing all closed events. - // /// - // /// Closed events have been voted up but havent been deleted and can therefore be watched or opened again. - // /// These events will be autodeleted after a while - // pub closed_events: Mutex, - /// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated. - pub old_date: Arc>, - - /// The newly created discord context - pub discord_ctx: Arc>>, -} - -/// 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, EventHolder, ParsedVote}; -/// let ev_ctx = EventHolder::default(); -/// let parsed_vote = ParsedVote::default(); -/// let id = add_pending_event(parsed_vote, &ev_ctx).unwrap(); -/// ``` -pub fn add_pending_event(event: ParsedVote, ev_ctx: &EventHolder) -> Result { - ev_ctx - .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, EventHolder}; -/// let ev_ctx = EventHolder::default(); -/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); -/// -/// make_into_ongoing_event(id, &ev_ctx).unwrap() -/// ``` -pub fn make_into_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { - ev_ctx - .pending_events - .lock() - .unwrap() - // .map_err(|_| IdleError::MutexError)? - .launch(uuid, ev_ctx) -} - -/// 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, EventHolder}; -/// let ev_ctx = EventHolder::default(); -/// let uuid = Uuid::new_v4(); // A new id -/// let parsed_vote = ParsedVote::default(); // A very legit event -/// -/// add_ongoing_event(uuid, parsed_vote, &ev_ctx).unwrap(); -/// ``` -pub fn add_ongoing_event( - uuid: Uuid, - event: ParsedVote, - ev_ctx: &EventHolder, -) -> Result<(), IdleError> { - ev_ctx - .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, EventHolder -/// # }; -/// let ev_ctx = EventHolder::default(); -/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); -/// make_into_ongoing_event(id, &ev_ctx).unwrap(); -/// -/// del_ongoing_event(id, &ev_ctx).unwrap(); -/// ``` -pub fn del_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { - ev_ctx - .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, EventHolder -/// # }; -/// let ev_ctx = EventHolder::default(); -/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); -/// del_pending_event(id, &ev_ctx).unwrap(); -/// ``` -pub fn del_pending_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { - ev_ctx - .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, EventHolder, -/// # }; -/// let ev_ctx = EventHolder::default(); -/// let id = add_pending_event(ParsedVote::default(), &ev_ctx).unwrap(); -/// make_into_ongoing_event(id, &ev_ctx).unwrap(); -/// close_ongoing_event(id, &ev_ctx).unwrap(); -/// ``` -pub fn close_ongoing_event(uuid: Uuid, ev_ctx: &EventHolder) -> Result { - ev_ctx - .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, -} - -/// 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; +use super::{add_ongoing_event, events::EventStatus, EventHolder, EventListType, ParsedVote}; /// The list of pending events, not yet started /// @@ -343,7 +41,7 @@ impl PendingEvents { /// 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 { + pub(super) fn add_pending_event(&mut self, event: ParsedVote) -> Result { let id = Uuid::new_v4(); self.pending_events.insert(id, event); Ok(id) @@ -368,7 +66,7 @@ impl PendingEvents { /// 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, ev_ctx: &EventHolder) -> Result<(), IdleError> { + pub(super) fn launch(&mut self, uuid: Uuid, ev_ctx: &EventHolder) -> Result<(), IdleError> { let event = self .pending_events .remove(&uuid) @@ -381,7 +79,7 @@ impl PendingEvents { /// 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 { + pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec { self.pending_events .iter() .filter(|&(_, e)| e.launch_date <= current_time) @@ -459,7 +157,7 @@ impl OngoingEvents { /// 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 { + pub(super) 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 @@ -473,7 +171,7 @@ impl OngoingEvents { /// 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 { + pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec { self.ongoing_events .iter() .filter(|(_, e)| e.auto_delete_date <= current_time) @@ -514,6 +212,11 @@ impl OngoingEvents { mod tests { use chrono::{Days, Local}; + use crate::votes::{ + add_pending_event, close_ongoing_event, del_ongoing_event, del_pending_event, + make_into_ongoing_event, + }; + use super::*; macro_rules! g { ($ev: expr) => { @@ -624,10 +327,4 @@ mod tests { // TODO: Check the status at several points } - - // #[test] - // #[ignore] - // fn test_ongoing_events() { - // unimplemented!() - // } } diff --git a/src/votes/mod.rs b/src/votes/mod.rs new file mode 100644 index 0000000..ea6b3c2 --- /dev/null +++ b/src/votes/mod.rs @@ -0,0 +1,50 @@ +//! 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)] + +mod ballots; +mod events; +mod helper_functions; +mod holders; + +// Republish +pub use ballots::Ballot; +pub use events::ParsedVote; +pub use helper_functions::EventHolder; +pub use helper_functions::*; +pub use holders::{OngoingEvents, PendingEvents}; + +use std::collections::HashMap; + +use uuid::Uuid; + +/// This split in two differents structs conceptually represents +/// the fact that very differents actions will be performed for each struct +type EventListType = HashMap; + +/// Placeholder datatype +/// +/// Links to an event, active or planned +pub type EventIdType = Uuid; + +/// Placeholder user data type +/// +/// Links back to an user +#[deprecated(note = "This is an incorrect type to define an user")] +pub type UserDataType = String; + +/// What an user voted for +#[deprecated(note = "This is an incorrect type to define a voting ballot")] +pub type BallotValueType = String; -- 2.45.1