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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Quality Control domain models
//!
//! Models for inspections, non-conformance reports (NCRs), and quality holds.

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

// ============================================================================
// Inspection Types
// ============================================================================

/// Quality inspection for goods
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Inspection {
    pub id: Uuid,
    pub inspection_number: String,
    pub inspection_type: InspectionType,
    pub reference_type: String,
    pub reference_id: Uuid,
    pub status: InspectionStatus,
    pub inspector_id: Option<String>,
    pub scheduled_at: Option<DateTime<Utc>>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub notes: Option<String>,
    pub items: Vec<InspectionItem>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Type of inspection
#[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 InspectionType {
    /// Incoming goods inspection (alias for Receiving)
    Incoming,
    /// Inspection of received goods
    Receiving,
    /// In-process quality check during manufacturing
    InProcess,
    /// Final inspection before shipping
    Final,
    /// Random quality audit
    Random,
    /// Customer return inspection
    Return,
}

impl Default for InspectionType {
    fn default() -> Self {
        Self::Incoming
    }
}

/// Status of an inspection
#[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 InspectionStatus {
    /// Inspection has been created but not yet scheduled.
    Pending,
    /// Inspection is scheduled for a future time.
    Scheduled,
    /// Inspector is actively performing the inspection.
    InProgress,
    /// All items passed the inspection criteria.
    Passed,
    /// One or more items failed the inspection criteria.
    Failed,
    /// Some items passed and some failed.
    PartialPass,
    /// Inspection is temporarily paused pending additional information.
    OnHold,
    /// Inspection was cancelled before completion.
    Cancelled,
}

impl Default for InspectionStatus {
    fn default() -> Self {
        Self::Pending
    }
}

/// Line item in an inspection
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InspectionItem {
    pub id: Uuid,
    pub inspection_id: Uuid,
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub quantity_inspected: Decimal,
    pub quantity_passed: Decimal,
    pub quantity_failed: Decimal,
    pub defect_codes: Vec<String>,
    pub measurements: Option<serde_json::Value>,
    pub result: InspectionResult,
    pub notes: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// Result of inspecting an item
#[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 InspectionResult {
    /// Result has not yet been recorded.
    Pending,
    /// Item fully meets the quality criteria.
    Pass,
    /// Item does not meet the quality criteria.
    Fail,
    /// Item meets criteria only under specific conditions or with minor rework.
    ConditionalPass,
}

impl Default for InspectionResult {
    fn default() -> Self {
        Self::Pending
    }
}

// ============================================================================
// Non-Conformance Report (NCR) Types
// ============================================================================

/// Non-Conformance Report for quality issues
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NonConformance {
    pub id: Uuid,
    pub ncr_number: String,
    pub inspection_id: Option<Uuid>,
    pub source: NonConformanceSource,
    pub severity: Severity,
    pub status: NcrStatus,
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub quantity_affected: Decimal,
    pub description: String,
    pub root_cause: Option<String>,
    pub corrective_action: Option<String>,
    pub preventive_action: Option<String>,
    pub disposition: Option<Disposition>,
    pub disposition_quantity: Option<Decimal>,
    pub assigned_to: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub closed_at: Option<DateTime<Utc>>,
}

/// Source of the non-conformance
#[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 NonConformanceSource {
    /// Defect discovered during a formal quality inspection.
    Inspection,
    /// Non-conformance reported by a customer.
    CustomerComplaint,
    /// Defect identified during an internal quality audit.
    InternalAudit,
    /// Problem attributed to a supplier's material or process.
    SupplierIssue,
    /// Defect introduced during the manufacturing process.
    ProductionDefect,
    /// Goods damaged in transit or during shipment.
    ShippingDamage,
}

impl Default for NonConformanceSource {
    fn default() -> Self {
        Self::Inspection
    }
}

/// Severity level
#[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 Severity {
    /// Defect poses an immediate safety or compliance risk; requires urgent action.
    Critical,
    /// Significant defect likely to affect product function or customer satisfaction.
    Major,
    /// Small defect with limited impact on product use or appearance.
    Minor,
    /// Noteworthy finding that does not rise to the level of a defect.
    Observation,
}

impl Default for Severity {
    fn default() -> Self {
        Self::Minor
    }
}

/// Status of an NCR
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, Serialize, Deserialize)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NcrStatus {
    /// NCR has been created and is awaiting assignment.
    Open,
    /// NCR is being assessed by the quality team.
    UnderReview,
    /// Investigation is complete; awaiting a disposition decision.
    PendingDisposition,
    /// Corrective actions are being implemented to address the root cause.
    CorrectiveAction,
    /// Preventive actions are being implemented to avoid recurrence.
    PreventiveAction,
    /// Actions have been taken; effectiveness is being verified.
    Verification,
    /// All actions verified effective; NCR is closed.
    Closed,
    /// NCR was opened in error or deemed not applicable.
    Cancelled,
}

