stateset-core 0.8.1

Core domain models and business logic for StateSet iCommerce
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Lot/Batch Tracking domain models
//!
//! Models for lot tracking, traceability, and batch management.

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumString};
use uuid::Uuid;

// ============================================================================
// Lot Types
// ============================================================================

/// A lot/batch of inventory items
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lot {
    pub id: Uuid,
    pub lot_number: String,
    pub sku: String,
    pub status: LotStatus,
    pub quantity_produced: Decimal,
    pub quantity_remaining: Decimal,
    pub quantity_reserved: Decimal,
    pub quantity_quarantined: Decimal,
    pub production_date: DateTime<Utc>,
    pub expiration_date: Option<DateTime<Utc>>,
    pub best_before_date: Option<DateTime<Utc>>,
    pub supplier_lot: Option<String>,
    pub supplier_id: Option<Uuid>,
    pub work_order_id: Option<Uuid>,
    pub purchase_order_id: Option<Uuid>,
    pub cost_per_unit: Option<Decimal>,
    pub attributes: serde_json::Value,
    pub notes: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Status of a lot
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, Serialize, Deserialize)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LotStatus {
    /// Lot is active and available
    Active,
    /// Lot is in quarantine pending inspection
    Quarantine,
    /// Lot has expired
    Expired,
    /// Lot is fully consumed
    Consumed,
    /// Lot is on hold (quality issue)
    OnHold,
    /// Lot has been recalled
    Recalled,
    /// Lot has been scrapped
    Scrapped,
}

impl Default for LotStatus {
    fn default() -> Self {
        Self::Active
    }
}

impl std::str::FromStr for LotStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "active" => Ok(Self::Active),
            "quarantine" => Ok(Self::Quarantine),
            "expired" => Ok(Self::Expired),
            "consumed" => Ok(Self::Consumed),
            "on_hold" => Ok(Self::OnHold),
            "recalled" => Ok(Self::Recalled),
            "scrapped" => Ok(Self::Scrapped),
            _ => Err(format!("Unknown lot status: {}", s)),
        }
    }
}

// ============================================================================
// Lot Transaction Types
// ============================================================================

/// Transaction record for lot movements
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LotTransaction {
    pub id: Uuid,
    pub lot_id: Uuid,
    pub transaction_type: LotTransactionType,
    pub quantity: Decimal,
    pub reference_type: String,
    pub reference_id: Uuid,
    pub from_location_id: Option<i32>,
    pub to_location_id: Option<i32>,
    pub reason: Option<String>,
    pub performed_by: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// Type of lot transaction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, Serialize, Deserialize)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LotTransactionType {
    /// Initial creation/receipt of lot
    Received,
    /// Consumed in production or sale
    Consumed,
    /// Manual adjustment
    Adjusted,
    /// Reserved for an order
    Reserved,
    /// Released from reservation
    Released,
    /// Moved to quarantine
    Quarantined,
    /// Released from quarantine
    QuarantineReleased,
    /// Transferred between locations
    Transferred,
    /// Scrapped
    Scrapped,
    /// Returned from customer
    Returned,
    /// Split from another lot
    Split,
    /// Merged with another lot
    Merged,
}

impl Default for LotTransactionType {
    fn default() -> Self {
        Self::Received
    }
}

// ============================================================================
// Lot Certificate Types
// ============================================================================

/// Certificate/document associated with a lot
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LotCertificate {
    pub id: Uuid,
    pub lot_id: Uuid,
    pub certificate_type: CertificateType,
    pub certificate_number: Option<String>,
    pub document_url: Option<String>,
    pub issued_by: Option<String>,
    pub issued_at: Option<DateTime<Utc>>,
    pub expires_at: Option<DateTime<Utc>>,
    pub notes: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// Type of certificate
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, Serialize, Deserialize)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CertificateType {
    /// Certificate of Analysis
    Coa,
    /// Certificate of Conformance
    Coc,
    /// Material Safety Data Sheet
    Msds,
    /// Safety Data Sheet
    Sds,
    /// Test Report
    TestReport,
    /// Inspection Report
    InspectionReport,
    /// Country of Origin
    CountryOfOrigin,
    /// Other
    Other,
}

impl Default for CertificateType {
    fn default() -> Self {
        Self::Coa
    }
}

// ============================================================================
// Lot Location Types
// ============================================================================

/// Inventory of a lot at a specific location
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LotLocation {
    pub lot_id: Uuid,
    pub location_id: i32,
    pub quantity: Decimal,
    pub updated_at: DateTime<Utc>,
}

