stateset-embedded 0.7.13

Embeddable commerce library - the SQLite of commerce operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Lot/Batch tracking operations
//!
//! Comprehensive lot management system supporting:
//! - Lot creation and lifecycle management
//! - Lot transactions (consumption, adjustment, transfer)
//! - Certificate management (COA, COC, MSDS)
//! - Forward and backward traceability
//!
//! # Example
//!
//! ```rust,ignore
//! use stateset_embedded::{Commerce, CreateLot};
//! use chrono::{Utc, Duration};
//! use rust_decimal_macros::dec;
//!
//! let commerce = Commerce::new("./store.db")?;
//!
//! // Create a lot for received materials
//! let lot = commerce.lots().create(CreateLot {
//!     lot_number: Some("LOT-2025-001".into()),
//!     sku: "RAW-MAT-001".into(),
//!     quantity_produced: dec!(1000),
//!     expiration_date: Some(Utc::now() + Duration::days(365)),
//!     ..Default::default()
//! })?;
//!
//! println!("Created lot {}", lot.lot_number);
//! # Ok::<(), stateset_embedded::CommerceError>(())
//! ```

use rust_decimal::Decimal;
use stateset_core::{
    AddLotCertificate, AdjustLot, ConsumeLot, CreateLot, Lot, LotCertificate, LotFilter,
    LotLocation, LotStatus, LotTransaction, MergeLots, ReserveLot, Result, SplitLot,
    TraceabilityResult, TransferLot, UpdateLot,
};
use stateset_db::Database;
use std::sync::Arc;
use uuid::Uuid;

/// Lot/Batch tracking management interface.
pub struct Lots {
    db: Arc<dyn Database>,
}

impl std::fmt::Debug for Lots {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Lots").finish_non_exhaustive()
    }
}

impl Lots {
    pub(crate) fn new(db: Arc<dyn Database>) -> Self {
        Self { db }
    }

    // ========================================================================
    // Basic CRUD
    // ========================================================================

