feat: Add an example about how to create a vote with comment
This commit is contained in:
@@ -73,6 +73,7 @@ pub struct Ballot {
|
||||
pub user_id: u32, // The ID of the user who cast this ballot
|
||||
pub vote_option_id: u8, // The 'id' of the VoteOption chosen
|
||||
pub shares_count: i64, // Number of shares/tokens/voting power
|
||||
pub comment: Option<String>, // Optional comment from the voter
|
||||
}
|
||||
|
||||
impl Ballot {
|
||||
@@ -94,6 +95,7 @@ impl Ballot {
|
||||
user_id,
|
||||
vote_option_id,
|
||||
shares_count,
|
||||
comment: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,4 +231,65 @@ impl Proposal {
|
||||
self.vote_status = new_status;
|
||||
self
|
||||
}
|
||||
|
||||
/// Cast a vote with a comment
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `ballot_id` - Optional ID for the ballot (use None for auto-generated ID)
|
||||
/// * `user_id` - ID of the user who is casting the vote
|
||||
/// * `chosen_option_id` - ID of the vote option chosen
|
||||
/// * `shares` - Number of shares/tokens/voting power
|
||||
/// * `comment` - Comment from the voter explaining their vote
|
||||
pub fn cast_vote_with_comment(
|
||||
mut self,
|
||||
ballot_id: Option<u32>,
|
||||
user_id: u32,
|
||||
chosen_option_id: u8,
|
||||
shares: i64,
|
||||
comment: impl ToString,
|
||||
) -> Self {
|
||||
// First check if voting is open
|
||||
if self.vote_status != VoteEventStatus::Open {
|
||||
eprintln!("Voting is not open for proposal '{}'", self.title);
|
||||
return self;
|
||||
}
|
||||
|
||||
// Check if the option exists
|
||||
if !self.options.iter().any(|opt| opt.id == chosen_option_id) {
|
||||
eprintln!(
|
||||
"Chosen option ID {} does not exist for proposal '{}'",
|
||||
chosen_option_id, self.title
|
||||
);
|
||||
return self;
|
||||
}
|
||||
|
||||
// Check eligibility for private proposals
|
||||
if let Some(group) = &self.private_group {
|
||||
if !group.contains(&user_id) {
|
||||
eprintln!(
|
||||
"User {} is not eligible to vote on proposal '{}'",
|
||||
user_id, self.title
|
||||
);
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new ballot with the comment
|
||||
let mut new_ballot = Ballot::new(ballot_id, user_id, chosen_option_id, shares);
|
||||
new_ballot.comment = Some(comment.to_string());
|
||||
|
||||
// Add the ballot to the proposal
|
||||
self.ballots.push(new_ballot);
|
||||
|
||||
// Update the vote count for the chosen option
|
||||
if let Some(option) = self
|
||||
.options
|
||||
.iter_mut()
|
||||
.find(|opt| opt.id == chosen_option_id)
|
||||
{
|
||||
option.count += shares;
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user