command_tower 0.23.0 → 0.24.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/home_notices_controller.rb +39 -0
  3. data/app/controllers/command_tower/me/home_notices_controller.rb +79 -0
  4. data/app/deserializers/command_tower/deserializers/admin/home_notices/control_deserializer.rb +40 -0
  5. data/app/deserializers/command_tower/deserializers/home_notices/notice_id_deserializer.rb +42 -0
  6. data/app/errors/command_tower/errors/home_notices/linked_message_unavailable_error.rb +23 -0
  7. data/app/errors/command_tower/errors/home_notices/rate_limit_error.rb +25 -0
  8. data/app/errors/command_tower/errors/home_notices/unavailable_error.rb +22 -0
  9. data/app/jobs/command_tower/home_notices/prune_ended_job.rb +14 -0
  10. data/app/models/command_tower/home_notice.rb +41 -0
  11. data/app/models/command_tower/home_notice_control.rb +12 -0
  12. data/app/serializers/command_tower/serializers/home_notices/control_serializer.rb +14 -0
  13. data/app/serializers/command_tower/serializers/home_notices/dismissal_serializer.rb +19 -0
  14. data/app/serializers/command_tower/serializers/home_notices/mutation_serializer.rb +16 -0
  15. data/app/serializers/command_tower/serializers/home_notices/notice_serializer.rb +35 -0
  16. data/app/serializers/command_tower/serializers/home_notices/selection_serializer.rb +21 -0
  17. data/app/services/command_tower/home_notices/campaign.rb +28 -0
  18. data/app/services/command_tower/home_notices/campaigns/update_app.rb +77 -0
  19. data/app/services/command_tower/home_notices/catalog/validator.rb +92 -0
  20. data/app/services/command_tower/home_notices/catalog.rb +92 -0
  21. data/app/services/command_tower/home_notices/context.rb +10 -0
  22. data/app/services/command_tower/home_notices/delivery.rb +43 -0
  23. data/app/services/command_tower/home_notices/notice.rb +88 -0
  24. data/app/services/command_tower/home_notices/notice_record.rb +28 -0
  25. data/app/services/command_tower/messaging/contract/inbox.rb +29 -0
  26. data/app/services/command_tower/messaging/contract/requests/document_for_communication.rb +24 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_document.rb +17 -0
  28. data/app/services/command_tower/services/auth/purge_user_associated_data.rb +6 -0
  29. data/app/services/command_tower/services/home_notices/acknowledge.rb +149 -0
  30. data/app/services/command_tower/services/home_notices/check_mutation_eligibility.rb +84 -0
  31. data/app/services/command_tower/services/home_notices/check_rate_limit.rb +52 -0
  32. data/app/services/command_tower/services/home_notices/compose.rb +113 -0
  33. data/app/services/command_tower/services/home_notices/deliver.rb +111 -0
  34. data/app/services/command_tower/services/home_notices/dismiss.rb +147 -0
  35. data/app/services/command_tower/services/home_notices/load_candidates.rb +85 -0
  36. data/app/services/command_tower/services/home_notices/pick_notices.rb +139 -0
  37. data/app/services/command_tower/services/home_notices/prune_ended.rb +93 -0
  38. data/app/services/command_tower/services/home_notices/read_controls.rb +31 -0
  39. data/app/services/command_tower/services/home_notices/record_impression.rb +154 -0
  40. data/app/services/command_tower/services/home_notices/resolve_notice.rb +69 -0
  41. data/app/services/command_tower/services/home_notices/select.rb +136 -0
  42. data/app/services/command_tower/services/home_notices/update_control.rb +56 -0
  43. data/app/workflows/command_tower/workflows/admin/home_notices/update_control_workflow.rb +64 -0
  44. data/app/workflows/command_tower/workflows/home_notices/acknowledge_workflow.rb +140 -0
  45. data/app/workflows/command_tower/workflows/home_notices/dismiss_workflow.rb +107 -0
  46. data/app/workflows/command_tower/workflows/home_notices/prune_ended_workflow.rb +25 -0
  47. data/app/workflows/command_tower/workflows/home_notices/record_impression_workflow.rb +92 -0
  48. data/app/workflows/command_tower/workflows/home_notices/show_workflow.rb +44 -0
  49. data/config/routes.rb +9 -0
  50. data/db/migrate/20261124200001_create_command_tower_home_notices.rb +43 -0
  51. data/db/migrate/20261124200002_create_command_tower_home_notice_controls.rb +12 -0
  52. data/docs/api_reference.md +108 -1
  53. data/docs/audit.md +12 -0
  54. data/docs/bootstrap/08-initializer.md +15 -0
  55. data/docs/bootstrap/09-rbac.md +6 -0
  56. data/docs/bootstrap/13-optional.md +12 -0
  57. data/docs/extending.md +2 -0
  58. data/docs/home_notices.md +236 -0
  59. data/docs/messaging_integration_guide.md +4 -0
  60. data/docs/models.md +4 -0
  61. data/docs/principal_capabilities.md +1 -0
  62. data/docs/ui.md +13 -0
  63. data/docs/upgrades/0.24.0.md +50 -0
  64. data/lib/command_tower/authorization/default.yml +10 -0
  65. data/lib/command_tower/configuration/config.rb +6 -0
  66. data/lib/command_tower/configuration/home_notices/config.rb +67 -0
  67. data/lib/command_tower/configuration/registry/audit/config.rb +61 -0
  68. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +1 -1
  69. data/lib/command_tower/engine.rb +1 -0
  70. data/lib/command_tower/install/baseline.rb +2 -0
  71. data/lib/command_tower/ui/document.rb +26 -5
  72. data/lib/command_tower/version.rb +1 -1
  73. data/lib/tasks/home_notices.rake +11 -0
  74. metadata +53 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 42e2598ba53291eb5392477e6bd78d1c8129b849f21682b8d3c2575afd98ae8d
