epcis-models 0.2.0

Type-safe GS1 EPCIS 2.0 event models implemented natively in Rust.
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Core shared types for the EPCIS 2.0 SDK.

#![deny(missing_docs)]
#![deny(unsafe_code)]
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]

use crate::error::EpcisModelError;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

/// Newtype representing an Electronic Product Code (EPC) URN.
///
/// # Examples
///
/// ```
/// use epcis_models::Epc;
///
/// let epc = Epc::try_from("urn:epc:id:sgtin:4012345.098765.12345").unwrap();
/// assert_eq!(epc.to_string(), "urn:epc:id:sgtin:4012345.098765.12345");
///
/// // Invalid schemes will fail validation
/// let invalid = Epc::try_from("invalid-scheme");
/// assert!(invalid.is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Epc(pub Cow<'static, str>);

impl From<String> for Epc {
    fn from(s: String) -> Self {
        Epc(Cow::Owned(s))
    }
}

impl From<Cow<'static, str>> for Epc {
    fn from(s: Cow<'static, str>) -> Self {
        Epc(s)
    }
}

impl TryFrom<&str> for Epc {
    type Error = EpcisModelError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.is_empty() {
            return Err(EpcisModelError::InvalidEpc(
                "EPC URN cannot be empty".to_string(),
            ));
        }
        if !s.starts_with("urn:epc:") && !s.starts_with("http://") && !s.starts_with("https://") {
            return Err(EpcisModelError::InvalidEpc(format!(
                "EPC URN must start with URN or HTTP scheme: {s}"
            )));
        }
        Ok(Epc(Cow::Owned(s.to_string())))
    }
}

impl std::fmt::Display for Epc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The Action component of an EPCIS event, specifying the status of the objects
/// identified in the event.
///
/// # Examples
///
/// ```
/// use epcis_models::Action;
///
/// let action = Action::Observe;
/// assert_eq!(action, Action::Observe);
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Action {
    /// Add action
    Add,
    /// Observe action
    Observe,
    /// Delete action
    Delete,
}

impl<'de> Deserialize<'de> for Action {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = crate::document::deserialize_string_or_map_text(deserializer)?;
        match s.as_str() {
            "ADD" => Ok(Action::Add),
            "OBSERVE" => Ok(Action::Observe),
            "DELETE" => Ok(Action::Delete),
            other => Err(serde::de::Error::custom(format!(
                "invalid action: {other}, expected ADD, OBSERVE, or DELETE"
            ))),
        }
    }
}

/// Type-safe identifier wrapper for `ReadPoint`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ReadPointId(pub Cow<'static, str>);

impl From<&'static str> for ReadPointId {
    fn from(s: &'static str) -> Self {
        ReadPointId(Cow::Borrowed(s))
    }
}

impl From<String> for ReadPointId {
    fn from(s: String) -> Self {
        ReadPointId(Cow::Owned(s))
    }
}

impl std::fmt::Display for ReadPointId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The physical location where the event took place.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReadPoint {
    /// Unique identifier of the read point
    pub id: ReadPointId,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

impl From<&'static str> for ReadPoint {
    fn from(id: &'static str) -> Self {
        ReadPoint {
            id: ReadPointId::from(id),
            extensions: serde_json::Map::new(),
        }
    }
}

impl From<String> for ReadPoint {
    fn from(id: String) -> Self {
        ReadPoint {
            id: ReadPointId::from(id),
            extensions: serde_json::Map::new(),
        }
    }
}

/// Type-safe identifier wrapper for `BizLocation`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BizLocationId(pub Cow<'static, str>);

impl From<&'static str> for BizLocationId {
    fn from(s: &'static str) -> Self {
        BizLocationId(Cow::Borrowed(s))
    }
}

impl From<String> for BizLocationId {
    fn from(s: String) -> Self {
        BizLocationId(Cow::Owned(s))
    }
}

impl std::fmt::Display for BizLocationId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The business location where the objects are expected to be after the event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BizLocation {
    /// Unique identifier of the business location
    pub id: BizLocationId,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

impl From<&'static str> for BizLocation {
    fn from(id: &'static str) -> Self {
        BizLocation {
            id: BizLocationId::from(id),
            extensions: serde_json::Map::new(),
        }
    }
}

impl From<String> for BizLocation {
    fn from(id: String) -> Self {
        BizLocation {
            id: BizLocationId::from(id),
            extensions: serde_json::Map::new(),
        }
    }
}

/// A business transaction associated with the event.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BizTransaction {
    /// Type of the business transaction (e.g. PO)
    #[serde(rename = "type")]
    pub r#type: String,
    /// Transaction ID value (e.g. URI)
    pub biz_transaction: String,
}

/// Source of the objects in the event (e.g. shipping location, possessing party).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Source {
    /// Type of the source (e.g. possessing party)
    #[serde(rename = "type")]
    pub r#type: String,
    /// Source value (e.g. SGLN URI)
    pub source: String,
}

/// Destination of the objects in the event (e.g. receiving location, owning party).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Destination {
    /// Type of the destination (e.g. owning party)
    #[serde(rename = "type")]
    pub r#type: String,
    /// Destination value (e.g. SGLN URI)
    pub destination: String,
}

