Merge branch 'main' into builders_in_script

* main:
  ..
  ...
  ...
  ...
  ...
  ...

# Conflicts:
#	herodb/src/cmd/dbexample2/main.rs
#	herodb/src/models/biz/currency.rs
#	herodb/src/models/biz/product.rs
This commit is contained in:
despiegk 2025-04-04 16:09:48 +02:00
commit 82052ef385
48 changed files with 8113 additions and 48 deletions

7
herodb/Cargo.lock generated
View File

@ -658,6 +658,7 @@ dependencies = [
"bincode",
"brotli",
"chrono",
"lazy_static",
"paste",
"poem",
"poem-openapi",
@ -831,6 +832,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.171"

View File

@ -21,6 +21,7 @@ poem-openapi = { version = "2.0.11", features = ["swagger-ui"] }
tokio = { version = "1", features = ["full"] }
rhai = "1.21.0"
paste = "1.0"
lazy_static = "1.4.0"
[[example]]
name = "rhai_demo"
@ -29,3 +30,7 @@ path = "examples/rhai_demo.rs"
[[bin]]
name = "dbexample2"
path = "src/cmd/dbexample2/main.rs"
[[bin]]
name = "dbexample_mcc"
path = "src/cmd/dbexample_mcc/main.rs"

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,134 @@
### Error Handling in Dynamic Functions
When working with the dynamic function signature, error handling is slightly different:
```rust
fn dynamic_function(ctx: NativeCallContext, args: &mut [&mut Dynamic]) -> Result<Dynamic, Box<EvalAltResult>> {
// Get the position information from the context
let pos = ctx.position();
// Validate arguments
if args.len() < 2 {
return Err(Box::new(EvalAltResult::ErrorRuntime(
format!("Expected at least 2 arguments, got {}", args.len()),
pos
)));
}
// Try to convert arguments with proper error handling
let arg1 = match args[0].as_int() {
Ok(val) => val,
Err(_) => return Err(Box::new(EvalAltResult::ErrorMismatchOutputType(
"Expected first argument to be an integer".into(),
pos,
"i64".into()
)))
};
// Process with error handling
if arg1 <= 0 {
return Err(Box::new(EvalAltResult::ErrorRuntime(
"First argument must be positive".into(),
pos
)));
}
// Return success
Ok(Dynamic::from(arg1 * 2))
}
```
## Advanced Patterns
### Working with Function Pointers
You can create function pointers that bind to Rust functions:
```rust
fn my_awesome_fn(ctx: NativeCallContext, args: &mut[&mut Dynamic]) -> Result<Dynamic, Box<EvalAltResult>> {
// Check number of arguments
if args.len() != 2 {
return Err("one argument is required, plus the object".into());
}
// Get call arguments
let x = args[1].try_cast::<i64>().map_err(|_| "argument must be an integer".into())?;
// Get mutable reference to the object map, which is passed as the first argument
let map = &mut *args[0].as_map_mut().map_err(|_| "object must be a map".into())?;
// Do something awesome here ...
let result = x * 2;
Ok(result.into())
}
// Register a function to create a pre-defined object
engine.register_fn("create_awesome_object", || {
// Use an object map as base
let mut map = Map::new();
// Create a function pointer that binds to 'my_awesome_fn'
let fp = FnPtr::from_fn("awesome", my_awesome_fn)?;
// ^ name of method
// ^ native function
// Store the function pointer in the object map
map.insert("awesome".into(), fp.into());
Ok(Dynamic::from_map(map))
});
```
### Creating Rust Closures from Rhai Functions
You can encapsulate a Rhai script as a Rust closure:
```rust
use rhai::{Engine, Func};
let engine = Engine::new();
let script = "fn calc(x, y) { x + y.len < 42 }";
// Create a Rust closure from a Rhai function
let func = Func::<(i64, &str), bool>::create_from_script(
engine, // the 'Engine' is consumed into the closure
script, // the script
"calc" // the entry-point function name
)?;
// Call the closure
let result = func(123, "hello")?;
// Pass it as a callback to another function
schedule_callback(func);
```
### Calling Rhai Functions from Rust
You can call Rhai functions from Rust:
```rust
// Compile the script to AST
let ast = engine.compile(script)?;
// Create a custom 'Scope'
let mut scope = Scope::new();
// Add variables to the scope
scope.push("my_var", 42_i64);
scope.push("my_string", "hello, world!");
scope.push_constant("MY_CONST", true);
// Call a function defined in the script
let result = engine.call_fn::<i64>(&mut scope, &ast, "hello", ("abc", 123_i64))?;
// For a function with one parameter, use a tuple with a trailing comma
let result = engine.call_fn::<i64>(&mut scope, &ast, "hello", (123_i64,))?;
// For a function with no parameters
let result = engine.call_fn::<i64>(&mut scope, &ast, "hello", ())?;
```

View File

@ -0,0 +1,187 @@
## Best Practices and Optimization
When wrapping Rust functions for use with Rhai, following these best practices will help you create efficient, maintainable, and robust code.
### Performance Considerations
1. **Minimize Cloning**: Rhai often requires cloning data, but you can minimize this overhead:
```rust
// Prefer immutable references when possible
fn process_data(data: &MyStruct) -> i64 {
// Work with data without cloning
data.value * 2
}
// Use mutable references for in-place modifications
fn update_data(data: &mut MyStruct) {
data.value += 1;
}
```
2. **Avoid Excessive Type Conversions**: Converting between Rhai's Dynamic type and Rust types has overhead:
```rust
// Inefficient - multiple conversions
fn process_inefficient(ctx: NativeCallContext, args: &mut [&mut Dynamic]) -> Result<Dynamic, Box<EvalAltResult>> {
let value = args[0].as_int()?;
let result = value * 2;
Ok(Dynamic::from(result))
}
// More efficient - use typed parameters when possible
fn process_efficient(value: i64) -> i64 {
value * 2
}
```
3. **Batch Operations**: For operations on collections, batch processing is more efficient:
```rust
// Process an entire array at once rather than element by element
fn sum_array(arr: Array) -> Result<i64, Box<EvalAltResult>> {
arr.iter()
.map(|v| v.as_int())
.collect::<Result<Vec<i64>, _>>()
.map(|nums| nums.iter().sum())
.map_err(|_| "Array must contain only integers".into())
}
```
4. **Compile Scripts Once**: Reuse compiled ASTs for scripts that are executed multiple times:
```rust
// Compile once
let ast = engine.compile(script)?;
// Execute multiple times with different parameters
for i in 0..10 {
let result = engine.eval_ast::<i64>(&ast)?;
println!("Result {}: {}", i, result);
}
```
### Thread Safety
1. **Use Sync Mode When Needed**: If you need thread safety, use the `sync` feature:
```rust
// In Cargo.toml
// rhai = { version = "1.x", features = ["sync"] }
// This creates a thread-safe engine
let engine = Engine::new();
// Now you can safely share the engine between threads
std::thread::spawn(move || {
let result = engine.eval::<i64>("40 + 2")?;
println!("Result: {}", result);
});
```
2. **Clone the Engine for Multiple Threads**: When not using `sync`, clone the engine for each thread:
```rust
let engine = Engine::new();
let handles: Vec<_> = (0..5).map(|i| {
let engine_clone = engine.clone();
std::thread::spawn(move || {
let result = engine_clone.eval::<i64>(&format!("{} + 2", i * 10))?;
println!("Thread {}: {}", i, result);
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
```
### Memory Management
1. **Control Scope Size**: Be mindful of the size of your scopes:
```rust
// Create a new scope for each operation to avoid memory buildup
for item in items {
let mut scope = Scope::new();
scope.push("item", item);
engine.eval_with_scope::<()>(&mut scope, "process(item)")?;
}
```
2. **Limit Script Complexity**: Use engine options to limit script complexity:
```rust
let mut engine = Engine::new();
// Set limits to prevent scripts from consuming too many resources
engine.set_max_expr_depths(64, 64) // Max expression/statement depth
.set_max_function_expr_depth(64) // Max function depth
.set_max_array_size(10000) // Max array size
.set_max_map_size(10000) // Max map size
.set_max_string_size(10000) // Max string size
.set_max_call_levels(64); // Max call stack depth
```
3. **Use Shared Values Carefully**: Shared values (via closures) have reference-counting overhead:
```rust
// Avoid unnecessary capturing in closures when possible
engine.register_fn("process", |x: i64| x * 2);
// Instead of capturing large data structures
let large_data = vec![1, 2, 3, /* ... thousands of items ... */];
engine.register_fn("process_data", move |idx: i64| {
if idx >= 0 && (idx as usize) < large_data.len() {
large_data[idx as usize]
} else {
0
}
});
// Consider registering a lookup function instead
let large_data = std::sync::Arc::new(vec![1, 2, 3, /* ... thousands of items ... */]);
let data_ref = large_data.clone();
engine.register_fn("lookup", move |idx: i64| {
if idx >= 0 && (idx as usize) < data_ref.len() {
data_ref[idx as usize]
} else {
0
}
});
```
### API Design
1. **Consistent Naming**: Use consistent naming conventions:
```rust
// Good: Consistent naming pattern
engine.register_fn("create_user", create_user)
.register_fn("update_user", update_user)
.register_fn("delete_user", delete_user);
// Bad: Inconsistent naming
engine.register_fn("create_user", create_user)
.register_fn("user_update", update_user)
.register_fn("remove", delete_user);
```
2. **Logical Function Grouping**: Group related functions together:
```rust
// Register all string-related functions together
engine.register_fn("str_length", |s: &str| s.len() as i64)
.register_fn("str_uppercase", |s: &str| s.to_uppercase())
.register_fn("str_lowercase", |s: &str| s.to_lowercase());
// Register all math-related functions together
engine.register_fn("math_sin", |x: f64| x.sin())
.register_fn("math_cos", |x: f64| x.cos())
.register_fn("math_tan", |x: f64| x.tan());
```
3. **Comprehensive Documentation**: Document your API thoroughly:
```rust
// Add documentation for script writers
let mut engine = Engine::new();
#[cfg(feature = "metadata")]
{
// Add function documentation
engine.register_fn("calculate_tax", calculate_tax)
.register_fn_metadata("calculate_tax", |metadata| {
metadata.set_doc_comment("Calculates tax based on income and rate.\n\nParameters:\n- income: Annual income\n- rate: Tax rate (0.0-1.0)\n\nReturns: Calculated tax amount");
});
}
```

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
[package]
name = "dbexample_governance"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "dbexample_governance"
path = "main.rs"
[dependencies]
herodb = { path = "../../.." }
chrono = "0.4"

View File

@ -0,0 +1,362 @@
use chrono::{Utc, Duration};
use herodb::db::DBBuilder;
use herodb::models::governance::{
Company, CompanyStatus, BusinessType,
Shareholder, ShareholderType,
Meeting, Attendee, MeetingStatus, AttendeeRole, AttendeeStatus,
User,
Vote, VoteOption, Ballot, VoteStatus,
Resolution, ResolutionStatus, Approval
};
use std::path::PathBuf;
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("DB Example: Governance Module");
println!("============================");
// Create a temporary directory for the database
let db_path = PathBuf::from("/tmp/dbexample_governance");
if db_path.exists() {
fs::remove_dir_all(&db_path)?;
}
fs::create_dir_all(&db_path)?;
println!("Database path: {:?}", db_path);
// Create a database instance with our governance models registered
let db = DBBuilder::new(&db_path)
.register_model::<Company>()
.register_model::<Shareholder>()
.register_model::<Meeting>()
.register_model::<User>()
.register_model::<Vote>()
.register_model::<Resolution>()
.build()?;
println!("\n1. Creating a Company");
println!("-------------------");
// Create a company
let company = Company::new(
1,
"Acme Corporation".to_string(),
"ACM123456".to_string(),
Utc::now(),
"December 31".to_string(),
"info@acmecorp.com".to_string(),
"+1-555-123-4567".to_string(),
"https://acmecorp.com".to_string(),
"123 Main St, Anytown, USA".to_string(),
BusinessType::Coop,
"Technology".to_string(),
"A leading technology company".to_string(),
CompanyStatus::Active,
);
// Insert the company
db.insert(&company)?;
println!("Company created: {} (ID: {})", company.name, company.id);
println!("Status: {:?}, Business Type: {:?}", company.status, company.business_type);
println!("\n2. Creating Users");
println!("---------------");
// Create users
let user1 = User::new(
1,
"John Doe".to_string(),
"john.doe@acmecorp.com".to_string(),
"password123".to_string(), // In a real app, this would be hashed
"Acme Corporation".to_string(),
"CEO".to_string(),
);
let user2 = User::new(
2,
"Jane Smith".to_string(),
"jane.smith@acmecorp.com".to_string(),
"password456".to_string(), // In a real app, this would be hashed
"Acme Corporation".to_string(),
"CFO".to_string(),
);
let user3 = User::new(
3,
"Bob Johnson".to_string(),
"bob.johnson@acmecorp.com".to_string(),
"password789".to_string(), // In a real app, this would be hashed
"Acme Corporation".to_string(),
"CTO".to_string(),
);
// Insert the users
db.insert(&user1)?;
db.insert(&user2)?;
db.insert(&user3)?;
println!("User created: {} ({})", user1.name, user1.role);
println!("User created: {} ({})", user2.name, user2.role);
println!("User created: {} ({})", user3.name, user3.role);
println!("\n3. Creating Shareholders");
println!("----------------------");
// Create shareholders
let mut shareholder1 = Shareholder::new(
1,
company.id,
user1.id,
user1.name.clone(),
1000.0,
40.0,
ShareholderType::Individual,
);
let mut shareholder2 = Shareholder::new(
2,
company.id,
user2.id,
user2.name.clone(),
750.0,
30.0,
ShareholderType::Individual,
);
let mut shareholder3 = Shareholder::new(
3,
company.id,
user3.id,
user3.name.clone(),
750.0,
30.0,
ShareholderType::Individual,
);
// Insert the shareholders
db.insert(&shareholder1)?;
db.insert(&shareholder2)?;
db.insert(&shareholder3)?;
println!("Shareholder created: {} ({} shares, {}%)",
shareholder1.name, shareholder1.shares, shareholder1.percentage);
println!("Shareholder created: {} ({} shares, {}%)",
shareholder2.name, shareholder2.shares, shareholder2.percentage);
println!("Shareholder created: {} ({} shares, {}%)",
shareholder3.name, shareholder3.shares, shareholder3.percentage);
// Update shareholder shares
shareholder1.update_shares(1100.0, 44.0);
db.insert(&shareholder1)?;
println!("Updated shareholder: {} ({} shares, {}%)",
shareholder1.name, shareholder1.shares, shareholder1.percentage);
println!("\n4. Creating a Meeting");
println!("------------------");
// Create a meeting
let mut meeting = Meeting::new(
1,
company.id,
"Q2 Board Meeting".to_string(),
Utc::now() + Duration::days(7), // Meeting in 7 days
"Conference Room A".to_string(),
"Quarterly board meeting to discuss financial results".to_string(),
);
// Create attendees
let attendee1 = Attendee::new(
1,
meeting.id,
user1.id,
user1.name.clone(),
AttendeeRole::Coordinator,
);
let attendee2 = Attendee::new(
2,
meeting.id,
user2.id,
user2.name.clone(),
AttendeeRole::Member,
);
let attendee3 = Attendee::new(
3,
meeting.id,
user3.id,
user3.name.clone(),
AttendeeRole::Member,
);
// Add attendees to the meeting
meeting.add_attendee(attendee1);
meeting.add_attendee(attendee2);
meeting.add_attendee(attendee3);
// Insert the meeting
db.insert(&meeting)?;
println!("Meeting created: {} ({})", meeting.title, meeting.date.format("%Y-%m-%d %H:%M"));
println!("Status: {:?}, Attendees: {}", meeting.status, meeting.attendees.len());
// Update attendee status
if let Some(attendee) = meeting.find_attendee_by_user_id_mut(user2.id) {
attendee.update_status(AttendeeStatus::Confirmed);
}
if let Some(attendee) = meeting.find_attendee_by_user_id_mut(user3.id) {
attendee.update_status(AttendeeStatus::Confirmed);
}
db.insert(&meeting)?;
// Get confirmed attendees
let confirmed = meeting.confirmed_attendees();
println!("Confirmed attendees: {}", confirmed.len());
for attendee in confirmed {
println!(" - {} ({})", attendee.name, match attendee.role {
AttendeeRole::Coordinator => "Coordinator",
AttendeeRole::Member => "Member",
AttendeeRole::Secretary => "Secretary",
AttendeeRole::Participant => "Participant",
AttendeeRole::Advisor => "Advisor",
AttendeeRole::Admin => "Admin",
});
}
println!("\n5. Creating a Resolution");
println!("----------------------");
// Create a resolution
let mut resolution = Resolution::new(
1,
company.id,
"Approval of Q1 Financial Statements".to_string(),
"Resolution to approve the Q1 financial statements".to_string(),
"The Board of Directors hereby approves the financial statements for Q1 2025.".to_string(),
user1.id, // Proposed by the CEO
);
// Link the resolution to the meeting
resolution.link_to_meeting(meeting.id);
// Insert the resolution
db.insert(&resolution)?;
println!("Resolution created: {} (Status: {:?})", resolution.title, resolution.status);
// Propose the resolution
resolution.propose();
db.insert(&resolution)?;
println!("Resolution proposed on {}", resolution.proposed_at.format("%Y-%m-%d"));
// Add approvals
resolution.add_approval(user1.id, user1.name.clone(), true, "Approved as proposed".to_string());
resolution.add_approval(user2.id, user2.name.clone(), true, "Financials look good".to_string());
resolution.add_approval(user3.id, user3.name.clone(), true, "No concerns".to_string());
db.insert(&resolution)?;
// Check approval status
println!("Approvals: {}, Rejections: {}",
resolution.approval_count(),
resolution.rejection_count());
// Approve the resolution
resolution.approve();
db.insert(&resolution)?;
println!("Resolution approved on {}",
resolution.approved_at.unwrap().format("%Y-%m-%d"));
println!("\n6. Creating a Vote");
println!("----------------");
// Create a vote
let mut vote = Vote::new(
1,
company.id,
"Vote on New Product Line".to_string(),
"Vote to approve investment in new product line".to_string(),
Utc::now(),
Utc::now() + Duration::days(3), // Voting period of 3 days
VoteStatus::Open,
);
// Add voting options
vote.add_option("Approve".to_string(), 0);
vote.add_option("Reject".to_string(), 0);
vote.add_option("Abstain".to_string(), 0);
// Insert the vote
db.insert(&vote)?;
println!("Vote created: {} (Status: {:?})", vote.title, vote.status);
println!("Voting period: {} to {}",
vote.start_date.format("%Y-%m-%d"),
vote.end_date.format("%Y-%m-%d"));
// Cast ballots
vote.add_ballot(user1.id, 1, 1000); // User 1 votes "Approve" with 1000 shares
vote.add_ballot(user2.id, 1, 750); // User 2 votes "Approve" with 750 shares
vote.add_ballot(user3.id, 3, 750); // User 3 votes "Abstain" with 750 shares
db.insert(&vote)?;
// Check voting results
println!("Voting results:");
for option in &vote.options {
println!(" - {}: {} votes", option.text, option.count);
}
// Create a resolution for this vote
let mut vote_resolution = Resolution::new(
2,
company.id,
"Investment in New Product Line".to_string(),
"Resolution to approve investment in new product line".to_string(),
"The Board of Directors hereby approves an investment of $1,000,000 in the new product line.".to_string(),
user1.id, // Proposed by the CEO
);
// Link the resolution to the vote
vote_resolution.link_to_vote(vote.id);
vote_resolution.propose();
db.insert(&vote_resolution)?;
println!("Created resolution linked to vote: {}", vote_resolution.title);
println!("\n7. Retrieving Related Objects");
println!("---------------------------");
// Retrieve company and related objects
let retrieved_company = db.get::<Company>(&company.id.to_string())?;
println!("Company: {} (ID: {})", retrieved_company.name, retrieved_company.id);
// Get resolutions for this company
let company_resolutions = retrieved_company.get_resolutions(&db)?;
println!("Company has {} resolutions:", company_resolutions.len());
for res in company_resolutions {
println!(" - {} (Status: {:?})", res.title, res.status);
}
// Get meeting and its resolutions
let retrieved_meeting = db.get::<Meeting>(&meeting.id.to_string())?;
println!("Meeting: {} ({})", retrieved_meeting.title, retrieved_meeting.date.format("%Y-%m-%d"));
let meeting_resolutions = retrieved_meeting.get_resolutions(&db)?;
println!("Meeting has {} resolutions:", meeting_resolutions.len());
for res in meeting_resolutions {
println!(" - {} (Status: {:?})", res.title, res.status);
}
// Get vote and its resolution
let retrieved_vote = db.get::<Vote>(&vote.id.to_string())?;
println!("Vote: {} (Status: {:?})", retrieved_vote.title, retrieved_vote.status);
if let Ok(Some(vote_res)) = retrieved_vote.get_resolution(&db) {
println!("Vote is linked to resolution: {}", vote_res.title);
}
// Get resolution and its related objects
let retrieved_resolution = db.get::<Resolution>(&resolution.id.to_string())?;
println!("Resolution: {} (Status: {:?})", retrieved_resolution.title, retrieved_resolution.status);
if let Ok(Some(res_meeting)) = retrieved_resolution.get_meeting(&db) {
println!("Resolution is discussed in meeting: {}", res_meeting.title);
}
println!("\nExample completed successfully!");
Ok(())
}

