<commit_before>import json
from collections import Counter

from django.db.models import Q
from django.http import Http404, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST

from corehq.apps.domain.decorators import login_and_domain_required, domain_admin_required
from corehq.apps.domain.models import Domain
from corehq.apps.enterprise.decorators import require_enterprise_admin
from corehq.apps.registry.models import DataRegistry, RegistryInvitation, RegistryGrant


@require_enterprise_admin
@login_and_domain_required
def data_registries(request, domain):
    owned, invited = [], []
    for registry in DataRegistry.objects.visible_to_domain(domain):
        if registry.domain == domain:
            owned.append(_registry_list_context(domain, registry))
        else:
            invited.append(_registry_list_context(domain, registry))

    context = {
        'domain': domain,
        'owned_registries': owned,
        'invited_registries': invited,
        'current_page': {
            'title': _('Data Registries'),
            'page_name': _('Data Registries'),
        },
    }
    return render(request, "registry/registry_list.html", context)


def _registry_list_context(domain, registry):
    invitations = registry.invitations.all()
    domain_obj = Domain.get_by_name(registry.domain)
    other_domain_invitations = [
        invitation for invitation in invitations
        if not invitation.domain == domain
    ]
    context = {
        "domain_name": domain_obj.display_name() if domain_obj else registry.domain,
        "name": registry.name,
        "description": registry.description or '',
        "slug": registry.slug,
        "is_active": registry.is_active,
        "participator_count": len([
            invitation for invitation in other_domain_invitations
            if invitation.status == RegistryInvitation.STATUS_ACCEPTED
        ])
    }
    if domain == registry.domain:  # domain is owner
        status_counter = Counter([invitation.status for invitation in other_domain_invitations])
        context.update({
            "invitation_count": len(invitations),
            "accepted_invitation_count": status_counter[RegistryInvitation.STATUS_ACCEPTED],
            "pending_invitation_count": status_counter[RegistryInvitation.STATUS_PENDING],
            "rejected_invitation_count": status_counter[RegistryInvitation.STATUS_REJECTED]
        })
    else:
        for_this_domain = [invitation for invitation in invitations if invitation.domain == domain]
        context.update({
            "invitation": for_this_domain[0].to_json()
        })
    return context


@domain_admin_required
@require_POST
def accept_registry_invitation(request, domain):
    registry_slug = request.POST.get('registry_slug')
    invitation = _get_invitation_or_404(domain, registry_slug)

    if not invitation.is_accepted:
        invitation.accept(request.user)

    return JsonResponse({"invitation": invitation.to_json()})


@domain_admin_required
@require_POST
def reject_registry_invitation(request, domain):
    registry_slug = request.POST.get('registry_slug')
    invitation = _get_invitation_or_404(domain, registry_slug)

    if not invitation.is_rejected:
        invitation.reject(request.user)

    return JsonResponse({"invitation": invitation.to_json()})


def _get_invitation_or_404(domain, registry_slug):
    try:
        return RegistryInvitation.objects.get(
            registry__slug=registry_slug,
            domain=domain
        )
    except RegistryInvitation.DoesNotExist:
        raise Http404


@domain_admin_required
def manage_registry(request, domain, registry_slug):
    registry = _get_registry_or_404(domain, registry_slug)

    is_owner = registry.domain == domain
    all_invitations = list(registry.invitations.all())
    domain_invitation = [invitation for invitation in all_invitations if invitation.domain == domain][0]
    if is_owner:
        invitations = all_invitations
        grants = registry.grants.all()
    else:
        invitations = []
        grants = registry.grants.filter(Q(from_domain=domain) | Q(to_domains__contains=[domain]))
    context = {
        "domain": domain,
        "is_owner": is_owner,
        "registry": {
            "domain": registry.domain,
            "current_domain": domain,
            "is_owner": is_owner,
            "name": registry.name,
            "description": registry.description or '',
            "slug": registry.slug,
            "is_active": registry.is_active,
            "schema": registry.case_types,
            "invitations": [invitation.to_json() for invitation in invitations if invitation.domain != domain],
            "domain_invitation": domain_invitation,
            "grants": [grant.to_json() for grant in grants]
        },
        "available_case_types": ["patient", "household"],  # TODO
        "available_domains": ["skelly", "d1"],  # TODO,
        "invited_domains": [invitation.domain for invitation in all_invitations],
        "current_page": {
            "title": "Manage Registry",
            "page_name": "Manage Registry",
            "parents": [
                {
                    "title": "Data Registries",
                    "page_name": "Data Registries",
                    "url": reverse("data_registries", args=[domain]),
                },
            ],
        },
    }
    return render(request, "registry/registry_edit.html", context)


@require_enterprise_admin
@require_POST
def edit_registry_attr(request, domain, registry_slug, attr):
    registry = _get_registry_or_404(domain, registry_slug)
    if registry.domain != domain:
        return JsonResponse({"error": _("Action not permitted")}, status=403)

    if attr not in ["name", "description", "schema", "is_active"]:<commit_msg>get case types from DD<commit_after>import json
from collections import Counter

from django.db.models import Q
from django.http import Http404, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST

