1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! 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>,
}