spree_cm_commissioner 2.14.4 → 2.14.6

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 (72) hide show
  1. checksums.yaml +4 -4
  2. data/.env.example +7 -1
  3. data/Gemfile.lock +1 -1
  4. data/app/controllers/concerns/spree_cm_commissioner/content_cachable.rb +59 -3
  5. data/app/controllers/concerns/spree_cm_commissioner/waiting_room_authorization.rb +41 -8
  6. data/app/controllers/spree/admin/api_caches_controller.rb +23 -8
  7. data/app/controllers/spree/admin/homepage_section_controller.rb +63 -5
  8. data/app/controllers/spree/admin/homepage_section_relatable_controller.rb +24 -0
  9. data/app/controllers/spree/api/v2/organizer/invite_guests_controller.rb +2 -2
  10. data/app/controllers/spree/api/v2/resource_controller_decorator.rb +8 -0
  11. data/app/controllers/spree/api/v2/storefront/draft_orders_controller.rb +6 -2
  12. data/app/controllers/spree/api/v2/storefront/homepage_sections_controller.rb +1 -0
  13. data/app/controllers/spree/api/v2/storefront/invite_guests_controller.rb +2 -2
  14. data/app/controllers/spree/api/v2/storefront/preview_sections_controller.rb +1 -0
  15. data/app/controllers/spree/api/v2/storefront/queue_draft_orders_controller.rb +6 -2
  16. data/app/controllers/spree/api/v2/storefront/trip_search_controller.rb +18 -13
  17. data/app/controllers/spree/api/v2/storefront/user_contacts_controller.rb +2 -0
  18. data/app/controllers/spree/api/v2/tenant/draft_orders_controller.rb +6 -2
  19. data/app/controllers/spree/api/v2/tenant/homepage_sections_controller.rb +1 -0
  20. data/app/controllers/spree/api/v2/tenant/preview_sections_controller.rb +1 -0
  21. data/app/controllers/spree/api/v2/tenant/trip_search_controller.rb +18 -13
  22. data/app/factory/spree_cm_commissioner/order_telegram_message_factory.rb +5 -1
  23. data/app/helpers/spree_cm_commissioner/admin/homepage_segment_helper.rb +28 -0
  24. data/app/interactors/spree_cm_commissioner/account_recover.rb +23 -2
  25. data/app/interactors/spree_cm_commissioner/firebase_id_token_provider.rb +6 -2
  26. data/app/interactors/spree_cm_commissioner/telegram_chats_auto_finder.rb +26 -2
  27. data/app/interactors/spree_cm_commissioner/telegram_chats_finder.rb +1 -1
  28. data/app/interactors/spree_cm_commissioner/user_telegram_oauth_authenticator.rb +2 -11
  29. data/app/models/active_storage/variation_decorator.rb +18 -0
  30. data/app/models/concerns/spree_cm_commissioner/event_metadata.rb +4 -0
  31. data/app/models/concerns/spree_cm_commissioner/order_holdable.rb +3 -2
  32. data/app/models/concerns/spree_cm_commissioner/order_state_machine.rb +18 -13
  33. data/app/models/spree_cm_commissioner/homepage_section.rb +33 -0
  34. data/app/models/spree_cm_commissioner/homepage_section_app_background.rb +13 -0
  35. data/app/models/spree_cm_commissioner/homepage_section_web_background.rb +13 -0
  36. data/app/models/spree_cm_commissioner/maintenance_tasks/cache_invalidation.rb +95 -11
  37. data/app/models/spree_cm_commissioner/pin_code.rb +2 -1
  38. data/app/models/spree_cm_commissioner/pin_code_event_telegram.rb +31 -0
  39. data/app/models/spree_cm_commissioner/product_decorator.rb +7 -0
  40. data/app/models/spree_cm_commissioner/service_calendar.rb +2 -2
  41. data/app/models/spree_cm_commissioner/taxon_decorator.rb +7 -0
  42. data/app/models/spree_cm_commissioner/vendor_decorator.rb +6 -0
  43. data/app/overrides/spree/admin/taxons/_form/enforce_waiting_room_session.html.erb.deface +10 -0
  44. data/app/queries/spree_cm_commissioner/trip_query.rb +20 -2
  45. data/app/serializers/spree/v2/storefront/homepage_section_serializer.rb +4 -1
  46. data/app/serializers/spree/v2/tenant/homepage_section_serializer.rb +3 -1
  47. data/app/services/spree_cm_commissioner/api_caches/fetch_details.rb +128 -0
  48. data/app/services/spree_cm_commissioner/api_caches/invalidate.rb +31 -14
  49. data/app/services/spree_cm_commissioner/api_caches/invalidate_all.rb +16 -19
  50. data/app/services/spree_cm_commissioner/api_caches/request_clear.rb +71 -0
  51. data/app/services/spree_cm_commissioner/guests/claim_invite_guest_service.rb +5 -3
  52. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_service_calendars.rb +3 -0
  53. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trip_stop.rb +21 -4
  54. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trips.rb +30 -4
  55. data/app/services/spree_cm_commissioner/inventory_items/bulk_generate_permanent_items.rb +15 -4
  56. data/app/services/spree_cm_commissioner/line_items/validate_purchase_limits.rb +56 -5
  57. data/app/services/spree_cm_commissioner/telegram/verify_oauth_id_token.rb +10 -0
  58. data/app/services/spree_cm_commissioner/telegram_alerts/send_telegram_order_alerts.rb +49 -0
  59. data/app/views/spree/admin/api_caches/_dialog.html.erb +47 -0
  60. data/app/views/spree/admin/api_caches/show.html.erb +88 -0
  61. data/app/views/spree/admin/homepage_section/_form.html.erb +44 -0
  62. data/app/views/spree/admin/homepage_section/edit.html.erb +16 -1
  63. data/app/views/spree/admin/shared/_api_cache_button.html.erb +5 -2
  64. data/config/initializers/spree_permitted_attributes.rb +1 -0
  65. data/config/locales/dry_validations.en.yml +4 -0
  66. data/config/locales/en.yml +50 -0
  67. data/config/locales/km.yml +50 -0
  68. data/config/routes.rb +8 -4
  69. data/db/migrate/20261021000001_add_section_type_to_cm_homepage_sections.rb +6 -0
  70. data/lib/spree_cm_commissioner/version.rb +1 -1
  71. metadata +13 -3
  72. data/app/jobs/spree_cm_commissioner/invalidate_cache_request_job.rb +0 -10