View File

@ -0,0 +1,399 @@
use chrono::{Utc, Duration};
use herodb::db::DBBuilder;
use herodb::models::mcc::{
Calendar, Event,
Email, Attachment, Envelope,
Contact, Message
};
use herodb::models::circle::Circle;
use std::path::PathBuf;
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("DB Example MCC: Mail, Calendar, Contacts with Group Support");
println!("=======================================================");
// Create a temporary directory for the database
let db_path = PathBuf::from("/tmp/dbexample_mcc");
if db_path.exists() {
fs::remove_dir_all(&db_path)?;
}
fs::create_dir_all(&db_path)?;
println!("Database path: {:?}", db_path);
// Create a database instance with our models registered
let db = DBBuilder::new(&db_path)
.register_model::<Calendar>()
.register_model::<Event>()
.register_model::<Email>()
.register_model::<Contact>()
.register_model::<Message>()
.register_model::<Circle>()
.build()?;
println!("\n1. Creating Circles (Groups)");
println!("---------------------------");
// Create circles (groups)
let work_circle = Circle::new(
1,
"Work".to_string(),
"Work-related communications".to_string()
);
let family_circle = Circle::new(
2,
"Family".to_string(),
"Family communications".to_string()
);
let friends_circle = Circle::new(
3,
"Friends".to_string(),
"Friends communications".to_string()
);
// Insert circles
db.set::<Circle>(&work_circle)?;
db.set::<Circle>(&family_circle)?;
db.set::<Circle>(&friends_circle)?;
println!("Created circles:");
println!(" - Circle #{}: {}", work_circle.id, work_circle.name);
println!(" - Circle #{}: {}", family_circle.id, family_circle.name);
println!(" - Circle #{}: {}", friends_circle.id, friends_circle.name);
println!("\n2. Creating Contacts with Group Support");
println!("------------------------------------");
// Create contacts
let mut john = Contact::new(
1,
"John".to_string(),
"Doe".to_string(),
"john.doe@example.com".to_string(),
"work".to_string()
);
john.add_group(work_circle.id);
let mut alice = Contact::new(
2,
"Alice".to_string(),
"Smith".to_string(),
"alice.smith@example.com".to_string(),
"family".to_string()
);
alice.add_group(family_circle.id);
let mut bob = Contact::new(
3,
"Bob".to_string(),
"Johnson".to_string(),
"bob.johnson@example.com".to_string(),
"friends".to_string()
);
bob.add_group(friends_circle.id);
bob.add_group(work_circle.id); // Bob is both a friend and a work contact
// Insert contacts
db.set::<Contact>(&john)?;
db.set::<Contact>(&alice)?;
db.set::<Contact>(&bob)?;
println!("Created contacts:");
println!(" - {}: {} (Groups: {:?})", john.full_name(), john.email, john.groups);
println!(" - {}: {} (Groups: {:?})", alice.full_name(), alice.email, alice.groups);
println!(" - {}: {} (Groups: {:?})", bob.full_name(), bob.email, bob.groups);
println!("\n3. Creating Calendars with Group Support");
println!("-------------------------------------");
// Create calendars
let mut work_calendar = Calendar::new(
1,
"Work Calendar".to_string(),
"Work-related events".to_string()
);
work_calendar.add_group(work_circle.id);
let mut personal_calendar = Calendar::new(
2,
"Personal Calendar".to_string(),
"Personal events".to_string()
);
personal_calendar.add_group(family_circle.id);
personal_calendar.add_group(friends_circle.id);
// Insert calendars
db.set::<Calendar>(&work_calendar)?;
db.set::<Calendar>(&personal_calendar)?;
println!("Created calendars:");
println!(" - {}: {} (Groups: {:?})", work_calendar.id, work_calendar.title, work_calendar.groups);
println!(" - {}: {} (Groups: {:?})", personal_calendar.id, personal_calendar.title, personal_calendar.groups);
println!("\n4. Creating Events with Group Support");
println!("----------------------------------");
// Create events
let now = Utc::now();
let tomorrow = now + Duration::days(1);
let next_week = now + Duration::days(7);
let mut work_meeting = Event::new(
1,
work_calendar.id,
"Team Meeting".to_string(),
"Weekly team sync".to_string(),
"Conference Room A".to_string(),
tomorrow,
tomorrow + Duration::hours(1),
"organizer@example.com".to_string()
);
work_meeting.add_group(work_circle.id);
work_meeting.add_attendee(john.email.clone());
work_meeting.add_attendee(bob.email.clone());
let mut family_dinner = Event::new(
2,
personal_calendar.id,
"Family Dinner".to_string(),
"Weekly family dinner".to_string(),
"Home".to_string(),
next_week,
next_week + Duration::hours(2),
"me@example.com".to_string()
);
family_dinner.add_group(family_circle.id);
family_dinner.add_attendee(alice.email.clone());
// Insert events
db.set::<Event>(&work_meeting)?;
db.set::<Event>(&family_dinner)?;
println!("Created events:");
println!(" - {}: {} on {} (Groups: {:?})",
work_meeting.id,
work_meeting.title,
work_meeting.start_time.format("%Y-%m-%d %H:%M"),
work_meeting.groups
);
println!(" - {}: {} on {} (Groups: {:?})",
family_dinner.id,
family_dinner.title,
family_dinner.start_time.format("%Y-%m-%d %H:%M"),
family_dinner.groups
);
println!("\n5. Creating Emails with Group Support");
println!("----------------------------------");
// Create emails
let mut work_email = Email::new(
1,
101,
1,
"INBOX".to_string(),
"Here are the meeting notes from yesterday's discussion.".to_string()
);
work_email.add_group(work_circle.id);
let work_attachment = Attachment {
filename: "meeting_notes.pdf".to_string(),
content_type: "application/pdf".to_string(),
hash: "abc123def456".to_string(),
size: 1024,
};
work_email.add_attachment(work_attachment);
let work_envelope = Envelope {
date: now.timestamp(),
subject: "Meeting Notes".to_string(),
from: vec!["john.doe@example.com".to_string()],
sender: vec!["john.doe@example.com".to_string()],
reply_to: vec!["john.doe@example.com".to_string()],
to: vec!["me@example.com".to_string()],
cc: vec!["bob.johnson@example.com".to_string()],
bcc: vec![],
in_reply_to: "".to_string(),
message_id: "msg123@example.com".to_string(),
};
work_email.set_envelope(work_envelope);
let mut family_email = Email::new(
2,
102,
2,
"INBOX".to_string(),
"Looking forward to seeing you at dinner next week!".to_string()
);
family_email.add_group(family_circle.id);
let family_envelope = Envelope {
date: now.timestamp(),
subject: "Family Dinner".to_string(),
from: vec!["alice.smith@example.com".to_string()],
sender: vec!["alice.smith@example.com".to_string()],
reply_to: vec!["alice.smith@example.com".to_string()],
to: vec!["me@example.com".to_string()],
cc: vec![],
bcc: vec![],
in_reply_to: "".to_string(),
message_id: "msg456@example.com".to_string(),
};
family_email.set_envelope(family_envelope);
// Insert emails
db.set::<Email>(&work_email)?;
db.set::<Email>(&family_email)?;
println!("Created emails:");
println!(" - From: {}, Subject: {} (Groups: {:?})",
work_email.envelope.as_ref().unwrap().from[0],
work_email.envelope.as_ref().unwrap().subject,
work_email.groups
);
println!(" - From: {}, Subject: {} (Groups: {:?})",
family_email.envelope.as_ref().unwrap().from[0],
family_email.envelope.as_ref().unwrap().subject,
family_email.groups
);
println!("\n6. Creating Messages (Chat) with Group Support");
println!("-----------------------------------------");
// Create messages
let mut work_chat = Message::new(
1,
"thread_work_123".to_string(),
"john.doe@example.com".to_string(),
"Can we move the meeting to 3pm?".to_string()
);
work_chat.add_group(work_circle.id);
work_chat.add_recipient("me@example.com".to_string());
work_chat.add_recipient("bob.johnson@example.com".to_string());
let mut friends_chat = Message::new(
2,
"thread_friends_456".to_string(),
"bob.johnson@example.com".to_string(),
"Are we still on for the game this weekend?".to_string()
);
friends_chat.add_group(friends_circle.id);
friends_chat.add_recipient("me@example.com".to_string());
friends_chat.add_reaction("👍".to_string());
// Insert messages
db.set::<Message>(&work_chat)?;
db.set::<Message>(&friends_chat)?;
println!("Created messages:");
println!(" - From: {}, Content: {} (Groups: {:?})",
work_chat.sender_id,
work_chat.content,
work_chat.groups
);
println!(" - From: {}, Content: {} (Groups: {:?}, Reactions: {:?})",
friends_chat.sender_id,
friends_chat.content,
friends_chat.groups,
friends_chat.meta.reactions
);
println!("\n7. Demonstrating Utility Methods");
println!("------------------------------");
// Filter contacts by group
println!("\nFiltering contacts by work group (ID: {}):", work_circle.id);
let all_contacts = db.list::<Contact>()?;
for contact in all_contacts {
if contact.filter_by_groups(&[work_circle.id]) {
println!(" - {} ({})", contact.full_name(), contact.email);
}
}
// Search emails by subject
println!("\nSearching emails with subject containing 'Meeting':");
let all_emails = db.list::<Email>()?;
for email in all_emails {
if email.search_by_subject("Meeting") {
println!(" - Subject: {}, From: {}",
email.envelope.as_ref().unwrap().subject,
email.envelope.as_ref().unwrap().from[0]
);
}
}
// Get events for a calendar
println!("\nGetting events for Work Calendar (ID: {}):", work_calendar.id);
let all_events = db.list::<Event>()?;
let work_events: Vec<Event> = all_events
.into_iter()
.filter(|event| event.calendar_id == work_calendar.id)
.collect();
for event in work_events {
println!(" - {}: {} on {}",
event.id,
event.title,
event.start_time.format("%Y-%m-%d %H:%M")
);
}
// Get attendee contacts for an event
println!("\nGetting attendee contacts for Team Meeting (ID: {}):", work_meeting.id);
let all_contacts = db.list::<Contact>()?;
let attendee_contacts: Vec<Contact> = all_contacts
.into_iter()
.filter(|contact| work_meeting.attendees.contains(&contact.email))
.collect();
for contact in attendee_contacts {
println!(" - {} ({})", contact.full_name(), contact.email);
}
// Convert email to message
println!("\nConverting work email to message:");
let email_to_message = work_email.to_message(3, "thread_converted_789".to_string());
println!(" - Original Email Subject: {}", work_email.envelope.as_ref().unwrap().subject);
println!(" - Converted Message Content: {}", email_to_message.content.split('\n').next().unwrap_or(""));
println!(" - Converted Message Groups: {:?}", email_to_message.groups);
// Insert the converted message
db.set::<Message>(&email_to_message)?;
println!("\n8. Relationship Management");
println!("------------------------");
// Get the calendar for an event
println!("\nGetting calendar for Family Dinner event (ID: {}):", family_dinner.id);
let event_calendar = db.get::<Calendar>(&family_dinner.calendar_id.to_string())?;
println!(" - Calendar: {} ({})", event_calendar.title, event_calendar.description);
// Get events for a contact
println!("\nGetting events where John Doe is an attendee:");
let all_events = db.list::<Event>()?;
let john_events: Vec<Event> = all_events
.into_iter()
.filter(|event| event.attendees.contains(&john.email))
.collect();
for event in john_events {
println!(" - {}: {} on {}",
event.id,
event.title,
event.start_time.format("%Y-%m-%d %H:%M")
);
}
// Get messages in the same thread
println!("\nGetting all messages in the work chat thread:");
let all_messages = db.list::<Message>()?;
let thread_messages: Vec<Message> = all_messages
.into_iter()
.filter(|message| message.thread_id == work_chat.thread_id)
.collect();
for message in thread_messages {
println!(" - From: {}, Content: {}", message.sender_id, message.content);
}
println!("\nExample completed successfully!");
Ok(())
}

