fix merge issues and rhai examples wip
This commit is contained in:
@@ -14,14 +14,13 @@ print(`BusinessType Global: ${BusinessTypeConstants::Global}`);
|
||||
// --- Testing Company Model ---
|
||||
print("\n--- Testing Company Model ---");
|
||||
|
||||
let company1_id = 1001;
|
||||
let company1_uuid = "comp-uuid-alpha-001";
|
||||
let company1_name = "Innovatech Solutions Ltd.";
|
||||
let company1_reg = "REG-ISL-2024";
|
||||
let company1_inc_date = 1672531200; // Jan 1, 2023
|
||||
|
||||
print(`Creating a new company (ID: ${company1_id}, UUID: ${company1_uuid})...`);
|
||||
let company1 = new_company(company1_id, company1_name, company1_reg, company1_inc_date)
|
||||
print(`Creating a new company (UUID: ${company1_uuid})...`);
|
||||
let company1 = new_company(company1_name, company1_reg, company1_inc_date)
|
||||
.email("contact@innovatech.com")
|
||||
.phone("+1-555-0100")
|
||||
.website("https://innovatech.com")
|
||||
@@ -38,26 +37,26 @@ print(`Company 1 Name: ${company1.name}, Status: ${company1.status}`);
|
||||
print(`Company 1 Email: ${company1.email}, Industry: ${company1.industry}`);
|
||||
// Save the company to the database
|
||||
print("\nSaving company1 to database...");
|
||||
set_company(company1);
|
||||
company1 = set_company(company1); // Capture the company with the DB-assigned ID
|
||||
print("Company1 saved.");
|
||||
|
||||
// Retrieve the company
|
||||
print(`\nRetrieving company by ID (${company1_id})...`);
|
||||
let retrieved_company = get_company_by_id(company1_id);
|
||||
print(`\nRetrieving company by ID (${company1.id})...`);
|
||||
let retrieved_company = get_company_by_id(company1.id);
|
||||
print(`Retrieved Company: ${retrieved_company.name}, Status: ${retrieved_company.status}`);
|
||||
print(`Retrieved Company Reg No: ${retrieved_company.registration_number}, Website: ${retrieved_company.website}`);
|
||||
|
||||
// --- Testing Shareholder Model ---
|
||||
print("\n--- Testing Shareholder Model ---");
|
||||
|
||||
let sh1_id = 2001;
|
||||
|
||||
let sh1_user_id = 3001; // Example user ID
|
||||
let sh1_name = "Alice Wonderland";
|
||||
let sh1_since = 1672617600; // Example timestamp (Jan 2, 2023)
|
||||
|
||||
print(`Creating shareholder 1 (ID: ${sh1_id}) for company ${company1_id}...`);
|
||||
let shareholder1 = new_shareholder(sh1_id)
|
||||
.company_id(company1_id)
|
||||
print(`Creating shareholder 1 for company ${company1.id}...`);
|
||||
let shareholder1 = new_shareholder()
|
||||
.company_id(company1.id)
|
||||
.user_id(sh1_user_id)
|
||||
.name(sh1_name)
|
||||
.shares(1000.0)
|
||||
@@ -66,20 +65,20 @@ let shareholder1 = new_shareholder(sh1_id)
|
||||
.since(sh1_since)
|
||||
.set_base_created_at(1672617600);
|
||||
|
||||
set_shareholder(shareholder1);
|
||||
shareholder1 = set_shareholder(shareholder1);
|
||||
print("Shareholder 1 saved.");
|
||||
|
||||
let retrieved_sh1 = get_shareholder_by_id(sh1_id);
|
||||
let retrieved_sh1 = get_shareholder_by_id(shareholder1.id);
|
||||
print(`Retrieved Shareholder 1: ${retrieved_sh1.name}, Type: ${retrieved_sh1.type_}, Shares: ${retrieved_sh1.shares}`);
|
||||
|
||||
let sh2_id = 2002;
|
||||
|
||||
let sh2_entity_id = 4001; // Example corporate entity ID
|
||||
let sh2_name = "Mad Hatter Inc.";
|
||||
let sh2_since = 1672704000; // Example timestamp (Jan 3, 2023)
|
||||
|
||||
print(`\nCreating shareholder 2 (ID: ${sh2_id}) for company ${company1_id}...`);
|
||||
let shareholder2 = new_shareholder(sh2_id)
|
||||
.company_id(company1_id)
|
||||
print(`\nCreating shareholder 2 for company ${company1.id}...`);
|
||||
let shareholder2 = new_shareholder()
|
||||
.company_id(company1.id)
|
||||
.user_id(sh2_entity_id) // Using user_id field for entity_id for simplicity in example
|
||||
.name(sh2_name)
|
||||
.shares(5000.0)
|
||||
@@ -88,10 +87,10 @@ let shareholder2 = new_shareholder(sh2_id)
|
||||
.since(sh2_since)
|
||||
.set_base_created_at(1672704000);
|
||||
|
||||
set_shareholder(shareholder2);
|
||||
shareholder2 = set_shareholder(shareholder2);
|
||||
print("Shareholder 2 saved.");
|
||||
|
||||
let retrieved_sh2 = get_shareholder_by_id(sh2_id);
|
||||
let retrieved_sh2 = get_shareholder_by_id(shareholder2.id);
|
||||
print(`Retrieved Shareholder 2: ${retrieved_sh2.name}, Type: ${retrieved_sh2.type_}, Percentage: ${retrieved_sh2.percentage}`);
|
||||
|
||||
// --- Testing Update for Company (Example - if setters were fully implemented for complex updates) ---
|
||||
@@ -105,7 +104,7 @@ print(`Updated Company - Name: ${updated_company.name}, New Phone: ${updated_com
|
||||
set_company(updated_company);
|
||||
print("Updated Company saved.");
|
||||
|
||||
let final_retrieved_company = get_company_by_id(company1_id);
|
||||
let final_retrieved_company = get_company_by_id(company1.id);
|
||||
print(`Final Retrieved Company - Description: '${final_retrieved_company.description}', Phone: ${final_retrieved_company.phone}`);
|
||||
|
||||
print("\n--- Testing Product Model ---");
|
||||
@@ -127,12 +126,12 @@ let component1 = new_product_component("Super Capacitor")
|
||||
print(`\nCreated Product Component: ${component1.name}, Qty: ${component1.quantity}`);
|
||||
|
||||
// Create Product 1 (a physical product with a component)
|
||||
let product1_id = 3001;
|
||||
|
||||
let product1_name = "Advanced Gadget X";
|
||||
let product1_creation_time = 1672876800; // Example timestamp (Jan 5, 2023)
|
||||
|
||||
print(`\nCreating Product 1 (ID: ${product1_id}): ${product1_name}...`);
|
||||
let product1 = new_product(product1_id)
|
||||
print(`\nCreating Product 1: ${product1_name}...`);
|
||||
let product1 = new_product()
|
||||
.name(product1_name)
|
||||
.description("A revolutionary gadget with cutting-edge features.")
|
||||
.price(299.99)
|
||||
@@ -146,11 +145,11 @@ let product1 = new_product(product1_id)
|
||||
.set_base_created_at(product1_creation_time);
|
||||
|
||||
print("Saving Product 1...");
|
||||
set_product(product1);
|
||||
product1 = set_product(product1);
|
||||
print("Product 1 saved.");
|
||||
|
||||
print(`\nRetrieving Product 1 (ID: ${product1_id})...`);
|
||||
let retrieved_product1 = get_product_by_id(product1_id);
|
||||
print(`\nRetrieving Product 1 (ID: ${product1.id})...`);
|
||||
let retrieved_product1 = get_product_by_id(product1.id);
|
||||
print(`Retrieved Product 1: ${retrieved_product1.name}, Price: ${retrieved_product1.price}, Type: ${retrieved_product1.type_}`);
|
||||
if retrieved_product1.components.len() > 0 {
|
||||
print(`Product 1 Component 1: ${retrieved_product1.components[0].name}, Desc: ${retrieved_product1.components[0].description}`);
|
||||
@@ -159,12 +158,12 @@ if retrieved_product1.components.len() > 0 {
|
||||
}
|
||||
|
||||
// Create Product 2 (a service)
|
||||
let product2_id = 3002;
|
||||
|
||||
let product2_name = "Cloud Backup Service - Pro Plan";
|
||||
let product2_creation_time = 1672963200; // Example timestamp (Jan 6, 2023)
|
||||
|
||||
print(`\nCreating Product 2 (ID: ${product2_id}): ${product2_name}...`);
|
||||
let product2 = new_product(product2_id)
|
||||
print(`\nCreating Product 2: ${product2_name}...`);
|
||||
let product2 = new_product()
|
||||
.name(product2_name)
|
||||
.description("Unlimited cloud backup with 24/7 support.")
|
||||
.price(19.99) // Monthly price
|
||||
@@ -175,11 +174,11 @@ let product2 = new_product(product2_id)
|
||||
.set_base_created_at(product2_creation_time);
|
||||
|
||||
print("Saving Product 2...");
|
||||
set_product(product2);
|
||||
product2 = set_product(product2);
|
||||
print("Product 2 saved.");
|
||||
|
||||
print(`\nRetrieving Product 2 (ID: ${product2_id})...`);
|
||||
let retrieved_product2 = get_product_by_id(product2_id);
|
||||
print(`\nRetrieving Product 2 (ID: ${product2.id})...`);
|
||||
let retrieved_product2 = get_product_by_id(product2.id);
|
||||
print(`Retrieved Product 2: ${retrieved_product2.name}, Category: ${retrieved_product2.category}, Status: ${retrieved_product2.status}`);
|
||||
if retrieved_product2.components.len() > 0 {
|
||||
print(`Product 2 has ${retrieved_product2.components.len()} components.`);
|
||||
@@ -198,7 +197,7 @@ print(`Sale Status Completed: ${SaleStatusConstants::Completed}`);
|
||||
print(`Sale Status Cancelled: ${SaleStatusConstants::Cancelled}`);
|
||||
|
||||
// Create SaleItem 1 (using product1 from above)
|
||||
let sale_item1_product_id = product1_id; // Using product1_id from product example
|
||||
let sale_item1_product_id = product1.id; // Using product1.id after it's set // Using product1_id from product example
|
||||
let sale_item1_name = retrieved_product1.name; // Using name from retrieved product1
|
||||
let sale_item1_qty = 2;
|
||||
let sale_item1_unit_price = retrieved_product1.price;
|
||||
@@ -209,7 +208,7 @@ let sale_item1 = new_sale_item(sale_item1_product_id, sale_item1_name, sale_item
|
||||
print(`SaleItem 1: Product ID ${sale_item1.product_id}, Qty: ${sale_item1.quantity}, Subtotal: ${sale_item1.subtotal}`);
|
||||
|
||||
// Create SaleItem 2 (using product2 from above)
|
||||
let sale_item2_product_id = product2_id; // Using product2_id from product example
|
||||
let sale_item2_product_id = product2.id; // Using product2.id after it's set // Using product2_id from product example
|
||||
let sale_item2_name = retrieved_product2.name;
|
||||
let sale_item2_qty = 1;
|
||||
let sale_item2_unit_price = retrieved_product2.price;
|
||||
@@ -220,14 +219,13 @@ let sale_item2 = new_sale_item(sale_item2_product_id, sale_item2_name, sale_item
|
||||
print(`SaleItem 2: Product ID ${sale_item2.product_id}, Qty: ${sale_item2.quantity}, Subtotal: ${sale_item2.subtotal}`);
|
||||
|
||||
// Create a Sale
|
||||
let sale1_id = 4001;
|
||||
let sale1_customer_id = company1_id; // Example: company1 is the customer
|
||||
|
||||
let sale1_customer_id = company1.id; // Example: company1 is the customer
|
||||
let sale1_date = 1673049600; // Example timestamp (Jan 7, 2023)
|
||||
let sale1_total_amount = sale_item1.subtotal + sale_item2.subtotal;
|
||||
|
||||
print(`\nCreating Sale 1 (ID: ${sale1_id}) for Customer ID: ${sale1_customer_id}...`);
|
||||
print(`\nCreating Sale 1 for Customer ID: ${sale1_customer_id}...`);
|
||||
let sale1 = new_sale(
|
||||
sale1_id,
|
||||
sale1_customer_id, // for company_id_i64 in Rhai registration
|
||||
"Temp Buyer Name", // for buyer_name in Rhai registration
|
||||
"temp@buyer.com", // for buyer_email in Rhai registration
|
||||
@@ -262,12 +260,12 @@ print(`Sale 1 Base Comments: ${sale1.comments}`);
|
||||
|
||||
// Save Sale 1 to database
|
||||
print("\nSaving Sale 1 to database...");
|
||||
set_sale(sale1);
|
||||
sale1 = set_sale(sale1);
|
||||
print("Sale 1 saved.");
|
||||
|
||||
// Retrieve Sale 1 from database
|
||||
print(`\nRetrieving Sale 1 by ID (${sale1_id})...`);
|
||||
let retrieved_sale1 = get_sale_by_id(sale1_id);
|
||||
print(`\nRetrieving Sale 1 by ID (${sale1.id})...`);
|
||||
let retrieved_sale1 = get_sale_by_id(sale1.id);
|
||||
print(`Retrieved Sale 1: ID ${retrieved_sale1.id}, Customer: ${retrieved_sale1.customer_id}, Status: ${retrieved_sale1.status}`);
|
||||
print(`Retrieved Sale 1 Total: ${retrieved_sale1.total_amount}, Notes: '${retrieved_sale1.notes}'`);
|
||||
if retrieved_sale1.items.len() > 0 {
|
||||
|
@@ -2,29 +2,31 @@
|
||||
let db = get_db();
|
||||
|
||||
// Create a new calendar using the constructor and builder methods
|
||||
print("Creating a new calendar with ID 1 via registered constructor...");
|
||||
let calendar = new_calendar(1).
|
||||
print("Creating a new calendar (ID will be DB-assigned) via registered constructor...");
|
||||
let calendar = new_calendar(). // ID removed
|
||||
name("My First Calendar").
|
||||
description("A calendar for testing Rhai integration");
|
||||
|
||||
let event = new_event(1).
|
||||
let event = new_event(). // ID removed
|
||||
title("My First Event").
|
||||
description("An event for testing Rhai integration")
|
||||
.add_attendee(new_attendee(1));
|
||||
.add_attendee(new_attendee(1)); // new_attendee(contact_id), not Attendee ID
|
||||
|
||||
calendar.add_event(1);
|
||||
// Add event's ID to calendar. event.id will be 0 if not saved separately.
|
||||
// Calendar::add_event returns the modified calendar, so we re-assign.
|
||||
calendar = calendar.add_event(event.id);
|
||||
|
||||
print("Type of calendar object: " + type_of(calendar));
|
||||
print("Created calendar: " + calendar.name);
|
||||
|
||||
// Save the calendar to the database
|
||||
set_calendar(db, calendar);
|
||||
// Save the calendar to the database and capture the result with DB-assigned ID
|
||||
let calendar = set_calendar(db, calendar); // Capture result
|
||||
print("Calendar saved to database");
|
||||
|
||||
// Check if calendar exists and retrieve it
|
||||
if calendar_exists(db, 1) {
|
||||
let retrieved_calendar = get_calendar_by_id(db, 1);
|
||||
print("Retrieved calendar: " + retrieved_calendar.name);
|
||||
if calendar_exists(db, calendar.id) { // Use calendar.id from the saved object
|
||||
let retrieved_calendar = get_calendar_by_id(db, calendar.id); // Use calendar.id
|
||||
print("Retrieved calendar ID: " + retrieved_calendar.id + ", Name: " + retrieved_calendar.name);
|
||||
// Access the 'description' field directly.
|
||||
// Note: 'description' is Option<String>. Rhai handles options.
|
||||
// You might want to check for 'is_some()' or 'is_none()' or use 'unwrap_or()' pattern if needed.
|
||||
@@ -35,17 +37,17 @@ if calendar_exists(db, 1) {
|
||||
print("No description available or it's None");
|
||||
}
|
||||
} else {
|
||||
print("Failed to retrieve calendar with ID 1");
|
||||
print("Failed to retrieve calendar with ID " + calendar.id);
|
||||
}
|
||||
|
||||
// Create another calendar
|
||||
print("Creating a new calendar with ID 2 using builder methods...");
|
||||
let calendar2 = new_calendar(2).
|
||||
print("Creating another new calendar (ID will be DB-assigned) using builder methods...");
|
||||
let calendar2 = new_calendar(). // ID removed
|
||||
name("My Second Calendar").
|
||||
description("Another calendar for testing");
|
||||
|
||||
set_calendar(db, calendar2);
|
||||
print("Second calendar saved");
|
||||
let calendar2 = set_calendar(db, calendar2); // Capture result
|
||||
print("Second calendar saved with ID: " + calendar2.id);
|
||||
|
||||
// Get all calendars
|
||||
let all_calendars = get_all_calendars(db);
|
||||
@@ -57,14 +59,14 @@ for cal_item in all_calendars { // Renamed loop variable to avoid conflict if 'c
|
||||
}
|
||||
|
||||
// Delete a calendar
|
||||
delete_calendar_by_id(db, 1);
|
||||
print("Deleted calendar with ID 1");
|
||||
delete_calendar_by_id(db, calendar.id); // Use ID from the first calendar object
|
||||
print("Attempted to delete calendar with ID " + calendar.id);
|
||||
|
||||
// Verify deletion
|
||||
if !calendar_exists(db, 1) {
|
||||
print("Calendar with ID 1 was successfully deleted");
|
||||
if !calendar_exists(db, calendar.id) { // Use ID from the first calendar object
|
||||
print("Calendar with ID " + calendar.id + " was successfully deleted");
|
||||
} else {
|
||||
print("Failed to delete calendar with ID 1");
|
||||
print("Failed to delete calendar with ID " + calendar.id + ", or it was not the one intended.");
|
||||
}
|
||||
|
||||
// Count remaining calendars
|
||||
|
@@ -2,139 +2,141 @@
|
||||
|
||||
print("--- Starting Finance Rhai Script ---");
|
||||
|
||||
// 1. Create an Account
|
||||
let acc1_id = 101;
|
||||
let user1_id = 1;
|
||||
let acc1 = new_account(acc1_id, "User1 Main Account", user1_id, "Primary account for User 1", "LedgerX", "0x123MainSt", "pubkeyUser1");
|
||||
print(`Created account: ${acc1.name} with ID ${acc1.id}`);
|
||||
// 1. Create an Account using the builder pattern
|
||||
let user1_id = 1; // Assuming this user_id is a separate concept, e.g. from an auth system
|
||||
let acc1 = new_account()
|
||||
.set_name("User1 Main Account")
|
||||
.set_user_id(user1_id) // user_id is i64 in Rhai, u32 in Rust. Conversion handled by setter.
|
||||
.set_description("Primary account for User 1")
|
||||
.set_ledger("LedgerX")
|
||||
.set_address("0x123MainSt")
|
||||
.set_pubkey("pubkeyUser1");
|
||||
print(`Created account (pre-save): ${acc1.get_name()} with temp ID ${acc1.get_id()}`);
|
||||
|
||||
// 2. Save Account to Mock DB
|
||||
set_account(acc1);
|
||||
print(`Account ${acc1.id} saved to DB.`);
|
||||
// 2. Save Account to Mock DB and get the version with DB-assigned ID
|
||||
let acc1 = set_account(acc1); // Shadowing acc1 with the returned instance
|
||||
print(`Account ${acc1.get_name()} saved to DB with ID ${acc1.get_id()}.`);
|
||||
|
||||
// 3. Retrieve Account from Mock DB
|
||||
let fetched_acc1 = get_account_by_id(acc1_id);
|
||||
print(`Fetched account from DB: ${fetched_acc1.name}, User ID: ${fetched_acc1.user_id}`);
|
||||
// 3. Retrieve Account from Mock DB (using the new ID)
|
||||
let fetched_acc1 = get_account_by_id(acc1.get_id()); // Use the ID from the saved acc1
|
||||
print(`Fetched account from DB: ${fetched_acc1.get_name()}, User ID: ${fetched_acc1.get_user_id()}`);
|
||||
|
||||
// 4. Create an Asset
|
||||
let asset1_id = 201;
|
||||
let asset1 = new_asset(asset1_id, "HeroCoin", "Utility token for Hero Platform", 1000.0, "0xTokenContract", "Erc20", 18);
|
||||
print(`Created asset: ${asset1.name} (ID: ${asset1.id}), Amount: ${asset1.amount}, Type: ${asset1.asset_type_str}`);
|
||||
// 4. Create an Asset using the builder pattern
|
||||
let asset1 = new_asset()
|
||||
.set_name("HeroCoin")
|
||||
.set_description("Utility token for Hero Platform")
|
||||
.set_amount(1000.0)
|
||||
.set_address("0xTokenContract")
|
||||
.set_asset_type("Erc20") // Setter handles string to enum
|
||||
.set_decimals(18);
|
||||
print(`Created asset (pre-save): ${asset1.get_name()} (temp ID: ${asset1.get_id()}), Amount: ${asset1.get_amount()}, Type: ${asset1.get_asset_type_str()}`);
|
||||
|
||||
// 5. Save Asset to Mock DB
|
||||
set_asset(asset1);
|
||||
print(`Asset ${asset1.id} saved to DB.`);
|
||||
// 5. Save Asset to Mock DB and get the version with DB-assigned ID
|
||||
let asset1 = set_asset(asset1); // Shadowing asset1
|
||||
print(`Asset ${asset1.get_name()} (ID: ${asset1.get_id()}) saved to DB.`);
|
||||
|
||||
// 6. Retrieve Asset from Mock DB
|
||||
let fetched_asset1 = get_asset_by_id(asset1_id);
|
||||
print(`Fetched asset from DB: ${fetched_asset1.name}, Address: ${fetched_asset1.address}`);
|
||||
// 6. Retrieve Asset from Mock DB (using the new ID)
|
||||
let fetched_asset1 = get_asset_by_id(asset1.get_id()); // Use the ID from the saved asset1
|
||||
print(`Fetched asset from DB: ${fetched_asset1.get_name()}, Address: ${fetched_asset1.get_address()}`);
|
||||
|
||||
// 7. Add Asset to Account (using the fetched instances)
|
||||
// Note: Account::add_asset takes Asset by value. We have 'fetched_asset1'.
|
||||
// The 'add_asset' method on the Account object in Rhai should work with the asset object.
|
||||
// First, let's ensure fetched_acc1 is mutable if 'add_asset' modifies it directly.
|
||||
// Or, if add_asset returns a new Account, we'd do: fetched_acc1 = fetched_acc1.add_asset(fetched_asset1);
|
||||
// For now, assuming add_asset modifies in place (Rust methods taking `&mut self` often allow this if the object itself is mutable in Rhai scope)
|
||||
// If Account.add_asset was registered as `fn(&mut Account, Asset)` then:
|
||||
// fetched_acc1.add_asset(fetched_asset1);
|
||||
// Let's assume for now that `add_asset` is available and works. We'll test this.
|
||||
// For the current setup, `Account::add_asset` takes `&mut self`, so the object must be mutable in Rhai.
|
||||
// We might need to re-fetch or re-set the account if we modify it and want the DB to know.
|
||||
// Let's try to add and then re-save the account.
|
||||
// 7. Add Asset to Account
|
||||
// We have 'acc1' and 'asset1' from previous steps, both saved to DB and have their IDs.
|
||||
print(`Attempting to add asset ${asset1.get_id()} to account ${acc1.get_id()}`);
|
||||
|
||||
// For simplicity in this first script, let's focus on marketplace.
|
||||
// Adding asset to account might require more setup in Rhai regarding object mutability
|
||||
// or how the add_asset method is exposed. We can refine this later.
|
||||
print("Skipping adding asset to account directly in this script version for brevity, focusing on listing.");
|
||||
// Fetch the latest version of the account before modifying
|
||||
// let mut acc1_for_update = get_account_by_id(acc1.get_id());
|
||||
// // Fetch the asset to add (or use fetched_asset1 if it's the correct one)
|
||||
// let asset_to_add = get_asset_by_id(asset1.get_id());
|
||||
//
|
||||
// try {
|
||||
// acc1_for_update = acc1_for_update.add_asset(asset_to_add); // add_asset returns the modified account
|
||||
// acc1_for_update = set_account(acc1_for_update); // Save the account with the new asset
|
||||
// print(`Asset '${asset_to_add.get_name()}' added to account '${acc1_for_update.get_name()}'.`);
|
||||
// print(`Account now has ${acc1_for_update.get_assets_cloned().len()} assets.`);
|
||||
// // Verify the asset is there
|
||||
if (acc1_for_update.get_assets_cloned().len() > 0) {
|
||||
let first_asset_in_account = acc1_for_update.get_assets_cloned()[0];
|
||||
print(`First asset in account: ${first_asset_in_account.get_name()} (ID: ${first_asset_in_account.get_id()})`);
|
||||
}
|
||||
} catch (err) {
|
||||
print(`Error adding asset to account: ${err}`);
|
||||
}
|
||||
|
||||
// 8. Create a Listing for the Asset
|
||||
let listing1_id = 301;
|
||||
// 8. Create a Listing for the Asset using the builder pattern
|
||||
let current_timestamp = timestamp(); // Rhai's built-in for current unix timestamp (seconds)
|
||||
let expires_at_ts = current_timestamp + (24 * 60 * 60 * 7); // Expires in 7 days
|
||||
|
||||
let listing1 = new_listing(
|
||||
listing1_id,
|
||||
"Rare HeroCoin Batch",
|
||||
"100 HeroCoins for sale",
|
||||
asset1_id.to_string(), // asset_id as string
|
||||
"Erc20", // asset_type as string
|
||||
user1_id.to_string(), // seller_id as string
|
||||
50.0, // price
|
||||
"USD", // currency
|
||||
"FixedPrice", // listing_type as string
|
||||
expires_at_ts, // expires_at_ts_opt as i64
|
||||
["token", "herocoin", "sale"], // tags as array of strings
|
||||
() // image_url_opt as string or ()
|
||||
);
|
||||
print(`Created listing: ${listing1.title} (ID: ${listing1.id}), Price: ${listing1.price} ${listing1.currency}`);
|
||||
print(`Listing type: ${listing1.listing_type_str}, Status: ${listing1.status_str}`);
|
||||
print(`Listing expires_at_ts_opt: ${listing1.expires_at_ts_opt}`);
|
||||
let listing1 = new_listing()
|
||||
.set_title("Rare HeroCoin Batch")
|
||||
.set_description("100 HeroCoins for sale")
|
||||
.set_asset_id(asset1.get_id().to_string()) // Use ID from the saved asset1
|
||||
.set_asset_type("Erc20") // asset_type as string
|
||||
.set_seller_id(user1_id.to_string()) // seller_id as string (using the predefined user1_id)
|
||||
.set_price(50.0) // price
|
||||
.set_currency("USD") // currency
|
||||
.set_listing_type("FixedPrice") // listing_type as string
|
||||
.set_expires_at_ts_opt(expires_at_ts) // expires_at_ts_opt as i64
|
||||
.set_tags(["token", "herocoin", "sale"]); // tags as array of strings
|
||||
// image_url is None by default from new_listing(), so no need to call set_image_url_opt for None
|
||||
|
||||
// 9. Save Listing to Mock DB
|
||||
set_listing(listing1);
|
||||
print(`Listing ${listing1.id} saved to DB.`);
|
||||
print(`Created listing (pre-save): ${listing1.get_title()} (temp ID: ${listing1.get_id()}), Price: ${listing1.get_price()} ${listing1.get_currency()}`);
|
||||
print(`Listing type: ${listing1.get_listing_type_str()}, Status: ${listing1.get_status_str()}`);
|
||||
print(`Listing expires_at_ts_opt: ${listing1.get_expires_at_ts_opt()}`);
|
||||
|
||||
// 10. Retrieve Listing from Mock DB
|
||||
let fetched_listing1 = get_listing_by_id(listing1_id);
|
||||
print(`Fetched listing from DB: ${fetched_listing1.title}, Seller ID: ${fetched_listing1.seller_id}`);
|
||||
print(`Fetched listing asset_id: ${fetched_listing1.asset_id}, asset_type: ${fetched_listing1.asset_type_str}`);
|
||||
// 9. Save Listing to Mock DB and get the version with DB-assigned ID
|
||||
let listing1 = set_listing(listing1); // Shadowing listing1
|
||||
print(`Listing ${listing1.get_title()} (ID: ${listing1.get_id()}) saved to DB.`);
|
||||
|
||||
// 11. Demonstrate an auction listing (basic structure)
|
||||
let listing2_id = 302;
|
||||
let auction_listing = new_listing(
|
||||
listing2_id,
|
||||
"Vintage Hero Figurine",
|
||||
"Rare collectible, starting bid low!",
|
||||
"asset_nft_123", // Mock asset ID for an NFT
|
||||
"Erc721",
|
||||
user1_id.to_string(),
|
||||
10.0, // Starting price
|
||||
"USD",
|
||||
"Auction",
|
||||
(), // No expiration for this example
|
||||
["collectible", "rare", "auction"],
|
||||
"http://example.com/figurine.png"
|
||||
);
|
||||
set_listing(auction_listing);
|
||||
print(`Created auction listing: ${auction_listing.title} (ID: ${auction_listing.id})`);
|
||||
// 10. Retrieve Listing from Mock DB (using the new ID)
|
||||
let fetched_listing1 = get_listing_by_id(listing1.get_id()); // Use the ID from the saved listing1
|
||||
print(`Fetched listing from DB: ${fetched_listing1.get_title()}, Seller ID: ${fetched_listing1.get_seller_id()}`);
|
||||
print(`Fetched listing asset_id: ${fetched_listing1.get_asset_id()}, asset_type: ${fetched_listing1.get_asset_type_str()}`);
|
||||
|
||||
// 12. Create a Bid for the auction listing
|
||||
let bid1 = new_bid(auction_listing.id.to_string(), 2, 12.0, "USD"); // User 2 bids 12 USD
|
||||
// 11. Demonstrate an auction listing using the builder pattern
|
||||
let auction_listing = new_listing()
|
||||
.set_title("Vintage Hero Figurine")
|
||||
.set_description("Rare collectible, starting bid low!")
|
||||
.set_asset_id("asset_nft_123") // Mock asset ID for an NFT - this asset isn't created/saved in script
|
||||
.set_asset_type("Erc721")
|
||||
.set_seller_id(user1_id.to_string()) // Using the predefined user1_id
|
||||
.set_price(10.0) // Starting price
|
||||
.set_currency("USD")
|
||||
.set_listing_type("Auction")
|
||||
// expires_at_ts_opt is None by default
|
||||
.set_tags(["collectible", "rare", "auction"])
|
||||
.set_image_url_opt("http://example.com/figurine.png");
|
||||
|
||||
// Save Auction Listing to Mock DB and get the version with DB-assigned ID
|
||||
let auction_listing = set_listing(auction_listing); // Shadowing auction_listing
|
||||
print(`Created auction listing: ${auction_listing.get_title()} (ID: ${auction_listing.get_id()})`);
|
||||
|
||||
// 12. Create a Bid for the auction listing (Bid model not using builder pattern in this refactor)
|
||||
let bid1 = new_bid(auction_listing.get_id().to_string(), 2, 12.0, "USD"); // User 2 bids 12 USD
|
||||
print(`Created bid for listing ${bid1.listing_id} by bidder ${bid1.bidder_id} for ${bid1.amount} ${bid1.currency}`);
|
||||
print(`Bid status: ${bid1.status_str}, Created at: ${bid1.created_at_ts}`);
|
||||
|
||||
// Add bid to listing - this requires the listing object to be mutable
|
||||
// and the add_listing_bid function to be correctly registered to modify it.
|
||||
// For now, we'll assume the function works and we'd need to re-set the listing to DB if modified.
|
||||
// To test `add_listing_bid` properly, we would typically do:
|
||||
// let mut mutable_auction_listing = get_listing_by_id(listing2_id);
|
||||
// mutable_auction_listing.add_listing_bid(bid1);
|
||||
// set_listing(mutable_auction_listing);
|
||||
// print(`Bid added to listing ${mutable_auction_listing.id}. New bid count: ${mutable_auction_listing.bids_cloned.len()}`);
|
||||
// For this initial script, we will call the function but acknowledge the db update step for a full flow.
|
||||
|
||||
// Get the listing again to add a bid
|
||||
let auction_listing_for_bid = get_listing_by_id(listing2_id);
|
||||
print(`Listing '${auction_listing_for_bid.title}' fetched for bidding. Current price: ${auction_listing_for_bid.price}, Bids: ${auction_listing_for_bid.bids_cloned.len()}`);
|
||||
// 13. Add bid to listing
|
||||
let mut auction_listing_for_bid = get_listing_by_id(auction_listing.get_id());
|
||||
print(`Listing '${auction_listing_for_bid.get_title()}' fetched for bidding. Current price: ${auction_listing_for_bid.get_price()}, Bids: ${auction_listing_for_bid.get_bids_cloned().len()}`);
|
||||
|
||||
try {
|
||||
auction_listing_for_bid.add_listing_bid(bid1);
|
||||
print(`Bid added to '${auction_listing_for_bid.title}'. New bid count: ${auction_listing_for_bid.bids_cloned.len()}, New price: ${auction_listing_for_bid.price};`);
|
||||
set_listing(auction_listing_for_bid); // Save updated listing to DB
|
||||
let updated_listing_after_bid = auction_listing_for_bid.add_listing_bid(bid1);
|
||||
print(`Bid added to '${updated_listing_after_bid.get_title()}'. New bid count: ${updated_listing_after_bid.get_bids_cloned().len()}, New price: ${updated_listing_after_bid.get_price()};`);
|
||||
set_listing(updated_listing_after_bid); // Save updated listing to DB
|
||||
print("Auction listing with new bid saved to DB;");
|
||||
} catch (err) {
|
||||
print(`Error adding bid: ${err}`);
|
||||
}
|
||||
|
||||
// Try to complete sale for the fixed price listing
|
||||
let listing_to_sell = get_listing_by_id(listing1_id);
|
||||
// 14. Try to complete sale for the fixed price listing
|
||||
let mut listing_to_sell = get_listing_by_id(listing1.get_id());
|
||||
let buyer_user_id = 3;
|
||||
print(`Attempting to complete sale for listing: ${listing_to_sell.title} by buyer ${buyer_user_id}`);
|
||||
print(`Attempting to complete sale for listing: ${listing_to_sell.get_title()} by buyer ${buyer_user_id}`);
|
||||
try {
|
||||
listing_to_sell.complete_listing_sale(buyer_user_id.to_string(), listing_to_sell.price);
|
||||
print(`Sale completed for listing ${listing_to_sell.id}. New status: ${listing_to_sell.status_str}`);
|
||||
print(`Buyer ID: ${listing_to_sell.buyer_id_opt}, Sale Price: ${listing_to_sell.sale_price_opt}`);
|
||||
set_listing(listing_to_sell); // Save updated listing
|
||||
let sold_listing = listing_to_sell.complete_listing_sale(buyer_user_id.to_string(), listing_to_sell.get_price());
|
||||
print(`Sale completed for listing ${sold_listing.get_id()}. New status: ${sold_listing.get_status_str()}`);
|
||||
print(`Buyer ID: ${sold_listing.get_buyer_id_opt()}, Sale Price: ${sold_listing.get_sale_price_opt()}`);
|
||||
set_listing(sold_listing); // Save updated listing
|
||||
} catch (err) {
|
||||
print(`Error completing sale: ${err}`);
|
||||
}
|
||||
|
9
heromodels/examples/project_rhai_wasm/.cargo/config.toml
Normal file
9
heromodels/examples/project_rhai_wasm/.cargo/config.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[build]
|
||||
# Set the default build target for this project
|
||||
target = "wasm32-unknown-unknown"
|
||||
|
||||
# Configuration for the wasm32-unknown-unknown target
|
||||
[target.wasm32-unknown-unknown]
|
||||
# Pass --cfg=wasm_js to rustc when compiling for this target.
|
||||
# This is required by the getrandom crate.
|
||||
rustflags = ["--cfg=wasm_js"] # For getrandom v0.3.x WASM support (required by rhai via ahash)
|
20
heromodels/examples/project_rhai_wasm/Cargo.toml
Normal file
20
heromodels/examples/project_rhai_wasm/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "project_rhai_wasm_example"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
heromodels = { path = "../..", features = ["rhai"] } # Match heromodels main crate
|
||||
wasm-bindgen = "0.2"
|
||||
web-sys = { version = "0.3", features = ["console"] }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
js-sys = "0.3"
|
||||
getrandom = { version = "0.3.3", features = ["js"] } # Align with rhai's dependency
|
||||
|
||||
[profile.release]
|
||||
# Tell `rustc` to optimize for small code size.
|
||||
lto = true
|
||||
opt-level = 's'
|
52
heromodels/examples/project_rhai_wasm/index.html
Normal file
52
heromodels/examples/project_rhai_wasm/index.html
Normal file
@@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>HeroModels Project Rhai WASM Test</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
|
||||
#output { margin-top: 20px; padding: 10px; border: 1px solid #ccc; background-color: #fff; white-space: pre-wrap; }
|
||||
button { padding: 10px 15px; font-size: 16px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 5px; }
|
||||
button:hover { background-color: #0056b3; }
|
||||
h1 { color: #0056b3; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>HeroModels Project Rhai WASM Test</h1>
|
||||
<p>Open your browser's developer console to see detailed logs from the Rhai script.</p>
|
||||
<button id="runScriptButton">Run Rhai Script in WASM</button>
|
||||
|
||||
<script type="module">
|
||||
// Import the WASM module
|
||||
import init, { run_project_script_wasm } from './pkg/project_rhai_wasm_example.js';
|
||||
|
||||
async function main() {
|
||||
// Initialize the WASM module
|
||||
await init();
|
||||
console.log("WASM module initialized.");
|
||||
|
||||
const runButton = document.getElementById('runScriptButton');
|
||||
runButton.onclick = () => {
|
||||
console.log("Button clicked, attempting to run script...");
|
||||
try {
|
||||
run_project_script_wasm();
|
||||
console.log("run_project_script_wasm called.");
|
||||
} catch (e) {
|
||||
console.error("Error calling run_project_script_wasm:", e);
|
||||
}
|
||||
};
|
||||
// Automatically run the script on load if desired
|
||||
// console.log("Attempting to run script on load...");
|
||||
// try {
|
||||
// run_project_script_wasm();
|
||||
// console.log("run_project_script_wasm called on load.");
|
||||
// } catch (e) {
|
||||
// console.error("Error calling run_project_script_wasm on load:", e);
|
||||
// }
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
126
heromodels/examples/project_rhai_wasm/src/lib.rs
Normal file
126
heromodels/examples/project_rhai_wasm/src/lib.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use heromodels::db::{OurDB, Db}; // Import Db trait
|
||||
use heromodels::models::projects::rhai::register_projects_rhai_module;
|
||||
use rhai::{Engine, Scope, Dynamic, EvalAltResult, Position};
|
||||
use std::sync::Arc;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::console;
|
||||
|
||||
// Called once when the WASM module is instantiated.
|
||||
#[wasm_bindgen(start)]
|
||||
pub fn main_wasm() -> Result<(), JsValue> {
|
||||
// For better panic messages in the browser console
|
||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn run_project_script_wasm() -> Result<(), JsValue> {
|
||||
console::log_1(&"Starting Rhai script execution in WASM...".into());
|
||||
|
||||
let script = r#"
|
||||
// Test script for Project Rhai integration
|
||||
|
||||
print("--- Testing Project Rhai Integration (WASM) ---");
|
||||
|
||||
// Create a new project
|
||||
let p1 = new_project()
|
||||
.name("Project Alpha WASM")
|
||||
.description("This is the first test project in WASM.")
|
||||
.owner_id(101)
|
||||
.add_member_id(102)
|
||||
.add_member_id(103)
|
||||
.member_ids([201, 202, 203])
|
||||
.add_tag("important")
|
||||
.add_tag("rhai_test")
|
||||
.add_tag("wasm")
|
||||
.tags(["core", "feature_test", "wasm_run"])
|
||||
.status(Status::InProgress)
|
||||
.priority(Priority::High)
|
||||
.item_type(ItemType::Feature)
|
||||
.add_base_comment(1001);
|
||||
|
||||
print("Created project p1: " + p1);
|
||||
print("p1.name: " + p1.name);
|
||||
print("p1.description: " + p1.description);
|
||||
print("p1.owner_id: " + p1.owner_id);
|
||||
print("p1.member_ids: " + p1.member_ids);
|
||||
print("p1.tags: " + p1.tags);
|
||||
print(`p1.status: ${p1.status.to_string()}`);
|
||||
print(`p1.priority: ${p1.priority.to_string()}`);
|
||||
print(`p1.item_type: ${p1.item_type.to_string()}`);
|
||||
print("p1.id: " + p1.id);
|
||||
print("p1.created_at: " + p1.created_at);
|
||||
print("p1.modified_at: " + p1.modified_at);
|
||||
print("p1.comments: " + p1.comments);
|
||||
|
||||
// Save to DB
|
||||
try {
|
||||
set_project(p1);
|
||||
print("Project p1 saved successfully.");
|
||||
} catch (err) {
|
||||
print("Error saving project p1: " + err);
|
||||
}
|
||||
|
||||
// Retrieve from DB
|
||||
try {
|
||||
let retrieved_p1 = get_project_by_id(1);
|
||||
if retrieved_p1 != () { // Check if Some(project) was returned (None becomes '()')
|
||||
print("Retrieved project by ID 1: " + retrieved_p1);
|
||||
print("Retrieved project name: " + retrieved_p1.name);
|
||||
print("Retrieved project tags: " + retrieved_p1.tags);
|
||||
} else {
|
||||
print("Project with ID 1 not found.");
|
||||
}
|
||||
} catch (err) {
|
||||
print("Error retrieving project by ID 1: " + err);
|
||||
}
|
||||
|
||||
// Test non-existent project
|
||||
try {
|
||||
let non_existent_project = get_project_by_id(999);
|
||||
if non_existent_project != () {
|
||||
print("Error: Found non-existent project 999: " + non_existent_project);
|
||||
} else {
|
||||
print("Correctly did not find project with ID 999.");
|
||||
}
|
||||
} catch (err) {
|
||||
print("Error checking for non-existent project: " + err);
|
||||
}
|
||||
|
||||
print("--- Project Rhai Integration Test Complete (WASM) ---");
|
||||
"#;
|
||||
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Redirect Rhai's print to browser console
|
||||
engine.on_print(|text| {
|
||||
console::log_1(&text.into());
|
||||
});
|
||||
|
||||
// Attempt to initialize OurDB. Sled's behavior in WASM with paths is experimental.
|
||||
// It might work as an in-memory/temporary DB, or it might fail.
|
||||
// Using a specific path and reset=true.
|
||||
let db = match OurDB::new("/project_rhai_wasm_db", true) {
|
||||
Ok(db_instance) => Arc::new(db_instance),
|
||||
Err(e) => {
|
||||
let err_msg = format!("Failed to initialize OurDB for WASM: {}", e);
|
||||
console::error_1(&err_msg.into());
|
||||
return Err(JsValue::from_str(&err_msg));
|
||||
}
|
||||
};
|
||||
|
||||
register_projects_rhai_module(&mut engine, db);
|
||||
|
||||
let mut scope = Scope::new();
|
||||
|
||||
match engine.run_with_scope(&mut scope, script) {
|
||||
Ok(_) => console::log_1(&"Rhai script executed successfully in WASM!".into()),
|
||||
Err(e) => {
|
||||
let err_msg = format!("Rhai script execution failed in WASM: {}\nDetails: {:?}", e, e.to_string());
|
||||
console::error_1(&err_msg.into());
|
||||
return Err(JsValue::from_str(&e.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
Reference in New Issue
Block a user