from django.core.management.base import BaseCommand
from toggle.models import Toggle

from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation
from corehq.toggles import FLAT_LOCATION_FIXTURE


class Command(BaseCommand):
    help = """
    To migrate to new flat fixture for locations. Update apps with locations and not having
    FLAT_LOCATION_FIXTURE enabled to have LocationFixtureConfiguration with
    sync_hierarchical_fixture True and sync_flat_fixture False to have old fixtures enabled.
    The Feature Flag should be removed after this
    """

    def handle(self, *args, **options):
        domains_having_locations = set(SQLLocation.objects.values_list('domain', flat=True))
        toggle = Toggle.get(FLAT_LOCATION_FIXTURE.slug)
        enabled_users = toggle.enabled_users
        enabled_domains = [user.split('domain:')[1] for user in enabled_users]
        for domain_name in domains_having_locations:
            if domain_name not in enabled_domains:
                domain_config = LocationFixtureConfiguration.for_domain(domain_name)
                # update configs that had not been changed which means both values are at default True
                if domain_config.sync_hierarchical_fixture and domain_config.sync_flat_fixture:
                    # update them to use hierarchical fixture
                    domain_config.sync_flat_fixture = False
                    domain_config.sync_hierarchical_fixture = True
                    domain_config.save()

import json
from django.core.management.base import BaseCommand
from toggle.models import Toggle

from corehq.apps.locations.models import SQLLocation
from corehq.apps.domain.models import Domain
from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN


class Command(BaseCommand):
    help = """
    To migrate to new flat fixture for locations. Enable FF HIERARCHICAL_LOCATION_FIXTURE for
    apps with locations and having commtrack:enabled in app files
    The Feature Flag FLAT_LOCATION_FIXTURE should be removed after this
    """

    def handle(self, *args, **options):
        domains_having_locations = (
            SQLLocation.objects.order_by('domain').distinct('domain')
            .values_list('domain', flat=True)
        )
        domains_with_hierarchical_fixture = find_applications_with_hierarchical_fixture(
            domains_having_locations
        )
        toggle = Toggle.get(HIERARCHICAL_LOCATION_FIXTURE.slug)
        for domain in domains_with_hierarchical_fixture:
            toggle.add(domain, True, NAMESPACE_DOMAIN)


def find_applications_with_hierarchical_fixture(domains):
    search_string = 'commtrack:enabled'
    domain_with_application = {}
    for domain in domains:
        domain_obj = Domain.get_by_name(domain)
        for application in domain_obj.applications():
            raw_doc = json.dumps(application.get_db().get(application.id))
            if search_string in raw_doc:
                search_string[domain] = application.id
                continue
    return domain_with_application

Update migration to fetch domains with applications using old location fixture
Update migration to fetch domains with applications using old location fixture
+ import json
  from django.core.management.base import BaseCommand
  from toggle.models import Toggle
  
- from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation
+ from corehq.apps.locations.models import SQLLocation
- from corehq.toggles import FLAT_LOCATION_FIXTURE
+ from corehq.apps.domain.models import Domain
+ from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN
  
  
  class Command(BaseCommand):
      help = """
+     To migrate to new flat fixture for locations. Enable FF HIERARCHICAL_LOCATION_FIXTURE for
+     apps with locations and having commtrack:enabled in app files
-     To migrate to new flat fixture for locations. Update apps with locations and not having
-     FLAT_LOCATION_FIXTURE enabled to have LocationFixtureConfiguration with
-     sync_hierarchical_fixture True and sync_flat_fixture False to have old fixtures enabled.
-     The Feature Flag should be removed after this
+     The Feature Flag FLAT_LOCATION_FIXTURE should be removed after this
      """
  
      def handle(self, *args, **options):
