Skip to main content

backbone_inventory/domain/entity/
scrap.rs

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