bible270 1.17.2 → 1.18.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c99403f2988bb64614996cf4b447679f8ad56731d1c4f6d5f9f6f93cb23d1d4d
4
- data.tar.gz: f87f1e3baf25aa620da73eb9ad2fc8e3ff40a082d4ffdfef10bbed98246e08d6
3
+ metadata.gz: 1932d8cdbae32aa00b8a05785ca6c680b403fa3be0be733752e9a6a2af1f99f6
4
+ data.tar.gz: ddb45896f1678fff0b941444a7a321b3769952160e8bfc5e4cc6929019d8b8d0
5
5
  SHA512:
6
- metadata.gz: 02fe754b4c1a32a3ae63c8353b145a034c98d9a5bb1c60e7a44675aebdc9aa6185ed9319482f1e21db9b72fecc32f32a7081aafb6a3b94dbf2b01f99aa0c2be1
7
- data.tar.gz: e8fcff4ab48c0bd01f778ec10b25ebd5c252f243aebba7b0c57ce795c27bc93d587b58dcc5c204f476610a0aae13884d70e4eb253f071c207549828ce6c64e95
6
+ metadata.gz: b9b08e64471767bab9832574dbbdfc6c44f9fa23989fdc4cc99c2ca84c64cfdd939bd1ad1d3d95446cbe8b11e8121738306c5eac27e2ffab9fbea073d99967e9
7
+ data.tar.gz: 5b4412c468de22d275f2274056f381ec980785273177dc1333e7a5eaba30b853a04ded9598e6ad557e42b4106a4883e7c18775ecc97326c693de9aa7b85a3dd2
data/CHANGELOG.md CHANGED
@@ -6,9 +6,22 @@ Notable changes, following [Keep a Changelog](https://keepachangelog.com/en/1.1.
6
6
 
7
7
  ### Added
8
8
 
9
+ - let admins link matching reader accounts for one-way progress sync, including existing completions
10
+ - queue reliable delivery between trusted instances, with retries and optional immediate background jobs
11
+
12
+ **Setup:** Install migration `20260101000028` on each instance, configure trusted connections, and schedule delivery on the primary. Progress sync is off until configured.
13
+
14
+ ## [1.17.2] - 2026-11-13
15
+
16
+ ### Added
17
+
9
18
  - add a session-remembered Show/Hide Scripture frames toggle in Admin
10
19
  - expand the bundled Scripture frame collection
11
20
 
21
+ ### Fixed
22
+
23
+ - update Admin assertions and stabilize headless browser focus tests
24
+
12
25
  ## [1.17.1] - 2026-11-13
13
26
 
14
27
  ### Added
@@ -880,7 +893,8 @@ This is the initial public release.
880
893
 
881
894
  - Email sign-in requires working Action Mailer delivery in the host application. Set `config.mailer_from`; delivery is inline by default, or set `email_sign_in_deliver_later` when a queue backend is available.
882
895
 
883
- [Unreleased]: https://github.com/avonderluft/bible270/compare/v1.17.1...main
896
+ [Unreleased]: https://github.com/avonderluft/bible270/compare/v1.17.2...main
897
+ [1.17.2]: https://github.com/avonderluft/bible270/compare/v1.17.1...v1.17.2
884
898
  [1.17.1]: https://github.com/avonderluft/bible270/compare/v1.17.0...v1.17.1
885
899
  [1.17.0]: https://github.com/avonderluft/bible270/compare/v1.16.0...v1.17.0
886
900
  [1.16.0]: https://github.com/avonderluft/bible270/compare/v1.15.1...v1.16.0
data/README.md CHANGED
@@ -274,6 +274,7 @@ The panel supports:
274
274
  - Delete unprotected readers **and all their check-offs and reflections across runs**.
275
275
  - Hide (reversibly) or delete reflections at `<mount>/admin/comments`. Posts are public immediately, without approval.
276
276
  - Manage [Scripture frame](#scripture-frame) texts.
277
+ - Link readers to trusted instances for [one-way progress sync](#progress-sync).
277
278
  - Send individually addressed email: **Write to everyone** reaches active readers; **Write to all admins** includes alumni admins. Both require an email address.
278
279
 
279
280
  To print a progress report ordered by completed days:
@@ -310,6 +311,46 @@ Each reader's **Past runs / history** table shows read-only start/end dates, arc
310
311
 
311
312
  Admin templates include `bible270/shared/admin_confirmations`, even with custom layouts. Keep this partial in host template overrides; no layout include is needed.
312
313
 
314
+ ### Progress sync
315
+
316
+ Admins can link a reader to existing, active accounts on other installations with the same email. Readers sign in only on the primary site. New check-offs sync automatically; **Sync existing progress** copies earlier completions. Both add only missing check-offs—never uncheck readings, change dates, or copy reflections.
317
+
318
+ Install migration `20260101000028` on every participating installation. Site administrators configure trust in their host initializers; no destination credentials are entered in Admin.
319
+
320
+ On the **primary**:
321
+
322
+ ```ruby
323
+ config.progress_sync_instance_id = 'primary'
324
+ config.progress_sync_destinations = {
325
+ 'church' => {
326
+ label: 'Church', url: 'https://church.example/daily-bread',
327
+ secret: ENV.fetch('B270_PRIMARY_CHURCH_SYNC_SECRET')
328
+ }
329
+ }
330
+ ```
331
+
332
+ On the **destination**:
333
+
334
+ ```ruby
335
+ config.progress_sync_sources = {
336
+ 'primary' => { secret: ENV.fetch('B270_PRIMARY_CHURCH_SYNC_SECRET') }
337
+ }
338
+ ```
339
+
340
+ Use the same randomly generated secret on both sides, at least 32 characters; `bin/rails secret` can generate one. Use a separate secret for each destination. URLs must be canonical HTTPS engine mount URLs, without redirects. Trust authorizes the primary's admins to link accounts by email; grant it only to installations you control or trust.
341
+
342
+ Schedule this command **every minute on the primary**, using the host's scheduler:
343
+
344
+ ```bash
345
+ RAILS_ENV=production bin/rails bible270:progress_sync:deliver
346
+ ```
347
+
348
+ If the host already has a **persistent Active Job backend and running worker**, also set `config.progress_sync_deliver_later = true` for immediate delivery. Keep the scheduled task for retries and recovery; inline and in-memory adapters are not used. No worker is needed on destinations.
349
+
350
+ In **Admin → reader → Progress sync**, select a destination, **Find account**, then **Link account**. Repeat for other destinations. Use **Sync existing progress** when wanted. Status, pending deliveries, and the latest result appear beside each link; **Unlink** stops queued updates without deleting progress. A request already being delivered may still finish.
351
+
352
+ Reading assignments must match, though start dates may differ. Account links use fixed reader/run identities after matching. Alumni status, run changes (including restart/revert), or changed assignments require explicit relinking. Imported progress is never forwarded. After repeated delivery failures, inspect the error, relink, and copy existing progress again if needed.
353
+
313
354
  ### Consistency ranking
314
355
 
315
356
  Consistency is the average end-of-day score on a dated schedule:
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bible270/progress_sync'
4
+ require 'bible270/progress_sync/client'
5
+
6
+ module Bible270
7
+ class AdminProgressSyncsController < ApplicationController
8
+ CANDIDATE_SESSION_KEY = :bible270_progress_sync_candidate
9
+ CANDIDATE_PURPOSE = 'progress-sync-link'
10
+
11
+ before_action :require_admin!
12
+ before_action :require_admin_view!
13
+ before_action :load_reader
14
+
15
+ rescue_from ProgressSync::Error, with: :sync_error
16
+ rescue_from ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique, with: :invalid_link
17
+
18
+ # Also used by the partial after the lookup redirect; no Admin#show setup is needed.
19
+ def self.candidate_for(token, reader:, admin:)
20
+ candidate = verifier.verified(token.to_s, purpose: CANDIDATE_PURPOSE)
21
+ return unless candidate.is_a?(Hash) && candidate['remote'].is_a?(Hash)
22
+
23
+ context = link_context(reader: reader, admin: admin, destination: candidate['destination'])
24
+ return unless context.all? { |key, value| candidate[key] == value }
25
+ return unless normalized_email(candidate['remote']['email']) == context['email']
26
+
27
+ candidate
28
+ rescue ProgressSync::Error
29
+ nil
30
+ end
31
+
32
+ def self.verifier
33
+ Rails.application.message_verifier('bible270-progress-sync-link')
34
+ end
35
+
36
+ def self.link_context(reader:, admin:, destination:)
37
+ raise ProgressSync::Unavailable, 'Progress sync migration is not installed' unless ProgressSync.available?
38
+
39
+ membership = Participation.chosen.active.find_by(reader_id: reader.id)
40
+ raise ProgressSync::Conflict, 'This reader must be active in the current run before linking progress' unless membership
41
+
42
+ email = normalized_email(reader.email)
43
+ # Construction validates the allowlist, instance ID, HTTPS URL and secret, without HTTP.
44
+ ProgressSync::Client.new(destination.to_s)
45
+ entry = Bible270.config.progress_sync_destinations.fetch(destination.to_s)
46
+ {
47
+ 'reader_id' => reader.id, 'admin_id' => admin.id,
48
+ 'participation_id' => membership.id, 'generation' => membership.progress_sync_generation,
49
+ 'destination' => destination.to_s, 'destination_url' => (entry[:url] || entry['url']).to_s.chomp('/'),
50
+ 'instance_id' => Bible270.config.progress_sync_instance_id.to_s, 'email' => email
51
+ }
52
+ end
53
+
54
+ def self.normalized_email(email)
55
+ value = email.to_s.strip.downcase
56
+ unless value.bytesize <= 320 && value.match?(%r{\A[^@\s]+@[^@\s]+\z})
57
+ raise ProgressSync::Conflict, 'This reader needs a valid email address before linking progress'
58
+ end
59
+
60
+ value
61
+ end
62
+
63
+ def lookup
64
+ session.delete(CANDIDATE_SESSION_KEY)
65
+ context = self.class.link_context(reader: @reader, admin: current_reader, destination: params[:destination])
66
+ remote = ProgressSync.lookup(destination: context['destination'], email: context['email'])
67
+ unless remote.is_a?(Hash) && self.class.normalized_email(remote['email']) == context['email']
68
+ raise ProgressSync::Conflict, 'Destination account email does not match this reader'
69
+ end
70
+
71
+ # Keep only the authenticated lookup fields, never destination credentials.
72
+ candidate = context.merge('remote' => remote.slice('reader_id', 'participation_id', 'generation', 'name', 'email', 'plan_fingerprint'))
73
+ session[CANDIDATE_SESSION_KEY] = self.class.verifier.generate(candidate, expires_in: 10.minutes, purpose: CANDIDATE_PURPOSE)
74
+ redirect_to_panel
75
+ end
76
+
77
+ def create
78
+ session.delete(CANDIDATE_SESSION_KEY)
79
+ candidate = confirmed_candidate!
80
+ # Match the core's lock order so confirmation and link creation see the same source identity.
81
+ Participation.find(candidate['participation_id']).plan_run.with_lock do
82
+ @reader.with_lock do
83
+ candidate = confirmed_candidate!
84
+ ProgressSync.link!(reader: @reader, destination: candidate['destination'], remote: candidate['remote'],
85
+ expected_participation_id: candidate['participation_id'])
86
+ end
87
+ end
88
+ redirect_to_panel(notice: 'Account linked. Existing progress is unchanged.')
89
+ end
90
+
91
+ def copy
92
+ ensure_available!
93
+ delivery = ProgressSync.copy_existing!(owned_link)
94
+ redirect_to_panel(notice: delivery ? 'Existing progress queued.' : 'There is no existing progress to sync.')
95
+ end
96
+
97
+ def destroy
98
+ ensure_available!
99
+ owned_link.destroy!
100
+ redirect_to_panel(notice: 'Account unlinked. All check-offs are unchanged.')
101
+ end
102
+
103
+ private
104
+
105
+ def load_reader
106
+ @reader = Reader.find(params[:reader_id])
107
+ end
108
+
109
+ def ensure_available!
110
+ raise ProgressSync::Unavailable, 'Progress sync migration is not installed' unless ProgressSync.available?
111
+ end
112
+
113
+ def confirmed_candidate!
114
+ candidate = self.class.candidate_for(params[:candidate], reader: @reader, admin: current_reader)
115
+ unless candidate && params[:destination].to_s == candidate['destination']
116
+ raise ProgressSync::Conflict, 'Account confirmation expired or changed. Find the account again.'
117
+ end
118
+
119
+ candidate
120
+ end
121
+
122
+ def owned_link
123
+ ProgressSyncLink.joins(:participation).where(bible270_participations: { reader_id: @reader.id }).find(params[:id])
124
+ end
125
+
126
+ def redirect_to_panel(**flash)
127
+ redirect_to admin_reader_path(@reader, anchor: 'b270-progress-sync'), status: :see_other, **flash
128
+ end
129
+
130
+ def sync_error(error)
131
+ session.delete(CANDIDATE_SESSION_KEY)
132
+ redirect_to_panel(alert: error.message)
133
+ end
134
+
135
+ def invalid_link(_error)
136
+ session.delete(CANDIDATE_SESSION_KEY)
137
+ redirect_to_panel(alert: 'This account could not be linked. It may already be linked.')
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'bible270/progress_sync'
5
+ require 'bible270/progress_sync/authentication'
6
+
7
+ module Bible270
8
+ class ProgressSyncController < ActionController::API
9
+ Sync = ProgressSync
10
+ Authentication = Sync::Authentication
11
+
12
+ def lookup
13
+ email = @payload['email']
14
+ unless email.is_a?(String) && email.bytesize <= 320 && email.strip.match?(%r{\A[^@\s]+@[^@\s]+\z})
15
+ raise Sync::Conflict, 'A valid reader email is required'
16
+ end
17
+
18
+ email = email.strip.downcase
19
+ # Ambiguity includes archived accounts: do not select one identity merely
20
+ # because the other account with the same address is currently inactive.
21
+ readers = matching_readers(email)
22
+ raise Sync::Conflict, 'No unique active reader matches that email' unless readers.length == 1
23
+
24
+ reader = readers.first
25
+ membership = Participation.chosen.find_by(reader_id: reader.id)
26
+ with_membership_lock(membership, reader.id) do |current|
27
+ unless reader.reload.email.to_s.strip.downcase == email && matching_readers(email).map(&:id) == [reader.id]
28
+ raise Sync::Conflict, 'No unique active reader matches that email'
29
+ end
30
+
31
+ render json: { reader_id: reader.id, participation_id: current.id, generation: current.progress_sync_generation,
32
+ name: reader.display_name, email: email, plan_fingerprint: Sync.fingerprint }
33
+ end
34
+ end
35
+
36
+ def complete
37
+ reader_id = integer!('reader_id', minimum: 1)
38
+ participation_id = integer!('participation_id', minimum: 1)
39
+ generation = integer!('generation', minimum: 0)
40
+ readings = validated_readings!
41
+ membership = Participation.find_by(id: participation_id, reader_id: reader_id)
42
+ with_membership_lock(membership, reader_id) do |current|
43
+ unless current.progress_sync_generation == generation
44
+ raise Sync::Conflict, 'Linked membership changed; explicitly relink'
45
+ end
46
+
47
+ existing = current.checkoffs.pluck(:day, :track, :part).to_set
48
+ missing = readings.reject { |triple| existing.include?(triple) }
49
+ Sync.suppress do
50
+ if missing.any?
51
+ Checkoff.insert_all(missing.map do |day, track, part|
52
+ { reader_id: reader_id, participation_id: current.id, day: day, track: track, part: part }
53
+ end)
54
+ end
55
+ end
56
+ render json: { added: missing.length, existing: readings.length - missing.length }
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ # Authenticate before calling super: ActionController's instrumentation reads
63
+ # filtered_parameters (and therefore parses JSON) before ordinary callbacks.
64
+ def process_action(*)
65
+ authenticate_request!
66
+ return if performed?
67
+
68
+ super
69
+ rescue Sync::Unauthorized
70
+ render json: { error: 'Progress sync authentication failed' }, status: :unauthorized
71
+ rescue Sync::Conflict, ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid
72
+ render json: { error: 'Reader, membership, plan, or completion batch is incompatible' }, status: :conflict
73
+ rescue Sync::Unavailable, Sync::ConfigurationError
74
+ render json: { error: 'Progress sync is unavailable' }, status: :service_unavailable
75
+ rescue JSON::ParserError, EncodingError
76
+ render json: { error: 'Invalid JSON payload' }, status: :bad_request
77
+ end
78
+
79
+ def authenticate_request!
80
+ if request.content_length.to_i > Authentication::MAX_BYTES
81
+ render json: { error: 'Progress sync request is too large' }, status: 413
82
+ return
83
+ end
84
+ body = request.body.read(Authentication::MAX_BYTES + 1)
85
+ request.body.rewind
86
+ if body.bytesize > Authentication::MAX_BYTES
87
+ render json: { error: 'Progress sync request is too large' }, status: 413
88
+ return
89
+ end
90
+ config = Bible270.config
91
+ sources = config.progress_sync_sources if config.respond_to?(:progress_sync_sources)
92
+ Authentication.authenticate!(headers: request.headers, sources: sources, method: request.request_method,
93
+ path: request.original_fullpath.split('?', 2).first, body: body)
94
+ raise Sync::Unavailable, 'Progress sync migration is not installed' unless Sync.available?
95
+
96
+ @payload = JSON.parse(body)
97
+ raise Sync::Conflict, 'A JSON object is required' unless @payload.is_a?(Hash)
98
+ raise Sync::Conflict, 'Reading plans differ' unless @payload['plan_fingerprint'] == Sync.fingerprint
99
+ end
100
+
101
+ def matching_readers(email)
102
+ # SQL LOWER/TRIM differ by adapter and do not match Ruby's normalization
103
+ # for all case mappings and surrounding whitespace. Lookup is infrequent;
104
+ # scan only identity columns in batches and stop once ambiguity is proven.
105
+ Reader.select(:id, :email).find_each.lazy.select do |reader|
106
+ reader.email.to_s.strip.downcase == email
107
+ end.take(2).force
108
+ end
109
+
110
+ def integer!(key, minimum:)
111
+ value = @payload[key]
112
+ raise Sync::Conflict, 'Invalid linked identity' unless value.is_a?(Integer) && value >= minimum
113
+
114
+ value
115
+ end
116
+
117
+ def validated_readings!
118
+ readings = @payload['readings']
119
+ unless readings.is_a?(Array) && readings.length <= 5000
120
+ raise Sync::Conflict, 'A batch must contain at most 5000 readings'
121
+ end
122
+
123
+ readings.each do |triple|
124
+ unless triple.is_a?(Array) && triple.length == 3
125
+ raise Sync::Conflict, 'Readings must be triples'
126
+ end
127
+
128
+ day, track, part = triple
129
+ unless day.is_a?(Integer) && part.is_a?(Integer) && Plan.valid_day?(day) &&
130
+ Plan::TRACKS.key?(track) && Plan.valid_part?(day, track, part)
131
+ raise Sync::Conflict, 'Invalid reading'
132
+ end
133
+ end
134
+ readings.uniq
135
+ end
136
+
137
+ def with_membership_lock(membership, reader_id)
138
+ raise Sync::Conflict, 'Linked membership no longer exists' unless membership
139
+
140
+ PlanRun.find(membership.plan_run_id).with_lock do
141
+ Reader.find(reader_id).with_lock do
142
+ membership.reload
143
+ unless membership.active? && PlanRun.where(id: membership.plan_run_id, current: true).exists? &&
144
+ Participation.chosen.where(id: membership.id).exists? && @payload['plan_fingerprint'] == Sync.fingerprint
145
+ raise Sync::Conflict, 'Linked membership is no longer active or compatible'
146
+ end
147
+
148
+ yield membership
149
+ end
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_job'
4
+ require 'bible270/progress_sync'
5
+
6
+ module Bible270
7
+ class ProgressSyncJob < ActiveJob::Base
8
+ class EnqueueFailure < StandardError; end
9
+
10
+ around_enqueue :sanitize_enqueue_failure
11
+
12
+ def perform(delivery_id)
13
+ return if delivery_id.nil?
14
+
15
+ # Retry timing and claims live in the outbox. The scheduled rake task
16
+ # recovers enqueue failures, expired leases, and transient delivery errors.
17
+ ProgressSync.deliver_pending(delivery_id: delivery_id)
18
+ end
19
+
20
+ private
21
+
22
+ # Active Job's enqueue instrumentation otherwise logs the adapter exception's
23
+ # message before the model can rescue it; that message can contain credentials.
24
+ def sanitize_enqueue_failure
25
+ yield
26
+ self.enqueue_error = EnqueueFailure.new(enqueue_error.class.name) if enqueue_error
27
+ rescue StandardError => e
28
+ raise EnqueueFailure, e.class.name, cause: nil
29
+ end
30
+ end
31
+ end
@@ -10,6 +10,7 @@ module Bible270
10
10
  belongs_to :reader, class_name: 'Bible270::Reader'
11
11
  belongs_to :participation, class_name: 'Bible270::Participation', inverse_of: :checkoffs
12
12
 
13
+ after_create :capture_progress_sync
13
14
  before_validation :assign_participation
14
15
  validate :participation_matches_reader
15
16
  validate :participation_is_writable
@@ -78,6 +79,10 @@ module Bible270
78
79
 
79
80
  private
80
81
 
82
+ def capture_progress_sync
83
+ ProgressSync.capture(participation, [[day, track, part]])
84
+ end
85
+
81
86
  def assign_participation
82
87
  self.participation ||= reader&.participation
83
88
  end
@@ -10,6 +10,8 @@ module Bible270
10
10
  belongs_to :plan_run, class_name: 'Bible270::PlanRun', inverse_of: :participations
11
11
  has_many :checkoffs, class_name: 'Bible270::Checkoff', dependent: :destroy, inverse_of: :participation
12
12
 
13
+ before_update :invalidate_progress_sync_generation
14
+
13
15
  validates :reader_id, uniqueness: { scope: :plan_run_id }
14
16
  validates :joined_at, presence: true
15
17
 
@@ -60,6 +62,14 @@ module Bible270
60
62
  self
61
63
  end
62
64
 
65
+ # Reverting a run or reactivating an alumnus must not silently restore a sync link.
66
+ def invalidate_progress_sync_generation
67
+ return unless has_attribute?(:progress_sync_generation) && will_save_change_to_active? && !active?
68
+
69
+ self.progress_sync_generation += 1
70
+ end
71
+ private :invalidate_progress_sync_generation
72
+
63
73
  def ensure_writable!
64
74
  unless active? && plan_run.current?
65
75
  raise ArchivedProgress, 'Archived progress is read-only; activate the reader in the current run first'
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bible270
4
+ class ProgressSyncDelivery < ApplicationRecord
5
+ self.table_name = 'bible270_progress_sync_deliveries'
6
+
7
+ belongs_to :progress_sync_link, class_name: 'Bible270::ProgressSyncLink', inverse_of: :deliveries
8
+
9
+ after_create_commit :enqueue_immediate_delivery
10
+
11
+ validates :readings, presence: true
12
+ validates :attempts, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
13
+ validates :next_attempt_at, presence: true
14
+
15
+ scope :pending, -> { where(delivered_at: nil) }
16
+ scope :due, ->(now = Time.current) {
17
+ pending.where('next_attempt_at <= ?', now).where('locked_until IS NULL OR locked_until <= ?', now)
18
+ }
19
+
20
+ def delivered? = delivered_at.present?
21
+
22
+ private
23
+
24
+ def enqueue_immediate_delivery
25
+ return unless Bible270.config.progress_sync_deliver_later
26
+
27
+ adapter = ProgressSyncJob.queue_adapter
28
+ if adapter.is_a?(ActiveJob::QueueAdapters::InlineAdapter) || adapter.is_a?(ActiveJob::QueueAdapters::AsyncAdapter)
29
+ warn_delivery_enqueue("Immediate delivery skipped: #{adapter.class.name} is not a durable worker adapter.")
30
+ return
31
+ end
32
+
33
+ unless ProgressSyncJob.perform_later(id)
34
+ warn_delivery_enqueue('Immediate delivery enqueue was not accepted.')
35
+ end
36
+ rescue StandardError => e
37
+ warn_delivery_enqueue("Immediate delivery enqueue failed (#{e.class.name}).")
38
+ end
39
+
40
+ def warn_delivery_enqueue(detail)
41
+ message = "[Bible270] #{detail} Progress sync outbox retained; configure a durable Active Job adapter and worker, " \
42
+ 'and schedule bible270:progress_sync:deliver every minute as fallback.'
43
+ sync_logger = defined?(Rails) && Rails.logger
44
+ sync_logger ||= self.class.logger
45
+ sync_logger ? sync_logger.warn(message) : warn(message)
46
+ rescue StandardError
47
+ # Logging and optional enqueue failures must never invalidate a checkoff.
48
+ nil
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bible270
4
+ class ProgressSyncLink < ApplicationRecord
5
+ self.table_name = 'bible270_progress_sync_links'
6
+
7
+ belongs_to :participation, class_name: 'Bible270::Participation'
8
+ has_many :deliveries, class_name: 'Bible270::ProgressSyncDelivery', dependent: :destroy,
9
+ inverse_of: :progress_sync_link
10
+
11
+ attr_readonly :participation_id, :source_generation, :destination, :destination_url,
12
+ :remote_reader_id, :remote_participation_id, :remote_generation,
13
+ :remote_name, :email, :plan_fingerprint
14
+
15
+ validates :source_generation, :remote_generation, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
16
+ validates :remote_reader_id, :remote_participation_id, numericality: { only_integer: true, greater_than: 0 }
17
+ validates :destination, :destination_url, :remote_name, :email, :plan_fingerprint, presence: true
18
+ validates :state, inclusion: { in: %w[active paused] }
19
+ validates :destination, uniqueness: { scope: :participation_id, conditions: -> { where(state: 'active') } }, if: :active?
20
+
21
+ scope :active, -> { where(state: 'active') }
22
+
23
+ def active? = state == 'active'
24
+ def paused? = state == 'paused'
25
+ def usable? = active? && ProgressSync.link_usable?(self)
26
+ def pending_count = deliveries.where(delivered_at: nil).count
27
+ def delivered_count = deliveries.where.not(delivered_at: nil).count
28
+
29
+ def status
30
+ return 'Needs attention' if paused? || last_error.present? || !usable?
31
+ return 'Pending' if pending_count.positive?
32
+
33
+ last_synced_at ? 'Synced' : 'Ready'
34
+ end
35
+ end
36
+ end
@@ -689,6 +689,7 @@ module Bible270
689
689
  created_at: now, updated_at: now }
690
690
  end
691
691
  )
692
+ ProgressSync.capture(participation, pairs.map { |track, part| [day, track, part] })
692
693
  end
693
694
 
694
695
  def clear_day!(day)
@@ -0,0 +1,92 @@
1
+ <%
2
+ config = Bible270.config
3
+ destinations = config.respond_to?(:progress_sync_destinations) ? config.progress_sync_destinations : {}
4
+ destinations = {} unless destinations.is_a?(Hash)
5
+ schema_available = Bible270::ProgressSync.available?
6
+ links = schema_available ? Bible270::ProgressSyncLink.joins(:participation)
7
+ .where(bible270_participations: { reader_id: @reader.id }).includes(:participation).order(created_at: :desc, id: :desc).to_a : []
8
+ %>
9
+ <% if destinations.any? || links.any? %>
10
+ <section class="b270-panel b270-progress-sync" id="b270-progress-sync" aria-labelledby="b270-progress-sync-heading">
11
+ <h2 class="b270-subhead" id="b270-progress-sync-heading">Progress sync</h2>
12
+ <p class="b270-hint">New check-offs sync one way to an account with the same email.</p>
13
+ <% unless schema_available %>
14
+ <p class="b270-flash alert">Progress sync needs a site update. Contact the site administrator.</p>
15
+ <% else %>
16
+ <% destination_options = destinations.filter_map do |key, entry|
17
+ next unless entry.is_a?(Hash)
18
+ [(entry[:label] || entry['label']).presence || key.to_s, key.to_s]
19
+ end %>
20
+ <% instance_configured = config.respond_to?(:progress_sync_instance_id) && config.progress_sync_instance_id.to_s.strip.present? %>
21
+ <% membership = Bible270::Participation.chosen.active.find_by(reader_id: @reader.id) %>
22
+ <% email_valid = @reader.email.to_s.bytesize <= 320 && @reader.email.to_s.strip.match?(%r{\A[^@\s]+@[^@\s]+\z}) %>
23
+ <% if destination_options.empty? || !instance_configured %>
24
+ <p class="b270-hint">Ask the site administrator to set up progress sync.</p>
25
+ <% elsif !membership %>
26
+ <p class="b270-hint">Make this reader active to link an account.</p>
27
+ <% elsif !email_valid %>
28
+ <p class="b270-hint">Add a valid email address to find an account.</p>
29
+ <% else %>
30
+ <% candidate_token = session[Bible270::AdminProgressSyncsController::CANDIDATE_SESSION_KEY] %>
31
+ <% candidate = Bible270::AdminProgressSyncsController.candidate_for(candidate_token, reader: @reader, admin: current_reader) %>
32
+ <%= form_with url: lookup_admin_reader_progress_sync_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
33
+ <label class="b270-field" for="b270-progress-sync-destination">Destination</label>
34
+ <span class="b270-select-wrap b270-select-wrap--full">
35
+ <%= select_tag :destination, options_for_select(destination_options, candidate && candidate['destination']),
36
+ id: 'b270-progress-sync-destination', class: 'b270-select' %>
37
+ </span>
38
+ <%= submit_tag 'Find account', class: 'b270-btn' %>
39
+ <% end %>
40
+ <% if candidate %>
41
+ <% remote = candidate.fetch('remote') %>
42
+ <div class="b270-progress-sync-candidate">
43
+ <p><strong><%= remote['name'] %></strong> · <%= remote['email'] %></p>
44
+ <p class="b270-hint">Confirm this account. Existing progress is copied only when requested.</p>
45
+ <%= form_with url: admin_reader_progress_syncs_path(@reader), method: :post, local: true, class: 'b270-emailform' do %>
46
+ <%= hidden_field_tag :candidate, candidate_token %>
47
+ <%= hidden_field_tag :destination, candidate['destination'] %>
48
+ <%= submit_tag 'Link account', class: 'b270-btn' %>
49
+ <% end %>
50
+ </div>
51
+ <% end %>
52
+ <% end %>
53
+
54
+ <% if links.empty? %>
55
+ <p class="b270-hint">No linked accounts.</p>
56
+ <% else %>
57
+ <ul class="b270-progress-sync-links">
58
+ <% links.each do |link| %>
59
+ <% entry = destinations[link.destination] %>
60
+ <% label = entry.is_a?(Hash) ? ((entry[:label] || entry['label']).presence || link.destination) : link.destination %>
61
+ <li class="b270-progress-sync-link">
62
+ <p><strong><%= label %></strong> · <%= link.remote_name %> · <%= link.status %></p>
63
+ <p class="b270-hint">
64
+ Run <%= link.participation.plan_run_id %> ·
65
+ Last synced: <%= link.last_synced_at ? link.last_synced_at.strftime('%b %-d, %Y %H:%M %Z') : 'Never' %> ·
66
+ Pending: <%= link.pending_count %>
67
+ <% unless link.last_added.nil? || link.last_existing.nil? %>
68
+ · <%= link.last_added %> added; <%= link.last_existing %> already present
69
+ <% end %>
70
+ </p>
71
+ <% if link.last_error.present? %>
72
+ <p class="b270-flash alert"><%= link.last_error %></p>
73
+ <% end %>
74
+ <% usable = link.usable? %>
75
+ <% unless usable %>
76
+ <p class="b270-hint">Find and link the account again to resume syncing.</p>
77
+ <% end %>
78
+ <div class="b270-progress-sync-actions">
79
+ <% if usable %>
80
+ <%= button_to 'Sync existing progress', copy_admin_reader_progress_sync_path(@reader, link), method: :post,
81
+ class: 'b270-btn', form: { class: 'b270-admin-inline-form', data: { b270_admin_confirm: 'Sync existing progress? Only missing check-offs will be added. Nothing will be removed.' } } %>
82
+ <% end %>
83
+ <%= button_to 'Unlink', admin_reader_progress_sync_path(@reader, link), method: :delete,
84
+ class: 'b270-btn', form: { class: 'b270-admin-inline-form', data: { b270_admin_confirm: 'Unlink this account? Queued syncs will stop. All check-offs will remain.' } } %>
85
+ </div>
86
+ </li>
87
+ <% end %>
88
+ </ul>
89
+ <% end %>
90
+ <% end %>
91
+ </section>
92
+ <% end %>