backbone-mail 0.2.32

Odoo mail core port — message/notification/followers/activity/alias/sms queue (schema: messaging)
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Messaging Module
//!
//! Generated by metaphor-schema. Enhanced with runtime implementations.
//!
//! This module provides:
//! - Domain entities and repositories
//! - Application services
//! - HTTP and gRPC handlers
//! - Route configuration
//! - State machine enforcement
//! - Validation rules runtime
//! - RBAC middleware
//! - Trigger execution system
//! - Computed fields
//! - Workflow orchestrator

#![recursion_limit = "1024"]
#![allow(unused_imports)]

// Generated modules
pub mod domain;
pub mod infrastructure;
pub mod application;
pub mod presentation;
pub mod seeders;
pub mod exports;

// Re-exports for convenience - Domain entities
pub use domain::entity::*;

// Re-exports - State Machine
pub use domain::state_machine::*;

// Re-exports - Infrastructure
pub use infrastructure::persistence::*;

// Re-exports - Application services
pub use application::service::MailActivityService;
pub use application::service::MailActivityTypeService;
pub use application::service::MailActivityPlanService;
pub use application::service::MailActivityPlanTemplateService;
pub use application::service::MailAliasDomainService;
pub use application::service::MailAliasService;
pub use application::service::MailAttachmentService;
pub use application::service::MailMessageAttachmentService;
pub use application::service::MailMessageStarService;
pub use application::service::MailMessageService;
pub use application::service::MailService;
pub use application::service::MailNotificationService;
pub use application::service::MailMessageSubtypeService;
pub use application::service::MailMessageReactionService;
pub use application::service::MailFollowersService;
pub use application::service::MailPresenceService;
pub use application::service::MailBlacklistService;
pub use application::service::MailTrackingValueService;
pub use application::service::DiscussChannelService;
pub use application::service::DiscussChannelMemberService;
pub use application::service::MailGuestService;
pub use application::service::MailServerService;
pub use application::service::FetchmailServerService;
pub use application::service::MailGatewayAllowedService;
pub use application::service::PhoneBlacklistService;
pub use application::service::MailMessageScheduleService;
pub use application::service::MailScheduledMessageService;
pub use application::service::SmsService;
pub use application::service::SmsTemplateService;
pub use application::service::SmsTrackerService;

// Re-exports - Validation
pub use application::validator::{ValidationError, ValidationResult};

use std::sync::Arc;
use axum::Router;
use sqlx::PgPool;

// <<< CUSTOM
use crate::application::service::{
    ActivityWriteService, AliasWriteService, AttachmentWriteService, ChannelMemberWriteService,
    ChannelQueryService, ChannelWriteService, FollowerWriteService, GuestWriteService,
    MailBlacklistWriteService, MailQueueWriteService, MessageEditService, MessageQueryService,
    MessageWriteService, PhoneBlacklistWriteService, PhoneBookPort, PhoneBookSlot,
    PhoneValidationService, PresenceWriteService, ReactionWriteService, RecipientQueryService,
    ScheduleWriteService, SmsStatusWebhookService, SmsWriteService, StaticThreadAccess,
    ThreadAclSlot, ThreadAccessResolver, ThreadChatterService, TypingService,
};

