Beispiel #1
0
def make_supply_point_product(supply_point_case, product_uuid, owner_id=None):
    domain = supply_point_case.domain
    id = uuid.uuid4().hex
    user_id = const.get_commtrack_user_id(domain)
    owner_id = owner_id or get_owner_id(supply_point_case) or user_id
    username = const.COMMTRACK_USERNAME
    product_name = Product.get(product_uuid).name
    caseblock = CaseBlock(
        case_id=id,
        create=True,
        version=V2,
        case_name=product_name,
        user_id=user_id,
        owner_id=owner_id,
        case_type=const.SUPPLY_POINT_PRODUCT_CASE_TYPE,
        update={
            "product": product_uuid
        },
        index={
            const.PARENT_CASE_REF: (const.SUPPLY_POINT_CASE_TYPE,
                                    supply_point_case._id),
        }
    )
    casexml = ElementTree.tostring(caseblock.as_xml())
    submit_case_blocks(casexml, domain, username, user_id,
                       xmlns=const.COMMTRACK_SUPPLY_POINT_PRODUCT_XMLNS)
    sppc = SupplyPointProductCase.get(id)
    sppc.bind_to_location(supply_point_case.location)
    sppc.save()
    return sppc
Beispiel #2
0
    def test_all_case_forms_deleted(self):
        from corehq.apps.callcenter.sync_user_case import sync_usercase
        sync_usercase(self.commcare_user)

        user_case_id = self.commcare_user.get_usercase_id()

        # other user submits form against the case (should get deleted)
        caseblock = CaseBlock(
            create=False,
            case_id=user_case_id,
        )
        submit_case_blocks(caseblock.as_string().decode('utf-8'), self.domain, user_id=self.other_user._id)

        case_ids = CaseAccessors(self.domain).get_case_ids_by_owners([self.commcare_user._id])
        self.assertEqual(1, len(case_ids))

        form_ids = FormAccessors(self.domain).get_form_ids_for_user(self.commcare_user._id)
        self.assertEqual(0, len(form_ids))

        user_case = self.commcare_user.get_usercase()
        self.assertEqual(2, len(user_case.xform_ids))

        self.commcare_user.retire()

        for form_id in user_case.xform_ids:
            self.assertTrue(FormAccessors(self.domain).get_form(form_id).is_deleted)

        self.assertTrue(CaseAccessors(self.domain).get_case(user_case_id).is_deleted)
Beispiel #3
0
    def test_case_block_index_default_relationship(self):
        """
        CaseBlock index relationship should default to "child"
        """
        case_block = CaseBlock(
            case_id='123456',
            case_type='newborn',
            date_modified='2015-07-24',
            date_opened='2015-07-24',
            index={
                'parent': ChildIndexAttrs(case_type='mother', case_id='789abc')
            },
        )

        self.assertEqual(
            ElementTree.tostring(case_block.as_xml()).decode('utf-8'),
            re.sub(r'(\n| {2,})', '', """
            <case case_id="123456" date_modified="2015-07-24" xmlns="http://commcarehq.org/case/transaction/v2">
                <update>
                    <case_type>newborn</case_type>
                    <date_opened>2015-07-24</date_opened>
                </update>
                <index>
                    <parent case_type="mother">789abc</parent>
                </index>
            </case>
            """)
        )
Beispiel #4
0
    def test_case_block_index_supports_relationship(self):
        """
        CaseBlock index should allow the relationship to be set
        """
        case_block = CaseBlock(
            case_id='abcdef',
            case_type='at_risk',
            date_modified='2015-07-24',
            date_opened='2015-07-24',
            index={
                'host': IndexAttrs(case_type='newborn', case_id='123456', relationship='extension')
            },
        )

        self.assertEqual(
            ElementTree.tostring(case_block.as_xml()).decode('utf-8'),
            re.sub(r'(\n| {2,})', '', """
            <case case_id="abcdef" date_modified="2015-07-24" xmlns="http://commcarehq.org/case/transaction/v2">
                <update>
                    <case_type>at_risk</case_type>
                    <date_opened>2015-07-24</date_opened>
                </update>
                <index>
                    <host case_type="newborn" relationship="extension">123456</host>
                </index>
            </case>
            """)
        )