View File

@ -1,7 +1,7 @@
use crate::db::db::DB;
use crate::db::base::{SledDBResult, SledModel};
use crate::impl_model_methods;
use crate::models::biz::{Product, Sale, Currency};
use crate::models::biz::{Product, Sale, Currency, ExchangeRate, Service, Customer, Contract, Invoice};
// Implement model-specific methods for Product
impl_model_methods!(Product, product, products);
@ -11,3 +11,18 @@ impl_model_methods!(Sale, sale, sales);
// Implement model-specific methods for Currency
impl_model_methods!(Currency, currency, currencies);
// Implement model-specific methods for ExchangeRate
impl_model_methods!(ExchangeRate, exchange_rate, exchange_rates);
// Implement model-specific methods for Service
impl_model_methods!(Service, service, services);
// Implement model-specific methods for Customer
impl_model_methods!(Customer, customer, customers);
// Implement model-specific methods for Contract
impl_model_methods!(Contract, contract, contracts);
// Implement model-specific methods for Invoice
impl_model_methods!(Invoice, invoice, invoices);

View File

@ -0,0 +1,371 @@
# Business Models Implementation Plan
## Overview
This document outlines the plan for implementing new business models in the codebase:
1. **Service**: For tracking recurring payments (similar to Sale)
2. **Customer**: For storing customer information
3. **Contract**: For linking services or sales to customers
4. **Invoice**: For invoicing customers
## Model Diagrams
### Core Models and Relationships
```mermaid
classDiagram
class Service {
+id: u32
+customer_id: u32
+total_amount: Currency
+status: ServiceStatus
+billing_frequency: BillingFrequency
+service_date: DateTime~Utc~
+created_at: DateTime~Utc~
+updated_at: DateTime~Utc~
+items: Vec~ServiceItem~
+calculate_total()
}
class ServiceItem {
+id: u32
+service_id: u32
+name: String
+quantity: i32
+unit_price: Currency
+subtotal: Currency
+tax_rate: f64
+tax_amount: Currency
+is_taxable: bool
+active_till: DateTime~Utc~
}
class Customer {
+id: u32
+name: String
+description: String
+pubkey: String
+contact_ids: Vec~u32~
+created_at: DateTime~Utc~
+updated_at: DateTime~Utc~
}
class Contract {
+id: u32
+customer_id: u32
+service_id: Option~u32~
+sale_id: Option~u32~
+terms: String
+start_date: DateTime~Utc~
+end_date: DateTime~Utc~
+auto_renewal: bool
+renewal_terms: String
+status: ContractStatus
+created_at: DateTime~Utc~
+updated_at: DateTime~Utc~
}
class Invoice {
+id: u32
+customer_id: u32
+total_amount: Currency
+balance_due: Currency
+status: InvoiceStatus
+payment_status: PaymentStatus
+issue_date: DateTime~Utc~
+due_date: DateTime~Utc~
+created_at: DateTime~Utc~
+updated_at: DateTime~Utc~
+items: Vec~InvoiceItem~
+payments: Vec~Payment~
}
class InvoiceItem {
+id: u32
+invoice_id: u32
+description: String
+amount: Currency
+service_id: Option~u32~
+sale_id: Option~u32~
}
class Payment {
+amount: Currency
+date: DateTime~Utc~
+method: String
}
Service "1" -- "many" ServiceItem : contains
Customer "1" -- "many" Service : has
Customer "1" -- "many" Contract : has
Contract "1" -- "0..1" Service : references
Contract "1" -- "0..1" Sale : references
Invoice "1" -- "many" InvoiceItem : contains
Invoice "1" -- "many" Payment : contains
Customer "1" -- "many" Invoice : has
InvoiceItem "1" -- "0..1" Service : references
InvoiceItem "1" -- "0..1" Sale : references
```
### Enums and Supporting Types
```mermaid
classDiagram
class BillingFrequency {
<<enumeration>>
Hourly
Daily
Weekly
Monthly
Yearly
}
class ServiceStatus {
<<enumeration>>
Active
Paused
Cancelled
Completed
}
class ContractStatus {
<<enumeration>>
Active
Expired
Terminated
}
class InvoiceStatus {
<<enumeration>>
Draft
Sent
Paid
Overdue
Cancelled
}
class PaymentStatus {
<<enumeration>>
Unpaid
PartiallyPaid
Paid
}
Service -- ServiceStatus : has
Service -- BillingFrequency : has
Contract -- ContractStatus : has
Invoice -- InvoiceStatus : has
Invoice -- PaymentStatus : has
```
## Detailed Implementation Plan
### 1. Service and ServiceItem (service.rs)
The Service model will be similar to Sale but designed for recurring payments:
- **Service**: Main struct for tracking recurring services
- Fields:
- id: u32
- customer_id: u32
- total_amount: Currency
- status: ServiceStatus
- billing_frequency: BillingFrequency
- service_date: DateTime<Utc>
- created_at: DateTime<Utc>
- updated_at: DateTime<Utc>
- items: Vec<ServiceItem>
- Methods:
- calculate_total(): Updates the total_amount based on all items
- add_item(item: ServiceItem): Adds an item and updates the total
- update_status(status: ServiceStatus): Updates the status and timestamp
- **ServiceItem**: Items within a service (similar to SaleItem)
- Fields:
- id: u32
- service_id: u32
- name: String
- quantity: i32
- unit_price: Currency
- subtotal: Currency
- tax_rate: f64
- tax_amount: Currency
- is_taxable: bool
- active_till: DateTime<Utc>
- Methods:
- calculate_subtotal(): Calculates subtotal based on quantity and unit_price
- calculate_tax(): Calculates tax amount based on subtotal and tax_rate
- **BillingFrequency**: Enum for different billing periods
- Variants: Hourly, Daily, Weekly, Monthly, Yearly
- **ServiceStatus**: Enum for service status
- Variants: Active, Paused, Cancelled, Completed
### 2. Customer (customer.rs)
The Customer model will store customer information:
- **Customer**: Main struct for customer data
- Fields:
- id: u32
- name: String
- description: String
- pubkey: String
- contact_ids: Vec<u32>
- created_at: DateTime<Utc>
- updated_at: DateTime<Utc>
- Methods:
- add_contact(contact_id: u32): Adds a contact ID to the list
- remove_contact(contact_id: u32): Removes a contact ID from the list
### 3. Contract (contract.rs)
The Contract model will link services or sales to customers:
- **Contract**: Main struct for contract data
- Fields:
- id: u32
- customer_id: u32
- service_id: Option<u32>
- sale_id: Option<u32>
- terms: String
- start_date: DateTime<Utc>
- end_date: DateTime<Utc>
- auto_renewal: bool
- renewal_terms: String
- status: ContractStatus
- created_at: DateTime<Utc>
- updated_at: DateTime<Utc>
- Methods:
- is_active(): bool - Checks if the contract is currently active
- is_expired(): bool - Checks if the contract has expired
- renew(): Updates the contract dates based on renewal terms
- **ContractStatus**: Enum for contract status
- Variants: Active, Expired, Terminated
### 4. Invoice (invoice.rs)
The Invoice model will handle billing:
- **Invoice**: Main struct for invoice data
- Fields:
- id: u32
- customer_id: u32
- total_amount: Currency
- balance_due: Currency
- status: InvoiceStatus
- payment_status: PaymentStatus
- issue_date: DateTime<Utc>
- due_date: DateTime<Utc>
- created_at: DateTime<Utc>
- updated_at: DateTime<Utc>
- items: Vec<InvoiceItem>
- payments: Vec<Payment>
- Methods:
- calculate_total(): Updates the total_amount based on all items
- add_item(item: InvoiceItem): Adds an item and updates the total
- add_payment(payment: Payment): Adds a payment and updates balance_due and payment_status
- update_status(status: InvoiceStatus): Updates the status and timestamp
- calculate_balance(): Updates the balance_due based on total_amount and payments
- **InvoiceItem**: Items within an invoice
- Fields:
- id: u32
- invoice_id: u32
- description: String
- amount: Currency
- service_id: Option<u32>
- sale_id: Option<u32>
- **Payment**: Struct for tracking payments
- Fields:
- amount: Currency
- date: DateTime<Utc>
- method: String
- **InvoiceStatus**: Enum for invoice status
- Variants: Draft, Sent, Paid, Overdue, Cancelled
- **PaymentStatus**: Enum for payment status
- Variants: Unpaid, PartiallyPaid, Paid
### 5. Updates to mod.rs
We'll need to update the mod.rs file to include the new modules and re-export the types:
```rust
pub mod currency;
pub mod product;
pub mod sale;
pub mod exchange_rate;
pub mod service;
pub mod customer;
pub mod contract;
pub mod invoice;
// Re-export all model types for convenience
pub use product::{Product, ProductComponent, ProductType, ProductStatus};
pub use sale::{Sale, SaleItem, SaleStatus};
pub use currency::Currency;
pub use exchange_rate::{ExchangeRate, ExchangeRateService, EXCHANGE_RATE_SERVICE};
pub use service::{Service, ServiceItem, ServiceStatus, BillingFrequency};
pub use customer::Customer;
pub use contract::{Contract, ContractStatus};
pub use invoice::{Invoice, InvoiceItem, InvoiceStatus, PaymentStatus, Payment};
// Re-export builder types
pub use product::{ProductBuilder, ProductComponentBuilder};
pub use sale::{SaleBuilder, SaleItemBuilder};
pub use currency::CurrencyBuilder;
pub use exchange_rate::ExchangeRateBuilder;
pub use service::{ServiceBuilder, ServiceItemBuilder};
pub use customer::CustomerBuilder;
pub use contract::ContractBuilder;
pub use invoice::{InvoiceBuilder, InvoiceItemBuilder};
```
### 6. Updates to model_methods.rs
We'll need to update the model_methods.rs file to implement the model methods for the new models:
```rust
use crate::db::db::DB;
use crate::db::base::{SledDBResult, SledModel};
use crate::impl_model_methods;
use crate::models::biz::{Product, Sale, Currency, ExchangeRate, Service, Customer, Contract, Invoice};
// Implement model-specific methods for Product
impl_model_methods!(Product, product, products);
// Implement model-specific methods for Sale
impl_model_methods!(Sale, sale, sales);
// Implement model-specific methods for Currency
impl_model_methods!(Currency, currency, currencies);
// Implement model-specific methods for ExchangeRate
impl_model_methods!(ExchangeRate, exchange_rate, exchange_rates);
// Implement model-specific methods for Service
impl_model_methods!(Service, service, services);
// Implement model-specific methods for Customer
impl_model_methods!(Customer, customer, customers);
// Implement model-specific methods for Contract
impl_model_methods!(Contract, contract, contracts);
// Implement model-specific methods for Invoice
impl_model_methods!(Invoice, invoice, invoices);
```
## Implementation Approach
1. Create the new model files (service.rs, customer.rs, contract.rs, invoice.rs)
2. Implement the structs, enums, and methods for each model
3. Update mod.rs to include the new modules and re-export the types
4. Update model_methods.rs to implement the model methods for the new models
5. Test the new models with example code

View File

@ -0,0 +1,250 @@
use crate::db::base::{SledModel, Storable}; // Import Sled traits from db module
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// ContractStatus represents the status of a contract
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContractStatus {
Active,
Expired,
Terminated,
}
/// Contract represents a legal agreement between a customer and the business
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contract {
pub id: u32,
pub customer_id: u32,
pub service_id: Option<u32>,
pub sale_id: Option<u32>,
pub terms: String,
pub start_date: DateTime<Utc>,
pub end_date: DateTime<Utc>,
pub auto_renewal: bool,
pub renewal_terms: String,
pub status: ContractStatus,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Contract {
/// Create a new contract with default timestamps
pub fn new(
id: u32,
customer_id: u32,
terms: String,
start_date: DateTime<Utc>,
end_date: DateTime<Utc>,
auto_renewal: bool,
renewal_terms: String,
) -> Self {
let now = Utc::now();
Self {
id,
customer_id,
service_id: None,
sale_id: None,
terms,
start_date,
end_date,
auto_renewal,
renewal_terms,
status: ContractStatus::Active,
created_at: now,
updated_at: now,
}
}
/// Link the contract to a service
pub fn link_to_service(&mut self, service_id: u32) {
self.service_id = Some(service_id);
self.sale_id = None; // A contract can only be linked to either a service or a sale
self.updated_at = Utc::now();
}
/// Link the contract to a sale
pub fn link_to_sale(&mut self, sale_id: u32) {
self.sale_id = Some(sale_id);
self.service_id = None; // A contract can only be linked to either a service or a sale
self.updated_at = Utc::now();
}
/// Check if the contract is currently active
pub fn is_active(&self) -> bool {
let now = Utc::now();
self.status == ContractStatus::Active &&
now >= self.start_date &&
now <= self.end_date
}
/// Check if the contract has expired
pub fn is_expired(&self) -> bool {
let now = Utc::now();
now > self.end_date
}
/// Update the contract status
pub fn update_status(&mut self, status: ContractStatus) {
self.status = status;
self.updated_at = Utc::now();
}
/// Renew the contract based on renewal terms
pub fn renew(&mut self) -> Result<(), &'static str> {
if !self.auto_renewal {
return Err("Contract is not set for auto-renewal");
}
if self.status != ContractStatus::Active {
return Err("Cannot renew a non-active contract");
}
// Calculate new dates based on the current end date
let duration = self.end_date - self.start_date;
self.start_date = self.end_date;
self.end_date = self.end_date + duration;
self.updated_at = Utc::now();
Ok(())
}
}
/// Builder for Contract
pub struct ContractBuilder {
id: Option<u32>,
customer_id: Option<u32>,
service_id: Option<u32>,
sale_id: Option<u32>,
terms: Option<String>,
start_date: Option<DateTime<Utc>>,
end_date: Option<DateTime<Utc>>,
auto_renewal: Option<bool>,
renewal_terms: Option<String>,
status: Option<ContractStatus>,
created_at: Option<DateTime<Utc>>,
updated_at: Option<DateTime<Utc>>,
}
impl ContractBuilder {
/// Create a new ContractBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
customer_id: None,
service_id: None,
sale_id: None,
terms: None,
start_date: None,
end_date: None,
auto_renewal: None,
renewal_terms: None,
status: None,
created_at: None,
updated_at: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the customer_id
pub fn customer_id(mut self, customer_id: u32) -> Self {
self.customer_id = Some(customer_id);
self
}
/// Set the service_id
pub fn service_id(mut self, service_id: u32) -> Self {
self.service_id = Some(service_id);
self.sale_id = None; // A contract can only be linked to either a service or a sale
self
}
/// Set the sale_id
pub fn sale_id(mut self, sale_id: u32) -> Self {
self.sale_id = Some(sale_id);
self.service_id = None; // A contract can only be linked to either a service or a sale
self
}
/// Set the terms
pub fn terms<S: Into<String>>(mut self, terms: S) -> Self {
self.terms = Some(terms.into());
self
}
/// Set the start_date
pub fn start_date(mut self, start_date: DateTime<Utc>) -> Self {
self.start_date = Some(start_date);
self
}
/// Set the end_date
pub fn end_date(mut self, end_date: DateTime<Utc>) -> Self {
self.end_date = Some(end_date);
self
}
/// Set auto_renewal
pub fn auto_renewal(mut self, auto_renewal: bool) -> Self {
self.auto_renewal = Some(auto_renewal);
self
}
/// Set the renewal_terms
pub fn renewal_terms<S: Into<String>>(mut self, renewal_terms: S) -> Self {
self.renewal_terms = Some(renewal_terms.into());
self
}
/// Set the status
pub fn status(mut self, status: ContractStatus) -> Self {
self.status = Some(status);
self
}
/// Build the Contract object
pub fn build(self) -> Result<Contract, &'static str> {
let now = Utc::now();
// Validate that start_date is before end_date
let start_date = self.start_date.ok_or("start_date is required")?;
let end_date = self.end_date.ok_or("end_date is required")?;
if start_date >= end_date {
return Err("start_date must be before end_date");
}
Ok(Contract {
id: self.id.ok_or("id is required")?,
customer_id: self.customer_id.ok_or("customer_id is required")?,
service_id: self.service_id,
sale_id: self.sale_id,
terms: self.terms.ok_or("terms is required")?,
start_date,
end_date,
auto_renewal: self.auto_renewal.unwrap_or(false),
renewal_terms: self.renewal_terms.ok_or("renewal_terms is required")?,
status: self.status.unwrap_or(ContractStatus::Active),
created_at: self.created_at.unwrap_or(now),
updated_at: self.updated_at.unwrap_or(now),
})
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Contract {}
// Implement SledModel trait
impl SledModel for Contract {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"contract"
}
}