/// An element representing a quantity of EPCs of a single class.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuantityElement {
    /// The EPC class (e.g. GTIN class)
    pub epc_class: String,
    /// Quantity of items in the class
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<f64>,
    /// Unit of measure (e.g. KGM)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uom: Option<String>,
}

/// Metadata about a sensor device or sensor data source.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SensorMetadata {
    /// Time when the sensor metadata was generated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<DateTime<Utc>>,
    /// Start of the period covered by the sensor element
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<DateTime<Utc>>,
    /// End of the period covered by the sensor element
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<DateTime<Utc>>,
    /// Device identifier
    #[serde(rename = "deviceID", skip_serializing_if = "Option::is_none")]
    pub device_id: Option<String>,
    /// URI pointing to device metadata details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_metadata: Option<String>,
    /// URI pointing to raw sensor data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_data: Option<String>,
    /// URI describing the data processing method applied
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_processing_method: Option<String>,
    /// URI pointing to business logic rules applied to the sensor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub biz_rules: Option<String>,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

/// A specific sensor report (e.g., temperature reading).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SensorReport {
    /// Type of measurement (e.g., temperature, relative humidity)
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>,
    /// Exception condition raised by the sensor (e.g. `ALARM_CONDITION`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exception: Option<String>,
    /// Device identifier
    #[serde(rename = "deviceID", skip_serializing_if = "Option::is_none")]
    pub device_id: Option<String>,
    /// URI pointing to device metadata details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_metadata: Option<String>,
    /// URI pointing to raw sensor data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_data: Option<String>,
    /// URI describing the data processing method applied
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_processing_method: Option<String>,
    /// Time when the reading occurred
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<DateTime<Utc>>,
    /// Microorganism measured (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub microorganism: Option<String>,
    /// Chemical substance measured (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chemical_substance: Option<String>,
    /// Numerical value of the sensor reading
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<f64>,
    /// Component the reading refers to (e.g. `Exterior`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component: Option<String>,
    /// String representation value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub string_value: Option<String>,
    /// Boolean representation value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub boolean_value: Option<bool>,
    /// Hex-binary value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hex_binary_value: Option<String>,
    /// URI value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri_value: Option<String>,
    /// Minimum value observed over the report period
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_value: Option<f64>,
    /// Maximum value observed over the report period
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_value: Option<f64>,
    /// Mean value observed over the report period
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mean_value: Option<f64>,
    /// Standard deviation over the report period
    #[serde(rename = "sDev", skip_serializing_if = "Option::is_none")]
    pub s_dev: Option<f64>,
    /// Percentile rank associated with `percValue`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub perc_rank: Option<f64>,
    /// Value at the percentile rank given by `percRank`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub perc_value: Option<f64>,
    /// Unit of measure (e.g. CEL)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uom: Option<String>,
    /// Coordinate reference system used for geographic readings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinate_reference_system: Option<String>,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

/// A sensor element grouping sensor metadata and reports.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SensorElement {
    /// Sensor device metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sensor_metadata: Option<SensorMetadata>,
    /// List of sensor reports
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sensor_report: Option<Vec<SensorReport>>,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

/// Declaration of error correction context.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDeclaration {
    /// The timestamp when the error was declared
    pub declaration_time: DateTime<Utc>,
    /// The reason for error declaration (e.g. incorrect data)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// List of event IDs that correct this event
    #[serde(rename = "correctiveEventIDs", skip_serializing_if = "Option::is_none")]
    pub corrective_event_ids: Option<Vec<String>>,
    /// Extra custom fields (namespace-qualified extensions)
    #[serde(flatten)]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cbv::BizStep;
    use std::str::FromStr;

    #[test]
    fn test_epc_validation() {
        // Valid URN
        let epc = Epc::try_from("urn:epc:id:sgtin:0614141.107346.2023");
        assert!(epc.is_ok());
        assert_eq!(
            epc.unwrap().to_string(),
            "urn:epc:id:sgtin:0614141.107346.2023"
        );

        // Valid URI
        let epc_uri = Epc::try_from("https://id.gs1.org/01/04012345987652/21/12345");
        assert!(epc_uri.is_ok());

        // Error: Empty
        let empty = Epc::try_from("");
        assert!(empty.is_err());
        assert!(matches!(empty.unwrap_err(), EpcisModelError::InvalidEpc(_)));

        // Error: Invalid scheme
        let bad_epc = Epc::try_from("bad:scheme:123");
        assert!(bad_epc.is_err());
    }

    #[test]
    fn test_action_deserialization_errors() {
        // Valid deserializations
        let observe: Action = serde_json::from_str("\"OBSERVE\"").unwrap();
        assert_eq!(observe, Action::Observe);

        // Invalid deserialization
        let err: Result<Action, _> = serde_json::from_str("\"INVALID\"");
        assert!(err.is_err());
    }

    #[test]
    fn test_biz_step_custom_and_standard() {
        // Standard CBV step parsing
        let step = BizStep::from_str("urn:epcglobal:cbv:bizstep:receiving").unwrap();
        assert_eq!(step.as_str(), "urn:epcglobal:cbv:bizstep:receiving");

        // Custom step parsing
        let custom = BizStep::from_str("https://example.com/custom-bizstep").unwrap();
        assert_eq!(custom.as_str(), "https://example.com/custom-bizstep");
    }
}