use crate::core::macros::tmf_struct;
use crate::core::{GeographicAddress, Ref, TimePeriod};
tmf_struct! {
@name = "ContactMedium";
pub struct ContactMedium {
id: String,
contact_type: String,
preferred: bool,
valid_for: TimePeriod,
email_address: String,
phone_number: String,
fax_number: String,
social_network_id: String,
street1: String,
street2: String,
city: String,
state_or_province: String,
post_code: String,
country: String,
geographic_address: Ref<GeographicAddress>,
}
}
impl ContactMedium {
pub fn email(address: impl Into<String>) -> Self {
Self::builder()
.email_address(address)
.at_type(ContactMediumKind::Email.type_name())
.build()
}
pub fn phone(number: impl Into<String>) -> Self {
Self::builder()
.phone_number(number)
.at_type(ContactMediumKind::Phone.type_name())
.build()
}
#[must_use]
pub fn kind(&self) -> ContactMediumKind {
ContactMediumKind::from_type_name(self.type_name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ContactMediumKind {
Base,
Email,
Phone,
Fax,
Social,
GeographicAddress,
Other,
}
impl ContactMediumKind {
#[must_use]
pub fn all() -> &'static [Self] {
&[
Self::Base,
Self::Email,
Self::Phone,
Self::Fax,
Self::Social,
Self::GeographicAddress,
]
}
#[must_use]
pub fn from_type_name(name: &str) -> Self {
match name {
"ContactMedium" => Self::Base,
"EmailContactMedium" => Self::Email,
"PhoneContactMedium" => Self::Phone,
"FaxContactMedium" => Self::Fax,
"SocialContactMedium" => Self::Social,
"GeographicAddressContactMedium" => Self::GeographicAddress,
_ => Self::Other,
}
}
#[must_use]
pub fn type_name(self) -> &'static str {
match self {
Self::Base | Self::Other => "ContactMedium",
Self::Email => "EmailContactMedium",
Self::Phone => "PhoneContactMedium",
Self::Fax => "FaxContactMedium",
Self::Social => "SocialContactMedium",
Self::GeographicAddress => "GeographicAddressContactMedium",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_subclass_round_trips_as_other() {
let json = r#"{"contactType":"work","@type":"VendorChatContactMedium","handle":"x"}"#;
let medium: ContactMedium = serde_json::from_str(json).unwrap();
assert_eq!(medium.kind(), ContactMediumKind::Other);
assert_eq!(medium.extensions.get("handle").unwrap(), "x");
assert_eq!(
serde_json::from_str::<serde_json::Value>(json).unwrap(),
serde_json::to_value(&medium).unwrap()
);
}
#[test]
fn constructors_set_the_discriminator() {
assert_eq!(
ContactMedium::phone("+49 30 1234").kind(),
ContactMediumKind::Phone
);
assert_eq!(ContactMedium::email("a@b.c").at_type, "EmailContactMedium");
}
#[test]
fn v5_puts_subclass_members_at_the_top_level() {
let json = r#"{"@type":"GeographicAddressContactMedium","city":"Berlin","country":"DE"}"#;
let medium: ContactMedium = serde_json::from_str(json).unwrap();
assert_eq!(medium.city.as_deref(), Some("Berlin"));
assert!(medium.extensions.is_empty());
}
}