diff --git a/app/routers/frontend.py b/app/routers/frontend.py index c816db6..e6d79f8 100644 --- a/app/routers/frontend.py +++ b/app/routers/frontend.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- import json -import datetime from typing import Annotated, List from fastapi import APIRouter, Depends, HTTPException @@ -15,6 +14,7 @@ UserInfo, ) from app.config import BIGQUERY_PROJECT +from app.utils import read_timestamp router = APIRouter(prefix="/frontend", tags=["Frontend Application"]) @@ -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"), @@ -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 diff --git a/app/types/frontend.py b/app/types/frontend.py index 42069d7..d127684 100644 --- a/app/types/frontend.py +++ b/app/types/frontend.py @@ -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] diff --git a/app/utils.py b/app/utils.py index 46f0d37..d831e75 100644 --- a/app/utils.py +++ b/app/utils.py @@ -2,6 +2,7 @@ from datetime import datetime, timedelta import hashlib import json +from typing import Literal import jwt from passlib.context import CryptContext @@ -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] \ No newline at end of file + 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")