Skip to main content

pain001_sdk/
types.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! Request and response shapes, from `conformance/openapi.json`.
3//!
4//! Response structs are `#[non_exhaustive]` so a field the server adds
5//! later is not a breaking change here.
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9
10/// The ISO 20022 message types the server generates and validates.
11///
12/// Methods take `impl AsRef<str>`, so a string the enum does not list yet
13/// (one a newer server supports) still works.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum MessageType {
17    /// `pain.001.001.03`
18    Pain00100103,
19    /// `pain.001.001.04`
20    Pain00100104,
21    /// `pain.001.001.05`
22    Pain00100105,
23    /// `pain.001.001.06`
24    Pain00100106,
25    /// `pain.001.001.07`
26    Pain00100107,
27    /// `pain.001.001.08`
28    Pain00100108,
29    /// `pain.001.001.09`
30    Pain00100109,
31    /// `pain.001.001.10`
32    Pain00100110,
33    /// `pain.001.001.11`
34    Pain00100111,
35    /// `pain.001.001.12`
36    Pain00100112,
37    /// `pain.001.001.13`
38    Pain00100113,
39    /// `pain.008.001.02`
40    Pain00800102,
41    /// `pain.008.001.08`
42    Pain00800108,
43}
44
45impl MessageType {
46    /// Every message type, in the order of the OpenAPI enum.
47    pub const ALL: [MessageType; 13] = [
48        MessageType::Pain00100103,
49        MessageType::Pain00100104,
50        MessageType::Pain00100105,
51        MessageType::Pain00100106,
52        MessageType::Pain00100107,
53        MessageType::Pain00100108,
54        MessageType::Pain00100109,
55        MessageType::Pain00100110,
56        MessageType::Pain00100111,
57        MessageType::Pain00100112,
58        MessageType::Pain00100113,
59        MessageType::Pain00800102,
60        MessageType::Pain00800108,
61    ];
62
63    /// The wire string, for example `"pain.001.001.09"`.
64    pub fn as_str(self) -> &'static str {
65        WIRE_NAMES[self as usize]
66    }
67}
68
69/// Wire strings, indexed by discriminant (the order of [`MessageType::ALL`]).
70const WIRE_NAMES: [&str; 13] = [
71    "pain.001.001.03",
72    "pain.001.001.04",
73    "pain.001.001.05",
74    "pain.001.001.06",
75    "pain.001.001.07",
76    "pain.001.001.08",
77    "pain.001.001.09",
78    "pain.001.001.10",
79    "pain.001.001.11",
80    "pain.001.001.12",
81    "pain.001.001.13",
82    "pain.008.001.02",
83    "pain.008.001.08",
84];
85
86impl AsRef<str> for MessageType {
87    fn as_ref(&self) -> &str {
88        self.as_str()
89    }
90}
91
92impl std::fmt::Display for MessageType {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str(self.as_str())
95    }
96}
97
98/// `GET /api/v1/health`.
99#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
100#[non_exhaustive]
101pub struct HealthResponse {
102    /// `"healthy"` when the server is up.
103    pub status: String,
104    /// The server's pain001 version.
105    pub version: String,
106    /// A human-readable message.
107    pub message: String,
108}
109
110/// One field error in a payment file's rows.
111///
112/// This is pain001's row error (`field`, `message`, `value`). The
113/// pain001 0.0.85 OpenAPI document names FastAPI's request-error schema
114/// for these lists by a name collision; the server sends this shape.
115#[derive(Debug, Clone, PartialEq, Deserialize)]
116#[non_exhaustive]
117pub struct RowError {
118    /// The field name or JSON path.
119    pub field: String,
120    /// What is wrong.
121    pub message: String,
122    /// The offending value, when the server reports it.
123    #[serde(default)]
124    pub value: Option<Value>,
125}
126
127/// One item of a `422` response's `detail` array: FastAPI's request
128/// validation error. See [`crate::Error::request_errors`].
129#[derive(Debug, Clone, PartialEq, Deserialize)]
130#[non_exhaustive]
131pub struct RequestError {
132    /// Where in the request: for example `["body", "message_type"]`.
133    pub loc: Vec<Value>,
134    /// What is wrong.
135    pub msg: String,
136    /// The error kind, for example `enum` or `missing`.
137    #[serde(rename = "type")]
138    pub kind: String,
139    /// The rejected input, when reported.
140    #[serde(default)]
141    pub input: Option<Value>,
142    /// Extra context, when reported.
143    #[serde(default)]
144    pub ctx: Option<Value>,
145}
146
147/// `POST /api/v1/ui/validate`.
148#[derive(Debug, Clone, PartialEq, Deserialize)]
149#[non_exhaustive]
150pub struct ValidationResponse {
151    /// Whether every row passed, and every requested scheme rulebook.
152    pub is_valid: bool,
153    /// Rows read from the file.
154    pub total_rows: u64,
155    /// Rows that passed.
156    #[serde(default)]
157    pub valid_rows: u64,
158    /// Rows that failed.
159    #[serde(default)]
160    pub invalid_rows: u64,
161    /// One entry per field error in the rows.
162    #[serde(default)]
163    pub errors: Vec<RowError>,
164    /// Scheme-rulebook violations, when a scheme was requested.
165    #[serde(default)]
166    pub scheme_violations: Vec<Map<String, Value>>,
167}
168
169/// `POST /api/v1/ui/generate`.
170#[derive(Debug, Clone, PartialEq, Deserialize)]
171#[non_exhaustive]
172pub struct GenerateResponse {
173    /// Whether the XML was generated.
174    pub success: bool,
175    /// A human-readable result message.
176    pub message: String,
177    /// The suggested download name for the XML.
178    #[serde(default)]
179    pub filename: Option<String>,
180    /// The generated XML document, on success.
181    #[serde(default)]
182    pub xml: Option<String>,
183    /// Field errors in the rows when generation was refused.
184    #[serde(default)]
185    pub validation_errors: Vec<RowError>,
186    /// Scheme-rulebook violations when generation was refused.
187    #[serde(default)]
188    pub scheme_violations: Vec<Map<String, Value>>,
189}
190
191/// One problem a rung of the validation ladder found.
192#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
193#[non_exhaustive]
194pub struct CheckFinding {
195    /// `xsd`, `mdr`, `scheme` or `schematron`.
196    pub rung: String,
197    /// The rule identifier.
198    pub rule: String,
199    /// `error` or `warning`.
200    pub severity: String,
201    /// What is wrong.
202    pub message: String,
203    /// Element path, context, or transaction number.
204    #[serde(default)]
205    pub location: Option<String>,
206}
207
208/// `POST /api/v1/check`.
209#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
210#[non_exhaustive]
211pub struct CheckResponse {
212    /// The detected message type, for example `pain.001.001.09`.
213    pub message_type: String,
214    /// `false` when a rung found an error.
215    pub passed: bool,
216    /// Number of error findings.
217    pub errors: u64,
218    /// Number of warning findings.
219    pub warnings: u64,
220    /// The rungs that ran, in order.
221    pub rungs: Vec<String>,
222    /// Every finding.
223    pub findings: Vec<CheckFinding>,
224}
225
226/// One entry of `GET /api/v1/faces`.
227#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
228#[non_exhaustive]
229pub struct FaceInfo {
230    /// The face name, used in the path of [`crate::Client::project_face`].
231    pub name: String,
232    /// The target standard.
233    pub description: String,
234    /// Binding keys the face accepts; any other is refused.
235    pub bindings: Vec<String>,
236}
237
238/// What a projection carried and what it did not, by indexed path.
239#[derive(Debug, Clone, PartialEq, Deserialize)]
240#[non_exhaustive]
241pub struct LossReport {
242    /// The face projected into.
243    pub face: String,
244    /// Source leaves counted.
245    pub total_source_elements: u64,
246    /// Leaves carried into the payload.
247    pub mapped_count: u64,
248    /// Leaves not carried.
249    pub unmapped_count: u64,
250    /// `true` when nothing was dropped.
251    pub is_lossless: bool,
252    /// Share of source leaves not carried.
253    pub loss_ratio: f64,
254    /// Paths carried.
255    pub mapped_paths: Vec<String>,
256    /// Paths not carried.
257    pub unmapped_paths: Vec<String>,
258}
259
260/// `POST /api/v1/faces/{face}`.
261#[derive(Debug, Clone, PartialEq, Deserialize)]
262#[non_exhaustive]
263pub struct FaceResponse {
264    /// The face projected into.
265    pub face: String,
266    /// The source pain.001 edition.
267    pub version: String,
268    /// The body in the target's shape, as raw JSON.
269    pub payload: Value,
270    /// What the projection did not carry.
271    pub loss_report: LossReport,
272}
273
274/// The body of `ui/validate` and `ui/generate`.
275#[derive(Serialize)]
276pub(crate) struct FilePayload<'a> {
277    pub content: &'a str,
278    pub filename: &'a str,
279    pub message_type: &'a str,
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub scheme: Option<&'a str>,
282}
283
284/// The body of `check`.
285#[derive(Serialize)]
286pub(crate) struct CheckRequest<'a> {
287    pub xml: &'a str,
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub scheme: Option<&'a str>,
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub schematron: Option<&'a str>,
292}
293
294/// The body of `faces/{face}`.
295#[derive(Serialize)]
296pub(crate) struct FaceRequest<'a> {
297    pub xml: &'a str,
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub version: Option<&'a str>,
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub bindings: Option<&'a Map<String, Value>>,
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn message_types_match_the_openapi_enum() {
310        let spec: Value = serde_json::from_str(include_str!("../conformance/openapi.json"))
311            .expect("openapi.json parses");
312        let wanted: Vec<&str> = spec["components"]["schemas"]["MessageType"]["enum"]
313            .as_array()
314            .expect("MessageType enum")
315            .iter()
316            .filter_map(Value::as_str)
317            .collect();
318        let ours: Vec<&str> = MessageType::ALL.iter().map(|m| m.as_str()).collect();
319        assert_eq!(ours, wanted);
320        assert_eq!(MessageType::Pain00800108.to_string(), "pain.008.001.08");
321        assert_eq!(MessageType::Pain00100109.as_ref(), "pain.001.001.09");
322    }
323
324    #[test]
325    fn optional_request_fields_are_left_out() {
326        let body = FilePayload {
327            content: "a",
328            filename: "p.csv",
329            message_type: "pain.001.001.09",
330            scheme: None,
331        };
332        let json = serde_json::to_value(&body).expect("serialises");
333        assert_eq!(json.as_object().map(Map::len), Some(3));
334        let check = CheckRequest {
335            xml: "<x/>",
336            scheme: Some("sepa-sct"),
337            schematron: None,
338        };
339        let json = serde_json::to_value(&check).expect("serialises");
340        assert_eq!(
341            json,
342            serde_json::json!({"xml": "<x/>", "scheme": "sepa-sct"})
343        );
344    }
345
346    #[test]
347    fn validation_response_defaults_the_optional_fields() {
348        let parsed: ValidationResponse =
349            serde_json::from_str(r#"{"is_valid": false, "total_rows": 2, "extra": 1}"#)
350                .expect("decodes");
351        assert_eq!(parsed.valid_rows, 0);
352        assert!(parsed.errors.is_empty() && parsed.scheme_violations.is_empty());
353    }
354
355    #[test]
356    fn row_errors_decode_the_server_shape() {
357        let parsed: GenerateResponse = serde_json::from_str(
358            r#"{"success": false, "message": "invalid",
359                "validation_errors": [{"field": "currency", "message": "bad", "value": "EUX"},
360                                      {"field": "id", "message": "missing", "value": null}]}"#,
361        )
362        .expect("decodes");
363        assert_eq!(parsed.validation_errors[0].field, "currency");
364        assert_eq!(parsed.validation_errors[0].value, Some(Value::from("EUX")));
365        assert_eq!(parsed.validation_errors[1].value, None);
366    }
367}