<commit_before>from functools import partial
from django.utils.translation import ugettext as _
import uuid
from dateutil.parser import parser
import simplejson
from casexml.apps.case.models import CommCareCase
from corehq.apps.users.models import CommCareUser
from couchforms.models import XFormInstance
from dimagi.utils.decorators.memoized import memoized
from pact import enums

from couchdbkit.schema.properties import ALLOWED_PROPERTY_TYPES
from pact.enums import TIME_LABEL_LOOKUP, PACT_SCHEDULES_NAMESPACE, DOT_ART, DOT_NONART, PACT_REGIMEN_CHOICES_FLAT_DICT, REGIMEN_CHOICES, PACT_DOMAIN
from pact.regimen import regimen_string_from_doc

ALLOWED_PROPERTY_TYPES.add(partial)

def make_uuid():
    return uuid.uuid4().hex

from datetime import datetime, timedelta
from couchdbkit.ext.django.schema import StringProperty, DateTimeProperty, BooleanProperty, Document, DateProperty, SchemaListProperty, IntegerProperty

dp = parser()

class DOTSubmission(XFormInstance):
    @property
    def has_pillbox_check(self):
        pillbox_check_str = self.form['pillbox_check'].get('check', '')
        if len(pillbox_check_str) > 0:
            pillbox_check_data = simplejson.loads(pillbox_check_str)
            anchor_date = dp.parse(pillbox_check_data.get('anchor', '0000-01-01'))
        else:
            pillbox_check_str = {}
            anchor_date = datetime.min
        encounter_date = self.form['encounter_date']  # datetime already from couch
        return 'yes' if anchor_date.date() == encounter_date else 'no'

    @property
    def drilldown_url(self):
        from pact.reports.dot import PactDOTReport
        if self.form['case'].has_key('case_id'):
            case_id = self.form['case'].get('case_id', None)
        elif self.form['case'].has_key('@case_id'):
            case_id = self.form['case'].get('@case_id', None)
        else:
            case_id = None

        if case_id is not None:
            return PactDOTReport.get_url(*[PACT_DOMAIN]) + "?dot_patient=%s&submit_id=%s" % (case_id, self._id)
        else:
            return "#"
        pass
    class Meta:
        app_label='pact'


