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
//! Product domain models

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

/// Product entity
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Product {
    pub id: ProductId,
    pub name: String,
    pub slug: String,
    pub description: String,
    pub status: ProductStatus,
    pub product_type: ProductType,
    pub attributes: Vec<ProductAttribute>,
    pub seo: Option<SeoMetadata>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Product variant (SKU-level)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProductVariant {
    pub id: Uuid,
    pub product_id: ProductId,
    pub sku: String,
    pub name: String,
    pub price: Decimal,
    pub compare_at_price: Option<Decimal>,
    pub cost: Option<Decimal>,
    pub barcode: Option<String>,
    pub weight: Option<Decimal>,
    pub weight_unit: Option<String>,
    pub options: Vec<VariantOption>,
    pub is_default: bool,
    pub is_active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Product status enumeration
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum ProductStatus {
    #[default]
    Draft,
    Active,
    Archived,
}

/// Product type enumeration
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum ProductType {
    #[default]
    Simple,
    Variable,
    Bundle,
    Digital,
}

/// Product attribute
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProductAttribute {
    pub name: String,
    pub value: String,
    pub group: Option<String>,
    pub is_visible: bool,
    pub is_variation: bool,
}

/// Variant option (e.g., size: Large, color: Blue)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VariantOption {
    pub name: String,
    pub value: String,
}

/// SEO metadata
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeoMetadata {
    pub title: Option<String>,
    pub description: Option<String>,
    pub keywords: Vec<String>,
}

/// Input for creating a product
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CreateProduct {
    pub name: String,
    pub slug: Option<String>,
    pub description: Option<String>,
    pub product_type: Option<ProductType>,
    pub attributes: Option<Vec<ProductAttribute>>,
    pub seo: Option<SeoMetadata>,
    pub variants: Option<Vec<CreateProductVariant>>,
}

/// Input for creating a product variant
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateProductVariant {
    pub sku: String,
    pub name: Option<String>,
    pub price: Decimal,
    pub compare_at_price: Option<Decimal>,
    pub cost: Option<Decimal>,
    pub barcode: Option<String>,
    pub weight: Option<Decimal>,
    pub weight_unit: Option<String>,
    pub options: Option<Vec<VariantOption>>,
    pub is_default: Option<bool>,
}

impl Default for CreateProductVariant {
    fn default() -> Self {
        Self {
            sku: String::new(),
            name: None,
            price: Decimal::ZERO,
            compare_at_price: None,
            cost: None,
            barcode: None,
            weight: None,
            weight_unit: None,
            options: None,
            is_default: None,
        }
    }
}

/// Input for updating a product
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateProduct {
    pub name: Option<String>,
    pub slug: Option<String>,
    pub description: Option<String>,
    pub status: Option<ProductStatus>,
    pub attributes: Option<Vec<ProductAttribute>>,
    pub seo: Option<SeoMetadata>,
}

/// Product filter for querying
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProductFilter {
    pub status: Option<ProductStatus>,
    pub product_type: Option<ProductType>,
    pub search: Option<String>,
    /// Matches product attributes with name/group "category" and the given value.
    pub category: Option<String>,
    pub min_price: Option<Decimal>,
    pub max_price: Option<Decimal>,
    pub in_stock: Option<bool>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
    /// Keyset cursor: return records after this `(sort_key, id)` pair.
    /// Sort key is `name` (ASC ordering).
    pub after_cursor: Option<(String, String)>,
}

impl Product {
    /// Generate slug from name if not provided
    pub fn generate_slug(name: &str) -> String {
        name.to_lowercase()
            .chars()
            .map(|c| if c.is_alphanumeric() { c } else { '-' })
            .collect::<String>()
            .split('-')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>()
            .join("-")
    }

    /// Check if product is purchasable
    pub fn is_purchasable(&self) -> bool {
        self.status == ProductStatus::Active
    }
}

impl ProductVariant {
    /// Calculate profit margin
    pub fn profit_margin(&self) -> Option<Decimal> {
        self.cost.map(|cost| {
            if cost > Decimal::ZERO {
                ((self.price - cost) / cost) * Decimal::from(100)
            } else {
                Decimal::ZERO
            }
        })
    }

    /// Check if on sale
    pub fn is_on_sale(&self) -> bool {
        self.compare_at_price.map(|compare| compare > self.price).unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;
    use std::str::FromStr;

    // ============================================================================
    // Test Helpers
    // ============================================================================

    #[test]
    fn product_status_display() {
        assert_eq!(ProductStatus::Draft.to_string(), "draft");
        assert_eq!(ProductStatus::Active.to_string(), "active");
        assert_eq!(ProductStatus::Archived.to_string(), "archived");
    }

    #[test]
    fn product_status_from_str() {
        assert_eq!(ProductStatus::from_str("draft").unwrap(), ProductStatus::Draft);
        assert_eq!(ProductStatus::from_str("Active").unwrap(), ProductStatus::Active);
        assert!(ProductStatus::from_str("unknown").is_err());
    }

    #[test]
    fn product_type_from_str() {
        assert_eq!(ProductType::from_str("simple").unwrap(), ProductType::Simple);
        assert_eq!(ProductType::from_str("Bundle").unwrap(), ProductType::Bundle);
        assert!(ProductType::from_str("physical").is_err());
    }

    fn create_test_product(status: ProductStatus) -> Product {
        let now = Utc::now();
        Product {
            id: ProductId::new(),
            name: "Test Product".to_string(),
            slug: "test-product".to_string(),
            description: "A great test product".to_string(),
            status,
            product_type: ProductType::Simple,
            attributes: vec![ProductAttribute {
                name: "Color".to_string(),
                value: "Blue".to_string(),
                group: Some("Appearance".to_string()),
                is_visible: true,
                is_variation: true,
            }],
            seo: Some(SeoMetadata {
                title: Some("Test Product | Store".to_string()),
                description: Some("Buy Test Product".to_string()),
                keywords: vec!["test".to_string(), "product".to_string()],
            }),
            created_at: now,
            updated_at: now,
        }
    }

    fn create_test_variant(
        price: Decimal,
        cost: Option<Decimal>,
        compare_at: Option<Decimal>,
    ) -> ProductVariant {
        let now = Utc::now();
        ProductVariant {
            id: Uuid::new_v4(),
            product_id: ProductId::new(),
            sku: "TEST-SKU-001".to_string(),
            name: "Test Variant".to_string(),
            price,
            compare_at_price: compare_at,
            cost,
            barcode: Some("1234567890123".to_string()),
            weight: Some(dec!(0.5)),
            weight_unit: Some("kg".to_string()),
            options: vec![VariantOption { name: "Size".to_string(), value: "Large".to_string() }],
            is_default: true,
            is_active: true,
            created_at: now,
            updated_at: now,
        }
    }

    // ============================================================================
    // Product Tests
    // ============================================================================

    #[test]
    fn test_product_generate_slug_simple() {
        let slug = Product::generate_slug("Test Product");
        assert_eq!(slug, "test-product");
    }

    #[test]
    fn test_product_generate_slug_with_special_chars() {
        let slug = Product::generate_slug("Test! Product @ 2024");
        assert_eq!(slug, "test-product-2024");
    }

    #[test]
    fn test_product_generate_slug_with_multiple_spaces() {
        let slug = Product::generate_slug("Test   Product   Name");
        assert_eq!(slug, "test-product-name");
    }

    #[test]
    fn test_product_generate_slug_already_lowercase() {
        let slug = Product::generate_slug("already-lowercase");
        assert_eq!(slug, "already-lowercase");
    }

    #[test]
    fn test_product_is_purchasable_when_active() {
        let product = create_test_product(ProductStatus::Active);
        assert!(product.is_purchasable());
    }

    #[test]
    fn test_product_not_purchasable_when_draft() {
        let product = create_test_product(ProductStatus::Draft);
        assert!(!product.is_purchasable());
    }

    #[test]
    fn test_product_not_purchasable_when_archived() {
        let product = create_test_product(ProductStatus::Archived);
        assert!(!product.is_purchasable());
    }

    // ============================================================================
    // ProductVariant Tests
    // ============================================================================

    #[test]
    fn test_variant_profit_margin_with_cost() {
        let variant = create_test_variant(dec!(100.00), Some(dec!(60.00)), None);
        let margin = variant.profit_margin().unwrap();
        // (100 - 60) / 60 * 100 = 66.666...%
        assert!(margin > dec!(66) && margin < dec!(67));
    }

    #[test]
    fn test_variant_profit_margin_zero_cost() {
        let variant = create_test_variant(dec!(100.00), Some(dec!(0.00)), None);
        let margin = variant.profit_margin().unwrap();
        assert_eq!(margin, dec!(0));
    }

    #[test]
    fn test_variant_profit_margin_no_cost() {
        let variant = create_test_variant(dec!(100.00), None, None);
        assert!(variant.profit_margin().is_none());
    }

    #[test]
    fn test_variant_profit_margin_100_percent() {
        let variant = create_test_variant(dec!(100.00), Some(dec!(50.00)), None);
        let margin = variant.profit_margin().unwrap();
        assert_eq!(margin, dec!(100));
    }

    #[test]
    fn test_variant_is_on_sale_true() {
        let variant = create_test_variant(dec!(79.99), None, Some(dec!(99.99)));
        assert!(variant.is_on_sale());
    }

    #[test]
    fn test_variant_is_on_sale_false_no_compare_price() {
        let variant = create_test_variant(dec!(79.99), None, None);
        assert!(!variant.is_on_sale());
    }

    #[test]
    fn test_variant_is_on_sale_false_same_price() {
        let variant = create_test_variant(dec!(99.99), None, Some(dec!(99.99)));
        assert!(!variant.is_on_sale());
    }

    #[test]
    fn test_variant_is_on_sale_false_compare_lower() {
        let variant = create_test_variant(dec!(99.99), None, Some(dec!(79.99)));
        assert!(!variant.is_on_sale());
    }

    // ============================================================================
    // ProductStatus Tests
    // ============================================================================

    #[test]
    fn test_product_status_default() {
        assert_eq!(ProductStatus::default(), ProductStatus::Draft);
    }

    #[test]
    fn test_product_status_display() {
        assert_eq!(format!("{}", ProductStatus::Draft), "draft");
        assert_eq!(format!("{}", ProductStatus::Active), "active");
        assert_eq!(format!("{}", ProductStatus::Archived), "archived");
    }

    #[test]
    fn test_product_status_serialization() {
        let status = ProductStatus::Active;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"active\"");

        let deserialized: ProductStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, status);
    }

    // ============================================================================
    // ProductType Tests
    // ============================================================================

    #[test]
    fn test_product_type_default() {
        assert_eq!(ProductType::default(), ProductType::Simple);
    }

    #[test]
    fn test_product_type_display() {
        assert_eq!(format!("{}", ProductType::Simple), "simple");
        assert_eq!(format!("{}", ProductType::Variable), "variable");
        assert_eq!(format!("{}", ProductType::Bundle), "bundle");
        assert_eq!(format!("{}", ProductType::Digital), "digital");
    }

    #[test]
    fn test_product_type_serialization() {
        let ptype = ProductType::Bundle;
        let json = serde_json::to_string(&ptype).unwrap();
        assert_eq!(json, "\"bundle\"");

        let deserialized: ProductType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ptype);
    }

    // ============================================================================
    // CreateProduct Tests
    // ============================================================================

    #[test]
    fn test_create_product_default() {
        let create = CreateProduct::default();
        assert!(create.name.is_empty());
        assert!(create.slug.is_none());
        assert!(create.description.is_none());
        assert!(create.product_type.is_none());
    }

    // ============================================================================
    // CreateProductVariant Tests
    // ============================================================================

    #[test]
    fn test_create_product_variant_default() {
        let create = CreateProductVariant::default();
        assert!(create.sku.is_empty());
        assert_eq!(create.price, Decimal::ZERO);
        assert!(create.name.is_none());
        assert!(create.cost.is_none());
    }

    // ============================================================================
    // UpdateProduct Tests
    // ============================================================================

    #[test]
    fn test_update_product_default() {
        let update = UpdateProduct::default();
        assert!(update.name.is_none());
        assert!(update.slug.is_none());
        assert!(update.status.is_none());
    }

    #[test]
    fn test_update_product_partial() {
        let update = UpdateProduct {
            status: Some(ProductStatus::Archived),
            name: Some("Updated Name".to_string()),
            ..Default::default()
        };

        assert_eq!(update.status, Some(ProductStatus::Archived));
        assert_eq!(update.name, Some("Updated Name".to_string()));
        assert!(update.description.is_none());
    }

    // ============================================================================
    // ProductFilter Tests
    // ============================================================================

    #[test]
    fn test_product_filter_default() {
        let filter = ProductFilter::default();
        assert!(filter.status.is_none());
        assert!(filter.product_type.is_none());
        assert!(filter.search.is_none());
        assert!(filter.min_price.is_none());
    }

    #[test]
    fn test_product_filter_with_price_range() {
        let filter = ProductFilter {
            min_price: Some(dec!(10.00)),
            max_price: Some(dec!(100.00)),
            in_stock: Some(true),
            ..Default::default()
        };

        assert_eq!(filter.min_price, Some(dec!(10.00)));
        assert_eq!(filter.max_price, Some(dec!(100.00)));
        assert_eq!(filter.in_stock, Some(true));
    }

    // ============================================================================
    // Serialization Tests
    // ============================================================================

    #[test]
    fn test_product_serialization_roundtrip() {
        let product = create_test_product(ProductStatus::Active);
        let json = serde_json::to_string(&product).unwrap();
        let deserialized: Product = serde_json::from_str(&json).unwrap();
        assert_eq!(product, deserialized);
    }

    #[test]
    fn test_product_variant_serialization_roundtrip() {
        let variant = create_test_variant(dec!(99.99), Some(dec!(50.00)), Some(dec!(129.99)));
        let json = serde_json::to_string(&variant).unwrap();
        let deserialized: ProductVariant = serde_json::from_str(&json).unwrap();
        assert_eq!(variant, deserialized);
    }

    #[test]
    fn test_product_attribute_serialization() {
        let attr = ProductAttribute {
            name: "Material".to_string(),
            value: "Cotton".to_string(),
            group: Some("Fabric".to_string()),
            is_visible: true,
            is_variation: false,
        };

        let json = serde_json::to_string(&attr).unwrap();
        let deserialized: ProductAttribute = serde_json::from_str(&json).unwrap();
        assert_eq!(attr, deserialized);
    }

    #[test]
    fn test_variant_option_serialization() {
        let option = VariantOption { name: "Color".to_string(), value: "Red".to_string() };

        let json = serde_json::to_string(&option).unwrap();
        let deserialized: VariantOption = serde_json::from_str(&json).unwrap();
        assert_eq!(option, deserialized);
    }

    #[test]
    fn test_seo_metadata_serialization() {
        let seo = SeoMetadata {
            title: Some("Great Product".to_string()),
            description: Some("Buy now!".to_string()),
            keywords: vec!["great".to_string(), "product".to_string()],
        };

        let json = serde_json::to_string(&seo).unwrap();
        let deserialized: SeoMetadata = serde_json::from_str(&json).unwrap();
        assert_eq!(seo, deserialized);
    }
}