def handle(self, *args, **options):

        # Get the app
        app = ConsentConfig.name

        # Load FHIR resources and update the FHIR server
        fhir_dir = os.path.join(settings.BASE_DIR, app, 'fhir')

        # Ensure it exists
        if not os.path.exists(fhir_dir):
            raise CommandError('App {} does not have a "fhir" directory'.format(app))

        # Collect resources
        for file_path in [os.path.join(fhir_dir, f) for f in os.listdir(fhir_dir) if os.path.isfile(os.path.join(fhir_dir, f))]:
            with open(file_path) as f:

                try:
                    # Read the resource JSON
                    resource = json.loads(f.read())

                    # Set the resource name
                    name = '{}/{}'.format(resource['resourceType'], resource['id'])

                    # Do the update
                    if FHIR.update_resource(resource):
                        self.stdout.write(self.style.SUCCESS('Successfully updated FHIR resource: {}'.format(name)))

                    else:
                        raise CommandError('Resource could not be updated: {}'.format(name))

                except ValueError:
                    raise CommandError('Resource could not be read: {}'.format(file_path))

                except KeyError:
                    raise CommandError('FHIR Resource does not contain ID and/or ResourceType: {}'.format(file_path))
Exemplo n.º 2
0
    def post(self, request, *args, **kwargs):
        logger.debug('Signature view')

        # Get the patient's email
        patient_email = get_jwt_email(request=request, verify=False)

        # Process the form
        try:
            # Check form type
            if request.session['individual']:
                logger.debug('Individual signature')

                # Get the form
                form = ASDIndividualSignatureForm(request.POST)
                if not form.is_valid():
                    logger.debug('Individual signature invalid: {}'.format(
                        form.errors.as_json()))

                    # Return the form
                    context = {'form': form, 'return_url': self.return_url}

                    return render(
                        request,
                        template_name=
                        'consent/asd/individual-signature-part-1.html',
                        context=context)

                # Build the data
                user_forms = dict({
                    'individual': form.cleaned_data,
                    'quiz': request.session['quiz']
                })

                # Submit the data
                FHIR.submit_asd_individual(patient_email,
                                           user_forms,
                                           dry=self.demo(request))

                # If in demo mode, do not create PDF
                if not self.demo(request):

                    # Submit consent PDF in the background
                    threading.Thread(target=APIConsentView.
                                     create_consent_document_reference,
                                     args=(request,
                                           PPM.Study.ASD.value)).start()

                # Get the return URL
                context = {
                    'return_url': self.return_url,
                    'demo': self.demo(request)
                }

                # Get the passed parameters
                return render(request,
                              template_name='consent/success.html',
                              context=context)

            else:
                logger.debug('Guardian/ward signature')

                # Check which signature
                if request.session.get('guardian'):
                    logger.debug('Ward signature')

                    # Get the form
                    form = ASDWardSignatureForm(request.POST)
                    if not form.is_valid():
                        logger.debug('Ward signature invalid: {}'.format(
                            form.errors.as_json()))

                        # Return the form
                        context = {'form': form, 'return_url': self.return_url}

                        return render(
                            request,
                            template_name=
                            'consent/asd/guardian-signature-part-3.html',
                            context=context)

                    # Build the data
                    user_forms = dict({
                        'ward': form.cleaned_data,
                        'guardian': request.session['guardian'],
                        'quiz': request.session['quiz']
                    })

                    # Submit the data
                    FHIR.submit_asd_guardian(patient_email,
                                             user_forms,
                                             dry=self.demo(request))

                    # If in demo mode, do not create PDF
                    if not self.demo(request):

                        # Submit consent PDF in the background
                        threading.Thread(target=APIConsentView.
                                         create_consent_document_reference,
                                         args=(request,
                                               PPM.Study.ASD.value)).start()

                    # Get the return URL
                    context = {
                        'return_url': self.return_url,
                        'demo': self.demo(request)
                    }

                    # Get the passed parameters
                    return render(request,
                                  template_name='consent/success.html',
                                  context=context)

                else:
                    logger.debug('Guardian signature')

                    # Get the form
                    form = ASDGuardianSignatureForm(request.POST)
                    if not form.is_valid():
                        logger.debug('Guardian signature invalid: {}'.format(
                            form.errors.as_json()))

                        # Return the form
                        context = {'form': form, 'return_url': self.return_url}

                        return render(
                            request,
                            template_name=
                            'consent/asd/guardian-signature-part-1-2.html',
                            context=context)

                    # Fix the date
                    date = form.cleaned_data['date'].isoformat()
                    form.cleaned_data['date'] = date

                    # Retain their responses
                    request.session['guardian'] = form.cleaned_data

                    # Make the ward signature form
                    form = ASDWardSignatureForm()

                    # Get the return URL
                    context = {
                        'form': form,
                        'return_url': self.return_url,
                    }

                    # Get the passed parameters
                    return render(request,
                                  template_name=
                                  'consent/asd/guardian-signature-part-3.html',
                                  context=context)

        except FHIR.PatientDoesNotExist:
            logger.warning('Patient does not exist')
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Consent does not exist: ASD')
            return render_error(
                request,
                title='Consent Does Not Exist',
                message='The requested consent does not exist!',
                support=False)

        except FHIR.QuestionnaireResponseAlreadyExists:
            logger.warning('Consent already finished')
            return render_error(
                request,
                title='Consent Already Completed',
                message='You have already filled out and submitted this '
                'consent.',
                support=False)

        except Exception as e:
            logger.error(
                "Error while submitting consent signature: {}".format(e),
                exc_info=True,
                extra={
                    'project': 'asd',
                    'request': request,
                })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error{}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)
