feat: 구름 합치기 GA4 이벤트 — game_start(첫 그림)·game_round(라운드 깸)·game_over(넘침)

This commit is contained in:
minaChoi committed 2026-10-29 09:04:11 +09:00
1 parent 63b4fa74fe
commit df3fba720c
26 files changed
+330 -900

No files matched your search

+2 -1
View File
@@ -14,9 +14,10 @@ INSTAGRAM_USER_ID=
PUBLIC_BASE_URL=https://weather.o2o.kr PUBLIC_BASE_URL=https://weather.o2o.kr
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
# 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용). # 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용).
# 비우면 채널 쇼츠 RSS(키 없음, 최신 15개)로 받는다 # 비우면 채널 쇼츠를 자동으로 못 받고 YOUTUBE_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개)
YOUTUBE_API_KEY= YOUTUBE_API_KEY=
YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w
YOUTUBE_SHORTS=
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다) # ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost DB_HOST=localhost
+1 -2
View File
@@ -59,7 +59,7 @@
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` | | [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | | | [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | | | [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
| [x] | 오늘 화면 쇼츠 줄 — 영상 ID 고정 목록(`youtube_shorts`) 없앰. API 키가 없으면 채널 쇼츠 RSS(`UUSH…` 재생목록, 키 없음)로 자동으로 받음. 키(`YOUTUBE_API_KEY`)를 운영 .env 에 넣으면 Data API 로 바뀌어 퍼가기·길이까지 거름 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 10/28 운영에 키가 없어 고정 목록만 나와 새 쇼츠가 안 붙음. 채널 RSS가 다시 200 | `backend/services/external/youtube.py`, `backend/services/shorts_service.py` | | [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` | | [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` | | [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` | | [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` |
@@ -98,7 +98,6 @@
| [ ] | 계정 레벨 — main 병합(10/28, 배포 남음). 사용자 결정 10/28: **레벨 제도**(포인트 소비형 아님). 단위는 '각'(출석 +10각 등 서비스 전체 행동으로 적립), 레벨은 모은 총량 기준이라 나중에 각을 쓰는 기능을 붙여도 안 내려감. 지금 있는 기능·캐릭터·색·기분은 잠그지 않고, 새로 생기는 것(날씨 사주 연애운·궁합 등, 새 캐릭터·테두리, 댓글 레벨 배지)만 레벨로 열림. 내 정보는 기존 화면에 레벨·각만 더함. 정할 것: 레벨 이름·단계·필요 각, 행동별 각·하루 한도, 해금 목록 | 기획서 '계정 레벨(각)·날씨 사주 UI 기획'(10/28 채팅 첨부) | `frontend/src/b/Sheets.tsx` `MeSheet` | | [ ] | 계정 레벨 — main 병합(10/28, 배포 남음). 사용자 결정 10/28: **레벨 제도**(포인트 소비형 아님). 단위는 '각'(출석 +10각 등 서비스 전체 행동으로 적립), 레벨은 모은 총량 기준이라 나중에 각을 쓰는 기능을 붙여도 안 내려감. 지금 있는 기능·캐릭터·색·기분은 잠그지 않고, 새로 생기는 것(날씨 사주 연애운·궁합 등, 새 캐릭터·테두리, 댓글 레벨 배지)만 레벨로 열림. 내 정보는 기존 화면에 레벨·각만 더함. 정할 것: 레벨 이름·단계·필요 각, 행동별 각·하루 한도, 해금 목록 | 기획서 '계정 레벨(각)·날씨 사주 UI 기획'(10/28 채팅 첨부) | `frontend/src/b/Sheets.tsx` `MeSheet` |
| [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(10/28 "니 알아서 하라"), 바꿀 수 있게 기록: 날씨 접목은 조후(한난조습) · 연애운은 열 때 성별 선택 입력(남/여/선택 안 함, 안 하면 도화·배우자궁만으로 본다고 표시) · 도화는 연지·일지 삼합 둘 다 · 홍염은 일간표(甲乙午 丙寅 丁未 戊己辰 庚戌 辛酉 壬子 癸申, 이견 있음 표시) · 합충형파해원진은 원국 네 지지 모두, 일지에 걸리면 연애 가중 · 절입 시각은 천문 계산식으로 1900~2100 표를 만들고 천문연 값으로 검증(패키지 안 씀) · 진태양시(출생지 경도)·서머타임 반영, 자시는 자정 기준(설정으로 변경) · 음력은 다음 단계(천문연 API) | 사용자 위임 10/28 | | | [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(10/28 "니 알아서 하라"), 바꿀 수 있게 기록: 날씨 접목은 조후(한난조습) · 연애운은 열 때 성별 선택 입력(남/여/선택 안 함, 안 하면 도화·배우자궁만으로 본다고 표시) · 도화는 연지·일지 삼합 둘 다 · 홍염은 일간표(甲乙午 丙寅 丁未 戊己辰 庚戌 辛酉 壬子 癸申, 이견 있음 표시) · 합충형파해원진은 원국 네 지지 모두, 일지에 걸리면 연애 가중 · 절입 시각은 천문 계산식으로 1900~2100 표를 만들고 천문연 값으로 검증(패키지 안 씀) · 진태양시(출생지 경도)·서머타임 반영, 자시는 자정 기준(설정으로 변경) · 음력은 다음 단계(천문연 API) | 사용자 위임 10/28 | |
| [ ] | **[결정 필요]** 날씨 사주 화면·문구 — '내 기운'(계절·날씨 장면 16종), 점수 → 사주 풀이 → 계절·날씨 한 스푼, 하루 풀이를 '오늘의 결정 카드'(언제·미룰 것·입을 것/갈 곳·이번 주 날짜)로 줄지, 규칙별 의미 사전·문구 검토, 기운 장면 그림 | 사용자 피드백 10/28 | 기획서 '날씨 사주 기획 v2', '계정 레벨·날씨 사주 UI 기획' | | [ ] | **[결정 필요]** 날씨 사주 화면·문구 — '내 기운'(계절·날씨 장면 16종), 점수 → 사주 풀이 → 계절·날씨 한 스푼, 하루 풀이를 '오늘의 결정 카드'(언제·미룰 것·입을 것/갈 곳·이번 주 날짜)로 줄지, 규칙별 의미 사전·문구 검토, 기운 장면 그림 | 사용자 피드백 10/28 | 기획서 '날씨 사주 기획 v2', '계정 레벨·날씨 사주 UI 기획' |
| [ ] | **[결정 필요]** 날씨 사주 Codex 검수(10/28) 중 반영 안 한 것: ① 금전·일 날짜 추천("큰돈 쓰거나 계약할 일은 10/31(토)") — Codex는 운세로 계약·면접 날짜를 정해 주지 말고 점검 행동만 주라고 했으나, 사주 앱 장르상 날짜가 핵심이라 유지하고 그날 점수 60 이상일 때만 고르게 함 ② 점수를 '참고 점수'로 부를지 ③ 결과 위에 출생 정보 요약·칸 이동 메뉴, 사주 글자 표 접기 ④ 11월부터 올해 운 자리에 내년 미리 보기 — 올해·내년을 따로 고르게 할지 ⑤ 연애운 성별 기준(남 재성·여 관성)을 '전통 기준'이라고 더 밝힐지 | Codex 검수 `/tmp/sweep/codex-review.md` | `backend/services/saju_service.py`, `frontend/src/b/SajuPage.tsx` |
## 진행 순서 ## 진행 순서
+2 -6
View File
@@ -1,9 +1,9 @@
import uuid import uuid
from datetime import date, datetime, time from datetime import date, datetime
from decimal import Decimal from decimal import Decimal
from typing import Optional from typing import Optional
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, Time, func from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, func
from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -364,10 +364,6 @@ class User(Base):
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
token_version: Mapped[int] = mapped_column(SmallInteger, default=1) token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
points: Mapped[int] = mapped_column(Integer, default=0) points: Mapped[int] = mapped_column(Integer, default=0)
birth_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
birth_time: Mapped[Optional[time]] = mapped_column(Time, nullable=True)
birth_place: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
gender: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
deleted: Mapped[bool] = mapped_column(Boolean, default=False) deleted: Mapped[bool] = mapped_column(Boolean, default=False)
+2 -1
View File
@@ -51,9 +51,10 @@ class Settings(BaseSettings):
azure_blob_base_url: str = "" azure_blob_base_url: str = ""
azure_blob_sas_token: str = "" azure_blob_sas_token: str = ""
# 오늘 화면 쇼츠 줄. API 키가 있으면 Data API 로(공개·퍼가기 허용·3분 이하), 없으면 채널 쇼츠 RSS 로 받는다 # 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
youtube_api_key: str = "" youtube_api_key: str = ""
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w" youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다 # 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = "" google_client_id: str = ""
-5
View File
@@ -330,11 +330,6 @@ CREATE TABLE IF NOT EXISTS public.point_log (
); );
CREATE UNIQUE INDEX IF NOT EXISTS uq_point_log ON public.point_log (user_id, day, action, ref); CREATE UNIQUE INDEX IF NOT EXISTS uq_point_log ON public.point_log (user_id, day, action, ref);
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS points INTEGER NOT NULL DEFAULT 0; -- 모은 각 총량 (point_log 합) ALTER TABLE public.users ADD COLUMN IF NOT EXISTS points INTEGER NOT NULL DEFAULT 0; -- 모은 각 총량 (point_log 합)
-- 날씨 사주에 넣은 생년월일. 로그인한 사람만, 저장하면 어느 기기에서든 바로 본다. 탈퇴하면 계정과 함께 지워진다
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_date DATE NULL;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_time TIME NULL; -- 모르면 NULL
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_place VARCHAR(20) NULL; -- 태어난 곳 키 (frontend sajuBirth.ts BIRTH_PLACES)
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS gender VARCHAR(10) NULL; -- male·female. 연애운에서 이성 인연을 볼 때만 쓴다
-- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다) -- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다)
CREATE TABLE IF NOT EXISTS public.fortune_draw ( CREATE TABLE IF NOT EXISTS public.fortune_draw (
-15
View File
@@ -14,21 +14,6 @@ class Req_Saju(Req_WebPacketProtocol):
gender: Optional[Literal["male", "female"]] = Field(None, description="연애운에서 이성 기운을 볼 때만") gender: Optional[Literal["male", "female"]] = Field(None, description="연애운에서 이성 기운을 볼 때만")
class SajuSavedBirth(WebPacketProtocol):
birth_date: date
birth_time: Optional[str] = Field(None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$", description="HH:MM (모르면 없음)")
place: Optional[str] = Field(None, pattern=r"^[a-z]{2,20}$", description="태어난 곳 키 (seoul 등)")
gender: Optional[Literal["male", "female"]] = None
class Req_SajuBirth(Req_WebPacketProtocol, SajuSavedBirth):
pass
class Res_SajuBirth(Res_WebPacketProtocol):
birth: Optional[SajuSavedBirth] = None
class SajuPillar(WebPacketProtocol): class SajuPillar(WebPacketProtocol):
position: str = Field(description="year·month·day·hour") position: str = Field(description="year·month·day·hour")
stem: str stem: str
+2 -27
View File
@@ -3,11 +3,11 @@ from typing import Optional
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from common.auth import current_user, optional_user from common.auth import optional_user
from common.database.model.models import User from common.database.model.models import User
from common.enums import ErrorType from common.enums import ErrorType
from common.models.errors import error_info from common.models.errors import error_info
from router.v1.saju.protocol import Req_Saju, Req_SajuBirth, Req_SajuMatch, Res_Saju, Res_SajuBirth, SajuSavedBirth, Res_SajuMatch, SajuBirth, SajuCard, SajuDay, SajuLock, SajuLove, SajuLoveDay, SajuMe, SajuPeriod, SajuPillar, SajuToday from router.v1.saju.protocol import Req_Saju, Req_SajuMatch, Res_Saju, Res_SajuMatch, SajuBirth, SajuCard, SajuDay, SajuLock, SajuLove, SajuLoveDay, SajuMe, SajuPeriod, SajuPillar, SajuToday
from services import saju_text as T from services import saju_text as T
from services.level_service import UNLOCKS from services.level_service import UNLOCKS
from services.saju.ganji import branch_element, ko, stem_element from services.saju.ganji import branch_element, ko, stem_element
@@ -55,31 +55,6 @@ async def reading(req: Req_Saju, user: Optional[User] = Depends(optional_user),
return Res_Saju(result=error_info(err)) if err is not ErrorType.SUCCESS or r is None else _res(r) return Res_Saju(result=error_info(err)) if err is not ErrorType.SUCCESS or r is None else _res(r)
def _saved(u: Optional[User]) -> Res_SajuBirth:
if u is None or u.birth_date is None:
return Res_SajuBirth()
t = f"{u.birth_time:%H:%M}" if u.birth_time else None
return Res_SajuBirth(birth=SajuSavedBirth(birth_date=u.birth_date, birth_time=t, place=u.birth_place, gender=u.gender))
@router.get("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="계정에 저장한 내 생년월일 (없으면 birth 없음)")
async def get_birth(user: User = Depends(current_user)) -> Res_SajuBirth:
return _saved(user)
@router.put("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)")
async def put_birth(req: Req_SajuBirth, user: User = Depends(current_user), service: SajuService = Depends()) -> Res_SajuBirth:
t = time(*map(int, req.birth_time.split(":"))) if req.birth_time else None
err, u = await service.save_birth(user, req.birth_date, t, req.place, req.gender)
return Res_SajuBirth(result=error_info(err)) if err is not ErrorType.SUCCESS or u is None else _saved(u)
@router.delete("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="계정에 저장한 내 생년월일 지우기")
async def delete_birth(user: User = Depends(current_user), service: SajuService = Depends()) -> Res_SajuBirth:
err, _ = await service.clear_birth(user)
return Res_SajuBirth(result=error_info(err))
def _birth(b: SajuBirth) -> tuple: def _birth(b: SajuBirth) -> tuple:
return b.birth_date, time(*map(int, b.birth_time.split(":"))) if b.birth_time else None, b.longitude return b.birth_date, time(*map(int, b.birth_time.split(":"))) if b.birth_time else None, b.longitude
-19
View File
@@ -1,6 +1,4 @@
import asyncio
import re import re
import xml.etree.ElementTree as ET
from typing import Optional from typing import Optional
import httpx import httpx
@@ -9,9 +7,6 @@ import httpx
API_URL = "https://www.googleapis.com/youtube/v3" API_URL = "https://www.googleapis.com/youtube/v3"
# 키 없이 영상 제목만 받을 때 # 키 없이 영상 제목만 받을 때
OEMBED_URL = "https://www.youtube.com/oembed" OEMBED_URL = "https://www.youtube.com/oembed"
# 키 없이 채널 쇼츠 목록을 받을 때: 채널 ID의 UC 를 UUSH 로 바꾼 재생목록이 그 채널의 쇼츠만 모은 목록이다
FEED_URL = "https://www.youtube.com/feeds/videos.xml"
_NS = {"a": "http://www.w3.org/2005/Atom", "yt": "http://www.youtube.com/xml/schemas/2015"}
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하 SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$") _DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
@@ -58,17 +53,3 @@ async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]
return None return None
res.raise_for_status() res.raise_for_status()
return res.json().get("title") return res.json().get("title")
async def feed_shorts(client: httpx.AsyncClient, channel_id: str, limit: int) -> list[dict]:
"""키 없이 채널의 공개 쇼츠 [{id, title, published}], 최신순. 퍼가기를 막은 영상은 뺀다."""
res = await client.get(FEED_URL, params={"playlist_id": "UUSH" + channel_id.removeprefix("UC")})
res.raise_for_status()
root = ET.fromstring(res.text)
entries = [
{"id": e.findtext("yt:videoId", namespaces=_NS), "title": e.findtext("a:title", namespaces=_NS), "published": e.findtext("a:published", namespaces=_NS)}
for e in root.findall("a:entry", _NS)
]
entries = sorted((e for e in entries if e["id"] and e["title"]), key=lambda e: e["published"] or "", reverse=True)[:limit]
embeddable = await asyncio.gather(*(video_title(client, e["id"]) for e in entries))
return [e for e, ok in zip(entries, embeddable) if ok]
+2 -2
View File
@@ -23,7 +23,7 @@ LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바
ACTIONS: dict[str, tuple[int, int, str]] = { ACTIONS: dict[str, tuple[int, int, str]] = {
"attend": (10, 10, "출석"), "attend": (10, 10, "출석"),
"tarot": (10, 10, "오늘 타로 뽑기"), "tarot": (10, 10, "오늘 타로 뽑기"),
"saju": (10, 10, "날씨 사주 보기"), "saju": (10, 10, "날씨 사주 오늘 기운"),
"react": (5, 10, "좋아요·댓글"), "react": (5, 10, "좋아요·댓글"),
"talk": (20, 20, "동네 이야기 글쓰기"), "talk": (20, 20, "동네 이야기 글쓰기"),
"checkin": (10, 10, "저녁 체크인"), "checkin": (10, 10, "저녁 체크인"),
@@ -40,7 +40,7 @@ STREAK_LOOKBACK = 60
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로) # 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
UNLOCKS: dict[int, list[tuple[str, str]]] = { UNLOCKS: dict[int, list[tuple[str, str]]] = {
2: [("saju_week", "날씨 사주 7일 흐름")], 2: [("saju_week", "날씨 사주 이번 주 흐름")],
3: [("saju_money", "금전운 · 일운")], 3: [("saju_money", "금전운 · 일운")],
4: [("saju_love", "연애운")], 4: [("saju_love", "연애운")],
5: [("saju_match", "궁합")], 5: [("saju_match", "궁합")],
+87 -153
View File
@@ -9,16 +9,15 @@ from common.database.model.models import User, WeatherDaily, WeatherHourly
from common.enums import ErrorType, RainType, Sky from common.enums import ErrorType, RainType, Sky
from common.utils.kma_time import KST, kst_midnight, now_kst from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.user_crud import UserCRUD
from crud.weather_crud import WeatherCRUD from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD from crud.week_crud import WeekCRUD
from services import saju_text as T from services import saju_text as T
from services.level_service import award, level_of, unlock_level from services.level_service import award, level_of, unlock_level
from services.saju.climate import HourWeather, best_window, chart_climate, climate_match from services.saju.climate import HourWeather, chart_climate, climate_match
from services.saju.daily import SCORE_WEIGHTS, DailyFacts, Interaction, daily_facts, interactions, score as pillar_score from services.saju.daily import DailyFacts, daily_facts, interactions, score as pillar_score
from services.saju.ganji import ko, main_stem from services.saju.ganji import branch_element, ko, stem_element
from services.saju.pillars import Chart, Pillar, make_chart from services.saju.pillars import Chart, Pillar, make_chart
from services.saju.rules import WEALTH, branch_relations, stem_relations, ten_god from services.saju.rules import branch_relations, stem_relations, ten_god
from services.weather_service import WeatherService from services.weather_service import WeatherService
from services.week_service import WeekService from services.week_service import WeekService
@@ -28,10 +27,7 @@ WEEK_DAYS = 7
WEATHER_SHARE = 0.6 WEATHER_SHARE = 0.6
SHOW_CENTER, SHOW_SPREAD, SHOW_MIN, SHOW_MAX = 68, 1.2, 25, 98 SHOW_CENTER, SHOW_SPREAD, SHOW_MIN, SHOW_MAX = 68, 1.2, 25, 98
RIVALS = ("비견", "겁재") RIVALS = ("비견", "겁재")
CROWDED = 3 # 일간을 뺀 원국 글자 중 비겁이 이만큼 이상이고 재성이 있으면 비겁 날 돈 조심 (군겁쟁재) CROWDED = 3 # 원국에 비겁이 이만큼 이상이면 비겁 날 돈 조심 (군겁쟁재)
PICK_MIN = 60 # 앞으로 7일 중 '좋은 날'로 고르려면 그날 점수가 이 이상
COMFY_C = (5, 30) # 외출 시간으로 권할 체감 온도 범위 (조후로는 맞아도 너무 춥거나 더운 때는 뺀다)
NOTES_MAX = 2 # 이달·올해 근거 줄 수
_WEEKDAY = "월화수목금토일" _WEEKDAY = "월화수목금토일"
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
@@ -77,8 +73,8 @@ class Reading:
level: int level: int
logged_in: bool logged_in: bool
week: Optional[list[DayReading]] = None week: Optional[list[DayReading]] = None
money: Optional[list[str]] = None money: Optional[str] = None
work: Optional[list[str]] = None work: Optional[str] = None
love: Optional[dict] = None love: Optional[dict] = None
month: Optional[dict] = None month: Optional[dict] = None
year: Optional[dict] = None year: Optional[dict] = None
@@ -157,66 +153,37 @@ def _pillars(chart: Chart) -> dict[str, Pillar]:
def crowded_rivals(chart: Chart) -> bool: def crowded_rivals(chart: Chart) -> bool:
"""일간 말고도 비견·겁재가 많고, 나눠 가질 재성이 원국에 있는지 (지지는 정기로 본다)""" """원국에 비견·겁재(일간 포함)가 많은지"""
me = chart.day.stem me = chart.day.stem
chars = [p.stem for pos, p in _pillars(chart).items() if pos != "day"] + [main_stem(p.branch) for p in _pillars(chart).values()] stems = [p.stem for p in _pillars(chart).values()]
gods = [ten_god(me, c) for c in chars] branches = [p.branch for p in _pillars(chart).values()]
return sum(g in RIVALS for g in gods) >= CROWDED and any(g in WEALTH for g in gods) n = sum(1 for s in stems if ten_god(me, s) in RIVALS) + sum(1 for b in branches if stem_element(me) == branch_element(b))
return n >= CROWDED
def why_words(facts: DailyFacts) -> list[str]: def why_words(facts: DailyFacts) -> list[str]:
"""점수를 가장 크게 움직인 사실 셋을 쉬운 말로, 올렸는지(↑) 내렸는지(↓)""" """점수에 가장 크게 작용한 사실 셋을 사람 말로"""
rels = {(i.relation.kind, i.relation.chars, i.position): i for i in facts.interactions}
out = [] out = []
for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]: for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]:
arrow = "↑" if c.points >= 0 else "↓" place = f"{T.PLACE_WORD[c.position]} 자리와 " if c.position else ""
if c.fact in T.GOD_PLAIN: sign = "+" if c.points >= 0 else "−"
line = f"오늘 들어오는 기운: {T.GOD_PLAIN[c.fact]}({c.fact})" out.append(f"{place}{c.fact}({'·'.join(ko(ch) for ch in c.chars)}) {sign}{abs(round(c.points))}")
elif c.fact == "도화":
line = "사람들 눈에 띄는 날(도화)"
elif c.fact == "홍염":
line = "매력이 드러나는 날(홍염)"
else:
i = rels.get((c.fact, c.chars, c.position))
line = _rel(i) if i else c.fact
out.append(f"{line} {arrow}")
return out return out
def _rel(i: Interaction) -> str: def _rel(i) -> str:
"""'태어난 날과 오늘이 부딪혀요(일지 사·해 충)'. 일간과의 관계는 '나와 오늘이 …'""" return f"{T.PLACE_WORD[i.position]} 자리와 {i.relation.kind}({'·'.join(ko(ch) for ch in i.relation.chars)})"
chars = "·".join(ko(ch) for ch in i.relation.chars)
if i.part == "stem" and i.position == "day":
who, term = "나와", "일간"
else:
positions = i.positions or (i.position,)
who = "·".join(T.PLACE_WORD[p].removeprefix("태어난 ") for p in positions)
who = f"태어난 {who}과" if who[-1] in "날달" else f"태어난 {who}와"
term = "".join(T.PLACE_TERM[p] for p in positions) + ("간" if i.part == "stem" else "지")
return f"{who} 오늘이 {T.REL_WORD[i.relation.kind]}({term} {chars} {i.relation.kind})"
def _weight(i: Interaction) -> float:
"""관계 하나가 점수에 주는 무게 (자리 비중까지)"""
share = 1.0 if i.positions else SCORE_WEIGHTS["position_share"][i.position]
return SCORE_WEIGHTS["relation"][i.relation.kind] * share
def _bad(facts: DailyFacts) -> list[Interaction]:
"""조심할 관계, 점수를 많이 깎는 것부터"""
kinds = {k for k, _ in T.AVOID_TEXT}
return sorted((i for i in facts.interactions if i.relation.kind in kinds), key=_weight)
def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]: def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]:
"""조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계""" """조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계 (나·연인 자리 먼저)"""
lines, subs = [], [] lines, subs = [], []
if facts.stem_ten_god in RIVALS and crowded_rivals(chart): if facts.stem_ten_god in RIVALS and crowded_rivals(chart):
lines.append(T.CROWDED_RIVALS) lines.append(T.CROWDED_RIVALS)
subs.append(T.CROWDED_WHY.format(god=facts.stem_ten_god)) subs.append(f"원국에 같은 기운이 많은 날 {T.josa(facts.stem_ten_god, '이가')} 들어와요")
for i in _bad(facts): bad = sorted((i for i in facts.interactions if i.relation.kind in {k for k, _ in T.AVOID_TEXT}), key=lambda i: 0 if i.position == "day" else 1)
key = (i.relation.kind, i.position if i.part == "branch" else "") for i in bad:
body = T.AVOID_TEXT.get(key) or T.AVOID_TEXT.get((i.relation.kind, "")) body = T.AVOID_TEXT.get((i.relation.kind, i.position)) or T.AVOID_TEXT.get((i.relation.kind, ""))
if body and body not in lines: if body and body not in lines:
lines.append(body) lines.append(body)
subs.append(_rel(i)) subs.append(_rel(i))
@@ -227,24 +194,21 @@ def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]:
def good_card(facts: DailyFacts) -> Optional[Card]: def good_card(facts: DailyFacts) -> Optional[Card]:
"""가장 무거운 합 하나. 같은 자리에 조심할 관계도 있으면 그 자리는 뺀다""" good = sorted((i for i in facts.interactions if i.relation.kind in T.GOOD_RELATIONS), key=lambda i: 0 if i.position == "day" else 1)
bad_at = {i.position for i in _bad(facts)}
good = sorted((i for i in facts.interactions if i.relation.kind in T.GOOD_RELATIONS and i.position not in bad_at), key=lambda i: -_weight(i))
if not good: if not good:
return None return None
i = good[0] i = good[0]
body = T.STEM_GOOD if i.part == "stem" and i.position == "day" else T.GOOD_TEXT[i.position] return Card(kind="good", title="오늘 좋은 흐름", body=T.GOOD_TEXT[i.position], sub=_rel(i))
return Card(kind="good", title="오늘 좋은 흐름", body=body, sub=_rel(i))
def when_card(r: DayReading, needs: list[tuple[str, str]]) -> Optional[Card]: def when_card(r: DayReading) -> Optional[Card]:
if not r.best_hours or r.weather is None: if not r.best_hours or r.weather is None:
return None return None
h = r.best_hours[0] h = r.best_hours[0]
temp, word = r.weather.by_hour.get(h, (None, r.weather.word)) temp, word = r.weather.by_hour.get(h, (None, r.weather.word))
walk = "산책·외출은 이때 하세요." helps = [T.NEED_WORD[(x["axis"], x["need"])] for x in r.reasons if x.get("helps") and (x["axis"], x["need"]) in T.NEED_WORD]
body = f"내 기운엔 {T.need_phrase(needs)}가 좋아요. 오늘 중엔 이때가 가장 알맞아요. {walk}" if needs else f"오늘 중 날씨가 가장 편안한 때예요. {walk}" body = f"내 기운에 필요한 {T.josa('·'.join(helps), '이가')} 가장 많이 오는 때예요. 중요한 일은 이때 하세요." if helps else "오늘 날씨가 내 기운과 가장 무난한 때예요. 중요한 일은 이때 하세요."
sub = f"{T.hour_word(h)} {word} {round(temp)}°" if temp is not None else word sub = f"{word} {round(temp)}°" if temp is not None else word
return Card(kind="when", title=window_text(r.best_hours), body=body, sub=sub) return Card(kind="when", title=window_text(r.best_hours), body=body, sub=sub)
@@ -257,88 +221,80 @@ def wear_card(r: DayReading, needs: list[tuple[str, str]], place: Optional[str])
if r.weather is None: if r.weather is None:
return None return None
feels = min(h.feels_c for h in r.weather.hours) feels = min(h.feels_c for h in r.weather.hours)
body = f"가장 쌀쌀할 때 체감 {round(feels)}°예요. {T.josa(T.clothes(feels), '을를')} 챙기세요." color = T.NEED_COLOR[needs[0]] if needs else None
if needs: body = f"아침저녁 체감 {round(feels)}°라 {T.clothes(feels)}" + (f", 색은 {color} 포인트" if color else "")
body += f"\n포인트 색은 {T.NEED_COLOR[needs[0]]} 해 보세요." return Card(kind="wear", title="입을 것 · 갈 곳", body=body, sub=f"갈 곳: {place}" if place else None)
return Card(kind="wear", title="오늘 입을 옷", body=body, sub=f"오늘 가기 좋은 곳: {place}" if place else None)
def _wet(r: DayReading) -> bool:
return r.weather is not None and r.weather.icon in ("rain", "snow")
def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) -> dict: def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) -> dict:
"""앞으로 7일 중 연애 기운이 좋은 날과 조심할 날. 연인 자리(일지)가 부딪히는 날은 좋은 날에서 빼고, 비·눈 오는 날은 뒤로""" """이번 주 연애 기운이 좋은 날과 조심할 날. 비 오는 날은 좋은 날에서 뒤로"""
goods, bads = [], [] goods, bads = [], []
for r in week: for r in week:
kinds, clash = set(), None kinds = set()
for x in r.facts.love.reasons: for x in r.facts.love.reasons:
k = x["kind"] k = x["kind"]
if k == "일지": if k == "일지":
rel = x.get("relation") rel = x.get("relation")
if rel in ("육합", "반합", "삼합"): (kinds.add("일지합") if rel in ("육합", "반합", "삼합") else bads.append((r, rel)))
kinds.add("일지합")
else:
clash = rel
else: else:
kinds.add(k) kinds.add(k)
if clash:
bads.append((r, clash))
continue
good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds] good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds]
if good: if good:
goods.append((r, good)) goods.append((r, good))
goods.sort(key=lambda g: (_wet(g[0]), -g[0].score)) goods.sort(key=lambda g: (g[0].weather is not None and g[0].weather.icon in ("rain", "snow"), -g[0].score))
out: dict = {"gender": gender} out: dict = {"gender": gender}
if goods: if goods:
r, kinds = goods[0] r, kinds = goods[0]
body = T.LOVE_GOOD[kinds[0]][0] + (" " + T.LOVE_WET.format(word=r.weather.word) if _wet(r) else "") rainy = r.weather is not None and r.weather.icon in ("rain", "snow")
out["good"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "icon": r.weather.icon if r.weather else None, "word": r.weather.word if r.weather else None, out["good"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "icon": r.weather.icon if r.weather else None, "word": r.weather.word if r.weather else None,
"temp_max": r.weather.temp_max if r.weather else None, "body": body, "why": " · ".join(T.LOVE_GOOD[k][1] for k in kinds)} "temp_max": r.weather.temp_max if r.weather else None, "body": T.LOVE_GOOD[kinds[0]] + (" " + T.LOVE_RAINY if rainy else ""), "why": "·".join(kinds)}
if bads: if bads:
r, rel = min(bads, key=lambda b: b[0].score) r, rel = bads[0]
out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD[rel], "why": T.LOVE_BAD_WHY[rel]} out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD.get(rel, "말을 한 번 더 고르세요."), "why": f"나·연인 자리와 {rel}"}
return out return out
MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "정인", "상관") MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "편관", "정인", "상관")
def day_word(d: date, today: Optional[date] = None) -> str: def _day_word(r: DayReading) -> str:
"""'10/31(토)', 오늘이면 '오늘(10/28)'""" return f"{_WEEKDAY[r.day.weekday()]} {r.day.day}일({T.TEN_GOD_TEXT[r.facts.stem_ten_god][0]})"
return f"오늘({d.month}/{d.day})" if d == today else f"{d.month}/{d.day}({_WEEKDAY[d.weekday()]})"
def money_work(week: list[DayReading]) -> tuple[list[str], list[str]]: def money_work(week: list[DayReading]) -> tuple[list[str], list[str]]:
"""금전·일: 앞으로 7일 중 그 십성이 드는 날에서 점수로 고른다. 좋은 날은 점수가 PICK_MIN 이상일 때만""" """금전·일: 이번 주에 정할 날과 피할 날 (오늘 카드를 되풀이하지 않는다)"""
def best(gods: tuple[str, ...]) -> Optional[DayReading]: def pick(gods: tuple[str, ...]) -> Optional[DayReading]:
days = [r for r in week if r.facts.stem_ten_god in gods and r.score >= PICK_MIN] return next((r for r in week if r.facts.stem_ten_god in gods), None)
return max(days, key=lambda r: r.score) if days else None
worst = min((r for r in week if r.facts.stem_ten_god in MONEY_BAD), key=lambda r: r.score, default=None) money, work = [], []
money = [T.MONEY_GOOD.format(day=day_word(g.day, week[0].day))] if (g := best(MONEY_GOOD)) else [T.MONEY_NONE] if (g := pick(MONEY_GOOD)) is not None:
if worst is not None: money.append(f"큰 결제·계약은 {_day_word(g)}에 하세요.")
money.append(T.MONEY_BAD.format(day=day_word(worst.day, week[0].day))) if (b := pick(MONEY_BAD)) is not None:
work = [T.WORK_GOOD.format(day=day_word(w.day, week[0].day))] if (w := best(WORK_GOOD)) else [T.WORK_NONE] money.append(f"돈 빌려주기·공동 지출은 {_day_word(b)}엔 피하세요.")
if (w := pick(WORK_GOOD)) is not None:
work.append(f"보고·발표·면접은 {_day_word(w)}에 잡으세요.")
if not money:
money.append("이번 주는 돈이 크게 움직이는 날이 없어요. 평소대로 쓰세요.")
if not work:
work.append("이번 주는 하던 일을 마무리하기 좋아요.")
return money, work return money, work
def year_months(chart: Chart, year: int, start: int = 1) -> list[int]: def year_months(chart: Chart, year: int) -> list[int]:
"""그해 start 월부터 남은 달(절 기준) 중 내 사주와 잘 맞는 달. 셋, 남은 달이 적으면 그 절반 (달 번호는 그 절이 드는 양력 달)""" """그해 열두 달(절 기준) 중 내 사주와 잘 맞는 달 셋 (달 번호는 그 절이 드는 양력 달)"""
scored = [] scored = []
for m in range(start, 13): for m in range(1, 13):
mp = make_chart(date(year, m, 15), time(12, 0)).month mp = make_chart(date(year, m, 15), time(12, 0)).month
found = interactions(chart, mp) found = interactions(chart, mp)
scored.append((pillar_score(chart, mp, found, [], False)[0], m)) scored.append((pillar_score(chart, mp, found, [], False)[0], m))
return sorted(m for _, m in sorted(scored, reverse=True)[: min(3, max(1, len(scored) // 2))]) return sorted(m for _, m in sorted(scored, reverse=True)[:3])
def period(chart: Chart, p: Pillar, unit: str, subject: str) -> dict: def period(chart: Chart, p: Pillar, unit: str) -> dict:
"""이달·올해: 그 간지 천간 십성 + 원국과의 관계. subject 는 근거 줄의 주어 ('이번 달이', '올해가')""" """이달·올해: 그 간지 천간 십성 + 원국과의 관계"""
god = ten_god(chart.day.stem, p.stem) god = ten_god(chart.day.stem, p.stem)
title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god] title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god]
found = sorted(interactions(chart, p), key=lambda i: -abs(_weight(i)))[:NOTES_MAX] return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i) for i in interactions(chart, p)]}
return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i).replace("오늘이", subject) for i in found]}
@dataclass @dataclass
@@ -346,62 +302,45 @@ class Match:
score: int score: int
title: str title: str
lines: list[str] lines: list[str]
day: Optional[DayReading] # 앞으로 7일 중 둘 다 점수가 괜찮고 비·눈이 없는 날 day: Optional[DayReading] # 이번 주 둘 다 좋은 날
friend_scene: str friend_scene: str
MATCH_SCORE = {"base": 55, "stem_hap": 12, "resource": 8, "wealth": 5, "output": 5, "rival": 2, "officer": 0, "branch_hap": 8, "branch_bad": -8, "climate_ok": 5} MATCH_SCORE = {"base": 55, "stem_hap": 12, "resource": 8, "wealth": 5, "output": 5, "rival": 2, "officer": 0, "branch_hap": 8, "branch_bad": -8, "climate_ok": 10}
_GROUPS = (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource"))
def _group(god: str) -> str:
return next(g for k, g in _GROUPS if god in k)
def match_reading(me: Chart, friend: Chart, my_days: list[DayReading], friend_days: list[DayReading]) -> Match: def match_reading(me: Chart, friend: Chart, my_days: list[DayReading], friend_days: list[DayReading]) -> Match:
"""궁합. 점수는 두 방향 십성 점수의 평균이라 누구를 먼저 넣어도 같다. 설명은 내 쪽에서 본 사이"""
god = ten_god(me.day.stem, friend.day.stem) god = ten_god(me.day.stem, friend.day.stem)
title, body = next(v for k, v in T.MATCH_TEXT.items() if god in k) title, body = next(v for k, v in T.MATCH_TEXT.items() if god in k)
back = ten_god(friend.day.stem, me.day.stem) group = next(g for k, g in (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource")) if god in k)
score, lines = MATCH_SCORE["base"] + (MATCH_SCORE[_group(god)] + MATCH_SCORE[_group(back)]) / 2, [body] score, lines = MATCH_SCORE["base"] + MATCH_SCORE[group], [body]
if any(r.kind == "천간합" for r in stem_relations(me.day.stem, friend.day.stem)): if any(r.kind == "천간합" for r in stem_relations(me.day.stem, friend.day.stem)):
score += MATCH_SCORE["stem_hap"] score += MATCH_SCORE["stem_hap"]
lines.append(T.MATCH_STEM_HAP) lines.append(T.MATCH_STEM_HAP)
for r in branch_relations(me.day.branch, friend.day.branch): for r in branch_relations(me.day.branch, friend.day.branch):
if r.kind in T.MATCH_BRANCH and T.MATCH_BRANCH[r.kind] not in lines: if r.kind in T.MATCH_BRANCH:
score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"] score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"]
lines.append(T.MATCH_BRANCH[r.kind]) lines.append(T.MATCH_BRANCH[r.kind])
break
a, b = chart_climate(me), chart_climate(friend) a, b = chart_climate(me), chart_climate(friend)
opposite = {"temp": {"warm": "cool", "cool": "warm"}, "moist": {"dry": "moist", "moist": "dry"}} if a.temp * b.temp < 0 or a.moist * b.moist < 0:
fills = [ax for ax in ("temp", "moist") if opposite[ax].get(a.need[ax]) == b.need[ax]] score += MATCH_SCORE["climate_ok"]
shared = [(ax, a.need[ax]) for ax in ("temp", "moist") if a.need[ax] != "mild" and a.need[ax] == b.need[ax]] lines.append(T.MATCH_CLIMATE_OK)
if fills: else:
score += MATCH_SCORE["climate_ok"] * len(fills) need = [T.NEED_WORD[n] for n in needs_of(a.need)]
lines.append(T.MATCH_CLIMATE_OK.format(axis=T.MATCH_CLIMATE_AXIS[fills[0]])) if need:
elif shared: lines.append(T.MATCH_CLIMATE_SAME.format(need=T.josa("·".join(need), "이가")))
lines.append(T.MATCH_CLIMATE_SAME.format(need=T.need_phrase(shared))) both = [(x, y) for x, y in zip(my_days, friend_days)]
both = [(x, y) for x, y in zip(my_days, friend_days) if not _wet(x) and min(x.score, y.score) >= PICK_MIN]
best = max(both, key=lambda p: min(p[0].score, p[1].score))[0] if both else None best = max(both, key=lambda p: min(p[0].score, p[1].score))[0] if both else None
return Match(score=max(0, min(100, round(score))), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0]) return Match(score=max(0, min(100, score)), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0])
class SajuService: class SajuService:
def __init__( def __init__(
self, regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), week_crud: WeekCRUD = Depends(WeekCRUD), self, regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), week_crud: WeekCRUD = Depends(WeekCRUD),
weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService), users: UserCRUD = Depends(UserCRUD), weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService),
) -> None: ) -> None:
self.regions, self.weather, self.week_crud, self.weather_service, self.week, self.users = regions, weather, week_crud, weather_service, week, users self.regions, self.weather, self.week_crud, self.weather_service, self.week = regions, weather, week_crud, weather_service, week
async def save_birth(self, user: User, birth_date: date, birth_time: Optional[time], place: Optional[str], gender: Optional[Gender]) -> tuple[ErrorType, Optional[User]]:
"""내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)"""
if not date(1900, 1, 1) <= birth_date <= now_kst().date():
return ErrorType.INVALID_INPUT, None
values = {"birth_date": birth_date, "birth_time": birth_time, "birth_place": place, "gender": gender}
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.users.update(s, user.user_id, values))
async def clear_birth(self, user: User) -> tuple[ErrorType, Optional[User]]:
values = {"birth_date": None, "birth_time": None, "birth_place": None, "gender": None}
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.users.update(s, user.user_id, values))
async def _weather(self, region_code: str, start: date) -> tuple[ErrorType, dict[date, DayWeather]]: async def _weather(self, region_code: str, start: date) -> tuple[ErrorType, dict[date, DayWeather]]:
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
@@ -431,18 +370,15 @@ class SajuService:
def _day(self, chart: Chart, d: date, w: Optional[DayWeather], gender: Optional[Gender]) -> DayReading: def _day(self, chart: Chart, d: date, w: Optional[DayWeather], gender: Optional[Gender]) -> DayReading:
facts = daily_facts(chart, d, gender) facts = daily_facts(chart, d, gender)
if w is None: if w is None:
return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=total_score(facts.score, None)) return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=facts.score)
m = climate_match(chart, w.hours) m = climate_match(chart, w.hours)
feels = {x.hour: x.feels_c for x in w.hours} return DayReading(day=d, facts=facts, weather=w, climate_score=m.score, best_hours=m.best_hours, reasons=m.reasons, score=total_score(facts.score, m.score))
comfy = {x.hour: x.score for x in m.hours if COMFY_C[0] <= feels.get(x.hour, COMFY_C[0]) <= COMFY_C[1]}
best = best_window(comfy) or m.best_hours
return DayReading(day=d, facts=facts, weather=w, climate_score=m.score, best_hours=best, reasons=m.reasons, score=total_score(facts.score, m.score))
def _year(self, chart: Chart, today: date) -> dict: def _year(self, chart: Chart, today: date) -> dict:
"""올해 운. 11월부터는 다음 해 미리 보기 (입춘 뒤 날짜로 그해 간지)""" """올해 운. 11월부터는 다음 해 미리 보기 (입춘 뒤 날짜로 그해 간지)"""
y = today.year + 1 if today.month >= 11 else today.year y = today.year + 1 if today.month >= 11 else today.year
p = make_chart(date(y, 6, 1), time(12, 0)).year p = make_chart(date(y, 6, 1), time(12, 0)).year
return {**period(chart, p, "해", "올해가" if y == today.year else f"{y}년이"), "year": y, "preview": y != today.year, "months": year_months(chart, y, today.month if y == today.year else 1)} return {**period(chart, p, "해"), "year": y, "preview": y != today.year, "months": year_months(chart, y)}
async def match( async def match(
self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User], self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User],
@@ -481,9 +417,7 @@ class SajuService:
_, places, _, _ = await self.week.places(region_code, today, None) _, places, _, _ = await self.week.places(region_code, today, None)
place = next((p.place.name for p in places if p.is_good), places[0].place.name if places else None) place = next((p.place.name for p in places if p.is_good), places[0].place.name if places else None)
todo = T.TEN_GOD_TEXT[r0.facts.stem_ten_god][1] todo = T.TEN_GOD_TEXT[r0.facts.stem_ten_god][1]
god = r0.facts.stem_ten_god cards = [c for c in (when_card(r0), Card(kind="do", title="오늘 할 것", body=todo, sub=f"오늘은 {T.josa(r0.facts.stem_ten_god, '이가')} 들어오는 날"), avoid_card(chart, r0.facts), good_card(r0.facts), wear_card(r0, needs, place)) if c]
do = Card(kind="do", title="오늘 할 것", body=todo, sub=f"오늘 들어오는 기운: {T.GOD_PLAIN[god]}({god})")
cards = [c for c in (when_card(r0, needs), do, avoid_card(chart, r0.facts), good_card(r0.facts), wear_card(r0, needs, place)) if c]
level = 1 level = 1
if user is not None: if user is not None:
@@ -496,12 +430,12 @@ class SajuService:
now_chart = make_chart(today, time(12, 0)) now_chart = make_chart(today, time(12, 0))
return ErrorType.SUCCESS, Reading( return ErrorType.SUCCESS, Reading(
chart=chart, scene=scene, scene_icon=T.SCENE_ICON.get(chart_climate.label, "sun") if chart_climate else "sun", chart=chart, scene=scene, scene_icon=T.SCENE_ICON.get(chart_climate.label, "sun") if chart_climate else "sun",
need=[T.need_phrase(needs)] if needs else [], today=r0, cards=cards, why=why_words(r0.facts), level=level, logged_in=user is not None, need=[T.NEED_WORD[n] for n in needs], today=r0, cards=cards, why=why_words(r0.facts), level=level, logged_in=user is not None,
week=days if unlocked("saju_week") else None, week=days if unlocked("saju_week") else None,
money=money_work(days)[0] if unlocked("saju_money") else None, money=money_work(days)[0] if unlocked("saju_money") else None,
work=money_work(days)[1] if unlocked("saju_money") else None, work=money_work(days)[1] if unlocked("saju_money") else None,
love=love_week(chart, days, gender) if unlocked("saju_love") else None, love=love_week(chart, days, gender) if unlocked("saju_love") else None,
month={**period(chart, now_chart.month, "달", "이번 달이"), "from": now_chart.jeol.at.date(), "until": now_chart.next_jeol.at.date(), "jeol": now_chart.jeol.name} if unlocked("saju_month") else None, month={**period(chart, now_chart.month, "달"), "from": now_chart.jeol.at.date(), "until": now_chart.next_jeol.at.date(), "jeol": now_chart.jeol.name} if unlocked("saju_month") else None,
year=self._year(chart, today) if unlocked("saju_year") else None, year=self._year(chart, today) if unlocked("saju_year") else None,
) )
+106 -118
View File
@@ -1,101 +1,104 @@
"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다. 쉬운 말을 앞에, 명리 용어는 괄호에.""" """날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다 (초안, 사용자 검토 대상)."""
# 오늘 천간 십성 → (제목, 오늘 할 것) # 오늘 천간 십성 → (제목, 오늘 할 것)
TEN_GOD_TEXT: dict[str, tuple[str, str]] = { TEN_GOD_TEXT: dict[str, tuple[str, str]] = {
"비견": ("내 페이스대로 가는 날", "남한테 맞추기보다 내가 정한 일 하나를 끝까지 해 보세요."), "비견": ("내 힘으로 밀고 가는 날", "혼자 끝낼 수 있는 일을 오늘 끝내세요."),
"겁재": ("내 몫을 챙겨야 하는 날", "같이 하는 일은 누가 무엇을 맡을지 먼저 정해 두세요."), "겁재": ("내 몫을 지키는 날", "남 눈치 보지 말고 내가 정한 일을 밀고 가세요."),
"식신": ("여유가 생기는 날", "맛있는 걸 먹거나 좋아하는 일에 시간을 내 보세요."), "식신": ("즐기고 먹는 날", "맛있는 걸 먹고 좋아하는 일에 시간을 쓰세요."),
"상관": ("말솜씨가 살아나는 날", "생각해 둔 아이디어를 말이나 글로 꺼내 보세요."), "상관": ("말과 재주가 빛나는 날", "발표·제안·글쓰기처럼 밖으로 꺼내는 일을 하세요."),
"편재": ("새 기회가 보이는 날", "새로 들어온 제안은 조건부터 차근차근 들어 보세요."), "편재": ("기회가 들어오는 날", "들어오는 제안은 들어 보고, 큰돈은 하루 생각한 뒤 정하세요."),
"정재": ("알뜰하게 챙기는 날", "가계부를 정리하거나 미뤄 둔 정산을 끝내 보세요."), "정재": ("차곡차곡 모으는 날", "정리·가계부·저축처럼 꼼꼼한 일을 하세요."),
"편관": ("책임이 무거운 날", "미뤄 둔 어려운 일을 작게 나눠 첫 단계만 끝내 보세요."), "편관": ("버티면 크는 날", "미뤄 둔 어려운 일에 먼저 손대 보세요."),
"정관": ("약속과 규칙을 챙기는 날", "약속 시간과 마감부터 확인하세요."), "정관": ("믿음을 얻는 날", "약속 시간과 규칙을 지키면 평가가 올라가요."),
"편인": ("혼자 생각할 시간이 필요한 날", "떠오른 생각을 메모해 두세요."), "편인": ("혼자 생각하는 날", "혼자 있는 시간에 떠오른 생각을 적어 두세요."),
"정인": ("배우기 좋은 날", "궁금했던 걸 찾아보거나 아는 사람에게 물어보세요."), "정인": ("배우고 도움받는 날", "공부·자격증·조언 구하기에 좋아요."),
}
# 십성 → 쉬운 말 ('오늘 들어오는 기운: 압박·책임(편관)')
GOD_PLAIN = {
"비견": "나와 닮은 힘", "겁재": "경쟁", "식신": "여유·즐거움", "상관": "표현", "편재": "새 돈·새 기회",
"정재": "모으는 돈", "편관": "압박·책임", "정관": "규칙·평판", "편인": "생각·직감", "정인": "배움·도움",
} }
# 원국 자리 → 쉬운 말. 일간은 '나', 나머지는 태어난 해·달·날·시 # 원국 자리 → 화면에 쓰는 짧은 이름
PLACE_WORD = {"year": "태어난 해", "month": "태어난 달", "day": "태어난 날", "hour": "태어난 시"} PLACE_WORD = {"year": "윗사람·바깥 일", "month": "직장·집안", "day": "나·연인", "hour": "아랫사람·앞날"}
PLACE_TERM = {"year": "연", "month": "월", "day": "일", "hour": "시"}
# 관계 → 쉬운 말
REL_WORD = {
"천간합": "어울려요", "육합": "어울려요", "반합": "어울려요", "삼합": "한데 묶여요",
"천간충": "부딪혀요", "충": "부딪혀요", "형": "엇갈려요", "삼형": "엇갈려요", "자형": "겹쳐 부담돼요",
"파": "틀어져요", "해": "어긋나요", "원진": "서로 꺼려요",
}
# (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로. 지지 관계의 일(日) 자리는 연인·배우자 자리(일지) # (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로
AVOID_TEXT: dict[tuple[str, str], str] = { AVOID_TEXT: dict[tuple[str, str], str] = {
("원진", "day"): "연인·가까운 사람의 말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.", ("원진", "day"): "연인·배우자에게 사소한 서운함이 생기기 쉬워요. 큰 이야기는 내일로 미루세요.",
("충", "day"): "가까운 사람과 의견이 부딪히기 쉬워요. 서로 원하는 걸 먼저 확인하세요.", ("충", "day"): "가까운 사람과 부딪히기 쉬워요. 다툼이 될 만한 이야기는 피하세요.",
("충", "month"): "회사·집안 일정이 바뀌기 쉬워요. 이직·이사처럼 큰 결정은 오늘 확정하지 마세요.", ("충", "month"): "직장·집안 일정이 흔들리기 쉬워요. 이직·이사 같은 큰 결정은 미루세요.",
("충", "year"): "밖에서 잡힌 일정이 바뀌기 쉬워요. 약속 시간과 장소를 다시 확인하세요.", ("충", "year"): "윗사람·바깥 일에서 변수가 생기기 쉬워요. 약속은 한 번 더 확인하세요.",
("충", "hour"): "계획대로 안 풀리기 쉬워요. 일정 사이에 여유를 두세요.", ("충", "hour"): "앞날 계획이 흔들리기 쉬워요. 일정은 여유 있게 잡으세요.",
("원진", ""): "말이 서운하게 들리기 쉬워요. 메시지는 보내기 전에 한 번 더 읽어 보세요.", ("원진", ""): "사소한 오해가 생기기 쉬워요. 말투를 한 번 더 고르세요.",
("형", ""): "서류·계약·약속은 한 번 더 확인하세요.", ("형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.", ("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
("자형", ""): "같은 고민을 계속 붙잡기 쉬워요. 적어 두고 일찍 쉬세요.", ("자형", ""): "생각이 많아 혼자 지치기 쉬워요. 오늘은 일찍 쉬세요.",
("파", ""): "약속이 틀어지기 쉬워요. 시간과 장소를 다시 확인하세요.", ("파", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
("해", ""): "좋은 뜻으로 한 일이 오해를 사기 쉬워요. 부탁받은 일은 범위부터 정하세요.", ("해", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
("천간충", ""): "마음이 오락가락하기 쉬워요. 결정할 일은 하나씩 정리하세요.", ("천간충", ""): "마음이 이리저리 흔들리기 쉬워요. 결정은 하나씩 하세요.",
} }
# 비겁이 많고 재성이 있는 원국에 비겁 날 (군겁쟁재) # 비겁이 많은 원국에 비겁 날 (군겁쟁재)
CROWDED_RIVALS = "돈을 빌려주거나 같이 투자하는 건 오늘 미루세요." CROWDED_RIVALS = "같이 쓰는 돈·더치페이·빌려주는 돈은 오늘 정하지 마세요."
CROWDED_WHY = "내 사주에 나와 같은 기운이 많은데 오늘도 같은 기운이 들어와요({god})"
# 지지 합이 든 자리 → 좋은 흐름. 일간과 천간합이면 STEM_GOOD # 자리 → 좋은 흐름 (합이 들 때)
GOOD_TEXT = { GOOD_TEXT = {
"day": "연인·가까운 사람과 사이가 부드러운 날이에요. 함께할 시간을 잡아 보세요.", "day": "연인·배우자와 가까워지는 날이에요. 같이 보낼 시간을 잡아 보세요.",
"month": "회사·집안 일이 순조로운 날이에요. 미뤄 둔 협업 이야기를 꺼내 보세요.", "month": "직장·팀 일이 잘 맞물려요. 협업 제안을 꺼내기 좋아요.",
"year": "밖에서 도움을 받기 좋은 날이에요. 부탁할 일이 있으면 오늘 꺼내 보세요.", "year": "윗사람·바깥 사람에게 도움을 받기 쉬워요. 부탁할 일을 꺼내 보세요.",
"hour": "후배·아이와 잘 통하는 날이에요. 먼저 말을 걸어 보세요.", "hour": "아랫사람·후배와 사이가 좋아지는 날이에요.",
} }
STEM_GOOD = "마음 맞는 사람을 만나기 좋은 날이에요. 미뤄 둔 연락을 해 보세요."
GOOD_RELATIONS = ("천간합", "육합", "삼합", "반합") GOOD_RELATIONS = ("천간합", "육합", "삼합", "반합")
# 금전·일: 앞으로 7일 중 고른 날 → 한 줄 ({day}는 '10/31(토)') # 금전운 · 일운: 오늘 천간 십성 → 한 줄
MONEY_GOOD = "큰돈 쓰거나 계약할 일은 {day}에 하세요." MONEY_TEXT = {
MONEY_BAD = "돈 빌려주기·같이 투자하기는 {day}엔 미루세요." "비견": "같이 쓰는 돈은 각자 내는 게 편한 날이에요.",
WORK_GOOD = "보고·발표·면접은 {day}에 잡아 보세요." "겁재": "빌려주거나 함께 투자하는 돈은 오늘 정하지 마세요.",
MONEY_NONE = "앞으로 7일 중엔 큰돈 쓰기 좋은 날이 따로 없어요." "식신": "즐기는 데 쓰는 돈이 늘기 쉬워요. 한도를 먼저 정하세요.",
WORK_NONE = "앞으로 7일 중엔 발표·면접 잡기 좋은 날이 따로 없어요." "상관": "충동 구매가 생기기 쉬워요. 장바구니에 하루 두었다 사세요.",
"편재": "뜻밖의 수입이나 할인 기회가 와요. 들어올 돈부터 챙기세요.",
"정재": "가계부·적금처럼 돈을 정리하기 좋아요.",
"편관": "갑자기 나갈 돈이 생기기 쉬워요. 여윳돈을 남겨 두세요.",
"정관": "공과금·세금처럼 정해진 돈을 처리하기 좋아요.",
"편인": "돈보다 정보가 남는 날이에요. 가격 비교를 해 두세요.",
"정인": "배우는 데 쓰는 돈은 아깝지 않은 날이에요.",
}
WORK_TEXT = {
"비견": "혼자 끝낼 수 있는 일에 집중하세요.",
"겁재": "공동 작업은 역할과 몫을 먼저 나누세요.",
"식신": "편하게 꺼낸 아이디어가 반응이 좋아요.",
"상관": "발표·제안에 좋아요. 윗사람 앞에선 말을 한 번 고르세요.",
"편재": "새 거래·새 사람과 일을 시작하기 좋아요.",
"정재": "숫자를 맞추고 결과를 정리하는 일에 좋아요.",
"편관": "어려운 일을 맡으면 인정받아요.",
"정관": "보고·결재처럼 정해진 일을 처리하기 좋아요.",
"편인": "자료 조사·기획처럼 준비하는 일에 좋아요.",
"정인": "배우거나 도움을 청하면 일이 풀려요.",
}
# 연애 기운이 드는 이유 → (한 줄, 이유 말) # 연애 기운이 드는 이유 → 한 줄
LOVE_GOOD = { LOVE_GOOD = {
"도화": ("눈에 잘 띄는 날이에요. 모임이나 소개팅에 나가 보세요.", "눈에 띄는 기운(도화)"), "도화": "사람들 눈에 잘 띄는 날이에요. 새 만남에 좋아요.",
"홍염": ("매력이 잘 드러나는 날이에요. 관심 있는 사람에게 먼저 연락해 보세요.", "매력의 기운(홍염)"), "홍염": "매력이 드러나는 날이에요.",
"일지합": ("연인과 마음이 잘 맞는 날이에요. 데이트 약속을 잡아 보세요.", "연인 자리와 어울림(일지 합)"), "일지합": "연인과 가까워지는 날이에요.",
"재성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(재성)"), "재성": "이성 기운이 들어오는 날이에요.",
"관성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(관성)"), "관성": "이성 기운이 들어오는 날이에요.",
} }
LOVE_BAD = { LOVE_BAD = {
"원진": "말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.", "원진": "서운한 말이 오가기 쉬워요.",
"충": "의견이 부딪히기 쉬워요. 중요한 이야기는 다른 날로 미루세요.", "충": "다투기 쉬워요.",
"형": "오해가 생기기 쉬워요. 메시지보다 직접 말하세요.", "형": "오해가 생기기 쉬워요.",
"자형": "혼자 속앓이하기 쉬워요. 서운한 건 담아 두지 말고 말하세요.", "자형": "혼자 속앓이하기 쉬워요.",
} }
LOVE_BAD_WHY = {"원진": "연인 자리와 서로 꺼림(일지 원진)", "충": "연인 자리와 부딪힘(일지 충)", "형": "연인 자리와 엇갈림(일지 형)", "자형": "연인 자리에 같은 글자가 겹침(일지 자형)"}
LOVE_WET = "{word} 예보가 있으니 실내 데이트로 잡으세요."
# 내 기운: 태어난 계절 × 원국의 결 # 내 기운: 태어난 계절 × 원국의 결
SCENES: dict[tuple[str, str], tuple[str, str]] = { SCENES: dict[tuple[str, str], tuple[str, str]] = {
("봄", "따뜻·마름"): ("봄햇살 기운", "새싹을 키우는 맑은 봄볕"), ("봄", "따뜻·마름"): ("봄햇살 기운", "새싹을 키우는 맑은 봄볕"),
("봄", "따뜻·촉촉"): ("봄 아지랑이 기운", "따뜻하고 포근한 봄 오후"), ("봄", "따뜻·촉촉"): ("봄 아지랑이 기운", "따뜻하고 포근한 봄 오후"),
("봄", "서늘·마름"): ("꽃샘바람 기운", "꽃봉오리를 스치는 쌀쌀한 봄바람"), ("봄", "서늘·마름"): ("꽃샘바람 기운", "쌀쌀해도 꽃을 피우는 봄바람"),
("봄", "서늘·촉촉"): ("봄비 기운", "새싹을 깨우는 촉촉한 이른 봄비"), ("봄", "서늘·촉촉"): ("봄비 기운", "새싹을 깨우는 촉촉한 이른 봄비"),
("여름", "따뜻·마름"): ("한낮 땡볕 기운", "뜨겁고 환한 여름 한낮"), ("여름", "따뜻·마름"): ("한낮 땡볕 기운", "뜨겁고 환한 여름 한낮"),
("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근한 오후에 쏟아지는 소나기"), ("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근하다 시원하게 쏟아지는 여름비"),
("여름", "서늘·마름"): ("여름밤 바람 기운", "열기를 식혀 주는 여름밤 바람"), ("여름", "서늘·마름"): ("여름밤 바람 기운", "열기를 식혀 주는 여름밤 바람"),
("여름", "서늘·촉촉"): ("장맛비 기운", "며칠씩 이어지는 여름 장맛비"), ("여름", "서늘·촉촉"): ("장맛비 기운", "오래 촉촉하게 내리는 장맛비"),
("가을", "따뜻·마름"): ("가을 햇살 기운", "곡식을 익히는 가을볕"), ("가을", "따뜻·마름"): ("가을 햇살 기운", "곡식을 익히는 가을볕"),
("가을", "따뜻·촉촉"): ("가을비 기운", "단풍을 적시는 포근한 가을비"), ("가을", "따뜻·촉촉"): ("가을비 기운", "단풍을 적시는 포근한 가을비"),
("가을", "서늘·마름"): ("가을바람 기운", "선선하고 맑은 가을바람"), ("가을", "서늘·마름"): ("소슬바람 기운", "선선하고 맑은 가을바람"),
("가을", "서늘·촉촉"): ("새벽 서리 기운", "풀잎에 서리가 내린 늦가을 새벽"), ("가을", "서늘·촉촉"): ("새벽 서리 기운", "찬 이슬이 맺히는 늦가을 새벽"),
("겨울", "따뜻·마름"): ("겨울 햇살 기운", "추위 속에 비치는 겨울볕"), ("겨울", "따뜻·마름"): ("겨울 햇살 기운", "추위 속에 비치는 겨울볕"),
("겨울", "따뜻·촉촉"): ("함박눈 기운", "포근하게 쌓이는 함박눈"), ("겨울", "따뜻·촉촉"): ("함박눈 기운", "포근하게 쌓이는 함박눈"),
("겨울", "서늘·마름"): ("칼바람 기운", "맑고 매서운 겨울바람"), ("겨울", "서늘·마름"): ("칼바람 기운", "맑고 매서운 겨울바람"),
@@ -103,18 +106,10 @@ SCENES: dict[tuple[str, str], tuple[str, str]] = {
} }
SCENE_ICON = {"따뜻·마름": "sun", "따뜻·촉촉": "sun_cloud", "서늘·마름": "coldwind", "서늘·촉촉": "rain"} SCENE_ICON = {"따뜻·마름": "sun", "따뜻·촉촉": "sun_cloud", "서늘·마름": "coldwind", "서늘·촉촉": "rain"}
# 조후에서 필요한 것 → (이어 쓰는 꼴, 끝맺는 꼴): '따뜻하고 건조한 날씨' # 조후에서 필요한 것 → 말
NEED_ADJ = {("temp", "warm"): ("따뜻하고", "따뜻한"), ("temp", "cool"): ("선선하고", "선선한"), ("moist", "dry"): ("건조하고", "건조한"), ("moist", "moist"): ("촉촉하고", "촉촉한")} NEED_WORD = {("temp", "warm"): "따뜻함", ("temp", "cool"): "시원함", ("moist", "dry"): "마른 공기", ("moist", "moist"): "촉촉함"}
# 옷 포인트 색 (오방색에서 착안) # 필요한 기운을 채우는 색 (오방색)
NEED_COLOR = {("temp", "warm"): "빨강·주황으로", ("temp", "cool"): "검정·남색으로", ("moist", "dry"): "노랑·베이지로", ("moist", "moist"): "초록·하늘색으로"} NEED_COLOR = {("temp", "warm"): "빨강·주황", ("temp", "cool"): "검정·남색", ("moist", "dry"): "노랑·베이지", ("moist", "moist"): "초록·하늘색"}
def need_phrase(needs: list[tuple[str, str]]) -> str:
"""[('temp','warm'), ('moist','dry')] → '따뜻하고 건조한 날씨'"""
if not needs:
return ""
words = [NEED_ADJ[n] for n in needs]
return " ".join([w[0] for w in words[:-1]] + [words[-1][1]]) + " 날씨"
def clothes(feels_min: float) -> str: def clothes(feels_min: float) -> str:
@@ -144,49 +139,42 @@ def josa(word: str, pair: str) -> str:
has = "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0 has = "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0
return word + (pair[0] if has or not ("가" <= last <= "힣") else pair[1]) return word + (pair[0] if has or not ("가" <= last <= "힣") else pair[1])
# 궁합: 친구 일간이 나에게 무슨 십성인지 → (제목, 설명)
# 궁합: 상대 일간이 나에게 무슨 십성인지 → (제목, 설명). 내 쪽에서 본 사이
MATCH_TEXT = { MATCH_TEXT = {
("비견", "겁재"): ("친구처럼 대등한 사이", "취향이 비슷해 편하게 지내기 쉬워요. 정할 일은 번갈아 정하세요."), ("비견", "겁재"): ("친구처럼 대등한 사이", "좋아하는 게 비슷해 편한 사이예요. 정할 일은 차례를 나눠 정하세요."),
("식신", "상관"): ("내가 더 챙겨 주는 사이", "내가 마음을 더 많이 쓰는 쪽이에요. 받고 싶은 것도 말로 꺼내세요."), ("식신", "상관"): ("내가 챙겨 주는 사이", "내가 아이디어와 마음을 더 많이 주는 쪽이에요."),
("편재", "정재"): ("내가 이끄는 사이", "약속이나 계획은 내가 먼저 정할 때 편해요. 상대 의견도 꼭 물어보세요."), ("편재", "정재"): ("내가 이끄는 사이", "내가 정하고 이끌 때 둘 다 편해지는 사이예요."),
("편관", "정관"): ("나를 잡아 주는 사이", "상대가 내 기준이 되어 주는 쪽이에요. 부담되면 솔직히 말하세요."), ("편관", "정관"): ("나를 다잡아 주는 사이", "상대가 내 기준을 세워 주고 정리해 줘요."),
("편인", "정인"): ("나를 챙겨 주는 사이", "상대에게 도움을 많이 받는 쪽이에요. 고마운 건 바로 표현하세요."), ("편인", "정인"): ("나를 키워 주는 사이", "상대가 나를 돕고 채워 주는 쪽이에요."),
} }
MATCH_STEM_HAP = "서로 끌리는 글자끼리 만나는 사이예요(일간 합)." MATCH_STEM_HAP = "일간끼리 합이라 처음부터 잘 끌리는 사이예요."
MATCH_BRANCH = { MATCH_BRANCH = {"육합": "함께 있으면 편안한 사이예요.", "반합": "함께 있으면 편안한 사이예요.", "충": "생활 리듬이 달라 부딪히기 쉬워요. 약속은 미리 맞추세요.", "원진": "사소한 일에 서운해하기 쉬워요. 말로 먼저 풀어 주세요."}
"육합": "같이 있으면 편안한 사이예요(일지 합).", MATCH_CLIMATE_OK = "서로의 날씨를 맞춰 주는 사이예요. 함께 있으면 둘 다 균형이 잡혀요."
"반합": "같이 있으면 편안한 사이예요(일지 합).", MATCH_CLIMATE_SAME = "둘 다 {need} 필요한 기운이라, 그런 날씨에 함께 나가면 좋아요."
"충": "생활 리듬이 달라 부딪히기 쉬워요. 연락·약속 방식을 미리 맞추세요(일지 충).",
"원진": "작은 일로 서운해하기 쉬워요. 서운한 건 그때그때 말하세요(일지 원진).",
}
# 궁합 날씨: 한 축에서 둘이 서로 모자란 걸 채워 줄 때 / 둘 다 같은 날씨가 맞을 때
MATCH_CLIMATE_AXIS = {"temp": "한 사람은 따뜻하고 한 사람은 서늘한 기운이라", "moist": "한 사람은 촉촉하고 한 사람은 건조한 기운이라"}
MATCH_CLIMATE_OK = "{axis} 서로 모자란 걸 채워 줘요."
MATCH_CLIMATE_SAME = "둘 다 {need}가 맞는 기운이라, 그런 날 함께 나가면 좋아요."
# 이달 · 올해: 그 간지 천간 십성 → (제목, 설명) # 이달 · 올해: 그 간지 천간 십성 → (제목, 설명)
MONTH_TEXT: dict[str, tuple[str, str]] = { MONTH_TEXT: dict[str, tuple[str, str]] = {
"비견": ("내 페이스대로 가는 달", "남에게 기대기보다 내 손으로 일을 끝내기 좋은 달이에요."), "비견": ("내 힘으로 서는 달", "혼자 해 온 일을 굳히기 좋은 달이에요. 새 일은 내 손으로 시작하세요."),
"겁재": ("내 몫을 챙겨야 하는 달", "같이 하는 일은 몫부터 정해 두세요. 돈 빌려주기·같이 투자하기는 서두르지 마세요."), "겁재": ("내 몫을 지키는 달", "돈 약속·공동 투자는 서두르지 말고, 내 몫부터 정해 두세요."),
"식신": ("여유가 생기는 달", "취미·맛집·여행처럼 나를 위한 일에 시간을 쓰세요."), "식신": ("즐기며 채우는 달", "취미·맛집·여행처럼 나를 채우는 일에 시간을 쓰세요."),
"상관": ("말솜씨가 살아나는 달", "발표·제안·글쓰기처럼 내 생각을 꺼내는 일을 해 보세요."), "상관": ("말과 재주가 빛나는 달", "발표·제안·창작처럼 밖으로 꺼내는 일이 잘 돼요."),
"편재": ("새 기회가 보이는 달", "새 제안과 사람이 많이 찾아오는 달이에요. 큰돈이 드는 일은 조건을 따져 보고 정하세요."), "편재": ("기회가 들어오는 달", "새 제안과 사람이 많이 들어와요. 큰돈은 한 번 더 따져 보고 정하세요."),
"정재": ("알뜰하게 모으는 달", "저축·가계부 정리처럼 돈을 차곡차곡 챙기기 좋은 달이에요."), "정재": ("차곡차곡 모으는 달", "저축·정리·계약처럼 꼼꼼한 일이 잘 맞아요."),
"편관": ("책임이 무거운 달", "맡는 일이 많아지는 달이에요. 할 일을 나눠 우선순위부터 정하세요."), "편관": ("버티면 크는 달", "맡는 일이 무거워지지만 끝내면 크게 인정받아요."),
"정관": ("평판을 쌓는 달", "약속과 마감을 잘 지키면 믿음을 얻기 좋은 달이에요."), "정관": ("믿음을 쌓는 달", "약속과 규칙을 지키면 자리와 평가가 올라가요."),
"편인": ("생각이 깊어지는 달", "공부·기획처럼 혼자 파고드는 일이 잘 맞아요."), "편인": ("생각을 다지는 달", "공부·기획·정리처럼 혼자 하는 일에 좋아요."),
"정인": ("배우기 좋은 달", "공부를 시작하거나 아는 사람에게 도움을 청해 보세요."), "정인": ("배우고 도움받는 달", "공부를 시작하거나 도움을 청하기 좋아요."),
} }
YEAR_TEXT: dict[str, tuple[str, str]] = { YEAR_TEXT: dict[str, tuple[str, str]] = {
"비견": ("홀로서기 좋은 해", "내 이름으로 하는 일을 시작하고 키우기 좋은 해예요."), "비견": ("홀로서기의 해", "내 이름으로 하는 일을 시작하고 굳히기 좋은 해예요."),
"겁재": ("내 몫을 챙겨야 하는 해", "동업·공동 투자는 몫과 역할을 문서로 정해 두세요."), "겁재": ("내 몫을 지키는 해", "같이 하는 돈·사업은 몫을 분명히 나누세요."),
"식신": ("하고 싶은 걸 하는 해", "좋아하는 일을 꾸준히 키우고 몸을 챙기기 좋은 해예요."), "식신": ("즐기며 넓히는 해", "좋아하는 일을 키우고 몸을 챙기기 좋은 해예요."),
"상관": ("나를 드러내는 해", "창작·발표처럼 내 실력을 보여 주는 일이 잘 맞는 해예요."), "상관": ("재주를 드러내는 해", "창작·발표·이직처럼 나를 보여 주는 일이 잘 맞아요."),
"편재": ("기회가 넓어지는 해", "새 사람·새 수입원이 생기기 쉬운 해예요. 크게 벌이는 일은 나눠서 하세요."), "편재": ("기회가 넓어지는 해", "새 사람·새 돈길이 열려요. 크게 벌이는 일은 나눠서 하세요."),
"정재": ("차곡차곡 모으는 해", "저축하고 고정 수입을 늘리기 좋은 해예요."), "정재": ("차곡차곡 쌓는 해", "저축·자산 정리·안정된 수입을 만들기 좋은 해예요."),
"편관": ("책임이 커지는 해", "맡는 일이 무거워지는 해예요. 혼자 다 떠안지 말고 도움받을 일을 나누세요."), "편관": ("단단해지는 해", "책임이 커지는 해예요. 버틴 만큼 자리가 생겨요."),
"정관": ("인정받기 좋은 해", "승진·자격시험처럼 정해진 길을 밟는 일이 잘 풀리는 해예요."), "정관": ("자리를 얻는 해", "승진·자격·약속처럼 제도 안의 일이 잘 풀려요."),
"편인": ("방향을 다시 잡는 해", "공부하거나 진로를 다시 생각해 보기 좋은 해예요."), "편인": ("나를 다시 짜는 해", "공부·기획·방향 전환을 준비하기 좋은 해예요."),
"정인": ("배움과 도움이 많은 해", "공부·자격증을 시작하거나 멘토를 찾기 좋은 해예요."), "정인": ("배우고 받는 해", "공부·자격증, 도와줄 사람을 만나기 좋은 해예요."),
} }
LOVE_RAINY = "비가 오니 실내 약속으로 잡으세요."
+7 -6
View File
@@ -1,5 +1,5 @@
import asyncio
import json import json
import xml.etree.ElementTree as ET
import httpx import httpx
from redis.exceptions import RedisError from redis.exceptions import RedisError
@@ -29,11 +29,11 @@ class ShortsService:
return await self.refresh() return await self.refresh()
async def refresh(self) -> tuple[ErrorType, list[dict]]: async def refresh(self) -> tuple[ErrorType, list[dict]]:
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로.""" """유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
try: try:
async with httpx.AsyncClient(timeout=10) as client: async with httpx.AsyncClient(timeout=10) as client:
items = await self._fetch(client) items = await self._fetch(client)
except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) as e: except (httpx.HTTPError, KeyError, ValueError) as e:
LOG.error(f"[shorts] fetch: {e}") LOG.error(f"[shorts] fetch: {e}")
return ErrorType.EXTERNAL_API_ERROR, [] return ErrorType.EXTERNAL_API_ERROR, []
try: try:
@@ -45,6 +45,7 @@ class ShortsService:
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]: async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
if settings.youtube_api_key: if settings.youtube_api_key:
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS) found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
else: return [{"id": v["id"], "title": v["title"]} for v in found]
found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS) ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
return [{"id": v["id"], "title": v["title"]} for v in found] titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
+1 -27
View File
@@ -37,8 +37,6 @@ async def test_reading_for_anyone_gives_me_today_and_cards(offline):
assert r["me"]["scene"].endswith("기운") and r["today"]["title"] and 0 <= r["today"]["score"] <= 100 assert r["me"]["scene"].endswith("기운") and r["today"]["title"] and 0 <= r["today"]["score"] <= 100
kinds = [x["kind"] for x in r["today"]["cards"]] kinds = [x["kind"] for x in r["today"]["cards"]]
assert "when" in kinds and "do" in kinds and "wear" in kinds assert "when" in kinds and "do" in kinds and "wear" in kinds
# 근거 줄은 쉬운 말 + 괄호 용어, 숫자 없이
assert r["today"]["why"] and not any(ch.isdigit() for w in r["today"]["why"] for ch in w)
# 로그인 안 하면 레벨로 여는 것은 모두 잠김, 내용도 안 옴 # 로그인 안 하면 레벨로 여는 것은 모두 잠김, 내용도 안 옴
assert r["logged_in"] is False and all(not x["unlocked"] for x in r["locks"]) assert r["logged_in"] is False and all(not x["unlocked"] for x in r["locks"])
assert "week" not in r and "love" not in r and "money" not in r assert "week" not in r and "love" not in r and "money" not in r
@@ -70,7 +68,7 @@ async def test_level_unlocks_sections_and_awards_once(offline):
h7 = await _login(c, "saju_07", points=1000) h7 = await _login(c, "saju_07", points=1000)
r = (await c.post("/v1/saju/reading", json=BIRTH, headers=h7)).json() r = (await c.post("/v1/saju/reading", json=BIRTH, headers=h7)).json()
assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and 1 <= len(r["year"]["months"]) <= 3 assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and len(r["year"]["months"]) == 3
@pytest.mark.anyio @pytest.mark.anyio
@@ -83,27 +81,3 @@ async def test_match_needs_level_five(offline):
h5 = await _login(c, "match_05", points=400) h5 = await _login(c, "match_05", points=400)
m = (await c.post("/v1/saju/match", json=body, headers=h5)).json() m = (await c.post("/v1/saju/match", json=body, headers=h5)).json()
assert m["title"].endswith("사이") and m["lines"] and 0 <= m["score"] <= 100 and m["day"]["weekday"] and m["friend_scene"].endswith("기운") assert m["title"].endswith("사이") and m["lines"] and 0 <= m["score"] <= 100 and m["day"]["weekday"] and m["friend_scene"].endswith("기운")
@pytest.mark.anyio
async def test_match_score_is_same_whoever_goes_first(offline):
a, b = {"birth_date": "1995-03-14"}, {"birth_date": "1996-11-02"}
async with client() as c:
h = await _login(c, "match_sym", points=400)
ab = (await c.post("/v1/saju/match", json={"region_code": REGION, "me": a, "friend": b}, headers=h)).json()
ba = (await c.post("/v1/saju/match", json={"region_code": REGION, "me": b, "friend": a}, headers=h)).json()
assert ab["score"] == ba["score"]
@pytest.mark.anyio
async def test_birth_is_saved_to_account(offline):
body = {"birth_date": "1995-03-14", "birth_time": "07:30", "place": "busan", "gender": "female"}
async with client() as c:
assert (await c.get("/v1/saju/birth")).status_code == 401
h = await _login(c, "birth_01")
assert "birth" not in (await c.get("/v1/saju/birth", headers=h)).json()
assert (await c.put("/v1/saju/birth", json=body, headers=h)).json()["birth"] == body
assert (await c.get("/v1/saju/birth", headers=h)).json()["birth"] == body
assert (await c.put("/v1/saju/birth", json={**body, "birth_date": "1899-12-31"}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
await c.delete("/v1/saju/birth", headers=h)
assert "birth" not in (await c.get("/v1/saju/birth", headers=h)).json()
+1 -27
View File
@@ -6,7 +6,7 @@ import pytest
from common.cache.redis_client import REDIS from common.cache.redis_client import REDIS
from common.enums import ErrorType from common.enums import ErrorType
from services import shorts_service from services import shorts_service
from services.external.youtube import channel_shorts, feed_shorts, seconds, video_title from services.external.youtube import channel_shorts, seconds, video_title
from services.shorts_service import CACHE_KEY, ShortsService from services.shorts_service import CACHE_KEY, ShortsService
@@ -58,32 +58,6 @@ async def test_video_title_none_when_embedding_blocked():
assert await video_title(client, "blocked") is None assert await video_title(client, "blocked") is None
def _feed(entries: list[tuple[str, str]]) -> str:
items = "".join(
f"<entry><yt:videoId>{vid}</yt:videoId><title>제목 {vid}</title><published>{published}</published></entry>" for vid, published in entries
)
return f'<feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://www.youtube.com/xml/schemas/2015">{items}</feed>'
@pytest.mark.anyio
async def test_feed_shorts_reads_channel_shorts_feed_newest_first_without_blocked():
seen = {}
def handle(req: httpx.Request) -> httpx.Response:
if req.url.path.endswith("/feeds/videos.xml"):
seen["playlist"] = req.url.params["playlist_id"]
return httpx.Response(200, text=_feed([("old", "2026-10-20T00:00:00+00:00"), ("new", "2026-10-28T00:00:00+00:00"), ("blocked", "2026-10-27T00:00:00+00:00")]))
if "blocked" in req.url.params["url"]:
return httpx.Response(401)
return httpx.Response(200, content=json.dumps({"title": "x"}))
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
found = await feed_shorts(client, "UCtest", 10)
assert seen["playlist"] == "UUSHtest"
assert [v["id"] for v in found] == ["new", "old"]
assert found[0]["title"] == "제목 new"
@pytest.mark.anyio @pytest.mark.anyio
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch): async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
calls = [] calls = []
+4
View File
@@ -55,8 +55,12 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` | | `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
| `saju_input` | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` | | `saju_input` | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` |
| `saju_view` | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score` | `SajuPage.tsx` `Reading` | | `saju_view` | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score` | `SajuPage.tsx` `Reading` |
| `game_start` | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속) | `CloudMergePage.tsx` `onUp` |
| `game_round` | 구름 합치기 라운드를 깸 | `round`(깬 라운드), `score`(그때 총점), `logged_in`(각을 받는지) | `CloudMergePage.tsx` `onScore` |
| `game_over` | 구름 합치기가 넘쳐서 끝남 | `round`(끝난 라운드), `score`, `best`(최고 기록 갱신), `drops`(떨어뜨린 횟수) | `CloudMergePage.tsx` `onOver` |
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다. - 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
- 구름 합치기 게임 방법 창은 `sheet_open`(`sheet: 'gameHelp'`)으로 잡혀 따로 보내지 않는다.
- 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다. - 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다.
- 점수 근거·댓글창 열기처럼 창으로 여는 기능은 따로 이벤트를 두지 않고 `sheet_open`의 `sheet`로 나눠 본다. - 점수 근거·댓글창 열기처럼 창으로 여는 기능은 따로 이벤트를 두지 않고 `sheet_open`의 `sheet`로 나눠 본다.
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다. - `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
+10
View File
@@ -7,6 +7,7 @@ import { gameRound, gameStart } from '@nalssigak/shared/api/client/sdk.gen'
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen' import type { ResLevel } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib' import { kst } from '@nalssigak/shared/lib'
import { slotAt } from '@nalssigak/shared/lib/weatherText' import { slotAt } from '@nalssigak/shared/lib/weatherText'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { createGame, DROP_Y, H, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge' import { createGame, DROP_Y, H, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
@@ -106,6 +107,8 @@ export function CloudMergePage() {
const [next, setNext] = useState(randomLevel) const [next, setNext] = useState(randomLevel)
const nextRef = useRef(next) const nextRef = useRef(next)
const coolRef = useRef(0) const coolRef = useRef(0)
// 이번 판에 떨어뜨린 횟수: 0 이면 아직 시작 전(첫 그림에서 game_start)
const dropsRef = useRef(0)
const [score, setScore] = useState(0) const [score, setScore] = useState(0)
const [best, setBest] = useState(loadBest) const [best, setBest] = useState(loadBest)
const [over, setOver] = useState(false) const [over, setOver] = useState(false)
@@ -124,6 +127,8 @@ export function CloudMergePage() {
canvas.height = H * ratio canvas.height = H * ratio
ctx.scale(ratio, ratio) ctx.scale(ratio, ratio)
let roundNo = 1 let roundNo = 1
let total = 0
dropsRef.current = 0
let base = 0 let base = 0
let flashTimer: ReturnType<typeof setTimeout> | undefined let flashTimer: ReturnType<typeof setTimeout> | undefined
let ticket: Promise<string | undefined> = Promise.resolve(undefined) let ticket: Promise<string | undefined> = Promise.resolve(undefined)
@@ -154,6 +159,7 @@ export function CloudMergePage() {
} }
const game = createGame(windMs, dir, { const game = createGame(windMs, dir, {
onScore: (s) => { onScore: (s) => {
total = s
setScore(s) setScore(s)
if (s - base >= roundTarget(roundNo)) { if (s - base >= roundTarget(roundNo)) {
roundNo += 1 roundNo += 1
@@ -164,6 +170,7 @@ export function CloudMergePage() {
clearTimeout(flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => setFlash(false), 1400) flashTimer = setTimeout(() => setFlash(false), 1400)
void claim(roundNo - 1) void claim(roundNo - 1)
track('game_round', { round: roundNo - 1, score: s, logged_in: loggedIn })
} }
setRoundGot(s - base) setRoundGot(s - base)
if (s > loadBest()) { if (s > loadBest()) {
@@ -173,6 +180,7 @@ export function CloudMergePage() {
}, },
onOver: () => { onOver: () => {
setOver(true) setOver(true)
track('game_over', { round: roundNo, score: total, best: total > 0 && total >= loadBest(), drops: dropsRef.current })
settle() settle()
}, },
}) })
@@ -205,6 +213,8 @@ export function CloudMergePage() {
const onUp = (e: PointerEvent<HTMLCanvasElement>) => { const onUp = (e: PointerEvent<HTMLCanvasElement>) => {
const game = gameRef.current const game = gameRef.current
if (!game || over || performance.now() < coolRef.current) return if (!game || over || performance.now() < coolRef.current) return
if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs })
dropsRef.current += 1
game.drop(nextRef.current, toX(e)) game.drop(nextRef.current, toX(e))
coolRef.current = performance.now() + 450 coolRef.current = performance.now() + 450
nextRef.current = randomLevel() nextRef.current = randomLevel()
+82 -154
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState, type ReactNode } from 'react' import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery } from '@tanstack/react-query'
import { matchMutation, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { reading } from '@nalssigak/shared/api/client/sdk.gen' import { reading } from '@nalssigak/shared/api/client/sdk.gen'
import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen' import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics' import { track } from '../lib/analytics'
@@ -9,7 +9,7 @@ import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { progress, useLevel } from './level' import { progress, useLevel } from './level'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { BIRTH_PLACES, placeLon, useAccountBirth, useBirth, useSaveBirth, validBirth, type Birth } from './sajuBirth' import { BIRTH_PLACES, placeLon, setBirth, useBirth, validBirth, type Birth } from './sajuBirth'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { Ic, TAP44 } from './ui' import { Ic, TAP44 } from './ui'
@@ -17,9 +17,6 @@ const SEEN_KEY = 'nalssigak.b.sajuSeen'
const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] } const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] }
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' } const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' }
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' } const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' }
const HOURS = Array.from({ length: 24 }, (_, i) => i)
const MINUTES = Array.from({ length: 60 }, (_, i) => i)
const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`
const toBody = (b: Birth) => ({ const toBody = (b: Birth) => ({
birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`, birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`,
@@ -49,7 +46,6 @@ function markSeen() {
export function SajuPage() { export function SajuPage() {
const navigate = useNavigate() const navigate = useNavigate()
const birth = useBirth() const birth = useBirth()
const loading = useAccountBirth()
const [editing, setEditing] = useState(false) const [editing, setEditing] = useState(false)
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/')) const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
return ( return (
@@ -63,38 +59,26 @@ export function SajuPage() {
날씨 사주 날씨 사주
</h2> </h2>
</div> </div>
{loading && !birth ? ( {!birth || editing ? <BirthForm initial={birth} onDone={() => setEditing(false)} /> : <Reading birth={birth} onEdit={() => setEditing(true)} />}
<p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">내 생년월일을 불러오는 중이에요…</p>
) : !birth || editing ? (
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
) : (
<Reading birth={birth} onEdit={() => setEditing(true)} />
)}
</div> </div>
) )
} }
function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) { function BirthForm({ initial, onDone }: { initial: Birth | null; onDone: () => void }) {
const { loggedIn } = useAuth()
const save = useSaveBirth()
const [y, setY] = useState(initial ? String(initial.y) : '') const [y, setY] = useState(initial ? String(initial.y) : '')
const [m, setM] = useState(initial ? String(initial.m) : '') const [m, setM] = useState(initial ? String(initial.m) : '')
const [d, setD] = useState(initial ? String(initial.d) : '') const [d, setD] = useState(initial ? String(initial.d) : '')
const [hour, setHour] = useState(initial?.hour != null ? String(initial.hour) : '') const [time, setTime] = useState(initial?.hour != null ? `${String(initial.hour).padStart(2, '0')}:${String(initial.minute ?? 0).padStart(2, '0')}` : '')
const [minute, setMinute] = useState(initial?.minute != null ? String(initial.minute) : '0')
const [place, setPlace] = useState(initial?.place ?? 'seoul') const [place, setPlace] = useState(initial?.place ?? 'seoul')
const [error, setError] = useState('') const [error, setError] = useState('')
const box = 'w-full min-w-0 rounded-2xl border-[1.5px] border-(--line) bg-white px-2 py-3 text-center text-[17px] font-bold' const input = 'min-w-0 flex-1 rounded-2xl border-[1.5px] border-(--line) bg-white px-3 py-3 text-center text-[17px] font-bold'
const pick = cx(box, 'cursor-pointer appearance-none bg-[url("data:image/svg+xml,%3Csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20width=%2712%27%20height=%278%27%3E%3Cpath%20d=%27M1%201l5%205%205-5%27%20fill=%27none%27%20stroke=%27%238a93a6%27%20stroke-width=%272%27/%3E%3C/svg%3E")] bg-[length:12px_8px] bg-[position:right_14px_center] bg-no-repeat pr-8')
const num = (set: (v: string) => void, max: number) => (e: { target: { value: string } }) => (set(e.target.value.replace(/\D/g, '').slice(0, max)), setError(''))
const submit = () => { const save = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)] const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!y || !m || !d) return setError('생년월일을 모두 넣어 주세요') if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요')
if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요') const [hh, mi] = time ? time.split(':').map(Number) : [null, null]
const hh = hour === '' ? null : Number(hour) setBirth({ y: yy, m: mm, d: dd, hour: hh, minute: mi, place, gender: initial?.gender ?? null })
save({ y: yy, m: mm, d: dd, hour: hh, minute: hh == null ? null : Number(minute), place, gender: initial?.gender ?? null }) track('saju_input', { with_time: time !== '' })
track('saju_input', { with_time: hh != null })
onDone() onDone()
} }
@@ -102,63 +86,35 @@ function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDon
<div className="mx-4 mt-4 flex flex-col gap-4 rounded-[24px] bg-white p-5 shadow-[inset_0_-5px_0_var(--shade)]"> <div className="mx-4 mt-4 flex flex-col gap-4 rounded-[24px] bg-white p-5 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="text-center"> <div className="text-center">
<Ic name="yin_yang" className="mx-auto size-14" /> <Ic name="yin_yang" className="mx-auto size-14" />
<p className="m-0 mt-2 font-jua text-[20px] leading-snug"> <p className="m-0 mt-2 font-jua text-[20px] leading-snug">태어난 날의 기운으로<br />오늘 날씨와 맞춰 봐요</p>
내 사주와 오늘 날씨로
<br />
오늘 하루를 봐요
</p>
</div> </div>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0"> <label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">생년월일 (양력)</legend> 생년월일 (양력)
<div className="grid grid-cols-[1.5fr_1fr_1fr] gap-1.5"> <span className="flex gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={num(setY, 4)} className={box} aria-label="년" /> <input inputMode="numeric" placeholder="1995" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={num(setM, 2)} className={box} aria-label="월" /> <input inputMode="numeric" placeholder="3" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={num(setD, 2)} className={box} aria-label="일" /> <input inputMode="numeric" placeholder="14" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="일" />
</div> </span>
</fieldset> </label>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0"> <label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">태어난 시각 (모르면 '모름')</legend> 태어난 시각 (모르면 비워 두세요)
<div className="grid grid-cols-2 gap-1.5"> <input type="time" value={time} onChange={(e) => setTime(e.target.value)} className={cx(input, 'w-full')} />
<select value={hour} onChange={(e) => setHour(e.target.value)} className={pick} aria-label="시"> </label>
<option value="">모름</option> <label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
{HOURS.map((h) => ( 태어난 곳 (시각을 그곳에 맞춰요)
<option key={h} value={h}> <select value={place} onChange={(e) => setPlace(e.target.value)} className={cx(input, 'w-full')}>
{h}시
</option>
))}
</select>
<select value={minute} onChange={(e) => setMinute(e.target.value)} disabled={hour === ''} className={cx(pick, 'disabled:bg-[#f3f5f9] disabled:text-[#a0a8ba]')} aria-label="분">
{MINUTES.map((mi) => (
<option key={mi} value={mi}>
{mi}분
</option>
))}
</select>
</div>
</fieldset>
<label className="flex min-w-0 flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
태어난 지역
<select value={place} onChange={(e) => setPlace(e.target.value)} className={pick}>
{BIRTH_PLACES.map(([k, n]) => ( {BIRTH_PLACES.map(([k, n]) => (
<option key={k} value={k}> <option key={k} value={k}>
{n} {n}
</option> </option>
))} ))}
</select> </select>
<span className="text-xs font-semibold text-(--ink3)">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</span>
</label> </label>
{error && <p className="m-0 text-center text-[13px] font-bold text-[#d9442f]">{error}</p>} {error && <p className="m-0 text-center text-[13px] font-bold text-[#d9442f]">{error}</p>}
<button type="button" onClick={submit} className="cursor-pointer rounded-full bg-(--orange) py-3.5 text-[15px] font-extrabold text-white"> <button type="button" onClick={save} className="cursor-pointer rounded-full bg-(--orange) py-3.5 text-[15px] font-extrabold text-white">
오늘 날씨 사주 보기 내 기운 보기
</button> </button>
{onCancel && ( <p className="m-0 text-center text-xs font-semibold text-(--ink3)">생년월일은 이 기기에만 저장돼요. 계산할 때만 보내고 서버에 남기지 않아요.</p>
<button type="button" onClick={onCancel} className="-mt-2 cursor-pointer py-1 text-[13px] font-extrabold text-(--ink3)">
취소
</button>
)}
<p className="m-0 text-center text-xs font-semibold text-(--ink3)">
{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}
</p>
</div> </div>
) )
} }
@@ -166,17 +122,13 @@ function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDon
function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { region } = useRegion() const { region } = useRegion()
const { loggedIn } = useAuth() const { loggedIn } = useAuth()
const queryClient = useQueryClient()
const level = useLevel().data?.level
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined } const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined }
// 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다
const q = useQuery({ const q = useQuery({
queryKey: ['saju', body, loggedIn, level], queryKey: ['saju', body, loggedIn],
staleTime: 10 * 60_000, staleTime: 10 * 60_000,
queryFn: async () => { queryFn: async () => {
const { data } = await reading({ body }) const { data } = await reading({ body })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju') if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju')
if (loggedIn) queryClient.invalidateQueries({ queryKey: myLevelQueryKey() })
return data return data
}, },
}) })
@@ -195,16 +147,8 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score }) track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score })
}, [r]) }, [r])
if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">사주를 풀고 있어요…</p> if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">기운을 읽는 중이에요…</p>
if (!r?.today || !r.me) if (!r?.today || !r.me) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">지금은 읽지 못했어요. 잠시 뒤에 다시 열어 주세요.</p>
return (
<div className="px-4 py-16 text-center">
<p className="m-0 font-semibold text-(--ink2)">결과를 불러오지 못했어요.</p>
<button type="button" onClick={() => q.refetch()} className="mt-3 cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white">
다시 시도
</button>
</div>
)
const t = r.today const t = r.today
const lock = (key: string) => r.locks?.find((l) => l.key === key) const lock = (key: string) => r.locks?.find((l) => l.key === key)
@@ -217,17 +161,17 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
<p className="m-0 text-center font-bagel text-[60px] leading-none">{t.score}</p> <p className="m-0 text-center font-bagel text-[60px] leading-none">{t.score}</p>
<h3 className="m-0 mt-1.5 text-center font-jua text-[23px] leading-tight font-normal">{t.title}</h3> <h3 className="m-0 mt-1.5 text-center font-jua text-[23px] leading-tight font-normal">{t.title}</h3>
<div className="mt-2.5 flex flex-wrap justify-center gap-1.5 text-[11.5px] font-extrabold"> <div className="mt-2.5 flex flex-wrap justify-center gap-1.5 text-[11.5px] font-extrabold">
<span className="rounded-full bg-[#f3f6fb] px-2.5 py-1">사주 {t.saju_score}점</span> <span className="rounded-full bg-[#f3f6fb] px-2.5 py-1">사주 {t.saju_score}</span>
{t.weather_points != null && ( {t.weather_points != null && (
<span className={cx('rounded-full px-2.5 py-1', t.weather_points >= 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}> <span className={cx('rounded-full px-2.5 py-1', t.weather_points >= 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>
날씨 영향 {t.weather_points >= 0 ? '+' : '−'} 오늘 날씨와 궁합 {t.weather_points >= 0 ? '+' : '−'}
{Math.abs(t.weather_points)}점 {Math.abs(t.weather_points)}
</span> </span>
)} )}
</div> </div>
{(t.why?.length ?? 0) > 0 && ( {(t.why?.length ?? 0) > 0 && (
<details className="mt-2 text-center"> <details className="mt-2 text-center">
<summary className="cursor-pointer text-xs font-bold text-(--ink3)">왜 이 점수인가요? (↑ 올린 것 · ↓ 내린 것)</summary> <summary className="cursor-pointer text-xs font-bold text-(--ink3)">왜 이 점수인가요?</summary>
<ul className="m-0 mt-1.5 list-none p-0 text-xs font-semibold text-(--ink2)"> <ul className="m-0 mt-1.5 list-none p-0 text-xs font-semibold text-(--ink2)">
{t.why!.map((w) => ( {t.why!.map((w) => (
<li key={w}>{w}</li> <li key={w}>{w}</li>
@@ -248,10 +192,9 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
{r.week && <Week r={r} />} {r.week && <Week r={r} />}
{r.money && ( {r.money && (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운"> <Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
{[...r.money.map((l) => ['money_bag', l]), ...(r.work ?? []).map((l) => ['briefcase', l])].map(([icon, l]) => ( {[...r.money.map((l) => ['💰', l]), ...(r.work ?? []).map((l) => ['💼', l])].map(([icon, l]) => (
<p key={l} className="m-0 mt-1.5 flex gap-2 text-[14px] font-semibold first:mt-0"> <p key={l} className="m-0 mt-1 text-[14px] font-semibold first:mt-0">
<Ic name={icon} className="mt-px size-5 shrink-0" /> {icon} {l}
{l}
</p> </p>
))} ))}
</Panel> </Panel>
@@ -281,7 +224,7 @@ function DecisionCard({ c }: { c: SajuCard }) {
<div className="flex gap-3 rounded-[20px] bg-white px-4 py-3 shadow-[inset_0_-4px_0_var(--shade)]"> <div className="flex gap-3 rounded-[20px] bg-white px-4 py-3 shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} className="mt-0.5 size-8 shrink-0" /> <Ic name={CARD_ICON[c.kind] ?? 'sparkles'} className="mt-0.5 size-8 shrink-0" />
<div className="min-w-0"> <div className="min-w-0">
<p className="m-0 text-[12px] font-extrabold text-(--orange)">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</p> <p className="m-0 text-[12px] font-extrabold text-(--orange)">{c.kind === 'when' ? '중요한 일은 이때' : c.title}</p>
<p className="m-0 font-jua text-[17px] leading-snug whitespace-pre-line">{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}</p> <p className="m-0 font-jua text-[17px] leading-snug whitespace-pre-line">{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}</p>
<p className="m-0 mt-0.5 text-[12px] leading-snug font-semibold text-(--ink3)">{c.kind === 'when' ? c.body : c.sub}</p> <p className="m-0 mt-0.5 text-[12px] leading-snug font-semibold text-(--ink3)">{c.kind === 'when' ? c.body : c.sub}</p>
</div> </div>
@@ -293,7 +236,7 @@ function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const me = r.me! const me = r.me!
const cols = [...me.pillars].reverse() const cols = [...me.pillars].reverse()
return ( return (
<Panel icon={me.scene_icon} title={`내 기운 · ${me.scene.replace(/ 기운$/, '')}`} right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}> <Panel icon={me.scene_icon} title={`내 기운 · ${me.scene}`} right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}>
<p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p> <p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p>
<div className="mt-3 grid grid-cols-4 gap-1.5 text-center"> <div className="mt-3 grid grid-cols-4 gap-1.5 text-center">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => ( {(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
@@ -306,15 +249,15 @@ function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
</> </>
) : ( ) : (
<> <>
<span className="grid flex-1 place-items-center rounded-xl bg-[#f1f3f7] text-[12px] font-extrabold text-[#a0a8ba]">시각 모름</span> <span className="rounded-xl bg-[#f1f3f7] py-3 text-[14px] font-extrabold text-[#a0a8ba]">?</span>
<span className="rounded-xl bg-[#f1f3f7] py-3 text-[14px] font-extrabold text-[#a0a8ba]">?</span>
</> </>
)} )}
</div> </div>
))} ))}
</div> </div>
<p className="m-0 mt-2 text-[11.5px] font-semibold text-(--ink3)">태어난 연·월·일·시의 여덟 글자(사주팔자)예요. 색은 나무·불·흙·쇠·물 다섯 기운이에요.</p> {(me.need?.length ?? 0) > 0 && <p className="m-0 mt-2.5 text-[13px] font-bold">내 기운에 필요한 날씨: {me.need!.join(' · ')}</p>}
{(me.need?.length ?? 0) > 0 && <p className="m-0 mt-2 text-[13px] font-bold">내 기운에 좋은 날씨: {me.need!.join(' · ')}</p>} {me.jeol_warning && <p className="m-0 mt-1 text-xs font-semibold text-[#c2471b]">태어난 날 절기가 바뀌어요. 시각을 넣으면 더 정확해요.</p>}
{me.jeol_warning && <p className="m-0 mt-1 text-xs font-semibold text-[#c2471b]">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</p>}
</Panel> </Panel>
) )
} }
@@ -355,13 +298,13 @@ function Locked({ locks }: { locks: SajuLock[] }) {
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Ic name="locked" className="size-8 shrink-0" /> <Ic name="locked" className="size-8 shrink-0" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16px]">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</p> <p className="m-0 font-jua text-[16px]">{loggedIn ? `다음에 열려요: ${next.name}` : '각을 모으면 차례로 열려요'}</p>
<p className="m-0 text-xs font-bold text-(--ink2)"> <p className="m-0 text-xs font-bold text-(--ink2)">
{loggedIn ? (close ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"} {loggedIn ? `Lv.${next.level}에서 열려요${close ? ` · ${level.next_points! - level.points}각 남았어요` : ''}` : '출석·사주·좋아요로 모은 각은 로그인해야 쌓여요'}
</p> </p>
</div> </div>
<button type="button" onClick={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-xs font-extrabold text-white"> <button type="button" onClick={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-xs font-extrabold text-white">
{loggedIn ? '각 모으는 법' : '로그인'} {loggedIn ? '각 모으기' : '로그인'}
</button> </button>
</div> </div>
{close && ( {close && (
@@ -382,63 +325,55 @@ function Locked({ locks }: { locks: SajuLock[] }) {
function Week({ r }: { r: ResSaju }) { function Week({ r }: { r: ResSaju }) {
return ( return (
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름"> <Panel id="saju_week" icon="spiral_calendar" title="이번 주 흐름">
<ol className="m-0 flex list-none flex-col gap-1 p-0"> <ol className="m-0 flex list-none flex-col gap-1 p-0">
{r.week!.map((d) => ( {r.week!.map((d) => (
<li key={d.day} className={cx('flex items-center gap-2 rounded-xl px-2 py-1.5 text-[13px] font-bold', d.best && 'bg-[#fff6ef]')}> <li key={d.day} className={cx('flex items-center gap-2 rounded-xl px-2 py-1.5 text-[13px] font-bold', d.best && 'bg-[#fff6ef]')}>
<span className="w-[66px] shrink-0 whitespace-nowrap">{dayWord(d.day, d.weekday)}</span> <span className="w-14 shrink-0">
{d.weekday} {Number(d.day.slice(8, 10))}일
</span>
{d.icon && <Ic name={d.icon} className="size-6 shrink-0" />} {d.icon && <Ic name={d.icon} className="size-6 shrink-0" />}
<span className="w-[52px] shrink-0 whitespace-nowrap text-(--ink2)">{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}</span> <span className="w-14 shrink-0 text-(--ink2)">{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}</span>
<span className="min-w-0 flex-1 truncate text-[12.5px] text-(--ink2)">{d.title}</span> <span className="min-w-0 flex-1 truncate text-(--ink2)">{d.title}</span>
<b className={cx('font-bagel text-[15px] font-normal', d.best ? 'text-(--orange)' : '')}>{d.score}</b> <b className={cx('font-bagel text-[15px] font-normal', d.best ? 'text-(--orange)' : '')}>{d.score}</b>
</li> </li>
))} ))}
</ol> </ol>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</p> <p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">점수는 그날 사주와 예보로 계산해요. 주황색이 이번 주 가장 좋은 날이에요.</p>
</Panel> </Panel>
) )
} }
function Love({ r, birth }: { r: ResSaju; birth: Birth }) { function Love({ r, birth }: { r: ResSaju; birth: Birth }) {
const love = r.love! const love = r.love!
const save = useSaveBirth() const pick = (g: 'M' | 'F' | null) => setBirth({ ...birth, gender: g })
const pick = (g: 'M' | 'F' | null) => save({ ...birth, gender: g })
const chip = 'cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1'
return ( return (
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운"> <Panel id="saju_love" icon="red_heart" title="이번 주 연애운">
{love.good ? ( {love.good ? (
<div className="rounded-xl bg-[#fff0f3] px-3 py-2.5"> <div className="rounded-xl bg-[#fff0f3] px-3 py-2.5">
<p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운이 좋은 날</p> <p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운 좋은 날</p>
<p className="m-0 font-jua text-[17px]"> <p className="m-0 font-jua text-[17px]">
{dayWord(love.good.day, love.good.weekday)} {love.good.weekday}요일 {Number(love.good.day.slice(8, 10))}일{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</p> </p>
<p className="m-0 text-[13px] font-semibold">{love.good.body}</p> <p className="m-0 text-[13px] font-semibold">{love.good.body}</p>
<p className="m-0 text-[11.5px] font-semibold text-(--ink3)">{love.good.why}</p> <p className="m-0 text-[11.5px] font-semibold text-(--ink3)">{love.good.why}</p>
</div> </div>
) : ( ) : (
<p className="m-0 text-[13px] font-semibold text-(--ink2)">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</p> <p className="m-0 text-[13px] font-semibold text-(--ink2)">이번 주엔 연애 기운이 특별히 드는 날이 없어요.</p>
)} )}
{love.caution && ( {love.caution && (
<p className="m-0 mt-2 text-[13px] font-semibold"> <p className="m-0 mt-2 text-[13px] font-semibold">
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <span className="text-(--ink3)">· {love.caution.why}</span> 조심할 날: {love.caution.weekday}요일 — {love.caution.body} <span className="text-(--ink3)">({love.caution.why})</span>
</p> </p>
)} )}
{love.gender_known ? ( {!love.gender_known && (
<p className="m-0 mt-2.5 text-xs font-bold text-(--ink3)"> <div className="mt-2.5 flex items-center gap-1.5 text-xs font-bold text-(--ink2)">
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '} 성별을 고르면 이성 기운까지 봐요
<button type="button" onClick={() => pick(null)} className="cursor-pointer font-extrabold text-(--orange)"> <button type="button" onClick={() => pick('M')} className="cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1">
빼고 보기 남
</button> </button>
</p> <button type="button" onClick={() => pick('F')} className="cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1">
) : ( 여
<div className="mt-2.5 flex flex-wrap items-center gap-1.5 text-xs font-bold text-(--ink2)">
성별을 고르면 이성 인연(재성·관성)까지 봐요
<button type="button" onClick={() => pick('M')} className={chip}>
남성
</button>
<button type="button" onClick={() => pick('F')} className={chip}>
여성
</button> </button>
</div> </div>
)} )}
@@ -450,15 +385,11 @@ function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResS
return ( return (
<Panel id={id} icon={icon} title={p.label}> <Panel id={id} icon={icon} title={p.label}>
<p className="m-0 font-jua text-[17px]"> <p className="m-0 font-jua text-[17px]">
{p.title} <span className="text-[13px] text-(--ink3)">({p.ten_god})</span> {p.title} <span className="text-[13px] text-(--ink3)">({p.pillar} · {p.ten_god})</span>
</p> </p>
<p className="m-0 mt-0.5 text-[13.5px] font-semibold">{p.body}</p> <p className="m-0 mt-0.5 text-[13.5px] font-semibold">{p.body}</p>
{(p.months?.length ?? 0) > 0 && <p className="m-0 mt-1.5 text-[13.5px] font-bold">{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}</p>} {(p.months?.length ?? 0) > 0 && <p className="m-0 mt-1.5 text-[13.5px] font-bold">잘 맞는 달: {p.months!.map((m) => `${m}월`).join(' · ')}</p>}
{p.notes?.map((n) => ( {(p.notes?.length ?? 0) > 0 && <p className="m-0 mt-1 text-xs font-semibold text-(--ink3)">{p.notes!.join(' · ')}</p>}
<p key={n} className="m-0 mt-1 text-xs font-semibold text-(--ink3)">
{n}
</p>
))}
</Panel> </Panel>
) )
} }
@@ -471,11 +402,10 @@ function Match({ birth }: { birth: Birth }) {
const [error, setError] = useState('') const [error, setError] = useState('')
const run = useMutation({ ...matchMutation() }) const run = useMutation({ ...matchMutation() })
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined
const input = 'w-full min-w-0 rounded-xl border-[1.5px] border-(--line) bg-white px-1 py-2 text-center text-[15px] font-bold' const input = 'min-w-0 flex-1 rounded-xl border-[1.5px] border-(--line) bg-white px-2 py-2 text-center text-[15px] font-bold'
const go = () => { const go = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)] const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!y || !m || !d) return setError('상대 생년월일을 모두 넣어 주세요') if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요')
if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요')
setError('') setError('')
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${yy}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`, longitude: 126.98 } } }) run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${yy}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`, longitude: 126.98 } } })
} }
@@ -490,7 +420,7 @@ function Match({ birth }: { birth: Birth }) {
</button> </button>
</p> </p>
<p className="m-0 font-jua text-[19px]"> <p className="m-0 font-jua text-[19px]">
{res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}점</span> {res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}</span>
</p> </p>
{res.lines?.map((l) => ( {res.lines?.map((l) => (
<p key={l} className="m-0 mt-1 text-[13.5px] font-semibold"> <p key={l} className="m-0 mt-1 text-[13.5px] font-semibold">
@@ -499,25 +429,23 @@ function Match({ birth }: { birth: Birth }) {
))} ))}
{res.day && ( {res.day && (
<p className="m-0 mt-2 rounded-xl bg-[#fff6ef] px-3 py-2 text-[13.5px] font-bold"> <p className="m-0 mt-2 rounded-xl bg-[#fff6ef] px-3 py-2 text-[13.5px] font-bold">
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)} 이번 주 같이 나가기 좋은 날: {res.day.weekday}요일 {Number(res.day.day.slice(8, 10))}일{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</p> </p>
)} )}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 기운: {res.friend_scene}</p> <p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 기운: {res.friend_scene}</p>
</> </>
) : ( ) : (
<> <>
<p className="m-0 mb-2 text-[13px] font-semibold text-(--ink2)">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</p> <p className="m-0 mb-2 text-[13px] font-semibold text-(--ink2)">상대 생년월일(양력)을 넣으면 둘의 사이와 이번 주 같이 나가기 좋은 날을 봐요.</p>
<div className="grid grid-cols-[1.5fr_1fr_1fr_auto] gap-1.5"> <div className="flex gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" /> <input inputMode="numeric" placeholder="1996" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" /> <input inputMode="numeric" placeholder="11" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" /> <input inputMode="numeric" placeholder="2" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
<button type="button" onClick={go} disabled={run.isPending} className="shrink-0 cursor-pointer rounded-xl bg-(--orange) px-3 text-[14px] font-extrabold text-white"> <button type="button" onClick={go} disabled={run.isPending} className="shrink-0 cursor-pointer rounded-xl bg-(--orange) px-3 text-[14px] font-extrabold text-white">
보기 보기
</button> </button>
</div> </div>
{error && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">{error}</p>} {error && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">{error}</p>}
{(run.isError || (run.data && !run.data.result?.success)) && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</p>}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 생년월일은 저장하지 않아요.</p> <p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 생년월일은 저장하지 않아요.</p>
</> </>
)} )}
+1 -34
View File
@@ -37,8 +37,7 @@ import { InstallSheet } from './installBanner'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib' import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet, MyGakSheet } from './myGak' import { MixSheet, MyGakSheet } from './myGak'
import { TarotSheet } from './fortune' import { TarotSheet } from './fortune'
import { LevelCard, LevelSheet, LevelUpSheet, useCloseAndGo, useShareReward } from './level' import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level'
import { BIRTH_PLACES, useAccountBirth, useBirth, useSaveBirth } from './sajuBirth'
import { ownPage, useRegion } from './regionContext' import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy' import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext' import { useSky } from './skyContext'
@@ -49,34 +48,6 @@ import { HeartIcon } from './svg'
import { MyTalks, TalkSheet } from './talk' import { MyTalks, TalkSheet } from './talk'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui' import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
/** 내 정보: 계정에 저장한 생년월일 (날씨 사주) */
function MyBirth() {
useAccountBirth()
const birth = useBirth()
const save = useSaveBirth()
const go = useCloseAndGo()
const place = BIRTH_PLACES.find(([k]) => k === birth?.place)?.[1]
return (
<section aria-label="내 생년월일" className="flex items-center gap-2.5 rounded-2xl bg-[#f6f8fc] px-3.5 py-3">
<Ic name="yin_yang" className="size-7 shrink-0" />
<div className="min-w-0 flex-1">
<p className="m-0 text-[13px] font-extrabold">내 생년월일</p>
<p className="m-0 truncate text-xs font-semibold text-(--ink2)">
{birth ? `${birth.y}.${birth.m}.${birth.d}${birth.hour != null ? ` ${birth.hour}시 ${birth.minute ?? 0}분` : ''}${place ? ` · ${place}` : ''}` : '넣어 두면 날씨 사주를 바로 볼 수 있어요'}
</p>
</div>
<button type="button" onClick={() => go('/saju')} className="shrink-0 cursor-pointer text-xs font-extrabold text-(--orange)">
{birth ? '사주 보기' : '넣기'}
</button>
{birth && (
<button type="button" onClick={() => save(null)} className="shrink-0 cursor-pointer text-xs font-extrabold text-(--ink3)">
지우기
</button>
)}
</section>
)
}
export function SheetProvider({ children }: { children: ReactNode }) { export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null) const [state, setState] = useState<SheetState>(null)
// 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다 // 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다
@@ -156,14 +127,11 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement const root = document.documentElement
const before = root.style.overflow const before = root.style.overflow
root.style.overflow = 'hidden' root.style.overflow = 'hidden'
// 창 안에서 끝까지 밀어도 뒤 페이지로 넘어가지 않게
root.style.overscrollBehavior = 'none'
// 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다 // 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS) const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => { return () => {
clearTimeout(pause) clearTimeout(pause)
root.style.overflow = before root.style.overflow = before
root.style.overscrollBehavior = ''
root.classList.remove('b-sheet-open') root.classList.remove('b-sheet-open')
} }
}, [isOpen]) }, [isOpen])
@@ -1233,7 +1201,6 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p> <p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div> </div>
<LevelCard /> <LevelCard />
<MyBirth />
{installable && ( {installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)"> <button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가 📲 홈 화면에 추가
+1 -1
View File
@@ -174,7 +174,7 @@ export function TarotSheet() {
} }
return ( return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pb-2"> <div className="px-4 pb-2">
{!card ? ( {!card ? (
<button <button
type="button" type="button"
+9 -18
View File
@@ -13,14 +13,8 @@ import { Ic } from './ui'
const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' } const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' }
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' } const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' }
// 받침 있으면 a, 없으면 b: josa('연애운', '이', '가') → '연애운이'
const josa = (w: string, a: string, b: string) => {
const c = w.charCodeAt(w.length - 1) - 0xac00
return w + (c >= 0 && c < 11172 && c % 28 === 0 ? b : a)
}
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다 // 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다
export function useCloseAndGo() { function useCloseAndGo() {
const { close } = useSheet() const { close } = useSheet()
const navigate = useNavigate() const navigate = useNavigate()
return (to: string) => { return (to: string) => {
@@ -131,11 +125,8 @@ export function LevelCard({ link = true }: { link?: boolean }) {
</div> </div>
<div className="mt-1.5 flex items-center justify-between gap-2 text-xs font-bold text-(--ink2)"> <div className="mt-1.5 flex items-center justify-between gap-2 text-xs font-bold text-(--ink2)">
<span> <span>
{level.next_points == null {level.next_points != null ? `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}` : '가장 높은 레벨이에요'}
? '가장 높은 레벨이에요' {unlock.length > 0 && <b className="text-(--orange)"> · {unlock.join(', ')}</b>}
: unlock.length > 0
? `${level.next_points - level.points}각 더 모으면 ${josa(unlock.join(', '), '이', '가')} 열려요`
: `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}`}
</span> </span>
{link && ( {link && (
<button type="button" onClick={() => open({ type: 'level' })} className="shrink-0 cursor-pointer text-(--orange)"> <button type="button" onClick={() => open({ type: 'level' })} className="shrink-0 cursor-pointer text-(--orange)">
@@ -154,7 +145,7 @@ export function LevelSheet() {
if (!level) return null if (!level) return null
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {}) const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {})
return ( return (
<div className="flex flex-1 flex-col gap-4 overflow-auto overscroll-contain px-4 pt-3.5 pb-4"> <div className="flex flex-col gap-4 px-4 pb-4">
<LevelCard link={false} /> <LevelCard link={false} />
<section> <section>
<h4 className="m-0 mb-2 text-sm font-extrabold">오늘 받을 수 있는 각</h4> <h4 className="m-0 mb-2 text-sm font-extrabold">오늘 받을 수 있는 각</h4>
@@ -171,14 +162,14 @@ export function LevelSheet() {
<span className={cx('grid size-5 place-items-center rounded-full text-[11px] text-white', done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]')}>{done ? '✓' : ''}</span> <span className={cx('grid size-5 place-items-center rounded-full text-[11px] text-white', done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]')}>{done ? '✓' : ''}</span>
<span className={cx(done && 'text-(--ink3) line-through')}>{a.name}</span> <span className={cx(done && 'text-(--ink3) line-through')}>{a.name}</span>
<span className="ml-auto font-bagel text-[13px] font-normal text-(--orange)"> <span className="ml-auto font-bagel text-[13px] font-normal text-(--orange)">
{done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`} {a.earned > 0 && a.cap > a.points ? `${a.earned}/${a.cap}` : `+${a.points}`}각
</span> </span>
{to && !done && <span className="text-(--ink3)">›</span>} {to && !done && <span className="text-(--ink3)">›</span>}
</li> </li>
) )
})} })}
</ul> </ul>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">{level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'}</p> <p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">{level.streak > 0 ? `${level.streak}일 이어 출석 · 7일마다 +50각` : '7일 이어 출석하면 +50각'}</p>
</section> </section>
<section> <section>
<h4 className="m-0 mb-2 text-sm font-extrabold">레벨이 오르면 열려요</h4> <h4 className="m-0 mb-2 text-sm font-extrabold">레벨이 오르면 열려요</h4>
@@ -192,7 +183,7 @@ export function LevelSheet() {
<b className="block text-[13.5px] font-extrabold"> <b className="block text-[13.5px] font-extrabold">
Lv.{lv} {name} <span className="font-semibold text-(--ink3)">· {points}각</span> Lv.{lv} {name} <span className="font-semibold text-(--ink3)">· {points}각</span>
</b> </b>
<span className="block text-xs font-semibold text-(--ink2)">{lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')}</span> <span className="block text-xs font-semibold text-(--ink2)">{lv === 1 ? '지금 있는 기능 전부' : (steps[lv] ?? []).join(', ')}</span>
</span> </span>
</li> </li>
) )
@@ -212,12 +203,12 @@ export function LevelUpSheet({ level: lv }: { level: number }) {
const opened = unlocks.map((u) => u.name) const opened = unlocks.map((u) => u.name)
const name = level?.levels?.find((l) => l.level === lv)?.name const name = level?.levels?.find((l) => l.level === lv)?.name
return ( return (
<div className="flex flex-1 flex-col items-center gap-2 overflow-auto overscroll-contain px-6 pt-2 pb-6 text-center"> <div className="flex flex-col items-center gap-2 px-6 pt-2 pb-6 text-center">
<Ic name={levelIcon(lv)} className="size-24" /> <Ic name={levelIcon(lv)} className="size-24" />
<b className="font-jua text-[28px] font-normal"> <b className="font-jua text-[28px] font-normal">
Lv.{lv} {name} Lv.{lv} {name}
</b> </b>
{opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요</p>} {opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">새로 열렸어요: {opened.join(', ')}</p>}
{unlocks.length > 0 && ( {unlocks.length > 0 && (
<button type="button" onClick={() => go(`/saju#${unlocks[0].key}`)} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white"> <button type="button" onClick={() => go(`/saju#${unlocks[0].key}`)} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
{opened[0]} 보러 가기 {opened[0]} 보러 가기
+2 -48
View File
@@ -1,11 +1,6 @@
import { useEffect, useSyncExternalStore } from 'react' import { useSyncExternalStore } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { getBirthQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { deleteBirth, getBirth, putBirth } from '@nalssigak/shared/api/client/sdk.gen'
import type { SajuSavedBirth } from '@nalssigak/shared/api/client/types.gen'
import { useAuth } from './authContext'
/** 날씨 사주에 쓰는 태어난 정보. 기기에 두고, 로그인했으면 계정에도 저장한다 */ /** 날씨 사주에 쓰는 태어난 정보. 이 기기에만 저장하고, 계산할 때만 서버에 보낸다(서버는 남기지 않는다) */
export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null } export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null }
const KEY = 'nalssigak.b.birth' const KEY = 'nalssigak.b.birth'
@@ -63,47 +58,6 @@ export function setBirth(b: Birth | null) {
export const useBirth = () => useSyncExternalStore(subscribe, () => birth) export const useBirth = () => useSyncExternalStore(subscribe, () => birth)
const pad = (n: number) => String(n).padStart(2, '0')
const toSaved = (b: Birth): SajuSavedBirth => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
place: b.place,
gender: b.gender === 'M' ? 'male' : b.gender === 'F' ? 'female' : undefined,
})
const fromSaved = (s: SajuSavedBirth): Birth => {
const [y, m, d] = s.birth_date.split('-').map(Number)
const [hour, minute] = s.birth_time ? s.birth_time.split(':').map(Number) : [null, null]
return { y, m, d, hour, minute, place: s.place ?? 'seoul', gender: s.gender === 'male' ? 'M' : s.gender === 'female' ? 'F' : null }
}
/** 로그인했으면 계정의 생년월일을 기기로 가져온다. 계정엔 없고 기기에만 있으면 계정으로 올린다 */
export function useAccountBirth() {
const { loggedIn } = useAuth()
const q = useQuery({ queryKey: getBirthQueryKey(), enabled: loggedIn, staleTime: Infinity, queryFn: async () => (await getBirth()).data })
useEffect(() => {
if (!loggedIn || !q.data?.result?.success) return
if (q.data.birth) setBirth(fromSaved(q.data.birth))
else if (birth) putBirth({ body: toSaved(birth) }).catch((e) => console.warn('[saju] 계정에 올리지 못함', e))
}, [loggedIn, q.data])
return loggedIn && q.isPending
}
/** 생년월일 저장·지우기: 기기에 두고, 로그인했으면 계정에도 */
export function useSaveBirth() {
const { loggedIn } = useAuth()
const queryClient = useQueryClient()
return async (b: Birth | null) => {
setBirth(b)
if (!loggedIn) return
try {
const { data } = b ? await putBirth({ body: toSaved(b) }) : await deleteBirth()
if (data.result?.success) queryClient.setQueryData(getBirthQueryKey(), data)
} catch (e) {
console.warn('[saju] 계정에 저장하지 못함', e)
}
}
}
/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */ /** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */
export function validBirth(y: number, m: number, d: number) { export function validBirth(y: number, m: number, d: number) {
const at = new Date(Date.UTC(y, m - 1, d)) const at = new Date(Date.UTC(y, m - 1, d))
+3
View File
@@ -33,6 +33,9 @@ type Events = {
today_icon: { icon: string } today_icon: { icon: string }
saju_input: { with_time: boolean } saju_input: { with_time: boolean }
saju_view: { scene: string; score: number } saju_view: { scene: string; score: number }
game_start: { again: boolean; logged_in: boolean; wind_ms: number }
game_round: { round: number; score: number; logged_in: boolean }
game_over: { round: number; score: number; best: boolean; drops: number }
toss_intro_start: Record<string, never> toss_intro_start: Record<string, never>
install_banner_close: Record<string, never> install_banner_close: Record<string, never>
} }
+2 -54
View File
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen'; import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, 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, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen'; import { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, 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, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AttendData, AttendError, AttendResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteBirthData, DeleteBirthError, DeleteBirthResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, DrawFortuneData, DrawFortuneError, DrawFortuneResponse, GameRoundData, GameRoundError, GameRoundResponse, GameStartData, GameStartError, GameStartResponse, GetArticleData, GetArticleError, GetArticleResponse, GetBirthData, GetBirthError, GetBirthResponse, 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, MatchData, MatchError, MatchResponse, MeData, MeError, MeResponse, MyLevelData, MyLevelError, MyLevelResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, PutBirthData, PutBirthError, PutBirthResponse, ReadingData, ReadingError, ReadingResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, SharedData, SharedError, SharedResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen'; import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AttendData, AttendError, AttendResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, DrawFortuneData, DrawFortuneError, DrawFortuneResponse, GameRoundData, GameRoundError, GameRoundResponse, GameStartData, GameStartError, GameStartResponse, 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, MatchData, MatchError, MatchResponse, MeData, MeError, MeResponse, MyLevelData, MyLevelError, MyLevelResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, ReadingData, ReadingError, ReadingResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, SharedData, SharedError, SharedResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen';
export type QueryKey<TOptions extends Options> = [ export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & { Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -1158,58 +1158,6 @@ export const readingMutation = (options?: Partial<Options<ReadingData>>): UseMut
return mutationOptions; return mutationOptions;
}; };
/**
* 계정에 저장한 내 생년월일 지우기
*/
export const deleteBirthMutation = (options?: Partial<Options<DeleteBirthData>>): UseMutationOptions<DeleteBirthResponse, DeleteBirthError, Options<DeleteBirthData>> => {
const mutationOptions: UseMutationOptions<DeleteBirthResponse, DeleteBirthError, Options<DeleteBirthData>> = {
mutationFn: async (fnOptions) => {
const { data } = await deleteBirth({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getBirthQueryKey = (options?: Options<GetBirthData>) => createQueryKey('getBirth', options);
/**
* 계정에 저장한 내 생년월일 (없으면 birth 없음)
*/
export const getBirthOptions = (options?: Options<GetBirthData>) => queryOptions<GetBirthResponse, GetBirthError, GetBirthResponse, ReturnType<typeof getBirthQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getBirth({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getBirthQueryKey(options)
});
/**
* 내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)
*/
export const putBirthMutation = (options?: Partial<Options<PutBirthData>>): UseMutationOptions<PutBirthResponse, PutBirthError, Options<PutBirthData>> => {
const mutationOptions: UseMutationOptions<PutBirthResponse, PutBirthError, Options<PutBirthData>> = {
mutationFn: async (fnOptions) => {
const { data } = await putBirth({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/** /**
* 궁합 (계정 레벨 5부터): 일간·일지·기운으로 본 사이, 이번 주 둘 다 좋은 날. 생년월일은 저장하지 않는다 * 궁합 (계정 레벨 5부터): 일간·일지·기운으로 본 사이, 이번 주 둘 다 좋은 날. 생년월일은 저장하지 않는다
*/ */
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts // This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, 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, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen'; export { addComment, addMyGak, addTalk, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, 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, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AttendData, type AttendError, type AttendErrors, type AttendResponse, type AttendResponses, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DayLogData, type DeleteBirthData, type DeleteBirthError, type DeleteBirthErrors, type DeleteBirthResponse, type DeleteBirthResponses, 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 GameRoundData, type GameRoundError, type GameRoundErrors, type GameRoundResponse, type GameRoundResponses, type GameStartData, type GameStartError, type GameStartErrors, type GameStartResponse, type GameStartResponses, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetBirthData, type GetBirthError, type GetBirthErrors, type GetBirthResponse, type GetBirthResponses, 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 GoogleLogLine truncated export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AttendData, type AttendError, type AttendErrors, type AttendResponse, type AttendResponses, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DayLogData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type DrawFortuneData, type DrawFortuneError, type DrawFortuneErrors, type DrawFortuneResponse, type DrawFortuneResponses, type ErrorInfo, type EventData, type Factor, type FortuneCard, type FortuneLuck, type FortunePlace, type GakSlide, type GameRoundData, type GameRoundError, type GameRoundErrors, type GameRoundResponse, type GameRoundResponses, type GameStartData, type GameStartError, type GameStartErrors, type GameStartResponse, type GameStartResponses, 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, tyLine truncated
+1 -23
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client'; import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen'; import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AttendData, AttendErrors, AttendResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteBirthData, DeleteBirthErrors, DeleteBirthResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, DrawFortuneData, DrawFortuneErrors, DrawFortuneResponses, GameRoundData, GameRoundErrors, GameRoundResponses, GameStartData, GameStartErrors, GameStartResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetBirthData, GetBirthErrors, GetBirthResponses, 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, MatchData, MatchErrors, MatchResponses, MeData, MeErrors, MeResponses, MyLevelData, MyLevelErrors, MyLevelResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, PutBirthData, PutBirthErrors, PutBirthResponses, ReadingData, ReadingErrors, ReadingResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, SharedData, SharedErrors, SharedResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UpLine truncated import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AttendData, AttendErrors, AttendResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, DrawFortuneData, DrawFortuneErrors, DrawFortuneResponses, GameRoundData, GameRoundErrors, GameRoundResponses, GameStartData, GameStartErrors, GameStartResponses, 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, MatchData, MatchErrors, MatchResponses, MeData, MeErrors, MeResponses, MyLevelData, MyLevelErrors, MyLevelResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, ReadingData, ReadingErrors, ReadingResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, SharedData, SharedErrors, SharedResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & { export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/** /**
@@ -425,28 +425,6 @@ export const reading = <ThrowOnError extends boolean = true>(options: Options<Re
} }
}); });
/**
* 계정에 저장한 내 생년월일 지우기
*/
export const deleteBirth = <ThrowOnError extends boolean = true>(options?: Options<DeleteBirthData, ThrowOnError>): RequestResult<DeleteBirthResponses, DeleteBirthErrors, ThrowOnError> => (options?.client ?? client).delete<DeleteBirthResponses, DeleteBirthErrors, ThrowOnError>({ url: '/v1/saju/birth', ...options });
/**
* 계정에 저장한 내 생년월일 (없으면 birth 없음)
*/
export const getBirth = <ThrowOnError extends boolean = true>(options?: Options<GetBirthData, ThrowOnError>): RequestResult<GetBirthResponses, GetBirthErrors, ThrowOnError> => (options?.client ?? client).get<GetBirthResponses, GetBirthErrors, ThrowOnError>({ url: '/v1/saju/birth', ...options });
/**
* 내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)
*/
export const putBirth = <ThrowOnError extends boolean = true>(options: Options<PutBirthData, ThrowOnError>): RequestResult<PutBirthResponses, PutBirthErrors, ThrowOnError> => (options.client ?? client).put<PutBirthResponses, PutBirthErrors, ThrowOnError>({
url: '/v1/saju/birth',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/** /**
* 궁합 (계정 레벨 5부터): 일간·일지·기운으로 본 사이, 이번 주 둘 다 좋은 날. 생년월일은 저장하지 않는다 * 궁합 (계정 레벨 5부터): 일간·일지·기운으로 본 사이, 이번 주 둘 다 좋은 날. 생년월일은 저장하지 않는다
*/ */
-157
View File
@@ -2157,32 +2157,6 @@ export type ReqSaju = {
gender?: 'male' | 'female' | null; gender?: 'male' | 'female' | null;
}; };
/**
* Req_SajuBirth
*/
export type ReqSajuBirth = {
/**
* Birth Date
*/
birth_date: string;
/**
* Birth Time
*
* HH:MM (모르면 없음)
*/
birth_time?: string | null;
/**
* Place
*
* 태어난 곳 키 (seoul 등)
*/
place?: string | null;
/**
* Gender
*/
gender?: 'male' | 'female' | null;
};
/** /**
* Req_SajuMatch * Req_SajuMatch
*/ */
@@ -3039,18 +3013,6 @@ export type ResSaju = {
locks?: Array<SajuLock>; locks?: Array<SajuLock>;
}; };
/**
* Res_SajuBirth
*/
export type ResSajuBirth = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
birth?: SajuSavedBirth | null;
};
/** /**
* Res_SajuMatch * Res_SajuMatch
*/ */
@@ -3847,32 +3809,6 @@ export type SajuPillar = {
branch_element: string; branch_element: string;
}; };
/**
* SajuSavedBirth
*/
export type SajuSavedBirth = {
/**
* Birth Date
*/
birth_date: string;
/**
* Birth Time
*
* HH:MM (모르면 없음)
*/
birth_time?: string | null;
/**
* Place
*
* 태어난 곳 키 (seoul 등)
*/
place?: string | null;
/**
* Gender
*/
gender?: 'male' | 'female' | null;
};
/** /**
* SajuToday * SajuToday
*/ */
@@ -6892,99 +6828,6 @@ export type ReadingResponses = {
export type ReadingResponse = ReadingResponses[keyof ReadingResponses]; export type ReadingResponse = ReadingResponses[keyof ReadingResponses];
export type DeleteBirthData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/saju/birth';
};
export type DeleteBirthErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type DeleteBirthError = DeleteBirthErrors[keyof DeleteBirthErrors];
export type DeleteBirthResponses = {
/**
* Successful Response
*/
200: ResSajuBirth;
};
export type DeleteBirthResponse = DeleteBirthResponses[keyof DeleteBirthResponses];
export type GetBirthData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/saju/birth';
};
export type GetBirthErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetBirthError = GetBirthErrors[keyof GetBirthErrors];
export type GetBirthResponses = {
/**
* Successful Response
*/
200: ResSajuBirth;
};
export type GetBirthResponse = GetBirthResponses[keyof GetBirthResponses];
export type PutBirthData = {
body: ReqSajuBirth;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/saju/birth';
};
export type PutBirthErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type PutBirthError = PutBirthErrors[keyof PutBirthErrors];
export type PutBirthResponses = {
/**
* Successful Response
*/
200: ResSajuBirth;
};
export type PutBirthResponse = PutBirthResponses[keyof PutBirthResponses];
export type MatchData = { export type MatchData = {
body: ReqSajuMatch; body: ReqSajuMatch;
headers?: { headers?: {