stateset-core 1.22.0

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
//! Validation traits and utilities for domain models
//!
//! This module provides a trait-based approach to validation that domain models
//! can implement to ensure data integrity before persistence.
//!
//! # Example
//!
//! ```rust
//! use stateset_core::{Validate, Result, CommerceError};
//!
//! struct MyModel {
//!     email: String,
//!     quantity: i32,
//! }
//!
//! impl Validate for MyModel {
//!     fn validate(&self) -> Result<()> {
//!         if self.email.is_empty() {
//!             return Err(CommerceError::InvalidInput {
//!                 field: "email".to_string(),
//!                 message: "cannot be empty".to_string(),
//!             });
//!         }
//!         if self.quantity < 0 {
//!             return Err(CommerceError::InvalidInput {
//!                 field: "quantity".to_string(),
//!                 message: "cannot be negative".to_string(),
//!             });
//!         }
//!         Ok(())
//!     }
//! }
//! ```

use crate::errors::{CommerceError, Result};
use rust_decimal::Decimal;

// ============================================================================
// Validate Trait
// ============================================================================

/// Trait for validating domain models before persistence
///
/// Implement this trait to add validation logic to your domain models.
/// The `validate()` method will be called before create/update operations.
pub trait Validate {
    /// Validate the model and return an error if validation fails
    fn validate(&self) -> Result<()>;

    /// Validate and return self if valid (for method chaining)
    fn validated(self) -> Result<Self>
    where
        Self: Sized,
    {
        self.validate()?;
        Ok(self)
    }

    /// Check if the model is valid without returning an error
    fn is_valid(&self) -> bool {
        self.validate().is_ok()
    }
}

// ============================================================================
// Validation Builder
// ============================================================================

/// A builder for composing multiple validations
///
/// # Example
///
/// ```rust
/// use stateset_core::ValidationBuilder;
///
/// let result = ValidationBuilder::new()
///     .required("email", "alice@example.com")
///     .email("email", "alice@example.com")
///     .max_length("name", "Alice", 100)
///     .build();
///
/// assert!(result.is_ok());
/// ```
#[derive(Debug, Default)]
#[must_use]
pub struct ValidationBuilder {
    errors: Vec<(String, String)>,
}

impl ValidationBuilder {
    /// Create a new validation builder
    pub const fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Add an error if the condition is false
    pub fn check(mut self, field: &str, condition: bool, message: &str) -> Self {
        if !condition {
            self.errors.push((field.to_string(), message.to_string()));
        }
        self
    }

    /// Validate that a string field is not empty
    pub fn required(self, field: &str, value: &str) -> Self {
        self.check(field, !value.trim().is_empty(), "cannot be empty")
    }

    /// Validate that an optional string field is not empty if present
    pub fn required_if_present(self, field: &str, value: Option<&str>) -> Self {
        match value {
            Some(v) => self.check(field, !v.trim().is_empty(), "cannot be empty if provided"),
            None => self,
        }
    }

    /// Validate email format
    pub fn email(self, field: &str, value: &str) -> Self {
        self.check(
            field,
            crate::errors::validate_email(value).is_ok(),
            "must be a valid email address",
        )
    }

    /// Validate optional email format
    pub fn email_if_present(self, field: &str, value: Option<&str>) -> Self {
        match value {
            Some(v) if !v.is_empty() => self.email(field, v),
            _ => self,
        }
    }

    /// Validate string maximum length
    pub fn max_length(self, field: &str, value: &str, max: usize) -> Self {
        self.check(
            field,
            value.trim().chars().count() <= max,
            &format!("cannot exceed {max} characters"),
        )
    }

    /// Validate string minimum length
    pub fn min_length(self, field: &str, value: &str, min: usize) -> Self {
        self.check(
            field,
            value.trim().chars().count() >= min,
            &format!("must be at least {min} characters"),
        )
    }

    /// Validate string length range
    pub fn length_range(self, field: &str, value: &str, min: usize, max: usize) -> Self {
        self.min_length(field, value, min).max_length(field, value, max)
    }

    /// Validate a positive decimal value (> 0)
    pub fn positive(self, field: &str, value: Decimal) -> Self {
        self.check(field, value > Decimal::ZERO, "must be positive")
    }

    /// Validate a non-negative decimal value (>= 0)
    pub fn non_negative(self, field: &str, value: Decimal) -> Self {
        self.check(field, value >= Decimal::ZERO, "cannot be negative")
    }

    /// Validate a decimal value is within range
    pub fn range(self, field: &str, value: Decimal, min: Decimal, max: Decimal) -> Self {
        self.check(field, value >= min && value <= max, &format!("must be between {min} and {max}"))
    }

