Skip to content

Commit ed1f085

Browse files
authored
Merge pull request #4417 from rubyforgood/kp/merge-line-items-at-request-save__data-migration
clean up any item duplicates in requests
2 parents 12423b9 + 3503188 commit ed1f085

2 files changed

Lines changed: 59 additions & 1 deletion

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class DedupItemRequestsInRequests < ActiveRecord::Migration[7.1]
2+
disable_ddl_transaction!
3+
4+
def up
5+
# There's some really gross request data in Jan 2023 and earlier
6+
# that we don't want to get swept up in this migration. We'll need
7+
# to fix it some day but for now we'll make recent-ish, well-formed
8+
# data obey the dedup requirement, which will reduce weird edge
9+
# cases when fulfilling requests + editing distributions.
10+
start_date = Date.new(2023, 6, 1)
11+
12+
Request.where(created_at: start_date..).find_each do |request|
13+
grouped_item_requests = request.item_requests.to_a.group_by(&:item_id)
14+
15+
if grouped_item_requests.values.all? { |item_requests| item_requests.length == 1 }
16+
next
17+
end
18+
19+
Request.transaction do
20+
request_items = grouped_item_requests.map do |item_id, item_requests|
21+
if item_requests.length == 1
22+
next {
23+
item_id: item_id,
24+
quantity: item_requests.first.quantity
25+
}
26+
end
27+
28+
quantity = item_requests.map { |item_request| item_request.quantity.to_i }.sum.to_s
29+
children = item_requests.flat_map(&:children).uniq
30+
31+
primary_item_request = item_requests.shift
32+
33+
# If item_requests isn't empty, then there were more
34+
# item_requests with that same item_id
35+
if !item_requests.empty?
36+
primary_item_request.update!(
37+
quantity: quantity,
38+
children: children
39+
)
40+
41+
item_requests.each(&:destroy!)
42+
end
43+
44+
{
45+
item_id: item_id,
46+
quantity: quantity
47+
}
48+
end
49+
50+
request.reload.update!(request_items: request_items)
51+
end
52+
end
53+
end
54+
55+
def down
56+
raise ActiveRecord::IrreversibleMigration
57+
end
58+
end

db/schema.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#
1111
# It's strongly recommended that you check this file into your version control system.
1212

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

0 commit comments

Comments
 (0)