Skip to main content

backbone_inventory/domain/entity/
lot.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 Lot
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct LotId(pub Uuid);
12
13impl LotId {
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 LotId {
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 LotId {
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 LotId {
33    fn from(id: Uuid) -> Self { Self(id) }
34}
35
36impl From<LotId> for Uuid {
37    fn from(id: LotId) -> Self { id.0 }
38}
39
40impl AsRef<Uuid> for LotId {
41    fn as_ref(&self) -> &Uuid { &self.0 }
42}
43
44impl std::ops::Deref for LotId {
45    type Target = Uuid;
46    fn deref(&self) -> &Self::Target { &self.0 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
50pub struct Lot {
51    pub id: Uuid,
52    pub name: String,
53    pub reference: Option<String>,
54    pub item_id: Uuid,
55    pub product_qty: Decimal,
56    pub location_id: Option<Uuid>,
57    pub note: Option<String>,
58    #[serde(default)]
59    #[sqlx(json)]
60    pub metadata: AuditMetadata,
61}
62
63impl Lot {
64    /// Create a builder for Lot
65    pub fn builder() -> LotBuilder {
66        <LotBuilder as Default>::default()
67    }
68
69    /// Create a new Lot with required fields
70    pub fn new(name: String, item_id: Uuid, product_qty: Decimal) -> Self {
71        Self {
72            id: Uuid::new_v4(),
73            name,
74            reference: None,
75            item_id,
76            product_qty,
77            location_id: None,
78            note: None,
79            metadata: AuditMetadata::default(),
80        }
81    }
82
83    /// Get the entity's unique identifier
84    pub fn id(&self) -> &Uuid {
85        &self.id
86    }
87
88    /// Get a strongly-typed ID for this entity
89    pub fn typed_id(&self) -> LotId {
90        LotId(self.id)
91    }
92
93    /// Get when this entity was created
94    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
95        self.metadata.created_at.as_ref()
96    }
97
98    /// Get when this entity was last updated
99    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
100        self.metadata.updated_at.as_ref()
101    }
102
103    /// Check if this entity is soft deleted
104    pub fn is_deleted(&self) -> bool {
105        self.metadata.deleted_at.is_some()
106    }
107
108    /// Check if this entity is active (not deleted)
109    pub fn is_active(&self) -> bool {
110        self.metadata.deleted_at.is_none()
111    }
112
113    /// Get when this entity was deleted
114    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
115        self.metadata.deleted_at.as_ref()
116    }
117
118    /// Get who created this entity
119    pub fn created_by(&self) -> Option<&Uuid> {
120        self.metadata.created_by.as_ref()
121    }
122
123    /// Get who last updated this entity
124    pub fn updated_by(&self) -> Option<&Uuid> {
125        self.metadata.updated_by.as_ref()
126    }
127
128    /// Get who deleted this entity
129    pub fn deleted_by(&self) -> Option<&Uuid> {
130        self.metadata.deleted_by.as_ref()
131    }
132
133
134    // ==========================================================
135    // Fluent Setters (with_* for optional fields)
136    // ==========================================================
137
138    /// Set the reference field (chainable)
139    pub fn with_reference(mut self, value: String) -> Self {
140        self.reference = Some(value);
141        self
142    }
143
144    /// Set the location_id field (chainable)
145    pub fn with_location_id(mut self, value: Uuid) -> Self {
146        self.location_id = Some(value);
147        self
148    }
149
150    /// Set the note field (chainable)
151    pub fn with_note(mut self, value: String) -> Self {
152        self.note = Some(value);
153        self
154    }
155
156    // ==========================================================
157    // Partial Update
158    // ==========================================================
159
160    /// Apply partial updates from a map of field name to JSON value
161    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
162        for (key, value) in fields {
163            match key.as_str() {
164                "name" => {
165                    if let Ok(v) = serde_json::from_value(value) { self.name = v; }
166                }
167                "reference" => {
168                    if let Ok(v) = serde_json::from_value(value) { self.reference = v; }
169                }
170                "item_id" => {
171                    if let Ok(v) = serde_json::from_value(value) { self.item_id = v; }
172                }
173                "product_qty" => {
174                    if let Ok(v) = serde_json::from_value(value) { self.product_qty = v; }
175                }
176                "location_id" => {
177                    if let Ok(v) = serde_json::from_value(value) { self.location_id = v; }
178                }
179                "note" => {
180                    if let Ok(v) = serde_json::from_value(value) { self.note = v; }
181                }
182                _ => {} // ignore unknown fields
183            }
184        }
185    }
186
187}
188
189impl super::Entity for Lot {
190    type Id = Uuid;
191
192    fn entity_id(&self) -> &Self::Id {
193        &self.id
194    }
195
196    fn entity_type() -> &'static str {
197        "Lot"
198    }
199}
200
201impl backbone_core::PersistentEntity for Lot {
202    fn entity_id(&self) -> String {
203        self.id.to_string()
204    }
205    fn set_entity_id(&mut self, id: String) {
206        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
207            self.id = uuid;
208        }
209    }
210    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
211        self.metadata.created_at
212    }
213    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
214        self.metadata.created_at = Some(ts);
215    }
216    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
217        self.metadata.updated_at
218    }
219    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
220        self.metadata.updated_at = Some(ts);
221    }
222    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
223        self.metadata.deleted_at
224    }
225    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
226        self.metadata.deleted_at = ts;
227    }
228}
229
230impl backbone_orm::EntityRepoMeta for Lot {
231    fn column_types() -> std::collections::HashMap<String, String> {
232        let mut m = std::collections::HashMap::new();
233        m.insert("id".to_string(), "uuid".to_string());
234        m.insert("item_id".to_string(), "uuid".to_string());
235        m.insert("location_id".to_string(), "uuid".to_string());
236        m
237    }
238    fn search_fields() -> &'static [&'static str] {
239        &["name"]
240    }
241    fn relations() -> &'static [(&'static str, &'static str, &'static str)] {
242        &[("location", "locations", "locationId")]
243    }
244}
245
246/// Builder for Lot entity
247///
248/// Provides a fluent API for constructing Lot instances.
249/// System fields (id, metadata, timestamps) are auto-initialized.
250#[derive(Debug, Clone, Default)]
251pub struct LotBuilder {
252    name: Option<String>,
253    reference: Option<String>,
254    item_id: Option<Uuid>,
255    product_qty: Option<Decimal>,
256    location_id: Option<Uuid>,
257    note: Option<String>,
258}
259
260impl LotBuilder {
261    /// Set the name field (required)
262    pub fn name(mut self, value: String) -> Self {
263        self.name = Some(value);
264        self
265    }
266
267    /// Set the reference field (optional)
268    pub fn reference(mut self, value: String) -> Self {
269        self.reference = Some(value);
270        self
271    }
272
273    /// Set the item_id field (required)
274    pub fn item_id(mut self, value: Uuid) -> Self {
275        self.item_id = Some(value);
276        self
277    }
278
279    /// Set the product_qty field (default: `Decimal::from(0)`)
280    pub fn product_qty(mut self, value: Decimal) -> Self {
281        self.product_qty = Some(value);
282        self
283    }
284
285    /// Set the location_id field (optional)
286    pub fn location_id(mut self, value: Uuid) -> Self {
287        self.location_id = Some(value);
288        self
289    }
290
291    /// Set the note field (optional)
292    pub fn note(mut self, value: String) -> Self {
293        self.note = Some(value);
294        self
295    }
296
297    /// Build the Lot entity
298    ///
299    /// Returns Err if any required field without a default is missing.
300    pub fn build(self) -> Result<Lot, String> {
301        let name = self.name.ok_or_else(|| "name is required".to_string())?;
302        let item_id = self.item_id.ok_or_else(|| "item_id is required".to_string())?;
303
304        Ok(Lot {
305            id: Uuid::new_v4(),
306            name,
307            reference: self.reference,
308            item_id,
309            product_qty: self.product_qty.unwrap_or(Decimal::from(0)),
310            location_id: self.location_id,
311            note: self.note,
312            metadata: AuditMetadata::default(),
313        })
314    }
315}