inttegro 0.8.0

Official server-side Rust SDK for Inttegro
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

const CUSTOM_DATA_MAX_KEY_BYTES: usize = 256;
const CUSTOM_DATA_MAX_BYTES: usize = 25 * 1024;

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SemanticCollectionError {
    #[error("custom-data key must be at most 256 UTF-8 bytes: {0}")]
    CustomDataKeyTooLong(String),
    #[error("custom data must encode to at most 25 KiB")]
    CustomDataTooLarge,
}

/// Merchant-defined string values with validated, controlled mutation.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct CustomData(BTreeMap<String, String>);

impl CustomData {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn try_from_values(
        values: impl IntoIterator<Item = (String, String)>,
    ) -> Result<Self, SemanticCollectionError> {
        let value = Self(values.into_iter().collect());
        value.validate()?;
        Ok(value)
    }

    pub fn insert(
        &mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Option<String>, SemanticCollectionError> {
        let key = key.into();
        let previous = self.0.insert(key.clone(), value.into());
        if let Err(error) = self.validate() {
            match previous.as_ref() {
                Some(previous) => {
                    self.0.insert(key, previous.clone());
                }
                None => {
                    self.0.remove(&key);
                }
            }
            return Err(error);
        }
        Ok(previous)
    }

    pub fn remove(&mut self, key: &str) -> Option<String> {
        self.0.remove(key)
    }

    pub fn get(&self, key: &str) -> Option<&str> {
        self.0.get(key).map(String::as_str)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
        self.0.iter()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    fn validate(&self) -> Result<(), SemanticCollectionError> {
        if let Some(key) = self
            .0
            .keys()
            .find(|key| key.len() > CUSTOM_DATA_MAX_KEY_BYTES)
        {
            return Err(SemanticCollectionError::CustomDataKeyTooLong(key.clone()));
        }
        if serde_json::to_vec(&self.0)
            .expect("string maps are always JSON encodable")
            .len()
            > CUSTOM_DATA_MAX_BYTES
        {
            return Err(SemanticCollectionError::CustomDataTooLarge);
        }
        Ok(())
    }
}

impl<'de> Deserialize<'de> for CustomData {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Self(BTreeMap::deserialize(deserializer)?);
        value.validate().map_err(D::Error::custom)?;
        Ok(value)
    }
}

/// Merchant-defined JSON values accepted by create operations.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(transparent)]
pub struct CustomDataInput(BTreeMap<String, Value>);

impl CustomDataInput {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(
        &mut self,
        key: impl Into<String>,
        value: impl Serialize,
    ) -> Result<Option<Value>, SemanticCollectionError> {
        let key = key.into();
        let value = serde_json::to_value(value).expect("serializable values produce JSON");
        let previous = self.0.insert(key.clone(), value);
        if let Err(error) = validate_json_custom_data(&self.0) {
            match previous.as_ref() {
                Some(previous) => {
                    self.0.insert(key, previous.clone());
                }
                None => {
                    self.0.remove(&key);
                }
            }
            return Err(error);
        }
        Ok(previous)
    }

    pub fn remove(&mut self, key: &str) -> Option<Value> {
        self.0.remove(key)
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &Value)> {
        self.0.iter()
    }
}

impl<'de> Deserialize<'de> for CustomDataInput {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Self(BTreeMap::deserialize(deserializer)?);
        validate_json_custom_data(&value.0).map_err(D::Error::custom)?;
        Ok(value)
    }
}

/// A custom-data update. JSON `null` explicitly removes a key.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(transparent)]
pub struct CustomDataPatch(BTreeMap<String, Value>);

impl CustomDataPatch {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn set(
        &mut self,
        key: impl Into<String>,
        value: impl Serialize,
    ) -> Result<Option<Value>, SemanticCollectionError> {
        let key = key.into();
        let value = serde_json::to_value(value).expect("serializable values produce JSON");
        self.insert_validated(key, value)
    }

    pub fn unset(
        &mut self,
        key: impl Into<String>,
    ) -> Result<Option<Value>, SemanticCollectionError> {
        self.insert_validated(key.into(), Value::Null)
    }

