feat: 사주 금전·일은 이번 주에 정할 날로, 올해 운에 잘 맞는 달, 레벨업 창에서 열린 칸으로 바로 가기

- 금전·일: 오늘 카드를 되풀이하지 않고 이번 주 중 결제·계약할 날, 돈 빌려주기 피할 날, 보고·면접 잡을 날
- 올해 운: 잘 맞는 달 3개, 11월부터는 다음 해 미리 보기
- 레벨업 창 '…보러 가기' → /saju#칸, 내 레벨 창의 각 모으는 일 줄을 누르면 그 화면으로
- 궁합 결과에 상대 생일과 다른 사람 보기
This commit is contained in:
minaChoi committed 2026-10-28 16:06:01 +09:00
1 parent e4834fd24e
commit cb013fcc9a
7 files changed
+121 -28

No files matched your search

+3 -2
View File
@@ -90,6 +90,7 @@ class SajuPeriod(WebPacketProtocol):
title: str
body: str
notes: list[str] = []
months: list[int] = Field([], description="올해: 잘 맞는 달 (양력 달)")
class SajuLock(WebPacketProtocol):
@@ -103,8 +104,8 @@ class Res_Saju(Res_WebPacketProtocol):
me: Optional[SajuMe] = None
today: Optional[SajuToday] = None
week: Optional[list[SajuDay]] = Field(None, description="레벨 2부터")
money: Optional[str] = Field(None, description="레벨 3부터")
work: Optional[str] = None
money: Optional[list[str]] = Field(None, description="레벨 3부터: 이번 주 돈을 정할 날·피할 날")
work: Optional[list[str]] = None
love: Optional[SajuLove] = Field(None, description="레벨 4부터")
month: Optional[SajuPeriod] = Field(None, description="레벨 6부터")
year: Optional[SajuPeriod] = Field(None, description="레벨 7부터")
+1 -1
View File
@@ -42,7 +42,7 @@ def _res(r: Reading) -> Res_Saju:
love=SajuLove(good=SajuLoveDay(**r.love["good"]) if r.love.get("good") else None, caution=SajuLoveDay(**r.love["caution"]) if r.love.get("caution") else None,
gender_known=r.love.get("gender") is not None) if r.love else None,
month=SajuPeriod(label=f"이달 · {r.month['from']:%-m/%-d} {r.month['jeol']} ~ {r.month['until']:%-m/%-d}", **{k: r.month[k] for k in ("pillar", "ten_god", "title", "body", "notes")}) if r.month else None,
year=SajuPeriod(label=f"{r.year['year']}년", **{k: r.year[k] for k in ("pillar", "ten_god", "title", "body", "notes")}) if r.year else None,
year=SajuPeriod(label=f"{r.year['year']}년" + (" 미리 보기" if r.year["preview"] else ""), months=r.year["months"], **{k: r.year[k] for k in ("pillar", "ten_god", "title", "body", "notes")}) if r.year else None,
level=r.level, logged_in=r.logged_in,
locks=[SajuLock(key=k, name=n, level=lv, unlocked=r.logged_in and r.level >= lv) for lv, items in UNLOCKS.items() for k, n in items],
)
+46 -4
View File
@@ -14,7 +14,7 @@ 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
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.pillars import Chart, Pillar, make_chart
from services.saju.rules import branch_relations, stem_relations, ten_god
@@ -254,6 +254,42 @@ def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) ->
return out
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 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)
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("이번 주는 하던 일을 마무리하기 좋아요.")
return money, work
def year_months(chart: Chart, year: int) -> list[int]:
"""그해 열두 달(절 기준) 중 내 사주와 잘 맞는 달 셋 (달 번호는 그 절이 드는 양력 달)"""
scored = []
for m in range(1, 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])
def period(chart: Chart, p: Pillar, unit: str) -> dict:
"""이달·올해: 그 간지 천간 십성 + 원국과의 관계"""
god = ten_god(chart.day.stem, p.stem)
@@ -338,6 +374,12 @@ class SajuService:
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))
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)}
async def match(
self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User],
) -> tuple[ErrorType, Optional[Match]]:
@@ -390,10 +432,10 @@ class SajuService:
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,
week=days if unlocked("saju_week") else None,
money=T.MONEY_TEXT[r0.facts.stem_ten_god] if unlocked("saju_money") else None,
work=T.WORK_TEXT[r0.facts.stem_ten_god] 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,
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,
year={**period(chart, now_chart.year, "해"), "year": today.year} if unlocked("saju_year") else None,
year=self._year(chart, today) if unlocked("saju_year") else None,
)
+2 -2
View File
@@ -61,14 +61,14 @@ async def test_level_unlocks_sections_and_awards_once(offline):
r = (await c.post("/v1/saju/reading", json={**BIRTH, "gender": "male"}, headers=h4)).json()
assert r["level"] == 4
assert len(r["week"]) == 7 and sum(d["best"] for d in r["week"]) == 1
assert r["money"] and r["work"] and r["love"]["gender_known"] is True
assert r["money"] and r["work"] and all(isinstance(x, str) for x in r["money"]) and r["love"]["gender_known"] is True
assert "month" not in r and "year" not in r
unlocked = {x["key"]: x["unlocked"] for x in r["locks"]}
assert unlocked["saju_love"] and not unlocked["saju_match"]
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 r["year"]["label"].endswith("년")
assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and len(r["year"]["months"]) == 3
@pytest.mark.anyio
+27 -12
View File
@@ -136,6 +136,11 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { open } = useSheet()
const r = q.data
useEffect(() => {
if (!r?.today || !window.location.hash) return
document.getElementById(window.location.hash.slice(1))?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}, [r])
useEffect(() => {
if (!r?.today) return
markSeen()
@@ -186,15 +191,18 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
{r.week && <Week r={r} />}
{r.money && (
<Panel icon="money_bag" title="금전운 · 일운">
<p className="m-0 text-[14px] font-semibold">💰 {r.money}</p>
<p className="m-0 mt-1.5 text-[14px] font-semibold">💼 {r.work}</p>
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
{[...r.money.map((l) => ['💰', l]), ...(r.work ?? []).map((l) => ['💼', l])].map(([icon, l]) => (
<p key={l} className="m-0 mt-1 text-[14px] font-semibold first:mt-0">
{icon} {l}
</p>
))}
</Panel>
)}
{r.love && <Love r={r} birth={birth} />}
{lock('saju_match')?.unlocked && <Match birth={birth} />}
{r.month && <Period icon="spiral_calendar" p={r.month} />}
{r.year && <Period icon="sunrise" p={r.year} />}
{r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<div className="mx-4 flex items-center justify-between">
@@ -264,9 +272,9 @@ function Char({ c, ko, el }: { c: string; ko: string; el: string }) {
)
}
function Panel({ icon, title, right, children }: { icon: string; title: string; right?: ReactNode; children: ReactNode }) {
function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
return (
<section className="mx-4 rounded-[22px] bg-white px-4 py-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<section id={id} className="mx-4 scroll-mt-20 rounded-[22px] bg-white px-4 py-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<div className="mb-2 flex items-center gap-2">
<Ic name={icon} className="size-7" />
<h3 className="m-0 font-jua text-[17px] font-normal">{title}</h3>
@@ -317,7 +325,7 @@ function Locked({ locks }: { locks: SajuLock[] }) {
function Week({ r }: { r: ResSaju }) {
return (
<Panel icon="spiral_calendar" title="이번 주 흐름">
<Panel id="saju_week" icon="spiral_calendar" title="이번 주 흐름">
<ol className="m-0 flex list-none flex-col gap-1 p-0">
{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]')}>
@@ -340,7 +348,7 @@ function Love({ r, birth }: { r: ResSaju; birth: Birth }) {
const love = r.love!
const pick = (g: 'M' | 'F' | null) => setBirth({ ...birth, gender: g })
return (
<Panel icon="red_heart" title="이번 주 연애운">
<Panel id="saju_love" icon="red_heart" title="이번 주 연애운">
{love.good ? (
<div className="rounded-xl bg-[#fff0f3] px-3 py-2.5">
<p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운 좋은 날</p>
@@ -373,13 +381,14 @@ function Love({ r, birth }: { r: ResSaju; birth: Birth }) {
)
}
function Period({ icon, p }: { icon: string; p: NonNullable<ResSaju['month']> }) {
function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel icon={icon} title={p.label}>
<Panel id={id} icon={icon} title={p.label}>
<p className="m-0 font-jua text-[17px]">
{p.title} <span className="text-[13px] text-(--ink3)">({p.pillar} · {p.ten_god})</span>
</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.months!.map((m) => `${m}월`).join(' · ')}</p>}
{(p.notes?.length ?? 0) > 0 && <p className="m-0 mt-1 text-xs font-semibold text-(--ink3)">{p.notes!.join(' · ')}</p>}
</Panel>
)
@@ -401,9 +410,15 @@ function Match({ birth }: { birth: Birth }) {
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 } } })
}
return (
<Panel icon="two_hearts" title="궁합">
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<p className="m-0 mb-1 flex items-center justify-between text-xs font-bold text-(--ink3)">
상대 {y}.{m}.{d}생
<button type="button" onClick={() => run.reset()} className="cursor-pointer font-extrabold text-(--orange)">
다른 사람 보기
</button>
</p>
<p className="m-0 font-jua text-[19px]">
{res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}</span>
</p>
+33 -4
View File
@@ -1,4 +1,5 @@
import { useEffect, useRef } from 'react'
import { useNavigate } from 'react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { attendMutation, myLevelOptions, myLevelQueryKey, sharedMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen'
@@ -8,6 +9,20 @@ import { HIDDEN } from './features'
import { useSheet } from './sheetContext'
import { Ic } from './ui'
// 각을 주는 일 → 그 일을 하러 가는 곳, 숨긴 기능에 딸린 일 (서버 ACTIONS 키)
const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' }
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' }
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다
function useCloseAndGo() {
const { close } = useSheet()
const navigate = useNavigate()
return (to: string) => {
window.addEventListener('popstate', () => navigate(to), { once: true })
close()
}
}
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 LEVELS)
const LEVEL_ICON = ['droplet', 'sun', 'leaf', 'rainbow', 'sunset', 'milky_way', 'shooting_star']
export const levelIcon = (level: number) => LEVEL_ICON[Math.min(Math.max(level, 1), LEVEL_ICON.length) - 1]
@@ -126,6 +141,7 @@ export function LevelCard({ link = true }: { link?: boolean }) {
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
export function LevelSheet() {
const level = useLevel().data
const go = useCloseAndGo()
if (!level) return null
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {})
return (
@@ -134,15 +150,21 @@ export function LevelSheet() {
<section>
<h4 className="m-0 mb-2 text-sm font-extrabold">오늘 받을 수 있는 각</h4>
<ul className="m-0 list-none rounded-2xl bg-white p-0 shadow-[inset_0_-4px_0_var(--shade)]">
{(level.today ?? []).filter((a) => !HIDDEN.has(a.action)).map((a) => {
{(level.today ?? []).filter((a) => !HIDDEN.has(ACTION_FEATURE[a.action] ?? a.action)).map((a) => {
const done = a.earned >= a.cap
const to = ACTION_TO[a.action]
return (
<li key={a.action} className="flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0">
<li
key={a.action}
onClick={to && !done ? () => go(to) : undefined}
className={cx('flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0', to && !done && 'cursor-pointer')}
>
<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="ml-auto font-bagel text-[13px] font-normal text-(--orange)">
{a.earned > 0 && a.cap > a.points ? `${a.earned}/${a.cap}` : `+${a.points}`}각
</span>
{to && !done && <span className="text-(--ink3)">›</span>}
</li>
)
})}
@@ -176,7 +198,9 @@ export function LevelSheet() {
export function LevelUpSheet({ level: lv }: { level: number }) {
const level = useLevel().data
const { open } = useSheet()
const opened = (level?.unlocks ?? []).filter((u) => u.level === lv).map((u) => u.name)
const go = useCloseAndGo()
const unlocks = (level?.unlocks ?? []).filter((u) => u.level === lv)
const opened = unlocks.map((u) => u.name)
const name = level?.levels?.find((l) => l.level === lv)?.name
return (
<div className="flex flex-col items-center gap-2 px-6 pt-2 pb-6 text-center">
@@ -185,7 +209,12 @@ export function LevelUpSheet({ level: lv }: { level: number }) {
Lv.{lv} {name}
</b>
{opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">새로 열렸어요: {opened.join(', ')}</p>}
<button type="button" onClick={() => open({ type: 'level' })} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
{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">
{opened[0]} 보러 가기
</button>
)}
<button type="button" onClick={() => open({ type: 'level' })} className={cx('w-full cursor-pointer py-2 text-[14px] font-extrabold', unlocks.length ? 'text-(--ink2)' : 'mt-3 rounded-full bg-(--orange) py-3 text-white')}>
내 레벨 보기
</button>
</div>
+9 -3
View File
@@ -2947,13 +2947,13 @@ export type ResSaju = {
/**
* Money
*
* 레벨 3부터
* 레벨 3부터: 이번 주 돈을 정할 날·피할 날
*/
money?: string | null;
money?: Array<string> | null;
/**
* Work
*/
work?: string | null;
work?: Array<string> | null;
/**
* 레벨 4부터
*/
@@ -3730,6 +3730,12 @@ export type SajuPeriod = {
* Notes
*/
notes?: Array<string>;
/**
* Months
*
* 올해: 잘 맞는 달 (양력 달)
*/
months?: Array<number>;
};
/**