    /// Validate a positive integer value (> 0)
    pub fn positive_i32(self, field: &str, value: i32) -> Self {
        self.check(field, value > 0, "must be positive")
    }

    /// Validate a non-negative integer value (>= 0)
    pub fn non_negative_i32(self, field: &str, value: i32) -> Self {
        self.check(field, value >= 0, "cannot be negative")
    }

    /// Validate a positive integer value (> 0)
    pub fn positive_i64(self, field: &str, value: i64) -> Self {
        self.check(field, value > 0, "must be positive")
    }

    /// Validate a UUID is not nil
    pub fn uuid_not_nil(self, field: &str, value: uuid::Uuid) -> Self {
        self.check(field, !value.is_nil(), "cannot be nil")
    }

    /// Validate a list is not empty
    pub fn non_empty_list<T>(self, field: &str, value: &[T]) -> Self {
        self.check(field, !value.is_empty(), "cannot be empty")
    }

    /// Validate a list has at most N items
    pub fn max_items<T>(self, field: &str, value: &[T], max: usize) -> Self {
        self.check(field, value.len() <= max, &format!("cannot have more than {max} items"))
    }

    /// Validate a SKU format (alphanumeric, hyphens, underscores)
    pub fn sku(self, field: &str, value: &str) -> Self {
        let value = value.trim();
        let is_valid = !value.is_empty()
            && value.chars().count() <= 100
            && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
        self.check(field, is_valid, "must be a valid SKU (alphanumeric, hyphens, underscores)")
    }

    /// Validate a currency code (3 uppercase letters)
    pub fn currency_code(self, field: &str, value: &str) -> Self {
        let value = value.trim();
        let is_valid = value.len() == 3
            && value.chars().all(|c| c.is_ascii_uppercase() && c.is_ascii_alphabetic());
        self.check(field, is_valid, "must be a 3-letter uppercase currency code")
    }

    /// Validate a phone number (basic validation)
    pub fn phone(self, field: &str, value: &str) -> Self {
        let value = value.trim();
        if value.is_empty() {
            self.check(field, false, "must have 7-15 digits")
        } else {
            let invalid_char = value.chars().any(|ch| {
                !(ch.is_ascii_digit()
                    || ch.is_ascii_whitespace()
                    || matches!(ch, '+' | '-' | '(' | ')' | '.'))
            });
            let digit_count = value.chars().filter(char::is_ascii_digit).count();
            self.check(
                field,
                !invalid_char && (7..=15).contains(&digit_count),
                "must have 7-15 digits",
            )
        }
    }

    /// Validate a postal code (basic validation)
    pub fn postal_code(self, field: &str, value: &str) -> Self {
        let value = value.trim();
        let is_valid = value.chars().count() >= 3
            && value.chars().count() <= 10
            && value.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ' || c == '-');
        self.check(field, is_valid, "must be a valid postal code")
    }

    /// Validate using a custom predicate
    pub fn custom<F>(self, field: &str, predicate: F, message: &str) -> Self
    where
        F: FnOnce() -> bool,
    {
        self.check(field, predicate(), message)
    }

    /// Build the validation result
    ///
    /// Returns Ok(()) if all validations passed, or the first error if any failed
    pub fn build(self) -> Result<()> {
        if let Some((field, message)) = self.errors.into_iter().next() {
            Err(CommerceError::InvalidInput { field, message })
        } else {
            Ok(())
        }
    }

    /// Build the validation result returning all errors
    ///
    /// Returns Ok(()) if all validations passed, or a validation error with all messages
    pub fn build_all(self) -> Result<()> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            let messages: Vec<String> =
                self.errors.iter().map(|(field, msg)| format!("{field}: {msg}")).collect();
            Err(CommerceError::ValidationError(messages.join("; ")))
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_validation_builder_success() {
        let result = ValidationBuilder::new()
            .required("name", "Alice")
            .email("email", "alice@example.com")
            .positive("price", dec!(10.00))
            .build();

        assert!(result.is_ok());
    }

    #[test]
    fn test_validation_builder_required_fails() {
        let result = ValidationBuilder::new().required("name", "").build();

        assert!(result.is_err());
        if let Err(CommerceError::InvalidInput { field, .. }) = result {
            assert_eq!(field, "name");
        } else {
            panic!("Expected InvalidInput error");
        }
    }

    #[test]
    fn test_validation_builder_required_trims_whitespace() {
        assert!(ValidationBuilder::new().required("name", "  ").build().is_err());
        assert!(ValidationBuilder::new().required("name", "  Bob  ").build().is_ok());
    }

    #[test]
    fn test_validation_builder_email_fails() {
        let result = ValidationBuilder::new().email("email", "not-an-email").build();

        assert!(result.is_err());
    }

