uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! The settle phase `[UFTP §2.6, §3.10, §4.2.28–29]`. The DSO builds each item from the
//! order it settles. The aggregator checks the settlement against the orders it accepted,
//! and answers each item Accepted or Disputed.
//!
//! The library computes no settlement: delivered power, deficiencies and penalties are
//! the DSO's calculation and the aggregator's accounting. It checks only what the
//! specification states as an identity: the item repeats its order, NetSettlement is
//! Price − Penalty, and the ordered power is the order's power × ActivationFactor.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use jiff::civil::Date;
use rust_decimal::Decimal;

use crate::error::{Rejection, quote};
use crate::msg::{
    FlexOrder, FlexOrderSettlement, FlexOrderSettlementStatus, FlexSettlement, Metadata,
    SettlementIsp,
};
use crate::reason::RejectionReason as R;
use crate::types::{
    AcceptedDisputed, AcceptedRejected, ActivationFactor, Amount, Currency, EntityAddress,
};

impl FlexOrder {
    /// The settlement item for this order. It copies the order's OrderReference, Period,
    /// CongestionPoint, ContractID, D-PrognosisMessageID, BaselineReference and Price.
    /// Penalty is 0 and NetSettlement is the price; see
    /// [`FlexOrderSettlement::with_penalty`].
    ///
    /// The ISP figures are yours: the baseline, the measured power and what was
    /// delivered. See [`SettlementIsp`] for their signs.
    #[must_use]
    pub fn settlement(&self, isps: Vec<SettlementIsp>) -> FlexOrderSettlement {
        FlexOrderSettlement {
            order_reference: Some(self.order_reference.clone()),
            period: self.header.period,
            contract_id: self.contract_id.clone(),
            d_prognosis_message_id: self.d_prognosis_message_id,
            baseline_reference: self.baseline_reference.clone(),
            congestion_point: self.header.congestion_point.clone(),
            price: self.price,
            penalty: Amount::ZERO,
            net_settlement: self.price,
            isps,
        }
    }
}

impl FlexOrderSettlement {
    /// An item without contract or baseline references: Penalty 0, NetSettlement the
    /// price. Prefer [`FlexOrder::settlement`] when you have the order.
    #[must_use]
    pub fn new(
        order_reference: impl Into<String>,
        period: Date,
        congestion_point: EntityAddress,
        price: Amount,
        isps: Vec<SettlementIsp>,
    ) -> Self {
        Self {
            order_reference: Some(order_reference.into()),
            period,
            contract_id: None,
            d_prognosis_message_id: None,
            baseline_reference: None,
            congestion_point,
            price,
            penalty: Amount::ZERO,
            net_settlement: price,
            isps,
        }
    }

    /// Sets the Penalty, and NetSettlement to Price − Penalty `[UFTP §4.2.28]`. The
    /// penalty is the amount deducted, so it is positive for a deficiency (SS-25).
    ///
    /// # Errors
    /// If Price − Penalty is not an amount (out of range).
    pub fn with_penalty(mut self, penalty: Amount) -> Result<Self, Rejection> {
        let net = self
            .price
            .value()
            .checked_sub(penalty.value())
            .ok_or_else(|| {
                Rejection::schema(
                    "[XSD CurrencyAmountType]",
                    format!("{} − {penalty} is out of range.", self.price),
                )
            })?;
        self.net_settlement = Amount::new(net)?;
        self.penalty = penalty;
        Ok(self)
    }

    /// This item accepted, for the [`FlexSettlementResponse`](crate::FlexSettlementResponse).
    #[must_use]
    pub fn accept(&self) -> FlexOrderSettlementStatus {
        FlexOrderSettlementStatus {
            order_reference: self.order_reference.clone(),
            disposition: AcceptedDisputed::Accepted,
            dispute_reason: None,
        }
    }

