repo clean up
This commit is contained in:
		@@ -1,229 +0,0 @@
 | 
			
		||||
// Payment Flow Rhai Example
 | 
			
		||||
// This script demonstrates the complete payment flow for company registration
 | 
			
		||||
// using the Rhai scripting interface.
 | 
			
		||||
 | 
			
		||||
print("=== Payment Flow Rhai Example ===");
 | 
			
		||||
print("Demonstrating company registration with payment integration");
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 1: Create Company with Pending Payment Status ---
 | 
			
		||||
print("Step 1: Creating company with pending payment status");
 | 
			
		||||
 | 
			
		||||
let company_name = "InnovateTech Solutions";
 | 
			
		||||
let company_reg = "REG-ITS-2024-001";
 | 
			
		||||
let company_inc_date = 1704067200; // Jan 1, 2024
 | 
			
		||||
 | 
			
		||||
// Create company (status defaults to PendingPayment)
 | 
			
		||||
let company = new_company(company_name, company_reg, company_inc_date)
 | 
			
		||||
    .email("contact@innovatetech.com")
 | 
			
		||||
    .phone("+1-555-0199")
 | 
			
		||||
    .website("https://innovatetech.com")
 | 
			
		||||
    .address("456 Innovation Blvd, Tech Valley, TV 67890")
 | 
			
		||||
    .business_type(BusinessTypeConstants::Starter)
 | 
			
		||||
    .industry("Software Development")
 | 
			
		||||
    .description("Cutting-edge software solutions for modern businesses")
 | 
			
		||||
    .fiscal_year_end("12-31");
 | 
			
		||||
 | 
			
		||||
print(`  Company: ${company.name}`);
 | 
			
		||||
print(`  Status: ${company.status} (default for new companies)`);
 | 
			
		||||
print(`  Registration: ${company.registration_number}`);
 | 
			
		||||
print(`  Email: ${company.email}`);
 | 
			
		||||
 | 
			
		||||
// Save company to database
 | 
			
		||||
company = set_company(company);
 | 
			
		||||
