Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
378ad55b5b | ||
|
|
14b6e95f9d | ||
|
|
87343c791b | ||
|
|
e5153eb66c | ||
|
|
fad20e8958 | ||
|
|
8219d3f45e | ||
|
|
18a287451e |
No files matched your search
@@ -13,6 +13,7 @@
|
||||
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
||||
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
||||
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
||||
| `activity` | 수집 시작·채널 실패·완료 · 사진 분석 · 첫 발행/재발행/빌드/되돌리기 시작·끝(`services/activity_feed.py`) | 없음(매번 보낸다) |
|
||||
|
||||
★ **게이트 반려는 알리지 않는다.** 사장님이 fact 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
||||
운영자가 손댈 일이 아니다 — `build_service._fail(reason, gate=None)` 일 때만 `build_failed`.
|
||||
|
||||
+6
-1
@@ -66,7 +66,12 @@ HTML 안에 있고 보이는 묶음만 바뀐다. 검색엔진은 네 묶음을
|
||||
거의 없는 집을 위한 것이라, 첫 화면과 객실 카드를 그림으로 채운다.
|
||||
|
||||
업종마다 쓸 수 있는 템플릿과 기본 템플릿은 같은 파일의 `industries`에 적는다. 숙박은 레트로가
|
||||
기본이고, 병원은 심플과 매거진만 쓸 수 있다.
|
||||
기본이다. 새 템플릿 8종(라운드 ~ 솔숲)은 네 업종 모두 쓸 수 있다. 병원은 그 밖에 심플과
|
||||
매거진만 쓴다(고택·레트로는 숙박·음식점 느낌이 강해 뺐다).
|
||||
|
||||
★ 새 템플릿은 숙박 기준으로 만들었다. 숙박이 아니면 객실 자리가 메뉴·시술로 바뀌고
|
||||
(`kit/unitWord.ts`, `UNIT_SPEC`), 객실별 '예약 요청' 버튼은 숨긴다 — 예약 시트가 숙박에만
|
||||
있어서 누르면 아무 일도 안 일어났다.
|
||||
|
||||
### 뼈대(레이아웃)는 필요한 것만 바꾼다
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import os
|
||||
|
||||
os.environ.setdefault("APP_ENV", "test")
|
||||
os.environ.setdefault("THUMBNAIL_CAPTURE", "0")
|
||||
|
||||
import uuid
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ class ISiteCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def list_all_sites(self, cdb: AsyncSession, skip, limit) -> Tuple[ErrorType, list, int]:
|
||||
async def list_all_sites(self, cdb: AsyncSession, skip, limit, search=None, category=None) -> Tuple[ErrorType, list, int]:
|
||||
"""전 계정 사이트 목록(회사 스코프 없음) — 내부 운영(DEVELOPER) 전용."""
|
||||
pass
|
||||
|
||||
@@ -145,12 +145,23 @@ class SiteCRUD(ISiteCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, [], 0
|
||||
|
||||
async def list_all_sites(self, cdb: AsyncSession, skip: int, limit: int) -> Tuple[ErrorType, list, int]:
|
||||
async def list_all_sites(
|
||||
self, cdb: AsyncSession, skip: int, limit: int, search: str | None = None, category: int | None = None
|
||||
) -> Tuple[ErrorType, list, int]:
|
||||
"""list_owner_sites 와 같은 조인이되 owner_user_id 필터가 없다 — 소유자 계정 정보를 같이 얹는다."""
|
||||
try:
|
||||
where = places.deleted == False # noqa: E712
|
||||
if category is not None:
|
||||
where = and_(where, places.category == category)
|
||||
if search and search.strip():
|
||||
like = f"%{search.strip()}%"
|
||||
where = and_(where, places.name.ilike(like) | users.email.ilike(like)
|
||||
| users.name.ilike(like) | users.id.ilike(like))
|
||||
|
||||
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(places).where(where))
|
||||
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(
|
||||
cdb,
|
||||
select(func.count()).select_from(places).join(users, users.user_id == places.owner_user_id).where(where),
|
||||
)
|
||||
if cnt_err != ErrorType.SUCCESS:
|
||||
return cnt_err, [], 0
|
||||
total = int(cnt_rows[0] or 0) if cnt_rows else 0
|
||||
|
||||
@@ -10,8 +10,14 @@ router = APIRouter(prefix="/v1/ops", tags=["Ops"])
|
||||
|
||||
|
||||
@router.get(path="/sites", response_model=Res_OpsSites, summary="전 계정 사이트 목록(개발자 전용)")
|
||||
async def list_sites(service: OpsService = Depends(), pg: PageParams = Depends(), _user=Depends(RequireDeveloper)):
|
||||
return RemoveNoneResponse(await service.list_sites(pg))
|
||||
async def list_sites(
|
||||
service: OpsService = Depends(),
|
||||
pg: PageParams = Depends(),
|
||||
search: str | None = Query(None, description="상호·소유자 이메일·이름·로그인 아이디 부분 일치"),
|
||||
category: int | None = Query(None, description="PlaceCategory"),
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.list_sites(pg, search, category))
|
||||
|
||||
|
||||
@router.get(path="/users", response_model=Res_OpsUsers, summary="전 계정 목록(개발자 전용)")
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Union
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy import select
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
import bcrypt
|
||||
from jose import jwt, JWTError, ExpiredSignatureError
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places
|
||||
from common.enums import (
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
EXCEPTION_ACCESS_TOKEN_EXPIRED,
|
||||
EXCEPTION_FORBIDDEN,
|
||||
EXCEPTION_INVALID_CLIENT_ACCESS,
|
||||
@@ -96,8 +102,40 @@ def DecodeRefreshToken(jwt_token: str) -> UserInfo:
|
||||
|
||||
|
||||
# Depends 용 토큰 검증기
|
||||
async def IsValidAccessToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo:
|
||||
return DecodeAccessToken(credentials.credentials)
|
||||
async def _place_owner(place_id: str) -> str | None:
|
||||
try:
|
||||
pid = uuid.UUID(place_id)
|
||||
except ValueError:
|
||||
return None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(
|
||||
s, select(places.owner_user_id).where(places.place_id == pid, places.deleted == False) # noqa: E712
|
||||
),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or not rows:
|
||||
return None
|
||||
return str(rows[0])
|
||||
|
||||
|
||||
async def _act_as_place_owner(request: Request, user_info: UserInfo) -> UserInfo:
|
||||
if (user_info.role or 0) < UserRole.DEVELOPER.value:
|
||||
return user_info
|
||||
place_id = request.path_params.get("place_id") or request.query_params.get("place_id")
|
||||
if not place_id:
|
||||
return user_info
|
||||
owner = await _place_owner(str(place_id))
|
||||
if owner is None or owner == str(user_info.user_id):
|
||||
return user_info
|
||||
LOG.i(f"[admin-access] {user_info.id} → place={place_id} owner={owner} {request.method} {request.url.path}")
|
||||
return UserInfo(user_id=owner, id=user_info.id, role=user_info.role, token_version=user_info.token_version)
|
||||
|
||||
|
||||
async def IsValidAccessToken(
|
||||
request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)
|
||||
) -> UserInfo:
|
||||
return await _act_as_place_owner(request, DecodeAccessToken(credentials.credentials))
|
||||
|
||||
|
||||
async def IsValidRefreshToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""크롤링 · 사진 분석 · 빌드 진행 이벤트를 Teams 로 보낸다."""
|
||||
from common.enums import LinkChannel, PlaceCategory
|
||||
from services import alert_service
|
||||
|
||||
KIND = "activity"
|
||||
|
||||
_CHANNEL_NAMES = {
|
||||
LinkChannel.YANOLJA.value: "야놀자",
|
||||
LinkChannel.GOODCHOICE.value: "여기어때",
|
||||
LinkChannel.NAVER_PLACE.value: "네이버 플레이스",
|
||||
LinkChannel.INSTAGRAM.value: "인스타그램",
|
||||
LinkChannel.OFFICIAL_SITE.value: "홈페이지",
|
||||
LinkChannel.BLOG.value: "블로그",
|
||||
LinkChannel.NAVER_BOOKING.value: "네이버 예약",
|
||||
LinkChannel.ETC.value: "기타",
|
||||
}
|
||||
|
||||
_CATEGORY_NAMES = {
|
||||
PlaceCategory.LODGING.value: "숙박",
|
||||
PlaceCategory.CAFE.value: "카페",
|
||||
PlaceCategory.RESTAURANT.value: "음식점",
|
||||
PlaceCategory.CLINIC.value: "피부과·성형외과",
|
||||
}
|
||||
|
||||
|
||||
def channel_name(code) -> str:
|
||||
return _CHANNEL_NAMES.get(code, f"채널{code}")
|
||||
|
||||
|
||||
def category_name(code) -> str:
|
||||
return _CATEGORY_NAMES.get(code, f"업종{code}")
|
||||
|
||||
|
||||
def place_label(place) -> str:
|
||||
return f"{place.name}({category_name(place.category)})"
|
||||
|
||||
|
||||
async def post(title: str, lines: list[str]) -> None:
|
||||
await alert_service.send_alert(KIND, title, "\n\n".join(line for line in lines if line))
|
||||
@@ -1,5 +1,6 @@
|
||||
"""정적 빌드 + 발행 — BUILD 잡이 하는 일."""
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -25,6 +26,7 @@ from crud.site_crud import SiteCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud.post_crud import PostCRUD
|
||||
from services import (
|
||||
activity_feed,
|
||||
alert_service,
|
||||
azure_static,
|
||||
indexnow,
|
||||
@@ -118,6 +120,45 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
|
||||
|
||||
async def run_build(job: dict) -> dict:
|
||||
"""BUILD 잡 핸들러."""
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = await _run_build(job)
|
||||
except Exception as ex:
|
||||
await activity_feed.post(
|
||||
"❌ 빌드 실패",
|
||||
[f"place_id={job['payload'].get('place_id')}", f"{type(ex).__name__}: {ex}",
|
||||
f"{time.monotonic() - started:.0f}초"],
|
||||
)
|
||||
raise
|
||||
await post_build_summary(result, time.monotonic() - started)
|
||||
return result
|
||||
|
||||
|
||||
async def post_build_summary(result: dict, elapsed: float) -> None:
|
||||
version = f"v{result.get('version')}"
|
||||
mode = result.get("mode") or "빌드"
|
||||
lines = [f"{result.get('label') or result.get('place_id')} {version}"]
|
||||
if result.get("build_status") == "BUILT":
|
||||
title = f"✅ {mode} 완료"
|
||||
if result.get("url"):
|
||||
lines.append(result["url"])
|
||||
elif result.get("gate", {}).get("passed") is False:
|
||||
title = f"🚫 {mode} 반려(게이트)"
|
||||
lines.append(str(result.get("error") or ""))
|
||||
else:
|
||||
title = f"❌ {mode} 실패"
|
||||
lines.append(str(result.get("error") or ""))
|
||||
media = result.get("render_media")
|
||||
if media:
|
||||
lines.append(
|
||||
f"굽기 — 사진 {media.get('total', 0)}장: 새로 받음 {media.get('fetched', 0)} · "
|
||||
f"기존 {media.get('cached', 0)} · 실패 {media.get('failed', 0)}"
|
||||
)
|
||||
lines.append(f"{elapsed:.0f}초")
|
||||
await activity_feed.post(title, lines)
|
||||
|
||||
|
||||
async def _run_build(job: dict) -> dict:
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
@@ -132,6 +173,7 @@ async def run_build(job: dict) -> dict:
|
||||
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
|
||||
site = await ensure_site(place_id)
|
||||
mode = ("재발행" if site.published_at is not None else "첫 발행") if want_publish else "빌드만"
|
||||
|
||||
# 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라 이때 받은 값이 실린다.
|
||||
try:
|
||||
@@ -198,7 +240,12 @@ async def run_build(job: dict) -> dict:
|
||||
raise BuildAborted(f"버전 생성 실패: {add_err.name}")
|
||||
|
||||
result = {"place_id": place_id, "site_id": str(site.site_id), "version": version_no,
|
||||
"site_version_id": str(version.site_version_id)}
|
||||
"site_version_id": str(version.site_version_id), "label": activity_feed.place_label(place),
|
||||
"mode": mode}
|
||||
await activity_feed.post(
|
||||
f"🏗 {mode} 시작",
|
||||
[f"{result['label']} v{version_no}", f"템플릿 {site.template_id or '기본'}"],
|
||||
)
|
||||
# 잡 결과에 남긴다 — "노래가 왜 없나" 를 잡 하나만 열어 보면 알 수 있어야 한다.
|
||||
if song_result is not None:
|
||||
result["song"] = song_result
|
||||
@@ -267,6 +314,8 @@ async def run_build(job: dict) -> dict:
|
||||
# 발행하지 않는다.
|
||||
return await _fail(str(ex))
|
||||
|
||||
if report.get("media"):
|
||||
result["render_media"] = report["media"]
|
||||
mismatches = list(report.get("mismatches") or [])
|
||||
unique_count_raw = report.get("uniqueContentCount")
|
||||
unique_count = unique_count_raw or 0
|
||||
@@ -366,6 +415,7 @@ async def run_build(job: dict) -> dict:
|
||||
if thumbnail_url:
|
||||
site.thumbnail_url = thumbnail_url
|
||||
result["published"] = True
|
||||
result["url"] = site_payload.publish_url(place, site)
|
||||
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
||||
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
||||
else:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""채널 발견 → 확정 URL 크롤링 → fact·사진 후보 저장."""
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import collect_diagnostics
|
||||
@@ -12,6 +13,7 @@ from common.utils.gtime import GTime
|
||||
from crud.fact_crud import FactCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from common.category_schema import get_schema
|
||||
from services import activity_feed
|
||||
from services.collector import AdapterDisabled, AdapterNotFound, REGISTRY
|
||||
from services.collector import yanolja_adapter
|
||||
from services.external import naver_place_lookup, perplexity, tour_lookup
|
||||
@@ -456,14 +458,47 @@ async def store_media(place_id: str, sources: list, unit_map: dict) -> dict:
|
||||
# 오케스트레이션
|
||||
async def run_collect(job: dict) -> dict:
|
||||
"""COLLECT 잡 핸들러."""
|
||||
started = time.monotonic()
|
||||
with collect_diagnostics.collecting():
|
||||
result = await _run_collect(job)
|
||||
try:
|
||||
result = await _run_collect(job)
|
||||
except Exception as ex:
|
||||
await activity_feed.post(
|
||||
"❌ 수집 실패",
|
||||
[f"place_id={job['payload'].get('place_id')}", f"{type(ex).__name__}: {ex}",
|
||||
f"{time.monotonic() - started:.0f}초"],
|
||||
)
|
||||
raise
|
||||
issues = collect_diagnostics.snapshot()
|
||||
if issues:
|
||||
result["issues"] = issues
|
||||
await _post_collect_summary(result, issues, time.monotonic() - started)
|
||||
return result
|
||||
|
||||
|
||||
async def _post_collect_summary(result: dict, issues: list[dict], elapsed: float) -> None:
|
||||
lines = [result.get("label") or f"place_id={result.get('place_id')}"]
|
||||
if result.get("note"):
|
||||
lines.append(result["note"])
|
||||
for row in result.get("channels") or []:
|
||||
lines.append(row)
|
||||
facts = result.get("facts")
|
||||
if facts:
|
||||
reasons = ", ".join(f"{k} {v}" for k, v in facts["by_reason"].items())
|
||||
lines.append(f"fact 저장 {facts['stored']} · 반려 {facts['rejected']}" + (f" ({reasons})" if reasons else ""))
|
||||
media = result.get("media")
|
||||
if media:
|
||||
lines.append(f"사진 {media['stored']}장 (중복 {media['skipped_duplicate']})")
|
||||
cov = result.get("coverage")
|
||||
if cov and cov["missing"]:
|
||||
lines.append(f"필수 항목 {cov['covered']}/{cov['total']} — 누락 {', '.join(cov['missing'])}")
|
||||
other = [i for i in issues if i["stage"] != "fetch"]
|
||||
for issue in other:
|
||||
lines.append(f"⚠️ {issue['stage']} 실패: {issue['error_type']}: {issue['message'][:200]}")
|
||||
lines.append(f"{elapsed:.0f}초")
|
||||
await activity_feed.post("✅ 수집 완료", lines)
|
||||
|
||||
|
||||
async def _run_collect(job: dict) -> dict:
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
@@ -480,7 +515,7 @@ async def _run_collect(job: dict) -> dict:
|
||||
if place.verified_at is None:
|
||||
raise CollectAborted("동일 업소 검증(verify) 전에는 수집하지 않는다 — 남의 가게가 섞인다")
|
||||
|
||||
result: dict = {"place_id": place_id}
|
||||
result: dict = {"place_id": place_id, "label": activity_feed.place_label(place)}
|
||||
result["discover"] = await discover_links(
|
||||
place,
|
||||
place_id,
|
||||
@@ -493,6 +528,12 @@ async def _run_collect(job: dict) -> dict:
|
||||
link.channel == LinkChannel.NAVER_PLACE.value for link in targets
|
||||
)
|
||||
|
||||
await activity_feed.post(
|
||||
"🔎 수집 시작",
|
||||
[result["label"], f"place_id={place_id}",
|
||||
f"크롤링 대상 {len(targets)}건: " + (", ".join(activity_feed.channel_name(l.channel) for l in targets) or "없음")],
|
||||
)
|
||||
|
||||
if not targets:
|
||||
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
||||
@@ -521,6 +562,8 @@ async def _run_collect(job: dict) -> dict:
|
||||
facts_stat = {"stored": 0, "refreshed": 0, "candidate": 0, "rejected": 0, "by_reason": {}}
|
||||
media_stat = {"stored": 0, "skipped_duplicate": 0}
|
||||
unit_total = 0
|
||||
channel_rows: list[str] = []
|
||||
result["channels"] = channel_rows
|
||||
|
||||
for index, link in enumerate(targets):
|
||||
if index > 0:
|
||||
@@ -530,11 +573,23 @@ async def _run_collect(job: dict) -> dict:
|
||||
fetch_stat["stopped_early"] = True
|
||||
LOG.i(f"[collect] 필수 항목 {cov['covered']}/{cov['total']} 확보 — "
|
||||
f"남은 링크 {fetch_stat['skipped_enough']}건 크롤링 생략")
|
||||
channel_rows.append(f"필수 항목 확보 — 남은 {fetch_stat['skipped_enough']}건 생략")
|
||||
break
|
||||
|
||||
name = activity_feed.channel_name(link.channel)
|
||||
fetch_started = time.monotonic()
|
||||
issues_before = len(collect_diagnostics.snapshot())
|
||||
source, outcome = await fetch_one(link, PlaceCategory(place.category))
|
||||
fetch_stat[outcome] += 1
|
||||
if source is None:
|
||||
fresh = collect_diagnostics.snapshot()[issues_before:]
|
||||
reason = f"{fresh[-1]['error_type']}: {fresh[-1]['message'][:300]}" if fresh else outcome
|
||||
channel_rows.append(f"❌ {name} — {reason}")
|
||||
if outcome == "failed":
|
||||
await activity_feed.post(
|
||||
"⚠️ 채널 크롤링 실패",
|
||||
[result["label"], f"{name} {link.url}", reason],
|
||||
)
|
||||
continue
|
||||
|
||||
# 수집 원문을 링크에 남긴다 — fact 가 아니라 '생성 근거' 자리다.
|
||||
@@ -558,6 +613,9 @@ async def _run_collect(job: dict) -> dict:
|
||||
facts_stat["by_reason"][reason] = facts_stat["by_reason"].get(reason, 0) + n
|
||||
media_stat["stored"] += m["stored"]
|
||||
media_stat["skipped_duplicate"] += m["skipped_duplicate"]
|
||||
channel_rows.append(
|
||||
f"✓ {name} — fact {f['stored']} · 사진 {m['stored']} · {time.monotonic() - fetch_started:.1f}초"
|
||||
)
|
||||
|
||||
result["fetch"] = fetch_stat
|
||||
result["units"] = unit_total
|
||||
|
||||
@@ -16,11 +16,11 @@ class OpsService:
|
||||
self.site_crud = site_crud
|
||||
self.user_crud = user_crud
|
||||
|
||||
async def list_sites(self, pg: PageParams) -> Res_OpsSites:
|
||||
async def list_sites(self, pg: PageParams, search: str | None = None, category: int | None = None) -> Res_OpsSites:
|
||||
res = Res_OpsSites(page=pg.page, size=pg.size)
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.site_crud.list_all_sites(s, pg.skip, pg.size),
|
||||
lambda s: self.site_crud.list_all_sites(s, pg.skip, pg.size, search, category),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환"""
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
@@ -17,8 +18,8 @@ from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud.site_crud import SiteCRUD
|
||||
from services import alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
||||
from services.build_service import ensure_site, load_channel_links
|
||||
from services import activity_feed, alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
||||
from services.build_service import post_build_summary, ensure_site, load_channel_links
|
||||
|
||||
_site_crud = SiteCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
@@ -45,6 +46,25 @@ async def _log(site_id, version_id, result: PublishResult, gate=None, actor=None
|
||||
|
||||
async def run_rollback(job: dict) -> dict:
|
||||
"""ROLLBACK 잡 핸들러."""
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = await _run_rollback(job)
|
||||
except Exception as ex:
|
||||
await activity_feed.post(
|
||||
"❌ 되돌리기 실패",
|
||||
[f"place_id={job['payload'].get('place_id')} → v{job['payload'].get('target_version')}",
|
||||
f"{type(ex).__name__}: {ex}", f"{time.monotonic() - started:.0f}초"],
|
||||
)
|
||||
raise
|
||||
await post_build_summary(
|
||||
{**result, "version": result.get("target_version"), "mode": "되돌리기",
|
||||
"build_status": "BUILT" if result.get("rolled_back") else "FAILED"},
|
||||
time.monotonic() - started,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def _run_rollback(job: dict) -> dict:
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
@@ -76,7 +96,9 @@ async def run_rollback(job: dict) -> dict:
|
||||
result = {
|
||||
"place_id": place_id, "site_id": str(site.site_id),
|
||||
"target_version": target_version, "site_version_id": str(version.site_version_id),
|
||||
"label": activity_feed.place_label(place),
|
||||
}
|
||||
await activity_feed.post("🏗 되돌리기 시작", [f"{result['label']} → v{target_version}"])
|
||||
|
||||
async def _fail(reason: str, gate: publish_gate.GateResult | None = None):
|
||||
await _log(site.site_id, version.site_version_id, PublishResult.REJECTED if gate else PublishResult.FAILED,
|
||||
@@ -107,6 +129,8 @@ async def run_rollback(job: dict) -> dict:
|
||||
except render_service.RenderFailed as ex:
|
||||
return await _fail(str(ex))
|
||||
|
||||
if report.get("media"):
|
||||
result["render_media"] = report["media"]
|
||||
mismatches = list(report.get("mismatches") or [])
|
||||
unique_count_raw = report.get("uniqueContentCount")
|
||||
|
||||
@@ -141,5 +165,6 @@ async def run_rollback(job: dict) -> dict:
|
||||
await alert_service.resolve_alert(f"build_failed:{place_id}", f"롤백 성공 — {place_id} → v{target_version}")
|
||||
|
||||
result["rolled_back"] = True
|
||||
result["url"] = site_payload.publish_url(place, site)
|
||||
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
||||
return result
|
||||
@@ -30,6 +30,10 @@ MAX_BYTES = 5 * 1024 * 1024
|
||||
# 썸네일은 재발행마다 바뀔 수 있고 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
|
||||
CACHE_CONTROL = "public, max-age=60, must-revalidate"
|
||||
|
||||
CAPTURE_ENV = "THUMBNAIL_CAPTURE"
|
||||
CAPTURE_VIEWPORT = {"width": 1280, "height": 800}
|
||||
CAPTURE_TIMEOUT_MS = 30_000
|
||||
|
||||
|
||||
# ── 썸네일 전용 저장소 ────────────────────────────────────────────────────────
|
||||
_BASE_ENV = "THUMBNAIL_BLOB_BASE_URL" # https://<계정>.blob.core.windows.net/<컨테이너>
|
||||
@@ -121,6 +125,30 @@ async def _fetch(url: str) -> tuple[bytes, str, str] | None:
|
||||
return data, content_type, ext
|
||||
|
||||
|
||||
def capture_enabled() -> bool:
|
||||
return os.environ.get(CAPTURE_ENV, "1").strip() != "0"
|
||||
|
||||
|
||||
async def _capture(url: str) -> tuple[bytes, str, str] | None:
|
||||
try:
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
async with async_playwright() as pw:
|
||||
browser = await pw.chromium.launch(headless=True)
|
||||
try:
|
||||
page = await browser.new_page(viewport=CAPTURE_VIEWPORT)
|
||||
await page.goto(url, wait_until="networkidle", timeout=CAPTURE_TIMEOUT_MS)
|
||||
data = await page.screenshot(type="jpeg", quality=80)
|
||||
finally:
|
||||
await browser.close()
|
||||
except Exception as ex: # noqa: BLE001
|
||||
LOG.w(f"[thumbnail] 화면 촬영 실패(대표 사진으로 대신한다) {url}: {type(ex).__name__}: {ex}")
|
||||
return None
|
||||
if not data or len(data) > MAX_BYTES:
|
||||
return None
|
||||
return data, "image/jpeg", "jpg"
|
||||
|
||||
|
||||
def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||
name = blob_name(slug, ext)
|
||||
settings = ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL)
|
||||
@@ -145,17 +173,21 @@ def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||
|
||||
|
||||
async def store(slug: str, snapshot: dict, version: int | None = None) -> str | None:
|
||||
"""대표 사진을 썸네일로 올리고 공개 URL 을 돌려준다."""
|
||||
"""발행된 화면을 찍어 썸네일로 올리고 공개 URL 을 돌려준다. 못 찍으면 대표 사진을 쓴다."""
|
||||
if not is_configured():
|
||||
return None
|
||||
|
||||
row = site_payload.primary_media(snapshot)
|
||||
url = str((row or {}).get("url") or "").strip()
|
||||
if not url:
|
||||
LOG.w(f"[thumbnail] 대표 사진이 없다 — 썸네일 없이 발행한다: {slug}")
|
||||
return None
|
||||
fetched = None
|
||||
if capture_enabled():
|
||||
fetched = await _capture(f"{site_payload.publish_origin()}/s/{slug}")
|
||||
|
||||
fetched = await _fetch(url)
|
||||
if fetched is None:
|
||||
row = site_payload.primary_media(snapshot)
|
||||
url = str((row or {}).get("url") or "").strip()
|
||||
if not url:
|
||||
LOG.w(f"[thumbnail] 대표 사진이 없다 — 썸네일 없이 발행한다: {slug}")
|
||||
return None
|
||||
fetched = await _fetch(url)
|
||||
if fetched is None:
|
||||
return None
|
||||
data, content_type, ext = fetched
|
||||
|
||||
@@ -9,6 +9,7 @@ from common.utils.gtime import GTime
|
||||
from config.server_configs import external_api_config
|
||||
from crud.media_crud import MediaCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services import activity_feed
|
||||
from services.external import gemini
|
||||
from services.llm import provider
|
||||
from common.job_errors import PermanentJobError
|
||||
@@ -112,4 +113,9 @@ async def run_vision(job: dict) -> dict:
|
||||
|
||||
LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · "
|
||||
f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})")
|
||||
await activity_feed.post(
|
||||
"🖼 사진 분석 완료" if not stat["failed"] else "⚠️ 사진 분석 일부 실패",
|
||||
[activity_feed.place_label(place),
|
||||
f"분석 {stat['analyzed']} · 승인 {stat['approved']} · 확인대기 {stat['needs_review']} · 실패 {stat['failed']}"],
|
||||
)
|
||||
return stat
|
||||
@@ -0,0 +1,57 @@
|
||||
from common.enums import UserRole
|
||||
|
||||
|
||||
async def _place(client, headers, name="남의가게"):
|
||||
r = await client.post("/v1/place", headers=headers, json={"name": name, "category": 2})
|
||||
return r.json()["place"]["place_id"]
|
||||
|
||||
|
||||
async def test_개발자는_남의_사업장을_열고_고칠_수_있다(auth_headers, client):
|
||||
owner = await auth_headers("owner1")
|
||||
dev = await auth_headers("dev1", role=UserRole.DEVELOPER.value)
|
||||
pid = await _place(client, owner)
|
||||
|
||||
got = (await client.get(f"/v1/place/{pid}", headers=dev)).json()
|
||||
assert got["result"]["success"] is True
|
||||
assert got["place"]["name"] == "남의가게"
|
||||
|
||||
assert (await client.get(f"/v1/place/{pid}/media/list", headers=dev)).json()["result"]["success"] is True
|
||||
as_owner = (await client.get(f"/v1/place/{pid}/site", headers=owner)).json()
|
||||
as_dev = (await client.get(f"/v1/place/{pid}/site", headers=dev)).json()
|
||||
assert as_dev == as_owner
|
||||
|
||||
|
||||
async def test_일반_사장님은_남의_사업장을_못_연다(auth_headers, client):
|
||||
owner = await auth_headers("owner2")
|
||||
other = await auth_headers("other2")
|
||||
boss = await auth_headers("boss2", role=UserRole.OWNER.value)
|
||||
pid = await _place(client, owner)
|
||||
|
||||
assert (await client.get(f"/v1/place/{pid}", headers=other)).json()["result"]["success"] is False
|
||||
assert (await client.get(f"/v1/place/{pid}", headers=boss)).json()["result"]["success"] is False
|
||||
|
||||
|
||||
async def test_개발자_자기_목록은_그대로다(auth_headers, client):
|
||||
owner = await auth_headers("owner3")
|
||||
dev = await auth_headers("dev3", role=UserRole.DEVELOPER.value)
|
||||
await _place(client, owner)
|
||||
|
||||
listed = (await client.get("/v1/place/list", headers=dev)).json()
|
||||
assert listed["result"]["success"] is True
|
||||
assert all(p["name"] != "남의가게" for p in listed["places"])
|
||||
|
||||
|
||||
async def test_사이트관리는_상호_소유자_업종으로_거른다(auth_headers, client):
|
||||
owner = await auth_headers("owner4", name="김사장")
|
||||
dev = await auth_headers("dev4", role=UserRole.DEVELOPER.value)
|
||||
await client.post("/v1/place", headers=owner, json={"name": "검색카페", "category": 2})
|
||||
await client.post("/v1/place", headers=owner, json={"name": "검색펜션", "category": 1})
|
||||
|
||||
def names(r):
|
||||
return sorted(s["name"] for s in r.json()["sites"])
|
||||
|
||||
assert names(await client.get("/v1/ops/sites", headers=dev, params={"search": "검색"})) == ["검색카페", "검색펜션"]
|
||||
assert names(await client.get("/v1/ops/sites", headers=dev, params={"search": "김사장"})) == ["검색카페", "검색펜션"]
|
||||
assert names(await client.get("/v1/ops/sites", headers=dev, params={"search": "검색", "category": 2})) == ["검색카페"]
|
||||
counted = (await client.get("/v1/ops/sites", headers=dev, params={"search": "펜션"})).json()
|
||||
assert counted["total"] == 1
|
||||
@@ -309,7 +309,7 @@ async def test_구조화데이터가_화면과_다르면_발행하지_않는다(
|
||||
|
||||
# 게이트 반려는 알리지 않는다 — 사장님 쪽 문제를 운영자에게 알리면 안 된다.
|
||||
async with db_engine.begin() as c:
|
||||
rows = (await c.execute(text("SELECT kind FROM alert_outbox"))).all()
|
||||
rows = (await c.execute(text("SELECT kind FROM alert_outbox WHERE kind <> 'activity'"))).all()
|
||||
assert rows == []
|
||||
|
||||
|
||||
|
||||
@@ -115,6 +115,39 @@ async def test_사이트_디렉터리_밖의_thumbs_에_올린다(blob, monkeypa
|
||||
|
||||
|
||||
# ── 발행 경로와의 배선 ──────────────────────────────────────────────────── 아래 두 건은 "발행이 썸네일에 매달리지 않는가" 를 본다.
|
||||
async def test_발행된_화면을_찍어_올린다(blob, monkeypatch):
|
||||
shots = []
|
||||
|
||||
async def _capture(url):
|
||||
shots.append(url)
|
||||
return b"shot", "image/jpeg", "jpg"
|
||||
|
||||
monkeypatch.setenv(site_thumbnail.CAPTURE_ENV, "1")
|
||||
monkeypatch.setattr(site_thumbnail, "_capture", _capture)
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
|
||||
|
||||
await site_thumbnail.store("butter", snapshot, 4)
|
||||
|
||||
from services import site_payload
|
||||
|
||||
assert shots == [f"{site_payload.publish_origin()}/s/butter"]
|
||||
assert blob.uploads[f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"]["body"] == b"shot"
|
||||
|
||||
|
||||
async def test_촬영에_실패하면_대표_사진을_쓴다(blob, monkeypatch):
|
||||
async def _capture(url):
|
||||
return None
|
||||
|
||||
monkeypatch.setenv(site_thumbnail.CAPTURE_ENV, "1")
|
||||
monkeypatch.setattr(site_thumbnail, "_capture", _capture)
|
||||
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=b"photo"))
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
|
||||
|
||||
await site_thumbnail.store("butter", snapshot, 5)
|
||||
|
||||
assert blob.uploads[f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"]["body"] == b"photo"
|
||||
|
||||
|
||||
async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_headers, client, db_engine, monkeypatch):
|
||||
from services import build_service
|
||||
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
*/
|
||||
|
||||
export type ListSitesParams = {
|
||||
/**
|
||||
* 상호·소유자 이메일·이름·로그인 아이디 부분 일치
|
||||
*/
|
||||
search?: string | null;
|
||||
/**
|
||||
* PlaceCategory
|
||||
*/
|
||||
category?: number | null;
|
||||
/**
|
||||
* @minimum 1
|
||||
*/
|
||||
|
||||
@@ -12,6 +12,9 @@ export const JOB_POLL_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
/** 연속 실패 허용치. */
|
||||
export const JOB_MAX_POLL_ERRORS = 3;
|
||||
|
||||
/** 응답이 한 번도 없을 때 포기하기까지의 시간. */
|
||||
export const JOB_UNREACHABLE_MS = 3 * 60 * 1000;
|
||||
|
||||
/** 폴링이 끝난 이유. */
|
||||
export type JobOutcome =
|
||||
| {kind: 'done'; job: JobData}
|
||||
@@ -26,6 +29,7 @@ export interface PollJobOptions {
|
||||
intervalMs?: number;
|
||||
timeoutMs?: number;
|
||||
maxErrors?: number;
|
||||
unreachableMs?: number;
|
||||
/** 폴링 1회마다 호출. */
|
||||
onTick?: (job: JobData) => void;
|
||||
}
|
||||
@@ -52,12 +56,14 @@ export async function pollJob(jobId: string, options: PollJobOptions): Promise<J
|
||||
intervalMs = JOB_POLL_MS,
|
||||
timeoutMs = JOB_POLL_TIMEOUT_MS,
|
||||
maxErrors = JOB_MAX_POLL_ERRORS,
|
||||
unreachableMs = JOB_UNREACHABLE_MS,
|
||||
onTick,
|
||||
} = options;
|
||||
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let errors = 0;
|
||||
let lastError: unknown;
|
||||
let lastReachedAt = Date.now();
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
await delay(intervalMs, signal);
|
||||
@@ -74,7 +80,10 @@ export async function pollJob(jobId: string, options: PollJobOptions): Promise<J
|
||||
|
||||
// 한 번이라도 잡을 받아오면 카운터를 되돌린다 — 잠깐 끊긴 네트워크로 몇 분짜리 잡을 접으면 안 된다.
|
||||
errors = job ? 0 : errors + 1;
|
||||
if (errors >= maxErrors) return {kind: 'unreachable', error: lastError};
|
||||
if (job) lastReachedAt = Date.now();
|
||||
if (errors >= maxErrors && Date.now() - lastReachedAt >= unreachableMs) {
|
||||
return {kind: 'unreachable', error: lastError};
|
||||
}
|
||||
if (!job) continue;
|
||||
|
||||
onTick?.(job);
|
||||
|
||||
@@ -79,7 +79,11 @@ export async function waitForVision(placeId: string, job: JobData, signal: Abort
|
||||
const visionJobId = (job.result as {vision_job_id?: string} | undefined)?.vision_job_id;
|
||||
if (!visionJobId) return;
|
||||
const outcome = await pollJob(visionJobId, {signal});
|
||||
if (outcome.kind === 'done') await refreshPlaceCaches(placeId);
|
||||
if (outcome.kind === 'aborted') return;
|
||||
await refreshPlaceCaches(placeId);
|
||||
if (outcome.kind !== 'done') {
|
||||
notify.warn('사진 분석 결과를 아직 받지 못했습니다.', '잠시 후 새로고침하면 사진이 보입니다.');
|
||||
}
|
||||
}
|
||||
|
||||
/** 수집이 끝난 뒤 서버가 진실인 것들 — place(주소·갱신시각) · 링크 · fact · **사진**. */
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import {useState} from 'react';
|
||||
import {Navigate} from 'react-router';
|
||||
import {Link, Navigate} from 'react-router';
|
||||
import {keepPreviousData} from '@tanstack/react-query';
|
||||
import {Building2, ChevronLeft, ChevronRight, ExternalLink, Loader2} from 'lucide-react';
|
||||
import {Building2, ChevronLeft, ChevronRight, ExternalLink, Loader2, Newspaper, Pencil, Search, Trash2, X} from 'lucide-react';
|
||||
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
|
||||
import {UserRole, useListSites, type OpsSiteData} from '@/api';
|
||||
import {changeStatus, deletePlace, PublishAction, UserRole, useListSites, type OpsSiteData} from '@/api';
|
||||
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {PUBLISH_HOST} from '@/lib/site';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useAuthStore} from '@/stores/auth';
|
||||
|
||||
const CATEGORY_LABEL: Record<number, string> = {
|
||||
@@ -39,14 +42,46 @@ export function OpsSitesPage() {
|
||||
const isRestoring = useAuthStore((s) => s.isRestoring);
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const [page, setPage] = useState(1);
|
||||
const [search, setSearch] = useState('');
|
||||
const [category, setCategory] = useState<number | null>(null);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const size = 20;
|
||||
// enabled: role 이 확정되기 전엔 요청하지 않는다 — 어차피 백엔드가 403 으로 막지만, 사장님 화면에서 실패 토스트가 먼저 뜨는 것과 새로고침 때 잠깐의 오탐 리다이렉트를 막는다.
|
||||
const {data, isLoading, isError, error} = useListSites(
|
||||
{page, size},
|
||||
const {data, isLoading, isError, error, refetch} = useListSites(
|
||||
{page, size, search: search || undefined, category: category ?? undefined},
|
||||
{query: {placeholderData: keepPreviousData, enabled: role === UserRole.DEVELOPER}},
|
||||
);
|
||||
|
||||
// RequireAuth 와 같은 이유 — 복구가 끝나기 전에 판단하면 새로고침마다 리다이렉트가 한 번 번쩍인다.
|
||||
const handleDelete = async (row: OpsSiteData) => {
|
||||
const published = row.status === SiteStatus.PUBLISHED;
|
||||
const message = published
|
||||
? `'${row.name}' 사업장을 삭제할까요?\n발행된 사이트를 먼저 내리고 삭제합니다.`
|
||||
: `'${row.name}' 사업장을 삭제할까요?`;
|
||||
if (!window.confirm(message)) return;
|
||||
setBusyId(row.place_id);
|
||||
try {
|
||||
if (published) {
|
||||
const down = await changeStatus(row.place_id, {action: PublishAction.UNPUBLISH});
|
||||
if (!down.result?.success) {
|
||||
notifyApiError({data: down}, '사이트를 내리지 못해 삭제하지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await deletePlace(row.place_id);
|
||||
if (!res.result?.success) {
|
||||
notifyApiError({data: res}, '사업장을 삭제하지 못했습니다.');
|
||||
return;
|
||||
}
|
||||
notify.success(`'${row.name}' 을(를) 삭제했습니다.`);
|
||||
await refetch();
|
||||
} catch (deleteError) {
|
||||
notifyApiError(deleteError, '사업장을 삭제하지 못했습니다.');
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (isRestoring) return null;
|
||||
if (role !== UserRole.DEVELOPER) return <Navigate to="/sites" replace />;
|
||||
|
||||
@@ -56,7 +91,55 @@ export function OpsSitesPage() {
|
||||
|
||||
return (
|
||||
<AppShell>
|
||||
<PageContainer title="사이트관리" description="전 계정 사이트 발행 현황입니다. 회사 스코프 없이 전부 보입니다.">
|
||||
<PageContainer
|
||||
title="사이트관리"
|
||||
description="전 계정 사이트 발행 현황입니다. 회사 스코프 없이 전부 보입니다."
|
||||
actions={
|
||||
<div className="relative w-64">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setPage(1);
|
||||
setSearch(event.target.value);
|
||||
}}
|
||||
placeholder="상호 · 이메일 · 이름 · 아이디 검색"
|
||||
aria-label="상호 · 이메일 · 이름 · 아이디 검색"
|
||||
className="h-9 pr-8 pl-8"
|
||||
/>
|
||||
{search && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="검색어 지우기"
|
||||
onClick={() => setSearch('')}
|
||||
className="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
{[null, ...Object.keys(CATEGORY_LABEL).map(Number)].map((value) => (
|
||||
<button
|
||||
key={value ?? 'all'}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPage(1);
|
||||
setCategory(value);
|
||||
}}
|
||||
className={cn(
|
||||
'h-8 cursor-pointer rounded-md border px-3 text-xs font-medium transition-colors',
|
||||
category === value ? 'border-foreground bg-foreground text-background' : 'border-border hover:bg-muted',
|
||||
)}
|
||||
>
|
||||
{value === null ? '전체' : CATEGORY_LABEL[value]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center py-20 text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
@@ -95,21 +178,47 @@ export function OpsSitesPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{url ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<Link
|
||||
to={`/builder?placeId=${row.place_id}`}
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
열기
|
||||
</a>
|
||||
) : (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{row.domain ? `주소 예약됨 · ${row.domain}` : '주소 미정'}
|
||||
</span>
|
||||
)}
|
||||
<Pencil className="size-3.5" />
|
||||
빌더
|
||||
</Link>
|
||||
<Link
|
||||
to={`/blog?placeId=${row.place_id}`}
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
>
|
||||
<Newspaper className="size-3.5" />
|
||||
미니블로그
|
||||
</Link>
|
||||
{url ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
열기
|
||||
</a>
|
||||
) : (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{row.domain ? `주소 예약됨 · ${row.domain}` : '주소 미정'}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label={`${row.name} 삭제`}
|
||||
disabled={busyId === row.place_id}
|
||||
onClick={() => handleDelete(row)}
|
||||
className="text-destructive"
|
||||
>
|
||||
{busyId === row.place_id ? <Loader2 className="animate-spin" /> : <Trash2 />}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -6,12 +6,10 @@ import {useMemo, useState} from 'react';
|
||||
import {Link, useNavigate} from 'react-router';
|
||||
import {
|
||||
Building2,
|
||||
CalendarClock,
|
||||
Coffee,
|
||||
ExternalLink,
|
||||
Loader2,
|
||||
MoreHorizontal,
|
||||
Newspaper,
|
||||
Pencil,
|
||||
Plus,
|
||||
Search,
|
||||
@@ -394,32 +392,6 @@ export function SitesPage() {
|
||||
<Pencil className="size-3.5" />
|
||||
디자인·컨텐츠 관리
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMenuId(null);
|
||||
navigate(`/blog?placeId=${row.place_id}`);
|
||||
}}
|
||||
className="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left text-xs transition-colors hover:bg-muted"
|
||||
>
|
||||
<Newspaper className="size-3.5" />
|
||||
미니블로그 관리
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMenuId(null);
|
||||
// 예약 요청은 DB 에 안 남는다 — 메일로만 가고 우리 쪽엔 로그 한 줄만 남는다.
|
||||
notify.info(
|
||||
'예약 요청은 메일로만 전달됩니다',
|
||||
'연락처를 따로 저장하지 않기로 했습니다(2026-09-16). 목록이 필요하면 먼저 이 방침을 바꿔야 합니다.',
|
||||
);
|
||||
}}
|
||||
className="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left text-xs transition-colors hover:bg-muted"
|
||||
>
|
||||
<CalendarClock className="size-3.5" />
|
||||
예약요청 관리
|
||||
</button>
|
||||
<div className="my-1 border-t border-border" />
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -502,7 +502,15 @@
|
||||
"simple",
|
||||
"magazine",
|
||||
"retro",
|
||||
"paper"
|
||||
"paper",
|
||||
"round",
|
||||
"cinema",
|
||||
"bigtype",
|
||||
"boutique",
|
||||
"graphic",
|
||||
"coral",
|
||||
"minimal",
|
||||
"pine"
|
||||
],
|
||||
"sections": [
|
||||
{
|
||||
@@ -629,7 +637,15 @@
|
||||
"simple",
|
||||
"magazine",
|
||||
"retro",
|
||||
"paper"
|
||||
"paper",
|
||||
"round",
|
||||
"cinema",
|
||||
"bigtype",
|
||||
"boutique",
|
||||
"graphic",
|
||||
"coral",
|
||||
"minimal",
|
||||
"pine"
|
||||
],
|
||||
"sections": [
|
||||
{
|
||||
@@ -754,7 +770,15 @@
|
||||
"defaultTemplate": "simple",
|
||||
"templates": [
|
||||
"simple",
|
||||
"magazine"
|
||||
"magazine",
|
||||
"round",
|
||||
"cinema",
|
||||
"bigtype",
|
||||
"boutique",
|
||||
"graphic",
|
||||
"coral",
|
||||
"minimal",
|
||||
"pine"
|
||||
],
|
||||
"sections": [
|
||||
{
|
||||
|
||||
@@ -255,9 +255,17 @@ const MEDIA_EXT: Record<string, string> = {
|
||||
};
|
||||
|
||||
/** 사진을 **우리 오리진으로 옮긴다.** */
|
||||
async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
||||
interface MediaMirrorStats {
|
||||
total: number;
|
||||
fetched: number;
|
||||
cached: number;
|
||||
failed: number;
|
||||
}
|
||||
|
||||
async function mirrorMedia(payload: SitePayload, siteDir: string): Promise<MediaMirrorStats> {
|
||||
const items = (payload.media ?? []).filter((item) => /^https?:\/\//i.test(item.url ?? ''));
|
||||
if (items.length === 0) return;
|
||||
const stats: MediaMirrorStats = {total: items.length, fetched: 0, cached: 0, failed: 0};
|
||||
if (items.length === 0) return stats;
|
||||
|
||||
const dir = join(siteDir, MEDIA_DIR);
|
||||
// 절대 주소로 바꾼다.
|
||||
@@ -275,6 +283,7 @@ async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
||||
if (hit) {
|
||||
wanted.add(hit);
|
||||
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${hit}`);
|
||||
stats.cached += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -297,6 +306,7 @@ async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
||||
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${name}`);
|
||||
fetched += 1;
|
||||
} catch (ex) {
|
||||
stats.failed += 1;
|
||||
console.warn(` ! 사진을 못 받았습니다(원래 주소를 씁니다): ${origin} — ${ex}`);
|
||||
}
|
||||
}
|
||||
@@ -306,6 +316,8 @@ async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
||||
if (!wanted.has(name)) rmSync(join(dir, name), {force: true});
|
||||
}
|
||||
if (fetched > 0) console.log(` 사진 ${fetched}장을 내려받았습니다 (총 ${wanted.size}장)`);
|
||||
stats.fetched = fetched;
|
||||
return stats;
|
||||
}
|
||||
|
||||
/** 이 슬러그·버전이 실제로 구워지는 자리 — `out/versions/<slug>/<version>/`. */
|
||||
@@ -573,6 +585,7 @@ interface RenderReport {
|
||||
/** 절대규칙 3 위반 목록. */
|
||||
mismatches: string[];
|
||||
error: string | null;
|
||||
media?: MediaMirrorStats;
|
||||
}
|
||||
|
||||
function writeReport(payloadFile: string, report: RenderReport) {
|
||||
@@ -922,7 +935,7 @@ async function main() {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
await mirrorMedia(entry.payload, stagingDir);
|
||||
const media = await mirrorMedia(entry.payload, stagingDir);
|
||||
const result = prerenderSite(entry.payload, args.out, assets, referenced);
|
||||
const payload = result.payload;
|
||||
origin = origin || payload.site.origin;
|
||||
@@ -955,6 +968,7 @@ async function main() {
|
||||
jsonld: result.jsonld,
|
||||
mismatches: [],
|
||||
error: null,
|
||||
media,
|
||||
};
|
||||
writeFileSync(savedReportPath, JSON.stringify({...report, origin: payload.site.origin}));
|
||||
writeReport(entry.file, report);
|
||||
|
||||
@@ -30,7 +30,7 @@ type PageId = 'home' | 'area' | 'stay' | 'story';
|
||||
|
||||
const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {title: string; note: string}> = {
|
||||
area: {title: '지역', note: '대문에서 걸어 닿는 자리와, 이 도시가 남긴 이야기입니다.'},
|
||||
stay: {title: '이용안내', note: '객실 상세와 요금, 예약하는 방법입니다.'},
|
||||
stay: {title: '이용안내', note: '상세 안내와 요금, 예약하는 방법입니다.'},
|
||||
story: {title: '이야기', note: '사장님이 남기는 글과 다녀가신 분들의 후기, 그리고 엽서 한 장입니다.'},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
import {BOOK_EVENT} from '../paper/Rooms';
|
||||
import {unitWord} from '../kit/unitWord';
|
||||
import {Sheet} from '../paper/Sheet';
|
||||
import {Idx} from './SectionHead';
|
||||
|
||||
@@ -32,6 +33,7 @@ function specRows(unit: UnitView, facts: Parameters<typeof factText>[0]) {
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -78,7 +80,7 @@ export function Rooms() {
|
||||
const [main, sub] = splitName(unit.name);
|
||||
return (
|
||||
<section key={unit.unitId} id={`unit-${unit.slug}`}>
|
||||
<Idx title={main} aside={`Room ${letter(i)}${sub ? ` · ${sub}` : ''}`} />
|
||||
<Idx title={main} aside={`${unitWord(payload.place.category)} ${letter(i)}${sub ? ` · ${sub}` : ''}`} />
|
||||
{unit.images.length > 0 && (
|
||||
<Car
|
||||
label={`${main} 사진`}
|
||||
@@ -104,14 +106,16 @@ export function Rooms() {
|
||||
<span>{main} 자세히</span>
|
||||
<span>+</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="line line--ink"
|
||||
onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}
|
||||
>
|
||||
<span>{main} 예약 요청</span>
|
||||
<span>→</span>
|
||||
</button>
|
||||
{lodging && (
|
||||
<button
|
||||
type="button"
|
||||
className="line line--ink"
|
||||
onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}
|
||||
>
|
||||
<span>{main} 예약 요청</span>
|
||||
<span>→</span>
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -30,7 +30,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {en: string; title: string; not
|
||||
stay: {
|
||||
en: 'Stay',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
en: 'Story',
|
||||
@@ -131,6 +131,7 @@ function useTabs() {
|
||||
export function Frame({children}: {children: ReactNode}) {
|
||||
const payload = useSite();
|
||||
const {place, site} = payload;
|
||||
const lodging = place.category === PlaceCategory.LODGING;
|
||||
const tabs = useTabs();
|
||||
const page = usePage();
|
||||
const solid = useSolid(page);
|
||||
@@ -245,7 +246,7 @@ export function Frame({children}: {children: ReactNode}) {
|
||||
onClick={() => setMenuOpen(false)}
|
||||
>
|
||||
<span className="b-menu-no">{pad2(i + 1)}</span>
|
||||
<span className="b-menu-en">{PAGE_EN[tab.page]}</span>
|
||||
<span className="b-menu-en">{tab.page === 'stay' && !lodging ? 'Guide' : PAGE_EN[tab.page]}</span>
|
||||
<span className="b-menu-ko">{tab.label}</span>
|
||||
</a>
|
||||
))}
|
||||
@@ -254,7 +255,7 @@ export function Frame({children}: {children: ReactNode}) {
|
||||
{(Object.keys(PAGE_HEAD) as Exclude<PageId, 'home'>[]).map((id) => (
|
||||
<div key={id} data-pg={id}>
|
||||
<section className="b-phead">
|
||||
<p className="b-phead-en">{PAGE_HEAD[id].en}</p>
|
||||
<p className="b-phead-en">{id === 'stay' && !lodging ? 'Guide' : PAGE_HEAD[id].en}</p>
|
||||
<p className="b-phead-ko">
|
||||
{id === 'area' ? (place.addressLocality?.replace(/(시|군)$/, '') ?? PAGE_HEAD.area.title) : PAGE_HEAD[id].title}
|
||||
</p>
|
||||
|
||||
@@ -31,7 +31,7 @@ export function Blog({full}: {full?: boolean}) {
|
||||
|
||||
return (
|
||||
<section className="b-sec" id={full ? 'blog' : undefined} aria-labelledby={full ? 'blog-heading' : undefined}>
|
||||
<Sh en="Journal" id={full ? 'blog-heading' : undefined} lead="사장님이 남기는 숙소 이야기입니다.">
|
||||
<Sh en="Journal" id={full ? 'blog-heading' : undefined} lead="사장님이 직접 남기는 소식입니다.">
|
||||
미니 블로그
|
||||
</Sh>
|
||||
<div className="b-wrap">
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
import {BOOK_EVENT} from '../paper/Rooms';
|
||||
import {unitWord} from '../kit/unitWord';
|
||||
import {Sheet} from '../paper/Sheet';
|
||||
|
||||
function splitName(name: string): [string, string | undefined] {
|
||||
@@ -31,6 +32,7 @@ const book = () => window.dispatchEvent(new Event(BOOK_EVENT));
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -43,7 +45,7 @@ export function Rooms() {
|
||||
<div data-pg="home">
|
||||
<section id="units" aria-labelledby="units-heading">
|
||||
<div className="wrap">
|
||||
<p className="label">ROOMS</p>
|
||||
<p className="label">{unitWord(payload.place.category).toUpperCase()}</p>
|
||||
<h2 id="units-heading">{sectionName(payload, spec.path, `${spec.label} 안내`)}</h2>
|
||||
</div>
|
||||
<div className="wrap">
|
||||
@@ -77,7 +79,7 @@ export function Rooms() {
|
||||
return (
|
||||
<section key={unit.unitId} className="unit" id={`unit-${unit.slug}`}>
|
||||
<div className="wrap">
|
||||
<p className="label">ROOM {String(i + 1).padStart(2, '0')}</p>
|
||||
<p className="label">{unitWord(payload.place.category).toUpperCase()} {String(i + 1).padStart(2, '0')}</p>
|
||||
<h2>
|
||||
{main} {sub && <span className="cnt">{sub}</span>}
|
||||
</h2>
|
||||
@@ -109,9 +111,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
{main} 자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={book}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={book}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -36,7 +36,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {label: string; title: string;
|
||||
stay: {
|
||||
label: 'STAY',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
label: 'STORY',
|
||||
|
||||
@@ -30,7 +30,7 @@ function Blog({full}: {full?: boolean}) {
|
||||
<section className="wrap" id={full ? 'blog' : undefined}>
|
||||
<p className="label">JOURNAL</p>
|
||||
<h2>미니 블로그</h2>
|
||||
<p className="lead">사장님이 남기는 숙소 이야기입니다.</p>
|
||||
<p className="lead">사장님이 직접 남기는 소식입니다.</p>
|
||||
<div className="posts" data-blog={full ? 'full' : 'home'}>
|
||||
{shown.map((item) => (
|
||||
<Post key={item.postId} publishedAt={item.publishedAt} body={item.body} />
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
import {BOOK_EVENT} from '../paper/Rooms';
|
||||
import {unitWord} from '../kit/unitWord';
|
||||
import {Sheet} from '../paper/Sheet';
|
||||
|
||||
function splitName(name: string): [string, string | undefined] {
|
||||
@@ -32,6 +33,7 @@ const book = () => window.dispatchEvent(new Event(BOOK_EVENT));
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -45,7 +47,7 @@ export function Rooms() {
|
||||
<div data-pg="home">
|
||||
<section id="units" aria-labelledby="units-heading">
|
||||
<div className="wrap">
|
||||
<p className="label">ROOMS</p>
|
||||
<p className="label">{unitWord(payload.place.category).toUpperCase()}</p>
|
||||
<h2 id="units-heading">{sectionName(payload, spec.path, `${spec.label} 안내`)}</h2>
|
||||
<div className="rgrid">
|
||||
{units.slice(0, HOME_UNITS).map((unit) => (
|
||||
@@ -69,7 +71,7 @@ export function Rooms() {
|
||||
return (
|
||||
<section key={unit.unitId} className="unit" id={`unit-${unit.slug}`}>
|
||||
<div className="wrap">
|
||||
<p className="label">ROOM {String(i + 1).padStart(2, '0')}</p>
|
||||
<p className="label">{unitWord(payload.place.category).toUpperCase()} {String(i + 1).padStart(2, '0')}</p>
|
||||
<h2>
|
||||
{main} {sub && <span className="cnt">{sub}</span>}
|
||||
</h2>
|
||||
@@ -101,9 +103,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
{main} 자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={book}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={book}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -36,7 +36,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {kicker: string; title: string;
|
||||
stay: {
|
||||
kicker: 'Reservation',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
kicker: 'Story',
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
import {BOOK_EVENT} from '../paper/Rooms';
|
||||
import {unitWord} from '../kit/unitWord';
|
||||
import {Sheet} from '../paper/Sheet';
|
||||
|
||||
function splitName(name: string): [string, string | undefined] {
|
||||
@@ -30,6 +31,7 @@ const HOME_MAX = 4;
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -42,7 +44,7 @@ export function Rooms() {
|
||||
<>
|
||||
<div data-pg="home">
|
||||
<section className="sec" id="units" aria-labelledby="units-heading">
|
||||
<p className="kicker">Room View</p>
|
||||
<p className="kicker">{lodging ? 'Room View' : unitWord(payload.place.category)}</p>
|
||||
<h2 id="units-heading">{sectionName(payload, spec.path, `${spec.label} 안내`)}</h2>
|
||||
<div className="rooms">
|
||||
{units.slice(0, HOME_MAX).map((unit, i) => (
|
||||
@@ -74,7 +76,7 @@ export function Rooms() {
|
||||
return (
|
||||
<section key={unit.unitId} className="sec" id={`unit-${unit.slug}`}>
|
||||
<p className="kicker">
|
||||
Room {String(i + 1).padStart(2, '0')}
|
||||
{unitWord(payload.place.category)} {String(i + 1).padStart(2, '0')}
|
||||
</p>
|
||||
<h2>
|
||||
{main} {sub && <span className="sub">{sub}</span>}
|
||||
@@ -105,9 +107,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ type PageId = 'home' | 'area' | 'stay' | 'story';
|
||||
|
||||
const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {title: string; note: string}> = {
|
||||
area: {title: '지역 소개', note: '대문에서 걸어 닿는 자리와, 이 도시가 남긴 이야기입니다.'},
|
||||
stay: {title: '이용안내', note: '객실 상세와 요금, 예약하는 방법입니다.'},
|
||||
stay: {title: '이용안내', note: '상세 안내와 요금, 예약하는 방법입니다.'},
|
||||
story: {title: '이야기', note: '사장님이 남기는 글과 다녀가신 분들의 후기, 그리고 엽서 한 장입니다.'},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
@@ -60,6 +60,7 @@ function UnitSheet({unit, onClose}: {unit: UnitView | null; onClose: () => void}
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -136,9 +137,11 @@ export function Rooms() {
|
||||
<button type="button" className="more" onClick={() => setOpen(unit)}>
|
||||
{main} 자세히
|
||||
</button>
|
||||
<button type="button" className="cta" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="cta" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
{main} 예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import {PlaceCategory} from '@o2o/shared';
|
||||
|
||||
const WORD: Record<number, string> = {
|
||||
[PlaceCategory.LODGING]: 'Room',
|
||||
[PlaceCategory.CAFE]: 'Menu',
|
||||
[PlaceCategory.RESTAURANT]: 'Menu',
|
||||
[PlaceCategory.CLINIC]: 'Program',
|
||||
};
|
||||
|
||||
export function unitWord(category: number): string {
|
||||
return WORD[category] ?? 'Menu';
|
||||
}
|
||||
@@ -36,7 +36,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {kicker: string; title: string;
|
||||
stay: {
|
||||
kicker: 'Reservation',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
kicker: 'Story',
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
import {BOOK_EVENT} from '../paper/Rooms';
|
||||
import {unitWord} from '../kit/unitWord';
|
||||
import {Sheet} from '../paper/Sheet';
|
||||
|
||||
function splitName(name: string): [string, string | undefined] {
|
||||
@@ -30,6 +31,7 @@ const HOME_MAX = 4;
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -42,7 +44,7 @@ export function Rooms() {
|
||||
<>
|
||||
<div data-pg="home">
|
||||
<section className="sec" id="units" aria-labelledby="units-heading">
|
||||
<p className="kicker">Stay</p>
|
||||
<p className="kicker">{lodging ? 'Stay' : unitWord(payload.place.category)}</p>
|
||||
<h2 id="units-heading">{sectionName(payload, spec.path, `${spec.label} 안내`)}</h2>
|
||||
<div className="rooms">
|
||||
{units.slice(0, HOME_MAX).map((unit) => (
|
||||
@@ -71,7 +73,7 @@ export function Rooms() {
|
||||
return (
|
||||
<section key={unit.unitId} className="sec" id={`unit-${unit.slug}`}>
|
||||
<p className="kicker">
|
||||
Room {String(i + 1).padStart(2, '0')}
|
||||
{unitWord(payload.place.category)} {String(i + 1).padStart(2, '0')}
|
||||
</p>
|
||||
<h2>
|
||||
{main} {sub && <span className="sub">{sub}</span>}
|
||||
@@ -102,9 +104,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -22,7 +22,7 @@ export function Blog({full}: {full?: boolean}) {
|
||||
<p className="eyebrow">BLOG</p>
|
||||
<h2>미니 블로그</h2>
|
||||
<p className="note" style={{margin: '-8px 0 14px'}}>
|
||||
사장님이 남기는 숙소 이야기입니다.
|
||||
사장님이 직접 남기는 소식입니다.
|
||||
</p>
|
||||
<div data-blog={full ? 'full' : 'home'}>
|
||||
{shown.map((item) => (
|
||||
|
||||
@@ -36,7 +36,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {kicker: string; title: string;
|
||||
stay: {
|
||||
kicker: '이용안내',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
kicker: '이야기',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
@@ -30,6 +30,7 @@ const HOME_MAX = 4;
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -102,9 +103,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -36,7 +36,7 @@ const PAGE_HEAD: Record<Exclude<PageId, 'home'>, {kicker: string; title: string;
|
||||
stay: {
|
||||
kicker: '이용안내',
|
||||
title: '이용안내 · 예약',
|
||||
note: '객실 상세와 요금, 예약하는 방법입니다.',
|
||||
note: '상세 안내와 요금, 예약하는 방법입니다.',
|
||||
},
|
||||
story: {
|
||||
kicker: '이야기',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {useState} from 'react';
|
||||
import {factText, sanitizeUnits} from '@o2o/shared';
|
||||
import {factText, sanitizeUnits, PlaceCategory} from '@o2o/shared';
|
||||
import {useSite} from '@site/lib/site-context';
|
||||
import {sectionName, unitSpec, unitViews, type UnitView} from '@site/lib/derive';
|
||||
import {Car} from '../paper/Car';
|
||||
@@ -30,6 +30,7 @@ const HOME_MAX = 4;
|
||||
|
||||
export function Rooms() {
|
||||
const payload = useSite();
|
||||
const lodging = payload.place.category === PlaceCategory.LODGING;
|
||||
const units = unitViews(payload);
|
||||
const spec = unitSpec(payload);
|
||||
const raw = new Map(sanitizeUnits(payload.units).map((unit) => [unit.unitId, unit]));
|
||||
@@ -102,9 +103,11 @@ export function Rooms() {
|
||||
<button type="button" className="btn ghost" onClick={() => setOpen(unit)}>
|
||||
자세히
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
{lodging && (
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||
예약 요청
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user