Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
378ad55b5b | ||
|
|
14b6e95f9d | ||
|
|
87343c791b | ||
|
|
e5153eb66c |
No files matched your search
@@ -13,6 +13,7 @@
|
|||||||
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
||||||
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
||||||
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
||||||
|
| `activity` | 수집 시작·채널 실패·완료 · 사진 분석 · 첫 발행/재발행/빌드/되돌리기 시작·끝(`services/activity_feed.py`) | 없음(매번 보낸다) |
|
||||||
|
|
||||||
★ **게이트 반려는 알리지 않는다.** 사장님이 fact 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
★ **게이트 반려는 알리지 않는다.** 사장님이 fact 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
||||||
운영자가 손댈 일이 아니다 — `build_service._fail(reason, gate=None)` 일 때만 `build_failed`.
|
운영자가 손댈 일이 아니다 — `build_service._fail(reason, gate=None)` 일 때만 `build_failed`.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
os.environ.setdefault("APP_ENV", "test")
|
os.environ.setdefault("APP_ENV", "test")
|
||||||
|
os.environ.setdefault("THUMBNAIL_CAPTURE", "0")
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class ISiteCRUD(ABC):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@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) 전용."""
|
"""전 계정 사이트 목록(회사 스코프 없음) — 내부 운영(DEVELOPER) 전용."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -145,12 +145,23 @@ class SiteCRUD(ISiteCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, [], 0
|
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 필터가 없다 — 소유자 계정 정보를 같이 얹는다."""
|
"""list_owner_sites 와 같은 조인이되 owner_user_id 필터가 없다 — 소유자 계정 정보를 같이 얹는다."""
|
||||||
try:
|
try:
|
||||||
where = places.deleted == False # noqa: E712
|
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:
|
if cnt_err != ErrorType.SUCCESS:
|
||||||
return cnt_err, [], 0
|
return cnt_err, [], 0
|
||||||
total = int(cnt_rows[0] or 0) if cnt_rows else 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="전 계정 사이트 목록(개발자 전용)")
|
@router.get(path="/sites", response_model=Res_OpsSites, summary="전 계정 사이트 목록(개발자 전용)")
|
||||||
async def list_sites(service: OpsService = Depends(), pg: PageParams = Depends(), _user=Depends(RequireDeveloper)):
|
async def list_sites(
|
||||||
return RemoveNoneResponse(await service.list_sites(pg))
|
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="전 계정 목록(개발자 전용)")
|
@router.get(path="/users", response_model=Res_OpsUsers, summary="전 계정 목록(개발자 전용)")
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
import uuid
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any, Union
|
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.responses import JSONResponse
|
||||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
import bcrypt
|
import bcrypt
|
||||||
from jose import jwt, JWTError, ExpiredSignatureError
|
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 (
|
from common.enums import (
|
||||||
|
DBWRType,
|
||||||
|
ErrorType,
|
||||||
EXCEPTION_ACCESS_TOKEN_EXPIRED,
|
EXCEPTION_ACCESS_TOKEN_EXPIRED,
|
||||||
EXCEPTION_FORBIDDEN,
|
EXCEPTION_FORBIDDEN,
|
||||||
EXCEPTION_INVALID_CLIENT_ACCESS,
|
EXCEPTION_INVALID_CLIENT_ACCESS,
|
||||||
@@ -96,8 +102,40 @@ def DecodeRefreshToken(jwt_token: str) -> UserInfo:
|
|||||||
|
|
||||||
|
|
||||||
# Depends 용 토큰 검증기
|
# Depends 용 토큰 검증기
|
||||||
async def IsValidAccessToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo:
|
async def _place_owner(place_id: str) -> str | None:
|
||||||
return DecodeAccessToken(credentials.credentials)
|
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:
|
async def IsValidRefreshToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo:
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""정적 빌드 + 발행 — BUILD 잡이 하는 일."""
|
"""정적 빌드 + 발행 — BUILD 잡이 하는 일."""
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
@@ -25,6 +26,7 @@ from crud.site_crud import SiteCRUD
|
|||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from crud.post_crud import PostCRUD
|
from crud.post_crud import PostCRUD
|
||||||
from services import (
|
from services import (
|
||||||
|
activity_feed,
|
||||||
alert_service,
|
alert_service,
|
||||||
azure_static,
|
azure_static,
|
||||||
indexnow,
|
indexnow,
|
||||||
@@ -118,6 +120,45 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
|
|||||||
|
|
||||||
async def run_build(job: dict) -> dict:
|
async def run_build(job: dict) -> dict:
|
||||||
"""BUILD 잡 핸들러."""
|
"""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"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
owner_user_id = payload["owner_user_id"]
|
owner_user_id = payload["owner_user_id"]
|
||||||
@@ -132,6 +173,7 @@ async def run_build(job: dict) -> dict:
|
|||||||
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||||
|
|
||||||
site = await ensure_site(place_id)
|
site = await ensure_site(place_id)
|
||||||
|
mode = ("재발행" if site.published_at is not None else "첫 발행") if want_publish else "빌드만"
|
||||||
|
|
||||||
# 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라 이때 받은 값이 실린다.
|
# 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라 이때 받은 값이 실린다.
|
||||||
try:
|
try:
|
||||||
@@ -198,7 +240,12 @@ async def run_build(job: dict) -> dict:
|
|||||||
raise BuildAborted(f"버전 생성 실패: {add_err.name}")
|
raise BuildAborted(f"버전 생성 실패: {add_err.name}")
|
||||||
|
|
||||||
result = {"place_id": place_id, "site_id": str(site.site_id), "version": version_no,
|
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:
|
if song_result is not None:
|
||||||
result["song"] = song_result
|
result["song"] = song_result
|
||||||
@@ -267,6 +314,8 @@ async def run_build(job: dict) -> dict:
|
|||||||
# 발행하지 않는다.
|
# 발행하지 않는다.
|
||||||
return await _fail(str(ex))
|
return await _fail(str(ex))
|
||||||
|
|
||||||
|
if report.get("media"):
|
||||||
|
result["render_media"] = report["media"]
|
||||||
mismatches = list(report.get("mismatches") or [])
|
mismatches = list(report.get("mismatches") or [])
|
||||||
unique_count_raw = report.get("uniqueContentCount")
|
unique_count_raw = report.get("uniqueContentCount")
|
||||||
unique_count = unique_count_raw or 0
|
unique_count = unique_count_raw or 0
|
||||||
@@ -366,6 +415,7 @@ async def run_build(job: dict) -> dict:
|
|||||||
if thumbnail_url:
|
if thumbnail_url:
|
||||||
site.thumbnail_url = thumbnail_url
|
site.thumbnail_url = thumbnail_url
|
||||||
result["published"] = True
|
result["published"] = True
|
||||||
|
result["url"] = site_payload.publish_url(place, site)
|
||||||
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
||||||
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""채널 발견 → 확정 URL 크롤링 → fact·사진 후보 저장."""
|
"""채널 발견 → 확정 URL 크롤링 → fact·사진 후보 저장."""
|
||||||
import re
|
import re
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from common import collect_diagnostics
|
from common import collect_diagnostics
|
||||||
@@ -12,6 +13,7 @@ from common.utils.gtime import GTime
|
|||||||
from crud.fact_crud import FactCRUD
|
from crud.fact_crud import FactCRUD
|
||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from common.category_schema import get_schema
|
from common.category_schema import get_schema
|
||||||
|
from services import activity_feed
|
||||||
from services.collector import AdapterDisabled, AdapterNotFound, REGISTRY
|
from services.collector import AdapterDisabled, AdapterNotFound, REGISTRY
|
||||||
from services.collector import yanolja_adapter
|
from services.collector import yanolja_adapter
|
||||||
from services.external import naver_place_lookup, perplexity, tour_lookup
|
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:
|
async def run_collect(job: dict) -> dict:
|
||||||
"""COLLECT 잡 핸들러."""
|
"""COLLECT 잡 핸들러."""
|
||||||
|
started = time.monotonic()
|
||||||
with collect_diagnostics.collecting():
|
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()
|
issues = collect_diagnostics.snapshot()
|
||||||
if issues:
|
if issues:
|
||||||
result["issues"] = issues
|
result["issues"] = issues
|
||||||
|
await _post_collect_summary(result, issues, time.monotonic() - started)
|
||||||
return result
|
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:
|
async def _run_collect(job: dict) -> dict:
|
||||||
payload = job["payload"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
@@ -480,7 +515,7 @@ async def _run_collect(job: dict) -> dict:
|
|||||||
if place.verified_at is None:
|
if place.verified_at is None:
|
||||||
raise CollectAborted("동일 업소 검증(verify) 전에는 수집하지 않는다 — 남의 가게가 섞인다")
|
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(
|
result["discover"] = await discover_links(
|
||||||
place,
|
place,
|
||||||
place_id,
|
place_id,
|
||||||
@@ -493,6 +528,12 @@ async def _run_collect(job: dict) -> dict:
|
|||||||
link.channel == LinkChannel.NAVER_PLACE.value for link in targets
|
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:
|
if not targets:
|
||||||
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
||||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
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": {}}
|
facts_stat = {"stored": 0, "refreshed": 0, "candidate": 0, "rejected": 0, "by_reason": {}}
|
||||||
media_stat = {"stored": 0, "skipped_duplicate": 0}
|
media_stat = {"stored": 0, "skipped_duplicate": 0}
|
||||||
unit_total = 0
|
unit_total = 0
|
||||||
|
channel_rows: list[str] = []
|
||||||
|
result["channels"] = channel_rows
|
||||||
|
|
||||||
for index, link in enumerate(targets):
|
for index, link in enumerate(targets):
|
||||||
if index > 0:
|
if index > 0:
|
||||||
@@ -530,11 +573,23 @@ async def _run_collect(job: dict) -> dict:
|
|||||||
fetch_stat["stopped_early"] = True
|
fetch_stat["stopped_early"] = True
|
||||||
LOG.i(f"[collect] 필수 항목 {cov['covered']}/{cov['total']} 확보 — "
|
LOG.i(f"[collect] 필수 항목 {cov['covered']}/{cov['total']} 확보 — "
|
||||||
f"남은 링크 {fetch_stat['skipped_enough']}건 크롤링 생략")
|
f"남은 링크 {fetch_stat['skipped_enough']}건 크롤링 생략")
|
||||||
|
channel_rows.append(f"필수 항목 확보 — 남은 {fetch_stat['skipped_enough']}건 생략")
|
||||||
break
|
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))
|
source, outcome = await fetch_one(link, PlaceCategory(place.category))
|
||||||
fetch_stat[outcome] += 1
|
fetch_stat[outcome] += 1
|
||||||
if source is None:
|
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
|
continue
|
||||||
|
|
||||||
# 수집 원문을 링크에 남긴다 — fact 가 아니라 '생성 근거' 자리다.
|
# 수집 원문을 링크에 남긴다 — 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
|
facts_stat["by_reason"][reason] = facts_stat["by_reason"].get(reason, 0) + n
|
||||||
media_stat["stored"] += m["stored"]
|
media_stat["stored"] += m["stored"]
|
||||||
media_stat["skipped_duplicate"] += m["skipped_duplicate"]
|
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["fetch"] = fetch_stat
|
||||||
result["units"] = unit_total
|
result["units"] = unit_total
|
||||||
|
|||||||
@@ -16,11 +16,11 @@ class OpsService:
|
|||||||
self.site_crud = site_crud
|
self.site_crud = site_crud
|
||||||
self.user_crud = user_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)
|
res = Res_OpsSites(page=pg.page, size=pg.size)
|
||||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||||
places.DBType(), DBWRType.DB_READ.value,
|
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:
|
if err_type != ErrorType.SUCCESS:
|
||||||
res.result.SetResult(err_type)
|
res.result.SetResult(err_type)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환"""
|
"""대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환"""
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
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 common.utils.gtime import GTime
|
||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from crud.site_crud import SiteCRUD
|
from crud.site_crud import SiteCRUD
|
||||||
from services import alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
from services import activity_feed, alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
||||||
from services.build_service import ensure_site, load_channel_links
|
from services.build_service import post_build_summary, ensure_site, load_channel_links
|
||||||
|
|
||||||
_site_crud = SiteCRUD()
|
_site_crud = SiteCRUD()
|
||||||
_place_crud = PlaceCRUD()
|
_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:
|
async def run_rollback(job: dict) -> dict:
|
||||||
"""ROLLBACK 잡 핸들러."""
|
"""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"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
owner_user_id = payload["owner_user_id"]
|
owner_user_id = payload["owner_user_id"]
|
||||||
@@ -76,7 +96,9 @@ async def run_rollback(job: dict) -> dict:
|
|||||||
result = {
|
result = {
|
||||||
"place_id": place_id, "site_id": str(site.site_id),
|
"place_id": place_id, "site_id": str(site.site_id),
|
||||||
"target_version": target_version, "site_version_id": str(version.site_version_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):
|
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,
|
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:
|
except render_service.RenderFailed as ex:
|
||||||
return await _fail(str(ex))
|
return await _fail(str(ex))
|
||||||
|
|
||||||
|
if report.get("media"):
|
||||||
|
result["render_media"] = report["media"]
|
||||||
mismatches = list(report.get("mismatches") or [])
|
mismatches = list(report.get("mismatches") or [])
|
||||||
unique_count_raw = report.get("uniqueContentCount")
|
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}")
|
await alert_service.resolve_alert(f"build_failed:{place_id}", f"롤백 성공 — {place_id} → v{target_version}")
|
||||||
|
|
||||||
result["rolled_back"] = True
|
result["rolled_back"] = True
|
||||||
|
result["url"] = site_payload.publish_url(place, site)
|
||||||
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
||||||
return result
|
return result
|
||||||
@@ -30,6 +30,10 @@ MAX_BYTES = 5 * 1024 * 1024
|
|||||||
# 썸네일은 재발행마다 바뀔 수 있고 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
|
# 썸네일은 재발행마다 바뀔 수 있고 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
|
||||||
CACHE_CONTROL = "public, max-age=60, must-revalidate"
|
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/<컨테이너>
|
_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
|
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:
|
def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||||
name = blob_name(slug, ext)
|
name = blob_name(slug, ext)
|
||||||
settings = ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL)
|
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:
|
async def store(slug: str, snapshot: dict, version: int | None = None) -> str | None:
|
||||||
"""대표 사진을 썸네일로 올리고 공개 URL 을 돌려준다."""
|
"""발행된 화면을 찍어 썸네일로 올리고 공개 URL 을 돌려준다. 못 찍으면 대표 사진을 쓴다."""
|
||||||
if not is_configured():
|
if not is_configured():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
row = site_payload.primary_media(snapshot)
|
fetched = None
|
||||||
url = str((row or {}).get("url") or "").strip()
|
if capture_enabled():
|
||||||
if not url:
|
fetched = await _capture(f"{site_payload.publish_origin()}/s/{slug}")
|
||||||
LOG.w(f"[thumbnail] 대표 사진이 없다 — 썸네일 없이 발행한다: {slug}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
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:
|
if fetched is None:
|
||||||
return None
|
return None
|
||||||
data, content_type, ext = fetched
|
data, content_type, ext = fetched
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from common.utils.gtime import GTime
|
|||||||
from config.server_configs import external_api_config
|
from config.server_configs import external_api_config
|
||||||
from crud.media_crud import MediaCRUD
|
from crud.media_crud import MediaCRUD
|
||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
|
from services import activity_feed
|
||||||
from services.external import gemini
|
from services.external import gemini
|
||||||
from services.llm import provider
|
from services.llm import provider
|
||||||
from common.job_errors import PermanentJobError
|
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']} · "
|
LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · "
|
||||||
f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})")
|
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
|
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:
|
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 == []
|
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):
|
async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_headers, client, db_engine, monkeypatch):
|
||||||
from services import build_service
|
from services import build_service
|
||||||
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
|
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
|
||||||
|
|||||||
@@ -6,6 +6,14 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListSitesParams = {
|
export type ListSitesParams = {
|
||||||
|
/**
|
||||||
|
* 상호·소유자 이메일·이름·로그인 아이디 부분 일치
|
||||||
|
*/
|
||||||
|
search?: string | null;
|
||||||
|
/**
|
||||||
|
* PlaceCategory
|
||||||
|
*/
|
||||||
|
category?: number | null;
|
||||||
/**
|
/**
|
||||||
* @minimum 1
|
* @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_MAX_POLL_ERRORS = 3;
|
||||||
|
|
||||||
|
/** 응답이 한 번도 없을 때 포기하기까지의 시간. */
|
||||||
|
export const JOB_UNREACHABLE_MS = 3 * 60 * 1000;
|
||||||
|
|
||||||
/** 폴링이 끝난 이유. */
|
/** 폴링이 끝난 이유. */
|
||||||
export type JobOutcome =
|
export type JobOutcome =
|
||||||
| {kind: 'done'; job: JobData}
|
| {kind: 'done'; job: JobData}
|
||||||
@@ -26,6 +29,7 @@ export interface PollJobOptions {
|
|||||||
intervalMs?: number;
|
intervalMs?: number;
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
maxErrors?: number;
|
maxErrors?: number;
|
||||||
|
unreachableMs?: number;
|
||||||
/** 폴링 1회마다 호출. */
|
/** 폴링 1회마다 호출. */
|
||||||
onTick?: (job: JobData) => void;
|
onTick?: (job: JobData) => void;
|
||||||
}
|
}
|
||||||
@@ -52,12 +56,14 @@ export async function pollJob(jobId: string, options: PollJobOptions): Promise<J
|
|||||||
intervalMs = JOB_POLL_MS,
|
intervalMs = JOB_POLL_MS,
|
||||||
timeoutMs = JOB_POLL_TIMEOUT_MS,
|
timeoutMs = JOB_POLL_TIMEOUT_MS,
|
||||||
maxErrors = JOB_MAX_POLL_ERRORS,
|
maxErrors = JOB_MAX_POLL_ERRORS,
|
||||||
|
unreachableMs = JOB_UNREACHABLE_MS,
|
||||||
onTick,
|
onTick,
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
let errors = 0;
|
let errors = 0;
|
||||||
let lastError: unknown;
|
let lastError: unknown;
|
||||||
|
let lastReachedAt = Date.now();
|
||||||
|
|
||||||
while (Date.now() < deadline) {
|
while (Date.now() < deadline) {
|
||||||
await delay(intervalMs, signal);
|
await delay(intervalMs, signal);
|
||||||
@@ -74,7 +80,10 @@ export async function pollJob(jobId: string, options: PollJobOptions): Promise<J
|
|||||||
|
|
||||||
// 한 번이라도 잡을 받아오면 카운터를 되돌린다 — 잠깐 끊긴 네트워크로 몇 분짜리 잡을 접으면 안 된다.
|
// 한 번이라도 잡을 받아오면 카운터를 되돌린다 — 잠깐 끊긴 네트워크로 몇 분짜리 잡을 접으면 안 된다.
|
||||||
errors = job ? 0 : errors + 1;
|
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;
|
if (!job) continue;
|
||||||
|
|
||||||
onTick?.(job);
|
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;
|
const visionJobId = (job.result as {vision_job_id?: string} | undefined)?.vision_job_id;
|
||||||
if (!visionJobId) return;
|
if (!visionJobId) return;
|
||||||
const outcome = await pollJob(visionJobId, {signal});
|
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 · **사진**. */
|
/** 수집이 끝난 뒤 서버가 진실인 것들 — place(주소·갱신시각) · 링크 · fact · **사진**. */
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
import {useState} from 'react';
|
import {useState} from 'react';
|
||||||
import {Navigate} from 'react-router';
|
import {Link, Navigate} from 'react-router';
|
||||||
import {keepPreviousData} from '@tanstack/react-query';
|
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 {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 {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
||||||
import {Badge} from '@/components/ui/badge';
|
import {Badge} from '@/components/ui/badge';
|
||||||
import {Button} from '@/components/ui/button';
|
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 {PUBLISH_HOST} from '@/lib/site';
|
||||||
|
import {cn} from '@/lib/utils';
|
||||||
import {useAuthStore} from '@/stores/auth';
|
import {useAuthStore} from '@/stores/auth';
|
||||||
|
|
||||||
const CATEGORY_LABEL: Record<number, string> = {
|
const CATEGORY_LABEL: Record<number, string> = {
|
||||||
@@ -39,14 +42,46 @@ export function OpsSitesPage() {
|
|||||||
const isRestoring = useAuthStore((s) => s.isRestoring);
|
const isRestoring = useAuthStore((s) => s.isRestoring);
|
||||||
const role = useAuthStore((s) => s.user?.role);
|
const role = useAuthStore((s) => s.user?.role);
|
||||||
const [page, setPage] = useState(1);
|
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;
|
const size = 20;
|
||||||
// enabled: role 이 확정되기 전엔 요청하지 않는다 — 어차피 백엔드가 403 으로 막지만, 사장님 화면에서 실패 토스트가 먼저 뜨는 것과 새로고침 때 잠깐의 오탐 리다이렉트를 막는다.
|
// enabled: role 이 확정되기 전엔 요청하지 않는다 — 어차피 백엔드가 403 으로 막지만, 사장님 화면에서 실패 토스트가 먼저 뜨는 것과 새로고침 때 잠깐의 오탐 리다이렉트를 막는다.
|
||||||
const {data, isLoading, isError, error} = useListSites(
|
const {data, isLoading, isError, error, refetch} = useListSites(
|
||||||
{page, size},
|
{page, size, search: search || undefined, category: category ?? undefined},
|
||||||
{query: {placeholderData: keepPreviousData, enabled: role === UserRole.DEVELOPER}},
|
{query: {placeholderData: keepPreviousData, enabled: role === UserRole.DEVELOPER}},
|
||||||
);
|
);
|
||||||
|
|
||||||
// RequireAuth 와 같은 이유 — 복구가 끝나기 전에 판단하면 새로고침마다 리다이렉트가 한 번 번쩍인다.
|
// 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 (isRestoring) return null;
|
||||||
if (role !== UserRole.DEVELOPER) return <Navigate to="/sites" replace />;
|
if (role !== UserRole.DEVELOPER) return <Navigate to="/sites" replace />;
|
||||||
|
|
||||||
@@ -56,7 +91,55 @@ export function OpsSitesPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell>
|
<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 && (
|
{isLoading && (
|
||||||
<div className="flex items-center justify-center py-20 text-muted-foreground">
|
<div className="flex items-center justify-center py-20 text-muted-foreground">
|
||||||
<Loader2 className="size-5 animate-spin" />
|
<Loader2 className="size-5 animate-spin" />
|
||||||
@@ -95,21 +178,47 @@ export function OpsSitesPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{url ? (
|
<div className="flex shrink-0 items-center gap-1.5">
|
||||||
<a
|
<Link
|
||||||
href={url}
|
to={`/builder?placeId=${row.place_id}`}
|
||||||
target="_blank"
|
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"
|
||||||
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" />
|
<Pencil className="size-3.5" />
|
||||||
열기
|
빌더
|
||||||
</a>
|
</Link>
|
||||||
) : (
|
<Link
|
||||||
<span className="shrink-0 text-xs text-muted-foreground">
|
to={`/blog?placeId=${row.place_id}`}
|
||||||
{row.domain ? `주소 예약됨 · ${row.domain}` : '주소 미정'}
|
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"
|
||||||
</span>
|
>
|
||||||
)}
|
<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>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -6,12 +6,10 @@ import {useMemo, useState} from 'react';
|
|||||||
import {Link, useNavigate} from 'react-router';
|
import {Link, useNavigate} from 'react-router';
|
||||||
import {
|
import {
|
||||||
Building2,
|
Building2,
|
||||||
CalendarClock,
|
|
||||||
Coffee,
|
Coffee,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
Loader2,
|
Loader2,
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
Newspaper,
|
|
||||||
Pencil,
|
Pencil,
|
||||||
Plus,
|
Plus,
|
||||||
Search,
|
Search,
|
||||||
@@ -394,32 +392,6 @@ export function SitesPage() {
|
|||||||
<Pencil className="size-3.5" />
|
<Pencil className="size-3.5" />
|
||||||
디자인·컨텐츠 관리
|
디자인·컨텐츠 관리
|
||||||
</button>
|
</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" />
|
<div className="my-1 border-t border-border" />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -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 ?? ''));
|
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);
|
const dir = join(siteDir, MEDIA_DIR);
|
||||||
// 절대 주소로 바꾼다.
|
// 절대 주소로 바꾼다.
|
||||||
@@ -275,6 +283,7 @@ async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
|||||||
if (hit) {
|
if (hit) {
|
||||||
wanted.add(hit);
|
wanted.add(hit);
|
||||||
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${hit}`);
|
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${hit}`);
|
||||||
|
stats.cached += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,6 +306,7 @@ async function mirrorMedia(payload: SitePayload, siteDir: string) {
|
|||||||
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${name}`);
|
item.url = joinUrl(publicBase, `${MEDIA_DIR}/${name}`);
|
||||||
fetched += 1;
|
fetched += 1;
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
|
stats.failed += 1;
|
||||||
console.warn(` ! 사진을 못 받았습니다(원래 주소를 씁니다): ${origin} — ${ex}`);
|
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 (!wanted.has(name)) rmSync(join(dir, name), {force: true});
|
||||||
}
|
}
|
||||||
if (fetched > 0) console.log(` 사진 ${fetched}장을 내려받았습니다 (총 ${wanted.size}장)`);
|
if (fetched > 0) console.log(` 사진 ${fetched}장을 내려받았습니다 (총 ${wanted.size}장)`);
|
||||||
|
stats.fetched = fetched;
|
||||||
|
return stats;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 이 슬러그·버전이 실제로 구워지는 자리 — `out/versions/<slug>/<version>/`. */
|
/** 이 슬러그·버전이 실제로 구워지는 자리 — `out/versions/<slug>/<version>/`. */
|
||||||
@@ -573,6 +585,7 @@ interface RenderReport {
|
|||||||
/** 절대규칙 3 위반 목록. */
|
/** 절대규칙 3 위반 목록. */
|
||||||
mismatches: string[];
|
mismatches: string[];
|
||||||
error: string | null;
|
error: string | null;
|
||||||
|
media?: MediaMirrorStats;
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeReport(payloadFile: string, report: RenderReport) {
|
function writeReport(payloadFile: string, report: RenderReport) {
|
||||||
@@ -922,7 +935,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
await mirrorMedia(entry.payload, stagingDir);
|
const media = await mirrorMedia(entry.payload, stagingDir);
|
||||||
const result = prerenderSite(entry.payload, args.out, assets, referenced);
|
const result = prerenderSite(entry.payload, args.out, assets, referenced);
|
||||||
const payload = result.payload;
|
const payload = result.payload;
|
||||||
origin = origin || payload.site.origin;
|
origin = origin || payload.site.origin;
|
||||||
@@ -955,6 +968,7 @@ async function main() {
|
|||||||
jsonld: result.jsonld,
|
jsonld: result.jsonld,
|
||||||
mismatches: [],
|
mismatches: [],
|
||||||
error: null,
|
error: null,
|
||||||
|
media,
|
||||||
};
|
};
|
||||||
writeFileSync(savedReportPath, JSON.stringify({...report, origin: payload.site.origin}));
|
writeFileSync(savedReportPath, JSON.stringify({...report, origin: payload.site.origin}));
|
||||||
writeReport(entry.file, report);
|
writeReport(entry.file, report);
|
||||||
|
|||||||
Reference in new issue
Block a user