View File

@ -0,0 +1,148 @@
use crate::db::base::{SledModel, Storable}; // Import Sled traits from db module
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// Customer represents a customer who can purchase products or services
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Customer {
pub id: u32,
pub name: String,
pub description: String,
pub pubkey: String,
pub contact_ids: Vec<u32>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Customer {
/// Create a new customer with default timestamps
pub fn new(
id: u32,
name: String,
description: String,
pubkey: String,
) -> Self {
let now = Utc::now();
Self {
id,
name,
description,
pubkey,
contact_ids: Vec::new(),
created_at: now,
updated_at: now,
}
}
/// Add a contact ID to the customer
pub fn add_contact(&mut self, contact_id: u32) {
if !self.contact_ids.contains(&contact_id) {
self.contact_ids.push(contact_id);
self.updated_at = Utc::now();
}
}
/// Remove a contact ID from the customer
pub fn remove_contact(&mut self, contact_id: u32) -> bool {
let len = self.contact_ids.len();
self.contact_ids.retain(|&id| id != contact_id);
if self.contact_ids.len() < len {
self.updated_at = Utc::now();
true
} else {
false
}
}
}
/// Builder for Customer
pub struct CustomerBuilder {
id: Option<u32>,
name: Option<String>,
description: Option<String>,
pubkey: Option<String>,
contact_ids: Vec<u32>,
created_at: Option<DateTime<Utc>>,
updated_at: Option<DateTime<Utc>>,
}
impl CustomerBuilder {
/// Create a new CustomerBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
name: None,
description: None,
pubkey: None,
contact_ids: Vec::new(),
created_at: None,
updated_at: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the name
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
self.name = Some(name.into());
self
}
/// Set the description
pub fn description<S: Into<String>>(mut self, description: S) -> Self {
self.description = Some(description.into());
self
}
/// Set the pubkey
pub fn pubkey<S: Into<String>>(mut self, pubkey: S) -> Self {
self.pubkey = Some(pubkey.into());
self
}
/// Add a contact ID
pub fn add_contact(mut self, contact_id: u32) -> Self {
self.contact_ids.push(contact_id);
self
}
/// Set multiple contact IDs
pub fn contact_ids(mut self, contact_ids: Vec<u32>) -> Self {
self.contact_ids = contact_ids;
self
}
/// Build the Customer object
pub fn build(self) -> Result<Customer, &'static str> {
let now = Utc::now();
Ok(Customer {
id: self.id.ok_or("id is required")?,
name: self.name.ok_or("name is required")?,
description: self.description.ok_or("description is required")?,
pubkey: self.pubkey.ok_or("pubkey is required")?,
contact_ids: self.contact_ids,
created_at: self.created_at.unwrap_or(now),
updated_at: self.updated_at.unwrap_or(now),
})
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Customer {}
// Implement SledModel trait
impl SledModel for Customer {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"customer"
}
}

View File

@ -0,0 +1,167 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::base::{SledModel, Storable};
/// ExchangeRate represents an exchange rate between two currencies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExchangeRate {
pub base_currency: String,
pub target_currency: String,
pub rate: f64,
pub timestamp: DateTime<Utc>,
}
impl ExchangeRate {
/// Create a new exchange rate
pub fn new(base_currency: String, target_currency: String, rate: f64) -> Self {
Self {
base_currency,
target_currency,
rate,
timestamp: Utc::now(),
}
}
}
/// Builder for ExchangeRate
pub struct ExchangeRateBuilder {
base_currency: Option<String>,
target_currency: Option<String>,
rate: Option<f64>,
timestamp: Option<DateTime<Utc>>,
}
impl ExchangeRateBuilder {
/// Create a new ExchangeRateBuilder with all fields set to None
pub fn new() -> Self {
Self {
base_currency: None,
target_currency: None,
rate: None,
timestamp: None,
}
}
/// Set the base currency
pub fn base_currency<S: Into<String>>(mut self, base_currency: S) -> Self {
self.base_currency = Some(base_currency.into());
self
}
/// Set the target currency
pub fn target_currency<S: Into<String>>(mut self, target_currency: S) -> Self {
self.target_currency = Some(target_currency.into());
self
}
/// Set the rate
pub fn rate(mut self, rate: f64) -> Self {
self.rate = Some(rate);
self
}
/// Set the timestamp
pub fn timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
self.timestamp = Some(timestamp);
self
}
/// Build the ExchangeRate object
pub fn build(self) -> Result<ExchangeRate, &'static str> {
let now = Utc::now();
Ok(ExchangeRate {
base_currency: self.base_currency.ok_or("base_currency is required")?,
target_currency: self.target_currency.ok_or("target_currency is required")?,
rate: self.rate.ok_or("rate is required")?,
timestamp: self.timestamp.unwrap_or(now),
})
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for ExchangeRate {}
// Implement SledModel trait
impl SledModel for ExchangeRate {
fn get_id(&self) -> String {
format!("{}_{}", self.base_currency, self.target_currency)
}
fn db_prefix() -> &'static str {
"exchange_rate"
}
}
/// ExchangeRateService provides methods to get and set exchange rates
#[derive(Clone)]
pub struct ExchangeRateService {
rates: Arc<Mutex<HashMap<String, ExchangeRate>>>,
}
impl ExchangeRateService {
/// Create a new exchange rate service
pub fn new() -> Self {
Self {
rates: Arc::new(Mutex::new(HashMap::new())),
}
}
/// Set an exchange rate
pub fn set_rate(&self, exchange_rate: ExchangeRate) {
let key = format!("{}_{}", exchange_rate.base_currency, exchange_rate.target_currency);
let mut rates = self.rates.lock().unwrap();
rates.insert(key, exchange_rate);
}
/// Get an exchange rate
pub fn get_rate(&self, base_currency: &str, target_currency: &str) -> Option<ExchangeRate> {
let key = format!("{}_{}", base_currency, target_currency);
let rates = self.rates.lock().unwrap();
rates.get(&key).cloned()
}
/// Convert an amount from one currency to another
pub fn convert(&self, amount: f64, from_currency: &str, to_currency: &str) -> Option<f64> {
// If the currencies are the same, return the amount
if from_currency == to_currency {
return Some(amount);
}
// Try to get the direct exchange rate
if let Some(rate) = self.get_rate(from_currency, to_currency) {
return Some(amount * rate.rate);
}
// Try to get the inverse exchange rate
if let Some(rate) = self.get_rate(to_currency, from_currency) {
return Some(amount / rate.rate);
}
// Try to convert via USD
if from_currency != "USD" && to_currency != "USD" {
if let Some(from_to_usd) = self.convert(amount, from_currency, "USD") {
return self.convert(from_to_usd, "USD", to_currency);
}
}
None
}
}
// Create a global instance of the exchange rate service
lazy_static::lazy_static! {
pub static ref EXCHANGE_RATE_SERVICE: ExchangeRateService = {
let service = ExchangeRateService::new();
// Set some default exchange rates
service.set_rate(ExchangeRate::new("USD".to_string(), "EUR".to_string(), 0.85));
service.set_rate(ExchangeRate::new("USD".to_string(), "GBP".to_string(), 0.75));
service.set_rate(ExchangeRate::new("USD".to_string(), "JPY".to_string(), 110.0));
service.set_rate(ExchangeRate::new("USD".to_string(), "CAD".to_string(), 1.25));
service.set_rate(ExchangeRate::new("USD".to_string(), "AUD".to_string(), 1.35));
service
};
}

View File

@ -0,0 +1,507 @@
use crate::models::biz::Currency; // Use crate:: for importing from the module
use crate::db::base::{SledModel, Storable}; // Import Sled traits from db module
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// InvoiceStatus represents the status of an invoice
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvoiceStatus {
Draft,
Sent,
Paid,
Overdue,
Cancelled,
}
/// PaymentStatus represents the payment status of an invoice
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PaymentStatus {
Unpaid,
PartiallyPaid,
Paid,
}
/// Payment represents a payment made against an invoice
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Payment {
pub amount: Currency,
pub date: DateTime<Utc>,
pub method: String,
}
impl Payment {
/// Create a new payment
pub fn new(amount: Currency, method: String) -> Self {
Self {
amount,
date: Utc::now(),
method,
}
}
}
/// InvoiceItem represents an item in an invoice
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvoiceItem {
pub id: u32,
pub invoice_id: u32,
pub description: String,
pub amount: Currency,
pub service_id: Option<u32>,
pub sale_id: Option<u32>,
}
impl InvoiceItem {
/// Create a new invoice item
pub fn new(
id: u32,
invoice_id: u32,
description: String,
amount: Currency,
) -> Self {
Self {
id,
invoice_id,
description,
amount,
service_id: None,
sale_id: None,
}
}
/// Link the invoice item to a service
pub fn link_to_service(&mut self, service_id: u32) {
self.service_id = Some(service_id);
self.sale_id = None; // An invoice item can only be linked to either a service or a sale
}
/// Link the invoice item to a sale
pub fn link_to_sale(&mut self, sale_id: u32) {
self.sale_id = Some(sale_id);
self.service_id = None; // An invoice item can only be linked to either a service or a sale
}
}
/// Builder for InvoiceItem
pub struct InvoiceItemBuilder {
id: Option<u32>,
invoice_id: Option<u32>,
description: Option<String>,
amount: Option<Currency>,
service_id: Option<u32>,
sale_id: Option<u32>,
}
impl InvoiceItemBuilder {
/// Create a new InvoiceItemBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
invoice_id: None,
description: None,
amount: None,
service_id: None,
sale_id: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the invoice_id
pub fn invoice_id(mut self, invoice_id: u32) -> Self {
self.invoice_id = Some(invoice_id);
self
}
/// Set the description
pub fn description<S: Into<String>>(mut self, description: S) -> Self {
self.description = Some(description.into());
self
}
/// Set the amount
pub fn amount(mut self, amount: Currency) -> Self {
self.amount = Some(amount);
self
}
/// Set the service_id
pub fn service_id(mut self, service_id: u32) -> Self {
self.service_id = Some(service_id);
self.sale_id = None; // An invoice item can only be linked to either a service or a sale
self
}
/// Set the sale_id
pub fn sale_id(mut self, sale_id: u32) -> Self {
self.sale_id = Some(sale_id);
self.service_id = None; // An invoice item can only be linked to either a service or a sale
self
}
/// Build the InvoiceItem object
pub fn build(self) -> Result<InvoiceItem, &'static str> {
Ok(InvoiceItem {
id: self.id.ok_or("id is required")?,
invoice_id: self.invoice_id.ok_or("invoice_id is required")?,
description: self.description.ok_or("description is required")?,
amount: self.amount.ok_or("amount is required")?,
service_id: self.service_id,
sale_id: self.sale_id,
})
}
}
/// Invoice represents an invoice sent to a customer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invoice {
pub id: u32,
pub customer_id: u32,
pub total_amount: Currency,
pub balance_due: Currency,
pub status: InvoiceStatus,
pub payment_status: PaymentStatus,
pub issue_date: DateTime<Utc>,
pub due_date: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub items: Vec<InvoiceItem>,
pub payments: Vec<Payment>,
}
impl Invoice {
/// Create a new invoice with default timestamps
pub fn new(
id: u32,
customer_id: u32,
currency_code: String,
issue_date: DateTime<Utc>,
due_date: DateTime<Utc>,
) -> Self {
let now = Utc::now();
let zero_amount = Currency {
amount: 0.0,
currency_code: currency_code.clone(),
};
Self {
id,
customer_id,
total_amount: zero_amount.clone(),
balance_due: zero_amount,
status: InvoiceStatus::Draft,
payment_status: PaymentStatus::Unpaid,
issue_date,
due_date,
created_at: now,
updated_at: now,
items: Vec::new(),
payments: Vec::new(),
}
}
/// Add an item to the invoice and update the total amount
pub fn add_item(&mut self, item: InvoiceItem) {
// Make sure the item's invoice_id matches this invoice
assert_eq!(self.id, item.invoice_id, "Item invoice_id must match invoice id");
// Update the total amount
if self.items.is_empty() {
// First item, initialize the total amount with the same currency
self.total_amount = Currency {
amount: item.amount.amount,
currency_code: item.amount.currency_code.clone(),
};
self.balance_due = Currency {
amount: item.amount.amount,
currency_code: item.amount.currency_code.clone(),
};
} else {
// Add to the existing total
// (Assumes all items have the same currency)
self.total_amount.amount += item.amount.amount;
self.balance_due.amount += item.amount.amount;
}
// Add the item to the list
self.items.push(item);
// Update the invoice timestamp
self.updated_at = Utc::now();
}
/// Calculate the total amount based on all items
pub fn calculate_total(&mut self) {
if self.items.is_empty() {
return;
}
// Get the currency code from the first item
let currency_code = self.items[0].amount.currency_code.clone();
// Calculate the total amount
let mut total = 0.0;
for item in &self.items {
total += item.amount.amount;
}
// Update the total amount
self.total_amount = Currency {
amount: total,
currency_code: currency_code.clone(),
};
// Recalculate the balance due
self.calculate_balance();
// Update the invoice timestamp
self.updated_at = Utc::now();
}
/// Add a payment to the invoice and update the balance due and payment status
pub fn add_payment(&mut self, payment: Payment) {
// Update the balance due
self.balance_due.amount -= payment.amount.amount;
// Add the payment to the list
self.payments.push(payment);
// Update the payment status
self.update_payment_status();
// Update the invoice timestamp
self.updated_at = Utc::now();
}
/// Calculate the balance due based on total amount and payments
pub fn calculate_balance(&mut self) {
// Start with the total amount
let mut balance = self.total_amount.amount;
// Subtract all payments
for payment in &self.payments {
balance -= payment.amount.amount;
}
// Update the balance due
self.balance_due = Currency {
amount: balance,
currency_code: self.total_amount.currency_code.clone(),
};
// Update the payment status
self.update_payment_status();
}
/// Update the payment status based on the balance due
fn update_payment_status(&mut self) {
if self.balance_due.amount <= 0.0 {
self.payment_status = PaymentStatus::Paid;
// If fully paid, also update the invoice status
if self.status != InvoiceStatus::Cancelled {
self.status = InvoiceStatus::Paid;
}
} else if self.payments.is_empty() {
self.payment_status = PaymentStatus::Unpaid;
} else {
self.payment_status = PaymentStatus::PartiallyPaid;
}
}
/// Update the status of the invoice
pub fn update_status(&mut self, status: InvoiceStatus) {
self.status = status;
self.updated_at = Utc::now();
// If the invoice is cancelled, don't change the payment status
if status != InvoiceStatus::Cancelled {
// Re-evaluate the payment status
self.update_payment_status();
}
}
/// Check if the invoice is overdue
pub fn is_overdue(&self) -> bool {
let now = Utc::now();
self.payment_status != PaymentStatus::Paid &&
now > self.due_date &&
self.status != InvoiceStatus::Cancelled
}
/// Mark the invoice as overdue if it's past the due date
pub fn check_if_overdue(&mut self) -> bool {
if self.is_overdue() && self.status != InvoiceStatus::Overdue {
self.status = InvoiceStatus::Overdue;
self.updated_at = Utc::now();
true
} else {
false
}
}
}
/// Builder for Invoice
pub struct InvoiceBuilder {
id: Option<u32>,
customer_id: Option<u32>,
total_amount: Option<Currency>,
balance_due: Option<Currency>,
status: Option<InvoiceStatus>,
payment_status: Option<PaymentStatus>,
issue_date: Option<DateTime<Utc>>,
due_date: Option<DateTime<Utc>>,
created_at: Option<DateTime<Utc>>,
updated_at: Option<DateTime<Utc>>,
items: Vec<InvoiceItem>,
payments: Vec<Payment>,
currency_code: Option<String>,
}
impl InvoiceBuilder {
/// Create a new InvoiceBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
customer_id: None,
total_amount: None,
balance_due: None,
status: None,
payment_status: None,
issue_date: None,
due_date: None,
created_at: None,
updated_at: None,
items: Vec::new(),
payments: Vec::new(),
currency_code: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the customer_id
pub fn customer_id(mut self, customer_id: u32) -> Self {
self.customer_id = Some(customer_id);
self
}
/// Set the currency_code
pub fn currency_code<S: Into<String>>(mut self, currency_code: S) -> Self {
self.currency_code = Some(currency_code.into());
self
}
/// Set the status
pub fn status(mut self, status: InvoiceStatus) -> Self {
self.status = Some(status);
self
}
/// Set the issue_date
pub fn issue_date(mut self, issue_date: DateTime<Utc>) -> Self {
self.issue_date = Some(issue_date);
self
}
/// Set the due_date
pub fn due_date(mut self, due_date: DateTime<Utc>) -> Self {
self.due_date = Some(due_date);
self
}
/// Add an item to the invoice
pub fn add_item(mut self, item: InvoiceItem) -> Self {
self.items.push(item);
self
}
/// Add a payment to the invoice
pub fn add_payment(mut self, payment: Payment) -> Self {
self.payments.push(payment);
self
}
/// Build the Invoice object
pub fn build(self) -> Result<Invoice, &'static str> {
let now = Utc::now();
let id = self.id.ok_or("id is required")?;
let currency_code = self.currency_code.ok_or("currency_code is required")?;
// Initialize with empty total amount and balance due
let mut total_amount = Currency {
amount: 0.0,
currency_code: currency_code.clone(),
};
// Calculate total amount from items
for item in &self.items {
// Make sure the item's invoice_id matches this invoice
if item.invoice_id != id {
return Err("Item invoice_id must match invoice id");
}
total_amount.amount += item.amount.amount;
}
// Calculate balance due (total minus payments)
let mut balance_due = total_amount.clone();
for payment in &self.payments {
balance_due.amount -= payment.amount.amount;
}
// Determine payment status
let payment_status = if balance_due.amount <= 0.0 {
PaymentStatus::Paid
} else if self.payments.is_empty() {
PaymentStatus::Unpaid
} else {
PaymentStatus::PartiallyPaid
};
// Determine invoice status if not provided
let status = if let Some(status) = self.status {
status
} else if payment_status == PaymentStatus::Paid {
InvoiceStatus::Paid
} else {
InvoiceStatus::Draft
};
Ok(Invoice {
id,
customer_id: self.customer_id.ok_or("customer_id is required")?,
total_amount: self.total_amount.unwrap_or(total_amount),
balance_due: self.balance_due.unwrap_or(balance_due),
status,
payment_status,
issue_date: self.issue_date.ok_or("issue_date is required")?,
due_date: self.due_date.ok_or("due_date is required")?,
created_at: self.created_at.unwrap_or(now),
updated_at: self.updated_at.unwrap_or(now),
items: self.items,
payments: self.payments,
})
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Invoice {}
// Implement SledModel trait
impl SledModel for Invoice {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"invoice"
}
}

