use crate::domains::fx_provider::{FxProviderConfig, RateProvider, build_provider};
use crate::math::fx_scenario::{budget_calculation, pricing_calculation};
use crate::server::evaluate::REQUEST_TIMEOUT_SECS;
use sdforge::error::ApiError;
use sdforge::forge;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct FxBudgetRequest {
pub tuition: f64,
pub tuition_currency: String,
#[serde(default)]
pub living_cost_monthly: Option<f64>,
pub duration_years: u32,
pub home_currency: String,
#[serde(default)]
pub lang: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct FxBudgetResponse {
pub tuition_foreign: f64,
pub tuition_currency: String,
pub tuition_home: f64,
pub home_currency: String,
pub rate: f64,
pub duration_years: u32,
pub annual_tuition_home: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub living_monthly_home: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total_living_home: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total_cost_home: Option<f64>,
pub exchange_risk: ExchangeRiskResponse,
pub rate_date: Option<String>,
pub rate_source: String,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct ExchangeRiskResponse {
pub range: String,
pub note: String,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct FxPricingRequest {
pub cost_cny: f64,
pub target_profit_rate: f64,
pub currencies: String,
#[serde(default = "default_platform_rate")]
pub platform_rate: f64,
#[serde(default = "default_safety_buffer")]
pub safety_buffer: f64,
#[serde(default)]
pub lang: Option<String>,
}
fn default_platform_rate() -> f64 {
0.15
}
fn default_safety_buffer() -> f64 {
0.05
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct FxPricingResponse {
pub cost_cny: f64,
pub target_profit_rate: f64,
pub platform_rate: f64,
pub safety_buffer: f64,
pub pricing: Vec<PricingItemResponse>,
pub rate_date: Option<String>,
pub rate_source: String,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PricingItemResponse {
pub currency: String,
pub recommended_price: f64,
pub actual_profit_rate: f64,
pub profit_cny: f64,
pub platform_fee_cny: f64,
}
fn shared_provider() -> Arc<dyn RateProvider> {
static PROVIDER: OnceLock<Arc<dyn RateProvider>> = OnceLock::new();
Arc::clone(PROVIDER.get_or_init(|| Arc::new(build_provider(&FxProviderConfig::from_env()))))
}
impl FxBudgetRequest {
fn validate(&self) -> Result<(), ApiError> {
if self.tuition <= 0.0 {
return Err(ApiError::validation("tuition", "tuition must be positive"));
}
if self.duration_years == 0 || self.duration_years > 10 {
return Err(ApiError::validation(
"duration_years",
"duration_years must be between 1 and 10",
));
}
if self.tuition_currency.len() != 3
|| !self
.tuition_currency
.chars()
.all(|c| c.is_ascii_alphabetic())
{
return Err(ApiError::validation(
"tuition_currency",
"must be a 3-letter ISO 4217 currency code",
));
}
if self.home_currency.len() != 3
|| !self.home_currency.chars().all(|c| c.is_ascii_alphabetic())
{
return Err(ApiError::validation(
"home_currency",
"must be a 3-letter ISO 4217 currency code",
));
}
if let Some(living) = self.living_cost_monthly
&& living < 0.0
{
return Err(ApiError::validation(
"living_cost_monthly",
"living_cost_monthly must be non-negative",
));
}
Ok(())
}
}
impl FxPricingRequest {
fn validate(&self) -> Result<(), ApiError> {
if self.cost_cny <= 0.0 {
return Err(ApiError::validation(
"cost_cny",
"cost_cny must be positive",
));
}
if self.target_profit_rate <= 0.0 || self.target_profit_rate >= 1.0 {
return Err(ApiError::validation(
"target_profit_rate",
"target_profit_rate must be between 0 and 1 (exclusive)",
));
}
if self.platform_rate < 0.0 || self.platform_rate >= 1.0 {
return Err(ApiError::validation(
"platform_rate",
"platform_rate must be in [0, 1)",
));
}
if self.safety_buffer < 0.0 || self.safety_buffer > 0.5 {
return Err(ApiError::validation(
"safety_buffer",
"safety_buffer must be in [0, 0.5]",
));
}
let currencies: Vec<&str> = self
.currencies
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
if currencies.is_empty() {
return Err(ApiError::validation(
"currencies",
"currencies list must not be empty",
));
}
if currencies.len() > 10 {
return Err(ApiError::validation(
"currencies",
"currencies list must not exceed 10 items",
));
}
for cur in ¤cies {
if cur.len() != 3 || !cur.chars().all(|c| c.is_ascii_alphabetic()) {
return Err(ApiError::validation(
"currencies",
format!("'{}' is not a valid 3-letter ISO 4217 currency code", cur),
));
}
}
Ok(())
}
}
#[forge(
name = "fx_budget",
version = 1,
path = "/fx_budget",
method = "POST",
tool_name = "fx_budget",
description = "Calculate study abroad budget with currency conversion. Args MUST be wrapped in a req object with fields: tuition, tuition_currency, home_currency, optional living_cost_monthly, duration_years, optional lang (response language, BCP-47 tag, 'en' default, 'zh' supported). Returns tuition/living/total in home currency plus a 3-percent exchange-rate risk range and rate_date (snapshot date). Errors: 400 InvalidInput (unknown currency), 503 ServiceUnavailable (FX upstream unreachable)."
)]
pub(crate) async fn fx_budget(req: FxBudgetRequest) -> Result<FxBudgetResponse, ApiError> {
fx_budget_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await
}
pub(crate) async fn fx_budget_with_timeout(
req: FxBudgetRequest,
timeout: Duration,
) -> Result<FxBudgetResponse, ApiError> {
run_fx_budget(req, timeout, shared_provider()).await
}
async fn run_fx_budget(
req: FxBudgetRequest,
timeout: Duration,
provider: Arc<dyn RateProvider>,
) -> Result<FxBudgetResponse, ApiError> {
req.validate()?;
let i18n = super::lang::resolve_i18n(req.lang.as_deref());
let tuition = req.tuition;
let tuition_currency = req.tuition_currency.clone();
let living_cost = req.living_cost_monthly;
let duration = req.duration_years;
let home_currency = req.home_currency.clone();
let i18n_in_task = i18n.clone();
let join_handle = tokio::task::spawn_blocking(move || {
let table = provider.rates().map_err(|e| {
ApiError::service_unavailable_with_source(
"fx_budget",
Some(5),
std::io::Error::other(e.to_string()),
)
})?;
let rate_date = Some(table.date.clone());
let rate_source = table.source.clone();
budget_calculation(
tuition,
&tuition_currency,
living_cost,
duration,
&home_currency,
&table,
)
.map(|result| (result, rate_date, rate_source))
.map_err(|e| {
ApiError::invalid_input(
super::evaluate::localized_error_detail(&e, &i18n_in_task),
None,
None,
)
})
});
let (result, rate_date, rate_source) = match tokio::time::timeout(timeout, join_handle).await {
Ok(Ok(r)) => r?,
Ok(Err(join_err)) => {
return Err(ApiError::internal_with_source(
"fx_budget task failed",
"spawn_blocking",
join_err,
));
}
Err(_) => {
return Err(ApiError::service_unavailable(
"fx_budget",
Some(timeout.as_secs()),
));
}
};
Ok(FxBudgetResponse {
tuition_foreign: result.tuition_foreign,
tuition_currency: result.tuition_currency,
tuition_home: result.tuition_home,
home_currency: result.home_currency,
rate: result.rate,
duration_years: result.duration_years,
annual_tuition_home: result.annual_tuition_home,
living_monthly_home: result.living_monthly_home,
total_living_home: result.total_living_home,
total_cost_home: result.total_cost_home,
exchange_risk: ExchangeRiskResponse {
range: format!(
"{:.0}~{:.0} {}",
result.exchange_risk.low, result.exchange_risk.high, result.exchange_risk.currency
),
note: i18n.t("msg.fx.budget_risk_note").to_string(),
},
rate_date,
rate_source,
})
}
#[forge(
name = "fx_pricing",
version = 1,
path = "/fx_pricing",
method = "POST",
tool_name = "fx_pricing",
description = "Cross-border e-commerce multi-currency pricing. Args MUST be wrapped in a req object with fields: cost_cny, target_profit_rate, currencies (comma separated), optional platform_rate, safety_buffer, optional lang (response language, BCP-47 tag, 'en' default, 'zh' supported). Returns per-currency recommended prices with platform fees, plus rate_date (snapshot date). Errors: 400 InvalidInput, 503 ServiceUnavailable (FX upstream unreachable)."
)]
pub(crate) async fn fx_pricing(req: FxPricingRequest) -> Result<FxPricingResponse, ApiError> {
fx_pricing_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await
}
pub(crate) async fn fx_pricing_with_timeout(
req: FxPricingRequest,
timeout: Duration,
) -> Result<FxPricingResponse, ApiError> {
run_fx_pricing(req, timeout, shared_provider()).await
}
async fn run_fx_pricing(
req: FxPricingRequest,
timeout: Duration,
provider: Arc<dyn RateProvider>,
) -> Result<FxPricingResponse, ApiError> {
req.validate()?;
let i18n = super::lang::resolve_i18n(req.lang.as_deref());
let cost = req.cost_cny;
let profit_rate = req.target_profit_rate;
let platform_rate = req.platform_rate;
let safety_buffer = req.safety_buffer;
let currencies: Vec<String> = req
.currencies
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
let join_handle = tokio::task::spawn_blocking(move || {
let table = provider.rates().map_err(|e| {
ApiError::service_unavailable_with_source(
"fx_pricing",
Some(5),
std::io::Error::other(e.to_string()),
)
})?;
let rate_date = Some(table.date.clone());
let rate_source = table.source.clone();
let cur_refs: Vec<&str> = currencies.iter().map(|s| s.as_str()).collect();
pricing_calculation(
cost,
profit_rate,
&cur_refs,
platform_rate,
safety_buffer,
&table,
)
.map(|result| (result, rate_date, rate_source))
.map_err(|e| {
ApiError::invalid_input(
super::evaluate::localized_error_detail(&e, &i18n),
None,
None,
)
})
});
let (result, rate_date, rate_source) = match tokio::time::timeout(timeout, join_handle).await {
Ok(Ok(r)) => r?,
Ok(Err(join_err)) => {
return Err(ApiError::internal_with_source(
"fx_pricing task failed",
"spawn_blocking",
join_err,
));
}
Err(_) => {
return Err(ApiError::service_unavailable(
"fx_pricing",
Some(timeout.as_secs()),
));
}
};
Ok(FxPricingResponse {
cost_cny: result.cost_cny,
target_profit_rate: profit_rate,
platform_rate,
safety_buffer,
pricing: result
.pricing
.into_iter()
.map(|item| PricingItemResponse {
currency: item.currency,
recommended_price: item.recommended_price,
actual_profit_rate: item.actual_profit_rate,
profit_cny: item.profit_cny,
platform_fee_cny: item.platform_fee_cny,
})
.collect(),
rate_date,
rate_source,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fx_budget_request_deserialize() {
let json = r#"{
"tuition": 50000.0,
"tuition_currency": "USD",
"living_cost_monthly": 2000.0,
"duration_years": 4,
"home_currency": "CNY"
}"#;
let req: FxBudgetRequest = serde_json::from_str(json).unwrap();
assert_eq!(req.tuition, 50000.0);
assert_eq!(req.tuition_currency, "USD");
assert_eq!(req.living_cost_monthly, Some(2000.0));
assert_eq!(req.duration_years, 4);
assert_eq!(req.home_currency, "CNY");
}
#[test]
fn test_fx_budget_request_no_living() {
let json = r#"{
"tuition": 10000.0,
"tuition_currency": "EUR",
"duration_years": 2,
"home_currency": "CNY"
}"#;
let req: FxBudgetRequest = serde_json::from_str(json).unwrap();
assert_eq!(req.living_cost_monthly, None);
}
#[test]
fn test_fx_pricing_request_deserialize() {
let json = r#"{
"cost_cny": 50.0,
"target_profit_rate": 0.3,
"currencies": "USD,EUR,GBP"
}"#;
let req: FxPricingRequest = serde_json::from_str(json).unwrap();
assert_eq!(req.cost_cny, 50.0);
assert_eq!(req.target_profit_rate, 0.3);
assert_eq!(req.currencies, "USD,EUR,GBP");
assert_eq!(req.platform_rate, 0.15); assert_eq!(req.safety_buffer, 0.05); }
#[test]
fn test_fx_pricing_request_custom_rates() {
let json = r#"{
"cost_cny": 100.0,
"target_profit_rate": 0.25,
"currencies": "USD",
"platform_rate": 0.10,
"safety_buffer": 0.03
}"#;
let req: FxPricingRequest = serde_json::from_str(json).unwrap();
assert_eq!(req.platform_rate, 0.10);
assert_eq!(req.safety_buffer, 0.03);
}
#[test]
fn test_fx_budget_validate_accepts_valid() {
let req = FxBudgetRequest {
tuition: 50000.0,
tuition_currency: "USD".into(),
living_cost_monthly: Some(2000.0),
duration_years: 4,
home_currency: "CNY".into(),
lang: None,
};
assert!(req.validate().is_ok());
}
#[test]
fn test_fx_budget_validate_rejects_zero_tuition() {
let req = FxBudgetRequest {
tuition: 0.0,
tuition_currency: "USD".into(),
living_cost_monthly: None,
duration_years: 2,
home_currency: "CNY".into(),
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_budget_validate_rejects_zero_duration() {
let req = FxBudgetRequest {
tuition: 50000.0,
tuition_currency: "USD".into(),
living_cost_monthly: None,
duration_years: 0,
home_currency: "CNY".into(),
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_budget_validate_rejects_invalid_currency() {
let req = FxBudgetRequest {
tuition: 50000.0,
tuition_currency: "USDX".into(), living_cost_monthly: None,
duration_years: 2,
home_currency: "CNY".into(),
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_pricing_validate_accepts_valid() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 0.3,
currencies: "USD,EUR".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
assert!(req.validate().is_ok());
}
#[test]
fn test_fx_pricing_validate_rejects_empty_currencies() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 0.3,
currencies: "".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_pricing_validate_rejects_too_many_currencies() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 0.3,
currencies: "USD,EUR,GBP,JPY,CNY,KRW,AUD,CAD,CHF,SGD,NZD".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_pricing_validate_rejects_profit_rate_one() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 1.0,
currencies: "USD".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_pricing_validate_rejects_negative_cost() {
let req = FxPricingRequest {
cost_cny: -10.0,
target_profit_rate: 0.3,
currencies: "USD".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
assert!(req.validate().is_err());
}
#[test]
fn test_fx_budget_response_serialize() {
let resp = FxBudgetResponse {
tuition_foreign: 50000.0,
tuition_currency: "USD".into(),
tuition_home: 362500.0,
home_currency: "CNY".into(),
rate: 7.25,
duration_years: 4,
annual_tuition_home: 90625.0,
living_monthly_home: Some(14500.0),
total_living_home: Some(696000.0),
total_cost_home: Some(1058500.0),
exchange_risk: ExchangeRiskResponse {
range: "1027345~1089655 CNY".into(),
note: "test".into(),
},
rate_date: Some("2026-09-13".into()),
rate_source: "test-frankfurter".into(),
};
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains(r#""tuition_foreign":50000.0"#));
assert!(json.contains(r#""tuition_currency":"USD""#));
assert!(json.contains(r#""exchange_risk""#));
assert!(json.contains(r#""rate_source":"test-frankfurter""#));
}
#[test]
fn test_fx_pricing_response_serialize() {
let resp = FxPricingResponse {
cost_cny: 50.0,
target_profit_rate: 0.3,
platform_rate: 0.15,
safety_buffer: 0.05,
pricing: vec![PricingItemResponse {
currency: "USD".into(),
recommended_price: 10.99,
actual_profit_rate: 0.287,
profit_cny: 14.35,
platform_fee_cny: 1.65,
}],
rate_date: Some("2026-09-13".into()),
rate_source: "test-frankfurter".into(),
};
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains(r#""cost_cny":50.0"#));
assert!(json.contains(r#""recommended_price":10.99"#));
assert!(json.contains(r#""currency":"USD""#));
assert!(json.contains(r#""rate_source":"test-frankfurter""#));
}
struct StaticProvider {
table: crate::math::fx::RateTable,
}
impl RateProvider for StaticProvider {
fn rates(&self) -> Result<crate::math::fx::RateTable, crate::core::CalcError> {
Ok(self.table.clone())
}
fn name(&self) -> &'static str {
"static"
}
}
fn static_provider(source: &str) -> Arc<dyn RateProvider> {
let mut rates = std::collections::HashMap::new();
rates.insert("USD".to_string(), 1.08);
rates.insert("CNY".to_string(), 7.85);
Arc::new(StaticProvider {
table: crate::math::fx::RateTable {
base: "EUR".into(),
date: "2026-09-13".into(),
rates,
source: source.into(),
},
})
}
#[tokio::test]
async fn test_fx_budget_response_rate_source_from_table() {
let req = FxBudgetRequest {
tuition: 50000.0,
tuition_currency: "USD".into(),
living_cost_monthly: Some(2000.0),
duration_years: 4,
home_currency: "CNY".into(),
lang: Some("en".into()),
};
let resp = run_fx_budget(
req,
Duration::from_secs(5),
static_provider("test-frankfurter"),
)
.await
.expect("static provider must succeed");
assert_eq!(resp.rate_source, "test-frankfurter");
assert_eq!(resp.rate_date.as_deref(), Some("2026-09-13"));
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains(r#""rate_source":"test-frankfurter""#));
}
#[tokio::test]
async fn test_fx_pricing_response_rate_source_from_table() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 0.3,
currencies: "USD,EUR".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: Some("en".into()),
};
let resp = run_fx_pricing(req, Duration::from_secs(5), static_provider("test-erapi"))
.await
.expect("static provider must succeed");
assert_eq!(resp.rate_source, "test-erapi");
assert_eq!(resp.rate_date.as_deref(), Some("2026-09-13"));
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains(r#""rate_source":"test-erapi""#));
}
struct SlowProvider {
delay: Duration,
}
impl RateProvider for SlowProvider {
fn rates(&self) -> Result<crate::math::fx::RateTable, crate::core::CalcError> {
std::thread::sleep(self.delay);
Err(crate::core::CalcError::dependency_unavailable(
"upstream stalled",
))
}
fn name(&self) -> &'static str {
"slow"
}
}
#[tokio::test]
async fn test_fx_budget_timeout_returns_503() {
let req = FxBudgetRequest {
tuition: 50000.0,
tuition_currency: "USD".into(),
living_cost_monthly: None,
duration_years: 4,
home_currency: "CNY".into(),
lang: None,
};
let provider: Arc<dyn RateProvider> = Arc::new(SlowProvider {
delay: Duration::from_secs(5),
});
let err = run_fx_budget(req, Duration::from_secs(1), provider)
.await
.expect_err("slow provider must hit request timeout");
match err {
ApiError::ServiceUnavailable {
service,
retry_after,
..
} => {
assert_eq!(service, "fx_budget");
assert_eq!(retry_after, Some(1));
}
other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
}
}
#[tokio::test]
async fn test_fx_pricing_timeout_returns_503() {
let req = FxPricingRequest {
cost_cny: 50.0,
target_profit_rate: 0.3,
currencies: "USD,EUR".into(),
platform_rate: 0.15,
safety_buffer: 0.05,
lang: None,
};
let provider: Arc<dyn RateProvider> = Arc::new(SlowProvider {
delay: Duration::from_secs(5),
});
let err = run_fx_pricing(req, Duration::from_secs(1), provider)
.await
.expect_err("slow provider must hit request timeout");
match err {
ApiError::ServiceUnavailable {
service,
retry_after,
..
} => {
assert_eq!(service, "fx_pricing");
assert_eq!(retry_after, Some(1));
}
other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
}
}
#[test]
fn test_shared_provider_returns_same_instance() {
let p1 = shared_provider();
let p2 = shared_provider();
assert!(
Arc::ptr_eq(&p1, &p2),
"shared_provider should return same instance"
);
}
}