delopay 0.20.0

Official Rust SDK for the DeloPay payments API
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Invoice settings models: how a merchant's invoices look and are taxed, at
//! the merchant default and per shop, and the tax rules that decide each
//! line.

use std::collections::BTreeMap;

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

use crate::core::models::invoice::{
    InvoiceLineTaxSource, InvoiceNoTaxReason, InvoiceNoTaxRuleReason,
};

/// The document's language: `en`, `de`, `fr`, `es`, `it`, `nl`, `pt` or `pl`.
pub type InvoiceLocale = String;

/// `vat` shows VAT at the default rate on gross prices; `no_vat` shows none
/// and needs a reason.
pub type InvoiceTaxMode = String;

/// How a document's language is chosen: `fixed` (always `locale`) or
/// `buyer_country` (the buyer country's language where supported).
pub type InvoiceLocaleMode = String;

/// Whether a stated order tax decides the lines' tax: `prefer_processor` or
/// `ignore`.
pub type InvoiceProcessorTaxMode = String;

/// Whether a paid payment or subscription cycle gets its invoice without a
/// request: `off`, `draft` (a draft to check and finalise by hand) or
/// `finalize` (issued; a document that cannot be finalised stays a draft).
pub type InvoiceAutoIssue = String;

/// Where an effective setting or a rule list came from: `shop`, `merchant` or
/// `default`.
pub type InvoiceSettingSource = String;

/// Which buyers a tax rule applies to: `any`, `business` (a VAT id or a tax
/// number), `vat_registered` (a VAT id) or `consumer` (neither).
pub type InvoiceBuyerType = String;

/// What a tax rule decides: `rate` (tax at `rate_bp`) or `no_tax`.
pub type InvoiceTaxRuleKind = String;

/// Invoice settings: the merchant default, or one shop's override of it.
///
/// On a shop's override every `None` inherits the merchant default; on the
/// merchant default it uses the built-in fallback.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceSettingsResponse {
    #[serde(default)]
    pub seller_name: Option<String>,
    #[serde(default)]
    pub seller_address: Option<String>,
    #[serde(default)]
    pub seller_tax_id: Option<String>,
    #[serde(default)]
    pub seller_vat_id: Option<String>,
    #[serde(default)]
    pub seller_registration: Option<String>,
    #[serde(default)]
    pub seller_email: Option<String>,
    #[serde(default)]
    pub seller_phone: Option<String>,
    #[serde(default)]
    pub seller_website: Option<String>,
    #[serde(default)]
    pub bank_details: Option<String>,
    /// `#RRGGBB`.
    #[serde(default)]
    pub accent_color: Option<String>,
    #[serde(default)]
    pub footer_text: Option<String>,
    /// Put on every new draft as its notes.
    #[serde(default)]
    pub default_notes: Option<String>,
    /// 0 to 365.
    #[serde(default)]
    pub payment_terms_days: Option<i32>,
    /// 1 to 16 of `A-Z` and `0-9`, printed as `INV-<prefix>-<n>`.
    #[serde(default)]
    pub number_prefix: Option<String>,
    /// A shop's override only: the shop numbers its documents on a sequence
    /// of its own.
    #[serde(default)]
    pub own_number_sequence: Option<bool>,
    /// See [`InvoiceLocale`].
    #[serde(default)]
    pub locale: Option<InvoiceLocale>,
    /// An IANA zone, such as `Europe/Berlin`.
    #[serde(default)]
    pub time_zone: Option<String>,
    /// Print the platform's name in the footer.
    #[serde(default)]
    pub show_platform_branding: Option<bool>,
    /// See [`InvoiceTaxMode`].
    #[serde(default)]
    pub tax_mode: Option<InvoiceTaxMode>,
    /// 0 to 10000; `1900` is 19 %.
    #[serde(default)]
    pub default_tax_rate_bp: Option<i32>,
    #[serde(default)]
    pub no_tax_reason: Option<InvoiceNoTaxReason>,
    /// See [`InvoiceLocaleMode`].
    #[serde(default)]
    pub locale_mode: Option<InvoiceLocaleMode>,
    /// `invoice`, `tax_invoice`, or a title of your own.
    #[serde(default)]
    pub document_title: Option<String>,
    /// The label of the seller's VAT id or tax number, such as `ABN`.
    #[serde(default)]
    pub seller_tax_id_label: Option<String>,
    /// The label of a rate from `default_tax_rate_bp`, such as `GST`.
    #[serde(default)]
    pub tax_label_default: Option<String>,
    /// ISO 4217. A document in another currency also prints its total tax in
    /// this one.
    #[serde(default)]
    pub tax_reporting_currency: Option<String>,
    /// See [`InvoiceProcessorTaxMode`].
    #[serde(default)]
    pub processor_tax_mode: Option<InvoiceProcessorTaxMode>,
    /// See [`InvoiceAutoIssue`].
    #[serde(default)]
    pub auto_issue: Option<InvoiceAutoIssue>,
    /// Read-only: where the logo is served, when one is set.
    #[serde(default)]
    pub logo_url: Option<String>,
    /// Read-only.
    #[serde(default)]
    pub logo_content_type: Option<String>,
    /// Read-only: changes with every new logo.
    #[serde(default)]
    pub logo_sha256: Option<String>,
    /// Read-only: `None` on the merchant default.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Read-only.
    #[serde(default)]
    pub modified_at: Option<String>,
    /// Read-only.
    #[serde(default)]
    pub modified_by: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The settings a shop's next document is finalised with.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct EffectiveInvoiceSettings {
    pub profile_id: String,
    pub settings: InvoiceSettingsResponse,
    /// One entry per field of `settings` that is set, naming where it came
    /// from (see [`InvoiceSettingSource`]).
    #[serde(default)]
    pub sources: BTreeMap<String, InvoiceSettingSource>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

