Skip to main content

acosmi/notifications/
types.rs

1//! 通知 / WebSocket 推送域类型。
2//!
3//! 端口自 `notifications/types.ts`(其端口自 `acosmi-sdk-go/types.go` v0.19.0)。
4//!
5//! 命名约定:字段名 = Go json tag 字面量(wire format)。
6
7use serde::{Deserialize, Serialize};
8
9// =============================================================================
10// Notifications
11// =============================================================================
12
13/// 单条通知。
14#[derive(Debug, Clone, Default, Serialize, Deserialize)]
15pub struct Notification {
16    pub id: String,
17    pub title: String,
18    pub content: String,
19    /// system | billing | security | task | commission | entitlement。
20    #[serde(rename = "type")]
21    pub r#type: String,
22    #[serde(rename = "isRead")]
23    pub is_read: bool,
24    #[serde(rename = "createdAt")]
25    pub created_at: String,
26}
27
28/// 分页通知列表。
29#[derive(Debug, Clone, Default, Serialize, Deserialize)]
30pub struct NotificationList {
31    pub list: Vec<Notification>,
32    #[serde(rename = "unreadCount")]
33    pub unread_count: i64,
34    pub total: i64,
35    pub page: i64,
36    #[serde(rename = "pageSize")]
37    pub page_size: i64,
38}
39
40/// 未读通知计数。
41#[derive(Debug, Clone, Default, Serialize, Deserialize)]
42pub struct NotificationUnreadCount {
43    #[serde(rename = "unreadCount")]
44    pub unread_count: i64,
45}
46
47/// 通知偏好(按类型+渠道)。
48#[derive(Debug, Clone, Default, Serialize, Deserialize)]
49pub struct NotificationPreference {
50    #[serde(rename = "typeCode")]
51    pub type_code: String,
52    #[serde(rename = "channelInApp")]
53    pub channel_in_app: bool,
54    #[serde(rename = "channelEmail")]
55    pub channel_email: bool,
56    #[serde(rename = "channelSms")]
57    pub channel_sms: bool,
58    #[serde(rename = "channelPush")]
59    pub channel_push: bool,
60}
61
62/// 推送设备注册。
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64pub struct DeviceRegistration {
65    /// android | ios | harmony。
66    pub platform: String,
67    pub token: String,
68    #[serde(rename = "appVersion")]
69    pub app_version: String,
70}
71
72// =============================================================================
73// WebSocket 类型(forward-declared 这里,实现在 ws.rs)
74// =============================================================================
75
76/// 服务端推送事件。
77#[derive(Debug, Clone, Default, Serialize, Deserialize)]
78pub struct WSEvent {
79    #[serde(rename = "type")]
80    pub r#type: String,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub topic: Option<String>,
83    /// `json.RawMessage` in Go。
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub data: Option<serde_json::Value>,
86    #[serde(rename = "connId", default, skip_serializing_if = "Option::is_none")]
87    pub conn_id: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub timestamp: Option<String>,
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub message: Option<String>,
92}
93
94/// 从 [`WSEvent`] 中解析通知。
95///
96/// 返回 `None` 表示该事件不是系统通知(对应 TS `parseNotificationEvent`)。
97pub fn parse_notification_event(ev: &WSEvent) -> Option<Notification> {
98    if ev.r#type != "event" || ev.topic.as_deref() != Some("system") {
99        return None;
100    }
101    let data = ev.data.as_ref()?;
102    // ev.data 在 wire 上可能是 raw JSON 串或已反序列化对象,两种形态都接住。
103    let n: Notification = if let Some(s) = data.as_str() {
104        serde_json::from_str(s).ok()?
105    } else {
106        serde_json::from_value(data.clone()).ok()?
107    };
108    if n.id.is_empty() {
109        return None;
110    }
111    Some(n)
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn parse_notification_event_object() {
120        let ev = WSEvent {
121            r#type: "event".to_string(),
122            topic: Some("system".to_string()),
123            data: Some(serde_json::json!({
124                "id": "n1", "title": "T", "content": "C", "type": "system",
125                "isRead": false, "createdAt": "2026-06-19T00:00:00Z"
126            })),
127            ..Default::default()
128        };
129        let n = parse_notification_event(&ev).unwrap();
130        assert_eq!(n.id, "n1");
131        assert_eq!(n.r#type, "system");
132    }
133
134    #[test]
135    fn parse_notification_event_string_data() {
136        let ev = WSEvent {
137            r#type: "event".to_string(),
138            topic: Some("system".to_string()),
139            data: Some(serde_json::Value::String(
140                r#"{"id":"n2","title":"T","content":"C","type":"billing","isRead":true,"createdAt":"x"}"#
141                    .to_string(),
142            )),
143            ..Default::default()
144        };
145        let n = parse_notification_event(&ev).unwrap();
146        assert_eq!(n.id, "n2");
147        assert!(n.is_read);
148    }
149
150    #[test]
151    fn parse_notification_event_non_system_returns_none() {
152        let ev = WSEvent {
153            r#type: "event".to_string(),
154            topic: Some("billing".to_string()),
155            data: Some(serde_json::json!({"id":"x"})),
156            ..Default::default()
157        };
158        assert!(parse_notification_event(&ev).is_none());
159        // type != event
160        let ev2 = WSEvent {
161            r#type: "welcome".to_string(),
162            topic: Some("system".to_string()),
163            ..Default::default()
164        };
165        assert!(parse_notification_event(&ev2).is_none());
166    }
167}