diff --git a/app/controllers/api/v3/facilities_controller.rb b/app/controllers/api/v3/facilities_controller.rb index feb13fdb5c..a398036e0f 100644 --- a/app/controllers/api/v3/facilities_controller.rb +++ b/app/controllers/api/v3/facilities_controller.rb @@ -44,17 +44,29 @@ def force_resync? end def records_to_sync - Facility - .updated_on_server_since(other_facilities_processed_since, limit) - .includes(:facility_group) - .where.not(facility_group: nil) + if Flipper.enabled?(:regions_prep) + other_facility_records + .with_block_region_id + .includes(:facility_group) + .where.not(facility_group: nil) + else + other_facility_records + .includes(:facility_group) + .where.not(facility_group: nil) + end end private + # Memoize this call so that we don't end up making thousands of calls to check user for each facility + def block_level_sync? + return @block_level_sync_enabled if defined? @block_level_sync_enabled + @block_level_sync_enabled = current_user&.block_level_sync? + end + def sync_region_id(facility) - if current_user&.block_level_sync? - facility.region.block_region.id + if block_level_sync? + facility.block_region_id else facility.facility_group_id end diff --git a/app/models/facility.rb b/app/models/facility.rb index 57fe234f0e..002c057ff2 100644 --- a/app/models/facility.rb +++ b/app/models/facility.rb @@ -49,6 +49,11 @@ class Facility < ApplicationRecord foreign_key: "assigned_facility_id" pg_search_scope :search_by_name, against: {name: "A", slug: "B"}, using: {tsearch: {prefix: true, any_word: true}} + scope :with_block_region_id, -> { + joins("INNER JOIN regions facility_regions ON facility_regions.source_id = facilities.id") + .joins("INNER JOIN regions block_region ON block_region.path @> facility_regions.path AND block_region.region_type = 'block'") + .select("block_region.id AS block_region_id, facilities.*") + } enum facility_size: { community: "community",