fn default_true() -> bool {
    true
}

/// One tax rule. A list is ordered; the first enabled rule whose conditions
/// all match decides a line. An empty condition matches everything.
///
/// Build one with [`rate`](Self::rate) or [`no_tax`](Self::no_tax), or change
/// a rule read back from the API and send the list again.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxRule {
    /// Read-only on output. On an update, the id of a rule of the same list
    /// keeps that id; `None` gives the rule a new one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// 1 to 120 characters, shown on the draft next to the lines it decided.
    pub name: String,
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// ISO 3166-1 alpha-2 codes; empty matches every country.
    #[serde(default)]
    pub buyer_countries: Vec<String>,
    /// ISO 3166-2 codes such as `US-CA`; empty matches every region.
    #[serde(default)]
    pub buyer_regions: Vec<String>,
    /// See [`InvoiceBuyerType`]. `None` sends nothing, which the API reads as
    /// `any`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub buyer_type: Option<InvoiceBuyerType>,
    /// Product tax categories (`[a-z0-9_]{1,32}`); empty matches every one.
    #[serde(default)]
    pub tax_categories: Vec<String>,
    /// See [`InvoiceTaxRuleKind`].
    pub kind: InvoiceTaxRuleKind,
    /// `kind: rate` only: 0 to 10000; `2000` is 20 %.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_bp: Option<i32>,
    /// `kind: rate` only: printed beside the rate, such as `TVA`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tax_label: Option<String>,
    /// Required for `kind: no_tax`, refused otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub no_tax_reason: Option<InvoiceNoTaxRuleReason>,
    /// Printed on the document once. Required for `kind: no_tax`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Any additional fields not modeled above, sent back as they came.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl InvoiceTaxRule {
    fn of_kind(name: String, kind: &str) -> Self {
        Self {
            id: None,
            name,
            enabled: true,
            buyer_countries: Vec::new(),
            buyer_regions: Vec::new(),
            buyer_type: None,
            tax_categories: Vec::new(),
            kind: kind.to_string(),
            rate_bp: None,
            tax_label: None,
            no_tax_reason: None,
            note: None,
            extra: serde_json::Map::new(),
        }
    }

    /// A rule taxing the lines it matches at `rate_bp` (`2000` is 20 %).
    pub fn rate(name: impl Into<String>, rate_bp: i32) -> Self {
        let mut rule = Self::of_kind(name.into(), "rate");
        rule.rate_bp = Some(rate_bp);
        rule
    }

    /// A rule showing no tax on the lines it matches, for `reason` (see
    /// [`InvoiceNoTaxRuleReason`]), with `note` printed as the legal mention.
    pub fn no_tax(
        name: impl Into<String>,
        reason: impl Into<String>,
        note: impl Into<String>,
    ) -> Self {
        let mut rule = Self::of_kind(name.into(), "no_tax");
        rule.no_tax_reason = Some(reason.into());
        rule.note = Some(note.into());
        rule
    }

    /// Keep the id of an existing rule of the same list.
    #[must_use]
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Enable or disable the rule.
    #[must_use]
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Match only buyers in these countries (ISO 3166-1 alpha-2).
    #[must_use]
    pub fn buyer_countries(mut self, countries: Vec<String>) -> Self {
        self.buyer_countries = countries;
        self
    }

    /// Match only buyers in these regions (ISO 3166-2).
    #[must_use]
    pub fn buyer_regions(mut self, regions: Vec<String>) -> Self {
        self.buyer_regions = regions;
        self
    }

    /// Match only this kind of buyer (see [`InvoiceBuyerType`]).
    #[must_use]
    pub fn buyer_type(mut self, buyer_type: impl Into<String>) -> Self {
        self.buyer_type = Some(buyer_type.into());
        self
    }

    /// Match only these product tax categories.
    #[must_use]
    pub fn tax_categories(mut self, categories: Vec<String>) -> Self {
        self.tax_categories = categories;
        self
    }

    /// The label printed beside the rate, such as `TVA`.
    #[must_use]
    pub fn tax_label(mut self, label: impl Into<String>) -> Self {
        self.tax_label = Some(label.into());
        self
    }

    /// The note printed on the document once.
    #[must_use]
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }
}