Exemplo n.º 3
0
    def get(self, request, *args, **kwargs):

        # Clearing any leftover sessions
        [
            request.session.pop(key, None)
            for key in ['quiz', 'individual', 'guardian']
        ]

        # Get the patient email and ensure they exist
        patient_email = get_jwt_email(request=request, verify=False)

        try:

            # If in demo mode, do not check participant and prior submissions
            if not self.demo(request):

                FHIR.check_patient(patient_email)

                # Check response
                FHIR.check_consent(PPM.Study.ASD.value, patient_email)

            # Create the form
            form = ASDTypeForm()

            context = {'form': form, 'return_url': self.return_url}

            return render(request,
                          template_name='consent/asd.html',
                          context=context)

        except FHIR.PatientDoesNotExist:
            logger.warning('Patient does not exist')
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Consent does not exist: NEER')
            return render_error(
                request,
                title='Consent Does Not Exist',
                message='The requested consent does not exist!',
                support=False)

        except FHIR.ConsentAlreadyExists:
            logger.warning('Consent already finished')
            return render_error(
                request,
                title='Consent Already Completed',
                message='You have already filled out and submitted this '
                'consent.',
                support=False)

        except Exception as e:
            logger.error("Error while rendering consent: {}".format(e),
                         exc_info=True,
                         extra={
                             'request': request,
                             'project': 'asd',
                         })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error{}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)
Exemplo n.º 4
0
    def post(self, request, *args, **kwargs):

        # Get the patient email
        patient_email = get_jwt_email(request=request, verify=False)

        # Get the form
        form = self.Form(request.POST)
        if not form.is_valid():

            # Return the form
            context = {
                'study': self.study,
                'form': form,
                'return_url': self.return_url
            }

            return render(request,
                          template_name='consent/{}.html'.format(self.study),
                          context=context)

        # Process the form
        try:
            # Submit the consent
            FHIR.submit_consent(self.study,
                                patient_email,
                                form.cleaned_data,
                                dry=self.demo(request))

            if not self.demo(request):

                # Submit consent PDF in the background
                threading.Thread(
                    target=APIConsentView.create_consent_document_reference,
                    args=(request, self.study)).start()

            # Get the return URL
            context = {
                'study': self.study,
                'return_url': self.return_url,
                'demo': self.demo(request)
            }

            # Get the passed parameters
            return render(request,
                          template_name='consent/success.html',
                          context=context)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Consent does not exist: {}'.format(
                PPM.Study.title(self.study)))
            return render_error(
                request,
                title='Consent Does Not Exist: {}'.format(
                    self.questionnaire_id),
                message='The requested consent does not exist!',
                support=False)

        except FHIR.PatientDoesNotExist:
            logger.warning(
                'Patient does not exist: {}'.format(patient_email[:3] +
                                                    '****' +
                                                    patient_email[-4:]))
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)
        except Exception as e:
            logger.error("Error while submitting consent: {}".format(e),
                         exc_info=True,
                         extra={
                             'request': request,
                             'project': self.study,
                             'questionnaire': self.questionnaire_id,
                             'form': self.Form
                         })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error {}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)