Beispiel #5
0
def submit_mapping_case_block(user, index):
    mapping = user.get_location_map_case()

    if mapping:
        caseblock = CaseBlock(
            create=False,
            case_id=mapping._id,
            version=V2,
            index=index
        )
    else:
        caseblock = CaseBlock(
            create=True,
            case_type=const.USER_LOCATION_OWNER_MAP_TYPE,
            case_id=location_map_case_id(user),
            version=V2,
            owner_id=user._id,
            index=index,
            case_name=const.USER_LOCATION_OWNER_MAP_TYPE.replace('-', ' '),
            user_id=const.COMMTRACK_USERNAME,
        )

    submit_case_blocks(
        ElementTree.tostring(
            caseblock.as_xml(format_datetime=json_format_datetime)
        ),
        user.domain,
    )
Beispiel #6
0
def submit_mapping_case_block(user, index):
    mapping = user.get_location_map_case()

    if mapping:
        caseblock = CaseBlock(
            create=False,
            case_id=mapping._id,
            version=V2,
            index=index
        )
    else:
        caseblock = CaseBlock(
            create=True,
            case_type=USER_LOCATION_OWNER_MAP_TYPE,
            case_id=location_map_case_id(user),
            version=V2,
            owner_id=user._id,
            index=index
        )

    submit_case_blocks(
        ElementTree.tostring(caseblock.as_xml()),
        user.domain,
        user.username,
        user._id
    )
Beispiel #7
0
def create_case_from_dhis2(dhis2_child, domain, user):
    """
    Create a new case using the data pulled from DHIS2

    :param dhis2_child: TRACKED_ENTITY (i.e. "Child") from DHIS2
    :param domain: (str) The name of the domain
    :param user: (Document) The owner of the new case
    :return: New case ID
    """
    case_id = uuid.uuid4().hex
    update = {k: dhis2_child[v] for k, v in NUTRITION_ASSESSMENT_PROGRAM_FIELDS.iteritems()}
    update['dhis_org_id'] = dhis2_child['Org unit']
    # Do the inverse of push_case() to 'Gender' / 'child_gender'
    if 'child_gender' in update:
        if update['child_gender'] == 'Undefined':
            del update['child_gender']
        else:
            update['child_gender'] = update['child_gender'].lower()
    caseblock = CaseBlock(
        create=True,
        case_id=case_id,
        owner_id=user.userID,
        user_id=user.userID,
        case_type=CASE_TYPE,
        case_name=update[CASE_NAME] if CASE_NAME else '',
        external_id=dhis2_child['Instance'],
        update=update
    )
    casexml = ElementTree.tostring(caseblock.as_xml())
    submit_case_blocks(casexml, domain)
    return case_id
Beispiel #8
0
    def test_multiple_case_blocks_some_deleted(self, rebuild_case):
        """ Don't rebuild deleted cases """

        case_ids = [uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex]

        for i, case_id in enumerate(case_ids):
            if i == 0:
                # only the first case is owned by the user getting retired
                owner_id = self.other_user._id
            else:
                owner_id = self.commcare_user._id

            caseblock = CaseBlock(
                create=True,
                case_id=case_id,
                owner_id=owner_id,
                user_id=self.commcare_user._id,
            )
            submit_case_blocks(caseblock.as_string(), self.domain, user_id=self.other_user._id)

        self.other_user.retire()

        detail = UserArchivedRebuild(user_id=self.other_user.user_id)
        expected_call_args = [mock.call(self.domain, case_id, detail) for case_id in case_ids[1:]]

        self.assertEqual(rebuild_case.call_count, len(case_ids) - 1)
        self.assertItemsEqual(rebuild_case.call_args_list, expected_call_args)
Beispiel #9
0
    def test_forms_touching_live_case_not_deleted(self):
        case_id = uuid.uuid4().hex
        caseblock = CaseBlock(
            create=True,
            case_id=case_id,
            owner_id=self.commcare_user._id,
            user_id=self.commcare_user._id,
        )
        xform, _ = submit_case_blocks(caseblock.as_string().decode('utf-8'), self.domain)

        # other user submits form against the case and another case not owned by the user
        # should NOT get deleted since this form touches a case that's still 'alive'
        double_case_xform, _ = submit_case_blocks([
            CaseBlock(
                create=False,
                case_id=case_id,
            ).as_string().decode('utf-8'),
            CaseBlock(
                create=True,
                case_id=uuid.uuid4().hex,
                owner_id=self.other_user._id,
                user_id=self.other_user._id,
            ).as_string().decode('utf-8')
        ], self.domain, user_id=self.other_user._id)

        self.commcare_user.retire()

        self.assertTrue(FormAccessors(self.domain).get_form(xform.form_id).is_deleted)
        self.assertFalse(FormAccessors(self.domain).get_form(double_case_xform.form_id).is_deleted)

        # When the other user is deleted then the form should get deleted since it no-longer touches
        # any 'live' cases.
        self.other_user.retire()
        self.assertTrue(FormAccessors(self.domain).get_form(double_case_xform.form_id).is_deleted)
