rutmf 0.3.0

Ergonomic, v5-first Rust types and clients for the TM Forum Open API domain model (unofficial)
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `CustomerBill` and the rest of TMF678.

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use crate::core::macros::{tmf_entity, tmf_patch_body, tmf_struct, tmf_value};
use crate::core::{
    Attachment, BillCycleSpecification, BillingAccount, Characteristic, FinancialAccount, Money,
    Payment, PaymentMethod, Ref, RelatedParty, TaxItem, TimePeriod, Timestamp,
};
use crate::product::Product;

/// Where a [`CustomerBill`] has got to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillState {
    /// Produced but not yet checked.
    #[serde(rename = "new")]
    New,
    /// Held back from the customer, pending a query.
    #[serde(rename = "onHold")]
    OnHold,
    /// Checked and correct.
    #[serde(rename = "validated")]
    Validated,
    /// Delivered to the customer.
    #[serde(rename = "sent")]
    Sent,
    /// Paid in full.
    #[serde(rename = "settled")]
    Settled,
    /// Some of the amount has been paid.
    #[serde(rename = "partiallyPaid")]
    PartiallyPaid,
    /// A value outside the v5 enumeration, preserved verbatim.
    #[serde(untagged)]
    Other(String),
}

impl CustomerBillState {
    /// Whether the bill still has money outstanding.
    ///
    /// An unrecognised state counts as **outstanding**: a collections process
    /// that writes off what it does not understand is worse than one that asks.
    #[must_use]
    pub fn is_outstanding(&self) -> bool {
        !matches!(self, Self::Settled)
    }
}

/// Whether a bill came from the regular run or was asked for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillRunType {
    /// Produced by the scheduled billing cycle.
    #[serde(rename = "onCycle")]
    OnCycle,
    /// Produced outside the cycle, on request.
    #[serde(rename = "offCycle")]
    OffCycle,
    /// A value outside the v5 enumeration, preserved verbatim.
    #[serde(untagged)]
    Other(String),
}

/// How an on-demand bill request is progressing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillOnDemandState {
    /// The bill is being produced.
    #[serde(rename = "inProgress")]
    InProgress,
    /// The request was refused.
    #[serde(rename = "rejected")]
    Rejected,
    /// The bill is ready.
    #[serde(rename = "done")]
    Done,
    /// Production failed.
    #[serde(rename = "terminatedWithError")]
    TerminatedWithError,
    /// A value outside the v5 enumeration, preserved verbatim.
    #[serde(untagged)]
    Other(String),
}

impl CustomerBillOnDemandState {
    /// Whether the request has stopped moving.
    ///
    /// An unrecognised state is **not** terminal, so a client polling for the
    /// bill keeps polling rather than giving up on a state it does not know.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        matches!(
            self,
            Self::Done | Self::Rejected | Self::TerminatedWithError
        )
    }
}

tmf_struct! {
    @name = "CustomerBill", @ref = "CustomerBillRef";
    /// An issued invoice: what the customer owes, and for what period.
    ///
    /// ```
    /// use rutmf::bill::{CustomerBill, CustomerBillState};
    ///
    /// let json = r#"{"@type":"CustomerBill","state":"sent"}"#;
    /// let bill: CustomerBill = serde_json::from_str(json).unwrap();
    ///
    /// assert!(bill.state.unwrap().is_outstanding());
    /// ```
    pub struct CustomerBill {
        /// Server-assigned identifier.
        id: String,
        /// Canonical URI of this bill.
        href: String,
        /// Name of the bill, as a `CustomerBillRef` carries it.
        name: String,
        /// The bill number the customer sees.
        bill_no: String,
        /// How the provider classifies this bill.
        category: String,
        /// Where the bill has got to.
        state: CustomerBillState,
        /// Whether it came from the cycle or was asked for.
        run_type: CustomerBillRunType,
        /// When the bill was produced.
        bill_date: Timestamp,
        /// When the next one is due to be produced.
        next_bill_date: Timestamp,
        /// When payment is due.
        payment_due_date: Timestamp,
        /// When the bill was last changed.
        last_update: Timestamp,
        /// The period the charges cover.
        billing_period: TimePeriod,
        /// The total the customer owes.
        amount_due: Money,
        /// What is still unpaid.
        remaining_amount: Money,
        /// The total before tax.
        tax_excluded_amount: Money,
        /// The total including tax.
        tax_included_amount: Money,
        /// The tax applied, broken down.
        tax_item: Vec<TaxItem>,
        /// Payments already applied to this bill.
        applied_payment: Vec<AppliedPayment>,
        /// The account this bill is issued against.
        billing_account: Ref<BillingAccount>,
        /// The financial account the money lands in.
        financial_account: Ref<FinancialAccount>,
        /// How the customer is set up to pay.
        payment_method: Ref<PaymentMethod>,
        /// The billing run that produced this bill.
        bill_cycle: Ref<BillCycle>,
        /// The bill itself, as a document.
        bill_document: Vec<Attachment>,
        /// Parties related to the bill.
        related_party: Vec<RelatedParty>,
        @renamed {
            /// The concrete class a `CustomerBillRef` points at.
            "@referredType" referred_type: String,
        }
    }
}

