<commit_before># coding=utf-8
from collections import OrderedDict, namedtuple
import json
import logging
from lxml import etree

from django.template.loader import render_to_string
from django.utils.translation import ugettext as _, gettext_lazy
from django.http import HttpResponse, Http404, HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_GET
from django.contrib import messages
from corehq.apps.app_manager.views.media_utils import process_media_attribute, \
    handle_media_edits
from corehq.apps.case_search.models import case_search_enabled_for_domain
from corehq.apps.reports.daterange import get_simple_dateranges

from dimagi.utils.logging import notify_exception

from corehq.apps.app_manager.views.utils import back_to_main, bail, get_langs
from corehq import toggles, feature_previews
from corehq.apps.app_manager.templatetags.xforms_extras import trans
from corehq.apps.app_manager.const import (
    CAREPLAN_GOAL,
    CAREPLAN_TASK,
    USERCASE_TYPE,
    APP_V1,
    CLAIM_DEFAULT_RELEVANT_CONDITION,
)
from corehq.apps.app_manager.util import (
    is_valid_case_type,
    is_usercase_in_use,
    get_per_type_defaults,
    ParentCasePropertyBuilder,
    prefix_usercase_properties,
    commtrack_ledger_sections,
    module_offers_search,
    module_case_hierarchy_has_circular_reference, get_app_manager_template)
from corehq.apps.fixtures.models import FixtureDataType
from corehq.apps.userreports.models import ReportConfiguration, \
    StaticReportConfiguration
from dimagi.utils.web import json_response, json_request
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.models import (
    AdvancedModule,
    CareplanModule,
    CaseSearch,
    CaseSearchProperty,
    DeleteModuleRecord,
    DetailColumn,
    DetailTab,
    FormActionCondition,
    Module,
    ModuleNotFoundException,
    OpenCaseAction,
    ParentSelect,
    ReportModule,
    ShadowModule,
    SortElement,
    ReportAppConfig,
    UpdateCaseAction,
    FixtureSelect,
    DefaultCaseSearchProperty, get_all_mobile_filter_configs, get_auto_filter_configurations)
from corehq.apps.app_manager.decorators import no_conflict_require_POST, \
    require_can_edit_apps, require_deploy_apps

logger = logging.getLogger(__name__)


def get_module_template(domain, module):
    if isinstance(module, CareplanModule):
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view_careplan.html",
            "app_manager/v2/module_view_careplan.html",
        )
    elif isinstance(module, AdvancedModule):
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view_advanced.html",
            "app_manager/v2/module_view_advanced.html",
        )
    elif isinstance(module, ReportModule):
        return get_app_manager_template(
            domain,
            'app_manager/v1/module_view_report.html',
            'app_manager/v2/module_view_report.html',
        )
    else:
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view.html",
            "app_manager/v2/module_view.html",
        )


def get_module_view_context(app, module, lang=None):
    # shared context
    context = {
        'module_brief': {
            'id': module.id,
            'case_type': module.case_type,
            'lang': lang,
            'langs': app.langs,
            'module_type': module.module_type,
            'requires_case_details': bool(module.requires_case_details),
        },
        'edit_name_url': reverse(
            'edit_module_attr',
            args=[app.domain, app.id, module.id, 'name']
        )
    }
    case_property_builder = _setup_case_property_builder(app)
    if isinstance(module, CareplanModule):
        context.update(_get_careplan_module_view_context(app, module, case_property_builder))
    elif isinstance(module, AdvancedModule):
        context.update(_get_shared_module_view_context(app, module, case_property_builder, lang))
        context.update(_get_advanced_module_view_context(app, module))
    elif isinstance(module, ReportModule):
        context.update(_get_report_module_context(app, module))
    else:
        context.update(_get_shared_module_view_context(app, module, case_property_builder, lang))
        context.update(_get_basic_module_view_context(app, module, case_property_builder))
    if isinstance(module, ShadowModule):
        context.update(_get_shadow_module_view_context(app, module, lang))
    return context


