def test_update_bad_response(handler, mocker, subject_update_badresponse):
    eHBResponse = mocker.MagicMock(
        status=200
    )
    sub_old = Subject(
        id=2,
        first_name='Jane',
        last_name='Sample',
        organization_id=1,
        organization_subject_id='MRN123',
        dob=datetime.datetime(1990, 1, 1),
        modified=datetime.datetime(2015, 1, 1),
        created=datetime.datetime(2015, 1, 1)
    )
    sub_new = Subject(
        id=2,
        first_name='Jane',
        last_name='Sample',
        organization_id=1,
        organization_subject_id='MRN123',
        dob=datetime.datetime(1990, 1, 1),
        modified=datetime.datetime(2015, 1, 1),
        created=datetime.datetime(2015, 1, 1),
    )
    sub_new.old_subject = sub_old
    eHBResponse.read = mocker.MagicMock(return_value=subject_update_badresponse)
    handler.request_handler.PUT = mocker.MagicMock(return_value=eHBResponse)
    res = handler.update(sub_new)[0]
    assert not res['success']
    def check_subject(self, subject_1, subject_2):
        try:
            subject_1_response = self.s_rh.get(id=subject_1)
            subject_2_response = self.s_rh.get(id=subject_2)
        except:
            return {'error': 'Invalid subject Selected'}

        sub1 = json.loads(Subject.json_from_identity(subject_1_response))
        sub2 = json.loads(Subject.json_from_identity(subject_2_response))
        if sub1['id'] is None or sub2['id'] is None:
            return {'error': 'Invalid subject Selected'}
        return True
def test_identity_to_json():
    sub = Subject(
        id=2,
        first_name='Jane',
        last_name='Sample',
        organization_id=1,
        organization_subject_id='MRN123',
        dob=datetime.datetime(1990, 1, 1),
        modified=datetime.datetime(2015, 1, 1),
        created=datetime.datetime(2015, 1, 1)
    )
    jsonStr = sub.json_from_identity(sub)
    assert isinstance(jsonStr, str)
示例#4
0
 def test_retrieve_pds_subject_list(self, mock_errh, mock_getsubs):
     view = PDSSubjectView.as_view()
     url = reverse(
         'pds-subject-list',
         kwargs={
             'pk': 1
         })
     mock_getsubs.return_value = [Subject(
         id=2,
         first_name='John',
         last_name='Doe',
         organization_id=1,
         organization_subject_id='1234',
         dob=datetime.date(1990, 1, 1),
         modified=datetime.datetime(2015, 1, 1),
         created=datetime.datetime(2015, 1, 1)
     )]
     mock_errh.return_value = [{
         'success': True,
         'external_record': [TestExternalRecord]
     }]
     request = factory.get(url)
     force_authenticate(request, user=self.test_user)
     response = view(
         request,
         pk=self.test_pds.id
     )
     response.render()
     self.assertEqual(response.status_code, 200)
     self.assertEqual(len(response.data['subjects']), 1)
     self.assertEqual(response.data['count'], 1)
 def subjects(self, external_system_id, path=None, organization_id=None):
     '''
     Attempts to get subject records for subjects that have externalrecords on the specified externalsystem
     Inputs:
     external_system_id : int value of the externalsystem record id
     path (optional) : If specified, this will only return Subjects with externalrecords matching this path
     organization_id (optional) : int value of the organization. If specified, this will only return Subjects
                               belonging to this organization with externalrecords on the externalsystem
     Outputs:
     list of Subject objects
     If no records are found PageNotFound is raised '''
     ehb_service_path = self.root_path + 'id/' + str(external_system_id) + '/'
     if organization_id is None:
         ehb_service_path += 'subjects/'
     else:
         ehb_service_path += 'organization/' + str(organization_id) + '/subjects/'
     if path:
         ers = self.external_records(external_system_id, path=path, organization_id=organization_id)
     response = self.processGet(ehb_service_path)
     status = []
     for o in json.loads(response):
         s = Subject.identity_from_jsonObject(o)
         if path is None:
             status.append(s)
         else:
             for er in ers:
                 if er.subject_id == s.id and not status.__contains__(s):
                     status.append(s)
     if len(status) == 0:
         raise PageNotFound(ehb_service_path)
     else:
         return status
