command_tower 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/messaging/gallery_controller.rb +35 -0
  3. data/app/controllers/command_tower/admin/messaging/gallery_test_sends_controller.rb +54 -0
  4. data/app/controllers/command_tower/me/inbox_controller.rb +19 -4
  5. data/app/controllers/command_tower/messaging/unsubscribe_controller.rb +43 -0
  6. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +36 -1
  7. data/app/errors/command_tower/errors/messaging/announcement_type_not_supported_error.rb +23 -0
  8. data/app/errors/command_tower/errors/messaging/gallery_test_send_failed_error.rb +26 -0
  9. data/app/errors/command_tower/errors/messaging/gallery_test_send_impersonating_error.rb +23 -0
  10. data/app/errors/command_tower/errors/messaging/gallery_test_send_rate_limit_error.rb +25 -0
  11. data/app/errors/command_tower/errors/messaging/unsubscribe_rate_limit_error.rb +25 -0
  12. data/app/jobs/command_tower/messaging/communications/produce_recipient_job.rb +2 -2
  13. data/app/mailers/command_tower/messaging/channel_mailer.rb +2 -0
  14. data/app/models/command_tower/messaging/communication.rb +10 -0
  15. data/app/serializers/command_tower/serializers/admin/messaging/gallery_serializer.rb +67 -0
  16. data/app/services/command_tower/email_theme/resolver.rb +13 -12
  17. data/app/services/command_tower/messaging/accept/coordinator.rb +57 -4
  18. data/app/services/command_tower/messaging/accept/persister.rb +3 -0
  19. data/app/services/command_tower/messaging/accept/request_normalizer.rb +9 -4
  20. data/app/services/command_tower/messaging/accept/resolve_communication_slots.rb +114 -0
  21. data/app/services/command_tower/messaging/announcement_definition.rb +88 -0
  22. data/app/services/command_tower/messaging/contract/inbox.rb +65 -0
  23. data/app/services/command_tower/messaging/contract/mappers/communication_mapper.rb +9 -0
  24. data/app/services/command_tower/messaging/contract/requests/mark_viewed_for_communication.rb +21 -0
  25. data/app/services/command_tower/messaging/contract/requests/viewed_for_communication.rb +21 -0
  26. data/app/services/command_tower/messaging/contract/results/communication_result.rb +3 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_view_mark.rb +18 -0
  28. data/app/services/command_tower/messaging/definitions/document_builder.rb +157 -0
  29. data/app/services/command_tower/messaging/definitions/render_context.rb +18 -0
  30. data/app/services/command_tower/messaging/inbox/item_result.rb +5 -1
  31. data/app/services/command_tower/messaging/inbox/mutator.rb +17 -0
  32. data/app/services/command_tower/messaging/inbox/reader.rb +12 -0
  33. data/app/services/command_tower/messaging/inbox/scope.rb +8 -0
  34. data/app/services/command_tower/messaging/inbox.rb +8 -0
  35. data/app/services/command_tower/messaging/message_definition/metadata.rb +35 -0
  36. data/app/services/command_tower/messaging/message_definition.rb +151 -0
  37. data/app/services/command_tower/messaging/notification_types/declaration.rb +12 -1
  38. data/app/services/command_tower/messaging/notification_types/message_definition_checks.rb +143 -0
  39. data/app/services/command_tower/messaging/notification_types/registry.rb +2 -0
  40. data/app/services/command_tower/messaging/rendering/channel_renderer.rb +73 -6
  41. data/app/services/command_tower/messaging/rendering/compliance_footer.rb +80 -0
  42. data/app/services/command_tower/messaging/rendering/defined_email_renderer.rb +141 -0
  43. data/app/services/command_tower/messaging/rendering/inbox_document_renderer.rb +79 -4
  44. data/app/services/command_tower/messaging/rendering/rendered_payload.rb +13 -1
  45. data/app/services/command_tower/messaging/rendering/unsubscribe_headers.rb +51 -0
  46. data/app/services/command_tower/messaging/unsubscribe/token_verifier.rb +26 -0
  47. data/app/services/command_tower/services/messaging/announcements/resolve_produce_arguments.rb +74 -0
  48. data/app/services/command_tower/services/messaging/communications/explicit_copy_rule.rb +50 -0
  49. data/app/services/command_tower/services/messaging/communications/produce.rb +18 -4
  50. data/app/services/command_tower/services/messaging/communications/produce_many.rb +20 -2
  51. data/app/services/command_tower/services/messaging/gallery/channel_failed.rb +31 -0
  52. data/app/services/command_tower/services/messaging/gallery/check_test_send_rate_limit.rb +47 -0
  53. data/app/services/command_tower/services/messaging/gallery/list_gallery_types.rb +44 -0
  54. data/app/services/command_tower/services/messaging/gallery/preview_builder.rb +122 -0
  55. data/app/services/command_tower/services/messaging/gallery/preview_channels.rb +51 -0
  56. data/app/services/command_tower/services/messaging/gallery/preview_checks.rb +85 -0
  57. data/app/services/command_tower/services/messaging/gallery/preview_email.rb +56 -0
  58. data/app/services/command_tower/services/messaging/gallery/render_gallery_preview.rb +85 -0
  59. data/app/services/command_tower/services/messaging/gallery/test_send.rb +55 -0
  60. data/app/services/command_tower/services/messaging/inbox.rb +36 -8
  61. data/app/services/command_tower/services/messaging/unsubscribe/check_rate_limit.rb +57 -0
  62. data/app/services/command_tower/services/messaging/unsubscribe/issue_token.rb +25 -0
  63. data/app/services/command_tower/services/messaging/unsubscribe/opt_out_of_email.rb +65 -0
  64. data/app/services/command_tower/services/messaging/unsubscribe/verify_token.rb +42 -0
  65. data/app/services/command_tower/services/users/record_last_known_time_zone.rb +40 -0
  66. data/app/workflows/command_tower/workflows/admin/messaging/create_announcement_workflow.rb +16 -3
  67. data/app/workflows/command_tower/workflows/admin/messaging/gallery/index_workflow.rb +29 -0
  68. data/app/workflows/command_tower/workflows/admin/messaging/gallery/show_workflow.rb +40 -0
  69. data/app/workflows/command_tower/workflows/admin/messaging/gallery/test_send_workflow.rb +103 -0
  70. data/app/workflows/command_tower/workflows/messaging/communications/produce_recipient_workflow.rb +2 -2
  71. data/app/workflows/command_tower/workflows/messaging/error_mapping.rb +8 -1
  72. data/app/workflows/command_tower/workflows/messaging/inbox.rb +30 -5
  73. data/app/workflows/command_tower/workflows/messaging/unsubscribe/one_click_workflow.rb +56 -0
  74. data/app/workflows/command_tower/workflows/messaging/unsubscribe/preferences_redirect_workflow.rb +24 -0
  75. data/config/routes.rb +9 -0
  76. data/db/migrate/20261124000001_add_message_definition_columns_to_messaging_communications.rb +9 -0
  77. data/docs/admin_workspace.md +2 -1
  78. data/docs/api_reference.md +78 -20
  79. data/docs/audit.md +9 -0
  80. data/docs/authentication_authorization_guide.md +1 -1
  81. data/docs/bootstrap/09-rbac.md +2 -0
  82. data/docs/bootstrap/11-auth-client-path.md +1 -1
  83. data/docs/cookie_authentication_guide.md +2 -0
  84. data/docs/extending.md +4 -0
  85. data/docs/messaging_integration_guide.md +40 -15
  86. data/docs/principal_capabilities.md +2 -0
  87. data/docs/ui.md +64 -2
  88. data/docs/upgrades/0.23.0.md +64 -0
  89. data/docs/upgrades/README.md +1 -0
  90. data/lib/command_tower/authorization/default.yml +8 -0
  91. data/lib/command_tower/configuration/messaging/compliance.rb +47 -0
  92. data/lib/command_tower/configuration/messaging/config.rb +25 -0
  93. data/lib/command_tower/configuration/registry/admin_workspace/config.rb +9 -0
  94. data/lib/command_tower/configuration/registry/admin_workspace/tool_definition.rb +10 -1
  95. data/lib/command_tower/configuration/registry/audit/config.rb +38 -0
  96. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +2 -0
  97. data/lib/command_tower/current.rb +1 -0
  98. data/lib/command_tower/email_theme/default_ui_tokens.json +18 -0
  99. data/lib/command_tower/email_theme/palette.rb +75 -0
  100. data/lib/command_tower/email_theme/token_file.rb +81 -0
  101. data/lib/command_tower/engine.rb +7 -0
  102. data/lib/command_tower/execution.rb +2 -1
  103. data/lib/command_tower/install/baseline.rb +1 -0
  104. data/lib/command_tower/rspec/message_definition.rb +125 -0
  105. data/lib/command_tower/ui/document.rb +18 -4
  106. data/lib/command_tower/ui/email/renderer/text_nodes.rb +2 -1
  107. data/lib/command_tower/ui/email/renderer.rb +17 -5
  108. data/lib/command_tower/ui/email/text_part.rb +53 -0
  109. data/lib/command_tower/ui/fragments/markdown.rb +121 -0
  110. data/lib/command_tower/ui/markdown_subset/chunker.rb +91 -0
  111. data/lib/command_tower/ui/markdown_subset/inline.rb +86 -0
  112. data/lib/command_tower/ui/markdown_subset/segment.rb +15 -0
  113. data/lib/command_tower/ui/markdown_subset/walker.rb +129 -0
  114. data/lib/command_tower/ui/nodes/instant.rb +3 -0
  115. data/lib/command_tower/ui/redaction.rb +44 -0
  116. data/lib/command_tower/ui/required_facts/matchers/text.rb +22 -0
  117. data/lib/command_tower/ui/required_facts/matchers/time.rb +37 -0
  118. data/lib/command_tower/ui/required_facts/verdict.rb +54 -0
  119. data/lib/command_tower/ui/text_derivation.rb +18 -17
  120. data/lib/command_tower/ui/time_formatter.rb +5 -3
  121. data/lib/command_tower/ui.rb +6 -0
  122. data/lib/command_tower/version.rb +1 -1
  123. data/lib/command_tower.rb +2 -0
  124. metadata +78 -2
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Accept
6
+ # Resolves what Accept stores for a definition-backed type: the channel slots, the stored
7
+ # title and body, the render zone and the metadata version. Pure apart from one user lookup
8
+ # for the zone. It never raises for an expected failure and never reads `strict_definitions`:
9
+ # it returns a {Resolution} and the caller decides whether a failure fails the request or is
10
+ # logged and degraded. Failures carry codes and attribute names only, never metadata values.
11
+ class ResolveCommunicationSlots
12
+ FAILURE_METADATA_SCHEMA = "metadata_schema_violation"
13
+ FAILURE_SLOTS = "slots_unbuildable"
14
+ FAILURE_HEADLINE = "headline_missing"
15
+
16
+ # `failure_code` is nil on success. `FAILURE_METADATA_SCHEMA` means the slots, title and
17
+ # body are still usable (the request may degrade); any other code means they are not.
18
+ Resolution = Data.define(
19
+ :slots, :title, :body, :render_zone, :metadata_version, :failure_code, :schema_errors
20
+ ) do
21
+ def success?
22
+ failure_code.nil?
23
+ end
24
+
25
+ def failure?
26
+ !success?
27
+ end
28
+
29
+ def degradable?
30
+ failure_code == FAILURE_METADATA_SCHEMA
31
+ end
32
+
33
+ # Attribute names and the code only.
34
+ def failure_message
35
+ detail = schema_errors.any? ? " (attributes: #{schema_errors.join(', ')})" : ""
36
+ "#{failure_code}#{detail}"
37
+ end
38
+ end
39
+
40
+ def self.call(...)
41
+ new(...).call
42
+ end
43
+
44
+ # @param definition [Class] a MessageDefinition subclass
45
+ def initialize(notification_type_key:, definition:, metadata:, recipient_id:)
46
+ @notification_type_key = notification_type_key.to_s
47
+ @definition = definition
48
+ @metadata = (metadata || {}).to_h.transform_keys(&:to_s)
49
+ @recipient_id = recipient_id
50
+ end
51
+
52
+ def call
53
+ @schema_errors = definition.metadata_schema.schema_errors(@metadata)
54
+ slots = build_slots
55
+ return resolution(FAILURE_SLOTS) if slots.nil?
56
+ return resolution(FAILURE_HEADLINE) if slots[:headline].to_s.strip.empty?
57
+
58
+ resolution(@schema_errors.any? ? FAILURE_METADATA_SCHEMA : nil, slots)
59
+ end
60
+
61
+ private
62
+
63
+ attr_reader :definition
64
+
65
+ # `slots` (symbol-keyed) is given only when title, body and slots are usable.
66
+ def resolution(failure_code, slots = nil)
67
+ Resolution.new(
68
+ slots: slots&.transform_keys(&:to_s),
69
+ title: slots && slots[:headline].to_s,
70
+ body: slots && (slots[:push_body].presence || slots[:headline].to_s),
71
+ render_zone:,
72
+ metadata_version: definition.metadata_version,
73
+ failure_code:,
74
+ schema_errors: @schema_errors
75
+ )
76
+ end
77
+
78
+ # nil when the definition's `slots` raised; the error is never surfaced (it may quote
79
+ # metadata).
80
+ def build_slots
81
+ Definitions::DocumentBuilder.slots(definition: definition.new, context:)
82
+ rescue StandardError
83
+ nil
84
+ end
85
+
86
+ def context
87
+ Definitions::RenderContext.new(
88
+ notification_type_key: @notification_type_key,
89
+ metadata: @metadata,
90
+ metadata_version: definition.metadata_version,
91
+ slots: nil,
92
+ render_zone:
93
+ )
94
+ end
95
+
96
+ # The recipient's last known zone when it is a TZInfo identifier, else the definition's
97
+ # default zone, else the platform UI default.
98
+ def render_zone
99
+ @render_zone ||= valid_zone(recipient_zone) ||
100
+ valid_zone(definition.default_zone) ||
101
+ CommandTower.config.ui.default_zone
102
+ end
103
+
104
+ def recipient_zone
105
+ User.where(id: @recipient_id).pick(:last_known_timezone)
106
+ end
107
+
108
+ def valid_zone(zone)
109
+ zone if zone.present? && TZInfo::Timezone.all_identifiers.include?(zone)
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ # The definition behind admin announcements (design D26). A host attaches it to a promotional
6
+ # notification type (`message: "CommandTower::Messaging::AnnouncementDefinition"`) and the admin
7
+ # announcement endpoint maps the admin's `title` and `body` into the metadata below.
8
+ #
9
+ # There is no fact block: documents validate with the `:default` profile, and the inbox and
10
+ # email composers are a `Header` (the title) over the `Markdown` fragment (the body).
11
+ class AnnouncementDefinition < MessageDefinition
12
+ TITLE_MAX = 200
13
+ BODY_MARKDOWN_MAX = 5000
14
+ PUSH_BODY_MAX = 178
15
+
16
+ class Metadata < CommandTower::Messaging::MessageDefinition::Metadata
17
+ attribute :title, :string
18
+ attribute :body_markdown, :string
19
+
20
+ validates :title, presence: true, length: { maximum: TITLE_MAX }
21
+ validates :body_markdown, presence: true, length: { maximum: BODY_MARKDOWN_MAX }
22
+ end
23
+
24
+ metadata_version 1
25
+ metadata_schema Metadata
26
+ promotional true
27
+ document_profile :default
28
+
29
+ fixture :default, metadata: {
30
+ "title" => "New classes this week",
31
+ "body_markdown" => "We added **three** classes.\n\n- Sunrise Stretch\n- Arms & Abs\n\n" \
32
+ "See the [schedule](/schedule) to book."
33
+ }
34
+
35
+ class << self
36
+ # Resolved when read so a host's `config.ui.default_zone` is honoured.
37
+ def default_zone(zone = nil)
38
+ return super if zone
39
+
40
+ super || CommandTower.config.ui.default_zone
41
+ end
42
+ end
43
+
44
+ def inbox(builder, metadata:)
45
+ compose(builder, metadata)
46
+ end
47
+
48
+ def email(builder, metadata:)
49
+ compose(builder, metadata)
50
+ end
51
+
52
+ def headline(metadata:)
53
+ metadata["title"]
54
+ end
55
+
56
+ def slots(metadata:, **)
57
+ title = metadata["title"].to_s
58
+ push = derived_text(metadata["body_markdown"]).presence || title
59
+ {
60
+ headline: title,
61
+ subject: title,
62
+ push_body: push,
63
+ pushover_message: push,
64
+ sms_body: "#{CommandTower.app_name_for_comms}: #{title}"
65
+ }
66
+ end
67
+
68
+ private
69
+
70
+ def compose(builder, metadata)
71
+ builder.card(surface: :raised) do |c|
72
+ c.fragment(CommandTower::UI::Fragments::Header, title: metadata["title"])
73
+ c.fragment(CommandTower::UI::Fragments::Markdown, source: metadata["body_markdown"])
74
+ end
75
+ end
76
+
77
+ # Plain text of the rendered markdown on one line, cut to the push/Pushover limit.
78
+ def derived_text(markdown)
79
+ return "" if markdown.blank?
80
+
81
+ scratch = CommandTower::UI::Builder.new
82
+ scratch.fragment(CommandTower::UI::Fragments::Markdown, source: markdown)
83
+ text = scratch.roots.map { |node| CommandTower::UI::TextDerivation.call(node) }.join(" ")
84
+ text.squish.truncate(PUSH_BODY_MAX, omission: "…")
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Contract
6
+ # Inbox view state keyed by communication. This contract emits no audit:
7
+ # a caller that mutates (mark_viewed_for_communication) must be a workflow
8
+ # that owns the audit decision.
9
+ module Inbox
10
+ class << self
11
+ # true/false for a live inbox item; nil when the communication is
12
+ # missing, not the recipient's, deleted, or not inbox-backed.
13
+ def viewed_for_communication?(request)
14
+ guarded("inbox.viewed_for_communication", request, Requests::ViewedForCommunication) do
15
+ CommandTower::Messaging::Inbox.viewed_for_communication(
16
+ recipient_id: request.recipient_id,
17
+ communication_id: request.communication_id
18
+ )
19
+ end
20
+ end
21
+
22
+ # Idempotent. Returns Results::InboxViewMark, or nil when the communication
23
+ # is missing, not the recipient's, deleted, or not inbox-backed.
24
+ def mark_viewed_for_communication(request)
25
+ guarded("inbox.mark_viewed_for_communication", request, Requests::MarkViewedForCommunication) do
26
+ item = CommandTower::Messaging::Inbox.mark_viewed_for_communication(
27
+ recipient_id: request.recipient_id,
28
+ communication_id: request.communication_id
29
+ )
30
+ item && view_mark(item)
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ def guarded(operation, request, expected_class, &)
37
+ ensure_request!(request, expected_class)
38
+ validate!(request)
39
+ Observability::OperationLogger.around(operation:, request:, &)
40
+ end
41
+
42
+ def view_mark(item)
43
+ Results::InboxViewMark.new(
44
+ communication_id: item.communication_id,
45
+ inbox_item_id: item.id,
46
+ viewed: !item.viewed_at.nil?,
47
+ newly_viewed: item.newly_viewed
48
+ ).freeze
49
+ end
50
+
51
+ def ensure_request!(request, expected_class)
52
+ return if request.is_a?(expected_class)
53
+
54
+ raise Contract::ValidationError, "expected #{expected_class}, got #{request.class}"
55
+ end
56
+
57
+ def validate!(request)
58
+ raise Contract::ValidationError, "communication_id is required" if request.communication_id.nil?
59
+ raise Contract::ValidationError, "recipient_id is required" if request.recipient_id.nil?
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -22,6 +22,9 @@ module CommandTower
22
22
  body: communication.body,