tmf_struct! {
    @name = "CustomerBill";
    /// Body of a `PATCH /customerBill/{id}` — the v5 `CustomerBill_MVO`.
    ///
    /// Deliberately almost empty. TMF678's `_MVO` declares only `state` and
    /// `billCycle`, so this type cannot express a change to `amountDue`,
    /// `taxItem` or `billNo` — an issued invoice is evidence, and the
    /// specification does not let a client rewrite what it says.
    ///
    /// There is no `CustomerBillCreate` for the same reason: `POST
    /// /customerBill` does not exist. Bills are produced by a billing run, or
    /// requested through [`CustomerBillOnDemandCreate`].
    pub struct CustomerBillUpdate {
        /// The state to move the bill to.
        state: CustomerBillState,
        /// The billing run to attribute it to.
        bill_cycle: Ref<BillCycle>,
    }
}

tmf_struct! {
    // TMF678 defines no `CustomerBillOnDemandRef`: an on-demand request is
    // addressed, never referenced.
    @name = "CustomerBillOnDemand";
    /// A request for a bill outside the regular cycle.
    pub struct CustomerBillOnDemand {
        /// Server-assigned identifier.
        id: String,
        /// Canonical URI of this request.
        href: String,
        /// Name of the request.
        name: String,
        /// Narrative description.
        description: String,
        /// How the request is progressing.
        state: CustomerBillOnDemandState,
        /// When the request was last changed.
        last_update: Timestamp,
        /// The account to bill.
        billing_account: Ref<BillingAccount>,
        /// The bill produced, once there is one.
        customer_bill: Ref<CustomerBill>,
        /// The party the request is for.
        related_party: RelatedParty,
    }
}

tmf_struct! {
    @name = "CustomerBillOnDemand";
    /// Body of a `POST /customerBillOnDemand` — the v5 `_FVO` schema.
    ///
    /// There is no matching update type: TMF678 defines `POST` and `GET` on
    /// this collection and nothing else. Poll the returned request with
    /// [`CustomerBillOnDemandState::is_finished`].
    pub struct CustomerBillOnDemandCreate {
        @required {
            /// The account to bill. **Required on create.**
            billing_account: Ref<BillingAccount>,
        }
        /// Client-supplied identifier, where the server permits one.
        id: String,
        /// Name of the request.
        name: String,
        /// Narrative description.
        description: String,
        /// The state to open the request in, where the server allows one.
        state: CustomerBillOnDemandState,
        /// When the request was last changed.
        last_update: Timestamp,
        /// The bill produced.
        customer_bill: Ref<CustomerBill>,
        /// The party the request is for.
        related_party: RelatedParty,
    }
}

