예제 #1
0
    def post(self, request, pk, subject, record, *args, **kwargs):
        '''Create a link between two subject records in the eHB
        '''
        try:
            pds = ProtocolDataSource.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response(
                {'error': 'ProtocolDatasource requested not found'},
                status=404)

        if pds.protocol.isUserAuthorized(request.user):
            data = request.data
            primary_rec = data['primaryRecord']
            secondary_rec = data['secondaryRecord']
            link_type = data['linkType']
            # Serialize
            primary_rec = ExternalRecord.identity_from_json(
                json.dumps(primary_rec))
            secondary_rec = ExternalRecord.identity_from_json(
                json.dumps(secondary_rec))
            res = self.er_rh.link(primary_rec, secondary_rec, link_type)
            if res['success']:
                return Response(res)
            else:
                return Response({
                    'success': False,
                    'error': res['error']
                },
                                status=422)
            return Response({
                'success': False,
                'error': 'Unknown Error'
            },
                            status=422)
예제 #2
0
    def create_new_ehb_external_record(protocol_data_source,
                                       user,
                                       subject,
                                       record_id,
                                       label=None):
        """Create a new external record for this PDS/subject in the EHB.

        Creates a new external record in the ehb-service for this data source,
        subject and record_id, using the credentials of the given user and the
        label, if given.

        Returns:
            If successful, returns the new ExternalRecord object.

        Raises:
            RecordCreationError: If the creation request response has errors or
                an Exception is raised during operation.
        """

        es = protocol_data_source.data_source.getExternalSystem()

        # Want to make sure we're not going to overwrite a record already in
        # the system
        try:

            if not label:
                label = 1

            er = ExternalRecord(record_id=record_id,
                                subject_id=subject['id'],
                                external_system_id=es.id,
                                path=protocol_data_source.path,
                                label_id=label)

            errh = ServiceClient.get_rh_for(
                record_type=ServiceClient.EXTERNAL_RECORD)

            response = errh.create(er)[0]

            if (response.get('success')):

                SubjectUtils.add_record_to_subject_record_group(
                    protocol_data_source.protocol, subject, er)

                return er

            else:

                errors = response.get('errors')

                raise RecordCreationError('electronic Honest Broker', '',
                                          record_id, errors)

        except RecordCreationError as rce:
            raise rce

        except Exception as e:

            raise RecordCreationError('electronic Honest Broker', '',
                                      record_id, str(e))
예제 #3
0
def getExternalIdentifiers(pds, subject, labels):
    er_rh = ServiceClient.get_rh_for(record_type=ServiceClient.EXTERNAL_RECORD)
    ck = '{0}_{1}_externalrecords'.format(pds.protocol.id, subject.id)
    # See if our records are in the cache.
    resp = cache.get(ck)
    if resp:
        pds_records = []
        for record in json.loads(resp):
            if record['external_system'] == pds.id:
                pds_records.append(
                    ExternalRecord(-1).identity_from_jsonObject(record))
    else:
        try:
            pds_records = er_rh.get(external_system_url=pds.data_source.url,
                                    path=pds.path,
                                    subject_id=subject.id)
        except PageNotFound:
            pds_records = []

    for ex_rec in pds_records:
        for label in labels:
            if ex_rec.label_id == label['id']:
                if label['label'] == '':
                    ex_rec.label_desc = 'Record'
                else:
                    ex_rec.label_desc = label['label']
    return pds_records
def test_json_from_identity_no_label():
    ExRecObject = 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,
        label_id=None,
    )
    json_string = ExRecObject.json_from_identity(ExRecObject)
    assert isinstance(json_string, str)
    ex_rec = json.loads(json_string)
    assert isinstance(ex_rec, dict)
    assert ex_rec["id"] == 1
예제 #5
0
    def create_new_ehb_external_record(protocol_data_source, user, subject, record_id, label=None):
        '''
        Creates a new external record in the ehb-service for this data source,
        subject, record_id and

        Output
        ------
        If successful returns the

        ehb_client.external_record_request_handler.ExternalRecord object
        '''

        es = protocol_data_source.data_source.getExternalSystem()

        # Want to make sure we're not going to overwrite a record already in the system
        try:
            if not label:
                label = 1
            er = ExternalRecord(
                record_id=record_id,
                subject_id=subject.id,
                external_system_id=es.id,
                path=protocol_data_source.path,
                label_id=label
            )
            errh = ServiceClient.get_rh_for(
                record_type=ServiceClient.EXTERNAL_RECORD
            )
            response = errh.create(er)[0]
            if(response.get('success')):
                SubjectUtils.add_record_to_subject_record_group(
                    protocol_data_source.protocol,
                    subject,
                    er
                )
                return er
            else:
                errors = response.get('errors')
                raise RecordCreationError(
                    'electronic Honest Broker',
                    '',
                    record_id,
                    errors
                )
        except RecordCreationError as rce:
            raise rce
        except Exception as e:
            raise RecordCreationError(
                'electronic Honest Broker',
                '',
                record_id,
                str(e)
            )