4
- data.tar.gz: 112e103cd27edb7bbcf923161a23760ba34a994aa771b64380bdd08caaad4e10
3
+ metadata.gz: 23f2057a8d104d4de929ece5a2679f42b9d09492728d21e2caae42826f7c471a
4
+ data.tar.gz: 60cad58488dfe758b7378682cf59ae67d049e91ff1d0729d358938da75f7eac4
5
5
  SHA512:
6
- metadata.gz: 17df018dc3daf30e315dbe95b80a0115a8171386059ec6ce0feb9bd3c8c10794574e9b14e38c9393e586ea5525e25a5ca8ecefdc8d7e8c06173fbf9aacb9e2b6
7
- data.tar.gz: c6e9a0567b1f5ba0642590ce2b2b01468ffea8cf79cd67e5bb1c480ba0f68d4768c6a2e198b2770ac2384c9f9504a8736d23a09fb551a02f227a2b5bd4b05f40
6
+ metadata.gz: a76d0fd890cbd63de67125c8e69cc7bba62d21dda0e5cbbd6b669fb3207a626d94e49dec9037499713b2fdc72f034486ce49d02dc58cdf218bbbe2e263a347e9
7
+ data.tar.gz: 9fdb40b61f0c1e4820300c188f92901c55e7a0f5209f9a3917754e8bd10683b92b1551e5093647ff98cf90843e64e6c230e61d8177892d7f819e50a6ad8e0599
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Admin
5
+ # The home-notice kill switch. Needs the `admin_home_notices_kill` grant (not in the principal
6
+ # capabilities catalog) and is refused while impersonating, by `Admin::ApplicationController`.
7
+ class HomeNoticesController < CommandTower::Admin::ApplicationController
8
+ before_action :set_no_store
9
+
10
+ def update
11
+ deserialized = CommandTower::Deserializers::Admin::HomeNotices::ControlDeserializer.call(params)
12
+ return render_deserializer_errors unless deserialized.success?
13
+
14
+ render_application_result(
15
+ CommandTower::Workflows::Admin::HomeNotices::UpdateControlWorkflow.call(
16
+ user: current_user,
17
+ key: deserialized.input.key,
18
+ enabled: deserialized.input.enabled
19
+ )
20
+ )
21
+ end
22
+
23
+ private
24
+
25
+ def set_no_store
26
+ response.headers["Cache-Control"] = "no-store"
27
+ end
28
+
29
+ def render_deserializer_errors
30
+ render_application_result(
31
+ CommandTower::Workflows::WorkflowResult.failure(
32
+ errors: [CommandTower::Errors::ValidationError.new(details: { base: "Invalid request parameters" })],
33
+ http_status: :unprocessable_entity
34
+ )
35
+ )
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Me
5
+ class HomeNoticesController < CommandTower::ApplicationController
6
+ include CommandTower::Auth::AuthenticationBoundary
7
+ include CommandTower::Auth::AuthorizationBoundary
8
+
9
+ before_action :authenticate_request!
10
+ before_action :authorize_request!
11
+
12
+ before_action :set_no_store
13
+
14
+ def index
15
+ result = CommandTower::Workflows::HomeNotices::ShowWorkflow.call(
16
+ user: current_user,
17
+ impersonating: impersonating_flag,
18
+ app_version: header_value("X-App-Version"),
19
+ platform: header_value("X-Client-Platform")&.downcase
20
+ )
21
+ render_application_result(result)
22
+ end
23
+
24
+ def impression
25
+ mutate(CommandTower::Workflows::HomeNotices::RecordImpressionWorkflow)
26
+ end
27
+
28
+ def acknowledge
29
+ mutate(CommandTower::Workflows::HomeNotices::AcknowledgeWorkflow)
30
+ end
31
+
32
+ def dismiss
33
+ mutate(CommandTower::Workflows::HomeNotices::DismissWorkflow)
34
+ end
35
+
36
+ private
37
+
38
+ def mutate(workflow)
39
+ deserialized = CommandTower::Deserializers::HomeNotices::NoticeIdDeserializer.call(params)
40
+ return render_not_found unless deserialized.success?
41
+
42
+ result = workflow.call(
43
+ user: current_user,
44
+ notice_id: deserialized.input,
45
+ impersonating: impersonating_flag,
46
+ app_version: header_value("X-App-Version"),
47
+ platform: header_value("X-Client-Platform")&.downcase
48
+ )
49
+ render_application_result(result)
50
+ end
51
+
52
+ # A malformed id names no notice.
53
+ def render_not_found
54
+ render_application_result(
55
+ CommandTower::Workflows::WorkflowResult.failure(
56
+ errors: [CommandTower::Errors::NotFoundError.new], http_status: :not_found
57
+ )
58
+ )
59
+ end
60
+
61
+ # Notices are per user and redacted while impersonating: never cache them.
62
+ def set_no_store
63
+ response.headers["Cache-Control"] = "no-store"
64
+ end
65
+
66
+ # From the authentication result: true while impersonating, false for a normal session,
67
+ # nil when there is no auth context (unknown, which redacts).
68
+ def impersonating_flag
69
+ return nil if current_auth_context.nil?
70
+
71
+ CommandTower::Current.impersonation_active == true
72
+ end
73
+
74
+ def header_value(name)
75
+ request.headers[name].to_s.strip.presence
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Deserializers
5
+ module Admin
6
+ module HomeNotices
7
+ # Reads the kill-switch update `PATCH /admin/home-notices/:key {enabled: bool}`: the notice
8
+ # `key` and a strict boolean `enabled`. Whether the key is a registered notice is the
9
+ # workflow's decision.
10
+ class ControlDeserializer < CommandTower::Deserializers::ApplicationDeserializer
11
+ KEY_FORMAT = /\A[a-z0-9_]+(\.[a-z0-9_]+)*\z/
12
+ KEY_MAX_LENGTH = 128
13
+
14
+ Input = Data.define(:key, :enabled)
15
+
16
+ def call(params)
17
+ key = unwrap(require_string(fetch_param(params, :key).value, field: :key))
18
+ return key if deserializer_result?(key)
19
+ return invalid(:key) unless KEY_FORMAT.match?(key) && key.length <= KEY_MAX_LENGTH
20
+
21
+ enabled_input(fetch_param(params, :enabled).value, key)
22
+ end
23
+
24
+ private
25
+
26
+ def enabled_input(enabled, key)
27
+ return invalid(:enabled, code: "missing_required_fields") if enabled.nil?
28
+ return invalid(:enabled) unless [true, false].include?(enabled)
29
+
30
+ success(Input.new(key:, enabled:))
31
+ end
32
+
33
+ def invalid(field, code: "invalid_value")
34
+ failure(errors: CommandTower::Deserializers::Failure.build(code:, field:))
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Deserializers
5
+ module HomeNotices
6
+ # Reads the `:id` of a home-notice mutation: a row `public_id` or `campaign:<key>`.
7
+ # The result carries exactly one of `public_id` and `campaign_key`.
8
+ class NoticeIdDeserializer < CommandTower::Deserializers::ApplicationDeserializer
9
+ CAMPAIGN_PREFIX = "campaign:"
10
+ PUBLIC_ID_FORMAT = /\A[A-Za-z0-9]{1,32}\z/
11
+ CAMPAIGN_KEY_FORMAT = /\A[a-z0-9_]+(\.[a-z0-9_]+)+\z/
12
+
13
+ Input = Data.define(:public_id, :campaign_key)
14
+
15
+ def call(params)
16
+ raw = unwrap(require_string(fetch_param(params, :id).value, field: :id))
17
+ return raw if deserializer_result?(raw)
18
+
19
+ raw.start_with?(CAMPAIGN_PREFIX) ? campaign_input(raw.delete_prefix(CAMPAIGN_PREFIX)) : public_id_input(raw)
20
+ end
21
+
22
+ private
23
+
24
+ def campaign_input(key)
25
+ return invalid unless CAMPAIGN_KEY_FORMAT.match?(key)
26
+
27
+ success(Input.new(public_id: nil, campaign_key: key))
28
+ end
29
+
30
+ def public_id_input(value)
31
+ return invalid unless PUBLIC_ID_FORMAT.match?(value)
32
+
33
+ success(Input.new(public_id: value, campaign_key: nil))
34
+ end
35
+
36
+ def invalid
37
+ failure(errors: CommandTower::Deserializers::Failure.build(code: "invalid_value", field: :id))
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module HomeNotices
6
+ # A linked delivery named a communication the user cannot see in their inbox (missing, deleted,
7
+ # foreign, or not backed by a message definition).
8
+ class LinkedMessageUnavailableError < CommandTower::Errors::ApplicationError
9
+ def code
10
+ "linked_message_unavailable"
11
+ end
12
+
13
+ def message
14
+ "The linked message is unavailable"
15
+ end
16
+
17
+ def log_level
18
+ :warn
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module HomeNotices
6
+ class RateLimitError < CommandTower::Errors::ApplicationError
7
+ def initialize(retry_after_seconds: nil)
8
+ super(details: retry_after_seconds ? { retry_after: retry_after_seconds } : nil)
9
+ end
10
+
11
+ def code
12
+ "home_notices_rate_limited"
13
+ end
14
+
15
+ def message
16
+ "Too many home notice requests"
17
+ end
18
+
19
+ def log_level
20
+ :warn
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module HomeNotices
6
+ # A home-notice mutation could not read its controls or write: the client retries later.
7
+ class UnavailableError < CommandTower::Errors::ApplicationError
8
+ def code
9
+ "home_notices_unavailable"
10
+ end
11
+
12
+ def message
13
+ "Home notices are currently unavailable"
14
+ end
15
+
16
+ def log_level
17
+ :error
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module HomeNotices
5
+ # Daily prune of ended, idle home notice rows. Scheduled by the host.
6
+ class PruneEndedJob < CommandTower::ApplicationJob
7
+ queue_as :default
8
+
9
+ def perform
10
+ execute_workflow(CommandTower::Workflows::HomeNotices::PruneEndedWorkflow)
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ # Persistence only. One row per user per notice occurrence (campaign period or delivery identity).
5
+ class HomeNotice < CommandTower::ApplicationRecord
6
+ PERIOD_KEY_LIMIT = 191
7
+ DIGEST_LENGTH = 16
8
+
9
+ self.table_name = "command_tower_home_notices"
10
+
11
+ belongs_to :user
12
+
13
+ before_validation :assign_public_id, on: :create
14
+ before_validation :normalize_period_key
15
+
16
+ validates :public_id, presence: true
17
+ validates :kind, :key, presence: true
18
+ validates :period_key, uniqueness: { scope: %i[user_id campaign_key] }, if: -> { campaign_key.present? }
19
+ validates :identity, uniqueness: { scope: :user_id }, if: -> { identity.present? }
20
+
21
+ # The stored form of a period key: to_s; an over-long value is truncated and given a digest
22
+ # suffix so it stays unique. Lookups by period key use the same form.
23
+ def self.stored_period_key(value)
24
+ value = value.to_s
25
+ return value if value.length <= PERIOD_KEY_LIMIT
26
+
27
+ digest = Digest::SHA256.hexdigest(value).first(DIGEST_LENGTH)
28
+ "#{value.first(PERIOD_KEY_LIMIT - DIGEST_LENGTH - 1)}-#{digest}"
29
+ end
30
+
31
+ private
32
+
33
+ def assign_public_id
34
+ self.public_id = SecureRandom.alphanumeric(32) if public_id.blank?
35
+ end
36
+
37
+ def normalize_period_key
38
+ self.period_key = self.class.stored_period_key(period_key)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ # Persistence only. One row per notice key that an admin has switched on or off.
5
+ class HomeNoticeControl < CommandTower::ApplicationRecord
6
+ self.table_name = "command_tower_home_notice_controls"
7
+ self.primary_key = "key"
8
+
9
+ validates :key, presence: true, length: { maximum: 128 }
10
+ validates :enabled, inclusion: { in: [true, false] }
11
+ end
12
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module HomeNotices
6
+ # The payload of a kill-switch update: `{ key, enabled }`.
7
+ class ControlSerializer
8
+ def self.serialize(key:, enabled:)
9
+ { key: key.to_s, enabled: enabled == true }
10
+ end
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module HomeNotices
6
+ # The payload of a dismiss: `{ id, dismissedUntil }` (design §3.3). `id` follows
7
+ # `NoticeSerializer`: `campaign:<key>` for a campaign, the row `public_id` for a delivery.
8
+ class DismissalSerializer
9
+ def self.serialize(notice_class:, public_id:, dismissed_until:)
10
+ campaign = notice_class < CommandTower::HomeNotices::Campaign
11
+ {
12
+ id: campaign ? "campaign:#{notice_class.key}" : public_id,
13
+ dismissedUntil: dismissed_until&.utc&.iso8601
14
+ }
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module HomeNotices
6
+ # The payload of a home-notice mutation (impression, acknowledge, dismiss): `{ recorded }`.
7
+ class MutationSerializer
8
+ # @param recorded [Boolean] true when the request changed state, false for a no-op
9
+ # (impersonation, or a repeat inside the idempotency window)
10
+ def self.serialize(recorded:)
11
+ { recorded: recorded == true }
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module HomeNotices
6
+ # One picked notice: `{ id, key, severity, endsAt, document }` (design §3.3).
7
+ # `id` is `campaign:<key>` for a campaign and the row `public_id` for a delivery.
8
+ class NoticeSerializer
9
+ # @param pick [CommandTower::Services::HomeNotices::PickNotices::Pick]
10
+ def self.serialize(pick)
11
+ klass = pick.notice_class
12
+ {
13
+ id: id_for(klass, pick.record),
14
+ key: klass.key.to_s,
15
+ severity: klass.blocking? ? "blocking" : "dismissible",
16
+ endsAt: ends_at_for(klass, pick.record)&.iso8601,
17
+ document: pick.document.as_json
18
+ }
19
+ end
20
+
21
+ def self.id_for(klass, record)
22
+ return "campaign:#{klass.key}" if klass < CommandTower::HomeNotices::Campaign
23
+
24
+ record.public_id
25
+ end
26
+
27
+ def self.ends_at_for(klass, record)
28
+ record&.ends_at || klass.window&.ends_at
29
+ end
30
+
31
+ private_class_method :id_for, :ends_at_for
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module HomeNotices
6
+ # The `GET /me/home-notices` payload: `{ blocking, dismissible, readOnly }` (design §3.3).
7
+ class SelectionSerializer
8
+ # @param blocking [PickNotices::Pick, nil]
9
+ # @param dismissible [PickNotices::Pick, nil]
10
+ # @param read_only [Boolean] true while impersonating (or when that is unknown)
11
+ def self.serialize(blocking:, dismissible:, read_only:)
12
+ {
13
+ blocking: blocking && NoticeSerializer.serialize(blocking),
14
+ dismissible: dismissible && NoticeSerializer.serialize(dismissible),
15
+ readOnly: read_only
16
+ }
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module HomeNotices
5
+ # A notice the host derives from application state (for example "make your picks"). The platform
6
+ # materializes one row per user per period. Adds the pacing and period macros.
7
+ class Campaign < Notice
8
+ Impressions = Data.define(:max, :cooldown)
9
+
10
+ class << self
11
+ # Pacing: at most `max` impressions, at least `cooldown` apart.
12
+ def impressions(max: nil, cooldown: nil)
13
+ return inherited_setting(:@impressions) if max.nil? && cooldown.nil?
14
+
15
+ @impressions = Impressions.new(max:, cooldown:)
16
+ end
17
+
18
+ # Block returning the period identity for a user, `{ |user:, context:| ... }`. Impressions
19
+ # and acknowledgement reset when the value changes.
20
+ def period_key(&block)
21
+ return inherited_setting(:@period_key) if block.nil?
22
+
23
+ @period_key = block
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module HomeNotices
5
+ module Campaigns
6
+ # Built-in dismissible campaign `ct.update_app` (design D10). Shown only while the client
7
+ # compatibility recommendation says `updateAvailable`, and again for each new recommended
8
+ # version. It is separate from the 426 gate, which this class never touches. Included in the
9
+ # catalog when `config.home_notices.update_app_campaign` is true; the key is reserved for it.
10
+ class UpdateApp < Campaign
11
+ TITLE = "A new version is ready"
12
+ BODY = "Update to get the latest fixes and improvements."
13
+ BODY_WITHOUT_URL = "Update from your device's app store to get the latest fixes and improvements."
14
+ BUTTON_LABEL = "Update now"
15
+
16
+ key "ct.update_app"
17
+ severity :dismissible
18
+ priority 100
19
+ impressions max: 3, cooldown: 24.hours
20
+
21
+ # A new recommended version starts a new period, so impressions and acknowledgement reset.
22
+ period_key { |user:, context:| Recommendation.new(context.client_compatibility).recommended_version } # rubocop:disable Lint/UnusedBlockArgument
23
+
24
+ def show?(user:, context:, notice:) # rubocop:disable Lint/UnusedMethodArgument
25
+ Recommendation.new(context.client_compatibility).update_available?
26
+ end
27
+
28
+ def compose(builder, user:, context:, notice:) # rubocop:disable Lint/UnusedMethodArgument
29
+ recommendation = Recommendation.new(context.client_compatibility)
30
+ url = recommendation.https_update_url
31
+
32
+ body = url ? BODY : BODY_WITHOUT_URL
33
+ builder.stack(gap: :md) do |stack|
34
+ stack.fragment(CommandTower::UI::Fragments::NoticeFrame, title: TITLE, body: [body])
35
+ add_versions(stack, your_version: context.app_version, latest: recommendation.recommended_version)
36
+ stack.button(BUTTON_LABEL, action: stack.navigate(href: url), variant: :primary) if url
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ def add_versions(builder, your_version:, latest:)
43
+ return if your_version.blank? && latest.blank?
44
+
45
+ builder.key_value do |rows|
46
+ rows.item("Your version", your_version.to_s) if your_version.present?
47
+ rows.item("Latest", latest.to_s) if latest.present?
48
+ end
49
+ end
50
+
51
+ # Reads the `Current.client_compatibility_recommendation` projection (symbol or string keys).
52
+ class Recommendation
53
+ def initialize(projection)
54
+ @projection = projection.respond_to?(:with_indifferent_access) ? projection.with_indifferent_access : {}
55
+ end
56
+
57
+ def update_available?
58
+ @projection[:updateAvailable] == true
59
+ end
60
+
61
+ def recommended_version
62
+ @projection[:recommendedVersion].presence&.to_s
63
+ end
64
+
65
+ # The update URL when it is an https URL the document can carry, else nil.
66
+ def https_update_url
67
+ url = @projection[:updateUrl].to_s
68
+ return nil unless url.start_with?("https://")
69
+ return nil if CommandTower::UI::Hardening.external_href_code(url)
70
+
71
+ url
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module HomeNotices
5
+ class Catalog
6
+ # Per-class boot checks (design D2). Returns the list of problems for one notice class.
7
+ module Validator
8
+ KEY_FORMAT = /\A[a-z0-9_]+(\.[a-z0-9_]+)+\z/
9
+ RESERVED_KEY_PREFIX = "ct."
10
+ MIN_BLOCKING_REASON_LENGTH = 20
11
+
12
+ module_function
13
+
14
+ # `builtin` is true for platform notices, which may use the reserved key prefix.
15
+ def errors_for(klass, builtin: false)
16
+ return ["must subclass CommandTower::HomeNotices::Campaign or Delivery"] unless notice_subclass?(klass)
17
+
18
+ key_errors(klass, builtin:) + severity_errors(klass) + kind_errors(klass) +
19
+ show_errors(klass) + compose_errors(klass) + window_errors(klass)
20
+ end
21
+
22
+ def notice_subclass?(klass)
23
+ klass.is_a?(Class) && (klass < Campaign || klass < Delivery)
24
+ end
25
+
26
+ def key_errors(klass, builtin: false)
27
+ key = klass.key
28
+ return ["key is required"] if key.nil?
29
+ return ["key #{key.inspect} must match #{KEY_FORMAT.inspect}"] unless KEY_FORMAT.match?(key)
30
+ return [] if builtin || !key.start_with?(RESERVED_KEY_PREFIX)
31
+
32
+ ["key #{key.inspect} uses the reserved #{RESERVED_KEY_PREFIX} prefix"]
33
+ end
34
+
35
+ def severity_errors(klass)
36
+ errors = []
37
+ errors << "severity is required" if klass.severity.nil?
38
+ errors << "priority is required" if klass.priority.nil?
39
+ if klass.blocking? && klass.blocking_reason.to_s.length < MIN_BLOCKING_REASON_LENGTH
40
+ errors << "a blocking notice needs blocking_reason of at least #{MIN_BLOCKING_REASON_LENGTH} characters"
41
+ end
42
+ errors
43
+ end
44
+
45
+ # Macros are defined on one kind only, so a notice of the other kind must not carry them.
46
+ def kind_errors(klass)
47
+ klass < Campaign ? campaign_errors(klass) : delivery_errors(klass)
48
+ end
49
+
50
+ def campaign_errors(klass)
51
+ errors = []
52
+ errors << "composer is a Delivery macro" if klass.respond_to?(:composer)
53
+ errors << "a dismissible campaign must declare impressions" if klass.dismissible? && klass.impressions.nil?
54
+ errors
55
+ end
56
+
57
+ def delivery_errors(klass)
58
+ return [] unless klass.respond_to?(:impressions) || klass.respond_to?(:period_key)
59
+
60
+ ["impressions and period_key are Campaign macros"]
61
+ end
62
+
63
+ # The owner of `show?` must not be `Notice`. An unlinked Delivery must not rely on `Delivery`
64
+ # either; the linked default (`composer :message`) counts as an override.
65
+ def show_errors(klass)
66
+ owner = klass.instance_method(:show?).owner
67
+ inherited = owner == Notice || (klass < Delivery && !linked_delivery?(klass) && owner == Delivery)
68
+ inherited ? ["show? must be overridden"] : []
69
+ end
70
+
71
+ def compose_errors(klass)
72
+ return [] if linked_delivery?(klass)
73
+ return [] unless klass.instance_method(:compose).owner == Notice
74
+
75
+ ["compose must be overridden"]
76
+ end
77
+
78
+ def window_errors(klass)
79
+ window = klass.window
80
+ return [] if window.nil? || window.starts_at.nil? || window.ends_at.nil?
81
+ return [] if window.starts_at < window.ends_at
82
+
83
+ ["window starts_at must be before ends_at"]
84
+ end
85
+
86
+ def linked_delivery?(klass)
87
+ klass < Delivery && klass.composer == :message
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end