Skip to main content

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