diff --git a/TODO.md b/TODO.md index 49344c3..e103fdc 100644 --- a/TODO.md +++ b/TODO.md @@ -89,7 +89,8 @@ | 상태 | 할 일 | 이유 | 관련 파일 | |---|---|---|---| | [ ] | **[결정 필요]** 타깃을 2030 직장인으로 좁히기 — 기능은 지우지 않고 첫 화면·각 순서만 이 사람 기준으로. 9/29 '타깃 정하지 않음'을 바꾸는 일이라 대표 결정 | 콘텐츠가 2030·4050·반려인·동네 주민으로 흩어져 누구에게도 1순위가 아님 | `frontend/src/b/TodayPage.tsx`, `backend/services/feed_service.py` | -| [ ] | 히어로 아래 '오늘 한 장'(날씨 운세) — 사용자 결정 10/28: 타로 1장 뽑기(하루 1장) + 행운(시간·장소·색·1위 각을 실제 날씨로) + 연속 기록, 저녁 체크인 최소판(기분·간 곳·오늘 카드 맞았나) 같이. 별자리·웹 푸시·일기 달력·회상·월말 요약은 4주 숫자 본 뒤. 구현 계획·문구 검토 후 착수 | 10/28 시장성 진단·날씨 운세 기획(채팅 첨부), 10/20 회의 '날씨 타로로 행동 추천' | `frontend/src/b/TodayPage.tsx` | +| [ ] | 히어로 아래 '오늘 한 장'(날씨 운세) — 만듦(`feat/today-card`): 타로 22장 하루 1장 뽑기 + 행운(시간·장소·색·1위 각을 실제 날씨로) + 연속 도장(7일에 쉬는 날 1번) + 저녁 체크인(기분·다녀온 곳·카드 맞았나). 로그인 안 하면 기기에, 로그인하면 계정(표 `fortune_draw`·`day_log`, 로그인 때 기기 기록 옮김). 남은 것: main 병합·배포(운영 init.sql 로 표 2개 생김), 토스 ait(`feat/apps-in-toss`에 main 합친 뒤) | 10/28 사용자 결정(덱 22장·리딩 한 문장·문구 1~13 그대로) | `frontend/src/b/fortune.tsx`, `backend/services/fortune_service.py`, `backend/services/fortune_deck.json` | +| [ ] | 날씨 사주 — 생년월일로 일간(나무·불·흙·쇠·물) 하나만 구해 오늘 실제 날씨 기운과의 관계로 한 줄. 생년월일은 기기 안에서만 계산. 별자리 대신 '오늘 한 장' 개인화로 | 사용자 결정 10/28: 2단계(오늘 한 장 4주 숫자 본 뒤) | `frontend/src/b/fortune.tsx` | | [ ] | **[결정 필요]** 아침 7시 웹 푸시 — 안드로이드 크롬은 바로, 아이폰은 홈 화면에 추가한 사람만(iOS 16.4+). 앱 위젯(10/21 결정)은 계속 | 다시 부르는 장치가 없음(코드에 웹 푸시 없음) → DAU가 쌓이지 않음 | `frontend/public/sw.js`, `frontend/src/b/install.ts` | | [ ] | **[결정 필요]** 좋아요·댓글 0이면 숫자 숨기기, 동네 이야기는 그날 글이 몇 개 넘을 때만 위에 | 첫 화면 '좋아요 0개'·동네 글 1개가 "아무도 안 쓴다"는 신호 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/talk.tsx` | | [ ] | **[결정 필요]** 4주 새 기능 동결 목록 — 후보: 나만의 각 피드 올리기, 동네 이야기 사진, 캐시워크·통신사 위젯, 새 각 추가, 지역 페이지 추가 확장(10/21 '모든 지역 추가'와 충돌) | 2명이 기능 폭을 넓히는 중, 바깥 사용자 반응은 거의 없음(계정 7개 대부분 팀 추정) | | diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index cbfab94..43eea34 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -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" diff --git a/backend/crud/card_crud.py b/backend/crud/card_crud.py index 887481c..8f39440 100644 --- a/backend/crud/card_crud.py +++ b/backend/crud/card_crud.py @@ -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 [] diff --git a/backend/crud/fortune_crud.py b/backend/crud/fortune_crud.py new file mode 100644 index 0000000..8742188 --- /dev/null +++ b/backend/crud/fortune_crud.py @@ -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] diff --git a/backend/crud/level_crud.py b/backend/crud/level_crud.py new file mode 100644 index 0000000..45b0db1 --- /dev/null +++ b/backend/crud/level_crud.py @@ -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 diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index ee5ead1..5d77a03 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -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: · spot: · event: + 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, diff --git a/backend/router/router.py b/backend/router/router.py index e35be0a..d89a536 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -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) diff --git a/backend/router/v1/card/card.py b/backend/router/v1/card/card.py index 5f0ccd8..8f2dccc 100644 --- a/backend/router/v1/card/card.py +++ b/backend/router/v1/card/card.py @@ -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) diff --git a/backend/router/v1/card/protocol.py b/backend/router/v1/card/protocol.py index 431f5a3..0a6b9e5 100644 --- a/backend/router/v1/card/protocol.py +++ b/backend/router/v1/card/protocol.py @@ -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 diff --git a/backend/router/v1/fortune/__init__.py b/backend/router/v1/fortune/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/fortune/fortune.py b/backend/router/v1/fortune/fortune.py new file mode 100644 index 0000000..2f0c0e6 --- /dev/null +++ b/backend/router/v1/fortune/fortune.py @@ -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]) diff --git a/backend/router/v1/fortune/protocol.py b/backend/router/v1/fortune/protocol.py new file mode 100644 index 0000000..71e931e --- /dev/null +++ b/backend/router/v1/fortune/protocol.py @@ -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/.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: · spot: · event:") + 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: · spot: · event:") + name: str + + +class Res_FortunePlaces(Res_WebPacketProtocol): + items: list[FortunePlace] = [] diff --git a/backend/router/v1/level/__init__.py b/backend/router/v1/level/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/level/level.py b/backend/router/v1/level/level.py new file mode 100644 index 0000000..67912af --- /dev/null +++ b/backend/router/v1/level/level.py @@ -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)) diff --git a/backend/router/v1/level/protocol.py b/backend/router/v1/level/protocol.py new file mode 100644 index 0000000..9c058ec --- /dev/null +++ b/backend/router/v1/level/protocol.py @@ -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="레벨 전체 (이름·필요한 각)") diff --git a/backend/services/fortune_deck.json b/backend/services/fortune_deck.json new file mode 100644 index 0000000..0cd9e1a --- /dev/null +++ b/backend/services/fortune_deck.json @@ -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" } + ] +} diff --git a/backend/services/fortune_service.py b/backend/services/fortune_service.py new file mode 100644 index 0000000..84f9de4 --- /dev/null +++ b/backend/services/fortune_service.py @@ -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]} diff --git a/backend/services/level_service.py b/backend/services/level_service.py new file mode 100644 index 0000000..b0a683b --- /dev/null +++ b/backend/services/level_service.py @@ -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) diff --git a/backend/services/reaction_service.py b/backend/services/reaction_service.py index 404e874..e9bbb2f 100644 --- a/backend/services/reaction_service.py +++ b/backend/services/reaction_service.py @@ -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: diff --git a/backend/services/talk_service.py b/backend/services/talk_service.py index e19b79b..9acb2d5 100644 --- a/backend/services/talk_service.py +++ b/backend/services/talk_service.py @@ -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: diff --git a/backend/tests/test_card.py b/backend/tests/test_card.py index 4eb6435..bb1cb2e 100644 --- a/backend/tests/test_card.py +++ b/backend/tests/test_card.py @@ -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 diff --git a/backend/tests/test_fortune.py b/backend/tests/test_fortune.py new file mode 100644 index 0000000..93663ed --- /dev/null +++ b/backend/tests/test_fortune.py @@ -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"] == [] diff --git a/backend/tests/test_level.py b/backend/tests/test_level.py new file mode 100644 index 0000000..a8936c0 --- /dev/null +++ b/backend/tests/test_level.py @@ -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 diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index 9700c66..56985bf 100644 --- a/docs/이벤트_추적.md +++ b/docs/이벤트_추적.md @@ -50,6 +50,9 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화 | `my_gak_save` | 내 각 만들기 성공 (로그인 전엔 기기에 저장) | `gak_name` | `myGakState.ts` `create` | | `toss_intro_start` | 토스판 첫 소개 화면에서 '시작하기' | 없음 | `tossIntro.tsx` | | `install_banner_close` | '홈 화면에 추가' 띠를 × 로 닫음 | 없음 | `installBanner.tsx` | +| `fortune_draw` | 오늘 한 장에서 카드를 뽑음 (하루 한 번, 다시 열 때는 안 보냄) | `card`(각 코드) | `fortune.tsx` `useTodayCard` | +| `day_log` | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` | +| `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`ootd`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` | - 공유창에서 사용자가 취소하면 `share`를 보내지 않는다. - 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다. diff --git a/frontend/public/b/icons/clapper.png b/frontend/public/b/icons/clapper.png new file mode 100644 index 0000000..77da148 Binary files /dev/null and b/frontend/public/b/icons/clapper.png differ diff --git a/frontend/public/b/icons/crystal_ball.png b/frontend/public/b/icons/crystal_ball.png new file mode 100644 index 0000000..df86b7e Binary files /dev/null and b/frontend/public/b/icons/crystal_ball.png differ diff --git a/frontend/public/b/icons/droplet.png b/frontend/public/b/icons/droplet.png new file mode 100644 index 0000000..55969e2 Binary files /dev/null and b/frontend/public/b/icons/droplet.png differ diff --git a/frontend/public/b/icons/leaf.png b/frontend/public/b/icons/leaf.png new file mode 100644 index 0000000..6f8a3b7 Binary files /dev/null and b/frontend/public/b/icons/leaf.png differ diff --git a/frontend/public/b/icons/milky_way.png b/frontend/public/b/icons/milky_way.png new file mode 100644 index 0000000..1d4e1aa Binary files /dev/null and b/frontend/public/b/icons/milky_way.png differ diff --git a/frontend/public/b/icons/rainbow.png b/frontend/public/b/icons/rainbow.png new file mode 100644 index 0000000..40d4629 Binary files /dev/null and b/frontend/public/b/icons/rainbow.png differ diff --git a/frontend/public/b/icons/shooting_star.png b/frontend/public/b/icons/shooting_star.png new file mode 100644 index 0000000..c1529a8 Binary files /dev/null and b/frontend/public/b/icons/shooting_star.png differ diff --git a/frontend/public/b/icons/speech.png b/frontend/public/b/icons/speech.png new file mode 100644 index 0000000..097a3ef Binary files /dev/null and b/frontend/public/b/icons/speech.png differ diff --git a/frontend/public/b/icons/tshirt.png b/frontend/public/b/icons/tshirt.png new file mode 100644 index 0000000..59d6662 Binary files /dev/null and b/frontend/public/b/icons/tshirt.png differ diff --git a/frontend/public/fortune/back.webp b/frontend/public/fortune/back.webp new file mode 100644 index 0000000..70a7762 Binary files /dev/null and b/frontend/public/fortune/back.webp differ diff --git a/frontend/public/fortune/bungeoppang.webp b/frontend/public/fortune/bungeoppang.webp new file mode 100644 index 0000000..2657f8e Binary files /dev/null and b/frontend/public/fortune/bungeoppang.webp differ diff --git a/frontend/public/fortune/camping.webp b/frontend/public/fortune/camping.webp new file mode 100644 index 0000000..84075ff Binary files /dev/null and b/frontend/public/fortune/camping.webp differ diff --git a/frontend/public/fortune/chimaek.webp b/frontend/public/fortune/chimaek.webp new file mode 100644 index 0000000..1db4356 Binary files /dev/null and b/frontend/public/fortune/chimaek.webp differ diff --git a/frontend/public/fortune/date.webp b/frontend/public/fortune/date.webp new file mode 100644 index 0000000..cc966aa Binary files /dev/null and b/frontend/public/fortune/date.webp differ diff --git a/frontend/public/fortune/dog.webp b/frontend/public/fortune/dog.webp new file mode 100644 index 0000000..1e102ba Binary files /dev/null and b/frontend/public/fortune/dog.webp differ diff --git a/frontend/public/fortune/drive.webp b/frontend/public/fortune/drive.webp new file mode 100644 index 0000000..826e7e0 Binary files /dev/null and b/frontend/public/fortune/drive.webp differ diff --git a/frontend/public/fortune/foliage.webp b/frontend/public/fortune/foliage.webp new file mode 100644 index 0000000..68c7c22 Binary files /dev/null and b/frontend/public/fortune/foliage.webp differ diff --git a/frontend/public/fortune/iced_hot.webp b/frontend/public/fortune/iced_hot.webp new file mode 100644 index 0000000..f2227ef Binary files /dev/null and b/frontend/public/fortune/iced_hot.webp differ diff --git a/frontend/public/fortune/jipkok.webp b/frontend/public/fortune/jipkok.webp new file mode 100644 index 0000000..12decdd Binary files /dev/null and b/frontend/public/fortune/jipkok.webp differ diff --git a/frontend/public/fortune/mood_song.webp b/frontend/public/fortune/mood_song.webp new file mode 100644 index 0000000..b561826 Binary files /dev/null and b/frontend/public/fortune/mood_song.webp differ diff --git a/frontend/public/fortune/netflix.webp b/frontend/public/fortune/netflix.webp new file mode 100644 index 0000000..7c6f879 Binary files /dev/null and b/frontend/public/fortune/netflix.webp differ diff --git a/frontend/public/fortune/pajeon.webp b/frontend/public/fortune/pajeon.webp new file mode 100644 index 0000000..b3e8773 Binary files /dev/null and b/frontend/public/fortune/pajeon.webp differ diff --git a/frontend/public/fortune/photo.webp b/frontend/public/fortune/photo.webp new file mode 100644 index 0000000..edac484 Binary files /dev/null and b/frontend/public/fortune/photo.webp differ diff --git a/frontend/public/fortune/picnic.webp b/frontend/public/fortune/picnic.webp new file mode 100644 index 0000000..dab3544 Binary files /dev/null and b/frontend/public/fortune/picnic.webp differ diff --git a/frontend/public/fortune/riverwind.webp b/frontend/public/fortune/riverwind.webp new file mode 100644 index 0000000..26f1ba5 Binary files /dev/null and b/frontend/public/fortune/riverwind.webp differ diff --git a/frontend/public/fortune/running.webp b/frontend/public/fortune/running.webp new file mode 100644 index 0000000..4ef79f5 Binary files /dev/null and b/frontend/public/fortune/running.webp differ diff --git a/frontend/public/fortune/sentimental.webp b/frontend/public/fortune/sentimental.webp new file mode 100644 index 0000000..5e76906 Binary files /dev/null and b/frontend/public/fortune/sentimental.webp differ diff --git a/frontend/public/fortune/stars.webp b/frontend/public/fortune/stars.webp new file mode 100644 index 0000000..61012f0 Binary files /dev/null and b/frontend/public/fortune/stars.webp differ diff --git a/frontend/public/fortune/sweetpotato.webp b/frontend/public/fortune/sweetpotato.webp new file mode 100644 index 0000000..922fe57 Binary files /dev/null and b/frontend/public/fortune/sweetpotato.webp differ diff --git a/frontend/public/fortune/themepark.webp b/frontend/public/fortune/themepark.webp new file mode 100644 index 0000000..707d679 Binary files /dev/null and b/frontend/public/fortune/themepark.webp differ diff --git a/frontend/public/fortune/walk.webp b/frontend/public/fortune/walk.webp new file mode 100644 index 0000000..f16b9db Binary files /dev/null and b/frontend/public/fortune/walk.webp differ diff --git a/frontend/public/fortune/yajang.webp b/frontend/public/fortune/yajang.webp new file mode 100644 index 0000000..e8746f0 Binary files /dev/null and b/frontend/public/fortune/yajang.webp differ diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index 1ce4957..a2b4b1e 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -10,6 +10,7 @@ import { AuthProvider } from './auth' import { RegionProvider } from './region' import { useAuth } from './authContext' import { preloadGoogle } from './googleScript' +import { LevelBadge, LevelWatcher } from './level' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { SheetProvider } from './Sheets' @@ -75,8 +76,9 @@ function TopBar() { {IS_TOSS ? null : mePending ? ( ) : me ? ( - ) : ( + ) : ( +
+
+ {card.name} +
+ {card.name} +

{card.reading}

+
+
+ {luck && ( +
+ + + + +
+ )} +

재미로 보는 날씨 운세

+
+ )} + {(streak > 0 || card) && ( +
+ {streak > 0 && ( + <> + + {Array.from({ length: STAMPS }, (_, i) => ( + + {i < filled ? '✓' : ''} + + ))} + + {streak}일째 + + )} + {card && ( + + )} +
+ )} + {card && today?.checkin_open && saveLog.mutate(v)} anon={!loggedIn} />} + + ) +} + +function Luck({ label, value, sub, swatch, icon }: { label: string; value?: string | null; sub?: string; swatch?: string; icon?: string | null }) { + if (!value) return null + return ( +
+
{label}
+
+ {swatch && } + {icon && } + {value} +
+ {sub &&

{sub}

} +
+ ) +} + +type LogInput = { mood: number; went_out: boolean; place_name?: string | null; place_ref?: string | null; card_hit?: boolean | null } + +/** 저녁 체크인: 기분 하나, 다녀온 곳(목록에서 찾거나 직접), 오늘 카드 맞았나 */ +function CheckIn({ log, saving, onSave, anon }: { log?: LogInput; saving: boolean; onSave: (v: LogInput) => void; anon: boolean }) { + const { region } = useRegion() + const [editing, setEditing] = useState(!log) + const [mood, setMood] = useState(log?.mood ?? 0) + const [place, setPlace] = useState(log?.place_name ?? '') + const [ref, setRef] = useState(log?.place_ref ?? null) + const [stayed, setStayed] = useState(log ? !log.went_out : false) + const [hit, setHit] = useState(log?.card_hit ?? null) + const [q, setQ] = useState('') + + // 글자를 멈춘 뒤에 찾는다 + useEffect(() => { + const t = setTimeout(() => setQ(ref ? '' : place.trim()), 250) + return () => clearTimeout(t) + }, [place, ref]) + const found = useQuery({ ...searchFortunePlacesOptions({ query: { region: region.code, q } }), enabled: q.length > 0, select: (d) => d.items ?? [] }) + + if (log && !editing) { + return ( + + ) + } + + const ready = mood > 0 && (stayed || place.trim().length > 0) + const save = () => { + onSave({ mood, went_out: !stayed, place_name: stayed ? null : place.trim(), place_ref: stayed ? null : ref, card_hit: hit }) + setEditing(false) + } + const chip = (on: boolean) => cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', on ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)') + + return ( +
+

오늘 하루 어땠어요?

+
+ {MOODS.map((m, i) => ( + + ))} +
+ +

어디 다녀왔어요?

+
+ { + setPlace(e.target.value.slice(0, 40)) + setRef(null) + setStayed(false) + }} + placeholder="장소 이름" + disabled={stayed} + className="min-w-0 flex-1 rounded-xl border border-(--line) bg-white px-3 py-2 text-[14px] font-semibold disabled:opacity-50" + /> + + {!stayed && !ref && (found.data?.length ?? 0) > 0 && ( +
    + {found.data!.map((p) => ( +
  • + +
  • + ))} +
+ )} +
+ +

