Пример #1
0
    def activate(request):
        try:
            # 1.2. Check schema
            SchemaValidator.validate_obj_structure(request.data,
                                                   'user/activate.json')

            user = User.objects.filter(
                activation_code=request.data['activation_code']).get()
            if user.is_active:
                raise HttpException(400, 'O user já está ativo.',
                                    'The user is already active.')

            user.password = bcrypt.hashpw(
                request.data['password'].encode('utf-8'),
                bcrypt.gensalt()).decode('utf-8')
            user.is_active = True
            user.save()

        except User.DoesNotExist:
            return HTTP.response(404, 'Código de ativação inválido.',
                                 'Activation code invalid.')
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(
                400, 'Ocorreu um erro inesperado',
                'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        return HTTP.response(200, 'Utilizador ativado com sucesso.')
Пример #2
0
    def create(request):
        try:
            if request.ROLE_ID != 1:
                raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.')

            # 1. Check schema
            SchemaValidator.validate_obj_structure(request.data, 'doctor/create.json')

            # 2. Add new User
            new_user = User(
                name=request.data['name'] if 'name' in request.data else None,
                username=request.data['username'],
                email=request.data['email'],
                phone=request.data['phone'] if 'phone' in request.data else None,
                password=bcrypt.hashpw(request.data['password'].encode('utf-8'), bcrypt.gensalt()).decode('utf-8'),
                role=Role.objects.doctor_role().get(),
                activation_code=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
                is_active=True,
            )
            new_user.save()

            # 3 Create new Doctor
            doctor = Doctor(
                user=new_user,
                department=request.data['department'] if 'department' in request.data else None
            )
            doctor.save()

        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message, e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Ocorreu um erro inesperado', 'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        return HTTP.response(201, 'Doctor criado com succeso.')
Пример #3
0
    def create(request):
        try:
            if not Permission.verify(request, ['Admin']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            data = request.data
            # 1. Check schema
            SchemaValidator.validate_obj_structure(data, 'task/create.json')

            new_task = Task(title=data['title'],
                            description=data.get('description', None),
                            multimedia_link=data.get('multimedia_link', None),
                            task_type=data['task_type_id'])
            new_task.save()

        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Erro Inesperado',
                                 'Unexpected Error: {}.'.format(str(e)))

        # Send Response
        data = {'task_id': new_task.id}
        return HTTP.response(201, 'Tarefa adicionada com sucesso.', data=data)
Пример #4
0
    def add_second_doctor(request):
        data = request.data

        try:
            # 0 - Handle Permissions
            if not Permission.verify(request, ['Admin', 'Doctor']):
                raise HttpException(401,
                                    'Não tem permissões para aceder a este recurso.',
                                    'You don\'t have access to this resource.')

            # 1. Check schema
            SchemaValidator.validate_obj_structure(data, 'patient/add_second_doctor.json')

            patient = Patient.objects.get(pk=data['patient_id'])
            second_doctor = Doctor.objects.get(pk=data['doctor_id'])
            relation = DoctorPatient.objects.filter(patient=patient)

            # 2. Exceptions:
            # 2.1. If the patient has no doctor and the one calling the api is not an admin
            if relation.count() == 0 and request.ROLE_ID != 1:
                raise HttpException(400,
                                    'Não tem permissões para adicionar mais médicos a este paciente.',
                                    'You can\'t add more doctors to this patient.')
            # 2.2. If patient has 2 doctors already
            if relation.count() > 1:
                raise HttpException(400,
                                    'Um paciente pode ter apenas 2 médicos.',
                                    'One patient can only have 2 doctors.')
            # 2.3. if the one calling the api is not the first doctor and is not an admin
            if relation.count() == 1 and relation.get().doctor.user != request.USER_ID and request.ROLE_ID != 1:
                raise HttpException(400,
                                    'Não tem permissões para adicionar médicos a este paciente.',
                                    'You can\'t add doctors to this patient')

            # 3. Add new relation
            new_relation = DoctorPatient(
                patient=patient,
                doctor=second_doctor
            )

            new_relation.save()

        except Doctor.DoesNotExist as e:
            return HTTP.response(404, 'Médico não encontrado', 'Doctor with id {} not found. {}'.format(
                data['doctor_id'], str(e)))
        except Patient.DoesNotExist as e:
            return HTTP.response(404, 'Paciente não encontrado', 'Patient with id {} not found. {}'.format(
                data['patient_id'], str(e)))
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message, e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Erro Inesperado', 'Unexpected Error: {}.'.format(str(e)))
        # Send Response
        return HTTP.response(201, 'Médico adicionado com sucesso.')
    def seen(request):
        try:
            data = request.data

            # 1. Validations
            # 1.1. Only Doctors can mark tas schedule as seen
            if not Permission.verify(request, ['Doctor']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            # 1.2. Check schema
            SchemaValidator.validate_obj_structure(
                data, 'patient_task_schedule/mark_as_seen.json')

            # 1.3. Check if Patient Task Schedule is valid
            patient_task_schedule = PatientTaskSchedule.objects.get(
                pk=data['patient_task_schedule_id'])
            if patient_task_schedule.status > 2:
                raise HttpException(
                    400, 'Esta atividade já foi realizada anteriormente',
                    'This activity was mark as done already.')

            # 1.4. Check if doctor is prehab's owner
            if request.ROLE_ID != 2 or request.ROLE_ID == 2 and patient_task_schedule.prehab.doctor.user.id != request.USER_ID:
                raise HttpException(
                    400, 'Não tem permissões para editar este Prehab',
                    'You can\'t update this Prehab Plan')

            # 2. Update This specific Task in PatientTaskSchedule
            patient_task_schedule.seen_by_doctor = data['seen']
            patient_task_schedule.doctor_notes = data[
                'doctor_notes'] if 'doctor_notes' in data else ''
            patient_task_schedule.save()

        except PatientTaskSchedule.DoesNotExist:
            return HTTP.response(
                404, 'Tarefa não encontrada',
                'Patient Task with id {} does not exist'.format(
                    str(request.data['patient_task_schedule_id'])))
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(
                400, 'Ocorreu um erro inesperado',
                'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        return HTTP.response(200, '')
Пример #6
0
    def create(request):
        try:
            if not Permission.verify(request, ['Admin']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            data = request.data
            # 1. Check schema
            SchemaValidator.validate_obj_structure(data, 'meal/create.json')

            # 2. Check if meal type is available
            if not any(data['meal_type_id'] in meal_type
                       for meal_type in Meal.meal_types):
                raise HttpException(400, 'Tipo de refeição não existe.',
                                    'Meal Type does not exist.')

            with transaction.atomic():
                new_meal = Meal(title=data['title'],
                                description=data.get('description', None),
                                multimedia_link=data.get(
                                    'multimedia_link', None),
                                meal_type=data['meal_type_id'])
                new_meal.save()

                # Insert constraint types
                for constraint_type_id in data['constraint_types']:
                    constraint_type = ConstraintType.objects.get(
                        pk=constraint_type_id)
                    meal_constraint_type = MealConstraintType(
                        meal=new_meal, constraint_type=constraint_type)
                    meal_constraint_type.save()

        except ConstraintType.DoesNotExist:
            return HTTP.response(404, 'Restrição alimentar not found.',
                                 'Constraint not found.')
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(
                400, 'Ocorreu um erro inesperado',
                'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        # Send Response
        data = {'meal_id': new_meal.id}
        return HTTP.response(201, 'Meal criada com sucesso.', data)
    def seen_in_bulk(request):
        try:
            data = request.data

            # 1. Validations
            # 1.1. Only Doctors can mark tas schedule as seen
            if not Permission.verify(request, ['Doctor', 'Admin']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            # 1.2. Check schema
            SchemaValidator.validate_obj_structure(
                data, 'patient_task_schedule/mark_as_seen_bulk.json')

            # 1.3. Check if Patient Task Schedule is valid
            patient_tasks = PatientTaskSchedule.objects.filter(
                prehab=data['prehab_id']).all()
            for patient_task in patient_tasks:
                patient_task.seen_by_doctor = True
                patient_task.save()

        except PatientTaskSchedule.DoesNotExist:
            return HTTP.response(
                404, 'Tarefa não encontrada',
                'Patient Task with id {} does not exist'.format(
                    str(request.data['patient_task_schedule_id'])))
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(
                400, 'Ocorreu um erro inesperado',
                'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        return HTTP.response(200, '')
Пример #8
0
    def test_validate_structure(self):
        body = {}
        try:
            self.assertRaises(HttpException, SchemaValidator.validate_obj_structure(body, 'test/test1.json'))
        except HttpException as e:
            self.assertEqual(e.http_code, 400)
            self.assertEqual(e.http_detail, 'Validation Error. Parameter required_string is a required property')

        body = {"required_string": "s", "max_len_string": "qwertyuiopasdfghjkl"}
        try:
            self.assertRaises(HttpException, SchemaValidator.validate_obj_structure(body, 'test/test1.json'))
        except HttpException as e:
            self.assertEqual(e.http_code, 400)
            self.assertEqual(e.http_detail, 'Validation Error. Parameter qwertyuiopasdfghjkl is too long')

        body = {"required_string": "s", "number": "dfgfgh"}
        try:
            self.assertRaises(HttpException, SchemaValidator.validate_obj_structure(body, 'test/test1.json'))
        except HttpException as e:
            self.assertEqual(e.http_code, 400)
            self.assertEqual(e.http_detail, 'Validation Error. dfgfgh is not of type number. Review: number')

        body = {"required_string": "s", "pattern": "4"}
        try:
            self.assertRaises(HttpException, SchemaValidator.validate_obj_structure(body, 'test/test1.json'))
        except HttpException as e:
            self.assertEqual(e.http_code, 400)
            self.assertEqual(e.http_detail, 'Validation Error. Parameter 4 does not match ^[1,2,3]$')

        body = {"required_string": "s"}
        self.assertEqual(SchemaValidator.validate_obj_structure(body, 'test/test1.json'), None)

        body = {"required_string": "s"}
        try:
            self.assertRaises(SchemaValidator.validate_obj_structure(body, 'test/test2.json'), Exception)
        except HttpException as e:
            self.assertEqual(e.http_code, 400)
            self.assertEqual(e.http_detail, 'File prehab_app/schemas/test/test2.json not found')
Пример #9
0
    def create(request):
        try:
            data = request.data

            # 1. Validations
            # 1.1. Only Doctors can create new Prehab Plans
            if not Permission.verify(request, ['Admin', 'Doctor']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            # 1.2. Check schema
            SchemaValidator.validate_obj_structure(data, 'prehab/create.json')

            # 1.3. Check if patient_id is one of this doctor patients
            patient_id = data['patient_id']
            patient = Patient.objects.get(pk=patient_id)
            doctor = Doctor.objects.get(pk=request.USER_ID)
            if request.ROLE_ID == 2 and not DoctorPatient.objects.is_a_match(
                    request.USER_ID, patient_id):
                raise HttpException(
                    400, 'Paciente não é do médico especificado.',
                    'Patient {} is not from Doctor {}.'.format(
                        patient_id, request.USER_ID))

            # 1.4. Check if surgery date is greater than init_date
            surgery_date = datetime.datetime.strptime(data['surgery_date'],
                                                      "%d-%m-%Y")
            init_date = datetime.datetime.strptime(data['init_date'],
                                                   "%d-%m-%Y")
            if surgery_date < init_date:
                raise HttpException(
                    400,
                    'Data de cirurgia deve ser posterior à data de inicio de prehab,',
                    'Surgery Date must be after prehab init.')

            # 1.5. Check if Task Schedule Id was created by
            # this specific doctor or a community Task Schedule (created by an admin)
            task_schedule = TaskSchedule.objects.get(
                pk=data['task_schedule_id'])
            if request.ROLE_ID != 1 and not task_schedule.doctor_can_use(
                    doctor.user.id):
                raise HttpException(
                    400, 'Você não é o dono deste prehab',
                    'You are not the owner of this task schedule.')

            # 1.6. Check if this patient has some prehab already
            if Prehab.objects.filter(patient=patient).filter(
                    status__lt=4).count() > 0:
                raise HttpException(400, 'Este paciente já tem um prehab',
                                    'This patient has a prehab already.')

            # 2. Transform General Task Schedule to a Custom Patient Task Schedule
            expected_end_date = init_date + datetime.timedelta(
                days=7 * task_schedule.number_of_weeks)

            # 3. Insert new Prehab
            with transaction.atomic():
                prehab = Prehab(patient=patient,
                                init_date=init_date,
                                expected_end_date=expected_end_date,
                                actual_end_date=None,
                                surgery_date=surgery_date,
                                number_of_weeks=task_schedule.number_of_weeks,
                                status=Prehab.PENDING,
                                created_by=doctor)
                prehab.save()

                # 4. Insert Patient Task Schedule
                patient_task_schedule_work_load = DataHelper.patient_task_schedule_work_load(
                    task_schedule)
                patient_tasks = []
                for row in patient_task_schedule_work_load:
                    patient_tasks.append(
                        PatientTaskSchedule(
                            prehab=prehab,
                            week_number=row['week_number'],
                            day_number=row['day_number'],
                            task=row['task'],
                            expected_repetitions=1,  # row['repetitions'],
                            actual_repetitions=None,
                            status=PatientTaskSchedule.PENDING))
                PatientTaskSchedule.objects.bulk_create(patient_tasks)

                # 5. Insert Patient Meal Schedule
                constraint_types = [
                    pct.constraint_type
                    for pct in PatientConstraintType.objects.filter(
                        patient=patient).all()
                ]
                patient_meal_schedule = DataHelper.patient_meal_schedule(
                    task_schedule.number_of_weeks, constraint_types)
                patient_meals = []
                for row in patient_meal_schedule:
                    patient_meals.append(
                        PatientMealSchedule(prehab=prehab,
                                            week_number=row['week_number'],
                                            day_number=row['day_number'],
                                            meal_order=row['meal_order'],
                                            meal=row['meal']))

                PatientMealSchedule.objects.bulk_create(patient_meals)

        except Patient.DoesNotExist as e:
            return HTTP.response(
                400, 'Patient with id of {} does not exist.'.format(
                    request.data['patient_id']))
        except TaskSchedule.DoesNotExist as e:
            return HTTP.response(
                400, 'Task Schedule with id of {} does not exist.'.format(
                    request.data['task_schedule_id']))
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Erro Inesperado',
                                 'Unexpected Error: {}.'.format(str(e)))

        # Send Response
        data = {'prehab_id': prehab.id}
        return HTTP.response(201, '', data)
Пример #10
0
    def create(request):
        try:
            # 0. Check Permissions
            if not Permission.verify(request, ['Admin', 'Doctor']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            data = request.data
            # 1. Check schema
            SchemaValidator.validate_obj_structure(
                data, 'full_task_schedule/create.json')

            with transaction.atomic():
                # 2. Create Task Schedule
                task_schedule = TaskSchedule(
                    title=request.data['title'],
                    number_of_weeks=request.data['number_of_weeks'],
                    created_by=User.objects.get(pk=request.USER_ID),
                    is_active=True)

                task_schedule.save()

                # For Each Week, add them
                for week in request.data['weeks']:
                    week_number = week['week_number']
                    if 0 > week_number > request.data['number_of_weeks']:
                        raise HttpException(400,
                                            'Número de semanas não eprmitida',
                                            'Number of week is not allowed.')

                    for week_task in week['tasks']:
                        try:
                            task = Task.objects.get(pk=week_task['task_id'])
                        except Task.DoesNotExist:
                            raise HttpException(
                                404, 'Tarefa não enconbtrada',
                                'Task with id {} does not exist.'.format(
                                    str(week_task['task_id'])))

                        schedule_week_task = WeekTaskSchedule(
                            task_schedule=task_schedule,
                            week_number=week_number,
                            task=task,
                            times_per_week=week_task['times_per_week'],
                            repetition_number=week_task.get(
                                'repetition_number', None))

                        schedule_week_task.save()

        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(
                400, 'Ocorreu um erro inesperado',
                'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        data = {'task_schedule_id': task_schedule.id}

        return HTTP.response(201, 'Task Schedule criado com sucesso.', data)
    def mark_as_done(request):
        try:
            data = request.data

            # 1. Validations
            # 1.1. Only Patients can create new Prehab Plans
            if not Permission.verify(request, ['Patient']):
                raise HttpException(
                    401, 'Não tem permissões para aceder a este recurso.',
                    'You don\'t have access to this resource.')

            # 1.2. Check schema
            SchemaValidator.validate_obj_structure(
                data, 'patient_task_schedule/mark_as_done.json')

            # 1.3. Check if Patient Task Schedule is valid
            patient_task_schedule = PatientTaskSchedule.objects.get(
                pk=data['patient_task_schedule_id'])
            if patient_task_schedule.status > 2:
                raise HttpException(400,
                                    'Esta atividade já tinha sido realizada.',
                                    'This activity was mark as done already.')

            # 1.4. Check if patient is prehab's owner
            if patient_task_schedule.prehab.patient.user.id != request.USER_ID:
                raise HttpException(400, 'Não pode atualizar este prehab.',
                                    'You can\'t update this Prehab Plan')

            # 2. Update This specific Task in PatientTaskSchedule
            # 2.1. Task completed with success
            if data['completed']:
                patient_task_schedule.status = PatientTaskSchedule.COMPLETED

            # 2.2. Task not completed
            else:
                patient_task_schedule.status = PatientTaskSchedule.NOT_COMPLETED

            patient_task_schedule.finished_date = datetime.datetime.now()
            patient_task_schedule.save()

            # 3. Report Difficulties
            patient_task_schedule.was_difficult = data['difficulties']
            patient_task_schedule.patient_notes = data[
                'notes'] if 'notes' in data else ''

            # Doctor only need to check activities that the patient had difficult
            patient_task_schedule.seen_by_doctor = False if data[
                'difficulties'] else True
            patient_task_schedule.save()

        except PatientTaskSchedule.DoesNotExist as e:
            return HTTP.response(404, 'Tarefa do paciente não encontrada.',
                                 'Patient Task Schedule not found.')
        except Prehab.DoesNotExist as e:
            return HTTP.response(
                404, 'Prehab não encontrado',
                'Prehab with id {} not found'.format(
                    request.data['prehab_id']))
        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message,
                                 e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Erro Inesperado',
                                 'Unexpected Error: {}.'.format(str(e)))

        return HTTP.response(200, 'Prehab atualizado com sucesso.')
Пример #12
0
    def create(request):
        try:
            # 0 - Handle Permissions
            if not Permission.verify(request, ['Doctor']):
                raise HttpException(401, 'Não tem permissões para aceder a este recurso.',
                                    'You don\'t have access to this resource.')

            data = request.data
            # 1. Check schema
            SchemaValidator.validate_obj_structure(data, 'patient/create.json')

            # 2. Add new User
            new_user = User(
                name='Anónimo',
                username='',
                email=data['email'] if 'email' in data else None,
                phone=data['phone'] if 'phone' in data else None,
                password=None,
                role=Role.objects.patient_role().get(),
                activation_code=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
                is_active=False,
            )
            new_user.save()
            # 1. Generate Activation Code & Username
            patient_tag = "HSJ{}{}".format(datetime.now().year, str(new_user.id).zfill(4))
            new_user.username = patient_tag
            new_user.save()
            doctor = Doctor.objects.get(pk=request.USER_ID)

            # 3. Add new Patient
            new_patient = Patient(
                user=new_user,
                patient_tag=patient_tag,
                age=data['age'],
                height=data['height'],
                weight=data['weight'],
                sex=data['sex']
            )
            new_patient.save()

            # 4. Create Doctor Patient Association
            relation = DoctorPatient(
                patient=new_patient,
                doctor=doctor
            )

            relation.save()

            # 5. Associate Constraints
            for constraint_id in data['constraints']:
                constraint_type = ConstraintType.objects.get(pk=constraint_id)
                constraint = PatientConstraintType(
                    patient=new_patient,
                    constraint_type=constraint_type
                )
                constraint.save()

        except HttpException as e:
            return HTTP.response(e.http_code, e.http_custom_message, e.http_detail)
        except Exception as e:
            return HTTP.response(400, 'Ocorreu um erro inesperado',
                                 'Unexpected Error. {}. {}.'.format(type(e).__name__, str(e)))

        # Send Response - access code
        data = {
            'access_code': new_user.activation_code
        }
        return HTTP.response(201, 'Paciente criado com sucesso.', data)