published_at-fix
This commit is contained in:
parent
839cc84c26
commit
0ba2d2ecee
|
@ -100,41 +100,31 @@ async def create_shout(_, info, inp):
|
||||||
logger.debug(f"Context user_id: {user_id}, author: {author_dict}")
|
logger.debug(f"Context user_id: {user_id}, author: {author_dict}")
|
||||||
|
|
||||||
if not author_dict:
|
if not author_dict:
|
||||||
logger.error("Author profile not found in context")
|
|
||||||
return {"error": "author profile was not found"}
|
return {"error": "author profile was not found"}
|
||||||
|
|
||||||
author_id = author_dict.get("id")
|
|
||||||
if user_id and author_id:
|
|
||||||
try:
|
try:
|
||||||
with local_session() as session:
|
with local_session() as session:
|
||||||
author_id = int(author_id)
|
# Добавляем текущее время как published_at если публикация не черновик
|
||||||
current_time = int(time.time())
|
current_time = int(time.time())
|
||||||
slug = inp.get("slug") or f"draft-{current_time}"
|
is_draft = inp.get("is_draft", False)
|
||||||
|
if not is_draft:
|
||||||
|
inp["published_at"] = current_time
|
||||||
|
|
||||||
logger.info(f"Creating shout with slug: {slug}")
|
inp["created_at"] = current_time
|
||||||
|
inp["updated_at"] = current_time
|
||||||
|
inp["created_by"] = author_dict.get("id")
|
||||||
|
|
||||||
# Создаем объект Shout напрямую, без промежуточного словаря
|
new_shout = Shout(**inp)
|
||||||
new_shout = Shout(
|
session.add(new_shout)
|
||||||
title=inp.get("title", ""),
|
session.flush() # Получаем id до коммита
|
||||||
subtitle=inp.get("subtitle", ""),
|
|
||||||
lead=inp.get("lead", ""),
|
|
||||||
description=inp.get("description", ""),
|
|
||||||
body=inp.get("body", ""),
|
|
||||||
layout=inp.get("layout", "article"),
|
|
||||||
created_by=author_id,
|
|
||||||
slug=slug,
|
|
||||||
published_at=None,
|
|
||||||
community=1,
|
|
||||||
created_at=current_time
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check for duplicate slug
|
# Check for duplicate slug
|
||||||
logger.debug(f"Checking for existing slug: {slug}")
|
logger.debug(f"Checking for existing slug: {new_shout.slug}")
|
||||||
same_slug_shout = session.query(Shout).filter(Shout.slug == new_shout.slug).first()
|
same_slug_shout = session.query(Shout).filter(Shout.slug == new_shout.slug).first()
|
||||||
c = 1
|
c = 1
|
||||||
while same_slug_shout is not None:
|
while same_slug_shout is not None:
|
||||||
logger.debug(f"Found duplicate slug, trying iteration {c}")
|
logger.debug(f"Found duplicate slug, trying iteration {c}")
|
||||||
new_shout.slug = f"{slug}-{c}"
|
new_shout.slug = f"{new_shout.slug}-{c}"
|
||||||
same_slug_shout = session.query(Shout).filter(Shout.slug == new_shout.slug).first()
|
same_slug_shout = session.query(Shout).filter(Shout.slug == new_shout.slug).first()
|
||||||
c += 1
|
c += 1
|
||||||
|
|
||||||
|
@ -149,8 +139,8 @@ async def create_shout(_, info, inp):
|
||||||
|
|
||||||
# Get created shout
|
# Get created shout
|
||||||
try:
|
try:
|
||||||
logger.debug(f"Retrieving created shout with slug: {slug}")
|
logger.debug(f"Retrieving created shout with slug: {new_shout.slug}")
|
||||||
shout = session.query(Shout).where(Shout.slug == slug).first()
|
shout = session.query(Shout).where(Shout.slug == new_shout.slug).first()
|
||||||
if not shout:
|
if not shout:
|
||||||
logger.error("Created shout not found in database")
|
logger.error("Created shout not found in database")
|
||||||
return {"error": "Shout creation failed - not found after commit"}
|
return {"error": "Shout creation failed - not found after commit"}
|
||||||
|
@ -160,12 +150,12 @@ async def create_shout(_, info, inp):
|
||||||
|
|
||||||
# Link author
|
# Link author
|
||||||
try:
|
try:
|
||||||
logger.debug(f"Linking author {author_id} to shout {shout.id}")
|
logger.debug(f"Linking author {author_dict.get('id')} to shout {shout.id}")
|
||||||
existing_sa = session.query(ShoutAuthor).filter_by(shout=shout.id, author=author_id).first()
|
existing_sa = session.query(ShoutAuthor).filter_by(shout=shout.id, author=author_dict.get("id")).first()
|
||||||
if not existing_sa:
|
if not existing_sa:
|
||||||
sa = ShoutAuthor(shout=shout.id, author=author_id)
|
sa = ShoutAuthor(shout=shout.id, author=author_dict.get("id"))
|
||||||
session.add(sa)
|
session.add(sa)
|
||||||
logger.info(f"Added author {author_id} to shout {shout.id}")
|
logger.info(f"Added author {author_dict.get('id')} to shout {shout.id}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error linking author: {e}", exc_info=True)
|
logger.error(f"Error linking author: {e}", exc_info=True)
|
||||||
return {"error": f"Error linking author: {str(e)}"}
|
return {"error": f"Error linking author: {str(e)}"}
|
||||||
|
@ -200,7 +190,7 @@ async def create_shout(_, info, inp):
|
||||||
|
|
||||||
# После успешного создания обновляем статистику автора
|
# После успешного создания обновляем статистику автора
|
||||||
try:
|
try:
|
||||||
author = session.query(Author).filter(Author.id == author_id).first()
|
author = session.query(Author).filter(Author.id == author_dict.get("id")).first()
|
||||||
if author and author.stat:
|
if author and author.stat:
|
||||||
author.stat["shouts"] = author.stat.get("shouts", 0) + 1
|
author.stat["shouts"] = author.stat.get("shouts", 0) + 1
|
||||||
session.add(author)
|
session.add(author)
|
||||||
|
@ -213,22 +203,30 @@ async def create_shout(_, info, inp):
|
||||||
# Преобразуем связанные сущности в словари
|
# Преобразуем связанные сущности в словари
|
||||||
try:
|
try:
|
||||||
shout_dict = shout.dict()
|
shout_dict = shout.dict()
|
||||||
shout_dict["authors"] = [author.dict() for author in shout.authors]
|
shout_dict["authors"] = [
|
||||||
shout_dict["topics"] = [topic.dict() for topic in shout.topics]
|
{"id": author.id, "name": author.name, "slug": author.slug, "pic": author.pic}
|
||||||
|
for author in shout.authors
|
||||||
|
]
|
||||||
|
shout_dict["topics"] = [
|
||||||
|
{"id": topic.id, "name": topic.name, "slug": topic.slug} for topic in shout.topics
|
||||||
|
]
|
||||||
logger.info(f"Successfully created shout {shout.id} with authors and topics as dicts")
|
logger.info(f"Successfully created shout {shout.id} with authors and topics as dicts")
|
||||||
return {"shout": shout_dict}
|
|
||||||
|
# Инвалидируем кэш
|
||||||
|
await invalidate_shouts_cache(["feed", f"author_{author_dict.get('id')}", "random_top", "unrated"])
|
||||||
|
|
||||||
|
# Обновляем кэш связанных сущностей
|
||||||
|
# TODO: await cache_related_entities(shout)
|
||||||
|
|
||||||
|
return {"shout": shout_dict, "error": None}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Error converting related entities to dicts: {e}", exc_info=True)
|
logger.warning(f"Error converting related entities to dicts: {e}", exc_info=True)
|
||||||
# Если преобразование не удалось, возвращаем исходный объект
|
# Если преобразование не удалось, возвращаем исходный объект
|
||||||
return {"shout": shout}
|
return {"shout": shout}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as exc:
|
||||||
logger.error(f"Unexpected error in create_shout: {e}", exc_info=True)
|
logger.error(f"Error in create_shout: {exc}", exc_info=True)
|
||||||
return {"error": f"Unexpected error: {str(e)}"}
|
return {"error": str(exc)}
|
||||||
|
|
||||||
error_msg = "cant create shout" if user_id else "unauthorized"
|
|
||||||
logger.error(f"Create shout failed: {error_msg}")
|
|
||||||
return {"error": error_msg}
|
|
||||||
|
|
||||||
|
|
||||||
def patch_main_topic(session, main_topic, shout):
|
def patch_main_topic(session, main_topic, shout):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user