diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index 3920ae9..7636c04 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -148,8 +148,8 @@ pub enum NaiveDateObject { /// This struct provides an abstraction over a list of date objects, enabling both sequential iteration /// over the dates in order or direct access to any date by its index. The structure is designed to handle /// different sources of date information, allowing for flexible data manipulation based on the provided dates. -#[derive(Debug, Default, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq, Eq, Clone))] +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +#[cfg_attr(test, derive(PartialEq, Eq))] pub struct NaiveDateList { /// The inner vector inner: Vec, diff --git a/src/ids.rs b/src/ids.rs index 4913eb8..9ed2f23 100644 --- a/src/ids.rs +++ b/src/ids.rs @@ -1,18 +1,46 @@ -//! Handle all Ids functionalities +//! This module contains utilities for generating event ids. //! //! Features: //! Generating a human readable ID for a HUID //! Finding the HUID from an ID //! Removing ID as needed +use crate::votes::EventHolder; + /// Generic type representing an ID pub type EventIdType = String; /// Generate an id +/// +/// # Examples +/// +/// ``` +/// use idlefox::ids::generate_id; +/// let id: String = generate_id(); +/// println!("Generated id: {}", id); +/// ``` pub fn generate_id() -> String { human_ids::generate(None) } +/// Generate a unique id, slower in timing but insure zero collision at runtime +/// +/// # Examples +/// +/// ``` +/// use idlefox::ids::generate_unique_id; +/// # use idlefox::votes::EventHolder; +/// let holder = EventHolder::default(); +/// let id: String = generate_unique_id(&holder); +/// println!("Generated id: {}", id); +pub fn generate_unique_id(holder: &EventHolder) -> String { + let id = generate_id(); + match holder.contains_event(&id) { + true => generate_unique_id(holder), + false => id, + } +} + #[cfg(test)] mod test { use super::generate_id; diff --git a/src/votes/ballots.rs b/src/votes/ballots.rs index 6275c5f..ab1c599 100644 --- a/src/votes/ballots.rs +++ b/src/votes/ballots.rs @@ -10,8 +10,8 @@ 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, Eq, PartialEq))] +#[derive(Serialize, Deserialize, Debug, Clone)] +#[cfg_attr(test, derive(Eq, PartialEq))] pub struct Ballot { /// The event the vote refers to linked_event: EventIdType, diff --git a/src/votes/events.rs b/src/votes/events.rs index 84fc634..65034b7 100644 --- a/src/votes/events.rs +++ b/src/votes/events.rs @@ -27,8 +27,8 @@ use super::Ballot; /// A pending event, waiting to be opened. In this state the even can be safely modified /// and either manual input or the autostart date will start the vote. -#[derive(Serialize, Deserialize, Default)] -#[cfg_attr(test, derive(Clone, Debug, PartialEq, Eq))] +#[derive(Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] pub struct EventPending { /// The parsed representation of the vote associated with this event. /// It holds the details required for the voting process. @@ -43,8 +43,8 @@ impl EventPending { } } -#[derive(Serialize, Deserialize)] -#[cfg_attr(test, derive(Debug, PartialEq, Clone))] +#[derive(Serialize, Deserialize, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] // An ongoing event, waiting to be closed thus allowing the ballots to be counted. pub struct EventOngoing { /// The parsed representation of the vote associated with this event. @@ -66,8 +66,8 @@ impl EventOngoing { } } -#[derive(Serialize, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Serialize, Deserialize, Clone)] +// #[cfg_attr(test, derive(Clone))] /// A closed event, while the users cannot interract with it in this state, /// this event can still be reopened and it's results can be read. /// All events have an expiry date and in this state the event will be cleaned @@ -86,8 +86,8 @@ pub struct EventClosed { /// 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, Eq, PartialEq))] +#[derive(Debug, Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Eq, PartialEq))] pub(super) struct ParsedVote { /// The title of the even pub(super) title: String, diff --git a/src/votes/helper_functions.rs b/src/votes/helper_functions.rs index fafc1e0..f4f0d60 100644 --- a/src/votes/helper_functions.rs +++ b/src/votes/helper_functions.rs @@ -5,7 +5,7 @@ use std::{fs::File, sync::Arc}; use super::{ events::{EventOngoing, EventPending}, - holders::ListClosedEvents, + holders::{ListClosedEvents, TypedEvent}, ListOngoingEvents, ListPendingEvents, }; use crate::{ @@ -210,6 +210,15 @@ pub struct EventHolder { pub discord_ctx: Arc>>, } +/// Access the inner value by borrowing the inner wrapper +/// +/// A macro is better than a trait and polymorphic code at this scale +macro_rules! inner { + ($value:expr) => { + $value.lock().unwrap().borrow_inner() + }; +} + impl EventHolder { pub fn try_load_from_disk() -> Result { Ok(Self { @@ -240,4 +249,34 @@ impl EventHolder { save_to_writer!(&holder.old_date, NaiveDate, "data/old_date.json"); Ok(()) } + + /// Check wether the holder contains an event + /// + /// This is a low level plumbing tool, mostly used to check for collisions + pub(crate) fn contains_event(&self, id: &String) -> bool { + inner!(self.pending_events).contains_key(id) + || inner!(self.pending_events).contains_key(id) + || inner!(self.pending_events).contains_key(id) + } + + /// Try to find an even by it's id, returns a TypedEvent to keep track of the location of the event + /// + /// Note that this function is useless right now as it clones the event making it very impractical + #[deprecated] + #[allow(dead_code)] + pub(crate) fn find_event(&self, id: &String) -> Option { + inner!(self.pending_events) + .get(id) + .map(|e| TypedEvent::Pending(e.clone())) + .or_else(|| { + inner!(self.ongoing_events) + .get(id) + .map(|e| TypedEvent::Ongoing(e.clone())) + }) + .or_else(|| { + inner!(self.closed_events) + .get(id) + .map(|e| TypedEvent::Closed(e.clone())) + }) + } } diff --git a/src/votes/holders.rs b/src/votes/holders.rs index f20b426..48dfb3a 100644 --- a/src/votes/holders.rs +++ b/src/votes/holders.rs @@ -12,6 +12,8 @@ //! application, ensuring separation between pending and ongoing events and supporting //! actions such as adding, launching, processing, and autoclosing events. +use std::collections::HashMap; + use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; @@ -98,13 +100,22 @@ impl ListPendingEvents { } // TODO: maybe add an update_upcoming(date) ? + // /// + // pub fn contains_event(&self, id: &str) -> bool { + // self.pending_events.contains_key(id) + // } + + /// Borrow the inner pending events + pub fn borrow_inner(&self) -> &HashMap { + &self.pending_events + } } /// 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, Default)] -#[cfg_attr(test, derive(Debug, PartialEq, Clone))] +#[derive(Serialize, Deserialize, Default, Clone)] +#[cfg_attr(test, derive(Debug, PartialEq))] pub struct ListOngoingEvents { /// The list of ongoing events ongoing_events: OngoingHashmap, @@ -183,7 +194,11 @@ impl ListOngoingEvents { .map(|(k, _)| k.clone()) .collect() } - // TODO: maybe add an update_ongoing(date) ? + + /// Borrow the inner ongoing events + pub fn borrow_inner(&self) -> &HashMap { + &self.ongoing_events + } } /// The list of closed events @@ -232,6 +247,23 @@ impl ListClosedEvents { false => Err(IdleError::EventPrune(failure)), } } + + /// Borrow the inner ongoing events + pub fn borrow_inner(&self) -> &HashMap { + &self.closed_events + } +} + +/// A generic event, holding an event and his type as variants, +/// doing so is the easiest way to pass an event around outside of the event lists +#[allow(dead_code)] +pub enum TypedEvent { + /// Event that is ongoing. + Ongoing(EventOngoing), + /// Event that has yet to be resolved. + Pending(EventPending), + /// Event that has been resolved and is pending deletion. + Closed(EventClosed), } #[cfg(test)]