23
23
  metadata: freeze_metadata(communication.metadata),
24
24
  inbox_presentation_snapshot: freeze_snapshot(communication.inbox_presentation_snapshot),
25
+ slots: freeze_slots(communication.slots),
26
+ render_zone: communication.render_zone,
27
+ metadata_version: communication.metadata_version,
25
28
  created_at: communication.created_at,
26
29
  destination_plan: DestinationPlanMapper.to_result(communication.destination_plan),
27
30
  inbox_item: InboxItemMapper.to_result(communication.inbox_item),
@@ -43,6 +46,12 @@ module CommandTower
43
46
  metadata.to_h.transform_keys(&:to_s).freeze
44
47
  end
45
48
 
49
+ def freeze_slots(slots)
50
+ return nil unless slots.is_a?(Hash)
51
+
52
+ slots.deep_stringify_keys.freeze
53
+ end
54
+
46
55
  def freeze_snapshot(snapshot)
47
56
  return nil unless snapshot.is_a?(Hash)
48
57
 
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Contract
6
+ module Requests
7
+ MarkViewedForCommunication = Data.define(
8
+ :communication_id,
9
+ :recipient_id
10
+ ) do
11
+ def self.build(communication_id:, recipient_id:)
12
+ new(
13
+ communication_id:,
14
+ recipient_id:
15
+ ).freeze
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Contract
6
+ module Requests
7
+ ViewedForCommunication = Data.define(
8
+ :communication_id,
9
+ :recipient_id
10
+ ) do
11
+ def self.build(communication_id:, recipient_id:)
12
+ new(
13
+ communication_id:,
14
+ recipient_id:
15
+ ).freeze
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -12,6 +12,9 @@ module CommandTower
12
12
  :body,