/// The realtime surface (SSE session proofs; tailer + stream land in Stage 4).
/// Declared inside the CUSTOM block so regeneration preserves it.
pub mod realtime;
// END CUSTOM
/// Messaging module configuration
///
/// Use the builder pattern to configure and register this module:
///
/// ```text
/// let messaging = MessagingModule::builder()
///     .with_database(pool.clone())
///     .build()?;
///
/// // Unguarded full CRUD (trusted/admin); compose a guarded router for production.
/// let router = messaging.all_crud_routes();
/// ```
pub struct MessagingModule {
    pub(crate) mail_activity_service: Arc<MailActivityService>,
    pub(crate) mail_activity_type_service: Arc<MailActivityTypeService>,
    pub(crate) mail_activity_plan_service: Arc<MailActivityPlanService>,
    pub(crate) mail_activity_plan_template_service: Arc<MailActivityPlanTemplateService>,
    pub(crate) mail_alias_domain_service: Arc<MailAliasDomainService>,
    pub(crate) mail_alias_service: Arc<MailAliasService>,
    pub(crate) mail_attachment_service: Arc<MailAttachmentService>,
    pub(crate) mail_message_attachment_service: Arc<MailMessageAttachmentService>,
    pub(crate) mail_message_star_service: Arc<MailMessageStarService>,
    pub(crate) mail_message_service: Arc<MailMessageService>,
    pub(crate) mail_service: Arc<MailService>,
    pub(crate) mail_notification_service: Arc<MailNotificationService>,
    pub(crate) mail_message_subtype_service: Arc<MailMessageSubtypeService>,
    pub(crate) mail_message_reaction_service: Arc<MailMessageReactionService>,
    pub(crate) mail_followers_service: Arc<MailFollowersService>,
    pub(crate) mail_presence_service: Arc<MailPresenceService>,
    pub(crate) mail_blacklist_service: Arc<MailBlacklistService>,
    pub(crate) mail_tracking_value_service: Arc<MailTrackingValueService>,
    pub(crate) discuss_channel_service: Arc<DiscussChannelService>,
    pub(crate) discuss_channel_member_service: Arc<DiscussChannelMemberService>,
    pub(crate) mail_guest_service: Arc<MailGuestService>,
    pub(crate) mail_server_service: Arc<MailServerService>,
    pub(crate) fetchmail_server_service: Arc<FetchmailServerService>,
    pub(crate) mail_gateway_allowed_service: Arc<MailGatewayAllowedService>,
    pub(crate) phone_blacklist_service: Arc<PhoneBlacklistService>,
    pub(crate) mail_message_schedule_service: Arc<MailMessageScheduleService>,
    pub(crate) mail_scheduled_message_service: Arc<MailScheduledMessageService>,
    pub(crate) sms_service: Arc<SmsService>,
    pub(crate) sms_template_service: Arc<SmsTemplateService>,
    pub(crate) sms_tracker_service: Arc<SmsTrackerService>,
    // <<< CUSTOM FIELDS
    /// Hand-authored write services (the validated write surface — generic CRUD
    /// bypasses domain invariants by design). Each owns one Odoo-ported behavior:
    /// message_post notify pump (MAIL-M16/B), follower policies (MAIL-M10),
    /// activity chaining (MAIL-M17), the sms queue drainer (SM-M1/2, MMB-4),
    /// the mail queue drainer (MAIL-M2, MMB-4), alias resolution (MAIL-M33).
    pub message_write_service: Arc<MessageWriteService>,
    pub follower_write_service: Arc<FollowerWriteService>,
    pub activity_write_service: Arc<ActivityWriteService>,
    pub sms_write_service: Arc<SmsWriteService>,
    pub mail_queue_write_service: Arc<MailQueueWriteService>,
    pub alias_write_service: Arc<AliasWriteService>,

    /// The swappable MAIL-B1 resolver slot — install a host's thread ACL with
    /// [`MessagingModule::set_thread_acl`]. Defaults to DenyHostDocs.
    pub thread_acl: ThreadAclSlot,
    /// The host-facing chatter edge (post/read/follow/schedule, all gated).
    pub thread_chatter_service: Arc<ThreadChatterService>,
    /// Increment-2 write services (user-owned; see each file's header).
    pub channel_write_service: Arc<ChannelWriteService>,
    pub channel_member_write_service: Arc<ChannelMemberWriteService>,
    pub typing_service: Arc<TypingService>,
    pub reaction_write_service: Arc<ReactionWriteService>,
    pub message_edit_service: Arc<MessageEditService>,
    pub guest_write_service: Arc<GuestWriteService>,
    pub presence_write_service: Arc<PresenceWriteService>,
    pub schedule_write_service: Arc<ScheduleWriteService>,
    pub attachment_write_service: Arc<AttachmentWriteService>,
    /// Increment-2 query services (MAIL-B1 procedural gates live here).
    pub message_query_service: Arc<MessageQueryService>,
    pub channel_query_service: Arc<ChannelQueryService>,
    pub recipient_query_service: Arc<RecipientQueryService>,
    /// The shared pool (route composers build one-off services — e.g. the
    /// sms webhook — without re-threading a pool through every caller).
    pub pool: sqlx::PgPool,
    /// The replica-local realtime fan-out (SSE ring + connection caps). The
    /// host app spawns the outbox tailer onto THIS same instance — the
    /// identity between the two is what makes post→stream delivery work.
    pub realtime_registry: std::sync::Arc<realtime::RealtimeRegistry>,
    /// The phone-validation opener (user-owned): the blacklist verbs and the
    /// live sanitized-for verb over the swappable phone-book slot.
    pub phone_blacklist_write_service: Arc<PhoneBlacklistWriteService>,
    /// The email-blacklist verbs (user-owned): the sanctioned write path for
    /// mail_blacklists — add (recording the opt-out reason when supplied),
    /// archive-only remove, point/batch membership checks.
    pub mail_blacklist_write_service: Arc<MailBlacklistWriteService>,
    /// The swappable recipient-candidate slot — install a host's phone book
    /// with [`MessagingModule::set_phone_book`]. Defaults to the refusing
    /// (fail-closed) book.
    pub phone_book: PhoneBookSlot,
    /// The live read-side verb: candidates → E.164 → blacklist standing.
    pub phone_validation_service: Arc<PhoneValidationService>,
    // END CUSTOM
}

