Ejemplo n.º 1
0
 def testGetAllStripHistory(self):
     # strip history doesn't work on SQL domains
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, footprint=True,
                               strip_history=True)
     self.assertEqual(self.expectedAll, len(list))
     self.assertListMatches(list, lambda c: len(c._couch_doc.actions) == 0)
     self.assertListMatches(list, lambda c: len(c._couch_doc.xform_ids) == 0)
Ejemplo n.º 2
0
 def testFiltersWithoutFootprint(self):
     name = _type_to_name(_child_case_type(self.test_type))
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL,
                               footprint=False,
                               filters={"properties/case_name": name})
     self.assertEqual(1, len(list))
     self.assertListMatches(list, lambda c: c['properties']['case_name'] == name)
Ejemplo n.º 3
0
def get_cases(request, domain):

    if request.couch_user.is_commcare_user():
        user_id = request.couch_user.get_id
    else:
        user_id = request.REQUEST.get("user_id", "")

    if not user_id and not request.couch_user.is_web_user():
        return HttpResponseBadRequest("Must specify user_id!")

    ids_only = string_to_boolean(request.REQUEST.get("ids_only", "false"))
    case_id = request.REQUEST.get("case_id", "")
    footprint = string_to_boolean(request.REQUEST.get("footprint", "false"))
    include_children = string_to_boolean(request.REQUEST.get("include_children", "false"))
    if case_id and not footprint and not include_children:
        # short circuit everything else and just return the case
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = CommCareCase.get(case_id)
        assert case.domain == domain
        cases = [CaseAPIResult(id=case_id, couch_doc=case, id_only=ids_only)]
    else:
        filters = get_filters_from_request(request)
        status = api_closed_to_status(request.REQUEST.get('closed', 'false'))
        case_type = filters.get('properties/case_type', None)
        cases = get_filtered_cases(domain, status=status, case_type=case_type,
                                   user_id=user_id, filters=filters,
                                   footprint=footprint, ids_only=ids_only,
                                   strip_history=True, include_children=include_children)
    return json_response(cases)
Ejemplo n.º 4
0
 def testGetAllIdsOnlyStripHistory(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, footprint=True, include_children=True,
                               ids_only=True, strip_history=True)
     self.assertEqual(self.expectedAll, len(list))
     self.assertListMatches(list, lambda c: isinstance(c._couch_doc, dict))
     self.assertListMatches(list, lambda c: 'actions' not in c._couch_doc)
     self.assertListMatches(list, lambda c: 'xform_ids' not in c._couch_doc)
     self.assertListMatches(list, lambda c: isinstance(c.to_json(), basestring))
Ejemplo n.º 5
0
 def testFiltersWithFootprint(self):
     name = _type_to_name(_child_case_type(self.test_type))
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL,
                               footprint=True,
                               filters={"properties/case_name": name})
     # when filtering with footprint, the filters get intentionally ignored
     # so just ensure the whole footprint including open and closed is available
     self.assertEqual(self.expectedOpenByUserWithFootprint + self.expectedClosedByUserWithFootprint, len(list))
Ejemplo n.º 6
0
 def testFiltersWithFootprint(self):
     name = _type_to_name(_child_case_type(self.test_type))
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL,
                               footprint=True,
                               filters={"properties/case_name": name})
     self.assertEqual(2, len(list))
     # make sure at least one doesn't actually have the right property
     # but was included in the footprint
     self.assertEqual(1, len([c for c in list if c['properties']['case_name'] != name]))
Ejemplo n.º 7
0
def filter_cases(request, domain, app_id, module_id):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    delegation = request.GET.get('task-list') == 'true'
    auth_cookie = request.COOKIES.get('sessionid')

    suite_gen = SuiteGenerator(app)
    xpath = suite_gen.get_filter_xpath(module, delegation=delegation)
    extra_instances = [{'id': inst.id, 'src': inst.src}
                       for inst in suite_gen.get_instances_for_module(module, additional_xpaths=[xpath])]

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    if delegation:
        case_type = DELEGATION_STUB_CASE_TYPE
    else:
        case_type = module.case_type

    if xpath:
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = SessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath, additional_filters, DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances)
        if result.get('status', None) == 'error':
            return HttpResponseServerError(
                result.get("message", _("Something went wrong filtering your cases.")))

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [res.id for res in get_filtered_cases(
            domain, status=CASE_STATUS_OPEN, case_type=case_type,
            user_id=request.couch_user._id, ids_only=True
        )]

    cases = [CommCareCase.wrap(doc) for doc in iter_docs(CommCareCase.get_db(), case_ids)]
    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.get_json(lite=True) for c in cases if c]
    parents = []
    if delegation:
        for case in cases:
            parent_id = case['indices']['parent']['case_id']
            parents.append(CommCareCase.get(parent_id))
        return json_response({
            'cases': cases,
            'parents': parents
        })
    else:
        return json_response(cases)
