fix: Fix all examples

This commit is contained in:
Mahmoud Emad 2025-05-17 16:03:00 +03:00
parent 57f59da43e
commit e4c50ca9d7
19 changed files with 166 additions and 80 deletions

View File

@ -1,8 +1,8 @@
// Get the database instance // Get the database instance
let db = get_db(); let db = get_db();
// Create a new calendar // Create a new calendar with auto-generated ID (pass 0 for auto-generated ID)
let calendar = calendar__builder(1); let calendar = calendar__builder(0);
calendar.name = "My First Calendar"; calendar.name = "My First Calendar";
set_description(calendar, "A calendar for testing Rhai integration"); set_description(calendar, "A calendar for testing Rhai integration");
@ -26,8 +26,8 @@ if calendar_exists(db, 1) {
print("Failed to retrieve calendar with ID 1"); print("Failed to retrieve calendar with ID 1");
} }
// Create another calendar // Create another calendar with auto-generated ID
let calendar2 = calendar__builder(2); let calendar2 = calendar__builder(0);
calendar2.name = "My Second Calendar"; calendar2.name = "My Second Calendar";
set_description(calendar2, "Another calendar for testing"); set_description(calendar2, "Another calendar for testing");

View File

@ -21,7 +21,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Register a calendar builder function // Register a calendar builder function
engine.register_fn("calendar__builder", |id: i64| { engine.register_fn("calendar__builder", |id: i64| {
Calendar::new(id as u32, "New Calendar") let id_option = if id <= 0 { None } else { Some(id as u32) };
Calendar::new(id_option, "New Calendar")
}); });
// Register setter methods for Calendar properties // Register setter methods for Calendar properties
@ -47,7 +48,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
engine.register_fn("get_calendar_by_id", |_db: Arc<OurDB>, id: i64| -> Calendar { engine.register_fn("get_calendar_by_id", |_db: Arc<OurDB>, id: i64| -> Calendar {
// In a real implementation, this would retrieve the calendar from the database // In a real implementation, this would retrieve the calendar from the database
Calendar::new(id as u32, "Retrieved Calendar") Calendar::new(Some(id as u32), "Retrieved Calendar")
}); });
// Register a function to check if a calendar exists // Register a function to check if a calendar exists
@ -59,7 +60,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Define the function separately to use with the wrap_vec_return macro // Define the function separately to use with the wrap_vec_return macro
fn get_all_calendars(_db: Arc<OurDB>) -> Vec<Calendar> { fn get_all_calendars(_db: Arc<OurDB>) -> Vec<Calendar> {
// In a real implementation, this would retrieve all calendars from the database // In a real implementation, this would retrieve all calendars from the database
vec![Calendar::new(1, "Calendar 1"), Calendar::new(2, "Calendar 2")] vec![Calendar::new(Some(1), "Calendar 1"), Calendar::new(Some(2), "Calendar 2")]
} }
// Register the function with the wrap_vec_return macro // Register the function with the wrap_vec_return macro

View File