impl MessagingModule {
    /// Create a new module builder
    pub fn builder() -> MessagingModuleBuilder {
        MessagingModuleBuilder::new()
    }

    /// Mount ALL generated CRUD endpoints (12 per entity) with NO domain
    /// validation — the fully **unguarded** surface. A well-formed request can
    /// create invalid rows or soft-delete a referenced master out from under its
    /// dependents. Prefer a guarded composition (read + validated writes) for any
    /// real deployment; use this only in trusted/admin/seeding contexts.
    pub fn all_crud_routes(&self) -> Router {
        use presentation::http::{
            create_mail_activity_routes,
            create_mail_activity_type_read_routes,
            create_mail_activity_plan_routes,
            create_mail_activity_plan_template_routes,
            create_mail_alias_domain_routes,
            create_mail_alias_routes,
            create_mail_attachment_routes,
            create_mail_message_attachment_routes,
            create_mail_message_star_routes,
            create_mail_message_read_routes,
            create_mail_read_routes,
            create_mail_notification_read_routes,
            create_mail_message_subtype_routes,
            create_mail_message_reaction_routes,
            create_mail_followers_routes,
            create_mail_presence_read_routes,
            create_mail_blacklist_routes,
            create_mail_tracking_value_routes,
            create_discuss_channel_read_routes,
            create_discuss_channel_member_routes,
            create_mail_guest_routes,
            create_mail_server_routes,
            create_fetchmail_server_read_routes,
            create_mail_gateway_allowed_routes,
            create_phone_blacklist_routes,
            create_mail_message_schedule_routes,
            create_mail_scheduled_message_routes,
            create_sms_read_routes,
            create_sms_template_routes,
            create_sms_tracker_read_routes,
        };

        Router::new()
            .merge(create_mail_activity_routes(self.mail_activity_service.clone()))
            // MailActivityType: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_mail_activity_type_read_routes(self.mail_activity_type_service.clone()))
            .merge(create_mail_activity_plan_routes(self.mail_activity_plan_service.clone()))
            .merge(create_mail_activity_plan_template_routes(self.mail_activity_plan_template_service.clone()))
            .merge(create_mail_alias_domain_routes(self.mail_alias_domain_service.clone()))
            .merge(create_mail_alias_routes(self.mail_alias_service.clone()))
            .merge(create_mail_attachment_routes(self.mail_attachment_service.clone()))
            .merge(create_mail_message_attachment_routes(self.mail_message_attachment_service.clone()))
            .merge(create_mail_message_star_routes(self.mail_message_star_service.clone()))
            // MailMessage: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_mail_message_read_routes(self.mail_message_service.clone()))
            // Mail: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_mail_read_routes(self.mail_service.clone()))
            // MailNotification: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_mail_notification_read_routes(self.mail_notification_service.clone()))
            .merge(create_mail_message_subtype_routes(self.mail_message_subtype_service.clone()))
            .merge(create_mail_message_reaction_routes(self.mail_message_reaction_service.clone()))
            .merge(create_mail_followers_routes(self.mail_followers_service.clone()))
            // MailPresence: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_mail_presence_read_routes(self.mail_presence_service.clone()))
            .merge(create_mail_blacklist_routes(self.mail_blacklist_service.clone()))
            .merge(create_mail_tracking_value_routes(self.mail_tracking_value_service.clone()))
            // DiscussChannel: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_discuss_channel_read_routes(self.discuss_channel_service.clone()))
            .merge(create_discuss_channel_member_routes(self.discuss_channel_member_service.clone()))
            .merge(create_mail_guest_routes(self.mail_guest_service.clone()))
            .merge(create_mail_server_routes(self.mail_server_service.clone()))
            // FetchmailServer: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_fetchmail_server_read_routes(self.fetchmail_server_service.clone()))
            .merge(create_mail_gateway_allowed_routes(self.mail_gateway_allowed_service.clone()))
            .merge(create_phone_blacklist_routes(self.phone_blacklist_service.clone()))
            .merge(create_mail_message_schedule_routes(self.mail_message_schedule_service.clone()))
            .merge(create_mail_scheduled_message_routes(self.mail_scheduled_message_service.clone()))
            // Sms: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_sms_read_routes(self.sms_service.clone()))
            .merge(create_sms_template_routes(self.sms_template_service.clone()))
            // SmsTracker: hand_set lifecycle — the state field moves only through the
            // module's validated verbs; generic writes cannot reach it, so only the
            // read surface mounts here.
            .merge(create_sms_tracker_read_routes(self.sms_tracker_service.clone()))
    }

