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.
Files changed (63) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile.lock +1 -1
  3. data/app/controllers/spree/admin/inventory_holds_controller.rb +10 -3
  4. data/app/controllers/spree/admin/inventory_monitorings_controller.rb +1 -1
  5. data/app/controllers/spree/api/v2/storefront/user_device_token_registrations_controller.rb +1 -0
  6. data/app/controllers/spree/api/v2/tenant/user_device_tokens_controller.rb +1 -0
  7. data/app/controllers/spree_cm_commissioner/admin/orders_controller_decorator.rb +2 -0
  8. data/app/factory/spree_cm_commissioner/order_telegram_message_factory.rb +15 -1
  9. data/app/helpers/spree_cm_commissioner/admin/transit_line_items_helper.rb +89 -0
  10. data/app/interactors/spree_cm_commissioner/account_linkage.rb +2 -1
  11. data/app/interactors/spree_cm_commissioner/firebase_email_fetcher.rb +34 -11
  12. data/app/interactors/spree_cm_commissioner/firebase_email_fetcher_cron_executor.rb +42 -12
  13. data/app/interactors/spree_cm_commissioner/firebase_id_token_provider.rb +13 -14
  14. data/app/interactors/spree_cm_commissioner/user_device_token_register.rb +2 -1
  15. data/app/interactors/spree_cm_commissioner/user_id_token_authenticator.rb +29 -11
  16. data/app/interactors/spree_cm_commissioner/user_id_token_checker.rb +7 -5
  17. data/app/interactors/spree_cm_commissioner/user_registration_with_id_token.rb +10 -9
  18. data/app/jobs/spree_cm_commissioner/firebase_email_fetcher_job.rb +3 -2
  19. data/app/models/concerns/spree_cm_commissioner/line_item_integration.rb +13 -0
  20. data/app/models/concerns/spree_cm_commissioner/route_type.rb +1 -1
  21. data/app/models/concerns/spree_cm_commissioner/service_type.rb +1 -1
  22. data/app/models/spree_cm_commissioner/integration.rb +7 -0
  23. data/app/models/spree_cm_commissioner/integrations/book_me_bus_v1.rb +8 -0
  24. data/app/models/spree_cm_commissioner/integrations/larryta.rb +7 -0
  25. data/app/models/spree_cm_commissioner/taxon_decorator.rb +1 -0
  26. data/app/models/spree_cm_commissioner/taxonomy_decorator.rb +11 -0
  27. data/app/models/spree_cm_commissioner/tenant.rb +52 -0
  28. data/app/models/spree_cm_commissioner/vendor_decorator.rb +6 -0
  29. data/app/notifications/delivery_methods/firebase_project_fcm.rb +55 -0
  30. data/app/notifications/noticed_fcm_base.rb +6 -1
  31. data/app/overrides/spree/admin/orders/_line_items/_line_items.html.erb.deface +21 -1
  32. data/app/queries/spree_cm_commissioner/inventory_hold_insights_query.rb +29 -11
  33. data/app/queries/spree_cm_commissioner/inventory_hold_overview_query.rb +6 -6
  34. data/app/request_schemas/spree_cm_commissioner/trip_search_request_schema.rb +8 -0
  35. data/app/serializers/spree/v2/storefront/user_device_token_serializer.rb +1 -1
  36. data/app/serializers/spree/v2/tenant/user_device_token_serializer.rb +1 -1
  37. data/app/services/spree_cm_commissioner/device_tokens/prune_other_projects.rb +24 -0
  38. data/app/services/spree_cm_commissioner/firebase_emails/resolve.rb +40 -0
  39. data/app/services/spree_cm_commissioner/firebase_projects.rb +39 -0
  40. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/inventory/unstock_inventory.rb +11 -3
  41. data/app/services/spree_cm_commissioner/integrations/book_me_bus_v1/polling/sync_trip_stop.rb +57 -18
  42. data/app/services/spree_cm_commissioner/inventory_items/reset.rb +13 -0
  43. data/app/services/spree_cm_commissioner/rates_availabilities/bulk_update.rb +11 -3
  44. data/app/services/spree_cm_commissioner/trips/update_single_leg.rb +2 -1
  45. data/app/services/spree_cm_commissioner/waiting_room/sessions/issue.rb +18 -4
  46. data/app/views/spree/admin/inventory_holds/_overview.html.erb +4 -1
  47. data/app/views/spree/admin/inventory_holds/_search.html.erb +10 -0
  48. data/app/views/spree/admin/orders/_transit_line_item.html.erb +103 -0
  49. data/app/views/spree/admin/rates_availabilities/_script.html.erb +6 -2
  50. data/app/views/spree/admin/tenants/_form.html.erb +21 -0
  51. data/app/views/spree/admin/tenants/form/_firebase.html.erb +32 -0
  52. data/config/initializers/user_manager_decorator.rb +3 -1
  53. data/config/locales/en.yml +5 -0
  54. data/config/locales/km.yml +5 -0
  55. data/db/migrate/20261119000001_add_firebase_project_to_cm_tenants.rb +12 -0
  56. data/db/migrate/20261119000002_add_firebase_project_id_to_cm_device_tokens.rb +6 -0
  57. data/db/migrate/20261120000001_add_internal_index_to_cm_integration_mappings.rb +10 -0
  58. data/lib/spree_cm_commissioner/test_helper/factories/user_factory.rb +3 -1
  59. data/lib/spree_cm_commissioner/test_helper/firebase_id_token_helper.rb +53 -0
  60. data/lib/spree_cm_commissioner/version.rb +1 -1
  61. data/lib/tasks/fetch_email.rake +4 -3
  62. data/lib/tasks/prune_device_tokens.rake +10 -0
  63. metadata +14 -2