示例#6
0
    def test_create_and_delete_subject_on_protocol(self, screate_mock, gadd_mock, gcreate_mock, sget_mock, subject_group_mock):
        '''
        Ensure that we can create a subject on a Protocol
        '''
        subject = {
            'first_name': 'John',
            'last_name': 'Doe',
            'organization_subject_id': '1234',
            'organization': '1',
            'dob': '2000-01-01'
        }
        url = reverse(
            'protocol-subject-create',
            kwargs={
                'pk': self.test_protocol.id
            })
        token = Token.objects.get(user__username='******')
        client = APIClient()
        client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        # Mock subject not found
        sget_mock.side_effect = PageNotFound(path='/')
        # Mock subject group creation
        gcreate_mock.return_value = [{'success': True}]
        # Mock addition of subject to group
        gadd_mock.add_subjects.return_value = [{'success': True}]
        screate_mock.return_value = [{
            'success': True,
            'errors': [],
            'subject': Subject(
                id=2,
                first_name='John',
                last_name='Doe',
                organization_id=1,
                organization_subject_id='1234',
                dob=datetime.date(1990, 1, 1),
                modified=datetime.datetime(2015, 1, 1),
                created=datetime.datetime(2015, 1, 1)
            )
        }]
        subject_group_mock.return_value.id = "12345"

        response = client.post(url, subject, format='json')
        success, subject, errors = response.data
        if errors:
            print(errors)
        self.assertTrue(success)
        self.assertEqual(len(errors), 0)
        url = reverse(
            'protocol-subject-view',
            kwargs={
                'pk': self.test_protocol.id,
                'subject': subject['id']
            })
        response = client.delete(url)
示例#7
0
 def put(self, request, pk, subject, *args, **kwargs):
     subject_update = json.loads(request.body.decode('utf-8'))
     # See if subject exists
     try:
         ehb_sub = self.s_rh.get(id=subject)
         org = self.o_rh.get(id=subject_update['organization'])
         protocol = Protocol.objects.get(pk=pk)
         old_group_name = SubjectUtils.protocol_subject_record_group_name(
             protocol, ehb_sub)
         group = self.g_rh.get(name=old_group_name)
     except:
         return Response({'error': 'subject not found'}, status=404)
     ehb_sub.old_subject = deepcopy(ehb_sub)
     ehb_sub.first_name = subject_update['first_name']
     ehb_sub.last_name = subject_update['last_name']
     ehb_sub.organization_subject_id = subject_update[
         'organization_subject_id']
     ehb_sub.organization_id = org.id
     ehb_sub.dob = datetime.strptime(subject_update['dob'], '%Y-%m-%d')
     new_group_name = SubjectUtils.protocol_subject_record_group_name(
         protocol, ehb_sub)
     group.name = new_group_name
     group.client_key = protocol._settings_prop('CLIENT_KEY', 'key', '')
     group.current_client_key(group.client_key)
     update = self.s_rh.update(ehb_sub)[0]
     if update['errors']:
         return Response(json.dumps({'error': 'Unable to update subject'}),
                         status=400)
     # If the update is succesful, update the subject record group associated with this subject
     res = self.g_rh.update(group)[0]
     if not res['success']:
         return Response(json.dumps({'error': 'Unable to update group'}),
                         status=400)
     # If the update is succesful, update the cache.
     sub = json.loads(Subject.json_from_identity(update['subject']))
     sub['organization_name'] = org.name
     cache_key = 'protocol{0}_sub_data'.format(pk)
     cache_data = self.cache.get(cache_key)
     if cache_data:
         if 'external_ids' in list(subject_update.keys()):
             sub['external_ids'] = subject_update['external_ids']
         else:
             sub['external_ids'] = []
         sub['external_records'] = subject_update['external_records']
         sub['organization_name'] = org.name
         subjects = json.loads(cache_data)
         for i in range(0, len(subjects)):
             if subjects[i]['id'] == sub['id']:
                 subjects[i] = sub
         self.cache.set(cache_key, json.dumps(subjects))
         if hasattr(self.cache, 'persist'):
             self.cache.persist(cache_key)
     return Response(sub, headers={'Access-Control-Allow-Origin': '*'})
