delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Fee models: flat fee schedules and the stored Euclid fee-rule program.
//!
//! [`FeeType`] and [`FeeOwner`] live here rather than in `resources` because
//! they appear on both the request and the response side, and the response
//! side must stay available in the `default-features = false` build.
//!
//! The Euclid program itself ([`PlatformFeeRuleRecord::algorithm`]) is left as
//! raw JSON: the typed program AST is a request-building convenience that
//! lives in the client-gated `resources` layer, and `core` must not depend on
//! it.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::models::common::Currency;

/// How a fee schedule prices a transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeeType {
    /// A percentage of the transaction amount.
    Percentage,
    /// A fixed amount in minor units.
    Flat,
    /// Percentage plus flat amount.
    Combined,
}

/// Who owns a fee schedule or fee-rule program.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeeOwner {
    /// Set by Delopay, platform-wide.
    Platform,
    /// Set by the merchant, overriding the platform default.
    Merchant,
}

/// A stored fee schedule, as returned by the fee-schedule endpoints.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeScheduleResponse {
    /// Unique fee schedule ID.
    pub id: String,
    /// Merchant account the schedule belongs to.
    pub merchant_id: String,
    /// How the schedule prices a transaction.
    pub fee_type: FeeType,
    /// Whether the schedule is currently active.
    pub is_active: bool,
    /// Who owns the schedule.
    pub fee_owner: FeeOwner,

    /// Shop (business profile) the schedule is restricted to, if any.
    #[serde(default)]
    pub shop_id: Option<String>,
    /// Percentage fee — `2.5` means 2.5%.
    #[serde(default)]
    pub percentage_fee: Option<f64>,
    /// Flat fee, in minor units.
    #[serde(default)]
    pub flat_fee_amount: Option<i64>,
    /// Currency of [`flat_fee_amount`](Self::flat_fee_amount).
    #[serde(default)]
    pub flat_fee_currency: Option<Currency>,
    /// Floor for the computed fee, in minor units.
    #[serde(default)]
    pub min_fee_amount: Option<i64>,
    /// Cap for the computed fee, in minor units.
    #[serde(default)]
    pub max_fee_amount: Option<i64>,
    /// Free-text description of the schedule.
    #[serde(default)]
    pub description: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A stored Euclid fee-rule program: the active version for one scope
/// (merchant-wide, or a single shop).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PlatformFeeRuleRecord {
    /// Human-readable program name.
    pub name: String,
    /// Who owns the program.
    pub fee_owner: FeeOwner,
    /// The Euclid program, echoed back verbatim.
    ///
    /// Raw JSON on purpose: the typed program AST is a request-side builder in
    /// the client-gated `resources` layer, which `core` cannot reference.
    /// Deserialize it yourself if you need the tree.
    pub algorithm: Value,

    /// Creation time, in whole seconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Last-modified time, in whole seconds since the Unix epoch.
    #[serde(default)]
    pub modified_at: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The outcome of dry-running a candidate fee-rule program against a sample
/// transaction. Persists nothing.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeRulePreviewResponse {
    /// True when the matched branch sets no concrete fee, so the engine falls
    /// through to the legacy schedule/tier chain.
    pub fell_through: bool,

    /// Name of the matched rule, or `None` when only the default selection
    /// matched.
    #[serde(default)]
    pub matched_rule: Option<String>,
    /// Computed fee in minor units, or `None` when it fell through.
    #[serde(default)]
    pub fee_amount: Option<i64>,
    /// Currency of [`fee_amount`](Self::fee_amount).
    #[serde(default)]
    pub fee_currency: Option<Currency>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fee_schedule_decodes_its_enums_and_keeps_unknown_fields() {
        let schedule: FeeScheduleResponse = serde_json::from_str(
            r#"{
                "id": "fee_1",
                "merchant_id": "merch_1",
                "fee_type": "combined",
                "is_active": true,
                "fee_owner": "merchant",
                "shop_id": "pro_1",
                "percentage_fee": 2.5,
                "flat_fee_amount": 30,
                "flat_fee_currency": "USD",
                "brand_new_field": "keep me"
            }"#,
        )
        .unwrap();

        // Pins the wire spelling: renaming the variant or dropping
        // `rename_all = "snake_case"` makes this fail.
        assert_eq!(schedule.fee_type, FeeType::Combined);
        assert_eq!(schedule.fee_owner, FeeOwner::Merchant);
        assert_eq!(schedule.percentage_fee, Some(2.5));
        assert_eq!(schedule.flat_fee_amount, Some(30));
        assert_eq!(schedule.min_fee_amount, None);
        assert_eq!(schedule.extra["brand_new_field"], "keep me");
    }

    #[test]
    fn fee_type_round_trips_through_its_wire_spelling() {
        for (variant, wire) in [
            (FeeType::Percentage, "\"percentage\""),
            (FeeType::Flat, "\"flat\""),
            (FeeType::Combined, "\"combined\""),
        ] {
            assert_eq!(serde_json::to_string(&variant).unwrap(), wire);
            assert_eq!(serde_json::from_str::<FeeType>(wire).unwrap(), variant);
        }
        assert_eq!(
            serde_json::to_string(&FeeOwner::Platform).unwrap(),
            "\"platform\""
        );
    }

    #[test]
    fn fee_rule_record_keeps_the_program_as_raw_json() {
        let record: PlatformFeeRuleRecord = serde_json::from_str(
            r#"{
                "name": "standard",
                "fee_owner": "merchant",
                "algorithm": {"defaultSelection": {}, "rules": [], "metadata": {}},
                "created_at": 1767225600,
                "modified_at": 1767312000
            }"#,
        )
        .unwrap();

        assert_eq!(record.name, "standard");
        assert_eq!(record.fee_owner, FeeOwner::Merchant);
        assert_eq!(record.created_at, Some(1767225600));
        assert_eq!(record.algorithm["rules"], serde_json::json!([]));
    }

    #[test]
    fn preview_response_decodes_a_fall_through() {
        let preview: FeeRulePreviewResponse = serde_json::from_str(
            r#"{"matched_rule":null,"fell_through":true,"fee_amount":null,"fee_currency":null}"#,
        )
        .unwrap();
        assert!(preview.fell_through);
        assert_eq!(preview.matched_rule, None);
        assert_eq!(preview.fee_amount, None);

        let matched: FeeRulePreviewResponse = serde_json::from_str(
            r#"{"matched_rule":"crypto","fell_through":false,"fee_amount":125,"fee_currency":"USD"}"#,
        )
        .unwrap();
        assert_eq!(matched.matched_rule.as_deref(), Some("crypto"));
        assert_eq!(matched.fee_amount, Some(125));
        assert_eq!(matched.fee_currency.as_deref(), Some("USD"));
    }
}