impl Default for NcrStatus {
    fn default() -> Self {
        Self::Open
    }
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "open" => Ok(Self::Open),
            "under_review" => Ok(Self::UnderReview),
            "pending_disposition" => Ok(Self::PendingDisposition),
            "corrective_action" => Ok(Self::CorrectiveAction),
            "preventive_action" => Ok(Self::PreventiveAction),
            "verification" => Ok(Self::Verification),
            "closed" => Ok(Self::Closed),
            "cancelled" => Ok(Self::Cancelled),
            _ => Err(format!("Unknown NCR status: {}", s)),
        }
    }
}

/// Disposition decision for non-conforming material
#[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 Disposition {
    /// Material is accepted in its current state without modification.
    UseAsIs,
    /// Material will be re-processed to meet the original specification.
    Rework,
    /// Material will be fixed to an acceptable but possibly different specification.
    Repair,
    /// Material is disposed of; cannot be used or sold.
    Scrap,
    /// Material is returned to the supplier for credit or replacement.
    ReturnToVendor,
    /// Material is reclassified to a lower-grade specification.
    Downgrade,
    /// Each unit is individually inspected to separate conforming from non-conforming.
    SortAndScreen,
}

// ============================================================================
// Quality Hold Types
// ============================================================================

/// Quality hold to prevent inventory movement
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QualityHold {
    pub id: Uuid,
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub location_id: Option<i32>,
    pub quantity_held: Decimal,
    pub reason: String,
    pub hold_type: HoldType,
    pub ncr_id: Option<Uuid>,
    pub inspection_id: Option<Uuid>,
    pub placed_by: String,
    pub released_by: Option<String>,
    pub release_notes: Option<String>,
    pub placed_at: DateTime<Utc>,
    pub released_at: Option<DateTime<Utc>>,
    pub expires_at: Option<DateTime<Utc>>,
}

/// Type of quality hold
#[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 HoldType {
    /// Held pending a quality inspection decision.
    QualityInspection,
    /// Returned by a customer; awaiting disposition.
    CustomerReturn,
    /// Subject to a product recall.
    Recall,
    /// Goods were damaged and cannot be sold as-is.
    Damaged,
    /// Goods have passed or are approaching their expiry date.
    Expired,
    /// Isolated to prevent potential contamination or spread.
    Quarantine,
    /// Held due to a regulatory agency requirement or investigation.
    RegulatoryHold,
    /// Held while an internal investigation is in progress.
    InvestigationHold,
}

impl Default for HoldType {
    fn default() -> Self {
        Self::QualityInspection
    }
}

// ============================================================================
// Defect Code Types
// ============================================================================

/// Defect code definition
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DefectCode {
    pub id: Uuid,
    pub code: String,
    pub name: String,
    pub description: Option<String>,
    pub category: String,
    pub severity: Severity,
    pub is_active: bool,
    pub created_at: DateTime<Utc>,
}

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

/// Input for creating an inspection
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CreateInspection {
    pub inspection_type: InspectionType,
    pub reference_type: String,
    pub reference_id: Uuid,
    pub inspector_id: Option<String>,
    pub scheduled_at: Option<DateTime<Utc>>,
    pub notes: Option<String>,
    pub items: Vec<CreateInspectionItem>,
}

/// Input for creating an inspection item
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateInspectionItem {
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub quantity_to_inspect: Decimal,
}

impl Default for CreateInspectionItem {
    fn default() -> Self {
        Self {
            sku: String::new(),
            lot_number: None,
            serial_number: None,
            quantity_to_inspect: Decimal::ZERO,
        }
    }
}

/// Input for updating an inspection
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct UpdateInspection {
    pub status: Option<InspectionStatus>,
    pub inspector_id: Option<String>,
    pub scheduled_at: Option<DateTime<Utc>>,
    pub notes: Option<String>,
}

/// Input for recording inspection results
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordInspectionResult {
    pub item_id: Uuid,
    pub quantity_passed: Decimal,
    pub quantity_failed: Decimal,
    pub result: InspectionResult,
    pub defect_codes: Vec<String>,
    pub measurements: Option<serde_json::Value>,
    pub notes: Option<String>,
}

