---
# System prepended metadata

title: Salusive - Backend v2

---

# Salusive - Backend v2
#### Germán Castro
#### german@strivelabs.io

---

This document will show all changes and new features implemented. It will try to explain in the simplest and most concise way possible. Any doubt or comment can be made in the document itself, to my mail or by slack. The document is in continuous development.


## Applications

The first point to highlight are the applications. A project in Django is composed of different applications that are connected. In other words, the project is modular. The applications must meet a minimum of functionality to be considered as such.

The old backend has the following applications:

- api: a list of endpoints without functionalities :-1: 
- home: a blank index :-1: 
- main: measurements, schedule, hospital...
- hosp_auth: doctor, patient, profiles...

In conclusion, there are only 2 applications without any organization. This must change.

For the second version, the following applications are developed. Each of them are entities with their own functionalities.

- facilities.
- providers.
- measurements.
- utils: contains different utilities common to various applications.
- salusive: the main application. It contains the settings and endpoints of the api.
- More applications not yet programmed.

Now the code is much more accessible and intelligently separated. :smile: 

---
## Packages and dependencies

The packages have been updated to more recent versions avoiding using deprecated packages.

* psycopg2 2.6.1 to **2.7**
* django 1.11 to to **2.2** (deprecated in 2020)
* djangorestframework 3.4 to **3.9**
* drf-nested-routers 0.11 to **0.91**
* More outdated dependencies. They will be indicated when they are used.


---
## Authentication

In the old backend, authentication is hardcoded, i.e. hand programmed. This increases the risk of bugs or failures.

Instead of completely rewriting it using the newly created models, it is preferable to use a well-tested package that minimizes the risks. 

On the other hand, in the old backend there are two login endpoints, depending on whether it is done in the app or on the web (this is counterproductive!). If there is something to change, it must be done on several sites).

The new backend uses **djangorestframework_simplejwt**, recommended by the developers of django rest framework.

In addition, this package gives us the possibility to have two tokens. The first one for access, the second one to regenerate the access token in case it expires. This significantly increases security without complicating the system.

```json
{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU3MDU0NDE5MSwianRpIjoiYjkyNTlhMGRiNDY2NDhmNDljMWViYmY3NmY3NTYwODMiLCJ1c2VyX2lkIjoxfQ.4BpqSKlz2Qii18d5NobE0qhdrqC0mcz6J_nA7CuE3RE",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTY1MTAwOTkxLCJqdGkiOiI5MWRhMGNlOTZhYTM0ZjUxOWI0ZDk2NzE1Y2Q0OWQyYyIsInVzZXJfaWQiOjF9.dMMdehF23Bhlq211JNKB9xswjeIXdbYuRew257ODQHo"
}
```
---
## Loggers

The configuration of the loggers has been reimplemented.

* Formats have been added for a clearer output of information both in console and file.

* In the new implementation, the logger *django.security* has been added to capture possible security problems and unsafe access.

* Depending on the working mode selected when launching the server (dev, staging, production) the loggers will show more or less information.

* The loggers in the different files have been rewritten (obviously)

* It is considered to implement a third party service for the capture of logs in critical environments (staging, production). The possibilities are: *Sentry* and *AWS Cloudwatch*. This section will be developed once one of the options has been implemented.

---
## Storage

S3 (AWS) technology is used for file storage. The current backend performs file uploads using s3's Boto client. 

In short, there are functions created by the previous developer that receive a file, upload it to s3 via client and store the url in the database. These functions must also extract the file extension and its name through regular expressions.

The new implementation uses **django-storages**. It only need a *File* or *Image* field in the model and indicate the path in the cloud.

Fast, easy and... 99% of the code (100 lines) has been removed! :rocket: 

---
## Endpoints

Endpoints in the old backend do not follow an ordered structure.

INDEX:
- /api : api urls
- /api/auth and /api/auth_portal : two endpoints for authentication! :dizzy_face: 
- /api/logout : unnecessary, is done in frontend.
- /api/check_auth
- api_auth : unnecessary

MAIN: 
- without endpoints...

HOSP_AUTH:
- without endpoints...

HOME:
- endpoint to home page (a blank page)

API: the rest of endpoints without order.

The following structure is suggested:

- /api/token for authentication
- /api/token/refresh/ for token refresh

- /api/v2/...
    - /providers
    - /facilities
    - /patients.
        - /<patient_id>/averages
        - /<patient_id>/thresholds
        - /<patient_id>/bp
        - /<patient_id>/glucose
        - ...
        - /<patient_id>/pharmacy
        - /<patient_id>/caretaker
        - /<patient_id>/schedules
        - /<patient_id>/encounters
        - /<patient_id>/documents
        - ...

The new structure is simple and intuitive. Better data handling is also achieved. To add or modify a patient-related element, it is done directly. Endpoints are also renamed, which must be plural with some exceptions.

An example with a patient's schedules:

In the old backend, a POST request had to be made to /api/schedules indicating the patient's ID.
If you wanted to get the schedules of a patient, you made a GET request to /api/schedules and filter by patient in the frontend, so the data of other patients were also sent :dizzy_face:

The new proposal works only with one patient, performing operations on him. To edit an schedule, it is enough to make a POST request to /patients/<patient_id>/schedules without indicating the patient's ID in the body, as this is implicit in the url.

At the time of receiving the schedules of a patient, these will be filtered automatically in the backend, making the application faster and safer.

---
## Facilities (Hospitals)

As indicated in previous lines, a new application **Facilities** has been created for a clearer organization.

#### Model
The data model remains similar. However, there are several changes in the methods.

In the old backend, the hospital has methods for obtaining oxygenation and blood pressure. A hospital does not have these properties. This must be done in the application of measures or patient. In addition, it does not reflect information about weight or glucose. 70 lines of code have been removed.

Also in the new model the fields *created_at* and *last_modified* are added. Sorting by creation date is also used, the *__str__* method is overloaded (a descriptive name for each *Facility* type object) and *providers* associated with the facility are allowed to be obtained.

#### Serializer
En el nuevo serializer, se especifica que el estado es un choice. También se devuelve el endpoint de los providers asociados para un fácil acceso.

#### View
The old backend generates the blood pressure and oxygenation of all patients before sending the information, which translates into unnecessary workload.

On the other hand, only the name filter is applied. New filters have been added:
* created_at
* name
* license

---

## Providers (Doctors)

#### Model
The data model remains similar. The relationship between Provider and Patient (ForeignKey field) is transferred to the patient model. The provider has a new avatar field. This is an image saved in S3. The 'created_at' and 'last_modified' fields are also added.

Sorting is used according to the last name of the provider. 

#### Serializer
The old backend has two serializers, one for GET requests and one for POST requests. They have been unified into a single serializer.

Now the facility is returned as url and the patients as a list of urls. Before it was avoided to return them.

Both serializers have email validation in case it is modified.

#### View
Views are subject to minimal change. Instead of inheriting 4 mixins, a single complete viewset is inherited, increasing functionality with minimal changes (list, get, modify, delete).

---