Beispiel #10
0
    def test_case_block_index_omit_child(self):
        """
        CaseBlock index relationship omit relationship attribute if set to "child"
        """
        case_block = CaseBlock(
            case_id='123456',
            case_type='newborn',
            date_modified='2015-07-24',
            index={
                'parent': IndexAttrs(case_type='mother', case_id='789abc', relationship='child')
            },
        )

        self.assertEqual(
            ElementTree.tostring(case_block.as_xml()),
            re.sub(r'(\n| {2,})', '', """
            <case case_id="123456" date_modified="2015-07-24" xmlns="http://commcarehq.org/case/transaction/v2">
                <update>
                    <case_type>newborn</case_type>
                </update>
                <index>
                    <parent case_type="mother">789abc</parent>
                </index>
            </case>
            """)
        )
Beispiel #11
0
 def testBadIndexReference(self):
     block = CaseBlock(create=True, case_id=self.CASE_ID, user_id=USER_ID, version=V2,
                       index={'bad': ('bad-case', 'not-an-existing-id')})
     try:
         post_case_blocks([block.as_xml()])
         self.fail("Submitting against a bad case in an index should fail!")
     except IllegalCaseId:
         pass
        def to_xml(to_update):
            caseblock = CaseBlock(
                create=False,
                case_id=to_update.case.case_id,
                user_id=MOTECH_ID,
                owner_id=to_update.new_owner_id or CaseBlock.undefined,
                case_type=to_update.new_type or CaseBlock.undefined,
            )

            return ElementTree.tostring(caseblock.as_xml())
Beispiel #13
0
def update_case_external_id(case, external_id):
    """
    Update the external_id of a case
    """
    caseblock = CaseBlock(
        create=False,
        case_id=case['_id'],
        external_id=external_id
    )
    casexml = ElementTree.tostring(caseblock.as_xml())
    submit_case_blocks(casexml, case['domain'])
Beispiel #14
0
 def _create_closed_case(cls):
     case_id = uuid.uuid4().hex
     caseblock = CaseBlock(
         case_id=case_id,
         case_type=cls.case_type,
         date_opened=cls.closed_case_date_opened,
         date_modified=cls.closed_case_date_closed,
         case_name=cls.case_name,
         close=True,
     )
     post_case_blocks([caseblock.as_xml()], domain=cls.domain)
     return case_id
