Ejemplo n.º 1
0
    def create_external_system_record(self, request, driver, pds, subject, record_id=None, label=None):

        def rec_id_validator(new_record_id):
            return SubjectUtils.validate_new_record_id(
                pds, subject, new_record_id)

        grp = SubjectUtils.get_protocol_subject_record_group(pds.protocol, subject)
        if grp:
            rec_id_prefix = grp.ehb_key
        else:
            request.META['action'] = 'No subject record group found'
            request.META['error'] = True
            raise Exception('No subject record group found')
        rec_id = None

        if record_id:
            if record_id.startswith(rec_id_prefix):
                rec_id = driver.create(
                    record_id_prefix=None, record_id=record_id, record_id_validator=rec_id_validator)
            else:
                rec_id = driver.create(
                    record_id_prefix=rec_id_prefix, record_id=record_id)
        else:
            rec_id = driver.create(
                record_id_prefix=rec_id_prefix, record_id_validator=rec_id_validator)

        er = SubjectUtils.create_new_ehb_external_record(
            pds, request.user, subject, rec_id, label)
        return er.id
Ejemplo n.º 2
0
    def create_external_system_record(self, request, driver, pds, subject, record_id=None, label=None):

        def rec_id_validator(new_record_id):
            return SubjectUtils.validate_new_record_id(
                pds, subject, new_record_id)

        grp = SubjectUtils.get_protocol_subject_record_group(pds.protocol, subject)
        if grp:
            rec_id_prefix = grp.ehb_key
        else:
            request.META['action'] = 'No subject record group found'
            request.META['error'] = True
            raise Exception('No subject record group found')
        rec_id = None

        if record_id:
            if record_id.startswith(rec_id_prefix):
                rec_id = driver.create(
                    record_id_prefix=None, record_id=record_id, record_id_validator=rec_id_validator)
            else:
                rec_id = driver.create(
                    record_id_prefix=rec_id_prefix, record_id=record_id)
        else:
            rec_id = driver.create(
                record_id_prefix=rec_id_prefix, record_id_validator=rec_id_validator)

        er = SubjectUtils.create_new_ehb_external_record(
            pds, request.user, subject, rec_id, label)
        return er.id
Ejemplo n.º 3
0
    def handle(self, *args, **options):

        if options['protocol']:
            if options['continue']:
                protocols = Protocol.objects.filter(
                    id__gte=options['protocol']).order_by('id').all()
            else:
                try:
                    protocols = Protocol.objects.filter(
                        id=options['protocol']).all()
                except Protocol.DoesNotExist:
                    print('Protocol specified does not exist')
                    return
        else:
            protocols = Protocol.objects.order_by('id').all()
        g_rh = ServiceClient.get_rh_for(record_type=ServiceClient.GROUP)
        errors = []
        msg = None
        for protocol in protocols:
            print('Checking {0} (ID:{1}) Group: {2}'.format(
                protocol.name, protocol.id, protocol.ehb_group_name()))
            try:
                g_rh.get(name=protocol.ehb_group_name())
            except RequestedRangeNotSatisfiable:
                msg = ('Unable to find expected group: {0}'.format(
                    protocol.ehb_group_name()))
                errors.append(msg)
                print(msg)
                msg = None
            # Check for pds groups
            subjects = protocol.getSubjects()
            if subjects:
                for subject in subjects:
                    try:
                        SubjectUtils.get_protocol_subject_record_group(
                            protocol, subject)
                    except RequestedRangeNotSatisfiable as e:
                        msg = (
                            'Warning: Group not found under Protocol: {0} Group name expected: {1}'
                            .format(protocol.name, e.errmsg))
                    except Organization.DoesNotExist:
                        msg = (
                            'Warning: Could not find associated Organization for protocol: {0}, eHB Org ID: {1} Likely eHB/BRP organizaiton mismatch'
                            .format(protocol.name, subject.organization_id))

                    except BadStatusLine:
                        msg = (
                            'Warning: Malformed Group Detected for Protocol: {0} Subject ID: {1} Likely Bad Organization ID'
                            .format(protocol.name, subject.id))
                    if msg:
                        errors.append(msg)
                        print(msg)
                        msg = None

        if csv:
            with open('group_report_{0}.csv'.format(
                    datetime.now().strftime('%Y%m%d.%H:%M.%S')),
                      'w',
                      newline='') as csvfile:
                csv_writer = csv.writer(csvfile,
                                        delimiter=' ',
                                        quotechar='"',
                                        quoting=csv.QUOTE_MINIMAL)
                for error in errors:
                    csv_writer.writerow([error])