예제 #6
0
    def post(self, request, pk, subject, record, *args, **kwargs):
        '''Create a link between two subject records in the eHB
        '''
        try:
            pds = ProtocolDataSource.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'ProtocolDatasource requested not found'}, status=404)

        if pds.protocol.isUserAuthorized(request.user):
            data = json.loads(request.body.decode('utf-8'))
            primary_rec = data['primaryRecord']
            secondary_rec = data['secondaryRecord']
            link_type = data['linkType']
            # Serialize
            primary_rec = ExternalRecord.identity_from_json(json.dumps(primary_rec))
            secondary_rec = ExternalRecord.identity_from_json(json.dumps(secondary_rec))
            res = self.er_rh.link(primary_rec, secondary_rec, link_type)
            if res['success']:
                return Response(res)
            else:
                return Response({'success': False, 'error': res['error']}, status=422)
            return Response({'success': False, 'error': 'Unknown Error'}, status=422)
예제 #7
0
    def delete(self, request, pk, subject, record, *args, **kwargs):
        '''Delete a link between two subject records in the eHB
        '''
        try:
            pds = ProtocolDataSource.objects.get(pk=pk)
        except ObjectDoesNotExist:
            return Response({'error': 'ProtocolDatasource requested not found'}, status=404)

        if pds.protocol.isUserAuthorized(request.user):
            data = json.loads(request.body.decode('utf-8'))
            primary_rec = data['primaryRecord']
            link_id = data['linkId']
            # Serialize
            primary_rec = ExternalRecord.identity_from_json(json.dumps(primary_rec))
            res = self.er_rh.unlink(primary_rec, link_id)
            if res['success']:
                return Response(res)
            return Response({'success': False}, status=422)
 def external_records(self, external_system_id, path=None, organization_id=None, subject_id=None):
     '''
     Attempts to get all externalRecord information for the specified externalsystem
     Inputs:
     external_system_id : int value of the externalsystem record id
     path (optional) If specified, this will only return records with this path
     organization_id (optional) : int value of the organization. If specified, this will only return ExternalRecords
                               whose Subject belongs to this organization
     subject_id (optional) : int value of the subject ehb id. If specified this will only return ExternalRecords
                             belonging to this subject
     Outputs:
     list of ExternalRecord 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 += 'records/'
     else:
         ehb_service_path += 'organization/' + str(organization_id) + '/records/'
     response = self.processGet(ehb_service_path)
     status = []
     for o in json.loads(response):
         er = ExternalRecord.identity_from_jsonObject(o)
         if path and subject_id:
             if er.subject_id == subject_id and er.path == path:
                     status.append(er)
         elif path:
             if er.path == path:
                 status.append(er)
         elif subject_id:
             if er.subject_id == subject_id:
                 status.append(er)
         else:
             status.append(er)
     if len(status) == 0:
         raise PageNotFound(ehb_service_path)
     else:
         return status
예제 #9
0
def pds_dataentry_form(request, pds_id, subject_id, form_spec, record_id):
    '''renders a page with a data form as generated by the driver for protocol_data_source with pk=pds_id for
    Subject with subject_id=subject_id. The specific data form is determined by the driver using the form_spec arg.
    '''
    def generateSubRecordForm(driver, external_record, form_spec,
                              attempt_count, max_attempts):
        try:
            key = 'subrecordform_{0}_{1}'.format(external_record.id, form_spec)
            # Caching turned off for the time being on SRF
            # cf = cache.get(key)
            cf = None
            if cf:
                return cf
            else:
                form = driver.subRecordForm(external_record=external_record,
                                            form_spec=form_spec,
                                            session=request.session)
            return form
        except RecordDoesNotExist:
            return None

    pds = getProtocolDataSource(pds_id)
    if not pds.protocol.isUserAuthorized(request.user):
        return forbidden(request)

    MANAGE_EXTERNAL_IDS = False
    er_label_rh = ServiceClient.get_rh_for(
        record_type=ServiceClient.EXTERNAL_RECORD_LABEL)
    lbls = er_label_rh.query()

    # Check to see if this PDS is managing external identifiers
    for _pds in pds.protocol.getProtocolDataSources():
        if _pds.driver == 3:
            ExIdSource = _pds
            MANAGE_EXTERNAL_IDS = True

    subject = getPDSSubject(pds=pds, sub_id=subject_id)

    # If we are managing external identifiers add them to the subject
    if MANAGE_EXTERNAL_IDS:
        subject.external_ids = getExternalIdentifiers(ExIdSource, subject,
                                                      lbls)

    er_rh = ServiceClient.get_rh_for(record_type=ServiceClient.EXTERNAL_RECORD)
    # this will be the ehb-service externalRecord for this pds, subject NOT the actual datasource record
    record = None
    error_msgs = []

    try:
        r = cache.get('externalrecord_{0}'.format(record_id))
        if r:
            record = ExternalRecord(1).identity_from_jsonObject(json.loads(r))
        else:
            record = er_rh.get(id=record_id)
    except PageNotFound:
        raise Http404

    try:
        driver = DriverUtils.getDriverFor(protocol_data_source=pds,
                                          user=request.user)
        # Need the external record for this pds, protcol, and subject
        # Get all external_record objects on the ehb-service for this system,
        # path, subject combination.
        if request.method == 'POST':
            # have the driver process this request
            key = 'subrecordform_{0}_{1}'.format(record.id, form_spec)
            # cache.delete(key)
            errors = driver.processForm(request=request,
                                        external_record=record,
                                        form_spec=form_spec,
                                        session=request.session)
            if errors:
                error_msgs = [e for e in errors]
            else:
                path = '%s/dataentry/protocoldatasource/%s/subject/%s/record/%s/start/' % (
                    ServiceClient.self_root_path, pds.id, subject_id,
                    record_id)
                return HttpResponseRedirect(path)
        else:
            # Generate a new form
            form = generateSubRecordForm(driver, record, form_spec, 0, 1)
            if form:
                o_rh = ServiceClient.get_rh_for(
                    record_type=ServiceClient.ORGANIZATION)
                org = o_rh.get(id=subject.organization_id)
                form_submission_url = '%s/dataentry/protocoldatasource/%s/subject/%s/record/%s/form_spec/%s/' % (
                    ServiceClient.self_root_path, pds.id, subject_id,
                    record_id, form_spec)
                # Find next form to support guided entry
                try:
                    forms = json.loads(pds.driver_configuration)['form_order']
                    current_index = forms.index(form_spec)
                    next_form = forms[current_index + 1]
                    next_form_url = '%s/dataentry/protocoldatasource/%s/subject/%s/record/%s/form_spec/%s/' % (
                        ServiceClient.self_root_path, pds.id, subject_id,
                        record_id, next_form)
                except:
                    next_form_url = ''
                context = {
                    'subRecordForm': form,
                    'protocol': pds.protocol,
                    'organization': org,
                    'subject': subject,
                    'root_path': ServiceClient.self_root_path,
                    'pds': pds,
                    'form_submission_url': form_submission_url,
                    'next_form_url': next_form_url,
                    'rec_id': str(record_id),
                    'redcap_status': getRedcapStatus()
                }

                return render_to_response(
                    'pds_dataentry_srf.html',
                    context,
                    context_instance=RequestContext(request))
            else:
                error_msgs.append(
                    'No record exists in the data source with the record id supplied by the eHB.'
                )
                log.error('Error {0}'.format(' '.join(error_msgs)))
    except PageNotFound:
        error_msgs.append(
            'No record could be found in the eHB for this request')
        log.error('Error {0}'.format(' '.join(error_msgs)))
    except ProtocolUserCredentials.DoesNotExist:
        error_msgs.append(
            'Your user credentials were not found for %s. Please contact system administrator.'
            % pds.data_source.name)

    # Some error must have occured:
    log.error('Error {0}'.format(' '.join(error_msgs)))
    return HttpResponse(' '.join(error_msgs))
예제 #10
0
                      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,
                                    label_id=1)
TestGroup = Group(id=1,
                  name='TestGroup',
                  is_locking=False,
                  client_key='testck',
                  description='A test group')

BRPApiView.s_rh.get = MagicMock(return_value=TestSubject)
BRPApiView.s_rh.update = MagicMock(return_value=[{
    'success': True,
    'errors': [],
    'subject': TestSubject
}])