Merge remote-tracking branch 'origin/main' into sns

This commit is contained in:
minaChoi committed 2026-10-30 11:37:28 +09:00
commit 1f040bc6d4
116 files changed
+2441 -471

No files matched your search

+20 -2
View File
@@ -30,15 +30,33 @@ $ARGUMENTS 가 있으면 위 목록에 더한다.
- `docs/검색_노출.md` 5장(노출 기록)의 '기록' 표 맨 아래에 오늘 날짜 행을 더한다. 형식은 그 표를 따른다.
- 어제 행과 비교해 바뀐 것(새로 잡힘·빠짐·순위 변화·색인 주소 수)을 뽑는다.
## 5. 다음 할 일 제안
## 5. 원인 분석 (빠짐·순위 하락이 하나라도 있으면 반드시)
숫자만 보고하고 끝내지 않는다. 왜 그렇게 됐는지 아래를 직접 확인하고, 확인한 것·배제한 것·남은 가설을 나눠 적는다.
- 페이지 상태: 빠진 주소를 Googlebot·Yeti UA 로 curl 해 상태 코드·title·canonical·robots meta, robots.txt 를 본다.
- 렌더 뒤 화면: 구글은 JS 실행 뒤 HTML 로 색인한다. 헤드리스 Chrome(`--headless=new --virtual-time-budget=20000 --dump-dom`, Googlebot UA)으로 렌더해 h1·검색어 문구·자주 묻는 질문이 남는지 센다.
- 색인 여부: 구글·네이버 `site:weather.o2o.kr <지역>` 에 그 주소가 있는지. 없으면 색인 문제, 있으면 순위 문제.
- 봇 방문: `ssh King_admin 'docker logs --since 72h o2o-weather-frontend-1'` 에서 Googlebot·Yeti 가 그 주소를 받았는지·상태 코드.
- 바뀐 것: 직전 측정 이후 `git log --since=<직전 측정일> -- frontend backend` 로 그 페이지 화면·제목·사이트맵에 닿은 커밋을 찾는다. 배포 시각과 측정 시각의 앞뒤를 맞춘다.
- 사이트 안 경쟁: `site:` 결과에 같은 검색어를 두고 겹치는 다른 주소(예: /shorts/*)가 있는지.
- 측정 잡음: 직전 순위가 구글 2p·네이버 10위 밖처럼 경계였는지, 직전 측정이 실패(`?`)였는지.
## 6. 대안 제시
- 원인마다 고칠 방법 1~3개와 추천 하나, 각 방법의 근거(공식 문서 또는 위에서 확인한 사실)와 예상 효과·단점을 쓴다.
- 고칠지는 AskUserQuestion 으로 묻고, 고르면 그대로 고친다.
## 7. 다음 할 일 제안
- 근거는 공식 문서만 쓴다: `docs/검색_노출.md` 4장(구글 검색 정책), 구글 Search Central, 네이버 서치어드바이저 가이드. 문서에 없는 건 "문서에 없음"이라 쓰고, 판단·추정은 따로 표시한다.
- 같은 페이지를 매일 수집 요청하지 않는다(네이버: 반영에 1일~몇 주, 매일 반복 불필요).
- 바꾼 뒤 결과는 몇 주 단위로 본다(구글: 변경 반영에 몇 시간~몇 달). 하루 변화로 원인을 단정하지 않는다.
- 코드·문구 수정이 필요하면 고치지 말고 제안만 하고, 결정이 필요한 건 `TODO.md`에 적는다.
## 6. 보고 (채팅, 짧게)
## 8. 보고 (채팅, 짧게)
- 바뀐 것 3줄 이내
- 검색어별 구글/네이버 순서 (없음·차단 포함)
- 빠짐·하락의 원인 분석(확인한 것·배제한 것·가설)과 대안·추천
- 다음 할 일 1~3개 (근거 출처 포함)
+75
View File
@@ -0,0 +1,75 @@
---
name: ga-report
description: 날씨각 GA4 와 운영 DB 숫자로 지난 기간 사용 현황을 분석해 바뀐 것·원인·다음 할 일을 짧게 보고한다
argument-hint: "<일수> 예) 7 · 28 (비우면 7일)"
---
날씨각(weather.o2o.kr·토스판) 사용 현황을 GA4 와 운영 DB 로 보고, 바로 앞 같은 길이 기간과 비교해 판단과 다음 할 일을 낸다. 인자 `$ARGUMENTS` = 일수(비우면 7). 기간은 어제까지(오늘은 하루가 안 끝나 뺀다). 아래 경로는 모두 저장소 루트 기준이다.
## 0. 처음 한 번 (PC마다)
- GA 키: 팀에서 받은 JSON 을 저장소 원본 폴더의 `secrets/ga-key.json` 으로 둔다(`secrets/` 는 `.gitignore` 라 커밋되지 않는다). 키는 사람마다 따로 발급한다(GCP `nalssigak` → 서비스 계정 `nalssigak-ga` → 키 추가). 키를 메신저·메일·git 으로 다시 돌리지 않는다.
- `uv` 가 없으면 `brew install uv`.
- 키가 없으면 1번 스크립트가 "GA 키가 없어요" 로 멈춘다. 그때는 사용자에게 키를 받으라고 알리고 멈춘다.
- (선택) Claude Code 에서 GA 를 직접 묻고 싶으면 `claude mcp add analytics-mcp --scope user -e GOOGLE_APPLICATION_CREDENTIALS=<저장소 원본 폴더>/secrets/ga-key.json -e GOOGLE_CLOUD_PROJECT=nalssigak -- uvx analytics-mcp` 후 Claude Code 를 다시 시작한다.
## 1. GA4 받기
```
uvx --from analytics-mcp python .claude/skills/ga-report/ga_pull.py <일수> > /tmp/ga_report.json
```
- 키는 스크립트가 저장소 원본 폴더의 `secrets/ga-key.json` 에서 찾는다(워크트리에서 불러도 같음).
- 속성 `558046406`(날씨각 웹, 계정 AIO2O). 서비스 계정 `nalssigak-ga@nalssigak.iam.gserviceaccount.com`, 권한은 GA 뷰어뿐. 키 파일 내용은 열거나 옮기지 않는다.
- 결과 JSON: 값마다 `[이번, 앞 기간]`. `totals`·`daily`·`platform`·`host`·`channels`·`sources`·`landing`·`pages`·`devices`·`new_vs_returning`·`cities`·`events`·`gak_views`·`region_changes`, 퍼널 4개(`funnel_saju`·`funnel_game`·`funnel_install`·`funnel_login`, 이번 기간만), `cohorts`(첫 방문 주별 재방문).
- `errors` 가 비어 있지 않으면 그 항목은 못 받은 것이다. 보고에 적고 넘어간다.
- 더 파고들 게 있으면 `analytics-mcp` MCP 도구(`run_report`·`run_funnel_report`·`run_realtime_report`)를 쓴다. 이 세션에 도구가 없으면 같은 키로 `google.analytics.data_v1beta` 를 직접 부른다.
- 이벤트 뜻은 저장소 `docs/이벤트_추적.md` 이벤트 목록을 기준으로 읽는다.
## 2. 운영 DB 숫자 (읽기만, 집계만)
GA 는 로그인·레벨·사주 저장을 모른다. 같은 기간을 운영 DB 에서 센다. 개인 값(닉네임·아이디·생년월일)은 뽑지 않는다.
```
ssh King_admin 'docker exec -i o2o-weather-postgres-1 sh -c "psql -U \$POSTGRES_USER -d \$POSTGRES_DB"' <<'SQL'
\set s '<시작 YYYY-MM-DD>'
\set e '<끝 YYYY-MM-DD>'
SELECT provider, count(*) AS signups FROM users WHERE NOT deleted AND (created_at AT TIME ZONE 'Asia/Seoul')::date BETWEEN :'s' AND :'e' GROUP BY provider ORDER BY provider;
SELECT action, count(*) AS n, count(DISTINCT user_id) AS users FROM point_log WHERE day BETWEEN :'s' AND :'e' AND action <> 'admin' GROUP BY action ORDER BY n DESC;
SELECT count(DISTINCT user_id) AS active_earners FROM point_log WHERE day BETWEEN :'s' AND :'e' AND action <> 'admin';
SELECT lv, count(*) FROM (SELECT CASE WHEN p >= 1000 THEN 7 WHEN p >= 700 THEN 6 WHEN p >= 400 THEN 5 WHEN p >= 200 THEN 4 WHEN p >= 100 THEN 3 WHEN p >= 30 THEN 2 ELSE 1 END AS lv
FROM (SELECT u.user_id, COALESCE(sum(l.points) FILTER (WHERE l.action <> 'admin'), 0) AS p FROM users u LEFT JOIN point_log l USING (user_id) WHERE NOT u.deleted GROUP BY u.user_id) t) x GROUP BY lv ORDER BY lv;
SELECT count(*) FILTER (WHERE birth_date IS NOT NULL) AS birth_saved, count(*) AS users FROM users WHERE NOT deleted;
SQL
```
- provider: 1 아이디, 2 구글, 3 토스. 앞 기간도 같은 쿼리로 센다.
- `point_log` 의 `action='admin'` 은 관리자가 레벨을 올려 준 것이라 늘 뺀다. 레벨 경계는 `backend/services/level_service.py` `LEVELS` 를 따른다(바뀌었으면 쿼리도 맞춘다).
## 3. 그 기간에 바뀐 것
`git log origin/main --first-parent --since=<시작> --until=<끝+1일> --format='%ad %s' --date=short` 로 배포된 변화를 뽑는다. 숫자 변화와 날짜가 겹치는 변화를 후보 원인으로만 적는다.
## 4. 읽는 규칙
- **결론부터, 판단으로.** 숫자를 늘어놓지 말고 "무엇이 좋아졌고 나빠졌는지 → 왜 그렇게 보는지(근거 숫자) → 그래서 할 일" 순서로 쓴다. 전제에서 결론까지 고리를 빠짐없이 적는다.
- **작은 수는 사람 수로.** 한 칸이 30명 미만이면 비율(전환율·참여율)로 말하지 않고 "12명 중 3명"처럼 적는다. 앞 기간이 10명 미만이면 증감 %를 쓰지 않는다.
- **우리 팀 트래픽을 가린다.** 회사가 성남(분당)이라 `cities` 의 Seongnam-si, `region_changes` 에서 소수가 수십 번 바꾼 지역(예: 분당구 108번·7명)은 팀 테스트일 가능성이 크다. 그 몫을 빼고 봤을 때도 결론이 같은지 함께 적는다. 추정이면 "추정"이라고 표시한다.
- **한 기간 변화로 원인을 단정하지 않는다.** 배포·홍보(인스타·검색)와 날짜가 겹치면 "후보"로 두고, 2기간 이상 같은 방향일 때만 원인이라고 쓴다.
- **퍼널은 개발 서버 이벤트가 섞여 있다**(퍼널 API 에 호스트 거름을 안 걸었다). 큰 그림만 보고, 단계 사이 사람 수가 1~2명이면 판단하지 않는다.
- **못 보는 것은 못 본다고 쓴다.** 지금 GA 맞춤 측정기준은 `gak_name`·`platform`·`region_name` 셋뿐이라, `today_icon` 의 `icon`·`sheet_open` 의 `sheet`·`saju_view` 의 `score` 같은 값별 나눔은 GA 에서 안 나온다. 필요하면 "GA4 관리 → 맞춤 정의에 ○○ 등록"을 할 일로 낸다(등록 전 데이터는 소급 안 됨).
- `platform` 이 `(not set)` 인 몫은 그 값이 붙기 전 이벤트(자동 수집 `page_view`·`session_start` 등)다. 웹·토스 비교는 `host`(weather.o2o.kr vs nalssigak.apps.tossmini.com)로 본다.
## 5. 기록
- 저장소 `docs/이벤트_추적.md` 맨 아래 `## 분석 기록` 표(없으면 만든다: 날짜 · 기간 · 활성 사용자(앞 기간) · 신규 · 가입(DB) · 바뀐 것 · 할 일)에 한 줄 더한다.
- 결정이 필요한 것(맞춤 측정기준 등록, 내부 트래픽 필터, 기능 손보기)은 `TODO.md` 에 `[결정 필요]` 행으로 적는다.
- main 에 바로 커밋하지 않는다. 작업 브랜치에서 커밋해 main 에 합친다. 커밋은 `docs: <날짜> GA 분석 — <한 줄>`.
- 코드·문구는 고치지 않는다. 제안만 한다.
## 6. 보고 (채팅, 짧게)
1. **결론 3줄 이내**: 이번 기간 핵심 변화와 그 판단.
2. **바뀐 것 (앞 기간 대비)**: 사용자·신규·재방문, 유입 경로, 기능별 사용(사주·게임·오늘 한 장·쇼츠·단풍·동네 이야기·각 상세), 가입·레벨(DB). 기능마다 한 줄, 사람 수로.
3. **다음 할 일 1~3개**: 무엇을 · 왜(근거 숫자) · 기대 효과. 측정이 안 돼서 판단 못 한 건 "측정 먼저"로 낸다.
4. 못 받은 항목(`errors`)·못 보는 것이 있으면 한 줄.
+143
View File
@@ -0,0 +1,143 @@
"""날씨각 GA4 숫자를 한 번에 받아 JSON 으로 낸다. 이번 기간과 바로 앞 같은 길이 기간을 함께 받는다.
실행: uvx --from analytics-mcp python .claude/skills/ga-report/ga_pull.py [일수]
키는 저장소 원본 폴더의 secrets/ga-key.json (워크트리에서 불러도 원본 폴더 것을 쓴다). GOOGLE_APPLICATION_CREDENTIALS 가 있으면 그걸 쓴다.
개발 서버(localhost 등)에서 나간 이벤트는 모두 뺀다.
"""
import json
import os
import subprocess
import sys
from datetime import date, timedelta
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
common = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=os.path.dirname(os.path.abspath(__file__)),
capture_output=True, text=True, check=True).stdout.strip()
key = os.path.join(os.path.dirname(common), "secrets", "ga-key.json")
if not os.path.exists(key):
sys.exit(f"GA 키가 없어요: {key} (팀에서 받은 키 파일을 이 이름으로 두세요)")
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = key
from google.analytics.data_v1alpha import AlphaAnalyticsDataClient
from google.analytics.data_v1alpha import types as A
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
CohortSpec, Cohort, CohortsRange, DateRange, Dimension, Filter, FilterExpression, FilterExpressionList, Metric, OrderBy, RunReportRequest,
)
PROPERTY = "properties/558046406"
DAYS = int(sys.argv[1]) if len(sys.argv) > 1 else 7
END = date.today() - timedelta(days=1) # 오늘은 하루가 안 끝나 빼고 어제까지
CUR = (END - timedelta(days=DAYS - 1), END)
PREV = (CUR[0] - timedelta(days=DAYS), CUR[0] - timedelta(days=1))
DEV_HOSTS = ["localhost", "127.0.0.1", "192.168."]
beta = BetaAnalyticsDataClient()
alpha = AlphaAnalyticsDataClient()
out: dict = {"days": DAYS, "cur": [str(CUR[0]), str(CUR[1])], "prev": [str(PREV[0]), str(PREV[1])], "errors": []}
def not_dev() -> FilterExpression:
return FilterExpression(not_expression=FilterExpression(or_group=FilterExpressionList(expressions=[
FilterExpression(filter=Filter(field_name="hostName", string_filter=Filter.StringFilter(match_type=Filter.StringFilter.MatchType.CONTAINS, value=h)))
for h in DEV_HOSTS
])))
def event_is(name: str) -> FilterExpression:
return FilterExpression(filter=Filter(field_name="eventName", string_filter=Filter.StringFilter(value=name)))
def both(a: FilterExpression, b: FilterExpression) -> FilterExpression:
return FilterExpression(and_group=FilterExpressionList(expressions=[a, b]))
def report(key: str, dims: list[str], metrics: list[str], limit: int = 30, compare: bool = True, where: FilterExpression | None = None) -> None:
"""이번·앞 기간 표. 행마다 {dims..., metric: [이번, 앞]}"""
ranges = [DateRange(start_date=str(CUR[0]), end_date=str(CUR[1]), name="cur")]
if compare:
ranges.append(DateRange(start_date=str(PREV[0]), end_date=str(PREV[1]), name="prev"))
try:
r = beta.run_report(RunReportRequest(
property=PROPERTY, date_ranges=ranges, dimensions=[Dimension(name=d) for d in dims], metrics=[Metric(name=m) for m in metrics],
dimension_filter=both(not_dev(), where) if where else not_dev(), limit=limit * 2,
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name=metrics[0]), desc=True)],
))
except Exception as e:
out["errors"].append(f"{key}: {e}")
return
rows: dict[tuple, dict] = {}
for row in r.rows:
vals = [v.value for v in row.dimension_values]
rng = vals[-1] if compare else "cur"
k = tuple(vals[:len(dims)])
item = rows.setdefault(k, {**dict(zip(dims, k)), **{m: [0, 0] for m in metrics}})
for m, v in zip(metrics, row.metric_values):
item[m][0 if rng == "cur" else 1] = round(float(v.value), 3)
out[key] = sorted(rows.values(), key=lambda x: -x[metrics[0]][0])[:limit]
def funnel(key: str, steps: list[tuple[str, str, str | None]]) -> None:
"""(단계 이름, 이벤트, page_location 에 들어갈 글자) 순서대로. 이번 기간만"""
def step(name: str, event: str, path: str | None) -> A.FunnelStep:
f = A.FunnelEventFilter(event_name=event)
if path:
f.funnel_parameter_filter_expression = A.FunnelParameterFilterExpression(funnel_parameter_filter=A.FunnelParameterFilter(
event_parameter_name="page_location", string_filter=A.StringFilter(match_type=A.StringFilter.MatchType.CONTAINS, value=path)))
return A.FunnelStep(name=name, filter_expression=A.FunnelFilterExpression(funnel_event_filter=f))
try:
r = alpha.run_funnel_report(A.RunFunnelReportRequest(
property=PROPERTY, date_ranges=[A.DateRange(start_date=str(CUR[0]), end_date=str(CUR[1]))],
funnel=A.Funnel(steps=[step(*s) for s in steps]),
))
except Exception as e:
out["errors"].append(f"{key}: {e}")
return
table = r.funnel_table
heads = [h.name for h in table.metric_headers]
out[key] = [{"step": row.dimension_values[0].value, **{h: round(float(v.value), 3) for h, v in zip(heads, row.metric_values)}} for row in table.rows]
def cohorts() -> None:
"""첫 방문 주별 4개 묶음이 그다음 주들에 몇 명 다시 왔는지"""
monday = END - timedelta(days=END.weekday())
groups = [Cohort(name=f"week_{i}", dimension="firstSessionDate", date_range=DateRange(
start_date=str(monday - timedelta(weeks=i)), end_date=str(monday - timedelta(weeks=i) + timedelta(days=6)))) for i in range(4, 0, -1)]
try:
r = beta.run_report(RunReportRequest(
property=PROPERTY, dimensions=[Dimension(name="cohort"), Dimension(name="cohortNthWeek")], metrics=[Metric(name="cohortActiveUsers")],
cohort_spec=CohortSpec(cohorts=groups, cohorts_range=CohortsRange(granularity=CohortsRange.Granularity.WEEKLY, end_offset=3)),
))
except Exception as e:
out["errors"].append(f"cohorts: {e}")
return
table: dict[str, dict] = {}
for g in groups:
table[g.name] = {"first_week": g.date_range.start_date}
for row in r.rows:
c, n = row.dimension_values[0].value, int(row.dimension_values[1].value)
table[c][f"week+{n}"] = int(row.metric_values[0].value)
out["cohorts"] = list(table.values())
report("totals", [], ["activeUsers", "newUsers", "sessions", "engagedSessions", "engagementRate", "averageSessionDuration", "screenPageViews", "eventCount"])
report("daily", ["date"], ["activeUsers", "newUsers", "sessions"], limit=DAYS, compare=False)
report("platform", ["customEvent:platform"], ["activeUsers", "sessions", "eventCount"])
report("host", ["hostName"], ["activeUsers", "sessions"], limit=10)
report("channels", ["sessionDefaultChannelGroup"], ["sessions", "activeUsers", "engagementRate"])
report("sources", ["sessionSource", "sessionMedium"], ["sessions", "activeUsers", "engagementRate"], limit=15)
report("landing", ["landingPage"], ["sessions", "engagementRate", "averageSessionDuration"], limit=20)
report("pages", ["pagePath"], ["screenPageViews", "activeUsers", "userEngagementDuration"], limit=25)
report("devices", ["deviceCategory", "operatingSystem"], ["activeUsers", "sessions", "engagementRate"], limit=10)
report("new_vs_returning", ["newVsReturning"], ["activeUsers", "sessions", "engagementRate"])
report("cities", ["city"], ["activeUsers"], limit=15)
report("events", ["eventName"], ["eventCount", "totalUsers"], limit=60)
report("gak_views", ["customEvent:gak_name"], ["eventCount", "totalUsers"], limit=15, where=event_is("view_gak"))
report("region_changes", ["customEvent:region_name"], ["eventCount", "totalUsers"], limit=15, where=event_is("region_change"))
funnel("funnel_saju", [("사주 페이지", "page_view", "/saju"), ("생년월일 넣음", "saju_input", None), ("결과 봄", "saju_view", None)])
funnel("funnel_game", [("게임 페이지", "page_view", "/game"), ("첫 판 시작", "game_start", None), ("라운드 깸", "game_round", None), ("끝까지 함", "game_over", None)])
funnel("funnel_install", [("설치 카드 봄", "install_banner_view", None), ("설치 누름", "install_click", None), ("설치 완료", "install_done", None)])
funnel("funnel_login", [("첫 방문", "first_visit", None), ("창 열기", "sheet_open", None), ("로그인", "login", None)])
cohorts()
print(json.dumps(out, ensure_ascii=False, indent=1))
+19
View File
@@ -99,6 +99,8 @@
| [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(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` |
| [x] | 사주 보정(10/29 사용자 지적: 토 많은 未월생이 '장맛비 기운'으로 나옴) — 월령 바탕값, 흙은 계절 따라 조습, 未 0.9, 오행 세력(지장간 날 수·월지 30·일지 20·그 외 10)·신강신약, 균형 축 이름은 세력 1위 오행 쪽 | 『궁통보감』 三夏己土, 계산식 `docs/사주_계산식.md` | `backend/services/saju/climate.py`, `strength.py` |
| [ ] | **[결정 필요]** 사주 명식 C안(요약 먼저형) 문구 확인 — 10/29 사용자 C안 선택, 구현은 `fix/saju-climate`(제목 '사주 명식', '흙(土) 기운이 가장 센 신강 사주', 오행 막대, 십성·'나'·월령 표시, 용어 풀이 10개). 문구 확인 뒤 병합 | 시안 v5, 사용자 선택 10/29 | `frontend/src/b/SajuPage.tsx` `MeCard`, `backend/router/v1/saju/saju.py` |
## 진행 순서
@@ -438,3 +440,20 @@ docs를 6개로 합칠 때 옛 내용을 그대로 옮겼다. 아래는 코드
| [ ] | 5단계: `.ait` 번들을 콘솔에 올리고 검수 요청 (3~5영업일, 반려 시 다시 3~5일) | 출시 | |
| [ ] | **[결정 필요]** 6단계(출시 후): 스마트 발송(알림) — 금요일 주말 판정, 노을 좋은 날. 노을 알림은 위 '노을 알림 재검토' 행 | 출시 후 별도 결정 | |
| [ ] | **[결정 필요]** 6단계(출시 후): 포인트 — 출시 후 2주만 쓰고 끊는다. 포인트를 끊은 주의 재방문율로 계속할지 판단 | 출시 후 별도 결정 | |
## GA 분석 (`/ga-report`, 기록은 `docs/이벤트_추적.md` '분석 기록')
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [ ] | **[결정 필요]** 자동 화면 테스트 트래픽을 GA에서 빼기 — ① 운영 사이트를 여는 Playwright 스크립트에서 GA 요청(googletagmanager·google-analytics)을 막기 ② GA4 관리 → 데이터 스트림 → 내부 트래픽 정의(사무실 IP) + 데이터 필터 활성 | 10/22~10/28 활성 206명 중 약 146명이 성남·아이폰 390x844(Playwright iPhone 기본 크기)·근무시간·참여 2~3초. 이대로면 사용자 수·전환율이 모두 틀림 | `/tmp/sweep/*.mjs` 등 Playwright 스크립트, GA4 관리 |
| [ ] | **[결정 필요]** GA4 맞춤 측정기준(이벤트 범위) 추가 등록 — `icon`(today_icon)·`sheet`(sheet_open)·`from`·`method`·`content_type`·`round`(game) | 지금 등록된 건 `gak_name`·`platform`·`region_name` 뿐이라 오늘 탭 아이콘별·창별·게임 라운드별 사용을 GA에서 못 나눔. 등록 전 데이터는 소급 안 됨 | GA4 관리 → 맞춤 정의 |
| [ ] | **[결정 필요]** '홈 화면에 추가' 카드 손보기 — 띄우는 조건(몇 번째 방문부터)·문구, 또는 빼기 | 10/22~10/28 테스트 트래픽 뺀 77명이 봤고 누른 사람 0 (앞 주 8명 중 1명 설치) | `frontend/src/b/installBanner.tsx` |
## 기념일 꾸밈 (`frontend/src/b/holiday.ts`)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [ ] | `feat/halloween` main 병합 → 킹서버 배포(백엔드 `TalkTopic` 6~9 포함). 10/31 00시 전에 올라가야 할로윈이 켜짐 | 10/30 킹서버 작업 중이라 배포 보류 | `deploy.sh` |
| [ ] | 할로윈 타로·코디 카드 (`/daily-tarot 할로윈`, `/daily-ootd`) — 킹서버 게시라 보류 | 10/30 킹서버 작업 중 | |
| [ ] | 2028년부터 추석 날짜 추가 (음력이라 해마다 `ranges` 에 한 줄) | 2027-09-14~16만 들어 있음 | `frontend/src/b/holiday.ts` |
+4 -1
View File
@@ -401,7 +401,9 @@ class Comment(Base):
__tablename__ = "comment"
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
post_id: Mapped[int] = mapped_column(BigInteger)
# 포스트 댓글은 post_id, 사람 글 댓글은 talk_id 하나만 채운다
post_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
talk_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)
ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
@@ -504,6 +506,7 @@ class Talk(Base):
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
topic: Mapped[int] = mapped_column(SmallInteger, default=1)
like_count: Mapped[int] = mapped_column(Integer, default=0)
comment_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+4
View File
@@ -125,6 +125,10 @@ class TalkTopic(CodeEnum):
RAIN = 3 # 비·눈
FOLIAGE = 4 # 단풍·꽃
OUTFIT = 5 # 오늘 옷차림
HALLOWEEN = 6 # 기념일 주제: 그 기간에만 고를 수 있다 (frontend holiday.ts)
PEPERO = 7
CHRISTMAS = 8
CHUSEOK = 9
class TalkReport(CodeEnum):
+29 -17
View File
@@ -6,12 +6,20 @@ from sqlalchemy import delete, func, or_, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, Talk, User, UserBlock
from common.liker import Liker
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
async def _count(s: AsyncSession, post_id: Optional[int], talk_id: Optional[int], delta: int) -> None:
"""댓글이 달린 곳(사람 글 또는 포스트)의 댓글 수를 고친다."""
if talk_id is not None:
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(comment_count=Talk.comment_count + delta))
elif post_id is not None:
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + delta))
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
model, keys = (member, {id_name: id_value, "user_id": who.user_id}) if who.user_id is not None else (anon, {id_name: id_value, "ip_hash": who.ip_hash})
@@ -54,10 +62,13 @@ class ReactionCRUD:
stmt = stmt.where(Post.post_id < cursor)
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
async def comments(
self, s: AsyncSession, post_id: Optional[int], viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int, talk_id: Optional[int] = None,
) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""포스트(post_id) 또는 사람 글(talk_id)의 댓글. 로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
target = Comment.talk_id == talk_id if talk_id is not None else Comment.post_id == post_id
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
target, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
)
if viewer is not None:
stmt = stmt.where(
@@ -76,10 +87,11 @@ class ReactionCRUD:
stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids))
return set((await s.scalars(stmt)).all())
async def add_comment(self, s: AsyncSession, post_id: int, who: Liker, body: str, region_name: Optional[str]) -> Comment:
c = Comment(post_id=post_id, user_id=who.user_id, body=body) if who.user_id is not None else Comment(post_id=post_id, ip_hash=who.ip_hash, region_name=region_name, body=body)
async def add_comment(self, s: AsyncSession, post_id: Optional[int], who: Liker, body: str, region_name: Optional[str], talk_id: Optional[int] = None) -> Comment:
c = (Comment(post_id=post_id, talk_id=talk_id, user_id=who.user_id, body=body) if who.user_id is not None
else Comment(post_id=post_id, talk_id=talk_id, ip_hash=who.ip_hash, region_name=region_name, body=body))
s.add(c)
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1))
await _count(s, post_id, talk_id, 1)
await s.flush()
return c
@@ -90,14 +102,14 @@ class ReactionCRUD:
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
.values(deleted=True).returning(Comment.post_id, Comment.talk_id, Comment.is_hidden)
)
row = res.first()
if row is None:
return False
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
if not row.is_hidden:
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
await _count(s, row.post_id, row.talk_id, -1)
return True
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
@@ -120,22 +132,22 @@ class ReactionCRUD:
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False))
.values(is_hidden=True).returning(Comment.post_id)
.values(is_hidden=True).returning(Comment.post_id, Comment.talk_id)
)
post_id = res.scalar()
if post_id is not None:
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
row = res.first()
if row is not None:
await _count(s, row.post_id, row.talk_id, -1)
async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool:
"""운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다."""
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False))
.values(is_hidden=hidden).returning(Comment.post_id)
.values(is_hidden=hidden).returning(Comment.post_id, Comment.talk_id)
)
post_id = res.scalar()
if post_id is None:
row = res.first()
if row is None:
return False
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1)))
await _count(s, row.post_id, row.talk_id, -1 if hidden else 1)
return True
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
+9 -4
View File
@@ -6,7 +6,7 @@ from typing import Optional
from sqlalchemy import delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, CommentReport, PointLog, Post, PostLike, PostSave, User, UserBlock
from common.database.model.models import Comment, CommentLike, CommentReport, PointLog, Post, PostLike, PostSave, Talk, User, UserBlock
class UserCRUD:
@@ -74,12 +74,17 @@ class UserCRUD:
if reported:
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).all()
mine = (await s.execute(
delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.talk_id, Comment.deleted, Comment.is_hidden)
)).all()
if mine:
ids = [c for c, _, _, _ in mine]
ids = [c for c, *_ in mine]
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).items():
shown = [(p, t) for _, p, t, deleted, hidden in mine if not deleted and not hidden]
for post_id, n in Counter(p for p, t in shown if t is None).items():
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n))
for talk_id, n in Counter(t for _, t in shown if t is not None).items():
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(comment_count=Talk.comment_count - n))
await s.execute(delete(User).where(User.user_id == user_id))
+1 -1
View File
@@ -70,7 +70,7 @@ td.n{white-space:nowrap;font-weight:600}
<tr><td class="n">등산 <span class="core">가을</span></td><td class="w">7~12시</td><td class="w">30·25·20·10·10·5</td><td>범위 10~20° (정상 기준 −6°)</td><td>마를수록</td><td>잔잔 ≤4, 한계 12</td><td>범위</td><td>주말 100, 평일 50</td><td>비 확률 70% 이상, 강풍주의보</td><td>등산로 통제, 낙석</td></tr>
<tr><td class="n">세차</td><td class="w">오늘 + 앞으로 이틀</td><td class="w">5·60·10·10·10·5</td><td>범위 5~28°</td><td>마를수록 (이틀 최대)</td><td>잔잔 ≤4, 한계 10</td><td>낮을수록</td><td>낮 100, 밤 40</td><td>이틀 안 비 70% 이상 → 20점 아래</td><td>황사·꽃가루</td></tr>
<tr><td class="n">캠핑 <span class="core">가을</span></td><td class="w">18~다음날 8시</td><td class="w">30·25·15·15·10·5</td><td>범위 12~22°</td><td>마를수록</td><td>잔잔 ≤3, 한계 9</td><td>낮을수록 (이슬)</td><td>금·토 100, 평일 60</td><td>비 확률 60% 이상, 강풍</td><td>캠핑장 예약</td></tr>
<tr><td class="n">러닝</td><td class="w">6~8시, 19~22시 중 좋은 쪽</td><td class="w">35·20·10·20·10·5</td><td>범위 8~18°</td><td>마를수록</td><td>잔잔 ≤4, 한계 10</td><td>낮을수록</td><td>아침·저녁 100, 늦은 밤 40</td><td>체감 35° 이상, 비 확률 90% 이상</td><td>노면 상태</td></tr>
<tr><td class="n">러닝</td><td class="w">6~8시, 19~22시 (지금 순위는 구간별, 하루 점수는 좋은 쪽)</td><td class="w">35·20·10·15·15·5</td><td>범위 5~18°, 최적 12° (5~8°도 좋음)</td><td>마를수록</td><td>잔잔 ≤3, 한계 8</td><td>낮을수록</td><td>활동 시간대와 겹치면 100, 아니면 0 (시간 비중 5%). 현재 구간은 남은 시간만 평가</td><td>0점: 비 소식, 비 확률 70% 이상, 체감 0° 미만·35° 이상, 바람 8m/s 이상, 돌풍 15m/s 이상, 강풍 특보, 초미세먼지 75㎍/㎥ 이상<br>최대 30점: 비 확률 60% 이상, 바람 6m/s 이상, 초미세먼지 36㎍/㎥ 이상, 체감 28° 이상<br>최대 40점: 체감 5° 미만<br>최대 50점: 활동 시간대와 겹치지 않는 구간 (더 낮은 상한 우선)</td><td>노면 상태</td></tr>
<tr><td class="n">별보기 <span class="core">가을</span></td><td class="w">21~02시</td><td class="w">5·15·5·10·20·45</td><td>범위 5~25°</td><td>마를수록</td><td>잔잔 ≤5, 한계 12</td><td>낮을수록</td><td>달이 어두울수록 100 (보름 20)</td><td>하늘 흐림(전체 구름) 80% 이상</td><td>도시 불빛 (지역 평균만)</td></tr>
<tr><td class="n">짬뽕각 <span class="fun">재미</span></td><td class="w">11~14시, 17~20시</td><td class="w">40·25·15·10·5·5</td><td>낮을수록 (25° 0점 → 5° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>식사 시간 100</td><td>없음</td><td>실제 주문량 검증 전</td></tr>
<tr><td class="n">막걸리각 <span class="fun">재미</span></td><td class="w">17~22시</td><td class="w">15·50·10·15·5·5</td><td>낮을수록 (28° 0점 → 10° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>금·토 100, 평일 50</td><td>없음</td><td>실제 판매량 검증 전</td></tr>
+9 -7
View File
@@ -259,20 +259,22 @@
- 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)
- 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음
- 시간대: 6~8시 / 19~22시
- 지금 순위는 구간별 날씨로 계산하며 현재 구간은 남은 시각만 평가합니다. 하루 점수는 활동 시간대 중 좋은 쪽을 씁니다.
- 요소별 규칙 (비중):
- 기온 35%: 체감 8~18°가 좋음
- 기온 35%: 체감 5~18°가 좋음 (최적 12°, 5~8°도 좋은 점수 유지)
- 비 20%: 비 안 올수록 좋음
- 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점)
- 바람 10%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 8m면 0점)
- 습도 15%: 낮을수록 좋음 (90%=0점 → 40%=100점)
- 미세먼지 15%: 초미세먼지 낮을수록 좋음
- 시간·요일 5%: 고정 100점
- 점수 깎이는 조건: 비 소식이 있으면 0점, 체감 35° 이상이면 0점, 비 확률 70% 이상이면 0점
- 시간·요일 5%: 활동 시간대와 겹치면 100점, 겹치지 않으면 0점
- 점수 깎이는 조건: 비 소식이 있으면 0점, 체감 35° 이상이면 0점, 비 확률 70% 이상이면 0점, 체감 0° 미만이면 0점, 강풍 특보가 있으면 0점, 바람 8m/s 이상이면 0점, 돌풍 15m/s 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점, 비 확률 60% 이상이면 최대 30점, 바람 6m/s 이상이면 최대 30점, 초미세먼지 36㎍/㎥ 이상이면 최대 30점, 체감 28° 이상이면 최대 30점, 체감 5° 미만이면 최대 40점, 활동 시간대가 아니면 최대 50점
- 상한이 겹치면 더 낮은 상한을 우선하도록 0점 → 최대 30점 → 최대 40점 → 최대 50점 순서로 조건을 둡니다. 중기예보 예상 점수에는 비 확률 상한만 적용됩니다.
- 반영 못 하는 것: 노면 상태는 반영하지 못해요
- 점수 구간별 설명 (상세 창에 나옴):
- 0~29점: 체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!
- 30~59점: 덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!
- 0~29점: 밖에서 뛰기엔 날씨가 험해요. 오늘은 러닝머신으로!
- 30~59점: 지금은 뛰기 애매해요. 아침·저녁에 짧게 가볍게!
- 60~79점: 뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.
- 80~100점: 8~18°에 공기 보송, 기록 갱신각 🏃
- 80~100점: 선선하고 공기 보송, 기록 갱신각 🏃
### 별보기각 (`stars`)
+5
View File
@@ -378,6 +378,11 @@ CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at
-- 글 주제 (TalkTopic: 1 동네 이야기, 2 하늘·노을, 3 비·눈, 4 단풍·꽃, 5 오늘 옷차림)
ALTER TABLE public.talk ADD COLUMN IF NOT EXISTS topic SMALLINT NOT NULL DEFAULT 1;
CREATE INDEX IF NOT EXISTS idx_talk_recent ON public.talk (created_at DESC) WHERE deleted = FALSE AND hidden = FALSE;
-- 사람 글 댓글은 comment 표를 같이 쓰고 talk_id 로 가른다 (post_id 는 비움). 숨긴 댓글은 댓글 수에서 빠진다
ALTER TABLE public.talk ADD COLUMN IF NOT EXISTS comment_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE public.comment ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS talk_id BIGINT NULL;
CREATE INDEX IF NOT EXISTS idx_comment_talk ON public.comment (talk_id, created_at) WHERE deleted = FALSE AND talk_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS public.talk_like (
talk_id BIGINT NOT NULL,
+12 -1
View File
@@ -183,12 +183,23 @@ class WeatherWhy(WebPacketProtocol):
note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)")
class TomorrowEvent(WebPacketProtocol):
event_id: int
name: str
place: str
icon: str
start_date: date
end_date: date
class HeroTomorrow(WebPacketProtocol):
"""히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
"""히어로 '내일' 스위치와 내일 페이지(/tomorrow/...). 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
day: date
weather_slots: dict[str, int] = Field(default_factory=dict, description="내일 구간별 날씨 점수 {morning·day·evening·night: 점수}")
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="내일 구간별 날씨 점수 근거")
top1: Optional[TopIndex] = Field(default=None, description="내일 하루 점수로 1위인 각. score·summary 는 내일 값")
ranked: list[TopIndex] = Field(default_factory=list, description="내일 하루 점수 순위 5개 (내일 페이지 '내일의 각'). top1 이 첫째")
events: list[TomorrowEvent] = Field(default_factory=list, description="내일 열리는 같은 시도 근처 행사 최대 3개 (내일 페이지)")
class Hero(WebPacketProtocol):
+23 -4
View File
@@ -24,6 +24,12 @@ def _comment(v: CommentView) -> CommentData:
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, official=v.official, created_at=c.created_at.astimezone(KST))
def _comment_list(err: ErrorType, items: list[CommentView]) -> Res_CommentList:
if err is not ErrorType.SUCCESS:
return Res_CommentList(result=error_info(err))
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
err, count = await service.like_post(post_id, who, on)
return Res_PostLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostLike(liked=on, like_count=count)
@@ -65,10 +71,7 @@ async def list_comments(
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: ReactionService = Depends(),
) -> Res_CommentList:
err, items = await service.comments(post_id, user, who.ip_hash, cursor)
if err is not ErrorType.SUCCESS:
return Res_CommentList(result=error_info(err))
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
return _comment_list(*await service.comments(post_id, user, who.ip_hash, cursor))
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
@@ -79,6 +82,22 @@ async def add_comment(
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
@router.get("/talk/{talk_id}/comment/list", response_model=Res_CommentList, response_model_exclude_none=True, summary="사람 글 댓글 목록 (로그인 없이 보기)")
async def list_talk_comments(
talk_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: ReactionService = Depends(),
) -> Res_CommentList:
return _comment_list(*await service.comments(None, user, who.ip_hash, cursor, talk_id))
@router.post("/talk/{talk_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="사람 글 댓글 쓰기 (로그인한 사람만, 60자, 링크·전화번호 불가, 이용약관 동의 전이면 TERMS_REQUIRED). 지우기·좋아요·신고·차단은 /comment/{comment_id} 그대로")
async def add_talk_comment(
talk_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
) -> Res_Comment:
err, v = await service.add_talk_comment(talk_id, user, who, req.body)
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)")
async def delete_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, who)))
+7
View File
@@ -37,6 +37,8 @@ class SajuPillar(WebPacketProtocol):
branch_ko: str
stem_element: str = Field(description="木火土金水")
branch_element: str
stem_ten_god: Optional[str] = Field(None, description="천간 십성 (일간은 없음)")
branch_ten_god: str = Field(description="지지 십성 (정기 기준)")
class SajuMe(WebPacketProtocol):
@@ -49,6 +51,11 @@ class SajuMe(WebPacketProtocol):
season: Optional[str] = None
climate: Optional[str] = Field(None, description="따뜻·마름 / 따뜻·촉촉 / 서늘·마름 / 서늘·촉촉")
need: list[str] = Field([], description="내 기운에 필요한 것 (따뜻함·마른 공기 등)")
elements: dict[str, float] = Field({}, description="오행 세력 점수 木火土金水 (월지 30·일지 20·나머지 10, 지지는 지장간 날 수로 나눔)")
top_element: Optional[str] = Field(None, description="가장 센 오행")
strong: Optional[bool] = Field(None, description="신강이면 true, 신약이면 false")
strength: Optional[str] = Field(None, description="신강 · 중화 · 신약 (득령이면 돕는 몫에 가산, 45~55% 사이는 중화)")
support: Optional[float] = Field(None, description="일간을 뺀 점수 중 일간을 돕는 기운 몫 0~1")
class SajuCard(WebPacketProtocol):
+7 -1
View File
@@ -11,6 +11,8 @@ from router.v1.saju.protocol import Req_Saju, Req_SajuBirth, Req_SajuMatch, Res_
from services import saju_text as T
from services.level_service import UNLOCKS
from services.saju.ganji import branch_element, ko, stem_element
from services.saju.rules import chart_ten_gods
from services.saju.strength import chart_strength
from services.saju_service import Reading, SajuService, shown_saju, weather_points
router = APIRouter(prefix="/v1/saju", tags=["saju"])
@@ -20,12 +22,16 @@ _WEEKDAY = "월화수목금토일"
def _res(r: Reading) -> Res_Saju:
c = r.chart
pillars = [("year", c.year), ("month", c.month), ("day", c.day)] + ([("hour", c.hour)] if c.hour else [])
gods = chart_ten_gods(c.day_stem, dict(pillars))
strength = chart_strength(c)
today = r.today
best = max(r.week, key=lambda d: d.score).day if r.week else None
return Res_Saju(
me=SajuMe(
pillars=[SajuPillar(position=pos, stem=p.stem, branch=p.branch, stem_ko=ko(p.stem), branch_ko=ko(p.branch), stem_element=stem_element(p.stem), branch_element=branch_element(p.branch)) for pos, p in pillars],
pillars=[SajuPillar(position=pos, stem=p.stem, branch=p.branch, stem_ko=ko(p.stem), branch_ko=ko(p.branch), stem_element=stem_element(p.stem), branch_element=branch_element(p.branch),
stem_ten_god=gods[pos]["stem"], branch_ten_god=gods[pos]["branch"]) for pos, p in pillars],
hour_known=c.hour is not None, jeol_warning=c.jeol_on_birth_day, scene=r.scene[0], scene_desc=r.scene[1], scene_icon=r.scene_icon, need=r.need,
elements=strength.elements, top_element=strength.top, strong=strength.strong, strength=strength.label, support=strength.support,
),
today=SajuToday(
day=today.day, pillar=ko(today.facts.pillar.stem + today.facts.pillar.branch), ten_god=today.facts.stem_ten_god, title=T.TEN_GOD_TEXT[today.facts.stem_ten_god][0],
+1
View File
@@ -19,6 +19,7 @@ class TalkData(WebPacketProtocol):
image: Optional[str] = Field(None, description="올린 사진 주소")
topic: TalkTopic = TalkTopic.LOCAL
like_count: int
comment_count: int = 0
liked: bool
mine: bool
created_at: datetime
+1 -1
View File
@@ -23,7 +23,7 @@ def _data(v: TalkView) -> TalkData:
t, u = v.talk, v.author
return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, comment_count=t.comment_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
ago=ago_text(t.created_at, now_kst()),
)
+69 -7
View File
@@ -717,16 +717,17 @@
"factor_rules": {
"temp": {
"type": "range",
"lo": 8,
"hi": 18
"lo": 5,
"hi": 18,
"best": 12
},
"rain": {
"dir": "dry"
},
"wind": {
"type": "calm",
"ok": 4,
"limit": 10
"ok": 3,
"limit": 8
},
"humidity": {
"type": "lower"
@@ -751,14 +752,75 @@
"field": "rain_prob",
"op": ">=",
"value": 70
},
{
"field": "feels_c",
"op": "<",
"value": 0
},
{
"field": "warning",
"op": "==",
"value": "wind"
},
{
"field": "wind_ms",
"op": ">=",
"value": 8
},
{
"field": "gust_ms",
"op": ">=",
"value": 15
},
{
"field": "pm25",
"op": ">=",
"value": 75
},
{
"field": "rain_prob",
"op": ">=",
"value": 60,
"cap": 30
},
{
"field": "wind_ms",
"op": ">=",
"value": 6,
"cap": 30
},
{
"field": "pm25",
"op": ">=",
"value": 36,
"cap": 30
},
{
"field": "feels_c",
"op": ">=",
"value": 28,
"cap": 30
},
{
"field": "feels_c",
"op": "<",
"value": 5,
"cap": 40
},
{
"field": "time_matches",
"op": "==",
"value": false,
"cap": 50
}
],
"limit_description": "노면 상태는 반영하지 못해요",
"sentences": {
"0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!",
"30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!",
"0": "밖에서 뛰기엔 날씨가 험해요. 오늘은 러닝머신으로!",
"30": "지금은 뛰기 애매해요. 아침·저녁에 짧게 가볍게!",
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
"80": "선선하고 공기 보송, 기록 갱신각 🏃"
},
"sort_order": 9,
"priority": 1,
+8 -1
View File
@@ -270,6 +270,8 @@ def _cond(r: dict) -> tuple[str, str, str]:
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
if r["field"] == "rain_before":
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
if r["field"] == "time_matches":
return "활동 시간대가 아니라", "활동 시간대가 아니거나", "활동 시간대가 아니면"
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
return f"{base}이라", f"{base}이거나", f"{base}이면"
@@ -293,7 +295,11 @@ _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐
def _summary(hours: list[Hour]) -> str:
mid = hours[len(hours) // 2]
return summary_line(hours[len(hours) // 2])
def summary_line(mid: Hour) -> str:
"""그 시각 날씨 한 줄 (오후 5시 13°, 비 60%)."""
wind = mid.wind_ms
tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else (
"바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else _SKY_WORD[mid.sky]
@@ -358,6 +364,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
"time_matches": ctx.time_matches,
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
+45 -22
View File
@@ -11,7 +11,7 @@ from common.cache.lock import redis_lock
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Article, CardSet, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
from common.enums import AirGrade, ArticleCategory, ErrorType, EventKind, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
from common.logger import LOG
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
from common.utils.text import compass, day_range, hour_label, short_day
@@ -22,7 +22,7 @@ from crud.season_crud import SeasonCRUD
from crud.weather_crud import WeatherCRUD
from router.v1.feed.protocol import (
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
PlanSlide, PlanStep, TomorrowEvent, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
)
from router.v1.index.protocol import TrendPoint
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
@@ -39,10 +39,13 @@ from services.now_service import NowService, NowWeather
from services.season_service import SeasonService
from services.sky_service import SkyService, SkyView, day_verdict
from services.weather_service import TodayWeather, WeatherService
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
from services.week_service import DayPlan, EventItem, WeekService, event_sidos, image_credit, mix_kinds
from services.weekend_plan import day_plan, forecast, pick_events
from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days
# 행사 포스트: 축제는 전부, 팝업·전시·콘서트는 종류마다 이만큼. 자리는 _EVENT_SLOTS 개까지
_EVENT_OTHERS = 2
_EVENT_SLOTS = 40
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/서비스_동작_안내.md).
LINEUP = [
(1, PostType.WEATHER, RefType.NONE, None),
@@ -70,6 +73,7 @@ LINEUP = [
(23, PostType.FOLIAGE, RefType.NONE, None),
(24, PostType.EVENTS_BAND, RefType.NONE, None),
(25, PostType.SEASON_BAND, RefType.NONE, None),
*((22 + rank, PostType.EVENT, RefType.NONE, rank) for rank in range(4, _EVENT_SLOTS + 1)),
]
# 피드 목록 대신 히어로·오늘의 각·단풍 지도·띠에 좋아요·댓글만 붙는 자리
_PINNED = {
@@ -237,9 +241,12 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
events = pool.get(PostType.EVENT, [])
front = range(1, max(1, len(rest) // 2 + 1))
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
# 앞쪽 절반에 다 못 들어가면 끝까지 한 장씩 걸러 끼우고, 그래도 남은 행사는 맨 뒤에
gaps = (sorted(random.Random(seed).sample(front, len(events)), reverse=True) if len(events) <= len(front)
else list(range(min(len(events), len(rest)), 0, -1)))
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
rest.insert(gap, e)
rest += events[len(gaps):]
# 카드뉴스(관리자가 올린 것)는 날씨 바로 아래, 같은 날 두 번째부터는 피드 중간쯤
cards = pool.get(PostType.CARD, [])
for i, card in enumerate(cards[1:]):
@@ -255,24 +262,24 @@ def _by_position(posts: list[Post]) -> list[Post]:
return list(out.values())
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
return best
def _tomorrow_ranked(board: IndexBoard, day: date) -> list[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수 순으로 제철 각과 그 점수 (동점이면 중요도 순)."""
scored = [(i, s) for i in board.items if i.in_season for s in i.trend if s.score_date == day]
return sorted(scored, key=lambda x: rank_score(x[1].score, x[0].definition.priority), reverse=True)
def tomorrow_events(items: list[EventItem], region_code: str, day: date) -> list[TomorrowEvent]:
"""그날 열리는 같은 시도 행사 3개 (종류를 섞어서)."""
on = [e for e in items if e.event.sido_code in event_sidos(region_code) and e.event.start_date <= day <= e.event.end_date]
return [TomorrowEvent(event_id=e.event.event_id, name=e.event.name, place=e.event.place_name, icon=e.event.icon,
start_date=e.event.start_date, end_date=e.event.end_date) for e in mix_kinds(on)[:3]]
def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
best = _tomorrow_best(board, day)
top1 = None
if best is not None:
d, s = best[0].definition, best[1]
top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary)
ranked = [TopIndex(index_id=i.definition.index_id, code=i.definition.code, name=i.definition.name, icon=i.definition.icon, score=s.score,
rank=n, summary=s.summary) for n, (i, s) in enumerate(_tomorrow_ranked(board, day)[:5], 1)]
return HeroTomorrow(
day=day, weather_slots=board.tomorrow_slots, top1=top1,
day=day, weather_slots=board.tomorrow_slots, top1=ranked[0] if ranked else None, ranked=ranked,
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()},
)
@@ -429,9 +436,12 @@ class FeedService:
has_warning = bool(now_w and now_w.warnings)
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
items = [i for i in board.items if i.in_season] if board else []
hero = self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or []))
if hero.tomorrow is not None:
hero.tomorrow.events = tomorrow_events(events, region.code, hero.tomorrow.day)
feed = Res_Feed(
region_code=region.code, region_name=region.name, slot=slot,
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
hero=hero,
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned,
bands=Bands(
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
@@ -537,7 +547,7 @@ class FeedService:
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon, image=a.image_url, image_credit=a.image_credit)],
share_messages=[a.title])
if t is PostType.EVENT:
soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
soon = feed_events([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
rank = p.index_rank or 1
if len(soon) < rank:
return None
@@ -757,8 +767,9 @@ class FeedService:
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute]
best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None
if best is not None:
ranked = _tomorrow_ranked(c.board, c.now.date() + timedelta(days=1)) if c.board else []
if ranked:
best = ranked[0]
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
icon = c.now_w.commute[0].icon if c.now_w.commute else "sun"
@@ -811,6 +822,18 @@ def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]
return f"내일 낮 최고 {round(highs[1])}°, 오늘보다 {abs(diff)}° {'더워요' if diff > 0 else '쌀쌀해요'}."
def feed_events(items: list[EventItem]) -> list[EventItem]:
"""피드에 포스트로 올릴 행사. 축제는 전부, 다른 종류는 받은 순서대로 _EVENT_OTHERS 개씩 골라 종류를 돌아가며 섞는다."""
taken: dict[int, int] = {}
picked = []
for e in items:
n = taken.get(e.event.kind, 0)
if e.event.kind == EventKind.FESTIVAL or n < _EVENT_OTHERS:
picked.append(e)
taken[e.event.kind] = n + 1
return mix_kinds(picked)
def _event_caption(e: EventItem) -> str:
"""진행 상태·거리·그날 날씨 중 있는 것. 다 없으면 일정 확정 여부."""
parts = ["지금 진행 중" if e.status == "live" else e.status_label]
+5 -3
View File
@@ -19,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score, summary_line
from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
@@ -240,8 +240,7 @@ def slot_results(
"""각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다."""
hours_by_slot = slot_hours(day, sunset_at)
hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR))
if now:
_trim_passed(hours_by_slot, day, sunset_at, now)
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)]
out = {}
for key, hours in hours_by_slot.items():
@@ -253,6 +252,9 @@ def slot_results(
windows = windows_for(window, day, region, by_at, by_om, only=hours)
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
if result is not None:
# 지금 구간 줄은 남은 시간의 가운데가 아니라 지금 시각 날씨로
if key == cur and windows and windows[0]:
result.summary = summary_line(windows[0][0])
out[key] = result
return out
+28 -4
View File
@@ -13,6 +13,7 @@ from common.utils.kma_time import kst_midnight, now_kst
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from services.bot_comment import BOT_COLORS, BOT_NAMES
from services.level_service import award
from services.talk_service import _LINK, _PHONE
@@ -43,8 +44,10 @@ class SavedView:
class ReactionService:
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
self.crud, self.feed, self.regions = crud, feed, regions
def __init__(
self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD), talks: TalkCRUD = Depends(TalkCRUD),
) -> None:
self.crud, self.feed, self.regions, self.talks = crud, feed, regions, talks
async def _post_exists(self, post_id: int) -> ErrorType:
err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id))
@@ -100,8 +103,9 @@ class ReactionService:
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
async def comments(self, post_id: Optional[int], user: Optional[User], ip_hash: str, cursor: Optional[int], talk_id: Optional[int] = None) -> tuple[ErrorType, list[CommentView]]:
"""포스트 댓글, talk_id 가 있으면 그 사람 글의 댓글."""
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE, talk_id))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
@@ -146,6 +150,26 @@ class ReactionService:
await award(user.user_id, "react", f"comment:{c.comment_id}")
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
async def add_talk_comment(self, talk_id: int, user: User, who: Liker, body: str) -> tuple[ErrorType, Optional[CommentView]]:
"""사람 글 댓글은 로그인한 사람만 쓴다. 글처럼 링크·전화번호는 막는다."""
body = body.strip()
if not body or len(body) > COMMENT_MAX:
return ErrorType.INVALID_INPUT, None
if user.terms_agreed_at is None:
return ErrorType.TERMS_REQUIRED, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
err, talk = await DB_SESSION_MNG.execute_lambda(lambda s: self.talks.get(s, talk_id))
if err is not ErrorType.SUCCESS:
return err, None
if talk is None or talk.hidden:
return ErrorType.NOT_FOUND, None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, None, who, body, None, talk_id))
if c is None:
return err, None
await award(user.user_id, "react", f"comment:{c.comment_id}")
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who))
if err is not ErrorType.SUCCESS:
+38 -12
View File
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from typing import Iterable
from services.saju.pillars import Chart
from services.saju.strength import POSITION_POINTS, Strength, chart_strength
# 글자별 (한난, 조습) 초안 — 주인 확인 필요. 한난: 차가움 −1 … 따뜻함 +1, 조습: 마름 −1 … 습함 +1
# 丙丁巳午는 불이라 따뜻하고 말리며, 壬癸亥子는 물이라 차고 젖는다. 庚辛申酉는 가을 쇠라 서늘하고 마르고,
@@ -18,17 +19,20 @@ CHAR_CLIMATE: dict[str, tuple[float, float]] = {
"寅": (-0.3, 0.0), "卯": (-0.1, 0.2),
"辰": (0.0, 0.6), # 봄 젖은 흙 (물 창고)
"巳": (0.8, -0.3), "午": (1.0, -0.5),
"未": (0.6, -0.7), # 여름 끝 마른 흙
"未": (0.9, -0.7), # 대서가 든 한여름 마른 흙 (지장간 丁火)
"申": (-0.3, -0.3), "酉": (-0.5, -0.5),
"戌": (0.2, -0.8), # 가을 마른 흙 (불 창고)
"亥": (-0.7, 0.8),
}
# 자리별 비중. 태어난 달(월령)이 계절을 정하므로 월지를 가장 크게
CHART_WEIGHTS = {
("year", "stem"): 1.0, ("year", "branch"): 1.0, ("month", "stem"): 1.0, ("month", "branch"): 3.0,
("day", "stem"): 1.0, ("day", "branch"): 1.5, ("hour", "stem"): 1.0, ("hour", "branch"): 1.0,
}
SEASONS = {"寅卯辰": "봄", "巳午未": "여름", "申酉戌": "가을", "亥子丑": "겨울"}
# 월령: 태어난 달이 다른 글자를 데우거나 식힌다 (『궁통보감』 조후). 달별 한난, 계절별 조습
MONTH_TEMP = {"寅": -0.4, "卯": -0.1, "辰": 0.2, "巳": 0.6, "午": 0.9, "未": 1.0, "申": 0.4, "酉": -0.1, "戌": -0.3, "亥": -0.6, "子": -0.9, "丑": -1.0}
SEASON_MOIST = {"봄": 0.3, "여름": -1.0, "가을": -0.5, "겨울": 1.0}
# 월령을 받는 세기. 흙(戊己辰戌丑未)은 계절 따라 마른 흙·젖은 흙이 되므로 더 크게 받는다 (三夏己土 取癸為要, 六月土燥)
SEASON_PULL = {"earth": {"temp": 0.5, "moist": 0.8}, "other": {"temp": 0.3, "moist": 0.2}}
EARTH = set("戊己辰戌丑未")
# 축이 균형(±balanced 안)일 때 이름(따뜻/서늘, 촉촉/마름)을 정할 기울기: 가장 센 오행. 토와 목은 월령을 따른다
ELEMENT_LEAN = {"火": (1.0, -0.5), "金": (-0.5, -0.5), "水": (-0.7, 0.9)}
# 날씨 → 같은 두 축. 한난: 체감 15°C 가 0, 15°C 차이마다 ±1. 조습: 습도 55% 가 0, 35%p 차이마다 ±1, 비가 오면 최소 +0.8
WEATHER_SCALE = {"neutral_c": 15.0, "span_c": 15.0, "neutral_humidity": 55.0, "span_humidity": 35.0, "rain_moist": 0.8}
@@ -60,8 +64,9 @@ class ChartClimate:
moist: float
label: str # 따뜻·마름 / 따뜻·촉촉 / 서늘·마름 / 서늘·촉촉
season: str # 월지 계절
strength: Strength
need: dict[str, str] # {"temp": warm|cool|mild, "moist": dry|moist|mild}
parts: tuple[dict, ...] # 글자별 기여 {"position", "part", "char", "temp", "moist", "weight"}
parts: tuple[dict, ...] # 글자별 기여 {"position", "part", "char", "temp", "moist", "weight"} (월령 보정 뒤 값)
@dataclass(frozen=True)
@@ -85,12 +90,30 @@ def _clamp(x: float, lo: float = -1.0, hi: float = 1.0) -> float:
return max(lo, min(hi, x))
def season_of(branch: str) -> str:
return next(name for group, name in SEASONS.items() if branch in group)
def seasoned(char: str, month_branch: str) -> tuple[float, float]:
"""월령을 받은 글자의 (한난, 조습). 월지 자신은 계절 그 자체라 그대로 둔다."""
t, m = CHAR_CLIMATE[char]
pull = SEASON_PULL["earth" if char in EARTH else "other"]
t += pull["temp"] * MONTH_TEMP[month_branch]
m += pull["moist"] * SEASON_MOIST[season_of(month_branch)]
return round(_clamp(t), 3), round(_clamp(m), 3)
def _lean(strength: Strength, month_branch: str) -> tuple[float, float]:
return ELEMENT_LEAN.get(strength.top) or CHAR_CLIMATE[month_branch]
def chart_climate(chart: Chart) -> ChartClimate:
mb = chart.month.branch
parts = []
for pos, p in chart.pillars().items():
for part, char in (("stem", p.stem), ("branch", p.branch)):
t, m = CHAR_CLIMATE[char]
parts.append({"position": pos, "part": part, "char": char, "temp": t, "moist": m, "weight": CHART_WEIGHTS[(pos, part)]})
t, m = CHAR_CLIMATE[char] if (pos, part) == ("month", "branch") else seasoned(char, mb)
parts.append({"position": pos, "part": part, "char": char, "temp": t, "moist": m, "weight": POSITION_POINTS[(pos, part)]})
total = sum(x["weight"] for x in parts)
temp = round(sum(x["temp"] * x["weight"] for x in parts) / total, 3)
moist = round(sum(x["moist"] * x["weight"] for x in parts) / total, 3)
@@ -99,9 +122,12 @@ def chart_climate(chart: Chart) -> ChartClimate:
"temp": "warm" if temp < -b else "cool" if temp > b else "mild",
"moist": "dry" if moist > b else "moist" if moist < -b else "mild",
}
label = f"{'따뜻' if temp >= 0 else '서늘'}·{'촉촉' if moist >= 0 else '마름'}"
season = next(name for group, name in SEASONS.items() if chart.month.branch in group)
return ChartClimate(temp, moist, label, season, need, tuple(parts))
strength = chart_strength(chart)
lean_t, lean_m = _lean(strength, mb)
warm = temp > 0 if abs(temp) > b else lean_t >= 0
wet = moist > 0 if abs(moist) > b else lean_m >= 0
label = f"{'따뜻' if warm else '서늘'}·{'촉촉' if wet else '마름'}"
return ChartClimate(temp, moist, label, season_of(mb), strength, need, tuple(parts))
def weather_vector(w: HourWeather) -> dict[str, float]:
+5
View File
@@ -25,6 +25,11 @@ HIDDEN_STEMS: dict[str, tuple[str, Optional[str], str]] = {
"戌": ("辛", "丁", "戊"),
"亥": ("戊", "甲", "壬"),
}
# 지장간이 맡는 날 수 (여기, 중기, 정기), 한 달 30일. 子卯酉는 중기 없이 10·20, 午는 丙10·己9·丁11
HIDDEN_DAYS: dict[str, tuple[int, int, int]] = {
"子": (10, 0, 20), "丑": (9, 3, 18), "寅": (7, 7, 16), "卯": (10, 0, 20), "辰": (9, 3, 18), "巳": (7, 7, 16),
"午": (10, 9, 11), "未": (9, 3, 18), "申": (7, 7, 16), "酉": (10, 0, 20), "戌": (9, 3, 18), "亥": (7, 7, 16),
}
def stem_element(stem: str) -> str:
+62
View File
@@ -0,0 +1,62 @@
"""오행 세력과 신강·신약. 자리마다 점수를 주고, 지지 점수는 지장간 날 수대로 나눈다."""
from dataclasses import dataclass
from services.saju.ganji import ELEMENTS, HIDDEN_DAYS, HIDDEN_STEMS, stem_element
from services.saju.pillars import Chart
# 자리별 점수. 득령(월지) 30 · 득지(일지) 20 · 나머지 10. 일간을 뺀 일곱 자리 합이 100
POSITION_POINTS = {
("year", "stem"): 10, ("year", "branch"): 10, ("month", "stem"): 10, ("month", "branch"): 30,
("day", "stem"): 10, ("day", "branch"): 20, ("hour", "stem"): 10, ("hour", "branch"): 10,
}
# 월령: 태어난 달의 오행. 일간 오행이 이와 같거나(왕) 달이 일간을 생하면(상) 득령. 강약은 득령을 먼저 본다
SEASON_ELEMENT = dict(zip("寅卯巳午申酉亥子辰戌丑未", "木木火火金金水水土土土土"))
DEUK_RYEONG_BONUS = 0.15 # 득령이면 돕는 몫에 더한다
STRONG_FROM, WEAK_BELOW = 0.55, 0.45 # (돕는 몫 + 득령 가산) 이 이상이면 신강, 미만이면 신약, 사이는 중화
@dataclass(frozen=True)
class Strength:
elements: dict[str, float] # 오행별 점수 (일간 포함), 木火土金水 순
top: str # 가장 센 오행
support: float # 일간을 뺀 점수 중 일간을 돕는 오행(같은 오행·생해 주는 오행) 몫 0~1
deuk_ryeong: bool
label: str # 신강 · 중화 · 신약
@property
def strong(self) -> bool:
return self.label == "신강"
def char_points(chart: Chart) -> list[tuple[str, str, str, float]]:
"""(자리, stem|branch, 천간, 점수). 지지는 지장간 천간들로 나눈다."""
out = []
for pos, p in chart.pillars().items():
out.append((pos, "stem", p.stem, float(POSITION_POINTS[(pos, "stem")])))
points = POSITION_POINTS[(pos, "branch")]
days = HIDDEN_DAYS[p.branch]
for stem, d in zip(HIDDEN_STEMS[p.branch], days):
if stem and d:
out.append((pos, "branch", stem, points * d / sum(days)))
return out
def chart_strength(chart: Chart) -> Strength:
me = ELEMENTS.index(stem_element(chart.day_stem))
helpers = {ELEMENTS[me], ELEMENTS[(me - 1) % 5]}
elements = dict.fromkeys(ELEMENTS, 0.0)
support = others = 0.0
for pos, part, stem, points in char_points(chart):
el = stem_element(stem)
elements[el] += points
if (pos, part) == ("day", "stem"):
continue
others += points
support += points if el in helpers else 0.0
elements = {k: round(v, 1) for k, v in elements.items()}
ratio = round(support / others, 3)
deuk = SEASON_ELEMENT[chart.month.branch] in helpers
judged = ratio + (DEUK_RYEONG_BONUS if deuk else 0.0)
label = "신강" if judged >= STRONG_FROM else "신약" if judged < WEAK_BELOW else "중화"
return Strength(elements, max(elements, key=elements.get), ratio, deuk, label)
+2
View File
@@ -148,6 +148,8 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
async with client() as c:
hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"]
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
assert len(hero["tomorrow"]["ranked"]) <= 5 and len(hero["tomorrow"]["events"]) <= 3
assert hero["tomorrow"]["top1"] == (hero["tomorrow"]["ranked"][0] if hero["tomorrow"]["ranked"] else None)
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
assert res["day"] == hero["tomorrow"]["day"]
+86
View File
@@ -195,6 +195,92 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
assert run(14, "2026-10-02:1144000000") == out
def test_feed_events_keeps_every_festival_and_two_of_other_kinds():
from types import SimpleNamespace
from common.enums import EventKind
from services.feed_service import feed_events
from services.week_service import EventItem
kinds = [EventKind.POPUP] * 4 + [EventKind.FESTIVAL] * 6 + [EventKind.CONCERT] * 3 + [EventKind.EXHIBITION] * 3
items = [EventItem(event=SimpleNamespace(kind=k.value, n=n), status="live", status_label="진행 중", fit=None) for n, k in enumerate(kinds)]
out = [e.event.kind for e in feed_events(items)]
assert out.count(EventKind.FESTIVAL.value) == 6
assert all(out.count(k.value) == 2 for k in (EventKind.POPUP, EventKind.CONCERT, EventKind.EXHIBITION))
assert out[:4] == [EventKind.FESTIVAL.value, EventKind.POPUP.value, EventKind.EXHIBITION.value, EventKind.CONCERT.value]
def test_tomorrow_events_keep_same_sido_events_running_that_day():
"""내일 페이지 행사: 내일 열리는 같은 시도 행사만, 종류를 섞어 3개까지."""
from types import SimpleNamespace
from common.enums import EventKind
from services.feed_service import tomorrow_events
from services.week_service import EventItem
day = date(2026, 10, 31)
def ev(n, kind, sido="11", start=day, end=day):
e = SimpleNamespace(event_id=n, name=f"행사{n}", place_name=f"장소{n}", icon="concert", kind=kind.value, sido_code=sido, start_date=start, end_date=end)
return EventItem(event=e, status="live", status_label="진행 중", fit=None)
items = [
ev(1, EventKind.CONCERT), ev(2, EventKind.CONCERT), ev(3, EventKind.FESTIVAL, start=day - timedelta(days=2)),
ev(4, EventKind.FESTIVAL, end=day - timedelta(days=1)), ev(5, EventKind.EXHIBITION, sido="41"), ev(6, EventKind.POPUP, start=day + timedelta(days=1)),
]
out = tomorrow_events(items, "1144000000", day)
assert [e.event_id for e in out] == [3, 1, 2]
assert out[0].place == "장소3" and out[0].start_date == day - timedelta(days=2)
def test_hero_tomorrow_ranks_in_season_gak_by_tomorrow_score():
"""내일의 각: 내일 하루 점수(중요도 반영) 순 5개, 철 지난 각은 빼고, 1위는 top1 과 같다."""
from types import SimpleNamespace
from services.feed_service import _hero_tomorrow
day = date(2026, 10, 31)
def item(n, score, in_season=True, priority=1.0):
d = SimpleNamespace(index_id=n, code=f"g{n}", name=f"각{n}", icon="sun", priority=priority)
trend = [SimpleNamespace(score_date=day - timedelta(days=1), score=100, summary="오늘"), SimpleNamespace(score_date=day, score=score, summary=f"내일{n}")]
return SimpleNamespace(definition=d, trend=trend, in_season=in_season)
board = SimpleNamespace(items=[item(1, 60), item(2, 99, in_season=False), item(3, 90), item(4, 70), item(5, 80), item(6, 50), item(7, 40)],
tomorrow_slots={}, tomorrow_why={})
hero = _hero_tomorrow(day, board)
assert [(g.index_id, g.rank) for g in hero.ranked] == [(3, 1), (5, 2), (4, 3), (1, 4), (6, 5)]
assert hero.top1 == hero.ranked[0] and hero.ranked[0].summary == "내일3"
def test_arrange_spreads_many_events_through_whole_feed():
"""행사가 앞쪽 절반 자리보다 많으면 끝까지 한 장씩 걸러 끼우고, 남은 건 맨 뒤에 다 붙인다."""
from datetime import datetime
from common.utils.kma_time import KST
from services.feed_service import arrange
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
others = [PostType.WEATHER, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE]
cards = [_card(t, n) for n, t in enumerate(others + [PostType.EVENT] * 20)]
out = arrange(cards, "day", datetime(2026, 10, 2, 13, tzinfo=KST), sunset, False, "2026-10-02:1144000000")
types = [c.post_type for c in out]
assert types.count(PostType.EVENT) == 20 and types[0] is PostType.WEATHER
rest = len(others) - 1
assert PostType.EVENT not in types[1:1 + 2 * rest:2] and types[2:2 + 2 * rest:2] == [PostType.EVENT] * rest
assert set(types[1 + 2 * rest:]) == {PostType.EVENT}
assert [c.post_id for c in out if c.post_type is PostType.EVENT] == list(range(len(others), len(others) + 20))
def test_lineup_event_slots_stay_below_card_positions():
from crud.card_crud import CARD_POSITION_START
from services.feed_service import LINEUP, _EVENT_SLOTS
positions = [x[0] for x in LINEUP]
assert len(positions) == len(set(positions)) and max(positions) < CARD_POSITION_START
assert sorted(x[3] for x in LINEUP if x[1] is PostType.EVENT) == list(range(1, _EVENT_SLOTS + 1))
@pytest.mark.anyio
async def test_build_day_makes_every_card_at_three():
thursday = date(2026, 10, 15)
+91
View File
@@ -68,6 +68,18 @@ def test_time_matching_does_not_replace_weekday_score():
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
def test_time_mismatch_cap_only_applies_outside_activity_hours():
limit = [{"field": "time_matches", "op": "==", "value": False, "cap": 50}]
defn = _defn(factor_rules=_defn().factor_rules | {"time": {"type": "fixed", "value": 100}}, zero_rules=limit)
matched = evaluate(defn, [[_h(7, wind=1.0)]], CTX)
unmatched = evaluate(defn, [[_h(12, wind=1.0)]], replace(CTX, time_matches=False))
assert matched.score == 100 and matched.zero_reason is None
assert unmatched.score == 50 and unmatched.zero_reason == "활동 시간대가 아니라 최대 50점"
assert zero_rules_text(limit) == "활동 시간대가 아니면 최대 50점"
assert zero_rules_text(limit + [{"field": "rain_prob", "op": ">=", "value": 60, "cap": 50}]) == \
"활동 시간대가 아니거나 비 확률 60% 이상이면 최대 50점"
def test_good_but_not_perfect_stays_below_100():
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
@@ -275,6 +287,85 @@ def _seed_score(code, day=_SAT, pm25=10, **hour):
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
@pytest.mark.parametrize("prob, ceiling", [(60, 30), (69, 30), (70, 0)])
def test_running_high_rain_probability_limits_score(prob, ceiling):
assert _seed_score("running", feels=12, prob=prob) <= ceiling
@pytest.mark.parametrize("rain", [RainType.RAIN, RainType.SNOW, RainType.SLEET])
def test_running_any_precipitation_in_window_is_zero(rain):
hours = [_h(6, feels=12), _h(7, feels=12, prob=10, rain=rain)]
result = evaluate(_SEED["running"], [hours], CTX)
assert result.score == 0 and result.zero_reason == "비 소식이 있어 0점"
@pytest.mark.parametrize("feels, ceiling", [(-3, 0), (0, 40), (2, 40), (3, 40), (4.9, 40), (28, 30), (35, 0)])
def test_running_cold_and_heat_limit_score(feels, ceiling):
assert _seed_score("running", feels=feels) <= ceiling
def test_running_cold_limit_uses_coldest_hour():
hours = [_h(6, feels=3), _h(7, feels=12)]
assert evaluate(_SEED["running"], [hours], CTX).score <= 40
@pytest.mark.parametrize("hour", [6, 7, 19, 21])
@pytest.mark.parametrize("feels", [5, 8, 10, 12, 15])
def test_running_clear_cool_morning_and_evening_stay_good(hour, feels):
result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], CTX)
assert result.score >= 80 and result.zero_reason is None
@pytest.mark.parametrize("hour, feels", [(12, 12), (12, 14), (12, 25), (22, 12), (26, 12)])
def test_running_outside_activity_hours_stays_low(hour, feels):
result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False))
assert result.factors["time"] == 0 and result.score <= 50
@pytest.mark.parametrize("wind, ceiling", [(6, 30), (8, 0)])
def test_running_strong_wind_limits_score(wind, ceiling):
assert _seed_score("running", feels=12, wind=wind) <= ceiling
def test_running_strong_gust_is_zero():
assert _seed_score("running", feels=12, gust_ms=15) == 0
@pytest.mark.parametrize("pm25, ceiling", [(36, 30), (75, 0)])
def test_running_bad_air_limits_score(pm25, ceiling):
assert _seed_score("running", feels=12, pm25=pm25) <= ceiling
def test_running_wind_warning_is_zero():
assert evaluate(_SEED["running"], [[_h(6, feels=12)]], replace(CTX, wind_warning=True)).score == 0
@pytest.mark.parametrize("hour", [dict(prob=60, feels=3), dict(prob=60, feels=35), dict(prob=60, wind=8)])
@pytest.mark.parametrize("time_matches", [True, False])
def test_running_stricter_limits_win_when_conditions_overlap(hour, time_matches):
result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], replace(CTX, time_matches=time_matches))
assert result.score <= (30 if hour.get("feels") == 3 else 0)
@pytest.mark.parametrize("time_matches", [True, False])
@pytest.mark.parametrize("hour", [dict(feels=12), dict(feels=20, hum=80), dict(feels=3, prob=60), dict(feels=12, wind=8, rain=RainType.RAIN)])
def test_other_definitions_ignore_unused_time_match_condition(time_matches, hour):
from unittest.mock import patch
from services.calc import index_calc
ctx = replace(CTX, time_matches=time_matches, pm25=30)
windows = [[_h(7, **hour)]]
zero = index_calc._zero
for code, defn in _SEED.items():
if code == "running":
continue
assert all(r["field"] != "time_matches" for r in defn.zero_rules)
actual = evaluate(defn, windows, ctx)
with patch.object(index_calc, "_zero", side_effect=lambda rules, agg: zero(rules, {k: v for k, v in agg.items() if k != "time_matches"})):
assert actual == evaluate(defn, windows, ctx), code
@pytest.mark.parametrize("code, good, bad", [
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
+50 -1
View File
@@ -1,10 +1,13 @@
import json
from dataclasses import replace
from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace
from common.enums import RainType, Sky
from common.utils.kma_time import kst_midnight
from services.calc.index_calc import Context, DayForecast
from services.index_service import day_result, slot_days, slot_label
from services.index_service import day_result, slot_days, slot_label, slot_results
REGION = SimpleNamespace(lat=37.56, lon=126.97)
SAT = date(2026, 10, 10)
@@ -18,6 +21,7 @@ DEFN = SimpleNamespace(
zero_rules=[], windows=[{"from": 11, "to": 16}],
)
FC = {SAT: DayForecast(temp_min_c=12, temp_max_c=22, rain_prob_am=10, rain_prob_pm=20, sky=Sky.CLEAR)}
RUNNING = SimpleNamespace(**next(x for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8")) if x["code"] == "running"))
def _hourly(day: date) -> dict:
@@ -71,3 +75,48 @@ def test_partial_hourly_falls_back_to_estimate():
def test_no_mid_forecast_gives_no_score():
assert day_result(DEFN, SAT, REGION, {}, {}, CTX, short=False) is None
def test_running_slot_rain_outside_activity_hours_still_zero():
start = kst_midnight(SAT)
hourly = _hourly(SAT)
for row in hourly.values():
row.feels_c = 12
hourly[start + timedelta(hours=9)].rain_type = RainType.RAIN.value
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, start + timedelta(hours=18))
assert results["morning"].score == 0
assert results["morning"].zero_reason == "비 소식이 있어 0점"
assert results["night"].score >= 80
def test_running_slots_lower_day_and_late_night_but_keep_activity_hours():
start = kst_midnight(SAT)
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
for row in hourly.values():
row.feels_c = 25 if 11 <= row.forecast_at.hour < 16 else 12
sunset = start + timedelta(hours=18)
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset)
assert results["morning"].score >= 80 and results["night"].score >= 80
assert results["day"].score <= 50 and results["early"].score <= 50
late = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=22))
assert late["night"].factors["time"] == 0 and late["night"].score <= 50
def test_running_muggy_morning_does_not_exceed_original_weather_score():
start = kst_midnight(SAT)
hourly = _hourly(SAT)
for row in hourly.values():
row.feels_c, row.humidity, row.wind_ms = 20, 80, 1.5
results = slot_results(RUNNING, SAT, REGION, hourly, {}, replace(CTX, pm25=30), start + timedelta(hours=18))
assert results["morning"].factors["time"] == 100
assert results["morning"].score <= 67
def test_now_slot_summary_shows_current_hour_not_middle_of_rest():
"""오후 4시 10분이면 지금 구간 줄은 남은 16~18시의 가운데(5시)가 아니라 지금(4시) 날씨로."""
start = kst_midnight(SAT)
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
sunset = start + timedelta(hours=17, minutes=30)
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=16, minutes=10))
assert results["evening"].summary.startswith("오후 4시"), results["evening"].summary
assert results["night"].summary.startswith("오후 4시") is False
+2
View File
@@ -35,6 +35,8 @@ async def test_reading_for_anyone_gives_me_today_and_cards(offline):
r = (await c.post("/v1/saju/reading", json=BIRTH)).json()
assert [p["stem"] + p["branch"] for p in r["me"]["pillars"]] == ["乙亥", "己卯", "甲辰"] and r["me"]["hour_known"] is False
assert r["me"]["scene"].endswith("기운") and r["today"]["title"] and 0 <= r["today"]["score"] <= 100
assert [(p.get("stem_ten_god"), p["branch_ten_god"]) for p in r["me"]["pillars"]] == [("겁재", "편인"), ("정재", "겁재"), (None, "편재")]
assert r["me"]["top_element"] == "木" and r["me"]["strong"] is True and r["me"]["strength"] == "신강" and r["me"]["elements"]["木"] == 58.3
kinds = [x["kind"] for x in r["today"]["cards"]]
assert "when" in kinds and "do" in kinds and "wear" in kinds
# 근거 줄은 쉬운 말 + 괄호 용어, 숫자 없이
+29 -1
View File
@@ -4,13 +4,14 @@ import pytest
from common.utils.kma_time import KST
from services.saju.birth import to_solar_time
from services.saju.climate import HourWeather, axis_effect, chart_climate, climate_match
from services.saju.climate import HourWeather, axis_effect, chart_climate, climate_match, seasoned
from services.saju.daily import SCORE_WEIGHTS, daily_facts
from services.saju.pillars import day_pillar, make_chart
from services.saju.rules import (
branch_relations, branch_ten_god, chart_ten_gods, dohwa_of, hongyeom_of, stem_relations, ten_god, triple_relations,
)
from services.saju.solar_terms import JEOL, jeol_of_year, nutation_longitude, sun_apparent_longitude
from services.saju.strength import chart_strength
EXAMPLE = make_chart(date(1995, 3, 14))
@@ -254,6 +255,33 @@ def test_example_chart_climate_and_best_window():
assert moist == {"axis": "moist", "need": "dry", "effect": "dries", "helps": True, "points": moist["points"], "weather": "체감 13°, 습도 40%"}
def test_example_strength_counts_hidden_stems_and_month_branch():
s = chart_strength(EXAMPLE) # 乙亥 己卯 甲辰
assert s.elements == {"木": 58.3, "火": 0.0, "土": 24.3, "金": 0.0, "水": 7.3}
assert s.top == "木" and s.strong and s.support == 0.696
def test_summer_earth_chart_reads_hot_and_dry_not_rainy():
chart = make_chart(date(1959, 7, 16)) # 己亥 辛未 己亥: 未월 토가 많고 물이 둘
climate = chart_climate(chart)
assert climate.season == "여름" and climate.label == "따뜻·마름" and climate.need["temp"] == "cool"
assert climate.strength.top == "土" and climate.strength.strong
def test_month_rooted_day_master_stays_strong_whatever_the_hour():
# 未월 己土는 득령(월령 土) — 시주가 물·쇠라도 신강, 득령 없는 같은 몫이면 낮게
for h in range(0, 24, 2):
s = chart_strength(make_chart(date(1959, 7, 16), time(h, 30)))
assert s.deuk_ryeong and s.label == "신강", (h, s)
winter = chart_strength(make_chart(date(1959, 12, 20))) # 子월 — 己土 득령 아님
assert not winter.deuk_ryeong
def test_month_dries_summer_earth_and_soaks_winter_earth():
assert seasoned("己", "未")[1] < 0 < seasoned("己", "子")[1]
assert seasoned("壬", "未")[0] > seasoned("壬", "子")[0]
def test_balanced_axis_prefers_mild_weather_and_rain_moistens():
assert axis_effect(0.0, 0.0) > axis_effect(0.0, 0.6) and axis_effect(0.0, 0.0) > axis_effect(0.0, -0.6)
assert axis_effect(-0.4, 0.8) > axis_effect(-0.4, 0.0) > axis_effect(-0.4, -0.8)
+26
View File
@@ -82,6 +82,32 @@ async def test_reports_hide_and_block_hides_author():
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
@pytest.mark.anyio
async def test_talk_comments_need_login_and_keep_count_on_talk():
async with client() as c:
h = await _login(c, "talk_c1")
t = (await _write(c, h))["talk"]
url = f"/v1/reaction/talk/{t['talk_id']}/comment"
count = lambda talks: next(x for x in talks if x["talk_id"] == t["talk_id"])["comment_count"] # noqa: E731
assert (await c.post(url, json={"body": "저도 봤어요"})).status_code == 401
other = await _login(c, "talk_c2")
assert (await c.post(url, headers=other, json={"body": "저도 봤어요"})).json()["result"]["desc"] == "TERMS_REQUIRED"
await c.post("/v1/auth/terms", headers=other)
assert (await c.post(url, headers=other, json={"body": "연락 010-1234-5678"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED"
assert (await c.post(url, headers=other, json={"body": "가" * 61})).json()["result"]["desc"] == "INVALID_INPUT"
made = (await c.post(url, headers=other, json={"body": " 저도 봤어요 "})).json()["comment"]
assert made["body"] == "저도 봤어요" and made["mine"] is True
listed = (await c.get(f"{url}/list")).json()["comments"]
assert [x["comment_id"] for x in listed] == [made["comment_id"]] and listed[0]["nickname"] == "talk_c2"
assert count((await c.get("/v1/talk/list")).json()["talks"]) == 1
assert (await c.delete(f"/v1/reaction/comment/{made['comment_id']}", headers=other)).json()["result"]["success"] is True
assert (await c.get(f"{url}/list")).json()["comments"] == []
assert count((await c.get("/v1/talk/list")).json()["talks"]) == 0
assert (await c.post("/v1/reaction/talk/999999999/comment", headers=other, json={"body": "안녕"})).json()["result"]["desc"] == "NOT_FOUND"
def test_weather_line():
class Row:
temp_c, sky, rain_type = 18.4, 1, 1
+6
View File
@@ -17,6 +17,12 @@ if [ -z "${DEPLOY_PULLED:-}" ]; then
fi
docker compose up -d --wait postgres redis
docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql
# 지금 빌드 파일을 모아 새 이미지에 같이 넣는다. 배포로 지우면 열어 둔 탭과 구글 렌더가 예전 HTML 로 없는 파일을 불러 첫 화면에서 멈춘다 (2주 지난 건 지움)
mkdir -p frontend/.old-assets
if [ -n "$(docker compose ps -q frontend)" ]; then
docker compose cp frontend:/usr/share/nginx/html/assets/. frontend/.old-assets/
fi
find frontend/.old-assets -type f ! -name .gitkeep -mtime +14 -delete
docker compose up -d --build backend worker frontend
docker compose exec -T backend python scripts/load_seed.py
# 피드 캐시는 최대 1시간이라, 각 규칙이 바뀌어도 오늘 탭만 옛 순위로 남는다
@@ -0,0 +1,79 @@
오늘 날씨 1371808B - 1371988B -
내일 날씨 1286270B - 1286446B -
모레 날씨 1150349B - 1150529B -
이번주 날씨 1312186B - 1312373B -
주말 날씨 1310861B - 1311044B -
날씨 1396630B - 1396810B -
서울 오늘 날씨 1281266B - 1281444B -
서울 내일 날씨 1283717B - 1283899B -
서울 날씨 1049772B - 1049958B -
부산 오늘 날씨 1245056B - 1245233B -
부산 내일 날씨 1266693B - 1266868B -
부산 날씨 1301723B - 1301909B -
인천 오늘 날씨 1269661B - 1269847B -
인천 내일 날씨 1262166B - 1262354B -
인천 날씨 1349694B - 1349880B -
대구 오늘 날씨 1226277B - 1226460B -
대구 내일 날씨 1242598B - 1242785B -
대구 날씨 1308738B - 1308920B -
대전 오늘 날씨 1237245B - 1237429B -
대전 내일 날씨 1274773B - 1274955B -
대전 날씨 1336096B - 1336282B -
광주 오늘 날씨 1309522B - 1309708B -
광주 내일 날씨 1252771B - 1252951B -
광주 날씨 1327984B - 1328170B -
울산 오늘 날씨 1262830B - 1263012B -
울산 내일 날씨 1231480B - 1231662B -
울산 날씨 1371449B - 1371627B -
세종 오늘 날씨 1245527B - 1245713B -
세종 내일 날씨 1313319B - 1313496B -
세종 날씨 1248849B - 1249029B -
수원 오늘 날씨 1265808B - 1265986B -
수원 내일 날씨 1243239B - 1243419B -
수원 날씨 1325589B - 1325769B -
성남 오늘 날씨 1253371B - 1253553B -
성남 내일 날씨 1177900B - 1178081B -
성남 날씨 1214952B - 1215137B -
고양 오늘 날씨 1270339B - 1270523B -
고양 내일 날씨 1249671B - 1249855B -
고양 날씨 1209803B - 1209983B -
용인 오늘 날씨 1243446B - 1243628B -
용인 내일 날씨 1203581B - 1203759B -
용인 날씨 1280794B - 1280976B -
창원 오늘 날씨 1209334B - 1209516B -
창원 내일 날씨 1221943B - 1222123B -
창원 날씨 1301874B - 1302054B -
청주 오늘 날씨 1239951B - 1240137B -
청주 내일 날씨 1253815B - 1253993B -
청주 날씨 1340520B - 1340700B -
천안 오늘 날씨 1221359B - 1221541B -
천안 내일 날씨 1218803B - 1218985B -
천안 날씨 1344315B - 1344497B -
전주 오늘 날씨 1806743B - 1806927B -
전주 내일 날씨 1758758B - 1758942B -
전주 날씨 1290043B - 1290227B -
군산 오늘 날씨 1255867B - 1256049B -
군산 내일 날씨 1205287B - 1205467B -
군산 날씨 1237974B - 1238154B -
포항 오늘 날씨 1205314B - 1205500B -
포항 내일 날씨 1256673B - 1256859B -
포항 날씨 1338947B - 1339126B -
제주 오늘 날씨 1284726B - 1284909B -
제주 내일 날씨 1224271B - 1224455B -
제주 날씨 1410935B - 1411375B -
김해 오늘 날씨 1202848B - 1203030B -
김해 내일 날씨 1237655B - 1237839B -
김해 날씨 1255061B - 1255242B -
화성 오늘 날씨 1320876B - 1321063B -
화성 내일 날씨 1158506B - 1158690B -
화성 날씨 1292521B - 1292705B -
부천 오늘 날씨 1208702B - 1208884B -
부천 내일 날씨 1207789B - 1207969B -
부천 날씨 1057895B - 1058083B -
안산 오늘 날씨 1257275B - 1257455B -
안산 내일 날씨 1517067B - 1517249B -
안산 날씨 1248040B - 1248222B -
남양주 오늘 날씨 1314986B - 1315174B -
남양주 내일 날씨 1246129B - 1246313B -
남양주 날씨 1309900B - 1310086B -
날씨각 587456B 1 https://weather.o2o.kr/ 587644B 1 https://weather.o2o.kr/
1 오늘 날씨 1371808B - 1371988B -
2 내일 날씨 1286270B - 1286446B -
3 모레 날씨 1150349B - 1150529B -
4 이번주 날씨 1312186B - 1312373B -
5 주말 날씨 1310861B - 1311044B -
6 날씨 1396630B - 1396810B -
7 서울 오늘 날씨 1281266B - 1281444B -
8 서울 내일 날씨 1283717B - 1283899B -
9 서울 날씨 1049772B - 1049958B -
10 부산 오늘 날씨 1245056B - 1245233B -
11 부산 내일 날씨 1266693B - 1266868B -
12 부산 날씨 1301723B - 1301909B -
13 인천 오늘 날씨 1269661B - 1269847B -
14 인천 내일 날씨 1262166B - 1262354B -
15 인천 날씨 1349694B - 1349880B -
16 대구 오늘 날씨 1226277B - 1226460B -
17 대구 내일 날씨 1242598B - 1242785B -
18 대구 날씨 1308738B - 1308920B -
19 대전 오늘 날씨 1237245B - 1237429B -
20 대전 내일 날씨 1274773B - 1274955B -
21 대전 날씨 1336096B - 1336282B -
22 광주 오늘 날씨 1309522B - 1309708B -
23 광주 내일 날씨 1252771B - 1252951B -
24 광주 날씨 1327984B - 1328170B -
25 울산 오늘 날씨 1262830B - 1263012B -
26 울산 내일 날씨 1231480B - 1231662B -
27 울산 날씨 1371449B - 1371627B -
28 세종 오늘 날씨 1245527B - 1245713B -
29 세종 내일 날씨 1313319B - 1313496B -
30 세종 날씨 1248849B - 1249029B -
31 수원 오늘 날씨 1265808B - 1265986B -
32 수원 내일 날씨 1243239B - 1243419B -
33 수원 날씨 1325589B - 1325769B -
34 성남 오늘 날씨 1253371B - 1253553B -
35 성남 내일 날씨 1177900B - 1178081B -
36 성남 날씨 1214952B - 1215137B -
37 고양 오늘 날씨 1270339B - 1270523B -
38 고양 내일 날씨 1249671B - 1249855B -
39 고양 날씨 1209803B - 1209983B -
40 용인 오늘 날씨 1243446B - 1243628B -
41 용인 내일 날씨 1203581B - 1203759B -
42 용인 날씨 1280794B - 1280976B -
43 창원 오늘 날씨 1209334B - 1209516B -
44 창원 내일 날씨 1221943B - 1222123B -
45 창원 날씨 1301874B - 1302054B -
46 청주 오늘 날씨 1239951B - 1240137B -
47 청주 내일 날씨 1253815B - 1253993B -
48 청주 날씨 1340520B - 1340700B -
49 천안 오늘 날씨 1221359B - 1221541B -
50 천안 내일 날씨 1218803B - 1218985B -
51 천안 날씨 1344315B - 1344497B -
52 전주 오늘 날씨 1806743B - 1806927B -
53 전주 내일 날씨 1758758B - 1758942B -
54 전주 날씨 1290043B - 1290227B -
55 군산 오늘 날씨 1255867B - 1256049B -
56 군산 내일 날씨 1205287B - 1205467B -
57 군산 날씨 1237974B - 1238154B -
58 포항 오늘 날씨 1205314B - 1205500B -
59 포항 내일 날씨 1256673B - 1256859B -
60 포항 날씨 1338947B - 1339126B -
61 제주 오늘 날씨 1284726B - 1284909B -
62 제주 내일 날씨 1224271B - 1224455B -
63 제주 날씨 1410935B - 1411375B -
64 김해 오늘 날씨 1202848B - 1203030B -
65 김해 내일 날씨 1237655B - 1237839B -
66 김해 날씨 1255061B - 1255242B -
67 화성 오늘 날씨 1320876B - 1321063B -
68 화성 내일 날씨 1158506B - 1158690B -
69 화성 날씨 1292521B - 1292705B -
70 부천 오늘 날씨 1208702B - 1208884B -
71 부천 내일 날씨 1207789B - 1207969B -
72 부천 날씨 1057895B - 1058083B -
73 안산 오늘 날씨 1257275B - 1257455B -
74 안산 내일 날씨 1517067B - 1517249B -
75 안산 날씨 1248040B - 1248222B -
76 남양주 오늘 날씨 1314986B - 1315174B -
77 남양주 내일 날씨 1246129B - 1246313B -
78 남양주 날씨 1309900B - 1310086B -
79 날씨각 587456B 1 https://weather.o2o.kr/ 587644B 1 https://weather.o2o.kr/
@@ -0,0 +1,79 @@
오늘 날씨 1241842B - 1242089B -
내일 날씨 1255827B - 1241265B -
모레 날씨 1146464B - 1150726B -
이번주 날씨 1290799B - 1290981B -
주말 날씨 1306886B - 1307070B -
날씨 1404122B - 1404306B -
서울 오늘 날씨 1241948B - 1242134B -
서울 내일 날씨 1282168B - 1282348B -
서울 날씨 985505B - 985689B -
부산 오늘 날씨 1264133B - 1264313B -
부산 내일 날씨 1265164B - 1265344B -
부산 날씨 1213605B - 1213787B -
인천 오늘 날씨 1300790B - 1300974B -
인천 내일 날씨 1293527B - 1293711B -
인천 날씨 1260461B - 1260641B -
대구 오늘 날씨 1244846B - 1245026B -
대구 내일 날씨 1305698B - 1305880B -
대구 날씨 1231166B - 1231339B -
대전 오늘 날씨 1260892B - 1261079B -
대전 내일 날씨 1315087B - 1315271B -
대전 날씨 1317624B - 1317802B -
광주 오늘 날씨 1277429B - 1277605B -
광주 내일 날씨 1282066B - 1282246B -
광주 날씨 1265430B - 1265611B -
울산 오늘 날씨 1238077B - 1238262B -
울산 내일 날씨 1213012B - 1213192B -
울산 날씨 1257139B - 1257323B -
세종 오늘 날씨 1335637B - 1335817B -
세종 내일 날씨 1244726B - 1244912B -
세종 날씨 1350300B - 1350480B -
수원 오늘 날씨 1238160B - 1238344B -
수원 내일 날씨 1228071B - 1228249B -
수원 날씨 1348504B - 1348684B -
성남 오늘 날씨 1279860B - 1280042B -
성남 내일 날씨 1189405B - 1189593B -
성남 날씨 1239403B - 1239585B -
고양 오늘 날씨 1286139B - 1286317B -
고양 내일 날씨 1208419B - 1208605B -
고양 날씨 1277571B - 1277753B -
용인 오늘 날씨 1200469B - 1200659B -
용인 내일 날씨 1236616B - 1236798B -
용인 날씨 1368350B - 1368532B -
창원 오늘 날씨 1244725B - 1244903B -
창원 내일 날씨 1203664B - 1203844B -
창원 날씨 1280151B - 1280329B -
청주 오늘 날씨 1302209B - 1302391B -
청주 내일 날씨 1278427B - 1278611B -
청주 날씨 1368258B - 1368442B -
천안 오늘 날씨 1236997B - 1237182B -
천안 내일 날씨 1243104B - 1243289B -
천안 날씨 1319722B - 1319904B -
전주 오늘 날씨 1800004B - 1800190B -
전주 내일 날씨 1783583B - 1783765B -
전주 날씨 1261004B - 1261188B -
군산 오늘 날씨 1282946B - 1283130B -
군산 내일 날씨 1271879B - 1272061B -
군산 날씨 1267946B - 1268128B -
포항 오늘 날씨 1279182B - 1279362B -
포항 내일 날씨 1261670B - 1261854B -
포항 날씨 1308817B - 1309003B -
제주 오늘 날씨 1253715B - 1253895B -
제주 내일 날씨 1334766B - 1334942B -
제주 날씨 1308240B - 1308434B -
김해 오늘 날씨 1221203B - 1221389B -
김해 내일 날씨 1221664B - 1221844B -
김해 날씨 1287333B - 1287517B -
화성 오늘 날씨 1249282B - 1249468B -
화성 내일 날씨 1233491B - 1233673B -
화성 날씨 997204B - 997384B -
부천 오늘 날씨 924121B - 924303B -
부천 내일 날씨 1239101B - 1239281B -
부천 날씨 1060555B - 1060741B -
안산 오늘 날씨 1271510B - 1271690B -
안산 내일 날씨 1590933B - 1591114B -
안산 날씨 1273204B - 1273392B -
남양주 오늘 날씨 1240661B - 1240841B -
남양주 내일 날씨 1263026B - 1263214B -
남양주 날씨 1308914B - 1309096B -
날씨각 612597B 1 https://weather.o2o.kr/tomorrow/incheon/namdong 612783B 1 https://weather.o2o.kr/tomorrow/incheon/namdong
1 오늘 날씨 1241842B - 1242089B -
2 내일 날씨 1255827B - 1241265B -
3 모레 날씨 1146464B - 1150726B -
4 이번주 날씨 1290799B - 1290981B -
5 주말 날씨 1306886B - 1307070B -
6 날씨 1404122B - 1404306B -
7 서울 오늘 날씨 1241948B - 1242134B -
8 서울 내일 날씨 1282168B - 1282348B -
9 서울 날씨 985505B - 985689B -
10 부산 오늘 날씨 1264133B - 1264313B -
11 부산 내일 날씨 1265164B - 1265344B -
12 부산 날씨 1213605B - 1213787B -
13 인천 오늘 날씨 1300790B - 1300974B -
14 인천 내일 날씨 1293527B - 1293711B -
15 인천 날씨 1260461B - 1260641B -
16 대구 오늘 날씨 1244846B - 1245026B -
17 대구 내일 날씨 1305698B - 1305880B -
18 대구 날씨 1231166B - 1231339B -
19 대전 오늘 날씨 1260892B - 1261079B -
20 대전 내일 날씨 1315087B - 1315271B -
21 대전 날씨 1317624B - 1317802B -
22 광주 오늘 날씨 1277429B - 1277605B -
23 광주 내일 날씨 1282066B - 1282246B -
24 광주 날씨 1265430B - 1265611B -
25 울산 오늘 날씨 1238077B - 1238262B -
26 울산 내일 날씨 1213012B - 1213192B -
27 울산 날씨 1257139B - 1257323B -
28 세종 오늘 날씨 1335637B - 1335817B -
29 세종 내일 날씨 1244726B - 1244912B -
30 세종 날씨 1350300B - 1350480B -
31 수원 오늘 날씨 1238160B - 1238344B -
32 수원 내일 날씨 1228071B - 1228249B -
33 수원 날씨 1348504B - 1348684B -
34 성남 오늘 날씨 1279860B - 1280042B -
35 성남 내일 날씨 1189405B - 1189593B -
36 성남 날씨 1239403B - 1239585B -
37 고양 오늘 날씨 1286139B - 1286317B -
38 고양 내일 날씨 1208419B - 1208605B -
39 고양 날씨 1277571B - 1277753B -
40 용인 오늘 날씨 1200469B - 1200659B -
41 용인 내일 날씨 1236616B - 1236798B -
42 용인 날씨 1368350B - 1368532B -
43 창원 오늘 날씨 1244725B - 1244903B -
44 창원 내일 날씨 1203664B - 1203844B -
45 창원 날씨 1280151B - 1280329B -
46 청주 오늘 날씨 1302209B - 1302391B -
47 청주 내일 날씨 1278427B - 1278611B -
48 청주 날씨 1368258B - 1368442B -
49 천안 오늘 날씨 1236997B - 1237182B -
50 천안 내일 날씨 1243104B - 1243289B -
51 천안 날씨 1319722B - 1319904B -
52 전주 오늘 날씨 1800004B - 1800190B -
53 전주 내일 날씨 1783583B - 1783765B -
54 전주 날씨 1261004B - 1261188B -
55 군산 오늘 날씨 1282946B - 1283130B -
56 군산 내일 날씨 1271879B - 1272061B -
57 군산 날씨 1267946B - 1268128B -
58 포항 오늘 날씨 1279182B - 1279362B -
59 포항 내일 날씨 1261670B - 1261854B -
60 포항 날씨 1308817B - 1309003B -
61 제주 오늘 날씨 1253715B - 1253895B -
62 제주 내일 날씨 1334766B - 1334942B -
63 제주 날씨 1308240B - 1308434B -
64 김해 오늘 날씨 1221203B - 1221389B -
65 김해 내일 날씨 1221664B - 1221844B -
66 김해 날씨 1287333B - 1287517B -
67 화성 오늘 날씨 1249282B - 1249468B -
68 화성 내일 날씨 1233491B - 1233673B -
69 화성 날씨 997204B - 997384B -
70 부천 오늘 날씨 924121B - 924303B -
71 부천 내일 날씨 1239101B - 1239281B -
72 부천 날씨 1060555B - 1060741B -
73 안산 오늘 날씨 1271510B - 1271690B -
74 안산 내일 날씨 1590933B - 1591114B -
75 안산 날씨 1273204B - 1273392B -
76 남양주 오늘 날씨 1240661B - 1240841B -
77 남양주 내일 날씨 1263026B - 1263214B -
78 남양주 날씨 1308914B - 1309096B -
79 날씨각 612597B 1 https://weather.o2o.kr/tomorrow/incheon/namdong 612783B 1 https://weather.o2o.kr/tomorrow/incheon/namdong
+26 -13
View File
@@ -402,7 +402,19 @@
순위 = 결과에서 weather.o2o.kr이 몇 번째 사이트인지(같은 사이트는 한 번만 셈). `-` 첫 페이지에 없음. 적힌 검색어만 나온 것, 나머지는 `-`.
구글은 첫 페이지(사이트 6~9개)만 본다. 로그인한 브라우저·위치(성남) 기준.
### 최근 요약 (10/28, 직전 10/27 대비)
### 최근 요약 (10/30, 직전 10/29 대비)
- 새로 잡힘: 없음
- 빠짐: 없음 (10/29에 빠진 `성남 오늘 날씨`·`고양 내일 날씨`·`수원 오늘 날씨`는 구글·네이버 모두 여전히 -)
- 순위 바뀜: 없음 — `날씨각` 네이버 1 그대로(첫 링크가 `/` → `/tomorrow/incheon/namdong`으로 바뀜), 구글은 `제주 날씨`부터 CAPTCHA로 `날씨각` 포함 16개 못 잼
### 지난 요약 (10/29, 직전 측정 대비 — 구글은 10/27, 네이버는 10/28)
- 새로 잡힘: 없음
- 빠짐: `성남 오늘 날씨` → 구글 2p8→-, 네이버 10→-. `고양 내일 날씨` → 구글 2p7→-. `수원 오늘 날씨` → 네이버 14→-. (구글 `site:weather.o2o.kr 성남` 은 9건 나와 색인은 살아 있음)
- 순위 바뀜: 없음 (`날씨각` 구글 1p1·네이버 1 그대로)
### 지난 요약 (10/28, 직전 10/27 대비)
- 새로 잡힘: `수원 오늘 날씨` → 네이버 14 (`/today/gyeonggi/suwon`)
- 순위 바뀜: `성남 오늘 날씨` → 네이버 6→10 (떨어짐)
@@ -424,21 +436,22 @@
실제 검색량이 큰 검색어 78개 + 날씨각. 구글 = 로그인 브라우저·성남 위치, 1~2페이지. 네이버 = 통합검색·웹 탭 첫 화면. `-` = 없음, `?` = 구글 차단으로 못 잼.
| 검색어 | 구글 10/26 | 구글 10/27 | 구글 10/28 | 네이버 10/26 | 네이버 10/27 | 네이버 10/28 |
|---|---|---|---|---|---|---|
| 날씨각 | 1p1 | 1p1 | 1p1 | 1 | 1 | 1 |
| 성남 오늘 날씨 | 2p10 `/today/gyeonggi/seongnam` | 2p8 | ? | 10 | 6 | 10 |
| 수원 오늘 날씨 | - | - | ? | - | - | 14 `/today/gyeonggi/suwon` |
| 고양 내일 날씨 | - | 2p7 `/tomorrow/gyeonggi/goyang` | ? | - | - | - |
| 군산 오늘 날씨 | 3p4 (2p 밖) | ? | ? | - | - | - |
| 오늘 날씨 · 내일 날씨 · 모레 날씨 · 이번주 날씨 · 주말 날씨 · 날씨 | - | - | ? | - | - | - |
| 서울 · 부산 · 인천 · 대전 · 광주 · 울산 · 세종 × 오늘/내일/날씨, 수원 내일·수원 날씨, 대구 날씨, 성남 내일·성남 날씨 | - | - | ? | - | - | - |
| 대구 오늘 날씨 · 대구 내일 날씨 | - | ? | ? | - | - | - |
| 고양 오늘·고양 날씨, 용인 · 창원 · 청주 · 천안 · 전주 × 오늘/내일/날씨 | - | - | ? | - | - | - |
| 군산 내일·군산 날씨, 포항 · 제주 · 김해 · 화성 · 부천 · 안산 · 남양주 × 오늘/내일/날씨 | - | ? | ? | - | - | - |
| 검색어 | 구글 10/26 | 구글 10/27 | 구글 10/28 | 구글 10/29 | 구글 10/30 | 네이버 10/26 | 네이버 10/27 | 네이버 10/28 | 네이버 10/29 | 네이버 10/30 |
|---|---|---|---|---|---|---|---|---|---|---|
| 날씨각 | 1p1 | 1p1 | 1p1 | 1p1 | ? | 1 | 1 | 1 | 1 | 1 `/tomorrow/incheon/namdong` |
| 성남 오늘 날씨 | 2p10 `/today/gyeonggi/seongnam` | 2p8 | ? | - | - | 10 | 6 | 10 | - | - |
| 수원 오늘 날씨 | - | - | ? | - | - | - | - | 14 `/today/gyeonggi/suwon` | - | - |
| 고양 내일 날씨 | - | 2p7 `/tomorrow/gyeonggi/goyang` | ? | - | - | - | - | - | - | - |
| 군산 오늘 날씨 | 3p4 (2p 밖) | ? | ? | - | - | - | - | - | - | - |
| 오늘 날씨 · 내일 날씨 · 모레 날씨 · 이번주 날씨 · 주말 날씨 · 날씨 | - | - | ? | - | - | - | - | - | - | - |
| 서울 · 부산 · 인천 · 대전 · 광주 · 울산 · 세종 × 오늘/내일/날씨, 수원 내일·수원 날씨, 대구 날씨, 성남 내일·성남 날씨 | - | - | ? | - | - | - | - | - | - | - |
| 대구 오늘 날씨 · 대구 내일 날씨 | - | ? | ? | - | - | - | - | - | - | - |
| 고양 오늘·고양 날씨, 용인 · 창원 · 청주 · 천안 · 전주 × 오늘/내일/날씨 | - | - | ? | - | - | - | - | - | - | - |
| 군산 내일·군산 날씨, 포항 · 제주 · 김해 · 화성 · 부천 · 안산 · 남양주 × 오늘/내일/날씨 | - | ? | ? | - | - (제주 날씨·김해·화성·부천·안산·남양주는 ?) | - | - | - | - | - |
- 서울·부산·인천·대구·대전·광주·울산은 시 단위 페이지가 없음(구 페이지만). '서울 날씨'를 받을 페이지 자체가 없다.
- 원본: `docs/search_log/{날짜}_naver_대표검색어.tsv`
- 10/30 구글: 탭에서 열어 63개까지 잼, `제주 날씨`에서 CAPTCHA(sorry)로 멈춤. 나머지 16개(`날씨각` 포함)는 `?`.
- 10/28 구글: 브라우저 fetch 로 받은 검색 결과가 'JavaScript 필요' 안내 페이지로 바뀌어 결과를 못 읽었고, 탭에서 직접 열자 CAPTCHA(sorry)가 떠 멈춤. 다음 측정은 탭에서 실제 페이지를 열어 읽는 방식으로 해야 함.
### 키워드별 잡힘 (10/26)
+88
View File
@@ -0,0 +1,88 @@
# 날씨 사주 계산식
코드가 기준이다. 값을 바꾸면 이 문서도 같이 고친다. 해석 기준 결정은 `TODO.md` '날씨 사주 해석 기준' 줄.
## 요약
| 단계 | 하는 일 | 코드 |
|---|---|---|
| 1. 네 기둥 | 연주는 입춘, 월주는 절입 시각(천문 계산), 일주·시주는 출생지 지방평균시(서머타임 걷어냄)로 가른다 | `services/saju/pillars.py`, `birth.py`, `solar_terms.py` |
| 2. 오행 세력 | 자리 점수(월지 30·일지 20·나머지 10)를 지지는 지장간 날 수대로 나눠 오행별로 더한다. 일간을 돕는 몫 + 득령 가산 0.15 가 55% 이상 신강, 45% 미만 신약, 사이 중화 | `services/saju/strength.py` |
| 3. 조후(내 기운) | 글자마다 한난·조습 값을 두고, 태어난 달(월령)이 다른 글자를 데우거나 식힌다. 흙은 계절 따라 마르고 젖는다. 자리 점수로 평균 → '따뜻·마름' 같은 결 + 계절 = 기운 장면 | `services/saju/climate.py` |
| 4. 사주 점수 | 50에서 시작, 오늘 일진의 십성·원국과의 합충형파해·도화·홍염을 더한다 | `services/saju/daily.py` |
| 5. 날씨 궁합 | 시간별 체감·습도·비가 내 조후를 균형 쪽으로 옮기는지. 50이 보통 | `services/saju/climate.py` |
| 6. 오늘 점수 | 사주 점수를 68 중심으로 늘리고 (날씨 궁합 − 50) × 0.6 을 더한다 | `services/saju_service.py` |
| 7. 궁합 | 서로의 일간 십성 평균 + 일간 합 + 일지 합·충 + 조후가 서로 채워 주는지 | `services/saju_service.py` `match_reading` |
## 1. 네 기둥
- 날짜 범위 1900-01-01 ~ 2100-12-31.
- 절입 시각: 태양 시황경을 Meeus 25장(VSOP87 요약표·장동·광행차)으로 계산, ΔT 는 Espenak–Meeus 다항식. 연주는 입춘(315°), 월주는 직전 절.
- 시간: 시계 시각 → 표준시 변경·서머타임을 걷어내고 지방평균시로. 평소 서울은 (경도 − 135) × 4분 ≈ −32분. 기본 경도 126.978(서울시청).
- 일주: 1900-01-01 甲戌부터 60일 주기. 시주: 23시부터 두 시간씩, 시간(時干)은 甲己→甲子 규칙.
- 자시: 기본 자정 기준(`midnight`), 설정으로 23시 기준(`23h`). 둘 다 23~01시 시주 간지는 같다.
- 시간을 모르면 시주 없이, 연·월주는 그날 12시 기준. 그날 절이 들면 `jeol_on_birth_day` 로 표시.
## 2. 오행 세력·신강신약
자리 점수 `POSITION_POINTS`:
| | 연 | 월 | 일 | 시 |
|---|---|---|---|---|
| 천간 | 10 | 10 | 10(일간) | 10 |
| 지지 | 10 | **30** | 20 | 10 |
- 지지 점수는 지장간 날 수(`HIDDEN_DAYS`, 30일)대로 나눈다. 고지(辰戌丑未) 9·3·18, 생지(寅申巳亥) 7·7·16, 子卯酉 10·20, 午 丙10·己9·丁11.
- 예: 월지 未 30점 → 丁(화) 9, 乙(목) 3, 己(토) 18.
- `elements`: 일간 포함 오행별 합. `top`: 가장 큰 오행(같으면 木火土金水 순 앞).
- `support` = (일간 빼고) 일간과 같은 오행 + 일간을 생하는 오행 점수 ÷ 일간 뺀 점수 합. 시주가 있으면 분모 100.
- 득령 = 월지 계절 오행(寅卯 木, 巳午 火, 申酉 金, 亥子 水, 辰戌丑未 土)이 일간과 같거나 일간을 생함. 득령이면 support 에 0.15 를 더해 판정.
- `label` = (support + 득령 가산) ≥ 0.55 신강, < 0.45 신약, 사이 중화. 강약은 득령을 먼저 본다 (10/29 사용자 결정 — 未월 己土가 시주 하나로 신약이 되던 문제).
- 근거: 득령(월지)·득지(일지)·득세 판단, 월지 30·일지 20·그 외 10 배점은 흔히 쓰는 예시 배점.
- 화면: API `me.elements`·`top_element`·`strong`·`support`, 기둥별 `stem_ten_god`·`branch_ten_god`(지지는 정기 기준) → 사주 명식 카드.
## 3. 조후 (내 기운)
1. 글자별 바탕값 `CHAR_CLIMATE` (한난 −1 차가움 … +1 따뜻, 조습 −1 마름 … +1 습함).
- 불 丙丁巳午: 따뜻·마름 / 물 壬癸亥子: 차고 젖음 / 쇠 庚辛申酉: 서늘·마름
- 흙: 戊未戌 마른 흙, 己丑辰 젖은 흙. 未는 대서가 든 한여름이라 (0.9, −0.7)
2. 월령 보정 `seasoned()` — 월지 자신 말고 모든 글자에:
- 한난 += 세기 × `MONTH_TEMP[월지]` (寅 −0.4, 卯 −0.1, 辰 0.2, 巳 0.6, 午 0.9, 未 1.0, 申 0.4, 酉 −0.1, 戌 −0.3, 亥 −0.6, 子 −0.9, 丑 −1.0)
- 조습 += 세기 × `SEASON_MOIST[계절]` (봄 0.3, 여름 −1, 가을 −0.5, 겨울 1)
- 세기 `SEASON_PULL`: 흙(戊己辰戌丑未) 한난 0.5·조습 0.8, 나머지 한난 0.3·조습 0.2. 결과는 −1~1 로 자름
- 근거: 『궁통보감』 三夏己土 "取癸為要,次用丙火", 六月 명례 평주 "六月土燥木枯" — 여름 흙은 마른 흙으로 본다
3. 평균: 보정된 값을 자리 점수(2번 표와 같음)로 가중 평균 → `temp`, `moist`.
4. 필요(`need`): 축 값이 ±0.1 밖이면 반대쪽이 필요 (차가우면 warm, 습하면 dry). 안이면 mild.
5. 이름(`label`): 축 값이 ±0.1 밖이면 부호대로. 안(균형)이면 세력 1위 오행 쪽으로 — 火 따뜻·마름, 金 서늘·마름, 水 서늘·촉촉, 土·木은 월지 글자 값.
6. 기운 장면 `SCENES[(계절, label)]` 16종 (`services/saju_text.py`). 계절은 월지 삼회(寅卯辰 봄 …).
## 4. 사주 점수 (`SCORE_WEIGHTS`)
- 50 + 오늘 천간 십성(비견 2, 겁재 −2, 식신 4, 상관 −2, 편재 3, 정재 4, 편관 −4, 정관 3, 편인 −1, 정인 4)
+ 오늘 지지(정기) 십성 × 0.5
+ 원국과의 관계(천간합 4, 천간충 −5, 육합 5, 삼합 6, 반합 3, 충 −6, 형 −4, 삼형 −6, 자형 −2, 파 −2, 해 −2, 원진 −3) × 자리 비중(연 0.8, 월 1, 일 1.5, 시 0.8, 삼합·삼형은 1)
+ 도화 3(연지·일지 기준) + 홍염 2 → 0~100 으로 자름.
- 삼합·삼형이 완성되면 같은 묶음의 반합·형은 겹쳐 세지 않는다. 용신은 보지 않는다.
## 5. 날씨 궁합 (`climate_match`)
- 날씨 → 두 축: 한난 = (체감 − 15) ÷ 15, 조습 = (습도 − 55) ÷ 35, 비가 오면 조습 최소 0.8. −1~1.
- 축 효과 = |사주| − |사주 + 0.3 × 날씨| (균형 쪽으로 옮기면 +). 이미 균형(±0.1)인 축은 순한 날씨(±0.3 안)에 +, 거센 날씨에 −.
- 시간 점수 = 50 + 120 × (0.6 × 한난 효과 + 0.4 × 조습 효과), 0~100.
- 하루 점수 = 06~21시 평균. 좋은 시간대 = 평균이 가장 높은 연속 3시간(체감 5~30° 안), 끝 시간이 5점 넘게 처지면 2시간.
## 6. 오늘 점수
- 화면 사주 점수 = 68 + (사주 점수 − 50) × 1.2, 25~98.
- 오늘 점수 = 화면 사주 점수 + round((날씨 궁합 − 50) × 0.6 × 1.2), 25~98. 날씨가 없으면 사주만.
- 앞으로 7일 '좋은 날'은 점수 60 이상만. 금전은 편재·정재 날, 일은 정관·정인·상관 날, 돈 조심은 비견·겁재 날 중 최저.
## 7. 궁합 (`MATCH_SCORE`)
- 55 + (내가 본 상대 일간 십성 묶음 점수 + 상대가 본 나) ÷ 2 — 인성 8, 재성 5, 식상 5, 비겁 2, 관성 0.
- 일간 천간합 +12, 일지 육합·반합 +8, 일지 충·형 등 −8.
- 조후가 서로 채워 주면(한쪽은 따뜻함이, 다른 쪽은 서늘함이 필요 등) 축마다 +5. 0~100.
## 연애운 (`love_facts`)
- 남자는 재성, 여자는 관성이 오늘 천간·지지에 들면. 성별을 안 고르면 이건 빼고 도화·홍염·일지 관계(육합·반합·충·형·자형·원진)만.
+16 -3
View File
@@ -34,14 +34,18 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `install_choice` | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
| `install_done` | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
| `app_launch` | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
| `boot_stuck` | 8초 넘게 '날씨 불러오는 중' 첫 화면이 남음 (페이지마다 한 번) | `reason`(첫 오류 문구, 100자), `seconds`, `tries`(연달아 다시 불러온 횟수), `app_started`(앱 파일 실행 여부) | `index.html` 첫 화면 스크립트 |
| `sheet_open` | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`) | `Sheets.tsx` `SheetProvider` `open` |
| `like` | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호) | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
| `comment` | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
| `talk_comment` | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
| `terms_agree` | 댓글 쓰기 전 이용약관 동의 성공 | 없음 | `Sheets.tsx` `CommentsSheet` `agreeAndSend` |
| `report` | 신고 성공 | `content_type: 'comment' \| 'talk'`, `reason`(신고 이유 번호) | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
| `block` | 차단 성공 | `content_type: 'comment' \| 'talk'` | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
| `talk_post` | 이야기 글 올리기 성공 | `topic`(주제 번호), `with_image` | `talk.tsx` 글쓰기 `submit` |
| `talk_post` | 이야기 글 올리기 성공 | `topic`(주제 번호, 6~9 는 기념일: 할로윈·빼빼로데이·크리스마스·추석), `with_image` | `talk.tsx` 글쓰기 `submit` |
| `feed_item_view` | 오늘 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보임 (한 장에 한 번) | `item_type: 'talk' \| 'event'`, `position`(피드에서 그 종류의 몇 번째) | `TodayPage.tsx` `Seen` |
| `hero_day_switch` | 히어로 오늘/내일 스위치를 바꿈 | `day: 'today' \| 'tomorrow'` | `TodayPage.tsx` |
| `tomorrow_to_today` | 내일 날씨 페이지(`/tomorrow/...`) 맨 아래 '오늘 ○○ 소식 보기'를 누름 | `region_name` | `TomorrowFeed.tsx` |
| `shorts_open` | 쇼츠 페이지(/shorts/영상ID)로 들어옴 (오늘 화면 쇼츠 줄·공유 링크) | `video_id` | `Shorts.tsx` `ShortsPage` |
| `shorts_view` | 쇼츠를 넘겨 다른 영상으로 감 | `video_id`, `index`(목록 순서) | `Shorts.tsx` `ShortsPage` |
| `shorts_sound` | 쇼츠 소리 켜기·끄기 | `on` | `Shorts.tsx` `toggleSound` |
@@ -54,8 +58,8 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `day_log` | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` |
| `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
| `saju_input` | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` |
| `saju_view` | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score` | `SajuPage.tsx` `Reading` |
| `game_start` | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속) | `CloudMergePage.tsx` `onUp` |
| `saju_view` | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score`, `strength`(신강·중화·신약), `top_element`(가장 센 오행) | `SajuPage.tsx` `Reading` |
| `game_start` | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속), `theme`(그림: `basic`·`halloween`·`pepero`·`christmas`·`chuseok`, `holiday.ts`) | `CloudMergePage.tsx` `onUp` |
| `game_round` | 구름 합치기 라운드를 깸 | `round`(깬 라운드), `score`(그때 총점), `logged_in`(각을 받는지) | `CloudMergePage.tsx` `onScore` |
| `game_over` | 구름 합치기가 넘쳐서 끝남 | `round`(끝난 라운드), `score`, `best`(최고 기록 갱신), `drops`(떨어뜨린 횟수) | `CloudMergePage.tsx` `onOver` |
@@ -71,3 +75,12 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
- 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 보고서를 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다. 등록 전 값은 보고서에 소급되지 않는다.
- 확인은 GA4 보고서 → 실시간, 또는 관리 → DebugView에서 한다. 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)나 운영 사이트에서 눌러 본다.
## 분석 기록
`/ga-report` 로 GA4·운영 DB 를 앞 같은 길이 기간과 비교한 기록. 사람 수 기준.
| 날짜 | 기간 | 활성 사용자(앞 기간) | 신규 | 가입(DB) | 바뀐 것 | 할 일 |
|---|---|---|---|---|---|---|
| 10/29 | 10/22~10/28 (앞: 10/15~10/21) | 206 (33). 그중 약 146명은 성남·아이폰 390x844·근무시간·한 번 열고 2~3초(자동 화면 테스트로 추정). 성남 밖 76 (약 26) | 187 (21) | 7 (구글 4·토스 3), 앞 기간 0 | 구글 검색 유입 37명(12)·참여율 72%로 실제 성장 대부분. 내일 페이지(서귀포·평택·성동·정읍)로 들어옴. 설치 카드 본 사람(테스트 뺀) 77명 중 누른 사람 0. 인스타 유입 5명. 사주 페이지 7명→결과 3명(10/28 출시, 판단 보류). 게임 GA 이벤트는 10/29부터 | 테스트 트래픽 GA에서 빼기, 맞춤 측정기준 등록, 설치 카드 손보기 (TODO.md 'GA 분석') |
+4
View File
@@ -25,3 +25,7 @@ dist-ssr
dist-toss
*.ait
# deploy.sh 가 모아 두는 지난 배포 빌드 파일
.old-assets/*
!.old-assets/.gitkeep
View File
Whitespace-only changes.
+2
View File
@@ -32,6 +32,8 @@ RUN npm run build
# ---- prod: nginx로 정적 파일 제공 ----
FROM nginx:1.29-alpine AS prod
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
# 지난 배포의 빌드 파일(deploy.sh 가 모아 둠). 이미 열어 둔 탭·구글 렌더가 예전 HTML 로 예전 파일을 불러도 뜨게 한다
COPY frontend/.old-assets/ /usr/share/nginx/html/assets/
COPY --from=build /app/frontend/dist /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
+62 -5
View File
@@ -13,24 +13,81 @@
<script>
// 이미 열었던 탭을 다시 열면 브라우저가 예전 HTML 을 다시 쓰고, 그 HTML 이 부르는 예전 빌드 파일은 배포로 지워져 첫 화면에서 멈춘다.
// 돌아왔을 때 망이 아직 안 붙어 다시 불러온 것까지 실패하기도 하니, 첫 화면이 남아 있는 동안은 계속 다시 시도한다:
// 빌드 파일을 못 받았을 때, 12초마다, 탭을 다시 볼 때, 망이 다시 붙을 때 (10초 안에 또 하지는 않는다)
// 빌드 파일을 못 받았을 때, 12초마다, 탭을 다시 볼 때, 망이 다시 붙을 때 (10초 안에 또 하지는 않는다).
// 연달아 3번 다시 불러와도 그대로면 멈추고, 8초 넘게 첫 화면이면 그 까닭과 '다시 불러오기'를 보여 주고 GA boot_stuck 으로 보낸다
(function () {
var KEY = 'nalssigak.bootReload'
var TRIES = 'nalssigak.bootTries'
var errs = []
var start = Date.now()
function tries() {
try {
return Date.now() - Number(sessionStorage.getItem(KEY) || 0) < 60000 ? Number(sessionStorage.getItem(TRIES) || 0) : 0
} catch (e) {
console.error('[boot] storage', e)
return 0
}
}
function retry() {
if (!document.getElementById('boot') || document.hidden) return
var n = tries()
try {
var last = Number(sessionStorage.getItem(KEY) || 0)
if (Date.now() - last < 10000) return
if (Date.now() - Number(sessionStorage.getItem(KEY) || 0) < 10000 || n >= 3) return
sessionStorage.setItem(KEY, String(Date.now()))
sessionStorage.setItem(TRIES, String(n + 1))
} catch (e) {
console.error('[boot] storage', e)
}
location.reload()
if (n < 1) return location.reload()
// 두 번째부터는 폰에 남은 빌드 파일(1년 캐시)이 깨졌을 수 있어 새로 받아 덮고, 서비스 워커도 걷어낸 뒤 다시 불러온다
var files = [].map.call(document.querySelectorAll('script[src^="/"],link[rel=stylesheet][href^="/"],link[rel=modulepreload][href^="/"]'), function (el) {
return fetch(el.src || el.href, { cache: 'reload' }).catch(function (e) {
console.error('[boot] refetch', e)
})
})
var sw = navigator.serviceWorker ? navigator.serviceWorker.getRegistrations().then(function (rs) {
return Promise.all(rs.map(function (r) { return r.unregister() }))
}) : null
Promise.all(files.concat(sw ? [sw] : [])).then(function () { location.reload() }, function (e) {
console.error('[boot] cleanup', e)
location.reload()
})
}
function note(msg) {
if (errs.length < 3) errs.push(String(msg).slice(0, 160))
}
window.addEventListener('error', function (e) {
var el = e.target
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK') && (el.src || el.href || '').indexOf(location.origin + '/') === 0) retry()
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK')) {
var url = el.src || el.href || ''
if (url.indexOf(location.origin + '/') !== 0) return
note('파일 못 받음 ' + url.slice(location.origin.length))
retry()
return
}
note((e.message || 'error') + (e.filename ? ' @' + e.filename.split('/').pop() + ':' + e.lineno : ''))
}, true)
window.addEventListener('unhandledrejection', function (e) {
var r = e.reason
note('promise ' + (r && r.message ? r.message : String(r)))
})
setTimeout(function () {
var boot = document.getElementById('boot')
if (!boot) return
var reason = errs[0] || (window.__appStarted ? '앱이 떴지만 첫 화면을 못 걷음' : '앱 파일이 실행되지 않음')
var p = document.createElement('p')
p.style.cssText = 'margin:0 24px;font:12px/1.5 sans-serif;opacity:.7;text-align:center;word-break:break-all'
p.textContent = errs.length ? errs.join(' / ') : reason
var b = document.createElement('button')
b.textContent = '다시 불러오기'
b.style.cssText = 'padding:10px 20px;border:0;border-radius:999px;background:#28304a;color:#fff;font:16px Jua,sans-serif'
b.onclick = function () {
location.reload()
}
boot.appendChild(p)
boot.appendChild(b)
gtag('event', 'boot_stuck', { reason: reason.slice(0, 100), seconds: Math.round((Date.now() - start) / 1000), tries: tries(), app_started: !!window.__appStarted })
}, 8000)
var timer = setInterval(function () {
if (document.getElementById('boot')) retry()
else clearInterval(timer)
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+2 -2
View File
@@ -16,7 +16,7 @@
},
{
"q": "더운 날 뭐 하면 좋을까요?",
"a": "더운 날엔 낮엔 물놀이·빙수·냉면, 운동은 해 뜨기 전 아침이나 해 진 뒤가 좋아요. 러닝각은 체감 35° 이상이면 0점이라 아침 6~8시나 저녁 7~10시 중 시원한 쪽을 고르세요. 빨래는 잘 마르니 이불 빨래하기 좋은 날이에요."
"a": "더운 낮에는 물놀이·빙수·냉면, 운동은 선선한 아침이나 저녁이 좋아요. 러닝각은 체감 28° 이상이면 최대 30점, 35° 이상이면 0점이에요."
},
{
"q": "추운 날 뭐 하면 좋을까요?",
@@ -45,7 +45,7 @@
},
{
"q": "러닝하기 좋은 날씨와 시간은 언제인가요?",
"a": "러닝은 체감 8~18°에 습도가 낮고 바람이 잔잔한 날이 좋아요. 러닝각은 아침 6~8시와 저녁 7~10시 날씨로 계산해 둘 중 좋은 쪽 점수를 보여 드려요."
"a": "러닝각은 체감 5~18°를 편한 범위로 보고 12° 부근을 가장 높게 평가해요. 비 소식이나 높은 비 확률, 체감 5° 미만의 추위에는 점수를 크게 낮춰요. 활동 시간대인 6~8시·19~22시와 겹치지 않는 구간은 최대 50점이에요."
},
{
"q": "캠핑하기 좋은 날씨는 언제인가요?",
+10 -1
View File
@@ -9,6 +9,7 @@ import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { currentHoliday } from './holiday'
import { LevelBadge, LevelWatcher } from './level'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
@@ -106,6 +107,8 @@ const SHOOTS = [
{ top: '14%', left: '96%', '--len': '120px', '--dur': '12s', '--dl': '9s' },
]
const HOLIDAY = currentHoliday()
/** 화면 전체 하늘: 시간대별 색, 아주 느리게 일렁이는 색 덩어리, 밤에는 별 */
function SkyBg() {
const { kind } = useSky()
@@ -116,10 +119,11 @@ function SkyBg() {
return () => document.removeEventListener('visibilitychange', onVis)
}, [])
return (
<div className={cx('b-skybg pointer-events-none fixed inset-0 overflow-hidden', hidden && 'b-paused')} data-t={kind} aria-hidden="true">
<div className={cx('b-skybg pointer-events-none fixed inset-0 overflow-hidden', hidden && 'b-paused')} data-t={kind} data-h={HOLIDAY?.key} aria-hidden="true">
{(['morning', 'day', 'sunset', 'night'] as const).map((k) => (
<div key={k} className={cx('b-sky-lay absolute inset-0', `b-sky-${k}`)} />
))}
{HOLIDAY && <div className="b-sky-lay b-sky-holiday absolute inset-0" />}
<span className="b-blob b-blob-1" />
<span className="b-blob b-blob-2" />
<span className="b-blob b-blob-3" />
@@ -264,6 +268,11 @@ function Shell() {
<FirstLoad />
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
{HOLIDAY && (
<div className="b-holiday-head pointer-events-none fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] overflow-hidden" data-h={HOLIDAY.key} data-t={kind} aria-hidden="true">
<i />
</div>
)}
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
<TopBar />
+2 -2
View File
@@ -10,7 +10,7 @@ import { slotAt } from '@nalssigak/shared/lib/weatherText'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
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, HOLIDAY, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
import { useLevel } from './level'
import { iconSrc } from './lib'
import { useRegion } from './regionContext'
@@ -213,7 +213,7 @@ export function CloudMergePage() {
const onUp = (e: PointerEvent<HTMLCanvasElement>) => {
const game = gameRef.current
if (!game || over || performance.now() < coolRef.current) return
if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs })
if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs, theme: HOLIDAY?.key ?? 'basic' })
dropsRef.current += 1
game.drop(nextRef.current, toX(e))
coolRef.current = performance.now() + 450
+1 -1
View File
@@ -126,7 +126,7 @@ function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
)
}
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
export function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
+144 -31
View File
@@ -17,6 +17,25 @@ const SEEN_KEY = 'nalssigak.b.sajuSeen'
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 POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' }
const EL_WORD: Record<string, string> = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' }
const EL_ART: Record<string, string> = { 木: 'wood', 火: 'fire', 土: 'earth', 金: 'metal', 水: 'water' }
const STRENGTH_WORD: Record<string, string> = {
신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요',
중화: '나를 돕는 기운과 다른 기운이 비슷한 사주',
신약: '나를 돕는 기운이 약한 사주',
}
const TEN_GOD_WORD: Record<string, string> = {
비견: '나와 같은 기운',
겁재: '나와 같지만 겨루는 기운',
식신: '내가 만들어 내는 기운',
상관: '내가 드러내는 기운',
편재: '내가 크게 굴리는 재물',
정재: '내가 차곡차곡 모으는 재물',
편관: '나를 세게 다잡는 기운',
정관: '나를 바르게 이끄는 기운',
편인: '나를 돕는 남다른 지혜',
정인: '나를 돕는 배움·도움',
}
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})`
@@ -192,7 +211,7 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
useEffect(() => {
if (!r?.today) return
markSeen()
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score })
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' })
}, [r])
if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">사주를 풀고 있어요…</p>
@@ -210,30 +229,40 @@ function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
return (
<div className="flex flex-col gap-3">
<div ref={shot} className="mx-4 mt-3 rounded-[26px] bg-white px-5 pt-4 pb-5 shadow-[inset_0_-5px_0_var(--shade)]">
<p className="m-0 text-center text-[12.5px] font-extrabold text-(--ink3)">
<div ref={shot} className="mx-4 mt-3 rounded-[26px] bg-white px-4 pt-4 pb-4 shadow-[inset_0_-5px_0_var(--shade)]">
<p className="m-0 text-[12.5px] font-extrabold text-(--ink3)">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</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>
<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>
{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]')}>
날씨 영향 {t.weather_points >= 0 ? '+' : '−'}
{Math.abs(t.weather_points)}점
</span>
)}
<div className="mt-2 flex items-center gap-4">
<ScoreRing score={t.score} />
<div className="min-w-0 flex-1">
<h3 className="m-0 font-jua text-[21px] leading-tight font-normal">{t.title}</h3>
<ScoreBar label="사주" value={t.saju_score} width={t.saju_score} color="var(--ink)" />
{t.weather_points != null && (
<ScoreBar
label="날씨 영향"
value={t.weather_points}
width={Math.min(100, Math.abs(t.weather_points) * 3)}
color={t.weather_points >= 0 ? '#1f7a4f' : '#e8663a'}
signed
/>
)}
</div>
</div>
{(t.why?.length ?? 0) > 0 && (
<details className="mt-2 text-center">
<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)">
{t.why!.map((w) => (
<li key={w}>{w}</li>
))}
</ul>
</details>
<ul className="m-0 mt-3 flex list-none flex-col gap-1.5 p-0">
{t.why!.map((w) => (
<li
key={w}
className={cx(
'rounded-xl px-3 py-2 text-[13px] leading-snug font-bold',
w.startsWith('↓') ? 'bg-[#fff1ea] text-[#b5421a]' : 'bg-[#eef3fb] text-(--ink)',
)}
>
{w}
</li>
))}
</ul>
)}
</div>
@@ -289,40 +318,124 @@ function DecisionCard({ c }: { c: SajuCard }) {
)
}
function ScoreRing({ score }: { score: number }) {
const r = 46
const len = 2 * Math.PI * r
return (
<div className="relative size-[116px] shrink-0">
<svg viewBox="0 0 116 116" className="size-full -rotate-90" aria-hidden>
<circle cx="58" cy="58" r={r} fill="none" stroke="#eef1f6" strokeWidth="11" />
<circle cx="58" cy="58" r={r} fill="none" stroke="var(--orange)" strokeWidth="11" strokeLinecap="round" strokeDasharray={`${(len * score) / 100} ${len}`} />
</svg>
<span className="absolute inset-0 grid place-items-center">
<span className="text-center">
<b className="block font-bagel text-[40px] leading-none">{score}</b>
<small className="text-[11px] font-extrabold text-(--ink3)">오늘의 점수</small>
</span>
</span>
</div>
)
}
function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) {
return (
<div className="mt-2">
<p className="m-0 flex justify-between text-[12.5px] font-extrabold" style={{ color }}>
<span>{label}</span>
<span>
{signed ? (value >= 0 ? '+' : '−') : ''}
{Math.abs(value)}점
</span>
</p>
<span className="mt-1 block h-2 overflow-hidden rounded-full bg-[#eef1f6]">
<span className="block h-full rounded-full" style={{ width: `${width}%`, background: color }} />
</span>
</div>
)
}
function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const me = r.me!
const cols = [...me.pillars].reverse()
const els = Object.entries(me.elements ?? {})
const total = els.reduce((a, [, v]) => a + v, 0)
const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))]
const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약')
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>}>
<p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p>
<Panel icon={me.scene_icon} title="사주 명식" right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}>
{me.top_element && strength && (
<div className="flex items-center gap-3">
<img src={`/saju/${EL_ART[me.top_element]}.webp`} alt="" className="size-16 shrink-0 object-contain" />
<div className="min-w-0">
<p className="m-0 font-jua text-[18px] leading-snug">
{EL_WORD[me.top_element]}({me.top_element}) 기운이 가장 센 {strength} 사주
</p>
<p className="m-0 mt-0.5 text-[13px] font-semibold text-(--ink2)">
나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene}
</p>
</div>
</div>
)}
{total > 0 && (
<>
<div className="mt-2.5 flex h-2.5 overflow-hidden rounded-full" role="img" aria-label={els.map(([k, v]) => `${k} ${Math.round(v)}`).join(', ')}>
{els.map(([k, v]) => (
<span key={k} style={{ width: `${(v / total) * 100}%`, background: EL_COLOR[k]?.[0] }} />
))}
</div>
<div className="mt-1.5 flex justify-between text-[12px] font-extrabold">
{els.map(([k, v]) => (
<span key={k} className="flex items-center gap-0.5" style={{ color: EL_COLOR[k]?.[0] }}>
<img src={`/saju/${EL_ART[k]}.webp`} alt="" className="size-5 object-contain" />
{k} {Math.round(v)}
</span>
))}
</div>
</>
)}
<div className="mt-3 grid grid-cols-4 gap-1.5 text-center">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<div key={p?.position ?? `none-${i}`} className="flex flex-col gap-1">
<span className="text-[11px] font-extrabold text-(--ink3)">{p ? POS_WORD[p.position] : '시'}</span>
<span className="text-[11px] font-extrabold text-(--ink3)">{p ? `${POS_WORD[p.position]}주` : '시주'}</span>
{p ? (
<>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} />
<span className={cx('text-[11.5px] font-extrabold', p.position === 'day' ? 'text-(--orange)' : 'text-(--ink2)')}>{p.position === 'day' ? '나' : p.stem_ten_god}</span>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} me={p.position === 'day'} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
<span className="text-[11.5px] font-extrabold text-(--ink2)">{p.branch_ten_god}</span>
{p.position === 'month' && <span className="text-[10.5px] font-extrabold text-(--ink3)">월령</span>}
</>
) : (
<>
<span className="grid flex-1 place-items-center rounded-xl bg-[#f1f3f7] text-[12px] font-extrabold text-[#a0a8ba]">시각 모름</span>
</>
<span className="grid flex-1 place-items-center rounded-xl bg-[#f1f3f7] px-1 text-[12px] font-extrabold text-[#a0a8ba]">시각 모름</span>
)}
</div>
))}
</div>
<p className="m-0 mt-2 text-[11.5px] font-semibold text-(--ink3)">태어난 연·월·일·시의 여덟 글자(사주팔자)예요. 색은 나무·불·흙·쇠·물 다섯 기운이에요.</p>
<ul className="m-0 mt-3 list-none border-t border-(--line) p-0 pt-2.5 text-[12.5px] leading-relaxed font-semibold text-(--ink2)">
{strength && (
<li>
<b className="text-(--ink)">{strength}</b> = {STRENGTH_WORD[strength]}
</li>
)}
{gods.map((g) => (
<li key={g}>
<b className="text-(--ink)">{g}</b> = {TEN_GOD_WORD[g]}
</li>
))}
<li>
<b className="text-(--ink)">월령</b> = 태어난 달의 계절 기운. 명식에서 가장 크게 봐요
</li>
</ul>
{(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>}
</Panel>
)
}
function Char({ c, ko, el }: { c: string; ko: string; el: string }) {
function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb']
return (
<span className="rounded-xl py-1.5" style={{ background: bg, color: fg }}>
<span className={cx('rounded-xl py-1.5', me && 'ring-2 ring-(--orange)')} style={{ background: bg, color: fg }}>
<b className="block font-batang text-[22px] leading-tight">{c}</b>
<small className="text-[10.5px] font-extrabold">{ko}</small>
</span>
+56 -29
View File
@@ -5,6 +5,7 @@ import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/aut
import { SITE_URL } from '../api/setup'
import {
addCommentMutation,
addTalkCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
@@ -14,6 +15,8 @@ import {
getSeasonWeekOptions,
likeCommentMutation,
listCommentsInfiniteOptions,
listTalkCommentsInfiniteOptions,
listTalkCommentsInfiniteQueryKey,
listBlockedOptions,
listBlockedQueryKey,
listCommentsInfiniteQueryKey,
@@ -44,9 +47,9 @@ import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
import { LEVELS } from './cloudMerge'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
import { SheetContext, useSheet, type CommentTarget, type SharePayload, type SheetState } from './sheetContext'
import { HeartIcon } from './svg'
import { MyTalks, TalkSheet } from './talk'
import { MyTalks } from './talk'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
export function SheetProvider({ children }: { children: ReactNode }) {
@@ -169,7 +172,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{shown.type === 'share' && <ShareSheet share={shown.share} />}
{shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{shown.type === 'comments' && <CommentsSheet to={shown} draft={shown.draft} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
{shown.type === 'me' && <MeSheet onDone={onClose} />}
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
@@ -180,7 +183,6 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{shown.type === 'tarot' && <TarotSheet />}
{shown.type === 'level' && <LevelSheet />}
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
{shown.type === 'gameHelp' && <GameHelpSheet />}
</div>
)}
@@ -725,7 +727,7 @@ const REPORT_REASONS = [
const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
@@ -748,7 +750,7 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
})
const go = (next: typeof step) => {
setFailed(false)
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } })
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } })
setStep(next)
}
const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50'
@@ -798,7 +800,7 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
)
}
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { region } = useRegion()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
@@ -831,7 +833,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
}
revert()
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) })
else setLikeFailed(true)
},
onError: () => {
@@ -850,7 +852,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
{
onSuccess: async (res) => {
if (!res.result?.success) return setRemoveFailed(true)
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } })
const key = commentListKey(to)
await queryClient.cancelQueries({ queryKey: key })
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
@@ -883,7 +885,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
</>
)}
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
</small>
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
@@ -893,16 +895,36 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
)
}
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
/** 댓글 목록 캐시 키: 지우기·신고 뒤 다시 받을 때 쓴다 */
function commentListKey(to: CommentTarget) {
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } })
}
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
const { region } = useRegion()
const { me } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
initialPageParam: { path: { post_id: postId } },
const talkId = 'talkId' in to ? to.talkId : undefined
const postId = 'postId' in to ? to.postId : undefined
// 둘 중 하나만 받는다
const postList = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
initialPageParam: { path: { post_id: postId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: postId != null,
})
const add = useMutation(addCommentMutation())
const talkList = useInfiniteQuery({
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
initialPageParam: { path: { talk_id: talkId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: talkId != null,
})
const list = talkId != null ? talkList : postList
const addPost = useMutation(addCommentMutation())
const addTalk = useMutation(addTalkCommentMutation())
const add = { isPending: addPost.isPending || addTalk.isPending }
const agree = useMutation(agreeTermsMutation())
const [addFailed, setAddFailed] = useState(false)
const [askTerms, setAskTerms] = useState(false)
@@ -921,26 +943,31 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const body = text.trim()
if (!body || add.isPending) return
setAddFailed(false)
add.mutate(
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
setAddFailed(!res.result?.success)
if (!res.result?.success) return
const handlers = {
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
setAddFailed(!res.result?.success)
if (!res.result?.success) return
setText('')
queryClient.invalidateQueries({ queryKey: commentListKey(to) })
if (talkId != null) {
track('talk_comment', { talk_id: talkId })
queryClient.invalidateQueries({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks' })
} else if (postId != null) {
track('comment', { post_id: postId })
setText('')
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
},
onError: () => setAddFailed(true),
}
},
)
onError: () => setAddFailed(true),
}
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers)
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers)
}
// 로그인했으면 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
const submit = (e: FormEvent) => {
e.preventDefault()
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } })
if (me && !me.terms_agreed) return setAskTerms(true)
send()
}
@@ -967,7 +994,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{comments.length ? (
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />)}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />)}
{list.hasNextPage && (
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
@@ -1014,7 +1041,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}
</p>
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
<button type="submit" disabled={add.isPending || !text.trim()} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
</button>
+2 -2
View File
@@ -5,7 +5,7 @@ import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
import { FeedComposer, TalkCard } from './talk'
import { TOPICS, useMyTalks, useTopicTalks } from './talkState'
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from './talkState'
import { Rail, Sec } from './ui'
type Tab = TalkTopic | 'all' | 'mine'
@@ -34,7 +34,7 @@ export function TalkPage() {
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab)
const mineList = useMyTalks(tab === 'mine' && loggedIn)
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...TOPICS, ['mine', '내 글']]
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']]
const go = (k: Tab) => setParams(k === 'mine' ? { mine: '1' } : k === 'all' ? {} : { topic: String(k) }, { replace: true })
return (
+100 -96
View File
@@ -6,9 +6,7 @@ import {
PostType,
RainType,
Sky,
TalkTopic,
type BandArticle,
type BandEvent,
type Hero as HeroData,
type PostReaction,
type ResWeatherToday,
@@ -18,7 +16,6 @@ import {
import { cx } from '../lib/utils'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { useAuth } from './authContext'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
@@ -28,9 +25,10 @@ import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
import { ShortsRail } from './Shorts'
import { FeedComposer, NearTalks, TalkGroup } from './talk'
import { topicName, useTalkGroups, useTodayMyTalks } from './talkState'
import { useRegion } from './regionContext'
import { FeedComposer, TalkPost } from './talk'
import { useTopicTalks } from './talkState'
import { TomorrowFeed } from './TomorrowFeed'
import { useLandingAbout, useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
@@ -537,25 +535,6 @@ function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: stri
)
}
function EventsBand({ events }: { events: BandEvent[] }) {
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
<Thumb image={e.image} icon={e.icon} credit={e.image_credit} className={cx('h-[116px]', `b-bg-${cardBg(e.icon, i)}`)} iconClassName="w-[76px]">
<span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-(--orange)')}>{e.status_label}</span>
</Thumb>
<span className="block px-3 pt-2.5 pb-3">
<b className="block font-jua text-[16.5px] leading-snug font-normal">{e.name}</b>
</span>
</Link>
))}
</Rail>
</Band>
)
}
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
@@ -575,8 +554,34 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
)
}
// 사람 글은 포스트 두 장마다 한 장씩 최신순으로 끼운다
const TALK_EVERY = 2
/** 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보일 때 한 번 GA 로 보낸다 */
function Seen({ item, position, children }: { item: 'talk' | 'event'; position: number; children: ReactNode }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const el = ref.current
if (!el) return
const io = new IntersectionObserver(
([e]) => {
if (!e.isIntersecting) return
track('feed_item_view', { item_type: item, position })
io.disconnect()
},
{ threshold: 0.5 },
)
io.observe(el)
return () => io.disconnect()
}, [item, position])
return <div ref={ref}>{children}</div>
}
export function TodayPage() {
const { region } = useRegion()
const about = useLandingAbout()
// 내일 날씨 페이지는 히어로 아래를 내일 것으로 (오늘 페이지와 본문이 거의 같아 구글이 둘 중 하나만 색인하던 것)
const ahead = useLocation().pathname.startsWith('/tomorrow/')
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
const { preview } = useSky()
@@ -588,20 +593,10 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 오늘 쓴 내 글은 글쓰기 칸 아래 '오늘 내 글'에 따로 있으니 빼고
const { loggedIn } = useAuth()
const mine = useTodayMyTalks(loggedIn)
const talkGroups = useTalkGroups()
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const group = (topic: number) => {
const talks = groupOf(topic)
return talks.length ? <TalkGroup key={`talk-${topic}`} title={topicName(topic)} topic={topic} talks={talks} /> : null
}
// 비·눈이 오거나 2시간 안에 올 때만 비·눈 묶음을 히어로 바로 아래로
const at = nowAt ? Date.parse(nowAt) : 0
const nowSlot = (today.data?.slots ?? []).filter((x) => x.temp_c != null).reduce<WeatherSlot | undefined>((a, b) => (!a || Math.abs(Date.parse(b.at) - at) < Math.abs(Date.parse(a.at) - at) ? b : a), undefined)
const raining = ['rain', 'snow', 'sleet'].includes(weatherOf(nowSlot)) || !!f?.hero?.will_rain_2h
const sunsetAt = posts.findIndex((p) => p.post_type === PostType.SUNSET)
const talks = useTopicTalks().talks
const talkAt = (i: number) => ((i + 1) % TALK_EVERY === 0 ? talks[(i + 1) / TALK_EVERY - 1] : undefined)
const talkFrom = Math.floor(posts.length / TALK_EVERY)
const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1]))
useEffect(() => {
window.scrollTo({ top: 0 })
@@ -618,70 +613,79 @@ export function TodayPage() {
if (g) open({ type: 'mix', shared: g })
}, [open])
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
]
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : [])].filter((tp) => groupOf(tp).length)
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
const spreadAt = new Map<number, ReactNode>()
let spreadN = 0
for (let i = 0; i < posts.length && spreadN < spreadTopics.length; i++) {
if (taken.has(i) || spreadAt.has(i - 1)) continue
spreadAt.set(i, group(spreadTopics[spreadN++]))
}
const spreadLeft = spreadTopics.slice(spreadN).map((tp) => group(tp))
// 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null]]
return (
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<section key={region.code} aria-label={ahead ? '내일' : '오늘'} aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<TodayIcons />
<ShortsRail />
<FeedComposer />
{mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
{raining && group(TalkTopic.RAIN)}
<div id={MY_GAK_ID} className="scroll-mt-16">
<MyGakRow />
</div>
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
{ahead ? (
<TomorrowFeed tomorrow={f?.hero?.tomorrow} load={load} />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
<>
<ShortsRail />
<FeedComposer />
<div id={MY_GAK_ID} className="scroll-mt-16">
<MyGakRow />
</div>
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
{load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
{posts.map((p, i) => {
const t = talkAt(i)
const ev = eventNo.get(p.post_id)
return (
<Fragment key={p.post_id}>
{ev ? (
<Seen item="event" position={ev}>
<PostCard post={p} />
</Seen>
) : (
<PostCard post={p} />
)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{t && (
<Seen item="talk" position={(i + 1) / TALK_EVERY}>
<TalkPost t={t} />
</Seen>
)}
</Fragment>
)
})}
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
{feed.isSuccess &&
talks.slice(talkFrom).map((t, n) => (
<Seen key={t.talk_id} item="talk" position={talkFrom + n + 1}>
<TalkPost t={t} />
</Seen>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</div>
</>
)}
{about && (
<div
data-nosnippet
className="mx-4 mt-6 mb-4 text-[13px] leading-relaxed text-(--ink3) [&_a]:underline [&_h1]:mb-1 [&_h1]:text-[15px] [&_h1]:font-bold [&_h1]:text-(--ink2) [&_h2]:mt-4 [&_h2]:mb-1 [&_h2]:text-[14px] [&_h2]:font-bold [&_h2]:text-(--ink2) [&_h3]:mt-2 [&_h3]:font-semibold [&_li]:inline [&_li]:mr-2 [&_p]:my-1 [&_ul]:m-0 [&_ul]:p-0"
dangerouslySetInnerHTML={{ __html: about }}
/>
)}
<NearTalks talks={groupOf(0)} loaded={talkGroups.loaded} />
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
{load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에, 단풍 이야기 묶음은 바로 아래 */}
{load !== 'loading' && posts.length > 0 && (
<>
<FoliageCard />
{group(TalkTopic.FOLIAGE)}
</>
)}
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === sunsetAt && group(TalkTopic.SKY)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{spreadAt.get(i)}
</Fragment>
))}
{/* 글이 모자라 끼울 자리가 없던 묶음은 맨 뒤에 */}
{feed.isSuccess && spreadLeft}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</div>
</section>
)
}
+88
View File
@@ -0,0 +1,88 @@
import { useQuery } from '@tanstack/react-query'
import { Link, useLocation } from 'react-router'
import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { HeroTomorrow, HoursSlide, TomorrowEvent } from '@nalssigak/shared/api/client'
import { type Load, MEDALS } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { PostCardSkel, PostFrame, SlideView } from './Post'
import { useRegion } from './regionContext'
import { Ic } from './ui'
const md = (d: string) => `${Number(d.slice(5, 7))}/${Number(d.slice(8, 10))}`
const days = (e: TomorrowEvent) => (e.start_date === e.end_date ? md(e.start_date) : `${md(e.start_date)}~${md(e.end_date)}`)
/** 내일 날씨 페이지(/tomorrow/...)의 히어로 아래. 오늘 피드 대신 내일 것만 둬서 오늘 페이지와 본문이 겹치지 않게 한다 */
export function TomorrowFeed({ tomorrow, load }: { tomorrow?: HeroTomorrow | null; load: Load }) {
const { region } = useRegion()
const { pathname } = useLocation()
const [sido] = region.name.split(' ')
const place = region.name.split(' ').at(-1)!
const w = useQuery(getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } })).data
const hours: HoursSlide | null =
w?.slots?.length && w.headline
? { kind: 'hours', eyebrow: '내일 하루 · 3시간마다', line: w.headline, hours: w.slots.map((s) => ({ label: s.label, icon: s.icon, temp_c: s.temp_c, tone: s.tone })) }
: null
const ranked = tomorrow?.ranked ?? []
const events = tomorrow?.events ?? []
return (
<div>
{ranked.length > 0 ? (
<PostFrame title={`내일의 각 · ${place}`} account="내일의 각" avatar="rabbit">
<div className="b-band-2 px-4 pt-3.5 pb-3">
<p className="m-0 font-jua text-[19px]">내일의 각 · {place} 하루 기준</p>
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
{ranked.map((g, i) => (
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[34px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
</li>
))}
</ol>
</div>
</PostFrame>
) : (
load === 'loading' && <PostCardSkel />
)}
{hours && (
<PostFrame title="내일 날씨" account="내일 날씨" avatar="sun">
<div className="relative flex aspect-[4/5] overflow-hidden">
<SlideView slide={hours} bg="sky" />
</div>
</PostFrame>
)}
{events.length > 0 && (
<PostFrame title={`내일 열리는 행사 · ${sido}`} account="주말·행사" avatar="concert" more={<Link to="/week">행사 더 보기 ›</Link>}>
<div className="b-band-3 px-4 pt-3.5 pb-3">
<p className="m-0 font-jua text-[19px]">내일 열리는 행사 · {sido}</p>
<ul className="m-0 mt-2 grid list-none gap-1.5 p-0">
{events.map((e) => (
<li key={e.event_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={e.icon} className="w-[32px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{e.name}</b>
<small className="block truncate text-xs font-semibold text-(--ink2)">
{e.place} · {days(e)}
</small>
</span>
</li>
))}
</ul>
</div>
</PostFrame>
)}
<Link
to={pathname.replace(/^\/tomorrow\//, '/today/')}
onClick={() => track('tomorrow_to_today', { region_name: region.name })}
className="mx-3 mt-4 mb-2 block rounded-full bg-white py-3 text-center font-jua text-[16px] shadow-[inset_0_-4px_0_var(--shade)]"
>
오늘 {place} 소식 보기 ›
</Link>
</div>
)
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more