Skip to main content

backbone_support/domain/entity/
service_level_agreement.rs

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