    #[test]
    fn test_validation_builder_email_rejects_whitespace_and_missing_parts() {
        assert!(ValidationBuilder::new().email("email", "alice @example.com").build().is_err());
        assert!(ValidationBuilder::new().email("email", "@example.com").build().is_err());
        assert!(ValidationBuilder::new().email("email", "alice@").build().is_err());
        assert!(ValidationBuilder::new().email("email", "alice@example").build().is_err());
    }

    #[test]
    fn test_validation_builder_email_rejects_invalid_labels_and_dots() {
        assert!(ValidationBuilder::new().email("email", "alice..bob@example.com").build().is_err());
        assert!(ValidationBuilder::new().email("email", "alice@-example.com").build().is_err());
        assert!(ValidationBuilder::new().email("email", "alice@example..com").build().is_err());
    }

    #[test]
    fn test_validation_builder_positive_fails() {
        let result = ValidationBuilder::new().positive("price", dec!(-5.00)).build();

        assert!(result.is_err());
        if let Err(CommerceError::InvalidInput { field, .. }) = result {
            assert_eq!(field, "price");
        } else {
            panic!("Expected InvalidInput error");
        }
    }

    #[test]
    fn test_validation_builder_max_length() {
        let result = ValidationBuilder::new().max_length("code", "ABC123", 3).build();

        assert!(result.is_err());
    }

    #[test]
    fn test_validation_builder_trimmed_lengths() {
        assert!(ValidationBuilder::new().min_length("name", "  abc  ", 3).build().is_ok());
        assert!(ValidationBuilder::new().max_length("name", "  abcd  ", 3).build().is_err());
    }

    #[test]
    fn test_validation_builder_sku() {
        // Valid SKUs
        assert!(ValidationBuilder::new().sku("sku", "SKU-001").build().is_ok());
        assert!(ValidationBuilder::new().sku("sku", "WIDGET_BLUE_XL").build().is_ok());
        assert!(ValidationBuilder::new().sku("sku", " sku-001 ").build().is_ok());

        // Invalid SKUs
        assert!(ValidationBuilder::new().sku("sku", "").build().is_err());
        assert!(ValidationBuilder::new().sku("sku", "SKU 001").build().is_err());
        assert!(ValidationBuilder::new().sku("sku", "s-kü").build().is_err());
    }

    #[test]
    fn test_validation_builder_currency_code_trimming() {
        assert!(ValidationBuilder::new().currency_code("currency", " usd ").build().is_err());
        assert!(ValidationBuilder::new().currency_code("currency", "USD").build().is_ok());
        assert!(ValidationBuilder::new().currency_code("currency", " USD ").build().is_ok());
    }

    #[test]
    fn test_validation_builder_build_all() {
        let result = ValidationBuilder::new()
            .required("name", "")
            .email("email", "bad")
            .positive("price", dec!(-1))
            .build_all();

        assert!(result.is_err());
        if let Err(CommerceError::ValidationError(msg)) = result {
            assert!(msg.contains("name:"));
            assert!(msg.contains("email:"));
            assert!(msg.contains("price:"));
        } else {
            panic!("Expected ValidationError");
        }
    }

    #[test]
    fn test_validation_builder_phone_rejects_invalid_characters() {
        assert!(ValidationBuilder::new().phone("phone", "123-456-ABCD").build().is_err());
        assert!(ValidationBuilder::new().phone("phone", "+1 (415) 555-2671").build().is_ok());
    }

    #[test]
    fn test_validation_builder_postal_code_validates_ascii_only() {
        assert!(ValidationBuilder::new().postal_code("postal", "12AB-34").build().is_ok());
        assert!(ValidationBuilder::new().postal_code("postal", "123-45").build().is_err());
    }

    struct TestModel {
        name: String,
        price: Decimal,
    }

    impl Validate for TestModel {
        fn validate(&self) -> Result<()> {
            ValidationBuilder::new()
                .required("name", &self.name)
                .positive("price", self.price)
                .build()
        }
    }

    #[test]
    fn test_validate_trait() {
        let valid = TestModel { name: "Widget".to_string(), price: dec!(10.00) };
        assert!(valid.validate().is_ok());
        assert!(valid.is_valid());

        let invalid = TestModel { name: String::new(), price: dec!(10.00) };
        assert!(invalid.validate().is_err());
        assert!(!invalid.is_valid());
    }

    #[test]
    fn test_validated_method() {
        let model = TestModel { name: "Widget".to_string(), price: dec!(10.00) };

        let result = model.validated();
        assert!(result.is_ok());
        assert_eq!(result.unwrap().name, "Widget");
    }
}