feat: 오늘 한 장 — 하루 한 장 날씨 카드(22장)·실제 날씨 행운·연속 도장·저녁 체크인
- 로그인 안 하면 기기에, 로그인하면 계정에 남기고 로그인할 때 기기 기록을 옮긴다 (표 fortune_draw·day_log) - 행운 시간은 오늘 남은 구간 중 날씨 점수가 가장 높은 때, 장소는 날씨 맞춤 데이트 명소, 1위 각은 지금 순위 - 체크인은 해 지기 2시간 전부터: 기분·다녀온 곳(명소·노을 명소·지금 하는 행사에서 찾거나 직접)·카드 맞았나 - GA4 fortune_draw·day_log
This commit is contained in:
1 parent
52a4830b08
commit
c37773f48f
43 files changed
+1567
-6
No files matched your search
@@ -453,6 +453,29 @@ class MyGak(Base):
|
||||
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"
|
||||
|
||||
|
||||
@@ -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]
|
||||
@@ -318,6 +318,29 @@ 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.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,7 @@ 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.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 +49,7 @@ 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(talk_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
|
||||
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] = []
|
||||
@@ -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,205 @@
|
||||
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.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
|
||||
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()
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.save_log(s, user.user_id, today, values))
|
||||
|
||||
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,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"] == []
|
||||
Reference in new issue
Block a user