def testSubmissionError(self):
        evil_laugh = "mwa ha ha!"

        def fail(sender, xform, **kwargs):
            raise Exception(evil_laugh)

        successful_form_received.connect(fail)

        try:
            file = os.path.join(os.path.dirname(__file__), "data",
                                "simple_form.xml")
            with open(file) as f:
                res = self.client.post(self.url, {"xml_submission_file": f})
                self.assertEqual(201, res.status_code)
                self.assertIn(evil_laugh, res.content)

            # make sure we logged it
            log = SubmissionErrorLog.view(
                "couchforms/all_submissions_by_domain",
                reduce=False,
                include_docs=True,
                startkey=[self.domain.name, "by_type", "XFormError"],
                endkey=[self.domain.name, "by_type", "XFormError", {}],
            ).one()

            self.assertTrue(log is not None)
            self.assertIn(evil_laugh, log.problem)
            with open(file) as f:
                self.assertEqual(f.read(), log.get_xml())

        finally:
            successful_form_received.disconnect(fail)
Exemplo n.º 2
0
    def testSubmissionError(self):
        evil_laugh = "mwa ha ha!"

        def fail(sender, xform, **kwargs):
            raise Exception(evil_laugh)

        successful_form_received.connect(fail)

        try:
            file = os.path.join(os.path.dirname(__file__), "data",
                                "simple_form.xml")
            with open(file) as f:
                res = self.client.post(self.url, {
                    "xml_submission_file": f
                })
                self.assertEqual(201, res.status_code)
                self.assertIn(evil_laugh, res.content)

            # make sure we logged it
            log = SubmissionErrorLog.view(
                "couchforms/all_submissions_by_domain",
                reduce=False,
                include_docs=True,
                startkey=[self.domain.name, "by_type", "XFormError"],
                endkey=[self.domain.name, "by_type", "XFormError", {}],
            ).one()

            self.assertIsNotNone(log)
            self.assertIn(evil_laugh, log.problem)
            with open(file) as f:
                self.assertEqual(f.read(), log.get_xml())
        
        finally:
            successful_form_received.disconnect(fail)
Exemplo n.º 3
0
    def testSubmissionError(self):
        evil_laugh = "mwa ha ha!"

        def fail(sender, xform, **kwargs):
            raise Exception(evil_laugh)

        successful_form_received.connect(fail)

        try:
            file = os.path.join(os.path.dirname(__file__), "data",
                                "simple_form.xml")
            with open(file) as f:
                res = self.client.post(self.url, {
                    "xml_submission_file": f
                })
                self.assertEqual(201, res.status_code)
                self.assertIn(evil_laugh, res.content)

            # make sure we logged it
            [log] = get_forms_by_type(self.domain.name, 'XFormError', limit=1)

            self.assertIsNotNone(log)
            self.assertIn(evil_laugh, log.problem)
            with open(file) as f:
                self.assertEqual(f.read(), log.get_xml())
        
        finally:
            successful_form_received.disconnect(fail)
Exemplo n.º 4
0
def failing_signal_handler(error_message):
    def fail(sender, xform, **kwargs):
        raise Exception(error_message)

    successful_form_received.connect(fail)

    try:
        yield
    finally:
        successful_form_received.disconnect(fail)
Exemplo n.º 5
0
def failing_signal_handler(error_message):
    def fail(sender, xform, **kwargs):
        raise Exception(error_message)

    successful_form_received.connect(fail)

    try:
        yield
    finally:
        successful_form_received.disconnect(fail)
Exemplo n.º 6
0
    def testSubmissionError(self):
        evil_laugh = "mwa ha ha!"

        def fail(sender, xform, **kwargs):
            raise Exception(evil_laugh)

        successful_form_received.connect(fail)

        try:
            file, res = self._submit("simple_form.xml")
            self.assertEqual(201, res.status_code)
            self.assertIn(evil_laugh, res.content)

            # make sure we logged it
            [log] = FormAccessors(self.domain.name).get_forms_by_type('XFormError', limit=1)

            self.assertIsNotNone(log)
            self.assertIn(evil_laugh, log.problem)
            with open(file) as f:
                self.assertEqual(f.read(), log.get_xml())
        
        finally:
            successful_form_received.disconnect(fail)
Exemplo n.º 7
0
    def testSubmissionError(self):
        evil_laugh = "mwa ha ha!"

        def fail(sender, xform, **kwargs):
            raise Exception(evil_laugh)

        successful_form_received.connect(fail)

        try:
            file, res = self._submit("simple_form.xml")
            self.assertEqual(201, res.status_code)
            self.assertIn(evil_laugh, res.content)

            # make sure we logged it
            [log] = FormAccessors(self.domain.name).get_forms_by_type(
                'XFormError', limit=1)

            self.assertIsNotNone(log)
            self.assertIn(evil_laugh, log.problem)
            with open(file) as f:
                self.assertEqual(f.read(), log.get_xml())

        finally:
            successful_form_received.disconnect(fail)