-         domains_having_locations = set(SQLLocation.objects.values_list('domain', flat=True))
+         domains_having_locations = (
+             SQLLocation.objects.order_by('domain').distinct('domain')
+             .values_list('domain', flat=True)
+         )
+         domains_with_hierarchical_fixture = find_applications_with_hierarchical_fixture(
+             domains_having_locations
+         )
-         toggle = Toggle.get(FLAT_LOCATION_FIXTURE.slug)
+         toggle = Toggle.get(HIERARCHICAL_LOCATION_FIXTURE.slug)
+         for domain in domains_with_hierarchical_fixture:
+             toggle.add(domain, True, NAMESPACE_DOMAIN)
-         enabled_users = toggle.enabled_users
-         enabled_domains = [user.split('domain:')[1] for user in enabled_users]
-         for domain_name in domains_having_locations:
-             if domain_name not in enabled_domains:
-                 domain_config = LocationFixtureConfiguration.for_domain(domain_name)
-                 # update configs that had not been changed which means both values are at default True
-                 if domain_config.sync_hierarchical_fixture and domain_config.sync_flat_fixture:
-                     # update them to use hierarchical fixture
-                     domain_config.sync_flat_fixture = False
-                     domain_config.sync_hierarchical_fixture = True
-                     domain_config.save()
  
+ 
+ def find_applications_with_hierarchical_fixture(domains):
+     search_string = 'commtrack:enabled'
+     domain_with_application = {}
+     for domain in domains:
+         domain_obj = Domain.get_by_name(domain)
+         for application in domain_obj.applications():
+             raw_doc = json.dumps(application.get_db().get(application.id))
+             if search_string in raw_doc:
+                 search_string[domain] = application.id
+                 continue
+     return domain_with_application
+ 
Update migration to fetch domains with applications using old location fixture
## Code Before:
from django.core.management.base import BaseCommand
from toggle.models import Toggle

from corehq.apps.locations.models import LocationFixtureConfiguration, SQLLocation
from corehq.toggles import FLAT_LOCATION_FIXTURE


class Command(BaseCommand):
    help = """
    To migrate to new flat fixture for locations. Update apps with locations and not having
    FLAT_LOCATION_FIXTURE enabled to have LocationFixtureConfiguration with
    sync_hierarchical_fixture True and sync_flat_fixture False to have old fixtures enabled.
    The Feature Flag should be removed after this
    """

    def handle(self, *args, **options):
        domains_having_locations = set(SQLLocation.objects.values_list('domain', flat=True))
        toggle = Toggle.get(FLAT_LOCATION_FIXTURE.slug)
        enabled_users = toggle.enabled_users
        enabled_domains = [user.split('domain:')[1] for user in enabled_users]
        for domain_name in domains_having_locations:
            if domain_name not in enabled_domains:
                domain_config = LocationFixtureConfiguration.for_domain(domain_name)
                # update configs that had not been changed which means both values are at default True
                if domain_config.sync_hierarchical_fixture and domain_config.sync_flat_fixture:
                    # update them to use hierarchical fixture
                    domain_config.sync_flat_fixture = False
                    domain_config.sync_hierarchical_fixture = True
                    domain_config.save()

## Instruction:
Update migration to fetch domains with applications using old location fixture
## Code After:
import json
from django.core.management.base import BaseCommand
from toggle.models import Toggle

from corehq.apps.locations.models import SQLLocation
from corehq.apps.domain.models import Domain
from corehq.toggles import HIERARCHICAL_LOCATION_FIXTURE, NAMESPACE_DOMAIN


class Command(BaseCommand):
    help = """
    To migrate to new flat fixture for locations. Enable FF HIERARCHICAL_LOCATION_FIXTURE for
    apps with locations and having commtrack:enabled in app files
    The Feature Flag FLAT_LOCATION_FIXTURE should be removed after this
    """

    def handle(self, *args, **options):
        domains_having_locations = (
            SQLLocation.objects.order_by('domain').distinct('domain')
            .values_list('domain', flat=True)
        )
        domains_with_hierarchical_fixture = find_applications_with_hierarchical_fixture(
            domains_having_locations
        )
        toggle = Toggle.get(HIERARCHICAL_LOCATION_FIXTURE.slug)
        for domain in domains_with_hierarchical_fixture:
            toggle.add(domain, True, NAMESPACE_DOMAIN)


def find_applications_with_hierarchical_fixture(domains):
    search_string = 'commtrack:enabled'
    domain_with_application = {}
    for domain in domains:
        domain_obj = Domain.get_by_name(domain)
        for application in domain_obj.applications():
            raw_doc = json.dumps(application.get_db().get(application.id))
            if search_string in raw_doc:
                search_string[domain] = application.id
                continue
    return domain_with_application
