tap-msg 0.7.0

Core message processing library for the Transaction Authorization Protocol
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
//! Invoice message types and structures according to TAIP-16.
//!
//! This module defines the structured Invoice object that can be embedded
//! in a TAIP-14 Payment Request message.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Tax category for a line item or tax subtotal
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxCategory {
    /// Tax category code (e.g., "S" for standard rate, "Z" for zero-rated)
    pub id: String,

    /// Tax rate percentage
    pub percent: f64,

    /// Tax scheme (e.g., "VAT", "GST")
    #[serde(rename = "taxScheme")]
    pub tax_scheme: String,
}

/// Line item in an invoice
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineItem {
    /// Unique identifier for the line item
    pub id: String,

    /// Description of the item or service
    pub description: String,

    /// Quantity of the item
    pub quantity: f64,

    /// Optional unit of measure (e.g., "KGM" for kilogram)
    #[serde(rename = "unitCode", skip_serializing_if = "Option::is_none")]
    pub unit_code: Option<String>,

    /// Price per unit
    #[serde(rename = "unitPrice")]
    pub unit_price: f64,

    /// Total amount for this line item
    #[serde(rename = "lineTotal")]
    pub line_total: f64,

    /// Optional tax category for the line item
    #[serde(rename = "taxCategory", skip_serializing_if = "Option::is_none")]
    pub tax_category: Option<TaxCategory>,

    /// Optional product name (schema.org/Product)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Optional product image URL (schema.org/Product)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,

    /// Optional product URL (schema.org/Product)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// Builder for LineItem objects
#[derive(Default)]
pub struct LineItemBuilder {
    id: Option<String>,
    description: Option<String>,
    quantity: Option<f64>,
    unit_code: Option<String>,
    unit_price: Option<f64>,
    line_total: Option<f64>,
    tax_category: Option<TaxCategory>,
    name: Option<String>,
    image: Option<String>,
    url: Option<String>,
}

impl LineItemBuilder {
    /// Set the line item ID
    pub fn id(mut self, id: String) -> Self {
        self.id = Some(id);
        self
    }

    /// Set the line item description
    pub fn description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }

    /// Set the quantity
    pub fn quantity(mut self, quantity: f64) -> Self {
        self.quantity = Some(quantity);
        self
    }

    /// Set the unit code
    pub fn unit_code(mut self, unit_code: String) -> Self {
        self.unit_code = Some(unit_code);
        self
    }

    /// Set the unit price
    pub fn unit_price(mut self, unit_price: f64) -> Self {
        self.unit_price = Some(unit_price);
        self
    }

    /// Set the line total
    pub fn line_total(mut self, line_total: f64) -> Self {
        self.line_total = Some(line_total);
        self
    }

    /// Set the tax category
    pub fn tax_category(mut self, tax_category: TaxCategory) -> Self {
        self.tax_category = Some(tax_category);
        self
    }

    /// Set the product name (schema.org/Product)
    pub fn name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    /// Set the product image URL (schema.org/Product)
    pub fn image(mut self, image: String) -> Self {
        self.image = Some(image);
        self
    }

    /// Set the product URL (schema.org/Product)
    pub fn url(mut self, url: String) -> Self {
        self.url = Some(url);
        self
    }

    /// Build the LineItem
    pub fn build(self) -> LineItem {
        LineItem {
            id: self.id.expect("id is required"),
            description: self.description.expect("description is required"),
            quantity: self.quantity.expect("quantity is required"),
            unit_code: self.unit_code,
            unit_price: self.unit_price.expect("unit_price is required"),
            line_total: self.line_total.expect("line_total is required"),
            tax_category: self.tax_category,
            name: self.name,
            image: self.image,
            url: self.url,
        }
    }
}

impl LineItem {
    /// Create a builder for constructing LineItem objects
    pub fn builder() -> LineItemBuilder {
        LineItemBuilder::default()
    }
}

/// Tax subtotal information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxSubtotal {
    /// Amount subject to this tax
    #[serde(rename = "taxableAmount")]
    pub taxable_amount: f64,

    /// Tax amount for this category
    #[serde(rename = "taxAmount")]
    pub tax_amount: f64,

    /// Tax category information
    #[serde(rename = "taxCategory")]
    pub tax_category: TaxCategory,
}

/// Aggregate tax information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxTotal {
    /// Total tax amount for the invoice
    #[serde(rename = "taxAmount")]
    pub tax_amount: f64,

    /// Optional breakdown of taxes by category
    #[serde(rename = "taxSubtotal", skip_serializing_if = "Option::is_none")]
    pub tax_subtotal: Option<Vec<TaxSubtotal>>,
}

/// Order reference information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderReference {
    /// Order identifier
    pub id: String,

    /// Optional issue date of the order
    #[serde(rename = "issueDate", skip_serializing_if = "Option::is_none")]
    pub issue_date: Option<String>,
}