/// Filter for listing inspections
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct InspectionFilter {
    pub inspection_type: Option<InspectionType>,
    pub status: Option<InspectionStatus>,
    pub reference_type: Option<String>,
    pub reference_id: Option<Uuid>,
    pub inspector_id: Option<String>,
    pub from_date: Option<DateTime<Utc>>,
    pub to_date: Option<DateTime<Utc>>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Input for creating an NCR
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateNonConformance {
    pub inspection_id: Option<Uuid>,
    pub source: NonConformanceSource,
    pub severity: Severity,
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub quantity_affected: Decimal,
    pub description: String,
    pub assigned_to: Option<String>,
}

impl Default for CreateNonConformance {
    fn default() -> Self {
        Self {
            inspection_id: None,
            source: NonConformanceSource::default(),
            severity: Severity::default(),
            sku: String::new(),
            lot_number: None,
            serial_number: None,
            quantity_affected: Decimal::ZERO,
            description: String::new(),
            assigned_to: None,
        }
    }
}

/// Input for updating an NCR
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct UpdateNonConformance {
    pub status: Option<NcrStatus>,
    pub severity: Option<Severity>,
    pub root_cause: Option<String>,
    pub corrective_action: Option<String>,
    pub preventive_action: Option<String>,
    pub disposition: Option<Disposition>,
    pub disposition_quantity: Option<Decimal>,
    pub assigned_to: Option<String>,
}

/// Filter for listing NCRs
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct NonConformanceFilter {
    pub source: Option<NonConformanceSource>,
    pub severity: Option<Severity>,
    pub status: Option<NcrStatus>,
    pub sku: Option<String>,
    pub lot_number: Option<String>,
    pub assigned_to: Option<String>,
    pub from_date: Option<DateTime<Utc>>,
    pub to_date: Option<DateTime<Utc>>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Input for creating a quality hold
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateQualityHold {
    pub sku: String,
    pub lot_number: Option<String>,
    pub serial_number: Option<String>,
    pub location_id: Option<i32>,
    pub quantity: Decimal,
    pub reason: String,
    pub hold_type: HoldType,
    pub ncr_id: Option<Uuid>,
    pub inspection_id: Option<Uuid>,
    pub placed_by: String,
    pub expires_at: Option<DateTime<Utc>>,
}

impl Default for CreateQualityHold {
    fn default() -> Self {
        Self {
            sku: String::new(),
            lot_number: None,
            serial_number: None,
            location_id: None,
            quantity: Decimal::ZERO,
            reason: String::new(),
            hold_type: HoldType::default(),
            ncr_id: None,
            inspection_id: None,
            placed_by: String::new(),
            expires_at: None,
        }
    }
}

/// Input for releasing a quality hold
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseQualityHold {
    pub released_by: String,
    pub release_notes: Option<String>,
}

/// Filter for listing quality holds
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct QualityHoldFilter {
    pub sku: Option<String>,
    pub lot_number: Option<String>,
    pub hold_type: Option<HoldType>,
    pub location_id: Option<i32>,
    pub active_only: Option<bool>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Input for creating a defect code
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CreateDefectCode {
    pub code: String,
    pub name: String,
    pub description: Option<String>,
    pub category: String,
    pub severity: Severity,
}

// ============================================================================
// Type Aliases for API compatibility
// ============================================================================

/// Alias for `CreateNonConformance` for API convenience
pub type CreateNcr = CreateNonConformance;

/// Input for completing an inspection
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompleteInspection {
    pub quantity_passed: Decimal,
    pub quantity_failed: Decimal,
    pub inspector_id: Option<String>,
    pub notes: Option<String>,
}

impl Default for CompleteInspection {
    fn default() -> Self {
        Self {
            quantity_passed: Decimal::ZERO,
            quantity_failed: Decimal::ZERO,
            inspector_id: None,
            notes: None,
        }
    }
}

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

impl Inspection {
    /// Check if inspection can be started
    pub const fn can_start(&self) -> bool {
        matches!(self.status, InspectionStatus::Pending | InspectionStatus::Scheduled)
    }

    /// Check if inspection can be completed
    pub const fn can_complete(&self) -> bool {
        matches!(self.status, InspectionStatus::InProgress)
    }

    /// Check if all items have been inspected
    pub fn all_items_inspected(&self) -> bool {
        self.items.iter().all(|item| item.result != InspectionResult::Pending)
    }

    /// Get overall pass rate
    pub fn pass_rate(&self) -> Option<Decimal> {
        let total_inspected: Decimal = self.items.iter().map(|i| i.quantity_inspected).sum();
        if total_inspected > Decimal::ZERO {
            let total_passed: Decimal = self.items.iter().map(|i| i.quantity_passed).sum();
            Some((total_passed / total_inspected) * Decimal::from(100))
        } else {
            None
        }
    }

    /// Calculate overall result based on items
    pub fn calculate_overall_result(&self) -> InspectionStatus {
        if self.items.is_empty() || self.items.iter().any(|i| i.result == InspectionResult::Pending)
        {
            return InspectionStatus::InProgress;
        }

        let all_passed = self.items.iter().all(|i| i.result == InspectionResult::Pass);
        let any_passed = self.items.iter().any(|i| {
            i.result == InspectionResult::Pass || i.result == InspectionResult::ConditionalPass
        });

        if all_passed {
            InspectionStatus::Passed
        } else if any_passed {
            InspectionStatus::PartialPass
        } else {
            InspectionStatus::Failed
        }
    }
}

impl NonConformance {
    /// Check if NCR can be closed
    pub const fn can_close(&self) -> bool {
        matches!(
            self.status,
            NcrStatus::Verification | NcrStatus::CorrectiveAction | NcrStatus::PreventiveAction
        ) && self.disposition.is_some()
    }

    /// Check if NCR requires immediate action based on severity
    pub const fn requires_immediate_action(&self) -> bool {
        matches!(self.severity, Severity::Critical)
    }

    /// Check if disposition has been set
    pub const fn has_disposition(&self) -> bool {
        self.disposition.is_some()
    }
}

impl QualityHold {
    /// Check if hold is active
    pub const fn is_active(&self) -> bool {
        self.released_at.is_none()
    }

    /// Check if hold has expired
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at {
            Utc::now() > expires_at && self.released_at.is_none()
        } else {
            false
        }
    }
}