    /// Create a new lot.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, CreateLot};
    /// use chrono::{Utc, Duration};
    /// use rust_decimal_macros::dec;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let lot = commerce.lots().create(CreateLot {
    ///     lot_number: Some("BATCH-001".into()),
    ///     sku: "PROD-001".into(),
    ///     quantity_produced: dec!(500),
    ///     production_date: Some(Utc::now()),
    ///     expiration_date: Some(Utc::now() + Duration::days(180)),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn create(&self, input: CreateLot) -> Result<Lot> {
        self.db.lots().create(input)
    }

    /// Get a lot by ID.
    pub fn get(&self, id: Uuid) -> Result<Option<Lot>> {
        self.db.lots().get(id)
    }

    /// Get a lot by lot number.
    pub fn get_by_number(&self, lot_number: &str) -> Result<Option<Lot>> {
        self.db.lots().get_by_number(lot_number)
    }

    /// List lots with optional filtering.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, LotFilter, LotStatus};
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // Get all active lots for a SKU
    /// let lots = commerce.lots().list(LotFilter {
    ///     sku: Some("PROD-001".into()),
    ///     status: Some(LotStatus::Active),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn list(&self, filter: LotFilter) -> Result<Vec<Lot>> {
        self.db.lots().list(filter)
    }

    /// Update a lot.
    pub fn update(&self, id: Uuid, input: UpdateLot) -> Result<Lot> {
        self.db.lots().update(id, input)
    }

    /// Delete a lot (only if unused).
    pub fn delete(&self, id: Uuid) -> Result<()> {
        self.db.lots().delete(id)
    }

    // ========================================================================
    // Status Management
    // ========================================================================

    /// Quarantine a lot (prevent usage).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::Commerce;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// commerce.lots().quarantine(Uuid::new_v4(), "Quality issue detected")?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn quarantine(&self, id: Uuid, reason: &str) -> Result<Lot> {
        self.db.lots().quarantine(id, reason)
    }

    /// Release a lot from quarantine.
    pub fn release_quarantine(&self, id: Uuid) -> Result<Lot> {
        self.db.lots().release_quarantine(id)
    }

    // ========================================================================
    // Inventory Operations
    // ========================================================================

    /// Adjust lot quantity (positive or negative).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, AdjustLot};
    /// use rust_decimal_macros::dec;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // Remove 10 units due to damage
    /// commerce.lots().adjust(AdjustLot {
    ///     lot_id: Uuid::new_v4(),
    ///     quantity: dec!(-10),
    ///     reason: "Damaged in storage".into(),
    ///     performed_by: Some("warehouse_user".into()),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn adjust(&self, input: AdjustLot) -> Result<LotTransaction> {
        self.db.lots().adjust(input)
    }

    /// Consume quantity from a lot.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, ConsumeLot};
    /// use rust_decimal_macros::dec;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// commerce.lots().consume(ConsumeLot {
    ///     lot_id: Uuid::new_v4(),
    ///     quantity: dec!(25),
    ///     reference_type: "work_order".into(),
    ///     reference_id: Uuid::new_v4(),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn consume(&self, input: ConsumeLot) -> Result<LotTransaction> {
        self.db.lots().consume(input)
    }

    /// Reserve quantity in a lot.
    ///
    /// Returns the reservation ID which can be used to release or confirm the reservation.
    pub fn reserve(&self, input: ReserveLot) -> Result<Uuid> {
        self.db.lots().reserve(input)
    }

    /// Release a reservation (cancel it without consuming).
    pub fn release_reservation(&self, reservation_id: Uuid) -> Result<()> {
        self.db.lots().release_reservation(reservation_id)
    }

    /// Confirm a reservation (convert to actual consumption).
    pub fn confirm_reservation(&self, reservation_id: Uuid) -> Result<LotTransaction> {
        self.db.lots().confirm_reservation(reservation_id)
    }

    /// Transfer lot to a different location.
    pub fn transfer(&self, input: TransferLot) -> Result<LotTransaction> {
        self.db.lots().transfer(input)
    }

    /// Split a lot into two.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, SplitLot};
    /// use rust_decimal_macros::dec;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // Split 100 units into a new lot
    /// let new_lot = commerce.lots().split(SplitLot {
    ///     source_lot_id: Uuid::new_v4(),
    ///     new_lot_number: Some("LOT-2025-001B".into()),
    ///     quantity: dec!(100),
    ///     reason: Some("Customer allocation".into()),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn split(&self, input: SplitLot) -> Result<Lot> {
        self.db.lots().split(input)
    }

    /// Merge multiple lots into one.
    pub fn merge(&self, input: MergeLots) -> Result<Lot> {
        self.db.lots().merge(input)
    }

    // ========================================================================
    // Certificates
    // ========================================================================

    /// Add a certificate to a lot.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, AddLotCertificate, CertificateType};
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// commerce.lots().add_certificate(AddLotCertificate {
    ///     lot_id: Uuid::new_v4(),
    ///     certificate_type: CertificateType::Coa,
    ///     document_url: Some("https://storage.example.com/certs/coa-123.pdf".into()),
    ///     issued_by: Some("Quality Lab Inc.".into()),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn add_certificate(&self, input: AddLotCertificate) -> Result<LotCertificate> {
        self.db.lots().add_certificate(input)
    }

    /// Get certificates for a lot.
    pub fn get_certificates(&self, lot_id: Uuid) -> Result<Vec<LotCertificate>> {
        self.db.lots().get_certificates(lot_id)
    }

    /// Remove a certificate from a lot.
    pub fn delete_certificate(&self, certificate_id: Uuid) -> Result<()> {
        self.db.lots().delete_certificate(certificate_id)
    }

    // ========================================================================
    // Locations
    // ========================================================================

    /// Get lot quantities by location.
    pub fn get_locations(&self, lot_id: Uuid) -> Result<Vec<LotLocation>> {
        self.db.lots().get_lot_locations(lot_id)
    }

    /// Get quantity at a specific location.
    pub fn get_quantity_at_location(
        &self,
        lot_id: Uuid,
        location_id: i32,
    ) -> Result<Option<Decimal>> {
        self.db.lots().get_quantity_at_location(lot_id, location_id)
    }

    // ========================================================================
    // Transactions
    // ========================================================================

    /// Get transaction history for a lot.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::Commerce;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let transactions = commerce.lots().get_transactions(
    ///     Uuid::new_v4(),
    ///     100,  // limit
    /// )?;
    ///
    /// for tx in transactions {
    ///     println!("{:?}: {} units", tx.transaction_type, tx.quantity);
    /// }
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn get_transactions(&self, lot_id: Uuid, limit: u32) -> Result<Vec<LotTransaction>> {
        self.db.lots().get_transactions(lot_id, limit)
    }

    // ========================================================================
    // Traceability
    // ========================================================================

    /// Get full bidirectional traceability (upstream and downstream).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::Commerce;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let trace = commerce.lots().trace(Uuid::new_v4())?;
    ///
    /// println!("Upstream sources: {} nodes", trace.upstream.len());
    /// println!("Downstream destinations: {} nodes", trace.downstream.len());
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn trace(&self, lot_id: Uuid) -> Result<TraceabilityResult> {
        self.db.lots().trace(lot_id)
    }

    // ========================================================================
    // Queries
    // ========================================================================

    /// Get lots expiring within a number of days.
    pub fn get_expiring_lots(&self, days: i32) -> Result<Vec<Lot>> {
        self.db.lots().get_expiring_lots(days)
    }

    /// Get already expired lots.
    pub fn get_expired_lots(&self) -> Result<Vec<Lot>> {
        self.db.lots().get_expired_lots()
    }

    /// Get lots with available quantity for a SKU.
    ///
    /// Returns lots ordered by production date (FIFO).
    pub fn get_available_lots_for_sku(&self, sku: &str) -> Result<Vec<Lot>> {
        self.db.lots().get_available_lots_for_sku(sku)
    }

    /// Count lots matching filter.
    pub fn count(&self, filter: LotFilter) -> Result<u64> {
        self.db.lots().count(filter)
    }

    // ========================================================================
    // Batch Operations
    // ========================================================================

    /// Create multiple lots at once.
    pub fn create_batch(&self, inputs: Vec<CreateLot>) -> Result<stateset_core::BatchResult<Lot>> {
        self.db.lots().create_batch(inputs)
    }

    /// Get multiple lots by ID.
    pub fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<Lot>> {
        self.db.lots().get_batch(ids)
    }

    // ========================================================================
    // Convenience Methods
    // ========================================================================

    /// Get all active lots for a SKU.
    pub fn get_active_lots(&self, sku: &str) -> Result<Vec<Lot>> {
        self.list(LotFilter {
            sku: Some(sku.to_string()),
            status: Some(LotStatus::Active),
            ..Default::default()
        })
    }

    /// Get all quarantined lots.
    pub fn get_quarantined(&self) -> Result<Vec<Lot>> {
        self.list(LotFilter { status: Some(LotStatus::Quarantine), ..Default::default() })
    }
}