@ -1,11 +1,16 @@
// heromodels/examples/governance_proposal_example/main.rs // heromodels/examples/governance_proposal_example/main.rs
use chrono::{Utc, Duration}; use chrono::{Utc, Duration};
use heromodels::db::{Collection, Db};
use heromodels::models::governance::{Proposal, ProposalStatus, VoteEventStatus}; use heromodels::models::governance::{Proposal, ProposalStatus, VoteEventStatus};
fn main() { fn main() {
println!("Governance Proposal Model Example\n"); println!("Governance Proposal Model Example\n");
// Create a new DB instance, reset before every run
let db_path = "/tmp/ourdb_governance_proposal_example";
let db = heromodels::db::hero::OurDB::new(db_path, true).expect("Can create DB");
// Create a new proposal with auto-generated ID // Create a new proposal with auto-generated ID
let mut proposal = Proposal::new( let mut proposal = Proposal::new(
None, // id (auto-generated) None, // id (auto-generated)
@ -16,9 +21,9 @@ fn main() {
Utc::now() + Duration::days(14) // vote_end_date (14 days from now) Utc::now() + Duration::days(14) // vote_end_date (14 days from now)
); );
println!("Created Proposal: '{}' (ID: {})", proposal.title, proposal.base_data.id); println!("Before saving - Created Proposal: '{}' (ID: {})", proposal.title, proposal.base_data.id);
println!("Status: {:?}, Vote Status: {:?}", proposal.status, proposal.vote_status); println!("Before saving - Status: {:?}, Vote Status: {:?}", proposal.status, proposal.vote_status);
println!("Vote Period: {} to {}\n", proposal.vote_start_date, proposal.vote_end_date); println!("Before saving - Vote Period: {} to {}\n", proposal.vote_start_date, proposal.vote_end_date);
// Add vote options // Add vote options
proposal = proposal.add_option(1, "Approve Allocation"); proposal = proposal.add_option(1, "Approve Allocation");
@ -31,6 +36,16 @@ fn main() {
} }
println!(""); println!("");
// Save the proposal to the database
let collection = db.collection::<Proposal>().expect("can open proposal collection");
let (proposal_id, saved_proposal) = collection.set(&proposal).expect("can save proposal");
println!("After saving - Proposal ID: {}", saved_proposal.base_data.id);
println!("After saving - Returned ID: {}", proposal_id);
// Use the saved proposal for further operations
proposal = saved_proposal;
// Simulate casting votes // Simulate casting votes
println!("Simulating Votes..."); println!("Simulating Votes...");
// User 1 votes for 'Approve Allocation' with 100 shares (with explicit ballot ID) // User 1 votes for 'Approve Allocation' with 100 shares (with explicit ballot ID)
@ -83,7 +98,7 @@ fn main() {
// Example of a private proposal (not fully implemented in cast_vote eligibility yet) // Example of a private proposal (not fully implemented in cast_vote eligibility yet)
let mut private_proposal = Proposal::new( let mut private_proposal = Proposal::new(
Some(2), // explicit ID None, // auto-generated ID
"user_admin_001", "user_admin_001",
"Internal Team Restructure Vote", "Internal Team Restructure Vote",
"Vote on proposed internal team changes.", "Vote on proposed internal team changes.",
@ -94,8 +109,16 @@ fn main() {
private_proposal = private_proposal.add_option(1, "Accept Restructure"); private_proposal = private_proposal.add_option(1, "Accept Restructure");
private_proposal = private_proposal.add_option(2, "Reject Restructure"); private_proposal = private_proposal.add_option(2, "Reject Restructure");
println!("\nCreated Private Proposal: '{}'", private_proposal.title); println!("\nBefore saving - Created Private Proposal: '{}'", private_proposal.title);
println!("Eligible Voters (Group): {:?}", private_proposal.private_group); println!("Before saving - Eligible Voters (Group): {:?}", private_proposal.private_group);
// Save the private proposal to the database
let (private_proposal_id, saved_private_proposal) = collection.set(&private_proposal).expect("can save private proposal");
private_proposal = saved_private_proposal;
println!("After saving - Private Proposal ID: {}", private_proposal.base_data.id);
println!("After saving - Returned ID: {}", private_proposal_id);
// User 10 (eligible) votes with explicit ballot ID // User 10 (eligible) votes with explicit ballot ID
private_proposal = private_proposal.cast_vote(Some(201), 10, 1, 100); private_proposal = private_proposal.cast_vote(Some(201), 10, 1, 100);
// User 40 (ineligible) tries to vote with auto-generated ballot ID // User 40 (ineligible) tries to vote with auto-generated ballot ID
@ -106,5 +129,6 @@ fn main() {
println!(" - {}: {} (Votes: {})", option.id, option.text, option.count); println!(" - {}: {} (Votes: {})", option.id, option.text, option.count);
} }
println!("\nGovernance Proposal Example Finished."); println!("\nExample finished. DB stored at {}", db_path);
println!("To clean up, you can manually delete the directory: {}", db_path);
} }

View File

@ -27,7 +27,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
engine.register_fn("create_proposal", |id: i64, creator_id: String, title: String, description: String| { engine.register_fn("create_proposal", |id: i64, creator_id: String, title: String, description: String| {
let start_date = Utc::now(); let start_date = Utc::now();
let end_date = start_date + Duration::days(14); let end_date = start_date + Duration::days(14);
Proposal::new(id as u32, creator_id, title, description, start_date, end_date) let id_option = if id <= 0 { None } else { Some(id as u32) };
Proposal::new(id_option, creator_id, title, description, start_date, end_date)
}); });
engine.register_fn("create_vote_option", |id: i64, text: String| { engine.register_fn("create_vote_option", |id: i64, text: String| {
@ -35,7 +36,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}); });
engine.register_fn("create_ballot", |id: i64, user_id: i64, vote_option_id: i64, shares_count: i64| { engine.register_fn("create_ballot", |id: i64, user_id: i64, vote_option_id: i64, shares_count: i64| {
Ballot::new(id as u32, user_id as u32, vote_option_id as u8, shares_count) let id_option = if id <= 0 { None } else { Some(id as u32) };
Ballot::new(id_option, user_id as u32, vote_option_id as u8, shares_count)
}); });
// Register getter and setter methods for Proposal properties // Register getter and setter methods for Proposal properties
@ -69,7 +71,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}); });
engine.register_fn("cast_vote_on_proposal", |mut proposal: Proposal, ballot_id: i64, user_id: i64, option_id: i64, shares: i64| -> Proposal { engine.register_fn("cast_vote_on_proposal", |mut proposal: Proposal, ballot_id: i64, user_id: i64, option_id: i64, shares: i64| -> Proposal {
proposal.cast_vote(ballot_id as u32, user_id as u32, option_id as u8, shares) let ballot_id_option = if ballot_id <= 0 { None } else { Some(ballot_id as u32) };
proposal.cast_vote(ballot_id_option, user_id as u32, option_id as u8, shares)
}); });
engine.register_fn("change_proposal_status", |mut proposal: Proposal, status_str: String| -> Proposal { engine.register_fn("change_proposal_status", |mut proposal: Proposal, status_str: String| -> Proposal {
@ -103,7 +106,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// In a real implementation, this would retrieve the proposal from the database // In a real implementation, this would retrieve the proposal from the database
let start_date = Utc::now(); let start_date = Utc::now();
let end_date = start_date + Duration::days(14); let end_date = start_date + Duration::days(14);
Proposal::new(id as u32, "Retrieved Creator", "Retrieved Proposal", "Retrieved Description", start_date, end_date) Proposal::new(Some(id as u32), "Retrieved Creator", "Retrieved Proposal", "Retrieved Description", start_date, end_date)
}); });
// Register a function to check if a proposal exists // Register a function to check if a proposal exists
@ -118,8 +121,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let start_date = Utc::now(); let start_date = Utc::now();
let end_date = start_date + Duration::days(14); let end_date = start_date + Duration::days(14);
vec![ vec![
Proposal::new(1, "Creator 1", "Proposal 1", "Description 1", start_date, end_date), Proposal::new(Some(1), "Creator 1", "Proposal 1", "Description 1", start_date, end_date),
Proposal::new(2, "Creator 2", "Proposal 2", "Description 2", start_date, end_date) Proposal::new(Some(2), "Creator 2", "Proposal 2", "Description 2", start_date, end_date)
] ]
} }
@ -160,7 +163,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
if index >= 0 && index < proposal.ballots.len() as i64 { if index >= 0 && index < proposal.ballots.len() as i64 {
proposal.ballots[index as usize].clone() proposal.ballots[index as usize].clone()
} else { } else {
Ballot::new(0, 0, 0, 0) Ballot::new(None, 0, 0, 0)
} }
}); });

