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 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 validate_obj_structure(req_json, file_path): try: with open('prehab_app/schemas/' + file_path, encoding='utf-8') as data_file: schema = json.loads(data_file.read()) jsonschema.validate(req_json, schema) except jsonschema.SchemaError as e: raise HttpException(400, 'Erro de Validação de dados.', e.message) except jsonschema.ValidationError as e: if e.validator in ('pattern', 'required', 'maxLength'): detail = "Validation Error. Parameter {}".format(e.message.replace('\'', '')) else: detail = "Validation Error. {}".format(SchemaValidator.get_error_message(e)) raise HttpException(400, 'Erro de Validação de dados', detail) # except AttributeError as e: # raise HttpException(400, str(e)) except FileNotFoundError as e: raise HttpException(400, 'Erro com esquema de validação.', "File {} not found".format(e.filename)) # except Exception as e: # raise HttpException(400, str(e)) return None
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 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 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 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 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 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 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 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 _get_meals(meals, times): meals_bulk = [] if len(meals) == 0: raise HttpException( 401, 'Não existem refeições para este tipo de paciente.', 'Number of meals for this type of patient is zero.') for i in range(math.ceil(times / len(meals))): meals_bulk = meals_bulk + list(meals) return random.sample(meals_bulk, times)
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 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 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 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.')
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)
def retrieve(request, pk=None): try: prehab = Prehab.objects.get(pk=pk) if request.ROLE_ID != 1 and request.USER_ID not in ( prehab.created_by.user.id, prehab.patient.user.id): raise HttpException( 401, 'Você não tem permissões para ver este prehab.', 'You don\'t have permissions to see this Prehab Plan') # STATISTICS patient_tasks = PatientTaskSchedule.objects.filter( prehab=prehab).all() pass_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() ] prehab_statistics = { '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() } # DOCTORS prehab_doctors = [] for doctor_patient in DoctorPatient.objects.filter( patient=prehab.patient).all(): prehab_doctors.append( SimpleDoctorSerializer(doctor_patient.doctor, many=False).data) except Prehab.DoesNotExist: return HTTP.response( 404, 'Prehab não encontrado', 'Prehab 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))) data = FullPrehabSerializer(prehab, many=False).data data['alerts'] = [ { 'patient_task_schedule_id': t['id'], 'task_title': t['title'], 'task_description': t['description'], 'task_type': t['task_type'], 'status': t['status'], 'date': t['patient_task_info']['date'].split('T')[0], 'seen_by_doctor': t['patient_task_info']['seen_by_doctor'], 'doctor_notes': t['patient_task_info']['doctor_notes'], 'was_difficult': t['patient_task_info']['was_difficult'], } for d, tasks in data['task_schedule'].items() for t in tasks if t['patient_task_info']['was_difficult'] or t['status_id'] == PatientTaskSchedule.NOT_COMPLETED ] data['number_of_alerts_unseen'] = len( [a for a in data['alerts'] if not a['seen_by_doctor']]) data['number_of_alerts'] = len(data['alerts']) data['statistics'] = prehab_statistics data['patient'] = PatientWithConstraintsSerializer(prehab.patient, many=False).data data['patient']['patient_constraints'] = [ patient_constraint['constraint_type']['title'] for patient_constraint in data['patient']['patient_constraints'] ] data['doctors'] = prehab_doctors return HTTP.response(200, data=data)
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)
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)