stateset-primitives 0.9.7

Strongly-typed primitive types 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
//! Strongly-typed entity identifiers.
//!
//! Each ID type is a newtype around [`Uuid`] that prevents accidentally mixing up
//! identifiers from different domains. All ID types are `Copy`, `Eq`, `Hash`, and
//! support serialization via `serde`.

use serde::{Deserialize, Serialize};
use std::fmt;
use uuid::Uuid;

/// Generate a strongly-typed ID newtype around `Uuid`.
///
/// The generated type implements:
/// - `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`
/// - `Display` (delegates to `Uuid::to_string()`)
/// - `FromStr` (parses via `Uuid::parse_str`)
/// - `From<Uuid>`, `From<IdType> for Uuid`
/// - `AsRef<Uuid>`
/// - `Serialize`, `Deserialize` (transparent)
/// - `new()` to generate a random v4 ID
/// - `nil()` for a zero/nil ID
macro_rules! define_id {
    (
        $(#[$meta:meta])*
        $name:ident
    ) => {
        $(#[$meta])*
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[serde(transparent)]
        #[must_use]
        pub struct $name(Uuid);

        impl $name {
            /// Create a new random ID (UUID v4).
            #[inline]
            pub fn new() -> Self {
                Self(Uuid::new_v4())
            }

            /// Create a nil (all-zeros) ID.
            #[inline]
            pub const fn nil() -> Self {
                Self(Uuid::nil())
            }

            /// Create from an existing [`Uuid`].
            #[inline]
            pub const fn from_uuid(id: Uuid) -> Self {
                Self(id)
            }

            /// Get the inner [`Uuid`].
            #[inline]
            pub const fn as_uuid(&self) -> &Uuid {
                &self.0
            }

            /// Consume and return the inner [`Uuid`].
            #[inline]
            pub const fn into_uuid(self) -> Uuid {
                self.0
            }

            /// Returns `true` if this is a nil (all-zeros) ID.
            #[inline]
            pub const fn is_nil(&self) -> bool {
                self.0.is_nil()
            }
        }

        impl Default for $name {
            #[inline]
            fn default() -> Self {
                Self::new()
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}({})", stringify!($name), self.0)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(f)
            }
        }

        impl std::str::FromStr for $name {
            type Err = uuid::Error;

            #[inline]
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Uuid::parse_str(s).map(Self)
            }
        }

        impl From<Uuid> for $name {
            #[inline]
            fn from(id: Uuid) -> Self {
                Self(id)
            }
        }

        impl From<$name> for Uuid {
            #[inline]
            fn from(id: $name) -> Self {
                id.0
            }
        }

        impl AsRef<Uuid> for $name {
            #[inline]
            fn as_ref(&self) -> &Uuid {
                &self.0
            }
        }

        #[cfg(feature = "sqlx-postgres")]
        impl sqlx::Type<sqlx::Postgres> for $name {
            fn type_info() -> sqlx::postgres::PgTypeInfo {
                <Uuid as sqlx::Type<sqlx::Postgres>>::type_info()
            }
        }

        #[cfg(feature = "sqlx-postgres")]
        impl sqlx::postgres::PgHasArrayType for $name {
            fn array_type_info() -> sqlx::postgres::PgTypeInfo {
                <Uuid as sqlx::postgres::PgHasArrayType>::array_type_info()
            }
        }

        #[cfg(feature = "sqlx-postgres")]
        impl<'q> sqlx::Encode<'q, sqlx::Postgres> for $name {
            fn encode_by_ref(
                &self,
                buf: &mut sqlx::postgres::PgArgumentBuffer,
            ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
                <Uuid as sqlx::Encode<sqlx::Postgres>>::encode_by_ref(&self.0, buf)
            }
        }

        #[cfg(feature = "sqlx-postgres")]
        impl<'r> sqlx::Decode<'r, sqlx::Postgres> for $name {
            fn decode(value: sqlx::postgres::PgValueRef<'r>)
            -> Result<Self, sqlx::error::BoxDynError> {
                <Uuid as sqlx::Decode<'r, sqlx::Postgres>>::decode(value).map(Self)
            }
        }

        #[cfg(any(test, feature = "arbitrary"))]
        impl proptest::arbitrary::Arbitrary for $name {
            type Parameters = ();
            type Strategy = proptest::strategy::MapInto<
                proptest::arbitrary::StrategyFor<[u8; 16]>,
                Self,
            >;

            fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
                use proptest::strategy::Strategy;
                proptest::arbitrary::any::<[u8; 16]>().prop_map_into()
            }
        }

        #[cfg(any(test, feature = "arbitrary"))]
        impl From<[u8; 16]> for $name {
            fn from(bytes: [u8; 16]) -> Self {
                Self(Uuid::from_bytes(bytes))
            }
        }

        #[cfg(feature = "rusqlite")]
        impl rusqlite::types::ToSql for $name {
            #[inline]
            fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
                // Write UUID to stack buffer (no heap allocation)
                Ok(rusqlite::types::ToSqlOutput::Owned(
                    rusqlite::types::Value::Text(self.0.to_string()),
                ))
            }
        }

        #[cfg(feature = "rusqlite")]
        impl rusqlite::types::FromSql for $name {
            #[inline]
            fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
                let text = value.as_str()?;
                Uuid::parse_str(text)
                    .map(Self)
                    .map_err(|e| rusqlite::types::FromSqlError::Other(Box::new(e)))
            }
        }
    };
}