13
13
  :metadata,
14
14
  :inbox_presentation_snapshot,
15
+ :slots,
16
+ :render_zone,
17
+ :metadata_version,
15
18
  :created_at,
16
19
  :destination_plan,
17
20
  :inbox_item,
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Contract
6
+ module Results
7
+ # Outcome of marking a communication's inbox item viewed. newly_viewed is
8
+ # true only for the call that set viewed_at (first view).
9
+ InboxViewMark = Data.define(
10
+ :communication_id,
11
+ :inbox_item_id,
12
+ :viewed,
13
+ :newly_viewed
14
+ )
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Definitions
6
+ # The `d` a MessageDefinition composer receives. It is a `UI::Builder` that also knows the
7
+ # definition and the {RenderContext}, so a composer can say:
8
+ #
9
+ # def inbox(d, metadata:)
10
+ # d.card(surface: :raised) { |c| c.facts; c.button "Find a class", action: d.navigate(path: "/schedule") }
11
+ # end
12
+ #
13
+ # - `d.facts` / `c.facts` with no block inserts the definition's fact block.
14
+ # - `d.basic` builds the `:basic` layout: a raised card with the headline, the fact block and
15
+ # a primary button (no button without a safe deep link).
16
+ # - `d.t.(at, zone:, format:)` renders a time with the zone label always shown; `zone: :user`
17
+ # resolves to the context's `render_zone`.
18
+ #
19
+ # Pure: no DB, no network. The class methods return validated documents (profile `:message`
20
+ # unless told otherwise) and raise `UI::InvalidDocumentError` (paths and codes only).
21
+ class DocumentBuilder < CommandTower::UI::Builder
22
+ # `profile:` defaults to the definition's own `document_profile` (`:message` unless the
23
+ # definition opts out of the fact block, as `AnnouncementDefinition` does).
24
+ class << self
25
+ # @return [CommandTower::UI::Document] the definition's inbox document
26
+ def inbox(definition:, context:, profile: nil)
27
+ document(definition:, context:, profile:) do |builder|
28
+ definition.inbox(builder, metadata: context.metadata)
29
+ end
30
+ end
31
+
32
+ # @return [CommandTower::UI::Document] the definition's email document
33
+ def email(definition:, context:, profile: nil)
34
+ document(definition:, context:, profile:) do |builder|
35
+ definition.email(builder, metadata: context.metadata)
36
+ end
37
+ end
38
+
39
+ # The fact block alone as a document, or nil when the definition has no fact block.
40
+ # @return [CommandTower::UI::Document, nil]
41
+ def facts(definition:, context:, profile: nil)
42
+ builder = new(definition:, context:)
43
+ builder.facts
44
+ return nil if builder.roots.empty?
45
+
46
+ finish(builder, context:, profile: profile || profile_for(definition))
47
+ end
48
+
49
+ # Channel slots as a symbol-keyed Hash; nil values are dropped.
50
+ # @return [Hash{Symbol => String}]
51
+ def slots(definition:, context:)
52
+ builder = new(definition:, context:)
53
+ raw = definition.slots(metadata: context.metadata, t: builder.t)
54
+ raw.to_h.transform_keys(&:to_sym).compact
55
+ end
56
+
57
+ private
58
+
59
+ def document(definition:, context:, profile:)
60
+ builder = new(definition:, context:)
61
+ yield builder
62
+ finish(builder, context:, profile: profile || profile_for(definition))
63
+ end
64
+
65
+ def profile_for(definition)
66
+ definition.class.document_profile
67
+ end
68
+
69
+ # Same root rule as `UI.document`: exactly one root node.
70
+ def finish(builder, context:, profile:)
71
+ roots = builder.roots
72
+ unless roots.one?
73
+ code = roots.empty? ? "root_required" : "multiple_roots"
74
+ raise UI::InvalidDocumentError.new("Invalid UI document: root:#{code}",
75
+ details: [{ path: "root", code: }])
76
+ end
77
+
78
+ built = UI::Document.new(root: roots.first, text_fallback: "-")
79
+ built.validate!(profile:)
80
+ fallback = UI::TextDerivation.call(built.root, user_zone: zone_for(context))
81
+ UI::Document.new(root: built.root, text_fallback: fallback).validate!(profile:)
82
+ end
83
+
84
+ def zone_for(context)
85
+ context.render_zone.presence || CommandTower.config.ui.default_zone
86
+ end
87
+ end
88
+
89
+ def initialize(definition:, context:)
90
+ super()
91
+ @definition = definition
92
+ @context = context
93
+ @inserting_facts = false
94
+ end
95
+
96
+ # With a block: the base `facts` container. Without: the definition's fact block.
97
+ def facts(&block)
98
+ return super if block
99
+ raise ArgumentError, "a definition's facts must not call d.facts without a block" if @inserting_facts
100
+
101
+ @inserting_facts = true
102
+ @definition.facts(self, metadata: @context.metadata)
103
+ ensure
104
+ @inserting_facts = false unless block
105
+ end
106
+
107
+ # Raised card: headline, fact block, primary button. The button needs a deep link.
108
+ def basic
109
+ card(surface: :raised) do |c|
110
+ c.text(headline, variant: :heading_m)
111
+ c.facts
112
+ destination = deep_link_destination
113
+ c.button(cta_label, action: navigate(**destination), variant: :primary) if destination
114
+ end
115
+ end
116
+
117
+ # Zone-aware time formatter, `t.(at, zone:, format:)`.
118
+ def t
119
+ @t ||= lambda do |at, zone:, format:|
120
+ UI::TimeFormatter.call(at:, zone:, format:, label: :always, user_zone: user_zone)
121
+ end
122
+ end
123
+
124
+ private
125
+
126
+ def user_zone
127
+ @context.render_zone.presence || CommandTower.config.ui.default_zone
128
+ end
129
+
130
+ def headline
131
+ slots = @context.slots
132
+ stored = slots.respond_to?(:to_h) ? slots.to_h.transform_keys(&:to_s)["headline"] : nil
133
+ stored.presence || @definition.headline(metadata: @context.metadata)
134
+ end
135
+
136
+ def cta_label
137
+ label = metadata_value("cta_label")
138
+ label.is_a?(String) && !label.strip.empty? ? label : "Open in #{CommandTower.app_name}"
139
+ end
140
+
141
+ # Internal path wins over an external href, as in the generic inbox document.
142
+ def deep_link_destination
143
+ path = metadata_value("deep_link_path")
144
+ return { path: } if UI::Hardening.internal_path?(path)
145
+
146
+ href = metadata_value("deep_link")
147
+ { href: } if UI::Hardening.external_href_code(href).nil?
148
+ end
149
+
150
+ def metadata_value(key)
151
+ metadata = @context.metadata
152
+ metadata.is_a?(Hash) ? (metadata[key] || metadata[key.to_sym]) : nil
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Definitions
6
+ # Input to every MessageDefinition composer (inbox, email, facts, slots). Composers receive
7
+ # this value, never an ActiveRecord row, so Accept, Deliver, the inbox read and the gallery
8
+ # all run the same pure code path. `slots` is nil until Accept has resolved them.
9
+ RenderContext = Data.define(
10
+ :notification_type_key,
11
+ :metadata,
12
+ :metadata_version,
13
+ :slots,
14
+ :render_zone
15
+ )
16
+ end
17
+ end
18
+ end
@@ -14,7 +14,9 @@ module CommandTower
14
14
  :deleted_at,
