Skip to main content

yang_base/
admin.rs

1//! 可选后台展示元数据。
2//!
3//! 本模块只保存对 Action/Table/DefinitionCatalog 稳定 ID 的引用,不持有或修改 dispatch 对象。
4//! 审核流、业务状态机和权限判定仍属于业务插件,不进入这些展示类型。
5
6use crate::BaseError;
7use std::collections::BTreeMap;
8
9/// 后台组件的展示形态。
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum AdminDisplayKind {
13    /// 导航菜单。
14    Menu,
15    /// 操作按钮。
16    Button,
17    /// 列表视图。
18    List,
19    /// 树形视图。
20    Tree,
21    /// 表单视图。
22    Form,
23}
24
25/// 展示元数据引用的稳定核心目标。
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum AdminTarget {
29    /// Registry 中的 Action 稳定名称。
30    Action {
31        /// 模块名。
32        module: String,
33        /// Action 名。
34        action: String,
35    },
36    /// 模块内的 [`crate::table::TableDefinition`] 稳定名称。
37    Table {
38        /// 模块名。
39        module: String,
40        /// 表名。
41        table: String,
42    },
43    /// DefinitionCatalog 的 operation id。
44    ApiOperation {
45        /// operation id。
46        operation_id: String,
47    },
48}
49
50impl AdminTarget {
51    /// 构造 Action 引用。
52    pub fn action(module: &str, action: &str) -> Result<Self, BaseError> {
53        validate_stable_id(module)?;
54        validate_stable_id(action)?;
55        Ok(Self::Action {
56            module: module.to_string(),
57            action: action.to_string(),
58        })
59    }
60
61    /// 构造 Table 引用。
62    pub fn table(module: &str, table: &str) -> Result<Self, BaseError> {
63        validate_stable_id(module)?;
64        validate_stable_id(table)?;
65        Ok(Self::Table {
66            module: module.to_string(),
67            table: table.to_string(),
68        })
69    }
70
71    /// 构造 DefinitionCatalog operation id 引用。
72    pub fn api_operation(operation_id: &str) -> Result<Self, BaseError> {
73        validate_stable_id(operation_id)?;
74        Ok(Self::ApiOperation {
75            operation_id: operation_id.to_string(),
76        })
77    }
78}
79
80/// 一项后台展示描述。
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct AdminMetadata {
83    /// 展示项自身的稳定 ID。
84    pub id: String,
85    /// 用户可见标题。
86    pub label: String,
87    /// 展示形态。
88    pub kind: AdminDisplayKind,
89    /// 被引用的核心对象稳定 ID。
90    pub target: AdminTarget,
91    /// 可选图标名称。
92    pub icon: Option<String>,
93    /// 可选展示分组。
94    pub group: Option<String>,
95    /// 确定性排序权重。
96    pub order: i32,
97}
98
99impl AdminMetadata {
100    /// 创建展示项并校验稳定 ID 与非空标题。
101    pub fn new(
102        id: &str,
103        label: &str,
104        kind: AdminDisplayKind,
105        target: AdminTarget,
106    ) -> Result<Self, BaseError> {
107        validate_stable_id(id)?;
108        if label.trim().is_empty() {
109            return Err(BaseError::ConfigError("后台元数据标题不能为空".to_string()));
110        }
111        Ok(Self {
112            id: id.to_string(),
113            label: label.to_string(),
114            kind,
115            target,
116            icon: None,
117            group: None,
118            order: 0,
119        })
120    }
121
122    /// 设置图标名称。
123    pub fn icon(mut self, icon: impl Into<String>) -> Self {
124        self.icon = Some(icon.into());
125        self
126    }
127
128    /// 设置展示分组。
129    pub fn group(mut self, group: impl Into<String>) -> Self {
130        self.group = Some(group.into());
131        self
132    }
133
134    /// 设置排序权重。
135    pub fn order(mut self, order: i32) -> Self {
136        self.order = order;
137        self
138    }
139}
140
141/// 确定性、只读的后台元数据注册表。
142#[derive(Debug, Clone)]
143pub struct AdminMetadataRegistry {
144    entries: Vec<AdminMetadata>,
145    positions: BTreeMap<String, usize>,
146}
147
148impl AdminMetadataRegistry {
149    /// 构建注册表;重复 ID 直接失败。
150    pub fn new(mut entries: Vec<AdminMetadata>) -> Result<Self, BaseError> {
151        entries.sort_by(|left, right| {
152            left.order
153                .cmp(&right.order)
154                .then_with(|| left.id.cmp(&right.id))
155        });
156        let mut positions = BTreeMap::new();
157        for (index, entry) in entries.iter().enumerate() {
158            if positions.insert(entry.id.clone(), index).is_some() {
159                return Err(BaseError::ConfigError(format!(
160                    "后台元数据 ID 重复: {}",
161                    entry.id
162                )));
163            }
164        }
165        Ok(Self { entries, positions })
166    }
167
168    /// 返回确定性排序的全部展示项。
169    pub fn entries(&self) -> &[AdminMetadata] {
170        &self.entries
171    }
172
173    /// 按稳定 ID 查询展示项。
174    pub fn get(&self, id: &str) -> Option<&AdminMetadata> {
175        self.positions
176            .get(id)
177            .and_then(|index| self.entries.get(*index))
178    }
179}
180
181fn validate_stable_id(id: &str) -> Result<(), BaseError> {
182    let mut chars = id.chars();
183    let Some(first) = chars.next() else {
184        return Err(BaseError::ConfigError("稳定 ID 不能为空".to_string()));
185    };
186    if !first.is_ascii_alphabetic()
187        || !chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | ':'))
188    {
189        return Err(BaseError::ConfigError(format!("非法稳定 ID: {id:?}")));
190    }
191    Ok(())
192}