fix merge issues and rhai examples wip
This commit is contained in:
@@ -97,8 +97,13 @@ impl<E: std::fmt::Debug + std::fmt::Display> std::fmt::Display for Error<E> {
|
||||
Error::DB(e) => write!(f, "Database error: {}", e),
|
||||
Error::Decode(e) => write!(f, "Failed to decode model: {}", e),
|
||||
Error::Encode(e) => write!(f, "Failed to encode model: {}", e),
|
||||
Error::InvalidId(s) => write!(f, "Invalid ID: {}", s),
|
||||
Error::IdMismatch(s) => write!(f, "ID Mismatch: {}", s),
|
||||
Error::IdCollision(s) => write!(f, "ID Collision: {}", s),
|
||||
Error::TypeError => write!(f, "Type error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A transaction that can be committed or rolled back
|
||||
pub trait Transaction {
|
||||
/// Error type for transaction operations
|
||||
|
@@ -99,9 +99,9 @@ impl Index for CompanyRegistrationNumberIndex {
|
||||
// --- Builder Pattern ---
|
||||
|
||||
impl Company {
|
||||
pub fn new(id: u32, name: String, registration_number: String, incorporation_date: i64) -> Self { // incorporation_date to i64
|
||||
pub fn new(name: String, registration_number: String, incorporation_date: i64) -> Self { // incorporation_date to i64
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
name,
|
||||
registration_number,
|
||||
incorporation_date, // This is i64 now
|
||||
|
@@ -84,9 +84,9 @@ impl Model for Product {
|
||||
}
|
||||
|
||||
impl Product {
|
||||
pub fn new(id: u32) -> Self {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
price: 0.0,
|
||||
|
@@ -43,7 +43,7 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
engine.register_type_with_name::<Company>("Company");
|
||||
|
||||
// Constructor
|
||||
engine.register_fn("new_company", |id: i64, name: String, registration_number: String, incorporation_date: i64| -> Result<Company, Box<EvalAltResult>> { Ok(Company::new(id as u32, name, registration_number, incorporation_date)) });
|
||||
engine.register_fn("new_company", |name: String, registration_number: String, incorporation_date: i64| -> Result<Company, Box<EvalAltResult>> { Ok(Company::new(name, registration_number, incorporation_date)) });
|
||||
|
||||
// Getters for Company
|
||||
engine.register_get("id", |company: &mut Company| -> Result<i64, Box<EvalAltResult>> { Ok(company.get_id() as i64) });
|
||||
@@ -85,9 +85,7 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
engine.register_type_with_name::<Shareholder>("Shareholder");
|
||||
|
||||
// Constructor for Shareholder (minimal, takes only ID)
|
||||
engine.register_fn("new_shareholder", |id: i64| -> Result<Shareholder, Box<EvalAltResult>> {
|
||||
Ok(Shareholder::new(id as u32))
|
||||
});
|
||||
engine.register_fn("new_shareholder", || -> Result<Shareholder, Box<EvalAltResult>> { Ok(Shareholder::new()) });
|
||||
|
||||
// Getters for Shareholder
|
||||
engine.register_get("id", |shareholder: &mut Shareholder| -> Result<i64, Box<EvalAltResult>> { Ok(shareholder.get_id() as i64) });
|
||||
@@ -147,7 +145,7 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
// --- Product ---
|
||||
engine.register_type_with_name::<Product>("Product")
|
||||
.register_fn("new_product", |id: i64| -> Result<Product, Box<EvalAltResult>> { Ok(Product::new(id as u32)) })
|
||||
.register_fn("new_product", || -> Result<Product, Box<EvalAltResult>> { Ok(Product::new()) })
|
||||
// Getters for Product
|
||||
.register_get("id", |p: &mut Product| -> Result<i64, Box<EvalAltResult>> { Ok(p.base_data.id as i64) })
|
||||
.register_get("name", |p: &mut Product| -> Result<String, Box<EvalAltResult>> { Ok(p.name.clone()) })
|
||||
@@ -212,9 +210,7 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
// --- Sale ---
|
||||
engine.register_type_with_name::<Sale>("Sale");
|
||||
engine.register_fn("new_sale", |id_i64: i64, company_id_i64: i64, buyer_name: String, buyer_email: String, total_amount: f64, status: SaleStatus, sale_date: i64| -> Result<Sale, Box<EvalAltResult>> {
|
||||
Ok(Sale::new(id_from_i64(id_i64)?, id_from_i64(company_id_i64)?, buyer_name, buyer_email, total_amount, status, sale_date))
|
||||
});
|
||||
engine.register_fn("new_sale", |company_id_i64: i64, buyer_name: String, buyer_email: String, total_amount: f64, status: SaleStatus, sale_date: i64| -> Result<Sale, Box<EvalAltResult>> { Ok(Sale::new(id_from_i64(company_id_i64)?, buyer_name, buyer_email, total_amount, status, sale_date)) });
|
||||
|
||||
// Getters for Sale
|
||||
engine.register_get("id", |s: &mut Sale| -> Result<i64, Box<EvalAltResult>> { Ok(s.get_id() as i64) });
|
||||
@@ -257,11 +253,14 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
});
|
||||
|
||||
// DB functions for Product
|
||||
let captured_db_for_set_prod = Arc::clone(&db);
|
||||
engine.register_fn("set_product", move |product: Product| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set_prod.set(&product).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Product (ID: {}): {}", product.get_id(), e).into(), Position::NONE))
|
||||
})
|
||||
let captured_db_for_set_product = Arc::clone(&db);
|
||||
engine.register_fn("set_product", move |product: Product| -> Result<Product, Box<EvalAltResult>> {
|
||||
let original_id_for_error = product.get_id();
|
||||
captured_db_for_set_product.set(&product)
|
||||
.map(|(_id, updated_product)| updated_product)
|
||||
.map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Product (Original ID: {}): {}", original_id_for_error, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
|
||||
let captured_db_for_get_prod = Arc::clone(&db);
|
||||
@@ -274,10 +273,13 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
// DB functions for Sale
|
||||
let captured_db_for_set_sale = Arc::clone(&db);
|
||||
engine.register_fn("set_sale", move |sale: Sale| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set_sale.set(&sale).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Sale (ID: {}): {}", sale.get_id(), e).into(), Position::NONE))
|
||||
})
|
||||
engine.register_fn("set_sale", move |sale: Sale| -> Result<Sale, Box<EvalAltResult>> {
|
||||
let original_id_for_error = sale.get_id();
|
||||
captured_db_for_set_sale.set(&sale)
|
||||
.map(|(_id, updated_sale)| updated_sale)
|
||||
.map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Sale (Original ID: {}): {}", original_id_for_error, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
|
||||
let captured_db_for_get_sale = Arc::clone(&db);
|
||||
@@ -289,11 +291,14 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
});
|
||||
|
||||
// Mock DB functions for Shareholder
|
||||
let captured_db_for_set_sh = Arc::clone(&db);
|
||||
engine.register_fn("set_shareholder", move |shareholder: Shareholder| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set_sh.set(&shareholder).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Shareholder (ID: {}): {}", shareholder.get_id(), e).into(), Position::NONE))
|
||||
})
|
||||
let captured_db_for_set_shareholder = Arc::clone(&db);
|
||||
engine.register_fn("set_shareholder", move |shareholder: Shareholder| -> Result<Shareholder, Box<EvalAltResult>> {
|
||||
let original_id_for_error = shareholder.get_id();
|
||||
captured_db_for_set_shareholder.set(&shareholder)
|
||||
.map(|(_id, updated_shareholder)| updated_shareholder)
|
||||
.map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Shareholder (Original ID: {}): {}", original_id_for_error, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
|
||||
let captured_db_for_get_sh = Arc::clone(&db);
|
||||
@@ -305,11 +310,14 @@ pub fn register_biz_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
});
|
||||
|
||||
// Mock DB functions for Company
|
||||
let captured_db_for_set = Arc::clone(&db);
|
||||
engine.register_fn("set_company", move |company: Company| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set.set(&company).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Company (ID: {}): {}", company.get_id(), e).into(), Position::NONE))
|
||||
})
|
||||
let captured_db_for_set_company = Arc::clone(&db);
|
||||
engine.register_fn("set_company", move |company: Company| -> Result<Company, Box<EvalAltResult>> {
|
||||
let original_id_for_error = company.get_id(); // Capture ID before it's potentially changed by DB
|
||||
captured_db_for_set_company.set(&company)
|
||||
.map(|(_id, updated_company)| updated_company) // Use the model returned by db.set()
|
||||
.map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Company (Original ID: {}): {}", original_id_for_error, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
|
||||
let captured_db_for_get = Arc::clone(&db);
|
||||
|
@@ -102,7 +102,6 @@ impl Model for Sale {
|
||||
impl Sale {
|
||||
/// Creates a new `Sale`.
|
||||
pub fn new(
|
||||
id: u32,
|
||||
company_id: u32,
|
||||
buyer_name: String,
|
||||
buyer_email: String,
|
||||
@@ -111,7 +110,7 @@ impl Sale {
|
||||
sale_date: i64,
|
||||
) -> Self {
|
||||
Sale {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
company_id,
|
||||
buyer_name,
|
||||
buyer_email,
|
||||
|
@@ -26,9 +26,9 @@ pub struct Shareholder {
|
||||
}
|
||||
|
||||
impl Shareholder {
|
||||
pub fn new(id: u32) -> Self {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
company_id: 0, // Default, to be set by builder
|
||||
user_id: 0, // Default, to be set by builder
|
||||
name: String::new(), // Default
|
||||
|
@@ -60,17 +60,13 @@ pub struct Event {
|
||||
|
||||
impl Event {
|
||||
/// Creates a new event
|
||||
pub fn new(
|
||||
id: i64,
|
||||
title: impl ToString,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> Self {
|
||||
base_data: BaseModelData::new(id as u32),
|
||||
title: String::new(),
|
||||
pub fn new(title: impl ToString, start_time: DateTime<Utc>, end_time: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(),
|
||||
title: title.to_string(),
|
||||
description: None,
|
||||
start_time: Utc::now(),
|
||||
end_time: Utc::now(),
|
||||
start_time,
|
||||
end_time,
|
||||
attendees: Vec::new(),
|
||||
location: None,
|
||||
}
|
||||
|
@@ -1,25 +1,50 @@
|
||||
use rhai::{Engine, EvalAltResult, NativeCallContext};
|
||||
use rhai::{Engine, EvalAltResult, NativeCallContext, ImmutableString};
|
||||
use std::sync::Arc;
|
||||
|
||||
use heromodels_core::BaseModelData;
|
||||
use crate::db::hero::OurDB;
|
||||
use super::calendar::{Calendar, Event, Attendee, AttendanceStatus};
|
||||
use adapter_macros::{adapt_rhai_i64_input_fn, adapt_rhai_i64_input_method};
|
||||
use rhai_wrapper::wrap_vec_return;
|
||||
use adapter_macros::rhai_timestamp_helpers;
|
||||
|
||||
// Helper function for get_all_calendars registration
|
||||
fn get_all_calendars_helper(_db: Arc<OurDB>) -> Vec<Calendar> {
|
||||
// In a real implementation, this would retrieve all calendars from the database
|
||||
vec![Calendar::new(1 as u32), Calendar::new(2 as u32)]
|
||||
|
||||
|
||||
fn new_calendar_rhai(name: String) -> Result<Calendar, Box<EvalAltResult>> {
|
||||
Ok(Calendar::new(None, name))
|
||||
}
|
||||
|
||||
fn new_event_rhai(
|
||||
context: NativeCallContext,
|
||||
title_rhai: ImmutableString,
|
||||
start_time_ts: i64,
|
||||
end_time_ts: i64,
|
||||
) -> Result<Event, Box<EvalAltResult>> {
|
||||
let start_time = rhai_timestamp_helpers::rhai_timestamp_to_datetime(start_time_ts)
|
||||
.map_err(|e_str| Box::new(EvalAltResult::ErrorRuntime(
|
||||
format!("Failed to convert start_time for Event: {}", e_str).into(),
|
||||
context.position(),
|
||||
)))?;
|
||||
|
||||
let end_time = rhai_timestamp_helpers::rhai_timestamp_to_datetime(end_time_ts)
|
||||
.map_err(|e_str| Box::new(EvalAltResult::ErrorRuntime(
|
||||
format!("Failed to convert end_time for Event: {}", e_str).into(),
|
||||
context.position(),
|
||||
)))?;
|
||||
|
||||
Ok(Event::new(title_rhai.to_string(), start_time, end_time))
|
||||
}
|
||||
|
||||
pub fn register_rhai_engine_functions(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
engine.register_fn("new_calendar", adapt_rhai_i64_input_fn!(Calendar::new, u32));
|
||||
engine.register_fn("name", move |calendar: Calendar, name: String| Calendar::name(calendar, name));
|
||||
engine.register_fn("description", move |calendar: Calendar, description: String| Calendar::description(calendar, description));
|
||||
engine.register_fn("add_event", Calendar::add_event); // Corrected: expects i64, Rhai provides i64
|
||||
engine.register_fn("add_event", Calendar::add_event);
|
||||
// Note: Event IDs are i64 in Calendar.events, but Event model's base_data.id is u32.
|
||||
// This might require adjustment if events are fetched by ID from the DB via Calendar.events.
|
||||
|
||||
engine.register_fn("new_event", Event::new); // Corrected: expects i64, Rhai provides i64
|
||||
engine.register_fn("new_event", |context: NativeCallContext, title_rhai: ImmutableString, start_time_ts: i64, end_time_ts: i64| -> Result<Event, Box<EvalAltResult>> {
|
||||
new_event_rhai(context, title_rhai, start_time_ts, end_time_ts)
|
||||
});
|
||||
engine.register_fn("title", move |event: Event, title: String| Event::title(event, title));
|
||||
engine.register_fn("description", move |event: Event, description: String| Event::description(event, description));
|
||||
engine.register_fn("add_attendee", move |event: Event, attendee: Attendee| Event::add_attendee(event, attendee));
|
||||
@@ -36,6 +61,8 @@ pub fn register_rhai_engine_functions(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
engine.register_fn("new_attendee", adapt_rhai_i64_input_fn!(Attendee::new, u32));
|
||||
|
||||
engine.register_fn("new_calendar", |name: String| -> Result<Calendar, Box<EvalAltResult>> { new_calendar_rhai(name) });
|
||||
|
||||
// Register a function to get the database instance
|
||||
engine.register_fn("get_db", move || db.clone());
|
||||
|
||||
@@ -53,24 +80,8 @@ pub fn register_rhai_engine_functions(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
// Register getters for BaseModelData
|
||||
engine.register_get("id", |bmd: &mut BaseModelData| -> Result<i64, Box<EvalAltResult>> { Ok(bmd.id.into()) });
|
||||
|
||||
// Mock database interaction functions from the example - these would typically interact with the `db` Arc
|
||||
engine.register_fn("set_calendar", |_db: Arc<OurDB>, calendar: Calendar| {
|
||||
println!("Mock save: Calendar saved: {}", calendar.name);
|
||||
});
|
||||
|
||||
engine.register_fn("get_calendar_by_id", |_db: Arc<OurDB>, id_i64: i64| -> Calendar {
|
||||
Calendar::new(id_i64 as u32)
|
||||
});
|
||||
|
||||
engine.register_fn("calendar_exists", |_db: Arc<OurDB>, id_i64: i64| -> bool {
|
||||
id_i64 == 1 || id_i64 == 2 // Mock check
|
||||
});
|
||||
|
||||
engine.register_fn("get_all_calendars", wrap_vec_return!(get_all_calendars_helper, Arc<OurDB> => Calendar));
|
||||
|
||||
engine.register_fn("delete_calendar_by_id", |_db: Arc<OurDB>, id_i64: i64| {
|
||||
println!("Mock delete: Calendar deleted with ID: {}", id_i64);
|
||||
});
|
||||
// Database interaction functions for Calendar are expected to be provided by #[rhai_model_export(..)] on the Calendar struct.
|
||||
// Ensure that `db.rs` or similar correctly wires up the `OurDB` methods for these.
|
||||
|
||||
// Getters for Event
|
||||
engine.register_get("id", |e: &mut Event| -> Result<i64, Box<EvalAltResult>> { Ok(e.base_data.id as i64) });
|
||||
|
@@ -4,8 +4,6 @@ use serde::{Deserialize, Serialize};
|
||||
use rhai::{CustomType, TypeBuilder};
|
||||
use heromodels_derive::model;
|
||||
use heromodels_core::BaseModelData;
|
||||
use heromodels_derive::model;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::asset::Asset;
|
||||
|
||||
|
@@ -4,8 +4,6 @@ use serde::{Deserialize, Serialize};
|
||||
use rhai::{CustomType, TypeBuilder};
|
||||
use heromodels_derive::model;
|
||||
use heromodels_core::BaseModelData;
|
||||
use heromodels_derive::model;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// AssetType defines the type of blockchain asset
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
|
@@ -5,8 +5,6 @@ use rhai::{CustomType, TypeBuilder};
|
||||
use chrono::{DateTime, Utc};
|
||||
use heromodels_core::BaseModelData;
|
||||
use heromodels_derive::model;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::asset::AssetType;
|
||||
|
||||
|
@@ -1,13 +1,22 @@
|
||||
use rhai::{Engine, Array, ImmutableString, INT, EvalAltResult};
|
||||
use rhai::{Engine, Array, Dynamic, ImmutableString, INT, EvalAltResult, NativeCallContext};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error as StdError; // For Box<dyn StdError>
|
||||
|
||||
use chrono::Utc;
|
||||
// Custom error type for Rhai that wraps a String
|
||||
#[derive(Debug)]
|
||||
struct RhaiStringError(String);
|
||||
|
||||
use adapter_macros::register_rhai_enum_accessors;
|
||||
use adapter_macros::register_rhai_datetime_accessors;
|
||||
use adapter_macros::register_rhai_vec_string_accessors;
|
||||
use adapter_macros::rhai_timestamp_helpers;
|
||||
impl std::fmt::Display for RhaiStringError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for RhaiStringError {}
|
||||
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::models::finance::account::Account;
|
||||
use crate::models::finance::asset::{Asset, AssetType};
|
||||
@@ -67,7 +76,6 @@ fn string_to_bid_status(s: &str) -> Result<BidStatus, Box<EvalAltResult>> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn register_rhai_engine_functions(
|
||||
engine: &mut Engine,
|
||||
db_accounts: Arc<Mutex<HashMap<u32, Account>>>,
|
||||
@@ -75,68 +83,213 @@ pub fn register_rhai_engine_functions(
|
||||
db_listings: Arc<Mutex<HashMap<u32, Listing>>>,
|
||||
) {
|
||||
// --- Account model ---
|
||||
engine.build_type::<Account>()
|
||||
.register_fn("new_account",
|
||||
|id_rhai: INT, name_rhai: ImmutableString, user_id_rhai: INT, desc_rhai: ImmutableString, ledger_rhai: ImmutableString, addr_rhai: ImmutableString, pubkey_rhai: ImmutableString| -> Account {
|
||||
Account::new(id_rhai as u32, name_rhai, user_id_rhai as u32, desc_rhai, ledger_rhai, addr_rhai, pubkey_rhai)
|
||||
}
|
||||
)
|
||||
.register_get_set("name",
|
||||
|obj: &mut Account| -> ImmutableString { obj.name.clone().into() },
|
||||
|obj: &mut Account, val: ImmutableString| obj.name = val.to_string()
|
||||
)
|
||||
.register_get_set("user_id",
|
||||
|obj: &mut Account| obj.user_id as INT,
|
||||
|obj: &mut Account, val: INT| obj.user_id = val as u32
|
||||
)
|
||||
.register_get_set("description",
|
||||
|obj: &mut Account| -> ImmutableString { obj.description.clone().into() },
|
||||
|obj: &mut Account, val: ImmutableString| obj.description = val.to_string()
|
||||
)
|
||||
.register_get_set("ledger",
|
||||
|obj: &mut Account| -> ImmutableString { obj.ledger.clone().into() },
|
||||
|obj: &mut Account, val: ImmutableString| obj.ledger = val.to_string()
|
||||
)
|
||||
.register_get_set("address",
|
||||
|obj: &mut Account| -> ImmutableString { obj.address.clone().into() },
|
||||
|obj: &mut Account, val: ImmutableString| obj.address = val.to_string()
|
||||
)
|
||||
.register_get_set("pubkey",
|
||||
|obj: &mut Account| -> ImmutableString { obj.pubkey.clone().into() },
|
||||
|obj: &mut Account, val: ImmutableString| obj.pubkey = val.to_string()
|
||||
)
|
||||
.register_get("created_at_ts", |obj: &mut Account| obj.base_data.created_at);
|
||||
engine.register_get("assets_list", |acc: &mut Account| -> Array {
|
||||
acc.assets.iter().cloned().map(rhai::Dynamic::from).collect()
|
||||
engine.register_type_with_name::<Account>("Account");
|
||||
engine.register_fn("new_account", || -> Account {
|
||||
Account::new(None, "", 0, "", "", "", "")
|
||||
});
|
||||
// Getters
|
||||
engine.register_get("id", |acc: &mut Account| acc.base_data.id as INT);
|
||||
engine.register_get("created_at_ts", |acc: &mut Account| acc.base_data.created_at);
|
||||
engine.register_get("name", |acc: &mut Account| -> ImmutableString { acc.name.clone().into() });
|
||||
engine.register_get("user_id", |acc: &mut Account| acc.user_id as INT);
|
||||
engine.register_get("description", |acc: &mut Account| -> ImmutableString { acc.description.clone().into() });
|
||||
engine.register_get("ledger", |acc: &mut Account| -> ImmutableString { acc.ledger.clone().into() });
|
||||
engine.register_get("address", |acc: &mut Account| -> ImmutableString { acc.address.clone().into() });
|
||||
engine.register_get("pubkey", |acc: &mut Account| -> ImmutableString { acc.pubkey.clone().into() });
|
||||
engine.register_get("assets_list", |acc: &mut Account| -> Result<Array, Box<EvalAltResult>> {
|
||||
Ok(acc.assets.iter().cloned().map(rhai::Dynamic::from).collect())
|
||||
});
|
||||
engine.register_get("modified_at_ts", |acc: &mut Account| acc.base_data.modified_at);
|
||||
|
||||
// Setters (Builder Pattern)
|
||||
engine.register_fn("set_name", |mut acc: Account, name: ImmutableString| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.name = name.to_string(); Ok(acc)
|
||||
});
|
||||
engine.register_fn("set_user_id", |mut acc: Account, user_id: INT| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.user_id = user_id as u32; Ok(acc)
|
||||
});
|
||||
engine.register_fn("set_description", |mut acc: Account, description: ImmutableString| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.description = description.to_string(); Ok(acc)
|
||||
});
|
||||
engine.register_fn("set_ledger", |mut acc: Account, ledger: ImmutableString| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.ledger = ledger.to_string(); Ok(acc)
|
||||
});
|
||||
engine.register_fn("set_address", |mut acc: Account, address: ImmutableString| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.address = address.to_string(); Ok(acc)
|
||||
});
|
||||
engine.register_fn("set_pubkey", |mut acc: Account, pubkey: ImmutableString| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.pubkey = pubkey.to_string(); Ok(acc)
|
||||
});
|
||||
// Action: Add an Asset object to the account's asset list
|
||||
engine.register_fn("add_asset", |mut acc: Account, asset: Asset| -> Result<Account, Box<EvalAltResult>> {
|
||||
acc.assets.push(asset);
|
||||
Ok(acc)
|
||||
});
|
||||
|
||||
// --- Asset model ---
|
||||
engine.build_type::<Asset>()
|
||||
.register_fn("new_asset",
|
||||
|id_rhai: INT, name: ImmutableString, description: ImmutableString, amount: f64, address: ImmutableString, asset_type_str_rhai: ImmutableString, decimals_rhai: INT| -> Result<Asset, Box<EvalAltResult>> {
|
||||
let asset_type = self::string_to_asset_type(asset_type_str_rhai.as_str())?;
|
||||
Ok(Asset::new(id_rhai as u32, name, description, amount, address, asset_type, decimals_rhai as u8))
|
||||
}
|
||||
)
|
||||
.register_get("id", |asset: &mut Asset| asset.base_data.id as INT)
|
||||
.register_get_set("name",
|
||||
|asset: &mut Asset| -> ImmutableString { asset.name.clone().into() },
|
||||
|asset: &mut Asset, val: ImmutableString| asset.name = val.to_string()
|
||||
)
|
||||
.register_get_set("description",
|
||||
|asset: &mut Asset| -> ImmutableString { asset.description.clone().into() },
|
||||
|asset: &mut Asset, val: ImmutableString| asset.description = val.to_string()
|
||||
)
|
||||
.register_get_set("amount", |asset: &mut Asset| asset.amount, |asset: &mut Asset, amount_val: f64| asset.amount = amount_val)
|
||||
.register_get_set("address",
|
||||
|asset: &mut Asset| -> ImmutableString { asset.address.clone().into() },
|
||||
|asset: &mut Asset, val: ImmutableString| asset.address = val.to_string()
|
||||
)
|
||||
.register_get("decimals", |asset: &mut Asset| asset.decimals as INT)
|
||||
.register_get("created_at_ts", |obj: &mut Asset| obj.base_data.created_at);
|
||||
register_rhai_enum_accessors!(engine, Asset, asset_type, "asset_type_str", self::asset_type_to_string, self::string_to_asset_type);
|
||||
engine.register_type_with_name::<Asset>("Asset");
|
||||
engine.register_fn("new_asset", || -> Asset {
|
||||
Asset::new(None, "", "", 0.0, "", AssetType::Native, 0)
|
||||
});
|
||||
// Getters
|
||||
engine.register_get("id", |asset: &mut Asset| asset.base_data.id as INT);
|
||||
engine.register_get("created_at_ts", |asset: &mut Asset| asset.base_data.created_at);
|
||||
engine.register_get("name", |asset: &mut Asset| -> ImmutableString { asset.name.clone().into() });
|
||||
engine.register_get("description", |asset: &mut Asset| -> ImmutableString { asset.description.clone().into() });
|
||||
engine.register_get("amount", |asset: &mut Asset| asset.amount);
|
||||
engine.register_get("address", |asset: &mut Asset| -> ImmutableString { asset.address.clone().into() });
|
||||
engine.register_get("asset_type_str", |asset: &mut Asset| -> ImmutableString { self::asset_type_to_string(&asset.asset_type) });
|
||||
engine.register_get("decimals", |asset: &mut Asset| asset.decimals as INT);
|
||||
engine.register_get("modified_at_ts", |asset: &mut Asset| asset.base_data.modified_at);
|
||||
|
||||
// Setters (Builder Pattern)
|
||||
engine.register_fn("set_name", |mut asset: Asset, name: ImmutableString| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.name = name.to_string(); Ok(asset)
|
||||
});
|
||||
engine.register_fn("set_description", |mut asset: Asset, description: ImmutableString| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.description = description.to_string(); Ok(asset)
|
||||
});
|
||||
engine.register_fn("set_amount", |mut asset: Asset, amount: f64| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.amount = amount; Ok(asset)
|
||||
});
|
||||
engine.register_fn("set_address", |mut asset: Asset, address: ImmutableString| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.address = address.to_string(); Ok(asset)
|
||||
});
|
||||
engine.register_fn("set_asset_type_str", |mut asset: Asset, asset_type_str: ImmutableString| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.asset_type = self::string_to_asset_type(asset_type_str.as_str())?;
|
||||
Ok(asset)
|
||||
});
|
||||
engine.register_fn("set_decimals", |mut asset: Asset, decimals: INT| -> Result<Asset, Box<EvalAltResult>> {
|
||||
asset.decimals = decimals as u8; Ok(asset)
|
||||
});
|
||||
|
||||
// --- Bid model ---
|
||||
// --- Listing model ---
|
||||
engine.register_type_with_name::<Listing>("Listing");
|
||||
engine.register_fn("new_listing", || -> Listing {
|
||||
Listing::new(None, "", "", "", AssetType::Native, "", 0.0, "", ListingType::FixedPrice, None, Vec::new(), None::<String>)
|
||||
});
|
||||
// Getters
|
||||
engine.register_get("id", |l: &mut Listing| l.base_data.id as INT);
|
||||
engine.register_get("created_at_ts", |l: &mut Listing| l.base_data.created_at);
|
||||
engine.register_get("modified_at_ts", |l: &mut Listing| l.base_data.modified_at);
|
||||
engine.register_get("title", |l: &mut Listing| -> ImmutableString { l.title.clone().into() });
|
||||
engine.register_get("description", |l: &mut Listing| -> ImmutableString { l.description.clone().into() });
|
||||
engine.register_get("asset_id", |l: &mut Listing| -> ImmutableString { l.asset_id.clone().into() });
|
||||
engine.register_get("asset_type_str", |l: &mut Listing| -> ImmutableString { self::asset_type_to_string(&l.asset_type) });
|
||||
engine.register_get("seller_id", |l: &mut Listing| -> ImmutableString { l.seller_id.clone().into() });
|
||||
engine.register_get("price", |l: &mut Listing| l.price);
|
||||
engine.register_get("currency", |l: &mut Listing| -> ImmutableString { l.currency.clone().into() });
|
||||
engine.register_get("listing_type_str", |l: &mut Listing| -> ImmutableString { self::listing_type_to_string(&l.listing_type) });
|
||||
engine.register_get("status_str", |l: &mut Listing| -> ImmutableString { self::listing_status_to_string(&l.status) });
|
||||
engine.register_get("expires_at_ts", |l: &mut Listing| l.expires_at);
|
||||
engine.register_get("tags", |l: &mut Listing| -> Result<Array, Box<EvalAltResult>> {
|
||||
Ok(l.tags.iter().map(|s| Dynamic::from(s.clone())).collect())
|
||||
});
|
||||
engine.register_get("image_url", |l: &mut Listing| -> Option<ImmutableString> { l.image_url.as_ref().map(|s| s.clone().into()) });
|
||||
engine.register_get("bids_list", |l: &mut Listing| -> Result<Array, Box<EvalAltResult>> {
|
||||
Ok(l.bids.iter().cloned().map(rhai::Dynamic::from).collect())
|
||||
});
|
||||
// Setters (Builder Pattern)
|
||||
engine.register_fn("set_title", |mut l: Listing, title: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.title = title.to_string(); Ok(l)
|
||||
});
|
||||
engine.register_fn("set_description", |mut l: Listing, description: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.description = description.to_string(); Ok(l)
|
||||
});
|
||||
engine.register_fn("set_asset_id", |mut l: Listing, asset_id: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.asset_id = asset_id.to_string(); Ok(l)
|
||||
});
|
||||
engine.register_fn("set_asset_type_str", |mut l: Listing, asset_type_str: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.asset_type = self::string_to_asset_type(asset_type_str.as_str())?;
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("set_seller_id", |mut l: Listing, seller_id: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.seller_id = seller_id.to_string(); Ok(l)
|
||||
});
|
||||
engine.register_fn("set_price", |mut l: Listing, price: f64| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.price = price; Ok(l)
|
||||
});
|
||||
engine.register_fn("set_currency", |mut l: Listing, currency: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.currency = currency.to_string(); Ok(l)
|
||||
});
|
||||
engine.register_fn("set_listing_type_str", |mut l: Listing, listing_type_str: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.listing_type = self::string_to_listing_type(listing_type_str.as_str())?;
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("set_status_str", |mut l: Listing, status_str: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.status = self::string_to_listing_status(status_str.as_str())?;
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("set_expires_at_ts", |mut l: Listing, expires_at_ts: Option<INT>| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.expires_at = expires_at_ts.map(|ts| DateTime::from_timestamp(ts, 0).unwrap_or_else(|| Utc::now()));
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("set_tags", |mut l: Listing, tags_array: Array| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.tags = tags_array.into_iter().map(|d| d.into_string().unwrap_or_default()).collect();
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("add_tag", |mut l: Listing, tag: ImmutableString| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.tags.push(tag.to_string());
|
||||
Ok(l)
|
||||
});
|
||||
engine.register_fn("set_image_url", |mut l: Listing, image_url: Option<ImmutableString>| -> Result<Listing, Box<EvalAltResult>> {
|
||||
l.image_url = image_url.map(|s| s.to_string());
|
||||
Ok(l)
|
||||
});
|
||||
// Listing Action Methods (preserved)
|
||||
engine.register_fn("add_listing_bid", |listing: Listing, bid: Bid| -> Result<Listing, Box<EvalAltResult>> {
|
||||
listing.add_bid(bid).map_err(|e_str| {
|
||||
Box::new(EvalAltResult::ErrorSystem(
|
||||
"Failed to add bid".to_string(),
|
||||
Box::new(RhaiStringError(e_str.to_string())),
|
||||
))
|
||||
})
|
||||
});
|
||||
engine.register_fn("accept_listing_bid", |listing: Listing, bid_index_rhai: i64| -> Result<Listing, Box<EvalAltResult>> {
|
||||
let bid_index = bid_index_rhai as usize;
|
||||
if bid_index >= listing.bids.len() {
|
||||
return Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
"Invalid bid index".to_string(),
|
||||
Box::new(RhaiStringError(format!("Bid index {} out of bounds for {} bids", bid_index, listing.bids.len()))),
|
||||
)));
|
||||
}
|
||||
|
||||
let bid_to_accept = listing.bids[bid_index].clone();
|
||||
|
||||
if bid_to_accept.status != BidStatus::Active {
|
||||
return Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
"Bid not active".to_string(),
|
||||
Box::new(RhaiStringError(format!("Cannot accept bid at index {} as it is not active (status: {:?})", bid_index, bid_to_accept.status))),
|
||||
)));
|
||||
}
|
||||
|
||||
let mut listing_after_sale = listing.complete_sale(bid_to_accept.bidder_id.to_string(), bid_to_accept.amount)
|
||||
.map_err(|e_str| Box::new(EvalAltResult::ErrorSystem(
|
||||
"Failed to complete sale".to_string(),
|
||||
Box::new(RhaiStringError(e_str.to_string())),
|
||||
)))?;
|
||||
|
||||
// Update bid statuses on the new listing state
|
||||
for (idx, bid_in_list) in listing_after_sale.bids.iter_mut().enumerate() {
|
||||
if idx == bid_index {
|
||||
*bid_in_list = bid_in_list.clone().update_status(BidStatus::Accepted);
|
||||
} else {
|
||||
if bid_in_list.status == BidStatus::Active { // Only reject other active bids
|
||||
*bid_in_list = bid_in_list.clone().update_status(BidStatus::Rejected);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(listing_after_sale)
|
||||
});
|
||||
engine.register_fn("cancel_listing", |_ctx: NativeCallContext, listing: Listing| -> Result<Listing, Box<EvalAltResult>> {
|
||||
listing.cancel().map_err(|e_str| {
|
||||
Box::new(EvalAltResult::ErrorSystem(
|
||||
"Failed to cancel listing".to_string(),
|
||||
Box::new(RhaiStringError(e_str.to_string()))
|
||||
))
|
||||
})
|
||||
});
|
||||
// --- Bid model (preserved as is) ---
|
||||
engine.register_type_with_name::<Bid>("Bid")
|
||||
.register_fn("new_bid",
|
||||
|listing_id_rhai: ImmutableString, bidder_id_rhai: INT, amount_rhai: f64, currency_rhai: ImmutableString| -> Bid {
|
||||
@@ -152,110 +305,41 @@ pub fn register_rhai_engine_functions(
|
||||
.register_get_set("currency",
|
||||
|bid: &mut Bid| -> ImmutableString { bid.currency.clone().into() },
|
||||
|bid: &mut Bid, val: ImmutableString| bid.currency = val.to_string()
|
||||
);
|
||||
register_rhai_enum_accessors!(engine, Bid, status, "status_str", self::bid_status_to_string, self::string_to_bid_status);
|
||||
register_rhai_datetime_accessors!(engine, Bid, created_at, "created_at_ts", _required);
|
||||
engine.register_fn("update_bid_status_script",
|
||||
|bid: Bid, status_str_rhai: ImmutableString| -> Result<Bid, Box<EvalAltResult>> {
|
||||
let status = self::string_to_bid_status(status_str_rhai.as_str())?;
|
||||
let updated_bid = bid.update_status(status);
|
||||
Ok(updated_bid)
|
||||
)
|
||||
.register_get("status_str", |bid: &mut Bid| -> ImmutableString { self::bid_status_to_string(&bid.status) });
|
||||
|
||||
engine.register_fn("accept_bid_script", |bid: Bid| -> Result<Bid, Box<EvalAltResult>> {
|
||||
// Ensure the bid is active before accepting
|
||||
if bid.status != BidStatus::Active {
|
||||
return Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
"Bid not active".to_string(),
|
||||
Box::new(RhaiStringError(format!("Cannot accept bid as it is not active (status: {:?})", bid.status)))
|
||||
)));
|
||||
}
|
||||
);
|
||||
|
||||
// --- Listing --- (id is u32)
|
||||
engine.register_type_with_name::<Listing>("Listing")
|
||||
.register_fn("new_listing",
|
||||
|id_rhai: INT, title_rhai: ImmutableString, description_rhai: ImmutableString,
|
||||
asset_id_rhai: ImmutableString, asset_type_str_rhai: ImmutableString, seller_id_rhai: ImmutableString,
|
||||
price_rhai: f64, currency_rhai: ImmutableString, listing_type_str_rhai: ImmutableString,
|
||||
expires_at_ts_opt_rhai: Option<INT>, tags_dyn_rhai: Array, image_url_opt_rhai: Option<ImmutableString>|
|
||||
-> Result<Listing, Box<EvalAltResult>> {
|
||||
|
||||
let asset_type = self::string_to_asset_type(asset_type_str_rhai.as_str())?;
|
||||
let listing_type = self::string_to_listing_type(listing_type_str_rhai.as_str())?;
|
||||
let expires_at = rhai_timestamp_helpers::option_rhai_timestamp_to_datetime(expires_at_ts_opt_rhai)?;
|
||||
|
||||
let tags = tags_dyn_rhai.into_iter().map(|d| d.into_string().unwrap_or_default()).collect();
|
||||
let image_url = image_url_opt_rhai.map(|s| s.to_string());
|
||||
|
||||
Ok(Listing::new(
|
||||
id_rhai as u32, title_rhai, description_rhai, asset_id_rhai,
|
||||
asset_type, seller_id_rhai, price_rhai, currency_rhai, listing_type,
|
||||
expires_at, tags, image_url
|
||||
))
|
||||
}
|
||||
)
|
||||
.register_get("id", |l: &mut Listing| l.base_data.id as INT)
|
||||
.register_get_set("title",
|
||||
|l: &mut Listing| -> ImmutableString { l.title.clone().into() },
|
||||
|l: &mut Listing, v: ImmutableString| l.title = v.to_string()
|
||||
)
|
||||
.register_get_set("description",
|
||||
|l: &mut Listing| -> ImmutableString { l.description.clone().into() },
|
||||
|l: &mut Listing, v: ImmutableString| l.description = v.to_string()
|
||||
)
|
||||
.register_get_set("asset_id",
|
||||
|l: &mut Listing| -> ImmutableString { l.asset_id.clone().into() },
|
||||
|l: &mut Listing, v: ImmutableString| l.asset_id = v.to_string()
|
||||
)
|
||||
.register_get_set("seller_id",
|
||||
|l: &mut Listing| -> ImmutableString { l.seller_id.clone().into() },
|
||||
|l: &mut Listing, v: ImmutableString| l.seller_id = v.to_string()
|
||||
)
|
||||
.register_get_set("price", |l: &mut Listing| l.price, |l: &mut Listing, v: f64| l.price = v)
|
||||
.register_get_set("currency",
|
||||
|l: &mut Listing| -> ImmutableString { l.currency.clone().into() },
|
||||
|l: &mut Listing, v: ImmutableString| l.currency = v.to_string()
|
||||
)
|
||||
.register_get_set("buyer_id",
|
||||
|l: &mut Listing| -> Option<ImmutableString> { l.buyer_id.clone().map(ImmutableString::from) },
|
||||
|l: &mut Listing, v_opt: Option<ImmutableString>| l.buyer_id = v_opt.map(|s| s.to_string())
|
||||
)
|
||||
.register_get_set("sale_price",
|
||||
|l: &mut Listing| -> Option<f64> { l.sale_price },
|
||||
|l: &mut Listing, v_opt: Option<f64>| l.sale_price = v_opt
|
||||
)
|
||||
.register_get_set("image_url",
|
||||
|l: &mut Listing| -> Option<ImmutableString> { l.image_url.clone().map(ImmutableString::from) },
|
||||
|l: &mut Listing, v: Option<ImmutableString>| l.image_url = v.map(|s| s.to_string())
|
||||
)
|
||||
.register_get("created_at_ts", |obj: &mut Listing| obj.base_data.created_at);
|
||||
|
||||
register_rhai_enum_accessors!(engine, Listing, listing_type, "listing_type_str", self::listing_type_to_string, self::string_to_listing_type);
|
||||
register_rhai_enum_accessors!(engine, Listing, status, "status_str", self::listing_status_to_string, self::string_to_listing_status);
|
||||
register_rhai_enum_accessors!(engine, Listing, asset_type, "asset_type_str_listing", self::asset_type_to_string, self::string_to_asset_type);
|
||||
|
||||
register_rhai_datetime_accessors!(engine, Listing, expires_at, "expires_at_ts_opt");
|
||||
register_rhai_datetime_accessors!(engine, Listing, sold_at, "sold_at_ts_opt");
|
||||
|
||||
register_rhai_vec_string_accessors!(engine, Listing, tags, "tags_cloned");
|
||||
|
||||
engine.register_fn("add_listing_bid",
|
||||
|listing: Listing, bid: Bid| -> Result<Listing, Box<EvalAltResult>> {
|
||||
listing.add_bid(bid).map_err(|e| e.into())
|
||||
Ok(bid.update_status(BidStatus::Accepted))
|
||||
});
|
||||
engine.register_fn("reject_bid_script", |bid: Bid| -> Result<Bid, Box<EvalAltResult>> {
|
||||
// Ensure the bid is active before rejecting
|
||||
if bid.status != BidStatus::Active {
|
||||
return Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
"Bid not active".to_string(),
|
||||
Box::new(RhaiStringError(format!("Cannot reject bid as it is not active (status: {:?})", bid.status)))
|
||||
)));
|
||||
}
|
||||
);
|
||||
engine.register_fn("get_bids_cloned", |listing: &mut Listing| listing.bids.clone());
|
||||
engine.register_fn("complete_listing_sale_script",
|
||||
|listing: Listing, buyer_id_rhai: ImmutableString, sale_price_rhai: f64| -> Result<Listing, Box<EvalAltResult>> {
|
||||
listing.complete_sale(buyer_id_rhai.as_str(), sale_price_rhai).map_err(|e| e.into())
|
||||
Ok(bid.update_status(BidStatus::Rejected))
|
||||
});
|
||||
engine.register_fn("cancel_bid_script", |bid: Bid| -> Result<Bid, Box<EvalAltResult>> {
|
||||
// Ensure the bid is active before cancelling
|
||||
if bid.status != BidStatus::Active {
|
||||
return Err(Box::new(EvalAltResult::ErrorSystem(
|
||||
"Bid not active".to_string(),
|
||||
Box::new(RhaiStringError(format!("Cannot cancel bid as it is not active (status: {:?})", bid.status)))
|
||||
)));
|
||||
}
|
||||
);
|
||||
engine.register_fn("cancel_listing_script",
|
||||
|listing: Listing| -> Result<Listing, Box<EvalAltResult>> {
|
||||
listing.cancel().map_err(|e| e.into())
|
||||
}
|
||||
);
|
||||
engine.register_fn("add_listing_tags_script",
|
||||
|listing: Listing, tags_dyn_rhai: Array| -> Result<Listing, Box<EvalAltResult>> {
|
||||
let tags_to_add: Vec<String> = tags_dyn_rhai.into_iter().map(|d| d.into_string().unwrap_or_default()).collect();
|
||||
Ok(listing.add_tags(tags_to_add))
|
||||
}
|
||||
);
|
||||
Ok(bid.update_status(BidStatus::Cancelled))
|
||||
});
|
||||
|
||||
// --- Global Helper Functions (Enum conversions, potentially already covered by macros but good for direct script use) ---
|
||||
// These are useful if scripts need to convert strings to enums outside of object setters.
|
||||
engine.register_fn("str_to_asset_type", |s: ImmutableString| self::string_to_asset_type(s.as_str()));
|
||||
engine.register_fn("asset_type_to_str", self::asset_type_to_string);
|
||||
engine.register_fn("str_to_listing_status", |s: ImmutableString| self::string_to_listing_status(s.as_str()));
|
||||
@@ -265,12 +349,16 @@ pub fn register_rhai_engine_functions(
|
||||
engine.register_fn("str_to_bid_status", |s: ImmutableString| self::string_to_bid_status(s.as_str()));
|
||||
engine.register_fn("bid_status_to_str", self::bid_status_to_string);
|
||||
|
||||
|
||||
// --- Mock DB functions ---
|
||||
// --- Mock DB functions (preserved) ---
|
||||
let accounts_db_clone = Arc::clone(&db_accounts);
|
||||
engine.register_fn("set_account", move |account: Account| {
|
||||
engine.register_fn("set_account", move |mut account: Account| -> Account {
|
||||
let mut db = accounts_db_clone.lock().unwrap();
|
||||
db.insert(account.base_data.id, account);
|
||||
if account.base_data.id == 0 {
|
||||
let next_id = db.keys().max().cloned().unwrap_or(0) + 1;
|
||||
account.base_data.update_id(next_id);
|
||||
}
|
||||
db.insert(account.base_data.id, account.clone());
|
||||
account
|
||||
});
|
||||
|
||||
let accounts_db_clone_get = Arc::clone(&db_accounts);
|
||||
@@ -283,9 +371,14 @@ pub fn register_rhai_engine_functions(
|
||||
});
|
||||
|
||||
let assets_db_clone = Arc::clone(&db_assets);
|
||||
engine.register_fn("set_asset", move |asset: Asset| {
|
||||
engine.register_fn("set_asset", move |mut asset: Asset| -> Asset {
|
||||
let mut db = assets_db_clone.lock().unwrap();
|
||||
db.insert(asset.base_data.id, asset);
|
||||
if asset.base_data.id == 0 {
|
||||
let next_id = db.keys().max().cloned().unwrap_or(0) + 1;
|
||||
asset.base_data.update_id(next_id);
|
||||
}
|
||||
db.insert(asset.base_data.id, asset.clone());
|
||||
asset
|
||||
});
|
||||
|
||||
let assets_db_clone_get = Arc::clone(&db_assets);
|
||||
@@ -298,9 +391,14 @@ pub fn register_rhai_engine_functions(
|
||||
});
|
||||
|
||||
let listings_db_clone = Arc::clone(&db_listings);
|
||||
engine.register_fn("set_listing", move |listing: Listing| {
|
||||
engine.register_fn("set_listing", move |mut listing: Listing| -> Listing {
|
||||
let mut db = listings_db_clone.lock().unwrap();
|
||||
db.insert(listing.base_data.id, listing);
|
||||
if listing.base_data.id == 0 {
|
||||
let next_id = db.keys().max().cloned().unwrap_or(0) + 1;
|
||||
listing.base_data.update_id(next_id);
|
||||
}
|
||||
db.insert(listing.base_data.id, listing.clone());
|
||||
listing
|
||||
});
|
||||
|
||||
let listings_db_clone_get = Arc::clone(&db_listings);
|
||||
|
@@ -29,9 +29,9 @@ impl Flow {
|
||||
/// Create a new flow.
|
||||
/// The `id` is the database primary key.
|
||||
/// The `flow_uuid` should be a Uuid::new_v4().to_string().
|
||||
pub fn new(id: u32, flow_uuid: impl ToString) -> Self {
|
||||
pub fn new(_id: u32, flow_uuid: impl ToString) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
flow_uuid: flow_uuid.to_string(),
|
||||
name: String::new(), // Default name, to be set by builder
|
||||
status: String::from("Pending"), // Default status, to be set by builder
|
||||
|
@@ -22,9 +22,9 @@ pub struct FlowStep {
|
||||
|
||||
impl FlowStep {
|
||||
/// Create a new flow step.
|
||||
pub fn new(id: u32, step_order: u32) -> Self {
|
||||
pub fn new(_id: u32, step_order: u32) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
description: None,
|
||||
step_order,
|
||||
status: String::from("Pending"), // Default status
|
||||
|
@@ -103,7 +103,7 @@ pub fn register_flow_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
let captured_db_for_set_flow = Arc::clone(&db);
|
||||
engine.register_fn("set_flow", move |flow: Flow| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set_flow.set(&flow).map_err(|e| {
|
||||
captured_db_for_set_flow.set(&flow).map(|_| ()).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set Flow (ID: {}): {}", flow.base_data.id, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
@@ -121,7 +121,7 @@ pub fn register_flow_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
|
||||
let captured_db_for_set_sig_req = Arc::clone(&db);
|
||||
engine.register_fn("set_signature_requirement", move |sr: SignatureRequirement| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set_sig_req.set(&sr).map_err(|e| {
|
||||
captured_db_for_set_sig_req.set(&sr).map(|_| ()).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(format!("Failed to set SignatureRequirement (ID: {}): {}", sr.base_data.id, e).into(), Position::NONE))
|
||||
})
|
||||
});
|
||||
|
@@ -31,9 +31,9 @@ pub struct SignatureRequirement {
|
||||
|
||||
impl SignatureRequirement {
|
||||
/// Create a new signature requirement.
|
||||
pub fn new(id: u32, flow_step_id: u32, public_key: impl ToString, message: impl ToString) -> Self {
|
||||
pub fn new(_id: u32, flow_step_id: u32, public_key: impl ToString, message: impl ToString) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
flow_step_id,
|
||||
public_key: public_key.to_string(),
|
||||
message: message.to_string(),
|
||||
|
@@ -161,9 +161,9 @@ pub struct Contract {
|
||||
}
|
||||
|
||||
impl Contract {
|
||||
pub fn new(base_id: u32, contract_id: String) -> Self {
|
||||
pub fn new(_base_id: u32, contract_id: String) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(base_id),
|
||||
base_data: BaseModelData::new(),
|
||||
contract_id,
|
||||
title: String::new(),
|
||||
description: String::new(),
|
||||
|
@@ -239,7 +239,7 @@ pub fn register_legal_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
let captured_db_for_set = Arc::clone(&db);
|
||||
engine.register_fn("set_contract",
|
||||
move |contract: Contract| -> Result<(), Box<EvalAltResult>> {
|
||||
captured_db_for_set.set(&contract).map_err(|e| {
|
||||
captured_db_for_set.set(&contract).map(|_| ()).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorRuntime(
|
||||
format!("Failed to set Contract (ID: {}): {}", contract.base_data.id, e).into(),
|
||||
Position::NONE,
|
||||
|
@@ -91,9 +91,9 @@ impl Model for Project {
|
||||
}
|
||||
|
||||
impl Project {
|
||||
pub fn new(id: u32, name: String, description: String, owner_id: u32) -> Self {
|
||||
pub fn new(_id: u32, name: String, description: String, owner_id: u32) -> Self {
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data: BaseModelData::new(),
|
||||
name,
|
||||
description,
|
||||
owner_id,
|
||||
@@ -207,8 +207,10 @@ impl Model for Label {
|
||||
|
||||
impl Label {
|
||||
pub fn new(id: u32, name: String, color: String) -> Self {
|
||||
let mut base_data = BaseModelData::new();
|
||||
base_data.update_id(id);
|
||||
Self {
|
||||
base_data: BaseModelData::new(id),
|
||||
base_data,
|
||||
name,
|
||||
color,
|
||||
}
|
||||
|
@@ -217,7 +217,7 @@ pub fn register_projects_rhai_module(engine: &mut Engine, db: Arc<OurDB>) {
|
||||
))
|
||||
})?;
|
||||
|
||||
collection.set(&project).map_err(|e| {
|
||||
collection.set(&project).map(|_| ()).map_err(|e| {
|
||||
Box::new(EvalAltResult::ErrorSystem(
|
||||
"Failed to save project".to_string(),
|
||||
format!("DB operation failed: {:?}", e).into(),
|
||||
|
Reference in New Issue
Block a user