Skip to main content

ocpi_tariffs/
version.rs

1//! The OCPI versions this crate supports, and the guess at which version a CDR or tariff is.
2
3#[cfg(test)]
4mod test;
5
6#[cfg(test)]
7mod test_guess_cdr;
8
9#[cfg(test)]
10mod test_guess_tariff;
11
12#[cfg(test)]
13mod test_real_world;
14
15use std::fmt;
16
17use tracing::debug;
18
19use crate::{cdr, json, tariff};
20
21/// The OCPI versions supported by this crate.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub enum Version {
24    /// OCPI version 2.2.1.
25    ///
26    /// See: <https://github.com/ocpi/ocpi/tree/a57ecb624fbe0f19537ac7956a11f3019a65018f>.
27    V221,
28
29    /// OCPI version 2.1.1.
30    ///
31    /// See: <https://github.com/ocpi/ocpi/tree/28ea45329a50c3dbfd790505b97860854db1d4a6>.
32    V211,
33}
34
35impl Versioned for Version {
36    fn version(&self) -> Version {
37        *self
38    }
39}
40
41impl fmt::Display for Version {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        match self {
44            Version::V221 => f.write_str("v221"),
45            Version::V211 => f.write_str("v211"),
46        }
47    }
48}
49
50/// An object for a specific OCPI [`Version`].
51pub trait Versioned: fmt::Debug {
52    /// Return the OCPI `Version` of this object.
53    fn version(&self) -> Version;
54}
55
56/// An object with an uncertain [`Version`].
57pub trait Unversioned: fmt::Debug {
58    /// The concrete [`Versioned`] type.
59    type Versioned: Versioned;
60
61    /// Forced an [`Unversioned`] object to be the given [`Version`].
62    ///
63    /// This does not change the structure of the OCPI object.
64    /// It simply relabels the object as a different OCPI Version.
65    ///
66    /// Use this with care.
67    fn force_into_versioned(self, version: Version) -> Self::Versioned;
68}
69
70/// An OCPI object with a certain or uncertain version.
71#[derive(Debug)]
72pub enum Guess<V, U>
73where
74    V: Versioned,
75    U: fmt::Debug,
76{
77    /// The version of the object `V` is certain.
78    Certain(V),
79
80    /// The version of the object `U` is uncertain.
81    Uncertain(U),
82}
83
84impl<V, U> Guess<V, U>
85where
86    V: Versioned,
87    U: Unversioned<Versioned = V>,
88{
89    /// Convert the OCPI object into its [`Version`] if it's [`Versioned`].
90    /// Otherwise, return `Uncertain(())`.
91    pub fn into_version(self) -> Guess<Version, ()> {
92        match self {
93            Guess::Certain(v) => Guess::Certain(v.version()),
94            Guess::Uncertain(_) => Guess::Uncertain(()),
95        }
96    }
97
98    /// Convert a reference to the OCPI object into its [`Version`] if it's
99    /// [`Versioned`]. Otherwise, return `Uncertain(())`.
100    pub fn as_version(&self) -> Guess<Version, ()> {
101        match self {
102            Guess::Certain(v) => Guess::Certain(v.version()),
103            Guess::Uncertain(_) => Guess::Uncertain(()),
104        }
105    }
106
107    /// Return the contained OCPI object if it's [`Versioned`]. Otherwise, force convert the
108    /// object to the given [`Version`].
109    pub fn certain_or(self, fallback: Version) -> V {
110        match self {
111            Guess::Certain(v) => v,
112            Guess::Uncertain(u) => u.force_into_versioned(fallback),
113        }
114    }
115
116    /// Return `Some` OCPI object if it's [`Versioned`]. Otherwise, return None if the
117    /// object's version is uncertain.
118    pub fn certain_or_none(self) -> Option<V> {
119        match self {
120            Guess::Certain(v) => Some(v),
121            Guess::Uncertain(_) => None,
122        }
123    }
124}
125
126/// Guess the `Version` of the given CDR [`json::Document`].
127pub(crate) fn cdr_version(doc: json::Document<'_>) -> cdr::VersionGuess<'_> {
128    guess_cdr_version(doc)
129}
130
131/// Try to guess a CDR's [`Version`] and return a [`cdr::VersionGuess`] with the outcome.
132fn guess_cdr_version(doc: json::Document<'_>) -> cdr::VersionGuess<'_> {
133    /// Fields present in `v2.1.1` CDR that do not exist in `v2.2.1`.
134    /// `auth_id` and `location` were replaced by `cdr_token` and `cdr_location`.
135    const V211_EXCLUSIVE_FIELDS: &[&str] = &["auth_id", "location", "stop_date_time"];
136
137    /// Fields introduced in `v2.2.1` CDR that do not exist in `v2.1.1`.
138    /// Sorted alphabetically; required fields marked for reference.
139    const V221_EXCLUSIVE_FIELDS: &[&str] = &[
140        "authorization_reference",
141        "cdr_location", // Required in `v2.2.1`
142        "cdr_token",    // Required in `v2.2.1`
143        "country_code", // Required in `v2.2.1`
144        "credit",
145        "credit_reference_id",
146        "end_date_time", // Required in `v2.2.1`
147        "home_charging_compensation",
148        "invoice_reference_id",
149        "party_id", // Required in `v2.2.1`
150        "session_id",
151        "signed_data",
152        "total_energy_cost",
153        "total_fixed_cost",
154        "total_parking_cost",
155        "total_reservation_cost",
156        "total_time_cost",
157    ];
158
159    // The `Document` is expected to be an object (see `json::parse_object`); if it is not,
160    // there are no fields to inspect so the version stays uncertain.
161    let Some(fields) = doc.root().as_object_fields() else {
162        return Guess::Uncertain(cdr::Unversioned::new(doc));
163    };
164
165    for field in fields {
166        let key = field.key();
167
168        if key.eq_any_escape_aware(V211_EXCLUSIVE_FIELDS) {
169            return Guess::Certain(cdr::VersionedJson::new(doc, Version::V211));
170        } else if key.eq_any_escape_aware(V221_EXCLUSIVE_FIELDS) {
171            return Guess::Certain(cdr::VersionedJson::new(doc, Version::V221));
172        }
173    }
174
175    Guess::Uncertain(cdr::Unversioned::new(doc))
176}
177
178/// Guess the `Version` of the given tariff [`json::Document`].
179pub(crate) fn tariff_version(doc: json::Document<'_>) -> tariff::VersionGuess<'_> {
180    guess_tariff_version(doc)
181}
182
183/// The private impl for detecting a tariff's version.
184fn guess_tariff_version(doc: json::Document<'_>) -> tariff::VersionGuess<'_> {
185    /// Fields introduced in `v2.2.1` Tariff that do not exist in `v2.1.1.`.
186    const V221_EXCLUSIVE_FIELDS: &[&str] = &[
187        "country_code", // Required in `v2.2.1`
188        "end_date_time",
189        "max_price",
190        "min_price",
191        "party_id", // Required in `v2.2.1`
192        "start_date_time",
193        "type",
194    ];
195
196    /// Fields present in both `v2.1.1` and `v2.2.1` Tariff.
197    /// Seeing any of these — without a `v2.2.1` exclusive field — confirms the object
198    /// is a `v2.1.1` tariff rather than an unrecognized document.
199    const V211_V221_SHARED_FIELDS: &[&str] = &[
200        "currency",
201        "elements",
202        "energy_mix",
203        "id",
204        "last_updated",
205        "tariff_alt_text",
206        "tariff_alt_url",
207    ];
208
209    // The `Document` is expected to be an object (see `json::parse_object`); if it is not,
210    // there are no fields to inspect so the version stays uncertain.
211    let Some(fields) = doc.root().as_object_fields() else {
212        return Guess::Uncertain(tariff::Unversioned::new(doc));
213    };
214
215    let mut seen_known_field = false;
216    for field in fields {
217        let key = field.key();
218        if key.eq_any_escape_aware(V221_EXCLUSIVE_FIELDS) {
219            debug!(
220                "Tariff is v221 because of field: `{}`",
221                key.as_unescaped_str()
222            );
223            return tariff::VersionGuess::Certain(tariff::VersionedJson::new(doc, Version::V221));
224        }
225        if key.eq_any_escape_aware(V211_V221_SHARED_FIELDS) {
226            seen_known_field = true;
227        }
228    }
229
230    if seen_known_field {
231        return tariff::VersionGuess::Certain(tariff::VersionedJson::new(doc, Version::V211));
232    }
233
234    Guess::Uncertain(tariff::Unversioned::new(doc))
235}