use crate::error::{AccountError, Result};
use crate::id::ProfileIx;
use crate::registry::anchor::ProfileAnchor;
use crate::registry::visibility::ProfileVisibility;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileEnd {
at_height: u32,
}
impl ProfileEnd {
pub(crate) fn at(at_height: u32) -> Result<Self> {
if at_height == 0 {
return Err(AccountError::ProfileEndHeightZero);
}
Ok(Self { at_height })
}
pub fn at_height(self) -> u32 {
self.at_height
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileEntry {
ix: ProfileIx,
anchor: ProfileAnchor,
label: Option<String>,
#[serde(default)]
visibility: ProfileVisibility,
#[serde(default, skip_serializing_if = "Option::is_none")]
ended: Option<ProfileEnd>,
}
impl ProfileEntry {
pub(crate) fn new(ix: ProfileIx, anchor: ProfileAnchor, label: Option<String>) -> Self {
Self {
ix,
anchor,
label,
visibility: ProfileVisibility::Shown,
ended: None,
}
}
pub fn ix(&self) -> ProfileIx {
self.ix
}
pub fn anchor(&self) -> &ProfileAnchor {
&self.anchor
}
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
pub fn visibility(&self) -> ProfileVisibility {
self.visibility
}
pub fn is_shown(&self) -> bool {
self.visibility == ProfileVisibility::Shown
}
pub fn ended(&self) -> Option<ProfileEnd> {
self.ended
}
pub fn is_live(&self) -> bool {
self.ended.is_none()
}
pub(crate) fn end(&mut self, end: ProfileEnd) {
self.ended = Some(end);
}
pub(crate) fn set_label(&mut self, label: Option<String>) {
self.label = label;
}
pub(crate) fn set_visibility(&mut self, visibility: ProfileVisibility) {
self.visibility = visibility;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mint::fixtures::bound_mint;
fn entry(label: Option<&str>) -> ProfileEntry {
let (did, store) = bound_mint(1);
ProfileEntry::new(
ProfileIx(3),
ProfileAnchor::from_confirmed(&did, &store).unwrap(),
label.map(str::to_string),
)
}
#[test]
fn a_new_entry_is_shown_and_unlabelled() {
let entry = entry(None);
assert!(entry.is_shown());
assert_eq!(entry.label(), None);
}
#[test]
fn an_entry_without_a_visibility_field_loads_as_shown() {
let full = serde_json::to_value(entry(Some("work"))).unwrap();
let mut without = full.as_object().unwrap().clone();
without.remove("visibility");
let loaded: ProfileEntry = serde_json::from_value(without.into()).unwrap();
assert!(loaded.is_shown());
assert_eq!(loaded.label(), Some("work"));
}
}