Skip to main content

backbone_catalog/domain/entity/
attribute.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5
6use super::AttributeType;
7use super::CatalogStatus;
8use super::AuditMetadata;
9
10/// Strongly-typed ID for Attribute
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct AttributeId(pub Uuid);
14
15impl AttributeId {
16    pub fn new(id: Uuid) -> Self { Self(id) }
17    pub fn generate() -> Self { Self(Uuid::new_v4()) }
18    pub fn into_inner(self) -> Uuid { self.0 }
19}
20
21impl std::fmt::Display for AttributeId {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        write!(f, "{}", self.0)
24    }
25}
26
27impl std::str::FromStr for AttributeId {
28    type Err = uuid::Error;
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        Ok(Self(Uuid::parse_str(s)?))
31    }
32}
33
34impl From<Uuid> for AttributeId {
35    fn from(id: Uuid) -> Self { Self(id) }
36}
37
38impl From<AttributeId> for Uuid {
39    fn from(id: AttributeId) -> Self { id.0 }
40}
41
42impl AsRef<Uuid> for AttributeId {
43    fn as_ref(&self) -> &Uuid { &self.0 }
44}
45
46impl std::ops::Deref for AttributeId {
47    type Target = Uuid;
48    fn deref(&self) -> &Self::Target { &self.0 }
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
52pub struct Attribute {
53    pub id: Uuid,
54    pub code: String,
55    pub name: String,
56    pub attribute_type: AttributeType,
57    pub status: CatalogStatus,
58    #[serde(default)]
59    #[sqlx(json)]
60    pub metadata: AuditMetadata,
61}
62
63impl Attribute {
64    /// Create a builder for Attribute
65    pub fn builder() -> AttributeBuilder {
66        <AttributeBuilder as Default>::default()
67    }
68
69    /// Create a new Attribute with required fields
70    pub fn new(code: String, name: String, attribute_type: AttributeType, status: CatalogStatus) -> Self {
71        Self {
72            id: Uuid::new_v4(),
73            code,
74            name,
75            attribute_type,
76            status,
77            metadata: AuditMetadata::default(),
78        }
79    }
80
81    /// Get the entity's unique identifier
82    pub fn id(&self) -> &Uuid {
83        &self.id
84    }
85
86    /// Get a strongly-typed ID for this entity
87    pub fn typed_id(&self) -> AttributeId {
88        AttributeId(self.id)
89    }
90
91    /// Get when this entity was created
92    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
93        self.metadata.created_at.as_ref()
94    }
95
96    /// Get when this entity was last updated
97    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
98        self.metadata.updated_at.as_ref()
99    }
100
101    /// Check if this entity is soft deleted
102    pub fn is_deleted(&self) -> bool {
103        self.metadata.deleted_at.is_some()
104    }
105
106    /// Check if this entity is active (not deleted)
107    pub fn is_active(&self) -> bool {
108        self.metadata.deleted_at.is_none()
109    }
110
111    /// Get when this entity was deleted
112    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
113        self.metadata.deleted_at.as_ref()
114    }
115
116    /// Get who created this entity
117    pub fn created_by(&self) -> Option<&Uuid> {
118        self.metadata.created_by.as_ref()
119    }
120
121    /// Get who last updated this entity
122    pub fn updated_by(&self) -> Option<&Uuid> {
123        self.metadata.updated_by.as_ref()
124    }
125
126    /// Get who deleted this entity
127    pub fn deleted_by(&self) -> Option<&Uuid> {
128        self.metadata.deleted_by.as_ref()
129    }
130
131    /// Get the current status
132    pub fn status(&self) -> &CatalogStatus {
133        &self.status
134    }
135
136
137    // ==========================================================
138    // Partial Update
139    // ==========================================================
140
141    /// Apply partial updates from a map of field name to JSON value
142    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
143        for (key, value) in fields {
144            match key.as_str() {
145                "code" => {
146                    if let Ok(v) = serde_json::from_value(value) { self.code = v; }
147                }
148                "name" => {
149                    if let Ok(v) = serde_json::from_value(value) { self.name = v; }
150                }
151                "attribute_type" => {
152                    if let Ok(v) = serde_json::from_value(value) { self.attribute_type = v; }
153                }
154                "status" => {
155                    if let Ok(v) = serde_json::from_value(value) { self.status = v; }
156                }
157                _ => {} // ignore unknown fields
158            }
159        }
160    }
161
162}
163
164impl super::Entity for Attribute {
165    type Id = Uuid;
166
167    fn entity_id(&self) -> &Self::Id {
168        &self.id
169    }
170
171    fn entity_type() -> &'static str {
172        "Attribute"
173    }
174}
175
176impl backbone_core::PersistentEntity for Attribute {
177    fn entity_id(&self) -> String {
178        self.id.to_string()
179    }
180    fn set_entity_id(&mut self, id: String) {
181        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
182            self.id = uuid;
183        }
184    }
185    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
186        self.metadata.created_at
187    }
188    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
189        self.metadata.created_at = Some(ts);
190    }
191    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
192        self.metadata.updated_at
193    }
194    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
195        self.metadata.updated_at = Some(ts);
196    }
197    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
198        self.metadata.deleted_at
199    }
200    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
201        self.metadata.deleted_at = ts;
202    }
203}
204
205impl backbone_orm::EntityRepoMeta for Attribute {
206    fn column_types() -> std::collections::HashMap<String, String> {
207        let mut m = std::collections::HashMap::new();
208        m.insert("id".to_string(), "uuid".to_string());
209        m.insert("attribute_type".to_string(), "attribute_type".to_string());
210        m.insert("status".to_string(), "catalog_status".to_string());
211        m
212    }
213    fn search_fields() -> &'static [&'static str] {
214        &["code", "name"]
215    }
216}
217
218/// Builder for Attribute entity
219///
220/// Provides a fluent API for constructing Attribute instances.
221/// System fields (id, metadata, timestamps) are auto-initialized.
222#[derive(Debug, Clone, Default)]
223pub struct AttributeBuilder {
224    code: Option<String>,
225    name: Option<String>,
226    attribute_type: Option<AttributeType>,
227    status: Option<CatalogStatus>,
228}
229
230impl AttributeBuilder {
231    /// Set the code field (required)
232    pub fn code(mut self, value: String) -> Self {
233        self.code = Some(value);
234        self
235    }
236
237    /// Set the name field (required)
238    pub fn name(mut self, value: String) -> Self {
239        self.name = Some(value);
240        self
241    }
242
243    /// Set the attribute_type field (default: `AttributeType::default()`)
244    pub fn attribute_type(mut self, value: AttributeType) -> Self {
245        self.attribute_type = Some(value);
246        self
247    }
248
249    /// Set the status field (default: `CatalogStatus::default()`)
250    pub fn status(mut self, value: CatalogStatus) -> Self {
251        self.status = Some(value);
252        self
253    }
254
255    /// Build the Attribute entity
256    ///
257    /// Returns Err if any required field without a default is missing.
258    pub fn build(self) -> Result<Attribute, String> {
259        let code = self.code.ok_or_else(|| "code is required".to_string())?;
260        let name = self.name.ok_or_else(|| "name is required".to_string())?;
261
262        Ok(Attribute {
263            id: Uuid::new_v4(),
264            code,
265            name,
266            attribute_type: self.attribute_type.unwrap_or_default(),
267            status: self.status.unwrap_or_default(),
268            metadata: AuditMetadata::default(),
269        })
270    }
271}