Beispiel #15
0
def pull_child_entities(settings, dhis2_children):
    """
    Create new child cases for nutrition tracking in CommCare.

    Sets external_id on new child cases, and CCHQ Case ID on DHIS2
    tracked entity instances. (CCHQ Case ID is initially unset because the
    case is new and does not exist in CommCare.)

    :param settings: DHIS2 settings, incl. relevant domain
    :param dhis2_children: A list of dictionaries of Child tracked entities
                           from the DHIS2 API where CCHQ Case ID is unset

    This fulfills the third requirement of `DHIS2 Integration`_.


    .. _DHIS2 Integration: https://www.dropbox.com/s/8djk1vh797t6cmt/WV Sri Lanka Detailed Requirements.docx
    """
    dhis2_api = Dhis2Api(settings.dhis2.host, settings.dhis2.username, settings.dhis2.password,
                         settings.dhis2.top_org_unit_name)
    for dhis2_child in dhis2_children:
        # Add each child separately. Although this is slower, it avoids problems if a DHIS2 API call fails
        # ("Instance" is DHIS2's friendly name for "id")
        case = get_case_by_external_id(settings.domain, dhis2_child['Instance'])
        if case:
            case_id = case['case_id']
        else:
            user = get_user_by_org_unit(settings.domain, dhis2_child['Org unit'], settings.dhis2.top_org_unit_name)
            if not user:
                # No user is assigned to this organisation unit (i.e. region or facility). Now what?
                # TODO: Now what? Ascend to parent org unit?
                continue
            case_id = uuid.uuid4().hex
            caseblock = CaseBlock(
                create=True,
                case_id=case_id,
                owner_id=user.userID,
                user_id=user.userID,
                version=V2,
                case_type='child_gmp',  # TODO: Move to a constant / setting
                external_id=dhis2_child['Instance'],
                update={
                    'name': dhis2_child['Name'],
                    'height': dhis2_child['Height'],
                    'weight': dhis2_child['Weight'],
                    'age': dhis2_child['Age at time of visit'],
                    'bmi': dhis2_child['Body-mass index'],
                }
            )
            casexml = ElementTree.tostring(caseblock.as_xml())
            submit_case_blocks(casexml, settings.domain)
        dhis2_child['CCHQ Case ID'] = case_id
        dhis2_api.update_te_inst(dhis2_child)
    def testUserRestoreWithCase(self):
        restore_user = create_restore_user(domain=self.domain)
        expected_case_block = CaseBlock(
            create=True,
            case_id='my-case-id',
            user_id=restore_user.user_id,
            owner_id=restore_user.user_id,
            case_type='test-case-type',
            update={'external_id': 'someexternal'},
        )
        _, [case] = post_case_blocks([expected_case_block.as_xml()], {'domain': self.domain})

        assert_user_has_case(self, restore_user, case.case_id)
    def setUpClass(cls):
        super(TestFormProcessorCouch, cls).setUpClass()
        cls.case_id = uuid.uuid4().hex
        case = CaseBlock(
            create=True,
            case_id=cls.case_id,
            user_id='user1',
            owner_id='user1',
            case_type='demo',
            case_name='wrap?'
        )
        cls.domain = uuid.uuid4().hex

        cls.case = post_case_blocks([case.as_xml()], domain=cls.domain)[1][0]
Beispiel #18
0
 def _create_case(cls, parent_id):
     case_id = uuid.uuid4().hex
     caseblock = CaseBlock(
         case_id=case_id,
         case_type=cls.case_type,
         date_opened=cls.case_date_opened,
         case_name=cls.case_name,
         update=cls._get_case_property_values(),
         index={
             'parent': (cls.case_type, parent_id)
         }
     )
     post_case_blocks([caseblock.as_xml()], domain=cls.domain)
     return case_id
Beispiel #19
0
def sync_user_cases(commcare_user):
    domain = commcare_user.project
    if not (domain and domain.call_center_config.enabled):
        return

    # language or phone_number can be null and will break
    # case submission
    fields = {
        'name': commcare_user.name or commcare_user.raw_username,
        'email': commcare_user.email,
        'language': commcare_user.language or '',
        'phone_number': commcare_user.phone_number or ''
    }
    # fields comes second to prevent custom user data overriding
    fields = dict(commcare_user.user_data, **fields)

    found = False
    try:
        case = get_case_by_domain_hq_user_id(domain.name, commcare_user._id, include_docs=True)
        found = bool(case)
    except MultipleResultsFound:
        return

    close = commcare_user.to_be_deleted() or not commcare_user.is_active

    owner_id = domain.call_center_config.case_owner_id
    if found:
        caseblock = CaseBlock(
            create=False,
            case_id=case._id,
            version=V2,
            owner_id=owner_id,
            case_type=domain.call_center_config.case_type,
            close=close,
            update=fields
        )
    else:
        fields['hq_user_id'] = commcare_user._id
        caseblock = CaseBlock(
            create=True,
            case_id=uuid.uuid4().hex,
            owner_id=owner_id,
            user_id=owner_id,
            version=V2,
            case_type=domain.call_center_config.case_type,
            update=fields
        )

    casexml = ElementTree.tostring(caseblock.as_xml())
    submit_case_blocks(casexml, domain.name)
    def testBadIndexReferenceDomain(self):
        case_in_other_domain = 'text-index-mother-case'
        parent_domain = 'parent'
        child_domain = 'child'

        post_case_blocks([
            CaseBlock(create=True, case_id=case_in_other_domain, user_id=USER_ID,
                      version=V2).as_xml()
        ], form_extras={'domain': parent_domain})

        block = CaseBlock(create=True, case_id='child-case-id', user_id=USER_ID, version=V2,
                          index={'bad': ('bad-case', case_in_other_domain)})

        with self.assertRaisesRegexp(IllegalCaseId, 'Bad case id'):
            post_case_blocks([block.as_xml()], form_extras={'domain': child_domain})
