<commit_before>import warnings
from functools import partial

from bulk_update.helper import bulk_update as bulk_update_helper

from couchdbkit import ResourceNotFound
from dimagi.ext.couchdbkit import *
import itertools
from corehq.apps.cachehq.mixins import CachedCouchDocumentMixin
from dimagi.utils.couch.database import iter_docs
from dimagi.utils.couch.migration import SyncSQLToCouchMixin, SyncCouchToSQLMixin
from dimagi.utils.decorators.memoized import memoized
from datetime import datetime
from django.db import models, transaction
import jsonfield
from casexml.apps.case.cleanup import close_case
from corehq.form_processor.interfaces.supply import SupplyInterface
from corehq.form_processor.exceptions import CaseNotFound
from corehq.apps.commtrack.const import COMMTRACK_USERNAME
from corehq.apps.domain.models import Domain
from corehq.apps.products.models import SQLProduct
from corehq.toggles import LOCATION_TYPE_STOCK_RATES
from corehq.util.soft_assert import soft_assert
from mptt.models import MPTTModel, TreeForeignKey, TreeManager


LOCATION_REPORTING_PREFIX = 'locationreportinggroup-'


def notify_of_deprecation(msg):
    _assert = soft_assert(notify_admins=True, fail_if_debug=True)
    message = "Deprecated Locations feature used: {}".format(msg)
    _assert(False, message)


class LocationTypeManager(models.Manager):

    def full_hierarchy(self, domain):
        """
        Returns a graph of the form
        {
           '<loc_type_id>: (
               loc_type,
               {'<child_loc_type_id>': (child_loc_type, [...])}
           )
        }
        """
        hierarchy = {}

        def insert_loc_type(loc_type):
            """
            Get parent location's hierarchy, insert loc_type into it, and return
            hierarchy below loc_type
            """
            if not loc_type.parent_type:
                lt_hierarchy = hierarchy
            else:
                lt_hierarchy = insert_loc_type(loc_type.parent_type)
            if loc_type.id not in lt_hierarchy:
                lt_hierarchy[loc_type.id] = (loc_type, {})
            return lt_hierarchy[loc_type.id][1]

        for loc_type in self.filter(domain=domain).all():
            insert_loc_type(loc_type)

        return hierarchy

    def by_domain(self, domain):
        """
        Sorts location types by hierarchy
        """
        ordered_loc_types = []

        def step_through_graph(hierarchy):
            for _, (loc_type, children) in hierarchy.items():
                ordered_loc_types.append(loc_type)
                step_through_graph(children)

        step_through_graph(self.full_hierarchy(domain))
        return ordered_loc_types


StockLevelField = partial(models.DecimalField, max_digits=10, decimal_places=1)


@memoized
def stock_level_config_for_domain(domain, commtrack_enabled):
    from corehq.apps.commtrack.models import CommtrackConfig
    ct_config = CommtrackConfig.for_domain(domain)
    if (
        (ct_config is None) or
        (not commtrack_enabled) or
        LOCATION_TYPE_STOCK_RATES.enabled(domain)
    ):
        return None
    else:
        return ct_config.stock_levels_config


class LocationType(models.Model):
    domain = models.CharField(max_length=255, db_index=True)
    name = models.CharField(max_length=255)
    code = models.SlugField(db_index=False, null=True)
    parent_type = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
    administrative = models.BooleanField(default=False)
    shares_cases = models.BooleanField(default=False)
    view_descendants = models.BooleanField(default=False)
    _expand_from = models.ForeignKey(
        'self',
        null=True,
        related_name='+',
        db_column='expand_from',
        on_delete=models.CASCADE,
    )  # levels below this location type that we start expanding from
    _expand_from_root = models.BooleanField(default=False, db_column='expand_from_root')
    expand_to = models.ForeignKey('self', null=True, related_name='+')  # levels above this type that are synced
    last_modified = models.DateTimeField(auto_now=True)

    emergency_level = StockLevelField(default=0.5)
    understock_threshold = StockLevelField(default=1.5)
    overstock_threshold = StockLevelField(default=3.0)

    objects = LocationTypeManager()
<commit_msg>add default on_delete<commit_after>import warnings
from functools import partial

from bulk_update.helper import bulk_update as bulk_update_helper

