spree_cm_commissioner 2.15.4 → 2.15.5

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 (28) hide show
  1. checksums.yaml +4 -4
  2. data/.env.example +1 -1
  3. data/Gemfile.lock +1 -1
  4. data/app/controllers/spree/admin/integrations_controller.rb +9 -0
  5. data/app/models/concerns/spree_cm_commissioner/line_item_inventory_holdable.rb +58 -0
  6. data/app/models/concerns/spree_cm_commissioner/order_holdable.rb +7 -0
  7. data/app/models/concerns/spree_cm_commissioner/product_hold_duration.rb +46 -0
  8. data/app/models/spree_cm_commissioner/line_item_decorator.rb +1 -14
  9. data/app/models/spree_cm_commissioner/product_decorator.rb +1 -0
  10. data/app/overrides/spree/admin/products/_form/enable_inventory_hold.html.erb.deface +24 -8
  11. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/external_client/client.rb +4 -3
  12. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_nationality_pricing.rb +1 -1
  13. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trips.rb +37 -21
  14. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_vehicle_types.rb +10 -4
  15. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/resources/trip.rb +14 -0
  16. data/app/services/spree_cm_commissioner/inventory_items/bulk_generate_permanent_items.rb +3 -0
  17. data/app/services/spree_cm_commissioner/line_items/validate_purchase_limits.rb +6 -6
  18. data/app/services/spree_cm_commissioner/order_holds/hold.rb +2 -2
  19. data/app/services/spree_cm_commissioner/user_informers/firebase_decorator.rb +17 -0
  20. data/app/services/spree_cm_commissioner/waiting_room/sessions/issue.rb +3 -3
  21. data/app/views/spree/admin/integrations/_book_me_bus_v1_fields.html.erb +10 -0
  22. data/app/views/spree/admin/inventory_holds/_search.html.erb +17 -0
  23. data/app/views/spree/admin/private_sales/_stock.html.erb +8 -2
  24. data/config/initializers/spree_permitted_attributes.rb +5 -0
  25. data/config/locales/en.yml +4 -0
  26. data/config/locales/km.yml +3 -0
  27. data/lib/spree_cm_commissioner/version.rb +1 -1
  28. metadata +5 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9729da447b28b6f2e0beafb9333442257c6d9efb60a317dd8012810248085654
4
- data.tar.gz: 5ff7d533406299db932f42c402b26e495d2e4127859611291344248083b7f1dc
3
+ metadata.gz: 2886bc2b2d9efa386bb7bf633edede791f7905b23daad67c093f09c91ffd398a
4
+ data.tar.gz: bcc38797affc78e662afad3b13959b3d262d8072c14d8533dc4a7b12fdf03ffd
5
5
  SHA512:
6
- metadata.gz: 014cf7cea9a4d55083a537cbcc4e9c4afa529edaf8fb8468b078200ccd92342991e050c58ffd139e8409cc1e85d08b0fa54214cac356ca2e93367f278527f295
7
- data.tar.gz: 1312f2a920a682b616b907687576ea6e8a9b9170780270e4d41853fa343865645f93406bd88bd32ce86b0d8cef012e5c04d9e5a4bf5167cfcc6ff0c0bb787a5a
6
+ metadata.gz: 7d9a5e8a3c32a37b87cc693025f08b15c2cf1dc12cdcb40bed95e05a936e3b462ee7b06a35b6187a4e9afcd8d06ff34e0d65afa86d3870ed1963ba805cdf52e7
7
+ data.tar.gz: b60dc08be24c97d34e9082a8fc4c95f9116eecb6674925c11a8a5a2b61a169dac315e305aa80c00862b497ffb2abe5c54e44c7a4265580ca87f83a4112bcbe38
data/.env.example CHANGED
@@ -73,7 +73,7 @@ IMPORT_ORDERS_BATCH_SIZE=50
73
73
 
74
74
  # Inventory Hold System
75
75
  # See: app/services/spree_cm_commissioner/order_holds/hold.rb
76
- HOLD_DURATION_IN_MINUTES=8 # How long a hold is active after checkout begins (address step)
76
+ HOLD_DURATION_IN_MINUTES=8 # Default hold after checkout begins (address step); per-product hold_duration_in_minutes overrides it
77
77
 
78
78
  # See: app/services/spree_cm_commissioner/order_holds/lock_for_payment.rb
79
79
  PAYMENT_LOCK_MIN_DURATION_IN_MINUTES=5 # Minimum remaining hold time required when entering the payment step; hold is extended if below this threshold
data/Gemfile.lock CHANGED
@@ -34,7 +34,7 @@ GIT
34
34
  PATH
35
35
  remote: .
36
36
  specs:
37
- spree_cm_commissioner (2.15.4)
37
+ spree_cm_commissioner (2.15.5)
38
38
  activerecord-multi-tenant
39
39
  activerecord_json_validator (~> 2.1, >= 2.1.3)
40
40
  aws-sdk-cloudfront
@@ -48,7 +48,16 @@ module Spree
48
48
 
