Skip to main content

backbone_inventory/domain/entity/
stock_reconciliation_item.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 StockReconciliationItem
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct StockReconciliationItemId(pub Uuid);
12
13impl StockReconciliationItemId {
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 StockReconciliationItemId {
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 StockReconciliationItemId {
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 StockReconciliationItemId {
33    fn from(id: Uuid) -> Self { Self(id) }
34}
35
36impl From<StockReconciliationItemId> for Uuid {
37    fn from(id: StockReconciliationItemId) -> Self { id.0 }
38}
39
40impl AsRef<Uuid> for StockReconciliationItemId {
41    fn as_ref(&self) -> &Uuid { &self.0 }
42}
43
44impl std::ops::Deref for StockReconciliationItemId {
45    type Target = Uuid;
46    fn deref(&self) -> &Self::Target { &self.0 }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
50pub struct StockReconciliationItem {
51    pub id: Uuid,
52    pub reconciliation_id: Uuid,
53    pub item_id: Uuid,
54    pub counted_qty: Decimal,
55    pub counted_rate: Decimal,
56    pub qty_difference: Decimal,
57    pub value_difference: Decimal,
58    #[serde(default)]
59    #[sqlx(json)]
60    pub metadata: AuditMetadata,
61}
62
63impl StockReconciliationItem {
64    /// Create a builder for StockReconciliationItem
65    pub fn builder() -> StockReconciliationItemBuilder {
66        <StockReconciliationItemBuilder as Default>::default()
67    }
68
69    /// Create a new StockReconciliationItem with required fields
70    pub fn new(reconciliation_id: Uuid, item_id: Uuid, counted_qty: Decimal, counted_rate: Decimal, qty_difference: Decimal, value_difference: Decimal) -> Self {
71        Self {
72            id: Uuid::new_v4(),
73            reconciliation_id,
74            item_id,
75            counted_qty,
76            counted_rate,
77            qty_difference,
78            value_difference,
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) -> StockReconciliationItemId {
90        StockReconciliationItemId(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    // Partial Update
136    // ==========================================================
137
138    /// Apply partial updates from a map of field name to JSON value
139    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
140        for (key, value) in fields {
141            match key.as_str() {
142                "reconciliation_id" => {
143                    if let Ok(v) = serde_json::from_value(value) { self.reconciliation_id = v; }
144                }
145                "item_id" => {
146                    if let Ok(v) = serde_json::from_value(value) { self.item_id = v; }
147                }
148                "counted_qty" => {
149                    if let Ok(v) = serde_json::from_value(value) { self.counted_qty = v; }
150                }
151                "counted_rate" => {
152                    if let Ok(v) = serde_json::from_value(value) { self.counted_rate = v; }
153                }
154                "qty_difference" => {
155                    if let Ok(v) = serde_json::from_value(value) { self.qty_difference = v; }
156                }
157                "value_difference" => {
158                    if let Ok(v) = serde_json::from_value(value) { self.value_difference = v; }
159                }
160                _ => {} // ignore unknown fields
161            }
162        }
163    }
164
165}
166
167impl super::Entity for StockReconciliationItem {
168    type Id = Uuid;
169
170    fn entity_id(&self) -> &Self::Id {
171        &self.id
172    }
173
174    fn entity_type() -> &'static str {
175        "StockReconciliationItem"
176    }
177}
178
179impl backbone_core::PersistentEntity for StockReconciliationItem {
180    fn entity_id(&self) -> String {
181        self.id.to_string()
182    }
183    fn set_entity_id(&mut self, id: String) {
184        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
185            self.id = uuid;
186        }
187    }
188    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
189        self.metadata.created_at
190    }
191    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
192        self.metadata.created_at = Some(ts);
193    }
194    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
195        self.metadata.updated_at
196    }
197    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
198        self.metadata.updated_at = Some(ts);
199    }
200    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
201        self.metadata.deleted_at
202    }
203    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
204        self.metadata.deleted_at = ts;
205    }
206}
207
208impl backbone_orm::EntityRepoMeta for StockReconciliationItem {
209    fn column_types() -> std::collections::HashMap<String, String> {
210        let mut m = std::collections::HashMap::new();
211        m.insert("id".to_string(), "uuid".to_string());
212        m.insert("reconciliation_id".to_string(), "uuid".to_string());
213        m.insert("item_id".to_string(), "uuid".to_string());
214        m
215    }
216    fn search_fields() -> &'static [&'static str] {
217        &[]
218    }
219    fn relations() -> &'static [(&'static str, &'static str, &'static str)] {
220        &[("reconciliation", "stock_reconciliations", "reconciliationId")]
221    }
222}
223
224/// Builder for StockReconciliationItem entity
225///
226/// Provides a fluent API for constructing StockReconciliationItem instances.
227/// System fields (id, metadata, timestamps) are auto-initialized.
228#[derive(Debug, Clone, Default)]
229pub struct StockReconciliationItemBuilder {
230    reconciliation_id: Option<Uuid>,
231    item_id: Option<Uuid>,
232    counted_qty: Option<Decimal>,
233    counted_rate: Option<Decimal>,
234    qty_difference: Option<Decimal>,
235    value_difference: Option<Decimal>,
236}
237
238impl StockReconciliationItemBuilder {
239    /// Set the reconciliation_id field (required)
240    pub fn reconciliation_id(mut self, value: Uuid) -> Self {
241        self.reconciliation_id = Some(value);
242        self
243    }
244
245    /// Set the item_id field (required)
246    pub fn item_id(mut self, value: Uuid) -> Self {
247        self.item_id = Some(value);
248        self
249    }
250
251    /// Set the counted_qty field (required)
252    pub fn counted_qty(mut self, value: Decimal) -> Self {
253        self.counted_qty = Some(value);
254        self
255    }
256
257    /// Set the counted_rate field (default: `Decimal::from(0)`)
258    pub fn counted_rate(mut self, value: Decimal) -> Self {
259        self.counted_rate = Some(value);
260        self
261    }
262
263    /// Set the qty_difference field (default: `Decimal::from(0)`)
264    pub fn qty_difference(mut self, value: Decimal) -> Self {
265        self.qty_difference = Some(value);
266        self
267    }
268
269    /// Set the value_difference field (default: `Decimal::from(0)`)
270    pub fn value_difference(mut self, value: Decimal) -> Self {
271        self.value_difference = Some(value);
272        self
273    }
274
275    /// Build the StockReconciliationItem entity
276    ///
277    /// Returns Err if any required field without a default is missing.
278    pub fn build(self) -> Result<StockReconciliationItem, String> {
279        let reconciliation_id = self.reconciliation_id.ok_or_else(|| "reconciliation_id is required".to_string())?;
280        let item_id = self.item_id.ok_or_else(|| "item_id is required".to_string())?;
281        let counted_qty = self.counted_qty.ok_or_else(|| "counted_qty is required".to_string())?;
282
283        Ok(StockReconciliationItem {
284            id: Uuid::new_v4(),
285            reconciliation_id,
286            item_id,
287            counted_qty,
288            counted_rate: self.counted_rate.unwrap_or(Decimal::from(0)),
289            qty_difference: self.qty_difference.unwrap_or(Decimal::from(0)),
290            value_difference: self.value_difference.unwrap_or(Decimal::from(0)),
291            metadata: AuditMetadata::default(),
292        })
293    }
294}