Skip to content

Commit

Permalink
Merge pull request #3 from Ckk3/feature/generate-pdfs
Browse files Browse the repository at this point in the history
New feature: Generate pdfs
  • Loading branch information
filiperochalopes authored Dec 8, 2022
2 parents 7a03350 + 91623b3 commit 893e343
Show file tree
Hide file tree
Showing 118 changed files with 33,259 additions and 322 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ POSTGRES_USER="postgres"
POSTGRES_PASSWORD="kd&njf%s7@nme$7"
FLASKAPP_PORT=5006
APP_PORT=83
SECRET_KEY=40da743e52d28395796361da56614621fd4b59cd1338dd4587918fb6d8e18106
SECRET_KEY="40da743e52d28395796361da56614621fd4b59cd1338dd4587918fb6d8e18106"
MASTER_KEY="passw@rd"
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ POSTGRES_USER="postgres"
POSTGRES_PASSWORD="kd&njf%s7@nme$7"
FLASKAPP_PORT=5006
APP_PORT=83
SECRET_KEY=
SECRET_KEY=
MASTER_KEY=
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
__pycache__
.env
sqlite3.db
.idea
flaskapp/app/graphql/mutations/pdfs/tests/pdfs_created_files_test/*
instance/
*.db
21 changes: 15 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
build:
docker-compose build --no-cache
run:
docker-compose up -d --build
docker-compose up --build
logs:
docker-compose logs -f
seed:
docker exec -it mapa_ga_filipelopesmedbr_flaskapp bash -c "FLASK_APP=app/__init__.py && \
docker exec -it evolucao_hospitalar_flaskapp bash -c "FLASK_APP=app/__init__.py && \
flask seed"
terminal:
docker exec -it mapa_ga_filipelopesmedbr_flaskapp bash
docker exec -it evolucao_hospitalar_flaskapp bash
shell:
docker exec -it mapa_ga_filipelopesmedbr_flaskapp bash -c "flask shell"
docker exec -it evolucao_hospitalar_flaskapp bash -c "flask shell"
migrate:
docker exec -it mapa_ga_filipelopesmedbr_flaskapp bash -c "flask db upgrade"
docker exec -it evolucao_hospitalar_flaskapp bash -c "flask db upgrade"
makemigrations:
docker exec -it mapa_ga_filipelopesmedbr_flaskapp bash -c 'flask db migrate -m "$(m)"'
docker exec -it evolucao_hospitalar_flaskapp bash -c 'flask db migrate -m "$(m)"'
reset_db:
docker exec -it evolucao_hospitalar_flaskapp bash -c ' \
rm -rf migrations && \
rm -rf instance && \
flask db init && \
flask db migrate -m "Initial migration" && \
flask db upgrade'
76 changes: 70 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# O que é um MAPA?
# Sistema de Evolução Clínica

MAPA de pacientes é uma ferramenta onde colocamos de forma resumida os dados relevantes dos paciente internados para melhorar o seguimento do cuidado.
Inicialmente criado com a ideia de ser um registro para acompanhamento de pacientes por médicos de um pronto atendimento, o conceito foi migrado ao notar a debilidade de um Hospital de Pequeno Porte em registrar as condutas de seus pacientes. Esse novo escopo visa ser responsável pela melhoria da comunicação e atenção da equipe.

# Sobre o sistema
## Ambiente de desenvolvimento

O sistema foi criado para viabilizar um mapa simples, como um projeto piloto pessoal para minha prática médiga em uma Policlínica
Para desenvolvimento foi criado um ambiente docker que supre as necessidades da construção, entretando para produção será instalado em um computador Windows de baixo custo da unidade que funcionará como servidor.

### Gerando secret key

Expand All @@ -27,13 +27,77 @@ make migrate

```sh
make migrate
make comment="update some table" makemigrations
make m="update some table" makemigrations
```

## Utilizando o alembic no
## Utilizando o alembic no ambiente de desenvolvimento

```sh
# Abrindo terminal no container flask
make terminal
flask db init
flask db migrate -m "Initial migration"
flask db upgrade
```

## Ambiente de produção

Orientações para instalação de todo o sistema em Windows

### instalando dependências

Instalamos o [python](https://www.python.org/downloads/) e o [node](https://nodejs.org/en/download/). Após isso ié necessário [criar um ambiente virtual](https://docs.python.org/pt-br/3/library/venv.html#creating-virtual-environments) e o [yarn] que será necessário para criar a build React:

```sh
npm install --global yarn
```

### Realizando a build React

```sh
cd flaskapp/app/templates/reactapp
yarn
yarn build
```

### Rodando aplicação completa

```sh
cd flaskapp
# criando ambiente virtual
python -m venv path/to/myenv
# ativando o ambiente virtual
myenv/Scripts/activate
FLASK_APP=app/__init__.py
FLASK_DEBUG=false
pip install -r requirements.txt
gunicorn --bind 0.0.0.0:5000 wsgi:app --daemon
```

### Rodando ao inicializar Windows 7

Salvar arquivo `C:\Users\(username)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\run_internment.bat`:

```bat
@echo off
cd C:\path\to\project
myenv/Scripts/activate
FLASK_APP=app/__init__.py
FLASK_DEBUG=false
gunicorn --bind 0.0.0.0:5000 wsgi:app --daemon
```

# Como rodar os testes
### Entre no diretorio /app/app
```cd /app/app```
### Agora rode os teste utilizando esse comando
```pytest /app/app/graphql/mutations/pdfs/tests/```

### O resultado é pra ser parecido isso:
```
root@d956c3253006:/app/app# pytest /app/app/graphql/mutations/pdfs/tests/
========================================================================================== test session starts ==========================================================================================platform linux -- Python 3.8.15, pytest-7.1.3, pluggy-1.0.0
rootdir: /app/app
plugins: anyio-3.6.1
collected 819 items
```
9 changes: 5 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
version: "3"
services:
flaskapp:
container_name: mapa_ga_filipelopesmedbr_flaskapp
container_name: evolucao_hospitalar_flaskapp
restart: always
build:
context: ./flaskapp
dockerfile: Dockerfile
environment:
- SECRET_KEY=${SECRET_KEY}
volumes:
- ./flaskapp:/app
environment:
- SECRET_KEY=${SECRET_KEY}
- MASTER_KEY=${MASTER_KEY}
ports:
- "${FLASKAPP_PORT}:5000"
nginx:
container_name: mapa_ga_filipelopesmedbr_nginx
container_name: evolucao_hospitalar_nginx
restart: always
build:
context: .
Expand Down
2 changes: 1 addition & 1 deletion flaskapp/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ RUN pip3 install -r requirements.txt
COPY . .

ENV FLASK_APP=app/__init__.py
ENV FLASK_ENV=development
ENV FLASK_DEBUG=true

EXPOSE 5000

Expand Down
145 changes: 124 additions & 21 deletions flaskapp/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,145 @@
from app.routes.auth import auth as auth_blueprint
from app.routes.main import main as main_blueprint
from flask_autocrud import AutoCrud
from flask_login import LoginManager
from flask import Flask
from .env import InstitutionData
from .graphql import query, type_defs, mutation
from flask import Flask, request, jsonify, send_from_directory
from flask_migrate import Migrate
from ariadne import graphql_sync, make_executable_schema
from flask_scss import Scss
from app.models import db
from app.models import User
from ariadne.constants import PLAYGROUND_HTML
from app.models import db, Cid10, Config, Diet, Drug, DrugKindEnum, FluidBalance, NursingActivity, RestingActivity, State
from flask_cors import CORS
from app.serializers import ma
from flask import Blueprint, render_template

import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite+pysqlite:///db.sqlite3'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///local.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['AUTOCRUD_METADATA_ENABLED'] = True
app.secret_key = os.getenv('SECRET_KEY')

db.init_app(app)
ma.init_app(app)
CORS(app)


# AutoCrud(app, db)
migrate = Migrate(app, db)
Scss(app, static_dir='app/static/css', asset_dir='app/assets/scss')

login_manager = LoginManager()
login_manager.init_app(app)

main = Blueprint('main', __name__)


@app.route('/templates/reactapp/build/<path:path>')
def send_report(path):
return send_from_directory('templates/reactapp/build', path)


@main.route('/<path:path>')
def index(path):
return render_template('reactapp/build/index.html')


schema = make_executable_schema(type_defs, [query, mutation])


@app.route("/api/v1/graphql", methods=["GET"])
def graphql_playground():
'''
Create a GraphQL Playground UI for the GraphQL schema
'''
# Playground accepts GET requests only.
# If you wanted to support POST you'd have to
# change the method to POST and set the content
# type header to application/graphql
return PLAYGROUND_HTML

@login_manager.user_loader
def load_user(user_id):
return db.session.query(User).get(user_id)
# Create a GraphQL endpoint for executing GraphQL queries


@app.route("/api/v1/graphql", methods=["POST"])
def graphql_server():
data = request.get_json()
success, result = graphql_sync(
schema, data, context_value={"request": request})
status_code = 200 if success else 400
return jsonify(result), status_code


app.register_blueprint(main)

'''
Comandos flask cli
'''

app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint)

@app.cli.command("seed")
def seed():
"""Seed the database."""
user_1 = User(username="medico", password="senha@123".encode('utf-8'))
db.session.add(user_1)
db.session.commit()
print(user_1)
import csv

# cadastrando lista de Cid10
with open(os.path.join(os.path.dirname(__file__), 'assets', 'CID-10-DATASUS.csv'), 'r', encoding='ISO-8859-1') as file:
csvreader = csv.reader(file, dialect='excel', delimiter=';')
next(file)
for row in csvreader:
cid10 = Cid10(code=row[0], description=row[4])
db.session.add(cid10)

# cadastrando lista de Estados
with open(os.path.join(os.path.dirname(__file__), 'assets', 'ESTADOS-UF.csv'), 'r') as file:
csvreader = csv.reader(file, delimiter=',')
next(file)
for row in csvreader:
state = State(ibge_code=int(row[0]), name=row[1], uf=row[2])
db.session.add(state)

# Adicionando configurações das instituições
configs = [
Config(key='institution_name',
value=InstitutionData.NAME[0]),
Config(key='institution_cnes', value=InstitutionData.CNES[0]),
Config(key='institution_director', value=InstitutionData.DIRECTOR[0]),
Config(key='institution_cnpj', value=InstitutionData.CNPJ[0]),
]
db.session.bulk_save_objects(configs)

# Adicionando algumas medicações iniciais
drugs = [
Drug(name='Dipirona 500mg/mL 2ml', usual_dosage='1g (1 ampola) no momento', usual_route='Intramuscular', comment='Dose pediátrica: (20-25mg/kg/dose), dica: Dividir o peso em kg por 20 é a quantidade em ml a sr administrada EV/IM', kind=DrugKindEnum.oth),
Drug(name='Diclofenaco 25mg/ml 3m', usual_dosage='75mg (1 ampola) no momento', usual_route='Intramuscular', kind=DrugKindEnum.oth),
Drug(name='Dexametasona 4mg/2,5ml', usual_dosage='10mg (1 ampola) no momento', usual_route='Intramuscular', kind=DrugKindEnum.oth),
Drug(name='Nebulização 1ml de adrenalina + 5ml de SF 0,9% + 10 gotas de Ipratrópio 0,25 mg/mL', usual_dosage='1g (1 ampola) no momento', usual_route='Inalatória por via nasal', comment='Zhang L, Sanguebsche LS. The safety of nebulization with 3 to 5 ML of adrenaline (1:1000) in children: An evidence based review. Jornal de Pediatria. 2005;81(3):193–7. ', kind=DrugKindEnum.oth),
Drug(name='Ceftriaxona 1g', usual_dosage='1g 12/12h', usual_route='Endovenoso', comment='Dose pediátrica usual: (50mg/kg/dose) 12/12h', kind=DrugKindEnum.atb),
Drug(name='Oxigênio', usual_dosage='Cateter nasal 3L/min se SpO2 < 92%', usual_route='Nasal', kind=DrugKindEnum.oth),
Drug(name='Oxigênio', usual_dosage='Cateter nasal 3L/min', usual_route='Nasal', kind=DrugKindEnum.oth),
]
db.session.bulk_save_objects(drugs)
# Adicionando algumas atividades de enfermagem iniciais
nursing_activities = [
NursingActivity(name='Aferir sinais vitais 6/6h'),
NursingActivity(name='Monitoração multiparamétrica contínua(cardioscopia, pressão arterial, saturação de O2'),
NursingActivity(name='Balanço hídrico'),
]
db.session.bulk_save_objects(nursing_activities)
# Adicionando algumas atividades de descanso
resting_activities = [
RestingActivity(name='Repouso absoluto, cabeceira elevada 30°, atenção para lesões por pressão. Variar decúbito a cada 2h'),
RestingActivity(name='Repouso relativo'),
]
# Adicionndo alguns tipos de dieta
diets = [
Diet(name='Dieta livre'),
Diet(name='Dieta branda, para diabéticos (sem carboidratos simples)'),
Diet(name='Dieta branda, para hipertensos (hipossódica)'),
Diet(name='Dieta branda, para hipertensos e diabéticos'),
Diet(name='Dieta pastosa'),
Diet(name='Dieta líquida'),
Diet(name='Dieta zero')
]
# Adicionndo algumas descrições de Balanço hídrico
fluid_balance_description = [

]

# Enviando informações para o banco
db.session.commit()
Loading

0 comments on commit 893e343

Please sign in to comment.