Ejemplo n.º 8
0
 def obj_get_list(self, bundle, domain, **kwargs):
     user_id = bundle.request.GET.get('user_id')
     status = api_closed_to_status(bundle.request.REQUEST.get('closed', 'false'))
     filters = get_filters_from_request(bundle.request, limit_top_level=self.fields)
     case_type = filters.get('properties/case_type', None)
     return map(dict_object, get_filtered_cases(domain, status=status,
                               case_type=case_type,
                               user_id=user_id,
                               filters=filters))
Ejemplo n.º 9
0
 def testFiltersOnOwned(self):
     list = get_filtered_cases(
         self.domain,
         user_id=self.test_user_id,
         status=CASE_STATUS_ALL,
         filters={"properties/case_name": _type_to_name(self.test_type)},
     )
     self.assertEqual(2, len(list))
     self.assertListMatches(list, lambda c: c["properties"]["case_name"] == _type_to_name(self.test_type))
Ejemplo n.º 10
0
 def testFiltersOnOwned(self):
     list = get_filtered_cases(
         self.domain,
         user_id=self.test_user_id,
         status=CASE_STATUS_ALL,
         filters={"properties/case_name": _type_to_name(self.test_type)})
     self.assertEqual(2, len(list))
     self.assertListMatches(
         list, lambda c: c['properties']['case_name'] == _type_to_name(
             self.test_type))
Ejemplo n.º 11
0
 def testFiltersWithoutFootprint(self):
     name = _type_to_name(_child_case_type(self.test_type))
     list = get_filtered_cases(self.domain,
                               user_id=self.test_user_id,
                               status=CASE_STATUS_ALL,
                               footprint=False,
                               filters={"properties/case_name": name})
     self.assertEqual(1, len(list))
     self.assertListMatches(list,
                            lambda c: c['properties']['case_name'] == name)
Ejemplo n.º 12
0
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    auth_cookie = request.COOKIES.get('sessionid')

    suite_gen = SuiteGenerator(app)
    xpath = SuiteGenerator.get_filter_xpath(module)
    extra_instances = [{'id': inst.id, 'src': inst.src}
                       for inst in suite_gen.get_instances_for_module(module, additional_xpaths=[xpath])]

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    case_type = module.case_type

    if xpath:
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = SessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath, additional_filters, DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances)
        if result.get('status', None) == 'error':
            code = result.get('code', 500)
            message = result.get('message', _("Something went wrong filtering your cases."))
            if code == 500:
                notify_exception(None, message=message)
            return json_response(message, status_code=code)

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [res.id for res in get_filtered_cases(
            domain,
            status=CASE_STATUS_OPEN,
            case_type=case_type,
            user_id=request.couch_user._id,
            footprint=True,
            ids_only=True,
        )]

    cases = [CommCareCase.wrap(doc) for doc in iter_docs(CommCareCase.get_db(), case_ids)]

    if parent_id:
        cases = filter(lambda c: c.parent and c.parent.case_id == parent_id, cases)

    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.get_json(lite=True) for c in cases if c]

    return json_response(cases)
Ejemplo n.º 13
0
 def testFiltersWithFootprint(self):
     name = _type_to_name(_child_case_type(self.test_type))
     list = get_filtered_cases(self.domain,
                               user_id=self.test_user_id,
                               status=CASE_STATUS_ALL,
                               footprint=True,
                               filters={"properties/case_name": name})
     # when filtering with footprint, the filters get intentionally ignored
     # so just ensure the whole footprint including open and closed is available
     self.assertEqual(
         self.expectedOpenByUserWithFootprint +
         self.expectedClosedByUserWithFootprint, len(list))
Ejemplo n.º 14
0
 def obj_get_list(self, bundle, domain, **kwargs):
     user_id = bundle.request.GET.get('user_id')
     status = api_closed_to_status(
         bundle.request.REQUEST.get('closed', 'false'))
     filters = get_filters_from_request(bundle.request,
                                        limit_top_level=self.fields)
     case_type = filters.get('properties/case_type', None)
     return map(
         dict_object,
         get_filtered_cases(domain,
                            status=status,
                            case_type=case_type,
                            user_id=user_id,
                            filters=filters))
