use time::Duration;
use crate::domain::{
MAX_SPOT_STALENESS, PriceBreakdown, Region, TimeRange, TrvReference, price_breakdown,
price_series,
};
use crate::ports::{IntensityRepository, SpotPriceRepository};
use super::ApplicationError;
const ANCHOR_METHODOLOGY: &str = "rte-direct";
pub struct GetElectricityPrice<R: IntensityRepository, P: SpotPriceRepository> {
repository: R,
spot: P,
}
impl<R: IntensityRepository, P: SpotPriceRepository> GetElectricityPrice<R, P> {
pub fn new(repository: R, spot: P) -> Self {
Self { repository, spot }
}
pub async fn current(&self, region: Region) -> Result<PriceBreakdown, ApplicationError> {
let base = self
.repository
.latest(region, ANCHOR_METHODOLOGY)
.await?
.ok_or(ApplicationError::NotFound(region))?;
let mix = base.mix.ok_or(ApplicationError::NotFound(region))?;
let spot = self
.spot
.price_at(base.at)
.await?
.ok_or(ApplicationError::NotFound(region))?;
if base.at - spot.at > MAX_SPOT_STALENESS {
return Err(ApplicationError::NotFound(region));
}
Ok(price_breakdown(
base.at,
region,
&spot,
&mix,
&TrvReference::in_force_at(base.at),
))
}
pub async fn history(
&self,
region: Region,
range: TimeRange,
) -> Result<Vec<PriceBreakdown>, ApplicationError> {
let measurements = self
.repository
.range(region, ANCHOR_METHODOLOGY, range)
.await?;
let price_range =
TimeRange::new(range.start() - Duration::hours(24), range.end()).unwrap_or(range);
let spots = self.spot.price_range(price_range).await?;
Ok(price_series(
&measurements,
&spots,
TrvReference::in_force_at,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::{
CarbonIntensity, GenerationMix, Measurement, Methodology, PriceComponentKind, SpotPrice,
Vintage,
};
use crate::ports::{RepositoryError, SpotPriceRepository};
use async_trait::async_trait;
use time::OffsetDateTime;
fn mix() -> GenerationMix {
GenerationMix {
nucleaire: 40000.0,
gaz: 1000.0,
charbon: 0.0,
fioul: 0.0,
hydraulique: 5000.0,
eolien: 3000.0,
solaire: 1000.0,
bioenergies: 800.0,
pompage: 0.0,
echanges: 0.0,
thermique: None,
}
}
struct FakeRepo {
at: OffsetDateTime,
with_mix: bool,
}
#[async_trait]
impl IntensityRepository for FakeRepo {
async fn upsert_many(&self, _: &[Measurement]) -> Result<usize, RepositoryError> {
Ok(0)
}
async fn latest(
&self,
region: Region,
_methodology_id: &str,
) -> Result<Option<Measurement>, RepositoryError> {
Ok(Some(Measurement {
at: self.at,
region,
intensity: CarbonIntensity::new(40.0).unwrap(),
methodology: Methodology::rte_direct(),
vintage: Vintage::Consolidated,
mix: self.with_mix.then(mix),
}))
}
async fn range(
&self,
_: Region,
_: &str,
_: TimeRange,
) -> Result<Vec<Measurement>, RepositoryError> {
Ok(vec![])
}
async fn stats(
&self,
_: Region,
_: &str,
_: TimeRange,
) -> Result<Option<crate::domain::IntensityStats>, RepositoryError> {
Ok(None)
}
async fn rollup(
&self,
_: Region,
_: &str,
_: TimeRange,
_: crate::domain::Granularity,
) -> Result<Vec<crate::domain::RollupBucket>, RepositoryError> {
Ok(vec![])
}
async fn refresh_rollups(&self) -> Result<(), RepositoryError> {
Ok(())
}
}
struct FakeSpot {
price: Option<SpotPrice>,
}
#[async_trait]
impl SpotPriceRepository for FakeSpot {
async fn upsert_prices(&self, _: &[SpotPrice]) -> Result<usize, RepositoryError> {
Ok(0)
}
async fn price_at(&self, _: OffsetDateTime) -> Result<Option<SpotPrice>, RepositoryError> {
Ok(self.price)
}
async fn price_range(&self, _: TimeRange) -> Result<Vec<SpotPrice>, RepositoryError> {
Ok(self.price.into_iter().collect())
}
}
#[tokio::test]
async fn current_decomposes_with_spot_energy() {
let at = OffsetDateTime::UNIX_EPOCH;
let repo = FakeRepo { at, with_mix: true };
let spot = FakeSpot {
price: Some(SpotPrice::new(at, 70.0).unwrap()),
};
let got = GetElectricityPrice::new(repo, spot)
.current(Region::National)
.await
.unwrap();
let energie = got
.components
.iter()
.find(|c| c.kind == PriceComponentKind::Energie)
.unwrap();
assert_eq!(energie.amount_eur_mwh, 70.0);
assert!(got.total_eur_mwh() > 70.0, "le total inclut TURPE + taxes");
}
#[tokio::test]
async fn missing_spot_is_not_found() {
let at = OffsetDateTime::UNIX_EPOCH;
let repo = FakeRepo { at, with_mix: true };
let spot = FakeSpot { price: None };
let err = GetElectricityPrice::new(repo, spot)
.current(Region::National)
.await;
assert!(matches!(err, Err(ApplicationError::NotFound(_))));
}
#[tokio::test]
async fn missing_mix_is_not_found() {
let at = OffsetDateTime::UNIX_EPOCH;
let repo = FakeRepo {
at,
with_mix: false,
};
let spot = FakeSpot {
price: Some(SpotPrice::new(at, 70.0).unwrap()),
};
let err = GetElectricityPrice::new(repo, spot)
.current(Region::National)
.await;
assert!(matches!(err, Err(ApplicationError::NotFound(_))));
}
#[tokio::test]
async fn stale_spot_is_not_found() {
let at = OffsetDateTime::UNIX_EPOCH + time::Duration::days(100);
let repo = FakeRepo { at, with_mix: true };
let spot = FakeSpot {
price: Some(SpotPrice::new(at - time::Duration::hours(7), 70.0).unwrap()),
};
let err = GetElectricityPrice::new(repo, spot)
.current(Region::National)
.await;
assert!(matches!(err, Err(ApplicationError::NotFound(_))));
}
}