View File

@ -1,13 +1,28 @@
pub mod currency;
pub mod product;
pub mod sale;
pub mod exchange_rate;
pub mod service;
pub mod customer;
pub mod contract;
pub mod invoice;
// Re-export all model types for convenience
pub use product::{Product, ProductComponent, ProductType, ProductStatus};
pub use sale::{Sale, SaleItem, SaleStatus};
pub use currency::Currency;
pub use exchange_rate::{ExchangeRate, ExchangeRateService, EXCHANGE_RATE_SERVICE};
pub use service::{Service, ServiceItem, ServiceStatus, BillingFrequency};
pub use customer::Customer;
pub use contract::{Contract, ContractStatus};
pub use invoice::{Invoice, InvoiceItem, InvoiceStatus, PaymentStatus, Payment};
// Re-export builder types
pub use product::{ProductBuilder, ProductComponentBuilder};
pub use sale::{SaleBuilder, SaleItemBuilder};
pub use currency::CurrencyBuilder;
pub use exchange_rate::ExchangeRateBuilder;
pub use service::{ServiceBuilder, ServiceItemBuilder};
pub use customer::CustomerBuilder;
pub use contract::ContractBuilder;
pub use invoice::{InvoiceBuilder, InvoiceItemBuilder};

View File

@ -0,0 +1,469 @@
use crate::models::biz::Currency; // Use crate:: for importing from the module
use crate::db::base::{SledModel, Storable}; // Import Sled traits from db module
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// BillingFrequency represents the frequency of billing for a service
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BillingFrequency {
Hourly,
Daily,
Weekly,
Monthly,
Yearly,
}
/// ServiceStatus represents the status of a service
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ServiceStatus {
Active,
Paused,
Cancelled,
Completed,
}
/// ServiceItem represents an item in a service
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceItem {
pub id: u32,
pub service_id: u32,
pub product_id: u32,
pub name: String,
pub quantity: i32,
pub unit_price: Currency,
pub subtotal: Currency,
pub tax_rate: f64,
pub tax_amount: Currency,
pub is_taxable: bool,
pub active_till: DateTime<Utc>,
}
impl ServiceItem {
/// Create a new service item
pub fn new(
id: u32,
service_id: u32,
product_id: u32,
name: String,
quantity: i32,
unit_price: Currency,
tax_rate: f64,
is_taxable: bool,
active_till: DateTime<Utc>,
) -> Self {
// Calculate subtotal
let amount = unit_price.amount * quantity as f64;
let subtotal = Currency {
amount,
currency_code: unit_price.currency_code.clone(),
};
// Calculate tax amount if taxable
let tax_amount = if is_taxable {
Currency {
amount: subtotal.amount * tax_rate,
currency_code: unit_price.currency_code.clone(),
}
} else {
Currency {
amount: 0.0,
currency_code: unit_price.currency_code.clone(),
}
};
Self {
id,
service_id,
product_id,
name,
quantity,
unit_price,
subtotal,
tax_rate,
tax_amount,
is_taxable,
active_till,
}
}
/// Calculate the subtotal based on quantity and unit price
pub fn calculate_subtotal(&mut self) {
let amount = self.unit_price.amount * self.quantity as f64;
self.subtotal = Currency {
amount,
currency_code: self.unit_price.currency_code.clone(),
};
}
/// Calculate the tax amount based on subtotal and tax rate
pub fn calculate_tax(&mut self) {
if self.is_taxable {
self.tax_amount = Currency {
amount: self.subtotal.amount * self.tax_rate,
currency_code: self.subtotal.currency_code.clone(),
};
} else {
self.tax_amount = Currency {
amount: 0.0,
currency_code: self.subtotal.currency_code.clone(),
};
}
}
}
/// Builder for ServiceItem
pub struct ServiceItemBuilder {
id: Option<u32>,
service_id: Option<u32>,
product_id: Option<u32>,
name: Option<String>,
quantity: Option<i32>,
unit_price: Option<Currency>,
subtotal: Option<Currency>,
tax_rate: Option<f64>,
tax_amount: Option<Currency>,
is_taxable: Option<bool>,
active_till: Option<DateTime<Utc>>,
}
impl ServiceItemBuilder {
/// Create a new ServiceItemBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
service_id: None,
product_id: None,
name: None,
quantity: None,
unit_price: None,
subtotal: None,
tax_rate: None,
tax_amount: None,
is_taxable: None,
active_till: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the service_id
pub fn service_id(mut self, service_id: u32) -> Self {
self.service_id = Some(service_id);
self
}
/// Set the product_id
pub fn product_id(mut self, product_id: u32) -> Self {
self.product_id = Some(product_id);
self
}
/// Set the name
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
self.name = Some(name.into());
self
}
/// Set the quantity
pub fn quantity(mut self, quantity: i32) -> Self {
self.quantity = Some(quantity);
self
}
/// Set the unit_price
pub fn unit_price(mut self, unit_price: Currency) -> Self {
self.unit_price = Some(unit_price);
self
}
/// Set the tax_rate
pub fn tax_rate(mut self, tax_rate: f64) -> Self {
self.tax_rate = Some(tax_rate);
self
}
/// Set is_taxable
pub fn is_taxable(mut self, is_taxable: bool) -> Self {
self.is_taxable = Some(is_taxable);
self
}
/// Set the active_till
pub fn active_till(mut self, active_till: DateTime<Utc>) -> Self {
self.active_till = Some(active_till);
self
}
/// Build the ServiceItem object
pub fn build(self) -> Result<ServiceItem, &'static str> {
let unit_price = self.unit_price.ok_or("unit_price is required")?;
let quantity = self.quantity.ok_or("quantity is required")?;
let tax_rate = self.tax_rate.unwrap_or(0.0);
let is_taxable = self.is_taxable.unwrap_or(false);
// Calculate subtotal
let amount = unit_price.amount * quantity as f64;
let subtotal = Currency {
amount,
currency_code: unit_price.currency_code.clone(),
};
// Calculate tax amount if taxable
let tax_amount = if is_taxable {
Currency {
amount: subtotal.amount * tax_rate,
currency_code: unit_price.currency_code.clone(),
}
} else {
Currency {
amount: 0.0,
currency_code: unit_price.currency_code.clone(),
}
};
Ok(ServiceItem {
id: self.id.ok_or("id is required")?,
service_id: self.service_id.ok_or("service_id is required")?,
product_id: self.product_id.ok_or("product_id is required")?,
name: self.name.ok_or("name is required")?,
quantity,
unit_price,
subtotal,
tax_rate,
tax_amount,
is_taxable,
active_till: self.active_till.ok_or("active_till is required")?,
})
}
}
/// Service represents a recurring service with billing frequency
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Service {
pub id: u32,
pub customer_id: u32,
pub total_amount: Currency,
pub status: ServiceStatus,
pub billing_frequency: BillingFrequency,
pub service_date: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub items: Vec<ServiceItem>,
}
impl Service {
/// Create a new service with default timestamps
pub fn new(
id: u32,
customer_id: u32,
currency_code: String,
status: ServiceStatus,
billing_frequency: BillingFrequency,
) -> Self {
let now = Utc::now();
Self {
id,
customer_id,
total_amount: Currency { amount: 0.0, currency_code },
status,
billing_frequency,
service_date: now,
created_at: now,
updated_at: now,
items: Vec::new(),
}
}
/// Add an item to the service and update the total amount
pub fn add_item(&mut self, item: ServiceItem) {
// Make sure the item's service_id matches this service
assert_eq!(self.id, item.service_id, "Item service_id must match service id");
// Update the total amount
if self.items.is_empty() {
// First item, initialize the total amount with the same currency
self.total_amount = Currency {
amount: item.subtotal.amount + item.tax_amount.amount,
currency_code: item.subtotal.currency_code.clone(),
};
} else {
// Add to the existing total
// (Assumes all items have the same currency)
self.total_amount.amount += item.subtotal.amount + item.tax_amount.amount;
}
// Add the item to the list
self.items.push(item);
// Update the service timestamp
self.updated_at = Utc::now();
}
/// Calculate the total amount based on all items
pub fn calculate_total(&mut self) {
if self.items.is_empty() {
return;
}
// Get the currency code from the first item
let currency_code = self.items[0].subtotal.currency_code.clone();
// Calculate the total amount
let mut total = 0.0;
for item in &self.items {
total += item.subtotal.amount + item.tax_amount.amount;
}
// Update the total amount
self.total_amount = Currency {
amount: total,
currency_code,
};
// Update the service timestamp
self.updated_at = Utc::now();
}
/// Update the status of the service
pub fn update_status(&mut self, status: ServiceStatus) {
self.status = status;
self.updated_at = Utc::now();
}
}
/// Builder for Service
pub struct ServiceBuilder {
id: Option<u32>,
customer_id: Option<u32>,
total_amount: Option<Currency>,
status: Option<ServiceStatus>,
billing_frequency: Option<BillingFrequency>,
service_date: Option<DateTime<Utc>>,
created_at: Option<DateTime<Utc>>,
updated_at: Option<DateTime<Utc>>,
items: Vec<ServiceItem>,
currency_code: Option<String>,
}
impl ServiceBuilder {
/// Create a new ServiceBuilder with all fields set to None
pub fn new() -> Self {
Self {
id: None,
customer_id: None,
total_amount: None,
status: None,
billing_frequency: None,
service_date: None,
created_at: None,
updated_at: None,
items: Vec::new(),
currency_code: None,
}
}
/// Set the id
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// Set the customer_id
pub fn customer_id(mut self, customer_id: u32) -> Self {
self.customer_id = Some(customer_id);
self
}
/// Set the currency_code
pub fn currency_code<S: Into<String>>(mut self, currency_code: S) -> Self {
self.currency_code = Some(currency_code.into());
self
}
/// Set the status
pub fn status(mut self, status: ServiceStatus) -> Self {
self.status = Some(status);
self
}
/// Set the billing_frequency
pub fn billing_frequency(mut self, billing_frequency: BillingFrequency) -> Self {
self.billing_frequency = Some(billing_frequency);
self
}
/// Set the service_date
pub fn service_date(mut self, service_date: DateTime<Utc>) -> Self {
self.service_date = Some(service_date);
self
}
/// Add an item to the service
pub fn add_item(mut self, item: ServiceItem) -> Self {
self.items.push(item);
self
}
/// Build the Service object
pub fn build(self) -> Result<Service, &'static str> {
let now = Utc::now();
let id = self.id.ok_or("id is required")?;
let currency_code = self.currency_code.ok_or("currency_code is required")?;
// Initialize with empty total amount
let mut total_amount = Currency {
amount: 0.0,
currency_code: currency_code.clone(),
};
// Calculate total amount from items
for item in &self.items {
// Make sure the item's service_id matches this service
if item.service_id != id {
return Err("Item service_id must match service id");
}
if total_amount.amount == 0.0 {
// First item, initialize the total amount with the same currency
total_amount = Currency {
amount: item.subtotal.amount + item.tax_amount.amount,
currency_code: item.subtotal.currency_code.clone(),
};
} else {
// Add to the existing total
// (Assumes all items have the same currency)
total_amount.amount += item.subtotal.amount + item.tax_amount.amount;
}
}
Ok(Service {
id,
customer_id: self.customer_id.ok_or("customer_id is required")?,
total_amount: self.total_amount.unwrap_or(total_amount),
status: self.status.ok_or("status is required")?,
billing_frequency: self.billing_frequency.ok_or("billing_frequency is required")?,
service_date: self.service_date.unwrap_or(now),
created_at: self.created_at.unwrap_or(now),
updated_at: self.updated_at.unwrap_or(now),
items: self.items,
})
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Service {}
// Implement SledModel trait
impl SledModel for Service {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"service"
}
}

View File

@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use crate::db::{SledModel, Storable};
use std::collections::HashMap;
/// Role represents the role of a member in a circle

View File

@ -6,4 +6,4 @@ pub use circle::{Circle, Member, Role};
pub use name::{Name, Record, RecordType};
// Re-export database components
pub use crate::core::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};

View File

@ -5,5 +5,5 @@ pub mod name;
pub use circle::{Circle, Member, Role};
pub use name::{Name, Record, RecordType};
// Re-export database components from core module
pub use crate::core::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};
// Re-export database components from db module
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};

View File

@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use crate::db::{SledModel, Storable};
/// Record types for a DNS record
#[derive(Debug, Clone, Serialize, Deserialize)]

View File

