def retrieve(request, pk=None): 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.') # Check if Task Schedule exists and if it's the owner requesting it task_schedule = TaskSchedule.objects.get(pk=pk) if request.ROLE_ID == 2 and task_schedule.created_by.id != request.USER_ID: raise HttpException( 401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') data = FullTaskScheduleSerializer(instance=task_schedule).data except TaskSchedule.DoesNotExist: return HTTP.response( 404, 'Plano de Tarefas não encontrado.', 'Task Schedule with id {} not found.'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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, data=data)
def clean_tasks(request): try: patient_tasks = PatientTaskSchedule.objects.all() for patient_task in patient_tasks: prehab_init_date = patient_task.prehab.init_date task_date = prehab_init_date + datetime.timedelta( days=7 * (patient_task.week_number - 1)) + datetime.timedelta( days=(patient_task.day_number - 1)) patient_task.date = task_date if task_date < datetime.date.today( ) and patient_task.status == 1: patient_task.status = PatientTaskSchedule.NOT_COMPLETED patient_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))) return HTTP.response(200, '')
def list(self, 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.') # In case it's an Admin -> Retrieve ALL patients info if request.ROLE_ID == 1: queryset = self.paginate_queryset(TaskSchedule.objects.all()) # In case it's a Doctor -> Retrieve ALL his/her task schedules info elif request.ROLE_ID == 2: queryset = self.paginate_queryset( TaskSchedule.objects.created_by(request.USER_ID)) else: raise HttpException(400) data = TaskScheduleSerializer(queryset, many=True).data 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, data=data) # , paginator=self.paginator)
def clean_prehabs(request): try: prehabs = Prehab.objects.filter(status__lt=3).all() for prehab in prehabs: # Automatic start prehab if prehab.init_date <= datetime.date.today( ) and prehab.status == 1: prehab.status = Prehab.ONGOING # Achieve Prehabs due 30 days elif (prehab.expected_end_date + datetime.timedelta(30) ) <= datetime.date.today() and prehab.status < 3: prehab.actual_end_date = datetime.date.today() prehab.status = Prehab.CANCEL prehab.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(200, '')
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.')
def retrieve(request, pk=None): try: patient_task_schedule = PatientTaskSchedule.objects.get(pk=pk) # In case it's a Doctor -> check if he/she has permission if request.ROLE_ID == 2 and request.USER_ID != patient_task_schedule.prehab.created_by.user.id: raise HttpException( 401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') # In case it's a Patient -> check if it's own information elif request.ROLE_ID == 3 and request.USER_ID != patient_task_schedule.prehab.patient.user.id: raise HttpException( 401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') data = SimplePatientTaskScheduleSerializer(patient_task_schedule, many=False).data except PatientTaskSchedule.DoesNotExist: return HTTP.response( 404, 'Paciente não encontrado.', 'Patient with id {} does not exist'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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, data=data)
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)
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.')
def __call__(self, request): if request.path in ('/api/cron/tasks', '/api/cron/prehabs'): return self.get_response(request) if 'HTTP_PLATFORM' not in request.META or request.META[ 'HTTP_PLATFORM'] not in ('web', 'mobile'): return HTTP.response(403, 'Precisa de enviar a plataforma', 'You don\'t have access') request.PLATFORM = request.META['HTTP_PLATFORM'] # Code to be executed for each request before # the view (and later middleware) are called. if request.path not in ('/api/login/', '/api/login', '/api/user/activate/', '/api/user/activate'): if 'HTTP_JWT' not in request.META: return HTTP.response(401, 'Falta o token nos headers.', 'Token not present') try: jwt_encoded = request.META['HTTP_JWT'] jwt_decoded = jwt.decode(jwt_encoded, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM) except DecodeError: return HTTP.response(401, 'Token não é válido.', 'Token not valid.') request.USER_ID = jwt_decoded['user_id'] request.ROLE_ID = jwt_decoded['role_id'] return self.get_response(request)
def retrieve(request, pk=None): try: patient = Patient.objects.get(pk=pk) # In case it's a Doctor -> check if he/she has permission if request.ROLE_ID == 2 and DoctorPatient.objects.filter(doctor=request.USER_ID).filter( patient=patient).count == 0: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') # In case it's a Patient -> check if it's own information elif request.ROLE_ID == 3 and request.USER_ID == patient.user.id: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') data = PatientSerializer(patient, many=False).data # DOCTORS doctors = DoctorPatient.objects.filter(patient=patient.pk).all() data['doctors_associated'] = [DoctorSerializer(d.doctor, many=False).data for d in doctors] # CONSTRAINTS constraints = PatientConstraintType.objects.filter(patient=patient.pk).all() data['constraints'] = [ConstraintTypeSerializer(c.constraint_type, many=False).data for c in constraints] except Patient.DoesNotExist: return HTTP.response(404, 'Paciente não encontrado.', 'Patient with id {} not found.'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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, data=data)
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 statistics(request, pk=None): try: patient = Patient.objects.get(pk=pk) # In case it's a Doctor -> check if he/she has permission if request.ROLE_ID == 2 and DoctorPatient.objects.filter(doctor=request.USER_ID).filter( patient=patient).count == 0: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') # In case it's a Patient -> check if it's own information elif request.ROLE_ID == 3 and request.USER_ID == patient.user.id: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') prehab = Prehab.objects.filter(patient=patient).first() if prehab is not None: raise HttpException(400, 'Paciente não tem Prehabs associados', 'Patient needs a prehab to retrieve statistics.') patient_tasks = PatientTaskSchedule.objects.filter(prehab=prehab).all() days_to_surgery = (datetime.now().date() - prehab.surgery_date).days current_week_num = math.floor(days_to_surgery / 7) current_day_num = days_to_surgery - 7 * current_week_num pass_patient_tasks = [t for t in patient_tasks if t.week_number <= current_week_num and t.day_number <= current_day_num] data = { 'patient_id': pk, 'prehab_week_number': prehab.number_of_weeks, 'prehab_start_date': prehab.init_date, 'prehab_expected_end_date': prehab.expected_end_date, 'surgery_day': prehab.surgery_date, 'days_until_surgery': days_to_surgery if days_to_surgery > 0 else None, 'total_activities': len(patient_tasks), 'total_activities_until_now': len(pass_patient_tasks), 'activities_done': len([t for t in pass_patient_tasks if t.status == PatientTaskSchedule.COMPLETED]), 'activities_with_difficulty': len([t for t in pass_patient_tasks if t.was_difficult]), 'activities_not_done': len( [t for t in pass_patient_tasks if t.status == PatientTaskSchedule.NOT_COMPLETED]), 'prehab_status_id': prehab.status, 'prehab_status': prehab.get_status_display() } except Patient.DoesNotExist: return HTTP.response(404, 'Paciente não encontrado', 'Patient with id {} not found.'.format(str(pk))) 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, data=data)
def login(request): try: # 1. Check if pair username-password is correct user = User.objects.filter(username=request.data['username']).get() if not bcrypt.checkpw(request.data['password'].encode('utf-8'), user.password.encode('utf-8')): raise HttpException(401, 'Credenciais não válidas.', 'Wrong credentials.') # In Case of a Patient - only if platform is MOBILE # In Case of a Doctor - only if platform is WEB if (user.role.id == 3 and request.PLATFORM != 'mobile') or ( user.role.id == 2 and request.PLATFORM != 'web'): raise HttpException( 401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') # 3. Get Context Information - TODO prehab_id = None if user.role.id == 3: prehab = Prehab.objects.filter(patient_id=user.id) if prehab.count(): prehab_id = prehab.first().id # 4. Generate JWT jwt_data = { 'user_id': user.id, 'role_id': user.role.id, } jwt_encoded = jwt.encode( jwt_data, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM).decode('utf-8') except User.DoesNotExist as e: return HTTP.response(401, 'Utilizador não existe.', 'User not valid.') 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 = {'jwt': jwt_encoded, 'role': user.role.title} if prehab_id is not None: data['prehab_id'] = prehab_id return HTTP.response(200, data=data)
def list(self, request): try: queryset = self.paginate_queryset(Meal.objects.all()) data = MealSerializer(queryset, many=True).data 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, '', data=data, paginator=self.paginator)
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, '')
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 list(self, request): try: # In case it's a patient -> don't allow it if request.ROLE_ID == 3: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') doctors = self.paginate_queryset(Doctor.objects.all()) queryset = self.paginate_queryset(doctors) 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 = DoctorSerializer(queryset, many=True).data return HTTP.response(200, '', data=data, paginator=self.paginator)
def retrieve(request, pk=None): try: # In case it's not Admin -> fails if request.ROLE_ID != 1 and request.USER_ID != pk: raise HttpException(401, 'Não tem permissões para aceder a este recurso.', 'You don\'t have access to this resource.') doctor = Doctor.objects.get(user_id=pk) data = FullDoctorSerializer(doctor, many=False).data except Doctor.DoesNotExist: return HTTP.response(404, 'Doctor com id {} não foi encontrado.'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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, data=data)
def test_details_in_responses(self): res = HTTP.response(200, 'Este é um teste para ver os detalhes', 'This is a test for details') body = json.loads(res.content) self.assertEqual(res.status_code, 200) self.assertEqual(body['code'], 200) self.assertEqual(body['message'], 'Success') self.assertEqual(body['details'], 'This is a test for details') self.assertEqual(body['custom_message'], 'Este é um teste para ver os detalhes') self.assertEqual(body['data'], {})
def retrieve(request, pk=None): try: meal = Meal.objects.get(pk=pk) except Meal.DoesNotExist: return HTTP.response(404, 'Refeição não encontrada.', 'Meal with id {} not found.'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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 = MealSerializer(meal, many=False).data return HTTP.response(200, data=data)
def retrieve(request, pk=None): try: queryset = TaskSchedule.objects.get(pk=pk) data = TaskScheduleSerializer(queryset, many=False).data except TaskSchedule.DoesNotExist: return HTTP.response( 404, 'Paciente não encontrado', 'Patient with id {} not found.'.format(str(pk))) except ValueError: return HTTP.response(404, 'Url com formato inválido.', 'Invalid URL format. {}'.format(str(pk))) 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, data=data)
def list(self, request): """ Query Parameters: patient_id :param request: :return: """ try: if 'patient_id' in request.GET and request.GET.get('patient_id'): patient_task_schedule = PatientTaskSchedule.objects.filter( patient=request.GET['patient_id']) else: patient_task_schedule = PatientTaskSchedule.objects # In case it's an Admin -> Retrieve ALL PREHABS info if request.ROLE_ID == 1: patient_task_schedule = patient_task_schedule.all() # In case it's a Doctor -> Retrieve ALL plans created by him elif request.ROLE_ID == 2: patient_task_schedule = patient_task_schedule.filter( prehab__created_by_id=request.USER_ID).all() # In case it's a Patient -> Retrieve his plan elif request.ROLE_ID == 3: patient_task_schedule = patient_task_schedule.filter( prehab__patient_id=request.USER_ID).all() else: raise HttpException(400) queryset = self.paginate_queryset(patient_task_schedule) data = SimplePatientTaskScheduleSerializer(queryset, many=True).data 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, '', data=data, paginator=self.paginator)
def list(self, request): try: # In case it's an Admin -> Retrieve ALL patients info if request.ROLE_ID == 1: queryset = self.paginate_queryset(Patient.objects.all()) # In case it's a Doctor -> Retrieve ALL his/her patients info elif request.ROLE_ID == 2: patients_ids = list( DoctorPatient.objects.filter(doctor_id=request.USER_ID).values_list('patient_id', flat=True)) queryset = self.paginate_queryset(Patient.objects.filter(pk__in=patients_ids)) # In case it's a Patient -> Retrieve info about that specific patient elif request.ROLE_ID == 3: return PatientViewSet.retrieve(request, request.USER_ID) else: raise HttpException(400) patients = PatientSerializer(queryset, many=True).data data = [] for patient in patients: record = dict(patient) # DOCTORS doctors = DoctorPatient.objects.filter(patient=patient['user']).all() record['doctors_associated'] = [DoctorSerializer(d.doctor, many=False).data for d in doctors] # CONSTRAINTS constraints = PatientConstraintType.objects.filter(patient=patient['user']).all() record['constraints'] = [ConstraintTypeSerializer(c.constraint_type, many=False).data for c in constraints] data.append(record) 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, '', data=data, paginator=self.paginator)
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, '')
def cancel(request, pk=None): try: prehab = Prehab.objects.get(pk=pk) 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.') if request.ROLE_ID == 2 and not DoctorPatient.objects.is_a_match( request.USER_ID, prehab.patient.pk): raise HttpException( 400, 'Paciente não é paciente do medico especificado.'.format( prehab.patient.pk, request.USER_ID), 'Patient {} is not from doctor {}.'.format( prehab.patient.pk, request.USER_ID)) prehab.actual_end_date = datetime.date.today() prehab.status = Prehab.CANCEL prehab.save() except Patient.DoesNotExist as e: return HTTP.response( 400, 'Paciente não encontrado.', 'Patient with id {} not found.'.format( request.data['patient_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 return HTTP.response(200, 'Prehab cancelado com sucesso.')
def logout(request): # TODO - Not Implemented - blacklist token return HTTP.response(200)
def destroy(request, pk=None): return HTTP.response(405)
def update(request, pk=None): return HTTP.response(405)
def list(self, request): try: if 'active' in request.GET and request.GET.get('active'): prehabs = Prehab.objects.filter(status__not_in=4) else: prehabs = Prehab.objects.filter(status__lt=4) # In case it's an Admin -> Retrieve ALL PREHABS info if request.ROLE_ID == 1: prehabs = prehabs.all() # In case it's a Doctor -> Retrieve ALL plans created by him elif request.ROLE_ID == 2: prehabs = prehabs.filter(created_by=request.USER_ID).all() # In case it's a Patient -> Retrieve his plan elif request.ROLE_ID == 3: prehabs = prehabs.filter(patient_id=request.USER_ID).all() else: raise HttpException(400) queryset = self.paginate_queryset(prehabs) data = PrehabSerializer(queryset, many=True).data for record in data: # STATISTICS prehab = Prehab.objects.get(pk=record['id']) patient_tasks = PatientTaskSchedule.objects.filter( prehab=prehab).all() past_patient_tasks = [ t for t in patient_tasks if t.week_number <= prehab.get_current_week_num() and t.day_number <= prehab.get_current_day_num() ] record['info'] = { 'patient_id': prehab.patient.pk, 'patient_tag': prehab.patient.patient_tag, 'prehab_week_number': prehab.number_of_weeks, 'prehab_start_date': prehab.init_date, 'prehab_expected_end_date': prehab.expected_end_date, 'surgery_day': prehab.surgery_date, 'days_until_surgery': prehab.get_days_to_prehab_end() if prehab.get_days_to_prehab_end() else None, 'total_activities': len(patient_tasks), 'total_activities_until_now': len(past_patient_tasks), 'activities_done': len([ t for t in past_patient_tasks if t.status == PatientTaskSchedule.COMPLETED ]), 'activities_with_difficulty': len([t for t in past_patient_tasks if t.was_difficult]), 'activities_not_done': len([ t for t in past_patient_tasks if t.status == PatientTaskSchedule.NOT_COMPLETED ]), 'prehab_status_id': prehab.status, 'prehab_status': prehab.get_status_display(), 'number_of_alerts_unseen': len([ t for t in past_patient_tasks if (t.status == PatientTaskSchedule.NOT_COMPLETED or t.was_difficult) and not t.seen_by_doctor ]), 'number_of_alerts': len([ t for t in past_patient_tasks if (t.status == PatientTaskSchedule.NOT_COMPLETED or t.was_difficult) ]) } 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, '', data=data) # , paginator=self.paginator)
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)