Beispiel #21
0
    def test_long_value_validation(self):
        case_id = uuid.uuid4().hex
        case = CaseBlock(
            create=True,
            case_id=case_id,
            user_id='user1',
            owner_id='user1',
            case_type='demo',
            case_name='this is a very long case name that exceeds the 255 char limit' * 5
        )

        xform, cases = post_case_blocks([case.as_xml()], domain=DOMAIN)
        self.assertEqual(0, len(cases))
        self.assertTrue(xform.is_error)
        self.assertIn('CaseValueError', xform.problem)
Beispiel #22
0
def update_supply_point_product_stock_level(spp, current_stock):
    caseblock = CaseBlock(
        case_id=spp._id,
        create=False,
        version=V2,
        user_id=spp.user_id,
        owner_id=spp.owner_id,
        case_type=const.SUPPLY_POINT_PRODUCT_CASE_TYPE,
        update={
            "current_stock": current_stock
        },
    )
    username = const.COMMTRACK_USERNAME
    casexml = ElementTree.tostring(caseblock.as_xml())
    submit_case_blocks(casexml, spp.domain, username, spp.user_id,
                       xmlns=const.COMMTRACK_SUPPLY_POINT_PRODUCT_XMLNS)
Beispiel #23
0
    def test_dont_rebuild(self, rebuild_case):
        """ Don't rebuild cases that are owned by other users """

        case_id = uuid.uuid4().hex
        caseblock = CaseBlock(
            create=True,
            case_id=case_id,
            owner_id=self.commcare_user._id,
            user_id=self.commcare_user._id,
        )
        casexml = ElementTree.tostring(caseblock.as_xml())
        submit_case_blocks(casexml, self.domain, user_id=self.commcare_user._id)

        self.other_user.retire()

        self.assertEqual(rebuild_case.call_count, 0)
    def test_reprocess_xform_error(self):
        case_id = uuid.uuid4().hex
        parent_case_id = uuid.uuid4().hex
        case = CaseBlock(
            create=True,
            case_id=case_id,
            user_id='user1',
            owner_id='user1',
            case_type='demo',
            case_name='child',
            index={'parent': ('parent_type', parent_case_id)}
        )

        post_case_blocks([case.as_xml()], domain=self.domain)

        form_accessors = FormAccessors(self.domain)
        error_forms = form_accessors.get_forms_by_type('XFormError', 10)
        self.assertEqual(1, len(error_forms))

        form = error_forms[0]
        reprocess_xform_error(form)
        error_forms = form_accessors.get_forms_by_type('XFormError', 10)
        self.assertEqual(1, len(error_forms))

        case = CaseBlock(
            create=True,
            case_id=parent_case_id,
            user_id='user1',
            owner_id='user1',
            case_type='parent_type',
            case_name='parent',
        )

        post_case_blocks([case.as_xml()], domain=self.domain)

        reprocess_xform_error(form_accessors.get_form(form.form_id))

        form = form_accessors.get_form(form.form_id)
        # self.assertTrue(form.initial_processing_complete)  Can't change this with SQL forms at the moment
        self.assertTrue(form.is_normal)
        self.assertIsNone(form.problem)

        case = CaseAccessors(self.domain).get_case(case_id)
        self.assertEqual(1, len(case.indices))
        self.assertEqual(case.indices[0].referenced_id, parent_case_id)
        self._validate_case(case)
Beispiel #25
0
    def test_edit_an_error(self):
        form_id = uuid.uuid4().hex
        case_block = CaseBlock(
            create=True,
            case_id='',  # this should cause the submission to error
            case_type='person',
            owner_id='some-owner',
        )

        form, _ = submit_case_blocks(case_block.as_string(), domain=self.domain, form_id=form_id)
        self.assertTrue(form.is_error)
        self.assertTrue('IllegalCaseId' in form.problem)

        case_block.case_id = uuid.uuid4().hex
        form, _ = submit_case_blocks(case_block.as_string(), domain=self.domain, form_id=form_id)
        self.assertFalse(form.is_error)
        self.assertEqual(None, getattr(form, 'problem', None))