@@ -13,16 +13,34 @@ module SpreeCmCommissioner
13
13
  @options = options
14
14
  end
15
15
 
16
+ # Every matching trip, unless the client asks for pages with `per_page`: the apps sort and filter the full
17
+ # list locally, so a default page size would silently drop trips (Kaminari.paginate_array cuts to 25).
16
18
  def call
17
- return Kaminari.paginate_array([]) if date.to_date < Date.current
19
+ return [] if date.to_date < Date.current
18
20
 
19
21
  result = direct_trips
20
22
  result += multi_leg_trips if result.empty? || result.size < 3 || ActiveModel::Type::Boolean.new.cast(@options[:include_multi_leg])
21
- Kaminari.paginate_array(result)
23
+ preload_vehicle_type_assets(result)
24
+ paginate(result)
22
25
  end
23
26
 
24
27
  private
25
28
 
29
+ def paginate(result)
30
+ return result if options[:per_page].blank?
31
+
32
+ Kaminari.paginate_array(result).page(options[:page]).per(options[:per_page])
33
+ end
34
+
35
+ # The serializer reads each vehicle type's photos and option types; loading them once here avoids a pair of
36
+ # queries per distinct vehicle type.
37
+ def preload_vehicle_type_assets(result)
38
+ vehicle_types = result.flat_map(&:trips).filter_map(&:vehicle_type).uniq
39
+ return if vehicle_types.empty?
40
+
41
+ ActiveRecord::Associations::Preloader.new(records: vehicle_types, associations: %i[vehicle_photos option_types]).call
42
+ end
43
+
26
44
  def direct_trips