示例#8
0
 def put(self, request, pk, subject, *args, **kwargs):
     subject_update = json.loads(request.body.decode('utf-8'))
     # See if subject exists
     try:
         ehb_sub = self.s_rh.get(id=subject)
         org = self.o_rh.get(id=subject_update['organization'])
         protocol = Protocol.objects.get(pk=pk)
         old_group_name = SubjectUtils.protocol_subject_record_group_name(protocol, ehb_sub)
         group = self.g_rh.get(name=old_group_name)
     except:
         return Response({'error': 'subject not found'}, status=404)
     ehb_sub.old_subject = deepcopy(ehb_sub)
     ehb_sub.first_name = subject_update['first_name']
     ehb_sub.last_name = subject_update['last_name']
     ehb_sub.organization_subject_id = subject_update['organization_subject_id']
     ehb_sub.organization_id = org.id
     ehb_sub.dob = datetime.strptime(subject_update['dob'], '%Y-%m-%d')
     new_group_name = SubjectUtils.protocol_subject_record_group_name(protocol, ehb_sub)
     group.name = new_group_name
     group.client_key = protocol._settings_prop(
         'CLIENT_KEY', 'key', '')
     group.current_client_key(group.client_key)
     update = self.s_rh.update(ehb_sub)[0]
     if update['errors']:
         return Response(json.dumps({'error': 'Unable to update subject'}), status=400)
     # If the update is succesful, update the subject record group associated with this subject
     res = self.g_rh.update(group)[0]
     if not res['success']:
         return Response(json.dumps({'error': 'Unable to update group'}), status=400)
     # If the update is succesful, update the cache.
     sub = json.loads(Subject.json_from_identity(update['subject']))
     sub['organization_name'] = org.name
     cache_key = 'protocol{0}_sub_data'.format(pk)
     cache_data = self.cache.get(cache_key)
     if cache_data:
         if 'external_ids' in list(subject_update.keys()):
             sub['external_ids'] = subject_update['external_ids']
         else:
             sub['external_ids'] = []
         sub['external_records'] = subject_update['external_records']
         sub['organization_name'] = org.name
         subjects = json.loads(cache_data)
         for i in range(0, len(subjects)):
             if subjects[i]['id'] == sub['id']:
                 subjects[i] = sub
         self.cache.set(cache_key, json.dumps(subjects))
         if hasattr(self.cache, 'persist'):
             self.cache.persist(cache_key)
     return Response(
         sub,
         headers={'Access-Control-Allow-Origin': '*'}
     )
示例#9
0
def getProtocolSubjects(protocol):
    ck = '{0}_subjects'.format(protocol.id)
    resp = cache.get(ck)
    if resp:
        subs = [
            Subject(-1).identity_from_jsonObject(sub)
            for sub in json.loads(resp)
        ]
        return subs
    else:
        subs = protocol.getSubjects()
        if subs:
            cache_payload = [
                json.loads(subject.json_from_identity(subject))
                for subject in subs
            ]
            cache.set(ck, json.dumps(cache_payload))
        return subs
