backbone-mailing 0.6.0

Email marketing — mass-mail engine: audiences, subscriptions, hand-set mailing lifecycle, seeded A/B testing, per-recipient traces, cycle-44 bridge targets (Odoo mass_mailing port)
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

use super::TraceType;
use super::TraceStatus;
use super::TraceFailureType;
use super::AuditMetadata;

use crate::domain::state_machine::{TraceStatusStateMachine, TraceStatusState, StateMachineError};

/// Strongly-typed ID for MailingTrace
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct MailingTraceId(pub Uuid);

impl MailingTraceId {
    pub fn new(id: Uuid) -> Self { Self(id) }
    pub fn generate() -> Self { Self(Uuid::new_v4()) }
    pub fn into_inner(self) -> Uuid { self.0 }
}

impl std::fmt::Display for MailingTraceId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for MailingTraceId {
    type Err = uuid::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(Uuid::parse_str(s)?))
    }
}

impl From<Uuid> for MailingTraceId {
    fn from(id: Uuid) -> Self { Self(id) }
}

impl From<MailingTraceId> for Uuid {
    fn from(id: MailingTraceId) -> Self { id.0 }
}

impl AsRef<Uuid> for MailingTraceId {
    fn as_ref(&self) -> &Uuid { &self.0 }
}

impl std::ops::Deref for MailingTraceId {
    type Target = Uuid;
    fn deref(&self) -> &Self::Target { &self.0 }
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct MailingTrace {
    pub id: Uuid,
    pub trace_type: TraceType,
    pub is_test_trace: bool,
    pub mailing_id: Uuid,
    pub campaign_id: Option<Uuid>,
    pub recipient_model: String,
    pub recipient_id: Uuid,
    pub recipient_email: String,
    pub mail_id: Option<Uuid>,
    pub sms_uuid: Option<String>,
    pub recipient_phone: Option<String>,
    pub message_id: Option<String>,
    pub(crate) trace_status: TraceStatus,
    pub failure_type: Option<TraceFailureType>,
    pub failure_reason: Option<String>,
    pub sent_datetime: Option<DateTime<Utc>>,
    pub open_datetime: Option<DateTime<Utc>>,
    pub reply_datetime: Option<DateTime<Utc>>,
    pub links_click_datetime: Option<DateTime<Utc>>,
    #[serde(default)]
    #[sqlx(json)]
    pub metadata: AuditMetadata,
}

impl MailingTrace {
    /// Create a builder for MailingTrace
    pub fn builder() -> MailingTraceBuilder {
        <MailingTraceBuilder as Default>::default()
    }

    /// Create a new MailingTrace with required fields
    pub fn new(trace_type: TraceType, is_test_trace: bool, mailing_id: Uuid, recipient_model: String, recipient_id: Uuid, recipient_email: String, trace_status: TraceStatus) -> Self {
        Self {
            id: Uuid::new_v4(),
            trace_type,
            is_test_trace,
            mailing_id,
            campaign_id: None,
            recipient_model,
            recipient_id,
            recipient_email,
            mail_id: None,
            sms_uuid: None,
            recipient_phone: None,
            message_id: None,
            trace_status,
            failure_type: None,
            failure_reason: None,
            sent_datetime: None,
            open_datetime: None,
            reply_datetime: None,
            links_click_datetime: None,
            metadata: AuditMetadata::default(),
        }
    }

    /// Get the entity's unique identifier
    pub fn id(&self) -> &Uuid {
        &self.id
    }

    /// Get a strongly-typed ID for this entity
    pub fn typed_id(&self) -> MailingTraceId {
        MailingTraceId(self.id)
    }

    /// Get when this entity was created
    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
        self.metadata.created_at.as_ref()
    }

