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 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': '*'})
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': '*'} )
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)
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)
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 )
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 )
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)
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)