// ============================================================================
// Traceability Types
// ============================================================================

/// Result of a traceability query
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceabilityResult {
    pub lot: Lot,
    /// Upstream trace - where did this lot come from
    pub upstream: Vec<TraceNode>,
    /// Downstream trace - where did this lot go
    pub downstream: Vec<TraceNode>,
}

/// A node in the traceability chain
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceNode {
    pub node_type: TraceNodeType,
    pub node_id: Uuid,
    pub reference_number: Option<String>,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub quantity: Decimal,
    pub timestamp: DateTime<Utc>,
    pub entity_name: Option<String>,
}

/// Type of node in traceability chain
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TraceNodeType {
    PurchaseOrder,
    Receipt,
    WorkOrder,
    Order,
    Shipment,
    Return,
    Transfer,
    Adjustment,
}

impl std::fmt::Display for TraceNodeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::PurchaseOrder => write!(f, "purchase_order"),
            Self::Receipt => write!(f, "receipt"),
            Self::WorkOrder => write!(f, "work_order"),
            Self::Order => write!(f, "order"),
            Self::Shipment => write!(f, "shipment"),
            Self::Return => write!(f, "return"),
            Self::Transfer => write!(f, "transfer"),
            Self::Adjustment => write!(f, "adjustment"),
        }
    }
}

// ============================================================================
// Input/Output Types
// ============================================================================

/// Input for creating a lot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateLot {
    pub lot_number: Option<String>,
    pub sku: String,
    pub quantity: Decimal,
    pub production_date: Option<DateTime<Utc>>,
    pub expiration_date: Option<DateTime<Utc>>,
    pub best_before_date: Option<DateTime<Utc>>,
    pub supplier_lot: Option<String>,
    pub supplier_id: Option<Uuid>,
    pub work_order_id: Option<Uuid>,
    pub purchase_order_id: Option<Uuid>,
    pub cost_per_unit: Option<Decimal>,
    pub attributes: Option<serde_json::Value>,
    pub notes: Option<String>,
    pub initial_location_id: Option<i32>,
}

impl Default for CreateLot {
    fn default() -> Self {
        Self {
            lot_number: None,
            sku: String::new(),
            quantity: Decimal::ZERO,
            production_date: None,
            expiration_date: None,
            best_before_date: None,
            supplier_lot: None,
            supplier_id: None,
            work_order_id: None,
            purchase_order_id: None,
            cost_per_unit: None,
            attributes: None,
            notes: None,
            initial_location_id: None,
        }
    }
}

/// Input for updating a lot
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateLot {
    pub status: Option<LotStatus>,
    pub expiration_date: Option<DateTime<Utc>>,
    pub best_before_date: Option<DateTime<Utc>>,
    pub cost_per_unit: Option<Decimal>,
    pub attributes: Option<serde_json::Value>,
    pub notes: Option<String>,
}

/// Input for adjusting lot quantity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdjustLot {
    pub lot_id: Uuid,
    pub quantity_change: Decimal,
    pub reason: String,
    pub reference_type: Option<String>,
    pub reference_id: Option<Uuid>,
    pub location_id: Option<i32>,
    pub performed_by: Option<String>,
}

impl Default for AdjustLot {
    fn default() -> Self {
        Self {
            lot_id: Uuid::nil(),
            quantity_change: Decimal::ZERO,
            reason: String::new(),
            reference_type: None,
            reference_id: None,
            location_id: None,
            performed_by: None,
        }
    }
}

/// Input for consuming from a lot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsumeLot {
    pub lot_id: Uuid,
    pub quantity: Decimal,
    pub reference_type: String,
    pub reference_id: Uuid,
    pub location_id: Option<i32>,
    pub performed_by: Option<String>,
}

impl Default for ConsumeLot {
    fn default() -> Self {
        Self {
            lot_id: Uuid::nil(),
            quantity: Decimal::ZERO,
            reference_type: String::new(),
            reference_id: Uuid::nil(),
            location_id: None,
            performed_by: None,
        }
    }
}

/// Input for reserving from a lot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReserveLot {
    pub lot_id: Uuid,
    pub quantity: Decimal,
    pub reference_type: String,
    pub reference_id: Uuid,
    pub expires_in_seconds: Option<i64>,
}