15
15
  :created_at,
16
16
  :updated_at,
17
+ :newly_viewed,
17
18
  ) do
19
+ # newly_viewed is true only on the result of a mark_viewed call that set viewed_at.
18
20
  def self.build(
19
21
  id:,
20
22
  communication_id:,
@@ -25,7 +27,8 @@ module CommandTower
25
27
  archived_at:,
26
28
  deleted_at:,
27
29
  created_at:,
28
- updated_at:
30
+ updated_at:,
31
+ newly_viewed: false
29
32
  )
30
33
  new(
31
34
  id:,
@@ -38,6 +41,7 @@ module CommandTower
38
41
  deleted_at:,
39
42
  created_at:,
40
43
  updated_at:,
44
+ newly_viewed: newly_viewed == true,
41
45
  ).freeze
42
46
  end
43
47
 
@@ -17,6 +17,21 @@ module CommandTower
17
17
  mutate(recipient_id:, inbox_item_id:, operation: :mark_viewed)
18
18
  end
19
19
 
20
+ # Keyed by communication. Returns nil when the communication is not the
21
+ # recipient's, has no inbox item, or the item is deleted. Idempotent:
22
+ # result.newly_viewed is true only on the call that set viewed_at.
23
+ def mark_viewed_for_communication(recipient_id:, communication_id:)
24
+ recipient_id = require_recipient_id!(recipient_id)
25
+ raise ValidationError, "communication_id is required" if blank?(communication_id)
26
+
27
+ record = Scope.find_for_recipient_communication(recipient_id:, communication_id:)
28
+ return nil if record.nil? || record.deleted?
29
+
30
+ mark_viewed(recipient_id:, inbox_item_id: record.id)
31
+ rescue NotFoundError
32
+ nil
33
+ end
34
+
20
35
  def mark_unviewed(recipient_id:, inbox_item_id:)