    /// Get when this entity was last updated
    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
        self.metadata.updated_at.as_ref()
    }

    /// Check if this entity is soft deleted
    pub fn is_deleted(&self) -> bool {
        self.metadata.deleted_at.is_some()
    }

    /// Check if this entity is active (not deleted)
    pub fn is_active(&self) -> bool {
        self.metadata.deleted_at.is_none()
    }

    /// Get when this entity was deleted
    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
        self.metadata.deleted_at.as_ref()
    }

    /// Get who created this entity
    pub fn created_by(&self) -> Option<&Uuid> {
        self.metadata.created_by.as_ref()
    }

    /// Get who last updated this entity
    pub fn updated_by(&self) -> Option<&Uuid> {
        self.metadata.updated_by.as_ref()
    }

    /// Get who deleted this entity
    pub fn deleted_by(&self) -> Option<&Uuid> {
        self.metadata.deleted_by.as_ref()
    }


    // ==========================================================
    // Fluent Setters (with_* for optional fields)
    // ==========================================================

    /// Set the campaign_id field (chainable)
    pub fn with_campaign_id(mut self, value: Uuid) -> Self {
        self.campaign_id = Some(value);
        self
    }

    /// Set the mail_id field (chainable)
    pub fn with_mail_id(mut self, value: Uuid) -> Self {
        self.mail_id = Some(value);
        self
    }

    /// Set the sms_uuid field (chainable)
    pub fn with_sms_uuid(mut self, value: String) -> Self {
        self.sms_uuid = Some(value);
        self
    }

    /// Set the recipient_phone field (chainable)
    pub fn with_recipient_phone(mut self, value: String) -> Self {
        self.recipient_phone = Some(value);
        self
    }

    /// Set the message_id field (chainable)
    pub fn with_message_id(mut self, value: String) -> Self {
        self.message_id = Some(value);
        self
    }

    /// Set the failure_type field (chainable)
    pub fn with_failure_type(mut self, value: TraceFailureType) -> Self {
        self.failure_type = Some(value);
        self
    }

    /// Set the failure_reason field (chainable)
    pub fn with_failure_reason(mut self, value: String) -> Self {
        self.failure_reason = Some(value);
        self
    }

    /// Set the sent_datetime field (chainable)
    pub fn with_sent_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.sent_datetime = Some(value);
        self
    }

    /// Set the open_datetime field (chainable)
    pub fn with_open_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.open_datetime = Some(value);
        self
    }

    /// Set the reply_datetime field (chainable)
    pub fn with_reply_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.reply_datetime = Some(value);
        self
    }

    /// Set the links_click_datetime field (chainable)
    pub fn with_links_click_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.links_click_datetime = Some(value);
        self
    }

    // ==========================================================
    // State Machine
    // ==========================================================

    /// Transition to a new state via the trace_status state machine.
    ///
    /// Returns `Err` if the transition is not permitted from the current state.
    /// Use this method instead of assigning `self.trace_status` directly.
    pub fn transition_to(&mut self, new_state: TraceStatusState) -> Result<(), StateMachineError> {
        let current = self.trace_status.to_string().parse::<TraceStatusState>()?;
        let mut sm = TraceStatusStateMachine::from_state(current);
        sm.transition_to_state(new_state)?;
        self.trace_status = new_state.to_string().parse::<TraceStatus>()
            .map_err(|e| StateMachineError::InvalidState(e.to_string()))?;
        Ok(())
    }

    // ==========================================================
    // Partial Update
    // ==========================================================

    /// Apply partial updates from a map of field name to JSON value
    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
        for (key, value) in fields {
            match key.as_str() {
                "trace_type" => {
                    if let Ok(v) = serde_json::from_value(value) { self.trace_type = v; }
                }
                "is_test_trace" => {
                    if let Ok(v) = serde_json::from_value(value) { self.is_test_trace = v; }
                }
                "mailing_id" => {
                    if let Ok(v) = serde_json::from_value(value) { self.mailing_id = v; }
                }
                "campaign_id" => {
                    if let Ok(v) = serde_json::from_value(value) { self.campaign_id = v; }
                }
                "recipient_model" => {
                    if let Ok(v) = serde_json::from_value(value) { self.recipient_model = v; }
                }
                "recipient_id" => {
                    if let Ok(v) = serde_json::from_value(value) { self.recipient_id = v; }
                }
                "recipient_email" => {
                    if let Ok(v) = serde_json::from_value(value) { self.recipient_email = v; }
                }
                "mail_id" => {
                    if let Ok(v) = serde_json::from_value(value) { self.mail_id = v; }
                }
                "sms_uuid" => {
                    if let Ok(v) = serde_json::from_value(value) { self.sms_uuid = v; }
                }
                "recipient_phone" => {
                    if let Ok(v) = serde_json::from_value(value) { self.recipient_phone = v; }
                }
                "message_id" => {
                    if let Ok(v) = serde_json::from_value(value) { self.message_id = v; }
                }
                "failure_type" => {
                    if let Ok(v) = serde_json::from_value(value) { self.failure_type = v; }
                }
                "failure_reason" => {
                    if let Ok(v) = serde_json::from_value(value) { self.failure_reason = v; }
                }
                "sent_datetime" => {
                    if let Ok(v) = serde_json::from_value(value) { self.sent_datetime = v; }
                }
                "open_datetime" => {
                    if let Ok(v) = serde_json::from_value(value) { self.open_datetime = v; }
                }
                "reply_datetime" => {
                    if let Ok(v) = serde_json::from_value(value) { self.reply_datetime = v; }
                }
                "links_click_datetime" => {
                    if let Ok(v) = serde_json::from_value(value) { self.links_click_datetime = v; }
                }
                _ => {} // ignore unknown fields
            }
        }
    }

    // <<< CUSTOM METHODS START >>>
    // <<< CUSTOM METHODS END >>>
}

