Skip to main content

backbone_inventory/domain/entity/
picking_batch.rs

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