def _get_shared_module_view_context(app, module, case_property_builder, lang=None):
    '''
    Get context items that are used by both basic and advanced modules.
    '''
    case_type = module.case_type
    return {
        'details': _get_module_details_context(app, module, case_property_builder, case_type),
        'js_options': {
            'fixture_columns_by_type': _get_fixture_columns_by_type(app.domain),
            'case_list_form_options': _case_list_form_options(app, module, case_type, lang),
            'valid_parent_modules': _get_valid_parent_modules(app, module),
            'is_search_enabled': case_search_enabled_for_domain(app.domain),
            'search_properties': module.search_config.properties if module_offers_search(module) else [],
            'include_closed': module.search_config.include_closed if module_offers_search(module) else False,
            'default_properties': module.search_config.default_properties if module_offers_search(module) else [],
            'search_button_display_condition':
                module.search_config.search_button_display_condition if module_offers_search(module) else "",
        }
    }


def _get_careplan_module_view_context(app, module, case_property_builder):
    subcase_types = list(app.get_subcase_types(module.case_type))
    return {
        'parent_modules': _get_parent_modules(app, module,
                                             case_property_builder,
                                             CAREPLAN_GOAL),
        'details': [
            {
                'label': gettext_lazy('Goal List'),
                'detail_label': gettext_lazy('Goal Detail'),
                'type': 'careplan_goal',
                'model': 'case',
                'properties': sorted(
                    case_property_builder.get_properties(CAREPLAN_GOAL)),
                'sort_elements': module.goal_details.short.sort_elements,
                'short': module.goal_details.short,
                'long': module.goal_details.long,
                'subcase_types': subcase_types,<commit_msg>case_list_form_options needed by both js and template<commit_after># coding=utf-8
from collections import OrderedDict, namedtuple
import json
import logging
from lxml import etree

from django.template.loader import render_to_string
from django.utils.translation import ugettext as _, gettext_lazy
from django.http import HttpResponse, Http404, HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_GET
from django.contrib import messages
from corehq.apps.app_manager.views.media_utils import process_media_attribute, \
    handle_media_edits
from corehq.apps.case_search.models import case_search_enabled_for_domain
from corehq.apps.reports.daterange import get_simple_dateranges

from dimagi.utils.logging import notify_exception

from corehq.apps.app_manager.views.utils import back_to_main, bail, get_langs
from corehq import toggles, feature_previews
from corehq.apps.app_manager.templatetags.xforms_extras import trans
from corehq.apps.app_manager.const import (
    CAREPLAN_GOAL,
    CAREPLAN_TASK,
    USERCASE_TYPE,
    APP_V1,
    CLAIM_DEFAULT_RELEVANT_CONDITION,
)
from corehq.apps.app_manager.util import (
    is_valid_case_type,
    is_usercase_in_use,
    get_per_type_defaults,
    ParentCasePropertyBuilder,
    prefix_usercase_properties,
    commtrack_ledger_sections,
    module_offers_search,
    module_case_hierarchy_has_circular_reference, get_app_manager_template)
from corehq.apps.fixtures.models import FixtureDataType
from corehq.apps.userreports.models import ReportConfiguration, \
    StaticReportConfiguration
from dimagi.utils.web import json_response, json_request
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.models import (
    AdvancedModule,
    CareplanModule,
    CaseSearch,
    CaseSearchProperty,
    DeleteModuleRecord,
    DetailColumn,
    DetailTab,
    FormActionCondition,
    Module,
    ModuleNotFoundException,
    OpenCaseAction,
    ParentSelect,
    ReportModule,
    ShadowModule,
    SortElement,
    ReportAppConfig,
    UpdateCaseAction,
    FixtureSelect,
    DefaultCaseSearchProperty, get_all_mobile_filter_configs, get_auto_filter_configurations)
from corehq.apps.app_manager.decorators import no_conflict_require_POST, \
    require_can_edit_apps, require_deploy_apps

logger = logging.getLogger(__name__)


def get_module_template(domain, module):
    if isinstance(module, CareplanModule):
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view_careplan.html",
            "app_manager/v2/module_view_careplan.html",
        )
    elif isinstance(module, AdvancedModule):
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view_advanced.html",
            "app_manager/v2/module_view_advanced.html",
        )
    elif isinstance(module, ReportModule):
        return get_app_manager_template(
            domain,
            'app_manager/v1/module_view_report.html',
            'app_manager/v2/module_view_report.html',
        )
    else:
        return get_app_manager_template(
            domain,
            "app_manager/v1/module_view.html",
            "app_manager/v2/module_view.html",
        )


def get_module_view_context(app, module, lang=None):
    # shared context
    context = {
        'module_brief': {
            'id': module.id,
            'case_type': module.case_type,
            'lang': lang,
            'langs': app.langs,
            'module_type': module.module_type,
            'requires_case_details': bool(module.requires_case_details),
        },
        'edit_name_url': reverse(
            'edit_module_attr',
            args=[app.domain, app.id, module.id, 'name']
        )
    }
    case_property_builder = _setup_case_property_builder(app)
    if isinstance(module, CareplanModule):
        context.update(_get_careplan_module_view_context(app, module, case_property_builder))
    elif isinstance(module, AdvancedModule):
        context.update(_get_shared_module_view_context(app, module, case_property_builder, lang))
        context.update(_get_advanced_module_view_context(app, module))
    elif isinstance(module, ReportModule):
        context.update(_get_report_module_context(app, module))
    else:
        context.update(_get_shared_module_view_context(app, module, case_property_builder, lang))
        context.update(_get_basic_module_view_context(app, module, case_property_builder))
    if isinstance(module, ShadowModule):
        context.update(_get_shadow_module_view_context(app, module, lang))
    return context


def _get_shared_module_view_context(app, module, case_property_builder, lang=None):
    '''
    Get context items that are used by both basic and advanced modules.
    '''
    case_type = module.case_type
    return {
        'details': _get_module_details_context(app, module, case_property_builder, case_type),
        'case_list_form_options': _case_list_form_options(app, module, case_type, lang),
        'js_options': {
            'fixture_columns_by_type': _get_fixture_columns_by_type(app.domain),
            'valid_parent_modules': _get_valid_parent_modules(app, module),
            'is_search_enabled': case_search_enabled_for_domain(app.domain),
            'search_properties': module.search_config.properties if module_offers_search(module) else [],
            'include_closed': module.search_config.include_closed if module_offers_search(module) else False,
            'default_properties': module.search_config.default_properties if module_offers_search(module) else [],
            'search_button_display_condition':
                module.search_config.search_button_display_condition if module_offers_search(module) else "",
        }
    }


def _get_careplan_module_view_context(app, module, case_property_builder):
    subcase_types = list(app.get_subcase_types(module.case_type))
    return {
        'parent_modules': _get_parent_modules(app, module,
                                             case_property_builder,
                                             CAREPLAN_GOAL),
        'details': [
            {
                'label': gettext_lazy('Goal List'),
                'detail_label': gettext_lazy('Goal Detail'),
                'type': 'careplan_goal',
                'model': 'case',
                'properties': sorted(
                    case_property_builder.get_properties(CAREPLAN_GOAL)),
                'sort_elements': module.goal_details.short.sort_elements,
                'short': module.goal_details.short,
                'long': module.goal_details.long,
                'subcase_types': subcase_types,
{'fraction_non_alphanumeric': 0.07727952167414051, 'fraction_numerical': 0.0019431988041853513, 'mean_word_length': 3.3402530003243593, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '398749', 'n_tokens_mistral': 3939, 'n_tokens_neox': 3886, 'n_words': 677}