class PactPatientCase(CommCareCase):
    class Meta:
        app_label = 'pact'

    @memoized
    def get_user_map(self):
        domain_users = CommCareUser.by_domain(enums.PACT_DOMAIN)
        return dict((du.get_id, du.username_in_report) for du in domain_users)

    @property
    def gender_display(self):
        return self._get_display_string('gender', enums.GENDER_CHOICES_DICT)

    @property
    def race_display(self):
        return self._get_display_string('race', enums.PACT_RACE_CHOICES_DICT)

    @property
    def hp_status_display(self):
        return self._get_display_string(
            'hp_status', enums.PACT_HP_CHOICES_DICT)

    @property
    def dot_status_display(self):
        return self._get_display_string(
            'dot_status', enums.PACT_DOT_CHOICES_DICT)

    @property
    def hiv_care_clinic_display(self):
        return self._get_display_string(
            'hiv_care_clinic', enums.PACT_HIV_CLINIC_CHOICES_DICT
        )


    def update_providers(self, cc_user, provider_ids):
        from pact.api import submit_case_update_form
        update_dict = dict(('provider%d' % ix, provider_id) for (ix, provider_id) in enumerate(provider_ids, start=1))
        submit_case_update_form(self, update_dict, cc_user)


    def get_provider_ids(self):
        for x in range(1,10):
            providerx = getattr(self, 'provider%d' % x, None)
            if providerx is not None and providerx != "":
                yield providerx

    @property
    def get_providers(self):
        """
        return a list of all the providers for this patient
        """
        from pact.api import get_all_providers
        all_providers = get_all_providers()
        pt_providers = list(self.get_provider_ids())

        providers_dict = dict((x.fields['id'], x.fields) for x in all_providers)
        #filtered= filter(lambda x: x.fields['id'] in pt_providers, all_providers)
        #return [x.fields for x in filtered]

        return [providers_dict[x] for x in pt_providers if x in providers_dict]


    def _get_display_string(self, attr, display_dict):
        attr_val = getattr(self, attr, None)
        if attr_val is not None:
            return display_dict.get(attr_val, attr_val)
        else:
            return ""
    def is_dot(self):
        dot_status = getattr(self, 'dot_status', None)
        if dot_status is None:
            return False
        else:
            if dot_status.lower().startswith('dot'):
                return True
            else:
                return None

    def art_regimen_label_string(self):
        """
        representation of the labeled strings of the art regimen" morning,noon,evening
        """
        return regimen_string_from_doc(DOT_ART, self.to_json())

    def nonart_regimen_label_string(self):
        """
        representation of the labeled strings of the nonart regimen: morning,noon,evening, etc
        """
        return regimen_string_from_doc(DOT_NONART, self.to_json())

    def art_regimen_label_string_display(self):
        regimen_string = regimen_string_from_doc(DOT_ART, self.to_json())
        if regimen_string is None:
            return "No regimen"
        else:
            return "[%s] %s" % (REGIMEN_CHOICES[int(self.art_properties()[enums.CASE_ART_REGIMEN_PROP])], PACT_REGIMEN_CHOICES_FLAT_DICT[regimen_string])

    def nonart_regimen_label_string_display(self):
        regimen_string = regimen_string_from_doc(DOT_NONART, self.to_json())
        if regimen_string is None:
            return "No regimen"
        elif regimen_string.startswith('Error,'):
            return "[%s] %s" % (self.nonartregimen, regimen_string)
        else:
            return "[%s] %s" % (REGIMEN_CHOICES[int(self.nonart_properties()[enums.CASE_NONART_REGIMEN_PROP])], PACT_REGIMEN_CHOICES_FLAT_DICT[regimen_string])

    def art_properties(self):
        return {<commit_msg>handle error messages in pact patient reports<commit_after>from functools import partial
from django.utils.translation import ugettext as _
import uuid
from dateutil.parser import parser
import simplejson
from casexml.apps.case.models import CommCareCase
from corehq.apps.users.models import CommCareUser
from couchforms.models import XFormInstance
from dimagi.utils.decorators.memoized import memoized
from pact import enums

from couchdbkit.schema.properties import ALLOWED_PROPERTY_TYPES
from pact.enums import TIME_LABEL_LOOKUP, PACT_SCHEDULES_NAMESPACE, DOT_ART, DOT_NONART, PACT_REGIMEN_CHOICES_FLAT_DICT, REGIMEN_CHOICES, PACT_DOMAIN
from pact.regimen import regimen_string_from_doc

ALLOWED_PROPERTY_TYPES.add(partial)

def make_uuid():
    return uuid.uuid4().hex

from datetime import datetime, timedelta
from couchdbkit.ext.django.schema import StringProperty, DateTimeProperty, BooleanProperty, Document, DateProperty, SchemaListProperty, IntegerProperty

dp = parser()

class DOTSubmission(XFormInstance):
    @property
    def has_pillbox_check(self):
        pillbox_check_str = self.form['pillbox_check'].get('check', '')
        if len(pillbox_check_str) > 0:
            pillbox_check_data = simplejson.loads(pillbox_check_str)
            anchor_date = dp.parse(pillbox_check_data.get('anchor', '0000-01-01'))
        else:
            pillbox_check_str = {}
            anchor_date = datetime.min
        encounter_date = self.form['encounter_date']  # datetime already from couch
        return 'yes' if anchor_date.date() == encounter_date else 'no'

    @property
    def drilldown_url(self):
        from pact.reports.dot import PactDOTReport
        if self.form['case'].has_key('case_id'):
            case_id = self.form['case'].get('case_id', None)
        elif self.form['case'].has_key('@case_id'):
            case_id = self.form['case'].get('@case_id', None)
        else:
            case_id = None

        if case_id is not None:
            return PactDOTReport.get_url(*[PACT_DOMAIN]) + "?dot_patient=%s&submit_id=%s" % (case_id, self._id)
        else:
            return "#"
        pass
    class Meta:
        app_label='pact'


class PactPatientCase(CommCareCase):
    class Meta:
        app_label = 'pact'

    @memoized
    def get_user_map(self):
        domain_users = CommCareUser.by_domain(enums.PACT_DOMAIN)
        return dict((du.get_id, du.username_in_report) for du in domain_users)

    @property
    def gender_display(self):
        return self._get_display_string('gender', enums.GENDER_CHOICES_DICT)

    @property
    def race_display(self):
        return self._get_display_string('race', enums.PACT_RACE_CHOICES_DICT)

    @property
    def hp_status_display(self):
        return self._get_display_string(
            'hp_status', enums.PACT_HP_CHOICES_DICT)

    @property
    def dot_status_display(self):
        return self._get_display_string(
            'dot_status', enums.PACT_DOT_CHOICES_DICT)

    @property
    def hiv_care_clinic_display(self):
        return self._get_display_string(
            'hiv_care_clinic', enums.PACT_HIV_CLINIC_CHOICES_DICT
        )


    def update_providers(self, cc_user, provider_ids):
        from pact.api import submit_case_update_form
        update_dict = dict(('provider%d' % ix, provider_id) for (ix, provider_id) in enumerate(provider_ids, start=1))
        submit_case_update_form(self, update_dict, cc_user)


    def get_provider_ids(self):
        for x in range(1,10):
            providerx = getattr(self, 'provider%d' % x, None)
            if providerx is not None and providerx != "":
                yield providerx

    @property
    def get_providers(self):
        """
        return a list of all the providers for this patient
        """
        from pact.api import get_all_providers
        all_providers = get_all_providers()
        pt_providers = list(self.get_provider_ids())

        providers_dict = dict((x.fields['id'], x.fields) for x in all_providers)
        #filtered= filter(lambda x: x.fields['id'] in pt_providers, all_providers)
        #return [x.fields for x in filtered]

        return [providers_dict[x] for x in pt_providers if x in providers_dict]


    def _get_display_string(self, attr, display_dict):
        attr_val = getattr(self, attr, None)
        if attr_val is not None:
            return display_dict.get(attr_val, attr_val)
        else:
            return ""
    def is_dot(self):
        dot_status = getattr(self, 'dot_status', None)
        if dot_status is None:
            return False
        else:
            if dot_status.lower().startswith('dot'):
                return True
            else:
                return None

    def art_regimen_label_string(self):
        """
        representation of the labeled strings of the art regimen" morning,noon,evening
        """
        return regimen_string_from_doc(DOT_ART, self.to_json())

    def nonart_regimen_label_string(self):
        """
        representation of the labeled strings of the nonart regimen: morning,noon,evening, etc
        """
        return regimen_string_from_doc(DOT_NONART, self.to_json())

    def art_regimen_label_string_display(self):
        regimen_string = regimen_string_from_doc(DOT_ART, self.to_json())
        if regimen_string is None:
            return "No regimen"
        elif regimen_string.startswith('Error,'):
            return "[%s] %s" % (REGIMEN_CHOICES[int(self.art_properties()[enums.CASE_ART_REGIMEN_PROP])], regimen_string)
        else:
            return "[%s] %s" % (REGIMEN_CHOICES[int(self.art_properties()[enums.CASE_ART_REGIMEN_PROP])], PACT_REGIMEN_CHOICES_FLAT_DICT[regimen_string])

    def nonart_regimen_label_string_display(self):
        regimen_string = regimen_string_from_doc(DOT_NONART, self.to_json())
        if regimen_string is None:
            return "No regimen"
        elif regimen_string.startswith('Error,'):
            return "[%s] %s" % (self.nonartregimen, regimen_string)
        else:
            return "[%s] %s" % (REGIMEN_CHOICES[int(self.nonart_properties()[enums.CASE_NONART_REGIMEN_PROP])], PACT_REGIMEN_CHOICES_FLAT_DICT[regimen_string])

    def art_properties(self):
        return {
{'fraction_non_alphanumeric': 0.09164486592544147, 'fraction_numerical': 0.002289077828646174, 'mean_word_length': 3.0858383433533736, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 5, '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': '4413725', 'n_tokens_mistral': 3964, 'n_tokens_neox': 3841, 'n_words': 819}