49
49
  private
50
50
 
51
+ # The form only sends the private_metadata fields it shows. Replacing the whole hash wiped operator_id, the access
52
+ # token and any setting without a field, so the submitted fields are merged into what is stored.
51
53
  def permitted_resource_params
54
+ permitted = integration_params
55
+ return permitted unless permitted.key?(:private_metadata)
56
+
57
+ permitted.merge(private_metadata: (@object.private_metadata || {}).merge(permitted[:private_metadata].to_h))
58
+ end
59
+
60
+ def integration_params
52
61
  params.require(:spree_cm_commissioner_integration).permit(
53
62
  :name,
54
63
  :type,
@@ -0,0 +1,58 @@
1
+ # Caches the product's inventory hold setting of a line item in private_metadata, as
2
+ # inventory_hold_duration_in_minutes (0 = this line holds no inventory).
3
+ #
4
+ # Why cache?
5
+ # Acquire, LockForPayment, Release, Convert and RedisStock::Unstock each ask should_hold_inventory?
6
+ # at a different point of the hold. Re-reading product.enable_inventory_hold live, an admin toggling
7
+ # it mid-checkout would make Release/Convert skip counters Acquire took (stuck held stock) or touch
8
+ # ones it never took (oversell). It also saves a product load per line on every one of those reads.
9
+ #
10
+ # Behavior:
11
+ # The value is set once at line item creation and remains immutable, so a cart keeps the product's
12
+ # setting from when the item was added. A line created before this cache existed has no key and
13
+ # falls back to the live product check.
14
+ module SpreeCmCommissioner
15
+ module LineItemInventoryHoldable
16
+ extend ActiveSupport::Concern
17
+
18
+ included do
19
+ store_private_metadata :inventory_hold_duration_in_minutes, :integer
20
+
21
+ # Must run after LineItemSeatSelection#set_required_seat_selection_flag, which this reads.
22
+ before_create :set_inventory_hold_duration
23
+ end
24
+
25
+ def should_hold_inventory?
26
+ return inventory_hold_duration_in_minutes.positive? unless inventory_hold_duration_in_minutes.nil?
27
+
28
+ inventory_hold_applicable?
29
+ end
30
+
31
+ # Seat-selection lines cache 0 (no inventory hold) but still hold seat blocks, so they read the
32
+ # product's duration.
33
+ def hold_duration
34
+ minutes = inventory_hold_duration_in_minutes.to_i
35
+ minutes.positive? ? minutes.minutes : product&.hold_duration
36
+ end
37
+
38
+ private
39
+
40
+ def inventory_hold_applicable?
41
+ return false unless variant.should_track_inventory?
42
+ return false if required_seat_selection?
43
+
44
+ # The count hold is what guarantees an auto-assigned seat exists at completion, so these lines
45
+ # take it regardless of the product's enable_inventory_hold setting.
46
+ return true if auto_assign_seats?
47
+
48
+ product.enable_inventory_hold?
49
+ end
50
+
51
+ def set_inventory_hold_duration
52
+ return unless inventory_hold_duration_in_minutes.nil?
53
+ return if variant.nil? || product.nil?
54
+
55
+ self.inventory_hold_duration_in_minutes = inventory_hold_applicable? ? product.hold_duration.in_minutes.to_i : 0
56
+ end
57
+ end
58
+ end
@@ -33,6 +33,13 @@ module SpreeCmCommissioner
33
33
  false
34
34
  end
35
35
 
36
+ # Seat blocks and the inventory hold share one expiry per order, so a mixed cart takes the
37
+ # shortest product duration: a high-demand product never stays held longer than its owner set.
38
+ def hold_duration
39
+ line_items.filter_map(&:hold_duration).min ||
40
+ SpreeCmCommissioner::ProductHoldDuration::DEFAULT_HOLD_DURATION
41
+ end
42
+
36
43
  # Called before transitioning to :address state.
37
44
  # Acquires seat holds (if applicable) + inventory holds for the order.
38
45
  def hold_order_holds
@@ -0,0 +1,46 @@
1
+ # Optional per-product override of how long an order hold (seat blocks + inventory) lasts once
2
+ # checkout begins. High-demand products can release unpaid stock sooner; blank falls back to
3
+ # HOLD_DURATION_IN_MINUTES so existing products keep today's behaviour.
4
+ module SpreeCmCommissioner
5
+ module ProductHoldDuration
6
+ extend ActiveSupport::Concern
7
+
8
+ DEFAULT_HOLD_DURATION = ENV.fetch('HOLD_DURATION_IN_MINUTES', '8').to_i.minutes
9
+
10
+ # The hold must outlast guest-details entry until a payment exists (LockForPayment then extends
11
+ # it). Shorter would expire real checkouts mid-form and trip HOLD_COOLDOWN_AFTER_EXPIRY_IN_MINUTES.
12
+ MIN_HOLD_DURATION_IN_MINUTES = 2
13
+
14
+ # Caps a typo (e.g. 800) from tying up seats/stock in abandoned carts for hours.
15
+ MAX_HOLD_DURATION_IN_MINUTES = 30
16
+
17
+ included do
18
+ store_public_metadata :hold_duration_in_minutes, :integer
19
+
20
+ validates :hold_duration_in_minutes,
21
+ numericality: {
22
+ only_integer: true,
23
+ greater_than_or_equal_to: MIN_HOLD_DURATION_IN_MINUTES,
24
+ less_than_or_equal_to: MAX_HOLD_DURATION_IN_MINUTES
25
+ },
26
+ allow_nil: true
27
+
28
+ before_validation :normalize_hold_duration_in_minutes
29
+ end
30
+
31
+ def hold_duration
32
+ minutes = hold_duration_in_minutes.to_i
33
+ minutes.between?(MIN_HOLD_DURATION_IN_MINUTES, MAX_HOLD_DURATION_IN_MINUTES) ? minutes.minutes : DEFAULT_HOLD_DURATION
34
+ end
35
+
36
+ private
37
+
38
+ # The :integer reader casts with to_i, so a form-submitted "" would read back as 0 and fail
39
+ # validation instead of meaning "use the default".
40
+ def normalize_hold_duration_in_minutes
41
+ return if public_metadata.blank?
42
+
43
+ public_metadata['hold_duration_in_minutes'] = nil if public_metadata['hold_duration_in_minutes'].blank?
44
+ end
45
+ end
46
+ end
@@ -90,6 +90,7 @@ module SpreeCmCommissioner
90
90
  base.include SpreeCmCommissioner::LineItemGuestsConcern
91
91
  base.include SpreeCmCommissioner::LineItemTransitable
92
92
  base.include SpreeCmCommissioner::LineItemSeatSelection
93
+ base.include SpreeCmCommissioner::LineItemInventoryHoldable
93
94
  base.include SpreeCmCommissioner::Integrations::IntegrationMappable
94
95
  base.include SpreeCmCommissioner::ProductType
95
96
  base.include SpreeCmCommissioner::ProductDelegation
@@ -160,20 +161,6 @@ module SpreeCmCommissioner
160
161
  required_self_check_in_location
161
162
  end
162
163
 
163
- def should_hold_inventory?
164
- return false unless variant.should_track_inventory?
165
- return false if required_seat_selection?
166
-
167
- # The count hold is what guarantees an auto-assigned seat exists at completion, so these lines
168
- # take it regardless of the product's enable_inventory_hold setting.
169
- return true if auto_assign_seats?
170
-
171
- return true if ENV.fetch('INVENTORY_HOLD_ENABLED', nil) == 'true'
172
- return true if product.enable_inventory_hold?
173
-
174
- false
175
- end
176
-
177
164
  def amount_per_guest
178
165
  amount / quantity
179
166
  end
@@ -11,6 +11,7 @@ module SpreeCmCommissioner
11
11
  base.include SpreeCmCommissioner::StoreMetadata
12
12
  base.include SpreeCmCommissioner::HomepageSectionRelatableConcern
13
13
  base.include SpreeCmCommissioner::PurchaseLimitable
14
+ base.include SpreeCmCommissioner::ProductHoldDuration
14
15
  base.include SpreeCmCommissioner::ProductSeatAutoAssignable
15
16
 
16
17
  base.delegate :is_open_dated, :is_open_dated?, to: :trip, allow_nil: true
@@ -1,18 +1,34 @@
1
1
  <!-- insert_after "[data-hook='admin_product_form_promotionable']" -->
2
2
 
3
- <%#=
4
- NOTE: This field and the corresponding model attribute can be removed
5
- once the system fully enforces holds by default.
6
- %>
7
-
8
3
  <div>
9
4
  <%= f.field_container :enable_inventory_hold do %>
10
5
  <%= f.label :enable_inventory_hold do %>
11
6
  <%= f.check_box :enable_inventory_hold %>
12
7
  <%= Spree.t(:enable_inventory_hold) %>
13
8
  <% end %>
14
- <small class="form-text text-muted">
15
- Experimental: Holds bookings for <%= ENV.fetch('HOLD_DURATION_IN_MINUTES', '8') %> minutes until confirmed or cancelled. May affect availability with many pending bookings.
16
- </small>
17
9
  <% end %>
10
+
11
+ <div id="hold_duration_in_minutes_field" class="<%= 'd-none' unless f.object.enable_inventory_hold %>">
12
+ <%= f.field_container :hold_duration_in_minutes do %>
13
+ <%= f.label :hold_duration_in_minutes, Spree.t(:hold_duration_in_minutes) %>
14
+ <%= f.number_field :hold_duration_in_minutes, value: f.object.hold_duration_in_minutes,
15
+ min: SpreeCmCommissioner::ProductHoldDuration::MIN_HOLD_DURATION_IN_MINUTES,
16
+ max: SpreeCmCommissioner::ProductHoldDuration::MAX_HOLD_DURATION_IN_MINUTES, class: 'form-control',
17
+ placeholder: Spree.t(:hold_duration_in_minutes_placeholder, minutes: SpreeCmCommissioner::ProductHoldDuration::DEFAULT_HOLD_DURATION.in_minutes.to_i) %>
18
+ <small class="form-text text-muted"><%= Spree.t(:hold_duration_in_minutes_note) %></small>
19
+ <%= f.error_message_on :hold_duration_in_minutes %>
20
+ <% end %>
21
+ </div>
18
22
  </div>
23
+
24
+ <script>
25
+ (function () {
26
+ var checkbox = document.getElementById('product_enable_inventory_hold');
27
+ var field = document.getElementById('hold_duration_in_minutes_field');
28
+ if (!checkbox || !field) return;
29
+
30
+ checkbox.addEventListener('change', function () {
31
+ field.classList.toggle('d-none', !checkbox.checked);
32
+ });
33
+ })();
34
+ </script>
@@ -28,7 +28,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
28
28
  # @return [Array<SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::TripLocation>]
29
29
  def get_trip_locations! # rubocop:disable Naming/AccessorMethodName
30
30
  endpoint = "#{BASE_PATH}/trip_locations"
31
- params = { operator_id: integration.operator_id }.compact
31
+ params = { operator_id: integration.operator_id.presence }.compact
32
32
 
33
33
  response = get(endpoint, params)
34
34
  handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::TripLocation, collection: true) || []