示例#10
0
    def get(self, request, pk, subject, *args, **kwargs):
        ''' get all subject data:
        external records, Organization, external ids and relationships'''
        # TODO: add getting relationships for subjects here
        try:
            p = Protocol.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'Protocol requested not found'},
                            status=404)

        if p.isUserAuthorized(request.user):
            protocoldatasources = p.getProtocolDataSources()
            manageExternalIDs = False
            for pds in protocoldatasources:
                if pds.driver == 3:
                    ExIdSource = pds
                    manageExternalIDs = True
            try:
                subject = self.s_rh.get(id=subject)
                organization = self.o_rh.get(id=subject.organization_id)
            except:
                return Response({'error': 'Subject not found'}, status=404)
            sub = json.loads(Subject.json_from_identity(subject))
            sub['organization_name'] = organization.name
            sub['external_records'] = []
            for pds in protocoldatasources:
                sub['external_records'].extend(
                    pds.getSubjectExternalRecords(sub))
            if manageExternalIDs:
                # Break out external ids into a separate object for ease of use
                sub['external_ids'] = []
                for record in sub['external_records']:
                    if record['external_system'] == 3:
                        sub['external_ids'].append(record)
            return Response(sub)
        else:
            return Response(
                {
                    "detail":
                    "You are not authorized to view subjects in this protocol"
                },
                status=403)
示例#11
0
    def getSubject(self, subjectId):
        cache_key = '{}_subjects'.format(self.protocol.id)
        cached = cache.get(cache_key)
        if cached:
            subs = json.loads(cached)
            for subject in subs:
                if subject['id'] == int(subjectId):
                    return Subject(-1).identity_from_jsonObject(subject)
        else:
            try:
                s_rh = ServiceClient.get_rh_for(record_type=ServiceClient.SUBJECT)
                subject = s_rh.get(id=subjectId)
                if not self.protocol.isSubjectOnProtocol(subject):
                    raise Http404
                else:
                    return subject
            except PageNotFound:
                raise Http404

        return None
示例#12
0
def getPDSSubject(pds, sub_id):
    ck = '{0}_subjects'.format(pds.protocol.id)
    resp = cache.get(ck)
    if resp:
        subs = json.loads(resp)
        for subject in subs:
            if subject['id'] == int(sub_id):
                return Subject(-1).identity_from_jsonObject(subject)
    else:
        try:
            s_rh = ServiceClient.get_rh_for(record_type=ServiceClient.SUBJECT)
            subject = s_rh.get(id=sub_id)
            if not pds.protocol.isSubjectOnProtocol(subject):
                raise Http404
            else:
                return subject
        except PageNotFound:
            raise Http404

    return None
示例#13
0
    def getSubject(self, subjectId):
        """Get a subject from the EHB by subject id.

        Raises Http404 if the subject is not found or is not part of the
        related protocol.
        """

        cache_key = '{}_subjects'.format(self.protocol.id)
        cached = cache.get(cache_key)

        if cached:

            subs = json.loads(cached)

            for subject in subs:
                if subject['id'] == int(subjectId):
                    return Subject(-1).identity_from_jsonObject(subject)

        else:

            try:

                s_rh = ServiceClient.get_rh_for(
                    record_type=ServiceClient.SUBJECT)

                subject = s_rh.get(id=subjectId)

                # If the subject is not in this protocol, raise an error.
                if not self.protocol.isSubjectOnProtocol(subject):
                    raise Http404

                else:
                    return subject

            except PageNotFound:
                raise Http404

        # TODO: Is this statement ever reached? If not, refactor for clarity.
        return None
示例#14
0
    def get(self, request, pk, subject, *args, **kwargs):
        ''' get subject '''
        try:
            p = Protocol.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'Protocol requested not found'}, status=404)

        if p.isUserAuthorized(request.user):
            protocoldatasources = p.getProtocolDataSources()
            manageExternalIDs = False
            for pds in protocoldatasources:
                if pds.driver == 3:
                    ExIdSource = pds
                    manageExternalIDs = True
            try:
                subject = self.s_rh.get(id=subject)
                organization = self.o_rh.get(id=subject.organization_id)
            except:
                return Response({'error': 'Subject not found'}, status=404)
            sub = json.loads(Subject.json_from_identity(subject))
            sub['organization_name'] = organization.name
            sub['external_records'] = []
            for pds in protocoldatasources:
                sub['external_records'].extend(pds.getSubjectExternalRecords(sub))
            if manageExternalIDs:
                # Break out external ids into a separate object for ease of use
                sub['external_ids'] = []
                for record in sub['external_records']:
                    if record['external_system'] == 3:
                        sub['external_ids'].append(record)
            return Response(sub)
        else:
            return Response(
                {"detail": "You are not authorized to view subjects in this protocol"},
                status=403
            )