impl super::Entity for MailingTrace {
    type Id = Uuid;

    fn entity_id(&self) -> &Self::Id {
        &self.id
    }

    fn entity_type() -> &'static str {
        "MailingTrace"
    }
}

impl backbone_core::PersistentEntity for MailingTrace {
    fn write_protected_fields() -> &'static [&'static str] {
        &["trace_status"]
    }
    fn entity_id(&self) -> String {
        self.id.to_string()
    }
    fn set_entity_id(&mut self, id: String) {
        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
            self.id = uuid;
        }
    }
    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        self.metadata.created_at
    }
    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
        self.metadata.created_at = Some(ts);
    }
    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        self.metadata.updated_at
    }
    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
        self.metadata.updated_at = Some(ts);
    }
    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        self.metadata.deleted_at
    }
    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
        self.metadata.deleted_at = ts;
    }
}

impl backbone_orm::EntityRepoMeta for MailingTrace {
    fn column_types() -> std::collections::HashMap<String, String> {
        let mut m = std::collections::HashMap::new();
        m.insert("id".to_string(), "uuid".to_string());
        m.insert("mailing_id".to_string(), "uuid".to_string());
        m.insert("campaign_id".to_string(), "uuid".to_string());
        m.insert("recipient_id".to_string(), "uuid".to_string());
        m.insert("mail_id".to_string(), "uuid".to_string());
        m.insert("trace_type".to_string(), "trace_type".to_string());
        m.insert("trace_status".to_string(), "trace_status".to_string());
        m.insert("failure_type".to_string(), "trace_failure_type".to_string());
        m.insert("sent_datetime".to_string(), "timestamptz".to_string());
        m.insert("open_datetime".to_string(), "timestamptz".to_string());
        m.insert("reply_datetime".to_string(), "timestamptz".to_string());
        m.insert("links_click_datetime".to_string(), "timestamptz".to_string());
        m
    }
    fn search_fields() -> &'static [&'static str] {
        &["recipient_model", "recipient_email"]
    }
}

/// Builder for MailingTrace entity
///
/// Provides a fluent API for constructing MailingTrace instances.
/// System fields (id, metadata, timestamps) are auto-initialized.
#[derive(Debug, Clone, Default)]
pub struct MailingTraceBuilder {
    trace_type: Option<TraceType>,
    is_test_trace: Option<bool>,
    mailing_id: Option<Uuid>,
    campaign_id: Option<Uuid>,
    recipient_model: Option<String>,
    recipient_id: Option<Uuid>,
    recipient_email: Option<String>,
    mail_id: Option<Uuid>,
    sms_uuid: Option<String>,
    recipient_phone: Option<String>,
    message_id: Option<String>,
    trace_status: Option<TraceStatus>,
    failure_type: Option<TraceFailureType>,
    failure_reason: Option<String>,
    sent_datetime: Option<DateTime<Utc>>,
    open_datetime: Option<DateTime<Utc>>,
    reply_datetime: Option<DateTime<Utc>>,
    links_click_datetime: Option<DateTime<Utc>>,
}