View File

@ -1,8 +1,8 @@
// Get the database instance // Get the database instance
let db = get_db(); let db = get_db();
// Create a new proposal // Create a new proposal with auto-generated ID (pass 0 for auto-generated ID)
let proposal = create_proposal(1, "user_creator_123", "Community Fund Allocation for Q3", let proposal = create_proposal(0, "user_creator_123", "Community Fund Allocation for Q3",
"Proposal to allocate funds for community projects in the third quarter."); "Proposal to allocate funds for community projects in the third quarter.");
print("Created Proposal: '" + get_title(proposal) + "' (ID: " + get_id(proposal) + ")"); print("Created Proposal: '" + get_title(proposal) + "' (ID: " + get_id(proposal) + ")");
@ -26,14 +26,14 @@ print("\nProposal saved to database");
// Simulate casting votes // Simulate casting votes
print("\nSimulating Votes..."); print("\nSimulating Votes...");
// User 1 votes for 'Approve Allocation' with 100 shares // User 1 votes for 'Approve Allocation' with 100 shares (with explicit ballot ID)
let proposal_with_votes = cast_vote_on_proposal(proposal_with_options, 101, 1, 1, 100); let proposal_with_votes = cast_vote_on_proposal(proposal_with_options, 101, 1, 1, 100);
// User 2 votes for 'Reject Allocation' with 50 shares // User 2 votes for 'Reject Allocation' with 50 shares (with explicit ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 102, 2, 2, 50); proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 102, 2, 2, 50);
// User 3 votes for 'Approve Allocation' with 75 shares // User 3 votes for 'Approve Allocation' with 75 shares (with auto-generated ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 103, 3, 1, 75); proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 0, 3, 1, 75);
// User 4 abstains with 20 shares // User 4 abstains with 20 shares (with auto-generated ballot ID)
proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 104, 4, 3, 20); proposal_with_votes = cast_vote_on_proposal(proposal_with_votes, 0, 4, 3, 20);
print("\nVote Counts After Simulation:"); print("\nVote Counts After Simulation:");
option_count = get_option_count(proposal_with_votes); option_count = get_option_count(proposal_with_votes);