示例#15
0
    def post(self, request, pk, *args, **kwargs):
        '''
        Add a subject to the protocol

        Expects a request body of the form:
        {
            "first_name": "John",
            "last_name": "Doe",
            "organization_subject_id": "123123123",
            "organization": "1",
            "dob": "2000-01-01"
        }
        '''
        try:
            protocol = Protocol.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'Protocol requested not found'}, status=404)

        subject = json.loads(request.body.decode('utf-8'))
        new_subject = Subject(
            first_name=subject['first_name'],
            last_name=subject['last_name'],
            organization_id=int(subject['organization']),
            organization_subject_id=subject['organization_subject_id'],
            dob=datetime.strptime(subject['dob'], '%Y-%m-%d')
        )
        try:
            org = self.o_rh.get(id=subject['organization'])
        except:
            return Response({'error': 'Invalid Organization Selected'}, status=400)

        errors = []
        try:
            subject = self.s_rh.get(
                organization_id=new_subject.organization_id,
                organization_subject_id=new_subject.organization_subject_id)
            success = True
            # If found this indicates the subject is already in the ehb for
            # this organization, but not necessarily for this protocol.
            # That will be checked below in the external record search
            prefix = "A subject with this " + org.subject_id_label + " exists but with "
            if subject.first_name != new_subject.first_name:
                success = False
                errors.append(prefix + "first name: " + subject.first_name)
            if subject.last_name != new_subject.last_name:
                success = False
                errors.append(prefix + "last name: " + subject.last_name)
            if subject.dob != new_subject.dob.date():
                success = False
                errors.append(prefix + "birth date: " + str(subject.dob))
        except PageNotFound:
            # Subject is not in the system so create it
            r = self.s_rh.create(new_subject)[0]
            success = r.get('success')
            errors = r.get('errors')
            subject = r.get(Subject.identityLabel)

        # Dont proceed if creation was not a success
        if not success:
            subject = json.loads(Subject.json_from_identity(subject))
            return Response([success, subject, errors], status=422)

        if not errors:
            errors = []
        # First check if the subject is already in the group.
        if protocol.getSubjects() and subject in protocol.getSubjects():
            # Subject is already in protocol
            errors.append(
                'This subject ' + org.subject_id_label +
                ' has already been added to this project.'
            )
            logger.error("Could not add subject. They already exist on this protocol.")
            success = False
        else:
            # Add this subject to the protocol and create external record group
            if self.subject_utils.create_protocol_subject_record_group(protocol, new_subject):
                if protocol.addSubject(subject):
                    success = True
                else:
                    # Could not add subject to project
                    errors.append(
                        'Failed to complete eHB transactions. Could not add subject to project. Please try again.')
                    success = False
            else:
                # For some reason we couldn't get the eHB to add the subject to the protocol group
                errors.append(
                    'Failed to complete eHB transactions. Could not add subject to project. Please try again.')
                success = False

        subject = json.loads(Subject.json_from_identity(subject))

        if not success:
            return Response(
                [success, subject, errors],
                headers={'Access-Control-Allow-Origin': '*'},
                status=400
            )
        # Add subject to cache
        cache_key = 'protocol{0}_sub_data'.format(protocol.id)
        cache_data = self.cache.get(cache_key)
        if cache_data:
            subject['external_ids'] = []
            subject['external_records'] = []
            subject['organization_name'] = org.name
            subjects = json.loads(cache_data)
            subjects.append(subject)
            self.cache.set(cache_key, json.dumps(subjects))
            if hasattr(self.cache, 'persist'):
                self.cache.persist(cache_key)
        return Response(
            [success, subject, errors],
            headers={'Access-Control-Allow-Origin': '*'},
            status=200
        )