tmf_struct! {
    // Likewise, no `AppliedCustomerBillingRateRef` is declared.
    @name = "AppliedCustomerBillingRate";
    /// One charge that went onto a bill.
    ///
    /// Read-only: TMF678 declares `GET` on this collection and nothing else.
    /// Charges are produced by rating, not authored by a client.
    pub struct AppliedCustomerBillingRate {
        /// Server-assigned identifier.
        id: String,
        /// Canonical URI of this charge.
        href: String,
        /// Name of the charge.
        name: String,
        /// Narrative description.
        description: String,
        /// How the provider classifies the charge.
        applied_billing_rate_type: String,
        /// When the charge was applied.
        date: Timestamp,
        /// Whether it has appeared on a bill yet.
        is_billed: bool,
        /// The period the charge covers.
        period_coverage: TimePeriod,
        /// The amount before tax.
        tax_excluded_amount: Money,
        /// The amount including tax.
        tax_included_amount: Money,
        /// The tax applied.
        applied_tax: Vec<AppliedBillingTaxRate>,
        /// The bill this charge appears on.
        bill: Ref<CustomerBill>,
        /// The account it is charged to.
        billing_account: Ref<BillingAccount>,
        /// The product being charged for.
        product: Ref<Product>,
        /// Provider-defined attributes of the charge.
        characteristic: Vec<Characteristic>,
    }
}

tmf_struct! {
    @name = "BillCycle", @ref = "BillCycleRef";
    /// One run of the billing process.
    ///
    /// Read-only: cycles are scheduled by the billing system, not created by a
    /// client.
    pub struct BillCycle {
        /// Server-assigned identifier.
        id: String,
        /// Canonical URI of this cycle.
        href: String,
        /// Name of the cycle.
        name: String,
        /// Narrative description.
        description: String,
        /// The period the cycle covers.
        billing_period: String,
        /// When bills are produced.
        billing_date: Timestamp,
        /// When charges are applied.
        charge_date: Timestamp,
        /// When credits are applied.
        credit_date: Timestamp,
        /// When bills are posted.
        mailing_date: Timestamp,
        /// When payment falls due.
        payment_due_date: Timestamp,
        /// Period during which the cycle is valid.
        valid_for: TimePeriod,
        @renamed {
            /// The specification this cycle runs to.
            ///
            /// # The schema and the example disagree about this name
            ///
            /// TMF678's `BillCycle` schema declares the member as
            /// `BillCycleSpecification`, capitalised, against the `camelCase`
            /// of every other v5 member — while its own retrieve example sends
            /// `billCycleSpecification`. One of the two is a typo and the
            /// specification does not say which.
            ///
            /// This types the **schema** spelling, because that is what
            /// `tests/coverage.rs` checks a conformant server against. A server
            /// that follows the example instead still round-trips losslessly:
            /// the lowercase member is captured in `extensions` rather than
            /// dropped. Read both if you are integrating against a real
            /// deployment.
            "BillCycleSpecification" bill_cycle_specification: Ref<BillCycleSpecification>,
            /// The concrete class a `BillCycleRef` points at.
            "@referredType" referred_type: String,
        }
    }
}

tmf_struct! {
    @name = "AppliedBillingTaxRate";
    /// Tax applied to one charge.
    pub struct AppliedBillingTaxRate {
        /// Server-assigned identifier.
        id: String,
        /// Canonical URI.
        href: String,
        /// The kind of tax.
        tax_category: String,
        /// The amount of tax.
        tax_amount: Money,
        @decimal {
            /// The rate applied, as a percentage.
            ///
            /// TMF678 spells this `number/float`; it is a [`Decimal`] here for
            /// the same reason [`Money::value`](crate::core::Money) is — this
            /// rate is multiplied into a monetary amount, and a binary float
            /// carries its rounding error into the result.
            tax_rate: Decimal,
        }
    }
}

tmf_value! {
    /// A payment set against a bill.
    ///
    /// A plain object: TMF678 gives it no `@type`.
    pub struct AppliedPayment {
        /// How much of the payment was applied here.
        applied_amount: Money,
        /// The payment it came from.
        payment: Ref<Payment>,
    }
}

/// The name of the characteristic that carries a bill line's usage.
///
/// TMF678 gives [`AppliedCustomerBillingRate`] no member for the usage it charges
/// for, and TMF635 v5 declares no `ProductUsageRef`. So the link is a convention,
/// written down once: one `ObjectArrayCharacteristic` called `productUsage`,
/// whose value is a list of generic `EntityRef`s naming `ProductUsage`. Any v5
/// consumer can read it; [`AppliedCustomerBillingRate::product_usages`] and
/// [`AppliedCustomerBillingRate::with_product_usages`] read and write it.
#[cfg(feature = "usage")]
#[cfg_attr(docsrs, doc(cfg(feature = "usage")))]
pub const PRODUCT_USAGE_CHARACTERISTIC: &str = "productUsage";