@@ -49,8 +49,9 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
49
49
  on_date: on_date,
50
50
  # Scopes results to this integration's operator when multiple Integrations share one
51
51
  # BookMeBus application (Application#use_multiple_operators?). Compacted out (rather than
52
- # sent as an empty value) when unset, so a single-operator setup behaves exactly as before.
53
- operator_id: integration.operator_id
52
+ # sent as an empty value) when unset or left blank in the admin form, so a single-operator setup behaves
53
+ # exactly as before.
54
+ operator_id: integration.operator_id.presence
54
55
  }.compact
55
56
  endpoint = "#{BASE_PATH}/trip_availabilities"
56
57
 
@@ -55,7 +55,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
55
55
  private
56
56
 
57
57
  def find_or_create_pricing_model
58
- @vendor.pricing_models.find_or_create_by!(name: PRICING_MODEL_NAME) do |m|
58
+ @vendor.pricing_models.find_or_create_by!(name: "#{PRICING_MODEL_NAME} - #{@route.route_name} ##{@route.id}") do |m|
59
59
  m.status = :active
60
60
  end
61
61
  end
@@ -291,6 +291,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
291
291
  @seat_layout_synced_variant_ids = Set.new
292
292
  @seat_layout_freshness = SpreeCmCommissioner::Integrations::BookMeBusV1::SeatLayoutFreshness.new(integration)
