<commit_before>import logging

from django.core.management import BaseCommand

from django_prbac.models import Grant, Role

from corehq import toggles
from corehq.apps.accounting.management.commands.change_role_for_software_plan_version import (
    change_role_for_software_plan_version,
)
from corehq.apps.accounting.models import (
    SoftwarePlanEdition,
    SoftwarePlanVisibility,
    Subscription,
)
from corehq.apps.domain.models import Domain

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    """
    Enables the RELEASE_MANAGEMENT privilege on any domain that has the Linked Projects feature flag enabled
    """

    def add_arguments(self, parser):
        parser.add_argument('-q', '--quiet', help="Quiet output to warnings/errors only")
        parser.add_argument('--dry-run', action='store_true', default=False)

    def handle(self, quiet, dry_run, **options):
        logger.setLevel(logging.WARNING if quiet else logging.INFO)
        automatic_upgrades, manual_upgrades = _find_plans_with_linked_projects_toggle()
        _upgrade_plans(automatic_upgrades, dry_run=dry_run)
        logger.info('The following plans need to be manually audited to determine if they are eligible for ERM.')
        formatted_manual_info = "\n".join(manual_upgrades)
        logger.info(formatted_manual_info)


def _find_plans_with_linked_projects_toggle():
    manual_audits = []
    automated_upgrades = []
    for domain in toggles.LINKED_DOMAINS.get_enabled_domains():
        domain_obj = Domain.get_by_name(domain)
        if not domain_obj:
            continue
        if not domain_obj.is_test == 'true':
            continue
        subscription = Subscription.get_active_subscription_by_domain(domain)
        plan_version = subscription.plan_version if subscription else \
            Subscription.get_subscribed_plan_by_domain(domain)
        if plan_version.role.slug not in ['enterprise_plan_v0', 'enterprise_plan_v1']:
            is_public = plan_version.plan.visibility == SoftwarePlanVisibility.PUBLIC
            is_community = plan_version.plan.edition == SoftwarePlanEdition.COMMUNITY
            entry = {
                'domain': domain,
                'plan': plan_version.plan.name,
                'role_slug': plan_version.role.slug,
                'role_name': plan_version.role.name,
                'edition': plan_version.plan.edition,
                'visibility': plan_version.plan.visibility,
                'active_subscription': subscription is not None,
            }
            if is_public or is_community:
                manual_audits.append(entry)
            else:
                automated_upgrades.append(entry)

    return automated_upgrades, manual_audits


def _upgrade_plans(automatic_upgrades, dry_run=False):
    slug_suffix = '_with_erm'
    name_suffix = '(With ERM)'
    for plan_info in automatic_upgrades:
        new_role = _get_or_create_role(plan_info['role_slug'], slug_suffix, name_suffix, dry_run=dry_run)
        change_role_for_software_plan_version(plan_info['role_slug'], new_role.slug, dry_run=dry_run)
<commit_msg>fix logic on test domain, add created_by<commit_after>import logging

from django.core.management import BaseCommand

from django_prbac.models import Grant, Role

from corehq import toggles
from corehq.apps.accounting.management.commands.change_role_for_software_plan_version import (
    change_role_for_software_plan_version,
)
from corehq.apps.accounting.models import (
    SoftwarePlanEdition,
    SoftwarePlanVisibility,
    Subscription,
)
from corehq.apps.domain.models import Domain

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    """
    Enables the RELEASE_MANAGEMENT privilege on any domain that has the Linked Projects feature flag enabled
    """

    def add_arguments(self, parser):
        parser.add_argument('-q', '--quiet', help="Quiet output to warnings/errors only")
        parser.add_argument('--dry-run', action='store_true', default=False)

    def handle(self, quiet, dry_run, **options):
        logger.setLevel(logging.WARNING if quiet else logging.INFO)
        automatic_upgrades, manual_upgrades = _find_plans_with_linked_projects_toggle()
        _upgrade_plans(automatic_upgrades, dry_run=dry_run)
        logger.info('The following plans need to be manually audited to determine if they are eligible for ERM.')
        formatted_manual_info = "\n".join(manual_upgrades)
        logger.info(formatted_manual_info)


def _find_plans_with_linked_projects_toggle():
    manual_audits = []
    automated_upgrades = []
    for domain in toggles.LINKED_DOMAINS.get_enabled_domains():
        domain_obj = Domain.get_by_name(domain)
        if not domain_obj:
            continue
        if domain_obj.is_test == 'true':
            continue
        subscription = Subscription.get_active_subscription_by_domain(domain)
        plan_version = subscription.plan_version if subscription else \
            Subscription.get_subscribed_plan_by_domain(domain)
        if plan_version.role.slug not in ['enterprise_plan_v0', 'enterprise_plan_v1']:
            is_public = plan_version.plan.visibility == SoftwarePlanVisibility.PUBLIC
            is_community = plan_version.plan.edition == SoftwarePlanEdition.COMMUNITY
            entry = {
                'domain': domain,
                'plan': plan_version.plan.name,
                'role_slug': plan_version.role.slug,
                'role_name': plan_version.role.name,
                'edition': plan_version.plan.edition,
                'visibility': plan_version.plan.visibility,
                'active_subscription': subscription is not None,
                'created_by': domain_obj.creating_user,
            }
            if is_public or is_community:
                manual_audits.append(entry)
            else:
                automated_upgrades.append(entry)

    return automated_upgrades, manual_audits


def _upgrade_plans(automatic_upgrades, dry_run=False):
    slug_suffix = '_with_erm'
    name_suffix = '(With ERM)'
    for plan_info in automatic_upgrades:
        new_role = _get_or_create_role(plan_info['role_slug'], slug_suffix, name_suffix, dry_run=dry_run)
        change_role_for_software_plan_version(plan_info['role_slug'], new_role.slug, dry_run=dry_run)

{'fraction_non_alphanumeric': 0.0809138505473584, 'fraction_numerical': 0.0006346184356655561, 'mean_word_length': 3.2565833896016207, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3318864', 'n_tokens_mistral': 1886, 'n_tokens_neox': 1824, 'n_words': 371}