Beispiel #26
0
    def testArchiveModifiedOn(self):
        case_id = uuid.uuid4().hex
        now = datetime.utcnow().replace(microsecond=0)
        earlier = now - timedelta(hours=1)
        way_earlier = now - timedelta(days=1)
        # make sure we timestamp everything so they have the right order
        create_block = CaseBlock(case_id, create=True, date_modified=way_earlier)
        FormProcessorInterface.post_case_blocks([create_block.as_xml()], form_extras={'received_on': way_earlier})
        update_block = CaseBlock(case_id, update={'foo': 'bar'}, date_modified=earlier)
        FormProcessorInterface.post_case_blocks([update_block.as_xml()], form_extras={'received_on': earlier})

        case = CommCareCase.get(case_id)
        self.assertEqual(earlier, case.modified_on)

        second_form = XFormInstance.get(case.xform_ids[-1])
        second_form.archive()
        case = CommCareCase.get(case_id)
        self.assertEqual(way_earlier, case.modified_on)
Beispiel #27
0
def _create_tech_issue_delegate_for_escalation(tech_issue, owner_id):
    case_id = uuid.uuid4().hex
    caseblock = CaseBlock(
        case_id,
        case_type='tech_issue_delegate',
        create=True,
        update={'change_in_level': '1'},
        user_id=SYSTEM_USER_ID,
        owner_id=owner_id,
        case_name=tech_issue.name,
        index={'parent': (tech_issue.type, tech_issue.case_id, 'child')},
    )
    return submit_case_blocks(
        ElementTree.tostring(caseblock.as_xml()).decode('utf-8'),
        tech_issue.domain,
        user_id=SYSTEM_USER_ID,
        xmlns=AUTO_UPDATE_XMLNS,
        device_id=__name__ + "._create_tech_issue_delegate_for_escalation",
    )
Beispiel #28
0
    def test_rebuild_cases_with_new_owner(self, rebuild_case):
        """
            If cases have a different owner to the person who submitted it
            rebuild it when the submitter is retired.
        """

        case_id = uuid.uuid4().hex
        caseblock = CaseBlock(
            create=True,
            case_id=case_id,
            owner_id=self.commcare_user._id,
            user_id=self.commcare_user._id,
        )
        casexml = ElementTree.tostring(caseblock.as_xml())
        submit_case_blocks(casexml, self.domain, user_id=self.other_user._id)

        self.other_user.retire()

        rebuild_case.assert_called_once_with(case_id)
Beispiel #29
0
    def test_globally_unique_case_id(self):
        case_id = uuid.uuid4().hex
        case = CaseBlock(
            create=True,
            case_id=case_id,
            user_id='user1',
            owner_id='user1',
            case_type='demo',
            case_name='create_case'
        )

        with override_settings(TESTS_SHOULD_USE_SQL_BACKEND=False):
            post_case_blocks([case.as_xml()], domain='domain1')

        with override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True):
            xform, cases = post_case_blocks([case.as_xml()], domain='domain2')
            self.assertEqual(0, len(cases))
            self.assertTrue(xform.is_error)
            self.assertIn('IllegalCaseId', xform.problem)
Beispiel #30
0
    def testBadIndexReferenceDomain(self):
        case_in_other_domain = self.MOTHER_CASE_ID
        parent_domain = 'parent'
        child_domain = 'child'

        post_case_blocks([
            CaseBlock(create=True, case_id=case_in_other_domain, user_id=self.user.user_id).as_xml()
        ], form_extras={'domain': parent_domain})

        block = CaseBlock(create=True, case_id='child-case-id', user_id=self.user.user_id,
                          index={'bad': ('bad-case', case_in_other_domain)})

        xform, _ = post_case_blocks([block.as_xml()],
                                    form_extras={'domain': child_domain})

        self.assertTrue(xform.is_error)
        self.assertEqual(xform.doc_type, 'XFormError')
        self.assertIn('IllegalCaseId', xform.problem)
        self.assertIn('Bad case id', xform.problem)
 def submit_case_block(self, create, case_id, **kwargs):
     return post_case_blocks([
         CaseBlock.deprecated_init(create=create, case_id=case_id, **
                                   kwargs).as_xml()
     ],
                             domain=self.domain)
Beispiel #32
0
def _create_case(domain, **kwargs):
    from casexml.apps.case.mock import CaseBlock
    from corehq.apps.hqcase.utils import submit_case_blocks
    return submit_case_blocks([CaseBlock(**kwargs).as_text()], domain=domain)