293
293
  @variant_ids_needing_items = Set.new
294
+ @trips_seen = 0
295
+ @trip_errors = []
294
296
  end
295
297
 
296
298
  # @param on_dates [Array<String>] dates to sync trips for, e.g. the next 7 days for a full
@@ -373,6 +375,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
373
375
  # Per date, not per run: a new trip's items must exist before later dates in the window adjust them.
374
376
  enqueue_permanent_items_generation!
375
377
  end
378
+ record_error_if_every_trip_failed
376
379
 
377
380
  # Nothing came back for any date in the window - don't touch route stops/cleanup based
378
381
  # on an empty result (could be a transient outage rather than a genuinely dead route).
@@ -392,6 +395,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
392
395
  # Sync route stops using every trip seen across the whole window, not just one date -
393
396
  # a stop only served by a non-daily trip must survive dates it doesn't run.
394
397
  sync_route_stops!(all_external_trips)
398
+ sync_route_type!(all_external_trips)
395
399
 
396
400
  # Clean up stale trip mappings using the full window's synced ids - archiving per single
397
401
  # date would flap a non-daily trip's mapping active/archived across this run.
@@ -427,21 +431,34 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
427
431
  end
428
432
 
429
433
  def process_external_trips(external_trips)
430
- external_trips.filter_map do |external_trip|
434
+ @trips_seen += external_trips.size
435
+
436
+ external_trips.map do |external_trip|
431
437
  sync_trip!(external_trip)
432
438
  rescue SpreeCmCommissioner::Integrations::RateLimitedError
433
439
  raise # e.g. the seat layout call of this trip
434
- rescue SpreeCmCommissioner::Integrations::SyncError => e
435
- @sync_result.record_error(e)
436
- Rails.logger.warn("[SyncTrips] Sync error for trip #{external_trip.trip_id}: #{e.message}")
437
- nil
438
440
  rescue StandardError => e
439
- @sync_result.record_error(e)
440
- Rails.logger.error("[SyncTrips] Unexpected error for trip #{external_trip.trip_id}: #{e.message}")
441
- nil
441
+ skip_failed_trip(external_trip, e)
442
442
  end
443
443
  end
444
444
 