Exemplo n.º 8
0
    def send_request(self, repeat_record, payload):
        value_sources = chain(
            six.itervalues(self.openmrs_config.case_config.patient_identifiers),
            six.itervalues(self.openmrs_config.case_config.person_properties),
            six.itervalues(self.openmrs_config.case_config.person_preferred_name),
            six.itervalues(self.openmrs_config.case_config.person_preferred_address),
            six.itervalues(self.openmrs_config.case_config.person_attributes),
        )
        case_trigger_infos = get_relevant_case_updates_from_form_json(
            self.domain, payload, case_types=self.white_listed_case_types,
            extra_fields=[vs.case_property for vs in value_sources if hasattr(vs, 'case_property')]
        )
        form_question_values = get_form_question_values(payload)

        return send_openmrs_data(
            self.requests,
            self.domain,
            payload,
            self.openmrs_config,
            case_trigger_infos,
            form_question_values
        )


def create_openmrs_repeat_records(sender, xform, **kwargs):
    create_repeat_records(OpenmrsRepeater, xform)


successful_form_received.connect(create_openmrs_repeat_records)
Exemplo n.º 9
0
            CreateVisitsEncountersObsTask(requests, domain, info, form_json,
                                          openmrs_config,
                                          patient['person']['uuid']), )

        errors.extend(execute_workflow(workflow))

    if errors:
        requests.notify_error(
            f'Errors encountered sending OpenMRS data: {errors}')
        # If the form included multiple patients, some workflows may
        # have succeeded, but don't say everything was OK if any
        # workflows failed. (Of course most forms will only involve one
        # case, so one workflow.)
        return OpenmrsResponse(
            400, 'Bad Request',
            "Errors: " + pformat_json([str(e) for e in errors]))

    if warnings:
        return OpenmrsResponse(
            201, "Accepted",
            "Warnings: " + pformat_json([str(e) for e in warnings]))

    return OpenmrsResponse(200, "OK")


def create_openmrs_repeat_records(sender, xform, **kwargs):
    create_repeat_records(OpenmrsRepeater, xform)