Exemplo n.º 5
0
    def get(self, request, *args, **kwargs):

        # Get the patient email and ensure they exist
        patient_email = get_jwt_email(request=request, verify=False)

        try:
            # If in demo mode, do not check participant and prior submissions
            if not self.demo(request):

                # Ensure the current user has a record
                FHIR.check_patient(patient_email)

                # Check response
                FHIR.check_consent(self.study, patient_email)

            # Create the form
            form = self.Form()

            context = {
                'study': self.study,
                'form': form,
                'return_url': self.return_url
            }

            # Build the template response
            response = render(request,
                              template_name='consent/{}.html'.format(
                                  self.study),
                              context=context)

            return response

        except FHIR.PatientDoesNotExist:
            logger.warning('Patient does not exist')
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Consent does not exist: {}'.format(
                PPM.Study.title(self.study)))
            return render_error(
                request,
                title='Consent Does Not Exist: {}'.format(
                    self.questionnaire_id),
                message='The requested consent does not exist!',
                support=False)

        except FHIR.ConsentAlreadyExists:
            logger.warning('Consent already finished')
            return render_error(
                request,
                title='Consent Already Completed',
                message='You have already filled out and submitted this '
                'consent.',
                support=False)

        except Exception as e:
            logger.error("Error while rendering consent: {}".format(e),
                         exc_info=True,
                         extra={
                             'request': request,
                             'project': self.study,
                             'questionnaire': self.questionnaire_id,
                             'form': self.Form
                         })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error{}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        logger.debug(f'PPM/{self.study}: POST questionnaire')

        # Get the patient email
        patient_email = get_jwt_email(request=request, verify=False)

        # create a form instance and populate it with data from the request:
        form = self.Form(self.questionnaire_id, request.POST)

        # check whether it's valid:
        if not form.is_valid():
            logger.debug(
                f'PPM/{self.study}: Form was invalid: {form.errors.as_json()}')

            # Return with errors
            context = {
                'study': self.study,
                'form': form,
                'questionnaire_id': self.questionnaire_id,
                'return_url': self.return_url,
            }

            # Get the passed parameters
            return render(request,
                          template_name='questionnaire/{}.html'.format(
                              self.study),
                          context=context)

        else:
            logger.debug(f'PPM/{self.study}: Form was valid')

        # Process the form
        try:

            # Submit the form
            FHIR.submit_questionnaire(self.study,
                                      patient_email,
                                      form.cleaned_data,
                                      dry=self.demo(request))

            # Get the return URL
            logger.debug(
                f'PPM/{self.study}: Success, returning user to: {self.return_url}'
            )
            context = {
                'questionnaire_id': self.questionnaire_id,
                'return_url': self.return_url,
                'demo': self.demo(request)
            }

            # Get the passed parameters
            return render(request,
                          template_name='questionnaire/success.html',
                          context=context)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Questionnaire does not exist: {}'.format(
                self.questionnaire_id))
            return render_error(
                request,
                title='Questionnaire Does Not Exist',
                message='The requested questionnaire does not exist!',
                support=False)

        except FHIR.PatientDoesNotExist:
            logger.warning(
                'Patient does not exist: {}'.format(patient_email[:3] +
                                                    '****' +
                                                    patient_email[-4:]))
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)
        except Exception as e:
            logger.error("Error while submitting questionnaire: {}".format(e),
                         exc_info=True,
                         extra={
                             'project': self.study,
                         })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error{}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)
Exemplo n.º 7
0
    def get(self, request, *args, **kwargs):
        logger.debug(f'PPM/{self.study}: GET questionnaire')

        # Get the patient email and ensure they exist
        patient_email = get_jwt_email(request=request, verify=False)

        try:
            # If demo mode, disable checks for participant and past submissions
            if not self.demo(request):

                # Check the current patient
                FHIR.check_patient(patient_email)

                # Check response
                FHIR.check_response(self.questionnaire_id, patient_email)

            # Create the form
            form = self.Form(self.questionnaire_id)

            # Prepare the context
            context = {
                'study': self.study,
                'questionnaire_id': self.questionnaire_id,
                'form': form,
                'return_url': self.return_url,
            }

            # Get the passed parameters
            return render(request,
                          template_name='questionnaire/{}.html'.format(
                              self.study),
                          context=context)

        except FHIR.PatientDoesNotExist:
            logger.warning(
                'Patient does not exist: {}'.format(patient_email[:3] +
                                                    '****' +
                                                    patient_email[-4:]))
            return render_error(
                request,
                title='Patient Does Not Exist',
                message=
                'A FHIR resource does not yet exist for the current user. '
                'Please sign into the People-Powered dashboard to '
                'create your user.',
                support=False)

        except FHIR.QuestionnaireDoesNotExist:
            logger.warning('Questionnaire does not exist: {}'.format(
                self.questionnaire_id))
            return render_error(
                request,
                title='Questionnaire Does Not Exist',
                message='The requested questionnaire does not exist!',
                support=False)

        except FHIR.QuestionnaireResponseAlreadyExists:
            logger.warning('Questionnaire already finished')
            return render_error(
                request,
                title='Questionnaire Already Completed',
                message='You have already filled out and submitted this '
                'questionnaire.',
                support=False)

        except Exception as e:
            logger.error("Error while rendering questionnaire: {}".format(e),
                         exc_info=True,
                         extra={
                             'request': request,
                             'project': self.study,
                         })
            return render_error(
                request,
                title='Application Error',
                message='The application has experienced an unknown error {}'.
                format(': {}'.format(e) if settings.DEBUG else '.'),
                support=False)