445
+ # One trip BookMeBus cannot answer for (e.g. a seat layout that returns 500) must not fail its whole route. Its id is
446
+ # still returned: without it cleanup_stale_mappings! would archive a trip BookMeBus still sells. It keeps its last
447
+ # synced data and is tried again on the next sync.
448
+ def skip_failed_trip(external_trip, error)
449
+ @trip_errors << error
450
+ sync_result.increment_metric(:trip, :failed)
451
+ Rails.logger.warn("[SyncTrips] Skipped trip #{external_trip.sync_identifier}: #{error.message}")
452
+ external_trip.sync_identifier
453
+ end
454
+
455
+ # Only a route where every trip failed is a failure: that points at BookMeBus or at us, not at one trip.
456
+ def record_error_if_every_trip_failed
457
+ return if @trip_errors.empty? || @trip_errors.size < @trips_seen
458
+
459
+ sync_result.record_error(@trip_errors.last)
460
+ end
461
+
445
462
  def enqueue_permanent_items_generation!
446
463
  return if @variant_ids_needing_items.empty?
447
464
 
@@ -596,7 +613,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
596
613
  destination_place: destination_place,
597
614
  departure_time: parse_departure_time(external_trip),
598
615
  duration: external_trip.travel_duration.to_i,
599
- route_type: map_route_type(external_trip.route_type),
616
+ route_type: external_trip.mapped_route_type,
600
617
  name: product.name,
601
618
  short_name: product.short_name,
602
619
  allow_seat_selection: !external_trip.auto_assigned_seat
@@ -653,6 +670,17 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
653
670
  ).call(external_trips: external_trips)
654
671
  end
655
672
 
673
+ # SyncRoutes creates the route before its trips are known, as a bus. A route whose trips disagree stays as it is.
674
+ def sync_route_type!(external_trips)
675
+ route_types = external_trips.map(&:mapped_route_type).uniq
676
+ return unless route_types.one?
677
+
678
+ sync_result.track(:route, route) do |tracker|
679
+ route.route_type = route_types.first
680
+ tracker.save_if_changed!(route)
681
+ end
682
+ end
683
+
656
684
  def sync_service_calendar!(product, external_trip)
657
685
  SyncServiceCalendars.new(
658
686
  integration: integration,
@@ -811,17 +839,5 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
811
839
  rescue ArgumentError, TypeError
812
840
  nil
813
841
  end
814
-
815
- # SpreeCmCommissioner::RouteType::ROUTE_TYPES (the Trip#route_type enum) only allows
816
- # bus/intercity_taxi/airport_shuttle/rails/ferry - there is no :van. Assigning an invalid
817
- # enum value raises ArgumentError, so a 'van' from BookMeBus used to crash sync_trip! for
818
- # every van trip (rescued and logged by process_external_trips, but never actually synced).
819
- def map_route_type(route_type)
820
- case route_type&.to_s&.downcase
821
- when 'ferry' then :ferry
822
- when 'private_taxi' then :intercity_taxi
823
- else :bus
824
- end
825
- end
826
842
  end
827
843
  end
@@ -19,7 +19,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
19
19
  # - 'suv', 'mid_size_suv', 'full_size_suv', 'luxury_suv' => :suv
20
20
  # - 'sleeping_bus' => :sleeping_bus
21
21
  # - 'air_bus' => :air_bus
22
- # - unknown types => :bus (default)
22
+ # - any vehicle on a rail trip => :train
23
+ # - unknown types => :ferry on a ferry trip, otherwise :bus (default)
23
24
  #
24
25
  # Usage:
25
26
  # sync_service = SyncVehicleTypes.new(integration: integration, sync_result: sync_result)
@@ -54,7 +55,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
54
55
  vehicle_type.assign_attributes(
55
56
  vendor: @integration.vendor,
56
57
  name: unique_name_for(vehicle_type, external_trip),
57
- kind: map_vehicle_type_to_kind(external_trip.vehicle_type_type_name)
58
+ kind: map_vehicle_type_to_kind(external_trip)
58
59
  )
59
60
  tracker.save_if_changed!(vehicle_type)
60
61
  end
@@ -76,7 +77,12 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
76
77
  taken ? "#{name} (#{external_trip.vehicle_type_id})" : name
77
78
  end
78
79
 
79
- def map_vehicle_type_to_kind(type_name)
80
+ # BookMeBus gives train vehicles a seat category as type_name (e.g. 'suv'), so a rail vehicle is a train whatever it
81
+ # is called, and a ferry vehicle with an unknown type_name is a ferry rather than the bus default.
82
+ def map_vehicle_type_to_kind(external_trip)
83
+ route_type = external_trip.mapped_route_type
84
+ return :train if route_type == :rails
85
+
80
86
  mapping = {
81
87
  'bus' => :bus,
82
88
  'van' => :van,
@@ -97,7 +103,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
97
103
  'speed_boat' => :boat,
98
104
  'air_bus' => :air_bus
99
105
  }
100
- mapping.fetch(type_name, :bus)
106
+ mapping.fetch(external_trip.vehicle_type_type_name) { route_type == :ferry ? :ferry : :bus }
101
107
  end
102
108
  end
103
109
  end
@@ -7,6 +7,15 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Resources
7
7
  hits_origin hits_destination
8
8
  ].freeze