示例#16
0
    def post(self, request, pk, *args, **kwargs):
        '''
        Add a subject to the protocol

        Expects a request body of the form:
        {
            "first_name": "John",
            "last_name": "Doe",
            "organization_subject_id": "123123123",
            "organization": "1",
            "dob": "2000-01-01"
        }
        '''
        try:
            protocol = Protocol.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'Protocol requested not found'},
                            status=404)

        subject = json.loads(request.body.decode('utf-8'))
        new_subject = Subject(
            first_name=subject['first_name'],
            last_name=subject['last_name'],
            organization_id=int(subject['organization']),
            organization_subject_id=subject['organization_subject_id'],
            dob=datetime.strptime(subject['dob'], '%Y-%m-%d'))
        try:
            org = self.o_rh.get(id=subject['organization'])
        except:
            return Response({'error': 'Invalid Organization Selected'},
                            status=400)

        errors = []
        try:
            subject = self.s_rh.get(
                organization_id=new_subject.organization_id,
                organization_subject_id=new_subject.organization_subject_id)
            success = True
            # If found this indicates the subject is already in the ehb for
            # this organization, but not necessarily for this protocol.
            # That will be checked below in the external record search
            prefix = "A subject with this " + org.subject_id_label + " exists but with "
            if subject.first_name != new_subject.first_name:
                success = False
                errors.append(prefix + "first name: " + subject.first_name)
            if subject.last_name != new_subject.last_name:
                success = False
                errors.append(prefix + "last name: " + subject.last_name)
            if subject.dob != new_subject.dob.date():
                success = False
                errors.append(prefix + "birth date: " + str(subject.dob))
        except PageNotFound:
            # Subject is not in the system so create it
            r = self.s_rh.create(new_subject)[0]
            success = r.get('success')
            errors = r.get('errors')
            subject = r.get(Subject.identityLabel)

        # Dont proceed if creation was not a success
        if not success:
            subject = json.loads(Subject.json_from_identity(subject))
            return Response([success, subject, errors], status=422)

        if not errors:
            errors = []
        # First check if the subject is already in the group.
        if protocol.getSubjects() and subject in protocol.getSubjects():
            # Subject is already in protocol
            errors.append('This subject ' + org.subject_id_label +
                          ' has already been added to this project.')
            logger.error(
                "Could not add subject. They already exist on this protocol.")
            success = False
        else:
            # Add this subject to the protocol and create external record group
            if self.subject_utils.create_protocol_subject_record_group(
                    protocol, new_subject):
                if protocol.addSubject(subject):
                    success = True
                else:
                    # Could not add subject to project
                    errors.append(
                        'Failed to complete eHB transactions. Could not add subject to project. Please try again.'
                    )
                    success = False
            else:
                # For some reason we couldn't get the eHB to add the subject to the protocol group
                errors.append(
                    'Failed to complete eHB transactions. Could not add subject to project. Please try again.'
                )
                success = False

        subject = json.loads(Subject.json_from_identity(subject))

        if not success:
            return Response([success, subject, errors],
                            headers={'Access-Control-Allow-Origin': '*'},
                            status=400)
        # Add subject to cache
        cache_key = 'protocol{0}_sub_data'.format(protocol.id)
        cache_data = self.cache.get(cache_key)
        if cache_data:
            subject['external_ids'] = []
            subject['external_records'] = []
            subject['organization_name'] = org.name
            subjects = json.loads(cache_data)
            subjects.append(subject)
            self.cache.set(cache_key, json.dumps(subjects))
            if hasattr(self.cache, 'persist'):
                self.cache.persist(cache_key)
        return Response([success, subject, errors],
                        headers={'Access-Control-Allow-Origin': '*'},
                        status=200)
