spree_cm_commissioner 2.15.1 → 2.15.3
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 +4 -4
- data/.env.example +3 -0
- data/Gemfile.lock +2 -2
- data/app/controllers/spree/admin/inventory_holds_controller.rb +32 -6
- data/app/errors/spree_cm_commissioner/integrations/rate_limited_error.rb +28 -0
- data/app/jobs/spree_cm_commissioner/integrations/book_me_bus_v1/sync_route_job.rb +70 -0
- data/app/jobs/spree_cm_commissioner/seats/auto_assign_job.rb +16 -0
- data/app/models/concerns/spree_cm_commissioner/line_item_seat_selection.rb +25 -3
- data/app/models/concerns/spree_cm_commissioner/order_seat_auto_assignable.rb +73 -0
- data/app/models/concerns/spree_cm_commissioner/product_seat_auto_assignable.rb +29 -0
- data/app/models/spree_cm_commissioner/block.rb +33 -0
- data/app/models/spree_cm_commissioner/integration_mapping.rb +8 -0
- data/app/models/spree_cm_commissioner/integrations/book_me_bus_v1.rb +5 -0
- data/app/models/spree_cm_commissioner/line_item_decorator.rb +4 -0
- data/app/models/spree_cm_commissioner/order_decorator.rb +17 -1
- data/app/models/spree_cm_commissioner/product_decorator.rb +1 -0
- data/app/models/spree_cm_commissioner/reserved_block.rb +19 -3
- data/app/models/spree_cm_commissioner/seats/auto_assign_validator.rb +63 -0
- data/app/overrides/spree/admin/products/_form/auto_assign_seats.html.erb.deface +14 -0
- data/app/queries/spree_cm_commissioner/inventory_hold_insights_query.rb +151 -0
- data/app/queries/spree_cm_commissioner/inventory_hold_overview_query.rb +79 -0
- data/app/queries/spree_cm_commissioner/seats/free_runs_query.rb +73 -0
- data/app/serializers/spree/v2/storefront/line_item_serializer_decorator.rb +1 -1
- data/app/serializers/spree/v2/storefront/product_serializer_decorator.rb +1 -1
- data/app/serializers/spree/v2/tenant/line_item_serializer.rb +1 -1
- data/app/services/spree_cm_commissioner/integrations/base/sync_result.rb +7 -0
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/external_client/client.rb +24 -7
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/external_client/connection.rb +19 -13
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_item_availability.rb +12 -6
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_locations.rb +10 -3
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_routes.rb +11 -2
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_seat_layout.rb +8 -59
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trips.rb +55 -35
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/resources/trip.rb +0 -4
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/route_freshness.rb +48 -0
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/seat_layout_freshness.rb +46 -0
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/sync_manager.rb +5 -6
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/sync_strategies/full_sync_strategy.rb +32 -15
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/sync_strategies/incremental_sync_strategy.rb +43 -40
- data/app/services/spree_cm_commissioner/integrations/call_limiter.rb +89 -0
- data/app/services/spree_cm_commissioner/integrations/polling_scheduler.rb +13 -7
- data/app/services/spree_cm_commissioner/integrations/sync_backoff.rb +61 -0
- data/app/services/spree_cm_commissioner/order_holds/release.rb +3 -1
- data/app/services/spree_cm_commissioner/seat_layouts/save_seat_order.rb +111 -0
- data/app/services/spree_cm_commissioner/seats/apply_locks.rb +13 -7
- data/app/services/spree_cm_commissioner/seats/auto_assign.rb +135 -0
- data/app/services/spree_cm_commissioner/seats/block_date_iteration.rb +5 -2
- data/app/services/spree_cm_commissioner/seats/block_history.rb +168 -0
- data/app/services/spree_cm_commissioner/seats/lock_state.rb +3 -1
- data/app/services/spree_cm_commissioner/seats/pick_seats.rb +79 -0
- data/app/services/spree_cm_commissioner/seats/swap_seats.rb +265 -0
- data/app/services/spree_cm_commissioner/seats/unlock_blocks.rb +11 -12
- data/app/views/spree/admin/inventory_holds/_insights.html.erb +99 -0
- data/app/views/spree/admin/inventory_holds/_insights_drawer.html.erb +83 -0
- data/app/views/spree/admin/inventory_holds/_order_status.html.erb +9 -0
- data/app/views/spree/admin/inventory_holds/_overview.html.erb +109 -0
- data/app/views/spree/admin/inventory_holds/_section.html.erb +5 -0
- data/app/views/spree/admin/inventory_holds/_stat.html.erb +4 -0
- data/app/views/spree/admin/inventory_holds/index.html.erb +12 -1
- data/config/routes.rb +4 -0
- data/db/migrate/20261106000001_add_seat_index_to_cm_blocks.rb +16 -0
- data/db/migrate/20261110000001_add_seat_assignment_status_to_spree_line_items.rb +11 -0
- data/lib/spree_cm_commissioner/version.rb +1 -1
- metadata +29 -2
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
# Test/abandon/fraud signals for one hold, shown in the admin inventory holds drawer. Every
|
|
3
|
+
# section is a single aggregate (COUNT ... FILTER) or a LIMITed pluck, so the query count is
|
|
4
|
+
# fixed no matter how many orders/holds the user or IP has.
|
|
5
|
+
class InventoryHoldInsightsQuery
|
|
6
|
+
RECENT_LIMIT = 10
|
|
7
|
+
# Shared with InventoryHoldOverviewQuery as a Postgres `~*` pattern, so keep it POSIX-compatible.
|
|
8
|
+
TEST_EMAIL_SOURCE = '(\+test|test@|@example\.com|@bookme\.local)'.freeze
|
|
9
|
+
TEST_EMAIL_PATTERN = Regexp.new(TEST_EMAIL_SOURCE, Regexp::IGNORECASE)
|
|
10
|
+
|
|
11
|
+
IP_BURST_5M = 5
|
|
12
|
+
IP_DISTINCT_USERS_24H = 3
|
|
13
|
+
USER_CONCURRENT_HOLDS = 2
|
|
14
|
+
USER_ABANDONED_NO_CONVERT = 3
|
|
15
|
+
LARGE_QUANTITY = 10
|
|
16
|
+
|
|
17
|
+
# Highest-severity flag kind wins the drawer's headline verdict.
|
|
18
|
+
VERDICT_ORDER = %i[fraud test abandon].freeze
|
|
19
|
+
|
|
20
|
+
def initialize(hold:)
|
|
21
|
+
@hold = hold
|
|
22
|
+
@order = hold.order
|
|
23
|
+
@user = hold.user || hold.order&.user
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def call
|
|
27
|
+
result = {
|
|
28
|
+
hold: hold,
|
|
29
|
+
order: order,
|
|
30
|
+
user: user,
|
|
31
|
+
roles: roles,
|
|
32
|
+
user_orders: user_order_stats,
|
|
33
|
+
recent_orders: recent_orders,
|
|
34
|
+
user_holds: hold_stats(:user_id, user&.id),
|
|
35
|
+
ip_holds: hold_stats(:ip_address, hold.ip_address, distinct_users: true),
|
|
36
|
+
ip_recent_holds: ip_recent_holds
|
|
37
|
+
}
|
|
38
|
+
flags = flags(result)
|
|
39
|
+
result.merge(flags: flags, verdict: VERDICT_ORDER.find { |kind| flags[kind].any? } || :normal)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
attr_reader :hold, :order, :user
|
|
45
|
+
|
|
46
|
+
def roles
|
|
47
|
+
return [] unless user
|
|
48
|
+
|
|
49
|
+
Spree::Role.joins(:role_users).where(spree_role_users: { user_id: user.id }).pluck(:name)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def user_order_stats
|
|
53
|
+
empty = { completed: 0, incomplete: 0, last_completed_at: nil }
|
|
54
|
+
return empty unless user
|
|
55
|
+
|
|
56
|
+
completed, incomplete, last_completed_at = Spree::Order.where(user_id: user.id).pick(
|
|
57
|
+
Arel.sql('COUNT(*) FILTER (WHERE completed_at IS NOT NULL)'),
|
|
58
|
+
Arel.sql('COUNT(*) FILTER (WHERE completed_at IS NULL)'),
|
|
59
|
+
Arel.sql('MAX(completed_at)')
|
|
60
|
+
)
|
|
61
|
+
{ completed: completed.to_i, incomplete: incomplete.to_i, last_completed_at: last_completed_at }
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def recent_orders
|
|
65
|
+
return [] unless user
|
|
66
|
+
|
|
67
|
+
Spree::Order.where(user_id: user.id).order(created_at: :desc).limit(RECENT_LIMIT)
|
|
68
|
+
.pluck(:number, :state, :payment_state, :total, :currency, :created_at, :completed_at)
|
|
69
|
+
.map { |row| %i[number state payment_state total currency created_at completed_at].zip(row).to_h }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Burst windows end at this hold's created_at so an old hold shows the burst it was part of.
|
|
73
|
+
def hold_stats(column, value, distinct_users: false)
|
|
74
|
+
keys = %i[total converted concurrent abandoned in_3m in_5m]
|
|
75
|
+
return keys.index_with(0).merge(distinct_users: 0, distinct_users_24h: 0) if value.blank?
|
|
76
|
+
|
|
77
|
+
relation = InventoryHold.where(column => value)
|
|
78
|
+
|
|
79
|
+
at = hold.created_at
|
|
80
|
+
selects = [
|
|
81
|
+
'COUNT(*)',
|
|
82
|
+
"COUNT(*) FILTER (WHERE status = #{InventoryHold.statuses[:converted]})",
|
|
83
|
+
"COUNT(*) FILTER (WHERE status IN (#{InventoryHold.statuses.values_at(:active, :payment_locked).join(',')}))",
|
|
84
|
+
"COUNT(*) FILTER (WHERE release_reason IN (#{InventoryHold.release_reasons.values_at(:hold_expired, :payment_timeout).join(',')}))",
|
|
85
|
+
window_count(at - 3.minutes, at),
|
|
86
|
+
window_count(at - 5.minutes, at)
|
|
87
|
+
]
|
|
88
|
+
if distinct_users
|
|
89
|
+
keys += %i[distinct_users distinct_users_24h]
|
|
90
|
+
selects << 'COUNT(DISTINCT user_id)'
|
|
91
|
+
selects << sanitize('COUNT(DISTINCT user_id) FILTER (WHERE created_at BETWEEN ? AND ?)', at - 24.hours, at)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
keys.zip(relation.pick(*selects.map { |sql| Arel.sql(sql) }).map(&:to_i)).to_h
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def window_count(from, to)
|
|
98
|
+
sanitize('COUNT(*) FILTER (WHERE created_at BETWEEN ? AND ?)', from, to)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def sanitize(sql, *binds)
|
|
102
|
+
InventoryHold.sanitize_sql_array([sql, *binds])
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def ip_recent_holds
|
|
106
|
+
return [] if hold.ip_address.blank?
|
|
107
|
+
|
|
108
|
+
InventoryHold.where(ip_address: hold.ip_address).where.not(id: hold.id)
|
|
109
|
+
.left_joins(:order, :user).order(created_at: :desc).limit(RECENT_LIMIT)
|
|
110
|
+
.pluck(:id, :status, :created_at, 'spree_orders.number', 'spree_orders.state', 'spree_orders.payment_state', 'spree_users.email')
|
|
111
|
+
.map { |row| %i[id status created_at order_number order_state payment_state email].zip(row).to_h }
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def flags(result)
|
|
115
|
+
{ test: test_flags(result[:roles]), abandon: abandon_flags(result), fraud: fraud_flags(result) }
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def test_flags(roles)
|
|
119
|
+
email = user&.email.presence || order&.email.to_s
|
|
120
|
+
[
|
|
121
|
+
('Test-like email' if email.match?(TEST_EMAIL_PATTERN)),
|
|
122
|
+
("Staff role: #{roles.join(', ')}" if roles.any?),
|
|
123
|
+
('Zero total order' if order&.total.to_d.zero?),
|
|
124
|
+
('Created by another user (dashboard)' if created_by_other_user?)
|
|
125
|
+
].compact
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def created_by_other_user?
|
|
129
|
+
order&.created_by_id.present? && order.created_by_id != order.user_id
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def abandon_flags(result)
|
|
133
|
+
holds = result[:user_holds]
|
|
134
|
+
orders = result[:user_orders]
|
|
135
|
+
[
|
|
136
|
+
("#{holds[:abandoned]} abandoned holds, 0 converted" if holds[:abandoned] >= USER_ABANDONED_NO_CONVERT && holds[:converted].zero?),
|
|
137
|
+
("#{orders[:incomplete]} incomplete orders, 0 completed" if orders[:incomplete].positive? && orders[:completed].zero?)
|
|
138
|
+
].compact
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def fraud_flags(result)
|
|
142
|
+
ip = result[:ip_holds]
|
|
143
|
+
[
|
|
144
|
+
("IP burst: #{ip[:in_5m]} holds in 5m" if ip[:in_5m] >= IP_BURST_5M),
|
|
145
|
+
("#{ip[:distinct_users_24h]} different users on this IP in 24h" if ip[:distinct_users_24h] >= IP_DISTINCT_USERS_24H),
|
|
146
|
+
("#{result[:user_holds][:concurrent]} holds open at once" if result[:user_holds][:concurrent] >= USER_CONCURRENT_HOLDS),
|
|
147
|
+
("Large hold: #{hold.total_quantity_on_hold} items" if hold.total_quantity_on_hold.to_i >= LARGE_QUANTITY)
|
|
148
|
+
].compact
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
# Aggregate test/abandon/fraud signals across a filtered set of holds, for the admin holds
|
|
3
|
+
# "Overall insights" drawer. Six grouped queries, each LIMITed, regardless of how many holds match.
|
|
4
|
+
class InventoryHoldOverviewQuery
|
|
5
|
+
TOP_LIMIT = 10
|
|
6
|
+
BURST_BINS = { '3m' => 180, '5m' => 300 }.freeze
|
|
7
|
+
|
|
8
|
+
# `holds` may carry ransack joins; wrapping it as an id subquery keeps the raw SQL below unambiguous.
|
|
9
|
+
def initialize(holds:)
|
|
10
|
+
@holds = InventoryHold.where(id: holds.reorder(nil).select(:id))
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def call
|
|
14
|
+
{
|
|
15
|
+
funnel: funnel,
|
|
16
|
+
top_ips: top_ips,
|
|
17
|
+
bursts: BURST_BINS.transform_values { |seconds| bursts(seconds) },
|
|
18
|
+
abandoners: abandoners,
|
|
19
|
+
test_accounts: test_accounts
|
|
20
|
+
}
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
attr_reader :holds
|
|
26
|
+
|
|
27
|
+
def funnel
|
|
28
|
+
statuses = InventoryHold.statuses
|
|
29
|
+
reasons = InventoryHold.release_reasons
|
|
30
|
+
keys = %i[total converted open cart_abandoned payment_abandoned user_canceled cart_changed]
|
|
31
|
+
row = holds.pick(
|
|
32
|
+
Arel.sql('COUNT(*)'),
|
|
33
|
+
Arel.sql("COUNT(*) FILTER (WHERE status = #{statuses[:converted]})"),
|
|
34
|
+
Arel.sql("COUNT(*) FILTER (WHERE status IN (#{statuses.values_at(:pending, :active, :payment_locked).join(',')}))"),
|
|
35
|
+
*reasons.values_at(:hold_expired, :payment_timeout, :user_canceled, :cart_changed)
|
|
36
|
+
.map { |value| Arel.sql("COUNT(*) FILTER (WHERE release_reason = #{value})") }
|
|
37
|
+
)
|
|
38
|
+
result = keys.zip(row.map(&:to_i)).to_h
|
|
39
|
+
result.merge(conversion_rate: result[:total].zero? ? 0 : (100.0 * result[:converted] / result[:total]).round(1))
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def top_ips
|
|
43
|
+
holds.where.not(ip_address: [nil, '']).group(:ip_address)
|
|
44
|
+
.order(Arel.sql('COUNT(*) DESC')).limit(TOP_LIMIT)
|
|
45
|
+
.pluck(:ip_address, Arel.sql('COUNT(*)'), Arel.sql('COUNT(DISTINCT user_id)'),
|
|
46
|
+
Arel.sql("COUNT(*) FILTER (WHERE status = #{InventoryHold.statuses[:converted]})")
|
|
47
|
+
)
|
|
48
|
+
.map { |row| %i[ip_address holds users converted].zip(row).to_h }
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Fixed-width time buckets per IP; the busiest buckets are the bursts worth checking.
|
|
52
|
+
def bursts(seconds)
|
|
53
|
+
bucket = "to_timestamp(floor(extract(epoch FROM created_at) / #{seconds.to_i}) * #{seconds.to_i})"
|
|
54
|
+
holds.where.not(ip_address: [nil, '']).group(:ip_address, Arel.sql(bucket))
|
|
55
|
+
.having('COUNT(*) > 1').order(Arel.sql('COUNT(*) DESC')).limit(TOP_LIMIT)
|
|
56
|
+
.pluck(:ip_address, Arel.sql(bucket), Arel.sql('COUNT(*)'), Arel.sql('COUNT(DISTINCT user_id)'))
|
|
57
|
+
.map { |ip, started_at, count, users| { ip_address: ip, started_at: started_at&.in_time_zone, holds: count, users: users } }
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def abandoners
|
|
61
|
+
reasons = InventoryHold.release_reasons.values_at(:hold_expired, :payment_timeout).join(',')
|
|
62
|
+
abandoned = "COUNT(*) FILTER (WHERE cm_inventory_holds.release_reason IN (#{reasons}))"
|
|
63
|
+
holds.joins(:user).group(:user_id, 'spree_users.email')
|
|
64
|
+
.having("#{abandoned} > 0 AND COUNT(*) FILTER (WHERE cm_inventory_holds.status = #{InventoryHold.statuses[:converted]}) = 0")
|
|
65
|
+
.order(Arel.sql("#{abandoned} DESC")).limit(TOP_LIMIT)
|
|
66
|
+
.pluck(:user_id, 'spree_users.email', Arel.sql(abandoned), Arel.sql('COUNT(*)'))
|
|
67
|
+
.map { |row| %i[user_id email abandoned holds].zip(row).to_h }
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def test_accounts
|
|
71
|
+
staff = 'EXISTS (SELECT 1 FROM spree_role_users ru WHERE ru.user_id = spree_users.id)'
|
|
72
|
+
holds.joins(:user)
|
|
73
|
+
.where("spree_users.email ~* ? OR #{staff}", InventoryHoldInsightsQuery::TEST_EMAIL_SOURCE)
|
|
74
|
+
.group(:user_id, 'spree_users.email').order(Arel.sql('COUNT(*) DESC')).limit(TOP_LIMIT)
|
|
75
|
+
.pluck(:user_id, 'spree_users.email', Arel.sql('COUNT(*)'), Arel.sql("bool_or(#{staff})"))
|
|
76
|
+
.map { |row| %i[user_id email holds staff].zip(row).to_h }
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
module Seats
|
|
3
|
+
# A variant's free seats, grouped into runs of side-by-side seats for auto-assign.
|
|
4
|
+
#
|
|
5
|
+
# Walks the variant's linked seats in Block#seat_index order (see SeatLayouts::SaveSeatOrder), one
|
|
6
|
+
# layout at a time since each layout is numbered on its own:
|
|
7
|
+
# - a skipped number is the organizer's row break, so it starts the next stroke (0, 1, 2… in sell
|
|
8
|
+
# order) and ends the run;
|
|
9
|
+
# - a taken seat ends the run too, so a run is always seats a party can sit in together.
|
|
10
|
+
#
|
|
11
|
+
# seat_index: 1 2 3 5 6 7 (4 skipped: row break)
|
|
12
|
+
# taken: ✗
|
|
13
|
+
# runs: stroke 0 [1, 2], stroke 1 [5, 6, 7]
|
|
14
|
+
#
|
|
15
|
+
# Only active layouts count: an inactive/archived layout's seats are not on sale.
|
|
16
|
+
class FreeRunsQuery
|
|
17
|
+
Run = Struct.new(:seat_layout_id, :stroke, :start_index, :block_ids, keyword_init: true) do
|
|
18
|
+
delegate :size, to: :block_ids
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def initialize(variant_id:, inventory_item_id:)
|
|
22
|
+
@variant_id = variant_id
|
|
23
|
+
@inventory_item_id = inventory_item_id
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def call
|
|
27
|
+
seats = linked_seats.pluck(:id, :seat_layout_id, :seat_index)
|
|
28
|
+
taken = ReservedBlock.unavailable.where(inventory_item_id: @inventory_item_id, block_id: linked_seats.select(:id))
|
|
29
|
+
.pluck(:block_id).to_set
|
|
30
|
+
|
|
31
|
+
seats.group_by { |_id, seat_layout_id, _index| seat_layout_id }.flat_map do |seat_layout_id, layout_seats|
|
|
32
|
+
runs_in(seat_layout_id, layout_seats, taken)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
def linked_seats
|
|
39
|
+
Block.joins(:seat_layout)
|
|
40
|
+
.where(variant_id: @variant_id, cm_seat_layouts: { status: SeatLayout.statuses[:active] })
|
|
41
|
+
.where.not(seat_index: nil)
|
|
42
|
+
.order(:seat_layout_id, :seat_index)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def runs_in(seat_layout_id, seats, taken)
|
|
46
|
+
runs = []
|
|
47
|
+
stroke = 0
|
|
48
|
+
run = nil
|
|
49
|
+
|
|
50
|
+
seats.each_with_index do |(id, _seat_layout_id, index), i|
|
|
51
|
+
if i.positive? && index != seats[i - 1][2] + 1
|
|
52
|
+
stroke += 1
|
|
53
|
+
run = nil
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
if taken.include?(id)
|
|
57
|
+
run = nil
|
|
58
|
+
next
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
if run.nil?
|
|
62
|
+
run = Run.new(seat_layout_id: seat_layout_id, stroke: stroke, start_index: index, block_ids: [])
|
|
63
|
+
runs << run
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
run.block_ids << id
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
runs
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -11,7 +11,7 @@ module Spree
|
|
|
11
11
|
:high_demand, :jwt_token,
|
|
12
12
|
:direction, :trip_id, :boarding_trip_stop_id, :drop_off_trip_stop_id,
|
|
13
13
|
:service_fee_total, :display_service_fee_total,
|
|
14
|
-
:parent_id, :relation_type, :bundle_amount, :display_bundle_amount
|
|
14
|
+
:parent_id, :relation_type, :bundle_amount, :display_bundle_amount, :seat_assignment_status
|
|
15
15
|
|
|
16
16
|
base.attribute :required_self_check_in_location, &:required_self_check_in_location?
|
|
17
17
|
base.attribute :allowed_self_check_in, &:allowed_self_check_in?
|
|
@@ -19,7 +19,7 @@ module Spree
|
|
|
19
19
|
:use_video_as_default, :allow_transfer, :allow_gift_transfer
|
|
20
20
|
|
|
21
21
|
base.attributes :reveal_description, :discontinue_on, :public_metadata, :purchasable_on, :preview,
|
|
22
|
-
:enable_inventory_hold
|
|
22
|
+
:enable_inventory_hold, :auto_assign_seats
|
|
23
23
|
|
|
24
24
|
# Expose only the `event_id` here instead of the full event object.
|
|
25
25
|
# This lets the client fetch event details separately (usually already cached),
|
|
@@ -12,7 +12,7 @@ module Spree
|
|
|
12
12
|
:completion_steps, :available_social_contact_platforms, :allow_anonymous_booking,
|
|
13
13
|
:discontinue_on, :high_demand, :jwt_token, :pre_tax_amount, :display_pre_tax_amount, :public_metadata,
|
|
14
14
|
:direction, :trip_id, :boarding_trip_stop_id, :drop_off_trip_stop_id, :remark,
|
|
15
|
-
:service_fee_total, :display_service_fee_total
|
|
15
|
+
:service_fee_total, :display_service_fee_total, :seat_assignment_status
|
|
16
16
|
|
|
17
17
|
attribute :required_self_check_in_location, &:required_self_check_in_location?
|
|
18
18
|
attribute :allowed_self_check_in, &:allowed_self_check_in?
|
|
@@ -166,6 +166,13 @@ module SpreeCmCommissioner::Integrations::Base
|
|
|
166
166
|
message: error.message,
|
|
167
167
|
code: error.class.name.split('::').last
|
|
168
168
|
}
|
|
169
|
+
# The scheduler reads this to honour Retry-After.
|
|
170
|
+
@error[:retry_after] = error.retry_after if error.respond_to?(:retry_after) && error.retry_after
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# True when the last recorded error is a 429 from the partner.
|
|
174
|
+
def rate_limited?
|
|
175
|
+
@error.present? && @error[:code] == 'RateLimitedError'
|
|
169
176
|
end
|
|
170
177
|
|
|
171
178
|
# Check if sync was successful
|
data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/external_client/client.rb
CHANGED
|
@@ -41,7 +41,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
41
41
|
# @param destination_id [String] The destination location ID
|
|
42
42
|
# @param on_date [String] The travel date (YYYY-MM-DD format)
|
|
43
43
|
# @return [Array<SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::Trip>] Array of available trip objects
|
|
44
|
-
|
|
44
|
+
# @param lane [Symbol] :customer when a customer is waiting for the answer (see CallLimiter)
|
|
45
|
+
def search_trips!(origin_id:, destination_id:, on_date:, lane: :background)
|
|
45
46
|
params = {
|
|
46
47
|
origin_id: origin_id,
|
|
47
48
|
destination_id: destination_id,
|
|
@@ -53,7 +54,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
53
54
|
}.compact
|
|
54
55
|
endpoint = "#{BASE_PATH}/trip_availabilities"
|
|
55
56
|
|
|
56
|
-
response = get(endpoint, params)
|
|
57
|
+
response = get(endpoint, params, nil, lane: lane)
|
|
57
58
|
handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::Trip, collection: true)
|
|
58
59
|
end
|
|
59
60
|
|
|
@@ -66,7 +67,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
66
67
|
# @param on_date [String] The travel date (YYYY-MM-DD format)
|
|
67
68
|
# @param show_all_stops [Boolean] Whether to show all stops (default: false)
|
|
68
69
|
# @return [SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::SeatLayout] Seat layout object
|
|
69
|
-
|
|
70
|
+
# @param lane [Symbol] :customer when a customer is waiting for the answer (see CallLimiter)
|
|
71
|
+
def get_seat_layout!(trip_id:, from_stop_id:, to_stop_id:, on_date:, show_all_stops: false, lane: :background) # rubocop:disable Metrics/ParameterLists
|
|
70
72
|
params = {
|
|
71
73
|
trip_id: trip_id,
|
|
72
74
|
from_stop_id: from_stop_id,
|
|
@@ -76,7 +78,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
76
78
|
}
|
|
77
79
|
endpoint = "#{BASE_PATH}/seat_layouts"
|
|
78
80
|
|
|
79
|
-
response = get(endpoint, params)
|
|
81
|
+
response = get(endpoint, params, nil, lane: lane)
|
|
80
82
|
handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::SeatLayout)
|
|
81
83
|
end
|
|
82
84
|
|
|
@@ -125,7 +127,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
125
127
|
request: { method: 'POST', endpoint: endpoint, body: body },
|
|
126
128
|
auditable: params[:internal_order]
|
|
127
129
|
) do
|
|
128
|
-
response = post(endpoint, body)
|
|
130
|
+
response = post(endpoint, body, lane: :checkout)
|
|
129
131
|
handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::ReservationCart)
|
|
130
132
|
end
|
|
131
133
|
end
|
|
@@ -142,7 +144,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
142
144
|
request: { method: 'POST', endpoint: endpoint, body: {} },
|
|
143
145
|
auditable: internal_order
|
|
144
146
|
) do
|
|
145
|
-
response = post(endpoint, {})
|
|
147
|
+
response = post(endpoint, {}, lane: :checkout)
|
|
146
148
|
handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::WalletPayment)
|
|
147
149
|
end
|
|
148
150
|
end
|
|
@@ -158,7 +160,7 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
158
160
|
request: { method: 'POST', endpoint: endpoint, body: {} },
|
|
159
161
|
auditable: internal_order
|
|
160
162
|
) do
|
|
161
|
-
response = post(endpoint, {})
|
|
163
|
+
response = post(endpoint, {}, lane: :checkout)
|
|
162
164
|
handle_response(response, SpreeCmCommissioner::Integrations::BookMeBusV1::Resources::WalletPayment)
|
|
163
165
|
end
|
|
164
166
|
end
|
|
@@ -216,6 +218,12 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
216
218
|
end
|
|
217
219
|
|
|
218
220
|
def raise_api_error(response)
|
|
221
|
+
raise_rate_limited(response) if response.status == 429
|
|
222
|
+
|
|
223
|
+
raise_failed_request(response)
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def raise_failed_request(response)
|
|
219
227
|
status = response.status
|
|
220
228
|
body = response.body
|
|
221
229
|
|
|
@@ -237,5 +245,14 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
237
245
|
|
|
238
246
|
raise SpreeCmCommissioner::Integrations::ExternalClientError.new(message, status)
|
|
239
247
|
end
|
|
248
|
+
|
|
249
|
+
def raise_rate_limited(response)
|
|
250
|
+
retry_after = SpreeCmCommissioner::Integrations::RateLimitedError.parse_retry_after(response.headers['Retry-After'])
|
|
251
|
+
error = SpreeCmCommissioner::Integrations::RateLimitedError.new('API request failed with status 429', retry_after: retry_after)
|
|
252
|
+
|
|
253
|
+
# Everything but checkout stops calling the partner until its Retry-After has passed.
|
|
254
|
+
call_limiter.pause!(error.retry_after)
|
|
255
|
+
raise error
|
|
256
|
+
end
|
|
240
257
|
end
|
|
241
258
|
end
|
data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/external_client/connection.rb
CHANGED
|
@@ -4,24 +4,24 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
4
4
|
REQUEST_TIMEOUT = 30
|
|
5
5
|
OPEN_TIMEOUT = 10
|
|
6
6
|
|
|
7
|
-
def get(url, params = nil, headers = nil)
|
|
8
|
-
execute_request { connection.get(url, params, build_headers(headers)) }
|
|
7
|
+
def get(url, params = nil, headers = nil, lane: :background)
|
|
8
|
+
execute_request(lane: lane) { connection.get(url, params, build_headers(headers)) }
|
|
9
9
|
end
|
|
10
10
|
|
|
11
|
-
def post(url, body = nil, headers = nil)
|
|
12
|
-
execute_request { connection.post(url, body, build_headers(headers)) }
|
|
11
|
+
def post(url, body = nil, headers = nil, lane: :background)
|
|
12
|
+
execute_request(lane: lane) { connection.post(url, body, build_headers(headers)) }
|
|
13
13
|
end
|
|
14
14
|
|
|
15
|
-
def put(url, body = nil, headers = nil)
|
|
16
|
-
execute_request { connection.put(url, body, build_headers(headers)) }
|
|
15
|
+
def put(url, body = nil, headers = nil, lane: :background)
|
|
16
|
+
execute_request(lane: lane) { connection.put(url, body, build_headers(headers)) }
|
|
17
17
|
end
|
|
18
18
|
|
|
19
|
-
def patch(url, body = nil, headers = nil)
|
|
20
|
-
execute_request { connection.patch(url, body, build_headers(headers)) }
|
|
19
|
+
def patch(url, body = nil, headers = nil, lane: :background)
|
|
20
|
+
execute_request(lane: lane) { connection.patch(url, body, build_headers(headers)) }
|
|
21
21
|
end
|
|
22
22
|
|
|
23
|
-
def delete(url, params = nil, headers = nil)
|
|
24
|
-
execute_request { connection.delete(url, params, build_headers(headers)) }
|
|
23
|
+
def delete(url, params = nil, headers = nil, lane: :background)
|
|
24
|
+
execute_request(lane: lane) { connection.delete(url, params, build_headers(headers)) }
|
|
25
25
|
end
|
|
26
26
|
|
|
27
27
|
def connection
|
|
@@ -52,6 +52,10 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
52
52
|
@token_mutex ||= Mutex.new
|
|
53
53
|
end
|
|
54
54
|
|
|
55
|
+
def call_limiter
|
|
56
|
+
@call_limiter ||= SpreeCmCommissioner::Integrations::CallLimiter.new(base_url: @integration.base_url)
|
|
57
|
+
end
|
|
58
|
+
|
|
55
59
|
def token_expired?
|
|
56
60
|
@access_token.blank? || @token_expires_at.blank? || Time.current >= @token_expires_at
|
|
57
61
|
end
|
|
@@ -81,15 +85,17 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::ExternalClient
|
|
|
81
85
|
reset_connection
|
|
82
86
|
end
|
|
83
87
|
|
|
84
|
-
#
|
|
85
|
-
def execute_request(retry_count: 0, &block)
|
|
88
|
+
# Runs the request, refreshing the token once on a 401. Counted against CallLimiter first, except checkout calls.
|
|
89
|
+
def execute_request(lane: :background, retry_count: 0, &block)
|
|
90
|
+
call_limiter.take!(lane: lane)
|
|
91
|
+
|
|
86
92
|
response = block.call
|
|
87
93
|
|
|
88
94
|
if response.status == 401 && retry_count.zero?
|
|
89
95
|
invalidate_token
|
|
90
96
|
access_token
|
|
91
97
|
reset_connection
|
|
92
|
-
return execute_request(retry_count: 1, &block)
|
|
98
|
+
return execute_request(lane: lane, retry_count: 1, &block)
|
|
93
99
|
end
|
|
94
100
|
|
|
95
101
|
response
|
|
@@ -51,9 +51,11 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
51
51
|
|
|
52
52
|
return unless should_sync_item?(inventory_item_mapping)
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
# Before the transaction: the call can take up to 30 s and would hold a database connection.
|
|
55
|
+
external_trip = fetch_external_trip(trip, on_date)
|
|
56
|
+
return if external_trip.nil? # no mapping data to look it up: leave the inventory untouched
|
|
56
57
|
|
|
58
|
+
ActiveRecord::Base.transaction do
|
|
57
59
|
case external_trip
|
|
58
60
|
when UNAVAILABLE
|
|
59
61
|
# A confirmed response (not a failed/ambiguous lookup - see fetch_external_trip) shows
|
|
@@ -62,8 +64,6 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
62
64
|
# Zero it out so BookMe+ stops selling a date BookMeBus has pulled, rather than only
|
|
63
65
|
# discovering that at the very end of checkout, after payment has been taken.
|
|
64
66
|
zero_out_inventory!(inventory_item)
|
|
65
|
-
when nil
|
|
66
|
-
return # rubocop:disable Rails/TransactionExitStatement -- couldn't determine (missing mapping data) - leave existing inventory untouched rather than guess
|
|
67
67
|
else
|
|
68
68
|
sync_price(inventory_item, external_trip)
|
|
69
69
|
|
|
@@ -79,6 +79,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
79
79
|
|
|
80
80
|
update_last_sync_at(inventory_item_mapping)
|
|
81
81
|
end
|
|
82
|
+
rescue SpreeCmCommissioner::Integrations::RateLimitedError
|
|
83
|
+
raise # #call records it and stops: the remaining items would only be refused too
|
|
82
84
|
rescue StandardError => e
|
|
83
85
|
@sync_result.record_error(e)
|
|
84
86
|
CmAppLogger.error(label: '[BookMeBusV1::SyncItemAvailability] error', data: { inventory_item_id: inventory_item.id, error: e.message })
|
|
@@ -179,7 +181,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
179
181
|
client.search_trips!(
|
|
180
182
|
origin_id: origin_id,
|
|
181
183
|
destination_id: destination_id,
|
|
182
|
-
on_date: on_date
|
|
184
|
+
on_date: on_date,
|
|
185
|
+
lane: :customer
|
|
183
186
|
) || []
|
|
184
187
|
end
|
|
185
188
|
end
|
|
@@ -295,9 +298,12 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
295
298
|
trip_id: external_trip.id,
|
|
296
299
|
from_stop_id: external_trip.from_stop_id,
|
|
297
300
|
to_stop_id: external_trip.to_stop_id,
|
|
298
|
-
on_date: external_trip.on_date || Time.zone.today.to_s
|
|
301
|
+
on_date: external_trip.on_date || Time.zone.today.to_s,
|
|
302
|
+
lane: :customer
|
|
299
303
|
)
|
|
300
304
|
end
|
|
305
|
+
rescue SpreeCmCommissioner::Integrations::RateLimitedError
|
|
306
|
+
raise
|
|
301
307
|
rescue SpreeCmCommissioner::Integrations::ExternalClientError => e
|
|
302
308
|
CmAppLogger.error(label: '[BookMeBusV1::SyncItemAvailability] get_seat_layout failed', data: { error: e.message })
|
|
303
309
|
@sync_result.record_error(e)
|
data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_locations.rb
CHANGED
|
@@ -3,6 +3,10 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
3
3
|
# Initialize SyncLocations service
|
|
4
4
|
# @param integration [SpreeCmCommissioner::Integrations::BookMeBusV1] The integration instance
|
|
5
5
|
# @param sync_result [SpreeCmCommissioner::Integrations::Base::SyncResult] Optional sync result tracker
|
|
6
|
+
# The operator's trips with their cities, as fetched by the last call. SyncRoutes builds routes from the same
|
|
7
|
+
# answer, so the full sync asks BookMeBus once for it, not once per step.
|
|
8
|
+
attr_reader :trip_locations
|
|
9
|
+
|
|
6
10
|
def initialize(integration:, sync_result: nil)
|
|
7
11
|
@integration = integration
|
|
8
12
|
@sync_result = sync_result || SpreeCmCommissioner::Integrations::Base::SyncResult.new
|
|
@@ -50,13 +54,15 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
50
54
|
end
|
|
51
55
|
|
|
52
56
|
def fetch_external_locations
|
|
53
|
-
trip_locations = begin
|
|
57
|
+
@trip_locations = begin
|
|
54
58
|
@sync_result.track_api_call('get_trip_locations') { client.get_trip_locations! }
|
|
59
|
+
rescue SpreeCmCommissioner::Integrations::RateLimitedError
|
|
60
|
+
raise # the strategy stops the whole run on a 429, see FullSyncStrategy
|
|
55
61
|
rescue SpreeCmCommissioner::Integrations::ExternalClientError => e
|
|
56
62
|
raise SpreeCmCommissioner::Integrations::SyncError, "Failed to sync locations: #{e.message}"
|
|
57
63
|
end
|
|
58
64
|
|
|
59
|
-
trip_locations.flat_map(&:locations).uniq(&:id)
|
|
65
|
+
@trip_locations.flat_map(&:locations).uniq(&:id)
|
|
60
66
|
end
|
|
61
67
|
|
|
62
68
|
# Sync a single location and create it as a place with vendor place mapping
|
|
@@ -99,7 +105,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
99
105
|
tracker.save_if_changed!(vendor_place)
|
|
100
106
|
end
|
|
101
107
|
|
|
102
|
-
|
|
108
|
+
# Saved only when something changed (or an hour has passed): most runs find every location as it was.
|
|
109
|
+
mapping.confirm_active!(external_payload: external_location.to_h)
|
|
103
110
|
mapping
|
|
104
111
|
end
|
|
105
112
|
|
|
@@ -3,9 +3,11 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
3
3
|
# Initialize SyncRoutes service
|
|
4
4
|
# @param integration [SpreeCmCommissioner::Integrations::BookMeBusV1] The integration instance
|
|
5
5
|
# @param sync_result [SpreeCmCommissioner::Integrations::Base::SyncResult] Optional sync result tracker
|
|
6
|
-
|
|
6
|
+
# @param trip_locations [Array, nil] the answer SyncLocations already got from BookMeBus. Fetched here when absent.
|
|
7
|
+
def initialize(integration:, sync_result: nil, trip_locations: nil)
|
|
7
8
|
@integration = integration
|
|
8
9
|
@sync_result = sync_result || SpreeCmCommissioner::Integrations::Base::SyncResult.new
|
|
10
|
+
@trip_locations = trip_locations
|
|
9
11
|
end
|
|
10
12
|
|
|
11
13
|
def call
|
|
@@ -70,7 +72,8 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
70
72
|
tracker.save_if_changed!(route)
|
|
71
73
|
end
|
|
72
74
|
|
|
73
|
-
|
|
75
|
+
# Saved only when something changed (or an hour has passed): most runs find every route as it was.
|
|
76
|
+
mapping.confirm_active!(
|
|
74
77
|
external_payload: {
|
|
75
78
|
origin_place_id: origin_mapping.external_id,
|
|
76
79
|
destination_place_id: destination_mapping.external_id,
|
|
@@ -109,7 +112,13 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
109
112
|
|
|
110
113
|
# Raised before any route is written, so a failed call never reaches cleanup_stale_mappings!.
|
|
111
114
|
def external_trip_locations
|
|
115
|
+
# The answer handed in by the full sync, if any. Not remembered after a fetch: a second call on this object must
|
|
116
|
+
# ask BookMeBus again.
|
|
117
|
+
return @trip_locations if @trip_locations
|
|
118
|
+
|
|
112
119
|
@sync_result.track_api_call('get_trip_locations') { client.get_trip_locations! }
|
|
120
|
+
rescue SpreeCmCommissioner::Integrations::RateLimitedError
|
|
121
|
+
raise # the strategy stops the whole run on a 429, see FullSyncStrategy
|
|
113
122
|
rescue SpreeCmCommissioner::Integrations::ExternalClientError => e
|
|
114
123
|
raise SpreeCmCommissioner::Integrations::SyncError, "Failed to sync routes: #{e.message}"
|
|
115
124
|
end
|