@ -0,0 +1,496 @@
# Governance Module Enhancement Plan (Revised)
## 1. Current State Analysis
The governance module currently consists of:
- **Company**: Company model with basic company information
- **Shareholder**: Shareholder model for managing company ownership
- **Meeting**: Meeting and Attendee models for board meetings
- **User**: User model for system users
- **Vote**: Vote, VoteOption, and Ballot models for voting
All models implement the `Storable` and `SledModel` traits for database integration, but the module has several limitations:
- Not imported in src/models/mod.rs, making it inaccessible to the rest of the project
- No mod.rs file to organize and re-export the types
- No README.md file to document the purpose and usage
- Inconsistent imports across files (e.g., crate::db vs crate::core)
- Limited utility methods and relationships between models
- No integration with other modules like biz, mcc, or circle
## 2. Planned Enhancements
### 2.1 Module Organization and Integration
- Create a mod.rs file to organize and re-export the types
- Add the governance module to src/models/mod.rs
- Create a README.md file to document the purpose and usage
- Standardize imports across all files
### 2.2 New Models
#### 2.2.1 Resolution Model
Create a new `resolution.rs` file with a Resolution model for managing board resolutions:
- Resolution information (title, description, text)
- Resolution status (Draft, Proposed, Approved, Rejected)
- Voting results and approvals
- Integration with Meeting and Vote models
### 2.3 Enhanced Relationships and Integration
#### 2.3.1 Integration with Biz Module
- Link Company with biz::Customer and biz::Contract
- Link Shareholder with biz::Customer
- Link Meeting with biz::Invoice for expense tracking
#### 2.3.2 Integration with MCC Module
- Link Meeting with mcc::Calendar and mcc::Event
- Link User with mcc::Contact
- Link Vote with mcc::Message for notifications
#### 2.3.3 Integration with Circle Module
- Link Company with circle::Circle for group-based access control
- Link User with circle::Member for role-based permissions
### 2.4 Utility Methods and Functionality
- Add filtering and searching methods to all models
- Add relationship management methods between models
- Add validation and business logic methods
## 3. Implementation Plan
```mermaid
flowchart TD
A[Review Current Models] --> B[Create mod.rs and Update models/mod.rs]
B --> C[Standardize Imports and Fix Inconsistencies]
C --> D[Create Resolution Model]
D --> E[Implement Integration with Other Modules]
E --> F[Add Utility Methods]
F --> G[Create README.md and Documentation]
G --> H[Write Tests]
```
### 3.1 Detailed Changes
#### 3.1.1 Module Organization
Create a new `mod.rs` file in the governance directory:
```rust
pub mod company;
pub mod shareholder;
pub mod meeting;
pub mod user;
pub mod vote;
pub mod resolution;
// Re-export all model types for convenience
pub use company::{Company, CompanyStatus, BusinessType};
pub use shareholder::{Shareholder, ShareholderType};
pub use meeting::{Meeting, Attendee, MeetingStatus, AttendeeRole, AttendeeStatus};
pub use user::User;
pub use vote::{Vote, VoteOption, Ballot, VoteStatus};
pub use resolution::{Resolution, ResolutionStatus, Approval};
// Re-export database components from db module
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};
```
Update `src/models/mod.rs` to include the governance module:
```rust
pub mod biz;
pub mod mcc;
pub mod circle;
pub mod governance;
```
#### 3.1.2 Resolution Model (`resolution.rs`)
```rust
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable, SledDB, SledDBError};
use crate::models::governance::{Meeting, Vote};
/// ResolutionStatus represents the status of a resolution
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResolutionStatus {
Draft,
Proposed,
Approved,
Rejected,
Withdrawn,
}
/// Resolution represents a board resolution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Resolution {
pub id: u32,
pub company_id: u32,
pub meeting_id: Option<u32>,
pub vote_id: Option<u32>,
pub title: String,
pub description: String,
pub text: String,
pub status: ResolutionStatus,
pub proposed_by: u32, // User ID
pub proposed_at: DateTime<Utc>,
pub approved_at: Option<DateTime<Utc>>,
pub rejected_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub approvals: Vec<Approval>,
}
/// Approval represents an approval of a resolution by a board member
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Approval {
pub id: u32,
pub resolution_id: u32,
pub user_id: u32,
pub name: String,
pub approved: bool,
pub comments: String,
pub created_at: DateTime<Utc>,
}
impl Resolution {
/// Create a new resolution with default values
pub fn new(
id: u32,
company_id: u32,
title: String,
description: String,
text: String,
proposed_by: u32,
) -> Self {
let now = Utc::now();
Self {
id,
company_id,
meeting_id: None,
vote_id: None,
title,
description,
text,
status: ResolutionStatus::Draft,
proposed_by,
proposed_at: now,
approved_at: None,
rejected_at: None,
created_at: now,
updated_at: now,
approvals: Vec::new(),
}
}
/// Propose the resolution
pub fn propose(&mut self) {
self.status = ResolutionStatus::Proposed;
self.proposed_at = Utc::now();
self.updated_at = Utc::now();
}
/// Approve the resolution
pub fn approve(&mut self) {
self.status = ResolutionStatus::Approved;
self.approved_at = Some(Utc::now());
self.updated_at = Utc::now();
}
/// Reject the resolution
pub fn reject(&mut self) {
self.status = ResolutionStatus::Rejected;
self.rejected_at = Some(Utc::now());
self.updated_at = Utc::now();
}
/// Add an approval to the resolution
pub fn add_approval(&mut self, user_id: u32, name: String, approved: bool, comments: String) -> &Approval {
let id = if self.approvals.is_empty() {
1
} else {
self.approvals.iter().map(|a| a.id).max().unwrap_or(0) + 1
};
let approval = Approval {
id,
resolution_id: self.id,
user_id,
name,
approved,
comments,
created_at: Utc::now(),
};
self.approvals.push(approval);
self.updated_at = Utc::now();
self.approvals.last().unwrap()
}
/// Link this resolution to a meeting
pub fn link_to_meeting(&mut self, meeting_id: u32) {
self.meeting_id = Some(meeting_id);
self.updated_at = Utc::now();
}
/// Link this resolution to a vote
pub fn link_to_vote(&mut self, vote_id: u32) {
self.vote_id = Some(vote_id);
self.updated_at = Utc::now();
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Resolution {}
impl Storable for Approval {}
// Implement SledModel trait
impl SledModel for Resolution {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"resolution"
}
}
```
#### 3.1.3 Enhanced Company Model (`company.rs`)
Add integration with other modules:
```rust
impl Company {
// ... existing methods ...
/// Link this company to a Circle for access control
pub fn link_to_circle(&mut self, circle_id: u32) -> Result<(), SledDBError> {
// Implementation details
self.updated_at = Utc::now();
Ok(())
}
/// Link this company to a Customer in the biz module
pub fn link_to_customer(&mut self, customer_id: u32) -> Result<(), SledDBError> {
// Implementation details
self.updated_at = Utc::now();
Ok(())
}
/// Get all resolutions for this company
pub fn get_resolutions(&self, db: &SledDB<Resolution>) -> Result<Vec<Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let company_resolutions = all_resolutions
.into_iter()
.filter(|resolution| resolution.company_id == self.id)
.collect();
Ok(company_resolutions)
}
}
```
#### 3.1.4 Enhanced Meeting Model (`meeting.rs`)
Add integration with other modules:
```rust
impl Meeting {
// ... existing methods ...
/// Link this meeting to a Calendar Event in the mcc module
pub fn link_to_event(&mut self, event_id: u32) -> Result<(), SledDBError> {
// Implementation details
self.updated_at = Utc::now();
Ok(())
}
/// Get all resolutions discussed in this meeting
pub fn get_resolutions(&self, db: &SledDB<Resolution>) -> Result<Vec<Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let meeting_resolutions = all_resolutions
.into_iter()
.filter(|resolution| resolution.meeting_id == Some(self.id))
.collect();
Ok(meeting_resolutions)
}
}
```
#### 3.1.5 Enhanced Vote Model (`vote.rs`)
Add integration with Resolution model:
```rust
impl Vote {
// ... existing methods ...
/// Get the resolution associated with this vote
pub fn get_resolution(&self, db: &SledDB<Resolution>) -> Result<Option<Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let vote_resolution = all_resolutions
.into_iter()
.find(|resolution| resolution.vote_id == Some(self.id));
Ok(vote_resolution)
}
}
```
#### 3.1.6 Create README.md
Create a README.md file to document the purpose and usage of the governance module.
## 4. Data Model Diagram
```mermaid
classDiagram
class Company {
+u32 id
+String name
+String registration_number
+DateTime incorporation_date
+String fiscal_year_end
+String email
+String phone
+String website
+String address
+BusinessType business_type
+String industry
+String description
+CompanyStatus status
+DateTime created_at
+DateTime updated_at
+add_shareholder()
+link_to_circle()
+link_to_customer()
+get_resolutions()
}
class Shareholder {
+u32 id
+u32 company_id
+u32 user_id
+String name
+f64 shares
+f64 percentage
+ShareholderType type_
+DateTime since
+DateTime created_at
+DateTime updated_at
+update_shares()
}
class Meeting {
+u32 id
+u32 company_id
+String title
+DateTime date
+String location
+String description
+MeetingStatus status
+String minutes
+DateTime created_at
+DateTime updated_at
+Vec~Attendee~ attendees
+add_attendee()
+update_status()
+update_minutes()
+find_attendee_by_user_id()
+confirmed_attendees()
+link_to_event()
+get_resolutions()
}
class User {
+u32 id
+String name
+String email
+String password
+String company
+String role
+DateTime created_at
+DateTime updated_at
}
class Vote {
+u32 id
+u32 company_id
+String title
+String description
+DateTime start_date
+DateTime end_date
+VoteStatus status
+DateTime created_at
+DateTime updated_at
+Vec~VoteOption~ options
+Vec~Ballot~ ballots
+Vec~u32~ private_group
+add_option()
+add_ballot()
+get_resolution()
}
class Resolution {
+u32 id
+u32 company_id
+Option~u32~ meeting_id
+Option~u32~ vote_id
+String title
+String description
+String text
+ResolutionStatus status
+u32 proposed_by
+DateTime proposed_at
+Option~DateTime~ approved_at
+Option~DateTime~ rejected_at
+DateTime created_at
+DateTime updated_at
+Vec~Approval~ approvals
+propose()
+approve()
+reject()
+add_approval()
+link_to_meeting()
+link_to_vote()
}
Company "1" -- "many" Shareholder: has
Company "1" -- "many" Meeting: holds
Company "1" -- "many" Vote: conducts
Company "1" -- "many" Resolution: issues
Meeting "1" -- "many" Attendee: has
Meeting "1" -- "many" Resolution: discusses
Vote "1" -- "many" VoteOption: has
Vote "1" -- "many" Ballot: collects
Vote "1" -- "1" Resolution: decides
Resolution "1" -- "many" Approval: receives
```
## 5. Testing Strategy
1. Unit tests for each model to verify:
- Basic functionality
- Serialization/deserialization
- Utility methods
- Integration with other models
2. Integration tests to verify:
- Database operations with the models
- Relationships between models
- Integration with other modules
## 6. Future Considerations
1. **Committee Model**: Add a Committee model in the future if needed
2. **Compliance Model**: Add compliance-related models in the future if needed
3. **API Integration**: Develop REST API endpoints for the governance module
4. **UI Components**: Create UI components for managing governance entities
5. **Reporting**: Implement reporting functionality for governance metrics

View File

@ -0,0 +1,66 @@
# Governance Module
This directory contains the core data structures used in the Freezone Manager governance module. These models serve as the foundation for corporate governance functionality, providing essential data structures for companies, shareholders, meetings, voting, and more.
## Overview
The governance models implement the Serde traits (Serialize/Deserialize) and database traits (Storable, SledModel), which allows them to be stored and retrieved using the generic SledDB implementation. Each model provides:
- A struct definition with appropriate fields
- Serde serialization through derive macros
- Methods for database integration through the SledModel trait
- Utility methods for common operations
## Core Models
### Company (`company.rs`)
The Company model represents a company registered in the Freezone:
- **Company**: Main struct with fields for company information
- **CompanyStatus**: Enum for possible company statuses (Active, Inactive, Suspended)
- **BusinessType**: Enum for possible business types (Coop, Single, Twin, Starter, Global)
### Shareholder (`shareholder.rs`)
The Shareholder model represents a shareholder of a company:
- **Shareholder**: Main struct with fields for shareholder information
- **ShareholderType**: Enum for possible shareholder types (Individual, Corporate)
### Meeting (`meeting.rs`)
The Meeting model represents a board meeting of a company:
- **Meeting**: Main struct with fields for meeting information
- **Attendee**: Represents an attendee of a meeting
- **MeetingStatus**: Enum for possible meeting statuses (Scheduled, Completed, Cancelled)
- **AttendeeRole**: Enum for possible attendee roles (Coordinator, Member, Secretary, etc.)
- **AttendeeStatus**: Enum for possible attendee statuses (Confirmed, Pending, Declined)
### User (`user.rs`)
The User model represents a user in the Freezone Manager system:
- **User**: Main struct with fields for user information
### Vote (`vote.rs`)
The Vote model represents a voting item in the Freezone:
- **Vote**: Main struct with fields for vote information
- **VoteOption**: Represents an option in a vote
- **Ballot**: Represents a ballot cast by a user
- **VoteStatus**: Enum for possible vote statuses (Open, Closed, Cancelled)
## Usage
These models are used by the governance module to manage corporate governance. They are typically accessed through the database handlers that implement the generic SledDB interface.
## Future Enhancements
See the [GOVERNANCE_ENHANCEMENT_PLAN.md](./GOVERNANCE_ENHANCEMENT_PLAN.md) file for details on planned enhancements to the governance module, including:
1. New models for committees, resolutions, and compliance
2. Enhanced relationships with other modules (biz, mcc, circle)
3. Additional utility methods and functionality

View File

