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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Invoice models: the invoices and credit notes a merchant issues to their
//! buyers, their lines, and the messages sent about them.
//!
//! A document carries the buyer's name, address and contact details, which
//! are personal data. `Debug` on [`InvoiceParty`] prints none of them, so a
//! document logged with `{:?}` does not carry a buyer's address into the log.

use std::fmt;

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

// The same wire object the buyer portal returns, so one type serves both.
use crate::core::models::buyer_portal::InvoiceParty;

/// `invoice` or `credit_note`.
pub type InvoiceKind = String;

/// Where a document is in its life: `draft`, `issued` or `voided`.
pub type InvoiceDocumentStatus = String;

/// What a document is for: `payment` or `subscription_cycle`.
pub type InvoiceSourceKind = String;

/// What a line is: `product`, `addon`, `bundle`, `component`, `surcharge` or
/// `shipping`. `surcharge` is the difference between what the buyer was
/// charged and what the sold lines add up to.
pub type InvoiceLineRole = String;

/// How a line's tax was decided: `processor`, `reported`, `rule`, `default`
/// or `manual`.
pub type InvoiceLineTaxSource = String;

/// Why a tax rule shows no tax: `reverse_charge`, `exempt`, `export`,
/// `outside_scope` or `small_business`.
pub type InvoiceNoTaxRuleReason = String;

/// Why a message to the buyer was queued: `automatic` (the shop mails every
/// invoice it issues) or `manual` (a send by hand).
pub type InvoiceEmailOrigin = String;

/// What became of a message to the buyer: `queued`, `sending`, `sent`,
/// `failed` or `skipped`.
pub type InvoiceEmailStatus = String;

/// What the mail provider reported about a message after accepting it:
/// `bounced` or `complained`.
pub type InvoiceEmailDeliveryStatus = String;

/// The document-level reason for showing no VAT.
///
/// `kind` is `reverse_charge` (the buyer is liable; needs the buyer's and the
/// seller's VAT ids), `exempt` (with the `provision` relied on) or
/// `small_business` (no line may show VAT). Build one with
/// [`reverse_charge`](Self::reverse_charge), [`exempt`](Self::exempt) or
/// [`small_business`](Self::small_business).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InvoiceNoTaxReason {
    /// `reverse_charge`, `exempt` or `small_business`.
    pub kind: String,
    /// `exempt` only: the exemption provision, printed as supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provision: Option<String>,
    /// Any additional fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl InvoiceNoTaxReason {
    fn of_kind(kind: &str, provision: Option<String>) -> Self {
        Self {
            kind: kind.to_string(),
            provision,
            extra: serde_json::Map::new(),
        }
    }

    /// The buyer is liable for the tax.
    pub fn reverse_charge() -> Self {
        Self::of_kind("reverse_charge", None)
    }

    /// A supply exempt from VAT, under `provision` (nonblank).
    pub fn exempt(provision: impl Into<String>) -> Self {
        Self::of_kind("exempt", Some(provision.into()))
    }

    /// A small-business exemption: no line may show VAT.
    pub fn small_business() -> Self {
        Self::of_kind("small_business", None)
    }
}

