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;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillState {
#[serde(rename = "new")]
New,
#[serde(rename = "onHold")]
OnHold,
#[serde(rename = "validated")]
Validated,
#[serde(rename = "sent")]
Sent,
#[serde(rename = "settled")]
Settled,
#[serde(rename = "partiallyPaid")]
PartiallyPaid,
#[serde(untagged)]
Other(String),
}
impl CustomerBillState {
#[must_use]
pub fn is_outstanding(&self) -> bool {
!matches!(self, Self::Settled)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillRunType {
#[serde(rename = "onCycle")]
OnCycle,
#[serde(rename = "offCycle")]
OffCycle,
#[serde(untagged)]
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum CustomerBillOnDemandState {
#[serde(rename = "inProgress")]
InProgress,
#[serde(rename = "rejected")]
Rejected,
#[serde(rename = "done")]
Done,
#[serde(rename = "terminatedWithError")]
TerminatedWithError,
#[serde(untagged)]
Other(String),
}
impl CustomerBillOnDemandState {
#[must_use]
pub fn is_finished(&self) -> bool {
matches!(
self,
Self::Done | Self::Rejected | Self::TerminatedWithError
)
}
}
tmf_struct! {
@name = "CustomerBill", @ref = "CustomerBillRef";
pub struct CustomerBill {
id: String,
href: String,
name: String,
bill_no: String,
category: String,
state: CustomerBillState,
run_type: CustomerBillRunType,
bill_date: Timestamp,
next_bill_date: Timestamp,
payment_due_date: Timestamp,
last_update: Timestamp,
billing_period: TimePeriod,
amount_due: Money,
remaining_amount: Money,
tax_excluded_amount: Money,
tax_included_amount: Money,
tax_item: Vec<TaxItem>,
applied_payment: Vec<AppliedPayment>,
billing_account: Ref<BillingAccount>,
financial_account: Ref<FinancialAccount>,
payment_method: Ref<PaymentMethod>,
bill_cycle: Ref<BillCycle>,
bill_document: Vec<Attachment>,
related_party: Vec<RelatedParty>,
@renamed {
"@referredType" referred_type: String,
}
}
}
tmf_struct! {
@name = "CustomerBill";
pub struct CustomerBillUpdate {
state: CustomerBillState,
bill_cycle: Ref<BillCycle>,
}
}
tmf_struct! {
@name = "CustomerBillOnDemand";
pub struct CustomerBillOnDemand {
id: String,
href: String,
name: String,
description: String,
state: CustomerBillOnDemandState,
last_update: Timestamp,
billing_account: Ref<BillingAccount>,
customer_bill: Ref<CustomerBill>,
related_party: RelatedParty,
}
}
tmf_struct! {
@name = "CustomerBillOnDemand";
pub struct CustomerBillOnDemandCreate {
@required {
billing_account: Ref<BillingAccount>,
}
id: String,
name: String,
description: String,
state: CustomerBillOnDemandState,
last_update: Timestamp,
customer_bill: Ref<CustomerBill>,
related_party: RelatedParty,
}
}
tmf_struct! {
@name = "AppliedCustomerBillingRate";
pub struct AppliedCustomerBillingRate {
id: String,
href: String,
name: String,
description: String,
applied_billing_rate_type: String,
date: Timestamp,
is_billed: bool,
period_coverage: TimePeriod,
tax_excluded_amount: Money,
tax_included_amount: Money,
applied_tax: Vec<AppliedBillingTaxRate>,
bill: Ref<CustomerBill>,
billing_account: Ref<BillingAccount>,
product: Ref<Product>,
characteristic: Vec<Characteristic>,
}
}
tmf_struct! {
@name = "BillCycle", @ref = "BillCycleRef";
pub struct BillCycle {
id: String,
href: String,
name: String,
description: String,
billing_period: String,
billing_date: Timestamp,
charge_date: Timestamp,
credit_date: Timestamp,
mailing_date: Timestamp,
payment_due_date: Timestamp,
valid_for: TimePeriod,
@renamed {
"BillCycleSpecification" bill_cycle_specification: Ref<BillCycleSpecification>,
"@referredType" referred_type: String,
}
}
}
tmf_struct! {
@name = "AppliedBillingTaxRate";
pub struct AppliedBillingTaxRate {
id: String,
href: String,
tax_category: String,
tax_amount: Money,
@decimal {
tax_rate: Decimal,
}
}
}
tmf_value! {
pub struct AppliedPayment {
applied_amount: Money,
payment: Ref<Payment>,
}
}
#[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 {
#[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()
}
#[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::*;
#[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"]);
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() {
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() {
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() {
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"
);
}
}