    pub fn remove_change(&mut self, key: &str) -> Option<Value> {
        self.0.remove(key)
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    fn insert_validated(
        &mut self,
        key: String,
        value: Value,
    ) -> Result<Option<Value>, SemanticCollectionError> {
        let previous = self.0.insert(key.clone(), value);
        if let Err(error) = validate_json_custom_data(&self.0) {
            match previous.as_ref() {
                Some(previous) => {
                    self.0.insert(key, previous.clone());
                }
                None => {
                    self.0.remove(&key);
                }
            }
            return Err(error);
        }
        Ok(previous)
    }
}

impl<'de> Deserialize<'de> for CustomDataPatch {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Self(BTreeMap::deserialize(deserializer)?);
        validate_json_custom_data(&value.0).map_err(D::Error::custom)?;
        Ok(value)
    }
}

fn validate_json_custom_data(
    values: &BTreeMap<String, Value>,
) -> Result<(), SemanticCollectionError> {
    if let Some(key) = values
        .keys()
        .find(|key| key.len() > CUSTOM_DATA_MAX_KEY_BYTES)
    {
        return Err(SemanticCollectionError::CustomDataKeyTooLong(key.clone()));
    }
    if serde_json::to_vec(values)
        .expect("JSON values are always JSON encodable")
        .len()
        > CUSTOM_DATA_MAX_BYTES
    {
        return Err(SemanticCollectionError::CustomDataTooLarge);
    }
    Ok(())
}

macro_rules! string_collection {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(BTreeMap<String, String>);

        impl $name {
            pub fn new() -> Self {
                Self::default()
            }

            pub fn insert(
                &mut self,
                key: impl Into<String>,
                value: impl Into<String>,
            ) -> Option<String> {
                self.0.insert(key.into(), value.into())
            }

            pub fn remove(&mut self, key: &str) -> Option<String> {
                self.0.remove(key)
            }

            pub fn get(&self, key: &str) -> Option<&str> {
                self.0.get(key).map(String::as_str)
            }

            pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
                self.0.iter()
            }
        }
    };
}

string_collection!(
    FileMetadata,
    "Metadata attached to a file or upload request."
);
string_collection!(MessageHeaders, "Message headers keyed by header name.");
string_collection!(
    ProductDimensionDetails,
    "Custom product-dimension details keyed by attribute name."
);

/// Financial accounts configured to receive payouts in supported currencies.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayoutDestinations {
    /// Financial account that receives Ghana cedi payouts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ghs: Option<String>,
}
string_collection!(
    VariantValues,
    "Selected product variant values keyed by attribute name."
);

/// An intentionally open JSON object whose schema belongs to an external system.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct JsonData(BTreeMap<String, Value>);

impl JsonData {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, key: impl Into<String>, value: impl Serialize) -> Option<Value> {
        self.0.insert(
            key.into(),
            serde_json::to_value(value).expect("serializable values produce JSON"),
        )
    }

    pub fn remove(&mut self, key: &str) -> Option<Value> {
        self.0.remove(key)
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &Value)> {
        self.0.iter()
    }
}

/// A Dosh financial account. The API v1 representation is intentionally empty.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DoshAccount {}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FinancialAccountVerificationRequest {
    pub id: Option<String>,
    pub mechanism: Option<String>,
    #[serde(rename = "type")]
    pub kind: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FinancialAccountVerification {
    pub initiated_at: crate::Timestamp,
    pub completed_at: Option<crate::Timestamp>,
    pub request: FinancialAccountVerificationRequest,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderPayoutDestination {
    pub financial_account_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderPayoutSettings {
    pub destination: Option<OrderPayoutDestination>,
    pub enable_fx: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Address {
    pub name: String,
    pub phone_number: String,
    pub line1: String,
    pub line2: Option<String>,
    pub town: String,
    pub region: Option<String>,
    pub district: Option<String>,
    pub country: String,
    pub post_code: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Shipping {
    pub address: Address,
}

/// Customer balances keyed by currency.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CustomerBalance(BTreeMap<String, crate::CustomerBalanceValue>);

impl CustomerBalance {
    pub fn get(&self, currency: &str) -> Option<&crate::CustomerBalanceValue> {
        self.0.get(currency)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &crate::CustomerBalanceValue)> {
        self.0.iter()
    }
}

/// Country capabilities keyed by lowercase country code.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CountrySpecifications(BTreeMap<String, crate::CountrySpecification>);

impl CountrySpecifications {
    pub fn get(&self, country_code: &str) -> Option<&crate::CountrySpecification> {
        self.0.get(country_code)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &crate::CountrySpecification)> {
        self.0.iter()
    }
}