from couchdbkit import ResourceNotFound
from dimagi.ext.couchdbkit import *
import itertools
from corehq.apps.cachehq.mixins import CachedCouchDocumentMixin
from dimagi.utils.couch.database import iter_docs
from dimagi.utils.couch.migration import SyncSQLToCouchMixin, SyncCouchToSQLMixin
from dimagi.utils.decorators.memoized import memoized
from datetime import datetime
from django.db import models, transaction
import jsonfield
from casexml.apps.case.cleanup import close_case
from corehq.form_processor.interfaces.supply import SupplyInterface
from corehq.form_processor.exceptions import CaseNotFound
from corehq.apps.commtrack.const import COMMTRACK_USERNAME
from corehq.apps.domain.models import Domain
from corehq.apps.products.models import SQLProduct
from corehq.toggles import LOCATION_TYPE_STOCK_RATES
from corehq.util.soft_assert import soft_assert
from mptt.models import MPTTModel, TreeForeignKey, TreeManager


LOCATION_REPORTING_PREFIX = 'locationreportinggroup-'


def notify_of_deprecation(msg):
    _assert = soft_assert(notify_admins=True, fail_if_debug=True)
    message = "Deprecated Locations feature used: {}".format(msg)
    _assert(False, message)


class LocationTypeManager(models.Manager):

    def full_hierarchy(self, domain):
        """
        Returns a graph of the form
        {
           '<loc_type_id>: (
               loc_type,
               {'<child_loc_type_id>': (child_loc_type, [...])}
           )
        }
        """
        hierarchy = {}

        def insert_loc_type(loc_type):
            """
            Get parent location's hierarchy, insert loc_type into it, and return
            hierarchy below loc_type
            """
            if not loc_type.parent_type:
                lt_hierarchy = hierarchy
            else:
                lt_hierarchy = insert_loc_type(loc_type.parent_type)
            if loc_type.id not in lt_hierarchy:
                lt_hierarchy[loc_type.id] = (loc_type, {})
            return lt_hierarchy[loc_type.id][1]

        for loc_type in self.filter(domain=domain).all():
            insert_loc_type(loc_type)

        return hierarchy

    def by_domain(self, domain):
        """
        Sorts location types by hierarchy
        """
        ordered_loc_types = []

        def step_through_graph(hierarchy):
            for _, (loc_type, children) in hierarchy.items():
                ordered_loc_types.append(loc_type)
                step_through_graph(children)

        step_through_graph(self.full_hierarchy(domain))
        return ordered_loc_types


StockLevelField = partial(models.DecimalField, max_digits=10, decimal_places=1)


@memoized
def stock_level_config_for_domain(domain, commtrack_enabled):
    from corehq.apps.commtrack.models import CommtrackConfig
    ct_config = CommtrackConfig.for_domain(domain)
    if (
        (ct_config is None) or
        (not commtrack_enabled) or
        LOCATION_TYPE_STOCK_RATES.enabled(domain)
    ):
        return None
    else:
        return ct_config.stock_levels_config


class LocationType(models.Model):
    domain = models.CharField(max_length=255, db_index=True)
    name = models.CharField(max_length=255)
    code = models.SlugField(db_index=False, null=True)
    parent_type = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
    administrative = models.BooleanField(default=False)
    shares_cases = models.BooleanField(default=False)
    view_descendants = models.BooleanField(default=False)
    _expand_from = models.ForeignKey(
        'self',
        null=True,
        related_name='+',
        db_column='expand_from',
        on_delete=models.CASCADE,
    )  # levels below this location type that we start expanding from
    _expand_from_root = models.BooleanField(default=False, db_column='expand_from_root')
    expand_to = models.ForeignKey('self', null=True, related_name='+', on_delete=models.CASCADE)  # levels above this type that are synced
    last_modified = models.DateTimeField(auto_now=True)

    emergency_level = StockLevelField(default=0.5)
    understock_threshold = StockLevelField(default=1.5)
    overstock_threshold = StockLevelField(default=3.0)

    objects = LocationTypeManager()

{'fraction_non_alphanumeric': 0.07895953757225434, 'fraction_numerical': 0.003699421965317919, 'mean_word_length': 3.4070300560366786, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '7225161', 'n_tokens_mistral': 2634, 'n_tokens_neox': 2548, 'n_words': 537}