View File

@ -24,6 +24,7 @@ impl Account {
/// Create a new account with auto-generated ID /// Create a new account with auto-generated ID
/// ///
/// # Arguments /// # Arguments
/// * `id` - Optional ID for the account (use None for auto-generated ID)
/// * `name` - Name of the account /// * `name` - Name of the account
/// * `user_id` - ID of the user who owns the account /// * `user_id` - ID of the user who owns the account
/// * `description` - Description of the account /// * `description` - Description of the account
@ -31,6 +32,7 @@ impl Account {
/// * `address` - Address of the account on the blockchain /// * `address` - Address of the account on the blockchain
/// * `pubkey` - Public key /// * `pubkey` - Public key
pub fn new( pub fn new(
id: Option<u32>,
name: impl ToString, name: impl ToString,
user_id: u32, user_id: u32,
description: impl ToString, description: impl ToString,
@ -38,8 +40,13 @@ impl Account {
address: impl ToString, address: impl ToString,
pubkey: impl ToString pubkey: impl ToString
) -> Self { ) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self { Self {
base_data: BaseModelData::new(), base_data,
name: name.to_string(), name: name.to_string(),
user_id, user_id,
description: description.to_string(), description: description.to_string(),

View File

@ -34,7 +34,17 @@ pub struct Asset {
impl Asset { impl Asset {
/// Create a new asset with auto-generated ID /// Create a new asset with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the asset (use None for auto-generated ID)
/// * `name` - Name of the asset
/// * `description` - Description of the asset
/// * `amount` - Amount of the asset
/// * `address` - Address of the asset on the blockchain or bank
/// * `asset_type` - Type of the asset
/// * `decimals` - Number of decimals of the asset
pub fn new( pub fn new(
id: Option<u32>,
name: impl ToString, name: impl ToString,
description: impl ToString, description: impl ToString,
amount: f64, amount: f64,
@ -42,8 +52,13 @@ impl Asset {
asset_type: AssetType, asset_type: AssetType,
decimals: u8, decimals: u8,
) -> Self { ) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self { Self {
base_data: BaseModelData::new(), base_data,
name: name.to_string(), name: name.to_string(),
description: description.to_string(), description: description.to_string(),
amount, amount,

View File

@ -112,7 +112,22 @@ pub struct Listing {
impl Listing { impl Listing {
/// Create a new listing with auto-generated ID /// Create a new listing with auto-generated ID
///
/// # Arguments
/// * `id` - Optional ID for the listing (use None for auto-generated ID)
/// * `title` - Title of the listing
/// * `description` - Description of the listing
/// * `asset_id` - ID of the asset being listed
/// * `asset_type` - Type of the asset
/// * `seller_id` - ID of the seller
/// * `price` - Initial price for fixed price, or starting price for auction
/// * `currency` - Currency of the price
/// * `listing_type` - Type of the listing
/// * `expires_at` - Optional expiration date
/// * `tags` - Tags for the listing
/// * `image_url` - Optional image URL
pub fn new( pub fn new(
id: Option<u32>,
title: impl ToString, title: impl ToString,
description: impl ToString, description: impl ToString,
asset_id: impl ToString, asset_id: impl ToString,
@ -125,8 +140,13 @@ impl Listing {
tags: Vec<String>, tags: Vec<String>,
image_url: Option<impl ToString>, image_url: Option<impl ToString>,
) -> Self { ) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self { Self {
base_data: BaseModelData::new(), base_data,
title: title.to_string(), title: title.to_string(),
description: description.to_string(), description: description.to_string(),
asset_id: asset_id.to_string(), asset_id: asset_id.to_string(),

View File

@ -78,12 +78,18 @@ impl Ballot {
/// Create a new ballot with auto-generated ID /// Create a new ballot with auto-generated ID
/// ///
/// # Arguments /// # Arguments
/// * `id` - Optional ID for the ballot (use None for auto-generated ID)
/// * `user_id` - ID of the user who cast this ballot /// * `user_id` - ID of the user who cast this ballot
/// * `vote_option_id` - ID of the vote option chosen /// * `vote_option_id` - ID of the vote option chosen
/// * `shares_count` - Number of shares/tokens/voting power /// * `shares_count` - Number of shares/tokens/voting power
pub fn new(user_id: u32, vote_option_id: u8, shares_count: i64) -> Self { pub fn new(id: Option<u32>, user_id: u32, vote_option_id: u8, shares_count: i64) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self { Self {
base_data: BaseModelData::new(), base_data,
user_id, user_id,
vote_option_id, vote_option_id,
shares_count, shares_count,
@ -116,14 +122,20 @@ impl Proposal {
/// Create a new proposal with auto-generated ID /// Create a new proposal with auto-generated ID
/// ///
/// # Arguments /// # Arguments
/// * `id` - Optional ID for the proposal (use None for auto-generated ID)
/// * `creator_id` - ID of the user who created the proposal /// * `creator_id` - ID of the user who created the proposal
/// * `title` - Title of the proposal /// * `title` - Title of the proposal
/// * `description` - Description of the proposal /// * `description` - Description of the proposal
/// * `vote_start_date` - Date when voting starts /// * `vote_start_date` - Date when voting starts
/// * `vote_end_date` - Date when voting ends /// * `vote_end_date` - Date when voting ends
pub fn new(creator_id: impl ToString, title: impl ToString, description: impl ToString, vote_start_date: DateTime<Utc>, vote_end_date: DateTime<Utc>) -> Self { pub fn new(id: Option<u32>, creator_id: impl ToString, title: impl ToString, description: impl ToString, vote_start_date: DateTime<Utc>, vote_end_date: DateTime<Utc>) -> Self {
let mut base_data = BaseModelData::new();
if let Some(id) = id {
base_data.update_id(id);
}
Self { Self {
base_data: BaseModelData::new(), base_data,
creator_id: creator_id.to_string(), creator_id: creator_id.to_string(),
title: title.to_string(), title: title.to_string(),
description: description.to_string(), description: description.to_string(),
@ -143,7 +155,7 @@ impl Proposal {
self self
} }
pub fn cast_vote(mut self, user_id: u32, chosen_option_id: u8, shares: i64) -> Self { pub fn cast_vote(mut self, ballot_id: Option<u32>, user_id: u32, chosen_option_id: u8, shares: i64) -> Self {
if self.vote_status != VoteEventStatus::Open { if self.vote_status != VoteEventStatus::Open {
eprintln!("Voting is not open for proposal '{}'", self.title); eprintln!("Voting is not open for proposal '{}'", self.title);
return self; return self;
@ -159,7 +171,7 @@ impl Proposal {
} }
} }
let new_ballot = Ballot::new(user_id, chosen_option_id, shares); let new_ballot = Ballot::new(ballot_id, user_id, chosen_option_id, shares);
self.ballots.push(new_ballot); self.ballots.push(new_ballot);
if let Some(option) = self.options.iter_mut().find(|opt| opt.id == chosen_option_id) { if let Some(option) = self.options.iter_mut().find(|opt| opt.id == chosen_option_id) {

View File

@ -0,0 +1 @@
1

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
2

Binary file not shown.

View File

@ -0,0 +1 @@
1

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
2

Binary file not shown.