    /// This item disputed, with a human-readable reason `[UFTP §4.2.29]`.
    #[must_use]
    pub fn dispute(&self, reason: impl Into<String>) -> FlexOrderSettlementStatus {
        FlexOrderSettlementStatus {
            order_reference: self.order_reference.clone(),
            disposition: AcceptedDisputed::Disputed,
            dispute_reason: Some(reason.into()),
        }
    }
}

impl FlexSettlement {
    /// A settlement of `order_settlements` for PeriodStart…PeriodEnd: Result Accepted
    /// (SS-01), no contract settlements.
    ///
    /// The 3.1.0 XSD requires at least one ContractSettlement (SS-02). Push one onto
    /// [`contract_settlements`](Self::contract_settlements) before you seal, or agree on
    /// [`DecodeOptions::allow_empty_contract_settlement`](crate::DecodeOptions::allow_empty_contract_settlement)
    /// with the receiver.
    #[must_use]
    pub fn new(
        meta: Metadata,
        period_start: Date,
        period_end: Date,
        currency: Currency,
        order_settlements: Vec<FlexOrderSettlement>,
    ) -> Self {
        Self {
            meta,
            result: AcceptedRejected::Accepted,
            rejection_reason: None,
            period_start,
            period_end,
            currency,
            order_settlements,
            contract_settlements: Vec::new(),
        }
    }

    /// The aggregator's check of this settlement `[UFTP §3.10.1]`, against the orders it
    /// accepted. Pass them all: only those sent by this settlement's sender to its
    /// recipient with a Period in PeriodStart…PeriodEnd are considered. Items are matched
    /// to orders by OrderReference, never by MessageID. If two orders share a reference,
    /// the first passed is used.
    ///
    /// Returns one status per item, in item order. An item is Disputed with a reason
    /// naming the first difference:
    /// - no OrderReference, or one already settled by an earlier item;
    /// - no considered order with that reference;
    /// - Period, CongestionPoint, Currency or Price differs from the order's;
    /// - NetSettlement is not Price − Penalty;
    /// - it settles an ISP the order does not cover;
    /// - its OrderedFlexPower differs from the order's power × ActivationFactor by a watt
    ///   or more.
    ///
    /// Delivered power, deficiency and penalty are not checked: they are the DSO's
    /// calculation. Overwrite a status with [`FlexOrderSettlement::dispute`] where your
    /// accounting disagrees. Every reason is one line of at most 512 bytes; received
    /// values are escaped.
    ///
    /// ```
    /// # use uftp::*;
    /// # use uftp::jiff::Timestamp;
    /// # fn answer(opened: Opened, accepted: &[FlexOrder], id: MessageUuid, now: Timestamp) -> Option<Message> {
    /// let settlement: FlexSettlement = opened.message().clone().try_into().ok()?;
    /// match settlement.check_against(accepted) {
    ///     Ok(statuses) => Some(settlement.reply(Reply::accepted(id, now), statuses).into()),
    ///     // Missing Settlement Items: the whole settlement is rejected.
    ///     Err(e) => opened.reject(e).response(id, now),
    /// }
    /// # }
    /// ```
    ///
    /// # Errors
    /// *Missing Settlement Items*, naming the first considered order that no item settles.
    /// Answer it with [`Opened::reject`](crate::Opened::reject).
    pub fn check_against<'a>(
        &self,
        orders: impl IntoIterator<Item = &'a FlexOrder>,
    ) -> Result<Vec<FlexOrderSettlementStatus>, Rejection> {
        let mut considered: Vec<&FlexOrder> = Vec::new();
        let mut by_reference: HashMap<&str, &FlexOrder> = HashMap::new();
        for order in orders {
            let m = &order.header.meta;
            if m.sender_domain == self.meta.sender_domain
                && m.recipient_domain == self.meta.recipient_domain
                && (self.period_start..=self.period_end).contains(&order.header.period)
            {
                considered.push(order);
                by_reference
                    .entry(order.order_reference.as_str())
                    .or_insert(order);
            }
        }
        // Sets, not scans: a received settlement may hold thousands of items.
        let settled: HashSet<&str> = self
            .order_settlements
            .iter()
            .filter_map(|s| s.order_reference.as_deref())
            .collect();
        if let Some(missing) = considered
            .iter()
            .find(|o| !settled.contains(o.order_reference.as_str()))
        {
            return Err(Rejection::because(
                R::MissingSettlementItems,
                format!(
                    "Order {} of {} is not settled.",
                    quote(&missing.order_reference),
                    missing.header.period
                ),
            )
            .at("FlexSettlement"));
        }
        let mut seen: HashSet<&str> = HashSet::new();
        Ok(self
            .order_settlements
            .iter()
            .map(
                |item| match self.dispute_reason(item, &by_reference, &mut seen) {
                    Some(reason) => item.dispute(reason),
                    None => item.accept(),
                },
            )
            .collect())
    }

    fn dispute_reason<'s>(
        &self,
        item: &'s FlexOrderSettlement,
        orders: &HashMap<&str, &FlexOrder>,
        seen: &mut HashSet<&'s str>,
    ) -> Option<String> {
        let Some(reference) = item.order_reference.as_deref() else {
            return Some("The item names no OrderReference.".into());
        };
        if !seen.insert(reference) {
            return Some(format!("Order {} is settled twice.", quote(reference)));
        }
        let Some(order) = orders.get(reference) else {
            return Some(format!(
                "No accepted order {} between these parties for {} to {}.",
                quote(reference),
                self.period_start,
                self.period_end
            ));
        };
        let r = quote(reference);
        if item.period != order.header.period {
            return Some(format!(
                "Period {} is not order {r}'s {}.",
                item.period, order.header.period
            ));
        }
        if item.congestion_point != order.header.congestion_point {
            return Some(format!(
                "CongestionPoint {} is not order {r}'s {}.",
                quote(item.congestion_point.as_str()),
                quote(order.header.congestion_point.as_str())
            ));
        }
        if self.currency != order.currency {
            return Some(format!(
                "The settlement is in {}; order {r} is in {}.",
                self.currency, order.currency
            ));
        }
        if item.price != order.price {
            return Some(format!(
                "Price {} is not order {r}'s {}.",
                item.price, order.price
            ));
        }
        let net = item.price.value().checked_sub(item.penalty.value());
        if net != Some(item.net_settlement.value()) {
            let penalty = if item.penalty.value().is_sign_negative() {
                format!("({})", item.penalty)
            } else {
                item.penalty.to_string()
            };
            let mut s = format!(
                "NetSettlement {} is not Price − Penalty ({} − {penalty}",
                item.net_settlement, item.price
            );
            let _ = match net {
                Some(n) => write!(s, " = {n})."),
                None => write!(s, " is out of range)."),
            };
            return Some(s);
        }
        item.isps.iter().find_map(|isp| ordered_power(isp, order))
    }
}

