use crate::AdditionalAttribute;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct Bo4eMeta {
#[serde(rename = "_typ", skip_serializing_if = "Option::is_none")]
pub typ: Option<String>,
#[serde(rename = "_version", skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub zusatz_attribute: Vec<AdditionalAttribute>,
}
impl Bo4eMeta {
pub fn with_type(typ: impl Into<String>) -> Self {
Self {
typ: Some(typ.into()),
..Default::default()
}
}
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn with_attribute(mut self, attr: AdditionalAttribute) -> Self {
self.zusatz_attribute.push(attr);
self
}
}
pub trait Bo4eObject {
fn type_name_german() -> &'static str;
fn type_name_english() -> &'static str;
fn meta(&self) -> &Bo4eMeta;
fn meta_mut(&mut self) -> &mut Bo4eMeta;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_meta_default() {
let meta = Bo4eMeta::default();
assert!(meta.typ.is_none());
assert!(meta.version.is_none());
assert!(meta.id.is_none());
assert!(meta.zusatz_attribute.is_empty());
}
#[test]
fn test_meta_builder() {
let meta = Bo4eMeta::with_type("Zaehler")
.version("202401.0.1")
.id("ext-123");
assert_eq!(meta.typ, Some("Zaehler".to_string()));
assert_eq!(meta.version, Some("202401.0.1".to_string()));
assert_eq!(meta.id, Some("ext-123".to_string()));
}
#[test]
fn test_meta_serialize() {
let meta = Bo4eMeta::with_type("Zaehler").version("202401.0.1");
let json = serde_json::to_string(&meta).unwrap();
assert!(json.contains(r#""_typ":"Zaehler""#));
assert!(json.contains(r#""_version":"202401.0.1""#));
assert!(!json.contains("zusatzAttribute")); }
#[test]
fn test_meta_deserialize() {
let json = r#"{"_typ":"Zaehler","_version":"202401.0.1","_id":"123"}"#;
let meta: Bo4eMeta = serde_json::from_str(json).unwrap();
assert_eq!(meta.typ, Some("Zaehler".to_string()));
assert_eq!(meta.version, Some("202401.0.1".to_string()));
assert_eq!(meta.id, Some("123".to_string()));
}
#[test]
fn test_meta_with_zusatz_attribute() {
let meta = Bo4eMeta::with_type("Zaehler")
.with_attribute(crate::AdditionalAttribute::string("sap_id", "SAP001"));
assert_eq!(meta.zusatz_attribute.len(), 1);
assert_eq!(meta.zusatz_attribute[0].name, "sap_id");
}
}