Skip to main content

sz_rust_orm_facade/data_scope/
rule.rs

1//! 数据范围规则定义 — `DataScopeMode` 枚举与 `DataScopeRule` 结构体
2
3use serde::{Deserialize, Serialize};
4
5/// 数据范围模式(5 种)
6///
7/// 对齐 FSSADMIN `DataScopeTrait` 的 scope 类型:
8/// - `All`:全部数据(超级管理员或无限制场景)
9/// - `Dept`:仅本部门数据
10/// - `DeptAndSub`:本部门及所有子部门数据
11/// - `Self_`:仅本人创建的数据
12/// - `Custom`:自定义条件(通过 `CustomConditionGenerator` 生成)
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum DataScopeMode {
16    All,
17    Dept,
18    DeptAndSub,
19    #[serde(rename = "self")]
20    Self_,
21    Custom,
22}
23
24impl DataScopeMode {
25    /// 转为字符串标识(用于日志和指标 label)
26    pub fn as_str(&self) -> &'static str {
27        match self {
28            Self::All => "all",
29            Self::Dept => "dept",
30            Self::DeptAndSub => "dept_and_sub",
31            Self::Self_ => "self",
32            Self::Custom => "custom",
33        }
34    }
35}
36
37impl std::fmt::Display for DataScopeMode {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.write_str(self.as_str())
40    }
41}
42
43/// 数据范围规则
44///
45/// 每条规则绑定一张表,声明该表的数据范围模式和字段映射。
46/// 规则按 `priority` 降序排列,首个匹配的规则生效。
47#[derive(Debug, Clone)]
48pub struct DataScopeRule {
49    /// 数据范围模式
50    pub mode: DataScopeMode,
51    /// 部门字段名(DEPT / DEPT_AND_SUB 模式必填,如 `"dept_id"`)
52    pub dept_field: Option<String>,
53    /// 创建者字段名(SELF 模式必填,如 `"creator_id"`)
54    pub creator_field: Option<String>,
55    /// 自定义条件生成器名称(CUSTOM 模式必填)
56    pub custom_generator: Option<String>,
57    /// 目标表名(如 `"order"`)
58    pub target_table: String,
59    /// 优先级(数值越大优先级越高,同表多规则时取最高优先级)
60    pub priority: u32,
61}
62
63impl DataScopeRule {
64    /// 创建一条新规则
65    pub fn new(target_table: impl Into<String>, mode: DataScopeMode) -> Self {
66        Self {
67            mode,
68            dept_field: None,
69            creator_field: None,
70            custom_generator: None,
71            target_table: target_table.into(),
72            priority: 0,
73        }
74    }
75
76    /// 设置部门字段名
77    pub fn with_dept_field(mut self, field: impl Into<String>) -> Self {
78        self.dept_field = Some(field.into());
79        self
80    }
81
82    /// 设置创建者字段名
83    pub fn with_creator_field(mut self, field: impl Into<String>) -> Self {
84        self.creator_field = Some(field.into());
85        self
86    }
87
88    /// 设置自定义生成器名称
89    pub fn with_custom_generator(mut self, name: impl Into<String>) -> Self {
90        self.custom_generator = Some(name.into());
91        self
92    }
93
94    /// 设置优先级
95    pub fn with_priority(mut self, priority: u32) -> Self {
96        self.priority = priority;
97        self
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn test_mode_as_str() {
107        assert_eq!(DataScopeMode::All.as_str(), "all");
108        assert_eq!(DataScopeMode::Dept.as_str(), "dept");
109        assert_eq!(DataScopeMode::DeptAndSub.as_str(), "dept_and_sub");
110        assert_eq!(DataScopeMode::Self_.as_str(), "self");
111        assert_eq!(DataScopeMode::Custom.as_str(), "custom");
112    }
113
114    #[test]
115    fn test_mode_serde() {
116        let json = serde_json::to_string(&DataScopeMode::DeptAndSub).unwrap();
117        assert_eq!(json, "\"dept_and_sub\"");
118        let mode: DataScopeMode = serde_json::from_str("\"self\"").unwrap();
119        assert_eq!(mode, DataScopeMode::Self_);
120    }
121
122    #[test]
123    fn test_rule_builder() {
124        let rule = DataScopeRule::new("order", DataScopeMode::DeptAndSub)
125            .with_dept_field("dept_id")
126            .with_priority(10);
127        assert_eq!(rule.target_table, "order");
128        assert_eq!(rule.mode, DataScopeMode::DeptAndSub);
129        assert_eq!(rule.dept_field.as_deref(), Some("dept_id"));
130        assert_eq!(rule.priority, 10);
131    }
132
133    #[test]
134    fn test_mode_display() {
135        assert_eq!(format!("{}", DataScopeMode::All), "all");
136        assert_eq!(format!("{}", DataScopeMode::Dept), "dept");
137        assert_eq!(format!("{}", DataScopeMode::DeptAndSub), "dept_and_sub");
138        assert_eq!(format!("{}", DataScopeMode::Self_), "self");
139        assert_eq!(format!("{}", DataScopeMode::Custom), "custom");
140    }
141}