Ejemplo n.º 4
0
    def post(self, request, **kwargs):
        context = self.get_context_data(**kwargs)

        def rec_id_validator(new_record_id, include_path):
            return SubjectUtils.validate_new_record_id(context['pds'],
                                                       context['subject'],
                                                       new_record_id,
                                                       include_path)

        try:
            grp = SubjectUtils.get_protocol_subject_record_group(
                self.pds.protocol, self.subject)
            grp.client_key = self.pds.protocol._settings_prop(
                'CLIENT_KEY', 'key', '')
            rec_id_prefix = ''

            label_id = request.POST.get('label_id', 1)
            if grp:
                rec_id_prefix = grp.ehb_key
            else:
                request.META[
                    'action'] = 'Subject record group not found for {0}'.format(
                        context['subject'].id)
                request.META['error'] = True
                raise Exception('No subject record group found')
            # Try to process the new record form
            try:
                rec_id = self.driver.process_new_record_form(
                    request=request,
                    record_id_prefix=rec_id_prefix,
                    record_id_validator=rec_id_validator)
                # If we have successfully created the record. Make sure it is in the eHB.
                try:
                    self.record_id = SubjectUtils.create_new_ehb_external_record(
                        self.pds, request.user, self.subject, rec_id,
                        label_id).id
                    if self.check_cache():
                        self.update_cache()
                    return HttpResponseRedirect(self.start_path)
                except RecordCreationError as rce:  # exception from the eHB
                    request.META['action'] = rce.errmsg
                    request.META['error'] = True
                    context['errors'].append(
                        ('The record could not be created on the '
                         'electronic Honest Broker. Please contact a '
                         'system administrator. There could be a '
                         'connection problem.'))
            except IgnoreEhbExceptions as iee:
                # TODO this is a hack until BRP can create Nautilus records
                rec_id = iee.record_id
                ehb_rec_id = ''
                try:
                    # this will create the ehb external_record entry
                    # and add that record to the subject's record group
                    self.record_id = SubjectUtils.create_new_ehb_external_record(
                        self.pds, request.user, self.subject, rec_id,
                        label_id).id

                    if self.check_cache():
                        self.update_cache()
                    self.start_path = '{0}/dataentry/protocoldatasource/{1}/subject/{2}/record/{3}/start/'.format(
                        self.service_client.self_root_path, self.pds.id,
                        self.subject.id, self.record_id)
                    return HttpResponseRedirect(self.start_path)

                except RecordCreationError as rce:  # exception from the eHB
                    request.META['action'] = rce.errmsg
                    request.META['error'] = True
                    record_already_exists = 6
                    cause = rce.raw_cause
                    if cause and len(
                            cause) == 1 and record_already_exists == cause[0]:
                        er_rh = ServiceClient.get_rh_for(
                            record_type=ServiceClient.EXTERNAL_RECORD)
                        ehb_recs = er_rh.get(
                            external_system_url=self.pds.data_source.url,
                            subject_id=self.subject.id,
                            path=self.pds.path)
                        ehb_rec_id = None
                        for record in ehb_recs:
                            if record.record_id == rec_id:
                                ehb_rec_id = record.id
                        if ehb_rec_id:
                            self.start_path = '%s/dataentry/protocoldatasource/%s/subject/%s/record/%s/start' % (
                                ServiceClient.self_root_path, self.pds.id,
                                self.subject.id, ehb_rec_id)
                        else:
                            context['errors'].append(
                                'This ID has already been assigned to another subject.'
                            )
                            return render_to_response(
                                'pds_dataentry_rec_create.html',
                                context,
                                context_instance=RequestContext(request))
                    else:
                        request.META['action'] = 'Record could not be created'
                        request.META['error'] = True
                        context['errors'].append(
                            ('The record could not be created on the '
                             'electronic Honest Broker. Please contact '
                             'a system administrator. There could be a'
                             ' connection problem.'))
                except:
                    return HttpResponse('Unknown Error')
                return HttpResponseRedirect(self.start_path)

        except RecordCreationError as rce:
            # Handle errors in the form.
            request.META['action'] = rce.errmsg
            request.META['error'] = True
            context['errors'].append(rce.cause)
            return render_to_response('pds_dataentry_rec_create.html',
                                      context,
                                      context_instance=RequestContext(request))