9
9
 
10
+ # BookMeBus route types (avocado Transit::Trip#route_type) that BookMe+ sells as their own type; any other is a bus.
11
+ ROUTE_TYPES = {
12
+ 'ferry' => :ferry,
13
+ 'rails' => :rails,
14
+ 'tram' => :rails,
15
+ 'subway' => :rails,
16
+ 'private_taxi' => :intercity_taxi
17
+ }.freeze
18
+
10
19
  attr_accessor :id,
11
20
  :type,
12
21
  :trip_id,
@@ -91,6 +100,11 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Resources
91
100
  seats_remaining
92
101
  end
93
102
 
103
+ # BookMeBus labels some ferry trips `bus` while their vehicle is a boat, so the vehicle's type decides those.
104
+ def mapped_route_type
105
+ ROUTE_TYPES[route_type.to_s.downcase] || ROUTE_TYPES[vehicle_type_route_type.to_s.downcase] || :bus
106
+ end
107
+
94
108
  # BookMe+ charges the non-local (foreigner) price by default, falling back to local_price
95
109
  # only when BookMeBus doesn't provide one. Single source of truth for both trip-creation
96
110
  # (SyncTrips) and per-date availability refresh (SyncItemAvailability) so they can't diverge.
@@ -72,6 +72,9 @@ module SpreeCmCommissioner
72
72
  )
73
73
  rescue ActiveRecord::RecordNotUnique
74
74
  # concurrent worker won the race; record already exists
75
+ rescue ActiveRecord::RecordInvalid
76
+ # Same race, caught earlier: the model's uniqueness validation sees the other worker's row before the index does.
77
+ raise unless variant.inventory_items.exists?(inventory_date: inventory_date)
75
78
  end
76
79
 
77
80
  # Returns a hash: { variant_id => total_on_hand, ... }
@@ -18,11 +18,11 @@ module SpreeCmCommissioner
18
18
  COUNTED_STATES = %w[complete resumed].freeze
19
19
 
20
20
  # An unpaid cart counts until its hold expires. Without a hold (a product without inventory
21
- # holds) it counts while still in checkout - not sent back to `cart`, not archived - for one
22
- # hold duration after its last update; entering checkout or paying bumps updated_at. A
23
- # released hold clears hold_expires_at and sends the cart back to `cart`, so it stops
24
- # counting at once. A `cart` order can't be paid without re-entering `address`, which runs
25
- # this check again (OrderStateMachine#ensure_within_purchase_limits).
21
+ # holds) it counts while still in checkout - not sent back to `cart`, not archived - for this
22
+ # product's hold duration (ProductHoldDuration) after its last update; entering checkout or
23
+ # paying bumps updated_at. A released hold clears hold_expires_at and sends the cart back to
24
+ # `cart`, so it stops counting at once. A `cart` order can't be paid without re-entering
25
+ # `address`, which runs this check again (OrderStateMachine#ensure_within_purchase_limits).
26
26
  # Spree's metadata serializer stores public_metadata as a JSON string inside the jsonb
27
27
  # column, so `->>` on it is always NULL; `#>> '{}'` unwraps it (or an object) back to jsonb.
28
28
  COUNTED_ORDERS_SQL = <<~SQL.squish.freeze
@@ -163,7 +163,7 @@ module SpreeCmCommissioner
163
163
  end
164
164
 
165
165
  def hold_seconds
166
- SpreeCmCommissioner::OrderHolds::Hold::HOLD_DURATION.to_i
166
+ @product.hold_duration.to_i
167
167
  end
168
168
  end
169
169
  end
@@ -10,9 +10,9 @@ module SpreeCmCommissioner
10
10
  UnableToHoldInventoryError = Class.new(StandardError)
11
11
  UnableToHoldExternalInventoryError = Class.new(StandardError)
12
12
 
13
- HOLD_DURATION = ENV.fetch('HOLD_DURATION_IN_MINUTES', '8').to_i.minutes
13
+ def call(order:, expires_at: nil)
14
+ expires_at ||= order.hold_duration.from_now
14
15
 
15
- def call(order:, expires_at: HOLD_DURATION.from_now)
16
16
  held_blocks = hold_seat_blocks!(order, expires_at)
17
17
  inventory_hold = acquire_inventory_hold!(order, expires_at)
18
18
  hold_external_inventory!(order)
@@ -0,0 +1,17 @@
1
+ module SpreeCmCommissioner
2
+ module UserInformers
3
+ module FirebaseDecorator
4
+ # override: vpago builds a new Firestore client per informer, i.e. per order/payment status
5
+ # update, paying a fresh gRPC channel, TLS handshake and OAuth token fetch each time. Use the
6
+ # per-process shared client instead, so it also gets FirestoreClients' fork handling and the
7
+ # per-example reset in specs.
8
+ def firestore
9
+ @firestore ||= SpreeCmCommissioner::FirestoreClients.fetch(service_account)
10
+ end
11
+ end
12
+ end
13
+ end
14
+
15
+ unless Vpago::UserInformers::Firebase.included_modules.include?(SpreeCmCommissioner::UserInformers::FirebaseDecorator)
16
+ Vpago::UserInformers::Firebase.prepend(SpreeCmCommissioner::UserInformers::FirebaseDecorator)
17
+ end
@@ -14,9 +14,9 @@ module SpreeCmCommissioner
14
14
  SESSION_CREATION_LOCK_KEY = 'waiting_room_session_creation'.freeze