    /// Deprecated alias for [`Self::all_crud_routes`]. `routes()` reads like
    /// "the routes" but mounts UNVALIDATED generic CRUD on every entity — a naive
    /// mount exposes unguarded writes. Compose a guarded router (read + validated
    /// writes) for production, or call `all_crud_routes()` to opt into the full
    /// unguarded surface explicitly.
    #[deprecated(note = "mounts unvalidated generic CRUD; prefer readonly_routes() + validated writes, or all_crud_routes() for the full/unguarded surface")]
    pub fn routes(&self) -> Router {
        self.all_crud_routes()
    }

    /// Read-only routes for every entity (GET endpoints only) — the safe base.
    ///
    /// Generic mutation can't reach here, so this surface cannot bypass a
    /// validated write service's invariants. Use this as the production base and
    /// merge validated write routes (or a write service's HTTP layer) onto it.
    pub fn readonly_routes(&self) -> Router {
        use presentation::http::{
            create_mail_activity_read_routes,
            create_mail_activity_type_read_routes,
            create_mail_activity_plan_read_routes,
            create_mail_activity_plan_template_read_routes,
            create_mail_alias_domain_read_routes,
            create_mail_alias_read_routes,
            create_mail_attachment_read_routes,
            create_mail_message_attachment_read_routes,
            create_mail_message_star_read_routes,
            create_mail_message_read_routes,
            create_mail_read_routes,
            create_mail_notification_read_routes,
            create_mail_message_subtype_read_routes,
            create_mail_message_reaction_read_routes,
            create_mail_followers_read_routes,
            create_mail_presence_read_routes,
            create_mail_blacklist_read_routes,
            create_mail_tracking_value_read_routes,
            create_discuss_channel_read_routes,
            create_discuss_channel_member_read_routes,
            create_mail_guest_read_routes,
            create_mail_server_read_routes,
            create_fetchmail_server_read_routes,
            create_mail_gateway_allowed_read_routes,
            create_phone_blacklist_read_routes,
            create_mail_message_schedule_read_routes,
            create_mail_scheduled_message_read_routes,
            create_sms_read_routes,
            create_sms_template_read_routes,
            create_sms_tracker_read_routes,
        };

        Router::new()
            .merge(create_mail_activity_read_routes(self.mail_activity_service.clone()))
            .merge(create_mail_activity_type_read_routes(self.mail_activity_type_service.clone()))
            .merge(create_mail_activity_plan_read_routes(self.mail_activity_plan_service.clone()))
            .merge(create_mail_activity_plan_template_read_routes(self.mail_activity_plan_template_service.clone()))
            .merge(create_mail_alias_domain_read_routes(self.mail_alias_domain_service.clone()))
            .merge(create_mail_alias_read_routes(self.mail_alias_service.clone()))
            .merge(create_mail_attachment_read_routes(self.mail_attachment_service.clone()))
            .merge(create_mail_message_attachment_read_routes(self.mail_message_attachment_service.clone()))
            .merge(create_mail_message_star_read_routes(self.mail_message_star_service.clone()))
            .merge(create_mail_message_read_routes(self.mail_message_service.clone()))
            .merge(create_mail_read_routes(self.mail_service.clone()))
            .merge(create_mail_notification_read_routes(self.mail_notification_service.clone()))
            .merge(create_mail_message_subtype_read_routes(self.mail_message_subtype_service.clone()))
            .merge(create_mail_message_reaction_read_routes(self.mail_message_reaction_service.clone()))
            .merge(create_mail_followers_read_routes(self.mail_followers_service.clone()))
            .merge(create_mail_presence_read_routes(self.mail_presence_service.clone()))
            .merge(create_mail_blacklist_read_routes(self.mail_blacklist_service.clone()))
            .merge(create_mail_tracking_value_read_routes(self.mail_tracking_value_service.clone()))
            .merge(create_discuss_channel_read_routes(self.discuss_channel_service.clone()))
            .merge(create_discuss_channel_member_read_routes(self.discuss_channel_member_service.clone()))
            .merge(create_mail_guest_read_routes(self.mail_guest_service.clone()))
            .merge(create_mail_server_read_routes(self.mail_server_service.clone()))
            .merge(create_fetchmail_server_read_routes(self.fetchmail_server_service.clone()))
            .merge(create_mail_gateway_allowed_read_routes(self.mail_gateway_allowed_service.clone()))
            .merge(create_phone_blacklist_read_routes(self.phone_blacklist_service.clone()))
            .merge(create_mail_message_schedule_read_routes(self.mail_message_schedule_service.clone()))
            .merge(create_mail_scheduled_message_read_routes(self.mail_scheduled_message_service.clone()))
            .merge(create_sms_read_routes(self.sms_service.clone()))
            .merge(create_sms_template_read_routes(self.sms_template_service.clone()))
            .merge(create_sms_tracker_read_routes(self.sms_tracker_service.clone()))
    }