Ejemplo n.º 5
0
    def post(self, request, **kwargs):
        context = self.get_context_data(**kwargs)

        def rec_id_validator(new_record_id, include_path):
            return SubjectUtils.validate_new_record_id(
                context['pds'], context['subject'], new_record_id, include_path)

        try:
            grp = SubjectUtils.get_protocol_subject_record_group(
                self.pds.protocol, self.subject)
            grp.client_key = self.pds.protocol._settings_prop(
                'CLIENT_KEY', 'key', '')
            rec_id_prefix = ''

            label_id = request.POST.get('label_id', 1)
            if grp:
                rec_id_prefix = grp.ehb_key
            else:
                request.META['action'] = 'Subject record group not found for {0}'.format(context['subject'].id)
                request.META['error'] = True
                raise Exception('No subject record group found')
            # Try to process the new record form
            try:
                rec_id = self.driver.process_new_record_form(
                    request=request,
                    record_id_prefix=rec_id_prefix,
                    record_id_validator=rec_id_validator
                )
                # If we have successfully created the record. Make sure it is in the eHB.
                try:
                    self.record_id = SubjectUtils.create_new_ehb_external_record(
                        self.pds, request.user, self.subject, rec_id, label_id).id
                    if self.check_cache():
                        self.update_cache()
                    return HttpResponseRedirect(self.start_path)
                except RecordCreationError as rce:  # exception from the eHB
                    request.META['action'] = rce.errmsg
                    request.META['error'] = True
                    context['errors'].append((
                        'The record could not be created on the '
                        'electronic Honest Broker. Please contact a '
                        'system administrator. There could be a '
                        'connection problem.'))
            except IgnoreEhbExceptions as iee:
                # TODO this is a hack until BRP can create Nautilus records
                rec_id = iee.record_id
                ehb_rec_id = ''
                try:
                    # this will create the ehb external_record entry
                    # and add that record to the subject's record group
                    self.record_id = SubjectUtils.create_new_ehb_external_record(
                        self.pds, request.user, self.subject, rec_id, label_id).id

                    if self.check_cache():
                        self.update_cache()
                    self.start_path = '{0}/dataentry/protocoldatasource/{1}/subject/{2}/record/{3}/start/'.format(
                        self.service_client.self_root_path,
                        self.pds.id,
                        self.subject.id,
                        self.record_id)
                    return HttpResponseRedirect(self.start_path)

                except RecordCreationError as rce:  # exception from the eHB
                    request.META['action'] = rce.errmsg
                    request.META['error'] = True
                    record_already_exists = 6
                    cause = rce.raw_cause
                    if cause and len(cause) == 1 and record_already_exists == cause[0]:
                        er_rh = ServiceClient.get_rh_for(
                            record_type=ServiceClient.EXTERNAL_RECORD)
                        ehb_recs = er_rh.get(
                            external_system_url=self.pds.data_source.url, subject_id=self.subject.id, path=self.pds.path)
                        ehb_rec_id = None
                        for record in ehb_recs:
                            if record.record_id == rec_id:
                                ehb_rec_id = record.id
                        if ehb_rec_id:
                            self.start_path = '%s/dataentry/protocoldatasource/%s/subject/%s/record/%s/start' % (
                                ServiceClient.self_root_path,
                                self.pds.id,
                                self.subject.id,
                                ehb_rec_id)
                        else:
                            context['errors'].append(
                                'This ID has already been assigned to another subject.')
                            return render_to_response(
                                'pds_dataentry_rec_create.html',
                                context,
                                context_instance=RequestContext(request)
                            )
                    else:
                        request.META['action'] = 'Record could not be created'
                        request.META['error'] = True
                        context['errors'].append((
                            'The record could not be created on the '
                            'electronic Honest Broker. Please contact '
                            'a system administrator. There could be a'
                            ' connection problem.'))
                except:
                    return HttpResponse('Unknown Error')
                return HttpResponseRedirect(self.start_path)

        except RecordCreationError as rce:
            # Handle errors in the form.
            request.META['action'] = rce.errmsg
            request.META['error'] = True
            context['errors'].append(rce.cause)
            return render_to_response(
                'pds_dataentry_rec_create.html',
                context,
                context_instance=RequestContext(request)
            )