@@ -8,6 +8,10 @@ module SpreeCmCommissioner
8
8
  # recount can tell "selling right now, try again" apart from a real failure.
9
9
  BUSY = :busy
10
10
 
11
+ # Fails with this as its value when the variant has no stock count to recount from (see #call), so a bulk
12
+ # recount can report it apart from BUSY: retrying never helps.
13
+ UNTRACKED = :untracked
14
+
11
15
  # Recounts under the item's row lock, so a concurrent adjust_quantity! or BulkAdjustQuantities* write
12
16
  # can't land between the read and the update and be overwritten.
13
17
  #
@@ -18,6 +22,15 @@ module SpreeCmCommissioner
18
22
  # is rolled back and this fails with BUSY. What's left is a hold whose Redis increment lands before the
19
23
  # snapshot and whose commit lands after the counts are read: one hold's commit latency, not the recount's.
20
24
  def call(inventory_item:)
25
+ # Spree's total_on_hand is INFINITY for a variant that doesn't track inventory (its own flag off, or
26
+ # Spree::Config.track_inventory_levels off), and #variant_total_inventory can't turn that into a capacity.
27
+ # Items are only created for tracked variants, so this is one whose tracking was turned off afterwards. A
28
+ # partner-owned variant never reads total_on_hand, so it still recounts.
29
+ variant = inventory_item.variant
30
+ unless variant.inventory_external_wins? || variant.should_track_inventory?
31
+ return failure(UNTRACKED, I18n.t('inventory_item.reset.untracked_inventory'))
32
+ end
33
+
21
34
  outcome = nil
22
35
 
23
36
  # requires_new, as in MoveToLocked: a Rollback in a bare nested transaction is swallowed, which would
@@ -49,7 +49,7 @@ module SpreeCmCommissioner
49
49
  end
50
50
 
51
51
  updated = send(action)
52
- success({ updated: updated, skipped: cells.size - updated, busy: @busy }.compact)
52
+ success({ updated: updated, skipped: cells.size - updated, busy: @busy, untracked: @untracked }.compact)
53
53
  rescue ActiveRecord::RecordInvalid, ArgumentError => e
54
54
  failure(nil, e.message)
55
55
  end
@@ -129,16 +129,24 @@ module SpreeCmCommissioner
129
129
  # product without dates sells from.
130
130
  #
131
131
  # A date being booked while it's recounted is left as it was and counted in `busy`, so the rest still apply.
132
+ # A variant that doesn't track inventory is left too, counted apart in `untracked`: retrying never helps it.
132
133
  def reset_stock
133
134
  items = stock_cells.filter_map { |cell| cell[:inventory_item] || undated_inventory_item(cell[:variant]) }
134
135
  raise ArgumentError, I18n.t('rates_availabilities.bulk.recount_limit', max: MAX_RECOUNT) if items.size > MAX_RECOUNT
135
136
 
136
137
  results = items.map { |item| InventoryItems::Reset.call(inventory_item: item) }
137
- busy, failed = results.reject(&:success?).partition { |result| result.value == InventoryItems::Reset::BUSY }
138
+ busy, untracked, failed = split_refusals(results)
138
139
  raise ArgumentError, failed.map { |result| result.error.to_s }.uniq.to_sentence if failed.any?
139
140
 
140
141
  @busy = busy.size if busy.any?
141
- items.size - busy.size
142
+ @untracked = untracked.size if untracked.any?
143
+ items.size - busy.size - untracked.size
144
+ end
145
+
146
+ # [busy, untracked, failed] among the refused recounts: the first two are reported, the rest raise.
147
+ def split_refusals(results)
148
+ refused = results.reject(&:success?).group_by(&:value)
149
+ [refused.delete(InventoryItems::Reset::BUSY).to_a, refused.delete(InventoryItems::Reset::UNTRACKED).to_a, refused.values.flatten]
142
150
  end
143
151
 
144
152
  def undated_inventory_item(variant)
@@ -129,7 +129,8 @@ module SpreeCmCommissioner
129
129
  allow_booking: form.allow_booking,
130
130
  allow_seat_selection: form.allow_seat_selection,
131
131
  name: form.name,
132
- short_name: form.short_name
132
+ short_name: form.short_name,
133
+ route_type: form.route_type
133
134
  }.compact
134
135
  end
135
136
 
@@ -52,6 +52,9 @@ module SpreeCmCommissioner
52
52
  # called createSession directly. The caller never touched this guest, no row exists yet, so
53
53
  # they fall through to a normal create_new_session. A row that's lapsed (expired_at passed) but
54
54
  # still under its own ceiling also lands here — the revival path in #create_new_session.
