delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Stored shop risk indexes, per connector.
//!
//! Every read returns a snapshot and never scores on demand, so
//! `computed_at` is the age of the answer rather than the time of the call.
//! The detailed breakdowns (components, settings snapshot, the adjusted
//! assessment) are kept as raw JSON: their shape follows the scoring model
//! version.
//!
//! The merchant's own tuning of its adjusted assessment is here too:
//! [`RiskAdjustments`] is both what a tuning read returns and what a save or
//! preview sends.

use std::collections::BTreeMap;

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

use crate::core::models::settings::SettingActor;

/// Every shop's stored risk for the caller's merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantRiskResponse {
    /// The merchant.
    pub merchant_id: String,
    /// The worst band across every shop and connector, or `None` when nothing
    /// has been scored. `insufficient_data` never wins this comparison.
    #[serde(default)]
    pub worst_band: Option<String>,
    /// The shops, worst first, then by index within a band.
    #[serde(default)]
    pub shops: Vec<ShopRiskResponse>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One shop's stored risk across the connectors it processes on.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopRiskResponse {
    /// The shop (business profile).
    pub shop_id: String,
    /// The newest `computed_at` across the shop's connectors, or `None` when
    /// the shop has never been scored.
    #[serde(default)]
    pub computed_at: Option<String>,
    /// One entry per connector. Empty means "not assessed", which is not the
    /// same as "no risk".
    #[serde(default)]
    pub connectors: Vec<ConnectorRisk>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One connector's stored risk in one shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorRisk {
    /// The connector.
    pub connector: String,
    /// `healthy`, `watch`, `at_risk`, `critical` or `insufficient_data`.
    pub band: String,
    /// 0 to 100; `None` when the band is `insufficient_data`.
    #[serde(default)]
    pub index: Option<i64>,
    /// `up`, `down` or `flat` against the previous snapshot.
    #[serde(default)]
    pub trend: Option<String>,
    /// The scoring model that produced the snapshot.
    pub model_version: i64,
    /// When the snapshot was computed, ISO 8601.
    pub computed_at: String,
    /// The component breakdown.
    #[serde(default)]
    pub components: Value,
    /// What the scoring pass could not measure.
    #[serde(default)]
    pub unmeasured: Option<Value>,
    /// The settings and readings the snapshot was scored with.
    #[serde(default)]
    pub settings_snapshot: Option<Value>,
    /// `reference`: DeloPay's own assessment.
    pub assessment: String,
    /// Whether the snapshot `trend` compares against was scored under another
    /// policy.
    #[serde(default)]
    pub policy_changed: Option<bool>,
    /// The merchant-adjusted assessment, when the merchant tunes its risk.
    #[serde(default)]
    pub adjusted: Option<Value>,
    /// Why the adjusted assessment is missing, in its place.
    #[serde(default)]
    pub adjusted_unavailable: Option<AdjustedRiskUnavailable>,
    /// Card-testing bursts detected on the connector.
    #[serde(default)]
    pub card_testing_incidents: Vec<RiskCardTestingIncident>,
    /// The provider warnings the snapshot took into account.
    #[serde(default)]
    pub provider_warnings: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Why a connector has no adjusted assessment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AdjustedRiskUnavailable {
    /// Why.
    pub reason: String,
    /// The settings revision of the newest adjustment that applies.
    pub adjustment_revision: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A card-testing burst detected on a connector.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskCardTestingIncident {
    /// The first stretch's start, ISO 8601.
    pub started_at: String,
    /// The last stretch's end, exclusive, ISO 8601.
    pub ended_at: String,
    /// The detection window, in minutes.
    pub window_minutes: i64,
    /// Card attempts inside the burst.
    pub attempts: i64,
    /// Refused card attempts inside the burst.
    pub refusals: i64,
    /// Different cards among the refusals, when known.
    #[serde(default)]
    pub distinct_cards: Option<i64>,
    /// The thresholds the burst met.
    #[serde(default)]
    pub thresholds: Value,
    /// The risk model version the thresholds came from.
    pub model_version: i64,
    /// When the burst was first detected, ISO 8601.
    pub first_detected_at: String,
    /// When the burst was last detected, ISO 8601.
    pub last_detected_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Where each band begins on the 0 to 100 index. The three values must
/// ascend and stay within 100.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RiskBands {
    /// Where `watch` begins.
    pub watch: i64,
    /// Where `at_risk` begins.
    pub at_risk: i64,
    /// Where `critical` begins.
    pub critical: i64,
}

impl RiskBands {
    /// Bands beginning at `watch`, `at_risk` and `critical`.
    pub fn new(watch: i64, at_risk: i64, critical: i64) -> Self {
        Self {
            watch,
            at_risk,
            critical,
        }
    }
}

/// One window's band boundaries, overridden together. A window left `None`
/// inherits its complete boundary set.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RiskWindowBandOverrides {
    /// The 30-day window.
    #[serde(rename = "30d", default, skip_serializing_if = "Option::is_none")]
    pub d30: Option<RiskBands>,
    /// The 60-day window.
    #[serde(rename = "60d", default, skip_serializing_if = "Option::is_none")]
    pub d60: Option<RiskBands>,
    /// The 90-day window.
    #[serde(rename = "90d", default, skip_serializing_if = "Option::is_none")]
    pub d90: Option<RiskBands>,
}

