Skip to content

Commit

Permalink
Merge pull request #4417 from rubyforgood/kp/merge-line-items-at-requ…
Browse files Browse the repository at this point in the history
…est-save__data-migration

clean up any item duplicates in requests
  • Loading branch information
awwaiid committed Jun 16, 2024
2 parents 12423b9 + 3503188 commit ed1f085
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
58 changes: 58 additions & 0 deletions db/migrate/20240601155348_dedup_item_requests_in_requests.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class DedupItemRequestsInRequests < ActiveRecord::Migration[7.1]
disable_ddl_transaction!

def up
# There's some really gross request data in Jan 2023 and earlier
# that we don't want to get swept up in this migration. We'll need
# to fix it some day but for now we'll make recent-ish, well-formed
# data obey the dedup requirement, which will reduce weird edge
# cases when fulfilling requests + editing distributions.
start_date = Date.new(2023, 6, 1)

Request.where(created_at: start_date..).find_each do |request|
grouped_item_requests = request.item_requests.to_a.group_by(&:item_id)

if grouped_item_requests.values.all? { |item_requests| item_requests.length == 1 }
next
end

Request.transaction do
request_items = grouped_item_requests.map do |item_id, item_requests|
if item_requests.length == 1
next {
item_id: item_id,
quantity: item_requests.first.quantity
}
end

quantity = item_requests.map { |item_request| item_request.quantity.to_i }.sum.to_s
children = item_requests.flat_map(&:children).uniq

primary_item_request = item_requests.shift

# If item_requests isn't empty, then there were more
# item_requests with that same item_id
if !item_requests.empty?
primary_item_request.update!(
quantity: quantity,
children: children
)

item_requests.each(&:destroy!)
end

{
item_id: item_id,
quantity: quantity
}
end

request.reload.update!(request_items: request_items)
end
end
end

def down
raise ActiveRecord::IrreversibleMigration
end
end
2 changes: 1 addition & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[7.1].define(version: 2024_05_19_201258) do
ActiveRecord::Schema[7.1].define(version: 2024_06_01_155348) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

Expand Down

0 comments on commit ed1f085

Please sign in to comment.