55
+ #
56
+ # All three are decided in #dispatch_session, which #call reruns once if its insert loses the race
57
+ # to Admission::CallGuestsChunk.
55
58
  def call(waiting_guest_firebase_doc_id:, remote_ip:, page_path: nil, tenant_id: nil, # rubocop:disable Metrics/ParameterLists
56
59
  device_attributes: nil, bypass_jwt: nil, bypass_order_token: nil, user: nil
57
60
  )
@@ -67,6 +70,19 @@ module SpreeCmCommissioner
67
70
  return failure(nil, 'must_provide_waiting_guest_firebase_doc_id') if waiting_guest_firebase_doc_id.blank?
68
71
  return failure(nil, 'must_provide_remote_ip') if remote_ip.blank?
69
72
 
73
+ dispatch_session
74
+ rescue ActiveRecord::RecordNotUnique
75
+ # Admission::CallGuestsChunk precreates rows outside our advisory lock, so the guest_identifier
76
+ # unique index is the only arbiter between us: it inserted this guest's row after our lookup saw
77
+ # none. Re-dispatch once against the row it wrote; a second conflict isn't expected and propagates.
78
+ CmAppLogger.log(label: 'waiting_room_session_issue_raced_admission', data: { guest_identifier: waiting_guest_firebase_doc_id })
79
+
80
+ dispatch_session
81
+ end
82
+
83
+ private
84
+
85
+ def dispatch_session
70
86
  existing = SpreeCmCommissioner::WaitingRoomSession.find_by(guest_identifier: waiting_guest_firebase_doc_id)
71
87
 
72
88
  if existing&.active?
@@ -78,8 +94,6 @@ module SpreeCmCommissioner
78
94
  end
79
95
  end
80
96
 
81
- private
82
-
83
97
  # An already-reserved slot is already counted in WaitingRoomSession.active.count, so
84
98
  # re-checking capacity on its own renewal can only ever reject the holder's own session — this
85
99
  # is the eviction-bug fix. No lock, no full? guard.
@@ -95,7 +109,7 @@ module SpreeCmCommissioner
95
109
  session
96
110
  end
97
111
 
98
- # No active row and no ceiling breach (see #call): a true new admission, a bypass-path entry, or
112
+ # No active row and no ceiling breach (see #dispatch_session): a true new admission, a bypass-path entry, or
99
113
  # a row that's lapsed but still under its own max_expired_at — goes through the normal
100
114
  # advisory-lock + full? gated path.
101
115
  def create_new_session
@@ -181,7 +195,7 @@ module SpreeCmCommissioner
181
195
  session = SpreeCmCommissioner::WaitingRoomSession.where(guest_identifier: waiting_guest_firebase_doc_id).first_or_initialize
182
196
 
183
197
  # A brand-new row gets a fresh ceiling. A row that already had one (lapsed but not yet past
184
- # its ceiling — see #call) keeps that same ceiling: reviving it here must not silently grant
198
+ # its ceiling — see #dispatch_session) keeps that same ceiling: reviving it here must not silently grant
185
199
  # it a new one just because it lapsed. Computed before generate_token so expired_at is
186
200
  # always capped against the ceiling that's actually being persisted, not a different one.
187
201
  session.max_expired_at ||= max_expired_at_ceiling
@@ -12,7 +12,10 @@
12
12
  ]
13
13
  %>
14
14
 
15
- <p class="small text-muted">All holds matching the table filters since <strong><%= order_time(@overview_from) %></strong>.</p>
15
+ <p class="small text-muted">
16
+ All holds matching the table filters
17
+ <% if @overview_from %>since <strong><%= order_time(@overview_from) %></strong><% else %>(all time)<% end %>.
18
+ </p>
16
19
 
17
20
  <%= render layout: 'section', locals: { title: 'How did holds end?', hint: '"Left at payment" jumping suddenly usually means a payment gateway problem, not customers.' } do %>
18
21
  <div class="hi-stats mb-3">
@@ -135,6 +135,16 @@
135
135
  } %>
136
136
  </div>
137
137
  </div>
138
+
139
+ <div class="col-12 col-lg-3">
140
+ <div class="form-group">
141
+ <%= label_tag :q_order_line_items_event_id_eq, 'Event' %>
142
+ <%= f.select :order_line_items_event_id_eq,
143
+ Spree::Taxon.events.order(:name).pluck(:name, :id),
144
+ { include_blank: true },
145
+ class: 'select2-clear js-filterable' %>
146
+ </div>
147
+ </div>
138
148
  </div>
139
149
 
140
150
  <div data-hook="admin_inventory_holds_index_search_buttons" class="form-actions">
