Skip to main content

backbone_inventory/domain/entity/
stock_entry.rs

1use chrono::{DateTime, Utc, NaiveDate};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5
6use super::StockEntryType;
7use super::DocStatus;
8use super::GlPostingState;
9use super::AuditMetadata;
10
11/// Strongly-typed ID for StockEntry
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(transparent)]
14pub struct StockEntryId(pub Uuid);
15
16impl StockEntryId {
17    pub fn new(id: Uuid) -> Self { Self(id) }
18    pub fn generate() -> Self { Self(Uuid::new_v4()) }
19    pub fn into_inner(self) -> Uuid { self.0 }
20}
21
22impl std::fmt::Display for StockEntryId {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "{}", self.0)
25    }
26}
27
28impl std::str::FromStr for StockEntryId {
29    type Err = uuid::Error;
30    fn from_str(s: &str) -> Result<Self, Self::Err> {
31        Ok(Self(Uuid::parse_str(s)?))
32    }
33}
34
35impl From<Uuid> for StockEntryId {
36    fn from(id: Uuid) -> Self { Self(id) }
37}
38
39impl From<StockEntryId> for Uuid {
40    fn from(id: StockEntryId) -> Self { id.0 }
41}
42
43impl AsRef<Uuid> for StockEntryId {
44    fn as_ref(&self) -> &Uuid { &self.0 }
45}
46
47impl std::ops::Deref for StockEntryId {
48    type Target = Uuid;
49    fn deref(&self) -> &Self::Target { &self.0 }
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
53pub struct StockEntry {
54    pub id: Uuid,
55    pub entry_number: String,
56    pub stock_entry_type: StockEntryType,
57    pub from_warehouse_id: Option<Uuid>,
58    pub to_warehouse_id: Option<Uuid>,
59    pub posting_date: NaiveDate,
60    pub transfer_id: Option<Uuid>,
61    pub status: DocStatus,
62    pub posting_state: GlPostingState,
63    pub notes: Option<String>,
64    #[serde(default)]
65    #[sqlx(json)]
66    pub metadata: AuditMetadata,
67}
68
69impl StockEntry {
70    /// Create a builder for StockEntry
71    pub fn builder() -> StockEntryBuilder {
72        <StockEntryBuilder as Default>::default()
73    }
74
75    /// Create a new StockEntry with required fields
76    pub fn new(entry_number: String, stock_entry_type: StockEntryType, posting_date: NaiveDate, status: DocStatus, posting_state: GlPostingState) -> Self {
77        Self {
78            id: Uuid::new_v4(),
79            entry_number,
80            stock_entry_type,
81            from_warehouse_id: None,
82            to_warehouse_id: None,
83            posting_date,
84            transfer_id: None,
85            status,
86            posting_state,
87            notes: None,
88            metadata: AuditMetadata::default(),
89        }
90    }
91
92    /// Get the entity's unique identifier
93    pub fn id(&self) -> &Uuid {
94        &self.id
95    }
96
97    /// Get a strongly-typed ID for this entity
98    pub fn typed_id(&self) -> StockEntryId {
99        StockEntryId(self.id)
100    }
101
102    /// Get when this entity was created
103    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
104        self.metadata.created_at.as_ref()
105    }
106
107    /// Get when this entity was last updated
108    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
109        self.metadata.updated_at.as_ref()
110    }
111
112    /// Check if this entity is soft deleted
113    pub fn is_deleted(&self) -> bool {
114        self.metadata.deleted_at.is_some()
115    }
116
117    /// Check if this entity is active (not deleted)
118    pub fn is_active(&self) -> bool {
119        self.metadata.deleted_at.is_none()
120    }
121
122    /// Get when this entity was deleted
123    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
124        self.metadata.deleted_at.as_ref()
125    }
126
127    /// Get who created this entity
128    pub fn created_by(&self) -> Option<&Uuid> {
129        self.metadata.created_by.as_ref()
130    }
131
132    /// Get who last updated this entity
133    pub fn updated_by(&self) -> Option<&Uuid> {
134        self.metadata.updated_by.as_ref()
135    }
136
137    /// Get who deleted this entity
138    pub fn deleted_by(&self) -> Option<&Uuid> {
139        self.metadata.deleted_by.as_ref()
140    }
141
142    /// Get the current status
143    pub fn status(&self) -> &DocStatus {
144        &self.status
145    }
146
147
148    // ==========================================================
149    // Fluent Setters (with_* for optional fields)
150    // ==========================================================
151
152    /// Set the from_warehouse_id field (chainable)
153    pub fn with_from_warehouse_id(mut self, value: Uuid) -> Self {
154        self.from_warehouse_id = Some(value);
155        self
156    }
157
158    /// Set the to_warehouse_id field (chainable)
159    pub fn with_to_warehouse_id(mut self, value: Uuid) -> Self {
160        self.to_warehouse_id = Some(value);
161        self
162    }
163
164    /// Set the transfer_id field (chainable)
165    pub fn with_transfer_id(mut self, value: Uuid) -> Self {
166        self.transfer_id = Some(value);
167        self
168    }
169
170    /// Set the notes field (chainable)
171    pub fn with_notes(mut self, value: String) -> Self {
172        self.notes = Some(value);
173        self
174    }
175
176    // ==========================================================
177    // Partial Update
178    // ==========================================================
179
180    /// Apply partial updates from a map of field name to JSON value
181    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
182        for (key, value) in fields {
183            match key.as_str() {
184                "entry_number" => {
185                    if let Ok(v) = serde_json::from_value(value) { self.entry_number = v; }
186                }
187                "stock_entry_type" => {
188                    if let Ok(v) = serde_json::from_value(value) { self.stock_entry_type = v; }
189                }
190                "from_warehouse_id" => {
191                    if let Ok(v) = serde_json::from_value(value) { self.from_warehouse_id = v; }
192                }
193                "to_warehouse_id" => {
194                    if let Ok(v) = serde_json::from_value(value) { self.to_warehouse_id = v; }
195                }
196                "posting_date" => {
197                    if let Ok(v) = serde_json::from_value(value) { self.posting_date = v; }
198                }
199                "transfer_id" => {
200                    if let Ok(v) = serde_json::from_value(value) { self.transfer_id = v; }
201                }
202                "status" => {
203                    if let Ok(v) = serde_json::from_value(value) { self.status = v; }
204                }
205                "posting_state" => {
206                    if let Ok(v) = serde_json::from_value(value) { self.posting_state = v; }
207                }
208                "notes" => {
209                    if let Ok(v) = serde_json::from_value(value) { self.notes = v; }
210                }
211                _ => {} // ignore unknown fields
212            }
213        }
214    }
215
216}
217
218impl super::Entity for StockEntry {
219    type Id = Uuid;
220
221    fn entity_id(&self) -> &Self::Id {
222        &self.id
223    }
224
225    fn entity_type() -> &'static str {
226        "StockEntry"
227    }
228}
229
230impl backbone_core::PersistentEntity for StockEntry {
231    fn write_protected_fields() -> &'static [&'static str] {
232        &["status"]
233    }
234    fn entity_id(&self) -> String {
235        self.id.to_string()
236    }
237    fn set_entity_id(&mut self, id: String) {
238        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
239            self.id = uuid;
240        }
241    }
242    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
243        self.metadata.created_at
244    }
245    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
246        self.metadata.created_at = Some(ts);
247    }
248    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
249        self.metadata.updated_at
250    }
251    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
252        self.metadata.updated_at = Some(ts);
253    }
254    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
255        self.metadata.deleted_at
256    }
257    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
258        self.metadata.deleted_at = ts;
259    }
260}
261
262impl backbone_orm::EntityRepoMeta for StockEntry {
263    fn column_types() -> std::collections::HashMap<String, String> {
264        let mut m = std::collections::HashMap::new();
265        m.insert("id".to_string(), "uuid".to_string());
266        m.insert("from_warehouse_id".to_string(), "uuid".to_string());
267        m.insert("to_warehouse_id".to_string(), "uuid".to_string());
268        m.insert("transfer_id".to_string(), "uuid".to_string());
269        m.insert("stock_entry_type".to_string(), "stock_entry_type".to_string());
270        m.insert("status".to_string(), "doc_status".to_string());
271        m.insert("posting_state".to_string(), "gl_posting_state".to_string());
272        m.insert("posting_date".to_string(), "date".to_string());
273        m
274    }
275    fn search_fields() -> &'static [&'static str] {
276        &["entry_number"]
277    }
278    fn relations() -> &'static [(&'static str, &'static str, &'static str)] {
279        &[("fromWarehouse", "warehouses", "fromWarehouseId"), ("toWarehouse", "warehouses", "toWarehouseId"), ("transfer", "transfers", "transferId")]
280    }
281}
282
283/// Builder for StockEntry entity
284///
285/// Provides a fluent API for constructing StockEntry instances.
286/// System fields (id, metadata, timestamps) are auto-initialized.
287#[derive(Debug, Clone, Default)]
288pub struct StockEntryBuilder {
289    entry_number: Option<String>,
290    stock_entry_type: Option<StockEntryType>,
291    from_warehouse_id: Option<Uuid>,
292    to_warehouse_id: Option<Uuid>,
293    posting_date: Option<NaiveDate>,
294    transfer_id: Option<Uuid>,
295    status: Option<DocStatus>,
296    posting_state: Option<GlPostingState>,
297    notes: Option<String>,
298}
299
300impl StockEntryBuilder {
301    /// Set the entry_number field (required)
302    pub fn entry_number(mut self, value: String) -> Self {
303        self.entry_number = Some(value);
304        self
305    }
306
307    /// Set the stock_entry_type field (default: `StockEntryType::default()`)
308    pub fn stock_entry_type(mut self, value: StockEntryType) -> Self {
309        self.stock_entry_type = Some(value);
310        self
311    }
312
313    /// Set the from_warehouse_id field (optional)
314    pub fn from_warehouse_id(mut self, value: Uuid) -> Self {
315        self.from_warehouse_id = Some(value);
316        self
317    }
318
319    /// Set the to_warehouse_id field (optional)
320    pub fn to_warehouse_id(mut self, value: Uuid) -> Self {
321        self.to_warehouse_id = Some(value);
322        self
323    }
324
325    /// Set the posting_date field (required)
326    pub fn posting_date(mut self, value: NaiveDate) -> Self {
327        self.posting_date = Some(value);
328        self
329    }
330
331    /// Set the transfer_id field (optional)
332    pub fn transfer_id(mut self, value: Uuid) -> Self {
333        self.transfer_id = Some(value);
334        self
335    }
336
337    /// Set the status field (default: `DocStatus::default()`)
338    pub fn status(mut self, value: DocStatus) -> Self {
339        self.status = Some(value);
340        self
341    }
342
343    /// Set the posting_state field (default: `GlPostingState::default()`)
344    pub fn posting_state(mut self, value: GlPostingState) -> Self {
345        self.posting_state = Some(value);
346        self
347    }
348
349    /// Set the notes field (optional)
350    pub fn notes(mut self, value: String) -> Self {
351        self.notes = Some(value);
352        self
353    }
354
355    /// Build the StockEntry entity
356    ///
357    /// Returns Err if any required field without a default is missing.
358    pub fn build(self) -> Result<StockEntry, String> {
359        let entry_number = self.entry_number.ok_or_else(|| "entry_number is required".to_string())?;
360        let posting_date = self.posting_date.ok_or_else(|| "posting_date is required".to_string())?;
361
362        Ok(StockEntry {
363            id: Uuid::new_v4(),
364            entry_number,
365            stock_entry_type: self.stock_entry_type.unwrap_or_default(),
366            from_warehouse_id: self.from_warehouse_id,
367            to_warehouse_id: self.to_warehouse_id,
368            posting_date,
369            transfer_id: self.transfer_id,
370            status: self.status.unwrap_or_default(),
371            posting_state: self.posting_state.unwrap_or_default(),
372            notes: self.notes,
373            metadata: AuditMetadata::default(),
374        })
375    }
376}