21
36
  mutate(recipient_id:, inbox_item_id:, operation: :mark_unviewed)
22
37
  end
@@ -80,6 +95,8 @@ module CommandTower
80
95
  OperationLogger.lifecycle_changed(operation:, item: result)
81
96
  end
82
97
 
98
+ result = result.with(newly_viewed: true) if operation == :mark_viewed && outcome == :changed
99
+
83
100
  result
84
101
  end
85
102
 
@@ -63,6 +63,18 @@ module CommandTower
63
63
  ItemResult.from_record(record)
64
64
  end
65
65
 
66
+ # Keyed by communication. true/false for a live inbox item; nil when the
67
+ # communication is not the recipient's, has no inbox item, or is deleted.
68
+ def viewed_for_communication(recipient_id:, communication_id:)
69
+ recipient_id = require_recipient_id!(recipient_id)
70
+ raise ValidationError, "communication_id is required" if blank?(communication_id)
71
+
72
+ record = Scope.find_for_recipient_communication(recipient_id:, communication_id:)
73
+ return nil if record.nil? || record.deleted?
74
+
75
+ !record.viewed_at.nil?
76
+ end
77
+
66
78
  def unread_count(recipient_id:)
67
79
  recipient_id = require_recipient_id!(recipient_id)
68
80
  unread = Scope.for_recipient(recipient_id).merge(Messaging::InboxItem.unread)
