use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SaTerminalInfo {
pub index: i32,
pub token_value: String,
pub device_type: String,
pub device_id: Option<String>,
pub extra_data: Option<serde_json::Value>,
pub create_time: i64,
}
impl SaTerminalInfo {
pub fn new(token_value: impl Into<String>, device_type: impl Into<String>) -> Self {
Self {
index: 0,
token_value: token_value.into(),
device_type: device_type.into(),
device_id: None,
extra_data: None,
create_time: chrono::Utc::now().timestamp_millis(),
}
}
pub fn with_device_id(mut self, device_id: impl Into<String>) -> Self {
self.device_id = Some(device_id.into());
self
}
pub fn with_extra_data(mut self, extra: serde_json::Value) -> Self {
self.extra_data = Some(extra);
self
}
pub fn have_extra_data(&self) -> bool {
matches!(&self.extra_data, Some(v) if !v.is_null())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_new_defaults() {
let t = SaTerminalInfo::new("tok1", "PC");
assert_eq!(t.index, 0);
assert_eq!(t.token_value, "tok1");
assert_eq!(t.device_type, "PC");
assert!(t.device_id.is_none());
assert!(!t.have_extra_data());
assert!(t.create_time > 0);
}
#[test]
fn test_with_extra_data() {
let t = SaTerminalInfo::new("tok1", "APP").with_extra_data(json!({"k": 1}));
assert!(t.have_extra_data());
}
#[test]
fn test_serde_round_trip() {
let t = SaTerminalInfo::new("tok1", "PC")
.with_device_id("dev-1")
.with_extra_data(json!({"ip": "127.0.0.1"}));
let json = serde_json::to_string(&t).unwrap();
let back: SaTerminalInfo = serde_json::from_str(&json).unwrap();
assert_eq!(t, back);
}
}