오늘 카드, 맞았어요?

+
+ + +
+ + + {anon &&

이 기기에만 남아요. 로그인하면 폰을 바꿔도 남아요.

} +
+ ) +} diff --git a/frontend/src/b/level.tsx b/frontend/src/b/level.tsx new file mode 100644 index 0000000..e1050fe --- /dev/null +++ b/frontend/src/b/level.tsx @@ -0,0 +1,192 @@ +import { useEffect, useRef } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { attendMutation, myLevelOptions, myLevelQueryKey, sharedMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' +import type { ResLevel } from '@nalssigak/shared/api/client/types.gen' +import { cx } from '../lib/utils' +import { useAuth } from './authContext' +import { useSheet } from './sheetContext' +import { Ic } from './ui' + +// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 LEVELS) +const LEVEL_ICON = ['droplet', 'sun', 'leaf', 'rainbow', 'sunset', 'milky_way', 'shooting_star'] +export const levelIcon = (level: number) => LEVEL_ICON[Math.min(Math.max(level, 1), LEVEL_ICON.length) - 1] + +const SEEN_KEY = 'nalssigak.b.levelSeen' + +/** 서버 응답에서 기본값이 있는 칸은 생략될 수 있어 채워 둔다 */ +export type Level = ResLevel & { points: number; level: number; floor: number; streak: number } + +const toLevel = (d: ResLevel): Level | undefined => (d.result?.success ? { ...d, points: d.points ?? 0, level: d.level ?? 1, floor: d.floor ?? 0, streak: d.streak ?? 0 } : undefined) + +/** 내 레벨 (로그인했을 때만). 각을 주는 일은 모두 mutation 이라 끝날 때마다 다시 받는다(main.tsx) */ +export function useLevel() { + const { loggedIn } = useAuth() + return useQuery({ ...myLevelOptions(), enabled: loggedIn, staleTime: 60_000, select: toLevel }) +} + +/** 다음 레벨까지 진행률 0~1 */ +export function progress(l: Level) { + if (l.next_points == null) return 1 + return Math.min(1, (l.points - l.floor) / (l.next_points - l.floor)) +} + +/** 다음 레벨에서 열리는 것 이름 */ +export const nextUnlock = (l: Level) => (l.unlocks ?? []).filter((u) => u.level === l.level + 1).map((u) => u.name) + +/** 로그인한 사람이 앱을 열면 하루 한 번 출석 각. 레벨이 오르면 축하 창을 띄운다 (레이아웃에 한 번 둔다) */ +export function LevelWatcher() { + const { loggedIn, me } = useAuth() + const { open } = useSheet() + const queryClient = useQueryClient() + const level = useLevel().data + const { mutate } = useMutation({ ...attendMutation() }) + const attended = useRef(null) + + useEffect(() => { + if (!loggedIn || !me || attended.current === me.login_id) return + attended.current = me.login_id + mutate({}, { onSuccess: (res) => res.result?.success && queryClient.setQueryData(myLevelQueryKey(), res) }) + }, [loggedIn, me, mutate, queryClient]) + + useEffect(() => { + if (!level || !me) return + const key = `${SEEN_KEY}.${me.login_id}` + let seen: number | null = null + try { + seen = Number(localStorage.getItem(key)) || null + localStorage.setItem(key, String(level.level)) + } catch (e) { + console.warn('[level] 본 레벨을 저장하지 못함', e) + } + // 처음 보는 기기에선 축하하지 않는다 (예전 레벨을 모름) + if (seen != null && level.level > seen) open({ type: 'levelUp', level: level.level }) + }, [level, me, open]) + + return null +} + +/** 공유를 마치면 하루 한 번 각 (로그인했을 때만) */ +export function useShareReward() { + const { loggedIn } = useAuth() + const { mutate } = useMutation({ ...sharedMutation() }) + return () => { + if (loggedIn) mutate({}) + } +} + +/** 헤더 아바타 옆 작은 레벨 표시 */ +export function LevelBadge() { + const level = useLevel().data + if (!level) return null + return Lv.{level.level} +} + +function Bar({ value }: { value: number }) { + return ( + + + + ) +} + +/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. link 가 있으면 '각 모으는 법'으로 내 레벨 창을 연다 */ +export function LevelCard({ link = true }: { link?: boolean }) { + const level = useLevel().data + const { open } = useSheet() + if (!level) return null + const unlock = nextUnlock(level) + return ( +
+
+ + + Lv.{level.level} {level.name} + + {level.points}각 +
+
+ +
+
+ + {level.next_points != null ? `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}` : '가장 높은 레벨이에요'} + {unlock.length > 0 && · {unlock.join(', ')}} + + {link && ( + + )} +
+
+ ) +} + +/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */ +export function LevelSheet() { + const level = useLevel().data + if (!level) return null + const steps = (level.unlocks ?? []).reduce>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {}) + return ( +
+ +
+

오늘 받을 수 있는 각

+
    + {(level.today ?? []).map((a) => { + const done = a.earned >= a.cap + return ( +
  • + {done ? '✓' : ''} + {a.name} + + {a.earned > 0 && a.cap > a.points ? `${a.earned}/${a.cap}` : `+${a.points}`}각 + +
  • + ) + })} +
+

{level.streak > 0 ? `${level.streak}일 이어 출석 · 7일마다 +50각` : '7일 이어 출석하면 +50각'}

+
+
+

레벨이 오르면 열려요

+
    + {(level.levels ?? []).map(({ level: lv, name, points }) => { + const reached = level.level >= lv + return ( +
  1. + + + + Lv.{lv} {name} · {points}각 + + {lv === 1 ? '지금 있는 기능 전부' : (steps[lv] ?? []).join(', ')} + +
  2. + ) + })} +
+
+
+ ) +} + +/** 레벨이 오른 순간 */ +export function LevelUpSheet({ level: lv }: { level: number }) { + const level = useLevel().data + const { open } = useSheet() + const opened = (level?.unlocks ?? []).filter((u) => u.level === lv).map((u) => u.name) + const name = level?.levels?.find((l) => l.level === lv)?.name + return ( +
+ + + Lv.{lv} {name} + + {opened.length > 0 &&

새로 열렸어요: {opened.join(', ')}

} + +
+ ) +} diff --git a/frontend/src/b/lib.ts b/frontend/src/b/lib.ts index 507500c..f6b2f2e 100644 --- a/frontend/src/b/lib.ts +++ b/frontend/src/b/lib.ts @@ -2,7 +2,7 @@ import type { CSSProperties } from 'react' import { ARTICLE_LABEL } from '@nalssigak/shared/lib' const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo']) -const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert']) +const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star']) /** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */ export function iconSrc(name: string) { diff --git a/frontend/src/b/sheetContext.ts b/frontend/src/b/sheetContext.ts index 2caa46f..a9f1f8e 100644 --- a/frontend/src/b/sheetContext.ts +++ b/frontend/src/b/sheetContext.ts @@ -21,6 +21,10 @@ export type SheetState = | { type: 'install' } | { type: 'weatherWhy'; why: WeatherWhyPayload } | { type: 'talk'; talk: TalkData } + | { type: 'tarot' } + | { type: 'ootd' } + | { type: 'level' } + | { type: 'levelUp'; level: number } | null export type SheetApi = { open: (s: Exclude) => void; close: () => void } diff --git a/frontend/src/b/todayIcons.tsx b/frontend/src/b/todayIcons.tsx new file mode 100644 index 0000000..e151aed --- /dev/null +++ b/frontend/src/b/todayIcons.tsx @@ -0,0 +1,136 @@ +import { useState, type ReactNode } from 'react' +import { Link } from 'react-router' +import { useQuery } from '@tanstack/react-query' +import { getPostOptions, latestCardOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' +import { kst } from '@nalssigak/shared/lib' +import { track } from '../lib/analytics' +import { useFoliage } from './foliage' +import { useTarotBadge } from './fortune' +import { PostCard, PostCardSkel } from './Post' +import { useRegion } from './regionContext' +import { useSheet } from './sheetContext' +import { Ic, Rail } from './ui' + +/** 오늘 탭 '내 각' 줄 자리 (아이콘에서 거기로 내려간다) */ +export const MY_GAK_ID = 'my-gak' + +const OOTD_SEEN = 'nalssigak.b.ootdSeen' + +function readSeen() { + try { + return Number(localStorage.getItem(OOTD_SEEN)) || null + } catch { + // 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 매번 새로 보는 것으로 + return null + } +} + +function markSeen(postId: number) { + try { + localStorage.setItem(OOTD_SEEN, String(postId)) + } catch (e) { + console.warn('[ootd] 본 코디를 저장하지 못함', e) + } +} + +function isToday(iso?: string | null) { + if (!iso) return false + const a = kst(iso) + const b = kst(new Date()) + return a.y === b.y && a.mo === b.mo && a.d === b.d +} + +const useLatestOotd = () => useQuery({ ...latestCardOptions({ query: { template: 'ootd' } }), staleTime: 10 * 60_000 }) + +type Item = { key: string; label: string; icon: string; badge?: ReactNode; to?: string; onClick?: () => void } + +const Dot = () => + +/** 오늘 탭 히어로 아래 아이콘 줄: 누르면 창이 뜨거나 그 페이지로 간다. 오늘 아직 안 본 것엔 빨간 점 */ +export function TodayIcons() { + const { open } = useSheet() + const tarot = useTarotBadge() + const ootd = useLatestOotd().data + const [seen, setSeen] = useState(readSeen) + const { inSeason } = useFoliage() + const newOotd = !!ootd?.post_id && isToday(ootd.published_at) && seen !== ootd.post_id + + const items: Item[] = [ + { + key: 'tarot', + label: '오늘 타로', + icon: 'crystal_ball', + badge: tarot.drawn ? ( + {tarot.streak}일째 + ) : ( + + ), + onClick: () => open({ type: 'tarot' }), + }, + { + key: 'ootd', + label: '오늘 코디', + icon: 'tshirt', + badge: newOotd ? : null, + onClick: () => { + if (ootd?.post_id) { + markSeen(ootd.post_id) + setSeen(ootd.post_id) + } + open({ type: 'ootd' }) + }, + }, + ...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []), + { key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' }, + { key: 'myGak', label: '내 각', icon: 'rabbit', onClick: () => document.getElementById(MY_GAK_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) }, + { key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' }, + ] + + const tile = (it: Item) => ( + <> + + + {it.badge} + + {it.label} + + ) + const cls = 'flex w-[60px] cursor-pointer flex-col items-center' + + return ( + + {items.map((it) => + it.to ? ( + track('today_icon', { icon: it.key })} className={cls}> + {tile(it)} + + ) : ( + + ), + )} + + ) +} + +/** 오늘 코디 창: 오늘 피드에 올린 코디 카드 (오늘 것이 없으면 안내) */ +export function OotdSheet() { + const { region } = useRegion() + const latest = useLatestOotd() + const postId = latest.data?.post_id + const today = isToday(latest.data?.published_at) + const post = useQuery({ ...getPostOptions({ path: { post_id: postId ?? 0 }, query: { region: region.code } }), enabled: !!postId && today }) + + if (latest.isPending || (postId && today && post.isPending)) return + if (!postId || !today || !post.data?.post) return

아직 오늘 코디가 없어요

+ return +} diff --git a/frontend/src/lib/analytics.ts b/frontend/src/lib/analytics.ts index ada55fb..e61630a 100644 --- a/frontend/src/lib/analytics.ts +++ b/frontend/src/lib/analytics.ts @@ -28,6 +28,9 @@ type Events = { foliage_open: Record foliage_spot: { spot_name: string; from: 'page' | 'card' } my_gak_save: { gak_name: string } + fortune_draw: { card: string } + day_log: { mood: number; went_out: boolean; card_hit: boolean | null } + today_icon: { icon: string } toss_intro_start: Record install_banner_close: Record } diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index cd3ae90..0c7b158 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,4 +1,5 @@ -import { keepPreviousData, QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { keepPreviousData, MutationCache, QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' @@ -11,8 +12,10 @@ import { track } from './lib/analytics' for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false }) // 칩·지역·검색어를 바꿔 다시 받는 동안 이전 결과를 그대로 두어 화면이 비거나 접히지 않게 한다 -const queryClient = new QueryClient({ +const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } }, + // 각을 주는 일(타로·좋아요·댓글·글·체크인·공유)은 모두 mutation 이라, 끝나면 내 레벨을 다시 받는다 + mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) }), }) // 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수 diff --git a/shared/api/client/@tanstack/react-query.gen.ts b/shared/api/client/@tanstack/react-query.gen.ts index cb8ca55..032d6bc 100644 --- a/shared/api/client/@tanstack/react-query.gen.ts +++ b/shared/api/client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { addComment, addMyGak, addTalk, agreeTerms, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportComment, reportTalk, savePost, scoreMyGak, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen'; -import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetReelCoverData, GetReelCoverError, GetReelVideoData, GetReelVideoError, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListReelsData, ListReelsError, ListReelsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListShortsData, ListShortsResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen'; +import { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, drawFortune, getArticle, getCardImage, getFeed, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, latestCard, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AttendData, AttendError, AttendResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, DrawFortuneData, DrawFortuneError, DrawFortuneResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetFortuneTodayData, GetFortuneTodayError, GetFortuneTodayResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetReelCoverData, GetReelCoverError, GetReelVideoData, GetReelVideoError, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, ImportFortuneData, ImportFortuneError, ImportFortuneResponse, LatestCardData, LatestCardError, LatestCardResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListReelsData, ListReelsError, ListReelsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListShortsData, ListShortsResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, MyLevelData, MyLevelError, MyLevelResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, SharedData, SharedError, SharedResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -968,6 +968,145 @@ export const deleteMyGakMutation = (options?: Partial>) return mutationOptions; }; +export const getFortuneTodayQueryKey = (options: Options) => createQueryKey('getFortuneToday', options); + +/** + * 오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이) + */ +export const getFortuneTodayOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await getFortuneToday({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: getFortuneTodayQueryKey(options) +}); + +/** + * 오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산 + */ +export const drawFortuneMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await drawFortune({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다 + */ +export const saveDayLogMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await saveDayLog({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다) + */ +export const importFortuneMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await importFortune({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const searchFortunePlacesQueryKey = (options: Options) => createQueryKey('searchFortunePlaces', options); + +/** + * 체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사 + */ +export const searchFortunePlacesOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await searchFortunePlaces({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: searchFortunePlacesQueryKey(options) +}); + +export const myLevelQueryKey = (options?: Options) => createQueryKey('myLevel', options); + +/** + * 내 레벨: 모은 각, 다음 레벨, 오늘 받은 각, 레벨로 열리는 것 + */ +export const myLevelOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await myLevel({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: myLevelQueryKey(options) +}); + +/** + * 출석 (하루 한 번 각). 7일 이어지면 보너스 + */ +export const attendMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await attend({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 공유를 마쳤을 때 (하루 한 번 각) + */ +export const sharedMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await shared({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + export const talkGroupsQueryKey = (options?: Options) => createQueryKey('talkGroups', options); /** @@ -1362,6 +1501,24 @@ export const createCardMutation = (options?: Partial>): return mutationOptions; }; +export const latestCardQueryKey = (options: Options) => createQueryKey('latestCard', options); + +/** + * 그 틀로 가장 최근에 피드에 올린 카드뉴스의 포스트 (오늘 탭 '오늘 코디' 아이콘) + */ +export const latestCardOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await latestCard({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: latestCardQueryKey(options) +}); + /** * 승인 대기 카드뉴스를 그날 피드에 올리기 (관리자) */ diff --git a/shared/api/client/index.ts b/shared/api/client/index.ts index 32889ab..52b2440 100644 --- a/shared/api/client/index.ts +++ b/shared/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { addComment, addMyGak, addTalk, agreeTerms, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportComment, reportTalk, savePost, scoreMyGak, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListBlockedData, type ListBlockedError, type ListBlockedErrors, type ListBlockedResponse, type ListBlockedResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListReelsData, type ListReelsError, type ListReelsErrors, type ListReelsResponse, type ListReelsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListShortsData, type ListShortsResponse, type ListShortsResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, type PostReaction, PostType, type PublishCardData, type PublishCardError, type PublishCardErrors, type PublishCardResponse, type PublishCardResponses, type PublishInstagram2Data, type PublishInstagram2Error, type PublishInstagram2Errors, type PublishInstagram2Response, type PublishInstagram2Responses, type PublishInstagramData, type PublishInstagramError, type PublishInstagramErrors, type PublishInstagramResponse, type PublishInstagramResponses, type Rain2h, type RainHourData, RainType, type RankData, type ReelItem, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type RejectCardData, type RejectCardError, type RejectCardErrors, type RejectCardResponse, type RejectCardResponses, type ReportCommentData, type ReportCommentError, type ReportCommentErrors, type ReportCommentResponse, type ReportCommentResponses, ReportReason, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqCardCreate, type ReqComment, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqReelCreate, type ReqRefresh, type ReqReport, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResBlockedList, type ResCard, type ResCardList, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResReel, type ResReelList, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResShortList, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkGroups, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type ShortItem, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, type TalkGroup, type TalkGroupsData, type TalkGroupsError, type TalkGroupsErrors, type TalkGroupsResponse, type TalkGroupsResponses, TalkReport, TalkTopic, type TermData, type Tomorrow, type TopIndex, type TossData, type TossError, type TossErrors, type TossResponse, type TossResponses, type TossUnlinkData, type TossUnlinkError, type TossUnlinkErrors, type TossUnlinkResponse, type TossUnlinkResponses, type TrendPoint, type UnblockData, type UnblockError, type UnblockErrors, type UnblockResponse, type UnblockResponses, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; +export { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, drawFortune, getArticle, getCardImage, getFeed, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, latestCard, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AttendData, type AttendError, type AttendErrors, type AttendResponse, type AttendResponses, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DayLogData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type DrawFortuneData, type DrawFortuneError, type DrawFortuneErrors, type DrawFortuneResponse, type DrawFortuneResponses, type ErrorInfo, type EventData, type Factor, type FortuneCard, type FortuneLuck, type FortunePlace, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetFortuneTodayData, type GetFortuneTodayError, type GetFortuneTodayErrors, type GetFortuneTodayResponse, type GetFortuneTodayResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, type ImportFortuneData, type ImportFortuneError, type ImportFortuneErrors, type ImportFortuneResponse, type ImportFortuneResponses, IndexCategory, type IndexSummary, type LatestCardData, type LatestCardError, type LatestCardErrors, type LatestCardResponse, type LatestCardResponses, type LevelAction, type LevelStep, type LevelUnlock, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListBlockedData, type ListBlockedError, type ListBlockedErrors, type ListBlockedResponse, type ListBlockedResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListReelsData, type ListReelsError, type ListReelsErrors, type ListReelsResponse, type ListReelsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListShortsData, type ListShortsResponse, type ListShortsResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LocalDraw, type LocalLog, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type MyLevelData, type MyLevelError, type MyLevelErrors, type MyLevelResponse, type MyLevelResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, type PostReaction, PostType, type PublishCardData, type PublishCardError, type PublishCardErrors, type PublishCardResponse, type PublishCardResponses, type PublishInstagram2Data, type PublishInstagram2Error, type PublishInstagram2Errors, type PublishInstagram2Response, type PublishInstagram2Responses, type PublishInstagramData, type PublishInstagramError, type PublishInstagramErrors, type PublishInstagramResponse, type PublishInstagramResponses, type Rain2h, type RainHourData, RainType, type RankData, type ReelItem, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type RejectCardData, type RejectCardError, type RejectCardErrors, type RejectCardResponse, type RejectCardResponses, type ReportCommentData, type ReportCommentError, type ReportCommentErrors, type ReportCommentResponse, type ReportCommentResponses, ReportReason, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqCardCreate, type ReqComment, type ReqDayLog, type ReqFortuneDraw, type ReqFortuneImport, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqReelCreate, type ReqRefresh, type ReqReport, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResBlockedList, type ResCard, type ResCardList, type ResComment, type ResCommentLike, type ResCommentList, type ResDayLog, type ResEventList, type ResFeed, type ResFortunePlaces, type ResFortuneToday, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLatestCard, type ResLevel, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResReel, type ResReelList, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResShortList, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkGroups, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SaveDayLogData, type SaveDayLogError, type SaveDayLogErrors, type SaveDayLogResponse, type SaveDayLogResponses, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type SearchFortunePlacesData, type SearchFortunePlacesError, type SearchFortunePlacesErrors, type SearchFortunePlacesResponse, type SearchFortunePlacesResponses, type SharedData, type SharedError, type SharedErrors, type SharedResponse, type SharedResponses, type ShortItem, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, type TalkGroup, type TalkGroupsData, type TalkGroupsError, type TalkGroupsErrors, type TalkGroupsResponse, type TalkGroupsResponses, TalkReport, TalkTopic, type TermData, type Tomorrow, type TopIndex, type TossData, type TossError, type TossErrors, type TossResponse, type TossResponses, type TossUnlinkData, type TossUnlinkError, type TossUnlinkErrors, type TossUnlinkResponse, type TossUnlinkResponses, type TrendPoint, type UnblockData, type UnblockError, type UnblockErrors, type UnblockResponse, type UnblockResponses, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; diff --git a/shared/api/client/sdk.gen.ts b/shared/api/client/sdk.gen.ts index 2eb4fac..1d0530e 100644 --- a/shared/api/client/sdk.gen.ts +++ b/shared/api/client/sdk.gen.ts @@ -2,7 +2,7 @@ import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client'; import { client } from './client.gen'; -import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListShortsData, ListShortsResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AttendData, AttendErrors, AttendResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, DrawFortuneData, DrawFortuneErrors, DrawFortuneResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetFortuneTodayData, GetFortuneTodayErrors, GetFortuneTodayResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, ImportFortuneData, ImportFortuneErrors, ImportFortuneResponses, LatestCardData, LatestCardErrors, LatestCardResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListShortsData, ListShortsResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, MyLevelData, MyLevelErrors, MyLevelResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, SharedData, SharedErrors, SharedResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen'; export type Options = Options2 & { /** @@ -335,6 +335,67 @@ export const scoreMyGak = (options: Options */ export const deleteMyGak = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/my-gak/{my_gak_id}', ...options }); +/** + * 오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이) + */ +export const getFortuneToday = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/fortune/today', ...options }); + +/** + * 오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산 + */ +export const drawFortune = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/fortune/draw', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다 + */ +export const saveDayLog = (options: Options): RequestResult => (options.client ?? client).put({ + url: '/v1/fortune/log', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다) + */ +export const importFortune = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/fortune/import', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사 + */ +export const searchFortunePlaces = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/fortune/places', ...options }); + +/** + * 내 레벨: 모은 각, 다음 레벨, 오늘 받은 각, 레벨로 열리는 것 + */ +export const myLevel = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/level/me', ...options }); + +/** + * 출석 (하루 한 번 각). 7일 이어지면 보너스 + */ +export const attend = (options?: Options): RequestResult => (options?.client ?? client).post({ url: '/v1/level/attend', ...options }); + +/** + * 공유를 마쳤을 때 (하루 한 번 각) + */ +export const shared = (options?: Options): RequestResult => (options?.client ?? client).post({ url: '/v1/level/share', ...options }); + /** * 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장) */ @@ -459,6 +520,11 @@ export const createCard = (options: Options } }); +/** + * 그 틀로 가장 최근에 피드에 올린 카드뉴스의 포스트 (오늘 탭 '오늘 코디' 아이콘) + */ +export const latestCard = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/card/latest', ...options }); + /** * 승인 대기 카드뉴스를 그날 피드에 올리기 (관리자) */ diff --git a/shared/api/client/types.gen.ts b/shared/api/client/types.gen.ts index 431c3dc..2f6d9fc 100644 --- a/shared/api/client/types.gen.ts +++ b/shared/api/client/types.gen.ts @@ -512,6 +512,42 @@ export type DayData = { is_rainy: boolean; }; +/** + * DayLogData + */ +export type DayLogData = { + /** + * Day + */ + day: string; + /** + * Mood + * + * 1(가장 좋음)~5 + */ + mood: number; + /** + * Went Out + */ + went_out: boolean; + /** + * Place Name + */ + place_name?: string | null; + /** + * Place Ref + * + * 목록에서 고른 곳: place: · spot: · event: + */ + place_ref?: string | null; + /** + * Card Hit + * + * 오늘 카드 맞았나 + */ + card_hit?: boolean | null; +}; + /** * ErrorInfo */ @@ -610,6 +646,92 @@ export type Factor = { note: string; }; +/** + * FortuneCard + */ +export type FortuneCard = { + /** + * Code + * + * 각 코드 (카드 그림은 /fortune/.webp) + */ + code: string; + /** + * Name + */ + name: string; + /** + * Icon + */ + icon: string; + /** + * Reading + * + * 리딩 한 문장 + */ + reading: string; + /** + * Color + * + * 행운 색 이름 + */ + color: string; + /** + * Hex + * + * 행운 색 #rrggbb + */ + hex: string; +}; + +/** + * FortuneLuck + */ +export type FortuneLuck = { + /** + * Time + * + * 행운 시간: 오늘 남은 구간 중 날씨가 가장 좋은 때 (예: 오후 4~7시) + */ + time?: string | null; + /** + * Place + * + * 행운 장소: 날씨 맞춤 데이트 명소 + */ + place?: string | null; + /** + * Place Id + */ + place_id?: number | null; + /** + * Top Gak + * + * 지금 1위 각 이름 + */ + top_gak?: string | null; + /** + * Top Icon + */ + top_icon?: string | null; +}; + +/** + * FortunePlace + */ +export type FortunePlace = { + /** + * Ref + * + * place: · spot: · event: + */ + ref: string; + /** + * Name + */ + name: string; +}; + /** * GakSlide */ @@ -993,6 +1115,124 @@ export type IndexSummary = { slots?: Array; }; +/** + * LevelAction + */ +export type LevelAction = { + /** + * Action + */ + action: string; + /** + * Name + */ + name: string; + /** + * Points + * + * 한 번에 주는 각 + */ + points: number; + /** + * Cap + * + * 하루 한도 + */ + cap: number; + /** + * Earned + * + * 오늘 받은 각 + */ + earned: number; +}; + +/** + * LevelStep + */ +export type LevelStep = { + /** + * Level + */ + level: number; + /** + * Name + */ + name: string; + /** + * Points + * + * 이 레벨이 되는 각 총량 + */ + points: number; +}; + +/** + * LevelUnlock + */ +export type LevelUnlock = { + /** + * Level + */ + level: number; + /** + * Key + */ + key: string; + /** + * Name + */ + name: string; +}; + +/** + * LocalDraw + */ +export type LocalDraw = { + /** + * Day + */ + day: string; + /** + * Card Code + */ + card_code: string; +}; + +/** + * LocalLog + */ +export type LocalLog = { + /** + * Region Code + */ + region_code: string; + /** + * Mood + */ + mood: number; + /** + * Went Out + */ + went_out: boolean; + /** + * Place Name + */ + place_name?: string | null; + /** + * Place Ref + */ + place_ref?: string | null; + /** + * Card Hit + */ + card_hit?: boolean | null; + /** + * Day + */ + day: string; +}; + /** * Me */ @@ -1691,6 +1931,72 @@ export type ReqComment = { region?: string | null; }; +/** + * Req_DayLog + */ +export type ReqDayLog = { + /** + * Region Code + */ + region_code: string; + /** + * Mood + */ + mood: number; + /** + * Went Out + */ + went_out: boolean; + /** + * Place Name + */ + place_name?: string | null; + /** + * Place Ref + */ + place_ref?: string | null; + /** + * Card Hit + */ + card_hit?: boolean | null; +}; + +/** + * Req_FortuneDraw + */ +export type ReqFortuneDraw = { + /** + * Region Code + */ + region_code: string; + /** + * Card Code + * + * 로그인 안 했을 때 기기에 있는 오늘 카드 (없으면 새로 뽑음) + */ + card_code?: string | null; + /** + * Days + * + * 로그인 안 했을 때 기기에 남은 뽑은 날 (연속 기록용) + */ + days?: Array; +}; + +/** + * Req_FortuneImport + */ +export type ReqFortuneImport = { + /** + * Draws + */ + draws?: Array; + /** + * Logs + */ + logs?: Array; +}; + /** * Req_Google */ @@ -2080,6 +2386,18 @@ export type ResCommentList = { next_cursor?: number | null; }; +/** + * Res_DayLog + */ +export type ResDayLog = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + log?: DayLogData | null; +}; + /** * Res_EventList */ @@ -2133,6 +2451,57 @@ export type ResFeed = { bands?: Bands | null; }; +/** + * Res_FortunePlaces + */ +export type ResFortunePlaces = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Items + */ + items?: Array; +}; + +/** + * Res_FortuneToday + */ +export type ResFortuneToday = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Day + */ + day?: string | null; + /** + * 오늘 뽑은 카드. 아직 안 뽑았으면 없음 + */ + card?: FortuneCard | null; + luck?: FortuneLuck | null; + /** + * Streak + * + * 이어 뽑은 날 수 (7일에 한 번 쉬는 날은 봐준다) + */ + streak?: number; + /** + * Checkin Open + * + * 저녁(해 지기 2시간 전)부터 체크인 + */ + checkin_open?: boolean; + /** + * 오늘 체크인 (로그인했을 때) + */ + log?: DayLogData | null; +}; + /** * Res_Health */ @@ -2227,6 +2596,86 @@ export type ResIndexList = { items?: Array; }; +/** + * Res_LatestCard + */ +export type ResLatestCard = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Post Id + */ + post_id?: number | null; + /** + * Published At + */ + published_at?: string | null; +}; + +/** + * Res_Level + */ +export type ResLevel = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Points + * + * 모은 각 총량 + */ + points?: number; + /** + * Level + */ + level?: number; + /** + * Name + */ + name?: string | null; + /** + * Floor + * + * 지금 레벨이 시작하는 각 + */ + floor?: number; + /** + * Next Points + * + * 다음 레벨에 필요한 총량 (마지막 레벨이면 없음) + */ + next_points?: number | null; + /** + * Next Name + */ + next_name?: string | null; + /** + * Streak + * + * 이어 출석한 날 + */ + streak?: number; + /** + * Today + */ + today?: Array; + /** + * Unlocks + */ + unlocks?: Array; + /** + * Levels + * + * 레벨 전체 (이름·필요한 각) + */ + levels?: Array; +}; + /** * Res_Logout */ @@ -5552,6 +6001,262 @@ export type DeleteMyGakResponses = { export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses]; +export type GetFortuneTodayData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query: { + /** + * Region + */ + region: string; + }; + url: '/v1/fortune/today'; +}; + +export type GetFortuneTodayErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetFortuneTodayError = GetFortuneTodayErrors[keyof GetFortuneTodayErrors]; + +export type GetFortuneTodayResponses = { + /** + * Successful Response + */ + 200: ResFortuneToday; +}; + +export type GetFortuneTodayResponse = GetFortuneTodayResponses[keyof GetFortuneTodayResponses]; + +export type DrawFortuneData = { + body: ReqFortuneDraw; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/fortune/draw'; +}; + +export type DrawFortuneErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DrawFortuneError = DrawFortuneErrors[keyof DrawFortuneErrors]; + +export type DrawFortuneResponses = { + /** + * Successful Response + */ + 200: ResFortuneToday; +}; + +export type DrawFortuneResponse = DrawFortuneResponses[keyof DrawFortuneResponses]; + +export type SaveDayLogData = { + body: ReqDayLog; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/fortune/log'; +}; + +export type SaveDayLogErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SaveDayLogError = SaveDayLogErrors[keyof SaveDayLogErrors]; + +export type SaveDayLogResponses = { + /** + * Successful Response + */ + 200: ResDayLog; +}; + +export type SaveDayLogResponse = SaveDayLogResponses[keyof SaveDayLogResponses]; + +export type ImportFortuneData = { + body: ReqFortuneImport; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/fortune/import'; +}; + +export type ImportFortuneErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ImportFortuneError = ImportFortuneErrors[keyof ImportFortuneErrors]; + +export type ImportFortuneResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type ImportFortuneResponse = ImportFortuneResponses[keyof ImportFortuneResponses]; + +export type SearchFortunePlacesData = { + body?: never; + path?: never; + query: { + /** + * Region + */ + region: string; + /** + * Q + */ + q: string; + }; + url: '/v1/fortune/places'; +}; + +export type SearchFortunePlacesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SearchFortunePlacesError = SearchFortunePlacesErrors[keyof SearchFortunePlacesErrors]; + +export type SearchFortunePlacesResponses = { + /** + * Successful Response + */ + 200: ResFortunePlaces; +}; + +export type SearchFortunePlacesResponse = SearchFortunePlacesResponses[keyof SearchFortunePlacesResponses]; + +export type MyLevelData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/level/me'; +}; + +export type MyLevelErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type MyLevelError = MyLevelErrors[keyof MyLevelErrors]; + +export type MyLevelResponses = { + /** + * Successful Response + */ + 200: ResLevel; +}; + +export type MyLevelResponse = MyLevelResponses[keyof MyLevelResponses]; + +export type AttendData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/level/attend'; +}; + +export type AttendErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AttendError = AttendErrors[keyof AttendErrors]; + +export type AttendResponses = { + /** + * Successful Response + */ + 200: ResLevel; +}; + +export type AttendResponse = AttendResponses[keyof AttendResponses]; + +export type SharedData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/level/share'; +}; + +export type SharedErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SharedError = SharedErrors[keyof SharedErrors]; + +export type SharedResponses = { + /** + * Successful Response + */ + 200: ResLevel; +}; + +export type SharedResponse = SharedResponses[keyof SharedResponses]; + export type TalkGroupsData = { body?: never; headers?: { @@ -6231,6 +6936,36 @@ export type CreateCardResponses = { export type CreateCardResponse = CreateCardResponses[keyof CreateCardResponses]; +export type LatestCardData = { + body?: never; + path?: never; + query: { + /** + * Template + */ + template: string; + }; + url: '/v1/card/latest'; +}; + +export type LatestCardErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type LatestCardError = LatestCardErrors[keyof LatestCardErrors]; + +export type LatestCardResponses = { + /** + * Successful Response + */ + 200: ResLatestCard; +}; + +export type LatestCardResponse = LatestCardResponses[keyof LatestCardResponses]; + export type PublishCardData = { body?: never; headers?: {