Ejemplo n.º 15
0
    def obj_get_list(self, request, domain, **kwargs):
        """"""
        user_id = request.GET.get('user_id')
        @dict
        @inline
        def filters():
            for path, val in request.REQUEST.items():
                if path == 'user_id':
                    continue
                if path == 'closed' and val == 'any':
                    continue
                if '/' in path or path in self.fields:
                    yield path, val

        return map(dict_object, get_filtered_cases(domain, user_id=user_id, filters=filters))
Ejemplo n.º 16
0
def get_cases(request, domain):
    request_params = request.GET

    if request.couch_user.is_commcare_user():
        user_id = request.couch_user.get_id
    else:
        user_id = request_params.get("user_id", "")

    if not user_id and not request.couch_user.is_web_user():
        return HttpResponseBadRequest("Must specify user_id!")

    ids_only = string_to_boolean(request_params.get("ids_only", "false"))
    case_id = request_params.get("case_id", "")
    footprint = string_to_boolean(request_params.get("footprint", "false"))
    accessor = CaseAccessors(domain)

    if toggles.HSPH_HACK.enabled(domain):
        hsph_case_id = request_params.get('hsph_hack', None)
        if hsph_case_id != 'None' and hsph_case_id and user_id:
            case = accessor.get_case(hsph_case_id)
            usercase_id = CommCareUser.get_by_user_id(user_id).get_usercase_id()
            usercase = accessor.get_case(usercase_id) if usercase_id else None
            return json_response(map(
                lambda case: CaseAPIResult(domain=domain, id=case['_id'], couch_doc=case, id_only=ids_only),
                filter(None, [case, case.parent, usercase])
            ))

    if case_id and not footprint:
        # short circuit everything else and just return the case
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = accessor.get_case(case_id)
        assert case.domain == domain
        cases = [CaseAPIResult(domain=domain, id=case_id, couch_doc=case, id_only=ids_only)]
    else:
        filters = get_filters_from_request_params(request_params)
        status = api_closed_to_status(request_params.get('closed', 'false'))
        case_type = filters.get('properties/case_type', None)
        cases = get_filtered_cases(domain, status=status, case_type=case_type,
                                   user_id=user_id, filters=filters,
                                   footprint=footprint, ids_only=ids_only,
                                   strip_history=True)
    return json_response(cases)
Ejemplo n.º 17
0
def get_cases(request, domain):

    if request.couch_user.is_commcare_user():
        user_id = request.couch_user.get_id
    else:
        user_id = request.REQUEST.get("user_id", "")

    if not user_id and not request.couch_user.is_web_user():
        return HttpResponseBadRequest("Must specify user_id!")

    @dict
    @inline
    def filters():
        """copy request.REQUEST but exclude user_id"""
        for path, val in request.REQUEST.items():
            if path != 'user_id':
                yield (path, val)

    cases = get_filtered_cases(domain, user_id=user_id, filters=filters)
    return json_response(cases)
Ejemplo n.º 18
0
 def testGetAllOpenWithType(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_OPEN, case_type=self.test_type)
     self.assertEqual(self.expectedOpenByType, len(list))
     self.assertListMatches(list, lambda c: not c['closed'] and c['properties']['case_type'] == self.test_type)
Ejemplo n.º 19
0
 def testGetOwnedClosedWithFootprint(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_CLOSED, footprint=True)
     self.assertEqual(self.expectedClosedByUserWithFootprint, len(list))
     self.assertListMatches(list, lambda c: c['closed'] or c['user_id'] != self.test_user_id)
Ejemplo n.º 20
0
 def testGetOwnedClosed(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_CLOSED, footprint=False)
     self.assertEqual(self.expectedClosedByUser, len(list))
     self.assertListMatches(list, lambda c: c["closed"] and c["user_id"] == self.test_user_id)
Ejemplo n.º 21
0
 def testGetAllOpenWithType(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_OPEN, case_type=self.test_type)
     self.assertEqual(self.expectedOpenByType, len(list))
     self.assertListMatches(list, lambda c: not c['closed'] and c['properties']['case_type'] == self.test_type)
