Skip to main content

backbone_inventory/domain/entity/
quant.rs

1use chrono::{DateTime, Utc, NaiveDate};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5use rust_decimal::Decimal;
6use super::AuditMetadata;
7
8/// Strongly-typed ID for Quant
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct QuantId(pub Uuid);
12
13impl QuantId {
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 QuantId {
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 QuantId {
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 QuantId {
33    fn from(id: Uuid) -> Self { Self(id) }
34}
35
36impl From<QuantId> for Uuid {
37    fn from(id: QuantId) -> Self { id.0 }
38}
39
40impl AsRef<Uuid> for QuantId {
41    fn as_ref(&self) -> &Uuid { &self.0 }
42}
43
44impl std::ops::Deref for QuantId {
45    type Target = Uuid;
46    fn deref(&self) -> &Self::Target { &self.0 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
50pub struct Quant {
51    pub id: Uuid,
52    pub item_id: Uuid,
53    pub location_id: Uuid,
54    pub lot_id: Option<Uuid>,
55    pub package_id: Option<Uuid>,
56    pub owner_id: Option<Uuid>,
57    pub quantity: Decimal,
58    pub reserved_quantity: Decimal,
59    pub available_quantity: Decimal,
60    pub in_date: Option<DateTime<Utc>>,
61    pub inventory_quantity: Option<Decimal>,
62    pub inventory_diff_quantity: Option<Decimal>,
63    pub inventory_quantity_set: bool,
64    pub inventory_date: Option<NaiveDate>,
65    pub sn_duplicated: bool,
66    #[serde(default)]
67    #[sqlx(json)]
68    pub metadata: AuditMetadata,
69}
70
71impl Quant {
72    /// Create a builder for Quant
73    pub fn builder() -> QuantBuilder {
74        <QuantBuilder as Default>::default()
75    }
76
77    /// Create a new Quant with required fields
78    pub fn new(item_id: Uuid, location_id: Uuid, quantity: Decimal, reserved_quantity: Decimal, available_quantity: Decimal, inventory_quantity_set: bool, sn_duplicated: bool) -> Self {
79        Self {
80            id: Uuid::new_v4(),
81            item_id,
82            location_id,
83            lot_id: None,
84            package_id: None,
85            owner_id: None,
86            quantity,
87            reserved_quantity,
88            available_quantity,
89            in_date: None,
90            inventory_quantity: None,
91            inventory_diff_quantity: None,
92            inventory_quantity_set,
93            inventory_date: None,
94            sn_duplicated,
95            metadata: AuditMetadata::default(),
96        }
97    }
98
99    /// Get the entity's unique identifier
100    pub fn id(&self) -> &Uuid {
101        &self.id
102    }
103
104    /// Get a strongly-typed ID for this entity
105    pub fn typed_id(&self) -> QuantId {
106        QuantId(self.id)
107    }
108
109    /// Get when this entity was created
110    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
111        self.metadata.created_at.as_ref()
112    }
113
114    /// Get when this entity was last updated
115    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
116        self.metadata.updated_at.as_ref()
117    }
118
119    /// Check if this entity is soft deleted
120    pub fn is_deleted(&self) -> bool {
121        self.metadata.deleted_at.is_some()
122    }
123
124    /// Check if this entity is active (not deleted)
125    pub fn is_active(&self) -> bool {
126        self.metadata.deleted_at.is_none()
127    }
128
129    /// Get when this entity was deleted
130    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
131        self.metadata.deleted_at.as_ref()
132    }
133
134    /// Get who created this entity
135    pub fn created_by(&self) -> Option<&Uuid> {
136        self.metadata.created_by.as_ref()
137    }
138
139    /// Get who last updated this entity
140    pub fn updated_by(&self) -> Option<&Uuid> {
141        self.metadata.updated_by.as_ref()
142    }
143
144    /// Get who deleted this entity
145    pub fn deleted_by(&self) -> Option<&Uuid> {
146        self.metadata.deleted_by.as_ref()
147    }
148
149
150    // ==========================================================
151    // Fluent Setters (with_* for optional fields)
152    // ==========================================================
153
154    /// Set the lot_id field (chainable)
155    pub fn with_lot_id(mut self, value: Uuid) -> Self {
156        self.lot_id = Some(value);
157        self
158    }
159
160    /// Set the package_id field (chainable)
161    pub fn with_package_id(mut self, value: Uuid) -> Self {
162        self.package_id = Some(value);
163        self
164    }
165
166    /// Set the owner_id field (chainable)
167    pub fn with_owner_id(mut self, value: Uuid) -> Self {
168        self.owner_id = Some(value);
169        self
170    }
171
172    /// Set the in_date field (chainable)
173    pub fn with_in_date(mut self, value: DateTime<Utc>) -> Self {
174        self.in_date = Some(value);
175        self
176    }
177
178    /// Set the inventory_quantity field (chainable)
179    pub fn with_inventory_quantity(mut self, value: Decimal) -> Self {
180        self.inventory_quantity = Some(value);
181        self
182    }
183
184    /// Set the inventory_diff_quantity field (chainable)
185    pub fn with_inventory_diff_quantity(mut self, value: Decimal) -> Self {
186        self.inventory_diff_quantity = Some(value);
187        self
188    }
189
190    /// Set the inventory_date field (chainable)
191    pub fn with_inventory_date(mut self, value: NaiveDate) -> Self {
192        self.inventory_date = Some(value);
193        self
194    }
195
196    // ==========================================================
197    // Partial Update
198    // ==========================================================
199
200    /// Apply partial updates from a map of field name to JSON value
201    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
202        for (key, value) in fields {
203            match key.as_str() {
204                "item_id" => {
205                    if let Ok(v) = serde_json::from_value(value) { self.item_id = v; }
206                }
207                "location_id" => {
208                    if let Ok(v) = serde_json::from_value(value) { self.location_id = v; }
209                }
210                "lot_id" => {
211                    if let Ok(v) = serde_json::from_value(value) { self.lot_id = v; }
212                }
213                "package_id" => {
214                    if let Ok(v) = serde_json::from_value(value) { self.package_id = v; }
215                }
216                "owner_id" => {
217                    if let Ok(v) = serde_json::from_value(value) { self.owner_id = v; }
218                }
219                "quantity" => {
220                    if let Ok(v) = serde_json::from_value(value) { self.quantity = v; }
221                }
222                "reserved_quantity" => {
223                    if let Ok(v) = serde_json::from_value(value) { self.reserved_quantity = v; }
224                }
225                "available_quantity" => {
226                    if let Ok(v) = serde_json::from_value(value) { self.available_quantity = v; }
227                }
228                "in_date" => {
229                    if let Ok(v) = serde_json::from_value(value) { self.in_date = v; }
230                }
231                "inventory_quantity" => {
232                    if let Ok(v) = serde_json::from_value(value) { self.inventory_quantity = v; }
233                }
234                "inventory_diff_quantity" => {
235                    if let Ok(v) = serde_json::from_value(value) { self.inventory_diff_quantity = v; }
236                }
237                "inventory_quantity_set" => {
238                    if let Ok(v) = serde_json::from_value(value) { self.inventory_quantity_set = v; }
239                }
240                "inventory_date" => {
241                    if let Ok(v) = serde_json::from_value(value) { self.inventory_date = v; }
242                }
243                "sn_duplicated" => {
244                    if let Ok(v) = serde_json::from_value(value) { self.sn_duplicated = v; }
245                }
246                _ => {} // ignore unknown fields
247            }
248        }
249    }
250
251}
252
253impl super::Entity for Quant {
254    type Id = Uuid;
255
256    fn entity_id(&self) -> &Self::Id {
257        &self.id
258    }
259
260    fn entity_type() -> &'static str {
261        "Quant"
262    }
263}
264
265impl backbone_core::PersistentEntity for Quant {
266    fn entity_id(&self) -> String {
267        self.id.to_string()
268    }
269    fn set_entity_id(&mut self, id: String) {
270        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
271            self.id = uuid;
272        }
273    }
274    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
275        self.metadata.created_at
276    }
277    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
278        self.metadata.created_at = Some(ts);
279    }
280    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
281        self.metadata.updated_at
282    }
283    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
284        self.metadata.updated_at = Some(ts);
285    }
286    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
287        self.metadata.deleted_at
288    }
289    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
290        self.metadata.deleted_at = ts;
291    }
292}
293
294impl backbone_orm::EntityRepoMeta for Quant {
295    fn column_types() -> std::collections::HashMap<String, String> {
296        let mut m = std::collections::HashMap::new();
297        m.insert("id".to_string(), "uuid".to_string());
298        m.insert("item_id".to_string(), "uuid".to_string());
299        m.insert("location_id".to_string(), "uuid".to_string());
300        m.insert("lot_id".to_string(), "uuid".to_string());
301        m.insert("package_id".to_string(), "uuid".to_string());
302        m.insert("owner_id".to_string(), "uuid".to_string());
303        m.insert("in_date".to_string(), "timestamptz".to_string());
304        m.insert("inventory_date".to_string(), "date".to_string());
305        m
306    }
307    fn search_fields() -> &'static [&'static str] {
308        &[]
309    }
310    fn relations() -> &'static [(&'static str, &'static str, &'static str)] {
311        &[("location", "locations", "locationId"), ("lot", "lots", "lotId"), ("package", "packages", "packageId")]
312    }
313}
314
315/// Builder for Quant entity
316///
317/// Provides a fluent API for constructing Quant instances.
318/// System fields (id, metadata, timestamps) are auto-initialized.
319#[derive(Debug, Clone, Default)]
320pub struct QuantBuilder {
321    item_id: Option<Uuid>,
322    location_id: Option<Uuid>,
323    lot_id: Option<Uuid>,
324    package_id: Option<Uuid>,
325    owner_id: Option<Uuid>,
326    quantity: Option<Decimal>,
327    reserved_quantity: Option<Decimal>,
328    available_quantity: Option<Decimal>,
329    in_date: Option<DateTime<Utc>>,
330    inventory_quantity: Option<Decimal>,
331    inventory_diff_quantity: Option<Decimal>,
332    inventory_quantity_set: Option<bool>,
333    inventory_date: Option<NaiveDate>,
334    sn_duplicated: Option<bool>,
335}
336
337impl QuantBuilder {
338    /// Set the item_id field (required)
339    pub fn item_id(mut self, value: Uuid) -> Self {
340        self.item_id = Some(value);
341        self
342    }
343
344    /// Set the location_id field (required)
345    pub fn location_id(mut self, value: Uuid) -> Self {
346        self.location_id = Some(value);
347        self
348    }
349
350    /// Set the lot_id field (optional)
351    pub fn lot_id(mut self, value: Uuid) -> Self {
352        self.lot_id = Some(value);
353        self
354    }
355
356    /// Set the package_id field (optional)
357    pub fn package_id(mut self, value: Uuid) -> Self {
358        self.package_id = Some(value);
359        self
360    }
361
362    /// Set the owner_id field (optional)
363    pub fn owner_id(mut self, value: Uuid) -> Self {
364        self.owner_id = Some(value);
365        self
366    }
367
368    /// Set the quantity field (default: `Decimal::from(0)`)
369    pub fn quantity(mut self, value: Decimal) -> Self {
370        self.quantity = Some(value);
371        self
372    }
373
374    /// Set the reserved_quantity field (default: `Decimal::from(0)`)
375    pub fn reserved_quantity(mut self, value: Decimal) -> Self {
376        self.reserved_quantity = Some(value);
377        self
378    }
379
380    /// Set the available_quantity field (default: `Decimal::from(0)`)
381    pub fn available_quantity(mut self, value: Decimal) -> Self {
382        self.available_quantity = Some(value);
383        self
384    }
385
386    /// Set the in_date field (optional)
387    pub fn in_date(mut self, value: DateTime<Utc>) -> Self {
388        self.in_date = Some(value);
389        self
390    }
391
392    /// Set the inventory_quantity field (optional)
393    pub fn inventory_quantity(mut self, value: Decimal) -> Self {
394        self.inventory_quantity = Some(value);
395        self
396    }
397
398    /// Set the inventory_diff_quantity field (optional)
399    pub fn inventory_diff_quantity(mut self, value: Decimal) -> Self {
400        self.inventory_diff_quantity = Some(value);
401        self
402    }
403
404    /// Set the inventory_quantity_set field (default: `false`)
405    pub fn inventory_quantity_set(mut self, value: bool) -> Self {
406        self.inventory_quantity_set = Some(value);
407        self
408    }
409
410    /// Set the inventory_date field (optional)
411    pub fn inventory_date(mut self, value: NaiveDate) -> Self {
412        self.inventory_date = Some(value);
413        self
414    }
415
416    /// Set the sn_duplicated field (default: `false`)
417    pub fn sn_duplicated(mut self, value: bool) -> Self {
418        self.sn_duplicated = Some(value);
419        self
420    }
421
422    /// Build the Quant entity
423    ///
424    /// Returns Err if any required field without a default is missing.
425    pub fn build(self) -> Result<Quant, String> {
426        let item_id = self.item_id.ok_or_else(|| "item_id is required".to_string())?;
427        let location_id = self.location_id.ok_or_else(|| "location_id is required".to_string())?;
428
429        Ok(Quant {
430            id: Uuid::new_v4(),
431            item_id,
432            location_id,
433            lot_id: self.lot_id,
434            package_id: self.package_id,
435            owner_id: self.owner_id,
436            quantity: self.quantity.unwrap_or(Decimal::from(0)),
437            reserved_quantity: self.reserved_quantity.unwrap_or(Decimal::from(0)),
438            available_quantity: self.available_quantity.unwrap_or(Decimal::from(0)),
439            in_date: self.in_date,
440            inventory_quantity: self.inventory_quantity,
441            inventory_diff_quantity: self.inventory_diff_quantity,
442            inventory_quantity_set: self.inventory_quantity_set.unwrap_or(false),
443            inventory_date: self.inventory_date,
444            sn_duplicated: self.sn_duplicated.unwrap_or(false),
445            metadata: AuditMetadata::default(),
446        })
447    }
448}