feat: 오늘 한 장 — 하루 한 장 날씨 카드(22장)·실제 날씨 행운·연속 도장·저녁 체크인

- 로그인 안 하면 기기에, 로그인하면 계정에 남기고 로그인할 때 기기 기록을 옮긴다 (표 fortune_draw·day_log)
- 행운 시간은 오늘 남은 구간 중 날씨 점수가 가장 높은 때, 장소는 날씨 맞춤 데이트 명소, 1위 각은 지금 순위
- 체크인은 해 지기 2시간 전부터: 기분·다녀온 곳(명소·노을 명소·지금 하는 행사에서 찾거나 직접)·카드 맞았나
- GA4 fortune_draw·day_log
This commit is contained in:
minaChoi committed 2026-10-28 13:22:55 +09:00
1 parent 52a4830b08
commit c37773f48f
43 files changed
+1567 -6

No files matched your search

+2 -1
View File
@@ -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개 대부분 팀 추정) | |
+23
View File
@@ -453,6 +453,29 @@ class MyGak(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class FortuneDraw(Base):
__tablename__ = "fortune_draw"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
day: Mapped[date] = mapped_column(Date, primary_key=True)
card_code: Mapped[str] = mapped_column(String(32))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class DayLog(Base):
__tablename__ = "day_log"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
day: Mapped[date] = mapped_column(Date, primary_key=True)
mood: Mapped[int] = mapped_column(SmallInteger)
went_out: Mapped[bool] = mapped_column(Boolean)
place_name: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
place_ref: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
card_hit: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
region_code: Mapped[str] = mapped_column(String(10))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class Talk(Base):
__tablename__ = "talk"
+52
View File
@@ -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]
+23
View File
@@ -318,6 +318,29 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
ALTER TABLE public.my_gak ADD COLUMN IF NOT EXISTS icon VARCHAR(32) NULL; -- 고른 아이콘 (각 아이콘 이름, 없으면 기본)
-- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다)
CREATE TABLE IF NOT EXISTS public.fortune_draw (
user_id UUID NOT NULL,
day DATE NOT NULL,
card_code VARCHAR(32) NOT NULL, -- 각 코드 (services/fortune_deck.json)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, day)
);
-- 저녁 체크인: 그날 기분·다녀온 곳·카드가 맞았는지 (본인만 본다)
CREATE TABLE IF NOT EXISTS public.day_log (
user_id UUID NOT NULL,
day DATE NOT NULL,
mood SMALLINT NOT NULL, -- 1(가장 좋음)~5
went_out BOOLEAN NOT NULL,
place_name VARCHAR(40) NULL, -- 다녀온 곳 이름 (목록에서 고르거나 직접 씀)
place_ref VARCHAR(40) NULL, -- 목록에서 고른 곳: place:<id> · spot:<id> · event:<id>
card_hit BOOLEAN NULL, -- 오늘 카드 맞았나 (안 고르면 NULL)
region_code VARCHAR(10) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, day)
);
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
CREATE TABLE IF NOT EXISTS public.talk (
talk_id BIGSERIAL PRIMARY KEY,
+2
View File
@@ -14,6 +14,7 @@ from router.v1.feed.feed import router as feed_router
from router.v1.image.image import router as image_router
from router.v1.index.index import router as index_router
from router.v1.my_gak.my_gak import router as my_gak_router
from router.v1.fortune.fortune import router as fortune_router
from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router
@@ -48,6 +49,7 @@ app.include_router(feed_router)
app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(my_gak_router)
app.include_router(fortune_router)
app.include_router(talk_router)
app.include_router(watch_router)
app.include_router(image_router)
Whitespace-only changes.
+61
View File
@@ -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])
+83
View File
@@ -0,0 +1,83 @@
from datetime import date
from typing import Optional
from pydantic import Field
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
class FortuneCard(WebPacketProtocol):
code: str = Field(description="각 코드 (카드 그림은 /fortune/<code>.webp)")
name: str
icon: str
reading: str = Field(description="리딩 한 문장")
color: str = Field(description="행운 색 이름")
hex: str = Field(description="행운 색 #rrggbb")
class FortuneLuck(WebPacketProtocol):
time: Optional[str] = Field(None, description="행운 시간: 오늘 남은 구간 중 날씨가 가장 좋은 때 (예: 오후 4~7시)")
place: Optional[str] = Field(None, description="행운 장소: 날씨 맞춤 데이트 명소")
place_id: Optional[int] = None
top_gak: Optional[str] = Field(None, description="지금 1위 각 이름")
top_icon: Optional[str] = None
class DayLogData(WebPacketProtocol):
day: date
mood: int = Field(ge=1, le=5, description="1(가장 좋음)~5")
went_out: bool
place_name: Optional[str] = None
place_ref: Optional[str] = Field(None, description="목록에서 고른 곳: place:<id> · spot:<id> · event:<id>")
card_hit: Optional[bool] = Field(None, description="오늘 카드 맞았나")
class Res_FortuneToday(Res_WebPacketProtocol):
day: Optional[date] = None
card: Optional[FortuneCard] = Field(None, description="오늘 뽑은 카드. 아직 안 뽑았으면 없음")
luck: Optional[FortuneLuck] = None
streak: int = Field(0, description="이어 뽑은 날 수 (7일에 한 번 쉬는 날은 봐준다)")
checkin_open: bool = Field(False, description="저녁(해 지기 2시간 전)부터 체크인")
log: Optional[DayLogData] = Field(None, description="오늘 체크인 (로그인했을 때)")
class Req_FortuneDraw(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
card_code: Optional[str] = Field(None, max_length=32, description="로그인 안 했을 때 기기에 있는 오늘 카드 (없으면 새로 뽑음)")
days: list[date] = Field(default=[], max_length=60, description="로그인 안 했을 때 기기에 남은 뽑은 날 (연속 기록용)")
class Req_DayLog(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
mood: int = Field(ge=1, le=5)
went_out: bool
place_name: Optional[str] = Field(None, max_length=40)
place_ref: Optional[str] = Field(None, max_length=40)
card_hit: Optional[bool] = None
class Res_DayLog(Res_WebPacketProtocol):
log: Optional[DayLogData] = None
class LocalDraw(WebPacketProtocol):
day: date
card_code: str = Field(max_length=32)
class LocalLog(Req_DayLog):
day: date
class Req_FortuneImport(Req_WebPacketProtocol):
draws: list[LocalDraw] = Field(default=[], max_length=60)
logs: list[LocalLog] = Field(default=[], max_length=60)
class FortunePlace(WebPacketProtocol):
ref: str = Field(description="place:<id> · spot:<id> · event:<id>")
name: str
class Res_FortunePlaces(Res_WebPacketProtocol):
items: list[FortunePlace] = []
+26
View File
@@ -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" }
]
}
+205
View File
@@ -0,0 +1,205 @@
import json
import random
import re
from dataclasses import dataclass
from datetime import date, timedelta
from pathlib import Path
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import DayLog, User
from common.enums import ErrorType
from common.utils.kma_time import now_kst
from crud.fortune_crud import FortuneCRUD
from services.calc.day_slot import SLOTS, slot_hours
from services.calc.sun import sun_times
from services.index_service import IndexService, current_slot, shown_slot
from services.week_service import WeekService
# 오늘 한 장 덱: 각 코드마다 리딩 한 문장과 행운 색. 이름·아이콘은 각 정의에서 가져온다
DECK: dict[str, dict] = {c["code"]: c for c in json.loads((Path(__file__).parent / "fortune_deck.json").read_text(encoding="utf-8"))["cards"]}
# 연속 기록은 이만큼 거슬러 올라가 센다. 기기에서 옮겨 오는 기록도 이 안쪽만 받는다
HISTORY_DAYS = 60
# 연속 기록에서 쉬는 날은 이 간격에 한 번만 봐준다
REST_EVERY_DAYS = 7
PLACE_LIMIT = 8
_PLACE_REF = re.compile(r"^(place|spot|event):\d{1,12}$")
def streak(days: set[date], today: date) -> int:
"""오늘(아직 안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수. 하루 빠진 날은 7일에 한 번 쉬는 날로 봐준다."""
d = today if today in days else today - timedelta(days=1)
count, rests = 0, []
while True:
if d in days:
count += 1
elif d - timedelta(days=1) in days and all((r - d).days >= REST_EVERY_DAYS for r in rests):
rests.append(d)
else:
return count
d -= timedelta(days=1)
def hours_text(hours: set[int]) -> str:
"""구간 시각(24 이상은 다음 날)을 '오후 4~7시'처럼. 끝은 마지막 시각의 다음 정각."""
start, end = min(hours), max(hours) + 1
def part(h: int) -> tuple[str, int]:
h %= 24
word = "새벽" if h < 6 else "오전" if h < 12 else "오후"
return word, h % 12 or 12
(w1, h1), (w2, h2) = part(start), part(end)
return f"{w1} {h1}~{h2}시" if w1 == w2 else f"{w1} {h1}시~{w2} {h2}시"
@dataclass
class Card:
code: str
name: str
icon: str
reading: str
color: str
hex: str
@dataclass
class Luck:
time: Optional[str] # 오늘 남은 구간 중 날씨 점수가 가장 높은 때
place: Optional[str] # 날씨 맞춤 데이트 명소 첫 곳
place_id: Optional[int]
top_gak: Optional[str] # 지금 1위 각
top_icon: Optional[str]
@dataclass
class Today:
day: date
card: Optional[Card]
luck: Optional[Luck]
streak: int
checkin_open: bool # 저녁(해 지기 2시간 전)부터 체크인을 받는다
log: Optional[DayLog] = None
class FortuneService:
def __init__(self, crud: FortuneCRUD = Depends(FortuneCRUD), index: IndexService = Depends(IndexService), week: WeekService = Depends(WeekService)) -> None:
self.crud, self.index, self.week = crud, index, week
async def _card(self, code: str) -> Optional[Card]:
if code not in DECK:
return None
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
d = next((d for d in defs or [] if d.code == code), None)
if err is not ErrorType.SUCCESS or d is None:
return None
c = DECK[code]
return Card(code=code, name=d.name, icon=d.icon, reading=c["reading"], color=c["color"], hex=c["hex"])
async def _luck(self, region_code: str) -> tuple[ErrorType, Optional[Luck], bool]:
err, board = await self.index.board(region_code)
if err is not ErrorType.SUCCESS or board is None:
return err, None, False
now = now_kst()
sunset_at = sun_times(board.day, float(board.region.lat), float(board.region.lon)).sunset_at
cur = current_slot(now, sunset_at)
left = SLOTS[SLOTS.index(shown_slot(cur)):]
best = max((k for k in left if k in board.weather_slots), key=lambda k: board.weather_slots[k], default=None)
_, places, _, _ = await self.week.places(region_code, board.day, None)
place = next((p for p in places if p.is_good), places[0] if places else None)
top = board.ranked[0].definition if board.ranked else None
luck = Luck(
time=hours_text(slot_hours(board.day, sunset_at)[best]) if best else None,
place=place.place.name if place else None, place_id=place.place.place_id if place else None,
top_gak=top.name if top else None, top_icon=top.icon if top else None,
)
return ErrorType.SUCCESS, luck, cur in ("evening", "night")
async def _streak(self, user: User, today: date) -> tuple[ErrorType, int]:
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_days(s, user.user_id, today - timedelta(days=HISTORY_DAYS)))
return err, streak(set(days or []), today)
async def today(self, region_code: str, user: Optional[User]) -> tuple[ErrorType, Optional[Today]]:
"""로그인했으면 오늘 뽑은 카드·체크인·연속 기록. 안 뽑았으면 카드 없이"""
today = now_kst().date()
if user is None:
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=0, checkin_open=False)
err, row = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
err, n = await self._streak(user, today)
if err is not ErrorType.SUCCESS:
return err, None
if row is None:
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=n, checkin_open=False)
err, luck, open_ = await self._luck(region_code)
if err is not ErrorType.SUCCESS:
return err, None
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
return ErrorType.SUCCESS, Today(day=today, card=await self._card(row.card_code), luck=luck, streak=n, checkin_open=open_, log=log)
async def draw(self, region_code: str, user: Optional[User], card_code: Optional[str], days: list[date]) -> tuple[ErrorType, Optional[Today]]:
"""하루 한 장. 로그인했으면 그날 처음 뽑은 카드, 안 했으면 기기에 있는 오늘 카드(없으면 새로 뽑음)와 기기에 남은 뽑은 날로 연속 기록."""
today = now_kst().date()
fresh = random.choice(list(DECK))
if user is not None:
err, row = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_draw(s, user.user_id, today, fresh))
if err is not ErrorType.SUCCESS or row is None:
return err, None
code = row.card_code
err, n = await self._streak(user, today)
if err is not ErrorType.SUCCESS:
return err, None
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
else:
code = card_code if card_code in DECK else fresh
n, log = streak({d for d in days if today - timedelta(days=HISTORY_DAYS) <= d < today} | {today}, today), None
card = await self._card(code)
if card is None:
return ErrorType.DB_ERROR, None
err, luck, open_ = await self._luck(region_code)
if err is not ErrorType.SUCCESS:
return err, None
return ErrorType.SUCCESS, Today(day=today, card=card, luck=luck, streak=n, checkin_open=open_, log=log)
async def save_log(self, user: User, region_code: str, mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool]) -> tuple[ErrorType, Optional[DayLog]]:
values = clean_log(mood, went_out, place_name, place_ref, card_hit, region_code)
if values is None:
return ErrorType.INVALID_INPUT, None
today = now_kst().date()
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.save_log(s, user.user_id, today, values))
async def import_local(self, user: User, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> ErrorType:
"""로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로. 최근 60일, 덱에 있는 카드, 형식이 맞는 체크인만"""
today = now_kst().date()
since = today - timedelta(days=HISTORY_DAYS)
ok_draws = [(d, c) for d, c in draws if since <= d <= today and c in DECK]
ok_logs = [(d, v) for d, raw in logs if since <= d <= today and (v := clean_log(**raw)) is not None]
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.import_rows(s, user.user_id, ok_draws, ok_logs))
return err
async def places(self, region_code: str, q: str) -> tuple[ErrorType, list[tuple[str, str]]]:
q = " ".join(q.split())
if not q:
return ErrorType.SUCCESS, []
today = now_kst().date()
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.search_places(s, q, region_code[:2], today, PLACE_LIMIT))
def clean_log(mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool], region_code: str) -> Optional[dict]:
"""체크인 값 확인. 안 나갔으면 다녀온 곳은 비운다"""
if not 1 <= mood <= 5 or not region_code:
return None
name = " ".join((place_name or "").split())[:40] or None
if place_ref is not None and not _PLACE_REF.match(place_ref):
return None
if not went_out:
name, place_ref = None, None
return {"mood": mood, "went_out": went_out, "place_name": name, "place_ref": place_ref if name else None, "card_hit": card_hit, "region_code": region_code[:10]}
+128
View File
@@ -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"] == []
+2
View File
@@ -50,6 +50,8 @@ 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` |
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
- 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다.
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+2
View File
@@ -23,6 +23,7 @@ import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
import { TodayCard } from './fortune'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
@@ -638,6 +639,7 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<TodayCard />
<ShortsRail />
<FeedComposer />
{mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
+20
View File
@@ -708,3 +708,23 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .b-tab-main > span {
--tw-ring-color: rgb(18 24 60 / 0.9);
}
/* 오늘 한 장: 뽑은 카드가 뒤집히며 나온다 */
.b-card-flip {
animation: b-card-flip 0.55s cubic-bezier(0.2, 0.8, 0.3, 1);
}
@keyframes b-card-flip {
0% {
opacity: 0.4;
transform: perspective(600px) rotateY(90deg);
}
100% {
opacity: 1;
transform: perspective(600px) rotateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.b-card-flip {
animation: none;
}
}
+336
View File
@@ -0,0 +1,336 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { getFortuneTodayOptions, getFortuneTodayQueryKey, importFortuneMutation, searchFortunePlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { drawFortune, saveDayLog } from '@nalssigak/shared/api/client/sdk.gen'
import type { DayLogData, LocalDraw, LocalLog, ResFortuneToday } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Sec } from './ui'
const KEY = 'nalssigak.b.fortune'
// 기기에 남기는 날 수 (서버도 이 안쪽만 받는다)
const KEEP_DAYS = 60
const MOODS = ['😆', '🙂', '😐', '😕', '😢']
const STAMPS = 7
/** 로그인하지 않았을 때 이 기기에 남기는 뽑은 카드·체크인 */
type Local = { draws: LocalDraw[]; logs: LocalLog[] }
const EMPTY: Local = { draws: [], logs: [] }
function readLocal(): Local {
try {
const raw = localStorage.getItem(KEY)
return raw ? { ...EMPTY, ...(JSON.parse(raw) as Local) } : EMPTY
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return EMPTY
}
}
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(next: Local) {
const recent = <T extends { day: string }>(rows: T[]) => [...rows].sort((a, b) => b.day.localeCompare(a.day)).slice(0, KEEP_DAYS)
local = { draws: recent(next.draws), logs: recent(next.logs) }
listeners.forEach((cb) => cb())
try {
if (local.draws.length || local.logs.length) localStorage.setItem(KEY, JSON.stringify(local))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[fortune] 기기에 저장하지 못함', e)
}
}
const pad = (n: number) => String(n).padStart(2, '0')
function todayKst() {
const t = kst(new Date())
return `${t.y}-${pad(t.mo)}-${pad(t.d)}`
}
async function draw(regionCode: string, cardCode?: string, days: string[] = []): Promise<ResFortuneToday> {
const { data } = await drawFortune({ body: { region_code: regionCode, card_code: cardCode, days } })
if (!data.result?.success || !data.card) throw new Error(data.result?.desc ?? 'draw')
return data
}
/** 오늘 카드·행운·체크인. 로그인했으면 서버, 아니면 이 기기에 있는 오늘 카드로 행운만 서버에서 받는다 */
function useTodayCard() {
const { loggedIn } = useAuth()
const { region } = useRegion()
const queryClient = useQueryClient()
const saved = useSyncExternalStore(subscribe, () => local)
const day = todayKst()
const mine = saved.draws.find((d) => d.day === day)
const pastDays = saved.draws.filter((d) => d.day < day).map((d) => d.day)
const serverKey = getFortuneTodayQueryKey({ query: { region: region.code } })
const deviceKey = ['fortuneDevice', region.code, mine?.card_code, day]
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
const device = useQuery({
queryKey: deviceKey,
enabled: !loggedIn && !!mine,
staleTime: 5 * 60_000,
queryFn: () => draw(region.code, mine?.card_code, pastDays),
})
const pick = useMutation({
mutationFn: () => draw(region.code, undefined, loggedIn ? [] : pastDays),
onSuccess: (data) => {
track('fortune_draw', { card: data.card!.code })
if (loggedIn) {
queryClient.setQueryData(serverKey, data)
return
}
setLocal({ ...local, draws: [...local.draws.filter((d) => d.day !== data.day), { day: data.day!, card_code: data.card!.code }] })
queryClient.setQueryData(['fortuneDevice', region.code, data.card!.code, data.day], data)
},
})
// 로그인하면 이 기기에 있던 기록을 계정으로 옮긴다
const { mutate: moveUp } = useMutation({ ...importFortuneMutation() })
useEffect(() => {
if (!loggedIn || (!saved.draws.length && !saved.logs.length)) return
moveUp(
{ body: { draws: saved.draws, logs: saved.logs } },
{
onSuccess: (res) => {
if (!res.result?.success) return
setLocal(EMPTY)
queryClient.invalidateQueries({ queryKey: serverKey })
},
},
)
}, [loggedIn, saved, moveUp, queryClient, serverKey])
const today = loggedIn ? server.data : device.data
const log: DayLogData | LocalLog | undefined = (loggedIn ? today?.log : saved.logs.find((g) => g.day === day)) ?? undefined
const saveLog = useMutation({
mutationFn: async (v: Omit<LocalLog, 'day' | 'region_code'>) => {
const body = { ...v, region_code: region.code }
if (!loggedIn) {
setLocal({ ...local, logs: [...local.logs.filter((g) => g.day !== day), { ...body, day }] })
return
}
const { data } = await saveDayLog({ body })
if (!data.result?.success || !data.log) throw new Error(data.result?.desc ?? 'log')
queryClient.setQueryData(serverKey, (old: ResFortuneToday | undefined) => (old ? { ...old, log: data.log } : old))
},
onSuccess: (_, v) => track('day_log', { mood: v.mood, went_out: v.went_out, card_hit: v.card_hit ?? null }),
})
const loading = loggedIn ? server.isPending : !!mine && device.isPending
return { today, log, loading, pick, saveLog, loggedIn }
}
/** 오늘 탭 '오늘 한 장': 하루 한 장 뽑는 날씨 카드, 실제 날씨로 정한 행운, 연속 도장, 저녁엔 체크인 */
export function TodayCard() {
const { today, log, loading, pick, saveLog, loggedIn } = useTodayCard()
const { open } = useSheet()
const shot = useRef<HTMLDivElement>(null)
const card = today?.card
const luck = today?.luck
const streak = today?.streak ?? 0
const filled = streak > 0 ? ((streak - 1) % STAMPS) + 1 : 0
const share = () => {
if (card && shot.current) open({ type: 'share', share: { title: `오늘 내 날씨 카드는 ${card.name}`, slides: [shot.current] } })
}
return (
<>
<Sec title="오늘 한 장" />
<div className="mx-4 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
{!card ? (
<button
type="button"
onClick={() => pick.mutate()}
disabled={loading || pick.isPending}
className="mx-auto flex w-full cursor-pointer flex-col items-center gap-2"
>
<img src="/fortune/back.webp" alt="" className={cx('aspect-[2/3] w-[150px] rounded-2xl object-cover', (loading || pick.isPending) && 'animate-pulse')} />
<span className="font-jua text-[16px] text-(--orange)">눌러서 오늘 카드 뽑기</span>
</button>
) : (
<div ref={shot} className="b-card-flip rounded-2xl bg-white">
<div className="flex gap-3">
<img src={`/fortune/${card.code}.webp`} alt={card.name} className="aspect-[2/3] w-[112px] shrink-0 rounded-xl object-cover" />
<div className="flex min-w-0 flex-col justify-center gap-1.5">
<b className="font-jua text-[22px] leading-tight font-normal">{card.name}</b>
<p className="m-0 text-[14px] leading-snug font-semibold text-(--ink2)">{card.reading}</p>
</div>
</div>
{luck && (
<dl className="m-0 mt-3 grid grid-cols-2 gap-1.5">
<Luck label="행운 시간" value={luck.time} sub="날씨가 가장 좋은 때" />
<Luck label="행운 장소" value={luck.place} />
<Luck label="행운 색" value={card.color} swatch={card.hex} />
<Luck label="오늘 1위" value={luck.top_gak} icon={luck.top_icon} />
</dl>
)}
<p className="m-0 mt-2 text-center text-[11px] font-semibold text-(--ink3)">재미로 보는 날씨 운세</p>
</div>
)}
{(streak > 0 || card) && (
<div className="mt-2.5 flex items-center gap-1.5">
{streak > 0 && (
<>
<span className="flex gap-1" aria-hidden>
{Array.from({ length: STAMPS }, (_, i) => (
<i key={i} className={cx('grid size-[18px] place-items-center rounded-full text-[10px] not-italic', i < filled ? 'bg-(--orange) text-white' : 'bg-[#ffe2cf]')}>
{i < filled ? '✓' : ''}
</i>
))}
</span>
<span className="text-xs font-bold text-(--ink2)">{streak}일째</span>
</>
)}
{card && (
<button type="button" onClick={share} className="ml-auto cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-extrabold text-white">
공유
</button>
)}
</div>
)}
{card && today?.checkin_open && <CheckIn log={log} saving={saveLog.isPending} onSave={(v) => saveLog.mutate(v)} anon={!loggedIn} />}
</div>
</>
)
}
function Luck({ label, value, sub, swatch, icon }: { label: string; value?: string | null; sub?: string; swatch?: string; icon?: string | null }) {
if (!value) return null
return (
<div className="rounded-xl bg-[#fff6ef] px-2.5 py-2">
<dt className="text-[11px] font-bold text-(--ink3)">{label}</dt>
<dd className="m-0 flex items-center gap-1 text-[14px] leading-tight font-extrabold">
{swatch && <span aria-hidden className="size-3 shrink-0 rounded-[4px] border border-black/10" style={{ background: swatch }} />}
{icon && <Ic name={icon} className="size-5 shrink-0" />}
<span className="truncate">{value}</span>
</dd>
{sub && <p className="m-0 text-[10.5px] font-semibold text-(--ink3)">{sub}</p>}
</div>
)
}
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<string | null>(log?.place_ref ?? null)
const [stayed, setStayed] = useState(log ? !log.went_out : false)
const [hit, setHit] = useState<boolean | null>(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 (
<button type="button" onClick={() => setEditing(true)} className="mt-3 flex w-full cursor-pointer items-center gap-2 rounded-xl bg-[#f3f6fb] px-3 py-2.5 text-left">
<span className="text-[22px] leading-none">{MOODS[log.mood - 1]}</span>
<span className="min-w-0 flex-1">
<b className="block text-[13.5px] font-extrabold">오늘 하루를 적어 뒀어요</b>
{log.place_name && <span className="block truncate text-xs font-semibold text-(--ink2)">{log.place_name}</span>}
</span>
</button>
)
}
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 (
<div className="mt-3 border-t border-(--line) pt-3">
<p className="m-0 font-jua text-[17px]">오늘 하루 어땠어요?</p>
<div className="mt-2 flex justify-between">
{MOODS.map((m, i) => (
<button key={m} type="button" onClick={() => setMood(i + 1)} aria-pressed={mood === i + 1} className={cx('grid size-11 cursor-pointer place-items-center rounded-full text-[24px]', mood === i + 1 ? 'bg-[#ffe2cf] ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}>
{m}
</button>
))}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">어디 다녀왔어요?</p>
<div className="relative mt-1.5 flex gap-1.5">
<input
value={place}
onChange={(e) => {
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"
/>
<button
type="button"
onClick={() => {
setStayed(!stayed)
setPlace('')
setRef(null)
}}
aria-pressed={stayed}
className={chip(stayed)}
>
안 나갔어요
</button>
{!stayed && !ref && (found.data?.length ?? 0) > 0 && (
<ul className="absolute top-full right-0 left-0 z-10 m-0 mt-1 max-h-48 list-none overflow-auto rounded-xl border border-(--line) bg-white p-1 shadow-lg">
{found.data!.map((p) => (
<li key={p.ref}>
<button
type="button"
onClick={() => {
setPlace(p.name)
setRef(p.ref)
}}
className="w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-[14px] font-semibold hover:bg-[#f3f6fb]"
>
{p.name}
</button>
</li>
))}
</ul>
)}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">오늘 카드, 맞았어요?</p>
<div className="mt-1.5 flex gap-1.5">
<button type="button" onClick={() => setHit(hit === true ? null : true)} aria-pressed={hit === true} className={chip(hit === true)}>
맞았어요
</button>
<button type="button" onClick={() => setHit(hit === false ? null : false)} aria-pressed={hit === false} className={chip(hit === false)}>
글쎄요
</button>
</div>
<button type="button" onClick={save} disabled={!ready || saving} className="mt-3.5 w-full cursor-pointer rounded-full bg-(--orange) py-2.5 text-[14px] font-extrabold text-white disabled:opacity-40">
적어 두기
</button>
{anon && <p className="m-0 mt-2 text-center text-[11.5px] font-semibold text-(--ink3)">이 기기에만 남아요. 로그인하면 폰을 바꿔도 남아요.</p>}
</div>
)
}
+2
View File
@@ -28,6 +28,8 @@ type Events = {
foliage_open: Record<string, never>
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 }
toss_intro_start: Record<string, never>
install_banner_close: Record<string, never>
}
+89 -2
View File
@@ -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, 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, 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, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, 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, 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, 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, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, 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<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -968,6 +968,93 @@ export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>)
return mutationOptions;
};
export const getFortuneTodayQueryKey = (options: Options<GetFortuneTodayData>) => createQueryKey('getFortuneToday', options);
/**
* 오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이)
*/
export const getFortuneTodayOptions = (options: Options<GetFortuneTodayData>) => queryOptions<GetFortuneTodayResponse, GetFortuneTodayError, GetFortuneTodayResponse, ReturnType<typeof getFortuneTodayQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getFortuneToday({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getFortuneTodayQueryKey(options)
});
/**
* 오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산
*/
export const drawFortuneMutation = (options?: Partial<Options<DrawFortuneData>>): UseMutationOptions<DrawFortuneResponse, DrawFortuneError, Options<DrawFortuneData>> => {
const mutationOptions: UseMutationOptions<DrawFortuneResponse, DrawFortuneError, Options<DrawFortuneData>> = {
mutationFn: async (fnOptions) => {
const { data } = await drawFortune({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다
*/
export const saveDayLogMutation = (options?: Partial<Options<SaveDayLogData>>): UseMutationOptions<SaveDayLogResponse, SaveDayLogError, Options<SaveDayLogData>> => {
const mutationOptions: UseMutationOptions<SaveDayLogResponse, SaveDayLogError, Options<SaveDayLogData>> = {
mutationFn: async (fnOptions) => {
const { data } = await saveDayLog({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다)
*/
export const importFortuneMutation = (options?: Partial<Options<ImportFortuneData>>): UseMutationOptions<ImportFortuneResponse, ImportFortuneError, Options<ImportFortuneData>> => {
const mutationOptions: UseMutationOptions<ImportFortuneResponse, ImportFortuneError, Options<ImportFortuneData>> = {
mutationFn: async (fnOptions) => {
const { data } = await importFortune({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const searchFortunePlacesQueryKey = (options: Options<SearchFortunePlacesData>) => createQueryKey('searchFortunePlaces', options);
/**
* 체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사
*/
export const searchFortunePlacesOptions = (options: Options<SearchFortunePlacesData>) => queryOptions<SearchFortunePlacesResponse, SearchFortunePlacesError, SearchFortunePlacesResponse, ReturnType<typeof searchFortunePlacesQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await searchFortunePlaces({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: searchFortunePlacesQueryKey(options)
});
export const talkGroupsQueryKey = (options?: Options<TalkGroupsData>) => createQueryKey('talkGroups', options);
/**
+2 -2
View File
@@ -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,Line truncated
export { addComment, addMyGak, addTalk, agreeTerms, 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, 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, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, 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 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 LikeCommentData, type LikeCommentError, type LikeCommentErLine truncated
+47 -1
View File
@@ -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, 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, 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, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, 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<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -335,6 +335,52 @@ export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options
*/
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
/**
* 오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이)
*/
export const getFortuneToday = <ThrowOnError extends boolean = true>(options: Options<GetFortuneTodayData, ThrowOnError>): RequestResult<GetFortuneTodayResponses, GetFortuneTodayErrors, ThrowOnError> => (options.client ?? client).get<GetFortuneTodayResponses, GetFortuneTodayErrors, ThrowOnError>({ url: '/v1/fortune/today', ...options });
/**
* 오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산
*/
export const drawFortune = <ThrowOnError extends boolean = true>(options: Options<DrawFortuneData, ThrowOnError>): RequestResult<DrawFortuneResponses, DrawFortuneErrors, ThrowOnError> => (options.client ?? client).post<DrawFortuneResponses, DrawFortuneErrors, ThrowOnError>({
url: '/v1/fortune/draw',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다
*/
export const saveDayLog = <ThrowOnError extends boolean = true>(options: Options<SaveDayLogData, ThrowOnError>): RequestResult<SaveDayLogResponses, SaveDayLogErrors, ThrowOnError> => (options.client ?? client).put<SaveDayLogResponses, SaveDayLogErrors, ThrowOnError>({
url: '/v1/fortune/log',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다)
*/
export const importFortune = <ThrowOnError extends boolean = true>(options: Options<ImportFortuneData, ThrowOnError>): RequestResult<ImportFortuneResponses, ImportFortuneErrors, ThrowOnError> => (options.client ?? client).post<ImportFortuneResponses, ImportFortuneErrors, ThrowOnError>({
url: '/v1/fortune/import',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사
*/
export const searchFortunePlaces = <ThrowOnError extends boolean = true>(options: Options<SearchFortunePlacesData, ThrowOnError>): RequestResult<SearchFortunePlacesResponses, SearchFortunePlacesErrors, ThrowOnError> => (options.client ?? client).get<SearchFortunePlacesResponses, SearchFortunePlacesErrors, ThrowOnError>({ url: '/v1/fortune/places', ...options });
/**
* 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)
*/
+462
View File
@@ -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:<id> · spot:<id> · event:<id>
*/
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/<code>.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:<id> · spot:<id> · event:<id>
*/
ref: string;
/**
* Name
*/
name: string;
};
/**
* GakSlide
*/
@@ -993,6 +1115,54 @@ export type IndexSummary = {
slots?: Array<SlotPoint>;
};
/**
* 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 +1861,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<string>;
};
/**
* Req_FortuneImport
*/
export type ReqFortuneImport = {
/**
* Draws
*/
draws?: Array<LocalDraw>;
/**
* Logs
*/
logs?: Array<LocalLog>;
};
/**
* Req_Google
*/
@@ -2080,6 +2316,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 +2381,57 @@ export type ResFeed = {
bands?: Bands | null;
};
/**
* Res_FortunePlaces
*/
export type ResFortunePlaces = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Items
*/
items?: Array<FortunePlace>;
};
/**
* 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
*/
@@ -5552,6 +5851,169 @@ 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 TalkGroupsData = {
body?: never;
headers?: {