Ejemplo n.º 22
0
 def testFiltersOnAll(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL,
                               filters={"properties/case_name": _type_to_name(self.test_type)})
     self.assertEqual(self.expectedByType, len(list))
     self.assertListMatches(list, lambda c: c['properties']['case_name'] == _type_to_name(self.test_type))
Ejemplo n.º 23
0
 def testGetOwnedBothWithFootprint(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL, footprint=True)
     self.assertEqual(self.expectedOpenByUserWithFootprint + self.expectedClosedByUserWithFootprint, len(list))
Ejemplo n.º 24
0
 def testGetOwnedBoth(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL, footprint=False)
     self.assertEqual(self.expectedByUser, len(list))
     self.assertListMatches(list, lambda c: c['user_id'] == self.test_user_id)
Ejemplo n.º 25
0
 def testGetAllOpen(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_OPEN)
     self.assertEqual(self.expectedOpen, len(list))
     self.assertListMatches(list, lambda c: not c['closed'])
Ejemplo n.º 26
0
 def testGetOwnedOpen(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_OPEN, footprint=False)
     self.assertEqual(self.expectedOpenByUser, len(list))
     self.assertListMatches(list, lambda c: not c['closed'] and c['user_id'] == self.test_user_id)
Ejemplo n.º 27
0
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    delegation = request.GET.get('task-list') == 'true'
    auth_cookie = request.COOKIES.get('sessionid')

    suite_gen = SuiteGenerator(app)
    xpath = suite_gen.get_filter_xpath(module, delegation=delegation)
    extra_instances = [{
        'id': inst.id,
        'src': inst.src
    } for inst in suite_gen.get_instances_for_module(
        module, additional_xpaths=[xpath])]

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    if delegation:
        case_type = DELEGATION_STUB_CASE_TYPE
    else:
        case_type = module.case_type

    if xpath:
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = SessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath,
                                     additional_filters,
                                     DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances)
        if result.get('status', None) == 'error':
            return HttpResponseServerError(
                result.get("message",
                           _("Something went wrong filtering your cases.")))

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [
            res.id
            for res in get_filtered_cases(domain,
                                          status=CASE_STATUS_OPEN,
                                          case_type=case_type,
                                          user_id=request.couch_user._id,
                                          ids_only=True)
        ]

    cases = [
        CommCareCase.wrap(doc)
        for doc in iter_docs(CommCareCase.get_db(), case_ids)
    ]

    if parent_id:
        cases = filter(lambda c: c.parent and c.parent.case_id == parent_id,
                       cases)

    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.get_json(lite=True) for c in cases if c]
    parents = []
    if delegation:
        for case in cases:
            parent_id = case['indices']['parent']['case_id']
            parents.append(CommCareCase.get(parent_id))
        return json_response({'cases': cases, 'parents': parents})
    else:
        return json_response(cases)
Ejemplo n.º 28
0
 def testFiltersOnAll(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL,
                               filters={"properties/case_name": _type_to_name(self.test_type)})
     self.assertEqual(self.expectedByType, len(list))
     self.assertListMatches(list, lambda c: c['properties']['case_name'] == _type_to_name(self.test_type))
Ejemplo n.º 29
0
 def testGetAllIdsOnly(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, footprint=True,
                               ids_only=True)
     self.assertEqual(self.expectedAll, len(list))
     self.assertListMatches(list, lambda c: c._couch_doc is None)
     self.assertListMatches(list, lambda c: isinstance(c.to_json(), basestring))
Ejemplo n.º 30
0
 def testGetOwnedBothWithFootprint(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL, footprint=True)
     self.assertEqual(self.expectedOpenByUserWithFootprint + self.expectedClosedByUserWithFootprint, len(list))
Ejemplo n.º 31
0
 def testGetAllWithClosedAndType(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, case_type=self.test_type)
     self.assertEqual(self.expectedByType, len(list))
     self.assertListMatches(list, lambda c: c['properties']['case_type'] == self.test_type)
Ejemplo n.º 32
0
 def testGetOwnedOpen(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_OPEN, footprint=False)
     self.assertEqual(self.expectedOpenByUser, len(list))
     self.assertListMatches(list, lambda c: not c['closed'] and c['user_id'] == self.test_user_id)
Ejemplo n.º 33
0
 def testGetAllWithClosed(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL)
     self.assertEqual(self.expectedOpen + self.expectedClosed, len(list))
