Skip to content

Commit

Permalink
Merge pull request #196 from prefeitura-rio/frontend/patient-using-bi…
Browse files Browse the repository at this point in the history
…g-query-data

Frontend/patient using big query data
  • Loading branch information
TanookiVerde committed Aug 16, 2024
2 parents fd75ba0 + 9f71331 commit d7fa689
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 67 deletions.
106 changes: 41 additions & 65 deletions app/routers/frontend.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
import json
import datetime

from typing import Annotated, List
from fastapi import APIRouter, Depends, HTTPException
Expand All @@ -15,6 +14,7 @@
UserInfo,
)
from app.config import BIGQUERY_PROJECT
from app.utils import read_timestamp

router = APIRouter(prefix="/frontend", tags=["Frontend Application"])

Expand Down Expand Up @@ -91,11 +91,7 @@ async def get_patient_header(

data_nascimento = None
if data.get("data_nascimento") is not None:
data_nascimento = (
datetime.datetime(1970, 1, 1) + datetime.timedelta(
milliseconds=data.get("data_nascimento")
)
).strftime("%Y-%m-%d")
data_nascimento = read_timestamp(data.get("data_nascimento"), format='date')

return {
"registration_name": data.get("nome"),
Expand Down Expand Up @@ -164,64 +160,44 @@ async def get_patient_encounters(
cpf: str,
) -> List[Encounter]:

if cpf == '19530236069':
raise HTTPException(status_code=404, detail="Patient not found")
elif cpf == '11111111111':
raise HTTPException(status_code=400, detail="Invalid CPF")
results_json = read_sql(
f"""
SELECT *
FROM `{BIGQUERY_PROJECT}`.`saude_historico_clinico`.`episodio_assistencial`
WHERE paciente.cpf = '{cpf}'
""",
from_file="/tmp/credentials.json",
).to_json(orient="records")

return [
{
"entry_datetime": "2023-09-05T10:00:00",
"exit_datetime": "2023-09-05T12:00:00",
"location": "UPA 24h Magalhães Bastos",
"type": "Consulta",
"subtype": "Marcada",
"active_cids": ["A10.2", "B02.5"],
"responsible": {"name": "Dr. João da Silva", "role": "Médico(a)"},
"description": "Lorem ipsum dolor sit amet consectetur.",
"filter_tags": ["UPA"],
},
{
"entry_datetime": "2021-09-01T10:00:00",
"exit_datetime": "2021-09-01T12:00:00",
"location": "UPA 24h Magalhães Bastos",
"type": "Consulta",
"subtype": "Emergência",
"active_cids": ["A10.2"],
"responsible": {"name": "Dr. João da Silva", "role": "Médico(a)"},
"description": (
"Lorem ipsum dolor sit amet consectetur. Sed vel suscipit id pulvinar"
"sed nam libero eu. Leo arcu sit lacus nisl nullam eget et dignissim sed."
"Fames pretium cursus viverra posuere arcu tortor sit lectus congue. Velit"
"tempor ultricies pulvinar magna pulvinar ridiculus consequat nibh..."
),
"filter_tags": ["UPA"],
},
{
"entry_datetime": "2021-08-21T22:00:00",
"exit_datetime": "2021-08-22T02:50:00",
"location": "CMS RAPHAEL DE PAULA SOUZA",
"type": "Consulta",
"subtype": "Pediatria",
"active_cids": ["Z10.2"],
"responsible": {"name": "Mariana Gomes", "role": "Enfermeiro(a)"},
"description": (
"Lorem ipsum dolor sit amet consectetur. Sed vel suscipit id pulvinar"
"sed nam libero eu. Leo arcu sit lacus nisl nullam eget et dignissim sed."
),
"filter_tags": ["CF/CMS"],
},
{
"entry_datetime": "2021-05-11T12:00:00",
"exit_datetime": "2021-05-12T20:50:00",
"location": "Hospital Municipal Rocha Faria",
"type": "Consulta",
"subtype": "Cirurgia",
"active_cids": ["E01.3"],
"responsible": {"name": "Dra. Claudia Simas", "role": "Medico(a)"},
"description": (
"Lorem ipsum dolor sit amet consectetur. Sed vel suscipit id pulvinar."
),
"filter_tags": ["Hospital"],
encounters = []
for result in json.loads(results_json):
# Responsible professional
professional = result.get('profissional_saude_responsavel')
if professional:
professional = {
"name": professional.get('nome'),
"role": professional.get('especialidade')
}

# CIDs
cids = []
for cid in result['condicoes']:
if cid.get('descricao') is not None:
cids.append(cid['descricao'])

encounter = {
"entry_datetime": read_timestamp(result['entrada_datahora'], format='datetime'),
"exit_datetime": read_timestamp(result['saida_datahora'], format='datetime'),
"location": result['estabelecimento']['nome'],
"type": result['tipo'],
"subtype": result['subtipo'],
"active_cids": cids,
"responsible": professional,
"description": result['motivo_atendimento'],
"motivation": result['motivo_atendimento'],
"summary": result['desfecho_atendimento'],
"filter_tags": [result['estabelecimento']['estabelecimento_tipo']],
}
]
encounters.append(encounter)

return encounters
4 changes: 3 additions & 1 deletion app/types/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ class Encounter(BaseModel):
type: str
subtype: Optional[str]
active_cids: List[str]
responsible: Responsible
responsible: Optional[Responsible]
description: Optional[str]
motivation: Optional[str]
summary: Optional[str]
filter_tags: List[str]


Expand Down
13 changes: 12 additions & 1 deletion app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from datetime import datetime, timedelta
import hashlib
import json
from typing import Literal
import jwt
from passlib.context import CryptContext

Expand Down Expand Up @@ -119,4 +120,14 @@ async def get_instance(Model, table, slug=None, code=None):
elif slug:
table[slug] = await Model.get_or_none(slug=slug)

return table[slug]
return table[slug]


def read_timestamp(timestamp: int, format=Literal['date','datetime']) -> str:
value = datetime(1970, 1, 1) + timedelta(milliseconds=timestamp)
if format == 'datetime':
return value.strftime("%Y-%m-%d %H:%M:%S")
elif format == 'date':
return value.strftime("%Y-%m-%d")
else:
raise ValueError("Invalid format")

0 comments on commit d7fa689

Please sign in to comment.