15
15
 
16
16
  # Soft ceiling on how long a session may keep renewing before it competes for capacity again
17
- # (see #max_expired_at_ceiling and #renew_active_session). 600s default; HOLD_DURATION (8 min) +
18
- # PAYMENT_LOCK_MIN_DURATION extension can push a genuinely active checkout to ~13 min, so this
19
- # is a soft cap — past it, the session self-expires and the next call falls back to the
17
+ # (see #max_expired_at_ceiling and #renew_active_session). 600s default; the order hold (8 min
18
+ # default, per product) + PAYMENT_LOCK_MIN_DURATION extension can push a genuinely active
19
+ # checkout to ~13 min, so this is a soft cap — past it, the session self-expires and the next call falls back to the
20
20
  # full?-gated path, rather than being evicted outright.
21
21
  WAITING_ROOM_SESSION_MAX_DURATION_IN_SECOND = (ENV['WAITING_ROOM_SESSION_MAX_DURATION_IN_SECOND'] || 600).to_i
22
22
 
@@ -38,6 +38,16 @@
38
38
  <% end %>
39
39
  </div>
40
40
 
41
+ <div class="col-6">
42
+ <%= f.field_container :operator_id do %>
43
+ <%= f.label :operator_id, I18n.t('spree.admin.external_integrations.operator_id', default: 'Operator ID') %>
44
+ <%= text_field_tag 'spree_cm_commissioner_integration[private_metadata][operator_id]', f.object.operator_id, class: 'form-control' %>
45
+ <small class="form-text text-muted">
46
+ <%= I18n.t('spree.admin.external_integrations.operator_id_description', default: 'BookMeBus operator to sync when the application serves several operators') %>
47
+ </small>
48
+ <% end %>
49
+ </div>
50
+
41
51
  <div class="col-12">
42
52
  <hr class="my-4">
43
53
 
@@ -120,6 +120,23 @@
120
120
  </div>
121
121
  </div>
122
122
 
123
+ <div class="row">
124
+ <div class="col-12 col-lg-3">
125
+ <div class="form-group">
126
+ <%= label_tag :q_order_line_items_variant_product_id_eq, 'Product' %>
127
+ <%= f.select :order_line_items_variant_product_id_eq,
128
+ options_from_collection_for_select(Spree::Product.where(id: params.dig(:q, :order_line_items_variant_product_id_eq)), :id, :name, params.dig(:q, :order_line_items_variant_product_id_eq)),
129
+ { include_blank: true },
130
+ class: 'js-filterable',
131
+ data: {
132
+ autocomplete_url_value: 'products_api_v2',
133
+ autocomplete_clear_value: true,
134
+ autocomplete_placeholder_value: Spree.t('admin.navigation.search_for_a_product')
135
+ } %>
136
+ </div>
137
+ </div>
138
+ </div>
139
+
123
140
  <div data-hook="admin_inventory_holds_index_search_buttons" class="form-actions">
124
141
  <%= button Spree.t(:filter_results), 'search.svg' %>
125
142
  </div>
@@ -50,7 +50,7 @@
50
50
  <span class="badge badge-info ml-1">Offline</span>
51
51
  <% end %>
52
52
  </td>
53
- <td class="text-right">
53
+ <td class="text-right text-nowrap">
54
54
  <%# Own column so these line up under the same x-position for every product, rather than
55
55
  sharing space with the name — icon-only, matching the with-tip pattern used for row
56
56
  actions elsewhere in this admin (e.g. import_existing_orders#index). Regardless of
@@ -82,7 +82,13 @@
82
82
  <td class="text-center text-muted"><%= item.max_capacity %></td>
83
83
  <td class="text-center"><%= item.quantity_reserved %></td>
84
84
  <td class="text-center"><%= render partial: 'spree/admin/shared/availability_percentage', locals: { inventory_item: item } %></td>
85
- <td class="text-center"><%= item.quantity_on_hold %></td>
85
+ <td class="text-center">
86
+ <%= item.quantity_on_hold %>
87
+ <%= link_to admin_inventory_holds_path(q: { order_line_items_variant_product_id_eq: product.id }),
88
+ class: 'btn btn-sm btn-outline-secondary with-tip icon-link ml-1', title: t('.view_holds') do %>
89
+ <%= svg_icon name: 'hourglass-split.svg', width: '14', height: '14' %>
90
+ <% end %>
91
+ </td>
86
92
  <td class="text-center"><strong><%= item.quantity_locked %></strong></td>
87
93
  <td class="text-center"><%= item.quantity_locked_on_hold %></td>
88
94
  <td class="text-center">
@@ -193,5 +193,10 @@ module Spree
193
193
  max_quantity_per_device
194
194
  max_quantity_per_ip
195
195
  ]
