diff --git a/.env.example b/.env.example index 748ceef..5812d14 100644 --- a/.env.example +++ b/.env.example @@ -14,10 +14,9 @@ INSTAGRAM_USER_ID= PUBLIC_BASE_URL=https://weather.o2o.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_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개) +# 비우면 채널 쇼츠 RSS(키 없음, 최신 15개)로 받는다 YOUTUBE_API_KEY= YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w -YOUTUBE_SHORTS= # ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다) DB_HOST=localhost diff --git a/TODO.md b/TODO.md index 3367bca..619fd9b 100644 --- a/TODO.md +++ b/TODO.md @@ -59,7 +59,7 @@ | [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` | | [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | | | [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | | -| [ ] | 오늘 화면 쇼츠 줄 — 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` | +| [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` | | [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` | | [ ] | 쇼츠를 올린 직후 목록 갱신(`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` | @@ -98,6 +98,7 @@ | [ ] | 계정 레벨 — main 병합(10/28, 배포 남음). 사용자 결정 10/28: **레벨 제도**(포인트 소비형 아님). 단위는 '각'(출석 +10각 등 서비스 전체 행동으로 적립), 레벨은 모은 총량 기준이라 나중에 각을 쓰는 기능을 붙여도 안 내려감. 지금 있는 기능·캐릭터·색·기분은 잠그지 않고, 새로 생기는 것(날씨 사주 연애운·궁합 등, 새 캐릭터·테두리, 댓글 레벨 배지)만 레벨로 열림. 내 정보는 기존 화면에 레벨·각만 더함. 정할 것: 레벨 이름·단계·필요 각, 행동별 각·하루 한도, 해금 목록 | 기획서 '계정 레벨(각)·날씨 사주 UI 기획'(10/28 채팅 첨부) | `frontend/src/b/Sheets.tsx` `MeSheet` | | [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(10/28 "니 알아서 하라"), 바꿀 수 있게 기록: 날씨 접목은 조후(한난조습) · 연애운은 열 때 성별 선택 입력(남/여/선택 안 함, 안 하면 도화·배우자궁만으로 본다고 표시) · 도화는 연지·일지 삼합 둘 다 · 홍염은 일간표(甲乙午 丙寅 丁未 戊己辰 庚戌 辛酉 壬子 癸申, 이견 있음 표시) · 합충형파해원진은 원국 네 지지 모두, 일지에 걸리면 연애 가중 · 절입 시각은 천문 계산식으로 1900~2100 표를 만들고 천문연 값으로 검증(패키지 안 씀) · 진태양시(출생지 경도)·서머타임 반영, 자시는 자정 기준(설정으로 변경) · 음력은 다음 단계(천문연 API) | 사용자 위임 10/28 | | | [ ] | **[결정 필요]** 날씨 사주 화면·문구 — '내 기운'(계절·날씨 장면 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` | ## 진행 순서 diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 43eea34..127bf56 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -1,9 +1,9 @@ import uuid -from datetime import date, datetime +from datetime import date, datetime, time from decimal import Decimal from typing import Optional -from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, func +from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, Time, func from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -364,6 +364,10 @@ class User(Base): terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) token_version: Mapped[int] = mapped_column(SmallInteger, default=1) points: Mapped[int] = mapped_column(Integer, default=0) + 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()) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) deleted: Mapped[bool] = mapped_column(Boolean, default=False) diff --git a/backend/config/settings.py b/backend/config/settings.py index 99093f3..d6fbd90 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -51,10 +51,9 @@ class Settings(BaseSettings): azure_blob_base_url: str = "" azure_blob_sas_token: str = "" - # 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다 + # 오늘 화면 쇼츠 줄. API 키가 있으면 Data API 로(공개·퍼가기 허용·3분 이하), 없으면 채널 쇼츠 RSS 로 받는다 youtube_api_key: str = "" youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w" - youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM" # 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다 google_client_id: str = "" diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 5d77a03..fa41173 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -330,6 +330,11 @@ 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); 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 ( diff --git a/backend/router/v1/saju/protocol.py b/backend/router/v1/saju/protocol.py index 1a7f4d5..20d04f0 100644 --- a/backend/router/v1/saju/protocol.py +++ b/backend/router/v1/saju/protocol.py @@ -14,6 +14,21 @@ class Req_Saju(Req_WebPacketProtocol): 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): position: str = Field(description="year·month·day·hour") stem: str diff --git a/backend/router/v1/saju/saju.py b/backend/router/v1/saju/saju.py index dcdc06e..61858f0 100644 --- a/backend/router/v1/saju/saju.py +++ b/backend/router/v1/saju/saju.py @@ -3,11 +3,11 @@ from typing import Optional from fastapi import APIRouter, Depends -from common.auth import optional_user +from common.auth import current_user, optional_user from common.database.model.models import User from common.enums import ErrorType from common.models.errors import error_info -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 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 services import saju_text as T from services.level_service import UNLOCKS from services.saju.ganji import branch_element, ko, stem_element @@ -55,6 +55,31 @@ 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) +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: return b.birth_date, time(*map(int, b.birth_time.split(":"))) if b.birth_time else None, b.longitude diff --git a/backend/services/external/youtube.py b/backend/services/external/youtube.py index b7999c7..e6a94a8 100644 --- a/backend/services/external/youtube.py +++ b/backend/services/external/youtube.py @@ -1,4 +1,6 @@ +import asyncio import re +import xml.etree.ElementTree as ET from typing import Optional import httpx @@ -7,6 +9,9 @@ import httpx API_URL = "https://www.googleapis.com/youtube/v3" # 키 없이 영상 제목만 받을 때 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분 이하 _DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$") @@ -53,3 +58,17 @@ async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str] return None res.raise_for_status() 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] diff --git a/backend/services/level_service.py b/backend/services/level_service.py index 786900a..5e7d43e 100644 --- a/backend/services/level_service.py +++ b/backend/services/level_service.py @@ -23,7 +23,7 @@ LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바 ACTIONS: dict[str, tuple[int, int, str]] = { "attend": (10, 10, "출석"), "tarot": (10, 10, "오늘 타로 뽑기"), - "saju": (10, 10, "날씨 사주 오늘 기운"), + "saju": (10, 10, "날씨 사주 보기"), "react": (5, 10, "좋아요·댓글"), "talk": (20, 20, "동네 이야기 글쓰기"), "checkin": (10, 10, "저녁 체크인"), @@ -40,7 +40,7 @@ STREAK_LOOKBACK = 60 # 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로) UNLOCKS: dict[int, list[tuple[str, str]]] = { - 2: [("saju_week", "날씨 사주 이번 주 흐름")], + 2: [("saju_week", "날씨 사주 7일 흐름")], 3: [("saju_money", "금전운 · 일운")], 4: [("saju_love", "연애운")], 5: [("saju_match", "궁합")], diff --git a/backend/services/saju_service.py b/backend/services/saju_service.py index c403b74..f9369a4 100644 --- a/backend/services/saju_service.py +++ b/backend/services/saju_service.py @@ -9,15 +9,16 @@ from common.database.model.models import User, WeatherDaily, WeatherHourly from common.enums import ErrorType, RainType, Sky from common.utils.kma_time import KST, kst_midnight, now_kst from crud.region_crud import RegionCRUD +from crud.user_crud import UserCRUD from crud.weather_crud import WeatherCRUD from crud.week_crud import WeekCRUD from services import saju_text as T from services.level_service import award, level_of, unlock_level -from services.saju.climate import HourWeather, chart_climate, climate_match -from services.saju.daily import DailyFacts, daily_facts, interactions, score as pillar_score -from services.saju.ganji import branch_element, ko, stem_element +from services.saju.climate import HourWeather, best_window, chart_climate, climate_match +from services.saju.daily import SCORE_WEIGHTS, DailyFacts, Interaction, daily_facts, interactions, score as pillar_score +from services.saju.ganji import ko, main_stem from services.saju.pillars import Chart, Pillar, make_chart -from services.saju.rules import branch_relations, stem_relations, ten_god +from services.saju.rules import WEALTH, branch_relations, stem_relations, ten_god from services.weather_service import WeatherService from services.week_service import WeekService @@ -27,7 +28,10 @@ WEEK_DAYS = 7 WEATHER_SHARE = 0.6 SHOW_CENTER, SHOW_SPREAD, SHOW_MIN, SHOW_MAX = 68, 1.2, 25, 98 RIVALS = ("비견", "겁재") -CROWDED = 3 # 원국에 비겁이 이만큼 이상이면 비겁 날 돈 조심 (군겁쟁재) +CROWDED = 3 # 일간을 뺀 원국 글자 중 비겁이 이만큼 이상이고 재성이 있으면 비겁 날 돈 조심 (군겁쟁재) +PICK_MIN = 60 # 앞으로 7일 중 '좋은 날'로 고르려면 그날 점수가 이 이상 +COMFY_C = (5, 30) # 외출 시간으로 권할 체감 온도 범위 (조후로는 맞아도 너무 춥거나 더운 때는 뺀다) +NOTES_MAX = 2 # 이달·올해 근거 줄 수 _WEEKDAY = "월화수목금토일" _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} @@ -73,8 +77,8 @@ class Reading: level: int logged_in: bool week: Optional[list[DayReading]] = None - money: Optional[str] = None - work: Optional[str] = None + money: Optional[list[str]] = None + work: Optional[list[str]] = None love: Optional[dict] = None month: Optional[dict] = None year: Optional[dict] = None @@ -153,37 +157,66 @@ def _pillars(chart: Chart) -> dict[str, Pillar]: def crowded_rivals(chart: Chart) -> bool: - """원국에 비견·겁재(일간 포함)가 많은지""" + """일간 말고도 비견·겁재가 많고, 나눠 가질 재성이 원국에 있는지 (지지는 정기로 본다)""" me = chart.day.stem - stems = [p.stem for p in _pillars(chart).values()] - branches = [p.branch for p in _pillars(chart).values()] - 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 + chars = [p.stem for pos, p in _pillars(chart).items() if pos != "day"] + [main_stem(p.branch) for p in _pillars(chart).values()] + gods = [ten_god(me, c) for c in chars] + return sum(g in RIVALS for g in gods) >= CROWDED and any(g in WEALTH for g in gods) def why_words(facts: DailyFacts) -> list[str]: - """점수에 가장 크게 작용한 사실 셋을 사람 말로""" + """점수를 가장 크게 움직인 사실 셋을 쉬운 말로, 올렸는지(↑) 내렸는지(↓)""" + rels = {(i.relation.kind, i.relation.chars, i.position): i for i in facts.interactions} out = [] for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]: - place = f"{T.PLACE_WORD[c.position]} 자리와 " if c.position else "" - sign = "+" if c.points >= 0 else "−" - out.append(f"{place}{c.fact}({'·'.join(ko(ch) for ch in c.chars)}) {sign}{abs(round(c.points))}") + arrow = "↑" if c.points >= 0 else "↓" + if c.fact in T.GOD_PLAIN: + line = f"오늘 들어오는 기운: {T.GOD_PLAIN[c.fact]}({c.fact})" + 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 -def _rel(i) -> str: - return f"{T.PLACE_WORD[i.position]} 자리와 {i.relation.kind}({'·'.join(ko(ch) for ch in i.relation.chars)})" +def _rel(i: Interaction) -> str: + """'태어난 날과 오늘이 부딪혀요(일지 사·해 충)'. 일간과의 관계는 '나와 오늘이 …'""" + 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]: - """조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계 (나·연인 자리 먼저)""" + """조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계""" lines, subs = [], [] if facts.stem_ten_god in RIVALS and crowded_rivals(chart): lines.append(T.CROWDED_RIVALS) - subs.append(f"원국에 같은 기운이 많은 날 {T.josa(facts.stem_ten_god, '이가')} 들어와요") - 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) - for i in bad: - body = T.AVOID_TEXT.get((i.relation.kind, i.position)) or T.AVOID_TEXT.get((i.relation.kind, "")) + subs.append(T.CROWDED_WHY.format(god=facts.stem_ten_god)) + for i in _bad(facts): + key = (i.relation.kind, i.position if i.part == "branch" else "") + body = T.AVOID_TEXT.get(key) or T.AVOID_TEXT.get((i.relation.kind, "")) if body and body not in lines: lines.append(body) subs.append(_rel(i)) @@ -194,21 +227,24 @@ def avoid_card(chart: Chart, 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: return None i = good[0] - return Card(kind="good", title="오늘 좋은 흐름", body=T.GOOD_TEXT[i.position], sub=_rel(i)) + body = T.STEM_GOOD if i.part == "stem" and i.position == "day" else T.GOOD_TEXT[i.position] + return Card(kind="good", title="오늘 좋은 흐름", body=body, sub=_rel(i)) -def when_card(r: DayReading) -> Optional[Card]: +def when_card(r: DayReading, needs: list[tuple[str, str]]) -> Optional[Card]: if not r.best_hours or r.weather is None: return None h = r.best_hours[0] temp, word = r.weather.by_hour.get(h, (None, r.weather.word)) - 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.josa('·'.join(helps), '이가')} 가장 많이 오는 때예요. 중요한 일은 이때 하세요." if helps else "오늘 날씨가 내 기운과 가장 무난한 때예요. 중요한 일은 이때 하세요." - sub = f"{word} {round(temp)}°" if temp is not None else word + walk = "산책·외출은 이때 하세요." + body = f"내 기운엔 {T.need_phrase(needs)}가 좋아요. 오늘 중엔 이때가 가장 알맞아요. {walk}" if needs else f"오늘 중 날씨가 가장 편안한 때예요. {walk}" + sub = f"{T.hour_word(h)} {word} {round(temp)}°" if temp is not None else word return Card(kind="when", title=window_text(r.best_hours), body=body, sub=sub) @@ -221,80 +257,88 @@ def wear_card(r: DayReading, needs: list[tuple[str, str]], place: Optional[str]) if r.weather is None: return None feels = min(h.feels_c for h in r.weather.hours) - color = T.NEED_COLOR[needs[0]] if needs else None - body = f"아침저녁 체감 {round(feels)}°라 {T.clothes(feels)}" + (f", 색은 {color} 포인트" if color else "") - return Card(kind="wear", title="입을 것 · 갈 곳", body=body, sub=f"갈 곳: {place}" if place else None) + body = f"가장 쌀쌀할 때 체감 {round(feels)}°예요. {T.josa(T.clothes(feels), '을를')} 챙기세요." + if needs: + body += f"\n포인트 색은 {T.NEED_COLOR[needs[0]]} 해 보세요." + 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: - """이번 주 연애 기운이 좋은 날과 조심할 날. 비 오는 날은 좋은 날에서 뒤로""" + """앞으로 7일 중 연애 기운이 좋은 날과 조심할 날. 연인 자리(일지)가 부딪히는 날은 좋은 날에서 빼고, 비·눈 오는 날은 뒤로""" goods, bads = [], [] for r in week: - kinds = set() + kinds, clash = set(), None for x in r.facts.love.reasons: k = x["kind"] if k == "일지": rel = x.get("relation") - (kinds.add("일지합") if rel in ("육합", "반합", "삼합") else bads.append((r, rel))) + if rel in ("육합", "반합", "삼합"): + kinds.add("일지합") + else: + clash = rel else: kinds.add(k) + if clash: + bads.append((r, clash)) + continue good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds] if good: goods.append((r, good)) - goods.sort(key=lambda g: (g[0].weather is not None and g[0].weather.icon in ("rain", "snow"), -g[0].score)) + goods.sort(key=lambda g: (_wet(g[0]), -g[0].score)) out: dict = {"gender": gender} if goods: r, kinds = goods[0] - rainy = r.weather is not None and r.weather.icon in ("rain", "snow") + body = T.LOVE_GOOD[kinds[0]][0] + (" " + T.LOVE_WET.format(word=r.weather.word) if _wet(r) else "") 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": T.LOVE_GOOD[kinds[0]] + (" " + T.LOVE_RAINY if rainy else ""), "why": "·".join(kinds)} + "temp_max": r.weather.temp_max if r.weather else None, "body": body, "why": " · ".join(T.LOVE_GOOD[k][1] for k in kinds)} if bads: - r, rel = bads[0] - out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD.get(rel, "말을 한 번 더 고르세요."), "why": f"나·연인 자리와 {rel}"} + r, rel = min(bads, key=lambda b: b[0].score) + out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD[rel], "why": T.LOVE_BAD_WHY[rel]} return out -MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "편관", "정인", "상관") +MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "정인", "상관") -def _day_word(r: DayReading) -> str: - return f"{_WEEKDAY[r.day.weekday()]} {r.day.day}일({T.TEN_GOD_TEXT[r.facts.stem_ten_god][0]})" +def day_word(d: date, today: Optional[date] = None) -> str: + """'10/31(토)', 오늘이면 '오늘(10/28)'""" + 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 pick(gods: tuple[str, ...]) -> Optional[DayReading]: - return next((r for r in week if r.facts.stem_ten_god in gods), None) + """금전·일: 앞으로 7일 중 그 십성이 드는 날에서 점수로 고른다. 좋은 날은 점수가 PICK_MIN 이상일 때만""" + def best(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 max(days, key=lambda r: r.score) if days else None - money, work = [], [] - if (g := pick(MONEY_GOOD)) is not None: - money.append(f"큰 결제·계약은 {_day_word(g)}에 하세요.") - if (b := pick(MONEY_BAD)) is not 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("이번 주는 하던 일을 마무리하기 좋아요.") + worst = min((r for r in week if r.facts.stem_ten_god in MONEY_BAD), key=lambda r: r.score, default=None) + money = [T.MONEY_GOOD.format(day=day_word(g.day, week[0].day))] if (g := best(MONEY_GOOD)) else [T.MONEY_NONE] + if worst is not None: + money.append(T.MONEY_BAD.format(day=day_word(worst.day, week[0].day))) + work = [T.WORK_GOOD.format(day=day_word(w.day, week[0].day))] if (w := best(WORK_GOOD)) else [T.WORK_NONE] return money, work -def year_months(chart: Chart, year: int) -> list[int]: - """그해 열두 달(절 기준) 중 내 사주와 잘 맞는 달 셋 (달 번호는 그 절이 드는 양력 달)""" +def year_months(chart: Chart, year: int, start: int = 1) -> list[int]: + """그해 start 월부터 남은 달(절 기준) 중 내 사주와 잘 맞는 달. 셋, 남은 달이 적으면 그 절반 (달 번호는 그 절이 드는 양력 달)""" scored = [] - for m in range(1, 13): + for m in range(start, 13): mp = make_chart(date(year, m, 15), time(12, 0)).month found = interactions(chart, mp) scored.append((pillar_score(chart, mp, found, [], False)[0], m)) - return sorted(m for _, m in sorted(scored, reverse=True)[:3]) + return sorted(m for _, m in sorted(scored, reverse=True)[: min(3, max(1, len(scored) // 2))]) -def period(chart: Chart, p: Pillar, unit: str) -> dict: - """이달·올해: 그 간지 천간 십성 + 원국과의 관계""" +def period(chart: Chart, p: Pillar, unit: str, subject: str) -> dict: + """이달·올해: 그 간지 천간 십성 + 원국과의 관계. subject 는 근거 줄의 주어 ('이번 달이', '올해가')""" god = ten_god(chart.day.stem, p.stem) title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god] - return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i) for i in interactions(chart, p)]} + 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).replace("오늘이", subject) for i in found]} @dataclass @@ -302,45 +346,62 @@ class Match: score: int title: str lines: list[str] - day: Optional[DayReading] # 이번 주 둘 다 좋은 날 + day: Optional[DayReading] # 앞으로 7일 중 둘 다 점수가 괜찮고 비·눈이 없는 날 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": 10} +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} +_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: + """궁합. 점수는 두 방향 십성 점수의 평균이라 누구를 먼저 넣어도 같다. 설명은 내 쪽에서 본 사이""" 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) - group = next(g for k, g in (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource")) if god in k) - score, lines = MATCH_SCORE["base"] + MATCH_SCORE[group], [body] + back = ten_god(friend.day.stem, me.day.stem) + score, lines = MATCH_SCORE["base"] + (MATCH_SCORE[_group(god)] + MATCH_SCORE[_group(back)]) / 2, [body] if any(r.kind == "천간합" for r in stem_relations(me.day.stem, friend.day.stem)): score += MATCH_SCORE["stem_hap"] lines.append(T.MATCH_STEM_HAP) for r in branch_relations(me.day.branch, friend.day.branch): - if r.kind in T.MATCH_BRANCH: + if r.kind in T.MATCH_BRANCH and T.MATCH_BRANCH[r.kind] not in lines: score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"] lines.append(T.MATCH_BRANCH[r.kind]) - break a, b = chart_climate(me), chart_climate(friend) - if a.temp * b.temp < 0 or a.moist * b.moist < 0: - score += MATCH_SCORE["climate_ok"] - lines.append(T.MATCH_CLIMATE_OK) - else: - need = [T.NEED_WORD[n] for n in needs_of(a.need)] - if need: - lines.append(T.MATCH_CLIMATE_SAME.format(need=T.josa("·".join(need), "이가"))) - both = [(x, y) for x, y in zip(my_days, friend_days)] + opposite = {"temp": {"warm": "cool", "cool": "warm"}, "moist": {"dry": "moist", "moist": "dry"}} + fills = [ax for ax in ("temp", "moist") if opposite[ax].get(a.need[ax]) == b.need[ax]] + shared = [(ax, a.need[ax]) for ax in ("temp", "moist") if a.need[ax] != "mild" and a.need[ax] == b.need[ax]] + if fills: + score += MATCH_SCORE["climate_ok"] * len(fills) + lines.append(T.MATCH_CLIMATE_OK.format(axis=T.MATCH_CLIMATE_AXIS[fills[0]])) + elif shared: + lines.append(T.MATCH_CLIMATE_SAME.format(need=T.need_phrase(shared))) + 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 - return Match(score=max(0, min(100, score)), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0]) + return Match(score=max(0, min(100, round(score))), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0]) class SajuService: def __init__( self, regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), week_crud: WeekCRUD = Depends(WeekCRUD), - weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService), + weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService), users: UserCRUD = Depends(UserCRUD), ) -> None: - self.regions, self.weather, self.week_crud, self.weather_service, self.week = regions, weather, week_crud, weather_service, week + self.regions, self.weather, self.week_crud, self.weather_service, self.week, self.users = regions, weather, week_crud, weather_service, week, users + + 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]]: err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) @@ -370,15 +431,18 @@ class SajuService: def _day(self, chart: Chart, d: date, w: Optional[DayWeather], gender: Optional[Gender]) -> DayReading: facts = daily_facts(chart, d, gender) if w is None: - return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=facts.score) + return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=total_score(facts.score, None)) m = climate_match(chart, 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)) + feels = {x.hour: x.feels_c for x in w.hours} + 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: """올해 운. 11월부터는 다음 해 미리 보기 (입춘 뒤 날짜로 그해 간지)""" y = today.year + 1 if today.month >= 11 else today.year p = make_chart(date(y, 6, 1), time(12, 0)).year - return {**period(chart, p, "해"), "year": y, "preview": y != today.year, "months": year_months(chart, y)} + 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)} async def match( self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User], @@ -417,7 +481,9 @@ class SajuService: _, 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) todo = T.TEN_GOD_TEXT[r0.facts.stem_ten_god][1] - 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] + god = r0.facts.stem_ten_god + 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 if user is not None: @@ -430,12 +496,12 @@ class SajuService: now_chart = make_chart(today, time(12, 0)) return ErrorType.SUCCESS, Reading( chart=chart, scene=scene, scene_icon=T.SCENE_ICON.get(chart_climate.label, "sun") if chart_climate else "sun", - 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, + 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, week=days if unlocked("saju_week") else None, money=money_work(days)[0] 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, - 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, ) diff --git a/backend/services/saju_text.py b/backend/services/saju_text.py index f056e03..93b445a 100644 --- a/backend/services/saju_text.py +++ b/backend/services/saju_text.py @@ -1,104 +1,101 @@ -"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다 (초안, 사용자 검토 대상).""" +"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다. 쉬운 말을 앞에, 명리 용어는 괄호에.""" # 오늘 천간 십성 → (제목, 오늘 할 것) 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] = { - ("원진", "day"): "연인·배우자에게 사소한 서운함이 생기기 쉬워요. 큰 이야기는 내일로 미루세요.", - ("충", "day"): "가까운 사람과 부딪히기 쉬워요. 다툼이 될 만한 이야기는 피하세요.", - ("충", "month"): "직장·집안 일정이 흔들리기 쉬워요. 이직·이사 같은 큰 결정은 미루세요.", - ("충", "year"): "윗사람·바깥 일에서 변수가 생기기 쉬워요. 약속은 한 번 더 확인하세요.", - ("충", "hour"): "앞날 계획이 흔들리기 쉬워요. 일정은 여유 있게 잡으세요.", - ("원진", ""): "사소한 오해가 생기기 쉬워요. 말투를 한 번 더 고르세요.", + ("원진", "day"): "연인·가까운 사람의 말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.", + ("충", "day"): "가까운 사람과 의견이 부딪히기 쉬워요. 서로 원하는 걸 먼저 확인하세요.", + ("충", "month"): "회사·집안 일정이 바뀌기 쉬워요. 이직·이사처럼 큰 결정은 오늘 확정하지 마세요.", + ("충", "year"): "밖에서 잡힌 일정이 바뀌기 쉬워요. 약속 시간과 장소를 다시 확인하세요.", + ("충", "hour"): "계획대로 안 풀리기 쉬워요. 일정 사이에 여유를 두세요.", + ("원진", ""): "말이 서운하게 들리기 쉬워요. 메시지는 보내기 전에 한 번 더 읽어 보세요.", ("형", ""): "서류·계약·약속은 한 번 더 확인하세요.", ("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.", - ("자형", ""): "생각이 많아 혼자 지치기 쉬워요. 오늘은 일찍 쉬세요.", - ("파", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.", - ("해", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.", - ("천간충", ""): "마음이 이리저리 흔들리기 쉬워요. 결정은 하나씩 하세요.", + ("자형", ""): "같은 고민을 계속 붙잡기 쉬워요. 적어 두고 일찍 쉬세요.", + ("파", ""): "약속이 틀어지기 쉬워요. 시간과 장소를 다시 확인하세요.", + ("해", ""): "좋은 뜻으로 한 일이 오해를 사기 쉬워요. 부탁받은 일은 범위부터 정하세요.", + ("천간충", ""): "마음이 오락가락하기 쉬워요. 결정할 일은 하나씩 정리하세요.", } -# 비겁이 많은 원국에 비겁 날 (군겁쟁재) -CROWDED_RIVALS = "같이 쓰는 돈·더치페이·빌려주는 돈은 오늘 정하지 마세요." +# 비겁이 많고 재성이 있는 원국에 비겁 날 (군겁쟁재) +CROWDED_RIVALS = "돈을 빌려주거나 같이 투자하는 건 오늘 미루세요." +CROWDED_WHY = "내 사주에 나와 같은 기운이 많은데 오늘도 같은 기운이 들어와요({god})" -# 자리 → 좋은 흐름 (합이 들 때) +# 지지 합이 든 자리 → 좋은 흐름. 일간과 천간합이면 STEM_GOOD GOOD_TEXT = { - "day": "연인·배우자와 가까워지는 날이에요. 같이 보낼 시간을 잡아 보세요.", - "month": "직장·팀 일이 잘 맞물려요. 협업 제안을 꺼내기 좋아요.", - "year": "윗사람·바깥 사람에게 도움을 받기 쉬워요. 부탁할 일을 꺼내 보세요.", - "hour": "아랫사람·후배와 사이가 좋아지는 날이에요.", + "day": "연인·가까운 사람과 사이가 부드러운 날이에요. 함께할 시간을 잡아 보세요.", + "month": "회사·집안 일이 순조로운 날이에요. 미뤄 둔 협업 이야기를 꺼내 보세요.", + "year": "밖에서 도움을 받기 좋은 날이에요. 부탁할 일이 있으면 오늘 꺼내 보세요.", + "hour": "후배·아이와 잘 통하는 날이에요. 먼저 말을 걸어 보세요.", } +STEM_GOOD = "마음 맞는 사람을 만나기 좋은 날이에요. 미뤄 둔 연락을 해 보세요." GOOD_RELATIONS = ("천간합", "육합", "삼합", "반합") -# 금전운 · 일운: 오늘 천간 십성 → 한 줄 -MONEY_TEXT = { - "비견": "같이 쓰는 돈은 각자 내는 게 편한 날이에요.", - "겁재": "빌려주거나 함께 투자하는 돈은 오늘 정하지 마세요.", - "식신": "즐기는 데 쓰는 돈이 늘기 쉬워요. 한도를 먼저 정하세요.", - "상관": "충동 구매가 생기기 쉬워요. 장바구니에 하루 두었다 사세요.", - "편재": "뜻밖의 수입이나 할인 기회가 와요. 들어올 돈부터 챙기세요.", - "정재": "가계부·적금처럼 돈을 정리하기 좋아요.", - "편관": "갑자기 나갈 돈이 생기기 쉬워요. 여윳돈을 남겨 두세요.", - "정관": "공과금·세금처럼 정해진 돈을 처리하기 좋아요.", - "편인": "돈보다 정보가 남는 날이에요. 가격 비교를 해 두세요.", - "정인": "배우는 데 쓰는 돈은 아깝지 않은 날이에요.", -} -WORK_TEXT = { - "비견": "혼자 끝낼 수 있는 일에 집중하세요.", - "겁재": "공동 작업은 역할과 몫을 먼저 나누세요.", - "식신": "편하게 꺼낸 아이디어가 반응이 좋아요.", - "상관": "발표·제안에 좋아요. 윗사람 앞에선 말을 한 번 고르세요.", - "편재": "새 거래·새 사람과 일을 시작하기 좋아요.", - "정재": "숫자를 맞추고 결과를 정리하는 일에 좋아요.", - "편관": "어려운 일을 맡으면 인정받아요.", - "정관": "보고·결재처럼 정해진 일을 처리하기 좋아요.", - "편인": "자료 조사·기획처럼 준비하는 일에 좋아요.", - "정인": "배우거나 도움을 청하면 일이 풀려요.", -} +# 금전·일: 앞으로 7일 중 고른 날 → 한 줄 ({day}는 '10/31(토)') +MONEY_GOOD = "큰돈 쓰거나 계약할 일은 {day}에 하세요." +MONEY_BAD = "돈 빌려주기·같이 투자하기는 {day}엔 미루세요." +WORK_GOOD = "보고·발표·면접은 {day}에 잡아 보세요." +MONEY_NONE = "앞으로 7일 중엔 큰돈 쓰기 좋은 날이 따로 없어요." +WORK_NONE = "앞으로 7일 중엔 발표·면접 잡기 좋은 날이 따로 없어요." -# 연애 기운이 드는 이유 → 한 줄 +# 연애 기운이 드는 이유 → (한 줄, 이유 말) LOVE_GOOD = { - "도화": "사람들 눈에 잘 띄는 날이에요. 새 만남에 좋아요.", - "홍염": "매력이 드러나는 날이에요.", - "일지합": "연인과 가까워지는 날이에요.", - "재성": "이성 기운이 들어오는 날이에요.", - "관성": "이성 기운이 들어오는 날이에요.", + "도화": ("눈에 잘 띄는 날이에요. 모임이나 소개팅에 나가 보세요.", "눈에 띄는 기운(도화)"), + "홍염": ("매력이 잘 드러나는 날이에요. 관심 있는 사람에게 먼저 연락해 보세요.", "매력의 기운(홍염)"), + "일지합": ("연인과 마음이 잘 맞는 날이에요. 데이트 약속을 잡아 보세요.", "연인 자리와 어울림(일지 합)"), + "재성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(재성)"), + "관성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(관성)"), } LOVE_BAD = { - "원진": "서운한 말이 오가기 쉬워요.", - "충": "다투기 쉬워요.", - "형": "오해가 생기기 쉬워요.", - "자형": "혼자 속앓이하기 쉬워요.", + "원진": "말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.", + "충": "의견이 부딪히기 쉬워요. 중요한 이야기는 다른 날로 미루세요.", + "형": "오해가 생기기 쉬워요. 메시지보다 직접 말하세요.", + "자형": "혼자 속앓이하기 쉬워요. 서운한 건 담아 두지 말고 말하세요.", } +LOVE_BAD_WHY = {"원진": "연인 자리와 서로 꺼림(일지 원진)", "충": "연인 자리와 부딪힘(일지 충)", "형": "연인 자리와 엇갈림(일지 형)", "자형": "연인 자리에 같은 글자가 겹침(일지 자형)"} +LOVE_WET = "{word} 예보가 있으니 실내 데이트로 잡으세요." # 내 기운: 태어난 계절 × 원국의 결 SCENES: dict[tuple[str, str], tuple[str, str]] = { ("봄", "따뜻·마름"): ("봄햇살 기운", "새싹을 키우는 맑은 봄볕"), ("봄", "따뜻·촉촉"): ("봄 아지랑이 기운", "따뜻하고 포근한 봄 오후"), - ("봄", "서늘·마름"): ("꽃샘바람 기운", "쌀쌀해도 꽃을 피우는 봄바람"), + ("봄", "서늘·마름"): ("꽃샘바람 기운", "꽃봉오리를 스치는 쌀쌀한 봄바람"), ("봄", "서늘·촉촉"): ("봄비 기운", "새싹을 깨우는 촉촉한 이른 봄비"), ("여름", "따뜻·마름"): ("한낮 땡볕 기운", "뜨겁고 환한 여름 한낮"), - ("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근하다 시원하게 쏟아지는 여름비"), + ("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근한 오후에 쏟아지는 소나기"), ("여름", "서늘·마름"): ("여름밤 바람 기운", "열기를 식혀 주는 여름밤 바람"), - ("여름", "서늘·촉촉"): ("장맛비 기운", "오래 촉촉하게 내리는 장맛비"), + ("여름", "서늘·촉촉"): ("장맛비 기운", "며칠씩 이어지는 여름 장맛비"), ("가을", "따뜻·마름"): ("가을 햇살 기운", "곡식을 익히는 가을볕"), ("가을", "따뜻·촉촉"): ("가을비 기운", "단풍을 적시는 포근한 가을비"), - ("가을", "서늘·마름"): ("소슬바람 기운", "선선하고 맑은 가을바람"), - ("가을", "서늘·촉촉"): ("새벽 서리 기운", "찬 이슬이 맺히는 늦가을 새벽"), + ("가을", "서늘·마름"): ("가을바람 기운", "선선하고 맑은 가을바람"), + ("가을", "서늘·촉촉"): ("새벽 서리 기운", "풀잎에 서리가 내린 늦가을 새벽"), ("겨울", "따뜻·마름"): ("겨울 햇살 기운", "추위 속에 비치는 겨울볕"), ("겨울", "따뜻·촉촉"): ("함박눈 기운", "포근하게 쌓이는 함박눈"), ("겨울", "서늘·마름"): ("칼바람 기운", "맑고 매서운 겨울바람"), @@ -106,10 +103,18 @@ SCENES: dict[tuple[str, str], tuple[str, str]] = { } SCENE_ICON = {"따뜻·마름": "sun", "따뜻·촉촉": "sun_cloud", "서늘·마름": "coldwind", "서늘·촉촉": "rain"} -# 조후에서 필요한 것 → 말 -NEED_WORD = {("temp", "warm"): "따뜻함", ("temp", "cool"): "시원함", ("moist", "dry"): "마른 공기", ("moist", "moist"): "촉촉함"} -# 필요한 기운을 채우는 색 (오방색) -NEED_COLOR = {("temp", "warm"): "빨강·주황", ("temp", "cool"): "검정·남색", ("moist", "dry"): "노랑·베이지", ("moist", "moist"): "초록·하늘색"} +# 조후에서 필요한 것 → (이어 쓰는 꼴, 끝맺는 꼴): '따뜻하고 건조한 날씨' +NEED_ADJ = {("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: @@ -139,42 +144,49 @@ def josa(word: str, pair: str) -> str: has = "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0 return word + (pair[0] if has or not ("가" <= last <= "힣") else pair[1]) -# 궁합: 친구 일간이 나에게 무슨 십성인지 → (제목, 설명) + +# 궁합: 상대 일간이 나에게 무슨 십성인지 → (제목, 설명). 내 쪽에서 본 사이 MATCH_TEXT = { - ("비견", "겁재"): ("친구처럼 대등한 사이", "좋아하는 게 비슷해 편한 사이예요. 정할 일은 차례를 나눠 정하세요."), - ("식신", "상관"): ("내가 챙겨 주는 사이", "내가 아이디어와 마음을 더 많이 주는 쪽이에요."), - ("편재", "정재"): ("내가 이끄는 사이", "내가 정하고 이끌 때 둘 다 편해지는 사이예요."), - ("편관", "정관"): ("나를 다잡아 주는 사이", "상대가 내 기준을 세워 주고 정리해 줘요."), - ("편인", "정인"): ("나를 키워 주는 사이", "상대가 나를 돕고 채워 주는 쪽이에요."), + ("비견", "겁재"): ("친구처럼 대등한 사이", "취향이 비슷해 편하게 지내기 쉬워요. 정할 일은 번갈아 정하세요."), + ("식신", "상관"): ("내가 더 챙겨 주는 사이", "내가 마음을 더 많이 쓰는 쪽이에요. 받고 싶은 것도 말로 꺼내세요."), + ("편재", "정재"): ("내가 이끄는 사이", "약속이나 계획은 내가 먼저 정할 때 편해요. 상대 의견도 꼭 물어보세요."), + ("편관", "정관"): ("나를 잡아 주는 사이", "상대가 내 기준이 되어 주는 쪽이에요. 부담되면 솔직히 말하세요."), + ("편인", "정인"): ("나를 챙겨 주는 사이", "상대에게 도움을 많이 받는 쪽이에요. 고마운 건 바로 표현하세요."), } -MATCH_STEM_HAP = "일간끼리 합이라 처음부터 잘 끌리는 사이예요." -MATCH_BRANCH = {"육합": "함께 있으면 편안한 사이예요.", "반합": "함께 있으면 편안한 사이예요.", "충": "생활 리듬이 달라 부딪히기 쉬워요. 약속은 미리 맞추세요.", "원진": "사소한 일에 서운해하기 쉬워요. 말로 먼저 풀어 주세요."} -MATCH_CLIMATE_OK = "서로의 날씨를 맞춰 주는 사이예요. 함께 있으면 둘 다 균형이 잡혀요." -MATCH_CLIMATE_SAME = "둘 다 {need} 필요한 기운이라, 그런 날씨에 함께 나가면 좋아요." +MATCH_STEM_HAP = "서로 끌리는 글자끼리 만나는 사이예요(일간 합)." +MATCH_BRANCH = { + "육합": "같이 있으면 편안한 사이예요(일지 합).", + "반합": "같이 있으면 편안한 사이예요(일지 합).", + "충": "생활 리듬이 달라 부딪히기 쉬워요. 연락·약속 방식을 미리 맞추세요(일지 충).", + "원진": "작은 일로 서운해하기 쉬워요. 서운한 건 그때그때 말하세요(일지 원진).", +} +# 궁합 날씨: 한 축에서 둘이 서로 모자란 걸 채워 줄 때 / 둘 다 같은 날씨가 맞을 때 +MATCH_CLIMATE_AXIS = {"temp": "한 사람은 따뜻하고 한 사람은 서늘한 기운이라", "moist": "한 사람은 촉촉하고 한 사람은 건조한 기운이라"} +MATCH_CLIMATE_OK = "{axis} 서로 모자란 걸 채워 줘요." +MATCH_CLIMATE_SAME = "둘 다 {need}가 맞는 기운이라, 그런 날 함께 나가면 좋아요." # 이달 · 올해: 그 간지 천간 십성 → (제목, 설명) MONTH_TEXT: dict[str, tuple[str, str]] = { - "비견": ("내 힘으로 서는 달", "혼자 해 온 일을 굳히기 좋은 달이에요. 새 일은 내 손으로 시작하세요."), - "겁재": ("내 몫을 지키는 달", "돈 약속·공동 투자는 서두르지 말고, 내 몫부터 정해 두세요."), - "식신": ("즐기며 채우는 달", "취미·맛집·여행처럼 나를 채우는 일에 시간을 쓰세요."), - "상관": ("말과 재주가 빛나는 달", "발표·제안·창작처럼 밖으로 꺼내는 일이 잘 돼요."), - "편재": ("기회가 들어오는 달", "새 제안과 사람이 많이 들어와요. 큰돈은 한 번 더 따져 보고 정하세요."), - "정재": ("차곡차곡 모으는 달", "저축·정리·계약처럼 꼼꼼한 일이 잘 맞아요."), - "편관": ("버티면 크는 달", "맡는 일이 무거워지지만 끝내면 크게 인정받아요."), - "정관": ("믿음을 쌓는 달", "약속과 규칙을 지키면 자리와 평가가 올라가요."), - "편인": ("생각을 다지는 달", "공부·기획·정리처럼 혼자 하는 일에 좋아요."), - "정인": ("배우고 도움받는 달", "공부를 시작하거나 도움을 청하기 좋아요."), + "비견": ("내 페이스대로 가는 달", "남에게 기대기보다 내 손으로 일을 끝내기 좋은 달이에요."), + "겁재": ("내 몫을 챙겨야 하는 달", "같이 하는 일은 몫부터 정해 두세요. 돈 빌려주기·같이 투자하기는 서두르지 마세요."), + "식신": ("여유가 생기는 달", "취미·맛집·여행처럼 나를 위한 일에 시간을 쓰세요."), + "상관": ("말솜씨가 살아나는 달", "발표·제안·글쓰기처럼 내 생각을 꺼내는 일을 해 보세요."), + "편재": ("새 기회가 보이는 달", "새 제안과 사람이 많이 찾아오는 달이에요. 큰돈이 드는 일은 조건을 따져 보고 정하세요."), + "정재": ("알뜰하게 모으는 달", "저축·가계부 정리처럼 돈을 차곡차곡 챙기기 좋은 달이에요."), + "편관": ("책임이 무거운 달", "맡는 일이 많아지는 달이에요. 할 일을 나눠 우선순위부터 정하세요."), + "정관": ("평판을 쌓는 달", "약속과 마감을 잘 지키면 믿음을 얻기 좋은 달이에요."), + "편인": ("생각이 깊어지는 달", "공부·기획처럼 혼자 파고드는 일이 잘 맞아요."), + "정인": ("배우기 좋은 달", "공부를 시작하거나 아는 사람에게 도움을 청해 보세요."), } YEAR_TEXT: dict[str, tuple[str, str]] = { - "비견": ("홀로서기의 해", "내 이름으로 하는 일을 시작하고 굳히기 좋은 해예요."), - "겁재": ("내 몫을 지키는 해", "같이 하는 돈·사업은 몫을 분명히 나누세요."), - "식신": ("즐기며 넓히는 해", "좋아하는 일을 키우고 몸을 챙기기 좋은 해예요."), - "상관": ("재주를 드러내는 해", "창작·발표·이직처럼 나를 보여 주는 일이 잘 맞아요."), - "편재": ("기회가 넓어지는 해", "새 사람·새 돈길이 열려요. 크게 벌이는 일은 나눠서 하세요."), - "정재": ("차곡차곡 쌓는 해", "저축·자산 정리·안정된 수입을 만들기 좋은 해예요."), - "편관": ("단단해지는 해", "책임이 커지는 해예요. 버틴 만큼 자리가 생겨요."), - "정관": ("자리를 얻는 해", "승진·자격·약속처럼 제도 안의 일이 잘 풀려요."), - "편인": ("나를 다시 짜는 해", "공부·기획·방향 전환을 준비하기 좋은 해예요."), - "정인": ("배우고 받는 해", "공부·자격증, 도와줄 사람을 만나기 좋은 해예요."), + "비견": ("홀로서기 좋은 해", "내 이름으로 하는 일을 시작하고 키우기 좋은 해예요."), + "겁재": ("내 몫을 챙겨야 하는 해", "동업·공동 투자는 몫과 역할을 문서로 정해 두세요."), + "식신": ("하고 싶은 걸 하는 해", "좋아하는 일을 꾸준히 키우고 몸을 챙기기 좋은 해예요."), + "상관": ("나를 드러내는 해", "창작·발표처럼 내 실력을 보여 주는 일이 잘 맞는 해예요."), + "편재": ("기회가 넓어지는 해", "새 사람·새 수입원이 생기기 쉬운 해예요. 크게 벌이는 일은 나눠서 하세요."), + "정재": ("차곡차곡 모으는 해", "저축하고 고정 수입을 늘리기 좋은 해예요."), + "편관": ("책임이 커지는 해", "맡는 일이 무거워지는 해예요. 혼자 다 떠안지 말고 도움받을 일을 나누세요."), + "정관": ("인정받기 좋은 해", "승진·자격시험처럼 정해진 길을 밟는 일이 잘 풀리는 해예요."), + "편인": ("방향을 다시 잡는 해", "공부하거나 진로를 다시 생각해 보기 좋은 해예요."), + "정인": ("배움과 도움이 많은 해", "공부·자격증을 시작하거나 멘토를 찾기 좋은 해예요."), } -LOVE_RAINY = "비가 오니 실내 약속으로 잡으세요." diff --git a/backend/services/shorts_service.py b/backend/services/shorts_service.py index 30f27ea..3c38244 100644 --- a/backend/services/shorts_service.py +++ b/backend/services/shorts_service.py @@ -1,5 +1,5 @@ -import asyncio import json +import xml.etree.ElementTree as ET import httpx from redis.exceptions import RedisError @@ -29,11 +29,11 @@ class ShortsService: return await self.refresh() async def refresh(self) -> tuple[ErrorType, list[dict]]: - """유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로.""" + """유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로.""" try: async with httpx.AsyncClient(timeout=10) as client: items = await self._fetch(client) - except (httpx.HTTPError, KeyError, ValueError) as e: + except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) as e: LOG.error(f"[shorts] fetch: {e}") return ErrorType.EXTERNAL_API_ERROR, [] try: @@ -45,7 +45,6 @@ class ShortsService: async def _fetch(self, client: httpx.AsyncClient) -> list[dict]: if settings.youtube_api_key: found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS) - return [{"id": v["id"], "title": v["title"]} for v in found] - ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS] - 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] + else: + found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS) + return [{"id": v["id"], "title": v["title"]} for v in found] diff --git a/backend/tests/test_saju_api.py b/backend/tests/test_saju_api.py index 27bbfc2..c0f3a8e 100644 --- a/backend/tests/test_saju_api.py +++ b/backend/tests/test_saju_api.py @@ -37,6 +37,8 @@ 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 kinds = [x["kind"] for x in r["today"]["cards"]] 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 "week" not in r and "love" not in r and "money" not in r @@ -68,7 +70,7 @@ async def test_level_unlocks_sections_and_awards_once(offline): h7 = await _login(c, "saju_07", points=1000) r = (await c.post("/v1/saju/reading", json=BIRTH, headers=h7)).json() - assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and len(r["year"]["months"]) == 3 + assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and 1 <= len(r["year"]["months"]) <= 3 @pytest.mark.anyio @@ -81,3 +83,27 @@ async def test_match_needs_level_five(offline): h5 = await _login(c, "match_05", points=400) 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("기운") + + +@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() diff --git a/backend/tests/test_shorts.py b/backend/tests/test_shorts.py index 111bf7a..7468567 100644 --- a/backend/tests/test_shorts.py +++ b/backend/tests/test_shorts.py @@ -6,7 +6,7 @@ import pytest from common.cache.redis_client import REDIS from common.enums import ErrorType from services import shorts_service -from services.external.youtube import channel_shorts, seconds, video_title +from services.external.youtube import channel_shorts, feed_shorts, seconds, video_title from services.shorts_service import CACHE_KEY, ShortsService @@ -58,6 +58,32 @@ async def test_video_title_none_when_embedding_blocked(): assert await video_title(client, "blocked") is None +def _feed(entries: list[tuple[str, str]]) -> str: + items = "".join( + f"{vid}제목 {vid}{published}" for vid, published in entries + ) + return f'{items}' + + +@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 async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch): calls = [] diff --git a/frontend/src/b/SajuPage.tsx b/frontend/src/b/SajuPage.tsx index bc251e8..10863c6 100644 --- a/frontend/src/b/SajuPage.tsx +++ b/frontend/src/b/SajuPage.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState, type ReactNode } from 'react' import { useNavigate } from 'react-router' -import { useMutation, useQuery } from '@tanstack/react-query' -import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { matchMutation, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { reading } from '@nalssigak/shared/api/client/sdk.gen' import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' @@ -9,7 +9,7 @@ import { cx } from '../lib/utils' import { useAuth } from './authContext' import { progress, useLevel } from './level' import { useRegion } from './regionContext' -import { BIRTH_PLACES, placeLon, setBirth, useBirth, validBirth, type Birth } from './sajuBirth' +import { BIRTH_PLACES, placeLon, useAccountBirth, useBirth, useSaveBirth, validBirth, type Birth } from './sajuBirth' import { useSheet } from './sheetContext' import { Ic, TAP44 } from './ui' @@ -17,6 +17,9 @@ const SEEN_KEY = 'nalssigak.b.sajuSeen' const EL_COLOR: Record = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] } const CARD_ICON: Record = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' } const POS_WORD: Record = { 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) => ({ birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`, @@ -46,6 +49,7 @@ function markSeen() { export function SajuPage() { const navigate = useNavigate() const birth = useBirth() + const loading = useAccountBirth() const [editing, setEditing] = useState(false) const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/')) return ( @@ -59,26 +63,38 @@ export function SajuPage() { 날씨 사주 - {!birth || editing ? setEditing(false)} /> : setEditing(true)} />} + {loading && !birth ? ( +

