Refactors votes into four files #36

Merged
Dandaedre merged 1 commits from dan into dev 2024-11-09 19:24:52 +01:00
7 changed files with 409 additions and 327 deletions

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 91%"><title>test-coverage: 91%</title><linearGradient id="bms-face6f22b39fe244" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-face6f22b39fe244"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-face6f22b39fe244)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-face6f22b39fe244)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">91%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">91%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 89%"><title>test-coverage: 89%</title><linearGradient id="bms-72c388a7ffe9bb07" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-72c388a7ffe9bb07"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-72c388a7ffe9bb07)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-72c388a7ffe9bb07)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">89%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">89%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -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;

22
src/votes/ballots.rs Normal file
View File

@ -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,
}

116
src/votes/events.rs Normal file
View File

@ -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<Ballot>,
/// 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<Ballot>,
// 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<VoteContainer> for ParsedVote {
type Error = IdleError;
fn try_from(value: VoteContainer) -> Result<Self, Self::Error> {
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)
}
}

View File

@ -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<Uuid, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
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<Mutex<>>` 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<Mutex<PendingEvents>>,
/// 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<Mutex<OngoingEvents>>,
// /// 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<ClosedEvents>,
/// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated.
pub old_date: Arc<Mutex<NaiveDate>>,
/// The newly created discord context
pub discord_ctx: Arc<Mutex<Option<poise::serenity_prelude::Context>>>,
}

View File

@ -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<Mutex<>>` 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<Mutex<PendingEvents>>,
/// 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<Mutex<OngoingEvents>>,
// /// 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<ClosedEvents>,
/// A reference-counted pointer to a mutex-protected `NaiveDate` instance, representing the last date the watchdog was updated.
pub old_date: Arc<Mutex<NaiveDate>>,
/// The newly created discord context
pub discord_ctx: Arc<Mutex<Option<poise::serenity_prelude::Context>>>,
}
/// 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<Uuid, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
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<ParsedVote, IdleError> {
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<Ballot>,
/// 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<Ballot>,
// 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<VoteContainer> 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<Uuid, ParsedVote>;
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<Uuid, IdleError> {
pub(super) fn add_pending_event(&mut self, event: ParsedVote) -> Result<Uuid, IdleError> {
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<Uuid> {
pub(super) fn find_upcoming(&self, current_time: NaiveDateTime) -> Vec<Uuid> {
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<Uuid> {
pub(super) fn find_autoclose(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
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<Uuid> {
pub(super) fn find_old(&mut self, current_time: NaiveDateTime) -> Vec<Uuid> {
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!()
// }
}

50
src/votes/mod.rs Normal file
View File

@ -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<EventIdType, ParsedVote>;
/// 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;