Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Zimovchik committed Jul 17, 2024
1 parent 473d186 commit e694bd6
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 5 deletions.
17 changes: 16 additions & 1 deletion userdata_api/routes/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from userdata_api.schemas.response_model import StatusResponseModel
from userdata_api.schemas.user import UserInfoGet, UserInfoUpdate, UsersInfoGet
from userdata_api.utils.user import get_user_info as get
from userdata_api.utils.user import get_users_info as get_users
from userdata_api.utils.user import patch_user_info as patch


Expand All @@ -16,7 +17,8 @@

@user.get("/{id}", response_model=UserInfoGet)
async def get_user_info(
id: int, user: dict[str, Any] = Depends(UnionAuth(scopes=[], allow_none=False, auto_error=True))
id: int,
user: dict[str, Any] = Depends(UnionAuth(scopes=[], allow_none=False, auto_error=True)),
) -> UserInfoGet:
"""
Получить информацию о пользователе
Expand Down Expand Up @@ -65,13 +67,22 @@ async def update_user(
:return:
"""
await patch(new_info, id, user)
<<<<<<< Updated upstream
return StatusResponseModel(status='Success', message='User patch succeeded', ru="Изменение успешно")
=======
return StatusResponseModel(status="Success", message="User patch succeeded", ru="Изменение успешно")
>>>>>>> Stashed changes


@user.get("", response_model=UsersInfoGet, response_model_exclude_unset=True)
async def get_users_info(
<<<<<<< Updated upstream
users: list[int] = Query(None),
categories: list[str] = Query(None),
=======
users: list[int] = Query(),
categories: list[str] = Query(),
>>>>>>> Stashed changes
user: dict[str, Any] = Depends(UnionAuth(scopes=["userdata.info.admin"], allow_none=False, auto_error=True)),
) -> UsersInfoGet:
"""
Expand All @@ -82,7 +93,11 @@ async def get_users_info(
:return: словарь, где ключь - id пользователя, значение - информация.
Например: {users: {1: {}, 2: {}}}
"""
<<<<<<< Updated upstream
result = {}
for user_id in users:
result[user_id] = await get(user_id, user, categories)
return UsersInfoGet(users=result)
=======
return UsersInfoGet.model_validate(await get_users(users, categories, user))
>>>>>>> Stashed changes
73 changes: 69 additions & 4 deletions userdata_api/utils/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from userdata_api.exceptions import Forbidden, ObjectNotFound
from userdata_api.models.db import Category, Info, Param, Source, ViewType
from userdata_api.schemas.user import UserInfoGet, UserInfoUpdate
from userdata_api.schemas.user import UserInfoGet, UserInfoUpdate, UsersInfoGet


async def patch_user_info(new: UserInfoUpdate, user_id: int, user: dict[str, int | list[dict[str, str | int]]]) -> None:
Expand Down Expand Up @@ -68,7 +68,10 @@ async def patch_user_info(new: UserInfoUpdate, user_id: int, user: dict[str, int
db.session.query(Info)
.join(Source)
.filter(
Info.param_id == param.id, Info.owner_id == user_id, Source.name == new.source, not_(Info.is_deleted)
Info.param_id == param.id,
Info.owner_id == user_id,
Source.name == new.source,
not_(Info.is_deleted),
)
.one_or_none()
)
Expand Down Expand Up @@ -181,8 +184,70 @@ async def get_user_info(
for item in param_dict.values():
if isinstance(item, list):
result.extend(
[{"category": _item.category.name, "param": _item.param.name, "value": _item.value} for _item in item]
[
{
"category": _item.category.name,
"param": _item.param.name,
"value": _item.value,
}
for _item in item
]
)
else:
result.append({"category": item.category.name, "param": item.param.name, "value": item.value})
result.append(
{
"category": item.category.name,
"param": item.param.name,
"value": item.value,
}
)
return UserInfoGet(items=result)


async def get_users_info(
users: list[int],
categories: list[str],
user: dict[str, int | list[dict[str, str | int]]],
) -> UsersInfoGet:
"""
Возвращает информацию о данных пользователей в указанных категориях
:param users: Список айди юзеров
:param categories: Список необходимых категорий
:param user: Сессия выполняющего запрос данных
:return: Словарь, где ключи - айди юзеров, значение - словарь данных, как в get_user_info
"""
scope_names = [scope["name"] for scope in user["session_scopes"]]
infos: list[Info] = (
Info.query(session=db.session)
.join(Param)
.join(Category)
.filter(
Info.owner_id.in_(users),
Param.category_id.in_(
Category.query(session=db.session).filter(Category.name.in_(categories)).with_entities(Category.id)
),
not_(Param.is_deleted),
not_(Category.is_deleted),
not_(Info.is_deleted),
)
.all()
)
if not infos:
raise ObjectNotFound(Info, users)
result = {}
for info in infos:
if info.owner_id not in result:

result[info.owner_id] = {"items": []}
if info.category.read_scope and info.category.read_scope not in scope_names and user["id"] != info.owner_id:
continue
result[info.owner_id]["items"].append(
{
"category": info.category.name,
"param": info.param.name,
"value": info.value,
}
)
print(result)
return UsersInfoGet(users=result)

0 comments on commit e694bd6

Please sign in to comment.