from corehq.apps.data_dictionary.util import get_data_dict_case_types
from corehq.apps.domain.decorators import login_and_domain_required, domain_admin_required
from corehq.apps.domain.models import Domain
from corehq.apps.enterprise.decorators import require_enterprise_admin
from corehq.apps.registry.models import DataRegistry, RegistryInvitation, RegistryGrant


@require_enterprise_admin
@login_and_domain_required
def data_registries(request, domain):
    owned, invited = [], []
    for registry in DataRegistry.objects.visible_to_domain(domain):
        if registry.domain == domain:
            owned.append(_registry_list_context(domain, registry))
        else:
            invited.append(_registry_list_context(domain, registry))

    context = {
        'domain': domain,
        'owned_registries': owned,
        'invited_registries': invited,
        'current_page': {
            'title': _('Data Registries'),
            'page_name': _('Data Registries'),
        },
    }
    return render(request, "registry/registry_list.html", context)


def _registry_list_context(domain, registry):
    invitations = registry.invitations.all()
    domain_obj = Domain.get_by_name(registry.domain)
    other_domain_invitations = [
        invitation for invitation in invitations
        if not invitation.domain == domain
    ]
    context = {
        "domain_name": domain_obj.display_name() if domain_obj else registry.domain,
        "name": registry.name,
        "description": registry.description or '',
        "slug": registry.slug,
        "is_active": registry.is_active,
        "participator_count": len([
            invitation for invitation in other_domain_invitations
            if invitation.status == RegistryInvitation.STATUS_ACCEPTED
        ])
    }
    if domain == registry.domain:  # domain is owner
        status_counter = Counter([invitation.status for invitation in other_domain_invitations])
        context.update({
            "invitation_count": len(invitations),
            "accepted_invitation_count": status_counter[RegistryInvitation.STATUS_ACCEPTED],
            "pending_invitation_count": status_counter[RegistryInvitation.STATUS_PENDING],
            "rejected_invitation_count": status_counter[RegistryInvitation.STATUS_REJECTED]
        })
    else:
        for_this_domain = [invitation for invitation in invitations if invitation.domain == domain]
        context.update({
            "invitation": for_this_domain[0].to_json()
        })
    return context


@domain_admin_required
@require_POST
def accept_registry_invitation(request, domain):
    registry_slug = request.POST.get('registry_slug')
    invitation = _get_invitation_or_404(domain, registry_slug)

    if not invitation.is_accepted:
        invitation.accept(request.user)

    return JsonResponse({"invitation": invitation.to_json()})


@domain_admin_required
@require_POST
def reject_registry_invitation(request, domain):
    registry_slug = request.POST.get('registry_slug')
    invitation = _get_invitation_or_404(domain, registry_slug)

    if not invitation.is_rejected:
        invitation.reject(request.user)

    return JsonResponse({"invitation": invitation.to_json()})


def _get_invitation_or_404(domain, registry_slug):
    try:
        return RegistryInvitation.objects.get(
            registry__slug=registry_slug,
            domain=domain
        )
    except RegistryInvitation.DoesNotExist:
        raise Http404


@domain_admin_required
def manage_registry(request, domain, registry_slug):
    registry = _get_registry_or_404(domain, registry_slug)

    is_owner = registry.domain == domain
    all_invitations = list(registry.invitations.all())
    domain_invitation = [invitation for invitation in all_invitations if invitation.domain == domain][0]
    if is_owner:
        invitations = all_invitations
        grants = registry.grants.all()
    else:
        invitations = []
        grants = registry.grants.filter(Q(from_domain=domain) | Q(to_domains__contains=[domain]))
    context = {
        "domain": domain,
        "is_owner": is_owner,
        "registry": {
            "domain": registry.domain,
            "current_domain": domain,
            "is_owner": is_owner,
            "name": registry.name,
            "description": registry.description or '',
            "slug": registry.slug,
            "is_active": registry.is_active,
            "schema": registry.case_types,
            "invitations": [invitation.to_json() for invitation in invitations if invitation.domain != domain],
            "domain_invitation": domain_invitation,
            "grants": [grant.to_json() for grant in grants]
        },
        "available_case_types": list(get_data_dict_case_types(registry.domain)),
        "available_domains": ["skelly", "d1"],  # TODO,
        "invited_domains": [invitation.domain for invitation in all_invitations],
        "current_page": {
            "title": "Manage Registry",
            "page_name": "Manage Registry",
            "parents": [
                {
                    "title": "Data Registries",
                    "page_name": "Data Registries",
                    "url": reverse("data_registries", args=[domain]),
                },
            ],
        },
    }
    return render(request, "registry/registry_edit.html", context)


@require_enterprise_admin
@require_POST
def edit_registry_attr(request, domain, registry_slug, attr):
    registry = _get_registry_or_404(domain, registry_slug)
    if registry.domain != domain:
        return JsonResponse({"error": _("Action not permitted")}, status=403)

    if attr not in ["name", "description", "schema", "is_active"]:
{'fraction_non_alphanumeric': 0.09798994974874371, 'fraction_numerical': 0.004522613065326633, 'mean_word_length': 3.1795589779488975, 'pattern_counts': {'":': 76, '<': 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': '4527329', 'n_tokens_mistral': 3346, 'n_tokens_neox': 3295, 'n_words': 703}