/// One line of a document. Amounts are in minor units of the document's
/// currency.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceLine {
    pub id: String,
    /// The line's place on the document.
    pub position: i32,
    pub description: String,
    pub quantity: i64,
    pub unit_net_amount: i64,
    pub line_net_amount: i64,
    /// VAT rate in basis points (`1900` is 19 %). `None` shows no VAT.
    #[serde(default)]
    pub tax_rate_bp: Option<i32>,
    #[serde(default)]
    pub tax_amount: Option<i64>,
    /// Why the line shows no VAT or 0 %.
    #[serde(default)]
    pub tax_exemption_note: Option<String>,
    pub gross_amount: i64,
    #[serde(default)]
    pub product_id: Option<String>,
    #[serde(default)]
    pub price_id: Option<String>,
    /// See [`InvoiceLineRole`].
    #[serde(default)]
    pub line_role: Option<InvoiceLineRole>,
    /// The bundle or product line this line belongs to.
    #[serde(default)]
    pub parent_line_id: Option<String>,
    /// `true` for a bundle component whose price the bundle line carries.
    #[serde(default)]
    pub included: bool,
    #[serde(default)]
    pub source_payment_line_id: Option<String>,
    /// On a credit note: the invoice line it credits.
    #[serde(default)]
    pub corrects_line_id: Option<String>,
    /// See [`InvoiceLineTaxSource`].
    #[serde(default)]
    pub tax_source: Option<InvoiceLineTaxSource>,
    /// The product tax category the line was taxed under.
    #[serde(default)]
    pub tax_category: Option<String>,
    /// The tax rule that decided the line, when one did.
    #[serde(default)]
    pub tax_rule_id: Option<String>,
    #[serde(default)]
    pub tax_rule_name: Option<String>,
    #[serde(default)]
    pub tax_label: Option<String>,
    #[serde(default)]
    pub tax_rule_note: Option<String>,
    /// See [`InvoiceNoTaxRuleReason`].
    #[serde(default)]
    pub tax_reason: Option<InvoiceNoTaxRuleReason>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A credit note issued against an invoice.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceCreditNoteSummary {
    pub id: String,
    #[serde(default)]
    pub document_number: Option<String>,
    /// See [`InvoiceDocumentStatus`].
    pub status: InvoiceDocumentStatus,
    pub gross_amount: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The document's total tax converted into the reporting currency set in the
/// invoice settings.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxReporting {
    /// ISO 4217 reporting currency.
    pub currency: String,
    /// The tax in minor units of `currency`.
    #[serde(default)]
    pub tax_amount: Option<i64>,
    /// The exchange rate applied, as a decimal string.
    #[serde(default)]
    pub rate: Option<String>,
    #[serde(default)]
    pub source: Option<String>,
    /// `YYYY-MM-DD`.
    #[serde(default)]
    pub rate_date: Option<String>,
    /// `true` when no rate could be found.
    pub unavailable: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The order tax a tax service or the processor stated for the source.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceProcessorTax {
    pub source: String,
    /// Minor units of `currency`.
    pub amount: i64,
    pub currency: String,
    /// `true` when the tax is included in the prices.
    pub inclusive: bool,
    #[serde(default)]
    pub rate_bp: Option<i32>,
    #[serde(default)]
    pub country: Option<String>,
    #[serde(default)]
    pub region: Option<String>,
    /// `true` when a merchant of record sold the payment.
    pub merchant_of_record: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Something about the document's tax worth a look before finalising it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceTaxWarning {
    pub code: String,
    pub message: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What was refunded of a payment's invoice, and how much of it is credited.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceRefundSummary {
    pub refunded_amount: i64,
    pub credited_amount: i64,
    /// Refunded, but not yet covered by a credit note.
    pub refunded_not_credited: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// An invoice or credit note a merchant issues to a buyer. Amounts are in
/// minor units of `currency`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantInvoiceDocument {
    pub id: String,
    pub merchant_id: String,
    pub profile_id: String,
    /// See [`InvoiceKind`].
    pub kind: InvoiceKind,
    /// See [`InvoiceDocumentStatus`].
    pub status: InvoiceDocumentStatus,
    /// See [`InvoiceSourceKind`].
    pub source: InvoiceSourceKind,
    #[serde(default)]
    pub payment_id: Option<String>,
    #[serde(default)]
    pub subscription_id: Option<String>,
    #[serde(default)]
    pub subscription_invoice_id: Option<String>,
    /// On a credit note: the invoice it corrects.
    #[serde(default)]
    pub corrects_invoice_id: Option<String>,
    pub test_mode: bool,
    /// The printed number. `None` on a draft.
    #[serde(default)]
    pub document_number: Option<String>,
    #[serde(default)]
    pub number: Option<i64>,
    #[serde(default)]
    pub series: Option<String>,
    /// ISO 8601.
    #[serde(default)]
    pub issued_at: Option<String>,
    /// `YYYY-MM-DD`.
    pub supply_date: String,
    /// `YYYY-MM-DD`.
    #[serde(default)]
    pub period_start: Option<String>,
    /// `YYYY-MM-DD`.
    #[serde(default)]
    pub period_end: Option<String>,
    /// `YYYY-MM-DD`.
    #[serde(default)]
    pub due_date: Option<String>,
    pub seller: InvoiceParty,
    pub buyer: InvoiceParty,
    pub currency: String,
    pub net_amount: i64,
    #[serde(default)]
    pub tax_amount: Option<i64>,
    pub gross_amount: i64,
    #[serde(default)]
    pub paid_amount: Option<i64>,
    #[serde(default)]
    pub no_tax_reason: Option<InvoiceNoTaxReason>,
    #[serde(default)]
    pub notes: Option<String>,
    /// The document's language, such as `en`.
    pub locale: String,
    #[serde(default)]
    pub void_reason: Option<String>,
    #[serde(default)]
    pub tax_reporting: Option<InvoiceTaxReporting>,
    #[serde(default)]
    pub processor_tax: Option<InvoiceProcessorTax>,
    #[serde(default)]
    pub tax_warnings: Vec<InvoiceTaxWarning>,
    /// A payment's invoice, read on its own: what was refunded. Never on a
    /// list row.
    #[serde(default)]
    pub refund: Option<InvoiceRefundSummary>,
    /// Empty on list rows unless the list asked for lines.
    #[serde(default)]
    pub lines: Vec<InvoiceLine>,
    #[serde(default)]
    pub credit_notes: Vec<InvoiceCreditNoteSummary>,
    /// ISO 8601.
    pub created_at: String,
    /// ISO 8601.
    pub modified_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of documents.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceList {
    #[serde(default)]
    pub data: Vec<MerchantInvoiceDocument>,
    pub total_count: i64,
    pub limit: i64,
    pub offset: i64,
    /// A payment's page only: the connector that sold the payment as merchant
    /// of record. Such a payment is invoiced by that connector, and creating
    /// an invoice for it is refused.
    #[serde(default)]
    pub merchant_of_record: Option<String>,
    /// A payment's page only: the payment's successful refunds, in minor
    /// units.
    #[serde(default)]
    pub refunded_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A public link to an issued document's stored PDF, valid for 7 days.
///
/// **Anyone holding `url` can open the document** without logging in, so
/// `Debug` prints it redacted.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceShareLink {
    /// Opens the PDF without logging in. A bad or expired link answers 404.
    pub url: String,
    /// ISO 8601.
    pub expires_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl fmt::Debug for InvoiceShareLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InvoiceShareLink")
            .field("url", &"<redacted>")
            .field("expires_at", &self.expires_at)
            .finish_non_exhaustive()
    }
}

/// One message about a document to its buyer, its stored PDF attached, and
/// what became of it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceEmailDelivery {
    pub id: String,
    pub invoice_id: String,
    /// The message, such as `invoice_issued`.
    pub template_id: String,
    /// 1 for the first message of this template about the document, one more
    /// for every resend.
    pub revision: i32,
    /// See [`InvoiceEmailOrigin`].
    pub origin: InvoiceEmailOrigin,
    /// See [`InvoiceEmailStatus`].
    pub status: InvoiceEmailStatus,
    /// The buyer's address, masked (`j***@example.com`).
    #[serde(default)]
    pub recipient: Option<String>,
    /// The language the message was written in.
    #[serde(default)]
    pub locale: Option<String>,
    /// A message about a test document.
    pub test_mode: bool,
    /// How many times it was handed to the mail provider.
    pub attempts: i32,
    /// The mail provider's id of the message, once accepted.
    #[serde(default)]
    pub provider_message_id: Option<String>,
    /// Why the message failed or was skipped, such as
    /// `merchant_limit_reached` or `no_recipient`. A free string: match the
    /// values you handle.
    #[serde(default)]
    pub error_code: Option<String>,
    #[serde(default)]
    pub error_message: Option<String>,
    /// ISO 8601.
    pub created_at: String,
    /// ISO 8601.
    pub modified_at: String,
    /// ISO 8601.
    #[serde(default)]
    pub sent_at: Option<String>,
    /// See [`InvoiceEmailDeliveryStatus`].
    #[serde(default)]
    pub delivery_status: Option<InvoiceEmailDeliveryStatus>,
    #[serde(default)]
    pub delivery_detail: Option<String>,
    /// ISO 8601.
    #[serde(default)]
    pub delivery_updated_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every message about one document to its buyer, newest first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvoiceEmailDeliveryList {
    #[serde(default)]
    pub data: Vec<InvoiceEmailDelivery>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    #[test]
    fn party_debug_prints_no_personal_data() {
        let party: InvoiceParty = serde_json::from_str(
            r#"{"country":"DE","name":"Erika Muster","address":"Hauptstr. 1",
                "email":"erika@example.com","vat_id":"DE123456789"}"#,
        )
        .unwrap();
        let out = format!("{party:?}");
        assert!(out.contains("DE"));
        for secret in ["Erika", "Hauptstr", "erika@example.com", "DE123456789"] {
            assert!(!out.contains(secret), "Debug leaked `{secret}`: {out}");
        }
    }

    #[test]
    fn share_link_debug_redacts_the_url() {
        let link: InvoiceShareLink = serde_json::from_str(
            r#"{"url":"https://api.test/invoice-documents/m/inv/pdf?token=tok_secret",
                "expires_at":"2026-01-08T00:00:00Z"}"#,
        )
        .unwrap();
        let out = format!("{link:?}");
        assert!(!out.contains("tok_secret"), "Debug leaked the link: {out}");
        assert!(out.contains("2026-01-08"));
    }

    #[test]
    fn no_tax_reason_serializes_as_the_tagged_object() {
        assert_eq!(
            serde_json::to_value(InvoiceNoTaxReason::exempt("Art. 132")).unwrap(),
            serde_json::json!({"kind":"exempt","provision":"Art. 132"})
        );
        assert_eq!(
            serde_json::to_value(InvoiceNoTaxReason::reverse_charge()).unwrap(),
            serde_json::json!({"kind":"reverse_charge"})
        );
    }
}