diff --git a/db/data_migration/v2.12/README.md b/db/data_migration/v2.12/README.md new file mode 100644 index 0000000000..29a91bfd41 --- /dev/null +++ b/db/data_migration/v2.12/README.md @@ -0,0 +1,13 @@ +# Migrations in 2.12 + +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.12/update_calculated_avg_fields_gbv.rb +``` \ No newline at end of file diff --git a/db/data_migration/v2.12/update_calculated_avg_fields_gbv.rb b/db/data_migration/v2.12/update_calculated_avg_fields_gbv.rb new file mode 100644 index 0000000000..3413f66850 --- /dev/null +++ b/db/data_migration/v2.12/update_calculated_avg_fields_gbv.rb @@ -0,0 +1,27 @@ +# 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(field, save) + old_avg_data = field.calculation.dig('expression', 'avg') + field.calculation = { type: 'number', expression: { avg: { data: old_avg_data, extra: { decimalPlaces: 2 } } } } + field.disabled = true + field.type = 'calculated' + if save + field.save! + puts "Updated field #{field.name}" + else + puts "Would update #{field.name} to the following" + puts field.inspect + end +end + +fields_with_old_avg_calculations.each { |f| migrate_field(f, save_records) }