impl Default for ReserveLot {
    fn default() -> Self {
        Self {
            lot_id: Uuid::nil(),
            quantity: Decimal::ZERO,
            reference_type: String::new(),
            reference_id: Uuid::nil(),
            expires_in_seconds: None,
        }
    }
}

/// Input for transferring lot between locations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransferLot {
    pub lot_id: Uuid,
    pub quantity: Decimal,
    pub from_location_id: i32,
    pub to_location_id: i32,
    pub reason: Option<String>,
    pub performed_by: Option<String>,
}

impl Default for TransferLot {
    fn default() -> Self {
        Self {
            lot_id: Uuid::nil(),
            quantity: Decimal::ZERO,
            from_location_id: 0,
            to_location_id: 0,
            reason: None,
            performed_by: None,
        }
    }
}

/// Input for splitting a lot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SplitLot {
    pub lot_id: Uuid,
    pub quantity: Decimal,
    pub new_lot_number: Option<String>,
    pub reason: Option<String>,
}

impl Default for SplitLot {
    fn default() -> Self {
        Self { lot_id: Uuid::nil(), quantity: Decimal::ZERO, new_lot_number: None, reason: None }
    }
}

/// Input for merging lots
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MergeLots {
    pub source_lot_ids: Vec<Uuid>,
    pub target_lot_number: Option<String>,
    pub reason: Option<String>,
}

/// Filter for listing lots
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LotFilter {
    pub sku: Option<String>,
    pub lot_number: Option<String>,
    pub status: Option<LotStatus>,
    pub supplier_id: Option<Uuid>,
    pub work_order_id: Option<Uuid>,
    pub purchase_order_id: Option<Uuid>,
    pub expiring_before: Option<DateTime<Utc>>,
    pub expiring_after: Option<DateTime<Utc>>,
    pub has_quantity: Option<bool>,
    pub location_id: Option<i32>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Input for adding a certificate to a lot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddLotCertificate {
    pub lot_id: Uuid,
    pub certificate_type: CertificateType,
    pub certificate_number: Option<String>,
    pub document_url: Option<String>,
    pub issued_by: Option<String>,
    pub issued_at: Option<DateTime<Utc>>,
    pub expires_at: Option<DateTime<Utc>>,
    pub notes: Option<String>,
}

impl Default for AddLotCertificate {
    fn default() -> Self {
        Self {
            lot_id: Uuid::nil(),
            certificate_type: CertificateType::default(),
            certificate_number: None,
            document_url: None,
            issued_by: None,
            issued_at: None,
            expires_at: None,
            notes: None,
        }
    }
}

// ============================================================================
// Business Logic
// ============================================================================

impl Lot {
    /// Check if lot has available quantity
    pub fn has_available(&self) -> bool {
        self.quantity_available() > Decimal::ZERO
    }

    /// Get available quantity (not reserved or quarantined)
    pub fn quantity_available(&self) -> Decimal {
        self.quantity_remaining - self.quantity_reserved - self.quantity_quarantined
    }

    /// Check if lot is expired
    pub fn is_expired(&self) -> bool {
        if let Some(exp) = self.expiration_date { Utc::now() > exp } else { false }
    }

    /// Check if lot is expiring soon (within days)
    pub fn is_expiring_soon(&self, days: i64) -> bool {
        if let Some(exp) = self.expiration_date {
            let threshold = Utc::now() + chrono::Duration::days(days);
            exp <= threshold && !self.is_expired()
        } else {
            false
        }
    }

    /// Check if lot can be consumed
    pub fn can_consume(&self, quantity: Decimal) -> bool {
        self.status == LotStatus::Active && self.quantity_available() >= quantity
    }

    /// Check if lot can be reserved
    pub fn can_reserve(&self, quantity: Decimal) -> bool {
        self.status == LotStatus::Active && self.quantity_available() >= quantity
    }

    /// Get days until expiration
    pub fn days_until_expiration(&self) -> Option<i64> {
        self.expiration_date.map(|exp| (exp - Utc::now()).num_days())
    }

    /// Get shelf life percentage remaining
    pub fn shelf_life_remaining(&self) -> Option<Decimal> {
        if let Some(exp) = self.expiration_date {
            let total_days = (exp - self.production_date).num_days();
            if total_days > 0 {
                let remaining_days = (exp - Utc::now()).num_days();
                Some(
                    Decimal::from(remaining_days.max(0)) / Decimal::from(total_days)
                        * Decimal::from(100),
                )
            } else {
                None
            }
        } else {
            None
        }
    }
}