/// Why `isp` does not settle `order`'s ordered power, walking the order's ISP elements
/// that cover its span.
fn ordered_power(isp: &SettlementIsp, order: &FlexOrder) -> Option<String> {
    let r = quote(&order.order_reference);
    let factor = order.activation_factor.value();
    let mut n = isp.span.start();
    while n <= isp.span.end() {
        let Some(o) = order
            .isps
            .iter()
            .find(|o| o.span.start() <= n && n <= o.span.end())
        else {
            return Some(format!("ISP {n} is not in order {r}."));
        };
        let expected = Decimal::from(o.power) * factor;
        if (Decimal::from(isp.ordered_flex_power) - expected).abs() >= Decimal::ONE {
            let mut s = format!(
                "OrderedFlexPower at ISP {n} is {} W; order {r} ordered {} W",
                isp.ordered_flex_power,
                expected.normalize()
            );
            if order.activation_factor != ActivationFactor::FULL {
                let _ = write!(s, " ({} W × {})", o.power, order.activation_factor);
            }
            s.push('.');
            return Some(s);
        }
        // An order covering ISP u32::MAX ends the walk instead of overflowing.
        match o.span.end().min(isp.span.end()).checked_add(1) {
            Some(next) => n = next,
            None => break,
        }
    }
    None
}