@@ -18,6 +18,14 @@ module CommandTower
18
18
  relation = relation.lock if lock
19
19
  relation.find_by(id: inbox_item_id)
20
20
  end
21
+
22
+ # An inbox item is 1:1 with its communication; nil when the communication
23
+ # is not the recipient's or has no inbox item.
24
+ def find_for_recipient_communication(recipient_id:, communication_id:, lock: false)
25
+ relation = for_recipient(recipient_id)
26
+ relation = relation.lock if lock
27
+ relation.find_by(communication_id:)
28
+ end
21
29
  end
22
30
  end
23
31
  end
@@ -21,6 +21,14 @@ module CommandTower
21
21
  Reader.unread_count(recipient_id:)
22
22
  end
23
23
 
24
+ def viewed_for_communication(recipient_id:, communication_id:)
25
+ Reader.viewed_for_communication(recipient_id:, communication_id:)
26
+ end
27
+
28
+ def mark_viewed_for_communication(recipient_id:, communication_id:)
29
+ Mutator.mark_viewed_for_communication(recipient_id:, communication_id:)
30
+ end
31
+
24
32
  def mark_viewed(recipient_id:, inbox_item_id:)
25
33
  Mutator.mark_viewed(recipient_id:, inbox_item_id:)
26
34
  end