@@ -0,0 +1,103 @@
1
+ <%# A transit line item as a trip card: route and when, where to board and get off, who sits where,
2
+ and the partner's booking reference. Departure and arrival come from the line item's own
3
+ from_date/to_date, which already carry the trip stops' times on the travel date. %>
4
+ <% trip = lookups[:trips][item.trip_id] %>
5
+ <% boarding = lookups[:trip_stops][item.boarding_trip_stop_id] %>
6
+ <% drop_off = lookups[:trip_stops][item.drop_off_trip_stop_id] %>
7
+ <% vendor = lookups[:vendors][item.vendor_id] %>
8
+ <% external_ref = item.external_ref %>
9
+
10
+ <div class="line-item transit-line-item border rounded p-3 mb-3" id="line-item-<%= item.id %>">
11
+ <div class="d-flex justify-content-between align-items-start flex-wrap">
12
+ <div class="mb-2">
13
+ <div class="d-flex align-items-center flex-wrap">
14
+ <%= transit_direction_badge(item) %>
15
+ <% if item.connected_trip_id.present? %>
16
+ <span class="badge badge-light border text-uppercase mr-2"><%= Spree.t(:connecting, default: 'Connecting') %></span>
17
+ <% end %>
18
+ <h6 class="mb-0"><%= link_to item.name, edit_admin_product_path(item.variant.product) %></h6>
19
+ <%# What staff paste into the partner's own system, so it sits right beside the route. %>
20
+ <% if external_ref.present? %>
21
+ <span class="d-inline-flex align-items-center ml-3 pl-3 border-left">
22
+ <span class="text-muted mr-1"><%= Spree.t(:external_ref, default: 'External Ref') %>:</span>
23
+ <strong><%= external_ref %></strong>
24
+ <%# Handled by spree_cm_commissioner/copy_to_clipboard.js, which swaps the icons with an inline display style: keep !important display classes (d-flex, d-inline-flex) off the two spans or they win and both icons show.
25
+ The icons are centred absolutely: Spree's button CSS adds margins to svgs, which pushed a flex-centred icon off-centre. %>
26
+ <button type="button" class="btn btn-light border ml-2"
27
+ style="position: relative; display: inline-block; vertical-align: middle; box-sizing: border-box; width: 24px; height: 24px; min-width: 24px; padding: 0;" title="<%= Spree.t(:copy, default: 'Copy') %>" data-copy-value="<%= external_ref %>">
28
+ <span data-copy-idle>
29
+ <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16" aria-hidden="true"
30
+ style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0 !important; display: block;">
31
+ <path d="M13 0H6a2 2 0 0 0-2 2 2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2 2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zm0 13V4a2 2 0 0 0-2-2H5a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1zM3 4a1 1 0 0 1 1-1h7a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4z"/>
32
+ </svg>
33
+ </span>
34
+ <span data-copy-done class="text-success" style="display: none;">
35
+ <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16" aria-hidden="true"
36
+ style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0 !important; display: block;">
37
+ <path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/>
38
+ </svg>
39
+ </span>
40
+ </button>
41
+ </span>
42
+ <% end %>
43
+ </div>
44
+ <div class="small text-muted mt-1">
45
+ <%= item.number %>
46
+ <% if vendor %> · <%= vendor.name %><% end %>
47
+ <% if trip&.vehicle_type %> · <%= trip.vehicle_type.name %><% end %>
48
+ </div>
49
+ </div>
50
+
51
+ <div class="d-flex align-items-center">
52
+ <%# The unit fare only: a line total here ignored adjustments and disagreed with the order summary. %>
53
+ <div class="text-right text-muted mr-3"><%= item.single_money.to_html %> × <%= item.quantity %></div>
54
+ <% if can? :update, item %>
55
+ <span class="d-flex" data-hook="cart_line_item_delete">
56
+ <%= link_to_with_icon 'edit.svg', Spree.t('edit'), edit_admin_order_line_item_path(item.order, item), class: 'btn btn-light btn-sm mr-1', title: Spree.t('edit'), no_text: true %>
57
+ <%= link_to_with_icon 'delete.svg', Spree.t('delete'), '#', class: 'delete-line-item btn btn-danger btn-sm', data: { 'line-item-id' => item.id, action: 'remove' }, title: Spree.t('delete'), no_text: true %>
58
+ </span>
59
+ <% end %>
60
+ </div>
61
+ </div>
62
+
63
+ <div class="row align-items-center bg-light rounded mx-0 py-2">
64
+ <div class="col-5">
65
+ <div class="small text-muted text-uppercase"><%= Spree.t(:departure, default: 'Departure') %></div>
66
+ <%= transit_datetime(item.from_date) %>
67
+ <div class="small mt-1"><%= transit_stop_label(boarding) %></div>
68
+ </div>
69
+ <div class="col-2 text-center text-muted">
70
+ <div class="h6 mb-1"><%= transit_duration(item.from_date, item.to_date) %></div>
71
+ <div>&rarr;</div>
72
+ </div>
73
+ <div class="col-5 text-right">
74
+ <div class="small text-muted text-uppercase"><%= Spree.t(:arrival, default: 'Arrival') %></div>
75
+ <%= transit_datetime(item.to_date) %>
76
+ <div class="small mt-1"><%= transit_stop_label(drop_off) %></div>
77
+ </div>
78
+ </div>
79
+
80
+ <div class="mt-3">
81
+ <div class="text-muted small text-uppercase mb-1"><%= Spree.t(:passengers, default: 'Passengers') %> (<%= item.quantity %>)</div>
82
+ <% if item.guests.any? %>
83
+ <%# Rows of plain flex cells, not a <table>: Spree's table CSS pads a header cell differently from a body cell,
84
+ which left the headings off their columns. Every row here uses the same three column widths and padding. %>
85
+ <div class="transit-passengers" role="table">
86
+ <div class="d-flex small text-muted text-uppercase font-weight-bold border-bottom py-2" role="row">
87
+ <div class="pr-2" style="width: 15%;" role="columnheader"><%= Spree.t(:seat, default: 'Seat') %></div>
88
+ <div class="px-2" style="width: 45%;" role="columnheader"><%= Spree.t(:name, default: 'Name') %></div>
89
+ <div class="px-2" style="width: 40%;" role="columnheader"><%= Spree.t(:nationality, default: 'Nationality') %></div>
90
+ </div>
91
+ <% item.guests.each do |guest| %>
92
+ <div class="d-flex border-bottom py-2" style="font-size: 0.875rem;" role="row">
93
+ <div class="pr-2" style="width: 15%;" role="cell"><strong><%= transit_passenger_seat_label(guest) %></strong></div>
94
+ <div class="px-2" style="width: 45%;" role="cell"><%= transit_passenger_name(guest) %></div>
95
+ <div class="px-2" style="width: 40%;" role="cell"><%= transit_passenger_fare_label(guest) %></div>
96
+ </div>
97
+ <% end %>
98
+ </div>
99
+ <% else %>
100
+ <span class="text-muted">-</span>
101
+ <% end %>
102
+ </div>
103
+ </div>
@@ -7,6 +7,7 @@
7
7
  saving: t('rates_availabilities.bulk.saving'),