/// A change to one component's rule. A part left `None` keeps the reference
/// model's value, which may differ per connector.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct RiskComponentAdjustment {
    /// The rate at which the component is at its limit, as a fraction
    /// (`0.0075` is 0.75%), for every connector. Must be greater than zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
    /// How much the component counts relative to the others, for every
    /// connector. Zero switches it off in the adjusted assessment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub weight: Option<f64>,
}

/// One merchant, project or shop's adjustments of how its risk is scored.
///
/// They feed only the merchant-adjusted assessment, never DeloPay's
/// reference assessment. Each part left absent inherits from the next scope
/// up (shop, then project, then merchant), and finally from the reference
/// settings.
///
/// `extra` keeps fields this SDK version does not know, so a tuning read and
/// saved back keeps them. The API refuses a field it does not know, so put
/// nothing in `extra` yourself.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct RiskAdjustments {
    /// The window that decides the band: `30d`, `60d`, `90d`, `worst_of` or
    /// `best_of`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deciding_window: Option<String>,
    /// Band boundaries per window.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bands: Option<RiskWindowBandOverrides>,
    /// The fewest payments a window needs to be scored, at least 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_volume: Option<i64>,
    /// Changes to component rules, keyed by component name, for example
    /// `dispute_rate` or `refund_rate`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub components: BTreeMap<String, RiskComponentAdjustment>,
    /// Fields not modeled above, kept as the API sent them.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl RiskAdjustments {
    /// No adjustments: everything inherits.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the window that decides the band.
    #[must_use]
    pub fn deciding_window(mut self, window: impl Into<String>) -> Self {
        self.deciding_window = Some(window.into());
        self
    }

    /// Override the band boundaries.
    #[must_use]
    pub fn bands(mut self, bands: RiskWindowBandOverrides) -> Self {
        self.bands = Some(bands);
        self
    }

    /// Set the fewest payments a window needs to be scored.
    #[must_use]
    pub fn min_volume(mut self, min_volume: i64) -> Self {
        self.min_volume = Some(min_volume);
        self
    }

    /// Change one component's rule.
    #[must_use]
    pub fn component(
        mut self,
        name: impl Into<String>,
        adjustment: RiskComponentAdjustment,
    ) -> Self {
        self.components.insert(name.into(), adjustment);
        self
    }
}

/// One scope's risk tuning: what it sets, what applies there and where each
/// part comes from, and DeloPay's reference beside it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskTuningResponse {
    /// `merchant`, `project` or `shop`.
    pub scope: String,
    /// The merchant, project or shop id.
    pub scope_id: String,
    /// What this scope sets itself. Empty when it inherits everything.
    #[serde(default)]
    pub adjustments: RiskAdjustments,
    /// Send it back as `expected_revision` with the next save or reset.
    pub revision: i64,
    /// When the tuning last changed, ISO 8601.
    #[serde(default)]
    pub updated_at: Option<String>,
    /// Who last changed it.
    #[serde(default)]
    pub updated_by: Option<SettingActor>,
    /// DeloPay's reference model and settings.
    #[serde(default)]
    pub reference: Option<Value>,
    /// What applies at this scope, and where each part comes from.
    #[serde(default)]
    pub effective: Option<Value>,
    /// Why the effective tuning cannot be used, when it cannot.
    #[serde(default)]
    pub unusable_reason: Option<String>,
    /// Whether the adjusted assessments are still being recomputed after a
    /// change.
    pub recompute_pending: bool,
    /// How long the last recompute took, in milliseconds.
    #[serde(default)]
    pub recompute_duration_ms: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A band and index estimated from stored evidence.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskTuningEstimate {
    /// `healthy`, `watch`, `at_risk`, `critical` or `insufficient_data`.
    pub band: String,
    /// The 0 to 100 index, when there is one.
    #[serde(default)]
    pub risk_index: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The estimate for one shop on one connector.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskTuningPreviewConnector {
    /// The connector.
    pub connector: String,
    /// DeloPay's reference assessment, which the tuning never changes.
    #[serde(default)]
    pub reference: Option<RiskTuningEstimate>,
    /// The adjusted assessment under the tuning in force now.
    #[serde(default)]
    pub current: Option<RiskTuningEstimate>,
    /// The adjusted assessment if the change is saved.
    #[serde(default)]
    pub proposed: Option<RiskTuningEstimate>,
    /// Why there is no estimate, for example `no_evidence`.
    #[serde(default)]
    pub unavailable: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The estimates for one shop a change reaches.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskTuningPreviewShop {
    /// The shop.
    pub shop_id: String,
    /// One estimate per connector.
    #[serde(default)]
    pub connectors: Vec<RiskTuningPreviewConnector>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a change to one scope's tuning would do. Nothing was stored or
/// scored.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RiskTuningPreviewResponse {
    /// `merchant`, `project` or `shop`.
    pub scope: String,
    /// The merchant, project or shop id.
    pub scope_id: String,
    /// Every shop the change reaches.
    #[serde(default)]
    pub shops: Vec<RiskTuningPreviewShop>,
    /// The day the estimate reads evidence up to, inclusive (`YYYY-MM-DD`).
    pub evidence_until: String,
    /// The reference model version the estimate uses.
    pub model_version: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}