    // <<< CUSTOM METHODS
    /// Register the host's thread ACL (MAIL-B1). Installs into the shared
    /// slot — every gated service (chatter facade, queries, schedules) sees
    /// the resolver from the next call. Idempotent (last install wins).
    pub fn set_thread_acl(&self, resolver: std::sync::Arc<dyn ThreadAccessResolver>) {
        self.thread_acl.install(resolver);
    }

    /// Register the host's phone book — the recipient-candidate walk for
    /// `PhoneValidationService::sanitized_for` over another module's
    /// records. Installs into the shared slot; until called, every lookup
    /// refuses (fail-closed, never a silent empty). Idempotent (last
    /// install wins).
    pub fn set_phone_book(&self, book: std::sync::Arc<dyn PhoneBookPort>) {
        self.phone_book.install(book);
    }

    /// Convenience: open a static set of document models to every
    /// authenticated partner — the config-driven resolver an app service can
    /// build without writing its own trait impl.
    pub fn set_static_thread_access(&self, open_models: Vec<String>) {
        self.thread_acl.install(std::sync::Arc::new(StaticThreadAccess { open_models }));
    }

    /// The shared pool (for app-level wiring: jobs, relay, one-off services).
    pub fn db_pool(&self) -> sqlx::PgPool {
        self.pool.clone()
    }

    // Route composers (increment 2 — the guarded wire surface). Kept inside
    // the CUSTOM METHODS block so regeneration preserves them.
    /// The guarded discuss/channel group: create, chat dedup, member verbs,
    /// typing, search, reactions, edits, stars. Mount behind app user auth +
    /// the `guest_context` middleware. Search is throttled (30/60s).
    pub fn discuss_routes(self: &Arc<Self>) -> Router {
        presentation::http::channel_routes::composer().with_state(self.clone())
    }

    /// The guarded thread/chatter group: fetches, counters, recipients,
    /// post/follow/schedule. Mount behind app user auth + `guest_context`.
    /// Recipient suggestions are throttled (30/60s).
    pub fn messaging_routes(self: &Arc<Self>) -> Router {
        presentation::http::thread_routes::composer().with_state(self.clone())
    }

    /// Guest self-service (mint + rename) — public surface behind
    /// `guest_context` only.
    pub fn guest_routes(self: &Arc<Self>) -> Router {
        presentation::http::guest_routes::composer().with_state(self.clone())
    }

    /// Presence (manual im_status + proof-gated bus liveness). Requires the
    /// `realtime::SessionSecret` router extension for the proof check.
    pub fn presence_routes(self: &Arc<Self>) -> Router {
        presentation::http::presence_routes::composer().with_state(self.clone())
    }

    /// Attachment register/attach/detach/token verbs (owner-gated,
    /// throttled 30/60s).
    pub fn attachment_routes(self: &Arc<Self>) -> Router {
        presentation::http::attachment_routes::composer().with_state(self.clone())
    }

    /// The public bootstrap — anonymous/guest entry to a public channel.
    /// Throttled hard (10/60s): unauthenticated by construction.
    pub fn public_routes(self: &Arc<Self>) -> Router {
        presentation::http::public_routes::composer().with_state(self.clone())
    }

    /// The sms provider callback (`POST /sms/status`, scheme `hmac_raw_body`
    /// per ADR-0021). BARE mount — no auth middleware; the HMAC IS the auth.
    /// Reads `SMS_WEBHOOK_SECRET` (env-var reference, ADR-0024); when unset
    /// the route answers 503 — fail closed, never forge-able with an empty key.
    /// Throttled 120/60s.
    pub fn webhook_routes(self: &Arc<Self>) -> Router {
        presentation::http::webhook_routes::composer().with_state(self.clone())
    }

