Skip to content

Commit

Permalink
Merge pull request #317 from noharm-ai/develop
Browse files Browse the repository at this point in the history
v3.02-beta
  • Loading branch information
marceloarocha authored May 26, 2024
2 parents 0d8e63f + 650eb9b commit 22f5fd9
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 28 deletions.
2 changes: 1 addition & 1 deletion mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@

@app.route("/version", methods=["GET"])
def getVersion():
return {"status": "success", "data": "v3.01-beta"}, status.HTTP_200_OK
return {"status": "success", "data": "v3.02-beta"}, status.HTTP_200_OK


@app.route("/exc", methods=["GET"])
Expand Down
146 changes: 121 additions & 25 deletions routes/names.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,135 @@
from flask import current_app
from os import getenv
import requests
from flask import Blueprint
from flask_jwt_extended import jwt_required, get_jwt
import logging
from http.client import HTTPConnection
from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from models.main import User, dbSession, db
from models.appendix import SchemaConfig
from exception.validation_error import ValidationError
from utils import status

app_names = Blueprint("app_names", __name__)


@app_names.route("/names/<int:idPatient>", methods=["GET"])
@jwt_required()
def proxy_name(idPatient):
return "not implemented"
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)

config = _get_config(user)
token = _get_token(config)

url = config["getname"]["url"]
params = dict(config["getname"]["params"], **{"cd_paciente": idPatient})
response = requests.get(
url,
headers={"Authorization": token},
params=params,
)

if response.status_code != status.HTTP_200_OK:
raise ValidationError(
"Erro ao buscar nome",
"errors.invalid",
response.status_code,
)

data = response.json()

if len(data["data"]) > 0:
patient = data["data"][0]

return {
"status": "success",
"idPatient": patient["idPatient"],
"name": patient["name"],
}, status.HTTP_200_OK
else:
return {
"status": "error",
"idPatient": int(idPatient),
"name": f"Paciente {str(int(idPatient))}",
}, status.HTTP_400_BAD_REQUEST


@app_names.route("/names", methods=["POST"])
@jwt_required()
def proxy_multiple():
user = User.find(get_jwt_identity())
dbSession.setSchema(user.schema)

data = request.get_json()
ids_list = data.get("patients", [])
config = _get_config(user)
token = _get_token(config)

url = config["getname"]["url"]
params = dict(
config["getname"]["params"],
**{"cd_paciente": " ".join(str(id) for id in ids_list)},
)
response = requests.get(url, headers={"Authorization": token}, params=params)

if response.status_code != status.HTTP_200_OK:
raise ValidationError(
"Erro ao buscar nome",
"errors.invalid",
response.status_code,
)

data = response.json()
found = []
names = []

for p in data["data"]:
found.append(str(p["idPatient"]))
names.append(
{"status": "success", "idPatient": p["idPatient"], "name": p["name"]}
)

for id_patient in ids_list:
if str(id_patient) not in found:
names.append(
{
"status": "error",
"idPatient": int(id_patient),
"name": "Paciente " + str(int(id_patient)),
}
)

return names, status.HTTP_200_OK


def _get_token(config):
token_url = config["getname"]["token"]["url"]
params = config["getname"]["token"]["params"]

response = requests.post(url=token_url, data=params)

if response.status_code != status.HTTP_200_OK:
raise ValidationError(
"Token inválido",
"errors.unauthorizedUser",
response.status_code,
)

# HTTPConnection.debuglevel = 1
# requests_log = logging.getLogger("requests.packages.urllib3")
# requests_log.setLevel(logging.DEBUG)
# requests_log.propagate = True
token_data = response.json()

# claims = get_jwt()
# schema = claims["schema"].upper()
# to_url = getenv(schema + '_PROXY_URL')
# header_env = getenv(schema + '_PROXY_HEADERS')
# headers = {}
return token_data["access_token"]

# #split headers
# for h in header_env.split("@@"):
# item = h.split(":")
# headers[item[0]] = item[1]

# response = requests.get(\
# url=to_url.replace("{idPatient}", str(idPatient)),\
# headers=headers)
def _get_config(user: User):
schema_config = (
db.session.query(SchemaConfig)
.filter(SchemaConfig.schemaName == user.schema)
.first()
)

# current_app.logger.info('proxyresponse %s', response.content)
if schema_config.config == None or "getname" not in schema_config.config:
raise ValidationError(
"Getname sem configuração",
"errors.invalid",
status.HTTP_400_BAD_REQUEST,
)

# return response.json()
return schema_config.config
2 changes: 1 addition & 1 deletion services/admin/integration_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def get_table_count(schema, table):


def can_refresh_agg(schema):
max_table_count = 500000
max_table_count = 300000

return get_table_count(schema, "prescricaoagg") <= max_table_count

Expand Down
2 changes: 1 addition & 1 deletion services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def _auth_user(
"nameUrl": nameUrl["value"] if "value" in nameUrl else None,
"multipleNameUrl": nameUrl["multiple"] if "multiple" in nameUrl else None,
"nameHeaders": nameUrl["headers"] if "headers" in nameUrl else {},
"proxy": True if "to" in nameUrl else False,
"proxy": nameUrl["proxy"] if "proxy" in nameUrl else False,
"notify": notification,
"access_token": access_token,
"refresh_token": refresh_token,
Expand Down

0 comments on commit 22f5fd9

Please sign in to comment.