27
45
  SpreeCmCommissioner::SingleLegTripsQuery.new(
28
46
  origin_id: origin_id,
@@ -2,8 +2,11 @@ module Spree
2
2
  module V2
3
3
  module Storefront
4
4
  class HomepageSectionSerializer < BaseSerializer
5
- attributes :id, :title, :segments, :mini_apps, :description, :active, :position, :preview, :created_at, :updated_at
5
+ attributes :id, :title, :segments, :mini_apps, :description, :active, :position, :preview,
6
+ :section_type, :font, :created_at, :updated_at
6
7
  has_many :homepage_section_relatables
8
+ has_one :app_background, serializer: ::SpreeCmCommissioner::V2::Storefront::AssetSerializer
9
+ has_one :web_background, serializer: ::SpreeCmCommissioner::V2::Storefront::AssetSerializer
7
10
  end
8
11
  end
9
12
  end
@@ -3,9 +3,11 @@ module Spree
3
3
  module Tenant
4
4
  class HomepageSectionSerializer < BaseSerializer
5
5
  attributes :id, :title, :segments, :description,
6
- :active, :position, :preview, :created_at, :updated_at
6
+ :active, :position, :preview, :section_type, :font, :created_at, :updated_at
7
7
 
8
8
  has_many :homepage_section_relatables, serializer: ::Spree::V2::Tenant::HomepageSectionRelatableSerializer
9
+ has_one :app_background, serializer: ::Spree::V2::Tenant::AssetSerializer
10
+ has_one :web_background, serializer: ::Spree::V2::Tenant::AssetSerializer
9
11
  end
10
12
  end
11
13
  end
@@ -0,0 +1,128 @@
1
+ module SpreeCmCommissioner
2
+ module ApiCaches
3
+ # Everything the clear-cache dialog shows, for the Spree admin (spree/admin/api_caches/show) and
4
+ # the cm-market-server dashboard (shared_console/api_caches/show), which style it separately. Only called when the
5
+ # dialog opens, never on page render. Takes the same model/id/tenant as RequestClear.
6
+ #
7
+ # eg. FetchDetails.call(model: 'Spree::Product', id: 123)
8
+ # => success(state: :edited, edited_at:, refresh_seconds:, sends_by:, sent_at:, cooldown_until:,
9
+ # failure:, busy:, history:, patterns:)
10
+ #
11
+ # state, the dialog's headline, leans towards waiting since every clear is a paid CloudFront
12
+ # invalidation:
13
+ # :queued a clear someone asked for is waiting to be sent.
14
+ # :pending an automatic clear (queued on save, including a linked record's save) is waiting
15
+ # for OrchestrateJob, which sends it by sends_by.
16
+ # :edited edited after the last sent clear, less than a CDN TTL ago: the app may still show
17
+ # the old version.
18
+ # :sent a clear was sent after the last edit, within the last CDN TTL.
19
+ # :up_to_date otherwise: any copy cached before the last edit has expired or been cleared.
20
+ #
21
+ # cooldown_until is a CDN TTL after the last sent clear: edits made since then show in the app on
22
+ # their own by that time anyway, so RequestClear refuses another clear before it for callers
23
+ # asked to apply it (dashboard users who aren't admins).
24
+ class FetchDetails
25
+ prepend ::Spree::ServiceModule::Base
26
+
27
+ HISTORY_LIMIT = 5
28
+
29
+ # Clear-alls of every model share their storefront as maintainable (CacheInvalidation), so more
30
+ # are read than shown and the rest filtered by model.
31
+ CLEAR_ALL_SCAN_LIMIT = HISTORY_LIMIT * 4
32
+
33
+ # An automatic task is due 5 minutes after it was queued (MaintenanceTask.due_for_retry) and
34
+ # picked up by OrchestrateJob, scheduled every 5 minutes in cm-market-server's schedule.yml.
35
+ AUTOMATIC_SEND_WITHIN = 10.minutes
36
+
37
+ def call(model:, id: nil, tenant: nil)
38
+ maintainable = MaintenanceTasks::CacheInvalidation.maintainable_for(model: model, id: id, tenant: tenant)
39
+ return failure(nil, "#{[model, id].compact.join(' ')} cannot be cleared") if maintainable.nil?
40
+
41
+ model_class = Invalidate::SUPPORTED_MODELS[model]
42
+ tasks = MaintenanceTasks::CacheInvalidation.where(maintainable: maintainable).order(created_at: :desc)
43
+
44
+ if id.present?
45
+ tasks = tasks.limit(HISTORY_LIMIT).to_a
46
+ patterns = Invalidate.new.patterns_for(maintainable, model_class: model_class)
47
+ edited_at = maintainable.updated_at
48
+ else
49
+ tasks = tasks.limit(CLEAR_ALL_SCAN_LIMIT).select { |task| task.target_model == model }.first(HISTORY_LIMIT)
50
+ patterns = InvalidateAll.new.patterns_for(model, tenant: tenant)
51
+ edited_at = InvalidateAll.new.records_scope(model_class, tenant).maximum(:updated_at)
52
+ end
53
+
54
+ success(**headline(tasks, edited_at), history: history(tasks), patterns: patterns)
55
+ end
56
+
57
+ private
58
+
59
+ def headline(tasks, edited_at)
60
+ latest = tasks.first
61
+ ttl = ContentCachable.cdn_max_age(:fresh)
62
+ sent = tasks.find { |task| task.clear_status == :sent }
63
+ pending = latest if automatic_pending?(latest)
64
+ cooldown_until = sent && (sent.completed_at + ttl)
65
+
66
+ {
67
+ state: state_for(latest, pending, edited_at, sent, ttl),
68
+ edited_at: edited_at,
69
+ refresh_seconds: ttl,
70
+ sends_by: pending && (pending.updated_at + AUTOMATIC_SEND_WITHIN),
71
+ sent_at: sent&.completed_at,
72
+ cooldown_until: (cooldown_until if cooldown_until&.future?),
73
+ failure: failure_of(latest),
74
+ busy: busy?(latest)
75
+ }
76
+ end
77
+
78
+ def state_for(latest, pending, edited_at, sent, ttl)
79
+ return :pending if pending
80
+ return :queued if latest&.clear_status == :queued
81
+
82
+ freshness_state(edited_at, sent, ttl)
83
+ end
84
+
85
+ def freshness_state(edited_at, sent, ttl)
86
+ # The task touched the record before sending, so an edit it covers has updated_at <= the
87
+ # task's completed_at.
88
+ covered = sent.present? && (edited_at.nil? || edited_at <= sent.completed_at)
89
+ return :edited if edited_at.present? && !covered && edited_at > ttl.seconds.ago
90
+ return :sent if covered && sent.completed_at > ttl.seconds.ago
91
+
92
+ :up_to_date
93
+ end
94
+
95
+ # A save queued it and nobody has clicked since. With automatic invalidation switched off it
96
+ # would only be skipped, so it promises nothing.
97
+ def automatic_pending?(task)
98
+ task&.clear_status == :queued && !task.manually_triggered? && ENV['CACHE_AUTO_INVALIDATION_DISABLED'] != 'yes'
99
+ end
100
+
101
+ # A clear someone asked for, which another click would only reuse. An automatic one waiting for
102
+ # OrchestrateJob, or a queued one that already failed once, is sent now by a click.
103
+ def busy?(latest)
104
+ latest&.clear_status == :queued && latest.manually_triggered? && latest.last_error.blank?
105
+ end
106
+
107
+ # Why the latest clear didn't (or hasn't yet) gone through.
108
+ def failure_of(task)
109
+ task.last_error.presence if %i[failed queued].include?(task&.clear_status)
110
+ end
111
+
112
+ def history(tasks)
113
+ users = Spree.user_class.where(id: tasks.filter_map(&:triggered_by_id).uniq).index_by(&:id)
114
+
115
+ tasks.map do |task|
116
+ { at: task.created_at, by: triggered_by_name(task, users), status: task.clear_status, error: failure_of(task) }
117
+ end
118
+ end
119
+
120
+ def triggered_by_name(task, users)
121
+ scope = 'spree_cm_commissioner.api_caches.details'
122
+ return I18n.t('automatic', scope: scope) unless task.manually_triggered?
123
+
124
+ users[task.triggered_by_id]&.display_name.presence || I18n.t('unknown_user', scope: scope)
125
+ end
126
+ end
127
+ end
128
+ end
@@ -1,9 +1,17 @@
1
1
  module SpreeCmCommissioner
2
2
  module ApiCaches
3
- # Clears one record's cached API responses. Every record of a model goes through InvalidateAll.
3
+ # Refreshes one record's Rails cache keys and returns the CloudFront paths that serve it, which
4
+ # MaintenanceTasks::CacheInvalidation sends. Every record of a model goes through InvalidateAll.
5
+ #
6
+ # Only the record's own storefront is cleared, as InvalidateAll does: its tenant's API
7
+ # (/api/v2/tenant/ paths) when it belongs to a tenant, the BookMe+ storefront otherwise. Each path
8
+ # is billed, and the other storefront's copy, if anything ever fetched one, expires within a CDN
9
+ # TTL anyway.
4
10
  class Invalidate
5
11
  prepend ::Spree::ServiceModule::Base
6
12
 
13
+ TENANT_PREFIX = '/api/v2/tenant/'.freeze
14
+
7
15
  SUPPORTED_MODELS = {
8
16
  'SpreeCmCommissioner::HomepageSection' => SpreeCmCommissioner::HomepageSection,
9
17
  'SpreeCmCommissioner::HomepageBackground' => SpreeCmCommissioner::HomepageBackground,
@@ -27,11 +35,11 @@ module SpreeCmCommissioner
27
35
 
28
36
  HOMEPAGE_BACKGROUND_PATTERNS = ['/api/v2/storefront/homepage*'].freeze
29
37
 
30
- # Deliberately broad, and identical for single-record and all-record
31
- # invalidation: a payment method is either vendor-owned or store-level, and a
32
- # store-level one is served for every vendor through the fallback in
33
- # SpreeCmCommissioner::PaymentMethods::Find. From the record alone we cannot
34
- # tell which vendors are affected.
38
+ # Deliberately broad, identical for single-record and all-record invalidation, and the one
39
+ # model not scoped to the record's storefront: a payment method is either vendor-owned or
40
+ # store-level, and a store-level one is served for every vendor, tenants included, through the
41
+ # fallback in SpreeCmCommissioner::PaymentMethods::Find. From the record alone we cannot tell
42
+ # which vendors are affected.
35
43
  #
36
44
  # vendor_id is a query param, so the trailing `*` is what clears every
37
45
  # vendor's cached variant of this path in one go.
@@ -61,19 +69,33 @@ module SpreeCmCommissioner
61
69
 
62
70
  refresh_record_cache_key(record)
63
71
 
72
+ success(record: record, api_patterns: patterns_for(record, model_class: model_class))
73
+ end
74
+
75
+ # Side-effect free, so the clear-cache dialog can show what a clear would send. Empty when the
76
+ # record's storefront has no API for it, e.g. a show of a vendor without a tenant.
77
+ # eg. patterns_for(product) => ['/api/v2/storefront/products/123*', '/api/v2/storefront/products/slug-of-product*']
78
+ def patterns_for(record, model_class: record.class)
64
79
  # The record's own class first (a Show found as a Spree::Taxon keeps its show paths), then the
65
80
  # model asked for, since STI subclasses such as Spree::Gateway::Payway have no entry of their own.
66
81
  patterns = single_api_pattern[record.class.name] || single_api_pattern[model_class.name]
67
- api_patterns = patterns.map do |pattern|
82
+ return patterns if patterns.equal?(PAYMENT_METHOD_PATTERNS)
83
+
84
+ tenant = tenant_of(record)
85
+ patterns.select { |pattern| pattern.start_with?(TENANT_PREFIX) == tenant.present? }.map do |pattern|
68
86
  pattern.gsub(/:(\w+)/) do
69
87
  key = Regexp.last_match(1)
70
88
  record.public_send(key).to_s
71
89
  end
72
90
  end
91
+ end
73
92
 
74
- enqueue_invalidate(api_patterns)
93
+ # A product, vendor or homepage section has its own tenant; a taxon, show or voting session has
94
+ # its vendor's. Menus, seat layouts and homepage backgrounds are BookMe+ only.
95
+ def tenant_of(record)
96
+ return record.tenant if record.respond_to?(:tenant)
75
97
 
76
- success(record: record, api_patterns: api_patterns)
98
+ record.vendor&.tenant if record.respond_to?(:vendor)
77
99
  end
78
100
 
79
101
  def single_api_pattern
@@ -117,11 +139,6 @@ module SpreeCmCommissioner
117
139
  record.touch
118
140
  # rubocop:enable Rails/SkipsModelValidations
119
141
  end
120
-
121
- # Enqueue cache invalidation jobs
122
- def enqueue_invalidate(patterns)
123
- SpreeCmCommissioner::InvalidateCacheRequestJob.perform_later(patterns: patterns)
124
- end
125
142
  end
126
143
  end
127
144
  end
@@ -1,8 +1,10 @@
1
1
  module SpreeCmCommissioner
2
2
  module ApiCaches
3
- # Clears every record of a model for one storefront. `tenant` is required so a clear-all never
4
- # pays for both namespaces by accident: nil is the BookMe+ storefront (/api/v2/storefront/
5
- # paths), a SpreeCmCommissioner::Tenant is that tenant's API (/api/v2/tenant/ paths).
3
+ # Refreshes every record of a model for one storefront and returns the CloudFront paths that
4
+ # serve them, which MaintenanceTasks::CacheInvalidation sends, as for Invalidate. `tenant` is
5
+ # required so a clear-all never pays for both namespaces by accident: nil is the BookMe+
6
+ # storefront (/api/v2/storefront/ paths), a SpreeCmCommissioner::Tenant is that tenant's API
7
+ # (/api/v2/tenant/ paths).
6
8
  #
7
9
  # Tenant APIs take the tenant from the OAuth token, not the URL, so every tenant shares one path
8
10
  # today; taking the record keeps callers the same if tenant paths ever carry it.
@@ -11,8 +13,6 @@ module SpreeCmCommissioner
11
13
  class InvalidateAll
12
14
  prepend ::Spree::ServiceModule::Base
13
15
 
14
- TENANT_PREFIX = '/api/v2/tenant/'.freeze
15
-
16
16
  API_PATTERNS = {
17
17
  'SpreeCmCommissioner::HomepageSection' => Invalidate::HOMEPAGE_SECTION_PATTERNS,
18
18
  'SpreeCmCommissioner::HomepageBackground' => Invalidate::HOMEPAGE_BACKGROUND_PATTERNS,
@@ -36,25 +36,22 @@ module SpreeCmCommissioner
36
36
  return failure(nil, 'Model is not supported') if model_class.nil?
37
37
  return failure(nil, 'tenant must be a SpreeCmCommissioner::Tenant or nil') unless tenant.nil? || tenant.is_a?(SpreeCmCommissioner::Tenant)
38
38
 
39
- refresh_records_cache_key(model_class, tenant)
40
-
41
- api_patterns = API_PATTERNS[model].select { |pattern| pattern.start_with?(TENANT_PREFIX) == tenant.present? }
42
-
43
- # Empty when the model has no API in this namespace, e.g. homepage backgrounds for a tenant,
44
- # and CloudFront rejects an empty batch.
45
- SpreeCmCommissioner::InvalidateCacheRequestJob.perform_later(patterns: api_patterns) if api_patterns.any?
39
+ records_scope(model_class, tenant).find_each(&:touch)
46
40
 
47
- success(api_patterns: api_patterns)
41
+ # Empty when the model has no API in this namespace, e.g. homepage backgrounds for a tenant.
42
+ success(api_patterns: patterns_for(model, tenant: tenant))
48
43
  end
49
44
 
50
- private
45
+ # Side-effect free, so the clear-cache dialog can show what a clear would send.
46
+ def patterns_for(model, tenant:)
47
+ API_PATTERNS.fetch(model, []).select { |pattern| pattern.start_with?(Invalidate::TENANT_PREFIX) == tenant.present? }
48
+ end
51
49
 
52
50
  # updated_at keys Spree's serializer and collection caches, so only this storefront's records
53
- # are touched when the model is tenant-scoped.
54
- def refresh_records_cache_key(model_class, tenant)
55
- scope = model_class.column_names.include?('tenant_id') ? model_class.where(tenant_id: tenant&.id) : model_class.all
56
-
57
- scope.find_each(&:touch)
51
+ # are touched when the model is tenant-scoped. Also where the clear-cache dialog reads the last
52
+ # edit from.
53
+ def records_scope(model_class, tenant)
54
+ model_class.column_names.include?('tenant_id') ? model_class.where(tenant_id: tenant&.id) : model_class.all
58
55
  end
59
56
  end
60
57
  end
@@ -0,0 +1,71 @@
1
+ module SpreeCmCommissioner
2
+ module ApiCaches
3
+ # What a clear-cache button calls. It records the click as a CacheInvalidation task and enqueues
4
+ # it, so the click returns at once and shows in the record's history (FetchDetails).
5
+ #
6
+ # Without id it clears every record of model on one storefront, as InvalidateAll: tenant for that
7
+ # tenant's API, nil for the BookMe+ storefront.
8
+ #
9
+ # cooldown: refuses a clear within a CDN TTL of the last one sent (FetchDetails#cooldown_until),
10
+ # for callers that limit how often their users pay for one.
11
+ #
12
+ # eg. RequestClear.call(model: 'Spree::Product', id: 123, user: current_user)
13
+ # RequestClear.call(model: 'SpreeCmCommissioner::HomepageSection', tenant: tenant, user: current_user, cooldown: true)
14
+ class RequestClear
15
+ prepend ::Spree::ServiceModule::Base
16
+
17
+ def call(model:, user:, id: nil, tenant: nil, cooldown: false)
18
+ maintainable = MaintenanceTasks::CacheInvalidation.maintainable_for(model: model, id: id, tenant: tenant)
19
+ return failure(nil, "#{[model, id].compact.join(' ')} cannot be cleared") if maintainable.nil?
20
+
21
+ cooldown_until = cooldown && FetchDetails.call(model: model, id: id, tenant: tenant).value[:cooldown_until]
22
+ return failure(nil, I18n.t('spree_cm_commissioner.api_caches.cooldown', time: I18n.l(cooldown_until, format: '%H:%M'))) if cooldown_until
23
+
24
+ task = find_or_create_task(maintainable, model: model, user: user)
25
+ return failure(nil, I18n.t('spree_cm_commissioner.api_caches.another_clear_in_progress')) if task.target_model != model
26
+
27
+ task.async_execute
28
+ success(task: task)
29
+ end
30
+
31
+ private
32
+
33
+ # index_unique_pending_maintenance_tasks allows one pending task per maintainable, which is also
34
+ # what stops a double click from paying twice: the second click reuses the first one's task.
35
+ def find_or_create_task(maintainable, model:, user:)
36
+ task = pending_task(maintainable)
37
+ return reuse(task, model, user) if task.present?
38
+
39
+ MaintenanceTasks::CacheInvalidation.create!(
40
+ maintainable: maintainable,
41
+ manually_triggered: true,
42
+ triggered_by_id: user&.id,
43
+ invalidation_model: model
44
+ )
45
+ rescue ActiveRecord::RecordNotUnique
46
+ reuse(pending_task(maintainable), model, user)
47
+ end
48
+
49
+ def pending_task(maintainable)
50
+ MaintenanceTasks::CacheInvalidation.pending.find_by(maintainable: maintainable)
51
+ end
52
+
53
+ # A pending task is either an automatic one still waiting for OrchestrateJob, which the click
54
+ # sends now and takes credit for, or a clear-all of the same storefront. One for another model
55
+ # is left alone, and the caller reports it is busy.
56
+ def reuse(task, model, user)
57
+ return task if task.invalidate_all? && task.target_model != model
58
+
59
+ task.update!(
60
+ manually_triggered: true,
61
+ triggered_by_id: user&.id || task.triggered_by_id,
62
+ invalidation_model: model,
63
+ attempt_count: 0,
64
+ last_error: nil
65
+ )
66
+
67
+ task
68
+ end
69
+ end
70
+ end
71
+ end
@@ -44,8 +44,10 @@ module SpreeCmCommissioner
44
44
 
45
45
  # Telegram Alert
46
46
  def send_claim_alert(guest, order)
47
- vendor = guest.event&.vendor
48
- return unless vendor&.preferred_telegram_chat_id
47
+ chat_id = guest.event&.telegram_alert_chat_id || guest.event&.vendor&.preferred_telegram_chat_id
48
+ return if chat_id.blank?
49
+
50
+ vendor = guest.event.vendor
49
51
 
50
52
  factory = SpreeCmCommissioner::InviteGuestClaimedTelegramMessageFactory.new(
51
53
  title: '📣 --- [NEW GUEST CLAIMED INVITATION] ---',
@@ -55,7 +57,7 @@ module SpreeCmCommissioner
55
57
  )
56
58
 
57
59
  SpreeCmCommissioner::TelegramNotificationSenderJob.perform_later(
58
- chat_id: vendor.preferred_telegram_chat_id,
60
+ chat_id: chat_id,
59
61
  message: factory.message,
60
62
  parse_mode: factory.parse_mode
61
63
  )
@@ -25,6 +25,9 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
25
25
  end_date: parse_date(calendar_data['end_date']),
26
26
  exception_rules: build_exception_rules(calendar_data['service_exception_rules'])
27
27
  )
28
+ # Before the change check: left to before_save, a blank date would count as a change on every poll and
29
+ # regenerate this trip's inventory each time.
30
+ service_calendar.set_dates
28
31
  tracker.save_if_changed!(service_calendar)
29
32
  end
30
33
 
@@ -38,6 +38,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
38
38
  stop_times = trip_mapping.external_payload&.dig('stop_times')
39
39
  return [] unless stop_times.is_a?(Array)
40
40
 
41
+ previous_time = nil
42
+
41
43
  synced_mappings = stop_times.each_with_index.map do |stop_time_data, index|
42
44
  # BookMeBus's stop_times[i]['arrival_time'] is the time the trip arrives at the NEXT
43
45
  # physical stop (i+1), not at stop i itself - it's 0/absent on the last entry, which has
@@ -50,7 +52,15 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
50
52
  # missing' on every booking attempt - never caught by specs because their fixtures set
51
53
  # arrival_time == departure_time on the same entry, sidestepping the real shape.
52
54
  incoming_arrival_time = index.positive? ? stop_times[index - 1]['arrival_time'] : nil
53
- sync_item!(trip_mapping, stop_time_data, incoming_arrival_time, index + 1, stop_times.size)
55
+
56
+ # BookMeBus sends time-of-day only, so an overnight trip (23:00 -> 05:00) needs its days rolled
57
+ # here: TransitOrder::Create trusts the stored datetimes and raises when arrival < departure.
58
+ arrival_time = roll_forward(parse_time(incoming_arrival_time), previous_time)
59
+ departure_time = roll_forward(parse_time(stop_time_data['departure_time']), arrival_time || previous_time)
60
+ previous_time = departure_time || arrival_time || previous_time
61
+
62
+ times = { arrival_time: arrival_time, departure_time: departure_time }
63
+ sync_item!(trip_mapping, stop_time_data, times, index + 1, stop_times.size)
54
64
  end.compact
55
65
 
56
66
  cleanup_stale_mappings!(trip_mapping, synced_mappings)
@@ -82,7 +92,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
82
92
  end
83
93
 
84
94
  # Sync a single trip stop
85
- def sync_item!(trip_mapping, stop_time_data, incoming_arrival_time, sequence, total_stops)
95
+ def sync_item!(trip_mapping, stop_time_data, times, sequence, total_stops)
86
96
  stop_data = stop_time_data['stop']
87
97
  location_data = stop_time_data['location']
88
98
  return nil unless stop_data.is_a?(Hash) && location_data.is_a?(Hash)
@@ -119,8 +129,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
119
129
  # BookMeBus returns one entry per search.
120
130
  allow_boarding: sequence == 1,
121
131
  allow_drop_off: sequence == total_stops,
122
- departure_time: parse_time(stop_time_data['departure_time']),
123
- arrival_time: parse_time(incoming_arrival_time)
132
+ departure_time: times[:departure_time],
133
+ arrival_time: times[:arrival_time]
124
134
  )
125
135
  tracker.save_if_changed!(trip_stop)
126
136
  end
@@ -206,6 +216,13 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
206
216
  mapping&.internal
207
217
  end
208
218
 
219
+ def roll_forward(time, not_before)
220
+ return time if time.nil? || not_before.nil?
221
+
222
+ time += 1.day while time < not_before
223
+ time
224
+ end
225
+
209
226
  def parse_time(seconds_from_midnight)
210
227
  return nil unless seconds_from_midnight.present? && seconds_from_midnight.to_i.positive?
211
228
 
@@ -286,6 +286,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
286
286
  @vendor = integration.vendor
287
287
  @location_mappings = {}
288
288
  @location_id_cache = {}
289
+ @variant_ids_needing_items = Set.new
289
290
  end
290
291
 
291
292
  # @param on_dates [Array<String>] dates to sync trips for, e.g. the next 7 days for a full
@@ -361,6 +362,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
361
362
  all_external_trips.concat(external_trips)
362
363
  synced_trip_ids.concat(process_external_trips(external_trips))
363
364
  bookable_ids_by_date[on_date] = external_trips.select(&:bookable?).to_set { |t| t.sync_identifier.to_s }
365
+ # Per date, not per run: a new trip's items must exist before later dates in the window adjust them.
366
+ enqueue_permanent_items_generation!
364
367
  end
365
368
 
366
369
  # Nothing came back for any date in the window - don't touch route stops/cleanup based
@@ -422,6 +425,16 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
422
425
  end
423
426
  end
424
427
 
428
+ def enqueue_permanent_items_generation!
429
+ return if @variant_ids_needing_items.empty?
430
+
431
+ # Sorted so the same set of trips shares one unique-job key.
432
+ SpreeCmCommissioner::InventoryItems::BulkGeneratePermanentItemsJob.perform_later(
433
+ variant_ids: @variant_ids_needing_items.to_a.sort
434
+ )
435
+ @variant_ids_needing_items.clear
436
+ end
437
+
425
438
  def sync_trip!(external_trip) # rubocop:disable Metrics/MethodLength
426
439
  # Return trip identifier for cleanup tracking even if unavailable/not currently bookable
427
440
  # (service_available false, or BookMeBus's own not_allowed/departure_over flags - Avocado's
@@ -452,6 +465,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
452
465
  # Only database mutations inside transaction
453
466
  trip_mapping = nil
454
467
  variant = nil
468
+ service_calendar = nil
455
469
 
456
470
  SpreeCmCommissioner::Trip.transaction do
457
471
  product = SyncProduct.new(
@@ -473,7 +487,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
473
487
  destination_place
474
488
  )
475
489
 
476
- sync_service_calendar!(product, external_trip)
490
+ service_calendar = sync_service_calendar!(product, external_trip) || product.service_calendar
477
491
 
478
492
  SyncInventory.new(
479
493
  sync_result: sync_result,
@@ -483,9 +497,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
483
497
  restore_inventory_if_previously_zeroed!(variant, external_trip)
484
498
  end
485
499
 
486
- SpreeCmCommissioner::InventoryItems::BulkGeneratePermanentItemsJob.perform_later(
487
- variant_ids: [variant.id]
488
- )
500
+ @variant_ids_needing_items << variant.id if permanent_items_needed?(service_calendar, variant, external_trip)
489
501
 
490
502
  # Post-transaction operations (can fail without rolling back trip creation)
491
503
  sync_seat_layout!(vehicle_type, external_trip, variant)
@@ -498,6 +510,19 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
498
510
  external_trip.sync_identifier
499
511
  end
500
512
 
513
+ # A calendar change can add dates anywhere in the window. A missing item for this date means its job never ran or
514
+ # was lost, so the next poll repairs it. Stock isn't checked: it only seeds items. New variants get their items
515
+ # from StockItem#create_inventory_items. service_available? stops a date the job would never create from
516
+ # re-enqueueing on every poll.
517
+ def permanent_items_needed?(service_calendar, variant, external_trip)
518
+ return false unless service_calendar
519
+ return true if service_calendar.saved_changes?
520
+
521
+ trip_date = parse_trip_date(external_trip.on_date)
522
+
523
+ trip_date.present? && service_calendar.service_available?(trip_date) && find_inventory_item_for_date(variant, external_trip).nil?
524
+ end
525
+
501
526
  def sync_vehicle_type!(external_trip)
502
527
  SyncVehicleTypes.new(
503
528
  integration: integration,
@@ -762,6 +787,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
762
787
  def map_route_type(route_type)
763
788
  case route_type&.to_s&.downcase
764
789
  when 'ferry' then :ferry
790
+ when 'private_taxi' then :intercity_taxi
765
791
  else :bus
766
792
  end
767
793
  end
@@ -30,8 +30,12 @@ module SpreeCmCommissioner
30
30
  end
31
31
  end
32
32
 
33
+ # Reads the existing dates per variant, not per batch: 1,000 variants over a year of dates would load 365,000 rows.
33
34
  def generate_inventory_items_for_variant(variant, count_on_hand)
34
- inventory_dates_for(variant).each do |inventory_date|
35
+ inventory_dates = inventory_dates_for(variant)
36
+ existing_dates = variant.inventory_items.where(inventory_date: inventory_dates).pluck(:inventory_date)
37
+
38
+ (inventory_dates - existing_dates).each do |inventory_date|
35
39
  create_inventory_item(variant, inventory_date, count_on_hand)
36
40
  end
37
41
  end
@@ -41,7 +45,7 @@ module SpreeCmCommissioner
41
45
  calendar = variant.product&.service_calendar
42
46
 
43
47
  if calendar.present?
44
- calendar.start_date.upto(calendar.end_date).select { |date| calendar.service_available?(date) }
48
+ calendar_dates_for(variant, calendar)
45
49
  else
46
50
  start_date = Time.zone.tomorrow
47
51
  end_date = Time.zone.today + pre_inventory_days_for(variant)
@@ -50,9 +54,16 @@ module SpreeCmCommissioner
50
54
  end
51
55
  end
52
56
 
53
- def create_inventory_item(variant, inventory_date, count_on_hand)
54
- return if variant.inventory_items.exists?(inventory_date: inventory_date)
57
+ # Calendars can span a century (BookMeBus sends 2010 to 2099), so they are cut to the days that can be sold.
58
+ # The daily generate_inventory_items task moves this window forward.
59
+ def calendar_dates_for(variant, calendar)
60
+ start_date = [calendar.start_date, Time.zone.today].max
61
+ end_date = [calendar.end_date, Time.zone.today + pre_inventory_days_for(variant)].min
55
62
 
63
+ start_date.upto(end_date).select { |date| calendar.service_available?(date) }
64
+ end
65
+
66
+ def create_inventory_item(variant, inventory_date, count_on_hand)
56
67
  variant.inventory_items.create!(
57
68
  inventory_date: inventory_date,
58
69
  quantity_available: count_on_hand,