示例#17
0
    def save(self, protocol):
        '''
        Attempts to save the data provided in the form as a new subject in
        ehb-service database.

        Output
        ------

        If the form is valid:
            {
                subject: Subject_instance,
                "success": boolean,
                "errors": errors
            }
            (Where errors is only present if there were errors in creating the
            object in the server db)

        else:
            None
        '''
        if self.is_valid():
            cleandata = self.cleaned_data
            sub_id = cleandata.get('subject_id')
            fn = cleandata.get('first_name')
            ln = cleandata.get('last_name')
            dob = cleandata.get('dob')
            org = self.getOrgFromSelection(cleandata.get('organization'))

            # Create the subject record for this organization
            # First check if the subject is in the system at all, if not create it
            srh = ServiceClient.get_rh_for(record_type=ServiceClient.SUBJECT)

            errors = []
            try:
                subject = srh.get(organization_id=org.id, organization_subject_id=sub_id)
                # If found this indicates the subject is already in the ehb for
                # this organization, but not necessarily for this protocol.
                # That will be checked below in the external record search

                # check if all new_subject form fields match this existing
                # subject if not, the form data must be corrected
                # should add an option to update the record (permission to do so might be role based)
                success = True
                prefix = "A subject with this " + org.subject_id_label + " exists but with "
                if subject.first_name != fn:
                    success = False
                    errors.append(prefix + "first name: " + subject.first_name)
                if subject.last_name != ln:
                    success = False
                    errors.append(prefix + "last name: " + subject.last_name)
                if subject.dob != dob:
                    success = False
                    errors.append(prefix + "birth date: " + str(subject.dob))
            except PageNotFound:
                # Subject not in system so create it
                s = Subject(first_name=fn,
                            last_name=ln,
                            dob=dob,
                            organization_id=org.id,
                            organization_subject_id=sub_id)
                r = srh.create(s)[0]
                success = r.get('success')
                errors = r.get('errors')
                subject = r.get(Subject.identityLabel)

            # Don't proceed any further if there are already errors
            if not success:
                logger.error('There was an error creating the subject.')
                return [success, subject, errors]

            if not errors:
                errors = []
            # First check if the subject is already in the group
            if protocol.getSubjects() and subject in protocol.getSubjects():
                # Subject is already on this protocol
                errors.append(
                    'This subject ' + org.subject_id_label +
                    ' has already been added to this project.'
                )
                logger.error("Could not add subject. They already exist on this protocol.")
                success = False
            else:
                # Add this subject to the protocol and create external record group
                # Create subject/protocol external record group
                if SubjectUtils.create_protocol_subject_record_group(protocol, subject):
                    # Add subject to protocol subject group
                    if protocol.addSubject(subject):
                        success = True
                    else:
                        logger.error("Could not add subject. Failure to create Protocol Subject Record Group.")
                        errors.append(
                            'Failed to complete eHB transactions. Could not add subject to project. Please try again.')
                        success = False
                else:
                    # For some reason we couldn't get the eHB to add the subject to the protocol group
                    logger.error("Could not add subject to project. Could not add subject to the protocol group.")
                    errors.append(
                        'Failed to complete eHB transactions. Could not add subject to project. Please try again.')
                    success = False

            return [success, subject, errors]
        else:
            return None
