spree_cm_commissioner 2.16.0 → 2.16.1
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/Gemfile.lock +1 -1
- data/app/controllers/spree/admin/inventory_holds_controller.rb +10 -3
- data/app/controllers/spree/admin/inventory_monitorings_controller.rb +1 -1
- data/app/controllers/spree/api/v2/storefront/user_device_token_registrations_controller.rb +1 -0
- data/app/controllers/spree/api/v2/tenant/user_device_tokens_controller.rb +1 -0
- data/app/controllers/spree_cm_commissioner/admin/orders_controller_decorator.rb +2 -0
- data/app/factory/spree_cm_commissioner/order_telegram_message_factory.rb +15 -1
- data/app/helpers/spree_cm_commissioner/admin/transit_line_items_helper.rb +89 -0
- data/app/interactors/spree_cm_commissioner/account_linkage.rb +2 -1
- data/app/interactors/spree_cm_commissioner/firebase_email_fetcher.rb +34 -11
- data/app/interactors/spree_cm_commissioner/firebase_email_fetcher_cron_executor.rb +42 -12
- data/app/interactors/spree_cm_commissioner/firebase_id_token_provider.rb +13 -14
- data/app/interactors/spree_cm_commissioner/user_device_token_register.rb +2 -1
- data/app/interactors/spree_cm_commissioner/user_id_token_authenticator.rb +29 -11
- data/app/interactors/spree_cm_commissioner/user_id_token_checker.rb +7 -5
- data/app/interactors/spree_cm_commissioner/user_registration_with_id_token.rb +10 -9
- data/app/jobs/spree_cm_commissioner/firebase_email_fetcher_job.rb +3 -2
- data/app/models/concerns/spree_cm_commissioner/line_item_integration.rb +13 -0
- data/app/models/concerns/spree_cm_commissioner/route_type.rb +1 -1
- data/app/models/concerns/spree_cm_commissioner/service_type.rb +1 -1
- data/app/models/spree_cm_commissioner/integration.rb +7 -0
- data/app/models/spree_cm_commissioner/integrations/book_me_bus_v1.rb +8 -0
- data/app/models/spree_cm_commissioner/integrations/larryta.rb +7 -0
- data/app/models/spree_cm_commissioner/taxon_decorator.rb +1 -0
- data/app/models/spree_cm_commissioner/taxonomy_decorator.rb +11 -0
- data/app/models/spree_cm_commissioner/tenant.rb +52 -0
- data/app/models/spree_cm_commissioner/vendor_decorator.rb +6 -0
- data/app/notifications/delivery_methods/firebase_project_fcm.rb +55 -0
- data/app/notifications/noticed_fcm_base.rb +6 -1
- data/app/overrides/spree/admin/orders/_line_items/_line_items.html.erb.deface +21 -1
- data/app/queries/spree_cm_commissioner/inventory_hold_insights_query.rb +29 -11
- data/app/queries/spree_cm_commissioner/inventory_hold_overview_query.rb +6 -6
- data/app/request_schemas/spree_cm_commissioner/trip_search_request_schema.rb +8 -0
- data/app/serializers/spree/v2/storefront/user_device_token_serializer.rb +1 -1
- data/app/serializers/spree/v2/tenant/user_device_token_serializer.rb +1 -1
- data/app/services/spree_cm_commissioner/device_tokens/prune_other_projects.rb +24 -0
- data/app/services/spree_cm_commissioner/firebase_emails/resolve.rb +40 -0
- data/app/services/spree_cm_commissioner/firebase_projects.rb +39 -0
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/inventory/unstock_inventory.rb +11 -3
- data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trip_stop.rb +57 -18
- data/app/services/spree_cm_commissioner/inventory_items/reset.rb +13 -0
- data/app/services/spree_cm_commissioner/rates_availabilities/bulk_update.rb +11 -3
- data/app/services/spree_cm_commissioner/trips/update_single_leg.rb +2 -1
- data/app/services/spree_cm_commissioner/waiting_room/sessions/issue.rb +18 -4
- data/app/views/spree/admin/inventory_holds/_overview.html.erb +4 -1
- data/app/views/spree/admin/inventory_holds/_search.html.erb +10 -0
- data/app/views/spree/admin/orders/_transit_line_item.html.erb +103 -0
- data/app/views/spree/admin/rates_availabilities/_script.html.erb +6 -2
- data/app/views/spree/admin/tenants/_form.html.erb +21 -0
- data/app/views/spree/admin/tenants/form/_firebase.html.erb +32 -0
- data/config/initializers/user_manager_decorator.rb +3 -1
- data/config/locales/en.yml +5 -0
- data/config/locales/km.yml +5 -0
- data/db/migrate/20261119000001_add_firebase_project_to_cm_tenants.rb +12 -0
- data/db/migrate/20261119000002_add_firebase_project_id_to_cm_device_tokens.rb +6 -0
- data/db/migrate/20261120000001_add_internal_index_to_cm_integration_mappings.rb +10 -0
- data/lib/spree_cm_commissioner/test_helper/factories/user_factory.rb +3 -1
- data/lib/spree_cm_commissioner/test_helper/firebase_id_token_helper.rb +53 -0
- data/lib/spree_cm_commissioner/version.rb +1 -1
- data/lib/tasks/fetch_email.rake +4 -3
- data/lib/tasks/prune_device_tokens.rake +10 -0
- metadata +14 -2
|
@@ -106,6 +106,7 @@ module SpreeCmCommissioner
|
|
|
106
106
|
|
|
107
107
|
base.scope :shows, -> { where(taxonomy_id: Spree::Taxonomy.shows.id, depth: 1) }
|
|
108
108
|
base.scope :events, -> { where(taxonomy_id: Spree::Taxonomy.events.id, depth: 1) }
|
|
109
|
+
base.scope :activities, -> { where(taxonomy_id: Spree::Taxonomy.activities.id, depth: 1) }
|
|
109
110
|
base.scope :ad_campaigns, -> { where(taxonomy_id: Spree::Taxonomy.ads.id, depth: 1) }
|
|
110
111
|
|
|
111
112
|
# Event taxons currently inside their live-stock sale window — see
|
|
@@ -15,6 +15,17 @@ module SpreeCmCommissioner
|
|
|
15
15
|
end
|
|
16
16
|
end
|
|
17
17
|
|
|
18
|
+
# Tours, classes and other bookable experiences sold from the /activity dashboard. Kept apart from Events so
|
|
19
|
+
# each dashboard only lists its own taxons, while sharing the event-style taxon/ticket model (kind: event).
|
|
20
|
+
def base.activities
|
|
21
|
+
ActiveRecord::Base.connected_to(role: :writing) do
|
|
22
|
+
activities = Spree::Taxonomy.find_or_create_by(name: 'Activities', store: Spree::Store.default)
|
|
23
|
+
activities.kind = :event
|
|
24
|
+
activities.save if activities.changed?
|
|
25
|
+
activities
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
18
29
|
def base.shows
|
|
19
30
|
ActiveRecord::Base.connected_to(role: :writing) do
|
|
20
31
|
shows = Spree::Taxonomy.find_or_create_by(name: 'Shows', store: Spree::Store.default)
|
|
@@ -26,11 +26,23 @@ module SpreeCmCommissioner
|
|
|
26
26
|
|
|
27
27
|
validates :sms_sender_id, length: { maximum: 11 }, allow_blank: true
|
|
28
28
|
|
|
29
|
+
# Service account JSON for this tenant's own Firebase project, used to send its app's pushes and
|
|
30
|
+
# look up its users' emails. Ciphertext at rest; the admin form never renders it back.
|
|
31
|
+
encrypts :firebase_service_account
|
|
32
|
+
|
|
33
|
+
# The admin form uploads the key file, and the project ID is read from it so the two can't drift.
|
|
34
|
+
# Ticking remove switches the tenant back to the shared project.
|
|
35
|
+
attr_accessor :firebase_service_account_upload, :remove_firebase_project
|
|
36
|
+
|
|
37
|
+
validate :firebase_service_account_matches_project
|
|
38
|
+
|
|
29
39
|
validates :default_currency, inclusion: { in: -> (tenant) { tenant.supported_currencies_list } }, allow_blank: true
|
|
30
40
|
|
|
31
41
|
enum state: { enabled: 0, disabled: 1 }
|
|
32
42
|
|
|
33
43
|
before_validation :generate_slug, if: -> { slug.blank? && name.present? }
|
|
44
|
+
before_validation :assign_firebase_service_account_from_upload, if: -> { firebase_service_account_upload.present? }
|
|
45
|
+
before_validation :normalize_firebase_project
|
|
34
46
|
|
|
35
47
|
validate :single_active_vendor
|
|
36
48
|
|
|
@@ -69,6 +81,15 @@ module SpreeCmCommissioner
|
|
|
69
81
|
supported_currencies_list.include?(currency.to_s.upcase)
|
|
70
82
|
end
|
|
71
83
|
|
|
84
|
+
def firebase_service_account_credentials
|
|
85
|
+
return if firebase_service_account.blank?
|
|
86
|
+
|
|
87
|
+
credentials = JSON.parse(firebase_service_account)
|
|
88
|
+
credentials.symbolize_keys if credentials.is_a?(Hash)
|
|
89
|
+
rescue JSON::ParserError
|
|
90
|
+
nil
|
|
91
|
+
end
|
|
92
|
+
|
|
72
93
|
# Three tiers, each only reached if the previous is unusable:
|
|
73
94
|
# 1. This tenant's own explicit default_currency, if set.
|
|
74
95
|
# 2. The platform's own default currency -- but only if it's inside this tenant's own
|
|
@@ -97,6 +118,37 @@ module SpreeCmCommissioner
|
|
|
97
118
|
self.slug = name.parameterize if slug.blank?
|
|
98
119
|
end
|
|
99
120
|
|
|
121
|
+
# Not validated here: `valid?` runs this before the validators, which report a bad file below. The
|
|
122
|
+
# upload is consumed so a later save of the same object doesn't read the spent file again.
|
|
123
|
+
def assign_firebase_service_account_from_upload
|
|
124
|
+
upload = firebase_service_account_upload
|
|
125
|
+
self.firebase_service_account_upload = nil
|
|
126
|
+
self.firebase_service_account = upload.respond_to?(:read) ? upload.read : upload.to_s
|
|
127
|
+
self.firebase_project_id = firebase_service_account_credentials&.dig(:project_id)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# A blank id must stay NULL so the tenant reads as on the shared project. Only an explicit remove drops the key;
|
|
131
|
+
# a key left without its project fails validation instead of being discarded quietly.
|
|
132
|
+
def normalize_firebase_project
|
|
133
|
+
if ActiveModel::Type::Boolean.new.cast(remove_firebase_project)
|
|
134
|
+
self.firebase_project_id = nil
|
|
135
|
+
self.firebase_service_account = nil
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
self.firebase_project_id = firebase_project_id.to_s.strip.presence
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def firebase_service_account_matches_project
|
|
142
|
+
return if firebase_service_account.blank?
|
|
143
|
+
|
|
144
|
+
credentials = firebase_service_account_credentials
|
|
145
|
+
if credentials.nil? || credentials.values_at(:project_id, :client_email, :private_key).any?(&:blank?)
|
|
146
|
+
errors.add(:firebase_service_account, :invalid_service_account)
|
|
147
|
+
elsif credentials[:project_id] != firebase_project_id
|
|
148
|
+
errors.add(:firebase_service_account, :service_account_project_mismatch, key_project: credentials[:project_id], project: firebase_project_id)
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
|
|
100
152
|
# Add Guardrails to ensure data integrity and make system predictable.
|
|
101
153
|
def single_active_vendor
|
|
102
154
|
return unless vendors.where(state: :active).count > 1
|
|
@@ -256,6 +256,12 @@ module SpreeCmCommissioner
|
|
|
256
256
|
taxons.events.find_by(slug: "events-#{event_id}")
|
|
257
257
|
end
|
|
258
258
|
|
|
259
|
+
def find_activity_by_id(activity_id: nil)
|
|
260
|
+
return nil if activity_id.blank?
|
|
261
|
+
|
|
262
|
+
taxons.activities.find_by(slug: "activities-#{activity_id}")
|
|
263
|
+
end
|
|
264
|
+
|
|
259
265
|
# Deep links to the public hotel detail page with a default 1-room/2-adult, 2-night search
|
|
260
266
|
# pre-filled — same query params the storefront's hotel page reads (see cm-market-client's
|
|
261
267
|
# JsonLd::HotelRequest), so "View Profile" previews the real booking page instead of the
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
module DeliveryMethods
|
|
2
|
+
# Noticed's FCM delivery sends every token with one credential. A tenant app's tokens belong to
|
|
3
|
+
# its own Firebase project, and FCM rejects them with 403 SENDER_ID_MISMATCH when sent through
|
|
4
|
+
# another project, which also aborts delivery to the recipient's remaining tokens. Send each
|
|
5
|
+
# project's tokens with that project's credential instead.
|
|
6
|
+
class FirebaseProjectFcm < Noticed::DeliveryMethods::Fcm
|
|
7
|
+
def deliver
|
|
8
|
+
notification.fcm_device_tokens_by_project(recipient).each do |firebase_project_id, tokens|
|
|
9
|
+
@credentials = credentials_for(firebase_project_id)
|
|
10
|
+
@authorizer = nil
|
|
11
|
+
@project_tokens = tokens
|
|
12
|
+
|
|
13
|
+
if @credentials.blank?
|
|
14
|
+
CmAppLogger.error(label: "#{self.class.name}#deliver skipped", data: { firebase_project_id: firebase_project_id, token_count: tokens.size })
|
|
15
|
+
next
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
deliver_to_project_tokens
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def device_tokens
|
|
23
|
+
@project_tokens
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
private
|
|
27
|
+
|
|
28
|
+
# Noticed's own loop, except a SENDER_ID_MISMATCH is pruned like an UNREGISTERED token instead of
|
|
29
|
+
# raising: the token's stored project is wrong (e.g. an app that reported the wrong one), it can
|
|
30
|
+
# never succeed with this credential, and raising would skip the recipient's remaining tokens.
|
|
31
|
+
# The app registers it again, with its project, on its next launch.
|
|
32
|
+
def deliver_to_project_tokens
|
|
33
|
+
device_tokens.each do |device_token|
|
|
34
|
+
post("#{BASE_URI}#{project_id}/messages:send", headers: { authorization: "Bearer #{access_token}" }, json: { message: format(device_token) })
|
|
35
|
+
rescue Noticed::ResponseUnsuccessful => e
|
|
36
|
+
raise unless invalid_token_response?(e.response)
|
|
37
|
+
|
|
38
|
+
cleanup_invalid_token(device_token)
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def invalid_token_response?(response)
|
|
43
|
+
return true if response.code == 404
|
|
44
|
+
return false unless response.code == 403
|
|
45
|
+
|
|
46
|
+
JSON.parse(response.body.to_s).dig('error', 'details')&.any? { |detail| detail['errorCode'] == 'SENDER_ID_MISMATCH' }
|
|
47
|
+
rescue JSON::ParserError
|
|
48
|
+
false
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def credentials_for(firebase_project_id)
|
|
52
|
+
SpreeCmCommissioner::FirebaseProjects.service_account_for(firebase_project_id, purpose: :push)&.symbolize_keys
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
class NoticedFcmBase < Noticed::Base
|
|
2
2
|
deliver_by :database, format: :format_for_database, if: :push_notificable?
|
|
3
|
-
deliver_by :fcm, credentials: :fcm_credentials, format: :format_notification, if: :push_notificable?
|
|
3
|
+
deliver_by :fcm, class: 'DeliveryMethods::FirebaseProjectFcm', credentials: :fcm_credentials, format: :format_notification, if: :push_notificable?
|
|
4
4
|
delegate :push_notificable?, to: :recipient
|
|
5
5
|
|
|
6
6
|
def format_for_database
|
|
@@ -24,6 +24,11 @@ class NoticedFcmBase < Noticed::Base
|
|
|
24
24
|
recipient.device_tokens.map(&:registration_token)
|
|
25
25
|
end
|
|
26
26
|
|
|
27
|
+
# A nil project is the shared one, which every token registered before tenant apps had their own uses.
|
|
28
|
+
def fcm_device_tokens_by_project(recipient)
|
|
29
|
+
recipient.device_tokens.group_by(&:firebase_project_id).transform_values { |tokens| tokens.map(&:registration_token) }
|
|
30
|
+
end
|
|
31
|
+
|
|
27
32
|
def format_notification(device_token)
|
|
28
33
|
{
|
|
29
34
|
data: convert_hash_values_to_str(payload),
|
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
<!-- replace "[data-hook='line-items']" -->
|
|
2
2
|
|
|
3
|
+
<%# Transit line items show as trip cards; everything else stays in the table below. %>
|
|
4
|
+
<% transit_items, other_items = split_order_line_items(order) %>
|
|
5
|
+
<% if transit_items.any? %>
|
|
6
|
+
<% lookups = transit_line_item_lookups(transit_items) %>
|
|
7
|
+
<div class="px-3 pt-3" data-hook="transit-line-items">
|
|
8
|
+
<% transit_items.each do |item| %>
|
|
9
|
+
<%= render 'spree/admin/orders/transit_line_item', item: item, lookups: lookups %>
|
|
10
|
+
<% end %>
|
|
11
|
+
</div>
|
|
12
|
+
<% end %>
|
|
13
|
+
<% if other_items.any? %>
|
|
14
|
+
<%# Only orders with a partner booking have an external ref; integration? is a cached flag, so this costs no query. %>
|
|
15
|
+
<% show_external_ref = other_items.any?(&:integration?) %>
|
|
3
16
|
<div class="table-responsive">
|
|
4
17
|
<table class="table line-items" data-hook="line-items" >
|
|
5
18
|
<thead class="text-muted">
|
|
6
19
|
<tr>
|
|
7
20
|
<th class="text-center"><%= Spree.t(:name) %></th>
|
|
8
21
|
<th class="text-center"><%= Spree.t(:number) %></th>
|
|
22
|
+
<% if show_external_ref %>
|
|
23
|
+
<th class="text-center"><%= Spree.t(:external_ref, default: 'External Ref') %></th>
|
|
24
|
+
<% end %>
|
|
9
25
|
<th class="text-center"><%= Spree.t(:option_text) %></th>
|
|
10
26
|
<th class="text-center"><%= Spree.t(:price) %></th>
|
|
11
27
|
<th class="text-center"><%= Spree.t(:total_price) %></th>
|
|
@@ -16,12 +32,15 @@
|
|
|
16
32
|
</tr>
|
|
17
33
|
</thead>
|
|
18
34
|
<tbody>
|
|
19
|
-
<%
|
|
35
|
+
<% other_items.each do |item| %>
|
|
20
36
|
<tr class="line-item" id="line-item-<%= item.id %>">
|
|
21
37
|
<td class="line-item-name text-center">
|
|
22
38
|
<%= link_to item.name, edit_admin_product_path(item.variant.product) %>
|
|
23
39
|
</td>
|
|
24
40
|
<td class="line-item-number text-center"><%= item.number %></td>
|
|
41
|
+
<% if show_external_ref %>
|
|
42
|
+
<td class="line-item-external-ref text-center"><%= item.external_ref %></td>
|
|
43
|
+
<% end %>
|
|
25
44
|
<td class="line-item-name text-center">
|
|
26
45
|
<%= item.options_text if item.options_text.present? %>
|
|
27
46
|
</td>
|
|
@@ -51,3 +70,4 @@
|
|
|
51
70
|
</tbody>
|
|
52
71
|
</table>
|
|
53
72
|
</div>
|
|
73
|
+
<% end %>
|
|
@@ -18,10 +18,12 @@ module SpreeCmCommissioner
|
|
|
18
18
|
# Highest-severity flag kind wins the drawer's headline verdict.
|
|
19
19
|
VERDICT_ORDER = %i[fraud test abandon].freeze
|
|
20
20
|
|
|
21
|
-
def initialize(hold:)
|
|
21
|
+
def initialize(hold:, vendor_id: nil, event_id: nil)
|
|
22
22
|
@hold = hold
|
|
23
23
|
@order = hold.order
|
|
24
24
|
@user = hold.user || hold.order&.user
|
|
25
|
+
@vendor_id = vendor_id
|
|
26
|
+
@event_id = event_id
|
|
25
27
|
end
|
|
26
28
|
|
|
27
29
|
def call
|
|
@@ -42,7 +44,22 @@ module SpreeCmCommissioner
|
|
|
42
44
|
|
|
43
45
|
private
|
|
44
46
|
|
|
45
|
-
attr_reader :hold, :order, :user
|
|
47
|
+
attr_reader :hold, :order, :user, :vendor_id, :event_id
|
|
48
|
+
|
|
49
|
+
def scoped_order_ids
|
|
50
|
+
line_items = Spree::LineItem.all
|
|
51
|
+
line_items = line_items.where(vendor_id: vendor_id) if vendor_id
|
|
52
|
+
line_items = line_items.where(event_id: event_id) if event_id
|
|
53
|
+
line_items.select(:order_id)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Platform admin passes no ids and sees everything; a vendor console must pass both, so it never
|
|
57
|
+
# sees another vendor's/event's orders, holds or customers.
|
|
58
|
+
def scope(relation, column)
|
|
59
|
+
return relation unless vendor_id && event_id
|
|
60
|
+
|
|
61
|
+
relation.where(column => scoped_order_ids)
|
|
62
|
+
end
|
|
46
63
|
|
|
47
64
|
def roles
|
|
48
65
|
return [] unless user
|
|
@@ -54,7 +71,7 @@ module SpreeCmCommissioner
|
|
|
54
71
|
empty = { completed: 0, incomplete: 0, last_completed_at: nil }
|
|
55
72
|
return empty unless user
|
|
56
73
|
|
|
57
|
-
completed, incomplete, last_completed_at = Spree::Order.where(user_id: user.id).pick(
|
|
74
|
+
completed, incomplete, last_completed_at = scope(Spree::Order.where(user_id: user.id), :id).pick(
|
|
58
75
|
Arel.sql('COUNT(*) FILTER (WHERE completed_at IS NOT NULL)'),
|
|
59
76
|
Arel.sql('COUNT(*) FILTER (WHERE completed_at IS NULL)'),
|
|
60
77
|
Arel.sql('MAX(completed_at)')
|
|
@@ -65,9 +82,10 @@ module SpreeCmCommissioner
|
|
|
65
82
|
def recent_orders
|
|
66
83
|
return [] unless user
|
|
67
84
|
|
|
68
|
-
Spree::Order.where(user_id: user.id)
|
|
69
|
-
|
|
70
|
-
|
|
85
|
+
scope(Spree::Order.where(user_id: user.id), :id)
|
|
86
|
+
.order(created_at: :desc).limit(RECENT_LIMIT)
|
|
87
|
+
.pluck(:number, :state, :payment_state, :total, :currency, :created_at, :completed_at)
|
|
88
|
+
.map { |row| %i[number state payment_state total currency created_at completed_at].zip(row).to_h }
|
|
71
89
|
end
|
|
72
90
|
|
|
73
91
|
# Burst windows end at this hold's created_at so an old hold shows the burst it was part of.
|
|
@@ -75,7 +93,7 @@ module SpreeCmCommissioner
|
|
|
75
93
|
keys = %i[total converted concurrent abandoned in_3m in_5m]
|
|
76
94
|
return keys.index_with(0).merge(distinct_users: 0, distinct_users_24h: 0) if value.blank?
|
|
77
95
|
|
|
78
|
-
relation = InventoryHold.where(column => value)
|
|
96
|
+
relation = scope(InventoryHold.where(column => value), :order_id)
|
|
79
97
|
|
|
80
98
|
at = hold.created_at
|
|
81
99
|
selects = [
|
|
@@ -106,10 +124,10 @@ module SpreeCmCommissioner
|
|
|
106
124
|
def ip_recent_holds
|
|
107
125
|
return [] if hold.ip_address.blank?
|
|
108
126
|
|
|
109
|
-
InventoryHold.where(ip_address: hold.ip_address).where.not(id: hold.id)
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
127
|
+
relation = scope(InventoryHold.where(ip_address: hold.ip_address).where.not(id: hold.id), :order_id)
|
|
128
|
+
relation.left_joins(:order, :user).order(created_at: :desc).limit(RECENT_LIMIT)
|
|
129
|
+
.pluck(:id, :status, :created_at, 'spree_orders.number', 'spree_orders.state', 'spree_orders.payment_state', 'spree_users.email')
|
|
130
|
+
.map { |row| %i[id status created_at order_number order_state payment_state email].zip(row).to_h }
|
|
113
131
|
end
|
|
114
132
|
|
|
115
133
|
def flags(result)
|
|
@@ -64,20 +64,20 @@ module SpreeCmCommissioner
|
|
|
64
64
|
def abandoners
|
|
65
65
|
reasons = InventoryHold.release_reasons.values_at(:hold_expired, :payment_timeout).join(',')
|
|
66
66
|
abandoned = "COUNT(*) FILTER (WHERE cm_inventory_holds.release_reason IN (#{reasons}))"
|
|
67
|
-
holds.joins(:user).group(:user_id, 'spree_users.email')
|
|
67
|
+
holds.joins(:user).group(:user_id, 'spree_users.email', 'spree_users.phone_number')
|
|
68
68
|
.having("#{abandoned} > 0 AND COUNT(*) FILTER (WHERE cm_inventory_holds.status = #{InventoryHold.statuses[:converted]}) = 0")
|
|
69
69
|
.order(Arel.sql("#{abandoned} DESC")).limit(TOP_LIMIT)
|
|
70
|
-
.pluck(:user_id, 'spree_users.email', Arel.sql(abandoned), Arel.sql('COUNT(*)'))
|
|
71
|
-
.map { |row| %i[user_id email abandoned holds].zip(row).to_h }
|
|
70
|
+
.pluck(:user_id, 'spree_users.email', 'spree_users.phone_number', Arel.sql(abandoned), Arel.sql('COUNT(*)'))
|
|
71
|
+
.map { |row| %i[user_id email phone_number abandoned holds].zip(row).to_h }
|
|
72
72
|
end
|
|
73
73
|
|
|
74
74
|
def test_accounts
|
|
75
75
|
staff = 'EXISTS (SELECT 1 FROM spree_role_users ru WHERE ru.user_id = spree_users.id)'
|
|
76
76
|
holds.joins(:user)
|
|
77
77
|
.where("spree_users.email ~* ? OR #{staff}", InventoryHoldInsightsQuery::TEST_EMAIL_SOURCE)
|
|
78
|
-
.group(:user_id, 'spree_users.email').order(Arel.sql('COUNT(*) DESC')).limit(TOP_LIMIT)
|
|
79
|
-
.pluck(:user_id, 'spree_users.email', Arel.sql('COUNT(*)'), Arel.sql("bool_or(#{staff})"))
|
|
80
|
-
.map { |row| %i[user_id email holds staff].zip(row).to_h }
|
|
78
|
+
.group(:user_id, 'spree_users.email', 'spree_users.phone_number').order(Arel.sql('COUNT(*) DESC')).limit(TOP_LIMIT)
|
|
79
|
+
.pluck(:user_id, 'spree_users.email', 'spree_users.phone_number', Arel.sql('COUNT(*)'), Arel.sql("bool_or(#{staff})"))
|
|
80
|
+
.map { |row| %i[user_id email phone_number holds staff].zip(row).to_h }
|
|
81
81
|
end
|
|
82
82
|
end
|
|
83
83
|
end
|
|
@@ -4,6 +4,14 @@ module SpreeCmCommissioner
|
|
|
4
4
|
required(:origin_id).value(:integer)
|
|
5
5
|
required(:destination_id).value(:integer)
|
|
6
6
|
required(:date).value(:date)
|
|
7
|
+
optional(:route_type).maybe(:string)
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
route_types = SpreeCmCommissioner::RouteType::ROUTE_TYPES.map(&:to_s)
|
|
11
|
+
|
|
12
|
+
# Blank stays valid (no filter). An unknown value used to search `route_type IS NULL` and silently return nothing.
|
|
13
|
+
rule(:route_type) do
|
|
14
|
+
key.failure("Invalid route_type. Use #{route_types}") if value.present? && route_types.exclude?(value)
|
|
7
15
|
end
|
|
8
16
|
|
|
9
17
|
rule(:date) do
|
|
@@ -2,7 +2,7 @@ module Spree
|
|
|
2
2
|
module V2
|
|
3
3
|
module Storefront
|
|
4
4
|
class UserDeviceTokenSerializer < BaseSerializer
|
|
5
|
-
attributes :user_id, :registration_token, :client_name, :client_version, :meta, :device_type
|
|
5
|
+
attributes :user_id, :registration_token, :client_name, :client_version, :meta, :device_type, :firebase_project_id
|
|
6
6
|
end
|
|
7
7
|
end
|
|
8
8
|
end
|
|
@@ -2,7 +2,7 @@ module Spree
|
|
|
2
2
|
module V2
|
|
3
3
|
module Tenant
|
|
4
4
|
class UserDeviceTokenSerializer < BaseSerializer
|
|
5
|
-
attributes :user_id, :registration_token, :client_name, :client_version, :meta, :device_type
|
|
5
|
+
attributes :user_id, :registration_token, :client_name, :client_version, :meta, :device_type, :firebase_project_id
|
|
6
6
|
end
|
|
7
7
|
end
|
|
8
8
|
end
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
module DeviceTokens
|
|
3
|
+
# Drops the push tokens a tenant's users registered from any Firebase project other than the
|
|
4
|
+
# tenant's own. Run it after switching the tenant's app to that project: a token from the old
|
|
5
|
+
# project keeps delivering, so an updated device would get every push twice. Nothing is lost by
|
|
6
|
+
# over-deleting, because every app registers its token again on each launch while signed in.
|
|
7
|
+
class PruneOtherProjects
|
|
8
|
+
prepend Spree::ServiceModule::Base
|
|
9
|
+
|
|
10
|
+
# The value is the number of tokens deleted.
|
|
11
|
+
def call(tenant_id:)
|
|
12
|
+
tenant = Tenant.find_by(id: tenant_id)
|
|
13
|
+
return failure(nil, "Tenant #{tenant_id.inspect} not found") if tenant.nil?
|
|
14
|
+
return failure(nil, "Tenant #{tenant.id} has no Firebase project of its own") if tenant.firebase_project_id.blank?
|
|
15
|
+
|
|
16
|
+
tokens = DeviceToken.where(user_id: Spree::User.where(tenant_id: tenant.id).select(:id))
|
|
17
|
+
.where('firebase_project_id IS DISTINCT FROM ?', tenant.firebase_project_id)
|
|
18
|
+
|
|
19
|
+
# destroy, not delete_all, so each user's device_tokens_count stays right.
|
|
20
|
+
success(tokens.find_each.count(&:destroy))
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
module FirebaseEmails
|
|
3
|
+
# Finds the email for a Firebase sign-in whose token carries none. Callers run it only when they
|
|
4
|
+
# need an email (registering, or a user whose email is still blank), so a returning user with an
|
|
5
|
+
# email costs no Firebase call.
|
|
6
|
+
#
|
|
7
|
+
# Looks in the token's own project first, then in the shared project by provider sub. Apple shares
|
|
8
|
+
# a user's email only on their first authorization of our team, so once a tenant app signs in
|
|
9
|
+
# through its own project, the shared project may be the only place still holding it. The sub is
|
|
10
|
+
# the same in both while the tenant project reuses BookMe's Apple team and Facebook app.
|
|
11
|
+
class Resolve
|
|
12
|
+
prepend Spree::ServiceModule::Base
|
|
13
|
+
|
|
14
|
+
# provider: as built by FirebaseIdTokenProvider. The value is the email, or nil when no project has one.
|
|
15
|
+
def call(provider:)
|
|
16
|
+
success(provider[:email].presence || from_token_project(provider) || from_shared_project(provider))
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
private
|
|
20
|
+
|
|
21
|
+
def from_token_project(provider)
|
|
22
|
+
return if provider[:firebase_user_id].blank?
|
|
23
|
+
|
|
24
|
+
fetch(user_id: provider[:firebase_user_id], project_id: provider[:firebase_project_id])
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def from_shared_project(provider)
|
|
28
|
+
return if FirebaseProjects.shared?(provider[:firebase_project_id])
|
|
29
|
+
return if provider[:sub].blank?
|
|
30
|
+
|
|
31
|
+
fetch(sub: provider[:sub], provider_id: provider[:sign_in_provider], project_id: FirebaseProjects.shared_project_id)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def fetch(**)
|
|
35
|
+
result = FirebaseEmailFetcher.call(**)
|
|
36
|
+
result.email.presence if result.success?
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
module SpreeCmCommissioner
|
|
2
|
+
# Resolves which Firebase project a token or device belongs to and the service account to act on
|
|
3
|
+
# it with. Tenant apps sign users in, and receive pushes, through their own project
|
|
4
|
+
# (`Tenant#firebase_project_id`). Everything else, including installs of a tenant app released
|
|
5
|
+
# before it had one, uses the shared project behind `cloud_firestore_service_account`, which also
|
|
6
|
+
# keeps serving the realtime Firestore docs (waiting room, payment statuses) for every app.
|
|
7
|
+
module FirebaseProjects
|
|
8
|
+
SHARED_SERVICE_ACCOUNTS = { push: :google_service_account, auth: :cloud_firestore_service_account }.freeze
|
|
9
|
+
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
def shared_project_id
|
|
13
|
+
Rails.application.credentials.cloud_firestore_service_account&.dig(:project_id)
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def shared?(project_id)
|
|
17
|
+
project_id.blank? || project_id == shared_project_id
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# The key to call `project_id` with. The shared project has one key per purpose in Rails
|
|
21
|
+
# credentials, each with its own roles; a tenant uploads one key for both.
|
|
22
|
+
#
|
|
23
|
+
# service_account_for(nil, purpose: :push) # => google_service_account
|
|
24
|
+
# service_account_for('bookmeplus', purpose: :auth) # => cloud_firestore_service_account
|
|
25
|
+
# service_account_for('hangmeas-prod', purpose: :push) # => Hang Meas's uploaded key, or nil
|
|
26
|
+
#
|
|
27
|
+
# Nil only when the tenant's key isn't uploaded yet, and callers skip rather than use the shared
|
|
28
|
+
# key: FCM rejects a `hangmeas-prod` token sent with it as SENDER_ID_MISMATCH, which deletes the
|
|
29
|
+
# token. Tenants on the same project (non-production) share it, so any one tenant's key works.
|
|
30
|
+
def service_account_for(project_id, purpose:)
|
|
31
|
+
return Rails.application.credentials.public_send(SHARED_SERVICE_ACCOUNTS.fetch(purpose)) if shared?(project_id)
|
|
32
|
+
|
|
33
|
+
Tenant.where(firebase_project_id: project_id)
|
|
34
|
+
.where.not(firebase_service_account: nil)
|
|
35
|
+
.order(:id)
|
|
36
|
+
.first&.firebase_service_account_credentials
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/inventory/unstock_inventory.rb
CHANGED
|
@@ -148,15 +148,16 @@ class SpreeCmCommissioner::Integrations::BookMeBusV1::Inventory::UnstockInventor
|
|
|
148
148
|
# can assign real seats server-side - dropping those guests entirely would undercount
|
|
149
149
|
# number_of_seats and reserve fewer seats than the order was actually paid for.
|
|
150
150
|
def build_reserved_seats(line_item, from_stop_id, integration, default_layer = nil) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
|
|
151
|
-
|
|
151
|
+
guests = line_item.guests.to_a
|
|
152
|
+
ActiveRecord::Associations::Preloader.new(records: guests, associations: :saved_guest).call
|
|
153
|
+
seats = guests.map do |guest|
|
|
152
154
|
seat_label = guest.block&.label
|
|
153
155
|
|
|
154
156
|
if seat_label.blank? && line_item.required_seat_selection?
|
|
155
157
|
raise SpreeCmCommissioner::Integrations::SyncError, "Guest ##{guest.id} on line item ##{line_item.id} has no assigned seat"
|
|
156
158
|
end
|
|
157
159
|
|
|
158
|
-
name =
|
|
159
|
-
name = "Guest #{guest.id}" if name.blank?
|
|
160
|
+
name = passenger_name(guest)
|
|
160
161
|
|
|
161
162
|
block_type = guest.block&.block_type&.to_s
|
|
162
163
|
|
|
@@ -172,6 +173,13 @@ class SpreeCmCommissioner::Integrations::BookMeBusV1::Inventory::UnstockInventor
|
|
|
172
173
|
seats.empty? ? {} : { from_stop_id.to_s => seats }
|
|
173
174
|
end
|
|
174
175
|
|
|
176
|
+
# The app saves what the buyer types for a passenger on the guest's saved_guest, and the guest's own name fields
|
|
177
|
+
# can still be empty at the time the reservation is sent. Reading only the guest sent BookMeBus "Guest <id>" for a
|
|
178
|
+
# passenger whose name BookMe+ already had.
|
|
179
|
+
def passenger_name(guest)
|
|
180
|
+
guest.full_name.presence || guest.saved_guest&.full_name.presence || "Guest #{guest.id}"
|
|
181
|
+
end
|
|
182
|
+
|
|
175
183
|
# A single-layer layout keeps its blocks top-level (no SeatSection, see SyncSeatLayout#build_seat_sections_by_layer),
|
|
176
184
|
# so the block carries no layer name. BookMeBus only marks a seat taken when label *and* layer match its own
|
|
177
185
|
# layout, and a single layer is not always called "BUS" ("VIP VAN", "2", ...) - sending the 'BUS' fallback left
|
data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trip_stop.rb
CHANGED
|
@@ -153,7 +153,19 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
153
153
|
def sync_stop_vendor_place!(external_stop, location_vendor_place)
|
|
154
154
|
return nil unless external_stop.id.present? && external_stop.name.present?
|
|
155
155
|
|
|
156
|
-
|
|
156
|
+
parent_place = location_vendor_place.place
|
|
157
|
+
coordinates = stop_coordinates(external_stop, parent_place)
|
|
158
|
+
|
|
159
|
+
# Several route jobs sync the same stops at once (the integration queue is multi-threaded) and neither
|
|
160
|
+
# `cm_places` nor `cm_vendor_places` has a unique index, so two jobs that both find nothing each create
|
|
161
|
+
# a Place for the same stop. The copies then break every later sync with "Place has already existed with
|
|
162
|
+
# this place type". One lock per stop makes the second job find the first job's rows.
|
|
163
|
+
with_stop_lock!(parent_place, external_stop.name) do
|
|
164
|
+
save_stop_vendor_place!(external_stop, location_vendor_place, coordinates)
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def save_stop_vendor_place!(external_stop, location_vendor_place, coordinates)
|
|
157
169
|
# Uses unique_external_id which is:
|
|
158
170
|
# - "branch-{operator_branch_id}" for branches (to avoid duplicates)
|
|
159
171
|
# - "stop-{id}" for regular stops (to preserve specific locations)
|
|
@@ -162,11 +174,14 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
162
174
|
external_id: external_stop.unique_external_id
|
|
163
175
|
)
|
|
164
176
|
|
|
177
|
+
# Scoped under its city so two differently-located stops sharing a common name (e.g. "Central Market"
|
|
178
|
+
# in two different cities) don't collapse into one Place.
|
|
179
|
+
stop_place = find_or_create_stop_place!(external_stop, parent_place: location_vendor_place.place, coordinates: coordinates)
|
|
180
|
+
|
|
181
|
+
# A mapping archived under another external id (BookMeBus re-issued the stop) leaves its VendorPlace
|
|
182
|
+
# behind; adopt it instead of building a second one the uniqueness validation rejects.
|
|
183
|
+
mapping.internal = existing_vendor_place(stop_place, external_stop.vendor_place_type) if mapping.internal.new_record?
|
|
165
184
|
stop_vendor_place = mapping.internal
|
|
166
|
-
# Create or find the Place record for this specific stop, scoped under its city so two
|
|
167
|
-
# differently-located stops sharing a common name (e.g. "Central Market" in two different
|
|
168
|
-
# cities) don't collapse into one Place.
|
|
169
|
-
stop_place = find_or_create_stop_place!(external_stop, parent_place: location_vendor_place.place)
|
|
170
185
|
|
|
171
186
|
@sync_result.track(:vendor_place, stop_vendor_place) do |tracker|
|
|
172
187
|
stop_vendor_place.assign_attributes(
|
|
@@ -193,25 +208,49 @@ module SpreeCmCommissioner::Integrations::BookMeBusV1::Polling
|
|
|
193
208
|
external_stop.branch? ? location_vendor_place.place : stop_place
|
|
194
209
|
end
|
|
195
210
|
|
|
196
|
-
def
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
211
|
+
def existing_vendor_place(place, place_type)
|
|
212
|
+
SpreeCmCommissioner::VendorPlace.find_by(vendor_id: @integration.vendor.id, place_id: place.id, place_type: place_type) ||
|
|
213
|
+
SpreeCmCommissioner::VendorPlace.new
|
|
214
|
+
end
|
|
200
215
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
216
|
+
# The oldest copy wins so the choice stays stable if duplicates already exist.
|
|
217
|
+
def find_stop_place(name, parent_place)
|
|
218
|
+
SpreeCmCommissioner::Place.where(name: name, parent_id: parent_place&.id).order(:id).first
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Geocoded before the lock is taken: the lock must not be held across a network call. Empty when the
|
|
222
|
+
# place already has coordinates, which are never overwritten.
|
|
223
|
+
def stop_coordinates(external_stop, parent_place)
|
|
224
|
+
place = find_stop_place(external_stop.name, parent_place)
|
|
225
|
+
return {} if place&.lat && place&.lon
|
|
226
|
+
|
|
227
|
+
location_data = @geocoder.fetch_location_data(external_stop.name, external_stop.location_name) || {}
|
|
228
|
+
{
|
|
229
|
+
lat: external_stop.latitude || location_data[:lat],
|
|
230
|
+
lon: external_stop.longitude || location_data[:lon],
|
|
231
|
+
reference: location_data[:reference]
|
|
232
|
+
}
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def find_or_create_stop_place!(external_stop, parent_place:, coordinates:)
|
|
236
|
+
place = find_stop_place(external_stop.name, parent_place) ||
|
|
237
|
+
SpreeCmCommissioner::Place.new(name: external_stop.name, parent_id: parent_place&.id)
|
|
210
238
|
|
|
239
|
+
place.assign_attributes(coordinates) if place.new_record? || place.lat.nil? || place.lon.nil?
|
|
211
240
|
place.save! if place.new_record? || place.changed?
|
|
212
241
|
place
|
|
213
242
|
end
|
|
214
243
|
|
|
244
|
+
def with_stop_lock!(parent_place, name)
|
|
245
|
+
key = "spree_cm_commissioner:book_me_bus_v1:stop_place:#{@integration.vendor.id}:#{parent_place&.id}:#{name.to_s.strip.downcase}"
|
|
246
|
+
lock_id = Zlib.crc32(key)
|
|
247
|
+
ActiveRecord::Base.connection.execute("SELECT pg_advisory_lock(#{lock_id})")
|
|
248
|
+
|
|
249
|
+
yield
|
|
250
|
+
ensure
|
|
251
|
+
ActiveRecord::Base.connection.execute("SELECT pg_advisory_unlock(#{lock_id})")
|
|
252
|
+
end
|
|
253
|
+
|
|
215
254
|
def find_vendor_place(location_id)
|
|
216
255
|
return nil unless location_id
|
|
217
256
|
|