Ejemplo n.º 6
0
    def handle(self, *args, **options):

        if options['protocol']:
            if options['continue']:
                protocols = Protocol.objects.filter(id__gte=options['protocol']).order_by('id').all()
            else:
                try:
                    protocols = Protocol.objects.filter(id=options['protocol']).all()
                except Protocol.DoesNotExist:
                    print('Protocol specified does not exist')
                    return
        else:
            protocols = Protocol.objects.order_by('id').all()
        g_rh = ServiceClient.get_rh_for(record_type=ServiceClient.GROUP)
        errors = []
        msg = None
        for protocol in protocols:
            print('Checking {0} (ID:{1}) Group: {2}'.format(
                protocol.name,
                protocol.id,
                protocol.ehb_group_name()))
            try:
                g_rh.get(name=protocol.ehb_group_name())
            except RequestedRangeNotSatisfiable:
                msg = ('Unable to find expected group: {0}'.format(protocol.ehb_group_name()))
                errors.append(msg)
                print(msg)
                msg = None
            # Check for pds groups
            subjects = protocol.getSubjects()
            if subjects:
                for subject in subjects:
                    try:
                        SubjectUtils.get_protocol_subject_record_group(protocol, subject)
                    except RequestedRangeNotSatisfiable as e:
                        msg = ('Warning: Group not found under Protocol: {0} Group name expected: {1}'.format(
                            protocol.name,
                            e.errmsg
                        ))
                    except Organization.DoesNotExist:
                        msg = ('Warning: Could not find associated Organization for protocol: {0}, eHB Org ID: {1} Likely eHB/BRP organizaiton mismatch'.format(
                            protocol.name,
                            subject.organization_id
                        ))

                    except BadStatusLine:
                        msg = ('Warning: Malformed Group Detected for Protocol: {0} Subject ID: {1} Likely Bad Organization ID'.format(
                            protocol.name,
                            subject.id
                        ))
                    if msg:
                        errors.append(msg)
                        print(msg)
                        msg = None

        if csv:
            with open('group_report_{0}.csv'.format(datetime.now().strftime('%Y%m%d.%H:%M.%S')), 'w', newline='') as csvfile:
                csv_writer = csv.writer(csvfile, delimiter=' ',
                                        quotechar='"', quoting=csv.QUOTE_MINIMAL)
                for error in errors:
                    csv_writer.writerow([error])