successful_form_received.connect(create_openmrs_repeat_records)
Exemplo n.º 10
0
Question: is it possible to receive registration data from the phone after Case 3?
If so, we need to check for a user created via Case 3 and link them to this account
automatically
"""

def create_user_from_commcare_registration(sender, xform, **kwargs):
    """
    # this comes in as xml that looks like:
    # <n0:registration xmlns:n0="openrosa.org/user-registration">
    # <username>user</username>
    # <password>pw</password>
    # <uuid>MTBZJTDO3SCT2ONXAQ88WM0CH</uuid>
    # <date>2008-01-07</date>
    # <registering_phone_id>NRPHIOUSVEA215AJL8FFKGTVR</registering_phone_id>
    # <user_data> ... some custom stuff </user_data>
    """
    if xform.xmlns not in VALID_USER_REGISTRATION_XMLNSES:
        return False
    
    try:
        couch_user, created = CommCareUser.create_or_update_from_xform(xform)
    except Exception, e:
        #import traceback, sys
        #exc_type, exc_value, exc_traceback = sys.exc_info()
        #traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
        logging.exception(e)
        raise
    return ReceiverResult(xml.get_response(couch_user, created), Certainty.CERTAIN)

successful_form_received.connect(create_user_from_commcare_registration)
Exemplo n.º 11
0
        raise Dhis2Exception(f"Unable to parse DHIS2 version {dhis2_version}.")
    return api_version


def fetch_metadata(requests):
    """
    Fetch metadata about a DHIS2 instance.

    Currently only used for determining what API version it supports.

    .. NOTE::
       Metadata is large (like a 100MB JSON document), and contains the
       IDs one would need to compile a human-readable configuration into
       one that maps to DHIS2 IDs.

    """
    response = requests.get('/api/metadata', raise_for_status=True)
    return response.json()


def create_dhis2_event_repeat_records(sender, xform, **kwargs):
    create_repeat_records(Dhis2Repeater, xform)


def create_dhis2_entity_repeat_records(sender, xform, **kwargs):
    create_repeat_records(Dhis2EntityRepeater, xform)


successful_form_received.connect(create_dhis2_event_repeat_records)
successful_form_received.connect(create_dhis2_entity_repeat_records)
Exemplo n.º 12
0
        'casexml.apps.case.signals.process_cases has been moved to '
        'casexml.apps.case.process_cases '
        'and the unused `sender` and `**kwargs` parameters have been removed.',
        DeprecationWarning,
    )
    from casexml.apps.case import process_cases
    process_cases(xform, config)


@log_exception()
def _process_cases(sender, xform, config=None, **kwargs):
    from casexml.apps.case import process_cases
    process_cases(xform, config)


successful_form_received.connect(_process_cases)


def rebuild_form_cases(sender, xform, *args, **kwargs):
    from casexml.apps.case.xform import get_case_ids_from_form
    from casexml.apps.case.cleanup import rebuild_case
    for case_id in get_case_ids_from_form(xform):
        rebuild_case(case_id)


xform_archived.connect(rebuild_form_cases)
xform_unarchived.connect(rebuild_form_cases)

# any time a case is saved
case_post_save = Signal(providing_args=["case"])
Exemplo n.º 13
0
    domain_name = application.domain
    config = CareplanConfig.for_domain(domain_name)

    if application.doc_type == 'Application-Deleted':
        if application.has_careplan_module:
            careplan_removed(domain_name, config, application.get_id)


def update_project_careplan_config_release(sender, application, **kwargs):
    domain_name = application.domain
    config = CareplanConfig.for_domain(domain_name)
    parent_app_id = application.copy_of

    latest_app = application.get_latest_app(released_only=True)
    if latest_app and latest_app.is_released and latest_app.has_careplan_module:
        config = config or CareplanConfig(domain=domain_name)
        update_careplan_config(config, parent_app_id, latest_app)
    else:
        careplan_removed(domain_name, config, parent_app_id)


successful_form_received.connect(get_custom_response_message)

app_post_save = Signal(providing_args=['application'])

app_post_save.connect(create_app_structure_repeat_records)
app_post_save.connect(update_project_careplan_config)

app_post_release = Signal(providing_args=['application'])
app_post_release.connect(update_project_careplan_config_release)
Exemplo n.º 14
0

def create_form_repeat_records(sender, xform, **kwargs):
    from corehq.apps.receiverwrapper.models import FormRepeater
    create_repeat_records(FormRepeater, xform)


def create_case_repeat_records(sender, case, **kwargs):
    from corehq.apps.receiverwrapper.models import CaseRepeater
    create_repeat_records(CaseRepeater, case)


def create_short_form_repeat_records(sender, xform, **kwargs):
    from corehq.apps.receiverwrapper.models import ShortFormRepeater
    create_repeat_records(ShortFormRepeater, xform)


def create_repeat_records(repeater_cls, payload):
    domain = payload.domain
    if domain:
        repeaters = repeater_cls.by_domain(domain)
        for repeater in repeaters:
            if not (getattr(repeater, 'exclude_device_reports', False)
                    and is_device_report(payload)):
                repeater.register(payload)


successful_form_received.connect(create_form_repeat_records)
successful_form_received.connect(create_short_form_repeat_records)
case_post_save.connect(create_case_repeat_records)
Exemplo n.º 15
0
        SupplyPointCase.wrap(c._doc) for c in cases
        if c.type == const.SUPPLY_POINT_CASE_TYPE
    ]
    case_updates = get_case_updates(xform)
    for sp in supply_points:
        created = any(
            filter(
                lambda update: update.id == sp._id and update.creates_case(),
                case_updates))
        supply_point_modified.send(sender=None,
                                   supply_point=sp,
                                   created=created)


def supply_point_processing(sender, xform, cases, **kwargs):
    if is_supply_point_form(xform):
        attach_locations(xform, cases)
        raise_supply_point_events(xform, cases)


cases_received.connect(supply_point_processing)


def bootstrap_commtrack_settings_if_necessary_signal(sender, **kwargs):
    bootstrap_commtrack_settings_if_necessary(kwargs['domain'])


commcare_domain_post_save.connect(
    bootstrap_commtrack_settings_if_necessary_signal)
successful_form_received.connect(process_stock_signal_catcher)
Exemplo n.º 16
0
    if requisition_cases and requisition_cases[0].requisition_status == RequisitionStatus.RECEIVED:
        requisition_receipt.send(sender=None, requisitions=requisition_cases)

    if requisition_cases and requisition_cases[0].requisition_status == RequisitionStatus.REQUESTED:
        requisition_modified.send(sender=None, cases=requisition_cases)


def raise_supply_point_events(xform, cases):
    supply_points = [SupplyPointCase.wrap(c._doc) for c in cases if c.type == const.SUPPLY_POINT_CASE_TYPE]
    case_updates = get_case_updates(xform)
    for sp in supply_points:
        created = any(filter(lambda update: update.id == sp._id and update.creates_case(), case_updates))
        supply_point_modified.send(sender=None, supply_point=sp, created=created)


def supply_point_processing(sender, xform, cases, **kwargs):
    if is_supply_point_form(xform):
        attach_locations(xform, cases)
        raise_supply_point_events(xform, cases)


cases_received.connect(supply_point_processing)


def bootstrap_commtrack_settings_if_necessary_signal(sender, **kwargs):
    bootstrap_commtrack_settings_if_necessary(kwargs["domain"])


commcare_domain_post_save.connect(bootstrap_commtrack_settings_if_necessary_signal)
successful_form_received.connect(process_stock_signal_catcher)
Exemplo n.º 17
0
    domain_name = application.domain
    config = CareplanConfig.for_domain(domain_name)

    if application.doc_type == 'Application-Deleted':
        if application.has_careplan_module:
            careplan_removed(domain_name, config, application.get_id)


def update_project_careplan_config_release(sender, application, **kwargs):
    domain_name = application.domain
    config = CareplanConfig.for_domain(domain_name)
    parent_app_id = application.copy_of

    latest_app = application.get_latest_app(released_only=True)
    if latest_app and latest_app.is_released and latest_app.has_careplan_module:
        config = config or CareplanConfig(domain=domain_name)
        update_careplan_config(config, parent_app_id, latest_app)
    else:
        careplan_removed(domain_name, config, parent_app_id)


successful_form_received.connect(get_custom_response_message)

app_post_save = Signal(providing_args=['application'])

app_post_save.connect(create_app_structure_repeat_records)
app_post_save.connect(update_project_careplan_config)

app_post_release = Signal(providing_args=['application'])
app_post_release.connect(update_project_careplan_config_release)
Exemplo n.º 18
0
def connect_user_signals():
    post_save.connect(django_user_post_save_signal, User,
                      dispatch_uid="django_user_post_save_signal")
    successful_form_received.connect(create_user_from_commcare_registration,
                                     dispatch_uid="create_user_from_commcare_registration")
    couch_user_post_save.connect(update_user_in_es, dispatch_uid="update_user_in_es")
Exemplo n.º 19
0
#placeholder for doing blocking vs. async via celery
BLOCKING = True


def process_dots_submission(sender, xform, **kwargs):
    from pact.tasks import recalculate_dots_data, eval_dots_block
    try:
        if xform.xmlns != "http://dev.commcarehq.org/pact/dots_form":
            return

        #grrr, if we were on celery 3.0, we could do this!
        #        chain = eval_dots_block.s(xform.to_json()) | recalculate_dots_data.s(case_id)
        #        chain()

        eval_dots_block(xform.to_json())
        case_id = get_case_id(xform)
        # get user from xform
        user_id = xform.metadata.userID
        cc_user = CouchUser.get_by_user_id(user_id)
        last_sync_token = getattr(xform, 'last_sync_token', None)
        recalculate_dots_data(case_id, cc_user, sync_token=last_sync_token)

    except Exception as ex:
        tb = traceback.format_exc()
        notify_exception(None, message="Error processing PACT DOT submission due to an unknown error: %s\n\tTraceback: %s" % (ex, tb))

#xform_saved.connect(process_dots_submission)
successful_form_received.connect(process_dots_submission)

Exemplo n.º 20
0
                    case,
                    resource_type,
                    case_block,
                    form_question_values,
                ))
        return case_trigger_info_list, resource_types_by_case_type


def _get_cases_by_id(domain, case_blocks):
    case_ids = [case_block['@case_id'] for case_block in case_blocks]
    cases = CaseAccessors(domain).get_cases(case_ids, ordered=True)
    return {c.case_id: c for c in cases}


def _get_resource_types_by_case_type(domain, fhir_version, cases):
    case_type_names = {case.type for case in cases}
    fhir_resource_types = (FHIRResourceType.objects.select_related(
        'case_type').prefetch_related('properties__case_property').filter(
            domain=domain,
            fhir_version=fhir_version,
            case_type__name__in=case_type_names,
        ))
    return {rt.case_type.name: rt for rt in fhir_resource_types}


def create_fhir_repeat_records(sender, xform, **kwargs):
    create_repeat_records(FHIRRepeater, xform)


successful_form_received.connect(create_fhir_repeat_records)
Exemplo n.º 21
0
        """
        return self.__class__.__name__

    @classmethod
    def available_for_domain(cls, domain):
        return DHIS2_INTEGRATION.enabled(domain)

    @classmethod
    def get_custom_url(cls, domain):
        return reverse(AddDhis2RepeaterView.urlname, args=[domain])

    def get_payload(self, repeat_record):
        payload = super(Dhis2Repeater, self).get_payload(repeat_record)
        return json.loads(payload)

    def send_request(self, repeat_record, payload):
        for form_config in self.dhis2_config.form_configs:
            if form_config.xmlns == payload['form']['@xmlns']:
                return send_data_to_dhis2(
                    Requests(self.domain, self.url, self.username, self.plaintext_password, verify=self.verify),
                    form_config,
                    payload,
                )


def create_dhis_repeat_records(sender, xform, **kwargs):
    create_repeat_records(Dhis2Repeater, xform)


successful_form_received.connect(create_dhis_repeat_records)