1use crate::taf7::{Channel, Entry, Observation, Quality};
8use core::fmt;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ClosingReading<'a> {
13 pub profile_id: &'a str,
14 pub channel: Channel<'a>,
15 pub end_utc: i64,
17 pub cumulative_wh: u64,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Error {
24 EmptyProfileId,
25 EmptyMeterId,
26 InvalidSchedule,
27 WrongChannel,
28 UnexpectedClose,
29 ScheduleComplete,
30}
31
32impl fmt::Display for Error {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 f.write_str(match self {
35 Self::EmptyProfileId => "supply an evaluation profile identifier",
36 Self::EmptyMeterId => "supply a meter identifier",
37 Self::InvalidSchedule => {
38 "supply a nonempty, strictly increasing list of billing closes"
39 }
40 Self::WrongChannel => "closing observation belongs to a different meter or direction",
41 Self::UnexpectedClose => "expected the next commissioned billing close",
42 Self::ScheduleComplete => "all commissioned billing periods have been finalized",
43 })
44 }
45}
46
47impl core::error::Error for Error {}
48
49pub struct Profile<'a> {
51 id: &'a str,
52 channel: Channel<'a>,
53 remaining: &'a [i64],
54}
55
56impl<'a> Profile<'a> {
57 pub fn new(id: &'a str, channel: Channel<'a>, closes_utc: &'a [i64]) -> Result<Self, Error> {
59 if id.trim().is_empty() {
60 return Err(Error::EmptyProfileId);
61 }
62 if channel.meter_id.trim().is_empty() {
63 return Err(Error::EmptyMeterId);
64 }
65 if closes_utc.is_empty() || closes_utc.windows(2).any(|pair| pair[0] >= pair[1]) {
66 return Err(Error::InvalidSchedule);
67 }
68 Ok(Self {
69 id,
70 channel,
71 remaining: closes_utc,
72 })
73 }
74
75 pub fn next_close(&self) -> Option<i64> {
76 self.remaining.first().copied()
77 }
78
79 pub fn close(
83 &mut self,
84 channel: Channel<'_>,
85 entry: Entry,
86 ) -> Result<Option<ClosingReading<'a>>, Error> {
87 let (&end_utc, rest) = self
88 .remaining
89 .split_first()
90 .ok_or(Error::ScheduleComplete)?;
91 if channel != self.channel {
92 return Err(Error::WrongChannel);
93 }
94 if entry.scheduled_utc != end_utc {
95 return Err(Error::UnexpectedClose);
96 }
97 self.remaining = rest;
98 Ok(match entry.observation {
99 Observation::Received {
100 quality: Quality::Valid,
101 cumulative_wh,
102 ..
103 } => Some(ClosingReading {
104 profile_id: self.id,
105 channel: self.channel,
106 end_utc,
107 cumulative_wh,
108 }),
109 _ => None,
110 })
111 }
112}