<commit_before>from __future__ import absolute_import
from __future__ import unicode_literals
from decimal import Decimal
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from corehq.apps.commtrack.models import CommtrackConfig
from corehq.apps.domain.models import Domain
from corehq.apps.commtrack import const
from corehq.apps.sms.api import send_sms_to_verified_number, MessageMetadata
from corehq import toggles
from lxml import etree
import logging

from corehq.form_processor.interfaces.supply import SupplyInterface
from corehq.util.soft_assert import soft_assert
from dimagi.utils.couch.loosechange import map_reduce
from dimagi.utils.parsing import json_format_datetime
from datetime import datetime
from corehq.apps.commtrack.util import get_supply_point_and_location
from corehq.apps.commtrack.xmlutil import XML
from corehq.apps.products.models import Product
from corehq.apps.users.models import CouchUser
from corehq.apps.receiverwrapper.util import submit_form_locally
from corehq.apps.commtrack.exceptions import (
    NoDefaultLocationException,
    NotAUserClassError,
    RequisitionsHaveBeenRemoved,
)
import re
from corehq.form_processor.parsers.ledgers.helpers import StockTransactionHelper
import six

logger = logging.getLogger('commtrack.sms')


class SMSError(RuntimeError):
    pass


def handle(verified_contact, text, msg):
    """top-level handler for incoming stock report messages"""
    domain = Domain.get_by_name(verified_contact.domain)
    if not domain.commtrack_enabled:
        return False

    try:
        if toggles.STOCK_AND_RECEIPT_SMS_HANDLER.enabled(domain.name):
            # handle special stock parser for custom domain logic
            data = StockAndReceiptParser(domain, verified_contact).parse(text.lower())
        else:
            # default report parser
            data = StockReportParser(domain, verified_contact).parse(text.lower())
        if not data:
            return False
    except NotAUserClassError:
        return False
    except Exception as e:
        if settings.UNIT_TESTING or settings.DEBUG:
            raise
        send_sms_to_verified_number(verified_contact, 'problem with stock report: %s' % six.text_type(e))
        return True

    process(domain.name, data)
    send_confirmation(verified_contact, data)
    return True


def process(domain, data):
    import pprint
    logger.debug(pprint.pformat(data))

    xml = to_instance(data)

    logger.debug(xml)

    submit_form_locally(
        instance=xml,
        domain=domain,
    )


class StockReportParser(object):
    """a helper object for parsing raw stock report texts"""

    def __init__(self, domain, verified_contact, location=None):
        self.domain = domain
        self.verified_contact = verified_contact

        self.location = location
        self.case = None
        u = verified_contact.owner

        if domain.commtrack_enabled:
            # if user is not actually a user, we let someone else process
            if not isinstance(u, CouchUser):
                raise NotAUserClassError

            if not self.location:
                self.location = u.location

            if self.location:
                self.case = SupplyInterface(domain.name).get_by_location(self.location)

        self.commtrack_settings = domain.commtrack_settings

    def parse(self, text):
        """take in a text and return the parsed stock transactions"""
        _assert = soft_assert('@'.join(['droberts', 'dimagi.com']))

        args = text.split()
<commit_msg>remove unused soft assert<commit_after>from __future__ import absolute_import
from __future__ import unicode_literals
from decimal import Decimal
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from corehq.apps.commtrack.models import CommtrackConfig
from corehq.apps.domain.models import Domain
from corehq.apps.commtrack import const
from corehq.apps.sms.api import send_sms_to_verified_number, MessageMetadata
from corehq import toggles
from lxml import etree
import logging

from corehq.form_processor.interfaces.supply import SupplyInterface
from dimagi.utils.couch.loosechange import map_reduce
from dimagi.utils.parsing import json_format_datetime
from datetime import datetime
from corehq.apps.commtrack.util import get_supply_point_and_location
from corehq.apps.commtrack.xmlutil import XML
from corehq.apps.products.models import Product
from corehq.apps.users.models import CouchUser
from corehq.apps.receiverwrapper.util import submit_form_locally
from corehq.apps.commtrack.exceptions import (
    NoDefaultLocationException,
    NotAUserClassError,
    RequisitionsHaveBeenRemoved,
)
import re
from corehq.form_processor.parsers.ledgers.helpers import StockTransactionHelper
import six

logger = logging.getLogger('commtrack.sms')


class SMSError(RuntimeError):
    pass


def handle(verified_contact, text, msg):
    """top-level handler for incoming stock report messages"""
    domain = Domain.get_by_name(verified_contact.domain)
    if not domain.commtrack_enabled:
        return False

    try:
        if toggles.STOCK_AND_RECEIPT_SMS_HANDLER.enabled(domain.name):
            # handle special stock parser for custom domain logic
            data = StockAndReceiptParser(domain, verified_contact).parse(text.lower())
        else:
            # default report parser
            data = StockReportParser(domain, verified_contact).parse(text.lower())
        if not data:
            return False
    except NotAUserClassError:
        return False
    except Exception as e:
        if settings.UNIT_TESTING or settings.DEBUG:
            raise
        send_sms_to_verified_number(verified_contact, 'problem with stock report: %s' % six.text_type(e))
        return True

    process(domain.name, data)
    send_confirmation(verified_contact, data)
    return True


def process(domain, data):
    import pprint
    logger.debug(pprint.pformat(data))

    xml = to_instance(data)

    logger.debug(xml)

    submit_form_locally(
        instance=xml,
        domain=domain,
    )


class StockReportParser(object):
    """a helper object for parsing raw stock report texts"""

    def __init__(self, domain, verified_contact, location=None):
        self.domain = domain
        self.verified_contact = verified_contact

        self.location = location
        self.case = None
        u = verified_contact.owner

        if domain.commtrack_enabled:
            # if user is not actually a user, we let someone else process
            if not isinstance(u, CouchUser):
                raise NotAUserClassError

            if not self.location:
                self.location = u.location

            if self.location:
                self.case = SupplyInterface(domain.name).get_by_location(self.location)

        self.commtrack_settings = domain.commtrack_settings

    def parse(self, text):
        """take in a text and return the parsed stock transactions"""
        args = text.split()

{'fraction_non_alphanumeric': 0.06674256439447844, 'fraction_numerical': 0.0, 'mean_word_length': 3.367930391547545, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, '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': '214823', 'n_tokens_mistral': 1991, 'n_tokens_neox': 1937, 'n_words': 528}