Skip to main content

backbone_inventory/domain/entity/
stock_ledger_entry.rs

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