@ -0,0 +1,146 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable, SledDB, SledDBError};
use crate::models::governance::User;
/// CommitteeRole represents the role of a member in a committee
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommitteeRole {
Chair,
ViceChair,
Secretary,
Member,
Advisor,
Observer,
}
/// CommitteeMember represents a member of a committee
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CommitteeMember {
pub id: u32,
pub committee_id: u32,
pub user_id: u32,
pub name: String,
pub role: CommitteeRole,
pub since: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
/// Committee represents a board committee
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Committee {
pub id: u32,
pub company_id: u32,
pub name: String,
pub description: String,
pub purpose: String,
pub circle_id: Option<u32>, // Link to Circle for access control
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub members: Vec<CommitteeMember>,
}
impl Committee {
/// Create a new committee with default values
pub fn new(
id: u32,
company_id: u32,
name: String,
description: String,
purpose: String,
) -> Self {
let now = Utc::now();
Self {
id,
company_id,
name,
description,
purpose,
circle_id: None,
created_at: now,
updated_at: now,
members: Vec::new(),
}
}
/// Add a member to the committee
pub fn add_member(&mut self, user_id: u32, name: String, role: CommitteeRole) -> &CommitteeMember {
let id = if self.members.is_empty() {
1
} else {
self.members.iter().map(|m| m.id).max().unwrap_or(0) + 1
};
let now = Utc::now();
let member = CommitteeMember {
id,
committee_id: self.id,
user_id,
name,
role,
since: now,
created_at: now,
};
self.members.push(member);
self.updated_at = now;
self.members.last().unwrap()
}
/// Find a member by user ID
pub fn find_member_by_user_id(&self, user_id: u32) -> Option<&CommitteeMember> {
self.members.iter().find(|m| m.user_id == user_id)
}
/// Find a member by user ID (mutable version)
pub fn find_member_by_user_id_mut(&mut self, user_id: u32) -> Option<&mut CommitteeMember> {
self.members.iter_mut().find(|m| m.user_id == user_id)
}
/// Remove a member from the committee
pub fn remove_member(&mut self, member_id: u32) -> bool {
let len = self.members.len();
self.members.retain(|m| m.id != member_id);
let removed = self.members.len() < len;
if removed {
self.updated_at = Utc::now();
}
removed
}
/// Link this committee to a Circle for access control
pub fn link_to_circle(&mut self, circle_id: u32) {
self.circle_id = Some(circle_id);
self.updated_at = Utc::now();
}
/// Get all users who are members of this committee
pub fn get_member_users(&self, db: &SledDB<User>) -> Result<Vec<User>, SledDBError> {
let mut users = Vec::new();
for member in &self.members {
if let Ok(user) = db.get(&member.user_id.to_string()) {
users.push(user);
}
}
Ok(users)
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Committee {}
impl Storable for CommitteeMember {}
// Implement SledModel trait
impl SledModel for Committee {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"committee"
}
}

View File

@ -1,4 +1,4 @@
use crate::core::{SledModel, Storable, SledDB, SledDBError};
use crate::db::{SledModel, Storable, SledDB, SledDBError};
use super::shareholder::Shareholder; // Use super:: for sibling module
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
@ -57,7 +57,6 @@ impl SledModel for Company {
}
}
impl Company {
/// Create a new company with default timestamps
pub fn new(
@ -107,6 +106,37 @@ impl Company {
Ok(())
}
// Removed dump and load_from_bytes methods, now provided by Storable trait
/// Link this company to a Circle for access control
pub fn link_to_circle(&mut self, circle_id: u32) -> Result<(), SledDBError> {
// Implementation would involve updating a mapping in a separate database
// For now, we'll just update the timestamp to indicate the change
self.updated_at = Utc::now();
Ok(())
}
/// Link this company to a Customer in the biz module
pub fn link_to_customer(&mut self, customer_id: u32) -> Result<(), SledDBError> {
// Implementation would involve updating a mapping in a separate database
// For now, we'll just update the timestamp to indicate the change
self.updated_at = Utc::now();
Ok(())
}
/// Get all resolutions for this company
pub fn get_resolutions(&self, db: &SledDB<crate::models::governance::Resolution>) -> Result<Vec<crate::models::governance::Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let company_resolutions = all_resolutions
.into_iter()
.filter(|resolution| resolution.company_id == self.id)
.collect();
Ok(company_resolutions)
}
// Future methods:
// /// Get all committees for this company
// pub fn get_committees(&self, db: &SledDB<Committee>) -> Result<Vec<Committee>, SledDBError> { ... }
//
// /// Get all compliance requirements for this company
// pub fn get_compliance_requirements(&self, db: &SledDB<ComplianceRequirement>) -> Result<Vec<ComplianceRequirement>, SledDBError> { ... }
}

View File

@ -0,0 +1,212 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable, SledDB, SledDBError};
use crate::models::governance::Company;
/// ComplianceRequirement represents a regulatory requirement
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ComplianceRequirement {
pub id: u32,
pub company_id: u32,
pub title: String,
pub description: String,
pub regulation: String,
pub authority: String,
pub deadline: DateTime<Utc>,
pub status: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// ComplianceDocument represents a compliance document
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ComplianceDocument {
pub id: u32,
pub requirement_id: u32,
pub title: String,
pub description: String,
pub file_path: String,
pub file_type: String,
pub uploaded_by: u32, // User ID
pub uploaded_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// ComplianceAudit represents a compliance audit
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ComplianceAudit {
pub id: u32,
pub company_id: u32,
pub title: String,
pub description: String,
pub auditor: String,
pub start_date: DateTime<Utc>,
pub end_date: DateTime<Utc>,
pub status: String,
pub findings: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl ComplianceRequirement {
/// Create a new compliance requirement with default values
pub fn new(
id: u32,
company_id: u32,
title: String,
description: String,
regulation: String,
authority: String,
deadline: DateTime<Utc>,
) -> Self {
let now = Utc::now();
Self {
id,
company_id,
title,
description,
regulation,
authority,
deadline,
status: "Pending".to_string(),
created_at: now,
updated_at: now,
}
}
/// Update the status of the requirement
pub fn update_status(&mut self, status: String) {
self.status = status;
self.updated_at = Utc::now();
}
/// Get the company associated with this requirement
pub fn get_company(&self, db: &SledDB<Company>) -> Result<Company, SledDBError> {
db.get(&self.company_id.to_string())
}
/// Get all documents associated with this requirement
pub fn get_documents(&self, db: &SledDB<ComplianceDocument>) -> Result<Vec<ComplianceDocument>, SledDBError> {
let all_documents = db.list()?;
let requirement_documents = all_documents
.into_iter()
.filter(|doc| doc.requirement_id == self.id)
.collect();
Ok(requirement_documents)
}
}
impl ComplianceDocument {
/// Create a new compliance document with default values
pub fn new(
id: u32,
requirement_id: u32,
title: String,
description: String,
file_path: String,
file_type: String,
uploaded_by: u32,
) -> Self {
let now = Utc::now();
Self {
id,
requirement_id,
title,
description,
file_path,
file_type,
uploaded_by,
uploaded_at: now,
created_at: now,
updated_at: now,
}
}
/// Get the requirement associated with this document
pub fn get_requirement(&self, db: &SledDB<ComplianceRequirement>) -> Result<ComplianceRequirement, SledDBError> {
db.get(&self.requirement_id.to_string())
}
}
impl ComplianceAudit {
/// Create a new compliance audit with default values
pub fn new(
id: u32,
company_id: u32,
title: String,
description: String,
auditor: String,
start_date: DateTime<Utc>,
end_date: DateTime<Utc>,
) -> Self {
let now = Utc::now();
Self {
id,
company_id,
title,
description,
auditor,
start_date,
end_date,
status: "Planned".to_string(),
findings: String::new(),
created_at: now,
updated_at: now,
}
}
/// Update the status of the audit
pub fn update_status(&mut self, status: String) {
self.status = status;
self.updated_at = Utc::now();
}
/// Update the findings of the audit
pub fn update_findings(&mut self, findings: String) {
self.findings = findings;
self.updated_at = Utc::now();
}
/// Get the company associated with this audit
pub fn get_company(&self, db: &SledDB<Company>) -> Result<Company, SledDBError> {
db.get(&self.company_id.to_string())
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for ComplianceRequirement {}
impl Storable for ComplianceDocument {}
impl Storable for ComplianceAudit {}
// Implement SledModel trait
impl SledModel for ComplianceRequirement {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"compliance_requirement"
}
}
impl SledModel for ComplianceDocument {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"compliance_document"
}
}
impl SledModel for ComplianceAudit {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"compliance_audit"
}
}

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable}; // Import Sled traits from new location
use crate::db::{SledModel, Storable, SledDB, SledDBError, SledDBResult}; // Import Sled traits from db module
// use std::collections::HashMap; // Removed unused import
// use super::db::Model; // Removed old Model trait import
@ -155,6 +155,24 @@ impl Meeting {
.filter(|a| a.status == AttendeeStatus::Confirmed)
.collect()
}
/// Link this meeting to a Calendar Event in the mcc module
pub fn link_to_event(&mut self, event_id: u32) -> Result<(), SledDBError> {
// Implementation would involve updating a mapping in a separate database
// For now, we'll just update the timestamp to indicate the change
self.updated_at = Utc::now();
Ok(())
}
/// Get all resolutions discussed in this meeting
pub fn get_resolutions(&self, db: &SledDB<crate::models::governance::Resolution>) -> Result<Vec<crate::models::governance::Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let meeting_resolutions = all_resolutions
.into_iter()
.filter(|resolution| resolution.meeting_id == Some(self.id))
.collect();
Ok(meeting_resolutions)
}
}
// Implement Storable trait (provides default dump/load)

View File

@ -0,0 +1,20 @@
pub mod company;
pub mod shareholder;
pub mod meeting;
pub mod user;
pub mod vote;
pub mod resolution;
// Future modules:
// pub mod committee;
// pub mod compliance;
// Re-export all model types for convenience
pub use company::{Company, CompanyStatus, BusinessType};
pub use shareholder::{Shareholder, ShareholderType};
pub use meeting::{Meeting, Attendee, MeetingStatus, AttendeeRole, AttendeeStatus};
pub use user::User;
pub use vote::{Vote, VoteOption, Ballot, VoteStatus};
pub use resolution::{Resolution, ResolutionStatus, Approval};
// Re-export database components from db module
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};

View File

@ -0,0 +1,196 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable, SledDB, SledDBError};
use crate::models::governance::{Meeting, Vote};
/// ResolutionStatus represents the status of a resolution
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResolutionStatus {
Draft,
Proposed,
Approved,
Rejected,
Withdrawn,
}
/// Resolution represents a board resolution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Resolution {
pub id: u32,
pub company_id: u32,
pub meeting_id: Option<u32>,
pub vote_id: Option<u32>,
pub title: String,
pub description: String,
pub text: String,
pub status: ResolutionStatus,
pub proposed_by: u32, // User ID
pub proposed_at: DateTime<Utc>,
pub approved_at: Option<DateTime<Utc>>,
pub rejected_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub approvals: Vec<Approval>,
}
/// Approval represents an approval of a resolution by a board member
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Approval {
pub id: u32,
pub resolution_id: u32,
pub user_id: u32,
pub name: String,
pub approved: bool,
pub comments: String,
pub created_at: DateTime<Utc>,
}
impl Resolution {
/// Create a new resolution with default values
pub fn new(
id: u32,
company_id: u32,
title: String,
description: String,
text: String,
proposed_by: u32,
) -> Self {
let now = Utc::now();
Self {
id,
company_id,
meeting_id: None,
vote_id: None,
title,
description,
text,
status: ResolutionStatus::Draft,
proposed_by,
proposed_at: now,
approved_at: None,
rejected_at: None,
created_at: now,
updated_at: now,
approvals: Vec::new(),
}
}
/// Propose the resolution
pub fn propose(&mut self) {
self.status = ResolutionStatus::Proposed;
self.proposed_at = Utc::now();
self.updated_at = Utc::now();
}
/// Approve the resolution
pub fn approve(&mut self) {
self.status = ResolutionStatus::Approved;
self.approved_at = Some(Utc::now());
self.updated_at = Utc::now();
}
/// Reject the resolution
pub fn reject(&mut self) {
self.status = ResolutionStatus::Rejected;
self.rejected_at = Some(Utc::now());
self.updated_at = Utc::now();
}
/// Withdraw the resolution
pub fn withdraw(&mut self) {
self.status = ResolutionStatus::Withdrawn;
self.updated_at = Utc::now();
}
/// Add an approval to the resolution
pub fn add_approval(&mut self, user_id: u32, name: String, approved: bool, comments: String) -> &Approval {
let id = if self.approvals.is_empty() {
1
} else {
self.approvals.iter().map(|a| a.id).max().unwrap_or(0) + 1
};
let approval = Approval {
id,
resolution_id: self.id,
user_id,
name,
approved,
comments,
created_at: Utc::now(),
};
self.approvals.push(approval);
self.updated_at = Utc::now();
self.approvals.last().unwrap()
}
/// Find an approval by user ID
pub fn find_approval_by_user_id(&self, user_id: u32) -> Option<&Approval> {
self.approvals.iter().find(|a| a.user_id == user_id)
}
/// Get all approvals
pub fn get_approvals(&self) -> &[Approval] {
&self.approvals
}
/// Get approval count
pub fn approval_count(&self) -> usize {
self.approvals.iter().filter(|a| a.approved).count()
}
/// Get rejection count
pub fn rejection_count(&self) -> usize {
self.approvals.iter().filter(|a| !a.approved).count()
}
/// Link this resolution to a meeting
pub fn link_to_meeting(&mut self, meeting_id: u32) {
self.meeting_id = Some(meeting_id);
self.updated_at = Utc::now();
}
/// Link this resolution to a vote
pub fn link_to_vote(&mut self, vote_id: u32) {
self.vote_id = Some(vote_id);
self.updated_at = Utc::now();
}
/// Get the meeting associated with this resolution
pub fn get_meeting(&self, db: &SledDB<Meeting>) -> Result<Option<Meeting>, SledDBError> {
match self.meeting_id {
Some(meeting_id) => {
let meeting = db.get(&meeting_id.to_string())?;
Ok(Some(meeting))
}
None => Ok(None),
}
}
/// Get the vote associated with this resolution
pub fn get_vote(&self, db: &SledDB<Vote>) -> Result<Option<Vote>, SledDBError> {
match self.vote_id {
Some(vote_id) => {
let vote = db.get(&vote_id.to_string())?;
Ok(Some(vote))
}
None => Ok(None),
}
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Resolution {}
impl Storable for Approval {}
// Implement SledModel trait
impl SledModel for Resolution {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"resolution"
}
}

View File

@ -1,4 +1,4 @@
use crate::core::{SledModel, Storable}; // Import Sled traits
use crate::db::{SledModel, Storable}; // Import Sled traits
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
// use std::collections::HashMap; // Removed unused import

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable}; // Import Sled traits
use crate::db::{SledModel, Storable}; // Import Sled traits
// use std::collections::HashMap; // Removed unused import
/// User represents a user in the Freezone Manager system

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable}; // Import Sled traits from new location
use crate::db::{SledModel, Storable, SledDB, SledDBError}; // Import Sled traits from db module
// use std::collections::HashMap; // Removed unused import
// use super::db::Model; // Removed old Model trait import
@ -126,6 +126,16 @@ impl Vote {
self.ballots.push(ballot);
self.ballots.last().unwrap()
}
/// Get the resolution associated with this vote
pub fn get_resolution(&self, db: &SledDB<crate::models::governance::Resolution>) -> Result<Option<crate::models::governance::Resolution>, SledDBError> {
let all_resolutions = db.list()?;
let vote_resolution = all_resolutions
.into_iter()
.find(|resolution| resolution.vote_id == Some(self.id));
Ok(vote_resolution)
}
}
// Implement Storable trait (provides default dump/load)

View File

@ -0,0 +1,316 @@
# MCC Models Enhancement Plan
## 1. Current State Analysis
The current MCC module consists of:
- **Mail**: Email, Attachment, Envelope models
- **Calendar**: Calendar model
- **Event**: Event, EventMeta models
- **Contacts**: Contact model
All models implement the `Storable` and `SledModel` traits for database integration.
## 2. Planned Enhancements
### 2.1 Add Group Support to All Models
Add a `groups: Vec<u32>` field to each model to enable linking to multiple groups defined in the Circle module.
### 2.2 Create New Message Model
Create a new `message.rs` file with a Message model for chat functionality:
- Different structure from Email
- Include thread_id, sender_id, content fields
- Include metadata for chat-specific features
- Implement Storable and SledModel traits
### 2.3 Add Utility Methods
Add utility methods to each model for:
- **Filtering/Searching**: Methods to filter by groups, search by content/subject
- **Format Conversion**: Methods to convert between formats (e.g., Email to Message)
- **Relationship Management**: Methods to manage relationships between models
## 3. Implementation Plan
```mermaid
flowchart TD
A[Review Current Models] --> B[Add groups field to all models]
B --> C[Create Message model]
C --> D[Add utility methods]
D --> E[Update mod.rs and lib.rs]
E --> F[Update README.md]
```
### 3.1 Detailed Changes
#### 3.1.1 Mail Model (`mail.rs`)
- Add `groups: Vec<u32>` field to `Email` struct
- Add utility methods:
- `filter_by_groups(groups: &[u32]) -> bool`
- `search_by_subject(query: &str) -> bool`
- `search_by_content(query: &str) -> bool`
- `to_message(&self) -> Message` (conversion method)
#### 3.1.2 Calendar Model (`calendar.rs`)
- Add `groups: Vec<u32>` field to `Calendar` struct
- Add utility methods:
- `filter_by_groups(groups: &[u32]) -> bool`
- `get_events(&self, db: &SledDB<Event>) -> SledDBResult<Vec<Event>>` (relationship method)
#### 3.1.3 Event Model (`event.rs`)
- Add `groups: Vec<u32>` field to `Event` struct
- Add utility methods:
- `filter_by_groups(groups: &[u32]) -> bool`
- `get_calendar(&self, db: &SledDB<Calendar>) -> SledDBResult<Calendar>` (relationship method)
- `get_attendee_contacts(&self, db: &SledDB<Contact>) -> SledDBResult<Vec<Contact>>` (relationship method)
#### 3.1.4 Contacts Model (`contacts.rs`)
- Add `groups: Vec<u32>` field to `Contact` struct
- Add utility methods:
- `filter_by_groups(groups: &[u32]) -> bool`
- `search_by_name(query: &str) -> bool`
- `search_by_email(query: &str) -> bool`
- `get_events(&self, db: &SledDB<Event>) -> SledDBResult<Vec<Event>>` (relationship method)
#### 3.1.5 New Message Model (`message.rs`)
```rust
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use chrono::{DateTime, Utc};
/// MessageStatus represents the status of a message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MessageStatus {
Sent,
Delivered,
Read,
Failed,
}
/// MessageMeta contains metadata for a chat message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageMeta {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub status: MessageStatus,
pub is_edited: bool,
pub reactions: Vec<String>,
}
/// Message represents a chat message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub id: u32, // Unique identifier
pub thread_id: String, // Thread/conversation identifier
pub sender_id: String, // Sender identifier
pub recipients: Vec<String>, // List of recipient identifiers
pub content: String, // Message content
pub attachments: Vec<String>, // References to attachments
pub groups: Vec<u32>, // Groups this message belongs to
pub meta: MessageMeta, // Message metadata
}
impl Message {
/// Create a new message
pub fn new(id: u32, thread_id: String, sender_id: String, content: String) -> Self {
let now = Utc::now();
Self {
id,
thread_id,
sender_id,
recipients: Vec::new(),
content,
attachments: Vec::new(),
groups: Vec::new(),
meta: MessageMeta {
created_at: now,
updated_at: now,
status: MessageStatus::Sent,
is_edited: false,
reactions: Vec::new(),
},
}
}
/// Add a recipient to this message
pub fn add_recipient(&mut self, recipient: String) {
self.recipients.push(recipient);
}
/// Add an attachment to this message
pub fn add_attachment(&mut self, attachment: String) {
self.attachments.push(attachment);
}
/// Add a group to this message
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Filter by groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Search by content
pub fn search_by_content(&self, query: &str) -> bool {
self.content.to_lowercase().contains(&query.to_lowercase())
}
/// Update message status
pub fn update_status(&mut self, status: MessageStatus) {
self.meta.status = status;
self.meta.updated_at = Utc::now();
}
/// Edit message content
pub fn edit_content(&mut self, new_content: String) {
self.content = new_content;
self.meta.is_edited = true;
self.meta.updated_at = Utc::now();
}
/// Add a reaction to the message
pub fn add_reaction(&mut self, reaction: String) {
self.meta.reactions.push(reaction);
self.meta.updated_at = Utc::now();
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Message {}
// Implement SledModel trait
impl SledModel for Message {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"message"
}
}
```
#### 3.1.6 Update Module Files
Update `mod.rs` and `lib.rs` to include the new Message model.
#### 3.1.7 Update README.md
Update the README.md to include information about the Message model and the new utility methods.
## 4. Data Model Diagram
```mermaid
classDiagram
class Email {
+u32 id
+u32 uid
+u32 seq_num
+String mailbox
+String message
+Vec~Attachment~ attachments
+Vec~String~ flags
+i64 receivetime
+Option~Envelope~ envelope
+Vec~u32~ groups
+filter_by_groups()
+search_by_subject()
+search_by_content()
+to_message()
}
class Calendar {
+u32 id
+String title
+String description
+Vec~u32~ groups
+filter_by_groups()
+get_events()
}
class Event {
+u32 id
+u32 calendar_id
+String title
+String description
+String location
+DateTime start_time
+DateTime end_time
+bool all_day
+String recurrence
+Vec~String~ attendees
+String organizer
+String status
+EventMeta meta
+Vec~u32~ groups
+filter_by_groups()
+get_calendar()
+get_attendee_contacts()
}
class Contact {
+u32 id
+i64 created_at
+i64 modified_at
+String first_name
+String last_name
+String email
+String group
+Vec~u32~ groups
+filter_by_groups()
+search_by_name()
+search_by_email()
+get_events()
}
class Message {
+u32 id
+String thread_id
+String sender_id
+Vec~String~ recipients
+String content
+Vec~String~ attachments
+Vec~u32~ groups
+MessageMeta meta
+filter_by_groups()
+search_by_content()
+update_status()
+edit_content()
+add_reaction()
}
class Circle {
+u32 id
+String name
+String description
+Vec~Member~ members
}
Calendar "1" -- "many" Event: contains
Contact "many" -- "many" Event: attends
Circle "1" -- "many" Email: groups
Circle "1" -- "many" Calendar: groups
Circle "1" -- "many" Event: groups
Circle "1" -- "many" Contact: groups
Circle "1" -- "many" Message: groups
```
## 5. Testing Strategy
1. Unit tests for each model to verify:
- Group field functionality
- New utility methods
- Serialization/deserialization with the new fields
2. Integration tests to verify:
- Database operations with the updated models
- Relationships between models