#[cfg(feature = "usage")]
#[cfg_attr(docsrs, doc(cfg(feature = "usage")))]
impl AppliedCustomerBillingRate {
    /// The usage records this charge was rated from — "why this amount?".
    ///
    /// Reads the [`PRODUCT_USAGE_CHARACTERISTIC`] convention. It never fails:
    /// a characteristic whose value is not a list, an entry without an `id`, or
    /// an entry naming some other `@referredType` is skipped, so a bill line from
    /// a server that does not follow the convention simply has no usage.
    ///
    /// ```
    /// use rutmf::bill::AppliedCustomerBillingRate;
    /// use rutmf::core::Ref;
    ///
    /// let line = AppliedCustomerBillingRate::builder()
    ///     .name("Roaming data")
    ///     .build()
    ///     .with_product_usages([Ref::new("U-1"), Ref::new("U-2")]);
    ///
    /// let ids: Vec<_> = line.product_usages().into_iter().map(|u| u.id).collect();
    /// assert_eq!(ids, ["U-1", "U-2"]);
    /// ```
    #[must_use]
    pub fn product_usages(&self) -> Vec<Ref<crate::usage::ProductUsage>> {
        self.characteristic
            .iter()
            .flatten()
            .filter(|c| c.name.as_deref() == Some(PRODUCT_USAGE_CHARACTERISTIC))
            .filter_map(|c| c.value.as_ref()?.as_array())
            .flatten()
            .filter_map(|entry| {
                let usage: Ref<crate::usage::ProductUsage> =
                    serde_json::from_value(entry.clone()).ok()?;
                let names_usage = usage
                    .referred_type
                    .as_deref()
                    .is_none_or(|t| t == "ProductUsage");
                (names_usage && !usage.id.is_empty()).then_some(usage)
            })
            .collect()
    }

    /// Records the usage records this charge was rated from, replacing any the
    /// line already named under [`PRODUCT_USAGE_CHARACTERISTIC`].
    ///
    /// Other characteristics are left as they were.
    #[must_use]
    pub fn with_product_usages(
        mut self,
        usages: impl IntoIterator<Item = Ref<crate::usage::ProductUsage>>,
    ) -> Self {
        let refs: Vec<serde_json::Value> = usages
            .into_iter()
            .filter_map(|usage| serde_json::to_value(usage).ok())
            .collect();
        let characteristics = self.characteristic.get_or_insert_with(Vec::new);
        characteristics.retain(|c| c.name.as_deref() != Some(PRODUCT_USAGE_CHARACTERISTIC));
        characteristics.push(Characteristic::new(
            PRODUCT_USAGE_CHARACTERISTIC,
            serde_json::Value::Array(refs),
        ));
        self
    }
}

