use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DataScopeMode {
All,
Dept,
DeptAndSub,
#[serde(rename = "self")]
Self_,
Custom,
}
impl DataScopeMode {
pub fn as_str(&self) -> &'static str {
match self {
Self::All => "all",
Self::Dept => "dept",
Self::DeptAndSub => "dept_and_sub",
Self::Self_ => "self",
Self::Custom => "custom",
}
}
}
impl std::fmt::Display for DataScopeMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone)]
pub struct DataScopeRule {
pub mode: DataScopeMode,
pub dept_field: Option<String>,
pub creator_field: Option<String>,
pub custom_generator: Option<String>,
pub target_table: String,
pub priority: u32,
}
impl DataScopeRule {
pub fn new(target_table: impl Into<String>, mode: DataScopeMode) -> Self {
Self {
mode,
dept_field: None,
creator_field: None,
custom_generator: None,
target_table: target_table.into(),
priority: 0,
}
}
pub fn with_dept_field(mut self, field: impl Into<String>) -> Self {
self.dept_field = Some(field.into());
self
}
pub fn with_creator_field(mut self, field: impl Into<String>) -> Self {
self.creator_field = Some(field.into());
self
}
pub fn with_custom_generator(mut self, name: impl Into<String>) -> Self {
self.custom_generator = Some(name.into());
self
}
pub fn with_priority(mut self, priority: u32) -> Self {
self.priority = priority;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mode_as_str() {
assert_eq!(DataScopeMode::All.as_str(), "all");
assert_eq!(DataScopeMode::Dept.as_str(), "dept");
assert_eq!(DataScopeMode::DeptAndSub.as_str(), "dept_and_sub");
assert_eq!(DataScopeMode::Self_.as_str(), "self");
assert_eq!(DataScopeMode::Custom.as_str(), "custom");
}
#[test]
fn test_mode_serde() {
let json = serde_json::to_string(&DataScopeMode::DeptAndSub).unwrap();
assert_eq!(json, "\"dept_and_sub\"");
let mode: DataScopeMode = serde_json::from_str("\"self\"").unwrap();
assert_eq!(mode, DataScopeMode::Self_);
}
#[test]
fn test_rule_builder() {
let rule = DataScopeRule::new("order", DataScopeMode::DeptAndSub)
.with_dept_field("dept_id")
.with_priority(10);
assert_eq!(rule.target_table, "order");
assert_eq!(rule.mode, DataScopeMode::DeptAndSub);
assert_eq!(rule.dept_field.as_deref(), Some("dept_id"));
assert_eq!(rule.priority, 10);
}
}