View File

@ -21,6 +21,14 @@ The Mail models provide email and IMAP functionality:
- **Attachment**: Represents a file attachment with file information
- **Envelope**: Represents an IMAP envelope structure with message headers
### Message (`message.rs`)
The Message models provide chat functionality:
- **Message**: Main struct for chat messages with thread and recipient information
- **MessageMeta**: Contains metadata for message status, editing, and reactions
- **MessageStatus**: Enum representing the status of a message (Sent, Delivered, Read, Failed)
### Calendar (`calendar.rs`)
The Calendar model represents a container for calendar events:
@ -40,6 +48,31 @@ The Contacts model provides contact management:
- **Contact**: Main struct for contact information with personal details and grouping
## Group Support
All models now support linking to multiple groups (Circle IDs):
- Each model has a `groups: Vec<u32>` field to store multiple group IDs
- Utility methods for adding, removing, and filtering by groups
- Groups are defined in the Circle module
## Utility Methods
Each model provides utility methods for:
### Filtering/Searching
- `filter_by_groups(groups: &[u32]) -> bool`: Filter by groups
- `search_by_subject/content/name/email(query: &str) -> bool`: Search by various fields
### Format Conversion
- `to_message()`: Convert Email to Message
### Relationship Management
- `get_events()`: Get events associated with a calendar or contact
- `get_calendar()`: Get the calendar an event belongs to
- `get_attendee_contacts()`: Get contacts for event attendees
- `get_thread_messages()`: Get all messages in the same thread
## Usage
These models are used by the MCC module to manage emails, calendar events, and contacts. They are typically accessed through the database handlers that implement the generic SledDB interface.

View File

@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use crate::db::{SledModel, Storable, SledDB, SledDBResult};
use crate::models::mcc::event::Event;
/// Calendar represents a calendar container for events
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -7,6 +8,7 @@ pub struct Calendar {
pub id: u32, // Unique identifier
pub title: String, // Calendar title
pub description: String, // Calendar details
pub groups: Vec<u32>, // Groups this calendar belongs to (references Circle IDs)
}
impl Calendar {
@ -16,8 +18,37 @@ impl Calendar {
id,
title,
description,
groups: Vec::new(),
}
}
/// Add a group to this calendar
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Remove a group from this calendar
pub fn remove_group(&mut self, group_id: u32) {
self.groups.retain(|&id| id != group_id);
}
/// Filter by groups - returns true if this calendar belongs to any of the specified groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Get all events associated with this calendar
pub fn get_events(&self, db: &SledDB<Event>) -> SledDBResult<Vec<Event>> {
let all_events = db.list()?;
let calendar_events = all_events
.into_iter()
.filter(|event| event.calendar_id == self.id)
.collect();
Ok(calendar_events)
}
}
// Implement Storable trait (provides default dump/load)

View File

@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use chrono::{DateTime, Utc};
use crate::db::{SledModel, Storable, SledDB, SledDBResult};
use crate::models::mcc::event::Event;
use chrono::Utc;
/// Contact represents a contact entry in an address book
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -14,6 +15,7 @@ pub struct Contact {
pub last_name: String,
pub email: String,
pub group: String, // Reference to a dns name, each group has a globally unique dns
pub groups: Vec<u32>, // Groups this contact belongs to (references Circle IDs)
}
impl Contact {
@ -28,9 +30,49 @@ impl Contact {
last_name,
email,
group,
groups: Vec::new(),
}
}
/// Add a group to this contact
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Remove a group from this contact
pub fn remove_group(&mut self, group_id: u32) {
self.groups.retain(|&id| id != group_id);
}
/// Filter by groups - returns true if this contact belongs to any of the specified groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Search by name - returns true if the name contains the query (case-insensitive)
pub fn search_by_name(&self, query: &str) -> bool {
let full_name = self.full_name().to_lowercase();
query.to_lowercase().split_whitespace().all(|word| full_name.contains(word))
}
/// Search by email - returns true if the email contains the query (case-insensitive)
pub fn search_by_email(&self, query: &str) -> bool {
self.email.to_lowercase().contains(&query.to_lowercase())
}
/// Get events where this contact is an attendee
pub fn get_events(&self, db: &SledDB<Event>) -> SledDBResult<Vec<Event>> {
let all_events = db.list()?;
let contact_events = all_events
.into_iter()
.filter(|event| event.attendees.contains(&self.email))
.collect();
Ok(contact_events)
}
/// Update the contact's information
pub fn update(&mut self, first_name: Option<String>, last_name: Option<String>, email: Option<String>, group: Option<String>) {
if let Some(first_name) = first_name {
@ -52,6 +94,12 @@ impl Contact {
self.modified_at = Utc::now().timestamp();
}
/// Update the contact's groups
pub fn update_groups(&mut self, groups: Vec<u32>) {
self.groups = groups;
self.modified_at = Utc::now().timestamp();
}
/// Get the full name of the contact
pub fn full_name(&self) -> String {
format!("{} {}", self.first_name, self.last_name)

View File

@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use crate::db::{SledModel, Storable, SledDB, SledDBResult};
use crate::models::mcc::calendar::Calendar;
use crate::models::mcc::contacts::Contact;
use chrono::{DateTime, Utc};
/// EventMeta contains additional metadata for a calendar event
@ -27,6 +29,7 @@ pub struct Event {
pub organizer: String, // Organizer email
pub status: String, // "CONFIRMED", "CANCELLED", "TENTATIVE"
pub meta: EventMeta, // Additional metadata
pub groups: Vec<u32>, // Groups this event belongs to (references Circle IDs)
}
impl Event {
@ -60,9 +63,43 @@ impl Event {
etag: String::new(),
color: String::new(),
},
groups: Vec::new(),
}
}
/// Add a group to this event
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Remove a group from this event
pub fn remove_group(&mut self, group_id: u32) {
self.groups.retain(|&id| id != group_id);
}
/// Filter by groups - returns true if this event belongs to any of the specified groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Get the calendar this event belongs to
pub fn get_calendar(&self, db: &SledDB<Calendar>) -> SledDBResult<Calendar> {
db.get(&self.calendar_id.to_string())
}
/// Get contacts for all attendees of this event
pub fn get_attendee_contacts(&self, db: &SledDB<Contact>) -> SledDBResult<Vec<Contact>> {
let all_contacts = db.list()?;
let attendee_contacts = all_contacts
.into_iter()
.filter(|contact| self.attendees.contains(&contact.email))
.collect();
Ok(attendee_contacts)
}
/// Add an attendee to this event
pub fn add_attendee(&mut self, attendee: String) {
self.attendees.push(attendee);
@ -77,6 +114,16 @@ impl Event {
pub fn set_status(&mut self, status: &str) {
self.status = status.to_string();
}
/// Search by title - returns true if the title contains the query (case-insensitive)
pub fn search_by_title(&self, query: &str) -> bool {
self.title.to_lowercase().contains(&query.to_lowercase())
}
/// Search by description - returns true if the description contains the query (case-insensitive)
pub fn search_by_description(&self, query: &str) -> bool {
self.description.to_lowercase().contains(&query.to_lowercase())
}
}
// Implement Storable trait (provides default dump/load)

View File

@ -2,12 +2,14 @@ pub mod calendar;
pub mod event;
pub mod mail;
pub mod contacts;
pub mod message;
// Re-export all model types for convenience
pub use calendar::Calendar;
pub use event::{Event, EventMeta};
pub use mail::{Email, Attachment, Envelope};
pub use contacts::Contact;
pub use message::{Message, MessageMeta, MessageStatus};
// Re-export database components from core module
pub use crate::core::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};
// Re-export database components from db module
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};

View File

@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use crate::core::{SledModel, Storable};
use chrono::{DateTime, Utc};
use crate::db::{SledModel, Storable, SledDBResult, SledDB};
use chrono::Utc;
/// Email represents an email message with all its metadata and content
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -17,6 +17,7 @@ pub struct Email {
pub flags: Vec<String>, // IMAP flags like \Seen, \Deleted, etc.
pub receivetime: i64, // Unix timestamp when the email was received
pub envelope: Option<Envelope>, // IMAP envelope information (contains From, To, Subject, etc.)
pub groups: Vec<u32>, // Groups this email belongs to (references Circle IDs)
}
/// Attachment represents an email attachment
@ -56,6 +57,7 @@ impl Email {
flags: Vec::new(),
receivetime: chrono::Utc::now().timestamp(),
envelope: None,
groups: Vec::new(),
}
}
@ -64,10 +66,86 @@ impl Email {
self.attachments.push(attachment);
}
/// Add a group to this email
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Remove a group from this email
pub fn remove_group(&mut self, group_id: u32) {
self.groups.retain(|&id| id != group_id);
}
/// Filter by groups - returns true if this email belongs to any of the specified groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Search by subject - returns true if the subject contains the query (case-insensitive)
pub fn search_by_subject(&self, query: &str) -> bool {
if let Some(env) = &self.envelope {
env.subject.to_lowercase().contains(&query.to_lowercase())
} else {
false
}
}
/// Search by content - returns true if the message content contains the query (case-insensitive)
pub fn search_by_content(&self, query: &str) -> bool {
self.message.to_lowercase().contains(&query.to_lowercase())
}
/// Set the envelope for this email
pub fn set_envelope(&mut self, envelope: Envelope) {
self.envelope = Some(envelope);
}
/// Convert this email to a Message (for chat)
pub fn to_message(&self, id: u32, thread_id: String) -> crate::models::mcc::message::Message {
use crate::models::mcc::message::Message;
let now = Utc::now();
let sender = if let Some(env) = &self.envelope {
if !env.from.is_empty() {
env.from[0].clone()
} else {
"unknown@example.com".to_string()
}
} else {
"unknown@example.com".to_string()
};
let subject = if let Some(env) = &self.envelope {
env.subject.clone()
} else {
"No Subject".to_string()
};
let recipients = if let Some(env) = &self.envelope {
env.to.clone()
} else {
Vec::new()
};
let content = if !subject.is_empty() {
format!("{}\n\n{}", subject, self.message)
} else {
self.message.clone()
};
let mut message = Message::new(id, thread_id, sender, content);
message.recipients = recipients;
message.groups = self.groups.clone();
// Convert attachments to references
for attachment in &self.attachments {
message.add_attachment(attachment.filename.clone());
}
message
}
}
// Implement Storable trait (provides default dump/load)

View File

@ -0,0 +1,134 @@
use serde::{Deserialize, Serialize};
use crate::db::{SledModel, Storable, SledDB, SledDBResult};
use chrono::{DateTime, Utc};
/// MessageStatus represents the status of a message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MessageStatus {
Sent,
Delivered,
Read,
Failed,
}
/// MessageMeta contains metadata for a chat message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageMeta {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub status: MessageStatus,
pub is_edited: bool,
pub reactions: Vec<String>,
}
/// Message represents a chat message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub id: u32, // Unique identifier
pub thread_id: String, // Thread/conversation identifier
pub sender_id: String, // Sender identifier
pub recipients: Vec<String>, // List of recipient identifiers
pub content: String, // Message content
pub attachments: Vec<String>, // References to attachments
pub groups: Vec<u32>, // Groups this message belongs to (references Circle IDs)
pub meta: MessageMeta, // Message metadata
}
impl Message {
/// Create a new message
pub fn new(id: u32, thread_id: String, sender_id: String, content: String) -> Self {
let now = Utc::now();
Self {
id,
thread_id,
sender_id,
recipients: Vec::new(),
content,
attachments: Vec::new(),
groups: Vec::new(),
meta: MessageMeta {
created_at: now,
updated_at: now,
status: MessageStatus::Sent,
is_edited: false,
reactions: Vec::new(),
},
}
}
/// Add a recipient to this message
pub fn add_recipient(&mut self, recipient: String) {
self.recipients.push(recipient);
}
/// Add an attachment to this message
pub fn add_attachment(&mut self, attachment: String) {
self.attachments.push(attachment);
}
/// Add a group to this message
pub fn add_group(&mut self, group_id: u32) {
if !self.groups.contains(&group_id) {
self.groups.push(group_id);
}
}
/// Remove a group from this message
pub fn remove_group(&mut self, group_id: u32) {
self.groups.retain(|&id| id != group_id);
}
/// Filter by groups - returns true if this message belongs to any of the specified groups
pub fn filter_by_groups(&self, groups: &[u32]) -> bool {
groups.iter().any(|g| self.groups.contains(g))
}
/// Search by content - returns true if the content contains the query (case-insensitive)
pub fn search_by_content(&self, query: &str) -> bool {
self.content.to_lowercase().contains(&query.to_lowercase())
}
/// Update message status
pub fn update_status(&mut self, status: MessageStatus) {
self.meta.status = status;
self.meta.updated_at = Utc::now();
}
/// Edit message content
pub fn edit_content(&mut self, new_content: String) {
self.content = new_content;
self.meta.is_edited = true;
self.meta.updated_at = Utc::now();
}
/// Add a reaction to the message
pub fn add_reaction(&mut self, reaction: String) {
self.meta.reactions.push(reaction);
self.meta.updated_at = Utc::now();
}
/// Get all messages in the same thread
pub fn get_thread_messages(&self, db: &SledDB<Message>) -> SledDBResult<Vec<Message>> {
let all_messages = db.list()?;
let thread_messages = all_messages
.into_iter()
.filter(|msg| msg.thread_id == self.thread_id)
.collect();
Ok(thread_messages)
}
}
// Implement Storable trait (provides default dump/load)
impl Storable for Message {}
// Implement SledModel trait
impl SledModel for Message {
fn get_id(&self) -> String {
self.id.to_string()
}
fn db_prefix() -> &'static str {
"message"
}
}

View File

@ -2,12 +2,14 @@ pub mod calendar;
pub mod event;
pub mod mail;
pub mod contacts;
pub mod message;
// Re-export all model types for convenience
pub use calendar::Calendar;
pub use event::{Event, EventMeta};
pub use mail::{Email, Attachment, Envelope};
pub use contacts::Contact;
pub use message::{Message, MessageMeta, MessageStatus};
// Re-export database components from core module
pub use crate::core::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};
// Re-export database components from db module
pub use crate::db::{SledDB, SledDBError, SledDBResult, Storable, SledModel, DB};

View File

@ -1 +1,4 @@
pub mod biz;
pub mod mcc;
pub mod circle;
pub mod governance;

View File

@ -1,4 +0,0 @@
segment_size: 524288
use_compression: false
version: 0.34
v

Binary file not shown.

View File

@ -1,4 +0,0 @@
segment_size: 524288
use_compression: false
version: 0.34
v

Binary file not shown.

View File

@ -1,4 +0,0 @@
segment_size: 524288
use_compression: false
version: 0.34
v

Binary file not shown.