/// Reference to an additional document
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentReference {
    /// Document identifier
    pub id: String,

    /// Optional document type
    #[serde(rename = "documentType", skip_serializing_if = "Option::is_none")]
    pub document_type: Option<String>,

    /// Optional URL where the document can be accessed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// Invoice structure according to TAIP-16
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invoice {
    /// Unique identifier for the invoice
    pub id: String,

    /// Date when the invoice was issued (ISO 8601 format)
    #[serde(rename = "issueDate")]
    pub issue_date: String,

    /// ISO 4217 currency code
    #[serde(rename = "currencyCode")]
    pub currency_code: String,

    /// Line items in the invoice
    #[serde(rename = "lineItems")]
    pub line_items: Vec<LineItem>,

    /// Optional tax total information
    #[serde(rename = "taxTotal", skip_serializing_if = "Option::is_none")]
    pub tax_total: Option<TaxTotal>,

    /// Total amount of the invoice, including taxes
    pub total: f64,

    /// Optional sum of line totals before taxes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub_total: Option<f64>,

    /// Optional due date for payment (ISO 8601 format)
    #[serde(rename = "dueDate", skip_serializing_if = "Option::is_none")]
    pub due_date: Option<String>,

    /// Optional additional notes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,

    /// Optional payment terms
    #[serde(rename = "paymentTerms", skip_serializing_if = "Option::is_none")]
    pub payment_terms: Option<String>,

    /// Optional accounting cost code
    #[serde(rename = "accountingCost", skip_serializing_if = "Option::is_none")]
    pub accounting_cost: Option<String>,

    /// Optional order reference
    #[serde(rename = "orderReference", skip_serializing_if = "Option::is_none")]
    pub order_reference: Option<OrderReference>,

    /// Optional references to additional documents
    #[serde(
        rename = "additionalDocumentReference",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_document_reference: Option<Vec<DocumentReference>>,

    /// Additional metadata
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl Invoice {
    /// Creates a new basic Invoice
    pub fn new(
        id: String,
        issue_date: String,
        currency_code: String,
        line_items: Vec<LineItem>,
        total: f64,
    ) -> Self {
        Self {
            id,
            issue_date,
            currency_code,
            line_items,
            tax_total: None,
            total,
            sub_total: None,
            due_date: None,
            note: None,
            payment_terms: None,
            accounting_cost: None,
            order_reference: None,
            additional_document_reference: None,
            metadata: HashMap::new(),
        }
    }

    /// Validate the Invoice according to TAIP-16 rules
    pub fn validate(&self) -> crate::error::Result<()> {
        use crate::error::Error;

        // Required fields validation
        if self.id.is_empty() {
            return Err(Error::Validation("Invoice ID is required".to_string()));
        }

        if self.issue_date.is_empty() {
            return Err(Error::Validation("Issue date is required".to_string()));
        }

        if self.currency_code.is_empty() {
            return Err(Error::Validation("Currency code is required".to_string()));
        }

        if self.line_items.is_empty() {
            return Err(Error::Validation(
                "At least one line item is required".to_string(),
            ));
        }

        // Validate line items
        for (i, item) in self.line_items.iter().enumerate() {
            if item.id.is_empty() {
                return Err(Error::Validation(format!(
                    "Line item {} is missing an ID",
                    i
                )));
            }

            if item.description.is_empty() {
                return Err(Error::Validation(format!(
                    "Line item {} is missing a description",
                    i
                )));
            }

            // Validate that line total is approximately equal to quantity * unit price
            // Allow for some floating point imprecision
            let calculated_total = item.quantity * item.unit_price;
            let difference = (calculated_total - item.line_total).abs();
            if difference > 0.01 {
                // Allow a small tolerance for floating point calculations
                return Err(Error::Validation(format!(
                    "Line item {}: Line total ({}) does not match quantity ({}) * unit price ({})",
                    i, item.line_total, item.quantity, item.unit_price
                )));
            }
        }

        // Validate sub_total if present
        if let Some(sub_total) = self.sub_total {
            let calculated_sub_total: f64 =
                self.line_items.iter().map(|item| item.line_total).sum();
            let difference = (calculated_sub_total - sub_total).abs();
            if difference > 0.01 {
                // Allow a small tolerance for floating point calculations
                return Err(Error::Validation(format!(
                    "Sub-total ({}) does not match the sum of line totals ({})",
                    sub_total, calculated_sub_total
                )));
            }
        }

        // Validate tax_total if present
        if let Some(tax_total) = &self.tax_total {
            if let Some(tax_subtotals) = &tax_total.tax_subtotal {
                let sum_of_subtotals: f64 = tax_subtotals.iter().map(|st| st.tax_amount).sum();
                let difference = (sum_of_subtotals - tax_total.tax_amount).abs();
                if difference > 0.01 {
                    // Allow a small tolerance for floating point calculations
                    return Err(Error::Validation(format!(
                        "Tax total amount ({}) does not match the sum of tax subtotal amounts ({})",
                        tax_total.tax_amount, sum_of_subtotals
                    )));
                }
            }
        }

        // Validate total
        let sub_total = self
            .sub_total
            .unwrap_or_else(|| self.line_items.iter().map(|item| item.line_total).sum());
        let tax_amount = self.tax_total.as_ref().map_or(0.0, |tt| tt.tax_amount);
        let calculated_total = sub_total + tax_amount;
        let difference = (calculated_total - self.total).abs();
        if difference > 0.01 {
            // Allow a small tolerance for floating point calculations
            return Err(Error::Validation(format!(
                "Total ({}) does not match sub-total ({}) + tax amount ({})",
                self.total, sub_total, tax_amount
            )));
        }

        // Validate date formats
        if self.issue_date.len() != 10 {
            return Err(Error::SerializationError(
                "issue_date must be in YYYY-MM-DD format".to_string(),
            ));
        }
        if chrono::NaiveDate::parse_from_str(&self.issue_date, "%Y-%m-%d").is_err() {
            return Err(Error::SerializationError(
                "Invalid issue_date format or value".to_string(),
            ));
        }

        if let Some(due_date) = &self.due_date {
            if due_date.len() != 10 {
                return Err(Error::SerializationError(
                    "due_date must be in YYYY-MM-DD format".to_string(),
                ));
            }
            if chrono::NaiveDate::parse_from_str(due_date, "%Y-%m-%d").is_err() {
                return Err(Error::SerializationError(
                    "Invalid due_date format or value".to_string(),
                ));
            }
        }

        Ok(())
    }
}