Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DAO: Data Migration for GBV Calculated Fields #482

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions db/data_migration/v2.11.1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Migrations in 2.11.1

This migration updates the configuration of GBV instances *only*. This migrates the fields that calculate average scores on subforms to new versions which support decimal places.

# Verification of data to be updated

These scripts will update the `Field` records where calculations exist.

To validate which fields will be updated, run the following:

```bash
rails r ./db/migrations/v2.11.1/update_calculated_avg_fields_gbv.rb
```
30 changes: 30 additions & 0 deletions db/data_migration/v2.11.1/update_calculated_avg_fields_gbv.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

save_records = ARGV[0] == 'true'

def fields_with_old_avg_calculations
return unless PrimeroModule.exists? unique_id: PrimeroModule::GBV

avg_fields = Field.where("calculation -> 'expression' ? 'avg'")
# The new type of calculated average field has the avg object as a hash, not an array.
avg_fields.filter { |f| f.calculation.dig('expression', 'avg').is_a?(Array) }
end

def migrate_field(orig_field, save)
old_avg_data = orig_field.calculation.dig('expression', 'avg')
new_field = orig_field.dup
new_field.calculation = { type: 'number', expression: { avg: { data: old_avg_data, extra: { decimalPlaces: 2 } } } }
new_field.disabled = true
new_field.type = 'calculated'
if save
# We because the type of a field cannot be changed, we need to destroy and recreate
orig_field.destroy!
new_field.save!
puts "Updated field #{new_field.name}"
else
puts "Would update #{new_field.name} to the following"
puts new_field.inspect
end
end

fields_with_old_avg_calculations.each { |f| migrate_field(f, save_records) }