Ejemplo n.º 34
0
 def testGetOwnedClosedWithFootprint(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_CLOSED, footprint=True)
     self.assertEqual(self.expectedClosedByUserWithFootprint, len(list))
     self.assertListMatches(list, lambda c: c['closed'] or c['user_id'] != self.test_user_id)
Ejemplo n.º 35
0
 def testGetAllWithClosedAndType(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, case_type=self.test_type)
     self.assertEqual(self.expectedByType, len(list))
     self.assertListMatches(list, lambda c: c['properties']['case_type'] == self.test_type)
Ejemplo n.º 36
0
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    auth_cookie = request.COOKIES.get('sessionid')
    requires_parent_cases = string_to_boolean(
        request.GET.get('requires_parent_cases', 'false'))

    xpath = EntriesHelper.get_filter_xpath(module)
    instances = get_instances_for_module(app,
                                         module,
                                         additional_xpaths=[xpath])
    extra_instances = [{'id': inst.id, 'src': inst.src} for inst in instances]
    use_formplayer = toggles.USE_FORMPLAYER.enabled(domain)
    accessor = CaseAccessors(domain)

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    case_type = module.case_type

    if xpath or should_use_sql_backend(domain):
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = BaseSessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath,
                                     additional_filters,
                                     DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances,
                                     use_formplayer=use_formplayer)
        if result.get('status', None) == 'error':
            code = result.get('code', 500)
            message = result.get(
                'message', _("Something went wrong filtering your cases."))
            if code == 500:
                notify_exception(None, message=message)
            return json_response(message, status_code=code)

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [
            res.id for res in get_filtered_cases(
                domain,
                status=CASE_STATUS_OPEN,
                case_type=case_type,
                user_id=request.couch_user._id,
                footprint=True,
                ids_only=True,
            )
        ]

    cases = accessor.get_cases(case_ids)

    if parent_id:
        cases = filter(lambda c: c.parent and c.parent.case_id == parent_id,
                       cases)

    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.to_api_json(lite=True) for c in cases if c]

    response = {'cases': cases}
    if requires_parent_cases:
        # Subtract already fetched cases from parent list
        parent_ids = set(map(lambda c: c['indices']['parent']['case_id'], cases)) - \
            set(map(lambda c: c['case_id'], cases))
        parents = accessor.get_cases(list(parent_ids))
        parents = [c.to_api_json(lite=True) for c in parents]
        response.update({'parents': parents})

    return json_response(response)
Ejemplo n.º 37
0
 def testGetAllIdsOnly(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, footprint=True, ids_only=True)
     self.assertEqual(self.expectedAll, len(list))
     self.assertListMatches(list, lambda c: isinstance(c._couch_doc, dict))
     self.assertListMatches(list, lambda c: isinstance(c.to_json(), basestring))
Ejemplo n.º 38
0
 def testGetAllStripHistory(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL, footprint=True,
                               strip_history=True)
     self.assertEqual(self.expectedAll, len(list))
     self.assertListMatches(list, lambda c: len(c._couch_doc.actions) == 0)
     self.assertListMatches(list, lambda c: len(c._couch_doc.xform_ids) == 0)
Ejemplo n.º 39
0
 def testGetAllOpen(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_OPEN)
     self.assertEqual(self.expectedOpen, len(list))
     self.assertListMatches(list, lambda c: not c['closed'])
Ejemplo n.º 40
0
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    auth_cookie = request.COOKIES.get('sessionid')

    suite_gen = SuiteGenerator(app)
    xpath = SuiteGenerator.get_filter_xpath(module)
    extra_instances = [{
        'id': inst.id,
        'src': inst.src
    } for inst in suite_gen.get_instances_for_module(
        module, additional_xpaths=[xpath])]

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    case_type = module.case_type

    if xpath:
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = SessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath,
                                     additional_filters,
                                     DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances)
        if result.get('status', None) == 'error':
            code = result.get('code', 500)
            message = result.get(
                'message', _("Something went wrong filtering your cases."))
            if code == 500:
                notify_exception(None, message=message)
            return json_response(message, status_code=code)

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [
            res.id for res in get_filtered_cases(
                domain,
                status=CASE_STATUS_OPEN,
                case_type=case_type,
                user_id=request.couch_user._id,
                footprint=True,
                ids_only=True,
            )
        ]

    cases = [
        CommCareCase.wrap(doc)
        for doc in iter_docs(CommCareCase.get_db(), case_ids)
    ]

    if parent_id:
        cases = filter(lambda c: c.parent and c.parent.case_id == parent_id,
                       cases)

    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.get_json(lite=True) for c in cases if c]

    return json_response(cases)