    /// The inbound email webhook (`POST /mail/inbound/:server_id`, MAIL-M27
    /// webhook mode). BARE mount — no auth middleware; the per-server bearer
    /// token IS the auth (SHA-256 consteq against the stored hash; unknown
    /// server / inactive server / bad token all answer the same 401 — no
    /// oracle). Throttled 120/60s.
    pub fn inbound_routes(self: &Arc<Self>) -> Router {
        presentation::http::inbound_routes::composer().with_state(self.clone())
    }

    /// The realtime SSE stream (`GET /mail/realtime/stream`). Requires the
    /// `guest_context` middleware AND the `realtime::SessionSecret` router
    /// extension — the same contract as the presence group. The host app
    /// also spawns [`realtime::tailer::spawn`] onto
    /// [`Self::realtime_registry`] or the stream serves only its keepalives.
    pub fn realtime_routes(self: &Arc<Self>) -> Router {
        realtime::sse::composer().with_state(self.clone())
    }
    // END CUSTOM
}

/// Builder for MessagingModule
pub struct MessagingModuleBuilder {
    db_pool: Option<PgPool>,
}

impl MessagingModuleBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            db_pool: None,
        }
    }

    /// Set the database connection pool
    pub fn with_database(mut self, pool: PgPool) -> Self {
        self.db_pool = Some(pool);
        self
    }

    // <<< CUSTOM - custom builder methods
    // END CUSTOM

    /// Build the module with configured dependencies
    pub fn build(self) -> anyhow::Result<MessagingModule> {
        let db_pool = self.db_pool
            .ok_or_else(|| anyhow::anyhow!("Database pool not configured"))?;

        // MailActivity service
        let mail_activity_repository = Arc::new(MailActivityRepository::new(db_pool.clone()));
        let mail_activity_service = Arc::new(MailActivityService::with_repository(mail_activity_repository.clone()));

        // MailActivityType service
        let mail_activity_type_repository = Arc::new(MailActivityTypeRepository::new(db_pool.clone()));
        let mail_activity_type_service = Arc::new(MailActivityTypeService::with_repository(mail_activity_type_repository.clone()));

        // MailActivityPlan service
        let mail_activity_plan_repository = Arc::new(MailActivityPlanRepository::new(db_pool.clone()));
        let mail_activity_plan_service = Arc::new(MailActivityPlanService::with_repository(mail_activity_plan_repository.clone()));

        // MailActivityPlanTemplate service
        let mail_activity_plan_template_repository = Arc::new(MailActivityPlanTemplateRepository::new(db_pool.clone()));
        let mail_activity_plan_template_service = Arc::new(MailActivityPlanTemplateService::with_repository(mail_activity_plan_template_repository.clone()));

        // MailAliasDomain service
        let mail_alias_domain_repository = Arc::new(MailAliasDomainRepository::new(db_pool.clone()));
        let mail_alias_domain_service = Arc::new(MailAliasDomainService::with_repository(mail_alias_domain_repository.clone()));

        // MailAlias service
        let mail_alias_repository = Arc::new(MailAliasRepository::new(db_pool.clone()));
        let mail_alias_service = Arc::new(MailAliasService::with_repository(mail_alias_repository.clone()));

        // MailAttachment service
        let mail_attachment_repository = Arc::new(MailAttachmentRepository::new(db_pool.clone()));
        let mail_attachment_service = Arc::new(MailAttachmentService::with_repository(mail_attachment_repository.clone()));

        // MailMessageAttachment service
        let mail_message_attachment_repository = Arc::new(MailMessageAttachmentRepository::new(db_pool.clone()));
        let mail_message_attachment_service = Arc::new(MailMessageAttachmentService::with_repository(mail_message_attachment_repository.clone()));

        // MailMessageStar service
        let mail_message_star_repository = Arc::new(MailMessageStarRepository::new(db_pool.clone()));
        let mail_message_star_service = Arc::new(MailMessageStarService::with_repository(mail_message_star_repository.clone()));

        // MailMessage service
        let mail_message_repository = Arc::new(MailMessageRepository::new(db_pool.clone()));
        let mail_message_service = Arc::new(MailMessageService::with_repository(mail_message_repository.clone()));

        // Mail service
        let mail_repository = Arc::new(MailRepository::new(db_pool.clone()));
        let mail_service = Arc::new(MailService::with_repository(mail_repository.clone()));

        // MailNotification service
        let mail_notification_repository = Arc::new(MailNotificationRepository::new(db_pool.clone()));
        let mail_notification_service = Arc::new(MailNotificationService::with_repository(mail_notification_repository.clone()));

        // MailMessageSubtype service
        let mail_message_subtype_repository = Arc::new(MailMessageSubtypeRepository::new(db_pool.clone()));
        let mail_message_subtype_service = Arc::new(MailMessageSubtypeService::with_repository(mail_message_subtype_repository.clone()));

        // MailMessageReaction service
        let mail_message_reaction_repository = Arc::new(MailMessageReactionRepository::new(db_pool.clone()));
        let mail_message_reaction_service = Arc::new(MailMessageReactionService::with_repository(mail_message_reaction_repository.clone()));

        // MailFollowers service
        let mail_followers_repository = Arc::new(MailFollowersRepository::new(db_pool.clone()));
        let mail_followers_service = Arc::new(MailFollowersService::with_repository(mail_followers_repository.clone()));

        // MailPresence service
        let mail_presence_repository = Arc::new(MailPresenceRepository::new(db_pool.clone()));
        let mail_presence_service = Arc::new(MailPresenceService::with_repository(mail_presence_repository.clone()));

        // MailBlacklist service
        let mail_blacklist_repository = Arc::new(MailBlacklistRepository::new(db_pool.clone()));
        let mail_blacklist_service = Arc::new(MailBlacklistService::with_repository(mail_blacklist_repository.clone()));

        // MailTrackingValue service
        let mail_tracking_value_repository = Arc::new(MailTrackingValueRepository::new(db_pool.clone()));
        let mail_tracking_value_service = Arc::new(MailTrackingValueService::with_repository(mail_tracking_value_repository.clone()));

        // DiscussChannel service
        let discuss_channel_repository = Arc::new(DiscussChannelRepository::new(db_pool.clone()));
        let discuss_channel_service = Arc::new(DiscussChannelService::with_repository(discuss_channel_repository.clone()));

        // DiscussChannelMember service
        let discuss_channel_member_repository = Arc::new(DiscussChannelMemberRepository::new(db_pool.clone()));
        let discuss_channel_member_service = Arc::new(DiscussChannelMemberService::with_repository(discuss_channel_member_repository.clone()));

        // MailGuest service
        let mail_guest_repository = Arc::new(MailGuestRepository::new(db_pool.clone()));
        let mail_guest_service = Arc::new(MailGuestService::with_repository(mail_guest_repository.clone()));

        // MailServer service
        let mail_server_repository = Arc::new(MailServerRepository::new(db_pool.clone()));
        let mail_server_service = Arc::new(MailServerService::with_repository(mail_server_repository.clone()));

        // FetchmailServer service
        let fetchmail_server_repository = Arc::new(FetchmailServerRepository::new(db_pool.clone()));
        let fetchmail_server_service = Arc::new(FetchmailServerService::with_repository(fetchmail_server_repository.clone()));

        // MailGatewayAllowed service
        let mail_gateway_allowed_repository = Arc::new(MailGatewayAllowedRepository::new(db_pool.clone()));
        let mail_gateway_allowed_service = Arc::new(MailGatewayAllowedService::with_repository(mail_gateway_allowed_repository.clone()));

        // PhoneBlacklist service
        let phone_blacklist_repository = Arc::new(PhoneBlacklistRepository::new(db_pool.clone()));
        let phone_blacklist_service = Arc::new(PhoneBlacklistService::with_repository(phone_blacklist_repository.clone()));

        // MailMessageSchedule service
        let mail_message_schedule_repository = Arc::new(MailMessageScheduleRepository::new(db_pool.clone()));
        let mail_message_schedule_service = Arc::new(MailMessageScheduleService::with_repository(mail_message_schedule_repository.clone()));

        // MailScheduledMessage service
        let mail_scheduled_message_repository = Arc::new(MailScheduledMessageRepository::new(db_pool.clone()));
        let mail_scheduled_message_service = Arc::new(MailScheduledMessageService::with_repository(mail_scheduled_message_repository.clone()));

        // Sms service
        let sms_repository = Arc::new(SmsRepository::new(db_pool.clone()));
        let sms_service = Arc::new(SmsService::with_repository(sms_repository.clone()));

        // SmsTemplate service
        let sms_template_repository = Arc::new(SmsTemplateRepository::new(db_pool.clone()));
        let sms_template_service = Arc::new(SmsTemplateService::with_repository(sms_template_repository.clone()));

        // SmsTracker service
        let sms_tracker_repository = Arc::new(SmsTrackerRepository::new(db_pool.clone()));
        let sms_tracker_service = Arc::new(SmsTrackerService::with_repository(sms_tracker_repository.clone()));

        // <<< CUSTOM
        let message_write_service = Arc::new(MessageWriteService::new(db_pool.clone()));
        let follower_write_service = Arc::new(FollowerWriteService::new(db_pool.clone()));
        let activity_write_service = Arc::new(ActivityWriteService::new(db_pool.clone()));
        let sms_write_service = Arc::new(SmsWriteService::new(db_pool.clone()));
        let mail_queue_write_service = Arc::new(MailQueueWriteService::new(db_pool.clone()));
        let alias_write_service = Arc::new(AliasWriteService::new(db_pool.clone()));

        // The shared MAIL-B1 slot (default DenyHostDocs — hosts install via
        // set_thread_acl post-build). Every gated service resolves through it.
        let thread_acl = ThreadAclSlot::default();
        let acl: Arc<dyn ThreadAccessResolver> = Arc::new(thread_acl.clone());
        let thread_chatter_service =
            Arc::new(ThreadChatterService::new(db_pool.clone(), Arc::clone(&acl)));
        let schedule_write_service =
            Arc::new(ScheduleWriteService::new(db_pool.clone(), Arc::clone(&acl)));
        let message_query_service =
            Arc::new(MessageQueryService::new(db_pool.clone(), Arc::clone(&acl)));
        let recipient_query_service =
            Arc::new(RecipientQueryService::new(db_pool.clone(), Arc::clone(&acl)));
        let channel_write_service = Arc::new(ChannelWriteService::new(db_pool.clone()));
        let channel_member_write_service =
            Arc::new(ChannelMemberWriteService::new(db_pool.clone()));
        let channel_query_service = Arc::new(ChannelQueryService::new(db_pool.clone()));
        let typing_service = Arc::new(TypingService::new(db_pool.clone()));
        let reaction_write_service = Arc::new(ReactionWriteService::new(db_pool.clone()));
        let message_edit_service = Arc::new(MessageEditService::new(db_pool.clone()));
        let guest_write_service = Arc::new(GuestWriteService::new(db_pool.clone()));
        let presence_write_service = Arc::new(PresenceWriteService::new(db_pool.clone()));
        let attachment_write_service = Arc::new(AttachmentWriteService::new(db_pool.clone()));

        // The replica-local SSE fan-out point (Stage 4). One per process;
        // the host app's tailer publishes into it, the stream route reads.
        let realtime_registry = std::sync::Arc::new(realtime::RealtimeRegistry::new());

        // The phone-validation opener: the blacklist verbs + the live
        // sanitized-for verb over the fail-closed phone-book slot (hosts
        // install a real book via set_phone_book post-build).
        let phone_blacklist_write_service =
            Arc::new(PhoneBlacklistWriteService::new(db_pool.clone()));
        // The email-blacklist verbs: add (recording opt_out_reason_id when
        // supplied), archive-only remove, membership checks.
        let mail_blacklist_write_service =
            Arc::new(MailBlacklistWriteService::new(db_pool.clone()));
        let phone_book = PhoneBookSlot::default();
        let phone_validation_service = Arc::new(PhoneValidationService::new(
            db_pool.clone(),
            phone_book.clone(),
            phone_blacklist_write_service.clone(),
        ));
        // END CUSTOM

        Ok(MessagingModule {
            mail_activity_service,
            mail_activity_type_service,
            mail_activity_plan_service,
            mail_activity_plan_template_service,
            mail_alias_domain_service,
            mail_alias_service,
            mail_attachment_service,
            mail_message_attachment_service,
            mail_message_star_service,
            mail_message_service,
            mail_service,
            mail_notification_service,
            mail_message_subtype_service,
            mail_message_reaction_service,
            mail_followers_service,
            mail_presence_service,
            mail_blacklist_service,
            mail_tracking_value_service,
            discuss_channel_service,
            discuss_channel_member_service,
            mail_guest_service,
            mail_server_service,
            fetchmail_server_service,
            mail_gateway_allowed_service,
            phone_blacklist_service,
            mail_message_schedule_service,
            mail_scheduled_message_service,
            sms_service,
            sms_template_service,
            sms_tracker_service,
            // <<< CUSTOM
            message_write_service,
            follower_write_service,
            activity_write_service,
            sms_write_service,
            mail_queue_write_service,
            alias_write_service,
            thread_acl,
            thread_chatter_service,
            channel_write_service,
            channel_member_write_service,
            typing_service,
            reaction_write_service,
            message_edit_service,
            guest_write_service,
            presence_write_service,
            schedule_write_service,
            attachment_write_service,
            message_query_service,
            channel_query_service,
            recipient_query_service,
            pool: db_pool.clone(),
            realtime_registry,
            phone_blacklist_write_service,
            mail_blacklist_write_service,
            phone_book,
            phone_validation_service,
            // END CUSTOM
        })
    }
}

impl Default for MessagingModuleBuilder {
    fn default() -> Self {
        Self::new()
    }
}