impl MailingTraceBuilder {
    /// Set the trace_type field (default: `TraceType::default()`)
    pub fn trace_type(mut self, value: TraceType) -> Self {
        self.trace_type = Some(value);
        self
    }

    /// Set the is_test_trace field (default: `false`)
    pub fn is_test_trace(mut self, value: bool) -> Self {
        self.is_test_trace = Some(value);
        self
    }

    /// Set the mailing_id field (required)
    pub fn mailing_id(mut self, value: Uuid) -> Self {
        self.mailing_id = Some(value);
        self
    }

    /// Set the campaign_id field (optional)
    pub fn campaign_id(mut self, value: Uuid) -> Self {
        self.campaign_id = Some(value);
        self
    }

    /// Set the recipient_model field (required)
    pub fn recipient_model(mut self, value: String) -> Self {
        self.recipient_model = Some(value);
        self
    }

    /// Set the recipient_id field (required)
    pub fn recipient_id(mut self, value: Uuid) -> Self {
        self.recipient_id = Some(value);
        self
    }

    /// Set the recipient_email field (required)
    pub fn recipient_email(mut self, value: String) -> Self {
        self.recipient_email = Some(value);
        self
    }

    /// Set the mail_id field (optional)
    pub fn mail_id(mut self, value: Uuid) -> Self {
        self.mail_id = Some(value);
        self
    }

    /// Set the sms_uuid field (optional)
    pub fn sms_uuid(mut self, value: String) -> Self {
        self.sms_uuid = Some(value);
        self
    }

    /// Set the recipient_phone field (optional)
    pub fn recipient_phone(mut self, value: String) -> Self {
        self.recipient_phone = Some(value);
        self
    }

    /// Set the message_id field (optional)
    pub fn message_id(mut self, value: String) -> Self {
        self.message_id = Some(value);
        self
    }

    /// Set the trace_status field (default: `TraceStatus::default()`)
    pub fn trace_status(mut self, value: TraceStatus) -> Self {
        self.trace_status = Some(value);
        self
    }

    /// Set the failure_type field (optional)
    pub fn failure_type(mut self, value: TraceFailureType) -> Self {
        self.failure_type = Some(value);
        self
    }

    /// Set the failure_reason field (optional)
    pub fn failure_reason(mut self, value: String) -> Self {
        self.failure_reason = Some(value);
        self
    }

    /// Set the sent_datetime field (optional)
    pub fn sent_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.sent_datetime = Some(value);
        self
    }

    /// Set the open_datetime field (optional)
    pub fn open_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.open_datetime = Some(value);
        self
    }

    /// Set the reply_datetime field (optional)
    pub fn reply_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.reply_datetime = Some(value);
        self
    }

    /// Set the links_click_datetime field (optional)
    pub fn links_click_datetime(mut self, value: DateTime<Utc>) -> Self {
        self.links_click_datetime = Some(value);
        self
    }

    /// Build the MailingTrace entity
    ///
    /// Returns Err if any required field without a default is missing.
    pub fn build(self) -> Result<MailingTrace, String> {
        let mailing_id = self.mailing_id.ok_or_else(|| "mailing_id is required".to_string())?;
        let recipient_model = self.recipient_model.ok_or_else(|| "recipient_model is required".to_string())?;
        let recipient_id = self.recipient_id.ok_or_else(|| "recipient_id is required".to_string())?;
        let recipient_email = self.recipient_email.ok_or_else(|| "recipient_email is required".to_string())?;

        Ok(MailingTrace {
            id: Uuid::new_v4(),
            trace_type: self.trace_type.unwrap_or_default(),
            is_test_trace: self.is_test_trace.unwrap_or(false),
            mailing_id,
            campaign_id: self.campaign_id,
            recipient_model,
            recipient_id,
            recipient_email,
            mail_id: self.mail_id,
            sms_uuid: self.sms_uuid,
            recipient_phone: self.recipient_phone,
            message_id: self.message_id,
            trace_status: self.trace_status.unwrap_or_default(),
            failure_type: self.failure_type,
            failure_reason: self.failure_reason,
            sent_datetime: self.sent_datetime,
            open_datetime: self.open_datetime,
            reply_datetime: self.reply_datetime,
            links_click_datetime: self.links_click_datetime,
            metadata: AuditMetadata::default(),
        })
    }
}