use crate::core::CalcError;
use crate::math::fx::{RateTable, convert};
#[derive(Clone, Debug, PartialEq)]
pub struct BudgetResult {
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,
pub living_monthly_foreign: Option<f64>,
pub living_monthly_home: Option<f64>,
pub total_living_home: Option<f64>,
pub total_cost_home: Option<f64>,
pub exchange_risk: ExchangeRisk,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExchangeRisk {
pub low: f64,
pub high: f64,
pub currency: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PricingItem {
pub currency: String,
pub recommended_price: f64,
pub actual_profit_rate: f64,
pub profit_cny: f64,
pub platform_fee_cny: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PricingResult {
pub cost_cny: f64,
pub pricing: Vec<PricingItem>,
}
pub fn budget_calculation(
tuition: f64,
tuition_currency: &str,
living_cost_monthly: Option<f64>,
duration_years: u32,
home_currency: &str,
table: &RateTable,
) -> Result<BudgetResult, CalcError> {
if tuition <= 0.0 {
return Err(CalcError::domain("tuition must be positive".to_string())
.with_i18n("msg.fxscenario.tuition_positive", vec![]));
}
if duration_years == 0 || duration_years > 10 {
return Err(
CalcError::domain("duration_years must be between 1 and 10".to_string())
.with_i18n("msg.fxscenario.duration_range", vec![]),
);
}
let rate = convert(1.0, tuition_currency, home_currency, table)?;
let tuition_home = convert(tuition, tuition_currency, home_currency, table)?;
let annual_tuition_home = tuition_home / duration_years as f64;
let (living_monthly_home, total_living_home, total_cost_home) = match living_cost_monthly {
Some(monthly) if monthly > 0.0 => {
let monthly_home = convert(monthly, tuition_currency, home_currency, table)?;
let total_living = monthly_home * 12.0 * duration_years as f64;
let total = tuition_home + total_living;
(Some(monthly_home), Some(total_living), Some(total))
}
_ => (None, None, None),
};
let base_for_risk = total_cost_home.unwrap_or(tuition_home);
let exchange_risk = ExchangeRisk {
low: base_for_risk * 0.97,
high: base_for_risk * 1.03,
currency: home_currency.to_string(),
};
Ok(BudgetResult {
tuition_foreign: tuition,
tuition_currency: tuition_currency.to_string(),
tuition_home,
home_currency: home_currency.to_string(),
rate,
duration_years,
annual_tuition_home,
living_monthly_foreign: living_cost_monthly,
living_monthly_home,
total_living_home,
total_cost_home,
exchange_risk,
})
}
pub fn pricing_calculation(
cost_cny: f64,
target_profit_rate: f64,
currencies: &[&str],
platform_rate: f64,
safety_buffer: f64,
table: &RateTable,
) -> Result<PricingResult, CalcError> {
if cost_cny <= 0.0 {
return Err(CalcError::domain("cost_cny must be positive".to_string())
.with_i18n("msg.fxscenario.cost_positive", vec![]));
}
if target_profit_rate <= 0.0 || target_profit_rate >= 1.0 {
return Err(CalcError::domain(
"target_profit_rate must be between 0 and 1 (exclusive)".to_string(),
)
.with_i18n("msg.fxscenario.profit_rate_range", vec![]));
}
if !(0.0..1.0).contains(&platform_rate) {
return Err(
CalcError::domain("platform_rate must be in [0, 1)".to_string())
.with_i18n("msg.fxscenario.platform_rate_range", vec![]),
);
}
if !(0.0..=0.5).contains(&safety_buffer) {
return Err(
CalcError::domain("safety_buffer must be in [0, 0.5]".to_string())
.with_i18n("msg.fxscenario.safety_buffer_range", vec![]),
);
}
if currencies.is_empty() {
return Err(
CalcError::domain("currencies list must not be empty".to_string())
.with_i18n("msg.fxscenario.currencies_empty", vec![]),
);
}
if currencies.len() > 10 {
return Err(
CalcError::domain("currencies list must not exceed 10 items".to_string())
.with_i18n("msg.fxscenario.currencies_too_many", vec![]),
);
}
let mut pricing = Vec::with_capacity(currencies.len());
for &cur in currencies {
let one_foreign_in_cny = convert(1.0, cur, "CNY", table)?;
let safe_rate = one_foreign_in_cny * (1.0 - safety_buffer);
let target_revenue_cny = cost_cny / (1.0 - target_profit_rate);
let price_foreign = target_revenue_cny / safe_rate / (1.0 - platform_rate);
let gross_cny = price_foreign * one_foreign_in_cny;
let platform_fee_cny = gross_cny * platform_rate;
let net_cny = gross_cny - platform_fee_cny;
let profit_cny = net_cny - cost_cny;
let actual_profit_rate = profit_cny / cost_cny;
pricing.push(PricingItem {
currency: cur.to_string(),
recommended_price: (price_foreign * 100.0).round() / 100.0, actual_profit_rate: (actual_profit_rate * 10000.0).round() / 10000.0, profit_cny: (profit_cny * 100.0).round() / 100.0,
platform_fee_cny: (platform_fee_cny * 100.0).round() / 100.0,
});
}
Ok(PricingResult { cost_cny, pricing })
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn mock_table() -> RateTable {
let mut rates = HashMap::new();
rates.insert("USD".to_string(), 1.08);
rates.insert("CNY".to_string(), 7.85);
rates.insert("GBP".to_string(), 0.85);
rates.insert("JPY".to_string(), 165.0);
RateTable {
base: "EUR".to_string(),
date: "2026-08-10".to_string(),
rates,
source: "frankfurter".to_string(),
}
}
#[test]
fn test_budget_happy_path_with_living() {
let table = mock_table();
let result = budget_calculation(50000.0, "USD", Some(2000.0), 4, "CNY", &table).unwrap();
let expected_rate = 1.0 / 1.08 * 7.85;
assert!((result.rate - expected_rate).abs() < 1e-6, "rate mismatch");
let expected_tuition_home = 50000.0 / 1.08 * 7.85;
assert!(
(result.tuition_home - expected_tuition_home).abs() < 0.01,
"tuition_home mismatch"
);
assert!((result.annual_tuition_home - expected_tuition_home / 4.0).abs() < 0.01);
let expected_monthly_home = 2000.0 / 1.08 * 7.85;
assert!((result.living_monthly_home.unwrap() - expected_monthly_home).abs() < 0.01);
let expected_total_living = expected_monthly_home * 12.0 * 4.0;
assert!((result.total_living_home.unwrap() - expected_total_living).abs() < 0.01);
let expected_total = expected_tuition_home + expected_total_living;
assert!((result.total_cost_home.unwrap() - expected_total).abs() < 0.01);
assert!((result.exchange_risk.low - expected_total * 0.97).abs() < 0.01);
assert!((result.exchange_risk.high - expected_total * 1.03).abs() < 0.01);
assert_eq!(result.exchange_risk.currency, "CNY");
}
#[test]
fn test_budget_tuition_only_no_living() {
let table = mock_table();
let result = budget_calculation(10000.0, "USD", None, 1, "CNY", &table).unwrap();
assert!(result.living_monthly_home.is_none());
assert!(result.total_living_home.is_none());
assert!(result.total_cost_home.is_none());
let tuition_home = 10000.0 / 1.08 * 7.85;
assert!((result.exchange_risk.low - tuition_home * 0.97).abs() < 0.01);
}
#[test]
fn test_budget_same_currency_identity() {
let table = mock_table();
let result = budget_calculation(50000.0, "USD", None, 2, "USD", &table).unwrap();
assert!(
(result.rate - 1.0).abs() < 1e-9,
"same currency rate should be 1.0"
);
assert!((result.tuition_home - 50000.0).abs() < 1e-9);
assert!((result.annual_tuition_home - 25000.0).abs() < 1e-9);
}
#[test]
fn test_budget_unknown_currency_error() {
let table = mock_table();
let result = budget_calculation(50000.0, "XYZ", None, 2, "CNY", &table);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
}
#[test]
fn test_budget_zero_duration_error() {
let table = mock_table();
let result = budget_calculation(50000.0, "USD", None, 0, "CNY", &table);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
}
#[test]
fn test_budget_zero_tuition_error() {
let table = mock_table();
let result = budget_calculation(0.0, "USD", None, 2, "CNY", &table);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind, crate::core::ErrorKind::Domain);
}
#[test]
fn test_budget_duration_exceeds_max_error() {
let table = mock_table();
let result = budget_calculation(50000.0, "USD", None, 11, "CNY", &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_happy_path_single_currency() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.3, &["USD"], 0.15, 0.05, &table).unwrap();
assert_eq!(result.cost_cny, 50.0);
assert_eq!(result.pricing.len(), 1);
let item = &result.pricing[0];
assert_eq!(item.currency, "USD");
assert!(item.recommended_price > 0.0);
assert!(
item.actual_profit_rate >= 0.3,
"actual profit rate {} should be >= target 0.3 (safety buffer)",
item.actual_profit_rate
);
assert!(item.profit_cny > 0.0);
assert!(item.platform_fee_cny > 0.0);
}
#[test]
fn test_pricing_multi_currency() {
let table = mock_table();
let result =
pricing_calculation(100.0, 0.25, &["USD", "EUR", "GBP"], 0.10, 0.05, &table).unwrap();
assert_eq!(result.pricing.len(), 3);
for item in &result.pricing {
assert!(item.recommended_price > 0.0);
assert!(item.profit_cny > 0.0);
}
}
#[test]
fn test_pricing_zero_cost_error() {
let table = mock_table();
let result = pricing_calculation(0.0, 0.3, &["USD"], 0.15, 0.05, &table);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind, crate::core::ErrorKind::Domain);
}
#[test]
fn test_pricing_negative_cost_error() {
let table = mock_table();
let result = pricing_calculation(-10.0, 0.3, &["USD"], 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_profit_rate_zero_error() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.0, &["USD"], 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_profit_rate_one_error() {
let table = mock_table();
let result = pricing_calculation(50.0, 1.0, &["USD"], 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_empty_currencies_error() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.3, &[], 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_too_many_currencies_error() {
let table = mock_table();
let currencies: Vec<&str> = (0..11).map(|_| "USD").collect();
let result = pricing_calculation(50.0, 0.3, ¤cies, 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_unknown_currency_error() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.3, &["XYZ"], 0.15, 0.05, &table);
assert!(result.is_err());
}
#[test]
fn test_pricing_zero_platform_rate() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.3, &["USD"], 0.0, 0.05, &table).unwrap();
assert_eq!(result.pricing[0].platform_fee_cny, 0.0);
}
#[test]
fn test_pricing_zero_safety_buffer() {
let table = mock_table();
let result = pricing_calculation(50.0, 0.3, &["USD"], 0.15, 0.0, &table).unwrap();
assert!(result.pricing[0].recommended_price > 0.0);
}
}