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}
157
158impl super::Entity for ServiceLevelAgreement {
159    type Id = Uuid;
160
161    fn entity_id(&self) -> &Self::Id {
162        &self.id
163    }
164
165    fn entity_type() -> &'static str {
166        "ServiceLevelAgreement"
167    }
168}
169
170impl backbone_core::PersistentEntity for ServiceLevelAgreement {
171    fn entity_id(&self) -> String {
172        self.id.to_string()
173    }
174    fn set_entity_id(&mut self, id: String) {
175        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
176            self.id = uuid;
177        }
178    }
179    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
180        self.metadata.created_at
181    }
182    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
183        self.metadata.created_at = Some(ts);
184    }
185    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
186        self.metadata.updated_at
187    }
188    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
189        self.metadata.updated_at = Some(ts);
190    }
191    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
192        self.metadata.deleted_at
193    }
194    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
195        self.metadata.deleted_at = ts;
196    }
197}
198
199impl backbone_orm::EntityRepoMeta for ServiceLevelAgreement {
200    fn column_types() -> std::collections::HashMap<String, String> {
201        let mut m = std::collections::HashMap::new();
202        m.insert("id".to_string(), "uuid".to_string());
203        m.insert("status".to_string(), "service_level_agreement_status".to_string());
204        m
205    }
206    fn search_fields() -> &'static [&'static str] {
207        &["name"]
208    }
209}
210
211/// Builder for ServiceLevelAgreement entity
212///
213/// Provides a fluent API for constructing ServiceLevelAgreement instances.
214/// System fields (id, metadata, timestamps) are auto-initialized.
215#[derive(Debug, Clone, Default)]
216pub struct ServiceLevelAgreementBuilder {
217    name: Option<String>,
218    is_default: Option<bool>,
219    status: Option<ServiceLevelAgreementStatus>,
220}
221
222impl ServiceLevelAgreementBuilder {
223    /// Set the name field (required)
224    pub fn name(mut self, value: String) -> Self {
225        self.name = Some(value);
226        self
227    }
228
229    /// Set the is_default field (default: `false`)
230    pub fn is_default(mut self, value: bool) -> Self {
231        self.is_default = Some(value);
232        self
233    }
234
235    /// Set the status field (default: `ServiceLevelAgreementStatus::default()`)
236    pub fn status(mut self, value: ServiceLevelAgreementStatus) -> Self {
237        self.status = Some(value);
238        self
239    }
240
241    /// Build the ServiceLevelAgreement entity
242    ///
243    /// Returns Err if any required field without a default is missing.
244    pub fn build(self) -> Result<ServiceLevelAgreement, String> {
245        let name = self.name.ok_or_else(|| "name is required".to_string())?;
246
247        Ok(ServiceLevelAgreement {
248            id: Uuid::new_v4(),
249            name,
250            is_default: self.is_default.unwrap_or(false),
251            status: self.status.unwrap_or_default(),
252            metadata: AuditMetadata::default(),
253        })
254    }
255}