This commit is contained in:
@@ -151,6 +151,17 @@ async def get_authors_with_stats(
|
|||||||
# Базовый запрос для получения авторов
|
# Базовый запрос для получения авторов
|
||||||
base_query = select(Author).where(Author.deleted_at.is_(None))
|
base_query = select(Author).where(Author.deleted_at.is_(None))
|
||||||
|
|
||||||
|
# Применяем фильтрацию по параметрам из by
|
||||||
|
if by:
|
||||||
|
for key, value in by.items():
|
||||||
|
if key != "order" and value is not None: # order обрабатывается отдельно
|
||||||
|
if hasattr(Author, key):
|
||||||
|
column = getattr(Author, key)
|
||||||
|
base_query = base_query.where(column == value)
|
||||||
|
logger.debug(f"Applied filter: {key} = {value}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"Unknown filter field: {key}")
|
||||||
|
|
||||||
# vars for statistics sorting
|
# vars for statistics sorting
|
||||||
stats_sort_field = None
|
stats_sort_field = None
|
||||||
default_sort_applied = False
|
default_sort_applied = False
|
||||||
@@ -753,29 +764,33 @@ async def get_author(
|
|||||||
if "stat" in cached_author:
|
if "stat" in cached_author:
|
||||||
author_dict["stat"] = cached_author["stat"]
|
author_dict["stat"] = cached_author["stat"]
|
||||||
|
|
||||||
if not author_dict or not author_dict.get("stat"):
|
# ВСЕГДА используем новый резолвер для получения полной статистики
|
||||||
# update stat from db using new comprehensive stats
|
try:
|
||||||
try:
|
# Используем новый резолвер для получения полной статистики
|
||||||
# Используем новый резолвер для получения полной статистики
|
filter_by: AuthorsBy = {}
|
||||||
filter_by: AuthorsBy = {}
|
if slug:
|
||||||
if slug:
|
filter_by["slug"] = slug
|
||||||
filter_by["slug"] = slug
|
elif author_id:
|
||||||
elif author_id:
|
filter_by["id"] = author_id # author_id уже int
|
||||||
filter_by["id"] = author_id # author_id уже int
|
|
||||||
|
|
||||||
authors_with_stats = await get_authors_with_stats(limit=1, offset=0, by=filter_by)
|
logger.debug(f"Calling get_authors_with_stats with filter: {filter_by}")
|
||||||
if authors_with_stats and len(authors_with_stats) > 0:
|
authors_with_stats = await get_authors_with_stats(limit=1, offset=0, by=filter_by)
|
||||||
author_dict = authors_with_stats[0]
|
|
||||||
# Фильтруем данные согласно правам доступа
|
if authors_with_stats and len(authors_with_stats) > 0:
|
||||||
if not is_admin:
|
author_dict = authors_with_stats[0]
|
||||||
# Убираем защищенные поля для не-админов
|
logger.debug(f"Got author with stats: shouts={author_dict.get('stat', {}).get('shouts', 'missing')}")
|
||||||
protected_fields = ["email", "phone"]
|
|
||||||
for field in protected_fields:
|
# Фильтруем данные согласно правам доступа
|
||||||
author_dict.pop(field, None)
|
if not is_admin:
|
||||||
# Кэшируем полные данные для админов
|
# Убираем защищенные поля для не-админов
|
||||||
_t = asyncio.create_task(cache_author(author_dict))
|
protected_fields = ["email", "phone"]
|
||||||
except Exception as e:
|
for field in protected_fields:
|
||||||
logger.error(f"Error getting author stats: {e}")
|
author_dict.pop(field, None)
|
||||||
|
|
||||||
|
# Кэшируем полные данные для админов
|
||||||
|
_t = asyncio.create_task(cache_author(author_dict))
|
||||||
|
else:
|
||||||
|
logger.warning(f"No author found with filter: {filter_by}")
|
||||||
# Fallback to basic author data without stats
|
# Fallback to basic author data without stats
|
||||||
with local_session() as session:
|
with local_session() as session:
|
||||||
if slug:
|
if slug:
|
||||||
@@ -784,6 +799,17 @@ async def get_author(
|
|||||||
author = session.query(Author).filter_by(id=author_id).first()
|
author = session.query(Author).filter_by(id=author_id).first()
|
||||||
if author:
|
if author:
|
||||||
author_dict = author.dict(is_admin)
|
author_dict = author.dict(is_admin)
|
||||||
|
logger.debug(f"Using fallback author dict: {author_dict.get('name', 'unknown')}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting author stats: {e}")
|
||||||
|
# Fallback to basic author data without stats
|
||||||
|
with local_session() as session:
|
||||||
|
if slug:
|
||||||
|
author = session.query(Author).filter_by(slug=slug).first()
|
||||||
|
else:
|
||||||
|
author = session.query(Author).filter_by(id=author_id).first()
|
||||||
|
if author:
|
||||||
|
author_dict = author.dict(is_admin)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -906,11 +932,11 @@ async def get_author_follows(
|
|||||||
has_access = is_admin or (viewer_id is not None and str(viewer_id) == str(temp_author.id))
|
has_access = is_admin or (viewer_id is not None and str(viewer_id) == str(temp_author.id))
|
||||||
followed_authors.append(temp_author.dict(has_access))
|
followed_authors.append(temp_author.dict(has_access))
|
||||||
|
|
||||||
# TODO: Get followed communities too
|
followed_communities = DEFAULT_COMMUNITIES # TODO: get followed communities
|
||||||
return {
|
return {
|
||||||
"authors": followed_authors,
|
"authors": followed_authors,
|
||||||
"topics": followed_topics,
|
"topics": followed_topics,
|
||||||
"communities": DEFAULT_COMMUNITIES,
|
"communities": followed_communities,
|
||||||
"shouts": [],
|
"shouts": [],
|
||||||
"error": None,
|
"error": None,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ type AuthorStat {
|
|||||||
# Взаимодействие с другими авторами
|
# Взаимодействие с другими авторами
|
||||||
coauthors: Int # Количество уникальных соавторов
|
coauthors: Int # Количество уникальных соавторов
|
||||||
followers: Int # Количество подписчиков
|
followers: Int # Количество подписчиков
|
||||||
|
authors: Int # Количество авторов, на которых подписан данный автор
|
||||||
|
|
||||||
# Рейтинговая система # Общий рейтинг (rating_shouts + rating_comments)
|
# Рейтинговая система
|
||||||
rating_shouts: Int # Рейтинг публикаций (сумма реакций LIKE/AGREE/ACCEPT/PROOF/CREDIT минус DISLIKE/DISAGREE/REJECT/DISPROOF)
|
rating_shouts: Int # Рейтинг публикаций (сумма реакций LIKE/AGREE/ACCEPT/PROOF/CREDIT минус DISLIKE/DISAGREE/REJECT/DISPROOF)
|
||||||
rating_comments: Int # Рейтинг комментариев (реакции на комментарии автора)
|
rating_comments: Int # Рейтинг комментариев (реакции на комментарии автора)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user