fix: 로그인 창에 남은 '또는 아이디로' 구분선과 '아이디로 로그인해 주세요' 안내 빼기, 빈 오류 칸 여백 줄이기
This commit is contained in:
1 parent
cc06d1fa6d
commit
aef8b4a022
10 files changed
+86
-21
No files matched your search
@@ -23,3 +23,19 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
|
||||
async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"tomorrow/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
|
||||
async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
@@ -21,7 +21,7 @@ from services.feed_service import FeedService
|
||||
|
||||
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
|
||||
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
|
||||
|
||||
@@ -61,15 +61,27 @@ def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[da
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
line = today_line(feed, rows, sunset_at)
|
||||
def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""내일 페이지 한 줄: 내일 하루 예보와 해 지는 시각."""
|
||||
parts = [day_summary(rows)] if rows else []
|
||||
if parts and sunset_at:
|
||||
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _put(template: str, line: str, extra: str = "") -> str:
|
||||
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
|
||||
if not line:
|
||||
return template
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||
return _put(template, today_line(feed, rows, sunset_at), ranks)
|
||||
|
||||
|
||||
class SeoService:
|
||||
@@ -98,9 +110,12 @@ class SeoService:
|
||||
LOG.error(f"[seo] feed {code}: {err}")
|
||||
return ErrorType.SUCCESS, template
|
||||
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||
today = now_kst().date()
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(today)
|
||||
ahead = path.startswith("tomorrow/")
|
||||
day = now_kst().date() + timedelta(days=1 if ahead else 0)
|
||||
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(day)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
if ahead:
|
||||
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
@@ -7,7 +7,7 @@ from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line, tomorrow_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
@@ -76,3 +76,25 @@ async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
|
||||
assert page.status_code == 200 and "지금 20°" in page.text
|
||||
|
||||
|
||||
def test_tomorrow_line_has_day_and_sunset():
|
||||
line = tomorrow_line([_hour(12, 19.5, prob=10)], datetime(2026, 10, 15, 17, 51, tzinfo=KST))
|
||||
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 해 지는 시각 오후 5시 51분."
|
||||
assert tomorrow_line([], datetime(2026, 10, 15, 17, 51, tzinfo=KST)) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
|
||||
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
|
||||
|
||||
async def template(self, path):
|
||||
return tmpl if path == "tomorrow/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/tomorrow/gyeonggi/seongnam/bundang")
|
||||
missing = await client.get("/v1/seo/tomorrow/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
|
||||
assert "지금 " not in page.text and "<ol>" not in page.text
|
||||
assert missing.status_code == 404
|
||||
+2
-2
@@ -37,8 +37,8 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||
location ~ ^/today/[a-z]+/[a-z]+(/[a-z]+)?$ {
|
||||
# 지역 검색 페이지: 백엔드가 정적 HTML(today·tomorrow/…/….html)에 오늘·내일 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||
location ~ ^/(today|tomorrow)/[a-z]+/[a-z]+(/[a-z]+)?$ {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api/v1/seo$uri;
|
||||
|
||||
@@ -13,6 +13,7 @@ export default function App() {
|
||||
<Route element={<BLayout />}>
|
||||
<Route index element={<TodayPage />} />
|
||||
<Route path="today/:sido/:place" element={<TodayPage />} />
|
||||
<Route path="tomorrow/:sido/:place" element={<TodayPage />} />
|
||||
<Route path="gak" element={<GakPage />} />
|
||||
<Route path="sky" element={<SkyPage />} />
|
||||
<Route path="week" element={<WeekPage />} />
|
||||
|
||||
@@ -232,7 +232,7 @@ function Shell() {
|
||||
{TABS.map((t) =>
|
||||
t.key === 'today' ? (
|
||||
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') || pathname.startsWith('/tomorrow/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
|
||||
<TabIcon name={t.key} className="size-[30px]" />
|
||||
</span>
|
||||
|
||||
@@ -831,7 +831,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
}}
|
||||
onFail={fail}
|
||||
/>
|
||||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
<p className="m-0 text-center text-[13px] font-bold text-(--heart) empty:hidden" aria-live="polite">
|
||||
{error}
|
||||
</p>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
|
||||
@@ -76,8 +76,7 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.</p>}
|
||||
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -10,9 +10,9 @@ const KEY = 'nalssigak.b.region'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
|
||||
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
|
||||
function pageOf(pathname: string): RegionPage | undefined {
|
||||
const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
|
||||
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
|
||||
return path ? regionPages.find((p) => p.path === path) : undefined
|
||||
}
|
||||
|
||||
@@ -45,9 +45,11 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate()
|
||||
const page = pageOf(pathname)
|
||||
const pageRef = useRef(page)
|
||||
const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today')
|
||||
useEffect(() => {
|
||||
pageRef.current = page
|
||||
}, [page])
|
||||
dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today'
|
||||
}, [page, pathname])
|
||||
const [stored] = useState(readStored)
|
||||
const [landing] = useState(page)
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
@@ -61,7 +63,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
const next = ownPage(r.code)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||
|
||||
+11
-1
@@ -83,7 +83,17 @@ for (const r of regionPages) {
|
||||
keywords,
|
||||
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`,
|
||||
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
|
||||
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p><h2>${r.name} 날씨 자주 묻는 질문</h2>${faqList(faq)}<p><a href="/faq/${sido}">${r.name.split(' ')[0]} 지역별 날씨 자주 묻는 질문</a> · <a href="/faq">날씨별로 뭐 하면 좋을까?</a></p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
|
||||
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p><p><a href="/tomorrow/${r.path}">${r.name} 내일 날씨 보기</a></p><h2>${r.name} 날씨 자주 묻는 질문</h2>${faqList(faq)}<p><a href="/faq/${sido}">${r.name.split(' ')[0]} 지역별 날씨 자주 묻는 질문</a> · <a href="/faq">날씨별로 뭐 하면 좋을까?</a></p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
|
||||
})
|
||||
// 내일 날씨는 따로 많이 찾는다: 같은 지역의 내일 페이지 (서버가 내일 예보를 채운다)
|
||||
const tomorrowKeywords = [...new Set([`${bare} 내일 날씨`, `${head} 내일 날씨`, `${r.name} 내일 날씨`, ...guNames.flatMap((g) => [`${g} 내일 날씨`, `${bareName(g)} 내일 날씨`]), '날씨각'])].join(', ')
|
||||
PAGES.push({
|
||||
path: `tomorrow/${r.path}`,
|
||||
code: r.main,
|
||||
keywords: tomorrowKeywords,
|
||||
title: `${head} 내일 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`,
|
||||
description: `내일 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 미리 알려 드려요.`,
|
||||
body: `<h1>${r.name} 내일 날씨, 뭐 할까?</h1><p>${bare} 내일 날씨, 내일 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보로 내일 하기 좋은 일을 아침, 낮, 저녁, 밤마다 점수로 미리 알려 드려요.</p><p>내일 최저·최고 기온과 강수확률, 해 지는 시각을 하루 8번 새 예보로 바꿔 드려요.</p><p><a href="/today/${r.path}">${r.name} 오늘 날씨 보기</a></p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 내일 날씨</h2><ul>${near.map((o) => `<li><a href="/tomorrow/${o.path}">${o.name} 내일 날씨</a></li>`).join('')}</ul>` : ''}`,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user