Ejemplo n.º 41
0
 def testGetAllWithClosed(self):
     list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL)
     self.assertEqual(self.expectedOpen + self.expectedClosed, len(list))
Ejemplo n.º 42
0
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = accessor.get_case(case_id)
        assert case.domain == domain
        cases = [CaseAPIResult(id=case_id, couch_doc=case, id_only=ids_only)]
    else:
        filters = get_filters_from_request_params(request_params)
        status = api_closed_to_status(request_params.get('closed', 'false'))
        case_type = filters.get('properties/case_type', None)
        cases = get_filtered_cases(domain,
                                   status=status,
                                   case_type=case_type,
                                   user_id=user_id,
                                   filters=filters,
                                   footprint=footprint,
                                   ids_only=ids_only,
                                   strip_history=True)
    return json_response(cases)


@cloudcare_api
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    auth_cookie = request.COOKIES.get('sessionid')
    requires_parent_cases = string_to_boolean(
        request.GET.get('requires_parent_cases', 'false'))

    xpath = EntriesHelper.get_filter_xpath(module)
Ejemplo n.º 43
0
 def testGetOwnedBoth(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_ALL, footprint=False)
     self.assertEqual(self.expectedByUser, len(list))
     self.assertListMatches(list, lambda c: c['user_id'] == self.test_user_id)
Ejemplo n.º 44
0
def filter_cases(request, domain, app_id, module_id, parent_id=None):
    app = Application.get(app_id)
    module = app.get_module(module_id)
    auth_cookie = request.COOKIES.get('sessionid')
    requires_parent_cases = string_to_boolean(request.GET.get('requires_parent_cases', 'false'))

    xpath = EntriesHelper.get_filter_xpath(module)
    instances = get_instances_for_module(app, module, additional_xpaths=[xpath])
    extra_instances = [{'id': inst.id, 'src': inst.src} for inst in instances]
    accessor = CaseAccessors(domain)

    # touchforms doesn't like this to be escaped
    xpath = HTMLParser.HTMLParser().unescape(xpath)
    case_type = module.case_type

    if xpath or should_use_sql_backend(domain):
        # if we need to do a custom filter, send it to touchforms for processing
        additional_filters = {
            "properties/case_type": case_type,
            "footprint": True
        }

        helper = BaseSessionDataHelper(domain, request.couch_user)
        result = helper.filter_cases(xpath, additional_filters, DjangoAuth(auth_cookie),
                                     extra_instances=extra_instances)
        if result.get('status', None) == 'error':
            code = result.get('code', 500)
            message = result.get('message', _("Something went wrong filtering your cases."))
            if code == 500:
                notify_exception(None, message=message)
            return json_response(message, status_code=code)

        case_ids = result.get("cases", [])
    else:
        # otherwise just use our built in api with the defaults
        case_ids = [res.id for res in get_filtered_cases(
            domain,
            status=CASE_STATUS_OPEN,
            case_type=case_type,
            user_id=request.couch_user._id,
            footprint=True,
            ids_only=True,
        )]

    cases = accessor.get_cases(case_ids)

    if parent_id:
        cases = filter(lambda c: c.parent and c.parent.case_id == parent_id, cases)

    # refilter these because we might have accidentally included footprint cases
    # in the results from touchforms. this is a little hacky but the easiest
    # (quick) workaround. should be revisted when we optimize the case list.
    cases = filter(lambda c: c.type == case_type, cases)
    cases = [c.to_api_json(lite=True) for c in cases if c]

    response = {'cases': cases}
    if requires_parent_cases:
        # Subtract already fetched cases from parent list
        parent_ids = set(map(lambda c: c['indices']['parent']['case_id'], cases)) - \
            set(map(lambda c: c['case_id'], cases))
        parents = accessor.get_cases(list(parent_ids))
        parents = [c.to_api_json(lite=True) for c in parents]
        response.update({'parents': parents})

    return json_response(response)
Ejemplo n.º 45
0
 def testGetOwnedOpenWithFootprint(self):
     list = get_filtered_cases(self.domain, user_id=self.test_user_id, status=CASE_STATUS_OPEN, footprint=True)
     self.assertEqual(self.expectedOpenByUserWithFootprint, len(list))
     self.assertListMatches(list, lambda c: not c["closed"] or c["user_id"] != self.test_user_id)