Files
o2o-weather/backend/crud/card_crud.py
T

53 lines
2.6 KiB
Python

from datetime import date, datetime
from typing import Optional
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import CardImage, CardSet, Post
from common.enums import CardStatus, PostType, RefType
# 카드뉴스 포스트 번호. 03:00 에 만드는 카드(LINEUP 1~20)와 겹치지 않게 101부터
CARD_POSITION_START = 101
NATIONAL_SCOPE = "00"
class CardCRUD:
async def create(self, s: AsyncSession, card: CardSet, images: list[bytes]) -> CardSet:
s.add(card)
await s.flush()
s.add_all(CardImage(card_id=card.card_id, seq=i + 1, data=data) for i, data in enumerate(images))
return card
async def get(self, s: AsyncSession, card_id: int) -> Optional[CardSet]:
return await s.get(CardSet, card_id)
async def recent(self, s: AsyncSession, limit: int) -> list[CardSet]:
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
if not card_ids:
return []
return list((await s.scalars(select(CardSet).where(CardSet.card_id.in_(card_ids)))).all())
async def image_counts(self, s: AsyncSession, card_ids: list[int]) -> dict[int, int]:
if not card_ids:
return {}
rows = await s.execute(select(CardImage.card_id, func.count()).where(CardImage.card_id.in_(card_ids)).group_by(CardImage.card_id))
return {card_id: n for card_id, n in rows.all()}
async def image(self, s: AsyncSession, card_id: int, seq: int) -> Optional[bytes]:
row = await s.get(CardImage, (card_id, seq))
return row.data if row is not None else None
async def publish(self, s: AsyncSession, card: CardSet, day: date, now: datetime, end: datetime) -> Post:
"""그날 전국 피드에 포스트 하나로 올린다. 같은 날 여러 개면 번호를 하나씩 늘린다."""
last = await s.scalar(select(func.max(Post.position)).where(Post.feed_date == day, Post.scope == NATIONAL_SCOPE, Post.position >= CARD_POSITION_START))
post = Post(feed_date=day, position=(last or CARD_POSITION_START - 1) + 1, scope=NATIONAL_SCOPE, post_type=PostType.CARD.value,
ref_type=RefType.CARD.value, ref_id=card.card_id, published_at=now, end_at=end)
s.add(post)
await s.flush()
card.status, card.post_id, card.published_at = CardStatus.PUBLISHED.value, post.post_id, now
return post