use std::fmt;
use crate::cdrtime::CdrTimestamp;
use crate::disposition::BatchReconciliation;
use crate::plmn::TadigCode;
use crate::sequence::{SequenceSpace, SequenceValue};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ScaledAmount {
value: i64,
decimal_places: u8,
}
impl ScaledAmount {
pub const MAX_DECIMAL_PLACES: u8 = 9;
#[must_use]
pub const fn new(value: i64, decimal_places: u8) -> Self {
Self {
value,
decimal_places,
}
}
#[must_use]
pub const fn zero(decimal_places: u8) -> Self {
Self::new(0, decimal_places)
}
#[must_use]
pub const fn value(self) -> i64 {
self.value
}
#[must_use]
pub const fn decimal_places(self) -> u8 {
self.decimal_places
}
#[must_use]
pub const fn is_representable(self) -> bool {
self.decimal_places <= Self::MAX_DECIMAL_PLACES
}
#[must_use]
pub const fn checked_add(self, other: Self) -> Option<Self> {
if self.decimal_places != other.decimal_places {
return None;
}
match self.value.checked_add(other.value) {
Some(value) => Some(Self::new(value, self.decimal_places)),
None => None,
}
}
#[must_use]
pub const fn checked_negate(self) -> Option<Self> {
match self.value.checked_neg() {
Some(value) => Some(Self::new(value, self.decimal_places)),
None => None,
}
}
#[must_use]
pub const fn is_zero(self) -> bool {
self.value == 0
}
}
impl fmt::Display for ScaledAmount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let places = usize::from(self.decimal_places);
if places == 0 {
return write!(f, "{}", self.value);
}
let negative = self.value < 0;
let digits = self.value.unsigned_abs().to_string();
let padded = if digits.len() <= places {
format!("{}{digits}", "0".repeat(places - digits.len() + 1))
} else {
digits
};
let split = padded.len() - places;
if negative {
f.write_str("-")?;
}
write!(f, "{}.{}", &padded[..split], &padded[split..])
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TapBatch {
pub sender: TadigCode,
pub recipient: TadigCode,
pub file_sequence: SequenceValue,
pub created: CdrTimestamp,
pub declared_events: u64,
pub earliest_event: Option<CdrTimestamp>,
pub latest_event: Option<CdrTimestamp>,
pub declared_charge: ScaledAmount,
}
impl TapBatch {
pub const SEQUENCE_SPACE: SequenceSpace = SequenceSpace::TAP;
pub const INCLUSION_DAYS: i64 = 30;
#[must_use]
pub fn audit(&self, actual_events: u64, actual_charge: ScaledAmount) -> Vec<BatchDiscrepancy> {
let mut found = Vec::new();
if self.sender == self.recipient {
found.push(BatchDiscrepancy::SenderIsRecipient);
}
if self.declared_events != actual_events {
found.push(BatchDiscrepancy::EventCountMismatch {
declared: self.declared_events,
actual: actual_events,
});
}
if self.declared_charge.decimal_places() != actual_charge.decimal_places() {
found.push(BatchDiscrepancy::ChargeScaleMismatch {
declared: self.declared_charge.decimal_places(),
actual: actual_charge.decimal_places(),
});
} else if self.declared_charge != actual_charge {
found.push(BatchDiscrepancy::ChargeMismatch {
declared: self.declared_charge,
actual: actual_charge,
});
}
if !self.declared_charge.is_representable() {
found.push(BatchDiscrepancy::ChargeScaleImplausible {
decimal_places: self.declared_charge.decimal_places(),
});
}
if let (Some(earliest), Some(latest)) = (self.earliest_event, self.latest_event)
&& earliest.to_utc() > latest.to_utc()
{
found.push(BatchDiscrepancy::EventWindowInverted);
}
if let Some(earliest) = self.earliest_event {
let age = self.created.to_utc() - earliest.to_utc();
if age > time::Duration::days(Self::INCLUSION_DAYS) {
found.push(BatchDiscrepancy::EventBeyondInclusionWindow { age });
}
}
if self.declared_events == 0
&& (self.earliest_event.is_some() || self.latest_event.is_some())
{
found.push(BatchDiscrepancy::EmptyBatchWithAWindow);
}
found
}
#[must_use]
pub fn covers(&self, event: CdrTimestamp) -> bool {
match (self.earliest_event, self.latest_event) {
(Some(earliest), Some(latest)) => {
event.to_utc() >= earliest.to_utc() && event.to_utc() <= latest.to_utc()
}
_ => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatchDiscrepancy {
SenderIsRecipient,
EventCountMismatch {
declared: u64,
actual: u64,
},
ChargeMismatch {
declared: ScaledAmount,
actual: ScaledAmount,
},
ChargeScaleMismatch {
declared: u8,
actual: u8,
},
ChargeScaleImplausible {
decimal_places: u8,
},
EventWindowInverted,
EventBeyondInclusionWindow {
age: time::Duration,
},
EmptyBatchWithAWindow,
}
impl BatchDiscrepancy {
#[must_use]
pub const fn rejects_the_file(self) -> bool {
matches!(
self,
Self::SenderIsRecipient
| Self::EventCountMismatch { .. }
| Self::ChargeMismatch { .. }
| Self::ChargeScaleMismatch { .. }
| Self::EventWindowInverted
)
}
}
impl fmt::Display for BatchDiscrepancy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SenderIsRecipient => f.write_str("sender and recipient are the same network"),
Self::EventCountMismatch { declared, actual } => {
write!(f, "audit block claims {declared} events, {actual} arrived")
}
Self::ChargeMismatch { declared, actual } => {
write!(f, "audit block claims {declared}, events sum to {actual}")
}
Self::ChargeScaleMismatch { declared, actual } => write!(
f,
"audit block uses {declared} decimal places, events use {actual}"
),
Self::ChargeScaleImplausible { decimal_places } => {
write!(f, "{decimal_places} decimal places is beyond any currency")
}
Self::EventWindowInverted => f.write_str("the earliest event is later than the latest"),
Self::EventBeyondInclusionWindow { age } => {
write!(f, "the earliest event is {age} old, past the 30-day window")
}
Self::EmptyBatchWithAWindow => {
f.write_str("no events declared, yet a window is stated")
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RapReturn {
Fatal,
Severe {
returned_events: u64,
},
}
impl RapReturn {
#[must_use]
pub const fn rejects_the_file(self) -> bool {
matches!(self, Self::Fatal)
}
#[must_use]
pub const fn accepted_events(self, batch_events: u64) -> Option<u64> {
match self {
Self::Fatal => Some(0),
Self::Severe { returned_events } => {
if returned_events > batch_events {
None
} else {
Some(batch_events - returned_events)
}
}
}
}
#[must_use]
pub fn effect_on(self, batch: BatchReconciliation) -> Option<BatchReconciliation> {
match self {
Self::Fatal => Some(BatchReconciliation::EMPTY),
Self::Severe { returned_events } => {
if returned_events > batch.released() {
return None;
}
let mut adjusted = BatchReconciliation::EMPTY;
for _ in 0..(batch.released() - returned_events) {
adjusted.observe(&crate::disposition::Disposition::Billable);
}
for _ in 0..returned_events {
adjusted.observe(&crate::disposition::Disposition::Rejected(
crate::disposition::RejectReason::Malformed,
));
}
for _ in 0..batch.suppressed() {
adjusted.observe(&crate::disposition::Disposition::Suppressed(
crate::disposition::SuppressReason::OperatorPolicy,
));
}
for _ in 0..batch.rejected() {
adjusted.observe(&crate::disposition::Disposition::Rejected(
crate::disposition::RejectReason::Malformed,
));
}
for _ in 0..batch.held() {
adjusted.observe(&crate::disposition::Disposition::Held(
crate::disposition::HoldReason::AwaitingCorrelation,
));
}
for _ in 0..batch.duplicate() {
adjusted.observe(&crate::disposition::Disposition::Suppressed(
crate::disposition::SuppressReason::OperatorPolicy,
));
}
Some(adjusted)
}
}
}
}
impl fmt::Display for RapReturn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Fatal => f.write_str("FATAL: the whole file"),
Self::Severe { returned_events } => {
write!(f, "SEVERE: {returned_events} event(s)")
}
}
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::ScaledAmount;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
#[serde(rename = "ScaledAmount")]
struct Repr {
value: i64,
decimal_places: u8,
}
impl Serialize for ScaledAmount {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Repr {
value: self.value(),
decimal_places: self.decimal_places(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ScaledAmount {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(deserializer)?;
Ok(ScaledAmount::new(r.value, r.decimal_places))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::disposition::{Disposition, HoldReason};
fn seq(value: u32) -> SequenceValue {
SequenceValue::new(TapBatch::SEQUENCE_SPACE, value).expect("in space")
}
fn batch(declared_events: u64, charge: ScaledAmount) -> TapBatch {
TapBatch {
sender: "DEUD1".parse().unwrap(),
recipient: "GBRVF".parse().unwrap(),
file_sequence: seq(42),
created: "2026-07-28T10:00:00+02:00".parse().unwrap(),
declared_events,
earliest_event: Some("2026-07-20T10:00:00+02:00".parse().unwrap()),
latest_event: Some("2026-07-27T10:00:00+02:00".parse().unwrap()),
declared_charge: charge,
}
}
#[test]
fn an_amount_renders_exactly_without_a_float() {
assert_eq!(ScaledAmount::new(1_234, 3).to_string(), "1.234");
assert_eq!(ScaledAmount::new(1_234, 0).to_string(), "1234");
assert_eq!(ScaledAmount::new(5, 3).to_string(), "0.005");
assert_eq!(ScaledAmount::new(0, 2).to_string(), "0.00");
assert_eq!(ScaledAmount::new(-1_234, 3).to_string(), "-1.234");
assert_eq!(ScaledAmount::new(-5, 3).to_string(), "-0.005");
}
#[test]
fn amounts_add_only_at_one_scale() {
let three = ScaledAmount::new(1_234, 3);
assert_eq!(three.checked_add(ScaledAmount::new(123, 2)), None);
assert_eq!(
three.checked_add(ScaledAmount::new(766, 3)),
Some(ScaledAmount::new(2_000, 3))
);
assert_eq!(
ScaledAmount::new(i64::MAX, 3).checked_add(ScaledAmount::new(1, 3)),
None
);
}
#[test]
fn an_amount_negates_and_an_implausible_scale_is_reported() {
let amount = ScaledAmount::new(1_234, 3);
assert_eq!(
amount.checked_negate().unwrap(),
ScaledAmount::new(-1_234, 3)
);
assert_eq!(ScaledAmount::new(i64::MIN, 3).checked_negate(), None);
assert!(amount.is_representable());
assert!(!ScaledAmount::new(1, 12).is_representable());
assert!(ScaledAmount::zero(2).is_zero());
}
#[test]
fn a_batch_that_describes_itself_correctly_reports_nothing() {
let charge = ScaledAmount::new(1_234, 3);
assert!(batch(10, charge).audit(10, charge).is_empty());
}
#[test]
fn a_count_or_charge_that_disagrees_rejects_the_file() {
let charge = ScaledAmount::new(1_234, 3);
let miscounted = batch(10, charge).audit(9, charge);
assert_eq!(
miscounted,
vec![BatchDiscrepancy::EventCountMismatch {
declared: 10,
actual: 9
}]
);
assert!(miscounted[0].rejects_the_file());
let mischarged = batch(10, charge).audit(10, ScaledAmount::new(1_000, 3));
assert!(matches!(
mischarged.as_slice(),
[BatchDiscrepancy::ChargeMismatch { .. }]
));
assert!(mischarged[0].rejects_the_file());
}
#[test]
fn a_scale_difference_is_distinguished_from_a_value_difference() {
let declared = ScaledAmount::new(1_234, 3);
let actual = ScaledAmount::new(1_234, 2);
let found = batch(10, declared).audit(10, actual);
assert_eq!(
found,
vec![BatchDiscrepancy::ChargeScaleMismatch {
declared: 3,
actual: 2,
}]
);
assert!(
!found
.iter()
.any(|d| matches!(d, BatchDiscrepancy::ChargeMismatch { .. })),
"a scale mismatch must not also read as a value mismatch"
);
}
#[test]
fn every_discrepancy_is_reported_not_only_the_first() {
let mut broken = batch(10, ScaledAmount::new(1, 12));
broken.recipient = broken.sender;
broken.earliest_event = Some("2026-01-01T10:00:00+02:00".parse().unwrap());
let found = broken.audit(9, ScaledAmount::new(1, 12));
assert!(found.len() >= 4, "{found:?}");
assert!(found.contains(&BatchDiscrepancy::SenderIsRecipient));
assert!(
found
.iter()
.any(|d| matches!(d, BatchDiscrepancy::EventCountMismatch { .. }))
);
assert!(
found
.iter()
.any(|d| matches!(d, BatchDiscrepancy::ChargeScaleImplausible { .. }))
);
assert!(
found
.iter()
.any(|d| matches!(d, BatchDiscrepancy::EventBeyondInclusionWindow { .. }))
);
}
#[test]
fn the_thirty_day_inclusion_window_is_measured_from_file_creation() {
let charge = ScaledAmount::zero(3);
let mut inside = batch(1, charge);
inside.earliest_event = Some("2026-06-29T10:00:00+02:00".parse().unwrap());
assert!(
!inside
.audit(1, charge)
.iter()
.any(|d| matches!(d, BatchDiscrepancy::EventBeyondInclusionWindow { .. })),
"29 days is inside the window"
);
let mut outside = batch(1, charge);
outside.earliest_event = Some("2026-06-27T10:00:00+02:00".parse().unwrap());
assert!(
outside
.audit(1, charge)
.iter()
.any(|d| matches!(d, BatchDiscrepancy::EventBeyondInclusionWindow { .. }))
);
}
#[test]
fn an_inclusion_breach_does_not_reject_the_whole_file() {
assert!(
!BatchDiscrepancy::EventBeyondInclusionWindow {
age: time::Duration::days(40)
}
.rejects_the_file()
);
assert!(BatchDiscrepancy::EventWindowInverted.rejects_the_file());
}
#[test]
fn an_inverted_or_impossible_window_is_caught() {
let charge = ScaledAmount::zero(3);
let mut inverted = batch(1, charge);
inverted.earliest_event = Some("2026-07-27T10:00:00+02:00".parse().unwrap());
inverted.latest_event = Some("2026-07-20T10:00:00+02:00".parse().unwrap());
assert!(
inverted
.audit(1, charge)
.contains(&BatchDiscrepancy::EventWindowInverted)
);
let mut empty = batch(0, charge);
empty.earliest_event = Some("2026-07-27T10:00:00+02:00".parse().unwrap());
assert!(
empty
.audit(0, charge)
.contains(&BatchDiscrepancy::EmptyBatchWithAWindow)
);
}
#[test]
fn the_declared_window_is_checkable_against_an_event() {
let charge = ScaledAmount::zero(3);
let batch = batch(1, charge);
assert!(batch.covers("2026-07-25T10:00:00+02:00".parse().unwrap()));
assert!(!batch.covers("2026-07-19T10:00:00+02:00".parse().unwrap()));
assert!(!batch.covers("2026-07-28T09:00:00+02:00".parse().unwrap()));
}
#[test]
fn a_tap_sequence_wraps_within_the_published_range() {
assert_eq!(TapBatch::SEQUENCE_SPACE.first(), 1);
assert_eq!(TapBatch::SEQUENCE_SPACE.last(), 99_999);
assert!(SequenceValue::new(TapBatch::SEQUENCE_SPACE, 0).is_none());
}
#[test]
fn a_fatal_return_empties_the_batch_and_a_severe_one_adjusts_it() {
let mut original = BatchReconciliation::EMPTY;
for _ in 0..10 {
original.observe(&Disposition::Billable);
}
let fatal = RapReturn::Fatal.effect_on(original).unwrap();
assert_eq!(fatal, BatchReconciliation::EMPTY);
assert_eq!(fatal.ingested(), 0, "none of it ever counted");
assert_eq!(RapReturn::Fatal.accepted_events(10), Some(0));
let severe = RapReturn::Severe { returned_events: 3 }
.effect_on(original)
.unwrap();
assert_eq!(severe.ingested(), 10, "the file still counted");
assert_eq!(severe.released(), 7);
assert_eq!(severe.rejected(), 3);
assert!(severe.balances());
assert_eq!(
RapReturn::Severe { returned_events: 3 }.accepted_events(10),
Some(7)
);
}
#[test]
fn returning_more_than_was_released_is_a_disagreement() {
let mut original = BatchReconciliation::EMPTY;
original.observe(&Disposition::Billable);
assert_eq!(
RapReturn::Severe { returned_events: 5 }.effect_on(original),
None
);
assert_eq!(
RapReturn::Severe { returned_events: 5 }.accepted_events(1),
None
);
}
#[test]
fn a_severe_return_preserves_the_batchs_other_outcomes() {
let mut original = BatchReconciliation::EMPTY;
for _ in 0..5 {
original.observe(&Disposition::Billable);
}
original.observe(&Disposition::Held(HoldReason::AwaitingPartial));
original.observe(&Disposition::Rejected(
crate::disposition::RejectReason::Malformed,
));
let adjusted = RapReturn::Severe { returned_events: 2 }
.effect_on(original)
.unwrap();
assert_eq!(adjusted.ingested(), original.ingested());
assert_eq!(adjusted.released(), 3);
assert_eq!(adjusted.held(), 1);
assert!(adjusted.balances());
}
#[test]
fn returns_render_legibly() {
assert_eq!(RapReturn::Fatal.to_string(), "FATAL: the whole file");
assert_eq!(
RapReturn::Severe { returned_events: 3 }.to_string(),
"SEVERE: 3 event(s)"
);
assert!(RapReturn::Fatal.rejects_the_file());
assert!(!RapReturn::Severe { returned_events: 3 }.rejects_the_file());
}
}