commerce-theory 0.1.2

Runtime Rust mirror of the CommerceTheory Lean package
Documentation
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
//! Runtime Rust mirror of the `CommerceTheory` Lean package.
//!
//! The Lean package stores proof fields in validated records. This crate mirrors
//! those records with private fields, smart constructors, executable predicates,
//! and tests that exercise the same safety guarantees at runtime.

#![forbid(unsafe_code)]
#![allow(clippy::too_many_arguments)]

#[doc(hidden)]
pub trait FieldAccess {
    type Output<'a>
    where
        Self: 'a;

    fn access(&self) -> Self::Output<'_>;
}

#[doc(hidden)]
pub trait RefFieldAccess {}

impl<T: RefFieldAccess> FieldAccess for T {
    type Output<'a>
        = &'a Self
    where
        Self: 'a;

    fn access(&self) -> Self::Output<'_> {
        self
    }
}

impl FieldAccess for String {
    type Output<'a> = &'a str;

    fn access(&self) -> Self::Output<'_> {
        self
    }
}

impl<T> FieldAccess for Vec<T> {
    type Output<'a>
        = &'a [T]
    where
        T: 'a;

    fn access(&self) -> Self::Output<'_> {
        self
    }
}

impl<T: Copy> FieldAccess for Option<T> {
    type Output<'a>
        = Self
    where
        T: 'a;

    fn access(&self) -> Self::Output<'_> {
        *self
    }
}

macro_rules! impl_copy_field_access {
    ($($ty:ty),* $(,)?) => {
        $(
            impl $crate::FieldAccess for $ty {
                type Output<'a> = Self;

                fn access(&self) -> Self::Output<'_> {
                    *self
                }
            }
        )*
    };
}

macro_rules! impl_ref_field_access {
    ($($ty:ty),* $(,)?) => {
        $(
            impl $crate::RefFieldAccess for $ty {}
        )*
    };
}

impl_copy_field_access!(
    bool,
    u128,
    i128,
    time::Date,
    time::Duration,
    time::PrimitiveDateTime,
);

macro_rules! field_getter {
    ($field:ident : $ty:ty) => {
        #[must_use]
        pub fn $field(&self) -> <$ty as $crate::FieldAccess>::Output<'_> {
            <$ty as $crate::FieldAccess>::access(&self.$field)
        }
    };
}