// ---------------------------------------------------------------------------
// Entity ID types
// ---------------------------------------------------------------------------

define_id! {
    /// Strongly-typed order identifier.
    OrderId
}

define_id! {
    /// Strongly-typed customer identifier.
    CustomerId
}

define_id! {
    /// Strongly-typed product identifier.
    ProductId
}

define_id! {
    /// Strongly-typed invoice identifier.
    InvoiceId
}

define_id! {
    /// Strongly-typed shipment identifier.
    ShipmentId
}

define_id! {
    /// Strongly-typed return/RMA identifier.
    ReturnId
}

define_id! {
    /// Strongly-typed warehouse identifier.
    WarehouseId
}

define_id! {
    /// Strongly-typed payment identifier.
    PaymentId
}

define_id! {
    /// Strongly-typed inventory item identifier.
    InventoryItemId
}

define_id! {
    /// Strongly-typed subscription identifier.
    SubscriptionId
}

define_id! {
    /// Strongly-typed shopping cart identifier.
    CartId
}

define_id! {
    /// Strongly-typed fulfillment identifier.
    FulfillmentId
}

define_id! {
    /// Strongly-typed order line item identifier.
    OrderItemId
}

define_id! {
    /// Strongly-typed purchase order identifier.
    PurchaseOrderId
}

define_id! {
    /// Strongly-typed promotion identifier.
    PromotionId
}

define_id! {
    /// Strongly-typed warranty identifier.
    WarrantyId
}

define_id! {
    /// Strongly-typed credit memo identifier.
    CreditId
}

define_id! {
    /// Strongly-typed agent identifier (A2A commerce).
    AgentId
}

define_id! {
    /// Strongly-typed gift card identifier.
    GiftCardId
}

define_id! {
    /// Strongly-typed store credit identifier.
    StoreCreditId
}

define_id! {
    /// Strongly-typed customer segment identifier.
    SegmentId
}

define_id! {
    /// Strongly-typed shipping zone identifier.
    ShippingZoneId
}

define_id! {
    /// Strongly-typed shipping method identifier.
    ShippingMethodId
}

define_id! {
    /// Strongly-typed product review identifier.
    ReviewId
}

define_id! {
    /// Strongly-typed wishlist identifier.
    WishlistId
}

define_id! {
    /// Strongly-typed loyalty program identifier.
    LoyaltyProgramId
}

define_id! {
    /// Strongly-typed reward identifier.
    RewardId
}

define_id! {
    /// Strongly-typed gift card transaction identifier.
    GiftCardTransactionId
}

define_id! {
    /// Strongly-typed store credit transaction identifier.
    StoreCreditTransactionId
}

define_id! {
    /// Strongly-typed loyalty transaction identifier.
    LoyaltyTransactionId
}

define_id! {
    /// Strongly-typed fraud rule identifier.
    FraudRuleId
}

define_id! {
    /// Strongly-typed search configuration identifier.
    SearchConfigId
}

define_id! {
    /// Strongly-typed loyalty account identifier.
    LoyaltyAccountId
}

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

    #[test]
    fn id_types_are_distinct() {
        let order_id = OrderId::new();
        let customer_id = CustomerId::new();

        // Both are UUIDs internally, but they're different types
        let _: Uuid = order_id.into();
        let _: Uuid = customer_id.into();

        // This would NOT compile (which is the point):
        // let _: OrderId = customer_id;
    }

    #[test]
    fn roundtrip_display_parse() {
        let id = OrderId::new();
        let s = id.to_string();
        let parsed: OrderId = s.parse().unwrap();
        assert_eq!(id, parsed);
    }

    #[test]
    fn serde_roundtrip() {
        let id = ProductId::new();
        let json = serde_json::to_string(&id).unwrap();
        let parsed: ProductId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, parsed);

        // Serializes as a plain UUID string
        let uuid_json = serde_json::to_string(id.as_uuid()).unwrap();
        assert_eq!(json, uuid_json);
    }

    #[test]
    fn nil_id() {
        let id = OrderId::nil();
        assert!(id.is_nil());
        assert_eq!(id.to_string(), "00000000-0000-0000-0000-000000000000");
    }

    #[test]
    fn debug_includes_type_name() {
        let id = CustomerId::nil();
        let debug = format!("{:?}", id);
        assert!(debug.starts_with("CustomerId("));
    }

    #[test]
    fn from_uuid_roundtrip() {
        let uuid = Uuid::new_v4();
        let order_id = OrderId::from(uuid);
        assert_eq!(Uuid::from(order_id), uuid);
    }

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn order_id_display_parse_roundtrip(id: OrderId) {
                let s = id.to_string();
                let parsed: OrderId = s.parse().unwrap();
                prop_assert_eq!(id, parsed);
            }

            #[test]
            fn customer_id_display_parse_roundtrip(id: CustomerId) {
                let s = id.to_string();
                let parsed: CustomerId = s.parse().unwrap();
                prop_assert_eq!(id, parsed);
            }

            #[test]
            fn product_id_serde_roundtrip(id: ProductId) {
                let json = serde_json::to_string(&id).unwrap();
                let parsed: ProductId = serde_json::from_str(&json).unwrap();
                prop_assert_eq!(id, parsed);
            }
        }
    }
}