196
+
197
+ # SpreeCmCommissioner::ProductHoldDuration, a public_metadata store_accessor.
198
+ @@product_attributes += %i[
199
+ hold_duration_in_minutes
200
+ ]
196
201
  end
197
202
  end
@@ -292,6 +292,9 @@ en:
292
292
  font: "Font"
293
293
  app_background: "App Background"
294
294
  web_background: "Web Background"
295
+ hold_duration_in_minutes: "Hold duration (minutes)"
296
+ hold_duration_in_minutes_placeholder: "Default: %{minutes} minutes"
297
+ hold_duration_in_minutes_note: "Optional. How long unpaid checkouts keep seats/stock for this product. Leave blank to use the default."
295
298
  section_types:
296
299
  default: "Default"
297
300
  trending: "Trending"
@@ -718,6 +721,7 @@ en:
718
721
  lock_release_confirm: "Apply this change to locked stock? This takes effect immediately."
719
722
  manage_product_stock: "Product stock"
720
723
  lock_history: "Lock history"
724
+ view_holds: "Inventory holds"
721
725
  per_date_stock: "This product's stock is per date — manage it on the product"
722
726
  revoke:
723
727
  revoked: "Private sale revoked. Its link no longer works."
@@ -250,6 +250,9 @@ km:
250
250
  font: "ពុម្ពអក្សរ"
251
251
  app_background: "ផ្ទៃខាងក្រោយកម្មវិធី"
252
252
  web_background: "ផ្ទៃខាងក្រោយវិបសាយ"
253
+ hold_duration_in_minutes: "រយៈពេលរក្សាទុក (នាទី)"
254
+ hold_duration_in_minutes_placeholder: "លំនាំដើម៖ %{minutes} នាទី"
255
+ hold_duration_in_minutes_note: "ស្រេចចិត្ត។ រយៈពេលដែលការទូទាត់មិនទាន់បង់ប្រាក់រក្សាកៅអី/ស្តុកសម្រាប់ផលិតផលនេះ។ ទុកទទេដើម្បីប្រើតម្លៃលំនាំដើម។"
253
256
  section_types:
254
257
  default: "លំនាំដើម"
255
258
  trending: "កំពុងពេញនិយម"
@@ -1,5 +1,5 @@
1
1
  module SpreeCmCommissioner
2
- VERSION = '2.15.4'.freeze
2
+ VERSION = '2.15.5'.freeze
3
3
 
4
4
  module_function
5
5
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: spree_cm_commissioner
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.15.4
4
+ version: 2.15.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - You
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-13 00:00:00.000000000 Z
11
+ date: 2026-11-17 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: spree
@@ -1494,6 +1494,7 @@ files:
1494
1494
  - app/models/concerns/spree_cm_commissioner/line_item_durationable.rb
1495
1495
  - app/models/concerns/spree_cm_commissioner/line_item_guests_concern.rb
1496
1496
  - app/models/concerns/spree_cm_commissioner/line_item_integration.rb
1497
+ - app/models/concerns/spree_cm_commissioner/line_item_inventory_holdable.rb
1497
1498
  - app/models/concerns/spree_cm_commissioner/line_item_open_dated_trippable.rb
1498
1499
  - app/models/concerns/spree_cm_commissioner/line_item_rate_plannable.rb
1499
1500
  - app/models/concerns/spree_cm_commissioner/line_item_seat_selection.rb
@@ -1516,6 +1517,7 @@ files:
1516
1517
  - app/models/concerns/spree_cm_commissioner/percent_fee_calculable.rb
1517
1518
  - app/models/concerns/spree_cm_commissioner/phone_number_sanitizer.rb
1518
1519
  - app/models/concerns/spree_cm_commissioner/product_delegation.rb
1520
+ - app/models/concerns/spree_cm_commissioner/product_hold_duration.rb
1519
1521
  - app/models/concerns/spree_cm_commissioner/product_relation_type.rb
1520
1522
  - app/models/concerns/spree_cm_commissioner/product_seat_auto_assignable.rb
1521
1523
  - app/models/concerns/spree_cm_commissioner/product_type.rb
@@ -2741,6 +2743,7 @@ files:
2741
2743
  - app/services/spree_cm_commissioner/url_embed/youtube_embed.rb
2742
2744
  - app/services/spree_cm_commissioner/user_authenticator.rb
2743
2745
  - app/services/spree_cm_commissioner/user_counters_service.rb
2746
+ - app/services/spree_cm_commissioner/user_informers/firebase_decorator.rb
2744
2747
  - app/services/spree_cm_commissioner/user_roles_assigner.rb
2745
2748
  - app/services/spree_cm_commissioner/users/backfill_device_tokens_count.rb
2746
2749
  - app/services/spree_cm_commissioner/users/block.rb