macro_rules! domain_struct {
    ($(#[$meta:meta])* $vis:vis struct $name:ident { $($field:ident : $ty:ty),* $(,)? }) => {
        $(#[$meta])*
        #[derive(Clone, Debug, PartialEq, Eq)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        $vis struct $name {
            $(pub(crate) $field: $ty),*
        }

        impl $name {
            #[must_use]
            pub const fn new($($field: $ty),*) -> Self {
                Self { $($field),* }
            }

            pub const fn try_new($($field: $ty),*) -> Result<Self, $crate::foundation::ValidationError> {
                Ok(Self::new($($field),*))
            }

            $(
                field_getter!($field: $ty);
            )*
        }

        impl $crate::RefFieldAccess for $name {}
    };
}

macro_rules! impl_getters {
    ($name:ident { $($field:ident : $ty:ty),* $(,)? }) => {
        impl $name {
            $(
                field_getter!($field: $ty);
            )*
        }
    };
}

pub mod accounting;
pub mod b2b;
pub mod basic;
pub mod catalog;
pub mod competitor_pricing;
pub mod crm;
pub mod dropship_profit;
pub mod dropshipping;
pub mod event_language;
pub mod event_replay;
pub mod event_sourcing;
pub mod forecasting;
pub mod foundation;
pub mod fulfillment_finance;
pub mod implicit_invariants;
pub mod inventory;
pub mod inventory_algorithms;
pub mod keyed_totals;
pub mod logistics;
pub mod marketing;
pub mod marketplace;
pub mod merchandising;
pub mod opportunity_portfolio;
pub mod opportunity_ranking;
pub mod orders;
pub mod post_purchase;
pub mod pricing;
pub mod risk_privacy;
pub mod summary;
pub mod tax;
pub mod validation;
pub mod workflow;

pub use accounting::*;
pub use b2b::*;
pub use basic::*;
pub use catalog::*;
pub use competitor_pricing::*;
pub use crm::*;
pub use dropship_profit::*;
pub use dropshipping::*;
pub use event_language::*;
pub use event_replay::*;
pub use event_sourcing::*;
pub use forecasting::*;
pub use foundation::*;
pub use fulfillment_finance::*;
pub use implicit_invariants::*;
pub use inventory::*;
pub use inventory_algorithms::*;
pub use keyed_totals::*;
pub use logistics::*;
pub use marketing::*;
pub use marketplace::*;
pub use merchandising::*;
pub use opportunity_portfolio::*;
pub use opportunity_ranking::*;
pub use orders::*;
pub use post_purchase::*;
pub use pricing::*;
pub use risk_privacy::*;
pub use tax::*;
pub use validation::*;
pub use workflow::*;

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

    #[test]
    fn crate_private_anchor_functions_are_covered() {
        let stock = StockState::try_new(Sku::new(1), 1, 0).unwrap();

        crate::b2b::_marketing_anchor(None);
        crate::dropship_profit::_dropshipping_anchor(None);
        crate::dropshipping::_b2b_anchor(None);
        crate::event_sourcing::_risk_anchor(None);
        crate::forecasting::_post_purchase_anchor(None);
        crate::fulfillment_finance::_merchandising_anchor(None);
        crate::merchandising::_competitor_anchor(None);
        crate::opportunity_portfolio::_forecasting_anchor(None);
        crate::post_purchase::_event_anchor(None);
        crate::pricing::_inventory_anchor(&stock);
    }
}

impl_copy_field_access!(
    AccountTier,
    Action,
    AccessPurpose,
    AdDestination,
    AdPlatform,
    AdType,
    CampaignStatus,
    CanOrderTransition,
    CompetitivePricingStrategy,
    Confidence,
    ConsentPurpose,
    ConsentStatus,
    ContactKind,
    Currency,
    CustomerKind,
    CRMAccountStatus,
    DataCategory,
    DropshipPOStatus,
    DropshipPOTransitionLabel,
    ErasureStatus,
    InteractionKind,
    LeadStatus,
    ListingStatus,
    LogisticsExceptionKind,
    Marketplace,
    OpportunityStage,
    OrderEventSymbol,
    OrderEventValidationState,
    OrderStatus,
    OrderTransitionLabel,
    PaymentState,
    PaymentTerms,
    PostingSide,
    ProcessingBasis,
    ProductStatus,
    PromotionStackingPolicy,
    ReservationStatus,
    ReturnAuthorizationStatus,
    Role,
    RoundingMode,
    SalesChannel,
    SerialNumber,
    ShipmentStatus,
    SubscriptionLifecycleStatus,
    SubscriptionStatus,
    SupplierReservationStatus,
    SupportCaseStatus,
    SupportPriority,
    TaxPriceMode,
    TaxRegime,
    TaxTreatment,
    TrackingEventKind,
    TradeMode,
    TrustLevel,
    ValidationError,
    Lead,
    SalesOpportunity,
    StockState,
    SupportCase,
    TimedReservation,
    VersionedStock,
);

impl<T> RefFieldAccess for Timed<T> {}

impl<S: OrderStatusMarker> FieldAccess for TypedOrder<S> {
    type Output<'a>
        = Self
    where
        S: 'a;

    fn access(&self) -> Self::Output<'_> {
        *self
    }
}

impl<S: PaymentStateMarker> FieldAccess for TypedPayment<S> {
    type Output<'a>
        = Self
    where
        S: 'a;

    fn access(&self) -> Self::Output<'_> {
        *self
    }
}

