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
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
use crate::foundation::*;
use crate::marketing::*;

domain_struct! {
    #[allow(clippy::struct_field_names)]
    pub struct FraudPolicy {
        max_coupon_uses: Nat,
        max_orders_per_hour: Nat,
        max_zero_total_items: Nat,
    }
}

#[must_use]
pub const fn coupon_uses_allowed(policy: &FraudPolicy, uses: Nat) -> bool {
    uses <= policy.max_coupon_uses
}

#[must_use]
pub const fn orders_per_hour_allowed(policy: &FraudPolicy, orders_per_hour: Nat) -> bool {
    orders_per_hour <= policy.max_orders_per_hour
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Role {
    Customer,
    Support,
    Warehouse,
    Manager,
    Finance,
    Admin,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Action {
    ViewOrder,
    PackOrder,
    ShipOrder,
    IssueRefund,
    OverridePrice,
    AdjustStock,
    DeleteOrder,
    ManageCRM,
    CreateSupportCase,
    ResolveSupportCase,
    ManageShipment,
    ApproveReturn,
}

#[must_use]
pub const fn can_perform(role: Role, action: Action) -> bool {
    matches!(
        (role, action),
        (Role::Admin, _)
            | (
                Role::Support | Role::Manager | Role::Finance,
                Action::ViewOrder
            )
            | (
                Role::Warehouse,
                Action::PackOrder
                    | Action::ShipOrder
                    | Action::AdjustStock
                    | Action::ManageShipment
            )
            | (
                Role::Manager,
                Action::OverridePrice
                    | Action::ManageCRM
                    | Action::ResolveSupportCase
                    | Action::ApproveReturn
            )
            | (
                Role::Support,
                Action::CreateSupportCase | Action::ResolveSupportCase | Action::ManageCRM
            )
            | (Role::Finance, Action::IssueRefund | Action::ApproveReturn)
    )
}

domain_struct! {
    pub struct AuditEvent {
        actor: Role,
        action: Action,
        order_id: OrderId,
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AuditedCommand {
    pub(crate) actor: Role,
    pub(crate) action: Action,
    pub(crate) order_id: OrderId,
    pub(crate) event: AuditEvent,
}

domain_struct! {
    pub struct EntityAuditEvent {
        actor: Role,
        action: Action,
        subject_id: Id,
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AuditedEntityCommand {
    pub(crate) actor: Role,
    pub(crate) action: Action,
    pub(crate) subject_id: Id,
    pub(crate) event: EntityAuditEvent,
}

impl AuditedEntityCommand {
    pub fn try_new(
        actor: Role,
        action: Action,
        subject_id: Id,
        event: EntityAuditEvent,
    ) -> DomainResult<Self> {
        if !can_perform(actor, action) {
            return Err(ValidationError::AuditPermissionDenied);
        }
        if event.actor != actor || event.action != action || event.subject_id != subject_id {
            return Err(ValidationError::Invariant(
                "entity audit event does not match command",
            ));
        }
        Ok(Self {
            actor,
            action,
            subject_id,
            event,
        })
    }
}

impl AuditedCommand {
    pub fn try_new(
        actor: Role,
        action: Action,
        order_id: OrderId,
        event: AuditEvent,
    ) -> DomainResult<Self> {
        if !can_perform(actor, action) {
            return Err(ValidationError::Invariant("actor cannot perform action"));
        }
        if event.actor != actor || event.action != action || event.order_id != order_id {
            return Err(ValidationError::Invariant(
                "audit event does not match command",
            ));
        }
        Ok(Self {
            actor,
            action,
            order_id,
            event,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ConsentPurpose {
    Marketing,
    Analytics,
    Personalization,
    FraudPrevention,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProcessingBasis {
    Consent,
    Contract,
    LegalObligation,
    LegitimateInterest,
}

domain_struct! {
    pub struct DataProcessingPermission {
        purpose: ConsentPurpose,
        basis: ProcessingBasis,
        allowed: bool,
    }
}

#[must_use]
pub const fn data_processing_allowed(permission: &DataProcessingPermission) -> bool {
    permission.allowed
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DataCategory {
    CustomerProfile,
    ContactData,
    OrderData,
    PaymentToken,
    MarketingProfile,
    SupportNotes,
    AnalyticsEvent,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AccessPurpose {
    CustomerSupport,
    Fulfillment,
    RefundProcessing,
    MarketingOperations,
    FraudReview,
    Analytics,
    Administration,
}

#[must_use]
pub const fn role_can_access_data(
    role: Role,
    purpose: AccessPurpose,
    category: DataCategory,
) -> bool {
    matches!(
        (role, purpose, category),
        (Role::Admin, _, _)
            | (
                Role::Support,
                AccessPurpose::CustomerSupport,
                DataCategory::OrderData | DataCategory::ContactData | DataCategory::SupportNotes
            )
            | (
                Role::Warehouse,
                AccessPurpose::Fulfillment,
                DataCategory::OrderData | DataCategory::ContactData
            )
            | (
                Role::Finance,
                AccessPurpose::RefundProcessing,
                DataCategory::OrderData | DataCategory::PaymentToken
            )
            | (
                Role::Manager,
                AccessPurpose::MarketingOperations | AccessPurpose::Administration,
                DataCategory::MarketingProfile
            )
            | (
                Role::Manager,
                AccessPurpose::MarketingOperations,
                DataCategory::ContactData
            )
            | (
                Role::Manager,
                AccessPurpose::Administration,
                DataCategory::CustomerProfile
            )
    )
}

#[must_use]
pub fn processing_allowed_for(
    permission: &DataProcessingPermission,
    purpose: ConsentPurpose,
    basis: ProcessingBasis,
) -> bool {
    data_processing_allowed(permission)
        && permission.purpose == purpose
        && permission.basis == basis
}

domain_struct! {
    pub struct MarketingConsentState {
        subscription: SubscriptionStatus,
        retargeting_consent: ConsentStatus,
        data_permission: DataProcessingPermission,
    }
}

#[must_use]
pub fn marketing_allowed(state: &MarketingConsentState) -> bool {
    can_send_marketing_message(state.subscription)
        && can_retarget(state.retargeting_consent)
        && processing_allowed_for(
            &state.data_permission,
            ConsentPurpose::Marketing,
            ProcessingBasis::Consent,
        )
}

#[must_use]
pub fn withdraw_marketing_consent(state: &MarketingConsentState) -> MarketingConsentState {
    MarketingConsentState::new(
        SubscriptionStatus::Unsubscribed,
        ConsentStatus::Denied,
        DataProcessingPermission::new(
            state.data_permission.purpose(),
            state.data_permission.basis(),
            false,
        ),
    )
}

domain_struct! {
    pub struct DataRetentionPolicy {
        category: DataCategory,
        retention_window: Duration,
    }
}

#[must_use]
pub fn within_retention_window(
    policy: &DataRetentionPolicy,
    now: Timestamp,
    collected_at: Timestamp,
) -> bool {
    collected_at <= now && timestamp_age(now, collected_at) <= policy.retention_window
}

#[must_use]
pub fn retention_expired(
    policy: &DataRetentionPolicy,
    now: Timestamp,
    collected_at: Timestamp,
) -> bool {
    collected_at <= now && policy.retention_window < timestamp_age(now, collected_at)
}

#[must_use]
pub fn can_retain_personal_data(
    policy: &DataRetentionPolicy,
    now: Timestamp,
    collected_at: Timestamp,
) -> bool {
    within_retention_window(policy, now, collected_at)
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RetainedPersonalData {
    pub(crate) subject_id: CustomerId,
    pub(crate) category: DataCategory,
    pub(crate) collected_at: Timestamp,
    pub(crate) checked_at: Timestamp,
    pub(crate) policy: DataRetentionPolicy,
}

impl RetainedPersonalData {
    pub fn try_new(
        subject_id: CustomerId,
        category: DataCategory,
        collected_at: Timestamp,
        checked_at: Timestamp,
        policy: DataRetentionPolicy,
    ) -> DomainResult<Self> {
        if policy.category != category
            || !can_retain_personal_data(&policy, checked_at, collected_at)
        {
            return Err(ValidationError::Invariant(
                "personal data cannot be retained",
            ));
        }
        Ok(Self {
            subject_id,
            category,
            collected_at,
            checked_at,
            policy,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ErasureStatus {
    Active,
    Requested,
    Completed,
    BlockedByLegalHold,
}

#[must_use]
pub fn personal_data_usable(status: ErasureStatus) -> bool {
    status == ErasureStatus::Active
}

#[must_use]
pub fn can_process_personal_data(
    status: ErasureStatus,
    permission: &DataProcessingPermission,
    purpose: ConsentPurpose,
    basis: ProcessingBasis,
) -> bool {
    personal_data_usable(status) && processing_allowed_for(permission, purpose, basis)
}

#[must_use]
pub fn can_complete_erasure(status: ErasureStatus, legal_hold: bool) -> bool {
    status == ErasureStatus::Requested && !legal_hold
}

#[must_use]
pub fn audit_log_appended(
    before: &[EntityAuditEvent],
    after: &[EntityAuditEvent],
    new_events: &[EntityAuditEvent],
) -> bool {
    after.len() == before.len() + new_events.len()
        && after.starts_with(before)
        && after[before.len()..] == new_events[..]
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AuditedDataAccess {
    pub(crate) actor: Role,
    pub(crate) action: Action,
    pub(crate) purpose: AccessPurpose,
    pub(crate) category: DataCategory,
    pub(crate) subject_id: Id,
    pub(crate) event: EntityAuditEvent,
}

impl AuditedDataAccess {
    pub fn try_new(
        actor: Role,
        action: Action,
        purpose: AccessPurpose,
        category: DataCategory,
        subject_id: Id,
        event: EntityAuditEvent,
    ) -> DomainResult<Self> {
        if !can_perform(actor, action) || !role_can_access_data(actor, purpose, category) {
            return Err(ValidationError::AuditPermissionDenied);
        }
        if event.actor != actor || event.action != action || event.subject_id != subject_id {
            return Err(ValidationError::Invariant(
                "data-access audit event does not match access",
            ));
        }
        Ok(Self {
            actor,
            action,
            purpose,
            category,
            subject_id,
            event,
        })
    }
}

impl_getters!(AuditedCommand {
    actor: Role,
    action: Action,
    order_id: OrderId,
    event: AuditEvent,
});

impl_getters!(AuditedEntityCommand {
    actor: Role,
    action: Action,
    subject_id: Id,
    event: EntityAuditEvent,
});

impl_getters!(RetainedPersonalData {
    subject_id: CustomerId,
    category: DataCategory,
    collected_at: Timestamp,
    checked_at: Timestamp,
    policy: DataRetentionPolicy,
});

impl_getters!(AuditedDataAccess {
    actor: Role,
    action: Action,
    purpose: AccessPurpose,
    category: DataCategory,
    subject_id: Id,
    event: EntityAuditEvent,
});