示例#18
0
    def post(self, request, pk, *args, **kwargs):
        '''
        Add a subject to the protocol

        Expects a request body of the form:
        {
            "last_name": "John",
            "last_name": "Doe",
            "organization_subject_id": "123123123",
            "organization": "1",
            "dob": "2000-01-01"
        }
        '''
        try:
            protocol = Protocol.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'Protocol requested not found'},
                            status=404)
        subject = request.data
        new_subject = Subject(
            first_name=subject['first_name'],
            last_name=subject['last_name'],
            organization_id=int(subject['organization']),
            organization_subject_id=subject['organization_subject_id'],
            dob=datetime.strptime(subject['dob'], '%Y-%m-%d'))
        try:
            org = self.o_rh.get(id=subject['organization'])
        except:
            return Response({'error': 'Invalid Organization Selected'},
                            status=400)
        errors = []
        try:
            subject = self.s_rh.get(
                organization_id=new_subject.organization_id,
                organization_subject_id=new_subject.organization_subject_id)
            success = True
            # If found this indicates the subject is already in the ehb for
            # this organization, but not necessarily for this protocol.
            # That will be checked below in the external record search
            prefix = "A subject with this " + org.subject_id_label + " exists but with "
            if subject.first_name != new_subject.first_name:
                success = False
                errors.append(prefix + "first name: " + subject.first_name)
            if subject.last_name != new_subject.last_name:
                success = False
                errors.append(prefix + "last name: " + subject.last_name)
            if subject.dob != new_subject.dob.date():
                success = False
                errors.append(prefix + "birth date: " + str(subject.dob))
        except PageNotFound:
            # Subject is not in the system so create it
            r = self.s_rh.create(new_subject)[0]
            success = r.get('success')
            errors = r.get('errors')
            subject = r.get(Subject.identityLabel)
        # Dont proceed if creation was not a success
        if not success:
            subject = json.loads(Subject.json_from_identity(subject))
            return Response([success, subject, errors], status=422)

        if not errors:
            errors = []
            # Add this subject to the protocol and create external record group
            if self.subject_utils.create_protocol_subject_record_group(
                    protocol, new_subject):
                if protocol.addSubject(subject):
                    success = True
                    # add this action to the user audit
                    user_audit_payload = [{
                        'subject':
                        subject.id,
                        'change_type':
                        "SubjectGroup",
                        'change_type_ehb_pk':
                        protocol._subject_group().id,
                        'change_action':
                        "Add",
                        'user_name':
                        request.user.username,
                        'protocol_id':
                        protocol.id
                    }]
                    ServiceClient.user_audit(user_audit_payload)
                else:
                    # Could not add subject to project
                    errors.append(
                        'Failed to complete eHB transactions. Could not add subject to project. Please try again.'
                    )
                    success = False
            else:
                # For some reason we couldn't get the eHB to add the subject to the protocol group
                subjects = protocol.getSubjects()
                if subjects and subject in subjects:
                    # Subject is already in protocol
                    errors.append('This subject ' + org.subject_id_label +
                                  ' has already been added to this project.')
                    logger.error(
                        "Could not add subject. They already exist on this protocol."
                    )
                    success = False
                else:
                    errors.append(
                        'Failed to complete eHB transactions. Could not add subject to project. Please try again.'
                    )
                    success = False
        subject = json.loads(Subject.json_from_identity(subject))
        subject['organization_name'] = org.name

        if not success:
            return Response([success, subject, errors],
                            headers={'Access-Control-Allow-Origin': '*'},
                            status=400)
        # Add subject to cache
        self.update_subject_cache(protocol.id, subject, True)
        return Response([success, subject, errors],
                        headers={'Access-Control-Allow-Origin': '*'},
                        status=200)
示例#19
0
from ehb_client.requests.external_record_request_handler import ExternalRecord
from ehb_client.requests.group_request_handler import Group
from ehb_client.requests.exceptions import PageNotFound
from ..models.protocols import Protocol, ProtocolDataSource
from ..views.protocol import ProtocolViewSet, ProtocolDataSourceView, \
    ProtocolOrganizationView, ProtocolSubjectsView, ProtocolSubjectDetailView
from ..views import PDSViewSet, PDSSubjectView, PDSSubjectRecordsView, \
    PDSSubjectRecordDetailView, PDSRecordLinkDetailView, PDSAvailableLinksView
from api.views.base import BRPApiView

factory = APIRequestFactory()

TestSubject = Subject(id=2,
                      first_name='Jane',
                      last_name='Sample',
                      organization_id=1,
                      organization_subject_id='MRN123',
                      dob=datetime.date(1990, 1, 1),
                      modified=datetime.datetime(2015, 1, 1),
                      created=datetime.datetime(2015, 1, 1))
TestOrganization = Organization(id=1,
                                name='Amazing Children\'s Hospital',
                                subject_id_label='Subject',
                                modified=datetime.datetime(2015, 1, 1),
                                created=datetime.datetime(2015, 1, 1))
TestExternalRecord = ExternalRecord(record_id='xyz123',
                                    external_system_id=1,
                                    subject_id=1,
                                    path='testpath',
                                    modified=datetime.datetime(2014, 1, 1),
                                    created=datetime.datetime(2014, 1, 1),
                                    id=1,