8
8
  done: t('rates_availabilities.bulk.done'),
9
9
  busy: t('rates_availabilities.bulk.busy'),
10
+ untracked: t('rates_availabilities.bulk.untracked'),
10
11
  useBaseStockConfirm: t('rates_availabilities.bulk.use_base_stock_confirm'),
11
12
  failed: t('rates_availabilities.modal.failed')
12
13
  }.to_json) %>;
@@ -493,9 +494,12 @@
493
494
  }).then((response) => response.json().then((body) => {
494
495
  if (!response.ok) throw new Error(body.error);
495
496
  return this.monthTables.reload().then(() => {
497
+ // One report: a second call would replace the first, losing busy when both come back.
498
+ const notes = [];
499
+ if (body.busy) notes.push(T.busy.replace('%{count}', body.busy));
500
+ if (body.untracked) notes.push(T.untracked.replace('%{count}', body.untracked));
496
501
  const done = T.done.replace('%{updated}', body.updated).replace('%{skipped}', body.skipped);
497
- if (body.busy) this.report(done + '. ' + T.busy.replace('%{count}', body.busy), 'warning');
498
- else this.report(done, 'success');
502
+ this.report([done].concat(notes).join('. '), notes.length ? 'warning' : 'success');
499
503
  });
500
504
  })).catch((error) => {
501
505
  this.report(error.message, 'danger');
@@ -250,6 +250,27 @@
250
250
  </div>
251
251
  </div>
252
252
 
253
+ <!-- ======================== Firebase ======================== -->
254
+ <div class="card mb-4">
255
+ <div class="card-body">
256
+ <div data-hook="admin_tenant_form_fields" class="row mt-4">
257
+ <div class="col-12 mb-4 d-flex flex-wrap align-items-center justify-content-between">
258
+ <h4 class="mb-0">Firebase <span class="text-muted" style="font-size: 1rem; font-weight: normal;">(this tenant app's own Firebase project for sign-in and push notifications)</span></h4>
259
+ <% if f.object.firebase_project_id.present? && f.object.firebase_service_account.present? %>
260
+ <span class="badge badge-success">Using this tenant's project</span>
261
+ <% elsif f.object.firebase_project_id.present? %>
262
+ <span class="badge badge-warning">No service account</span>
263
+ <% else %>
264
+ <span class="badge badge-secondary">Shared project</span>
265
+ <% end %>
266
+ </div>
267
+ <div class="col-12">
268
+ <%= render partial: 'spree/admin/tenants/form/firebase', locals: { f: f } %>
269
+ </div>
270
+ </div>
271
+ </div>
272
+ </div>
273
+
253
274
  <!-- ======================== Redirect Settings ======================== -->
254
275
  <div class="card mb-4">
255
276
  <div class="card-body">
@@ -0,0 +1,32 @@
1
+ <div data-hook="admin_tenant_firebase_fields" class="row">
2
+ <div class="col-md-6">
3
+ <%= f.field_container :firebase_service_account_upload do %>
4
+ <%= f.label :firebase_service_account_upload, 'Service account key (JSON)' %>
5
+ <span title="Only needs the Firebase Cloud Messaging API Admin and Firebase Authentication Viewer roles. Stored encrypted and never shown again. The project ID is read from the file."
6
+ style="cursor: help; margin-left: 4px;">&#9432;</span>
7
+ <%= f.file_field :firebase_service_account_upload, class: 'form-control-file', accept: 'application/json,.json' %>
8
+ <% if f.object.errors[:firebase_service_account].any? %>
9
+ <div class="error text-danger"><%= f.object.errors[:firebase_service_account].join(', ') %></div>
10
+ <% end %>
11
+ <% end %>
12
+ </div>
13
+
14
+ <div class="col-md-6">
15
+ <%= f.field_container :firebase_project_id do %>
16
+ <%= f.label :firebase_project_id, 'Project ID' %>
17
+ <span title="Users of older app installs on the shared BookMe+ project keep signing in after this is set."
18
+ style="cursor: help; margin-left: 4px;">&#9432;</span>
19
+ <input type="text" class="form-control text-monospace" readonly
20
+ value="<%= f.object.firebase_project_id %>" placeholder="Shared BookMe+ project">
21
+ <% if f.object.errors[:firebase_project_id].any? %>
22
+ <div class="error text-danger"><%= f.object.errors[:firebase_project_id].join(', ') %></div>
23
+ <% end %>
24
+ <% if f.object.firebase_project_id.present? %>
25
+ <div class="form-check mt-2">
26
+ <%= f.check_box :remove_firebase_project, class: 'form-check-input' %>
27
+ <%= f.label :remove_firebase_project, 'Switch back to the shared project', class: 'form-check-label' %>
28
+ </div>
29
+ <% end %>
30
+ <% end %>
31
+ </div>
32
+ </div>
@@ -4,13 +4,15 @@ module Firebase
4
4
  module Admin
5
5
  module Auth
6
6
  module UserManagerDecorator
7
+ # query: { sub:, provider_id: } where provider_id is the Firebase sign-in provider the sub
8
+ # belongs to ('google.com', 'apple.com'); defaults to Google.
7
9
  def get_user_by_sub(query)
8
10
  sub = query[:sub]
9
11
  return if sub.blank?
10
12
 
11
13
  payload = {
12
14
  federatedUserId: {
13
- providerId: 'google.com',
15
+ providerId: query[:provider_id] || 'google.com',
14
16
  rawId: sub
15
17
  }
16
18
  }
@@ -411,6 +411,7 @@ en:
411
411
  transit: "Transit"
412
412
  intercity_taxi: "Intercity Taxi"
413
413
  accommodation: "Accommodation"
414
+ activity: "Activity"
414
415
  service_type: "Service Type"
415
416
  primary_service_type: "Primary Service Type"
416
417
  select_service_type: "Select Service Type"
@@ -1121,6 +1122,8 @@ en:
1121
1122
  less_than_used: "cannot be less than paid votes used (%{used})"
1122
1123
  spree_cm_commissioner/tenant:
1123
1124
  format: "must not include protocol (http:// or https://)"
1125
+ invalid_service_account: "must be a Firebase service account JSON key"
1126
+ service_account_project_mismatch: "belongs to project %{key_project}, not %{project}"
1124
1127
  spree/taxon:
1125
1128
  attributes:
1126
1129
  from_date:
@@ -1373,6 +1376,7 @@ en:
1373
1376
  inventory_item:
1374
1377
  reset:
1375
1378
  busy: "Stock changed while it was being recounted, as someone is booking it. Try again in a moment."
1379
+ untracked_inventory: "This variant doesn't track inventory, so there's no stock to recount."
1376
1380
 
1377
1381
  # Displayed as-is on stock-status badges pushed to Firestore (see
1378
1382
  # SpreeCmCommissioner::Products::PublishStockStatusToFirestore) — not read via I18n at request
@@ -1850,6 +1854,7 @@ en:
1850
1854
  reset_stock_confirm: "Recount stock? Available and on-hold are recalculated from Base stock and orders, which undoes stock set on the date."
1851
1855
  recount_limit: "Recount up to %{max} dates at a time"
1852
1856
  busy: "%{count} were being booked and were left as they were; try them again in a moment."
1857
+ untracked: "%{count} don't track inventory and were left as they were."
1853
1858
  use_base_stock: "Use Base stock"
1854
1859
  use_base_stock_hint: "Recount the selected dates from Base stock and orders, undoing the stock set on them"
1855
1860
  use_base_stock_confirm: "Recount %{count} selected dates from Base stock and orders? Stock set on them is undone."
@@ -370,6 +370,7 @@ km:
370
370
  transit: "Transit"
371
371
  intercity_taxi: "Intercity Taxi"
372
372
  accommodation: "Accommodation"
373
+ activity: "Activity"
373
374
  service_type: "ប្រភេទសេវាកម្ម"
374
375
  primary_service_type: "ប្រភេទសេវាកម្មចម្បង"
375
376
  select_service_type: "ជ្រើសរើសប្រភេទសេវាកម្ម"
@@ -720,6 +721,8 @@ km:
720
721
  less_than_used: "មិនអាចតូចជាងចំនួនសំឡេងបង់ប្រាក់ដែលបានប្រើ (%{used})"
721
722
  spree_cm_commissioner/tenant:
722
723
  format: "មិនអនុញ្ញាតឱ្យបញ្ចូលឈ្មោះដែលភ្ជាប់ជាមួយ (http:// ឬ https://)"
724
+ invalid_service_account: "ត្រូវតែជាឯកសារ JSON គណនីសេវាកម្ម Firebase"
725
+ service_account_project_mismatch: "ជារបស់គម្រោង %{key_project} មិនមែន %{project} ទេ"
723
726
  spree/taxon:
724
727
  attributes:
725
728
  from_date:
@@ -875,6 +878,7 @@ km:
875
878
  inventory_item:
876
879
  reset:
877
880
  busy: "ស្តុកបានផ្លាស់ប្តូរពេលកំពុងរាប់ឡើងវិញ ព្រោះមានអ្នកកំពុងកក់។ សូមព្យាយាមម្តងទៀតបន្តិចទៀត។"
881
+ untracked_inventory: "វ៉ារ្យ៉ង់នេះមិនតាមដានស្តុកទេ ដូច្នេះគ្មានស្តុកសម្រាប់រាប់ឡើងវិញទេ។"
878
882
 
879
883
  stock_status:
880
884
  pending_hold: "តម្រូវការខ្ពស់"
@@ -1352,6 +1356,7 @@ km:
1352
1356
  reset_stock_confirm: "រាប់ស្តុកឡើងវិញ? ចំនួននៅសល់ និងកំពុងរក្សាទុកនឹងត្រូវគណនាឡើងវិញពីស្តុកមូលដ្ឋាន និងការកម្ម៉ង់ ដែលលុបស្តុកដែលបានកំណត់លើថ្ងៃនោះ។"
1353
1357
  recount_limit: "អាចរាប់ស្តុកឡើងវិញបានយ៉ាងច្រើន %{max} ថ្ងៃក្នុងមួយលើក"
1354
1358
  busy: "%{count} កំពុងត្រូវបានកក់ ហើយមិនត្រូវបានប្តូរទេ។ សូមព្យាយាមម្តងទៀតបន្តិចទៀត។"
1359
+ untracked: "%{count} មិនតាមដានស្តុកទេ ហើយមិនត្រូវបានប្តូរទេ។"
1355
1360
  use_base_stock: "ប្រើស្តុកមូលដ្ឋាន"
1356
1361
  use_base_stock_hint: "រាប់ស្តុកថ្ងៃដែលបានជ្រើសឡើងវិញពីស្តុកមូលដ្ឋាន និងការកម្ម៉ង់ ដោយលុបស្តុកដែលបានកំណត់លើថ្ងៃទាំងនោះ"
1357
1362
  use_base_stock_confirm: "រាប់ស្តុក %{count} ថ្ងៃដែលបានជ្រើសឡើងវិញពីស្តុកមូលដ្ឋាន និងការកម្ម៉ង់? ស្តុកដែលបានកំណត់លើថ្ងៃទាំងនោះនឹងត្រូវលុប។"
@@ -0,0 +1,12 @@
1
+ class AddFirebaseProjectToCmTenants < ActiveRecord::Migration[7.0]
2
+ def change
3
+ add_column :cm_tenants, :firebase_project_id, :string, if_not_exists: true
4
+
5
+ # Holds ActiveRecord::Encryption ciphertext of the service account JSON, never the JSON itself.
6
+ add_column :cm_tenants, :firebase_service_account, :text, if_not_exists: true
7
+
8
+ # Not unique: tenant apps share one non-production project (each app registered in it), so several
9
+ # tenants can point at the same ID.
10
+ add_index :cm_tenants, :firebase_project_id, where: 'firebase_project_id IS NOT NULL', if_not_exists: true
11
+ end
12
+ end
@@ -0,0 +1,6 @@
1
+ class AddFirebaseProjectIdToCmDeviceTokens < ActiveRecord::Migration[7.0]
2
+ def change
3
+ # NULL means the shared project: every token registered before tenant apps had their own.
4
+ add_column :cm_device_tokens, :firebase_project_id, :string, if_not_exists: true
5
+ end
6
+ end
@@ -0,0 +1,10 @@
1
+ class AddInternalIndexToCmIntegrationMappings < ActiveRecord::Migration[7.0]
2
+ # CONCURRENTLY can't run inside a transaction; it avoids locking cm_integration_mappings against writes during the build.
3
+ disable_ddl_transaction!
4
+
5
+ def change
6
+ columns = %i[internal_type internal_id]
7
+
8
+ add_index :cm_integration_mappings, columns, algorithm: :concurrently unless index_exists?(:cm_integration_mappings, columns)
9
+ end
10
+ end
@@ -1,9 +1,11 @@
1
1
  # Refactored with / from:
2
2
  # spree_core-4.4.0/lib/spree/testing_support/factories/user_factory.rb
3
3
 
4
+ require_relative '../firebase_id_token_helper'
5
+
4
6
  FactoryBot.define do
5
7
  sequence :cm_id_token do |_n|
6
- 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImE5NmFkY2U5OTk5YmJmNWNkMzBmMjlmNDljZDM3ZjRjNWU2NDI3NDAiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiUGFuaGEgQ2hvbSIsInBpY3R1cmUiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS9BTG01d3UyUXRmU2owU0NqTGpuSW9jNk5YSzBvSUpTVGVXZ1dXRWJ6XzgyTj1zOTYtYyIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9jbS1tYXJrZXQtNDMzYjEiLCJhdWQiOiJjbS1tYXJrZXQtNDMzYjEiLCJhdXRoX3RpbWUiOjE2NjkyODQwMDQsInVzZXJfaWQiOiJWcWZtY2o5V1F2UlM4QllBb2VmMk5meGVJdWQyIiwic3ViIjoiVnFmbWNqOVdRdlJTOEJZQW9lZjJOZnhlSXVkMiIsImlhdCI6MTY2OTI4NDAwNCwiZXhwIjoxNjY5Mjg3NjA0LCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7Imdvb2dsZS5jb20iOlsiMTExNTkxNzcwMTQ4MjcxOTc5NzYzIl19LCJzaWduX2luX3Byb3ZpZGVyIjoiZ29vZ2xlLmNvbSJ9fQ.R95hhSSQI-LEYgjJx9IQ-weuDIZRc7umxVURhdqWvii3pC67GZkPoXMT0QqnehBb4DB7TQyUN_AGbO_G34HlOJZ3g1L7_f_45zdnGodZdW0he4zrGaqNj59pe1oppyvnG9EwupXwjjP1p-ASMvxUJ5VW4_TvkwJx9nIyB3PHNuqvPEvg8eqHACdxQ4lrqJClPgxJoHvh9rLgQmPLbwGGMDBDH8DMSID1fum5qfwWHUrqDp87MGbe43566tb2rh7YBB0Lpb8LCR-SbkgugnyxSl4LY_2NvP2ozRRY5EtbbggYrW3akMaYNXq6abAJrIucf6GJzerL0tQW'
8
+ SpreeCmCommissioner::TestHelper::FirebaseIdTokenHelper.mint
7
9
  end
8
10
 
9
11
  sequence :cm_random_phone_number do |n|
@@ -0,0 +1,53 @@
1
+ require 'jwt'
2
+ require 'openssl'
3
+
4
+ module SpreeCmCommissioner
5
+ module TestHelper
6
+ # Mints Firebase-shaped ID tokens with fresh `iat`/`exp`, so specs build claims per case instead
7
+ # of reusing one captured token that expired years ago.
8
+ module FirebaseIdTokenHelper
9
+ KID = 'spec-firebase-kid'.freeze
10
+ PROJECT_ID = 'spec-firebase-project'.freeze
11
+
12
+ module_function
13
+
14
+ def mint(project_id: PROJECT_ID, claims: {}, key: signing_key, kid: KID, issued_at: Time.now.to_i)
15
+ payload = {
16
+ 'name' => 'Panha Chom',
17
+ 'iss' => "https://securetoken.google.com/#{project_id}",
18
+ 'aud' => project_id,
19
+ 'auth_time' => issued_at,
20
+ 'user_id' => 'Vqfmcj9WQvRS8BYAoef2NfxeIud2',
21
+ 'sub' => 'Vqfmcj9WQvRS8BYAoef2NfxeIud2',
22
+ 'iat' => issued_at,
23
+ 'exp' => issued_at + 3600,
24
+ 'firebase' => { 'identities' => { 'google.com' => ['111591770148271979763'] }, 'sign_in_provider' => 'google.com' }
25
+ }.merge(claims.stringify_keys)
26
+
27
+ JWT.encode(payload.compact, key, 'RS256', { kid: kid })
28
+ end
29
+
30
+ def certificates
31
+ { KID => certificate.to_pem }
32
+ end
33
+
34
+ def signing_key
35
+ @signing_key ||= OpenSSL::PKey::RSA.new(2048)
36
+ end
37
+
38
+ def certificate
39
+ @certificate ||= begin
40
+ cert = OpenSSL::X509::Certificate.new
41
+ cert.version = 2
42
+ cert.serial = 1
43
+ cert.subject = cert.issuer = OpenSSL::X509::Name.parse('/CN=securetoken.system.gserviceaccount.com')
44
+ cert.public_key = signing_key.public_key
45
+ cert.not_before = Time.now.utc - 3600
46
+ cert.not_after = Time.now.utc + (10 * 365 * 24 * 3600)
47
+ cert.sign(signing_key, OpenSSL::Digest.new('SHA256'))
48
+ cert
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -1,5 +1,5 @@
1
1
  module SpreeCmCommissioner
2
- VERSION = '2.16.0'.freeze
2
+ VERSION = '2.16.1'.freeze
3
3
 
4
4
  module_function
5
5
 
@@ -1,7 +1,8 @@
1
1
  # recommend to be used in schedule.yml & manually access in /sidekiq/cron
2
2
  namespace :spree_cm_commissioner do
3
- desc 'Fetch email from firebase'
4
- task fetch_email: :environment do
5
- SpreeCmCommissioner::FirebaseEmailFetcherJob.perform_now
3
+ desc 'Fill blank Google/Apple emails from the shared Firebase project. Run per tenant before switching its app ' \
4
+ 'to its own Firebase project: rake "spree_cm_commissioner:fetch_email[tenant_id]"'
5
+ task :fetch_email, [:tenant_id] => :environment do |_task, args|
6
+ SpreeCmCommissioner::FirebaseEmailFetcherJob.perform_now(tenant_id: args[:tenant_id].presence)
6
7
  end
7
8
  end
@@ -0,0 +1,10 @@
1
+ namespace :spree_cm_commissioner do
2
+ desc "Delete a tenant's push tokens that aren't from its own Firebase project. Run after switching its app " \
3
+ 'to that project, and again once old app versions are gone: rake "spree_cm_commissioner:prune_device_tokens[tenant_id]"'
4
+ task :prune_device_tokens, [:tenant_id] => :environment do |_task, args|
5
+ result = SpreeCmCommissioner::DeviceTokens::PruneOtherProjects.call(tenant_id: args[:tenant_id])
6
+ abort result.error.to_s if result.failure?
7
+
8
+ puts "Deleted #{result.value} device tokens"
9
+ end
10
+ end