Beispiel #33
0
    def test_case_management_ordering(self):
        case_id = uuid.uuid4().hex
        owner_id = uuid.uuid4().hex

        # create a case
        case_block = CaseBlock(
            create=True,
            case_id=case_id,
            case_type='person',
            owner_id=owner_id,
            version=V2,
        ).as_string()
        create_form_id = submit_case_blocks(case_block, domain=self.domain)

        # validate that worked
        case = CommCareCase.get(case_id)
        self.assertEqual([create_form_id], case.xform_ids)
        self.assertEqual([create_form_id], [a.xform_id for a in case.actions])
        for a in case.actions:
            self.assertEqual(create_form_id, a.xform_id)

        edit_date = datetime.utcnow()
        # set some property value
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            version=V2,
            date_modified=edit_date,
            update={
                'property': 'first value',
            }
        ).as_string()
        edit_form_id = submit_case_blocks(case_block, domain=self.domain)

        # validate that worked
        case = CommCareCase.get(case_id)
        self.assertEqual(case.property, 'first value')
        self.assertEqual([create_form_id, edit_form_id], case.xform_ids)
        self.assertEqual([create_form_id, edit_form_id], [a.xform_id for a in case.actions])

        # submit a second (new) form updating the value
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            version=V2,
            update={
                'property': 'final value',
            }
        ).as_string()
        second_edit_form_id = submit_case_blocks(case_block, domain=self.domain)

        # validate that worked
        case = CommCareCase.get(case_id)
        self.assertEqual(case.property, 'final value')
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], case.xform_ids)
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], [a.xform_id for a in case.actions])

        # deprecate the middle edit
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            version=V2,
            date_modified=edit_date,  # need to use the previous edit date for action sort comparisons
            update={
                'property': 'edited value',
                'added_property': 'added value',
            }
        ).as_string()
        submit_case_blocks(case_block, domain=self.domain, form_id=edit_form_id)

        # ensure that the middle edit stays in the right place and is applied
        # before the final one
        case = CommCareCase.get(case_id)
        self.assertEqual(case.property, 'final value')
        self.assertEqual(case.added_property, 'added value')
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], case.xform_ids)
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], [a.xform_id for a in case.actions])
Beispiel #34
0
def _update_episode_case(domain, case_id, updated_properties):
    post_case_blocks(
        [CaseBlock(case_id=case_id, update=updated_properties).as_xml()],
        {'domain': domain})
Beispiel #35
0
    def test_case_management_ordering(self):
        case_id = uuid.uuid4().hex
        owner_id = uuid.uuid4().hex

        # create a case
        case_block = CaseBlock(
            create=True,
            case_id=case_id,
            case_type='person',
            owner_id=owner_id,
        ).as_string()
        create_form_id = submit_case_blocks(case_block, domain=self.domain)[0].form_id

        # validate that worked
        case = self.casedb.get_case(case_id)
        self.assertEqual([create_form_id], case.xform_ids)

        if not settings.TESTS_SHOULD_USE_SQL_BACKEND:
            self.assertTrue(create_form_id in [a.xform_id for a in case.actions])
            for a in case.actions:
                self.assertEqual(create_form_id, a.xform_id)

        edit_date = datetime.utcnow()
        # set some property value
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            date_modified=edit_date,
            update={
                'property': 'first value',
            }
        ).as_string()
        edit_form_id = submit_case_blocks(case_block, domain=self.domain)[0].form_id

        # validate that worked
        case = self.casedb.get_case(case_id)
        self.assertEqual(case.dynamic_case_properties()['property'], 'first value')
        self.assertEqual([create_form_id, edit_form_id], case.xform_ids)

        if not settings.TESTS_SHOULD_USE_SQL_BACKEND:
            self.assertTrue(all(
                form_id in [a.xform_id for a in case.actions]
                for form_id in [create_form_id, edit_form_id]
            ))

        # submit a second (new) form updating the value
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            update={
                'property': 'final value',
            }
        ).as_string()
        second_edit_form_id = submit_case_blocks(case_block, domain=self.domain)[0].form_id

        # validate that worked
        case = self.casedb.get_case(case_id)
        self.assertEqual(case.dynamic_case_properties()['property'], 'final value')
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], case.xform_ids)

        if not settings.TESTS_SHOULD_USE_SQL_BACKEND:
            self.assertTrue(all(
                form_id in [a.xform_id for a in case.actions]
                for form_id in [create_form_id, edit_form_id, second_edit_form_id]
            ))

        # deprecate the middle edit
        case_block = CaseBlock(
            create=False,
            case_id=case_id,
            date_modified=edit_date,  # need to use the previous edit date for action sort comparisons
            update={
                'property': 'edited value',
                'added_property': 'added value',
            }
        ).as_string()
        submit_case_blocks(case_block, domain=self.domain, form_id=edit_form_id)

        # ensure that the middle edit stays in the right place and is applied
        # before the final one
        case = self.casedb.get_case(case_id)
        self.assertEqual(case.dynamic_case_properties()['property'], 'final value')
        self.assertEqual(case.dynamic_case_properties()['added_property'], 'added value')
        self.assertEqual([create_form_id, edit_form_id, second_edit_form_id], case.xform_ids)

        if not settings.TESTS_SHOULD_USE_SQL_BACKEND:
            self.assertEqual(
                [create_form_id, create_form_id, edit_form_id, second_edit_form_id],
                [a.xform_id for a in case.actions]
            )
