Skip to main content

backbone_maintenance/domain/entity/
maintenance_visit_part.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5use rust_decimal::Decimal;
6use super::AuditMetadata;
7
8/// Strongly-typed ID for MaintenanceVisitPart
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct MaintenanceVisitPartId(pub Uuid);
12
13impl MaintenanceVisitPartId {
14    pub fn new(id: Uuid) -> Self { Self(id) }
15    pub fn generate() -> Self { Self(Uuid::new_v4()) }
16    pub fn into_inner(self) -> Uuid { self.0 }
17}
18
19impl std::fmt::Display for MaintenanceVisitPartId {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        write!(f, "{}", self.0)
22    }
23}
24
25impl std::str::FromStr for MaintenanceVisitPartId {
26    type Err = uuid::Error;
27    fn from_str(s: &str) -> Result<Self, Self::Err> {
28        Ok(Self(Uuid::parse_str(s)?))
29    }
30}
31
32impl From<Uuid> for MaintenanceVisitPartId {
33    fn from(id: Uuid) -> Self { Self(id) }
34}
35
36impl From<MaintenanceVisitPartId> for Uuid {
37    fn from(id: MaintenanceVisitPartId) -> Self { id.0 }
38}
39
40impl AsRef<Uuid> for MaintenanceVisitPartId {
41    fn as_ref(&self) -> &Uuid { &self.0 }
42}
43
44impl std::ops::Deref for MaintenanceVisitPartId {
45    type Target = Uuid;
46    fn deref(&self) -> &Self::Target { &self.0 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
50pub struct MaintenanceVisitPart {
51    pub id: Uuid,
52    pub visit_id: Uuid,
53    pub item_id: Uuid,
54    pub quantity: Decimal,
55    pub unit_cost: Decimal,
56    pub amount: Decimal,
57    #[serde(default)]
58    #[sqlx(json)]
59    pub metadata: AuditMetadata,
60}
61
62impl MaintenanceVisitPart {
63    /// Create a builder for MaintenanceVisitPart
64    pub fn builder() -> MaintenanceVisitPartBuilder {
65        <MaintenanceVisitPartBuilder as Default>::default()
66    }
67
68    /// Create a new MaintenanceVisitPart with required fields
69    pub fn new(visit_id: Uuid, item_id: Uuid, quantity: Decimal, unit_cost: Decimal, amount: Decimal) -> Self {
70        Self {
71            id: Uuid::new_v4(),
72            visit_id,
73            item_id,
74            quantity,
75            unit_cost,
76            amount,
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) -> MaintenanceVisitPartId {
88        MaintenanceVisitPartId(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
132    // ==========================================================
133    // Partial Update
134    // ==========================================================
135
136    /// Apply partial updates from a map of field name to JSON value
137    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
138        for (key, value) in fields {
139            match key.as_str() {
140                "visit_id" => {
141                    if let Ok(v) = serde_json::from_value(value) { self.visit_id = v; }
142                }
143                "item_id" => {
144                    if let Ok(v) = serde_json::from_value(value) { self.item_id = v; }
145                }
146                "quantity" => {
147                    if let Ok(v) = serde_json::from_value(value) { self.quantity = v; }
148                }
149                "unit_cost" => {
150                    if let Ok(v) = serde_json::from_value(value) { self.unit_cost = v; }
151                }
152                "amount" => {
153                    if let Ok(v) = serde_json::from_value(value) { self.amount = v; }
154                }
155                _ => {} // ignore unknown fields
156            }
157        }
158    }
159
160    // <<< CUSTOM METHODS START >>>
161    // <<< CUSTOM METHODS END >>>
162}
163
164impl super::Entity for MaintenanceVisitPart {
165    type Id = Uuid;
166
167    fn entity_id(&self) -> &Self::Id {
168        &self.id
169    }
170
171    fn entity_type() -> &'static str {
172        "MaintenanceVisitPart"
173    }
174}
175
176impl backbone_core::PersistentEntity for MaintenanceVisitPart {
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 MaintenanceVisitPart {
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("visit_id".to_string(), "uuid".to_string());
210        m.insert("item_id".to_string(), "uuid".to_string());
211        m
212    }
213    fn search_fields() -> &'static [&'static str] {
214        &[]
215    }
216}
217
218/// Builder for MaintenanceVisitPart entity
219///
220/// Provides a fluent API for constructing MaintenanceVisitPart instances.
221/// System fields (id, metadata, timestamps) are auto-initialized.
222#[derive(Debug, Clone, Default)]
223pub struct MaintenanceVisitPartBuilder {
224    visit_id: Option<Uuid>,
225    item_id: Option<Uuid>,
226    quantity: Option<Decimal>,
227    unit_cost: Option<Decimal>,
228    amount: Option<Decimal>,
229}
230
231impl MaintenanceVisitPartBuilder {
232    /// Set the visit_id field (required)
233    pub fn visit_id(mut self, value: Uuid) -> Self {
234        self.visit_id = Some(value);
235        self
236    }
237
238    /// Set the item_id field (required)
239    pub fn item_id(mut self, value: Uuid) -> Self {
240        self.item_id = Some(value);
241        self
242    }
243
244    /// Set the quantity field (default: `Decimal::from(0)`)
245    pub fn quantity(mut self, value: Decimal) -> Self {
246        self.quantity = Some(value);
247        self
248    }
249
250    /// Set the unit_cost field (default: `Decimal::from(0)`)
251    pub fn unit_cost(mut self, value: Decimal) -> Self {
252        self.unit_cost = Some(value);
253        self
254    }
255
256    /// Set the amount field (default: `Decimal::from(0)`)
257    pub fn amount(mut self, value: Decimal) -> Self {
258        self.amount = Some(value);
259        self
260    }
261
262    /// Build the MaintenanceVisitPart entity
263    ///
264    /// Returns Err if any required field without a default is missing.
265    pub fn build(self) -> Result<MaintenanceVisitPart, String> {
266        let visit_id = self.visit_id.ok_or_else(|| "visit_id is required".to_string())?;
267        let item_id = self.item_id.ok_or_else(|| "item_id is required".to_string())?;
268
269        Ok(MaintenanceVisitPart {
270            id: Uuid::new_v4(),
271            visit_id,
272            item_id,
273            quantity: self.quantity.unwrap_or(Decimal::from(0)),
274            unit_cost: self.unit_cost.unwrap_or(Decimal::from(0)),
275            amount: self.amount.unwrap_or(Decimal::from(0)),
276            metadata: AuditMetadata::default(),
277        })
278    }
279}