내 생년월일을 불러오는 중이에요…

+ ) : !birth || editing ? ( + setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} /> + ) : ( + setEditing(true)} /> + )} ) } -function BirthForm({ initial, onDone }: { initial: Birth | null; onDone: () => void }) { +function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) { + const { loggedIn } = useAuth() + const save = useSaveBirth() const [y, setY] = useState(initial ? String(initial.y) : '') const [m, setM] = useState(initial ? String(initial.m) : '') const [d, setD] = useState(initial ? String(initial.d) : '') - const [time, setTime] = useState(initial?.hour != null ? `${String(initial.hour).padStart(2, '0')}:${String(initial.minute ?? 0).padStart(2, '0')}` : '') + const [hour, setHour] = useState(initial?.hour != null ? String(initial.hour) : '') + const [minute, setMinute] = useState(initial?.minute != null ? String(initial.minute) : '0') const [place, setPlace] = useState(initial?.place ?? 'seoul') const [error, setError] = useState('') - 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 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 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 save = () => { + const submit = () => { const [yy, mm, dd] = [Number(y), Number(m), Number(d)] - if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요') - const [hh, mi] = time ? time.split(':').map(Number) : [null, null] - setBirth({ y: yy, m: mm, d: dd, hour: hh, minute: mi, place, gender: initial?.gender ?? null }) - track('saju_input', { with_time: time !== '' }) + if (!y || !m || !d) return setError('생년월일을 모두 넣어 주세요') + if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요') + const hh = hour === '' ? null : Number(hour) + 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: hh != null }) onDone() } @@ -86,35 +102,63 @@ function BirthForm({ initial, onDone }: { initial: Birth | null; onDone: () => v
-

태어난 날의 기운으로
오늘 날씨와 맞춰 봐요

+

+ 내 사주와 오늘 날씨로 +
+ 오늘 하루를 봐요 +

- - -
+ +
+ 태어난 시각 (모르면 '모름') +
+ + +
+
+ {error &&

{error}

} - -

생년월일은 이 기기에만 저장돼요. 계산할 때만 보내고 서버에 남기지 않아요.

+ {onCancel && ( + + )} +

+ {loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'} +

) } @@ -122,13 +166,17 @@ function BirthForm({ initial, onDone }: { initial: Birth | null; onDone: () => v function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { const { region } = useRegion() 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 q = useQuery({ - queryKey: ['saju', body, loggedIn], + queryKey: ['saju', body, loggedIn, level], staleTime: 10 * 60_000, queryFn: async () => { const { data } = await reading({ body }) if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju') + if (loggedIn) queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) return data }, }) @@ -147,8 +195,16 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score }) }, [r]) - if (q.isPending) return

기운을 읽는 중이에요…

- if (!r?.today || !r.me) return

지금은 읽지 못했어요. 잠시 뒤에 다시 열어 주세요.

+ if (q.isPending) return

사주를 풀고 있어요…

+ if (!r?.today || !r.me) + return ( +
+

결과를 불러오지 못했어요.

+ +
+ ) const t = r.today const lock = (key: string) => r.locks?.find((l) => l.key === key) @@ -161,17 +217,17 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {

{t.score}

{t.title}

- 사주 {t.saju_score} + 사주 {t.saju_score}점 {t.weather_points != null && ( = 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}> - 오늘 날씨와 궁합 {t.weather_points >= 0 ? '+' : '−'} - {Math.abs(t.weather_points)} + 날씨 영향 {t.weather_points >= 0 ? '+' : '−'} + {Math.abs(t.weather_points)}점 )}
{(t.why?.length ?? 0) > 0 && (
- 왜 이 점수인가요? + 왜 이 점수인가요? (↑ 올린 것 · ↓ 내린 것)
    {t.why!.map((w) => (
  • {w}
  • @@ -192,9 +248,10 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { {r.week && } {r.money && ( - {[...r.money.map((l) => ['💰', l]), ...(r.work ?? []).map((l) => ['💼', l])].map(([icon, l]) => ( -

    - {icon} {l} + {[...r.money.map((l) => ['money_bag', l]), ...(r.work ?? []).map((l) => ['briefcase', l])].map(([icon, l]) => ( +

    + + {l}

    ))}
    @@ -224,7 +281,7 @@ function DecisionCard({ c }: { c: SajuCard }) {
    -

    {c.kind === 'when' ? '중요한 일은 이때' : c.title}

    +

    {c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}

    {c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}

    {c.kind === 'when' ? c.body : c.sub}

    @@ -236,7 +293,7 @@ function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) { const me = r.me! const cols = [...me.pillars].reverse() return ( - 생년월일 바꾸기}> + 생년월일 바꾸기}>

    {me.scene_desc}

    {(me.hour_known ? cols : [null, ...cols]).map((p, i) => ( @@ -249,15 +306,15 @@ function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) { ) : ( <> - ? - ? + 시각 모름 )}
    ))}
    - {(me.need?.length ?? 0) > 0 &&

    내 기운에 필요한 날씨: {me.need!.join(' · ')}

    } - {me.jeol_warning &&

    태어난 날 절기가 바뀌어요. 시각을 넣으면 더 정확해요.

    } +

    태어난 연·월·일·시의 여덟 글자(사주팔자)예요. 색은 나무·불·흙·쇠·물 다섯 기운이에요.

    + {(me.need?.length ?? 0) > 0 &&

    내 기운에 좋은 날씨: {me.need!.join(' · ')}

    } + {me.jeol_warning &&

    태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.

    } ) } @@ -298,13 +355,13 @@ function Locked({ locks }: { locks: SajuLock[] }) {
    -

    {loggedIn ? `다음에 열려요: ${next.name}` : '각을 모으면 차례로 열려요'}

    +

    {loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}

    - {loggedIn ? `Lv.${next.level}에서 열려요${close ? ` · ${level.next_points! - level.points}각 남았어요` : ''}` : '출석·사주·좋아요로 모은 각은 로그인해야 쌓여요'} + {loggedIn ? (close ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}

    {close && ( @@ -325,55 +382,63 @@ function Locked({ locks }: { locks: SajuLock[] }) { function Week({ r }: { r: ResSaju }) { return ( - +
      {r.week!.map((d) => (
    1. - - {d.weekday} {Number(d.day.slice(8, 10))}일 - + {dayWord(d.day, d.weekday)} {d.icon && } - {d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''} - {d.title} + {d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''} + {d.title} {d.score}
    2. ))}
    -

    점수는 그날 사주와 예보로 계산해요. 주황색이 이번 주 가장 좋은 날이에요.

    +

    점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.

    ) } function Love({ r, birth }: { r: ResSaju; birth: Birth }) { const love = r.love! - const pick = (g: 'M' | 'F' | null) => setBirth({ ...birth, gender: g }) + const save = useSaveBirth() + const pick = (g: 'M' | 'F' | null) => save({ ...birth, gender: g }) + const chip = 'cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1' return ( - + {love.good ? (
    -

    연애 기운 좋은 날

    +

    연애 기운이 좋은 날

    - {love.good.weekday}요일 {Number(love.good.day.slice(8, 10))}일{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''} + {dayWord(love.good.day, love.good.weekday)} + {love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}

    {love.good.body}

    {love.good.why}

    ) : ( -

    이번 주엔 연애 기운이 특별히 드는 날이 없어요.

    +

    앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.

    )} {love.caution && (

    - 조심할 날: {love.caution.weekday}요일 — {love.caution.body} ({love.caution.why}) + 조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} · {love.caution.why}

    )} - {!love.gender_known && ( -
    - 성별을 고르면 이성 기운까지 봐요 - - +
    )} @@ -385,11 +450,15 @@ function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable

    - {p.title} ({p.pillar} · {p.ten_god}) + {p.title} ({p.ten_god})

    {p.body}

    - {(p.months?.length ?? 0) > 0 &&

    잘 맞는 달: {p.months!.map((m) => `${m}월`).join(' · ')}

    } - {(p.notes?.length ?? 0) > 0 &&

    {p.notes!.join(' · ')}

    } + {(p.months?.length ?? 0) > 0 &&

    {p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}

    } + {p.notes?.map((n) => ( +

    + {n} +

    + ))}
    ) } @@ -402,10 +471,11 @@ function Match({ birth }: { birth: Birth }) { const [error, setError] = useState('') const run = useMutation({ ...matchMutation() }) const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined - 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 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 go = () => { const [yy, mm, dd] = [Number(y), Number(m), Number(d)] - if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요') + if (!y || !m || !d) return setError('상대 생년월일을 모두 넣어 주세요') + if (!validBirth(yy, mm, dd)) return 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 } } }) } @@ -420,7 +490,7 @@ function Match({ birth }: { birth: Birth }) {

    - {res.title} {res.score} + {res.title} {res.score}점

    {res.lines?.map((l) => (

    @@ -429,23 +499,25 @@ function Match({ birth }: { birth: Birth }) { ))} {res.day && (

    - 이번 주 같이 나가기 좋은 날: {res.day.weekday}요일 {Number(res.day.day.slice(8, 10))}일{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''} + 앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)} + {res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}

    )}

    상대 기운: {res.friend_scene}

    ) : ( <> -

    상대 생년월일(양력)을 넣으면 둘의 사이와 이번 주 같이 나가기 좋은 날을 봐요.

    -
    - setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" /> - setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" /> - setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" /> +

    상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.

    +
    + setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" /> + setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" /> + setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
    {error &&

    {error}

    } + {(run.isError || (run.data && !run.data.result?.success)) &&

    궁합을 불러오지 못했어요. 다시 눌러 주세요.

    }

    상대 생년월일은 저장하지 않아요.

    )} diff --git a/frontend/src/b/level.tsx b/frontend/src/b/level.tsx index cf518ff..1178ece 100644 --- a/frontend/src/b/level.tsx +++ b/frontend/src/b/level.tsx @@ -13,8 +13,14 @@ import { Ic } from './ui' const ACTION_TO: Record = { saju: '/saju', react: '/', talk: '/talk' } const ACTION_FEATURE: Record = { 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)에 이동해야 새 주소가 안 지워진다 -function useCloseAndGo() { +export function useCloseAndGo() { const { close } = useSheet() const navigate = useNavigate() return (to: string) => { @@ -125,8 +131,11 @@ export function LevelCard({ link = true }: { link?: boolean }) {
    - {level.next_points != null ? `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}` : '가장 높은 레벨이에요'} - {unlock.length > 0 && · {unlock.join(', ')}} + {level.next_points == null + ? '가장 높은 레벨이에요' + : unlock.length > 0 + ? `${level.next_points - level.points}각 더 모으면 ${josa(unlock.join(', '), '이', '가')} 열려요` + : `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}`} {link && (
-

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

+

{level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'}

레벨이 오르면 열려요

@@ -183,7 +192,7 @@ export function LevelSheet() { Lv.{lv} {name} · {points}각 - {lv === 1 ? '지금 있는 기능 전부' : (steps[lv] ?? []).join(', ')} + {lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')} ) @@ -203,12 +212,12 @@ export function LevelUpSheet({ level: lv }: { level: number }) { const opened = unlocks.map((u) => u.name) const name = level?.levels?.find((l) => l.level === lv)?.name return ( -
+
Lv.{lv} {name} - {opened.length > 0 &&

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

} + {opened.length > 0 &&

이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요

} {unlocks.length > 0 && (