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
//! 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 and the price are the order's × ActivationFactor
//! (SS-26).
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 and BaselineReference. Price is
/// the order's Price × ActivationFactor, to four fraction digits (SS-26). 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 {
let price = self.settled_price();
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,
penalty: Amount::ZERO,
net_settlement: price,
isps,
}
}
/// Price × ActivationFactor, exactly.
fn settled_price_exact(&self) -> Decimal {
self.price.value() * self.activation_factor.value()
}
/// Price × ActivationFactor, half-even to four digits, keeping the price's scale.
fn settled_price(&self) -> Amount {
let mut v = self.settled_price_exact().round_dp(4).normalize();
v.rescale(v.scale().max(self.price.value().scale()));
// Four digits at most, and |v| ≤ |price|: always an amount.
Amount::new(v).unwrap_or(self.price)
}
}
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 or Currency differs from the order's;
/// - Price is 0.0001 or more away from the order's Price × ActivationFactor (SS-26);
/// - 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;
/// # #[cfg(feature = "cs1")]
/// # 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
));
}
// SS-26: the factor is applied here, once; one 0.0001 step either way is accepted.
let expected = order.settled_price_exact();
if (item.price.value() - expected).abs() >= Decimal::new(1, 4) {
return Some(if order.activation_factor == ActivationFactor::FULL {
format!("Price {} is not order {r}'s {}.", item.price, order.price)
} else {
format!(
"Price {} is not order {r}'s {} × {} = {}.",
item.price,
order.price,
order.activation_factor,
order.settled_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
}