|
| 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 |
0 commit comments