impl_ref_field_access!(
    AcceptedPromotionSet,
    ActiveCRMAccount,
    ApprovedOrderableSupplierQuality,
    ApprovedSupplierQuality,
    AuditedCommand,
    AuditedDataAccess,
    AuditedEntityCommand,
    BackorderRequest,
    B2BTaxExemption,
    BalancedJournalEntry,
    BrandPricingPolicy,
    BoundedCouponApplication,
    BundleComponent,
    BundleReservation,
    CapturedPaymentJournalProjection,
    CapturedPaymentMatchesOrder,
    CarrierHandoff,
    CarrierQuote,
    CartLine,
    CashflowPlan,
    ChannelPricePolicy,
    Chargeback,
    ChargebackForCapturedPayment,
    ClickAttributedCampaign,
    CompetitorAwareDropshipOffer,
    CompetitorPriceBenchmark,
    ConcurrentReservationConflict,
    ConvertedLeadOpportunity,
    CRMAccount,
    CRMAccountContact,
    CRMApprovedReturnHandling,
    CRMInteraction,
    CRMInteractionForContact,
    CRMOrderContact,
    CustomerSegment,
    DeliveredShipment,
    DeliveryPromise,
    DistinctFulfillmentPlan,
    DomainEvent,
    DropshipCostUpperBounds,
    DropshipFulfillment,
    DropshipLine,
    DropshipOpportunityCandidate,
    DropshipOpportunityPortfolio,
    DropshipOffer,
    DropshipPurchaseOrder,
    DropshipReturnRequest,
    EventBackedCashflowPlan,
    Experiment,
    ExperimentVariant,
    ExchangeRate,
    FreshCurrencyConversion,
    FraudCheckedCouponApplication,
    Funnel,
    GiftCardRedemption,
    GuaranteedDropshipProfitQuote,
    LeadForContact,
    LogisticsExceptionSupportCase,
    LogisticsShipment,
    LogisticsShipmentPlan,
    MapCompliantCompetitorAwareOffer,
    MarketplaceFacilitatorTax,
    MarketplaceFeeLedger,
    MarketplaceOrder,
    MarketplacePayoutCalculation,
    MarketingCampaign,
    MatchedOrderAttributionLedger,
    Order,
    OrderAttributionLedger,
    OrderTaxInvoiceLink,
    OpportunityForContact,
    PaymentLedger,
    PermittedAccountMessage,
    PermittedCustomerMessage,
    PickTask,
    PreorderReservation,
    PreorderWindow,
    ProductCatalogEntry,
    PublishableFeedLine,
    ReconciliationWithinTolerance,
    RecurringSubscription,
    RefundJournalProjection,
    ReservedDropshipLine,
    ReservationAttempt,
    ResolvedSupportCase,
    RetainedPersonalData,
    RetentionOffer,
    RetailLine,
    ReturnAuthorization,
    ReturnReceipt,
    SalesPipeline,
    SafeProductFeedLine,
    SellableCatalogEntry,
    SegmentMembership,
    SerializedInventorySet,
    ShipmentForCRMOrder,
    SkuSubstitution,
    SourceableDistributorProduct,
    SplitFulfillmentPlan,
    SubscriptionPlan,
    SupplierDailyCapacity,
    SupplierReservation,
    SupportCaseForContact,
    SyncedMarketplaceListing,
    TaxCalculation,
    TaxExclusivePrice,
    TaxExemptionCertificate,
    TaxInclusivePrice,
    TaxInvoice,
    TaxInvoiceLine,
    TrackingHistory,
    TradePriceBookEntry,
    TrustedFreshCompetitorBenchmark,
    ValidEventStream,
    ValidGiftCardRedemptionAt,
    ValidListingContent,
    ValidRefund,
    ValidSearchResultItem,
    WarehouseShipment,
    WarehouseTransfer,
    WholesaleCreditAccount,
    WholesaleCreditCheckout,
    WholesaleLine,
);