print(`  Saved with ID: ${company.id}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 2: Create Payment Record ---
 | 
			
		||||
print("Step 2: Creating payment record");
 | 
			
		||||
 | 
			
		||||
let payment_intent_id = `pi_rhai_${timestamp()}`;
 | 
			
		||||
let payment_plan = "yearly";
 | 
			
		||||
let setup_fee = 750.0;
 | 
			
		||||
let monthly_fee = 149.0;
 | 
			
		||||
let total_amount = setup_fee + (monthly_fee * 12.0); // Setup + 12 months
 | 
			
		||||
 | 
			
		||||
let payment = new_payment(
 | 
			
		||||
    payment_intent_id,
 | 
			
		||||
    company.id,
 | 
			
		||||
    payment_plan,
 | 
			
		||||
    setup_fee,
 | 
			
		||||
    monthly_fee,
 | 
			
		||||
    total_amount
 | 
			
		||||
);
 | 
			
		||||
 | 
			
		||||
print(`  Payment Intent ID: ${payment.payment_intent_id}`);
 | 
			
		||||
print(`  Company ID: ${payment.company_id}`);
 | 
			
		||||
print(`  Payment Plan: ${payment.payment_plan}`);
 | 
			
		||||
print(`  Setup Fee: $${payment.setup_fee}`);
 | 
			
		||||
print(`  Monthly Fee: $${payment.monthly_fee}`);
 | 
			
		||||
print(`  Total Amount: $${payment.total_amount}`);
 | 
			
		||||
print(`  Status: ${payment.status} (default for new payments)`);
 | 
			
		||||
 | 
			
		||||
// Save payment to database
 | 
			
		||||
payment = set_payment(payment);
 | 
			
		||||
print(`  Saved with ID: ${payment.id}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 3: Process Payment Successfully ---
 | 
			
		||||
print("Step 3: Processing payment...");
 | 
			
		||||
 | 
			
		||||
// Simulate payment processing
 | 
			
		||||
print("  Contacting payment processor...");
 | 
			
		||||
print("  Validating payment details...");
 | 
			
		||||
print("  Processing transaction...");
 | 
			
		||||
 | 
			
		||||
// Complete the payment with Stripe customer ID
 | 
			
		||||
let stripe_customer_id = `cus_rhai_${timestamp()}`;
 | 
			
		||||
payment = payment.complete_payment(stripe_customer_id);
 | 
			
		||||
 | 
			
		||||
print("  Payment completed successfully!");
 | 
			
		||||
print(`  New Status: ${payment.status}`);
 | 
			
		||||
print(`  Stripe Customer ID: ${payment.stripe_customer_id}`);
 | 
			
		||||
 | 
			
		||||
// Save updated payment
 | 
			
		||||
payment = set_payment(payment);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 4: Update Company Status to Active ---
 | 
			
		||||
print("Step 4: Updating company status to Active");
 | 
			
		||||
 | 
			
		||||
company = company.status(CompanyStatusConstants::Active);
 | 
			
		||||
print(`  Company: ${company.name}`);
 | 
			
		||||
print(`  New Status: ${company.status}`);
 | 
			
		||||
 | 
			
		||||
// Save updated company
 | 
			
		||||
company = set_company(company);
 | 
			
		||||
print("  Company status updated successfully!");
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 5: Verify Payment Status ---
 | 
			
		||||
print("Step 5: Payment status verification");
 | 
			
		||||
print(`  Is payment completed? ${payment.is_completed()}`);
 | 
			
		||||
print(`  Is payment pending? ${payment.is_pending()}`);
 | 
			
		||||
print(`  Has payment failed? ${payment.has_failed()}`);
 | 
			
		||||
print(`  Is payment refunded? ${payment.is_refunded()}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 6: Retrieve Data from Database ---
 | 
			
		||||
print("Step 6: Verifying data from database");
 | 
			
		||||
 | 
			
		||||
let retrieved_company = get_company_by_id(company.id);
 | 
			
		||||
print(`  Retrieved Company: ${retrieved_company.name}`);
 | 
			
		||||
print(`  Status: ${retrieved_company.status}`);
 | 
			
		||||
 | 
			
		||||
let retrieved_payment = get_payment_by_id(payment.id);
 | 
			
		||||
print(`  Retrieved Payment: ${retrieved_payment.payment_intent_id}`);
 | 
			
		||||
print(`  Status: ${retrieved_payment.status}`);
 | 
			
		||||
print(`  Total: $${retrieved_payment.total_amount}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 7: Demonstrate Failed Payment Scenario ---
 | 
			
		||||
print("Step 7: Demonstrating failed payment scenario");
 | 
			
		||||
 | 
			
		||||
// Create another company for failed payment demo
 | 
			
		||||
let failed_company = new_company(
 | 
			
		||||
    "FailureDemo Corp",
 | 
			
		||||
    "REG-FDC-2024-002",
 | 
			
		||||
    1704067200
 | 
			
		||||
)
 | 
			
		||||
.email("demo@failurecorp.com")
 | 
			
		||||
.business_type(BusinessTypeConstants::Single)
 | 
			
		||||
.industry("Consulting");
 | 
			
		||||
 | 
			
		||||
failed_company = set_company(failed_company);
 | 
			
		||||
print(`  Created company: ${failed_company.name}`);
 | 
			
		||||
print(`  Status: ${failed_company.status} (pending payment)`);
 | 
			
		||||
 | 
			
		||||
// Create payment that will fail
 | 
			
		||||
let failed_payment_intent = `pi_fail_${timestamp()}`;
 | 
			
		||||
let failed_payment = new_payment(
 | 
			
		||||
    failed_payment_intent,
 | 
			
		||||
    failed_company.id,
 | 
			
		||||
    "monthly",
 | 
			
		||||
    300.0,
 | 
			
		||||
    59.0,
 | 
			
		||||
    359.0
 | 
			
		||||
);
 | 
			
		||||
 | 
			
		||||
failed_payment = set_payment(failed_payment);
 | 
			
		||||
 | 
			
		||||
// Simulate payment failure
 | 
			
		||||
print("  Simulating payment failure...");
 | 
			
		||||
failed_payment = failed_payment.fail_payment();
 | 
			
		||||
failed_payment = set_payment(failed_payment);
 | 
			
		||||
 | 
			
		||||
print(`  Failed Company: ${failed_company.name}`);
 | 
			
		||||
print(`  Company Status: ${failed_company.status} (remains pending)`);
 | 
			
		||||
print(`  Payment Status: ${failed_payment.status}`);
 | 
			
		||||
print(`  Payment failed: ${failed_payment.has_failed()}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Step 8: Demonstrate Payment Refund ---
 | 
			
		||||
print("Step 8: Demonstrating payment refund scenario");
 | 
			
		||||
 | 
			
		||||
// Create a payment to refund
 | 
			
		||||
let refund_company = new_company(
 | 
			
		||||
    "RefundDemo Inc",
 | 
			
		||||
    "REG-RDI-2024-003",
 | 
			
		||||
    1704067200
 | 
			
		||||
)
 | 
			
		||||
.email("refund@demo.com")
 | 
			
		||||
.business_type(BusinessTypeConstants::Twin);
 | 
			
		||||
 | 
			
		||||
refund_company = set_company(refund_company);
 | 
			
		||||
 | 
			
		||||
let refund_payment = new_payment(
 | 
			
		||||
    `pi_refund_${timestamp()}`,
 | 
			
		||||
    refund_company.id,
 | 
			
		||||
    "monthly",
 | 
			
		||||
    200.0,
 | 
			
		||||
    39.0,
 | 
			
		||||
    239.0
 | 
			
		||||
);
 | 
			
		||||
 | 
			
		||||
refund_payment = set_payment(refund_payment);
 | 
			
		||||
 | 
			
		||||
// First complete the payment
 | 
			
		||||
refund_payment = refund_payment.complete_payment(`cus_refund_${timestamp()}`);
 | 
			
		||||
refund_payment = set_payment(refund_payment);
 | 
			
		||||
print(`  Payment completed: ${refund_payment.is_completed()}`);
 | 
			
		||||
 | 
			
		||||
// Then refund it
 | 
			
		||||
refund_payment = refund_payment.refund_payment();
 | 
			
		||||
refund_payment = set_payment(refund_payment);
 | 
			
		||||
 | 
			
		||||
print(`  Payment refunded: ${refund_payment.is_refunded()}`);
 | 
			
		||||
print(`  Refund Status: ${refund_payment.status}`);
 | 
			
		||||
print("");
 | 
			
		||||
 | 
			
		||||
// --- Summary ---
 | 
			
		||||
print("=== Payment Flow Example Complete ===");
 | 
			
		||||
print("Summary of demonstrated features:");
 | 
			
		||||
print("✓ Company creation with PendingPayment status (default)");
 | 
			
		||||
print("✓ Payment record creation and database persistence");
 | 
			
		||||
print("✓ Successful payment processing and status updates");
 | 
			
		||||
print("✓ Company status transition from PendingPayment to Active");
 | 
			
		||||
print("✓ Payment status verification methods");
 | 
			
		||||
print("✓ Database retrieval and verification");
 | 
			
		||||
print("✓ Failed payment scenario handling");
 | 
			
		||||
print("✓ Payment refund processing");
 | 
			
		||||
print("");
 | 
			
		||||
print("Key Payment Statuses:");
 | 
			
		||||
print("- Pending: Initial state for new payments");
 | 
			
		||||
print("- Completed: Payment successfully processed");
 | 
			
		||||
print("- Failed: Payment processing failed");
 | 
			
		||||
print("- Refunded: Previously completed payment was refunded");
 | 
			
		||||
print("");
 | 
			
		||||
print("Key Company Statuses:");
 | 
			
		||||
print("- PendingPayment: Default for new companies (awaiting payment)");
 | 
			
		||||
print("- Active: Payment completed, company is operational");
 | 
			
		||||
print("- Suspended: Company temporarily suspended");
 | 
			
		||||
print("- Inactive: Company deactivated");
 | 
			
		||||
 | 
			
		||||
// Helper function to get current timestamp
 | 
			
		||||
fn timestamp() {
 | 
			
		||||
    // This would normally return current timestamp
 | 
			
		||||
    // For demo purposes, we'll use a static value
 | 
			
		||||
    1704067200
 | 
			
		||||
}
 | 
			
		||||
@@ -1,220 +0,0 @@
 | 
			
		||||
// Payment Flow Rhai Example Runner
 | 
			
		||||
// This example runs the payment_flow.rhai script to demonstrate
 | 
			
		||||
// the payment integration using Rhai scripting.
 | 
			
		||||
 | 
			
		||||
use heromodels::db::hero::OurDB;
 | 
			
		||||
use heromodels::models::biz::register_biz_rhai_module;
 | 
			
		||||
use rhai::Engine;
 | 
			
		||||
use std::sync::Arc;
 | 
			
		||||
 | 
			
		||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
 | 
			
		||||
    println!("=== Payment Flow Rhai Example Runner ===");
 | 
			
		||||
    println!("Running payment flow demonstration using Rhai scripting\n");
 | 
			
		||||
 | 
			
		||||
    // Initialize database
 | 
			
		||||
    let db = Arc::new(
 | 
			
		||||
        OurDB::new("/tmp/payment_flow_rhai_example", true)
 | 
			
		||||
            .map_err(|e| format!("DB Error: {}", e))?,
 | 
			
		||||
    );
 | 
			
		||||
 | 
			
		||||
    // Create and configure Rhai engine
 | 
			
		||||
    let mut engine = Engine::new();
 | 
			
		||||
 | 
			
		||||
    // Register the business models module with the engine
 | 
			
		||||
    register_biz_rhai_module(&mut engine, Arc::clone(&db));
 | 
			
		||||
 | 
			
		||||
    // Add a timestamp function for the Rhai script
 | 
			
		||||
    engine.register_fn("timestamp", || -> i64 { chrono::Utc::now().timestamp() });
 | 
			
		||||
 | 
			
		||||
    // Read and execute the Rhai script
 | 
			
		||||
    let script_path = "examples/biz_rhai/payment_flow.rhai";
 | 
			
		||||
 | 
			
		||||
    match std::fs::read_to_string(script_path) {
 | 
			
		||||
        Ok(script_content) => {
 | 
			
		||||
            println!("Executing Rhai script: {}\n", script_path);
 | 
			
		||||
 | 
			
		||||
            match engine.eval::<()>(&script_content) {
 | 
			
		||||
                Ok(_) => {
 | 
			
		||||
                    println!("\n✅ Rhai script executed successfully!");
 | 
			
		||||
                }
 | 
			
		||||
                Err(e) => {
 | 
			
		||||
                    eprintln!("❌ Error executing Rhai script: {}", e);
 | 
			
		||||
                    return Err(Box::new(e));
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        Err(e) => {
 | 
			
		||||
            eprintln!("❌ Error reading script file {}: {}", script_path, e);
 | 
			
		||||
            println!("Note: Make sure to run this example from the project root directory.");
 | 
			
		||||
            return Err(Box::new(e));
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    println!("\n=== Example Complete ===");
 | 
			
		||||
    println!("The payment flow has been successfully demonstrated using Rhai scripting.");
 | 
			
		||||
    println!("This shows how the payment integration can be used in scripted environments.");
 | 
			
		||||
 | 
			
		||||
    Ok(())
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#[cfg(test)]
 | 
			
		||||
mod tests {
 | 
			
		||||
    use super::*;
 | 
			
		||||
    use heromodels::db::Collection;
 | 
			
		||||
    use heromodels::models::biz::{Company, CompanyStatus, Payment, PaymentStatus};
 | 
			
		||||
 | 
			
		||||
    #[test]
 | 
			
		||||
    fn test_rhai_payment_integration() -> Result<(), Box<dyn std::error::Error>> {
 | 
			
		||||
        // Test that we can create and manipulate payment objects through Rhai
 | 
			
		||||
        let db_config = OurDBConfig {
 | 
			
		||||
            path: "/tmp/test_rhai_payment".to_string(),
 | 
			
		||||
            incremental_mode: true,
 | 
			
		||||
            file_size: None,
 | 
			
		||||
            keysize: None,
 | 
			
		||||
            reset: Some(true),
 | 
			
		||||
        };
 | 
			
		||||
 | 
			
		||||
        let db = Arc::new(OurDB::new(db_config)?);
 | 
			
		||||
        let mut engine = Engine::new();
 | 
			
		||||
        register_biz_rhai_module(&mut engine, Arc::clone(&db));
 | 
			
		||||
 | 
			
		||||
        // Test creating a company through Rhai
 | 
			
		||||
        let company_script = r#"
 | 
			
		||||
            let company = new_company("Test Company", "TEST-001", 1704067200)
 | 
			
		||||
                .email("test@example.com")
 | 
			
		||||
                .status(CompanyStatusConstants::PendingPayment);
 | 
			
		||||
            company = set_company(company);
 | 
			
		||||
            company.id
 | 
			
		||||
        "#;
 | 
			
		||||
 | 
			
		||||
        let company_id: i64 = engine.eval(company_script)?;
 | 
			
		||||
        assert!(company_id > 0);
 | 
			
		||||
 | 
			
		||||
        // Test creating a payment through Rhai
 | 
			
		||||
        let payment_script = format!(
 | 
			
		||||
            r#"
 | 
			
		||||
            let payment = new_payment("pi_test_123", {}, "monthly", 100.0, 50.0, 150.0);
 | 
			
		||||
            payment = set_payment(payment);
 | 
			
		||||
            payment.id
 | 
			
		||||
        "#,
 | 
			
		||||
            company_id
 | 
			
		||||
        );
 | 
			
		||||
 | 
			
		||||
        let payment_id: i64 = engine.eval(&payment_script)?;
 | 
			
		||||
        assert!(payment_id > 0);
 | 
			
		||||
 | 
			
		||||
        // Test completing payment through Rhai
 | 
			
		||||
        let complete_script = format!(
 | 
			
		||||
            r#"
 | 
			
		||||
            let payment = get_payment_by_id({});
 | 
			
		||||
            payment = payment.complete_payment("cus_test_123");
 | 
			
		||||
            payment = set_payment(payment);
 | 
			
		||||
            payment.is_completed()
 | 
			
		||||
        "#,
 | 
			
		||||
            payment_id
 | 
			
		||||
        );
 | 
			
		||||
 | 
			
		||||
        let is_completed: bool = engine.eval(&complete_script)?;
 | 
			
		||||
        assert!(is_completed);
 | 
			
		||||
 | 
			
		||||
        // Verify in database
 | 
			
		||||
        let payment: Payment = db.get_by_id(payment_id as u32)?.unwrap();
 | 
			
		||||
        assert_eq!(payment.status, PaymentStatus::Completed);
 | 
			
		||||
        assert_eq!(payment.stripe_customer_id, Some("cus_test_123".to_string()));
 | 
			
		||||
 | 
			
		||||
        Ok(())
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    #[test]
 | 
			
		||||
    fn test_payment_status_constants() -> Result<(), Box<dyn std::error::Error>> {
 | 
			
		||||
        // Test that payment status constants are available in Rhai
 | 
			
		||||
        let db_config = OurDBConfig {
 | 
			
		||||
            path: "/tmp/test_payment_constants".to_string(),
 | 
			
		||||
            incremental_mode: true,
 | 
			
		||||
            file_size: None,
 | 
			
		||||
            keysize: None,
 | 
			
		||||
            reset: Some(true),
 | 
			
		||||
        };
 | 
			
		||||
 | 
			
		||||
        let db = Arc::new(OurDB::new(db_config)?);
 | 
			
		||||
        let mut engine = Engine::new();
 | 
			
		||||
        register_biz_rhai_module(&mut engine, Arc::clone(&db));
 | 
			
		||||
 | 
			
		||||
        // Test that we can access payment status constants
 | 
			
		||||
        let constants_script = r#"
 | 
			
		||||
            let payment = new_payment("pi_test", 1, "monthly", 100.0, 50.0, 150.0);
 | 
			
		||||
            
 | 
			
		||||
            // Test status transitions
 | 
			
		||||
            payment = payment.status(PaymentStatusConstants::Pending);
 | 
			
		||||
            let is_pending = payment.is_pending();
 | 
			
		||||
            
 | 
			
		||||
            payment = payment.status(PaymentStatusConstants::Completed);
 | 
			
		||||
            let is_completed = payment.is_completed();
 | 
			
		||||
            
 | 
			
		||||
            payment = payment.status(PaymentStatusConstants::Failed);
 | 
			
		||||
            let has_failed = payment.has_failed();
 | 
			
		||||
            
 | 
			
		||||
            payment = payment.status(PaymentStatusConstants::Refunded);
 | 
			
		||||
            let is_refunded = payment.is_refunded();
 | 
			
		||||
            
 | 
			
		||||
            [is_pending, is_completed, has_failed, is_refunded]
 | 
			
		||||
        "#;
 | 
			
		||||
 | 
			
		||||
        let results: Vec<bool> = engine.eval(constants_script)?;
 | 
			
		||||
        assert_eq!(results, vec![true, true, true, true]);
 | 
			
		||||
 | 
			
		||||
        Ok(())
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    #[test]
 | 
			
		||||
    fn test_company_status_integration() -> Result<(), Box<dyn std::error::Error>> {
 | 
			
		||||
        // Test the integration between company and payment status
 | 
			
		||||
        let db_config = OurDBConfig {
 | 
			
		||||
            path: "/tmp/test_status_integration".to_string(),
 | 
			
		||||
            incremental_mode: true,
 | 
			
		||||
            file_size: None,
 | 
			
		||||
            keysize: None,
 | 
			
		||||
            reset: Some(true),
 | 
			
		||||
        };
 | 
			
		||||
 | 
			
		||||
        let db = Arc::new(OurDB::new(db_config)?);
 | 
			
		||||
        let mut engine = Engine::new();
 | 
			
		||||
        register_biz_rhai_module(&mut engine, Arc::clone(&db));
 | 
			
		||||
 | 
			
		||||
        let integration_script = r#"
 | 
			
		||||
            // Create company (defaults to PendingPayment)
 | 
			
		||||
            let company = new_company("Integration Test", "INT-001", 1704067200);
 | 
			
		||||
            company = set_company(company);
 | 
			
		||||
            
 | 
			
		||||
            // Create payment
 | 
			
		||||
            let payment = new_payment("pi_int_test", company.id, "yearly", 500.0, 99.0, 1688.0);
 | 
			
		||||
            payment = set_payment(payment);
 | 
			
		||||
            
 | 
			
		||||
            // Complete payment
 | 
			
		||||
            payment = payment.complete_payment("cus_int_test");
 | 
			
		||||
            payment = set_payment(payment);
 | 
			
		||||
            
 | 
			
		||||
            // Update company to active
 | 
			
		||||
            company = company.status(CompanyStatusConstants::Active);
 | 
			
		||||
            company = set_company(company);
 | 
			
		||||
            
 | 
			
		||||
            [payment.is_completed(), company.status]
 | 
			
		||||
        "#;
 | 
			
		||||
 | 
			
		||||
        let results: Vec<rhai::Dynamic> = engine.eval(integration_script)?;
 | 
			
		||||
 | 
			
		||||
        // Check that payment is completed
 | 
			
		||||
        assert!(results[0].as_bool().unwrap());
 | 
			
		||||
 | 
			
		||||
        // Check that company status is Active (we can't directly compare enum in Rhai result)
 | 
			
		||||
        // So we'll verify by retrieving from database
 | 
			
		||||
        let companies: Vec<Company> = db.get_all()?;
 | 
			
		||||
        let company = companies
 | 
			
		||||
            .into_iter()
 | 
			
		||||
            .find(|c| c.name == "Integration Test")
 | 
			
		||||
            .unwrap();
 | 
			
		||||
        assert_eq!(company.status, CompanyStatus::Active);
 | 
			
		||||
 | 
			
		||||
        Ok(())
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,231 +0,0 @@
 | 
			
		||||
use heromodels::db::postgres::Config;
 | 
			
		||||
use heromodels::db::{Collection, Db};
 | 
			
		||||
use heromodels::models::userexample::user::user_index::{is_active, username};
 | 
			
		||||
use heromodels::models::{Comment, User};
 | 
			
		||||
use heromodels_core::Model;
 | 
			
		||||
 | 
			
		||||
// Helper function to print user details
 | 
			
		||||
fn print_user_details(user: &User) {
 | 
			
		||||
    println!("\n--- User Details ---");
 | 
			
		||||
    println!("ID: {}", user.get_id());
 | 
			
		||||
    println!("Username: {}", user.username);
 | 
			
		||||
    println!("Email: {}", user.email);
 | 
			
		||||
    println!("Full Name: {}", user.full_name);
 | 
			
		||||
    println!("Active: {}", user.is_active);
 | 
			
		||||
    println!("Created At: {}", user.base_data.created_at);
 | 
			
		||||
    println!("Modified At: {}", user.base_data.modified_at);
 | 
			
		||||
    println!("Comments: {:?}", user.base_data.comments);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Helper function to print comment details
 | 
			
		||||
fn print_comment_details(comment: &Comment) {
 | 
			
		||||
    println!("\n--- Comment Details ---");
 | 
			
		||||
    println!("ID: {}", comment.get_id());
 | 
			
		||||
    println!("User ID: {}", comment.user_id);
 | 
			
		||||
    println!("Content: {}", comment.content);
 | 
			
		||||
    println!("Created At: {}", comment.base_data.created_at);
 | 
			
		||||
    println!("Modified At: {}", comment.base_data.modified_at);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn main() {
 | 
			
		||||
    let db = heromodels::db::postgres::Postgres::new(
 | 
			
		||||
        Config::new()
 | 
			
		||||
            .user(Some("postgres".into()))
 | 
			
		||||
            .password(Some("test123".into()))
 | 
			
		||||
            .host(Some("localhost".into()))
 | 
			
		||||
            .port(Some(5432)),
 | 
			
		||||
    )
 | 
			
		||||
    .expect("Can connect to postgress");
 | 
			
		||||
 | 
			
		||||
    println!("Hero Models - Basic Usage Example");
 | 
			
		||||
    println!("================================");
 | 
			
		||||
 | 
			
		||||
    // Create users with auto-generated IDs
 | 
			
		||||
 | 
			
		||||
    // User 1
 | 
			
		||||
    let user1 = User::new()
 | 
			
		||||
        .username("johndoe")
 | 
			
		||||
        .email("john.doe@example.com")
 | 
			
		||||
        .full_name("John Doe")
 | 
			
		||||
        .is_active(false)
 | 
			
		||||
        .build();
 | 
			
		||||
 | 
			
		||||
    // User 2
 | 
			
		||||
    let user2 = User::new()
 | 
			
		||||
        .username("janesmith")
 | 
			
		||||
        .email("jane.smith@example.com")
 | 
			
		||||
        .full_name("Jane Smith")
 | 
			
		||||
        .is_active(true)
 | 
			
		||||
        .build();
 | 
			
		||||
 | 
			
		||||
    // User 3
 | 
			
		||||
    let user3 = User::new()
 | 
			
		||||
        .username("willism")
 | 
			
		||||
        .email("willis.masters@example.com")
 | 
			
		||||
        .full_name("Willis Masters")
 | 
			
		||||
        .is_active(true)
 | 
			
		||||
        .build();
 | 
			
		||||
 | 
			
		||||
    // User 4
 | 
			
		||||
    let user4 = User::new()
 | 
			
		||||
        .username("carrols")
 | 
			
		||||
        .email("carrol.smith@example.com")
 | 
			
		||||
        .full_name("Carrol Smith")
 | 
			
		||||
        .is_active(false)
 | 
			
		||||
        .build();
 | 
			
		||||
 | 
			
		||||
    // Save all users to database and get their assigned IDs and updated models
 | 
			
		||||
    let (user1_id, db_user1) = db
 | 
			
		||||
        .collection()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .set(&user1)
 | 
			
		||||
        .expect("can set user");
 | 
			
		||||
    let (user2_id, db_user2) = db
 | 
			
		||||
        .collection()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .set(&user2)
 | 
			
		||||
        .expect("can set user");
 | 
			
		||||
    let (user3_id, db_user3) = db
 | 
			
		||||
        .collection()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .set(&user3)
 | 
			
		||||
        .expect("can set user");
 | 
			
		||||
    let (user4_id, db_user4) = db
 | 
			
		||||
        .collection()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .set(&user4)
 | 
			
		||||
        .expect("can set user");
 | 
			
		||||
 | 
			
		||||
    println!("User 1 assigned ID: {user1_id}");
 | 
			
		||||
    println!("User 2 assigned ID: {user2_id}");
 | 
			
		||||
    println!("User 3 assigned ID: {user3_id}");
 | 
			
		||||
    println!("User 4 assigned ID: {user4_id}");
 | 
			
		||||
 | 
			
		||||
    // We already have the updated models from the set method, so we don't need to retrieve them again
 | 
			
		||||
 | 
			
		||||
    // Print all users retrieved from database
 | 
			
		||||
    println!("\n--- Users Retrieved from Database ---");
 | 
			
		||||
    println!("\n1. First user:");
 | 
			
		||||
    print_user_details(&db_user1);
 | 
			
		||||
 | 
			
		||||
    println!("\n2. Second user:");
 | 
			
		||||
    print_user_details(&db_user2);
 | 
			
		||||
 | 
			
		||||
    println!("\n3. Third user:");
 | 
			
		||||
    print_user_details(&db_user3);
 | 
			
		||||
 | 
			
		||||
    println!("\n4. Fourth user:");
 | 
			
		||||
    print_user_details(&db_user4);
 | 
			
		||||
 | 
			
		||||
    // Demonstrate different ways to retrieve users from the database
 | 
			
		||||
 | 
			
		||||
    // 1. Retrieve by username index
 | 
			
		||||
    println!("\n--- Retrieving Users by Different Methods ---");
 | 
			
		||||
    println!("\n1. By Username Index:");
 | 
			
		||||
    let stored_users = db
 | 
			
		||||
        .collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .get::<username, _>("johndoe")
 | 
			
		||||
        .expect("can load stored user");
 | 
			
		||||
 | 
			
		||||
    assert_eq!(stored_users.len(), 1);
 | 
			
		||||
    print_user_details(&stored_users[0]);
 | 
			
		||||
 | 
			
		||||
    // 2. Retrieve by active status
 | 
			
		||||
    println!("\n2. By Active Status (Active = true):");
 | 
			
		||||
    let active_users = db
 | 
			
		||||
        .collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .get::<is_active, _>(&true)
 | 
			
		||||
        .expect("can load stored users");
 | 
			
		||||
 | 
			
		||||
    assert_eq!(active_users.len(), 2);
 | 
			
		||||
    for active_user in active_users.iter() {
 | 
			
		||||
        print_user_details(active_user);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // 3. Delete a user and show the updated results
 | 
			
		||||
    println!("\n3. After Deleting a User:");
 | 
			
		||||
    let user_to_delete_id = active_users[0].get_id();
 | 
			
		||||
    println!("Deleting user with ID: {user_to_delete_id}");
 | 
			
		||||
    db.collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .delete_by_id(user_to_delete_id)
 | 
			
		||||
        .expect("can delete existing user");
 | 
			
		||||
 | 
			
		||||
    // Show remaining active users
 | 
			
		||||
    let active_users = db
 | 
			
		||||
        .collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .get::<is_active, _>(&true)
 | 
			
		||||
        .expect("can load stored users");
 | 
			
		||||
 | 
			
		||||
    println!("   a. Remaining Active Users:");
 | 
			
		||||
    assert_eq!(active_users.len(), 1);
 | 
			
		||||
    for active_user in active_users.iter() {
 | 
			
		||||
        print_user_details(active_user);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Show inactive users
 | 
			
		||||
    let inactive_users = db
 | 
			
		||||
        .collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .get::<is_active, _>(&false)
 | 
			
		||||
        .expect("can load stored users");
 | 
			
		||||
 | 
			
		||||
    println!("   b. Inactive Users:");
 | 
			
		||||
    assert_eq!(inactive_users.len(), 2);
 | 
			
		||||
    for inactive_user in inactive_users.iter() {
 | 
			
		||||
        print_user_details(inactive_user);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Delete a user based on an index for good measure
 | 
			
		||||
    db.collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .delete::<username, _>("janesmith")
 | 
			
		||||
        .expect("can delete existing user");
 | 
			
		||||
 | 
			
		||||
    println!("\n--- User Model Information ---");
 | 
			
		||||
    println!("User DB Prefix: {}", User::db_prefix());
 | 
			
		||||
 | 
			
		||||
    // Demonstrate comment creation and association with a user
 | 
			
		||||
    println!("\n--- Working with Comments ---");
 | 
			
		||||
 | 
			
		||||
    // 1. Create and save a comment
 | 
			
		||||
    println!("\n1. Creating a Comment:");
 | 
			
		||||
    let comment = Comment::new()
 | 
			
		||||
        .user_id(db_user1.get_id()) // commenter's user ID
 | 
			
		||||
        .content("This is a comment on the user")
 | 
			
		||||
        .build();
 | 
			
		||||
 | 
			
		||||
    // Save the comment and get its assigned ID and updated model
 | 
			
		||||
    let (comment_id, db_comment) = db
 | 
			
		||||
        .collection()
 | 
			
		||||
        .expect("can open comment collection")
 | 
			
		||||
        .set(&comment)
 | 
			
		||||
        .expect("can set comment");
 | 
			
		||||
 | 
			
		||||
    println!("Comment assigned ID: {comment_id}");
 | 
			
		||||
 | 
			
		||||
    println!("   a. Comment Retrieved from Database:");
 | 
			
		||||
    print_comment_details(&db_comment);
 | 
			
		||||
 | 
			
		||||
    // 3. Associate the comment with a user
 | 
			
		||||
    println!("\n2. Associating Comment with User:");
 | 
			
		||||
    let mut updated_user = db_user1.clone();
 | 
			
		||||
    updated_user.base_data.add_comment(db_comment.get_id());
 | 
			
		||||
 | 
			
		||||
    // Save the updated user and get the new version
 | 
			
		||||
    let (_, user_with_comment) = db
 | 
			
		||||
        .collection::<User>()
 | 
			
		||||
        .expect("can open user collection")
 | 
			
		||||
        .set(&updated_user)
 | 
			
		||||
        .expect("can set updated user");
 | 
			
		||||
 | 
			
		||||
    println!("   a. User with Associated Comment:");
 | 
			
		||||
    print_user_details(&user_with_comment);
 | 
			
		||||
 | 
			
		||||
    println!("\n--- Model Information ---");
 | 
			
		||||
    println!("User DB Prefix: {}", User::db_prefix());
 | 
			
		||||
    println!("Comment DB Prefix: {}", Comment::db_prefix());
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user