Beispiel #36
0
        for identifier in patient_['identifiers']:
            yield identifier['identifierType']['uuid'], identifier[
                'identifier']

    case_config_ids = case_config['patient_identifiers']
    case_update = {}
    kwargs = {}
    for id_type_uuid, value in get_patient_id_type_uuids_values(patient):
        if id_type_uuid in case_config_ids:
            case_property = case_config_ids[id_type_uuid]['case_property']
            if case_property == 'external_id':
                check_duplicate_case_match(case, value)
                kwargs['external_id'] = value
            else:
                case_update[case_property] = value
    case_block = CaseBlock(case_id=case.get_id,
                           create=False,
                           update=case_update,
                           **kwargs)
    submit_case_blocks([case_block.as_text()],
                       case.domain,
                       xmlns=XMLNS_OPENMRS)


def check_duplicate_case_match(case, external_id):
    def get_case_str(case_):
        return (f'<Case case_id="{case_.case_id}", domain="{case_.domain}", '
                f'type="{case_.type}" name="{case_.name}">')

    another_case, error = importer_util.lookup_case(
        importer_util.EXTERNAL_ID,
Beispiel #37
0
    Creates an extension case so that the claimed case is synced to the claimant's device.
    """
    claim_id = uuid4().hex
    if not (host_type and host_name):
        case = CaseAccessors(domain).get_case(host_id)
        host_type = case.type
        host_name = case.name
    identifier = DEFAULT_CASE_INDEX_IDENTIFIERS[CASE_INDEX_EXTENSION]
    claim_case_block = CaseBlock(
        create=True,
        case_id=claim_id,
        case_name=host_name,
        case_type=CLAIM_CASE_TYPE,
        owner_id=owner_id,
        index={
            identifier: IndexAttrs(
                case_type=host_type,
                case_id=host_id,
                relationship=CASE_INDEX_EXTENSION,
            )
        }
    ).as_xml()
    post_case_blocks([claim_case_block], {'domain': domain})
    return claim_id


def get_first_claim(domain, user_id, case_id):
    """
    Returns the first claim by user_id of case_id, or None
    """
    case = CaseAccessors(domain).get_case(case_id)
Beispiel #38
0
            if date_opened:
                extras['date_opened'] = date_opened

        if not case:
            id = uuid.uuid4().hex

            if config.search_field == 'external_id':
                extras['external_id'] = search_id
            elif external_id:
                extras['external_id'] = external_id

            try:
                caseblock = CaseBlock(create=True,
                                      case_id=id,
                                      owner_id=owner_id,
                                      user_id=user_id,
                                      case_type=config.case_type,
                                      case_name=case_name or '',
                                      update=fields_to_update,
                                      **extras)
                caseblocks.append(RowAndCase(i, caseblock))
                created_count += 1
                if external_id:
                    ids_seen.add(external_id)
            except CaseBlockError:
                errors.add(ImportErrors.CaseGeneration, i + 1)
        else:
            if external_id:
                extras['external_id'] = external_id
            if uploaded_owner_id:
                extras['owner_id'] = owner_id
            if to_close == 'yes':
Beispiel #39
0
 def cases(self):
     """Dict of cases, keyed by case ID, from the sync body"""
     return {case.case_id: case for case in (CaseBlock.from_xml(node)
             for node in self.xml.findall("{%s}case" % V2_NAMESPACE))}