tmf_entity!(
    CustomerBill,
    CustomerBillOnDemand,
    AppliedCustomerBillingRate,
    BillCycle
);
tmf_patch_body!(CustomerBillUpdate);

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

    /// product-usage/SR-003: the reader is total — anything malformed is
    /// skipped, never a failure — and returns only references naming
    /// `ProductUsage`.
    #[cfg(feature = "usage")]
    #[test]
    fn a_bill_line_reads_only_well_formed_usage_references() {
        let line: AppliedCustomerBillingRate = serde_json::from_value(serde_json::json!({
            "@type": "AppliedCustomerBillingRate",
            "characteristic": [
                {"@type": "ObjectCharacteristic", "name": "productUsage", "value": {"id": "lonely"}},
                {"@type": "StringCharacteristic", "name": "productUsage", "value": "U-0"},
                {"@type": "ObjectArrayCharacteristic", "name": "productUsage", "value": [
                    {"@type": "EntityRef", "@referredType": "ProductUsage", "id": "U-1"},
                    {"@type": "EntityRef", "@referredType": "Product", "id": "P-9"},
                    {"@type": "EntityRef", "@referredType": "ProductUsage"},
                    {"@type": "EntityRef", "id": ""},
                    "U-2",
                    42,
                    {"id": "U-3"}
                ]},
                {"@type": "StringCharacteristic", "name": "zone", "value": "EU"}
            ]
        }))
        .unwrap();
        let ids: Vec<String> = line.product_usages().into_iter().map(|u| u.id).collect();
        assert_eq!(ids, ["U-1", "U-3"]);

        // Writing replaces the convention's characteristic and keeps the rest.
        let rewritten = line.with_product_usages([Ref::new("U-7")]);
        let names: Vec<_> = rewritten
            .characteristic
            .iter()
            .flatten()
            .filter_map(|c| c.name.as_deref())
            .collect();
        assert_eq!(names, ["zone", "productUsage"]);
        let json = serde_json::to_value(&rewritten).unwrap();
        let usage_link = &json["characteristic"][1];
        assert_eq!(usage_link["@type"], "ObjectArrayCharacteristic");
        assert_eq!(usage_link["value"][0]["@type"], "EntityRef");
        assert_eq!(usage_link["value"][0]["@referredType"], "ProductUsage");
        assert_eq!(rewritten.product_usages()[0].id, "U-7");
    }

    #[test]
    fn a_bill_patch_can_move_the_state_and_nothing_else() {
        // The whole point of the `_MVO`: an issued invoice is evidence. There
        // is no `amount_due` field to set, so this cannot compile into a
        // request that rewrites what the customer owes.
        let patch = CustomerBillUpdate::builder()
            .state(CustomerBillState::Settled)
            .build();

        let json = serde_json::to_value(&patch).unwrap();
        assert_eq!(json["state"], "settled");
        assert!(json.get("amountDue").is_none());
        assert!(json.get("billNo").is_none());
    }

    #[test]
    fn an_unknown_state_leaves_the_bill_outstanding() {
        let json = r#"{"@type":"CustomerBill","state":"disputed"}"#;
        let bill: CustomerBill = serde_json::from_str(json).unwrap();
        let state = bill.state.clone().expect("a state");

        assert_eq!(state, CustomerBillState::Other("disputed".into()));
        assert!(
            state.is_outstanding(),
            "writing off an unrecognised state is worse than asking"
        );
        assert_eq!(
            serde_json::to_value(&bill).unwrap(),
            serde_json::from_str::<serde_json::Value>(json).unwrap()
        );
    }

    #[test]
    fn the_example_spelling_survives_even_though_the_schema_differs() {
        // TM Forum's own example lowercases the member its schema capitalises.
        // The typed field follows the schema; the example's spelling is not
        // lost, it is captured — which is the whole point of `extensions`.
        let json = r#"{"@type":"BillCycle","billCycleSpecification":{"id":"BCSPEC-M"}}"#;
        let cycle: BillCycle = serde_json::from_str(json).unwrap();

        assert!(cycle.bill_cycle_specification.is_none());
        assert!(cycle.extensions.get("billCycleSpecification").is_some());
        assert_eq!(
            serde_json::to_value(&cycle).unwrap(),
            serde_json::from_str::<serde_json::Value>(json).unwrap(),
        );
    }

    #[test]
    fn the_capitalised_wire_name_is_preserved() {
        // TMF678 spells this member `BillCycleSpecification`, against the
        // camelCase of every other v5 member.
        let json = r#"{"@type":"BillCycle","BillCycleSpecification":{"id":"spec-1","@type":"BillCycleSpecificationRef"}}"#;
        let cycle: BillCycle = serde_json::from_str(json).unwrap();

        assert_eq!(
            cycle
                .bill_cycle_specification
                .as_ref()
                .map(|r| r.id.as_str()),
            Some("spec-1")
        );
        assert!(cycle.extensions.is_empty(), "the member must be typed");
    }

    #[test]
    fn an_on_demand_request_polls_until_finished() {
        assert!(!CustomerBillOnDemandState::InProgress.is_finished());
        assert!(CustomerBillOnDemandState::Done.is_finished());
        assert!(
            !CustomerBillOnDemandState::Other("queued".into()).is_finished(),
            "an unrecognised state must not stop a poller"
        );
    }
}