diff --git a/app/controllers/card_grants_controller.rb b/app/controllers/card_grants_controller.rb index 0bf2cdcabf..fa4ce9af7d 100644 --- a/app/controllers/card_grants_controller.rb +++ b/app/controllers/card_grants_controller.rb @@ -58,6 +58,31 @@ def update redirect_to card_grant_url(@card_grant) end + def set_index + card_grant = CardGrant.find(params[:id]) + authorize card_grant + + index = params[:index] + + # get all the card grants as an array + card_grants = StaticPageService::Index.new(current_user:).card_grants.not_hidden.to_a + + return head status: :bad_request if index < 0 || index >= card_grants.size + + # switch the position *in the in-memory array* + card_grants.delete card_grant + card_grants.insert index, card_grant + + # persist the sort order + ActiveRecord::Base.transaction do + card_grants.each_with_index do |cg, idx| + cg.update(sort_index: idx) + end + end + + render json: card_grants.pluck(:id) + end + def clear_purpose authorize @card_grant, :update? @card_grant.update(purpose: nil) diff --git a/app/javascript/controllers/sort_card_controller.js b/app/javascript/controllers/sort_card_controller.js new file mode 100644 index 0000000000..9a8d96ad17 --- /dev/null +++ b/app/javascript/controllers/sort_card_controller.js @@ -0,0 +1,30 @@ +import { Controller } from '@hotwired/stimulus' +import csrf from '../common/csrf' + +export default class extends Controller { + static values = { + order: Array, + } + + async sort({ detail: { oldIndex, newIndex } }) { + if (oldIndex == newIndex) return + + const copy = this.orderValue + + const id = copy[oldIndex] + + copy.splice(oldIndex, 1) + copy.splice(newIndex, 0, id) + + this.orderValue = copy + + await fetch(`/grants/${id}/set_index`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-CSRF-Token': csrf(), + }, + body: JSON.stringify({ index: newIndex }), + }) + } +} diff --git a/app/models/card_grant.rb b/app/models/card_grant.rb index fea5237231..03d31cf086 100644 --- a/app/models/card_grant.rb +++ b/app/models/card_grant.rb @@ -11,6 +11,7 @@ # keyword_lock :string # merchant_lock :string # purpose :string +# sort_index :float # status :integer default("active"), not null # created_at :datetime not null # updated_at :datetime not null diff --git a/app/views/static_pages/index.html.erb b/app/views/static_pages/index.html.erb index 0117a50bb4..bc47ff4a00 100644 --- a/app/views/static_pages/index.html.erb +++ b/app/views/static_pages/index.html.erb @@ -32,9 +32,17 @@ <% if current_user.card_grants.activated.size > 0 %>