Merge remote-tracking branch 'origin/main' into feat/weather-game
# Conflicts: # frontend/src/b/Sheets.tsx # frontend/src/b/sheetContext.ts
This commit is contained in:
commit
7d097a05de
99 files changed
+3230
-41
No files matched your search
@@ -363,6 +363,7 @@ class User(Base):
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
points: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
@@ -453,6 +454,41 @@ class MyGak(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PointLog(Base):
|
||||
__tablename__ = "point_log"
|
||||
|
||||
point_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
day: Mapped[date] = mapped_column(Date)
|
||||
action: Mapped[str] = mapped_column(String(20))
|
||||
ref: Mapped[str] = mapped_column(String(40), default="")
|
||||
points: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class FortuneDraw(Base):
|
||||
__tablename__ = "fortune_draw"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
day: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
card_code: Mapped[str] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class DayLog(Base):
|
||||
__tablename__ = "day_log"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
day: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
mood: Mapped[int] = mapped_column(SmallInteger)
|
||||
went_out: Mapped[bool] = mapped_column(Boolean)
|
||||
place_name: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
place_ref: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
card_hit: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Talk(Base):
|
||||
__tablename__ = "talk"
|
||||
|
||||
|
||||
@@ -26,6 +26,13 @@ class CardCRUD:
|
||||
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
|
||||
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
|
||||
|
||||
async def latest_published(self, s: AsyncSession, template: str) -> Optional[CardSet]:
|
||||
"""그 틀로 가장 최근에 피드에 올린 카드뉴스"""
|
||||
return await s.scalar(
|
||||
select(CardSet).where(CardSet.template == template, CardSet.status == CardStatus.PUBLISHED.value, CardSet.post_id.is_not(None))
|
||||
.order_by(CardSet.published_at.desc()).limit(1)
|
||||
)
|
||||
|
||||
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
|
||||
if not card_ids:
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import DayLog, Event, FortuneDraw, Place, SunsetSpot
|
||||
|
||||
|
||||
def _near(region_col, sido: str):
|
||||
return case((region_col.startswith(sido), 0), else_=1)
|
||||
|
||||
|
||||
class FortuneCRUD:
|
||||
async def draw_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[FortuneDraw]:
|
||||
return await s.get(FortuneDraw, (user_id, day))
|
||||
|
||||
async def add_draw(self, s: AsyncSession, user_id: uuid.UUID, day: date, card_code: str) -> FortuneDraw:
|
||||
"""그날 이미 뽑았으면 그 카드를 그대로 돌려준다 (폰과 PC 에서 동시에 뽑아도 처음 카드 하나로)"""
|
||||
await s.execute(insert(FortuneDraw).values(user_id=user_id, day=day, card_code=card_code).on_conflict_do_nothing())
|
||||
return await s.scalar(select(FortuneDraw).where(FortuneDraw.user_id == user_id, FortuneDraw.day == day))
|
||||
|
||||
async def draw_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
|
||||
return list((await s.scalars(select(FortuneDraw.day).where(FortuneDraw.user_id == user_id, FortuneDraw.day >= since))).all())
|
||||
|
||||
async def log_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[DayLog]:
|
||||
return await s.get(DayLog, (user_id, day))
|
||||
|
||||
async def save_log(self, s: AsyncSession, user_id: uuid.UUID, day: date, values: dict) -> DayLog:
|
||||
stmt = insert(DayLog).values(user_id=user_id, day=day, **values)
|
||||
await s.execute(stmt.on_conflict_do_update(index_elements=[DayLog.user_id, DayLog.day], set_={**values, "updated_at": func.now()}))
|
||||
return await s.scalar(select(DayLog).where(DayLog.user_id == user_id, DayLog.day == day).execution_options(populate_existing=True))
|
||||
|
||||
async def import_rows(self, s: AsyncSession, user_id: uuid.UUID, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> None:
|
||||
"""기기에 있던 기록을 계정으로. 계정에 이미 있는 날은 계정 쪽을 둔다"""
|
||||
if draws:
|
||||
await s.execute(insert(FortuneDraw).values([{"user_id": user_id, "day": d, "card_code": c} for d, c in draws]).on_conflict_do_nothing())
|
||||
if logs:
|
||||
await s.execute(insert(DayLog).values([{"user_id": user_id, "day": d, **v} for d, v in logs]).on_conflict_do_nothing())
|
||||
|
||||
async def search_places(self, s: AsyncSession, q: str, sido: str, today: date, limit: int) -> list[tuple[str, str]]:
|
||||
"""이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사. 같은 시도를 앞에. (place_ref, 이름)"""
|
||||
like = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
places = (await s.execute(select(Place.place_id, Place.name).where(Place.name.ilike(like, escape="\\")).order_by(_near(Place.region_code, sido), Place.name).limit(limit))).all()
|
||||
spots = (await s.execute(select(SunsetSpot.spot_id, SunsetSpot.name).where(SunsetSpot.name.ilike(like, escape="\\")).order_by(_near(SunsetSpot.region_code, sido), SunsetSpot.name).limit(limit))).all()
|
||||
events = (await s.execute(
|
||||
select(Event.event_id, Event.name).where(Event.name.ilike(like, escape="\\"), Event.start_date <= today, Event.end_date >= today)
|
||||
.order_by(case((Event.sido_code == sido, 0), else_=1), Event.name).limit(limit)
|
||||
)).all()
|
||||
return [(f"place:{i}", n) for i, n in places] + [(f"spot:{i}", n) for i, n in spots] + [(f"event:{i}", n) for i, n in events]
|
||||
@@ -0,0 +1,30 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import PointLog, User
|
||||
|
||||
|
||||
class LevelCRUD:
|
||||
async def earned(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str) -> int:
|
||||
return await s.scalar(select(func.coalesce(func.sum(PointLog.points), 0)).where(PointLog.user_id == user_id, PointLog.day == day, PointLog.action == action))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str, ref: str, points: int) -> int:
|
||||
"""같은 날 같은 일·대상이면 넣지 않는다. 넣었으면 총량에 더하고 새 총량을 돌려준다 (안 넣었으면 0)"""
|
||||
row = await s.scalar(insert(PointLog).values(user_id=user_id, day=day, action=action, ref=ref, points=points).on_conflict_do_nothing().returning(PointLog.point_id))
|
||||
if row is None:
|
||||
return 0
|
||||
return await s.scalar(update(User).where(User.user_id == user_id).values(points=User.points + points).returning(User.points))
|
||||
|
||||
async def today(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> dict[str, int]:
|
||||
rows = (await s.execute(select(PointLog.action, func.sum(PointLog.points)).where(PointLog.user_id == user_id, PointLog.day == day).group_by(PointLog.action))).all()
|
||||
return {a: int(p) for a, p in rows}
|
||||
|
||||
async def attend_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
|
||||
return list((await s.scalars(select(PointLog.day).where(PointLog.user_id == user_id, PointLog.action == "attend", PointLog.day >= since))).all())
|
||||
|
||||
async def points(self, s: AsyncSession, user_id: uuid.UUID) -> int:
|
||||
return await s.scalar(select(User.points).where(User.user_id == user_id)) or 0
|
||||
@@ -318,6 +318,42 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
|
||||
ALTER TABLE public.my_gak ADD COLUMN IF NOT EXISTS icon VARCHAR(32) NULL; -- 고른 아이콘 (각 아이콘 이름, 없으면 기본)
|
||||
|
||||
-- 계정 레벨: 날씨각에서 한 일로 모은 각 (로그인한 사람만). 레벨은 모은 총량으로 정하고, 같은 날 같은 일·대상은 한 번만 준다
|
||||
CREATE TABLE IF NOT EXISTS public.point_log (
|
||||
point_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
action VARCHAR(20) NOT NULL, -- services/level_service.py ACTIONS
|
||||
ref VARCHAR(40) NOT NULL DEFAULT '', -- 같은 날 같은 대상 중복 막기 (post:12 등)
|
||||
points SMALLINT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_point_log ON public.point_log (user_id, day, action, ref);
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS points INTEGER NOT NULL DEFAULT 0; -- 모은 각 총량 (point_log 합)
|
||||
|
||||
-- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다)
|
||||
CREATE TABLE IF NOT EXISTS public.fortune_draw (
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
card_code VARCHAR(32) NOT NULL, -- 각 코드 (services/fortune_deck.json)
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, day)
|
||||
);
|
||||
|
||||
-- 저녁 체크인: 그날 기분·다녀온 곳·카드가 맞았는지 (본인만 본다)
|
||||
CREATE TABLE IF NOT EXISTS public.day_log (
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
mood SMALLINT NOT NULL, -- 1(가장 좋음)~5
|
||||
went_out BOOLEAN NOT NULL,
|
||||
place_name VARCHAR(40) NULL, -- 다녀온 곳 이름 (목록에서 고르거나 직접 씀)
|
||||
place_ref VARCHAR(40) NULL, -- 목록에서 고른 곳: place:<id> · spot:<id> · event:<id>
|
||||
card_hit BOOLEAN NULL, -- 오늘 카드 맞았나 (안 고르면 NULL)
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, day)
|
||||
);
|
||||
|
||||
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
|
||||
CREATE TABLE IF NOT EXISTS public.talk (
|
||||
talk_id BIGSERIAL PRIMARY KEY,
|
||||
|
||||
@@ -14,6 +14,8 @@ from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.image.image import router as image_router
|
||||
from router.v1.index.index import router as index_router
|
||||
from router.v1.my_gak.my_gak import router as my_gak_router
|
||||
from router.v1.fortune.fortune import router as fortune_router
|
||||
from router.v1.level.level import router as level_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
@@ -48,6 +50,8 @@ app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(fortune_router)
|
||||
app.include_router(level_router)
|
||||
app.include_router(talk_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
|
||||
@@ -14,7 +14,7 @@ from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.card_crud import CardCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList
|
||||
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList, Res_LatestCard
|
||||
from services.bot_comment import fill_bot_comments
|
||||
from services.external import instagram
|
||||
from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day
|
||||
@@ -82,6 +82,16 @@ async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
|
||||
])
|
||||
|
||||
|
||||
@router.get("/latest", response_model=Res_LatestCard, response_model_exclude_none=True, summary="그 틀로 가장 최근에 피드에 올린 카드뉴스의 포스트 (오늘 탭 '오늘 코디' 아이콘)")
|
||||
async def latest_card(template: str = Query(..., pattern=r"^[a-z_]{1,20}$")) -> Res_LatestCard:
|
||||
err, card = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.latest_published(s, template))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_LatestCard(result=error_info(err))
|
||||
if card is None:
|
||||
return Res_LatestCard()
|
||||
return Res_LatestCard(post_id=card.post_id, published_at=card.published_at.astimezone(KST) if card.published_at else None)
|
||||
|
||||
|
||||
@router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)])
|
||||
async def create_card(req: Req_CardCreate) -> Res_Card:
|
||||
images = _jpegs(req.images)
|
||||
|
||||
@@ -18,6 +18,11 @@ class Req_CardCreate(WebPacketProtocol):
|
||||
publish: bool = Field(default=False, description="true 면 만들자마자 그날 피드에 올린다. false 면 승인 대기")
|
||||
|
||||
|
||||
class Res_LatestCard(Res_WebPacketProtocol):
|
||||
post_id: Optional[int] = None
|
||||
published_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class Res_Card(Res_WebPacketProtocol):
|
||||
card_id: Optional[int] = None
|
||||
status: Optional[CardStatus] = None
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,61 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import DayLog, User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.fortune.protocol import (
|
||||
DayLogData, FortuneCard, FortuneLuck, FortunePlace, Req_DayLog, Req_FortuneDraw, Req_FortuneImport, Res_DayLog, Res_FortunePlaces, Res_FortuneToday,
|
||||
)
|
||||
from services.fortune_service import FortuneService, Today
|
||||
|
||||
router = APIRouter(prefix="/v1/fortune", tags=["fortune"])
|
||||
|
||||
|
||||
def _log(g: Optional[DayLog]) -> Optional[DayLogData]:
|
||||
if g is None:
|
||||
return None
|
||||
return DayLogData(day=g.day, mood=g.mood, went_out=g.went_out, place_name=g.place_name, place_ref=g.place_ref, card_hit=g.card_hit)
|
||||
|
||||
|
||||
def _today(t: Today) -> Res_FortuneToday:
|
||||
return Res_FortuneToday(
|
||||
day=t.day, streak=t.streak, checkin_open=t.checkin_open, log=_log(t.log),
|
||||
card=FortuneCard(**t.card.__dict__) if t.card else None, luck=FortuneLuck(**t.luck.__dict__) if t.luck else None,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/today", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이)")
|
||||
async def get_fortune_today(region: str = Query(..., min_length=10, max_length=10), user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
|
||||
err, t = await service.today(region, user)
|
||||
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
|
||||
|
||||
|
||||
@router.post("/draw", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산")
|
||||
async def draw_fortune(req: Req_FortuneDraw, user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
|
||||
err, t = await service.draw(req.region_code, user, req.card_code, req.days)
|
||||
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
|
||||
|
||||
|
||||
@router.put("/log", response_model=Res_DayLog, response_model_exclude_none=True, summary="오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다")
|
||||
async def save_day_log(req: Req_DayLog, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_DayLog:
|
||||
err, g = await service.save_log(user, req.region_code, req.mood, req.went_out, req.place_name, req.place_ref, req.card_hit)
|
||||
return Res_DayLog(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_DayLog(log=_log(g))
|
||||
|
||||
|
||||
@router.post("/import", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다)")
|
||||
async def import_fortune(req: Req_FortuneImport, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_WebPacketProtocol:
|
||||
draws = [(d.day, d.card_code) for d in req.draws]
|
||||
logs = [(g.day, g.model_dump(exclude={"day"})) for g in req.logs]
|
||||
return Res_WebPacketProtocol(result=error_info(await service.import_local(user, draws, logs)))
|
||||
|
||||
|
||||
@router.get("/places", response_model=Res_FortunePlaces, response_model_exclude_none=True, summary="체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사")
|
||||
async def search_fortune_places(region: str = Query(..., min_length=10, max_length=10), q: str = Query(..., max_length=20), service: FortuneService = Depends()) -> Res_FortunePlaces:
|
||||
err, rows = await service.places(region, q)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_FortunePlaces(result=error_info(err))
|
||||
return Res_FortunePlaces(items=[FortunePlace(ref=r, name=n) for r, n in rows])
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class FortuneCard(WebPacketProtocol):
|
||||
code: str = Field(description="각 코드 (카드 그림은 /fortune/<code>.webp)")
|
||||
name: str
|
||||
icon: str
|
||||
reading: str = Field(description="리딩 한 문장")
|
||||
color: str = Field(description="행운 색 이름")
|
||||
hex: str = Field(description="행운 색 #rrggbb")
|
||||
|
||||
|
||||
class FortuneLuck(WebPacketProtocol):
|
||||
time: Optional[str] = Field(None, description="행운 시간: 오늘 남은 구간 중 날씨가 가장 좋은 때 (예: 오후 4~7시)")
|
||||
place: Optional[str] = Field(None, description="행운 장소: 날씨 맞춤 데이트 명소")
|
||||
place_id: Optional[int] = None
|
||||
top_gak: Optional[str] = Field(None, description="지금 1위 각 이름")
|
||||
top_icon: Optional[str] = None
|
||||
|
||||
|
||||
class DayLogData(WebPacketProtocol):
|
||||
day: date
|
||||
mood: int = Field(ge=1, le=5, description="1(가장 좋음)~5")
|
||||
went_out: bool
|
||||
place_name: Optional[str] = None
|
||||
place_ref: Optional[str] = Field(None, description="목록에서 고른 곳: place:<id> · spot:<id> · event:<id>")
|
||||
card_hit: Optional[bool] = Field(None, description="오늘 카드 맞았나")
|
||||
|
||||
|
||||
class Res_FortuneToday(Res_WebPacketProtocol):
|
||||
day: Optional[date] = None
|
||||
card: Optional[FortuneCard] = Field(None, description="오늘 뽑은 카드. 아직 안 뽑았으면 없음")
|
||||
luck: Optional[FortuneLuck] = None
|
||||
streak: int = Field(0, description="이어 뽑은 날 수 (7일에 한 번 쉬는 날은 봐준다)")
|
||||
checkin_open: bool = Field(False, description="저녁(해 지기 2시간 전)부터 체크인")
|
||||
log: Optional[DayLogData] = Field(None, description="오늘 체크인 (로그인했을 때)")
|
||||
|
||||
|
||||
class Req_FortuneDraw(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
card_code: Optional[str] = Field(None, max_length=32, description="로그인 안 했을 때 기기에 있는 오늘 카드 (없으면 새로 뽑음)")
|
||||
days: list[date] = Field(default=[], max_length=60, description="로그인 안 했을 때 기기에 남은 뽑은 날 (연속 기록용)")
|
||||
|
||||
|
||||
class Req_DayLog(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
mood: int = Field(ge=1, le=5)
|
||||
went_out: bool
|
||||
place_name: Optional[str] = Field(None, max_length=40)
|
||||
place_ref: Optional[str] = Field(None, max_length=40)
|
||||
card_hit: Optional[bool] = None
|
||||
|
||||
|
||||
class Res_DayLog(Res_WebPacketProtocol):
|
||||
log: Optional[DayLogData] = None
|
||||
|
||||
|
||||
class LocalDraw(WebPacketProtocol):
|
||||
day: date
|
||||
card_code: str = Field(max_length=32)
|
||||
|
||||
|
||||
class LocalLog(Req_DayLog):
|
||||
day: date
|
||||
|
||||
|
||||
class Req_FortuneImport(Req_WebPacketProtocol):
|
||||
draws: list[LocalDraw] = Field(default=[], max_length=60)
|
||||
logs: list[LocalLog] = Field(default=[], max_length=60)
|
||||
|
||||
|
||||
class FortunePlace(WebPacketProtocol):
|
||||
ref: str = Field(description="place:<id> · spot:<id> · event:<id>")
|
||||
name: str
|
||||
|
||||
|
||||
class Res_FortunePlaces(Res_WebPacketProtocol):
|
||||
items: list[FortunePlace] = []
|
||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.level.protocol import LevelAction, LevelStep, LevelUnlock, Res_Level
|
||||
from services.level_service import LEVELS, LevelService, Status
|
||||
|
||||
router = APIRouter(prefix="/v1/level", tags=["level"])
|
||||
|
||||
|
||||
def _res(err: ErrorType, st: Status | None) -> Res_Level:
|
||||
if err is not ErrorType.SUCCESS or st is None:
|
||||
return Res_Level(result=error_info(err))
|
||||
return Res_Level(
|
||||
points=st.points, level=st.level, name=st.name, floor=st.floor, next_points=st.next_points, next_name=st.next_name, streak=st.streak,
|
||||
today=[LevelAction(**a.__dict__) for a in st.today], unlocks=[LevelUnlock(level=lv, key=k, name=n) for lv, k, n in st.unlocks],
|
||||
levels=[LevelStep(level=i + 1, name=n, points=p) for i, (p, n) in enumerate(LEVELS)],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=Res_Level, response_model_exclude_none=True, summary="내 레벨: 모은 각, 다음 레벨, 오늘 받은 각, 레벨로 열리는 것")
|
||||
async def my_level(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.status(user))
|
||||
|
||||
|
||||
@router.post("/attend", response_model=Res_Level, response_model_exclude_none=True, summary="출석 (하루 한 번 각). 7일 이어지면 보너스")
|
||||
async def attend(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.attend(user))
|
||||
|
||||
|
||||
@router.post("/share", response_model=Res_Level, response_model_exclude_none=True, summary="공유를 마쳤을 때 (하루 한 번 각)")
|
||||
async def shared(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.share(user))
|
||||
@@ -0,0 +1,38 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class LevelAction(WebPacketProtocol):
|
||||
action: str
|
||||
name: str
|
||||
points: int = Field(description="한 번에 주는 각")
|
||||
cap: int = Field(description="하루 한도")
|
||||
earned: int = Field(description="오늘 받은 각")
|
||||
|
||||
|
||||
class LevelUnlock(WebPacketProtocol):
|
||||
level: int
|
||||
key: str
|
||||
name: str
|
||||
|
||||
|
||||
class LevelStep(WebPacketProtocol):
|
||||
level: int
|
||||
name: str
|
||||
points: int = Field(description="이 레벨이 되는 각 총량")
|
||||
|
||||
|
||||
class Res_Level(Res_WebPacketProtocol):
|
||||
points: int = Field(0, description="모은 각 총량")
|
||||
level: int = 1
|
||||
name: Optional[str] = None
|
||||
floor: int = Field(0, description="지금 레벨이 시작하는 각")
|
||||
next_points: Optional[int] = Field(None, description="다음 레벨에 필요한 총량 (마지막 레벨이면 없음)")
|
||||
next_name: Optional[str] = None
|
||||
streak: int = Field(0, description="이어 출석한 날")
|
||||
today: list[LevelAction] = []
|
||||
unlocks: list[LevelUnlock] = []
|
||||
levels: list[LevelStep] = Field([], description="레벨 전체 (이름·필요한 각)")
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"cards": [
|
||||
{ "code": "date", "reading": "미뤄 둔 약속, 오늘은 먼저 연락해 보세요.", "color": "코랄", "hex": "#ff7f6e" },
|
||||
{ "code": "yajang", "reading": "퇴근길에 바깥 자리 하나 잡고 오늘 얘기를 풀어 보세요.", "color": "호박색", "hex": "#e9a23b" },
|
||||
{ "code": "chimaek", "reading": "오늘 고생한 나한테 치킨 한 마리쯤은 괜찮아요.", "color": "머스터드", "hex": "#d9a400" },
|
||||
{ "code": "sentimental", "reading": "마음이 몽글한 날이에요. 오래 못 본 사람에게 안부를 보내 보세요.", "color": "라벤더", "hex": "#b8a6e3" },
|
||||
{ "code": "mood_song", "reading": "출근길 이어폰에 예전에 좋아하던 노래를 걸어 보세요.", "color": "네이비", "hex": "#25335c" },
|
||||
{ "code": "jipkok", "reading": "오늘은 약속보다 이불이 반가운 날, 쉬는 것도 일이에요.", "color": "오트밀", "hex": "#e3d7c3" },
|
||||
{ "code": "netflix", "reading": "찜만 해 둔 그 영화, 오늘 밤에 볼 차례예요.", "color": "버건디", "hex": "#7a1f2b" },
|
||||
{ "code": "pajeon", "reading": "오늘은 혼자 먹는 것보다 둘이 나눠 먹는 게 더 맛있어요.", "color": "올리브", "hex": "#7d8a3a" },
|
||||
{ "code": "bungeoppang", "reading": "주머니에 현금 한 장 챙겨 두면 길에서 작은 기쁨을 만나요.", "color": "브라운", "hex": "#8b5a2b" },
|
||||
{ "code": "sweetpotato", "reading": "손 시린 사람에게 따뜻한 걸 건네면 오래 기억돼요.", "color": "테라코타", "hex": "#c8643c" },
|
||||
{ "code": "iced_hot", "reading": "오늘은 차가운 것보다 따뜻한 한 잔이 머리를 맑게 해 줘요.", "color": "카멜", "hex": "#c19a6b" },
|
||||
{ "code": "stars", "reading": "잠들기 전 하늘을 한 번 올려다보면 고민이 작아 보여요.", "color": "짙은 파랑", "hex": "#1f3a7a" },
|
||||
{ "code": "riverwind", "reading": "저녁 바람 쐬며 걷다 보면 꼬였던 생각이 풀려요.", "color": "민트", "hex": "#9fdcc8" },
|
||||
{ "code": "photo", "reading": "오늘 본 예쁜 장면 하나를 사진으로 남겨 두세요.", "color": "피치", "hex": "#ffc2a1" },
|
||||
{ "code": "walk", "reading": "해 진 뒤 동네 한 바퀴가 생각 정리에 딱 좋아요.", "color": "세이지", "hex": "#a3b899" },
|
||||
{ "code": "running", "reading": "짧게라도 뛰어 보세요. 움직인 만큼 내일 몸이 가벼워요.", "color": "라임", "hex": "#b5d334" },
|
||||
{ "code": "picnic", "reading": "점심은 밖에서, 햇볕 아래 잠깐이 오후를 바꿔요.", "color": "버터 옐로", "hex": "#f6e27f" },
|
||||
{ "code": "drive", "reading": "창문 열고 좋아하는 길로 한 바퀴 돌면 기분이 바뀌어요.", "color": "하늘색", "hex": "#8ec5f0" },
|
||||
{ "code": "foliage", "reading": "지금 아니면 못 보는 것부터 챙기세요. 미루면 지나가요.", "color": "오렌지", "hex": "#f07a2a" },
|
||||
{ "code": "camping", "reading": "주말 계획을 오늘 정해 두면 한 주가 가벼워져요.", "color": "숲 초록", "hex": "#2f5d3a" },
|
||||
{ "code": "themepark", "reading": "오늘은 어른스럽지 않아도 돼요. 마음껏 웃어 보세요.", "color": "핫핑크", "hex": "#ff5fa2" },
|
||||
{ "code": "dog", "reading": "오늘은 누군가와 나란히 걷는 시간이 행운이에요.", "color": "크림", "hex": "#f3ead8" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import DayLog, User
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.fortune_crud import FortuneCRUD
|
||||
from services.calc.day_slot import SLOTS, slot_hours
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import IndexService, current_slot, shown_slot
|
||||
from services.level_service import award
|
||||
from services.week_service import WeekService
|
||||
|
||||
# 오늘 한 장 덱: 각 코드마다 리딩 한 문장과 행운 색. 이름·아이콘은 각 정의에서 가져온다
|
||||
DECK: dict[str, dict] = {c["code"]: c for c in json.loads((Path(__file__).parent / "fortune_deck.json").read_text(encoding="utf-8"))["cards"]}
|
||||
|
||||
# 연속 기록은 이만큼 거슬러 올라가 센다. 기기에서 옮겨 오는 기록도 이 안쪽만 받는다
|
||||
HISTORY_DAYS = 60
|
||||
# 연속 기록에서 쉬는 날은 이 간격에 한 번만 봐준다
|
||||
REST_EVERY_DAYS = 7
|
||||
PLACE_LIMIT = 8
|
||||
_PLACE_REF = re.compile(r"^(place|spot|event):\d{1,12}$")
|
||||
|
||||
|
||||
def streak(days: set[date], today: date) -> int:
|
||||
"""오늘(아직 안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수. 하루 빠진 날은 7일에 한 번 쉬는 날로 봐준다."""
|
||||
d = today if today in days else today - timedelta(days=1)
|
||||
count, rests = 0, []
|
||||
while True:
|
||||
if d in days:
|
||||
count += 1
|
||||
elif d - timedelta(days=1) in days and all((r - d).days >= REST_EVERY_DAYS for r in rests):
|
||||
rests.append(d)
|
||||
else:
|
||||
return count
|
||||
d -= timedelta(days=1)
|
||||
|
||||
|
||||
def hours_text(hours: set[int]) -> str:
|
||||
"""구간 시각(24 이상은 다음 날)을 '오후 4~7시'처럼. 끝은 마지막 시각의 다음 정각."""
|
||||
start, end = min(hours), max(hours) + 1
|
||||
|
||||
def part(h: int) -> tuple[str, int]:
|
||||
h %= 24
|
||||
word = "새벽" if h < 6 else "오전" if h < 12 else "오후"
|
||||
return word, h % 12 or 12
|
||||
|
||||
(w1, h1), (w2, h2) = part(start), part(end)
|
||||
return f"{w1} {h1}~{h2}시" if w1 == w2 else f"{w1} {h1}시~{w2} {h2}시"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Card:
|
||||
code: str
|
||||
name: str
|
||||
icon: str
|
||||
reading: str
|
||||
color: str
|
||||
hex: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Luck:
|
||||
time: Optional[str] # 오늘 남은 구간 중 날씨 점수가 가장 높은 때
|
||||
place: Optional[str] # 날씨 맞춤 데이트 명소 첫 곳
|
||||
place_id: Optional[int]
|
||||
top_gak: Optional[str] # 지금 1위 각
|
||||
top_icon: Optional[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Today:
|
||||
day: date
|
||||
card: Optional[Card]
|
||||
luck: Optional[Luck]
|
||||
streak: int
|
||||
checkin_open: bool # 저녁(해 지기 2시간 전)부터 체크인을 받는다
|
||||
log: Optional[DayLog] = None
|
||||
|
||||
|
||||
class FortuneService:
|
||||
def __init__(self, crud: FortuneCRUD = Depends(FortuneCRUD), index: IndexService = Depends(IndexService), week: WeekService = Depends(WeekService)) -> None:
|
||||
self.crud, self.index, self.week = crud, index, week
|
||||
|
||||
async def _card(self, code: str) -> Optional[Card]:
|
||||
if code not in DECK:
|
||||
return None
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
|
||||
d = next((d for d in defs or [] if d.code == code), None)
|
||||
if err is not ErrorType.SUCCESS or d is None:
|
||||
return None
|
||||
c = DECK[code]
|
||||
return Card(code=code, name=d.name, icon=d.icon, reading=c["reading"], color=c["color"], hex=c["hex"])
|
||||
|
||||
async def _luck(self, region_code: str) -> tuple[ErrorType, Optional[Luck], bool]:
|
||||
err, board = await self.index.board(region_code)
|
||||
if err is not ErrorType.SUCCESS or board is None:
|
||||
return err, None, False
|
||||
now = now_kst()
|
||||
sunset_at = sun_times(board.day, float(board.region.lat), float(board.region.lon)).sunset_at
|
||||
cur = current_slot(now, sunset_at)
|
||||
left = SLOTS[SLOTS.index(shown_slot(cur)):]
|
||||
best = max((k for k in left if k in board.weather_slots), key=lambda k: board.weather_slots[k], default=None)
|
||||
_, places, _, _ = await self.week.places(region_code, board.day, None)
|
||||
place = next((p for p in places if p.is_good), places[0] if places else None)
|
||||
top = board.ranked[0].definition if board.ranked else None
|
||||
luck = Luck(
|
||||
time=hours_text(slot_hours(board.day, sunset_at)[best]) if best else None,
|
||||
place=place.place.name if place else None, place_id=place.place.place_id if place else None,
|
||||
top_gak=top.name if top else None, top_icon=top.icon if top else None,
|
||||
)
|
||||
return ErrorType.SUCCESS, luck, cur in ("evening", "night")
|
||||
|
||||
async def _streak(self, user: User, today: date) -> tuple[ErrorType, int]:
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_days(s, user.user_id, today - timedelta(days=HISTORY_DAYS)))
|
||||
return err, streak(set(days or []), today)
|
||||
|
||||
async def today(self, region_code: str, user: Optional[User]) -> tuple[ErrorType, Optional[Today]]:
|
||||
"""로그인했으면 오늘 뽑은 카드·체크인·연속 기록. 안 뽑았으면 카드 없이"""
|
||||
today = now_kst().date()
|
||||
if user is None:
|
||||
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=0, checkin_open=False)
|
||||
err, row = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, n = await self._streak(user, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if row is None:
|
||||
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=n, checkin_open=False)
|
||||
err, luck, open_ = await self._luck(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, Today(day=today, card=await self._card(row.card_code), luck=luck, streak=n, checkin_open=open_, log=log)
|
||||
|
||||
async def draw(self, region_code: str, user: Optional[User], card_code: Optional[str], days: list[date]) -> tuple[ErrorType, Optional[Today]]:
|
||||
"""하루 한 장. 로그인했으면 그날 처음 뽑은 카드, 안 했으면 기기에 있는 오늘 카드(없으면 새로 뽑음)와 기기에 남은 뽑은 날로 연속 기록."""
|
||||
today = now_kst().date()
|
||||
fresh = random.choice(list(DECK))
|
||||
if user is not None:
|
||||
err, row = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_draw(s, user.user_id, today, fresh))
|
||||
if err is not ErrorType.SUCCESS or row is None:
|
||||
return err, None
|
||||
code = row.card_code
|
||||
await award(user.user_id, "tarot")
|
||||
err, n = await self._streak(user, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
else:
|
||||
code = card_code if card_code in DECK else fresh
|
||||
n, log = streak({d for d in days if today - timedelta(days=HISTORY_DAYS) <= d < today} | {today}, today), None
|
||||
card = await self._card(code)
|
||||
if card is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
err, luck, open_ = await self._luck(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, Today(day=today, card=card, luck=luck, streak=n, checkin_open=open_, log=log)
|
||||
|
||||
async def save_log(self, user: User, region_code: str, mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool]) -> tuple[ErrorType, Optional[DayLog]]:
|
||||
values = clean_log(mood, went_out, place_name, place_ref, card_hit, region_code)
|
||||
if values is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = now_kst().date()
|
||||
err, log = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.save_log(s, user.user_id, today, values))
|
||||
if err is ErrorType.SUCCESS:
|
||||
await award(user.user_id, "checkin")
|
||||
return err, log
|
||||
|
||||
async def import_local(self, user: User, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> ErrorType:
|
||||
"""로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로. 최근 60일, 덱에 있는 카드, 형식이 맞는 체크인만"""
|
||||
today = now_kst().date()
|
||||
since = today - timedelta(days=HISTORY_DAYS)
|
||||
ok_draws = [(d, c) for d, c in draws if since <= d <= today and c in DECK]
|
||||
ok_logs = [(d, v) for d, raw in logs if since <= d <= today and (v := clean_log(**raw)) is not None]
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.import_rows(s, user.user_id, ok_draws, ok_logs))
|
||||
return err
|
||||
|
||||
async def places(self, region_code: str, q: str) -> tuple[ErrorType, list[tuple[str, str]]]:
|
||||
q = " ".join(q.split())
|
||||
if not q:
|
||||
return ErrorType.SUCCESS, []
|
||||
today = now_kst().date()
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.search_places(s, q, region_code[:2], today, PLACE_LIMIT))
|
||||
|
||||
|
||||
def clean_log(mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool], region_code: str) -> Optional[dict]:
|
||||
"""체크인 값 확인. 안 나갔으면 다녀온 곳은 비운다"""
|
||||
if not 1 <= mood <= 5 or not region_code:
|
||||
return None
|
||||
name = " ".join((place_name or "").split())[:40] or None
|
||||
if place_ref is not None and not _PLACE_REF.match(place_ref):
|
||||
return None
|
||||
if not went_out:
|
||||
name, place_ref = None, None
|
||||
return {"mood": mood, "went_out": went_out, "place_name": name, "place_ref": place_ref if name else None, "card_hit": card_hit, "region_code": region_code[:10]}
|
||||
@@ -0,0 +1,141 @@
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.level_crud import LevelCRUD
|
||||
|
||||
# 계정 레벨: 모은 각 총량으로 정한다 (쓰는 기능이 생겨도 레벨은 안 내려간다). 사용자 결정 10/28
|
||||
LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바람"), (200, "무지개"), (400, "노을"), (700, "은하수"), (1000, "별똥별")]
|
||||
|
||||
# 각을 주는 일: (한 번에 주는 각, 하루 한도, 이름). 로그인한 사람만 쌓인다
|
||||
ACTIONS: dict[str, tuple[int, int, str]] = {
|
||||
"attend": (10, 10, "출석"),
|
||||
"tarot": (10, 10, "오늘 타로 뽑기"),
|
||||
"saju": (10, 10, "날씨 사주 오늘 기운"),
|
||||
"react": (5, 10, "좋아요·댓글"),
|
||||
"talk": (20, 20, "동네 이야기 글쓰기"),
|
||||
"checkin": (10, 10, "저녁 체크인"),
|
||||
"share": (10, 10, "공유하기"),
|
||||
"streak": (50, 50, "7일 연속 출석"),
|
||||
}
|
||||
STREAK_DAYS = 7
|
||||
STREAK_LOOKBACK = 60
|
||||
|
||||
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
|
||||
UNLOCKS: dict[int, list[tuple[str, str]]] = {
|
||||
2: [("saju_week", "날씨 사주 이번 주 흐름")],
|
||||
3: [("saju_money", "금전운 · 일운")],
|
||||
4: [("saju_love", "연애운")],
|
||||
5: [("saju_match", "궁합")],
|
||||
6: [("saju_month", "이달 운")],
|
||||
7: [("saju_year", "올해 운")],
|
||||
}
|
||||
|
||||
|
||||
def level_of(points: int) -> int:
|
||||
return max(i + 1 for i, (need, _) in enumerate(LEVELS) if points >= need)
|
||||
|
||||
|
||||
def unlock_level(key: str) -> int:
|
||||
return next((lv for lv, items in UNLOCKS.items() if any(k == key for k, _ in items)), 1)
|
||||
|
||||
|
||||
def is_unlocked(points: int, key: str) -> bool:
|
||||
return level_of(points) >= unlock_level(key)
|
||||
|
||||
|
||||
def streak(days: set[date], today: date) -> int:
|
||||
"""오늘부터 거꾸로 이어 출석한 날 수"""
|
||||
n = 0
|
||||
while today - timedelta(days=n) in days:
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
async def award(user_id: uuid.UUID, action: str, ref: str = "") -> int:
|
||||
"""각을 준다. 하루 한도·같은 대상 중복이면 주지 않는다. 본래 동작을 막지 않게 실패는 로그만 남긴다. 새 총량(안 줬으면 0)"""
|
||||
per, cap, _ = ACTIONS[action]
|
||||
day = now_kst().date()
|
||||
crud = LevelCRUD()
|
||||
err, earned = await DB_SESSION_MNG.execute_lambda(lambda s: crud.earned(s, user_id, day, action))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[level] 각 조회 실패 {action}")
|
||||
return 0
|
||||
if earned >= cap:
|
||||
return 0
|
||||
points = min(per, cap - earned)
|
||||
err, total = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add(s, user_id, day, action, ref, points))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[level] 각 적립 실패 {action}")
|
||||
return 0
|
||||
if action == "attend" and total:
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: crud.attend_days(s, user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
||||
n = streak(set(days or []), day) if err is ErrorType.SUCCESS else 0
|
||||
if n and n % STREAK_DAYS == 0:
|
||||
more = await award(user_id, "streak", str(n))
|
||||
total = more or total
|
||||
return total or 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class TodayAction:
|
||||
action: str
|
||||
name: str
|
||||
points: int # 한 번에 주는 각
|
||||
cap: int
|
||||
earned: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Status:
|
||||
points: int
|
||||
level: int
|
||||
name: str
|
||||
floor: int # 지금 레벨이 시작하는 각
|
||||
next_points: Optional[int] # 다음 레벨까지 필요한 총량 (마지막 레벨이면 없음)
|
||||
next_name: Optional[str]
|
||||
streak: int
|
||||
today: list[TodayAction]
|
||||
unlocks: list[tuple[int, str, str]] # (레벨, 키, 이름)
|
||||
|
||||
|
||||
class LevelService:
|
||||
def __init__(self, crud: LevelCRUD = Depends(LevelCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
async def status(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
day = now_kst().date()
|
||||
err, points = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.points(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, today = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.today(s, user.user_id, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.attend_days(s, user.user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
lv = level_of(points)
|
||||
floor, name = LEVELS[lv - 1]
|
||||
nxt = LEVELS[lv] if lv < len(LEVELS) else None
|
||||
return ErrorType.SUCCESS, Status(
|
||||
points=points, level=lv, name=name, floor=floor, next_points=nxt[0] if nxt else None, next_name=nxt[1] if nxt else None,
|
||||
streak=streak(set(days), day),
|
||||
today=[TodayAction(action=a, name=n, points=p, cap=c, earned=(today or {}).get(a, 0)) for a, (p, c, n) in ACTIONS.items() if a != "streak"],
|
||||
unlocks=[(lv_, k, n) for lv_, items in UNLOCKS.items() for k, n in items],
|
||||
)
|
||||
|
||||
async def attend(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
await award(user.user_id, "attend")
|
||||
return await self.status(user)
|
||||
|
||||
async def share(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
await award(user.user_id, "share")
|
||||
return await self.status(user)
|
||||
@@ -14,6 +14,7 @@ from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from services.bot_comment import BOT_COLORS, BOT_NAMES
|
||||
from services.level_service import award
|
||||
from services.talk_service import _LINK, _PHONE
|
||||
|
||||
COMMENT_MAX = 60
|
||||
@@ -55,7 +56,10 @@ class ReactionService:
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
if err is ErrorType.SUCCESS and on and who.user_id is not None:
|
||||
await award(who.user_id, "react", f"post:{post_id}")
|
||||
return err, count
|
||||
|
||||
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
|
||||
err = await self._post_exists(post_id)
|
||||
@@ -139,6 +143,7 @@ class ReactionService:
|
||||
return err, None
|
||||
if user is None:
|
||||
return err, self._view(c, None, None, None, None, False, who)
|
||||
await award(user.user_id, "react", f"comment:{c.comment_id}")
|
||||
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
|
||||
|
||||
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
|
||||
|
||||
@@ -14,6 +14,7 @@ from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.talk_crud import TalkCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.level_service import award
|
||||
from services.talk_image import is_ours
|
||||
|
||||
BODY_MAX = 100
|
||||
@@ -204,6 +205,7 @@ class TalkService:
|
||||
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err, None
|
||||
await award(user.user_id, "talk", str(t.talk_id))
|
||||
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
|
||||
|
||||
async def delete(self, user: User, talk_id: int) -> ErrorType:
|
||||
|
||||
@@ -142,3 +142,16 @@ async def test_instagram_requires_token(offline, admin_key, monkeypatch):
|
||||
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
|
||||
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_latest_card_by_template_is_public(offline, admin_key):
|
||||
async with client() as c:
|
||||
assert "post_id" not in (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
|
||||
ootd = (await c.post("/v1/card", json=body(template="ootd", title="오늘 코디", publish=True), headers=admin_key)).json()
|
||||
await c.post("/v1/card", json=body(template="ootd", title="승인 대기 코디"), headers=admin_key)
|
||||
await c.post("/v1/card", json=body(publish=True), headers=admin_key)
|
||||
# 그 틀로 피드에 올린 것 중 가장 최근 (승인 대기·다른 틀은 빼고)
|
||||
latest = (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
|
||||
assert latest["post_id"] == ootd["post_id"] and latest["published_at"]
|
||||
assert (await c.get("/v1/card/latest", params={"template": "../x"})).status_code == 422
|
||||
@@ -0,0 +1,128 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
from services.fortune_service import DECK, clean_log, hours_text, streak
|
||||
|
||||
REGION = "1144000000"
|
||||
D = date(2026, 10, 28)
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _days(*back: int) -> set[date]:
|
||||
return {D - timedelta(days=b) for b in back}
|
||||
|
||||
|
||||
def test_deck_is_22_cards_with_reading_and_color():
|
||||
assert len(DECK) == 22
|
||||
assert all(c["reading"] and c["color"] and c["hex"].startswith("#") for c in DECK.values())
|
||||
|
||||
|
||||
def test_streak_counts_back_from_today_or_yesterday():
|
||||
assert streak(set(), D) == 0
|
||||
assert streak(_days(0, 1, 2), D) == 3
|
||||
# 오늘 아직 안 뽑았으면 어제까지 센다
|
||||
assert streak(_days(1, 2), D) == 2
|
||||
|
||||
|
||||
def test_streak_forgives_one_rest_day_a_week():
|
||||
# 하루 빠진 날(2일 전)은 쉬는 날로 봐준다
|
||||
assert streak(_days(0, 1, 3, 4), D) == 4
|
||||
# 이틀 연속 빠지면 끊긴다
|
||||
assert streak(_days(0, 3, 4), D) == 1
|
||||
# 쉬는 날이 7일 안에 두 번이면 두 번째에서 끊긴다
|
||||
assert streak(_days(0, 2, 4, 5), D) == 2
|
||||
# 7일 넘게 떨어져 있으면 두 번 다 봐준다
|
||||
assert streak(_days(0, 2, 3, 4, 5, 6, 7, 8, 10), D) == 9
|
||||
|
||||
|
||||
def test_hours_text():
|
||||
assert hours_text({16, 17, 18}) == "오후 4~7시"
|
||||
assert hours_text({11, 12, 13, 14}) == "오전 11시~오후 3시"
|
||||
assert hours_text(set(range(19, 29))) == "오후 7시~새벽 5시"
|
||||
|
||||
|
||||
def test_clean_log_drops_place_when_stayed_home_and_rejects_bad_ref():
|
||||
v = clean_log(2, False, "하늘공원", "spot:3", True, REGION)
|
||||
assert v["place_name"] is None and v["place_ref"] is None and v["card_hit"] is True
|
||||
assert clean_log(2, True, " 하늘 공원 ", "spot:3", None, REGION)["place_name"] == "하늘 공원"
|
||||
assert clean_log(2, True, "하늘공원", "../x", None, REGION) is None
|
||||
assert clean_log(6, True, None, None, None, REGION) is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_draw_keeps_device_card_and_counts_device_days(offline):
|
||||
today = now_kst().date()
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/fortune/draw", json={"region_code": REGION})).json()
|
||||
assert first["card"]["code"] in DECK and first["card"]["name"].endswith("각")
|
||||
assert first["luck"]["time"] and first["luck"]["top_gak"]
|
||||
assert first["streak"] == 1
|
||||
# 기기에 있는 오늘 카드를 넘기면 그 카드 그대로, 기기에 남은 뽑은 날로 연속 기록
|
||||
again = (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": first["card"]["code"], "days": [str(today - timedelta(days=1)), str(today - timedelta(days=2))]})).json()
|
||||
assert again["card"]["code"] == first["card"]["code"] and again["streak"] == 3
|
||||
# 덱에 없는 카드면 새로 뽑는다
|
||||
assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": "laundry"})).json()["card"]["code"] in DECK
|
||||
# 로그인 안 했으면 오늘 보기는 카드 없이, 체크인은 못 한다
|
||||
assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION})).json()
|
||||
assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 1, "went_out": False})).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_login_draws_one_card_a_day_and_saves_checkin(offline):
|
||||
async with client() as c:
|
||||
h = await _login(c, "fortune_01")
|
||||
assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
|
||||
first = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"]
|
||||
# 다시 뽑아도, 기기 카드를 넘겨도 그날 처음 카드
|
||||
other = next(k for k in DECK if k != first)
|
||||
assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": other}, headers=h)).json()["card"]["code"] == first
|
||||
today = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
|
||||
assert today["card"]["code"] == first and today["streak"] == 1 and "log" not in today
|
||||
|
||||
saved = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 2, "went_out": True, "place_name": "하늘공원", "place_ref": "spot:2", "card_hit": True}, headers=h)).json()
|
||||
assert saved["log"]["place_name"] == "하늘공원" and saved["log"]["card_hit"] is True
|
||||
# 다시 보내면 고친다
|
||||
fixed = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 4, "went_out": False}, headers=h)).json()["log"]
|
||||
assert fixed["mood"] == 4 and "place_name" not in fixed
|
||||
assert (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()["log"]["mood"] == 4
|
||||
assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 9, "went_out": False}, headers=h)).status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_import_moves_device_records_but_keeps_account_days(offline):
|
||||
today = now_kst().date()
|
||||
async with client() as c:
|
||||
h = await _login(c, "fortune_02")
|
||||
mine = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"]
|
||||
other = next(k for k in DECK if k != mine)
|
||||
body = {
|
||||
"draws": [{"day": str(today), "card_code": other}, {"day": str(today - timedelta(days=1)), "card_code": other}, {"day": str(today - timedelta(days=90)), "card_code": other}],
|
||||
"logs": [{"day": str(today - timedelta(days=1)), "region_code": REGION, "mood": 1, "went_out": False}],
|
||||
}
|
||||
assert (await c.post("/v1/fortune/import", json=body, headers=h)).json()["result"]["success"] is True
|
||||
t = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()
|
||||
# 오늘은 계정에서 뽑은 카드 그대로, 어제 기록이 더해져 2일째. 60일보다 오래된 날은 받지 않는다
|
||||
assert t["card"]["code"] == mine and t["streak"] == 2
|
||||
assert (await c.post("/v1/fortune/import", json=body)).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_place_search_finds_spots_by_name():
|
||||
async with client() as c:
|
||||
items = (await c.get("/v1/fortune/places", params={"region": REGION, "q": "하늘공원"})).json()["items"]
|
||||
assert any(i["name"] == "하늘공원" and i["ref"].startswith("spot:") for i in items)
|
||||
# LIKE 기호는 글자 그대로 찾는다
|
||||
assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": "%"})).json()["items"] == []
|
||||
assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": " "})).json()["items"] == []
|
||||
@@ -0,0 +1,104 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import PointLog, User
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
from services.level_service import LEVELS, is_unlocked, level_of
|
||||
|
||||
REGION = "1144000000"
|
||||
pytestmark = pytest.mark.usefixtures("no_bot_comments")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||
await c.post("/v1/auth/terms", headers=h)
|
||||
return h
|
||||
|
||||
|
||||
def _earned(level: dict, action: str) -> int:
|
||||
return next(a["earned"] for a in level["today"] if a["action"] == action)
|
||||
|
||||
|
||||
def test_level_thresholds_and_unlocks():
|
||||
assert [need for need, _ in LEVELS] == [0, 30, 100, 200, 400, 700, 1000]
|
||||
assert level_of(0) == 1 and level_of(29) == 1 and level_of(30) == 2 and level_of(199) == 3 and level_of(200) == 4 and level_of(5000) == 7
|
||||
assert not is_unlocked(199, "saju_love") and is_unlocked(200, "saju_love")
|
||||
assert not is_unlocked(399, "saju_match") and is_unlocked(400, "saju_match")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_actions_award_once_and_respect_daily_caps(offline):
|
||||
async with client() as c:
|
||||
assert (await c.get("/v1/level/me")).status_code == 401
|
||||
h = await _login(c, "level_01")
|
||||
me = (await c.get("/v1/level/me", headers=h)).json()
|
||||
assert me["points"] == 0 and me["level"] == 1 and me["name"] == "이슬" and me["next_points"] == 30
|
||||
|
||||
# 출석은 하루 한 번
|
||||
assert (await c.post("/v1/level/attend", headers=h)).json()["points"] == 10
|
||||
assert (await c.post("/v1/level/attend", headers=h)).json()["points"] == 10
|
||||
|
||||
# 좋아요·댓글은 5각씩 하루 10각, 같은 글을 다시 눌러도 더 안 줌
|
||||
posts = [p["post_id"] for p in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][:3]]
|
||||
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers=h)
|
||||
await c.delete(f"/v1/reaction/post/{posts[0]}/like", headers=h)
|
||||
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers=h)
|
||||
assert _earned((await c.get("/v1/level/me", headers=h)).json(), "react") == 5
|
||||
await c.post(f"/v1/reaction/post/{posts[1]}/comment", json={"body": "오늘 노을 기대돼요"}, headers=h)
|
||||
await c.post(f"/v1/reaction/post/{posts[2]}/like", headers=h)
|
||||
me = (await c.get("/v1/level/me", headers=h)).json()
|
||||
assert _earned(me, "react") == 10 and me["points"] == 20
|
||||
|
||||
# 오늘 타로는 하루 한 번, 동네 이야기 글 20각 → 50각이면 Lv.2
|
||||
await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)
|
||||
await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)
|
||||
await c.post("/v1/talk", json={"region_code": REGION, "body": "오늘 하늘 맑아요"}, headers=h)
|
||||
me = (await c.get("/v1/level/me", headers=h)).json()
|
||||
assert _earned(me, "tarot") == 10 and _earned(me, "talk") == 20
|
||||
assert me["points"] == 50 and me["level"] == 2 and me["name"] == "햇살" and me["floor"] == 30 and me["next_points"] == 100
|
||||
|
||||
# 저녁 체크인·공유도 하루 한 번
|
||||
await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 2, "went_out": False}, headers=h)
|
||||
await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 3, "went_out": False}, headers=h)
|
||||
await c.post("/v1/level/share", headers=h)
|
||||
assert (await c.post("/v1/level/share", headers=h)).json()["points"] == 70
|
||||
|
||||
# 로그인 안 한 좋아요는 각이 없다 (다른 사람 계정에도 안 쌓임)
|
||||
await c.post(f"/v1/reaction/post/{posts[0]}/like", headers={"X-Forwarded-For": "203.0.113.50"})
|
||||
assert (await c.get("/v1/level/me", headers=h)).json()["points"] == 70
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seven_day_attendance_bonus(offline):
|
||||
async with client() as c:
|
||||
h = await _login(c, "level_02")
|
||||
await c.post("/v1/level/attend", headers=h)
|
||||
today = now_kst().date()
|
||||
|
||||
async def backfill(s):
|
||||
uid = await s.scalar(select(User.user_id).where(User.login_id == "level_02"))
|
||||
s.add_all([PointLog(user_id=uid, day=today - timedelta(days=d), action="attend", ref="", points=10) for d in range(1, 7)])
|
||||
|
||||
await DB_SESSION_MNG.execute_lambda_write(backfill)
|
||||
# 오늘 출석이 이미 있으니 다시 불러도 보너스가 생기지 않는다 → 다음 날처럼 오늘 기록을 지우고 다시 출석
|
||||
async def drop_today(s):
|
||||
uid = await s.scalar(select(User.user_id).where(User.login_id == "level_02"))
|
||||
row = await s.scalar(select(PointLog).where(PointLog.user_id == uid, PointLog.day == today))
|
||||
await s.delete(row)
|
||||
user = await s.get(User, uid)
|
||||
user.points -= 10
|
||||
|
||||
await DB_SESSION_MNG.execute_lambda_write(drop_today)
|
||||
me = (await c.post("/v1/level/attend", headers=h)).json()
|
||||
# 지난 6일은 장부만 넣어 총량엔 없다: 오늘 출석 10 + 7일 연속 50
|
||||
assert me["streak"] == 7 and me["points"] == 60
|
||||
Reference in new issue
Block a user