/// A rule list: the merchant's, or a shop's.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxRules {
    /// `None` on the merchant's list.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// On a shop: `true` when it has a list of its own, `false` when it uses
    /// the merchant's, which `rules` then shows. Always `true` on the
    /// merchant's list.
    pub own_rules: bool,
    /// In priority order.
    #[serde(default)]
    pub rules: Vec<InvoiceTaxRule>,
    /// ISO 8601.
    #[serde(default)]
    pub modified_at: Option<String>,
    #[serde(default)]
    pub modified_by: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a line would be taxed at.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxOutcome {
    /// See [`InvoiceTaxRuleKind`].
    pub kind: InvoiceTaxRuleKind,
    #[serde(default)]
    pub rate_bp: Option<i32>,
    /// `None`: the default label.
    #[serde(default)]
    pub tax_label: Option<String>,
    /// See [`InvoiceNoTaxRuleReason`].
    #[serde(default)]
    pub no_tax_reason: Option<InvoiceNoTaxRuleReason>,
    #[serde(default)]
    pub note: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of a tax-rule dry run. Nothing was written.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxRuleEvaluation {
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Whose list was evaluated: `shop` or `merchant`.
    pub rules_source: InvoiceSettingSource,
    /// `business` or `consumer`.
    pub buyer_type: InvoiceBuyerType,
    /// The buyer has a VAT id, so `vat_registered` rules match it.
    pub vat_registered: bool,
    /// The category evaluated.
    pub tax_category: String,
    /// `rule`, or `default` when no rule matched.
    pub source: InvoiceLineTaxSource,
    /// The first enabled rule that matched.
    #[serde(default)]
    pub matched_rule: Option<InvoiceTaxRule>,
    /// Its zero-based position in the list.
    #[serde(default)]
    pub matched_position: Option<i32>,
    pub outcome: InvoiceTaxOutcome,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    #[test]
    fn a_rate_rule_serializes_only_what_it_sets() {
        let rule = InvoiceTaxRule::rate("FR standard", 2000)
            .buyer_countries(vec!["FR".to_string()])
            .tax_label("TVA");
        assert_eq!(
            serde_json::to_value(rule).unwrap(),
            json!({
                "name": "FR standard",
                "enabled": true,
                "buyer_countries": ["FR"],
                "buyer_regions": [],
                "tax_categories": [],
                "kind": "rate",
                "rate_bp": 2000,
                "tax_label": "TVA"
            })
        );
    }

    #[test]
    fn a_rule_read_back_keeps_its_id_and_unknown_fields_on_the_way_out() {
        let rule: InvoiceTaxRule = serde_json::from_str(
            r#"{"id":"itr_1","name":"EU B2B","kind":"no_tax","no_tax_reason":"reverse_charge",
                "note":"Reverse charge","priority_hint":3}"#,
        )
        .unwrap();
        // Absent `enabled` reads as the API's default.
        assert!(rule.enabled);
        assert_eq!(rule.extra["priority_hint"], 3);
        let out = serde_json::to_value(&rule).unwrap();
        assert_eq!(out["id"], "itr_1");
        assert_eq!(out["priority_hint"], 3);
    }
}