Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
820a2e9e35 | ||
|
|
f2087aad5e | ||
|
|
0f7d22750f | ||
|
|
3f47d5ecd2 | ||
|
|
9773bc0496 | ||
|
|
f0c4d5f413 | ||
|
|
6b9e01d876 | ||
|
|
a1a416ca4a | ||
|
|
7425cb409e | ||
|
|
93bd5435ac | ||
|
|
3b4c5c98bc | ||
|
|
2824dedd42 |
No files matched your search
@@ -79,6 +79,14 @@ PUBLIC_WEB_BASE_URL=http://localhost
|
|||||||
# SITE_PUBLIC_HOST=web4ai.o2osolution.ai
|
# SITE_PUBLIC_HOST=web4ai.o2osolution.ai
|
||||||
# 비우면 색인 통보를 건너뛴다(발행은 정상)
|
# 비우면 색인 통보를 건너뛴다(발행은 정상)
|
||||||
INDEXNOW_KEY=
|
INDEXNOW_KEY=
|
||||||
|
|
||||||
|
# Google Search Console — 최초 소유권/서비스 계정 권한 설정 후 켠다 (docs/SEARCH_CONSOLE.md).
|
||||||
|
GSC_ENABLED=0
|
||||||
|
GSC_PROPERTY_URL=
|
||||||
|
GSC_CREDENTIALS_FILE=
|
||||||
|
GSC_CREDENTIALS_HOST_FILE=
|
||||||
|
GSC_ALERT_DAYS=7
|
||||||
|
GSC_ALERT_WEBHOOK_URL=
|
||||||
# 비우면 로컬 발행만 한다
|
# 비우면 로컬 발행만 한다
|
||||||
AZURE_STORAGE_CONNECTION_STRING=
|
AZURE_STORAGE_CONNECTION_STRING=
|
||||||
AZURE_STORAGE_CONTAINER=
|
AZURE_STORAGE_CONTAINER=
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
# AGENTS.md — 이 레포에서 작업하기 전에
|
# AGENTS.md — 이 레포에서 작업하기 전에
|
||||||
|
|
||||||
|
> 2026-09-15 발행 버전 전환: [docs/PUBLISH_VERSION.md](docs/PUBLISH_VERSION.md)가
|
||||||
|
> 아래의 상시 프리렌더·재굽기·자산 주소 교체 절차를 대체한다. 목업은 변경하지 않는다.
|
||||||
|
|
||||||
에이전트와 신규 합류자가 **먼저 읽는 파일**이다. 여기에는 *밟기 쉬운 함정*과 *규약*만 둔다.
|
에이전트와 신규 합류자가 **먼저 읽는 파일**이다. 여기에는 *밟기 쉬운 함정*과 *규약*만 둔다.
|
||||||
설명은 각 문서가 단일 출처다 — 여기로 복사하지 말고 링크한다.
|
설명은 각 문서가 단일 출처다 — 여기로 복사하지 말고 링크한다.
|
||||||
|
|
||||||
@@ -34,7 +37,48 @@
|
|||||||
→ **`out/assets` 에서 파일을 지우는 코드는 `out/s/**` 의 HTML 이 참조하는 것을 먼저 뺀다**
|
→ **`out/assets` 에서 파일을 지우는 코드는 `out/s/**` 의 HTML 이 참조하는 것을 먼저 뺀다**
|
||||||
(`prerender.ts` `referencedAssets`). 보관 기간으로는 못 막는다 — 기간이 지나면 같은 일이 난다.
|
(`prerender.ts` `referencedAssets`). 보관 기간으로는 못 막는다 — 기간이 지나면 같은 일이 난다.
|
||||||
→ 목업을 다루는 작업은 `out/s/` 를 먼저 열어 **payload 가 없는 디렉토리가 무엇인지** 본다.
|
→ 목업을 다루는 작업은 `out/s/` 를 먼저 열어 **payload 가 없는 디렉토리가 무엇인지** 본다.
|
||||||
|
→ ★ **`stay` 는 프리렌더가 굽지 않는다** (`prerender.ts` `PROTECTED_SLUGS`, 기본 `stay` ·
|
||||||
|
`PRERENDER_PROTECTED_SLUGS` 로 덮어쓴다). "payload 가 없으면 안 굽는다"
|
||||||
|
는 보호가 못 된다 — **payload 가 생기는 순간** 덮인다. 실측(2026-09-15): 누가 빌더에서
|
||||||
|
슬러그 `stay` 로 발행해 `payloads/stay.json` 이 생기자 프리렌더가 `/s/stay` 를 그 payload 로
|
||||||
|
구워 목업을 통째로 날렸다(캐치프레이즈 100개·미니 플레이어·날씨 문구·주입분 전부).
|
||||||
|
그 payload 는 `solution/site/payloads-mockup-hold/` 로 옮긴다 — 지우면 재발행 때 또 온다.
|
||||||
|
|
||||||
|
- **★ 굽기는 네트워크를 탄다 — 사진을 내려받는다** (`prerender.ts` `mirrorMedia`).
|
||||||
|
`payload.media[].url` 이 남의 도메인이면 `out/s/<slug>/img/<주소해시>.<확장자>` 로 받아 놓고
|
||||||
|
payload 의 주소를 **우리 오리진 절대주소**로 바꾼 뒤에 굽는다. 이유는 캔버스다 —
|
||||||
|
수집처(`*.pstatic.net` · `tong.visitkorea.or.kr`)가 `Access-Control-Allow-Origin` 을 안 줘서
|
||||||
|
그 사진을 캔버스에 그리면 오염돼 `toBlob` 이 막히고, **엽서 쓰기의 저장·공유가 모든 발행
|
||||||
|
사이트에서 죽어 있었다**(실측 2026-09-15). 클라이언트에서는 못 넘는다.
|
||||||
|
→ 못 받은 사진은 **원래 주소를 그대로 쓴다**(사진이 사라지는 것보다 낫다). 로그에 한 줄 남는다.
|
||||||
|
→ 주소가 그대로면 파일명도 그대로라 **다시 구워도 내려받지 않는다.** 처음 한 번만 느리다.
|
||||||
|
→ ★ **이미 나가 있는 사이트는 그대로 둔다.** 새 기능은 사장님이 **다시 발행할 때** 들어간다
|
||||||
|
(아래 항목). 그 사이를 메우는 건 **중계**다 — `/v1/image/relay?url=…`
|
||||||
|
(`backend/router/v1/media/relay.py`). 캔버스가 CORS 로 사진을 못 받으면 같은 오리진의
|
||||||
|
이 주소로 한 번 더 받아 본다(`site/src/lib/postcard-canvas.ts` `loadImage`).
|
||||||
|
열린 프록시가 아니다 — https · 호스트 allowlist · 이미지 타입 · 8MB · 리다이렉트 후
|
||||||
|
호스트 재검사. **호스트를 늘릴 때는 "우리가 이미 그 사진을 화면에 싣고 있는가" 를 먼저 본다.**
|
||||||
|
→ `originUrl` · `sourceType` 은 손대지 않는다 — 재게시 권리(DECISIONS 1-2)가 "불가" 로
|
||||||
|
결론 나면 `sourceType = CRAWL` 을 빼는 그 대응이 그대로 먹어야 한다.
|
||||||
|
- **★★ 배포해도 기존 사이트를 다시 굽지 않는다 — 자산 주소만 갈아 끼운다.**
|
||||||
|
(2026-09-15 대표 지시: "전체 재굽기 할 필요가 없어, 사장님이 재발행하면 끝인데 /
|
||||||
|
css js만 안 깨지게 하란 말이야")
|
||||||
|
예전에는 `solution-prerender` 가 뜰 때마다 payload 를 **전부 다시 구웠다.** 그러면 렌더러를
|
||||||
|
한 줄 고칠 때마다 이미 나가 있는 사이트의 HTML 이 통째로 바뀐다 — 사장님은 발행한 적이
|
||||||
|
없는데 내용이 달라지고, 구글이 다시 읽어 가는 값도 달라진다.
|
||||||
|
지금 기동이 하는 일은 `prerender.js --refresh-assets` 하나다
|
||||||
|
(`watch-payloads.mjs` `refreshAssets` → `prerender.ts` `refreshBakedAssets`):
|
||||||
|
→ 구워진 `index.html` 안의 `assets/index-<해시>.css|js` **파일명만** 새 번들로 바꾼다.
|
||||||
|
내용·구조·payload 는 손대지 않는다. 접두사(`/assets` · `/sites/assets`)도 그대로 둔다.
|
||||||
|
→ **한 번도 안 구워진 payload 만** 굽는다(볼륨이 비었거나 감시가 꺼진 새 발행).
|
||||||
|
→ ★ **payload 가 없는 디렉토리는 건드리지 않는다**(목업 `stay3` · `*.old`, 그리고
|
||||||
|
`PROTECTED_SLUGS`). 손으로 만든 유일본에 최신 번들을 물렸다가 깨지면 되돌릴 수 없다 —
|
||||||
|
그쪽 번들 교체는 사람이 한다(mockup/README "번들만 갈아 끼운다").
|
||||||
|
대상은 `--payload-dir` 에 `<슬러그>.json` 이 있는 사이트뿐이다.
|
||||||
|
★ 그래서 **정적 HTML 은 옛 렌더러의 것이고 스크립트는 새 렌더러**다. 어긋나면 리액트가
|
||||||
|
그 자리에서 다시 그리므로 손님 화면은 새것이지만, **크롤러가 읽는 HTML 은 옛것**이다.
|
||||||
|
둘을 맞추는 방법은 재발행뿐이고 그건 사장님이 누른다. 급하면 `republish_all.py` 지만
|
||||||
|
**먼저 묻는다** — 전 사이트의 발행일이 한꺼번에 움직이는 일이다.
|
||||||
- **번들 파일명은 콘텐츠 해시다.** HTML 은 `/assets/index-DvNTmLhy.css` 를 **루트 절대경로**로
|
- **번들 파일명은 콘텐츠 해시다.** HTML 은 `/assets/index-DvNTmLhy.css` 를 **루트 절대경로**로
|
||||||
가리킨다. 경로는 프리렌더가 `dist/client/.vite/manifest.json` 에서 읽어 박는다
|
가리킨다. 경로는 프리렌더가 `dist/client/.vite/manifest.json` 에서 읽어 박는다
|
||||||
(`prerender.ts:160`). 렌더러 CSS 를 고치면 이름이 바뀐다.
|
(`prerender.ts:160`). 렌더러 CSS 를 고치면 이름이 바뀐다.
|
||||||
@@ -50,15 +94,19 @@
|
|||||||
없고**, 그때 디스크에 있던 기존 자산이 전부 "대장에 없음" 으로 분류돼 한꺼번에 삭제됐다.
|
없고**, 그때 디스크에 있던 기존 자산이 전부 "대장에 없음" 으로 분류돼 한꺼번에 삭제됐다.
|
||||||
옛 자산을 남기려고 만든 코드가 첫 실행에서 정확히 반대로 동작했다.
|
옛 자산을 남기려고 만든 코드가 첫 실행에서 정확히 반대로 동작했다.
|
||||||
→ 자산을 지우는 코드를 손볼 때는 **"기록이 없다"와 "만료됐다"를 절대 같이 묶지 않는다.**
|
→ 자산을 지우는 코드를 손볼 때는 **"기록이 없다"와 "만료됐다"를 절대 같이 묶지 않는다.**
|
||||||
→ 이미 끊겼다면 복구는 `docker compose restart solution-prerender` (기동하며 전체 재굽기).
|
→ 이미 끊겼다면 복구는 `docker compose restart solution-prerender` — 기동이 공용 자산을
|
||||||
|
다시 깔고 구워진 HTML 의 자산 주소를 맞춘다(전체 재굽기가 아니다, 위 ★★ 항목).
|
||||||
- **★ 사이트를 굽는 컨테이너는 `solution-prerender` 다.** `solution-frontend` 는 **개발용**이라
|
- **★ 사이트를 굽는 컨테이너는 `solution-prerender` 다.** `solution-frontend` 는 **개발용**이라
|
||||||
운영에서는 아예 뜨지 않는다(`docker-compose.yml` `profiles: ["dev"]`). 이름이 비슷해서
|
운영에서는 아예 뜨지 않는다(`docker-compose.yml` `profiles: ["dev"]`). 이름이 비슷해서
|
||||||
`restart solution-frontend` 를 치면 **아무 일도 안 일어나는데 명령은 성공한다** —
|
`restart solution-frontend` 를 치면 **아무 일도 안 일어나는데 명령은 성공한다** —
|
||||||
재굽기를 했다고 믿고 넘어가게 된다. 실제로 그렇게 복구가 한 번 헛돌았다(2026-09-07).
|
재굽기를 했다고 믿고 넘어가게 된다. 실제로 그렇게 복구가 한 번 헛돌았다(2026-09-07).
|
||||||
- **★ 프론트(`solution/site`)를 배포하면 반드시 전체 재굽기 + 전체 재업로드.**
|
- **★ 프론트(`solution/site`)를 고쳐도 기존 사이트의 내용은 안 바뀐다.** 기동은 자산 주소만
|
||||||
`azure_static.publish(slug)` 는 공용 자산 + `s/<slug>` 만 올린다 —
|
맞춘다(위 ★★ 항목) — 새 렌더러로 다시 그려지는 건 **그 사장님이 다시 발행할 때**다.
|
||||||
**렌더러를 고쳐도 다른 사이트에는 반영되지 않는다.**
|
Azure 를 쓰는 경우엔 한 겹 더 있다: `azure_static.publish(slug)` 는 공용 자산 + `s/<slug>` 만
|
||||||
→ `docker compose restart solution-prerender` 후 `python scripts/republish_all.py`
|
올린다 — 다른 사이트의 블롭은 그대로다.
|
||||||
|
→ 전 사이트를 한꺼번에 새 렌더러로 맞춰야 할 일이 생기면
|
||||||
|
`docker compose restart solution-prerender` 후 `python scripts/republish_all.py` 인데,
|
||||||
|
**먼저 묻는다**(발행일이 전부 움직인다).
|
||||||
- **발행 호스트는 두 곳에 있고 같아야 한다.** 백엔드 `SITE_PUBLIC_HOST`(기본 `web4ai.o2osolution.ai`,
|
- **발행 호스트는 두 곳에 있고 같아야 한다.** 백엔드 `SITE_PUBLIC_HOST`(기본 `web4ai.o2osolution.ai`,
|
||||||
`site_payload.py`) ↔ 프론트 `VITE_PUBLISH_HOST`. canonical·og:url·sitemap·IndexNow 가 전부
|
`site_payload.py`) ↔ 프론트 `VITE_PUBLISH_HOST`. canonical·og:url·sitemap·IndexNow 가 전부
|
||||||
이 값을 쓴다. 그리고 **`origin` 은 payload JSON 에 구워진다** — 호스트를 바꾸면 프리렌더
|
이 값을 쓴다. 그리고 **`origin` 은 payload JSON 에 구워진다** — 호스트를 바꾸면 프리렌더
|
||||||
|
|||||||
@@ -1,127 +1,40 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# 배포 — 코드를 당기고, 지정한 서비스만 다시 빌드해 갈아끼운다.
|
# 서버 변경과 꺼진 admin을 보존한다. 렌더러 배포도 기존 사이트를 재굽지 않는다.
|
||||||
#
|
|
||||||
# ./deploy.sh 전체
|
|
||||||
# ./deploy.sh solution-backend 그 서비스만
|
|
||||||
# ./deploy.sh solution-backend solution-worker 여럿
|
|
||||||
#
|
|
||||||
# 서비스명 대신 컨테이너명(o2o-web4ai-solution-backend)으로 불러도 받는다.
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "$(dirname "$0")"
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
PREFIX=o2o-web4ai
|
|
||||||
# api·worker·api-admin 은 이미지 한 벌(o2o-web4ai-backend)을 나눠 쓴다.
|
|
||||||
BACKEND_SVCS=(solution-backend solution-worker admin-backend)
|
|
||||||
BRANCH=${DEPLOY_BRANCH:-main}
|
|
||||||
|
|
||||||
PULL=1
|
PULL=1
|
||||||
ONLY=0
|
ONLY=0
|
||||||
TARGETS=()
|
TARGETS=()
|
||||||
|
for arg in "$@"; do
|
||||||
usage() {
|
case "$arg" in
|
||||||
cat <<'USAGE'
|
|
||||||
사용법: ./deploy.sh [옵션] [서비스...]
|
|
||||||
|
|
||||||
옵션
|
|
||||||
--no-pull 코드를 당기지 않는다(디스크에 있는 코드 그대로 빌드)
|
|
||||||
--only 백엔드 형제 서비스를 함께 갈아끼우지 않는다 (아래 ★ 참고)
|
|
||||||
-h, --help
|
|
||||||
|
|
||||||
환경변수
|
|
||||||
DEPLOY_BRANCH 기본 main. 다른 브랜치를 배포할 때만 쓴다
|
|
||||||
|
|
||||||
서비스: solution-backend · solution-worker · solution-prerender · solution-site
|
|
||||||
admin-backend · admin-frontend (프로필 admin, 기본 기동에서 빠져 있다)
|
|
||||||
solution-frontend (프로필 dev, 로컬 HMR 전용 — 운영에서 띄우지 않는다)
|
|
||||||
o2o-web4ai-solution-backend 처럼 컨테이너명으로 적어도 된다
|
|
||||||
|
|
||||||
★ solution-backend·solution-worker·admin-backend 는 이미지가 한 벌이다. 하나를 빌드하면 나머지도 새 이미지로
|
|
||||||
갈아끼워야 한다 — 안 그러면 옛 코드로 도는 컨테이너가 남는데, 셋 다 "살아 있음" 이라
|
|
||||||
화면상으로는 배포가 끝난 것처럼 보인다. --only 는 그걸 알고 건너뛸 때만 쓴다.
|
|
||||||
USAGE
|
|
||||||
}
|
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case "$1" in
|
|
||||||
--no-pull) PULL=0 ;;
|
--no-pull) PULL=0 ;;
|
||||||
--only) ONLY=1 ;;
|
--only) ONLY=1 ;;
|
||||||
-h|--help) usage; exit 0 ;;
|
-h|--help) echo "사용법: ./deploy.sh [--no-pull] [--only] [서비스...]"; exit 0 ;;
|
||||||
-*) echo "모르는 옵션: $1" >&2; usage >&2; exit 2 ;;
|
-*) echo "모르는 옵션: $arg" >&2; exit 2 ;;
|
||||||
*) TARGETS+=("${1#"$PREFIX"-}") ;; # 컨테이너명으로 불러도 받는다
|
*) TARGETS+=("${arg#o2o-web4ai-}") ;;
|
||||||
esac
|
esac
|
||||||
shift
|
|
||||||
done
|
done
|
||||||
|
|
||||||
ALL_SVCS=$(docker compose config --services)
|
|
||||||
for t in ${TARGETS+"${TARGETS[@]}"}; do
|
|
||||||
grep -qx "$t" <<<"$ALL_SVCS" || {
|
|
||||||
echo "그런 서비스가 없다: $t" >&2
|
|
||||||
echo "있는 것: $(tr '\n' ' ' <<<"$ALL_SVCS")" >&2
|
|
||||||
exit 2
|
|
||||||
}
|
|
||||||
done
|
|
||||||
|
|
||||||
# ── 코드 ────────────────────────────────────────────────────────────
|
|
||||||
# 배포 서버의 작업트리는 main 의 **사본**이지 작업 공간이 아니다. 그래서 머지(pull)가 아니라
|
|
||||||
# origin/$BRANCH 로 하드 리셋한다 — 밖에서 force-push 가 나도 --ff-only 로 막히지 않고,
|
|
||||||
# 서버에서 누가 손댄 흔적이 다음 배포까지 살아남지 않는다.
|
|
||||||
#
|
|
||||||
# ★ fetch 가 실패하면 **리셋하지 않는다.** 이 서버엔 gitea 자격증명이 없어 fetch 가 죽는데,
|
|
||||||
# 그 상태의 origin/$BRANCH 는 마지막으로 fetch 된 낡은 ref 다.
|
|
||||||
# 실측(2026-09-01 킹서버): HEAD=9b4fe40 인데 origin/main=4871e50 — 믿고 리셋하면 한 커밋
|
|
||||||
# 롤백된다. 그러고도 빌드는 성공하고 컨테이너는 뜬다. 조용히 틀리는 종류다.
|
|
||||||
#
|
|
||||||
# ★ git clean 은 하지 않는다. .env 와 nginx/site.conf 는 추적되지 않는 파일이고 서버마다
|
|
||||||
# 다르다 — reset --hard 는 이 둘을 건드리지 않지만 clean 은 지운다.
|
|
||||||
if [ "$PULL" = 1 ]; then
|
if [ "$PULL" = 1 ]; then
|
||||||
echo "▶ git fetch origin $BRANCH"
|
git diff --quiet && git diff --cached --quiet || { echo "서버 변경을 먼저 정리하세요" >&2; exit 1; }
|
||||||
if git fetch --prune origin "$BRANCH" 2>&1; then
|
git pull --ff-only origin "${DEPLOY_BRANCH:-main}"
|
||||||
DIRTY=$(git status --porcelain)
|
|
||||||
if [ -n "$DIRTY" ]; then
|
|
||||||
echo " ! 작업트리 변경을 버린다:"
|
|
||||||
sed 's/^/ /' <<<"$DIRTY"
|
|
||||||
fi
|
|
||||||
echo "▶ git reset --hard origin/$BRANCH"
|
|
||||||
git reset --hard "origin/$BRANCH"
|
|
||||||
else
|
|
||||||
echo " ! fetch 실패 — 리셋을 건너뛰고 디스크에 있는 코드 그대로 간다." >&2
|
|
||||||
echo " origin/$BRANCH 가 낡았을 수 있어 그걸로 리셋하면 배포가 조용히 롤백된다." >&2
|
|
||||||
echo " (밖에서 밀어넣었으면 이대로 두면 되고, 자동화하려면 gitea 배포키를 건다)" >&2
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
echo "▶ 지금 코드: $(git log --oneline -1)"
|
[ ${#TARGETS[@]} -gt 0 ] || TARGETS=(solution-backend solution-worker solution-site)
|
||||||
|
RUNNING=$(docker compose ps --services --status running)
|
||||||
# ── 대상 정하기 ─────────────────────────────────────────────────────
|
if [ "$ONLY" = 0 ]; then
|
||||||
if [ ${#TARGETS[@]} -eq 0 ]; then
|
case " ${TARGETS[*]} " in
|
||||||
SVCS=() # 빈 인자 = compose 가 전부로 해석한다
|
*" solution-backend "*|*" solution-worker "*)
|
||||||
echo "▶ 대상: 전체"
|
TARGETS+=(solution-backend solution-worker)
|
||||||
else
|
if grep -qx admin-backend <<<"$RUNNING"; then TARGETS+=(admin-backend); fi ;;
|
||||||
SVCS=("${TARGETS[@]}")
|
esac
|
||||||
# 백엔드 하나를 건드리면 같은 이미지를 쓰는 형제도 함께 갈아끼운다.
|
|
||||||
if [ "$ONLY" = 0 ]; then
|
|
||||||
for t in "${TARGETS[@]}"; do
|
|
||||||
for b in "${BACKEND_SVCS[@]}"; do [ "$t" = "$b" ] || continue
|
|
||||||
for sib in "${BACKEND_SVCS[@]}"; do
|
|
||||||
printf '%s\n' "${SVCS[@]}" | grep -qx "$sib" || {
|
|
||||||
SVCS+=("$sib")
|
|
||||||
echo " + $sib — 같은 이미지를 쓴다(옛 코드로 남지 않게 함께 간다)"
|
|
||||||
}
|
|
||||||
done
|
|
||||||
done
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
echo "▶ 대상: ${SVCS[*]}"
|
|
||||||
fi
|
fi
|
||||||
|
SERVICES=()
|
||||||
# ── 빌드 · 교체 ─────────────────────────────────────────────────────
|
for target in "${TARGETS[@]}"; do
|
||||||
# build 절이 없는 서비스(node:24-alpine · nginx:alpine)는 build 가 조용히 건너뛴다.
|
case " ${SERVICES[*]-} " in *" $target "*) ;; *) SERVICES+=("$target");; esac
|
||||||
echo "▶ build"
|
done
|
||||||
docker compose build ${SVCS+"${SVCS[@]}"}
|
# site의 렌더러도 worker 이미지에 들어간다.
|
||||||
|
case " ${SERVICES[*]} " in
|
||||||
echo "▶ up -d"
|
*" solution-site "*) case " ${SERVICES[*]} " in *" solution-worker "*) ;; *) SERVICES+=(solution-worker);; esac ;;
|
||||||
docker compose up -d --force-recreate ${SVCS+"${SVCS[@]}"}
|
esac
|
||||||
|
docker compose build "${SERVICES[@]}"
|
||||||
echo
|
docker compose up -d --no-deps --force-recreate "${SERVICES[@]}"
|
||||||
docker compose ps
|
docker compose ps
|
||||||
echo
|
|
||||||
echo "로그: ./log.sh"
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 선택 연동. 키 파일은 저장소 밖에 두고 기존 API 스케줄러에만 읽기 전용으로 전달한다.
|
||||||
|
# docker compose -f docker-compose.yml -f docker-compose.search-console.yml up -d solution-backend
|
||||||
|
services:
|
||||||
|
solution-backend:
|
||||||
|
environment:
|
||||||
|
GSC_CREDENTIALS_FILE: /run/secrets/search-console.json
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: ${GSC_CREDENTIALS_HOST_FILE:?Search Console 키 파일 절대경로 필요}
|
||||||
|
target: /run/secrets/search-console.json
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
+29
-58
@@ -28,8 +28,12 @@ x-common-env: &common-env
|
|||||||
# ★ 기본값은 localhost 다. 운영 도메인을 기본으로 두면 .env 를 안 채운 로컬 빌드가
|
# ★ 기본값은 localhost 다. 운영 도메인을 기본으로 두면 .env 를 안 채운 로컬 빌드가
|
||||||
# 조용히 운영 주소를 번들에 굽는다(실측 2026-09-03: 로컬 링크가 킹서버로 갔다).
|
# 조용히 운영 주소를 번들에 굽는다(실측 2026-09-03: 로컬 링크가 킹서버로 갔다).
|
||||||
SITE_PUBLIC_HOST: ${SITE_PUBLIC_HOST:-localhost}
|
SITE_PUBLIC_HOST: ${SITE_PUBLIC_HOST:-localhost}
|
||||||
SITE_PAYLOAD_DIR: /app/out/payloads
|
# ★ 렌더러(solution/site/scripts/prerender.ts)가 songs·out 디렉토리를 **자기 파일 위치
|
||||||
SITE_OUTPUT_DIR: /app/out/sites
|
# 기준 상대경로**로 찾는다(SITE_ROOT = dist/prerender/../..) — 워커 컨테이너 안에서 그
|
||||||
|
# 렌더러를 직접 띄우므로(render_service.py) 세 디렉토리가 실제 설치 자리
|
||||||
|
# (/app/solution/site/) 아래 나란히 있어야 한다. 아래 볼륨 마운트와 짝이 맞아야 한다.
|
||||||
|
SITE_PAYLOAD_DIR: /app/solution/site/payloads
|
||||||
|
SITE_OUTPUT_DIR: /app/solution/site/out
|
||||||
# ★ 프리렌더와 같은 값이어야 한다. 어긋나면 색인 통보가 403 이다.
|
# ★ 프리렌더와 같은 값이어야 한다. 어긋나면 색인 통보가 403 이다.
|
||||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
||||||
|
|
||||||
@@ -48,10 +52,10 @@ services:
|
|||||||
# ★ 크론은 이 컨테이너에서만 돈다. 프로세스가 여럿이면 같은 시각에 중복 실행된다.
|
# ★ 크론은 이 컨테이너에서만 돈다. 프로세스가 여럿이면 같은 시각에 중복 실행된다.
|
||||||
SCHEDULER_ENABLED: "1"
|
SCHEDULER_ENABLED: "1"
|
||||||
volumes:
|
volumes:
|
||||||
- ./solution/site/payloads:/app/out/payloads
|
- ./solution/site/payloads:/app/solution/site/payloads
|
||||||
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 프리렌더가
|
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 워커가 렌더러를
|
||||||
# 사이트 디렉토리로 복사한다(services/song_service · site/scripts/prerender.ts).
|
# 돌릴 때 사이트 디렉토리로 복사된다(services/song_service · site/scripts/prerender.ts).
|
||||||
- ./solution/site/songs:/app/out/songs
|
- ./solution/site/songs:/app/solution/site/songs
|
||||||
# ★ 스키마 마이그레이션 SQL. 이미지에 굽지 않고 마운트한다 — 파일이 자주 늘고,
|
# ★ 스키마 마이그레이션 SQL. 이미지에 굽지 않고 마운트한다 — 파일이 자주 늘고,
|
||||||
# 이미 세운 DB 를 따라오게 하는 것이 목적이라 코드 배포와 별개로 돌 수 있어야 한다.
|
# 이미 세운 DB 를 따라오게 하는 것이 목적이라 코드 배포와 별개로 돌 수 있어야 한다.
|
||||||
- ./postgres-init:/app/postgres-init:ro
|
- ./postgres-init:/app/postgres-init:ro
|
||||||
@@ -64,13 +68,17 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options: { max-size: "10m", max-file: "5" }
|
options: { max-size: "10m", max-file: "5" }
|
||||||
|
|
||||||
|
# ★ BUILD·ROLLBACK 잡이 렌더러(solution/site)를 subprocess 로 직접 돌린다
|
||||||
|
# (services/render_service.py) — 예전에 solution-prerender 컨테이너가 하던 일이다.
|
||||||
|
# 그래서 이 서비스만 **다른 이미지**(Dockerfile.worker, Node 런타임 + 컴파일된 렌더러
|
||||||
|
# 포함)를 쓴다. solution-backend·admin-backend 는 그 Node 를 쓸 일이 없다.
|
||||||
solution-worker:
|
solution-worker:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: solution/backend/Dockerfile
|
dockerfile: solution/backend/Dockerfile.worker
|
||||||
image: o2o-web4ai-backend
|
image: o2o-web4ai-worker
|
||||||
container_name: o2o-web4ai-solution-worker
|
container_name: o2o-web4ai-solution-worker
|
||||||
command: ["python", "worker_main.py"]
|
command: ["sh", "-c", "node /app/solution/site/dist/prerender/prerender.js --seed-assets --out=/app/solution/site/out && exec python worker_main.py"]
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
environment:
|
environment:
|
||||||
@@ -79,15 +87,20 @@ services:
|
|||||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1}
|
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1}
|
||||||
JOB_DEADLINE_SEC: ${JOB_DEADLINE_SEC:-900}
|
JOB_DEADLINE_SEC: ${JOB_DEADLINE_SEC:-900}
|
||||||
JOB_LEASE_SEC: ${JOB_LEASE_SEC:-120}
|
JOB_LEASE_SEC: ${JOB_LEASE_SEC:-120}
|
||||||
|
# 렌더러 subprocess 가 굽는 동안 기다리는 시간(사진 내려받기 포함). BUILD 의
|
||||||
|
# job_deadline_sec 보다 짧아야 한다 — 안 그러면 잡 전체가 먼저 타임아웃된다.
|
||||||
|
RENDER_TIMEOUT_SEC: ${RENDER_TIMEOUT_SEC:-180}
|
||||||
# 이미지의 HEALTHCHECK 는 API 용(HTTP :9800)이다. 워커는 포트가 없어 그대로 두면 늘 unhealthy 다.
|
# 이미지의 HEALTHCHECK 는 API 용(HTTP :9800)이다. 워커는 포트가 없어 그대로 두면 늘 unhealthy 다.
|
||||||
healthcheck:
|
healthcheck:
|
||||||
disable: true
|
disable: true
|
||||||
volumes:
|
volumes:
|
||||||
- ./solution/site/payloads:/app/out/payloads
|
- ./solution/site/payloads:/app/solution/site/payloads
|
||||||
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 프리렌더가
|
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 렌더러가
|
||||||
# 사이트 디렉토리로 복사한다(services/song_service · site/scripts/prerender.ts).
|
# 사이트 디렉토리로 복사한다(services/song_service · site/scripts/prerender.ts).
|
||||||
- ./solution/site/songs:/app/out/songs
|
- ./solution/site/songs:/app/solution/site/songs
|
||||||
- site-out:/app/out/sites:ro
|
# ★ 이제 이 컨테이너가 굽는 쪽이다 — 읽기전용이 아니다(예전 solution-prerender 가
|
||||||
|
# 쓰던 자리를 그대로 이어받는다).
|
||||||
|
- site-out:/app/solution/site/out
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
stop_grace_period: 300s
|
stop_grace_period: 300s
|
||||||
@@ -124,10 +137,10 @@ services:
|
|||||||
start_period: 20s
|
start_period: 20s
|
||||||
retries: 3
|
retries: 3
|
||||||
volumes:
|
volumes:
|
||||||
- ./solution/site/payloads:/app/out/payloads
|
- ./solution/site/payloads:/app/solution/site/payloads
|
||||||
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 프리렌더가
|
# 노래 파일. payload 와 나란히 둔다 — 백엔드가 mp3 를 여기 떨구면 프리렌더가
|
||||||
# 사이트 디렉토리로 복사한다(services/song_service · site/scripts/prerender.ts).
|
# 사이트 디렉토리로 복사한다(services/song_service · site/scripts/prerender.ts).
|
||||||
- ./solution/site/songs:/app/out/songs
|
- ./solution/site/songs:/app/solution/site/songs
|
||||||
ports:
|
ports:
|
||||||
# ★ 내부망에만 연다. 0.0.0.0 으로 열면 API 를 가른 의미가 없다.
|
# ★ 내부망에만 연다. 0.0.0.0 으로 열면 API 를 가른 의미가 없다.
|
||||||
- "${ADMIN_API_BIND:-127.0.0.1}:${ADMIN_API_PORT_PUBLIC:-9801}:9801"
|
- "${ADMIN_API_BIND:-127.0.0.1}:${ADMIN_API_PORT_PUBLIC:-9801}:9801"
|
||||||
@@ -140,48 +153,6 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options: { max-size: "10m", max-file: "5" }
|
options: { max-size: "10m", max-file: "5" }
|
||||||
|
|
||||||
# 발행 사이트를 굽는다. **굽기만 한다** — 서빙은 solution-site(nginx)가 맡는다.
|
|
||||||
#
|
|
||||||
# ★ 사장님 앱 dev 서버는 여기서 빠졌다. 운영에 `vite dev` 를 띄우면 요청마다 트랜스파일하고
|
|
||||||
# 기동이 npm install 네트워크에 의존하고 /src 원본이 그대로 나간다. 번들은 solution-site
|
|
||||||
# 이미지가 굽는다(nginx/Dockerfile). 로컬에서 HMR 이 필요하면 `--profile dev`.
|
|
||||||
solution-prerender:
|
|
||||||
image: node:24-alpine
|
|
||||||
container_name: o2o-web4ai-solution-prerender
|
|
||||||
working_dir: /app
|
|
||||||
command:
|
|
||||||
- sh
|
|
||||||
- -c
|
|
||||||
- |
|
|
||||||
cd /app
|
|
||||||
# ★ `-d node_modules` 로 판단하면 안 된다. 익명 볼륨은 빈 디렉토리로 이미 존재해서
|
|
||||||
# 설치를 건너뛰고 `vite: not found`(exit 127)로 죽는다.
|
|
||||||
[ -x node_modules/.bin/vite ] || npm install
|
|
||||||
exec node solution/site/scripts/watch-payloads.mjs
|
|
||||||
environment:
|
|
||||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
|
||||||
# ★ 발행 호스트를 프론트 .env 에 따로 적지 않는다 — 루트 .env 의 SITE_PUBLIC_HOST 를
|
|
||||||
# 그대로 흘려보낸다. 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
|
|
||||||
VITE_PUBLISH_HOST: ${SITE_PUBLIC_HOST:-localhost}
|
|
||||||
volumes:
|
|
||||||
- ./package.json:/app/package.json
|
|
||||||
- ./package-lock.json:/app/package-lock.json
|
|
||||||
- ./tsconfig.base.json:/app/tsconfig.base.json
|
|
||||||
- ./solution:/app/solution
|
|
||||||
- ./admin:/app/admin
|
|
||||||
# ★ node_modules 는 컨테이너 것을 쓴다. 호스트가 macOS(arm64-darwin)라 그 안의
|
|
||||||
# rollup·esbuild 네이티브 바이너리를 리눅스 컨테이너가 못 쓴다.
|
|
||||||
- /app/node_modules
|
|
||||||
- /app/solution/site/node_modules
|
|
||||||
- /app/solution/frontend/node_modules
|
|
||||||
- /app/admin/frontend/node_modules
|
|
||||||
# ★ 산출물은 named volume. 호스트 경로면 재배포로 코드를 갈아엎는 순간 전 사이트가 404 다.
|
|
||||||
- site-out:/app/solution/site/out
|
|
||||||
restart: unless-stopped
|
|
||||||
logging:
|
|
||||||
driver: json-file
|
|
||||||
options: { max-size: "10m", max-file: "5" }
|
|
||||||
|
|
||||||
# 사장님 앱 dev 서버 + 발행본 정적서버(:3001). **로컬 전용**이다 — `--profile dev`.
|
# 사장님 앱 dev 서버 + 발행본 정적서버(:3001). **로컬 전용**이다 — `--profile dev`.
|
||||||
# 운영에서 이게 뜨면 안 된다(위 solution-prerender 주석).
|
# 운영에서 이게 뜨면 안 된다(위 solution-prerender 주석).
|
||||||
solution-frontend:
|
solution-frontend:
|
||||||
@@ -294,7 +265,7 @@ services:
|
|||||||
# 앞단 프록시를 세울 거면 여기서 포트만 옮기고 프록시가 이쪽을 가리키게 한다.
|
# 앞단 프록시를 세울 거면 여기서 포트만 옮기고 프록시가 이쪽을 가리키게 한다.
|
||||||
- "${SITE_HTTP_BIND:-0.0.0.0}:${SITE_HTTP_PORT:-80}:80"
|
- "${SITE_HTTP_BIND:-0.0.0.0}:${SITE_HTTP_PORT:-80}:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
- solution-prerender
|
- solution-backend
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
logging:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
# ARCHITECTURE
|
# ARCHITECTURE
|
||||||
|
|
||||||
|
> 2026-09-15: 현재 발행 실행·산출물 버전·배포는 [PUBLISH_VERSION.md](PUBLISH_VERSION.md).
|
||||||
|
> 아래의 별도 프리렌더 컨테이너·폴링·전체 재굽기 설명은 이전 구조다.
|
||||||
|
|
||||||
제품 판단은 [PRODUCT.md](PRODUCT.md), 배포 절차는 [DEPLOY.md](DEPLOY.md),
|
제품 판단은 [PRODUCT.md](PRODUCT.md), 배포 절차는 [DEPLOY.md](DEPLOY.md),
|
||||||
에이전트가 밟기 쉬운 함정 목록은 [AGENTS.md](../AGENTS.md). 여기는 **구조와 경계**만 다룬다.
|
에이전트가 밟기 쉬운 함정 목록은 [AGENTS.md](../AGENTS.md). 여기는 **구조와 경계**만 다룬다.
|
||||||
|
|
||||||
@@ -69,6 +72,10 @@ BUILD 잡 (worker) ─ services/build_service.py:99 run_build()
|
|||||||
|
|
||||||
## 3. 서빙 — 테스트 서버가 정적 파일을 직접 서빙한다
|
## 3. 서빙 — 테스트 서버가 정적 파일을 직접 서빙한다
|
||||||
|
|
||||||
|
Google 추적은 발행 잡 밖에서 실행한다. 기존 API 스케줄러가 발행 완료 DB를 감지해
|
||||||
|
사이트맵 제출·색인 조회·알림을 수행하고 `site_search_status`에 저장한다.
|
||||||
|
선택 설정/인증/재시도 경계는 [SEARCH_CONSOLE.md](SEARCH_CONSOLE.md)가 단일 출처다.
|
||||||
|
|
||||||
**결정 (2026-08-31).** 발행 사이트는 **서버 안에서 nginx 가 정적 파일로 서빙한다.**
|
**결정 (2026-08-31).** 발행 사이트는 **서버 안에서 nginx 가 정적 파일로 서빙한다.**
|
||||||
Azure Blob 업로드 경로(`azure_static.py`)는 코드에 있고 동작하지만 **지금은 켜지 않는다** —
|
Azure Blob 업로드 경로(`azure_static.py`)는 코드에 있고 동작하지만 **지금은 켜지 않는다** —
|
||||||
`AZURE_STORAGE_CONNECTION_STRING` 을 비워 두면 발행 잡이 업로드 단계를 건너뛴다.
|
`AZURE_STORAGE_CONNECTION_STRING` 을 비워 두면 발행 잡이 업로드 단계를 건너뛴다.
|
||||||
|
|||||||
+3
-1
@@ -7,6 +7,8 @@
|
|||||||
여기서는 그 앞뒤를 잇는다.
|
여기서는 그 앞뒤를 잇는다.
|
||||||
- 수집이 **무엇을 어디서 가져오는지**는 [COLLECTION_SEO_AEO_FLOW.md](COLLECTION_SEO_AEO_FLOW.md).
|
- 수집이 **무엇을 어디서 가져오는지**는 [COLLECTION_SEO_AEO_FLOW.md](COLLECTION_SEO_AEO_FLOW.md).
|
||||||
- 표를 고치는 절차는 [postgres-init/migrations/README.md](../postgres-init/migrations/README.md).
|
- 표를 고치는 절차는 [postgres-init/migrations/README.md](../postgres-init/migrations/README.md).
|
||||||
|
- Google 제출/색인 관측은 `site_search_status`의 별도 상태다. 발행 상태와 섞지 않는다.
|
||||||
|
컬럼 의미·조회·설정은 [SEARCH_CONSOLE.md](SEARCH_CONSOLE.md).
|
||||||
|
|
||||||
정의는 두 곳이고 **둘 다 최신이어야 한다** — ORM(`solution/backend/common/database/model/models.py`)
|
정의는 두 곳이고 **둘 다 최신이어야 한다** — ORM(`solution/backend/common/database/model/models.py`)
|
||||||
과 DDL(`postgres-init/init-data/init.sql` + `migrations/`). 컬럼 주석은 ORM 이 더 자세하다.
|
과 DDL(`postgres-init/init-data/init.sql` + `migrations/`). 컬럼 주석은 ORM 이 더 자세하다.
|
||||||
@@ -170,7 +172,7 @@ Gemini 가 쓰고, 곡은 Suno 가 붙인다.
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 WEATHER | Open-Meteo | — |
|
| 1 WEATHER | Open-Meteo | — |
|
||||||
| 2 FESTIVAL · 3 ATTRACTION · 4 RESTAURANT · 5 COURSE | TourAPI (좌표 반경) | — |
|
| 2 FESTIVAL · 3 ATTRACTION · 4 RESTAURANT · 5 COURSE | TourAPI (좌표 반경) | — |
|
||||||
| 6 STORY | Perplexity | `songs` `people` `chronicle` `postcard` `quiz` |
|
| 6 STORY | Perplexity | `songs` `daily` `people` `chronicle` `reading` `postcard` `quiz` |
|
||||||
|
|
||||||
`body`(JSONB)에 항목이 들어간다. **지역 이야기는 종류당 한 행**이고 항목들은 `body.items` 안에 있다.
|
`body`(JSONB)에 항목이 들어간다. **지역 이야기는 종류당 한 행**이고 항목들은 `body.items` 안에 있다.
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
# 배포 · 스토리지
|
# 배포 · 스토리지
|
||||||
|
|
||||||
|
> 2026-09-15 이후 절차는 [PUBLISH_VERSION.md](PUBLISH_VERSION.md)를 따른다.
|
||||||
|
> 기존 사이트 전체 재굽기는 하지 않는다. 최초 전환 때 구 프리렌더를 중지한다.
|
||||||
|
|
||||||
> **현재 결정 (2026-08-31): 발행 사이트는 서버 안에서 nginx 가 정적 서빙한다.**
|
> **현재 결정 (2026-08-31): 발행 사이트는 서버 안에서 nginx 가 정적 서빙한다.**
|
||||||
> Azure Blob 은 코드에 있으나 **켜지 않는다**(`AZURE_STORAGE_CONNECTION_STRING` 비움).
|
> Azure Blob 은 코드에 있으나 **켜지 않는다**(`AZURE_STORAGE_CONNECTION_STRING` 비움).
|
||||||
> 클라우드는 고도화 때 붙인다 — 근거는 [ARCHITECTURE.md 3절](ARCHITECTURE.md).
|
> 클라우드는 고도화 때 붙인다 — 근거는 [ARCHITECTURE.md 3절](ARCHITECTURE.md).
|
||||||
|
|||||||
@@ -1,10 +1,48 @@
|
|||||||
# 개발 일지
|
# 개발 일지
|
||||||
|
|
||||||
|
## 2026-09-15 — 워커 렌더·발행 버전·예약 안내·미리보기 대기
|
||||||
|
|
||||||
|
- 상시 프리렌더를 제거하고 워커가 컴파일된 Node 렌더러를 실행한다.
|
||||||
|
- 버전별 HTML을 보존하고 게이트 통과 뒤 공개 링크를 전환한다. 재시도는 저장된 성공본을 사용한다.
|
||||||
|
- 예약 전 확인을 이용안내에 통합하고 iframe 렌더 완료까지 스피너를 표시한다.
|
||||||
|
- 배포는 기존 HTML과 목업을 재굽지 않는다. 상세: [PUBLISH_VERSION.md](PUBLISH_VERSION.md).
|
||||||
|
- 읽기 생성 토큰 상한을 늘리고 추첨 배열을 고정해 반복 렌더를 방지한다.
|
||||||
|
- 편집기 주소는 /builder?placeId=…로 통일한다. 옛 step=editor 주소는 ID 복원 후 정정한다.
|
||||||
|
- 검증: 사이트 81건, 백엔드 발행·롤백·서치콘솔 45건 통과. 빌더·사이트 빌드 통과.
|
||||||
|
|
||||||
무엇을 왜 바꿨는지 날짜순으로 남긴다. 새 항목을 **위에** 추가한다.
|
무엇을 왜 바꿨는지 날짜순으로 남긴다. 새 항목을 **위에** 추가한다.
|
||||||
결론과 배경은 각 문서가 단일 출처다 — 여기에는 요약과 링크만 둔다.
|
결론과 배경은 각 문서가 단일 출처다 — 여기에는 요약과 링크만 둔다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 2026-09-15 — Google 사이트맵 자동 제출·색인 관측
|
||||||
|
|
||||||
|
- 기존 스케줄러에서 발행 완료 DB 감지 → 사이트맵 제출 → 색인 조회 → 지연/실패 알림.
|
||||||
|
- 관측값·재시도·알림 시각은 `site_search_status`에 보관. 발행 잡/상태는 건드리지 않는다.
|
||||||
|
- API 인증/호출과 DB·배치·알림 모듈 분리. Google·Teams 실호출은 설정 전까지 꺼진다.
|
||||||
|
- 설정/적용/관측 의미: [SEARCH_CONSOLE.md](SEARCH_CONSOLE.md). 운영 배포·권한 부여는 미실행.
|
||||||
|
|
||||||
|
**검증** — 관련 59건 통과. 추가 회귀 23건 통과·기존 발행 검수 실패 1건(변경 전 코드에서도 재현).
|
||||||
|
|
||||||
|
## 2026-09-14 — 엽서 쓰기를 발행본에도 넣는다 (사진이 남의 도메인이면 저장·공유는 막힌다)
|
||||||
|
|
||||||
|
**무슨 일** — 시연본에만 주입 스크립트로 있던 '엽서 쓰기'(사진 고르기 + 한 마디 + 캔버스 엽서)를
|
||||||
|
발행본 컴포넌트로 옮겼다. 그리기 규칙은 `site/src/lib/postcard-canvas.ts` 한 곳에 두고,
|
||||||
|
화면·입력·공유는 `sections/items/PostcardMakerSection.tsx` 가 맡는다. 사진이 있는 사이트면 나간다.
|
||||||
|
|
||||||
|
**★ 저장·공유가 사진 출처에 걸린다** — 캔버스는 **남의 도메인 사진을 그리면 오염돼서**(tainted)
|
||||||
|
`toBlob` 이 SecurityError 로 막힌다. 미리보기는 멀쩡히 보이는데 저장·공유만 죽는, 눈으로는 못 찾는 종류다.
|
||||||
|
CORS 로 받으면 안 오염되지만 실측(2026-09-14) 발행본 사진은 네이버 CDN(`*.pstatic.net`)에 있고
|
||||||
|
그쪽은 `Access-Control-Allow-Origin` 을 주지 않는다 — `curl -I` 로 확인했다.
|
||||||
|
|
||||||
|
→ 지금은 **정직하게 막는다.** CORS 로 한 번 받아 보고, 실패하면 CORS 없이 다시 받아 미리보기만 세우고
|
||||||
|
저장·공유 단추를 아예 감춘다("이 사진은 다른 사이트에 올라와 있어 …"). 눌러도 안 되는 단추를 두지 않는다.
|
||||||
|
→ **근본 해결은 사진을 우리 오리진으로 옮기는 것이다.** 시연본이 `img/mirror/` 로 그렇게 하고 있고,
|
||||||
|
발행 파이프라인이 같은 일을 하면(빌드 때 내려받아 `out/s/<slug>/img/` 에 두고 payload 주소를 바꾼다)
|
||||||
|
저장·공유가 풀린다. 덤으로 외부 주소 만료·핫링크 문제도 같이 사라진다. **아직 안 했다.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 2026-09-14 — FAQ 를 20개까지 채운다 (펜션 공통 질문 30개 + 문의 안내)
|
## 2026-09-14 — FAQ 를 20개까지 채운다 (펜션 공통 질문 30개 + 문의 안내)
|
||||||
|
|
||||||
**무슨 일** — COPY 잡의 FAQ 생성 상한을 8 → 20 으로 올리고, 그래도 모자라면 펜션 공통 질문 카탈로그에서
|
**무슨 일** — COPY 잡의 FAQ 생성 상한을 8 → 20 으로 올리고, 그래도 모자라면 펜션 공통 질문 카탈로그에서
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 발행 버전과 워커 (2026-09-15)
|
||||||
|
|
||||||
|
이 문서가 이전 문서의 프리렌더 상시 기동·전체 재굽기 절차를 대체한다.
|
||||||
|
|
||||||
|
`BUILD → snapshot → payload → Node 렌더 → 결과 게이트 → 공개 링크 전환 → DB 기록`
|
||||||
|
|
||||||
|
- Python은 HTML을 만들지 않는다. 미리 컴파일된 Node를 실행하고 JSON 보고서만 읽는다.
|
||||||
|
- 워커 이미지에 Node와 렌더러를 포함한다. 실행 중 npm 설치·번들 빌드는 없다.
|
||||||
|
- 공유 볼륨의 파일 잠금으로 렌더·공개 전환을 직렬화한다. 수집 등 다른 잡은 동시 실행한다.
|
||||||
|
- `out/versions/<slug>/<version>`에 성공한 HTML과 렌더 보고서를 보존한다.
|
||||||
|
- `out/s/<slug>`는 공개 버전의 상대 심볼릭 링크다. 게이트 통과 후 전환한다.
|
||||||
|
- 성공한 버전은 재시도·롤백 때 다시 쓰지 않는다. 기존 일반 디렉토리는 첫 재발행 때 legacy로 보존한다.
|
||||||
|
- 배포 시 HTML·기존 HTML의 자산 주소를 수정하지 않는다. 공용 자산과 미리보기 셸만 준비한다.
|
||||||
|
- 목업과 보관 버전의 참조 자산도 삭제 대상에서 제외한다. versions는 Azure 공용 업로드에서 제외한다.
|
||||||
|
- 롤백 API: `POST /v1/place/{place_id}/site/version/rollback`, `target_version`. 소유권 검사와 BUILD 중복 방지 키를 공유한다.
|
||||||
|
- 로컬 공개 전환과 DB/Azure는 단일 트랜잭션이 아니다. 외부 저장소·DB 실패 시 재시도 및 운영 확인이 필요하다.
|
||||||
|
- 최초 일반 디렉토리→링크 전환은 두 rename 사이 짧은 공백이 가능하다. 이후 링크 교체는 원자적이다.
|
||||||
|
|
||||||
|
## 배포
|
||||||
|
|
||||||
|
1. 진행 중 잡·서버 변경·목업 및 참조 자산 해시를 확인하고 site-out을 백업한다.
|
||||||
|
2. backend·worker·site 이미지를 빌드한다. admin은 기본 대상이 아니다.
|
||||||
|
3. 기존 worker와 solution-prerender를 중지한 뒤 새 worker를 기동한다. 두 렌더러를 동시에 실행하지 않는다.
|
||||||
|
4. API·미리보기·테스트 발행을 확인하고 목업 해시를 대조한다. 전체 재굽기·republish_all은 실행하지 않는다.
|
||||||
|
|
||||||
|
워커 경로: `SITE_PAYLOAD_DIR=/app/solution/site/payloads`, `SITE_OUTPUT_DIR=/app/solution/site/out`.
|
||||||
|
DB 테이블 추가는 없다. 기존 버전·잡·발행 로그를 사용한다.
|
||||||
|
|
||||||
|
## UI
|
||||||
|
|
||||||
|
예약 전 확인과 요약을 이용안내 및 예약에 통합한다. 별도 요약 섹션과 예약 카드의 중복 규정은 제거한다.
|
||||||
|
빌더 미리보기는 iframe 내부 렌더 완료 신호까지 스피너를 표시한다. 출처·iframe을 확인하고 12초 상한을 둔다.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# Google Search Console 자동 추적
|
||||||
|
|
||||||
|
`발행 DB 감지 → 공개 사이트맵 확인/제출 → 색인 조회 → 상태 저장·Teams 알림`
|
||||||
|
|
||||||
|
## 경계
|
||||||
|
|
||||||
|
- 기존 API의 스케줄러에서 10분마다 실행한다. 컨테이너 추가 없음.
|
||||||
|
- `sites.status=PUBLISHED`인 사이트만 등록하므로 초안/목업 디렉토리 나열을 작업 원장으로 쓰지 않는다.
|
||||||
|
- 발행 DB에서 재발견한다. 발행 순간 별도 큐 적재가 실패하는 틈이 없고 재시작해도 이어진다.
|
||||||
|
- 발행 트랜잭션/잡과 독립적이다. Google 실패가 사이트 발행을 실패로 바꾸지 않는다.
|
||||||
|
- 한 번에 신규 발행 100개 등록, 조회는 오래 기다린 5개 처리. 정상 조회는 24시간 후 반복.
|
||||||
|
- 현재 렌더러의 단일 루트 urlset만 지원하고 읽기 상한은 5MB다. 향후 sitemap index 분할 시 확장한다.
|
||||||
|
- 오류는 1·2·4·8·16·24시간 간격 재시도. 기본 주기 기준 하루 최대 720회 검사이며,
|
||||||
|
다른 도구의 같은 속성 사용량도 Google 할당량에 포함된다. 대량 백로그는 여러 날에 걸쳐 소진한다.
|
||||||
|
- PostgreSQL transaction advisory lock으로 다중 API 프로세스의 동시 배치를 막는다.
|
||||||
|
단일 배치는 외부 호출 동안 트랜잭션/연결 1개를 점유한다(검사 1건 최대 90초, 최대 5건).
|
||||||
|
- 사이트맵 제출 성공과 URL 색인 성공은 별개다. `first_indexed_at`은 **우리가 처음 PASS를 관측한 시각**이다.
|
||||||
|
Google 내부 색인 시각이나 최신 발행 버전 반영 시각이 아니다. 원본 `lastCrawlTime`도 함께 보관한다.
|
||||||
|
- 재발행 시 해당 발행의 관측 상태를 초기화한다. 지난 관측 이력 전체를 누적하는 이벤트 저장소는 아니다.
|
||||||
|
- `SITE_PUBLIC_HOST` 변경은 기존 지침대로 재발행이 필요하다. 사이트 주소의 단일 출처는 `site_payload`다.
|
||||||
|
|
||||||
|
## 최초 설정 (운영자)
|
||||||
|
|
||||||
|
1. Search Console에서 발행 도메인의 소유권 확인. URL-prefix 속성이면
|
||||||
|
`https://web4ai.o2osolution.ai/`, 도메인 속성이면 `sc-domain:web4ai.o2osolution.ai` 형태.
|
||||||
|
2. Google Cloud에서 Search Console API 활성화, 전용 서비스 계정 생성.
|
||||||
|
3. Search Console 속성 설정 → 사용자 및 권한에서 그 서비스 계정 이메일에 전체 사용자 권한 부여.
|
||||||
|
Google 로그인용 `GOOGLE_CLIENT_ID`와는 다른 인증이다.
|
||||||
|
4. 서비스 계정 JSON 키는 **저장소 밖**에 보관한다. 권한을 최소화하고 git/이미지/로그에 넣지 않는다.
|
||||||
|
5. 루트 `.env` 설정:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
GSC_ENABLED=1
|
||||||
|
GSC_PROPERTY_URL=https://web4ai.o2osolution.ai/
|
||||||
|
GSC_CREDENTIALS_HOST_FILE=/secure/location/search-console.json
|
||||||
|
GSC_ALERT_DAYS=7
|
||||||
|
GSC_ALERT_WEBHOOK_URL=
|
||||||
|
```
|
||||||
|
|
||||||
|
키 생성/권한 부여/실제 알림 전송은 구현 검증 중 자동 수행하지 않는다.
|
||||||
|
|
||||||
|
## 배포
|
||||||
|
|
||||||
|
먼저 새 이미지에 requirements를 설치하고 `0014_search_console.sql`을 기존 마이그레이션 도구로 적용한다.
|
||||||
|
프로젝트 전체 마이그레이션 순서를 확인한 뒤 실행한다. 아래는 운영자가 실행할 명령이며 자동 배포하지 않았다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec -T solution-backend python scripts/migrate.py
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.search-console.yml up -d --build solution-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
선택 compose 파일은 API에만 키를 읽기 전용 마운트하고 `GSC_CREDENTIALS_FILE`을 설정한다.
|
||||||
|
없는 파일을 디렉토리로 자동 생성하지 않는다. 이후 배포에서도 이 override를 함께 사용해야 한다.
|
||||||
|
로컬 Python 실행은 `GSC_CREDENTIALS_FILE`에 로컬 키 파일 경로를 지정한다.
|
||||||
|
켜진 스케줄러는 첫 10분 주기부터 기존 발행 사이트도 등록한다. `GSC_ENABLED=0`이면 DB/Google 호출 모두 생략한다.
|
||||||
|
|
||||||
|
## 알림
|
||||||
|
|
||||||
|
Teams Workflows의 webhook 수신 → 채널에 Adaptive Card 게시 흐름 URL을
|
||||||
|
`GSC_ALERT_WEBHOOK_URL`에 넣는다. 비우면 외부 전송 없이 경고 로그/DB만 남는다.
|
||||||
|
API/사이트맵 오류 또는 발행 후 기본 7일 미색인 시 알린다. 성공한 알림은 사이트별 24시간 중복 억제.
|
||||||
|
전송 실패는 `alerted_at`을 갱신하지 않아 다음 검사 때 재시도한다.
|
||||||
|
외부 전송 후 DB commit 전에 죽으면 중복 알림이 가능하다(at-least-once).
|
||||||
|
키·토큰·webhook URL·Google 오류 본문은 알림에 포함하지 않는다.
|
||||||
|
|
||||||
|
## 결과 확인
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec -T solution-backend python scripts/search_console_status.py
|
||||||
|
```
|
||||||
|
|
||||||
|
읽기 전용이며 Google API를 추가 호출하지 않는다. 프론트 화면/API 계약은 변경하지 않았다.
|
||||||
|
|
||||||
|
| 파일 | 책임 |
|
||||||
|
|---|---|
|
||||||
|
| `services/search_console_client.py` | 인증·Google HTTP·오류 정규화 |
|
||||||
|
| `services/search_console_settings.py` | 선택 설정·속성 URL 범위 |
|
||||||
|
| `services/search_console_service.py` | 배치 흐름·재시도·관측 결과 |
|
||||||
|
| `crud/search_console_crud.py` | 발행 감지·등록·조회 순서·동시 실행 잠금 |
|
||||||
|
| `services/search_console_alerts.py` | 알림 조건·Teams 전송 |
|
||||||
|
|
||||||
|
## 구글 지원 범위 / 남은 운영 작업
|
||||||
|
|
||||||
|
- [사이트맵 제출 API](https://developers.google.com/webmaster-tools/v1/sitemaps/submit)는 지원된다.
|
||||||
|
- [URL Inspection API](https://developers.google.com/webmaster-tools/v1/urlInspection.index/inspect)는
|
||||||
|
Google이 이미 알고 있는 상태 조회용이며 실시간 페이지 테스트나 색인 요청 API가 아니다.
|
||||||
|
- 일반 숙박 사이트는 [Indexing API](https://developers.google.com/search/apis/indexing-api/v3/using-api) 대상이 아니다.
|
||||||
|
- [검사 할당량](https://developers.google.com/webmaster-tools/limits)은 속성당 하루 2,000회다.
|
||||||
|
- [Teams webhook 형식](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook).
|
||||||
|
- 실제 서비스 계정 권한/사이트맵 제출/색인 관측/Teams 수신은 설정 후 운영 검증이 필요하다.
|
||||||
|
- 기존 루트 사이트맵의 백업 URL 정리와 IndexNow 개별 사이트맵 참조 문제는 이 기능과 별도다.
|
||||||
|
이 기능은 기존 공개 사이트맵을 제출하며 내용을 다시 만들거나 목업을 삭제하지 않는다.
|
||||||
|
|
||||||
|
## 구현 검증 (2026-09-15)
|
||||||
|
|
||||||
|
- 격리 PostgreSQL에서 클라이언트·배치·스키마·IndexNow 관련 59건 통과.
|
||||||
|
- 발행·설정·사이트 목록 회귀검사: 23건 통과, `test_unverified_fact_blocks_publish` 1건 실패.
|
||||||
|
해당 실패는 변경 전 HEAD `9773bc0`의 발행 코드에서도 동일 재현됨(GSC 비활성).
|
||||||
|
- Google/Teams 실호출 없음. 서비스 계정 권한·실제 제출·채널 수신은 운영 설정 후 검증 대상.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Search Console 클라이언트
|
||||||
|
|
||||||
|
`solution/backend/services/search_console_client.py` — Google Search Console 에
|
||||||
|
사이트맵을 제출하고 URL 색인 상태를 조회하는 REST 클라이언트만 다룬다.
|
||||||
|
DB 저장·스케줄링·발행 감지·환경 설정은 [SEARCH_CONSOLE.md](SEARCH_CONSOLE.md)를 따른다.
|
||||||
|
|
||||||
|
공식 문서: [Sitemaps.submit](https://developers.google.com/webmaster-tools/v1/sitemaps/submit) ·
|
||||||
|
[urlInspection.index.inspect](https://developers.google.com/webmaster-tools/v1/urlInspection.index/inspect)
|
||||||
|
|
||||||
|
## 1. 계약
|
||||||
|
|
||||||
|
```python
|
||||||
|
class SearchConsoleClient:
|
||||||
|
def __init__(self, credentials_file: str, *, transport: httpx.AsyncBaseTransport | None = None): ...
|
||||||
|
async def submit_sitemap(self, property_url: str, sitemap_url: str) -> None: ...
|
||||||
|
async def inspect_url(self, property_url: str, page_url: str) -> dict: ... # indexStatusResult 만
|
||||||
|
async def aclose(self) -> None: ...
|
||||||
|
# async with SearchConsoleClient(...) as client: ...
|
||||||
|
```
|
||||||
|
|
||||||
|
- `credentials_file`: 서비스 계정 JSON 키 파일 경로.
|
||||||
|
- `transport`: 테스트에서 `httpx.MockTransport` 를 꽂는 자리 — 실제 Google 호출 없이 검증한다.
|
||||||
|
- `inspect_url` 은 응답의 `inspectionResult.indexStatusResult` 만 돌려준다. 그 경로가
|
||||||
|
없거나(검사 실패) 빈 dict 면(실제 검사가 안 된 응답) `SearchConsoleError` 를 올린다 —
|
||||||
|
**"미색인"으로 넘겨짚지 않는다.**
|
||||||
|
|
||||||
|
## 2. 인증
|
||||||
|
|
||||||
|
서비스 계정 JSON 키 파일 + scope `https://www.googleapis.com/auth/webmasters`.
|
||||||
|
`google.oauth2.service_account` · `google.auth.transport.requests.Request` · `requests` 는
|
||||||
|
전부 함수 안에서 import 한다. 두 패키지는 백엔드 `requirements.txt`에 포함되어 있다.
|
||||||
|
|
||||||
|
- 토큰은 클라이언트 인스턴스에 캐시된다(`credentials.valid` 인 동안 재사용, 매 호출
|
||||||
|
갱신하지 않는다). 동시 호출은 `asyncio.Lock` 으로 갱신을 한 번만 태운다.
|
||||||
|
- 갱신은 `asyncio.to_thread` 로 별도 스레드에서 돈다. 내부 `requests.Session` 요청에는
|
||||||
|
타임아웃을 강제로 20초로 덮어씌운다(`Request.__call__` 기본값 120초를 무시) — 만료된
|
||||||
|
키·막힌 네트워크에서 무한정 걸리는 것을 막는다.
|
||||||
|
|
||||||
|
## 3. 오류 — `SearchConsoleError(code)`
|
||||||
|
|
||||||
|
`code` 문자열 하나만 들고 다닌다. **Google 응답 본문·액세스 토큰·키 파일 내용·원본 예외
|
||||||
|
메시지는 절대 담지 않는다** — 로그·잡 상태·관리 화면 어디로 흘러도 안전하다.
|
||||||
|
|
||||||
|
| code | 뜻 |
|
||||||
|
|---|---|
|
||||||
|
| `invalid_credentials_file` | 키 파일을 못 읽거나 형식이 잘못됨 |
|
||||||
|
| `auth_failed` | 토큰 갱신 실패, 또는 갱신 후에도 토큰이 비어 있음 |
|
||||||
|
| `unauthorized` | HTTP 401 |
|
||||||
|
| `forbidden` | HTTP 403 |
|
||||||
|
| `rate_limited` | HTTP 429 |
|
||||||
|
| `server_error` | HTTP 5xx |
|
||||||
|
| `http_<code>` | 그 외 실패 상태코드 |
|
||||||
|
| `timeout` | 요청 타임아웃 |
|
||||||
|
| `transport_error` | 그 외 전송 실패(연결 끊김 등) |
|
||||||
|
| `invalid_json` | 200 인데 본문이 JSON 이 아님 |
|
||||||
|
| `missing_inspection_result` | 응답에 `inspectionResult` 가 없음 |
|
||||||
|
| `missing_index_status_result` | `inspectionResult` 는 있는데 `indexStatusResult` 가 없거나 빈 dict |
|
||||||
|
|
||||||
|
## 4. 테스트
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd solution/backend
|
||||||
|
APP_ENV=test .venv/bin/python -m pytest tests/test_search_console_client.py --confcutdir=tests
|
||||||
|
```
|
||||||
|
|
||||||
|
`--confcutdir=tests` 가 필요한 이유: 저장소 루트 `conftest.py` 의 세션 스코프 autouse
|
||||||
|
픽스처가 실 Postgres 연결을 요구한다(`solution/backend/conftest.py`). 이 클라이언트
|
||||||
|
테스트는 DB 를 전혀 쓰지 않으므로 그 픽스처를 건너뛴다 — `--confcutdir=tests` 로 상위
|
||||||
|
`conftest.py` 탐색을 끊는다. (통합 후 전체 스위트를 돌릴 때는 이 플래그 없이 실행한다.)
|
||||||
|
|
||||||
|
Google 실 API 는 전부 `httpx.MockTransport` 로 막았다 — 네트워크 호출도, 과금도 없다.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Teams 웹훅 확인 (2026-09-15)
|
||||||
|
|
||||||
|
- Adaptive Card 요청의 `contentUrl: null` 및 `$schema`를 공식 예제에 맞춰 보완했다.
|
||||||
|
- HTTP 202는 워크플로의 요청 접수다. Teams 채널 게시 성공을 뜻하지 않는다.
|
||||||
|
- 실제 전송 2건은 202였지만 사용자가 확인한 워크플로 실행은 실패였다.
|
||||||
|
상세 오류를 확인하지 못했으므로 누락 필드를 실제 실패 원인으로 단정하지 않는다.
|
||||||
|
- 운영 자동 알림 활성화 전, 채널 수신 또는 워크플로의 최종 게시 단계 성공을 확인해야 한다.
|
||||||
|
- 웹훅은 `.env`에만 보관하고 커밋하지 않는다.
|
||||||
|
|
||||||
|
검증: 백엔드에서 `APP_ENV=test PYTHONPATH=. .venv/bin/pytest tests/test_search_console_alerts.py --confcutdir=tests`.
|
||||||
|
공식 형식: https://learn.microsoft.com/en-us/connectors/teams/#adaptivecarditemschema
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# 오늘의 날씨
|
||||||
|
|
||||||
|
`Open-Meteo → /v1/local/weather → useLiveWeather → WeatherSection`
|
||||||
|
|
||||||
|
관측값은 기존 API를 사용하며 브라우저에서 10분마다 갱신한다. 조회 실패 시 마지막 관측값과
|
||||||
|
관측 시각을 유지한다. 날씨 문구는 API 요청마다 생성하지 않는다.
|
||||||
|
|
||||||
|
`weather_notes.json → weather_notes.py → site_payload._weather → noteSets/tempNoteSets`
|
||||||
|
|
||||||
|
하늘 5종·기온 5구간에 각 5문구를 싣는다. 첫 렌더는 첫 문장으로 고정해 하이드레이션을 맞추고,
|
||||||
|
브라우저에서는 무작위 시작 후 20초마다 한 바퀴 안에서 중복 없이 순환한다.
|
||||||
|
기온 구간은 기존 `weatherBand`의 30·25·20·10도다. 구름많음은 그림상 흐림과 같지만 문구는 별도다.
|
||||||
|
|
||||||
|
목업 README 2.3의 순환 계약을 제품으로 옮겼다. 군산 전용 시설·장소를 다른 사업장에 복사하지
|
||||||
|
않도록 기본 문구는 장소·시설·영업시간을 주장하지 않는 공통 안내로 구성한다. **LLM 생성이 아니다.**
|
||||||
|
지역별 장소 추천을 자동 생성하는 작업은 포함하지 않았다. 목업의 수기 문구·산출물은 변경하지 않는다.
|
||||||
|
옛 단일 `note`·`notes`·`tempNotes` payload도 계속 지원한다. 이미 발행된 사이트는 재발행해야 반영된다.
|
||||||
Generated
+32
@@ -13,6 +13,9 @@
|
|||||||
"solution/site",
|
"solution/site",
|
||||||
"admin/frontend"
|
"admin/frontend"
|
||||||
],
|
],
|
||||||
|
"devDependencies": {
|
||||||
|
"playwright": "^1.63.0"
|
||||||
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
}
|
}
|
||||||
@@ -7337,6 +7340,35 @@
|
|||||||
"pathe": "^2.0.3"
|
"pathe": "^2.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.63.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/pony-cause": {
|
"node_modules/pony-cause": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/pony-cause/-/pony-cause-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/pony-cause/-/pony-cause-1.1.1.tgz",
|
||||||
|
|||||||
@@ -26,5 +26,8 @@
|
|||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"playwright": "^1.63.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,7 +93,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
|||||||
-- ============================================================
|
-- ============================================================
|
||||||
CREATE TABLE IF NOT EXISTS public.jobs (
|
CREATE TABLE IF NOT EXISTS public.jobs (
|
||||||
job_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- ★ 이 표만 server_default 가 꼭 필요하다 — 큐 전이가 raw SQL(RETURNING)이라 ORM 의 파이썬 default 가 안 먹는다
|
job_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- ★ 이 표만 server_default 가 꼭 필요하다 — 큐 전이가 raw SQL(RETURNING)이라 ORM 의 파이썬 default 가 안 먹는다
|
||||||
job_type SMALLINT NOT NULL, -- JobType: 1=collect 2=vision 3=copy 4=build 5=local_sync 6=ai_check
|
job_type SMALLINT NOT NULL, -- JobType: 1=collect 2=vision 3=copy 4=build 5=local_sync 6=ai_check 7=song 8=rollback
|
||||||
status SMALLINT NOT NULL DEFAULT 1, -- JobStatus: 1=pending 2=running 3=done 4=dead
|
status SMALLINT NOT NULL DEFAULT 1, -- JobStatus: 1=pending 2=running 3=done 4=dead
|
||||||
priority SMALLINT NOT NULL DEFAULT 100, -- 낮을수록 우선
|
priority SMALLINT NOT NULL DEFAULT 100, -- 낮을수록 우선
|
||||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
@@ -317,6 +317,25 @@ CREATE TABLE IF NOT EXISTS public.place_area_refs (
|
|||||||
-- ★ 정적 빌드 — DB 는 빌드 시점에만 읽고 방문자와 만나지 않는다.
|
-- ★ 정적 빌드 — DB 는 빌드 시점에만 읽고 방문자와 만나지 않는다.
|
||||||
-- ★ 해지는 물리 삭제가 아니라 상태 전이다. 색인된 페이지를 갑자기 404 로 만들지 않는다.
|
-- ★ 해지는 물리 삭제가 아니라 상태 전이다. 색인된 페이지를 갑자기 404 로 만들지 않는다.
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS public.site_search_status (
|
||||||
|
site_id uuid PRIMARY KEY,
|
||||||
|
site_version_id uuid NOT NULL,
|
||||||
|
property_url TEXT NOT NULL,
|
||||||
|
page_url TEXT NOT NULL,
|
||||||
|
published_at TIMESTAMPTZ NOT NULL,
|
||||||
|
sitemap_submitted_at TIMESTAMPTZ NULL,
|
||||||
|
inspected_at TIMESTAMPTZ NULL,
|
||||||
|
first_indexed_at TIMESTAMPTZ NULL,
|
||||||
|
inspection JSONB NULL,
|
||||||
|
error_code VARCHAR(100) NULL,
|
||||||
|
failures INTEGER NOT NULL DEFAULT 0,
|
||||||
|
next_check_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
alerted_at TIMESTAMPTZ NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
deleted BOOLEAN NOT NULL DEFAULT false
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS public.sites (
|
CREATE TABLE IF NOT EXISTS public.sites (
|
||||||
site_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
site_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
place_id uuid NOT NULL, -- 사업장과 1:1
|
place_id uuid NOT NULL, -- 사업장과 1:1
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- 발행 상태를 바꾸지 않고 Google 제출/검사 결과를 추적한다.
|
||||||
|
CREATE TABLE IF NOT EXISTS public.site_search_status (
|
||||||
|
site_id uuid PRIMARY KEY,
|
||||||
|
site_version_id uuid NOT NULL,
|
||||||
|
property_url TEXT NOT NULL,
|
||||||
|
page_url TEXT NOT NULL,
|
||||||
|
published_at TIMESTAMPTZ NOT NULL,
|
||||||
|
sitemap_submitted_at TIMESTAMPTZ NULL,
|
||||||
|
inspected_at TIMESTAMPTZ NULL,
|
||||||
|
first_indexed_at TIMESTAMPTZ NULL,
|
||||||
|
inspection JSONB NULL,
|
||||||
|
error_code VARCHAR(100) NULL,
|
||||||
|
failures INTEGER NOT NULL DEFAULT 0,
|
||||||
|
next_check_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
alerted_at TIMESTAMPTZ NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
deleted BOOLEAN NOT NULL DEFAULT false
|
||||||
|
);
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# 워커 전용 이미지 — solution-backend(:9800)·admin-backend(:9801) 와 **다른 이미지**다.
|
||||||
|
#
|
||||||
|
# ★ 왜 갈랐나 (프리렌더를 워커 실행으로 통합, 2026-09-15)
|
||||||
|
# BUILD·ROLLBACK 잡은 이제 컴파일된 Node 렌더러(solution/site)를 subprocess 로 직접
|
||||||
|
# 돌린다(services/render_service.py) — 예전에 별도 컨테이너(solution-prerender)가 하던
|
||||||
|
# 일이다. 그 렌더러가 필요한 건 **워커뿐**이다. Dockerfile(api/admin 겸용)에 Node 를
|
||||||
|
# 같이 넣으면 API 를 여는 요청만 받는 컨테이너에도 쓰지 않는 Node 런타임과 렌더러
|
||||||
|
# 번들이 실려 나간다 — 이미지가 커지고 공격 표면도 는다.
|
||||||
|
#
|
||||||
|
# ★ 기동·잡 실행 중에 npm install 을 하지 않는다. site-builder 스테이지가 이미지 빌드
|
||||||
|
# 시점에 한 번 굽고, 최종 이미지는 컴파일된 산출물만 COPY 한다.
|
||||||
|
# ★ node_modules 는 안 들어간다 — solution/site/vite.config.ts 가 SSR 번들에
|
||||||
|
# `ssr.noExternal: true` 로 react 등 의존성까지 전부 접어 넣는다(실측: node_modules 를
|
||||||
|
# 지우고 실행해도 그대로 돈다, dist/prerender/prerender.js 단일 파일 1.8MB).
|
||||||
|
#
|
||||||
|
# ★ 빌드 컨텍스트는 solution-backend 와 같은 **레포 루트**다 — solution/site 와
|
||||||
|
# solution/backend 를 한 이미지에 담아야 한다.
|
||||||
|
|
||||||
|
# ── 1단계: 렌더러 컴파일 (Node) ──────────────────────────────────────────────
|
||||||
|
FROM node:24-bookworm AS site-builder
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json tsconfig.base.json ./
|
||||||
|
COPY solution/shared/package.json solution/shared/
|
||||||
|
COPY solution/frontend/package.json solution/frontend/
|
||||||
|
COPY solution/site/package.json solution/site/
|
||||||
|
COPY admin/frontend/package.json admin/frontend/
|
||||||
|
# ★ npm workspaces 는 루트 package.json 의 workspaces 목록에 있는 자리마다 package.json 을
|
||||||
|
# 요구한다 — site 만 빌드해도 4개를 전부 COPY 해야 npm ci 가 성공한다(nginx/Dockerfile 과 같다).
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY solution/shared ./solution/shared
|
||||||
|
COPY solution/site ./solution/site
|
||||||
|
RUN npm run build:client -w @o2o/site \
|
||||||
|
&& npm run build:prerender -w @o2o/site
|
||||||
|
|
||||||
|
# ── 2단계: Node 런타임만 (바이너리를 뽑아 쓴다) ──────────────────────────────
|
||||||
|
# ★ python:3.12-slim 과 같은 계열(Debian bookworm)의 태그를 써야 한다 — glibc ABI 가
|
||||||
|
# 어긋나면 바이너리만 복사해서는 못 돈다("cannot execute binary file" 류로 죽는다).
|
||||||
|
FROM node:24-bookworm-slim AS node-runtime
|
||||||
|
|
||||||
|
# ── 3단계: 최종 워커 이미지 ───────────────────────────────────────────────
|
||||||
|
FROM python:3.12-slim-bookworm
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY solution/backend/requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
# ★ yanolja_adapter.py 가 Playwright 로 페이지를 렌더링한다(수집 파이프라인, 워커 전용 경로) —
|
||||||
|
# 패키지(pip)만으로는 브라우저 실행 파일이 없다. --with-deps 가 Chromium 이 필요로 하는
|
||||||
|
# 시스템 라이브러리(libnss3 등)까지 apt 로 같이 깐다.
|
||||||
|
RUN playwright install --with-deps chromium
|
||||||
|
|
||||||
|
# Node 바이너리만 옮겨 온다 — npm·corepack 은 쓰지 않는다(빌드는 site-builder 스테이지가
|
||||||
|
# 이미 끝냈다). /usr/local/bin/node 하나로 `node dist/prerender/prerender.js` 를 돌리는
|
||||||
|
# 데 충분하다(실측: 아래 COPY 만으로 `node --version` 과 렌더 스모크 테스트가 통과한다).
|
||||||
|
COPY --from=node-runtime /usr/local/bin/node /usr/local/bin/node
|
||||||
|
|
||||||
|
COPY solution/backend ./solution/backend
|
||||||
|
# ★ SITE_ROOT(solution/site/scripts/prerender.ts)가 자기 파일 위치 기준 상대경로로
|
||||||
|
# payloads·songs·out 을 찾는다 — dist·public 이 이 자리(/app/solution/site/)에 있어야
|
||||||
|
# 워커가 컨테이너 안에서 렌더러를 그대로 실행할 수 있다.
|
||||||
|
COPY --from=site-builder /app/solution/site/dist ./solution/site/dist
|
||||||
|
COPY --from=site-builder /app/solution/site/public ./solution/site/public
|
||||||
|
|
||||||
|
ENV APP_ENV=local
|
||||||
|
ENV PYTHONPATH=/app/solution/backend
|
||||||
|
WORKDIR /app/solution/backend
|
||||||
|
|
||||||
|
# 워커는 포트가 없다 — 이미지 공통 HEALTHCHECK 를 두지 않는다(compose 가 disable 한다).
|
||||||
|
CMD ["python", "worker_main.py"]
|
||||||
@@ -454,6 +454,25 @@ class sites(MainTableMixin, MAIN_BASE):
|
|||||||
thumbnail_url = Column(String(500), nullable=True)
|
thumbnail_url = Column(String(500), nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class site_search_status(MainTableMixin, MAIN_BASE):
|
||||||
|
"""발행 성공과 Google 색인 성공은 다른 사건이라 별도 보관한다."""
|
||||||
|
|
||||||
|
__tablename__ = "site_search_status"
|
||||||
|
site_id = Column(UUID(as_uuid=True), primary_key=True)
|
||||||
|
site_version_id = Column(UUID(as_uuid=True), nullable=False)
|
||||||
|
property_url = Column(Text, nullable=False)
|
||||||
|
page_url = Column(Text, nullable=False)
|
||||||
|
published_at = Column(DateTime(timezone=True), nullable=False)
|
||||||
|
sitemap_submitted_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
inspected_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
first_indexed_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
inspection = Column(JSONB, nullable=True)
|
||||||
|
error_code = Column(String(100), nullable=True)
|
||||||
|
failures = Column(Integer, nullable=False, server_default=text("0"))
|
||||||
|
next_check_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
|
||||||
|
alerted_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class site_sections(MainTableMixin, MAIN_BASE):
|
class site_sections(MainTableMixin, MAIN_BASE):
|
||||||
"""섹션 하나의 콘텐츠. **JSON import/export 의 단위**다.
|
"""섹션 하나의 콘텐츠. **JSON import/export 의 단위**다.
|
||||||
|
|
||||||
|
|||||||
@@ -318,7 +318,7 @@ class LocalContentType(CodeEnum):
|
|||||||
|
|
||||||
# 코드값 ↔ **타입명**. `area_contents.kind` 와 `site_sections.data.items[].kind` 가 같은 어휘를 쓴다 —
|
# 코드값 ↔ **타입명**. `area_contents.kind` 와 `site_sections.data.items[].kind` 가 같은 어휘를 쓴다 —
|
||||||
# 개인화 행(거리·숨김)이 어느 공용 실체를 가리키는지 이름만 보고 알 수 있어야 한다.
|
# 개인화 행(거리·숨김)이 어느 공용 실체를 가리키는지 이름만 보고 알 수 있어야 한다.
|
||||||
# ★ STORY 는 여기 없다. 그 다섯(songs·people·chronicle·postcard·quiz)은 kind 가 곧 타입명이고,
|
# ★ STORY 는 여기 없다. 그것들(songs·people·chronicle·reading·postcard·quiz)은 kind 가 곧 타입명이고,
|
||||||
# 코드값 하나(6)를 나눠 쓴다. 아래 표는 kind 가 비어 있던 장소류를 채우기 위한 것이다.
|
# 코드값 하나(6)를 나눠 쓴다. 아래 표는 kind 가 비어 있던 장소류를 채우기 위한 것이다.
|
||||||
AREA_KIND = {
|
AREA_KIND = {
|
||||||
LocalContentType.WEATHER.value: "weather",
|
LocalContentType.WEATHER.value: "weather",
|
||||||
@@ -328,9 +328,9 @@ AREA_KIND = {
|
|||||||
LocalContentType.COURSE.value: "course",
|
LocalContentType.COURSE.value: "course",
|
||||||
}
|
}
|
||||||
|
|
||||||
# 지역 이야기 여섯. `services/prompts/story.py` 의 산출물 키와 같아야 한다.
|
# 지역 이야기 일곱. `services/prompts/story.py` 의 산출물 키와 같아야 한다.
|
||||||
# ★ 순서는 발행본 '지역 이야기' 탭 순서다(`site/sections/items/StorySection.tsx`).
|
# ★ 순서는 발행본 '지역 이야기' 탭 순서다(`site/sections/items/StorySection.tsx`).
|
||||||
STORY_KINDS = ("songs", "daily", "people", "chronicle", "postcard", "quiz")
|
STORY_KINDS = ("songs", "daily", "people", "chronicle", "reading", "postcard", "quiz")
|
||||||
|
|
||||||
|
|
||||||
class LocalSource(CodeEnum):
|
class LocalSource(CodeEnum):
|
||||||
@@ -389,6 +389,7 @@ class PublishAction(CodeEnum):
|
|||||||
REBUILD = 3
|
REBUILD = 3
|
||||||
SUSPEND = 4
|
SUSPEND = 4
|
||||||
RESUME = 5
|
RESUME = 5
|
||||||
|
ROLLBACK = 6 # 예전 버전으로 공개 주소를 되돌림 — services/rollback_service.py
|
||||||
|
|
||||||
|
|
||||||
class PublishResult(CodeEnum):
|
class PublishResult(CodeEnum):
|
||||||
@@ -434,6 +435,7 @@ class JobType(CodeEnum):
|
|||||||
LOCAL_SYNC = 5 # 지역 정보 갱신 — 행정구역 코드 단위(같은 지역 사이트 50개여도 1회)
|
LOCAL_SYNC = 5 # 지역 정보 갱신 — 행정구역 코드 단위(같은 지역 사이트 50개여도 1회)
|
||||||
AI_CHECK = 6 # AI 검색 노출 점검
|
AI_CHECK = 6 # AI 검색 노출 점검
|
||||||
SONG = 7 # 이 숙소의 노래 한 곡 (가사 Gemini → 작곡 Suno). 발행이 이 잡을 건다
|
SONG = 7 # 이 숙소의 노래 한 곡 (가사 Gemini → 작곡 Suno). 발행이 이 잡을 건다
|
||||||
|
ROLLBACK = 8 # 예전 버전 스냅샷으로 다시 굽고 공개 주소를 그 버전으로 되돌림
|
||||||
|
|
||||||
|
|
||||||
class JobStatus(CodeEnum):
|
class JobStatus(CodeEnum):
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
|||||||
|
|
||||||
★ 왜 필요한가
|
★ 왜 필요한가
|
||||||
발행 게이트는 이제 **실제로 나갈 HTML** 을 보고 판정한다. 그 HTML 은 Node 렌더러가
|
발행 게이트는 이제 **실제로 나갈 HTML** 을 보고 판정한다. 그 HTML 은 Node 렌더러가
|
||||||
굽고, BUILD 잡은 그 결과 보고서를 기다린다(services/render_report.wait_for).
|
굽고, BUILD 잡은 렌더러 subprocess 를 직접 돌린다(services/render_service.render_site).
|
||||||
파이썬 테스트 환경에는 Node 렌더러가 없으므로, payload 를 읽어 보고서를 만들어 주는
|
파이썬 테스트 환경에는 Node 렌더러가 없으므로, payload 를 읽어 보고서를 만들어 주는
|
||||||
대역을 끼운다 — 여기서 검사하려는 건 **백엔드가 보고서를 어떻게 처리하는가** 다.
|
대역을 끼운다 — 여기서 검사하려는 건 **백엔드가 보고서를 어떻게 처리하는가** 다.
|
||||||
|
|
||||||
@@ -175,8 +175,9 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
|||||||
두 벌로 두면 어긋나고, 어긋난 걸 아무도 모르는 게 원래 문제였다.
|
두 벌로 두면 어긋나고, 어긋난 걸 아무도 모르는 게 원래 문제였다.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from services import render_report, site_payload
|
from services import render_report, render_service, site_payload
|
||||||
|
|
||||||
payload_dir = tmp_path_factory.mktemp("payloads")
|
payload_dir = tmp_path_factory.mktemp("payloads")
|
||||||
monkeypatch.setattr(site_payload, "payload_dir", lambda: payload_dir)
|
monkeypatch.setattr(site_payload, "payload_dir", lambda: payload_dir)
|
||||||
@@ -229,13 +230,16 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
|||||||
count += sum(1 for m in payload.get("media") or [] if long(m.get("alt")))
|
count += sum(1 for m in payload.get("media") or [] if long(m.get("alt")))
|
||||||
return count
|
return count
|
||||||
|
|
||||||
async def _wait_for(slug, site_version, timeout_sec, poll_sec=1.0):
|
async def _render_site(payload_path, site_version, timeout_sec):
|
||||||
path = payload_dir / f"{slug}.json"
|
path = Path(payload_path)
|
||||||
|
slug = path.stem
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
return None
|
raise render_service.RenderFailed(f"payload 파일이 없다: {payload_path}")
|
||||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||||
if payload["site"]["version"] != site_version:
|
if payload["site"]["version"] != site_version:
|
||||||
return None
|
raise render_service.RenderFailed(
|
||||||
|
f"버전이 다르다(payload={payload['site']['version']} 요청={site_version})"
|
||||||
|
)
|
||||||
place = payload.get("place") or {}
|
place = payload.get("place") or {}
|
||||||
count = _count(payload)
|
count = _count(payload)
|
||||||
# ★ 고유 콘텐츠 0건이면 렌더러는 **페이지를 쓰지 않는다**
|
# ★ 고유 콘텐츠 0건이면 렌더러는 **페이지를 쓰지 않는다**
|
||||||
@@ -276,5 +280,8 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
|||||||
"error": None,
|
"error": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
monkeypatch.setattr(render_report, "wait_for", _wait_for)
|
monkeypatch.setattr(render_service, "render_site", _render_site)
|
||||||
|
async def _activate_site(slug, site_version):
|
||||||
|
return None
|
||||||
|
monkeypatch.setattr(render_service, "activate_site", _activate_site)
|
||||||
return payload_dir
|
return payload_dir
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""발행 DB를 작업 원장으로 사용해 알림 적재 실패/재시작에도 대상을 다시 찾는다."""
|
||||||
|
from sqlalchemy import select, or_, text
|
||||||
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
|
|
||||||
|
from common.database.model.models import sites, places, site_versions, site_search_status as Status
|
||||||
|
from common.enums import SiteStatus
|
||||||
|
|
||||||
|
|
||||||
|
def published_conditions():
|
||||||
|
return (
|
||||||
|
sites.deleted.is_(False), places.deleted.is_(False),
|
||||||
|
sites.status == SiteStatus.PUBLISHED.value,
|
||||||
|
sites.published_at.is_not(None), sites.current_version_id.is_not(None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def lock_batch(session) -> bool:
|
||||||
|
# 여러 API 프로세스가 같은 크론을 등록해도 외부 호출은 한 곳만 수행한다.
|
||||||
|
return bool(await session.scalar(text("SELECT pg_try_advisory_xact_lock(734920151)")))
|
||||||
|
|
||||||
|
|
||||||
|
async def new_publications(session, property_url: str):
|
||||||
|
result = await session.execute(
|
||||||
|
select(sites, places, site_versions)
|
||||||
|
.join(places, places.place_id == sites.place_id)
|
||||||
|
.join(site_versions, site_versions.site_version_id == sites.current_version_id)
|
||||||
|
.outerjoin(Status, Status.site_id == sites.site_id)
|
||||||
|
.where(*published_conditions(), site_versions.deleted.is_(False), or_(
|
||||||
|
Status.site_id.is_(None), Status.site_version_id != sites.current_version_id,
|
||||||
|
Status.property_url != property_url, Status.published_at != sites.published_at,
|
||||||
|
))
|
||||||
|
.order_by(sites.published_at).limit(100)
|
||||||
|
)
|
||||||
|
return result.all()
|
||||||
|
|
||||||
|
|
||||||
|
async def register(session, values: dict):
|
||||||
|
reset = dict(values, sitemap_submitted_at=None, inspected_at=None, first_indexed_at=None,
|
||||||
|
inspection=None, error_code=None, failures=0, alerted_at=None,
|
||||||
|
next_check_at=text("now()"), updated_at=text("now()"), deleted=False)
|
||||||
|
await session.execute(insert(Status).values(**values).on_conflict_do_update(
|
||||||
|
index_elements=[Status.site_id], set_=reset,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
async def due_sites(session, property_url: str):
|
||||||
|
result = await session.execute(
|
||||||
|
select(Status).join(sites, sites.site_id == Status.site_id)
|
||||||
|
.join(places, places.place_id == sites.place_id)
|
||||||
|
.where(*published_conditions(), Status.deleted.is_(False),
|
||||||
|
Status.site_version_id == sites.current_version_id,
|
||||||
|
Status.published_at == sites.published_at, Status.property_url == property_url,
|
||||||
|
Status.next_check_at <= text("now()"))
|
||||||
|
.order_by(Status.next_check_at).limit(5)
|
||||||
|
.with_for_update(of=Status)
|
||||||
|
)
|
||||||
|
return result.scalars().all()
|
||||||
@@ -45,6 +45,10 @@ class ISiteCRUD(ABC):
|
|||||||
async def get_version(self, cdb: AsyncSession, site_id, site_version_id) -> Tuple[ErrorType, site_versions]:
|
async def get_version(self, cdb: AsyncSession, site_id, site_version_id) -> Tuple[ErrorType, site_versions]:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get_version_by_number(self, cdb: AsyncSession, site_id, version: int) -> Tuple[ErrorType, site_versions]:
|
||||||
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
||||||
pass
|
pass
|
||||||
@@ -189,6 +193,31 @@ class SiteCRUD(ISiteCRUD):
|
|||||||
LOG.e_no_callstack(ex)
|
LOG.e_no_callstack(ex)
|
||||||
return ErrorType.DB_RUN_FAILED, None
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
|
async def get_version_by_number(self, cdb: AsyncSession, site_id, version: int) -> Tuple[ErrorType, site_versions]:
|
||||||
|
"""롤백 대상 조회 — site_versions.version(사람이 보는 번호) 로 찾는다.
|
||||||
|
|
||||||
|
★ site_version_id(uuid) 가 아니다. 화면·API 는 버전 번호로 고르는 게 자연스럽고,
|
||||||
|
그 번호가 곧 out/versions/<slug>/<version>/ 디렉토리 이름이다(prerender.ts)."""
|
||||||
|
try:
|
||||||
|
query = (
|
||||||
|
select(site_versions)
|
||||||
|
.where(
|
||||||
|
site_versions.site_id == site_id,
|
||||||
|
site_versions.version == version,
|
||||||
|
site_versions.deleted == False, # noqa: E712
|
||||||
|
)
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
return err_type, None
|
||||||
|
if len(rows) != 1:
|
||||||
|
return ErrorType.DB_INVALID_KEY, None
|
||||||
|
return ErrorType.SUCCESS, rows[0]
|
||||||
|
except Exception as ex:
|
||||||
|
LOG.e_no_callstack(ex)
|
||||||
|
return ErrorType.DB_RUN_FAILED, None
|
||||||
|
|
||||||
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
||||||
"""빌드 결과를 버전에 기록한다(BUILT 또는 FAILED)."""
|
"""빌드 결과를 버전에 기록한다(BUILT 또는 FAILED)."""
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ orjson
|
|||||||
pydantic>=2.0
|
pydantic>=2.0
|
||||||
python-multipart
|
python-multipart
|
||||||
httpx
|
httpx
|
||||||
|
google-auth>=2.0 # Search Console 서비스 계정 인증 (선택 기능)
|
||||||
|
requests>=2.31 # google-auth 토큰 갱신 transport
|
||||||
apscheduler>=3.10
|
apscheduler>=3.10
|
||||||
pydantic-settings # 환경변수·.env 로드 (FastAPI 공식 설정 방식)
|
pydantic-settings # 환경변수·.env 로드 (FastAPI 공식 설정 방식)
|
||||||
azure-storage-blob>=12.19
|
azure-storage-blob>=12.19
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import router.v1.place.place
|
|||||||
import router.v1.fact.fact
|
import router.v1.fact.fact
|
||||||
import router.v1.faq.faq
|
import router.v1.faq.faq
|
||||||
import router.v1.media.media
|
import router.v1.media.media
|
||||||
|
import router.v1.media.relay
|
||||||
import router.v1.job.job
|
import router.v1.job.job
|
||||||
import router.v1.site.site
|
import router.v1.site.site
|
||||||
import router.v1.site.showcase
|
import router.v1.site.showcase
|
||||||
@@ -86,6 +87,9 @@ app.include_router(router.v1.place.place.router)
|
|||||||
app.include_router(router.v1.fact.fact.router)
|
app.include_router(router.v1.fact.fact.router)
|
||||||
app.include_router(router.v1.faq.faq.router)
|
app.include_router(router.v1.faq.faq.router)
|
||||||
app.include_router(router.v1.media.media.router)
|
app.include_router(router.v1.media.media.router)
|
||||||
|
# ★ 인증 없는 공개 중계. 발행본(정적 페이지)이 캔버스에 사진을 그릴 때 부른다 —
|
||||||
|
# 남의 CDN 이 CORS 를 안 줘서 캔버스가 오염되는 것을 피하는 유일한 길이다(relay.py).
|
||||||
|
app.include_router(router.v1.media.relay.router)
|
||||||
app.include_router(router.v1.job.job.router)
|
app.include_router(router.v1.job.job.router)
|
||||||
app.include_router(router.v1.site.site.router)
|
app.include_router(router.v1.site.site.router)
|
||||||
app.include_router(router.v1.site.site.my_router)
|
app.include_router(router.v1.site.site.my_router)
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""사진 중계 — 남의 도메인 사진을 **우리 오리진으로** 흘려보낸다.
|
||||||
|
|
||||||
|
★ 왜 필요한가 (2026-09-15, 실측)
|
||||||
|
수집한 사진은 `*.pstatic.net` · `tong.visitkorea.or.kr` 에 있고 그쪽은
|
||||||
|
`Access-Control-Allow-Origin` 을 주지 않는다. 그 사진을 캔버스에 그리면 캔버스가 **오염돼**
|
||||||
|
`toBlob` 이 막힌다 — 엽서 쓰기의 저장·공유가 죽는다. 브라우저 정책이라 클라이언트에서는
|
||||||
|
못 넘는다. CORS 없는 `fetch` 도 같은 벽이다. **같은 오리진에서 바이트가 와야** 풀린다.
|
||||||
|
|
||||||
|
★ 굽는 쪽(`site/scripts/prerender.ts` mirrorMedia)이 이미 사진을 내려받아 사이트 폴더에
|
||||||
|
놓는다. 그게 근본이다. 다만 그건 **다시 굽는 사이트에만** 적용된다 — 이미 나가 있는
|
||||||
|
사이트는 사장님이 재발행할 때까지 옛 주소를 문다. 이 중계가 그 사이를 메운다.
|
||||||
|
|
||||||
|
★ 열린 프록시가 되지 않게 좁혀 둔다. 이건 "아무 주소나 가져다주는 통로" 가 아니다:
|
||||||
|
· https 만
|
||||||
|
· 호스트가 `_ALLOWED_SUFFIXES` 에 있는 것만 (우리 수집기가 쓰는 사진 CDN)
|
||||||
|
· 응답이 이미지가 아니면 거절, 크기 상한
|
||||||
|
· 리다이렉트를 따라가되 최종 호스트도 다시 검사한다 — 안 그러면 allowlist 를 우회한다
|
||||||
|
"""
|
||||||
|
import ipaddress
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import APIRouter, HTTPException, Query, Response
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/v1/image", tags=["Image"])
|
||||||
|
|
||||||
|
# 우리 수집기가 사진을 가져오는 곳. 여기 없는 호스트는 중계하지 않는다.
|
||||||
|
# ★ 늘릴 때는 "우리가 이미 그 사진을 화면에 싣고 있는 곳인가" 를 먼저 본다.
|
||||||
|
_ALLOWED_SUFFIXES = (
|
||||||
|
".pstatic.net",
|
||||||
|
"tong.visitkorea.or.kr",
|
||||||
|
".visitkorea.or.kr",
|
||||||
|
"upload.wikimedia.org",
|
||||||
|
)
|
||||||
|
|
||||||
|
_MAX_BYTES = 8 * 1024 * 1024
|
||||||
|
_TIMEOUT = httpx.Timeout(10.0, connect=5.0)
|
||||||
|
# 기본 UA 를 거절하는 CDN 이 있다. 탐지 우회가 아니라 평범한 브라우저로 보이게 하는 것뿐이다.
|
||||||
|
_HEADERS = {"user-agent": "Mozilla/5.0 (compatible; o2o-web4ai/1.0)"}
|
||||||
|
|
||||||
|
|
||||||
|
def _allowed(url: str) -> bool:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
if parsed.scheme != "https" or not parsed.hostname:
|
||||||
|
return False
|
||||||
|
host = parsed.hostname.lower()
|
||||||
|
# 숫자 주소는 받지 않는다 — 사내망으로 향하는 통로를 만들지 않는다.
|
||||||
|
try:
|
||||||
|
ipaddress.ip_address(host)
|
||||||
|
return False
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
return any(host == suffix.lstrip(".") or host.endswith(suffix) for suffix in _ALLOWED_SUFFIXES)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/relay", summary="사진 중계 — 캔버스 오염을 피하려고 같은 오리진으로 흘려보낸다")
|
||||||
|
async def relay(url: str = Query(min_length=8, max_length=2000)):
|
||||||
|
"""인증을 요구하지 않는다. 발행본은 로그인 없이 열리는 정적 페이지이고, 여기서 나가는
|
||||||
|
것은 **그 페이지가 이미 화면에 싣고 있는 사진**뿐이다(allowlist 가 그걸 보장한다)."""
|
||||||
|
if not _allowed(url):
|
||||||
|
raise HTTPException(status_code=400, detail="중계할 수 없는 주소입니다")
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=_TIMEOUT, headers=_HEADERS, follow_redirects=True) as client:
|
||||||
|
res = await client.get(url)
|
||||||
|
except httpx.HTTPError as ex:
|
||||||
|
LOG.w(f"[image] 중계 실패 {url}: {ex}")
|
||||||
|
raise HTTPException(status_code=502, detail="사진을 가져오지 못했습니다")
|
||||||
|
|
||||||
|
# 리다이렉트로 allowlist 밖으로 나갔으면 거기서 끊는다.
|
||||||
|
if not _allowed(str(res.url)):
|
||||||
|
raise HTTPException(status_code=400, detail="중계할 수 없는 주소입니다")
|
||||||
|
|
||||||
|
kind = (res.headers.get("content-type") or "").split(";")[0].strip().lower()
|
||||||
|
if res.status_code != 200 or not kind.startswith("image/"):
|
||||||
|
raise HTTPException(status_code=502, detail="사진이 아닙니다")
|
||||||
|
if len(res.content) == 0 or len(res.content) > _MAX_BYTES:
|
||||||
|
raise HTTPException(status_code=502, detail="사진 크기가 범위를 벗어났습니다")
|
||||||
|
|
||||||
|
# 주소가 곧 내용이다(원본이 바뀌면 주소도 바뀐다) — 길게 캐시해서 중계 횟수를 줄인다.
|
||||||
|
return Response(
|
||||||
|
content=res.content,
|
||||||
|
media_type=kind,
|
||||||
|
headers={"cache-control": "public, max-age=604800, immutable"},
|
||||||
|
)
|
||||||
@@ -36,6 +36,17 @@ class Res_StartBuild(Res_WebPacketProtocol):
|
|||||||
created: bool = True
|
created: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class Req_Rollback(SiteProtocol):
|
||||||
|
"""예전 버전으로 공개 주소를 되돌린다.
|
||||||
|
|
||||||
|
★ 재굽기가 아니다 — 대상 버전이 디스크에 아직 있으면 심볼릭 링크만 돌린다. 지워졌으면
|
||||||
|
(보관 정책, prerender.ts pruneOldVersions) site_versions.snapshot 으로 다시 굽고 나서
|
||||||
|
돌린다. 어느 경우든 게이트를 다시 통과해야 한다(사장님이 이미 확인한 값이라 대개는
|
||||||
|
그대로 통과한다)."""
|
||||||
|
|
||||||
|
target_version: int
|
||||||
|
|
||||||
|
|
||||||
class SiteVersionData(WebPacketProtocol):
|
class SiteVersionData(WebPacketProtocol):
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from common.models.gmodel import PageParams, UserInfo
|
|||||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||||
from services.site_service import SiteService
|
from services.site_service import SiteService
|
||||||
from .protocol import (
|
from .protocol import (
|
||||||
|
Req_Rollback,
|
||||||
Req_SiteSlug,
|
Req_SiteSlug,
|
||||||
Req_SiteStatus,
|
Req_SiteStatus,
|
||||||
Req_SiteTemplate,
|
Req_SiteTemplate,
|
||||||
@@ -178,6 +179,20 @@ async def site_preview(
|
|||||||
return JSONResponse(content=payload)
|
return JSONResponse(content=payload)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
path="/version/rollback",
|
||||||
|
response_model=Res_StartBuild,
|
||||||
|
summary="예전 버전으로 되돌리기(비동기)",
|
||||||
|
description="target_version 을 다시 공개 주소로 내보낸다. 재수집·재생성을 하지 않는다 — "
|
||||||
|
"그 버전이 발행될 때 박제된 snapshot 을 그대로 다시 굽는다. 렌더러가 그 사이 "
|
||||||
|
"바뀌었을 수 있어 게이트는 다시 통과해야 한다. 실패하면 지금 공개된 버전은 그대로다.",
|
||||||
|
)
|
||||||
|
async def rollback_version(
|
||||||
|
place_id: UUID, req: Req_Rollback, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||||
|
):
|
||||||
|
return RemoveNoneResponse(await service.start_rollback(user_info, str(place_id), req))
|
||||||
|
|
||||||
|
|
||||||
@router.get(path="/version/list", response_model=Res_SiteVersions, summary="빌드 버전 목록")
|
@router.get(path="/version/list", response_model=Res_SiteVersions, summary="빌드 버전 목록")
|
||||||
async def list_versions(place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
async def list_versions(place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||||
return RemoveNoneResponse(await service.list_versions(user_info, str(place_id)))
|
return RemoveNoneResponse(await service.list_versions(user_info, str(place_id)))
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 SCHEDULER_ENABLED=1 인 프로세스에서만 등록한다.
|
다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 SCHEDULER_ENABLED=1 인 프로세스에서만 등록한다.
|
||||||
|
|
||||||
등록된 잡: 없음(스켈레톤). 붙을 잡 —
|
등록된 잡: Search Console (GSC_ENABLED=1, 10분마다). 붙을 잡 —
|
||||||
· 지역정보 갱신 : 축제 주 1회 / 관광정보 월 1회 / 날씨 시간 단위 — 행정구역 코드 단위 캐시 갱신
|
· 지역정보 갱신 : 축제 주 1회 / 관광정보 월 1회 / 날씨 시간 단위 — 행정구역 코드 단위 캐시 갱신
|
||||||
· 수집 재시도 : 실패한 수집 작업 재시도 (외부 API 실패 시 직전 값 유지 + 내부 알림)
|
· 수집 재시도 : 실패한 수집 작업 재시도 (외부 API 실패 시 직전 값 유지 + 내부 알림)
|
||||||
· 사이트 재빌드 : 검증 상태가 바뀐 place 만 개별 재빌드 (전체 재빌드 금지)
|
· 사이트 재빌드 : 검증 상태가 바뀐 place 만 개별 재빌드 (전체 재빌드 금지)
|
||||||
@@ -33,8 +33,12 @@ def start_scheduler():
|
|||||||
|
|
||||||
# 한국시간 기준. 잡은 scheduler/jobs.py 에 정의하고 여기서 add_job 으로 등록한다.
|
# 한국시간 기준. 잡은 scheduler/jobs.py 에 정의하고 여기서 add_job 으로 등록한다.
|
||||||
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
||||||
|
if os.environ.get("GSC_ENABLED") == "1":
|
||||||
|
from services.search_console_service import run_scheduled_check
|
||||||
|
_scheduler.add_job(run_scheduled_check, "interval", minutes=10,
|
||||||
|
id="search-console", max_instances=1, coalesce=True)
|
||||||
_scheduler.start()
|
_scheduler.start()
|
||||||
LOG.i("[scheduler] started (KST: 등록된 잡 없음)")
|
LOG.i(f"[scheduler] started (KST: {len(_scheduler.get_jobs())}개 잡)")
|
||||||
|
|
||||||
|
|
||||||
def shutdown_scheduler():
|
def shutdown_scheduler():
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""저장된 관측값만 출력한다. Google 호출/색인 요청은 하지 않는다."""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import site_search_status as Status
|
||||||
|
from common.enums import DBType
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async def read(session):
|
||||||
|
rows = (await session.execute(select(Status).where(Status.deleted.is_(False))
|
||||||
|
.order_by(Status.published_at.desc()))).scalars().all()
|
||||||
|
return [{"url": row.page_url, "published_at": row.published_at,
|
||||||
|
"sitemap_submitted_at": row.sitemap_submitted_at,
|
||||||
|
"inspected_at": row.inspected_at, "first_indexed_at": row.first_indexed_at,
|
||||||
|
"inspection": row.inspection, "error_code": row.error_code,
|
||||||
|
"next_check_at": row.next_check_at, "alerted_at": row.alerted_at} for row in rows]
|
||||||
|
try:
|
||||||
|
rows = await DB_SESSION_MNG.execute_lambda_write(DBType.MAIN.value, read)
|
||||||
|
print(json.dumps(rows, ensure_ascii=False, indent=2, default=str))
|
||||||
|
finally:
|
||||||
|
await DB_SESSION_MNG.dispose_all()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -22,7 +22,7 @@ def is_configured() -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def output_dir() -> Path:
|
def output_dir() -> Path:
|
||||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites"))
|
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/solution/site/out"))
|
||||||
|
|
||||||
|
|
||||||
def _content_type(path: Path) -> str:
|
def _content_type(path: Path) -> str:
|
||||||
@@ -104,7 +104,7 @@ def _upload_shared(container, root: Path, prefix: str) -> set[str]:
|
|||||||
for entry in sorted(root.iterdir()):
|
for entry in sorted(root.iterdir()):
|
||||||
# `s/` 는 사이트별 디렉터리다 — 발행한 사이트 하나만 따로 올린다.
|
# `s/` 는 사이트별 디렉터리다 — 발행한 사이트 하나만 따로 올린다.
|
||||||
# (여기서 함께 올리면 한 명이 발행할 때마다 전체 사이트를 다시 올리게 된다.)
|
# (여기서 함께 올리면 한 명이 발행할 때마다 전체 사이트를 다시 올리게 된다.)
|
||||||
if entry.name.startswith(".") or entry.name == SITE_ROOT_DIR:
|
if entry.name.startswith(".") or entry.name in {SITE_ROOT_DIR, "versions"}:
|
||||||
continue
|
continue
|
||||||
if entry.is_dir():
|
if entry.is_dir():
|
||||||
uploaded |= _upload_tree(container, root, entry.name, prefix)
|
uploaded |= _upload_tree(container, root, entry.name, prefix)
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ from services import (
|
|||||||
azure_static,
|
azure_static,
|
||||||
indexnow,
|
indexnow,
|
||||||
publish_gate,
|
publish_gate,
|
||||||
render_report,
|
render_service,
|
||||||
seo_keywords,
|
seo_keywords,
|
||||||
site_payload,
|
site_payload,
|
||||||
site_thumbnail,
|
site_thumbnail,
|
||||||
@@ -46,9 +46,9 @@ from services.snapshot import build_snapshot
|
|||||||
_site_crud = SiteCRUD()
|
_site_crud = SiteCRUD()
|
||||||
_place_crud = PlaceCRUD()
|
_place_crud = PlaceCRUD()
|
||||||
|
|
||||||
# 렌더러가 이 버전을 굽고 보고서를 돌려줄 때까지 기다리는 시간.
|
# 렌더러 subprocess 가 끝나기를 기다리는 시간(사진 내려받기 포함).
|
||||||
# ★ 넉넉해야 한다. 짧으면 멀쩡한 발행이 "렌더 대기 초과"로 실패한다 —
|
# ★ 넉넉해야 한다. 짧으면 멀쩡한 발행이 "렌더 시간 초과"로 실패한다 — 처음 보는 사진을
|
||||||
# 렌더러는 payload 를 2초 주기로 보고, 사이트 하나 굽는 데 1초 남짓 걸린다.
|
# 내려받는 발행은 몇 초가 더 걸린다(mirrorMedia, prerender.ts).
|
||||||
RENDER_TIMEOUT_SEC = float(os.environ.get("RENDER_TIMEOUT_SEC") or 180)
|
RENDER_TIMEOUT_SEC = float(os.environ.get("RENDER_TIMEOUT_SEC") or 180)
|
||||||
|
|
||||||
|
|
||||||
@@ -73,10 +73,13 @@ async def ensure_site(place_id: str) -> "sites":
|
|||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
async def _load_links(place_id: str) -> list:
|
async def load_channel_links(place_id: str) -> list:
|
||||||
"""채널 링크(야놀자·네이버 플레이스·인스타…).
|
"""채널 링크(야놀자·네이버 플레이스·인스타…).
|
||||||
|
|
||||||
스냅샷에 담기지 않는 유일한 발행 재료라 여기서 읽어 payload 로 넘긴다.
|
스냅샷에 담기지 않는 유일한 발행 재료라 여기서 읽어 payload 로 넘긴다 — 재빌드(run_build)
|
||||||
|
도 롤백(rollback_service.run_rollback)도 같은 함수를 쓴다. **스냅샷에는 안 싣는다** —
|
||||||
|
롤백이 옛 스냅샷으로 다시 구워도 링크는 항상 지금 확정된 것을 보여줘야 한다(끊긴 링크를
|
||||||
|
옛 버전째 되살리면 안 된다).
|
||||||
★ 실패해도 빈 목록으로 진행한다 — 링크가 없다고 발행을 막을 이유가 없다."""
|
★ 실패해도 빈 목록으로 진행한다 — 링크가 없다고 발행을 막을 이유가 없다."""
|
||||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||||
place_channels.DBType(),
|
place_channels.DBType(),
|
||||||
@@ -249,24 +252,25 @@ async def run_build(job: dict) -> dict:
|
|||||||
site.status = SiteStatus.PUBLISHED.value
|
site.status = SiteStatus.PUBLISHED.value
|
||||||
site.published_at = site.published_at or now
|
site.published_at = site.published_at or now
|
||||||
|
|
||||||
links = await _load_links(place_id)
|
links = await load_channel_links(place_id)
|
||||||
payload_path = await emit_payload(place, snapshot, site, version, links)
|
payload_path = await emit_payload(place, snapshot, site, version, links, publish=want_publish)
|
||||||
if not payload_path:
|
if not payload_path:
|
||||||
return await _fail("payload 를 쓰지 못했다 — 렌더러에 넘길 입력이 없다")
|
return await _fail("payload 를 쓰지 못했다 — 렌더러에 넘길 입력이 없다")
|
||||||
result["payload_path"] = payload_path
|
result["payload_path"] = payload_path
|
||||||
|
|
||||||
slug = site_payload.publish_slug(place, site)
|
slug = site_payload.publish_slug(place, site)
|
||||||
|
|
||||||
# ---- 렌더 결과를 기다린다 ----
|
# ---- 렌더러를 직접 돌린다 ----
|
||||||
# ★ 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 렌더러가 자기 산출물을 대조해
|
# ★ 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 렌더러가 자기 산출물을 대조해
|
||||||
# 구조화 데이터 불일치와 고유 콘텐츠 수를 보고서로 돌려준다.
|
# 구조화 데이터 불일치와 고유 콘텐츠 수를 보고서로 돌려준다.
|
||||||
report = await render_report.wait_for(slug, version_no, RENDER_TIMEOUT_SEC)
|
# ★ payload=False(미발행)면 렌더러는 `out/versions/<slug>/<version>/` 에만 굽고 공개
|
||||||
if report is None:
|
# 주소(`out/s/<slug>`)는 건드리지 않는다 — emit_payload 에 실은 publish 플래그가 정한다.
|
||||||
|
try:
|
||||||
|
report = await render_service.render_site(payload_path, version_no, RENDER_TIMEOUT_SEC)
|
||||||
|
except render_service.RenderFailed as ex:
|
||||||
# ★ 발행하지 않는다. 페이지가 있는지 확인하지 못한 채 "발행됨"으로 남기면
|
# ★ 발행하지 않는다. 페이지가 있는지 확인하지 못한 채 "발행됨"으로 남기면
|
||||||
# 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다.
|
# 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다.
|
||||||
return await _fail(
|
return await _fail(str(ex))
|
||||||
f"렌더 결과를 {RENDER_TIMEOUT_SEC}초 안에 받지 못했다 — 렌더러가 도는지 확인이 필요하다"
|
|
||||||
)
|
|
||||||
|
|
||||||
mismatches = list(report.get("mismatches") or [])
|
mismatches = list(report.get("mismatches") or [])
|
||||||
# ★ None(재지 못했다)과 0(재 봤더니 0건)을 뭉개지 않는다. 게이트는 raw 를 보고,
|
# ★ None(재지 못했다)과 0(재 봤더니 0건)을 뭉개지 않는다. 게이트는 raw 를 보고,
|
||||||
@@ -308,8 +312,9 @@ async def run_build(job: dict) -> dict:
|
|||||||
thumbnail_url = None
|
thumbnail_url = None
|
||||||
if want_publish:
|
if want_publish:
|
||||||
try:
|
try:
|
||||||
|
await render_service.activate_site(slug, version_no)
|
||||||
azure_result = await azure_static.publish(slug)
|
azure_result = await azure_static.publish(slug)
|
||||||
except azure_static.AzurePublishError as ex:
|
except (azure_static.AzurePublishError, render_service.RenderFailed) as ex:
|
||||||
return await _fail(str(ex), None, stamp)
|
return await _fail(str(ex), None, stamp)
|
||||||
if azure_result:
|
if azure_result:
|
||||||
result["azure"] = azure_result
|
result["azure"] = azure_result
|
||||||
@@ -383,4 +388,3 @@ async def run_build(job: dict) -> dict:
|
|||||||
version.build_status = BuildStatus.BUILT.value
|
version.build_status = BuildStatus.BUILT.value
|
||||||
version.built_at = now
|
version.built_at = now
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -11,9 +11,12 @@
|
|||||||
`search_results` 의 첫 줄을 붙인다 — 모델 답변은 환각이 섞이지만 search_results 는
|
`search_results` 의 첫 줄을 붙인다 — 모델 답변은 환각이 섞이지만 search_results 는
|
||||||
실제로 검색된 주소다(`grounding/channels.py` 와 같은 판단).
|
실제로 검색된 주소다(`grounding/channels.py` 와 같은 판단).
|
||||||
둘 다 없으면 항목을 버린다. 출처 없는 사실은 이 레포의 규칙 위반이다.
|
둘 다 없으면 항목을 버린다. 출처 없는 사실은 이 레포의 규칙 위반이다.
|
||||||
|
★ 예외가 하나 있다 — `_SEARCH_LINK_KINDS`. 거기 있는 종류는 **모델의 URL 을 아예 안 받고**
|
||||||
|
제목으로 찾아가는 검색 링크를 코드가 만든다.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
|
|
||||||
@@ -23,10 +26,27 @@ _TITLE_KEY = {
|
|||||||
"daily": "title",
|
"daily": "title",
|
||||||
"people": "name",
|
"people": "name",
|
||||||
"chronicle": "title",
|
"chronicle": "title",
|
||||||
|
"reading": "title",
|
||||||
"postcard": "line",
|
"postcard": "line",
|
||||||
"quiz": "question",
|
"quiz": "question",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ★ 출처를 **모델에게 받지 않고 코드가 만드는** 종류.
|
||||||
|
# 개별 문서 주소(`terms.naver.com/entry.naver?docId=…`)는 짐작해서 적으면 없는 문서로
|
||||||
|
# 이어진다 — 레포 절대규칙(없는 사실을 짓지 않는다)에 걸린다. 검색 링크는 제목을 그대로
|
||||||
|
# 넘기니 항상 관련 결과로 뜬다. 2026-09-14 대표 지시("확인필요 없애고 링크는 네이버 링크로"),
|
||||||
|
# 시연본 구현은 `site/scripts/mockup/build_reading.py` 의 `naver()`.
|
||||||
|
_SEARCH_LINK_KINDS = {"reading"}
|
||||||
|
|
||||||
|
|
||||||
|
def _search_source(title: str, region_label: str) -> dict:
|
||||||
|
"""제목으로 찾아가는 검색 링크. 지역명이 제목에 없으면 붙여 검색 정확도를 올린다."""
|
||||||
|
region = (region_label or "").split()[-1] if region_label else ""
|
||||||
|
query = title if (not region or region[:-1] in title or region in title) else f"{title} {region}"
|
||||||
|
return {"name": "네이버에서 찾아보기",
|
||||||
|
"url": "https://search.naver.com/search.naver?query=" + quote(query)}
|
||||||
|
|
||||||
|
|
||||||
# 코드펜스를 두르고 오는 경우가 있다. 규칙 1 로 금지했지만 모델은 종종 어긴다.
|
# 코드펜스를 두르고 오는 경우가 있다. 규칙 1 로 금지했지만 모델은 종종 어긴다.
|
||||||
_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE)
|
_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE)
|
||||||
|
|
||||||
@@ -57,7 +77,9 @@ def _clean_source(value) -> dict | None:
|
|||||||
return {"name": (value.get("name") or url).strip(), "url": url}
|
return {"name": (value.get("name") or url).strip(), "url": url}
|
||||||
|
|
||||||
|
|
||||||
def parse_items(payload: dict, kind: str, limit: int) -> tuple[list[dict], list[str]]:
|
def parse_items(
|
||||||
|
payload: dict, kind: str, limit: int, region_label: str = ""
|
||||||
|
) -> tuple[list[dict], list[str]]:
|
||||||
"""(쓸 수 있는 항목, 버린 이유) — 버린 이유는 로그와 잡 결과에 남긴다.
|
"""(쓸 수 있는 항목, 버린 이유) — 버린 이유는 로그와 잡 결과에 남긴다.
|
||||||
|
|
||||||
한 항목이 잘못돼도 나머지를 살린다. 지역 하나에 8~14건인데 한 줄 때문에 전부 버리면
|
한 항목이 잘못돼도 나머지를 살린다. 지역 하나에 8~14건인데 한 줄 때문에 전부 버리면
|
||||||
@@ -101,6 +123,14 @@ def parse_items(payload: dict, kind: str, limit: int) -> tuple[list[dict], list[
|
|||||||
item = {k: v for k, v in raw.items() if v not in (None, "", [], {})}
|
item = {k: v for k, v in raw.items() if v not in (None, "", [], {})}
|
||||||
item[title_key] = title
|
item[title_key] = title
|
||||||
|
|
||||||
|
if kind in _SEARCH_LINK_KINDS:
|
||||||
|
# 출처는 코드가 만든다(위 _SEARCH_LINK_KINDS). 모델이 URL 을 적어 왔어도 버린다 —
|
||||||
|
# 짐작해 적은 주소가 섞이는 통로를 아예 남기지 않는다. 검수 배지도 함께 뺀다.
|
||||||
|
item["source"] = _search_source(title, region_label)
|
||||||
|
item.pop("verified", None)
|
||||||
|
out.append(item)
|
||||||
|
continue
|
||||||
|
|
||||||
source = _clean_source(raw.get("source")) or fallback
|
source = _clean_source(raw.get("source")) or fallback
|
||||||
if source is None:
|
if source is None:
|
||||||
dropped.append(f"{title}: 출처가 없다")
|
dropped.append(f"{title}: 출처가 없다")
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ def is_configured() -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def output_dir() -> Path:
|
def output_dir() -> Path:
|
||||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites"))
|
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/solution/site/out"))
|
||||||
|
|
||||||
|
|
||||||
def site_urls(slug: str) -> list[str]:
|
def site_urls(slug: str) -> list[str]:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
"label": "가요 다방",
|
"label": "가요 다방",
|
||||||
"maxItems": 8,
|
"maxItems": 8,
|
||||||
"task": "[해야 할 일]\n[지역]을 노래한 대중가요를 8곡까지 찾아 아래 JSON 으로 정리한다.\n1960~80년대 곡을 우선하고, 지명·항구·강·다리가 제목이나 배경에 나오는 곡을 고른다.\n\n[스키마]\n{ \"kind\":\"songs\", \"version\":1, \"title\":\"가요 다방\", \"subtitle\":\"...\", \"items\":[\n { \"title\":\"곡명\", \"artist\":\"가수\", \"lyricist\":\"작사\", \"composer\":\"작곡\",\n \"year\":1966, \"label\":\"음반사\", \"labelColor\":\"#d4551f\",\n \"story\":\"곡의 배경 (두 문장 이내, 가사 없이)\",\n \"connection\":\"[업소]와 이 곡을 잇는 한 문장\",\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
"task": "[해야 할 일]\n[지역]을 노래한 대중가요를 8곡까지 찾아 아래 JSON 으로 정리한다.\n1960~80년대 곡을 우선하고, 지명·항구·강·다리가 제목이나 배경에 나오는 곡을 고른다.\n\n[스키마]\n{ \"kind\":\"songs\", \"version\":1, \"title\":\"가요 다방\", \"subtitle\":\"...\", \"items\":[\n { \"title\":\"곡명\", \"artist\":\"가수\", \"lyricist\":\"작사\", \"composer\":\"작곡\",\n \"year\":1966, \"label\":\"음반사\", \"labelColor\":\"#d4551f\",\n \"story\":\"곡의 배경 (두 문장 이내, 가사 없이)\",\n \"connection\":\"[업소]와 이 곡을 잇는 한 문장\",\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
||||||
"rules": "\n[이 아이템만의 규칙]\n· lyrics 필드는 스키마에 없다. 어떤 이유로도 만들지 마라. 가사 한 소절도 안 된다.\n· labelColor 는 레코드 라벨 색이다. 곡의 분위기에 맞춰 진한 색 하나를 hex 로 고른다.\n· 작사·작곡·발표연도를 모르면 그 필드를 뺀다. \"미상\" 이라고 쓰지 않는다.\n"
|
"rules": "\n[이 아이템만의 규칙]\n· lyrics 필드는 스키마에 없다. 어떤 이유로도 만들지 마라. 가사 한 소절도 안 된다.\n· labelColor 는 레코드 라벨 색이다. 곡의 분위기에 맞춰 진한 색 하나를 hex 로 고른다.\n **이건 사실이 아니라 디자인 값이다 — 공통 규칙 2 를 적용하지 말고 곡마다 반드시 채운다.**\n 앞뒤 곡과 같은 색을 쓰지 않는다. 비워 두면 판이 전부 한 색으로 깔린다(실측 2026-09-15:\n 67곡 중 63곡이 비어 있었다).\n· 작사·작곡·발표연도를 모르면 그 필드를 뺀다. \"미상\" 이라고 쓰지 않는다.\n"
|
||||||
},
|
},
|
||||||
"daily": {
|
"daily": {
|
||||||
"kind": "daily",
|
"kind": "daily",
|
||||||
@@ -30,6 +30,13 @@
|
|||||||
"task": "[해야 할 일]\n[지역]의 역사를 연도순으로 10~14개 사건으로 정리한다.\n가장 오래된 것부터 가장 최근까지 고르게 펴고, 한 시대에 몰지 않는다.\n\n[스키마]\n{ \"kind\":\"chronicle\", \"version\":1, \"title\":\"시간의 골목\", \"items\":[\n { \"year\":1899, \"title\":\"사건 이름\", \"summary\":\"두 문장 이내\",\n \"place\":\"지금 가 볼 수 있는 자리\", \"turning\":true,\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
"task": "[해야 할 일]\n[지역]의 역사를 연도순으로 10~14개 사건으로 정리한다.\n가장 오래된 것부터 가장 최근까지 고르게 펴고, 한 시대에 몰지 않는다.\n\n[스키마]\n{ \"kind\":\"chronicle\", \"version\":1, \"title\":\"시간의 골목\", \"items\":[\n { \"year\":1899, \"title\":\"사건 이름\", \"summary\":\"두 문장 이내\",\n \"place\":\"지금 가 볼 수 있는 자리\", \"turning\":true,\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
||||||
"rules": "\n[이 아이템만의 규칙]\n· turning 은 도시의 성격을 바꾼 해에만 true 다. 3~4개를 넘기지 않는다.\n· 연도가 불확실하면 그 항목을 통째로 뺀다. 연표에서 틀린 연도는 바로 들킨다.\n· place 는 지금도 찾아갈 수 있는 자리만 적는다. 없으면 필드를 뺀다.\n· 다만 **찾아갈 수 있는 자리가 있으면 반드시 적는다.** 행정 개편처럼 장소가 없어 보이는\n 사건에도 그 일이 남긴 자리가 대개 있다(개항 → 항구, 부두 건설 → 그 부두, 준공 → 그 구조물).\n 이 값으로 공공데이터에서 그 해의 사진을 찾아 붙인다 — 비면 연표가 활자만으로 선다.\n"
|
"rules": "\n[이 아이템만의 규칙]\n· turning 은 도시의 성격을 바꾼 해에만 true 다. 3~4개를 넘기지 않는다.\n· 연도가 불확실하면 그 항목을 통째로 뺀다. 연표에서 틀린 연도는 바로 들킨다.\n· place 는 지금도 찾아갈 수 있는 자리만 적는다. 없으면 필드를 뺀다.\n· 다만 **찾아갈 수 있는 자리가 있으면 반드시 적는다.** 행정 개편처럼 장소가 없어 보이는\n 사건에도 그 일이 남긴 자리가 대개 있다(개항 → 항구, 부두 건설 → 그 부두, 준공 → 그 구조물).\n 이 값으로 공공데이터에서 그 해의 사진을 찾아 붙인다 — 비면 연표가 활자만으로 선다.\n"
|
||||||
},
|
},
|
||||||
|
"reading": {
|
||||||
|
"kind": "reading",
|
||||||
|
"label": "지역 읽기",
|
||||||
|
"maxItems": 34,
|
||||||
|
"task": "[해야 할 일]\n[지역]을 소개하는 글 30~34꼭지를 갈래로 나눠 쓴다.\n갈래는 다섯이다 — 문학 · 섬과 바다 · 역사 · 장소 · 음식과 생활.\n한 갈래에 몰지 않되, 댈 수 있는 사실이 적은 갈래는 적게 쓴다.\n\n[스키마]\n{ \"kind\":\"reading\", \"version\":1, \"title\":\"[지역] 읽기\",\n \"subtitle\":\"문학 · 섬과 바다 · 역사 · 장소 · 음식과 생활 — 올 때마다 다른 몇 가지\",\n \"items\":[\n { \"group\":\"문학|섬과 바다|역사|장소|음식과 생활\",\n \"title\":\"꼭지 제목\", \"body\":\"서너 문장\", \"year\":1937 } ] }",
|
||||||
|
"rules": "\n[이 아이템만의 규칙]\n· body 는 **서너 문장**이다. 두 문장이면 카드가 한 줄로 접혀 빈 카드처럼 보인다.\n 다만 문장을 늘리려고 없는 숫자·연도·거리를 지어내지 않는다 — 널리 알려진 배경만 보탠다.\n· **이미 다른 자리에 선 것은 쓰지 않는다.** 인물·대중가요·축제·연표 사건·주변 명소·맛집은\n 각자 섹션이 있다. 같은 것을 두 번 세우면 페이지만 길어지고 손님은 같은 말을 두 번 읽는다.\n· year 는 연도를 댈 수 있는 꼭지에만 쓴다. 짐작해서 넣지 않는다.\n· source 와 verified 를 적지 않는다. **주소를 짐작해 적으면 없는 문서로 이어진다** —\n 제목으로 찾아가는 검색 링크를 서버가 붙인다(2026-09-14 대표 지시).\n· 시·소설·가사의 원문을 한 줄도 옮기지 않는다. 제목과 배경만 쓴다.\n· 부제에 전체 개수를 적지 않는다. 화면은 이 중 5~6개만 매번 무작위로 보여준다 —\n 숫자를 박으면 보이는 개수와 어긋난다.\n"
|
||||||
|
},
|
||||||
"postcard": {
|
"postcard": {
|
||||||
"kind": "postcard",
|
"kind": "postcard",
|
||||||
"label": "오늘의 엽서",
|
"label": "오늘의 엽서",
|
||||||
|
|||||||
@@ -1,22 +1,18 @@
|
|||||||
"""렌더 보고서 — SSG 가 실제로 페이지를 구웠는지 확인하는 창구.
|
"""렌더 보고서 — SSG 가 실제로 페이지를 구웠는지 확인하는 창구.
|
||||||
|
|
||||||
★ 왜 필요한가
|
★ 왜 필요한가
|
||||||
발행 잡은 payload JSON 을 쓰는 것까지가 끝이고, 방문자가 볼 HTML 은 프론트의 SSG 가 굽는다.
|
BUILD 잡은 payload JSON 을 쓰고 렌더러를 직접 돌린다(services/render_service). 렌더러는
|
||||||
그 사이가 끊겨 있었다. 프리렌더가 깨져도 DB 에는 "발행됨"으로 남고, 페이지는 없는데
|
굽는 동안 있었던 일(성공/실패, 구조화 데이터 대조, 고유 콘텐츠 수)을 사이트마다
|
||||||
아무도 그걸 모른다 — 사장님이 [사이트 열기] 를 눌러야 404 로 발견된다.
|
`<payload_dir>/.status/<slug>.json` 에 남긴다 — 백엔드에 마운트된 디렉토리가 payload
|
||||||
|
디렉토리뿐이라 보고서도 그 안에 둔다.
|
||||||
|
|
||||||
이제 프리렌더가 사이트마다 결과를 `<payload_dir>/.status/<slug>.json` 에 쓴다.
|
★ 여기서 하는 일 — 그 보고서를 읽는다.
|
||||||
백엔드에 마운트된 디렉토리가 payload 디렉토리뿐이라 보고서도 그 안에 둔다.
|
render_service 가 렌더러 subprocess 를 기다린 **직후** 한 번 읽어 발행 여부를 정하고,
|
||||||
|
사이트 조회 API(render_status)는 아무 때나 다시 읽어 "지금 이 버전이 구워져 있나" 를 보여준다.
|
||||||
★ 여기서 하는 두 가지
|
|
||||||
1. 렌더 상태 — 구워졌는가, 언제, 실패했으면 왜 (사이트 조회 API 가 그대로 내보낸다)
|
|
||||||
2. 발행 대기 — BUILD 잡이 이 버전의 보고서를 기다렸다가, 그 결과로 발행 여부를 정한다
|
|
||||||
(wait_for). 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다.
|
|
||||||
|
|
||||||
★ 읽기 전용이다. 보고서가 없거나 깨져 있어도 예외를 밖으로 내보내지 않는다 —
|
★ 읽기 전용이다. 보고서가 없거나 깨져 있어도 예외를 밖으로 내보내지 않는다 —
|
||||||
사이트 조회가 부수 산출물 때문에 실패하면 안 된다.
|
사이트 조회가 부수 산출물 때문에 실패하면 안 된다.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -58,29 +54,6 @@ def read_report(slug: str) -> dict | None:
|
|||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
async def wait_for(slug: str, site_version: int, timeout_sec: float, poll_sec: float = 1.0) -> dict | None:
|
|
||||||
"""이 버전의 렌더 보고서가 나올 때까지 기다린다. 시간 안에 안 나오면 None.
|
|
||||||
|
|
||||||
★ 왜 기다리나
|
|
||||||
발행 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 그 HTML 은 프론트 렌더러가
|
|
||||||
굽고, 렌더러는 payload 파일을 보고 도는 별도 프로세스다. 그래서 잡이 payload 를 쓴 뒤
|
|
||||||
보고서가 올 때까지 기다렸다가, 그 결과로 발행 여부를 정한다.
|
|
||||||
|
|
||||||
★ 버전이 맞는 보고서만 받는다. 직전 버전 보고서를 보고 통과시키면 이번에 바뀐 값은
|
|
||||||
아무도 검사하지 않은 채로 발행된다.
|
|
||||||
|
|
||||||
★ BUILD 잡은 heartbeat 로 lease 를 갱신하므로 여기서 기다려도 reaper 에 회수되지 않는다."""
|
|
||||||
deadline = asyncio.get_running_loop().time() + timeout_sec
|
|
||||||
while True:
|
|
||||||
report = read_report(slug)
|
|
||||||
if report is not None and report.get("siteVersion") == site_version:
|
|
||||||
return report
|
|
||||||
if asyncio.get_running_loop().time() >= deadline:
|
|
||||||
LOG.w(f"[render] 보고서 대기 시간 초과 slug={slug} v{site_version} ({timeout_sec}초)")
|
|
||||||
return None
|
|
||||||
await asyncio.sleep(poll_sec)
|
|
||||||
|
|
||||||
|
|
||||||
def render_status(slug: str, site_version: int | None = None) -> dict:
|
def render_status(slug: str, site_version: int | None = None) -> dict:
|
||||||
"""사이트 조회 API 가 그대로 내보내는 렌더 상태.
|
"""사이트 조회 API 가 그대로 내보내는 렌더 상태.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""렌더러 실행 — Python 워커가 미리 컴파일된 Node 렌더러를 subprocess 로 직접 돌린다.
|
||||||
|
|
||||||
|
★ 왜 (프리렌더를 워커 실행으로 통합, 2026-09-15)
|
||||||
|
예전에는 `solution-prerender` 라는 별도 상시 컨테이너가 payloads/ 디렉토리를 2초마다
|
||||||
|
폴링하며 바뀐 파일을 구웠고, BUILD 잡은 `.status/<slug>.json` 이 나타나기를 또 폴링했다
|
||||||
|
(render_report.wait_for). 컨테이너 하나·폴링 두 겹이 전부 "굽는 걸 어떻게 아느냐"는
|
||||||
|
같은 문제를 풀고 있었다 — 워커가 굽기를 직접 돌리면 둘 다 필요 없다: subprocess 가
|
||||||
|
끝나는 순간이 곧 "구워졌다"는 신호다.
|
||||||
|
|
||||||
|
★ 이 파일은 payload → 렌더러 실행 → 구조화된 결과, 그 경계만 다룬다.
|
||||||
|
Python 은 여전히 HTML 을 만들지 않는다(ARCHITECTURE 1절) — 여기서 하는 일은 미리 빌드된
|
||||||
|
JS 파일 하나를 `node` 로 실행하고 그 결과 보고서(.status/<slug>.json, prerender.ts 가 쓴다)
|
||||||
|
를 읽어 돌려주는 것뿐이다. 렌더러 코드 자체는 solution/site 소유 그대로다.
|
||||||
|
|
||||||
|
★ 워커 이미지에는 컴파일된 렌더러(`dist/client` · `dist/prerender/prerender.js`)와 `public/`
|
||||||
|
만 있으면 된다 — node_modules 는 필요 없다(vite.config.ts `ssr.noExternal: true`, 실측:
|
||||||
|
node_modules 를 지우고 실행해도 그대로 돈다). 기동·잡 실행 중에 npm install 을 하지 않는다.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import fcntl
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
from services import render_report
|
||||||
|
|
||||||
|
# 컴파일된 렌더러 진입점. Dockerfile 의 site-builder 스테이지가 여기에 굽는다.
|
||||||
|
RENDERER_ENTRY_ENV = "RENDERER_ENTRY"
|
||||||
|
DEFAULT_RENDERER_ENTRY = "/app/solution/site/dist/prerender/prerender.js"
|
||||||
|
|
||||||
|
NODE_BIN_ENV = "NODE_BIN"
|
||||||
|
DEFAULT_NODE_BIN = "node"
|
||||||
|
|
||||||
|
# 렌더러가 굽는 산출물 루트(out/). services/azure_static·indexnow 와 **같은 env** 를 본다 —
|
||||||
|
# 렌더러가 쓴 자리와 백엔드가 훑는 자리가 어긋나면 "구웠는데 없다"는 조용한 실패가 난다.
|
||||||
|
OUTPUT_DIR_ENV = "SITE_OUTPUT_DIR"
|
||||||
|
DEFAULT_OUTPUT_DIR = "/app/solution/site/out"
|
||||||
|
|
||||||
|
|
||||||
|
class RenderFailed(RuntimeError):
|
||||||
|
"""렌더러 프로세스 자체가 죽었거나(비정상 종료) 보고서를 남기지 못했다.
|
||||||
|
|
||||||
|
★ 게이트 반려(구조화 데이터 불일치·고유 콘텐츠 0건)는 여기 안 걸린다 — 그건 exit code
|
||||||
|
1 이어도 보고서가 정상적으로 남으므로 호출측이 report.ok 로 판단한다. 이 예외는
|
||||||
|
"무슨 일이 있었는지조차 모른다" 는 경우만 위한 것이다."""
|
||||||
|
|
||||||
|
|
||||||
|
def renderer_entry() -> str:
|
||||||
|
return os.environ.get(RENDERER_ENTRY_ENV) or DEFAULT_RENDERER_ENTRY
|
||||||
|
|
||||||
|
|
||||||
|
def output_dir() -> str:
|
||||||
|
return os.environ.get(OUTPUT_DIR_ENV) or DEFAULT_OUTPUT_DIR
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_subprocess(args: list[str], timeout_sec: float) -> tuple[int | None, str]:
|
||||||
|
"""같은 볼륨의 자산 대장·사이트맵은 한 프로세스만 갱신한다."""
|
||||||
|
root = Path(output_dir())
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
with (root / ".render.lock").open("a") as lock:
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(timeout_sec):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
break
|
||||||
|
except BlockingIOError:
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
return await _run_unlocked(args, timeout_sec)
|
||||||
|
except TimeoutError:
|
||||||
|
return None, "렌더 대기 또는 실행 시간 초과"
|
||||||
|
finally:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_unlocked(args: list[str], timeout_sec: float) -> tuple[int | None, str]:
|
||||||
|
"""렌더러 프로세스를 돌리고 (exit_code, stderr 일부) 를 돌려준다.
|
||||||
|
|
||||||
|
★ 타임아웃이면 프로세스를 죽이고 회수한다 — 좀비로 남겨 워커 컨테이너의 프로세스 표를
|
||||||
|
채우면 안 된다. exit_code 는 None 으로 남아 "시간 안에 안 끝났다" 를 구분한다."""
|
||||||
|
proc = await asyncio.create_subprocess_exec(
|
||||||
|
*args,
|
||||||
|
stdout=asyncio.subprocess.PIPE,
|
||||||
|
stderr=asyncio.subprocess.PIPE,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
_stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout_sec)
|
||||||
|
except (asyncio.TimeoutError, TimeoutError):
|
||||||
|
proc.kill()
|
||||||
|
# kill 후에도 반드시 wait 한다 — 안 하면 좀비 프로세스로 남는다.
|
||||||
|
await proc.wait()
|
||||||
|
return None, f"{timeout_sec:.0f}초 안에 끝나지 않아 강제 종료했다"
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
if proc.returncode is None:
|
||||||
|
proc.kill()
|
||||||
|
await proc.wait()
|
||||||
|
raise
|
||||||
|
# 사유는 앞부분에 나온다(watch-payloads.mjs 의 run() 과 같은 규칙) — 스택 전체를 들 이유가 없다.
|
||||||
|
return proc.returncode, stderr.decode("utf-8", errors="replace")[:4000]
|
||||||
|
|
||||||
|
|
||||||
|
async def render_site(payload_path: str, site_version: int, timeout_sec: float) -> dict:
|
||||||
|
"""payload 파일 하나를 굽는다. 끝나면 렌더 보고서(dict)를 돌려준다.
|
||||||
|
|
||||||
|
★ 게이트 판정은 여기서 하지 않는다 — 반환된 보고서의 `ok`·`mismatches`·
|
||||||
|
`uniqueContentCount` 를 build_service.run_build 가 그대로 판단한다(예전과 같은 계약,
|
||||||
|
render_report.wait_for 가 폴링해서 얻던 것과 같은 모양이다).
|
||||||
|
★ 멱등이다 — 같은 payload 파일로 다시 부르면 같은 결과가 나온다(재시도 안전). 렌더러
|
||||||
|
자신이 사이트별로 실패를 격리하므로, 이미 성공한 사이트를 다시 구워도 결과는 같다."""
|
||||||
|
slug = Path(payload_path).stem
|
||||||
|
# 재시도에서 같은 버전의 옛 성공 보고서를 이번 실행 결과로 읽지 않는다.
|
||||||
|
render_report.report_path(slug).unlink(missing_ok=True)
|
||||||
|
args = [
|
||||||
|
os.environ.get(NODE_BIN_ENV) or DEFAULT_NODE_BIN,
|
||||||
|
renderer_entry(),
|
||||||
|
f"--payload={payload_path}",
|
||||||
|
f"--out={output_dir()}",
|
||||||
|
"--stage-only",
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
code, stderr = await _run_subprocess(args, timeout_sec)
|
||||||
|
except OSError as ex:
|
||||||
|
raise RenderFailed(f"렌더러 실행 실패: {type(ex).__name__}") from ex
|
||||||
|
|
||||||
|
report = render_report.read_report(slug)
|
||||||
|
if code in (0, 1) and report is not None and report.get("siteVersion") == site_version:
|
||||||
|
return report
|
||||||
|
|
||||||
|
# ★ 프로세스가 죽거나 시간 초과였는데 보고서도 없으면(사이트를 하나도 돌기 전에 죽은 경우)
|
||||||
|
# 대신 실패로 남긴다 — 안 그러면 build_service 가 "렌더 결과를 못 받았다" 는 것만 알고
|
||||||
|
# 진짜 사유(모듈 누락·OOM 등)는 워커 로그에만 남는다.
|
||||||
|
reason = (
|
||||||
|
f"렌더러가 {timeout_sec:.0f}초 안에 끝나지 않았다"
|
||||||
|
if code is None
|
||||||
|
else f"렌더러가 비정상 종료했다(exit {code})" if code != 0 else "보고서를 남기지 못했다(버전 불일치 포함)"
|
||||||
|
)
|
||||||
|
detail = f"{reason}" + (f" — {stderr.strip()}" if stderr.strip() else "")
|
||||||
|
LOG.w(f"[render] {slug} v{site_version}: {detail}")
|
||||||
|
raise RenderFailed(detail)
|
||||||
|
|
||||||
|
|
||||||
|
async def activate_site(slug: str, site_version: int) -> None:
|
||||||
|
"""두 게이트를 통과한 뒤 Node가 공개 링크만 전환한다."""
|
||||||
|
args = [
|
||||||
|
os.environ.get(NODE_BIN_ENV) or DEFAULT_NODE_BIN,
|
||||||
|
renderer_entry(), f"--out={output_dir()}", f"--activate={slug}:{site_version}",
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
code, _stderr = await _run_subprocess(args, 30)
|
||||||
|
except OSError as ex:
|
||||||
|
raise RenderFailed(f"공개 전환 실행 실패: {type(ex).__name__}") from ex
|
||||||
|
if code != 0:
|
||||||
|
raise RenderFailed("공개 버전 전환 실패")
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
"""예전 버전으로 되돌리기 — ROLLBACK 잡이 하는 일.
|
||||||
|
|
||||||
|
대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환
|
||||||
|
|
||||||
|
★ 재수집·재생성을 하지 않는다. run_build 와 다른 점이 이것 하나다 — 대상 버전이
|
||||||
|
박제해 둔 snapshot(site_versions.snapshot)을 **그대로** 다시 payload 로 옮길 뿐이다.
|
||||||
|
사장님이 그때 이미 확인하고 발행했던 값이므로, 지금 fact 상태가 바뀌었어도 롤백은
|
||||||
|
그 시점의 값을 그대로 복원한다 — "롤백했는데 최신 수정이 섞여 있다"를 막는다.
|
||||||
|
|
||||||
|
★ 그래도 게이트는 다시 돈다. 스냅샷은 그대로지만 **렌더러는 그때와 다를 수 있다**
|
||||||
|
(그 사이 배포됐을 수 있다) — 새 렌더러가 옛 스냅샷을 어떻게 굽는지는 다시 확인해야 한다.
|
||||||
|
|
||||||
|
★ 재굽기가 필요 없을 수도 있다 — 대상 버전 디렉토리가 보관 기간 안에 아직 디스크에 있으면
|
||||||
|
렌더러가 그 사실을 알아서 이용한다(prerender.ts publishVersion 은 렌더 자체는 매번 다시
|
||||||
|
하지만, 결과가 같으면 파일 내용도 같다 — 멱등이다). 디스크에서 지워졌어도 문제없다 —
|
||||||
|
snapshot 이 있으니 처음부터 다시 굽는다.
|
||||||
|
|
||||||
|
★ 실패하면 지금 공개된 버전은 그대로다. render_service.render_site 가 실패를 던지거나
|
||||||
|
report.ok=False 면 심볼릭 링크를 아예 안 돌린다(prerender.ts publishVersion 은 성공한
|
||||||
|
렌더 결과에만 닿는다) — 발행 파이프라인과 같은 원자성 보장이다.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import places, site_publish_logs, site_versions, sites
|
||||||
|
from common.enums import (
|
||||||
|
BuildStatus,
|
||||||
|
DBWRType,
|
||||||
|
ErrorType,
|
||||||
|
PlaceCategory,
|
||||||
|
PublishAction,
|
||||||
|
PublishResult,
|
||||||
|
SiteStatus,
|
||||||
|
)
|
||||||
|
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 azure_static, indexnow, publish_gate, render_service, site_payload
|
||||||
|
from services.build_service import ensure_site, load_channel_links
|
||||||
|
|
||||||
|
_site_crud = SiteCRUD()
|
||||||
|
_place_crud = PlaceCRUD()
|
||||||
|
|
||||||
|
RENDER_TIMEOUT_SEC_ENV = "RENDER_TIMEOUT_SEC"
|
||||||
|
|
||||||
|
|
||||||
|
class RollbackAborted(RuntimeError):
|
||||||
|
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||||
|
|
||||||
|
|
||||||
|
async def _log(site_id, version_id, result: PublishResult, gate=None, actor=None):
|
||||||
|
row = site_publish_logs(
|
||||||
|
site_id=site_id,
|
||||||
|
site_version_id=version_id,
|
||||||
|
action=PublishAction.ROLLBACK.value,
|
||||||
|
result=result.value,
|
||||||
|
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
||||||
|
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
||||||
|
actor_user_id=uuid.UUID(actor) if actor else None,
|
||||||
|
)
|
||||||
|
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
||||||
|
|
||||||
|
|
||||||
|
async def run_rollback(job: dict) -> dict:
|
||||||
|
"""ROLLBACK 잡 핸들러. payload: {place_id, owner_user_id, target_version, requested_by?}"""
|
||||||
|
payload = job["payload"]
|
||||||
|
place_id = payload["place_id"]
|
||||||
|
owner_user_id = payload["owner_user_id"]
|
||||||
|
target_version = int(payload["target_version"])
|
||||||
|
render_timeout_sec = float(os.environ.get(RENDER_TIMEOUT_SEC_ENV) or 180)
|
||||||
|
|
||||||
|
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
places.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||||
|
)
|
||||||
|
if err != ErrorType.SUCCESS or place is None:
|
||||||
|
raise RollbackAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||||
|
|
||||||
|
site = await ensure_site(place_id)
|
||||||
|
|
||||||
|
v_err, version = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
site_versions.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: _site_crud.get_version_by_number(s, site.site_id, target_version),
|
||||||
|
)
|
||||||
|
if v_err != ErrorType.SUCCESS or version is None:
|
||||||
|
raise RollbackAborted(f"버전 {target_version} 을 찾을 수 없다")
|
||||||
|
if version.build_status != BuildStatus.BUILT.value or not version.snapshot:
|
||||||
|
raise RollbackAborted(f"버전 {target_version} 은 성공적으로 빌드된 적이 없어 되돌릴 수 없다")
|
||||||
|
if site.current_version_id == version.site_version_id:
|
||||||
|
raise RollbackAborted(f"이미 지금 공개 중인 버전이다(v{target_version})")
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"place_id": place_id, "site_id": str(site.site_id),
|
||||||
|
"target_version": target_version, "site_version_id": str(version.site_version_id),
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
gate, payload.get("requested_by"))
|
||||||
|
result["rolled_back"] = False
|
||||||
|
result["error"] = reason
|
||||||
|
LOG.w(f"[rollback] place={place_id} v{target_version} 실패: {reason}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
# ★ snapshot 을 그대로 옮긴다 — 재수집하지 않는다(파일 머리주석 참조).
|
||||||
|
links = await load_channel_links(place_id)
|
||||||
|
payload_dict = await site_payload.prepare_site_payload(
|
||||||
|
place, version.snapshot, site, version, links, publish=True
|
||||||
|
)
|
||||||
|
payload_path = site_payload.write_payload(payload_dict)
|
||||||
|
result["payload_path"] = payload_path
|
||||||
|
|
||||||
|
try:
|
||||||
|
report = await render_service.render_site(payload_path, target_version, render_timeout_sec)
|
||||||
|
except render_service.RenderFailed as ex:
|
||||||
|
return await _fail(str(ex))
|
||||||
|
|
||||||
|
mismatches = list(report.get("mismatches") or [])
|
||||||
|
unique_count_raw = report.get("uniqueContentCount")
|
||||||
|
|
||||||
|
# ★ 렌더러가 그때와 달라졌을 수 있으므로 게이트를 다시 돈다(파일 머리주석 참조) —
|
||||||
|
# fact 검증 게이트(1차)는 건너뛴다. snapshot 은 이미 확인된 값만 담아 발행했던 것이라
|
||||||
|
# 다시 물을 것이 없다 — 여기서 또 물으면 "그때는 됐는데 지금은 안 된다"는 모순이 난다.
|
||||||
|
gate = publish_gate.evaluate(
|
||||||
|
PlaceCategory(place.category), version.snapshot.get("facts") or [], unique_count_raw, mismatches
|
||||||
|
)
|
||||||
|
result["gate"] = {"passed": gate.passed, **gate.as_log()}
|
||||||
|
if not gate.passed:
|
||||||
|
return await _fail(f"{gate.reason.name}: {gate.as_log()}", gate)
|
||||||
|
if not report.get("ok"):
|
||||||
|
return await _fail(str(report.get("error") or "렌더 실패"))
|
||||||
|
|
||||||
|
slug = site_payload.publish_slug(place, site)
|
||||||
|
try:
|
||||||
|
await render_service.activate_site(slug, target_version)
|
||||||
|
await azure_static.publish(slug)
|
||||||
|
except (render_service.RenderFailed, azure_static.AzurePublishError) as ex:
|
||||||
|
return await _fail(str(ex))
|
||||||
|
await indexnow.submit(slug)
|
||||||
|
|
||||||
|
now = GTime.UTC()
|
||||||
|
site_update = {
|
||||||
|
"status": SiteStatus.PUBLISHED.value,
|
||||||
|
"current_version_id": version.site_version_id,
|
||||||
|
"published_at": now,
|
||||||
|
}
|
||||||
|
await DB_SESSION_MNG.execute_lambda_claim(
|
||||||
|
sites.DBType(), lambda s: _site_crud.update_site(s, site.site_id, site_update)
|
||||||
|
)
|
||||||
|
await _log(site.site_id, version.site_version_id, PublishResult.SUCCESS, None, payload.get("requested_by"))
|
||||||
|
|
||||||
|
result["rolled_back"] = True
|
||||||
|
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
||||||
|
return result
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Teams Workflow 수신용. 원문 오류/인증 정보는 메시지에 싣지 않는다."""
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from common.logger import LOG
|
||||||
|
|
||||||
|
|
||||||
|
def alert_reason(row, now, days: int) -> str | None:
|
||||||
|
if row.alerted_at and now - row.alerted_at < timedelta(days=1):
|
||||||
|
return None
|
||||||
|
if row.error_code:
|
||||||
|
return f"조회/제출 실패: {row.error_code}"
|
||||||
|
if (row.inspection or {}).get("verdict") == "PASS":
|
||||||
|
return None
|
||||||
|
if now - row.published_at >= timedelta(days=days):
|
||||||
|
return f"발행 후 {days}일 이상 색인 미확인"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def send_alert(webhook_url: str, page_url: str, reason: str) -> bool:
|
||||||
|
if not webhook_url:
|
||||||
|
return False
|
||||||
|
if not webhook_url.startswith("https://"):
|
||||||
|
LOG.w("[search-console] ALERT_URL_INVALID")
|
||||||
|
return False
|
||||||
|
payload = {"type": "message", "attachments": [{
|
||||||
|
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||||
|
"contentUrl": None,
|
||||||
|
"content": {"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||||
|
"type": "AdaptiveCard", "version": "1.2", "body": [
|
||||||
|
{"type": "TextBlock", "text": "Google 색인 확인 필요", "weight": "Bolder"},
|
||||||
|
{"type": "TextBlock", "text": page_url, "wrap": True},
|
||||||
|
{"type": "TextBlock", "text": reason, "wrap": True},
|
||||||
|
]},
|
||||||
|
}]}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
|
||||||
|
response = await client.post(webhook_url, json=payload)
|
||||||
|
response.raise_for_status()
|
||||||
|
return True
|
||||||
|
except httpx.HTTPError:
|
||||||
|
# webhook 주소 자체가 인증 수단이므로 예외 문자열도 로그에 남기지 않는다.
|
||||||
|
LOG.w("[search-console] ALERT_DELIVERY_FAILED")
|
||||||
|
return False
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""Google Search Console REST 클라이언트 — 사이트맵 제출 · URL 색인 상태 조회.
|
||||||
|
|
||||||
|
PUT https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/sitemaps/{feedpath}
|
||||||
|
POST https://searchconsole.googleapis.com/v1/urlInspection/index:inspect
|
||||||
|
|
||||||
|
자세한 계약은 docs/SEARCH_CONSOLE_CLIENT.md.
|
||||||
|
|
||||||
|
★ `SearchConsoleError` 는 `code` 문자열만 담는다 — Google 응답 본문·토큰·키·원본
|
||||||
|
예외 메시지는 절대 싣지 않는다.
|
||||||
|
★ `inspectionResult`·`indexStatusResult` 가 없거나 빈 응답은 "미색인"으로
|
||||||
|
넘겨짚지 않고 예외로 끊는다 — 검사 실패와 색인 결과를 구분 못하면 오판이 된다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
SITEMAPS_BASE = "https://www.googleapis.com/webmasters/v3/sites"
|
||||||
|
INSPECT_URL = "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect"
|
||||||
|
SCOPES = ["https://www.googleapis.com/auth/webmasters"]
|
||||||
|
TIMEOUT_SEC = 20.0
|
||||||
|
AUTH_REFRESH_TIMEOUT_SEC = 20.0
|
||||||
|
|
||||||
|
|
||||||
|
class SearchConsoleError(RuntimeError):
|
||||||
|
"""code 만 담는다 — Google 응답 본문·토큰·키는 여기 실으면 안 된다."""
|
||||||
|
|
||||||
|
def __init__(self, code: str):
|
||||||
|
self.code = code
|
||||||
|
super().__init__(code)
|
||||||
|
|
||||||
|
|
||||||
|
def _service_account_credentials(credentials_file: str):
|
||||||
|
"""lazy import — 미설치여도 이 모듈의 import 자체는 죽지 않는다."""
|
||||||
|
from google.oauth2 import service_account
|
||||||
|
|
||||||
|
return service_account.Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_sync(credentials) -> None:
|
||||||
|
"""동기 토큰 갱신. `asyncio.to_thread` 로 감싸 부른다.
|
||||||
|
|
||||||
|
`Request.__call__` 기본 타임아웃(120s)을 그대로 두면 만료된 키·막힌 네트워크에서
|
||||||
|
오래 걸릴 수 있다 — 매 요청에 상한을 강제로 덮어씌운다(호출측이 넘긴 값 포함)."""
|
||||||
|
import requests
|
||||||
|
from google.auth.transport.requests import Request
|
||||||
|
|
||||||
|
with requests.Session() as session:
|
||||||
|
original_request = session.request
|
||||||
|
|
||||||
|
def _request_with_timeout(*args, **kwargs):
|
||||||
|
kwargs["timeout"] = AUTH_REFRESH_TIMEOUT_SEC
|
||||||
|
return original_request(*args, **kwargs)
|
||||||
|
|
||||||
|
session.request = _request_with_timeout
|
||||||
|
credentials.refresh(Request(session=session))
|
||||||
|
|
||||||
|
|
||||||
|
def _status_error_code(status_code: int) -> str:
|
||||||
|
if status_code == 401:
|
||||||
|
return "unauthorized"
|
||||||
|
if status_code == 403:
|
||||||
|
return "forbidden"
|
||||||
|
if status_code == 429:
|
||||||
|
return "rate_limited"
|
||||||
|
if 500 <= status_code < 600:
|
||||||
|
return "server_error"
|
||||||
|
return f"http_{status_code}"
|
||||||
|
|
||||||
|
|
||||||
|
def _transport_error_code(ex: httpx.HTTPError) -> str:
|
||||||
|
if isinstance(ex, httpx.TimeoutException):
|
||||||
|
return "timeout"
|
||||||
|
return "transport_error"
|
||||||
|
|
||||||
|
|
||||||
|
class SearchConsoleClient:
|
||||||
|
def __init__(self, credentials_file: str, *, transport: httpx.AsyncBaseTransport | None = None):
|
||||||
|
self._credentials_file = credentials_file
|
||||||
|
self._client = httpx.AsyncClient(timeout=TIMEOUT_SEC, transport=transport)
|
||||||
|
self._credentials: Any = None
|
||||||
|
self._auth_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
async def __aenter__(self) -> "SearchConsoleClient":
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc, tb) -> None:
|
||||||
|
await self.aclose()
|
||||||
|
|
||||||
|
async def aclose(self) -> None:
|
||||||
|
await self._client.aclose()
|
||||||
|
|
||||||
|
async def submit_sitemap(self, property_url: str, sitemap_url: str) -> None:
|
||||||
|
url = f"{SITEMAPS_BASE}/{quote(property_url, safe='')}/sitemaps/{quote(sitemap_url, safe='')}"
|
||||||
|
headers = await self._auth_headers()
|
||||||
|
res = await self._put(url, headers)
|
||||||
|
self._raise_for_status(res)
|
||||||
|
|
||||||
|
async def inspect_url(self, property_url: str, page_url: str) -> dict[str, Any]:
|
||||||
|
headers = await self._auth_headers()
|
||||||
|
body = {"inspectionUrl": page_url, "siteUrl": property_url}
|
||||||
|
res = await self._post(INSPECT_URL, headers, body)
|
||||||
|
self._raise_for_status(res)
|
||||||
|
return _index_status_result(res)
|
||||||
|
|
||||||
|
async def _put(self, url: str, headers: dict[str, str]) -> httpx.Response:
|
||||||
|
try:
|
||||||
|
return await self._client.put(url, headers=headers)
|
||||||
|
except httpx.HTTPError as ex:
|
||||||
|
raise SearchConsoleError(_transport_error_code(ex)) from None
|
||||||
|
|
||||||
|
async def _post(self, url: str, headers: dict[str, str], body: dict[str, Any]) -> httpx.Response:
|
||||||
|
try:
|
||||||
|
return await self._client.post(url, headers=headers, json=body)
|
||||||
|
except httpx.HTTPError as ex:
|
||||||
|
raise SearchConsoleError(_transport_error_code(ex)) from None
|
||||||
|
|
||||||
|
def _raise_for_status(self, res: httpx.Response) -> None:
|
||||||
|
if not res.is_success:
|
||||||
|
raise SearchConsoleError(_status_error_code(res.status_code))
|
||||||
|
|
||||||
|
async def _auth_headers(self) -> dict[str, str]:
|
||||||
|
token = await self._access_token()
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
async def _access_token(self) -> str:
|
||||||
|
credentials = self._load_credentials()
|
||||||
|
if not getattr(credentials, "valid", False):
|
||||||
|
async with self._auth_lock:
|
||||||
|
if not getattr(credentials, "valid", False):
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(_refresh_sync, credentials)
|
||||||
|
except Exception:
|
||||||
|
raise SearchConsoleError("auth_failed") from None
|
||||||
|
token = getattr(credentials, "token", None)
|
||||||
|
if not token:
|
||||||
|
raise SearchConsoleError("auth_failed")
|
||||||
|
return token
|
||||||
|
|
||||||
|
def _load_credentials(self) -> Any:
|
||||||
|
if self._credentials is None:
|
||||||
|
try:
|
||||||
|
self._credentials = _service_account_credentials(self._credentials_file)
|
||||||
|
except Exception:
|
||||||
|
raise SearchConsoleError("invalid_credentials_file") from None
|
||||||
|
return self._credentials
|
||||||
|
|
||||||
|
|
||||||
|
def _index_status_result(res: httpx.Response) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
data = res.json()
|
||||||
|
except ValueError:
|
||||||
|
raise SearchConsoleError("invalid_json") from None
|
||||||
|
inspection_result = data.get("inspectionResult") if isinstance(data, dict) else None
|
||||||
|
if not isinstance(inspection_result, dict):
|
||||||
|
raise SearchConsoleError("missing_inspection_result")
|
||||||
|
index_status_result = inspection_result.get("indexStatusResult")
|
||||||
|
if not isinstance(index_status_result, dict) or not index_status_result:
|
||||||
|
raise SearchConsoleError("missing_index_status_result")
|
||||||
|
return index_status_result
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""발행 감지 → 사이트맵 제출 → 색인 조회 → 알림. 발행 잡과 별도 트랜잭션이다."""
|
||||||
|
import asyncio
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import DBType
|
||||||
|
from common.logger import LOG
|
||||||
|
from crud import search_console_crud as store
|
||||||
|
from services import site_payload
|
||||||
|
from services.search_console_alerts import alert_reason, send_alert
|
||||||
|
from services.search_console_client import SearchConsoleClient, SearchConsoleError
|
||||||
|
from services.search_console_settings import load_settings, belongs_to_property
|
||||||
|
|
||||||
|
|
||||||
|
async def run_scheduled_check():
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
if settings is None:
|
||||||
|
return
|
||||||
|
await DB_SESSION_MNG.execute_lambda_write(
|
||||||
|
DBType.MAIN.value, lambda session: run_batch(session, settings),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
# 크론 실패가 API/발행에 전파되지 않고 다음 주기에 재시도된다.
|
||||||
|
LOG.w("[search-console] BATCH_FAILED — 설정 및 DB 마이그레이션 확인 필요")
|
||||||
|
|
||||||
|
|
||||||
|
async def run_batch(session, settings):
|
||||||
|
if not await store.lock_batch(session):
|
||||||
|
return
|
||||||
|
if not belongs_to_property(site_payload.publish_origin() + "/sitemap.xml", settings.property_url):
|
||||||
|
raise SearchConsoleError("PROPERTY_MISMATCH")
|
||||||
|
await register_publications(session, settings)
|
||||||
|
rows = await store.due_sites(session, settings.property_url)
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
async with SearchConsoleClient(settings.credentials_file) as client:
|
||||||
|
submitted = set()
|
||||||
|
for row in rows:
|
||||||
|
await check_site(client, row, settings, submitted)
|
||||||
|
await session.flush()
|
||||||
|
|
||||||
|
|
||||||
|
async def register_publications(session, settings):
|
||||||
|
for site, place, version in await store.new_publications(session, settings.property_url):
|
||||||
|
slug = site_payload.publish_slug(place, site)
|
||||||
|
page_url = f"{site_payload.publish_origin()}/s/{slug}"
|
||||||
|
if not belongs_to_property(page_url, settings.property_url):
|
||||||
|
LOG.w("[search-console] PROPERTY_MISMATCH")
|
||||||
|
continue
|
||||||
|
await store.register(session, {
|
||||||
|
"site_id": site.site_id, "site_version_id": version.site_version_id,
|
||||||
|
"property_url": settings.property_url, "page_url": page_url,
|
||||||
|
"published_at": site.published_at,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
async def read_sitemap(sitemap_url: str) -> set[str]:
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=20, follow_redirects=False) as client:
|
||||||
|
async with client.stream("GET", sitemap_url) as response:
|
||||||
|
response.raise_for_status()
|
||||||
|
body = bytearray()
|
||||||
|
async for chunk in response.aiter_bytes():
|
||||||
|
body.extend(chunk)
|
||||||
|
if len(body) > 5_000_000:
|
||||||
|
raise SearchConsoleError("SITEMAP_TOO_LARGE")
|
||||||
|
root = ET.fromstring(body)
|
||||||
|
return {(item.text or "").strip() for item in root.iter(
|
||||||
|
"{http://www.sitemaps.org/schemas/sitemap/0.9}loc"
|
||||||
|
)}
|
||||||
|
except (httpx.HTTPError, ET.ParseError):
|
||||||
|
raise SearchConsoleError("SITEMAP_UNAVAILABLE") from None
|
||||||
|
|
||||||
|
|
||||||
|
async def submit_sitemap(client, row, submitted: set):
|
||||||
|
if row.sitemap_submitted_at:
|
||||||
|
return
|
||||||
|
sitemap_url = site_payload.publish_origin() + "/sitemap.xml"
|
||||||
|
# 디스크가 아니라 실제 공개 URL을 확인한다. 업로드 지연 시 Google에 먼저 알리지 않는다.
|
||||||
|
urls = await read_sitemap(sitemap_url)
|
||||||
|
if row.page_url not in urls:
|
||||||
|
raise SearchConsoleError("URL_NOT_IN_SITEMAP")
|
||||||
|
if sitemap_url not in submitted:
|
||||||
|
await client.submit_sitemap(row.property_url, sitemap_url)
|
||||||
|
submitted.add(sitemap_url)
|
||||||
|
row.sitemap_submitted_at = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def record_inspection(row, inspection: dict, now):
|
||||||
|
row.inspection = inspection
|
||||||
|
row.inspected_at = now
|
||||||
|
row.error_code = None
|
||||||
|
row.failures = 0
|
||||||
|
if inspection.get("verdict") == "PASS":
|
||||||
|
row.first_indexed_at = row.first_indexed_at or now
|
||||||
|
row.next_check_at = now + timedelta(days=1)
|
||||||
|
|
||||||
|
|
||||||
|
def record_error(row, code: str, now):
|
||||||
|
row.error_code = code
|
||||||
|
row.failures = (row.failures or 0) + 1
|
||||||
|
hours = min(24, 2 ** min(row.failures - 1, 5))
|
||||||
|
row.next_check_at = now + timedelta(hours=hours)
|
||||||
|
|
||||||
|
|
||||||
|
async def check_site(client, row, settings, submitted: set):
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
try:
|
||||||
|
if not belongs_to_property(row.page_url, settings.property_url):
|
||||||
|
raise SearchConsoleError("PROPERTY_MISMATCH")
|
||||||
|
async with asyncio.timeout(90):
|
||||||
|
await submit_sitemap(client, row, submitted)
|
||||||
|
inspection = await client.inspect_url(row.property_url, row.page_url)
|
||||||
|
record_inspection(row, inspection, now)
|
||||||
|
except SearchConsoleError as ex:
|
||||||
|
record_error(row, ex.code, now)
|
||||||
|
except TimeoutError:
|
||||||
|
record_error(row, "CHECK_TIMEOUT", now)
|
||||||
|
except Exception:
|
||||||
|
record_error(row, "CHECK_FAILED", now)
|
||||||
|
reason = alert_reason(row, now, settings.alert_days)
|
||||||
|
if reason:
|
||||||
|
LOG.w(f"[search-console] site={row.site_id} {reason}")
|
||||||
|
if await send_alert(settings.alert_url, row.page_url, reason):
|
||||||
|
row.alerted_at = now
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Google 로그인 설정과 분리한다. 서비스 계정 키는 서버 파일로만 읽는다."""
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SearchConsoleSettings:
|
||||||
|
property_url: str
|
||||||
|
credentials_file: str
|
||||||
|
alert_url: str = ""
|
||||||
|
alert_days: int = 7
|
||||||
|
|
||||||
|
|
||||||
|
def load_settings() -> SearchConsoleSettings | None:
|
||||||
|
if os.environ.get("GSC_ENABLED") != "1":
|
||||||
|
return None
|
||||||
|
prop = os.environ.get("GSC_PROPERTY_URL", "").strip()
|
||||||
|
key_file = os.environ.get("GSC_CREDENTIALS_FILE", "").strip()
|
||||||
|
if not prop or not key_file:
|
||||||
|
raise ValueError("GSC_CONFIG_MISSING")
|
||||||
|
parsed = urlsplit(prop)
|
||||||
|
domain_property = prop.startswith("sc-domain:") and bool(prop.removeprefix("sc-domain:"))
|
||||||
|
root_property = (parsed.scheme == "https" and parsed.hostname and parsed.path == "/"
|
||||||
|
and not parsed.query and not parsed.fragment and not parsed.username)
|
||||||
|
if not domain_property and not root_property:
|
||||||
|
raise ValueError("GSC_PROPERTY_INVALID")
|
||||||
|
days = int(os.environ.get("GSC_ALERT_DAYS", "7"))
|
||||||
|
if days < 1:
|
||||||
|
raise ValueError("GSC_ALERT_DAYS_INVALID")
|
||||||
|
return SearchConsoleSettings(prop, key_file, os.environ.get("GSC_ALERT_WEBHOOK_URL", ""), days)
|
||||||
|
|
||||||
|
|
||||||
|
def belongs_to_property(page_url: str, property_url: str) -> bool:
|
||||||
|
parsed = urlsplit(page_url)
|
||||||
|
if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
|
||||||
|
return False
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
return False
|
||||||
|
if property_url.startswith("sc-domain:"):
|
||||||
|
domain = property_url.removeprefix("sc-domain:").lower()
|
||||||
|
return bool(domain) and (parsed.hostname == domain or parsed.hostname.endswith("." + domain))
|
||||||
|
return page_url.startswith(property_url)
|
||||||
@@ -34,13 +34,19 @@ from common.enums import (
|
|||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from services.intro_summary import summarize_intro
|
from services.intro_summary import summarize_intro
|
||||||
from services.stay_guide import nol_stay_guide
|
from services.stay_guide import nol_stay_guide
|
||||||
|
from services.weather_notes import weather_notes
|
||||||
|
|
||||||
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
|
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
|
||||||
SCHEMA_VERSION = 1
|
SCHEMA_VERSION = 1
|
||||||
|
|
||||||
# 출력 디렉토리. 컨테이너 밖(볼륨·오브젝트 스토리지)으로 빼기 쉬우라고 env 로 둔다.
|
# 출력 디렉토리. 컨테이너 밖(볼륨·오브젝트 스토리지)으로 빼기 쉬우라고 env 로 둔다.
|
||||||
|
# ★ 기본값이 `solution/site/payloads` 아래인 이유 — 렌더러(prerender.ts)가 songs·out 디렉토리를
|
||||||
|
# **자기 파일 위치 기준 상대경로**로 찾는다(SITE_ROOT = dist/prerender/../..). 워커가 그
|
||||||
|
# 렌더러를 subprocess 로 직접 띄우면서(render_service.py) 세 디렉토리(payloads·songs·out)가
|
||||||
|
# 그 렌더러가 실제로 설치된 자리(`/app/solution/site/`) 아래에 나란히 있어야 한다 —
|
||||||
|
# 어긋나면 워커는 payload 를 잘 쓰는데 렌더러는 다른 곳에서 songs 를 찾다가 못 찾는다.
|
||||||
PAYLOAD_DIR_ENV = "SITE_PAYLOAD_DIR"
|
PAYLOAD_DIR_ENV = "SITE_PAYLOAD_DIR"
|
||||||
DEFAULT_PAYLOAD_DIR = "/app/out/payloads"
|
DEFAULT_PAYLOAD_DIR = "/app/solution/site/payloads"
|
||||||
|
|
||||||
# 커스텀 도메인이 없을 때 쓰는 기본 호스트. sites.domain 이 채워지면 그 값이 이긴다.
|
# 커스텀 도메인이 없을 때 쓰는 기본 호스트. sites.domain 이 채워지면 그 값이 이긴다.
|
||||||
#
|
#
|
||||||
@@ -140,7 +146,7 @@ _DEFAULT_THEME = {
|
|||||||
# 수집이 다 됐어도 그 섹션이 아예 안 나온다 — 저장값이 없는 사업장에는 이 표가 곧 발행본이다.
|
# 수집이 다 됐어도 그 섹션이 아예 안 나온다 — 저장값이 없는 사업장에는 이 표가 곧 발행본이다.
|
||||||
# ★ "이용 규정"은 뺐다 (2026-09-09) — 발행본에 그 섹션이 없다. 체크인·취소·취사·
|
# ★ "이용 규정"은 뺐다 (2026-09-09) — 발행본에 그 섹션이 없다. 체크인·취소·취사·
|
||||||
# 반려동물 줄은 기본 정보 안에서 규정 덩이로 묶여 나간다(EssentialInfoSection).
|
# 반려동물 줄은 기본 정보 안에서 규정 덩이로 묶여 나간다(EssentialInfoSection).
|
||||||
# ★ 가요·일력·인물·연표·엽서는 여기 넣지 않는다. 이 표의 항목은 전부 켜서 나가는데
|
# ★ 가요·일력·인물·연표·읽기·엽서는 여기 넣지 않는다. 이 표의 항목은 전부 켜서 나가는데
|
||||||
# (`_sections`), 그것들은 '지역 이야기'(story) 탭 **안에서** 그려지는 것이라
|
# (`_sections`), 그것들은 '지역 이야기'(story) 탭 **안에서** 그려지는 것이라
|
||||||
# 켜면 탭 밖에 한 번 더 선다. story 하나만 두면 데이터가 있는 것만 탭이 된다.
|
# 켜면 탭 밖에 한 번 더 선다. story 하나만 두면 데이터가 있는 것만 탭이 된다.
|
||||||
# ★ 퀴즈(quiz)도 넣지 않지만 사정이 다르다 — 탭이 아니라 **독립 섹션**이라
|
# ★ 퀴즈(quiz)도 넣지 않지만 사정이 다르다 — 탭이 아니라 **독립 섹션**이라
|
||||||
@@ -520,7 +526,7 @@ def _weather(row: dict):
|
|||||||
return {
|
return {
|
||||||
"temperature": temperature,
|
"temperature": temperature,
|
||||||
"condition": _weather_condition(body.get("weather_code")),
|
"condition": _weather_condition(body.get("weather_code")),
|
||||||
# note 는 LLM 이 쓰는 안내 문구다. 지금 그걸 만드는 경로가 없으므로 넣지 않는다(지어내지 않는다).
|
**weather_notes(),
|
||||||
"observedAt": observed_at,
|
"observedAt": observed_at,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -780,11 +786,15 @@ def region_label(*addresses: str | None) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
# ── payload 조립 ──────────────────────────────────────────────────────────
|
# ── payload 조립 ──────────────────────────────────────────────────────────
|
||||||
def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
def to_site_payload(place, snapshot: dict, site, version, links, publish: bool = False) -> dict:
|
||||||
"""스냅샷 + 사이트/버전 행 + 채널 링크 → SitePayload(dict).
|
"""스냅샷 + 사이트/버전 행 + 채널 링크 → SitePayload(dict).
|
||||||
|
|
||||||
순수 변환 함수다. DB 도 파일도 건드리지 않는다 — 그래야 테스트가 쉽고,
|
순수 변환 함수다. DB 도 파일도 건드리지 않는다 — 그래야 테스트가 쉽고,
|
||||||
같은 입력이면 언제나 같은 payload 가 나온다."""
|
같은 입력이면 언제나 같은 payload 가 나온다.
|
||||||
|
|
||||||
|
★ `publish` 는 렌더러(prerender.ts publishVersion)에게 "이 버전으로 공개 주소를
|
||||||
|
넘겨도 되는가"를 알리는 신호다. False(미리보기·게이트 통과 전 재빌드)면 렌더러가
|
||||||
|
`out/versions/<slug>/<version>/` 에만 굽고 `out/s/<slug>` 심볼릭 링크는 그대로 둔다."""
|
||||||
snapshot = snapshot or {}
|
snapshot = snapshot or {}
|
||||||
snap_place = snapshot.get("place") or {}
|
snap_place = snapshot.get("place") or {}
|
||||||
place_id = str(_get(place, "place_id"))
|
place_id = str(_get(place, "place_id"))
|
||||||
@@ -929,6 +939,7 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
|||||||
"publishedAt": published_at or updated_at,
|
"publishedAt": published_at or updated_at,
|
||||||
"updatedAt": updated_at,
|
"updatedAt": updated_at,
|
||||||
"version": int(_get(version, "version") or 1),
|
"version": int(_get(version, "version") or 1),
|
||||||
|
"publish": bool(publish),
|
||||||
},
|
},
|
||||||
"place": {
|
"place": {
|
||||||
"name": name,
|
"name": name,
|
||||||
@@ -1037,9 +1048,9 @@ def write_payload(payload: dict) -> str:
|
|||||||
return str(path)
|
return str(path)
|
||||||
|
|
||||||
|
|
||||||
async def prepare_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
async def prepare_site_payload(place, snapshot: dict, site, version, links, publish: bool = False) -> dict:
|
||||||
"""미리보기·발행 공통 보강. 요약은 DB 스냅샷이 아니라 응답/산출물에만 싣는다."""
|
"""미리보기·발행 공통 보강. 요약은 DB 스냅샷이 아니라 응답/산출물에만 싣는다."""
|
||||||
payload = to_site_payload(place, snapshot, site, version, links)
|
payload = to_site_payload(place, snapshot, site, version, links, publish)
|
||||||
for fact in payload["facts"]:
|
for fact in payload["facts"]:
|
||||||
if fact["key"] != "intro" or fact["status"] not in {s.value for s in PUBLISHABLE_FACT_STATUSES}:
|
if fact["key"] != "intro" or fact["status"] not in {s.value for s in PUBLISHABLE_FACT_STATUSES}:
|
||||||
continue
|
continue
|
||||||
@@ -1054,14 +1065,14 @@ async def prepare_site_payload(place, snapshot: dict, site, version, links) -> d
|
|||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
async def emit_payload(place, snapshot: dict, site, version, links) -> str | None:
|
async def emit_payload(place, snapshot: dict, site, version, links, publish: bool = False) -> str | None:
|
||||||
"""payload 조립 + 파일 쓰기. 실패해도 예외를 밖으로 내보내지 않는다.
|
"""payload 조립 + 파일 쓰기. 실패해도 예외를 밖으로 내보내지 않는다.
|
||||||
|
|
||||||
★ 발행 자체를 실패시키면 안 된다 — 게이트를 통과해 DB 에 남은 발행 기록은 이미 정확하고,
|
★ 발행 자체를 실패시키면 안 된다 — 게이트를 통과해 DB 에 남은 발행 기록은 이미 정확하고,
|
||||||
payload 는 그것을 화면으로 옮기는 부수 산출물이다. 디스크가 없거나 권한이 없어서
|
payload 는 그것을 화면으로 옮기는 부수 산출물이다. 디스크가 없거나 권한이 없어서
|
||||||
발행이 되돌려지는 게 더 나쁘다. 대신 경고 로그로 반드시 드러낸다."""
|
발행이 되돌려지는 게 더 나쁘다. 대신 경고 로그로 반드시 드러낸다."""
|
||||||
try:
|
try:
|
||||||
payload = await prepare_site_payload(place, snapshot, site, version, links)
|
payload = await prepare_site_payload(place, snapshot, site, version, links, publish)
|
||||||
path = write_payload(payload)
|
path = write_payload(payload)
|
||||||
LOG.i(
|
LOG.i(
|
||||||
f"[payload] {payload['site']['slug']} → {path} "
|
f"[payload] {payload['site']['slug']} → {path} "
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from router.v1.site.protocol import (
|
|||||||
Req_SiteStatus,
|
Req_SiteStatus,
|
||||||
Req_SiteTemplate,
|
Req_SiteTemplate,
|
||||||
Req_SiteTheme,
|
Req_SiteTheme,
|
||||||
|
Req_Rollback,
|
||||||
Req_StartBuild,
|
Req_StartBuild,
|
||||||
Res_MySites,
|
Res_MySites,
|
||||||
Res_PublishLogs,
|
Res_PublishLogs,
|
||||||
@@ -166,7 +167,7 @@ class SiteService:
|
|||||||
(`snapshot.build_snapshot` → `site_payload.prepare_site_payload`)를 그대로 거치므로,
|
(`snapshot.build_snapshot` → `site_payload.prepare_site_payload`)를 그대로 거치므로,
|
||||||
여기서 갈릴 자리가 없다. 버전은 아직 없으니 0 으로 넘긴다 — 화면에 안 쓰인다.
|
여기서 갈릴 자리가 없다. 버전은 아직 없으니 0 으로 넘긴다 — 화면에 안 쓰인다.
|
||||||
"""
|
"""
|
||||||
from services.build_service import ensure_site, _load_links
|
from services.build_service import ensure_site, load_channel_links
|
||||||
from services.site_payload import prepare_site_payload
|
from services.site_payload import prepare_site_payload
|
||||||
from services.snapshot import build_snapshot
|
from services.snapshot import build_snapshot
|
||||||
|
|
||||||
@@ -175,7 +176,7 @@ class SiteService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
site = await ensure_site(place_id)
|
site = await ensure_site(place_id)
|
||||||
links = await _load_links(place_id)
|
links = await load_channel_links(place_id)
|
||||||
snapshot = await build_snapshot(place)
|
snapshot = await build_snapshot(place)
|
||||||
# ★ version 은 None 이다. 발행 전이라 버전 행이 없고, payload 의 site.version 은
|
# ★ version 은 None 이다. 발행 전이라 버전 행이 없고, payload 의 site.version 은
|
||||||
# 캐시 무효화 키라 미리보기에서는 뜻이 없다(to_site_payload 가 0 으로 떨어뜨린다).
|
# 캐시 무효화 키라 미리보기에서는 뜻이 없다(to_site_payload 가 0 으로 떨어뜨린다).
|
||||||
@@ -570,6 +571,35 @@ class SiteService:
|
|||||||
res.created = created
|
res.created = created
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
async def start_rollback(self, user_info: UserInfo, place_id: str, req: Req_Rollback) -> Res_StartBuild:
|
||||||
|
"""예전 버전으로 공개 주소를 되돌리는 잡을 큐에 넣는다.
|
||||||
|
|
||||||
|
★ dedupe_key 를 빌드와 **같은 것**(`build:{place_id}`)을 쓴다 — 롤백 도중에 새 발행이
|
||||||
|
끼어들거나 그 반대가 되면 어느 쪽이 이겼는지 알 수 없는 상태가 된다. 이 사이트의
|
||||||
|
공개 주소를 바꾸는 작업은 항상 하나만 활성화된다."""
|
||||||
|
res = Res_StartBuild()
|
||||||
|
err_type, _place = await self._load_place(user_info, place_id)
|
||||||
|
if err_type != ErrorType.SUCCESS:
|
||||||
|
res.result.SetResult(err_type)
|
||||||
|
return res
|
||||||
|
|
||||||
|
job_id, created = await enqueue_job(
|
||||||
|
self.queue, JobType.ROLLBACK,
|
||||||
|
{
|
||||||
|
"place_id": place_id, "owner_user_id": user_info.user_id,
|
||||||
|
"target_version": req.target_version, "requested_by": user_info.user_id,
|
||||||
|
},
|
||||||
|
dedupe_key=f"build:{place_id}",
|
||||||
|
)
|
||||||
|
if job_id is None:
|
||||||
|
res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING)
|
||||||
|
return res
|
||||||
|
|
||||||
|
res.job_id = uuid.UUID(job_id)
|
||||||
|
res.status = JobStatus.PENDING
|
||||||
|
res.created = created
|
||||||
|
return res
|
||||||
|
|
||||||
async def list_versions(self, user_info: UserInfo, place_id: str) -> Res_SiteVersions:
|
async def list_versions(self, user_info: UserInfo, place_id: str) -> Res_SiteVersions:
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
|||||||
@@ -128,12 +128,21 @@ async def run_song(job: dict) -> dict:
|
|||||||
|
|
||||||
발행 경로는 이 잡을 거치지 않고 `ensure_song` 을 직접 부른다(build_service)."""
|
발행 경로는 이 잡을 거치지 않고 `ensure_song` 을 직접 부른다(build_service)."""
|
||||||
payload = job["payload"]
|
payload = job["payload"]
|
||||||
return await ensure_song(payload["place_id"], payload["owner_user_id"])
|
# ★ 이 잡은 "다시 만들어 달라" 는 요청이다 — 기존 곡이 있어도 만든다(ensure_song 주석).
|
||||||
|
return await ensure_song(payload["place_id"], payload["owner_user_id"], force=True)
|
||||||
|
|
||||||
|
|
||||||
async def ensure_song(place_id: str, owner_user_id: str) -> dict:
|
async def ensure_song(place_id: str, owner_user_id: str, *, force: bool = False) -> dict:
|
||||||
"""이 업장의 노래를 한 곡 만든다. 돌려주는 dict 가 곧 잡 결과이자 빌드 로그다.
|
"""이 업장의 노래를 한 곡 만든다. 돌려주는 dict 가 곧 잡 결과이자 빌드 로그다.
|
||||||
|
|
||||||
|
★ **이미 완성된 곡이 있으면 만들지 않는다**(2026-09-15 대표: "재발행할 때 노래 다시
|
||||||
|
생성하면 안 되거든"). 예전에는 `build_service` 가 `publish=True` 마다 이 함수를 불렀고
|
||||||
|
여기에 가드가 없어서, 내용이 하나도 안 바뀐 재발행에도 **Gemini 가사 1회 + Suno 작곡
|
||||||
|
1회**가 그대로 나갔다. 사장님이 발행을 다섯 번 누르면 유료 호출 다섯 번에
|
||||||
|
`place_songs` 행이 다섯 개다. 화면은 최신 READY 한 곡만 쓰므로(`SongCRUD.latest_ready`)
|
||||||
|
나머지는 값을 만들지 않고 돈만 쓴다.
|
||||||
|
★ 곡을 **일부러 다시 만드는 길은 남긴다** — `force=True`. 그 길은 발행이 아니라
|
||||||
|
SONG 잡(`run_song`)이고, 사람이 눌러야 돈다.
|
||||||
★ 실패를 예외로 올리지 않는다(사업장을 못 찾는 것 같은 진짜 고장만 예외다).
|
★ 실패를 예외로 올리지 않는다(사업장을 못 찾는 것 같은 진짜 고장만 예외다).
|
||||||
발행이 이 함수를 기다리는데 여기서 예외가 나면 **노래 때문에 발행이 통째로 실패**한다.
|
발행이 이 함수를 기다리는데 여기서 예외가 나면 **노래 때문에 발행이 통째로 실패**한다.
|
||||||
음악 API 가 느린 날 사장님 사이트가 안 나가는 것은 맞바꿀 수 없는 손해다."""
|
음악 API 가 느린 날 사장님 사이트가 안 나가는 것은 맞바꿀 수 없는 손해다."""
|
||||||
@@ -142,6 +151,17 @@ async def ensure_song(place_id: str, owner_user_id: str) -> dict:
|
|||||||
LOG.i(f"[song] place={place_id} 건너뜀 — SUNO_API_KEY 미설정")
|
LOG.i(f"[song] place={place_id} 건너뜀 — SUNO_API_KEY 미설정")
|
||||||
return {"place_id": place_id, "skipped": "SUNO_API_KEY 미설정"}
|
return {"place_id": place_id, "skipped": "SUNO_API_KEY 미설정"}
|
||||||
|
|
||||||
|
if not force:
|
||||||
|
err, ready = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
place_songs.DBType(),
|
||||||
|
DBWRType.DB_READ.value,
|
||||||
|
lambda s: _song_crud.latest_ready(s, uuid.UUID(place_id)),
|
||||||
|
)
|
||||||
|
# `execute()` 는 리스트를 준다(limit 1 이라 0개 아니면 1개다) — None 비교로 보지 않는다.
|
||||||
|
if err == ErrorType.SUCCESS and ready:
|
||||||
|
LOG.i(f"[song] place={place_id} 건너뜀 — 이미 곡이 있다(재발행은 다시 만들지 않는다)")
|
||||||
|
return {"place_id": place_id, "skipped": "이미 곡이 있다"}
|
||||||
|
|
||||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||||
places.DBType(),
|
places.DBType(),
|
||||||
DBWRType.DB_READ.value,
|
DBWRType.DB_READ.value,
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ async def _generate_kind(client: httpx.AsyncClient, kind: str, region_label: str
|
|||||||
{"role": "system", "content": prompts.SYSTEM_PROMPT},
|
{"role": "system", "content": prompts.SYSTEM_PROMPT},
|
||||||
{"role": "user", "content": prompts.build_prompt(kind, region_label)},
|
{"role": "user", "content": prompts.build_prompt(kind, region_label)},
|
||||||
],
|
],
|
||||||
"max_tokens": perplexity.DEFAULT_MAX_TOKENS,
|
"max_tokens": _MAX_TOKENS.get(kind, perplexity.DEFAULT_MAX_TOKENS),
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
payload = await perplexity.call(body, client=client)
|
payload = await perplexity.call(body, client=client)
|
||||||
@@ -74,12 +74,21 @@ async def _generate_kind(client: httpx.AsyncClient, kind: str, region_label: str
|
|||||||
LOG.w(f"[story] {kind} 호출 실패 region={region_label}: {ex}")
|
LOG.w(f"[story] {kind} 호출 실패 region={region_label}: {ex}")
|
||||||
return [], [f"호출 실패: {ex}"]
|
return [], [f"호출 실패: {ex}"]
|
||||||
|
|
||||||
items, dropped = grounding.parse_items(payload, kind, prompts.max_items(kind))
|
items, dropped = grounding.parse_items(payload, kind, prompts.max_items(kind), region_label)
|
||||||
items = await _attach_images(kind, items, region_label)
|
items = await _attach_images(kind, items, region_label)
|
||||||
LOG.i(f"[story] {region_label} {kind}: {len(items)}건 채택, {len(dropped)}건 버림")
|
LOG.i(f"[story] {region_label} {kind}: {len(items)}건 채택, {len(dropped)}건 버림")
|
||||||
return items, dropped
|
return items, dropped
|
||||||
|
|
||||||
|
|
||||||
|
# 종류별 응답 토큰 상한. 기본(2048)으로 모자란 종류만 적는다.
|
||||||
|
#
|
||||||
|
# ★ 왜 (실측 2026-09-15) `reading` 은 30~34꼭지 × 서너 문장이라 다른 종류의 서너 배다.
|
||||||
|
# 2048 로 부르면 응답이 **문장 한가운데서 잘려** 오고, 파서는 그걸 "JSON 이 아니다" 로
|
||||||
|
# 통째로 버린다 — 여섯 지역 전부 0건이었다. 잘린 것은 재시도해도 같은 자리에서 잘린다.
|
||||||
|
# ★ 상한만 올린다. 꼭지 수를 줄이면 화면이 매번 5~6개만 뽑는 의미가 없어진다
|
||||||
|
# (`site/sections/items/ReadingSection.tsx`).
|
||||||
|
_MAX_TOKENS = {"reading": 8000}
|
||||||
|
|
||||||
# 사진을 무엇으로 찾을지. 종류마다 출처가 다르다.
|
# 사진을 무엇으로 찾을지. 종류마다 출처가 다르다.
|
||||||
#
|
#
|
||||||
# chronicle · postcard 공공데이터(TourAPI) — 장소·시설 사진. 공공누리 Type1/Type3 만
|
# chronicle · postcard 공공데이터(TourAPI) — 장소·시설 사진. 공공누리 Type1/Type3 만
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"sky": {
|
||||||
|
"맑음": ["맑은 날에는 잠깐 쉬어 가며 오늘 담은 사진을 골라 보세요.", "분주했던 걸음을 멈추고 느긋하게 쉬어 가도 좋겠습니다.", "오늘 기억하고 싶은 장면을 한 줄 남겨 보세요.", "다음 일정을 서두르기보다 잠시 여유를 가져 보세요.", "좋아하는 책 몇 장을 넘기며 쉬어 가는 건 어떨까요?"],
|
||||||
|
"구름많음": ["구름이 많은 날에는 실내에서 다음 일정을 천천히 골라 보세요.", "여행 사진을 정리하며 잠깐 쉬어 가세요.", "함께 온 사람과 오늘 가장 좋았던 순간을 이야기해 보세요.", "바깥 일정 사이에 여유로운 휴식 시간을 넣어 보세요.", "오늘의 기분을 짧은 글로 남겨도 좋겠습니다."],
|
||||||
|
"흐림": ["흐린 날에는 실내에서 느긋하게 쉬어 가도 좋겠습니다.", "잠깐 책을 읽으며 다음 일정을 기다려 보세요.", "바깥 풍경 대신 오늘 나눈 이야기에 집중해 보세요.", "천천히 쉬면서 돌아갈 때 가져갈 추억을 골라 보세요.", "분주한 일정 사이에 조용한 휴식을 끼워 넣어 보세요."],
|
||||||
|
"비": ["비가 오는 동안에는 실내에서 쉬며 일정을 조정해 보세요.", "서두르지 말고 비가 잦아드는지 확인한 뒤 움직이세요.", "빗소리를 들으며 읽고 싶었던 글을 펼쳐 보세요.", "젖은 물건을 정리하고 잠깐 쉬어 가세요.", "바깥 일정 대신 함께 찍은 사진을 나눠 봐도 좋겠습니다."],
|
||||||
|
"눈": ["눈 오는 날에는 실내에서 쉬며 바깥 상황을 살펴보세요.", "다음 이동을 서두르지 말고 쉬어 가세요.", "따뜻하게 머물며 오늘의 여행을 한 줄 남겨 보세요.", "실내에서 다음 일정과 이동편을 확인해 보세요.", "눈길을 나서기 전에는 여유 있게 준비하세요."]
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"혹서": ["더위가 강한 시간에는 바깥 이동을 줄이고 실내 위주로 일정을 잡아 보세요.", "한낮 산책은 짧게 하고 충분히 쉬어 가세요.", "외출 전 기상특보와 방문할 곳의 운영 여부를 확인하세요.", "다음 장소로 이동할 때에는 쉴 시간을 넉넉히 두세요.", "긴 야외 일정은 미루고 가까운 동선부터 살펴보세요."],
|
||||||
|
"더움": ["바깥 일정 사이에 실내에서 쉬는 시간을 넣어 보세요.", "외출할 때에는 물을 챙기고 무리한 이동은 줄이세요.", "주변을 둘러보더라도 한 번에 오래 걷지는 마세요.", "방문할 곳의 운영 시간을 먼저 확인하고 이동하세요.", "더위가 느껴지면 일정을 줄이고 쉬어 가세요."],
|
||||||
|
"선선": ["비나 눈이 없다면 주변을 가볍게 둘러보는 건 어떨까요?", "날씨와 이동 경로를 확인하고 짧은 산책을 계획해 보세요.", "바깥 일정을 잡기 전에 방문할 곳의 운영 여부를 확인하세요.", "편한 신발을 챙기고 자신의 속도로 동네를 둘러보세요.", "비가 오지 않는다면 일정 사이에 잠깐 걸어 보세요."],
|
||||||
|
"쌀쌀": ["외출할 때에는 걸칠 옷을 챙겨 보세요.", "바깥에 오래 머물기보다 쉬어 갈 곳을 함께 정해 두세요.", "일교차에 대비해 옷차림을 조절하세요.", "이동 경로를 짧게 잡고 실내 일정도 함께 살펴보세요.", "돌아오는 시간의 기온도 확인한 뒤 외출하세요."],
|
||||||
|
"추움": ["따뜻한 옷을 챙기고 바깥 이동은 짧게 잡아 보세요.", "찬 바람을 피할 수 있는 실내 일정을 살펴보세요.", "출발 전 눈이나 결빙으로 이동이 어려운 곳은 없는지 확인하세요.", "야외에 오래 머무르지 않도록 쉬는 시간을 충분히 두세요.", "방문할 곳의 운영 여부를 확인하고 따뜻하게 준비하세요."]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""날씨 안내 계약. 관측값과 분리하고, 확인되지 않은 시설·영업시간은 쓰지 않는다."""
|
||||||
|
import json
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _templates() -> dict:
|
||||||
|
return json.loads(Path(__file__).with_name("weather_notes.json").read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def weather_notes() -> dict:
|
||||||
|
templates = _templates()
|
||||||
|
sky = {key: list(lines) for key, lines in templates["sky"].items()}
|
||||||
|
temperature = {key: list(lines) for key, lines in templates["temperature"].items()}
|
||||||
|
return {
|
||||||
|
"notes": {key: lines[0] for key, lines in sky.items()},
|
||||||
|
"tempNotes": {key: lines[0] for key, lines in temperature.items()},
|
||||||
|
"noteSets": sky,
|
||||||
|
"tempNoteSets": temperature,
|
||||||
|
}
|
||||||
@@ -100,10 +100,10 @@ async def test_unverified_fact_blocks_publish(auth_headers, client, db_engine):
|
|||||||
(필수 항목 누락은 2026-08-27 부터 막지 않는다. 그래서 여기서 걸리는 사유가 바뀌었다.)"""
|
(필수 항목 누락은 2026-08-27 부터 막지 않는다. 그래서 여기서 걸리는 사유가 바뀌었다.)"""
|
||||||
h = await auth_headers("u1")
|
h = await auth_headers("u1")
|
||||||
pid = await _place(client, h, "미검증펜션")
|
pid = await _place(client, h, "미검증펜션")
|
||||||
# 크롤링으로만 들어온 값 = 후보 상태
|
# 크롤링은 바로 노출되는 정책이다. 실제 미검증 상태를 만드는 API 출처로 검사한다.
|
||||||
for k, v in REQUIRED.items():
|
for k, v in REQUIRED.items():
|
||||||
await client.post(f"/v1/place/{pid}/fact", headers=h, json={
|
await client.post(f"/v1/place/{pid}/fact", headers=h, json={
|
||||||
"key": k, "value": v, "source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
|
"key": k, "value": v, "source_type": SourceType.API.value, "source_url": "https://api.test/1"})
|
||||||
|
|
||||||
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
|
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
|
||||||
await _run()
|
await _run()
|
||||||
@@ -292,17 +292,17 @@ async def _build(client, h, pid, publish=True):
|
|||||||
async def test_렌더가_실패하면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
async def test_렌더가_실패하면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
||||||
"""검증: 렌더러가 페이지를 굽지 못했다고 보고한다.
|
"""검증: 렌더러가 페이지를 굽지 못했다고 보고한다.
|
||||||
기대결과: ★ FAILED. 페이지가 없는데 "발행됨"으로 남으면 사장님은 404 를 눌러야 안다."""
|
기대결과: ★ FAILED. 페이지가 없는데 "발행됨"으로 남으면 사장님은 404 를 눌러야 안다."""
|
||||||
from services import render_report
|
from services import render_service
|
||||||
|
|
||||||
async def _broken(slug, site_version, timeout_sec, poll_sec=1.0):
|
async def _broken(payload_path, site_version, timeout_sec):
|
||||||
return {"schemaVersion": 1, "slug": slug, "siteId": "", "placeId": "",
|
return {"schemaVersion": 1, "slug": "t", "siteId": "", "placeId": "",
|
||||||
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
|
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
|
||||||
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
|
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
|
||||||
"mismatches": [], "error": "번들이 없다"}
|
"mismatches": [], "error": "번들이 없다"}
|
||||||
|
|
||||||
h = await auth_headers("u1")
|
h = await auth_headers("u1")
|
||||||
pid = await _built_place(client, h, db_engine)
|
pid = await _built_place(client, h, db_engine)
|
||||||
monkeypatch.setattr(render_report, "wait_for", _broken)
|
monkeypatch.setattr(render_service, "render_site", _broken)
|
||||||
|
|
||||||
r = await _build(client, h, pid)
|
r = await _build(client, h, pid)
|
||||||
assert r["build_status"] == "FAILED"
|
assert r["build_status"] == "FAILED"
|
||||||
@@ -316,10 +316,10 @@ async def test_렌더가_실패하면_발행하지_않는다(auth_headers, clien
|
|||||||
async def test_구조화데이터가_화면과_다르면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
async def test_구조화데이터가_화면과_다르면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
||||||
"""검증: 렌더러가 JSON-LD 불일치를 보고한다.
|
"""검증: 렌더러가 JSON-LD 불일치를 보고한다.
|
||||||
기대결과: ★ JSONLD_MISMATCH — 검색엔진에만 다른 말을 하는 페이지는 나가면 안 된다."""
|
기대결과: ★ JSONLD_MISMATCH — 검색엔진에만 다른 말을 하는 페이지는 나가면 안 된다."""
|
||||||
from services import render_report
|
from services import render_service
|
||||||
|
|
||||||
async def _mismatch(slug, site_version, timeout_sec, poll_sec=1.0):
|
async def _mismatch(payload_path, site_version, timeout_sec):
|
||||||
return {"schemaVersion": 1, "slug": slug, "siteId": "", "placeId": "",
|
return {"schemaVersion": 1, "slug": "t", "siteId": "", "placeId": "",
|
||||||
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
|
"siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z",
|
||||||
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
|
"routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [],
|
||||||
"mismatches": ["telephone: '02-0000-0000' 이 화면에 없다"],
|
"mismatches": ["telephone: '02-0000-0000' 이 화면에 없다"],
|
||||||
@@ -327,7 +327,7 @@ async def test_구조화데이터가_화면과_다르면_발행하지_않는다(
|
|||||||
|
|
||||||
h = await auth_headers("u1")
|
h = await auth_headers("u1")
|
||||||
pid = await _built_place(client, h, db_engine)
|
pid = await _built_place(client, h, db_engine)
|
||||||
monkeypatch.setattr(render_report, "wait_for", _mismatch)
|
monkeypatch.setattr(render_service, "render_site", _mismatch)
|
||||||
|
|
||||||
r = await _build(client, h, pid)
|
r = await _build(client, h, pid)
|
||||||
assert r["build_status"] == "FAILED"
|
assert r["build_status"] == "FAILED"
|
||||||
@@ -339,14 +339,14 @@ async def test_구조화데이터가_화면과_다르면_발행하지_않는다(
|
|||||||
async def test_렌더_결과가_안_오면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
async def test_렌더_결과가_안_오면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch):
|
||||||
"""검증: 렌더러가 죽어 보고서가 오지 않는다(타임아웃).
|
"""검증: 렌더러가 죽어 보고서가 오지 않는다(타임아웃).
|
||||||
기대결과: ★ FAILED. 확인하지 못한 것을 발행됨으로 남기지 않는다."""
|
기대결과: ★ FAILED. 확인하지 못한 것을 발행됨으로 남기지 않는다."""
|
||||||
from services import render_report
|
from services import render_service
|
||||||
|
|
||||||
async def _timeout(slug, site_version, timeout_sec, poll_sec=1.0):
|
async def _timeout(payload_path, site_version, timeout_sec):
|
||||||
return None
|
raise render_service.RenderFailed("렌더 결과를 받지 못했다 — 렌더러가 도는지 확인이 필요하다")
|
||||||
|
|
||||||
h = await auth_headers("u1")
|
h = await auth_headers("u1")
|
||||||
pid = await _built_place(client, h, db_engine)
|
pid = await _built_place(client, h, db_engine)
|
||||||
monkeypatch.setattr(render_report, "wait_for", _timeout)
|
monkeypatch.setattr(render_service, "render_site", _timeout)
|
||||||
|
|
||||||
r = await _build(client, h, pid)
|
r = await _build(client, h, pid)
|
||||||
assert r["build_status"] == "FAILED"
|
assert r["build_status"] == "FAILED"
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from services import render_service
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fake_renderer(monkeypatch, tmp_path):
|
||||||
|
# 이 파일은 conftest의 렌더 대역 대신 실제 자식 프로세스 수명만 검사한다.
|
||||||
|
monkeypatch.setenv("SITE_OUTPUT_DIR", str(tmp_path))
|
||||||
|
|
||||||
|
|
||||||
|
async def test_process_success():
|
||||||
|
code, _ = await render_service._run_subprocess([sys.executable, "-c", "print(1)"], 2)
|
||||||
|
assert code == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_timeout_releases_lock():
|
||||||
|
code, _ = await render_service._run_subprocess(
|
||||||
|
[sys.executable, "-c", "import time;time.sleep(5)"], 0.1
|
||||||
|
)
|
||||||
|
assert code is None
|
||||||
|
code, _ = await render_service._run_subprocess([sys.executable, "-c", "print(1)"], 2)
|
||||||
|
assert code == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cancel_releases_lock():
|
||||||
|
task = asyncio.create_task(render_service._run_subprocess(
|
||||||
|
[sys.executable, "-c", "import time;time.sleep(5)"], 10
|
||||||
|
))
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
task.cancel()
|
||||||
|
with pytest.raises(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
code, _ = await render_service._run_subprocess([sys.executable, "-c", "print(1)"], 2)
|
||||||
|
assert code == 0
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"""롤백 — 예전 버전으로 공개 주소를 되돌린다.
|
||||||
|
|
||||||
|
★ 이 경로가 절대 하면 안 되는 것:
|
||||||
|
- 재수집·재생성으로 스냅샷을 새로 만드는 것 (그 버전이 발행됐던 그대로여야 한다)
|
||||||
|
- 실패했는데 site.current_version_id 를 바꾸는 것 (직전 공개본이 그대로 있어야 한다)
|
||||||
|
- 지금 공개 중인 버전으로 "롤백"을 허용하는 것 (의미 없는 잡을 만든다)
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from common.enums import BuildStatus, JobStatus, SiteStatus
|
||||||
|
from crud.job_crud import JobQueue
|
||||||
|
from worker.handlers import build_handler
|
||||||
|
from worker.runner import Worker
|
||||||
|
|
||||||
|
from tests.test_build_publish import _approved_media, _place, _verified_facts
|
||||||
|
|
||||||
|
|
||||||
|
async def _run():
|
||||||
|
assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True
|
||||||
|
|
||||||
|
|
||||||
|
async def _publish(client, h, pid, intro="하조대 해변 도보 3분 거리의 펜션입니다."):
|
||||||
|
await _verified_facts(client, h, pid, {"intro": intro})
|
||||||
|
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
|
||||||
|
await _run()
|
||||||
|
return (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_rollback_to_earlier_version(auth_headers, client, db_engine):
|
||||||
|
"""검증: v1 발행 → v2 발행 → v1 로 롤백.
|
||||||
|
기대결과: 공개 버전이 다시 v1 이 된다. 롤백은 새 site_versions 행을 만들지 않는다."""
|
||||||
|
h = await auth_headers("u1")
|
||||||
|
pid = await _place(client, h)
|
||||||
|
await _approved_media(db_engine, pid)
|
||||||
|
|
||||||
|
r1 = await _publish(client, h, pid, "v1 소개 — 하조대 해변 도보 3분 거리의 펜션입니다.")
|
||||||
|
assert r1["published"] is True
|
||||||
|
r2 = await _publish(client, h, pid, "v2 소개 — 리모델링을 마친 하조대 앞 오션뷰 펜션입니다.")
|
||||||
|
assert r2["published"] is True
|
||||||
|
assert r2["version"] == r1["version"] + 1
|
||||||
|
|
||||||
|
job_id = (await client.post(
|
||||||
|
f"/v1/place/{pid}/site/version/rollback", headers=h, json={"target_version": r1["version"]}
|
||||||
|
)).json()["job_id"]
|
||||||
|
await _run()
|
||||||
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||||
|
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||||
|
result = job["result"]
|
||||||
|
assert result["rolled_back"] is True, result.get("error")
|
||||||
|
assert result["target_version"] == r1["version"]
|
||||||
|
|
||||||
|
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||||
|
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
||||||
|
assert site["current_version"]["version"] == r1["version"]
|
||||||
|
assert site["current_version"]["build_status"] == BuildStatus.BUILT.value
|
||||||
|
|
||||||
|
versions = (await client.get(f"/v1/place/{pid}/site/version/list", headers=h)).json()["versions"]
|
||||||
|
# ★ 롤백은 새 버전을 만들지 않는다 — v1·v2 두 개뿐이어야 한다.
|
||||||
|
assert len(versions) == 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_rollback_rejects_current_version(auth_headers, client, db_engine):
|
||||||
|
"""검증: 지금 공개 중인 버전으로 롤백을 시도한다.
|
||||||
|
기대결과: ★ 성공으로 끝나지 않는다(last_error) — 의미 없는 재굽기를 하지 않는다.
|
||||||
|
(BuildAborted 와 같은 패턴 — 재시도해도 소용없는 중단이라 PENDING(백오프)으로 남고,
|
||||||
|
소진되면 DEAD 된다. 여기서 보는 건 "그래도 site 상태는 안 바뀐다"는 것이다.)"""
|
||||||
|
h = await auth_headers("u1")
|
||||||
|
pid = await _place(client, h)
|
||||||
|
await _approved_media(db_engine, pid)
|
||||||
|
r1 = await _publish(client, h, pid)
|
||||||
|
|
||||||
|
job_id = (await client.post(
|
||||||
|
f"/v1/place/{pid}/site/version/rollback", headers=h, json={"target_version": r1["version"]}
|
||||||
|
)).json()["job_id"]
|
||||||
|
await _run()
|
||||||
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||||
|
assert job["status"] != JobStatus.DONE.value
|
||||||
|
assert "이미" in (job.get("last_error") or "")
|
||||||
|
|
||||||
|
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||||
|
assert site["current_version"]["version"] == r1["version"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_rollback_rejects_unknown_version(auth_headers, client, db_engine):
|
||||||
|
"""검증: 존재하지 않는 버전 번호로 롤백을 시도한다.
|
||||||
|
기대결과: ★ 잡이 성공으로 끝나지 않는다 — 공개 상태는 그대로다."""
|
||||||
|
h = await auth_headers("u1")
|
||||||
|
pid = await _place(client, h)
|
||||||
|
await _approved_media(db_engine, pid)
|
||||||
|
r1 = await _publish(client, h, pid)
|
||||||
|
|
||||||
|
job_id = (await client.post(
|
||||||
|
f"/v1/place/{pid}/site/version/rollback", headers=h, json={"target_version": 999}
|
||||||
|
)).json()["job_id"]
|
||||||
|
await _run()
|
||||||
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||||
|
assert job["status"] != JobStatus.DONE.value
|
||||||
|
|
||||||
|
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||||
|
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
||||||
|
assert site["current_version"]["version"] == r1["version"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_failed_rollback_keeps_current_published_version(auth_headers, client, db_engine, monkeypatch):
|
||||||
|
"""검증: 롤백 대상 렌더가 실패한다(구조화 데이터 불일치로 시뮬레이션).
|
||||||
|
기대결과: ★ site.current_version_id 는 바뀌지 않는다 — 직전 공개본이 그대로 서비스된다."""
|
||||||
|
from services import render_service
|
||||||
|
|
||||||
|
h = await auth_headers("u1")
|
||||||
|
pid = await _place(client, h)
|
||||||
|
await _approved_media(db_engine, pid)
|
||||||
|
r1 = await _publish(client, h, pid, "v1 소개 — 하조대 해변 도보 3분 거리의 펜션입니다.")
|
||||||
|
r2 = await _publish(client, h, pid, "v2 소개 — 리모델링을 마친 하조대 앞 오션뷰 펜션입니다.")
|
||||||
|
site_before = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||||
|
assert site_before["current_version"]["version"] == r2["version"]
|
||||||
|
|
||||||
|
async def _broken(payload_path, site_version, timeout_sec):
|
||||||
|
raise render_service.RenderFailed("렌더러가 죽었다(시뮬레이션)")
|
||||||
|
|
||||||
|
monkeypatch.setattr(render_service, "render_site", _broken)
|
||||||
|
|
||||||
|
job_id = (await client.post(
|
||||||
|
f"/v1/place/{pid}/site/version/rollback", headers=h, json={"target_version": r1["version"]}
|
||||||
|
)).json()["job_id"]
|
||||||
|
await _run()
|
||||||
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||||
|
assert job["status"] == JobStatus.DONE.value
|
||||||
|
assert job["result"]["rolled_back"] is False
|
||||||
|
|
||||||
|
site_after = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||||
|
assert site_after["current_version"]["version"] == r2["version"], "실패했는데 공개 버전이 바뀌었다"
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import httpx
|
||||||
|
from services import search_console_alerts as alerts
|
||||||
|
|
||||||
|
|
||||||
|
async def test_teams_payload_has_required_attachment_fields(monkeypatch):
|
||||||
|
requests = []
|
||||||
|
real_client = httpx.AsyncClient
|
||||||
|
|
||||||
|
def receive(request):
|
||||||
|
import json
|
||||||
|
requests.append(json.loads(request.content))
|
||||||
|
return httpx.Response(202)
|
||||||
|
|
||||||
|
monkeypatch.setattr(alerts.httpx, "AsyncClient", lambda **kw: real_client(
|
||||||
|
transport=httpx.MockTransport(receive), **kw,
|
||||||
|
))
|
||||||
|
assert await alerts.send_alert("https://example.test/webhook", "https://example.test/s/a", "test")
|
||||||
|
card = requests[0]["attachments"][0]
|
||||||
|
assert card["contentType"] == "application/vnd.microsoft.card.adaptive"
|
||||||
|
assert "contentUrl" in card and card["contentUrl"] is None
|
||||||
|
assert card["content"]["$schema"] == "http://adaptivecards.io/schemas/adaptive-card.json"
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
"""Search Console 클라이언트 — 사이트맵 제출 · URL 검사.
|
||||||
|
|
||||||
|
★ 실제 Google API 를 호출하지 않는다(httpx.MockTransport). google-auth 도 이
|
||||||
|
저장소의 의존성이 아니라서(Codex 가 추가) 인증은 모듈 함수
|
||||||
|
`_service_account_credentials` / `_refresh_sync` 를 monkeypatch 해서 흉내 낸다 —
|
||||||
|
설치 여부와 무관하게 이 테스트가 돌아야 한다.
|
||||||
|
|
||||||
|
여기서 고정하는 것:
|
||||||
|
1. `inspect_url` 은 `inspectionResult.indexStatusResult` 만 돌려준다
|
||||||
|
2. ★ 그 필드가 없는 응답을 "미색인"으로 짐작하지 않고 예외를 올린다
|
||||||
|
3. 오류는 전부 `SearchConsoleError(code)` 로 정규화되고, 원본 예외 메시지·응답
|
||||||
|
본문이 `code` 에 섞여 나오지 않는다
|
||||||
|
4. 사이트맵 제출 URL 은 property/sitemap 주소를 완전 percent-encode 한다
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from services import search_console_client as scc
|
||||||
|
from services.search_console_client import SearchConsoleClient, SearchConsoleError
|
||||||
|
|
||||||
|
PROPERTY = "https://example.com/"
|
||||||
|
SITEMAP = "https://example.com/sitemap.xml"
|
||||||
|
PAGE = "https://example.com/s/butter/"
|
||||||
|
|
||||||
|
|
||||||
|
def _auth(monkeypatch, *, token="test-token", load_error=None, refresh_error=None):
|
||||||
|
"""`_service_account_credentials`/`_refresh_sync` 를 흉내내 google-auth 없이 인증을 통과시킨다."""
|
||||||
|
state = {"loads": 0, "refreshes": 0}
|
||||||
|
|
||||||
|
class _FakeCredentials:
|
||||||
|
def __init__(self):
|
||||||
|
self.token = None
|
||||||
|
self.valid = False
|
||||||
|
|
||||||
|
def fake_load(path):
|
||||||
|
state["loads"] += 1
|
||||||
|
if load_error is not None:
|
||||||
|
raise load_error
|
||||||
|
return _FakeCredentials()
|
||||||
|
|
||||||
|
def fake_refresh(creds):
|
||||||
|
state["refreshes"] += 1
|
||||||
|
if refresh_error is not None:
|
||||||
|
raise refresh_error
|
||||||
|
creds.token = token
|
||||||
|
creds.valid = bool(token)
|
||||||
|
|
||||||
|
monkeypatch.setattr(scc, "_service_account_credentials", fake_load)
|
||||||
|
monkeypatch.setattr(scc, "_refresh_sync", fake_refresh)
|
||||||
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
def _client(handler, monkeypatch, **auth_kwargs) -> SearchConsoleClient:
|
||||||
|
_auth(monkeypatch, **auth_kwargs)
|
||||||
|
return SearchConsoleClient("dummy-credentials.json", transport=httpx.MockTransport(handler))
|
||||||
|
|
||||||
|
|
||||||
|
# ── 1) 사이트맵 제출 ──────────────────────────────────────────────────────
|
||||||
|
async def test_사이트맵_제출은_URL을_완전_퍼센트인코딩한다(monkeypatch):
|
||||||
|
"""검증: property/sitemap 주소를 PUT 경로에 싣는다.
|
||||||
|
기대결과: 두 주소 모두 `/` `:` 까지 percent-encode 되어 경로 세그먼트 하나로 들어간다."""
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
captured["method"] = request.method
|
||||||
|
captured["url"] = str(request.url)
|
||||||
|
captured["auth"] = request.headers.get("Authorization")
|
||||||
|
return httpx.Response(200)
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch, token="tok-abc")
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert captured["method"] == "PUT"
|
||||||
|
assert captured["url"] == (
|
||||||
|
f"{scc.SITEMAPS_BASE}/https%3A%2F%2Fexample.com%2F"
|
||||||
|
"/sitemaps/https%3A%2F%2Fexample.com%2Fsitemap.xml"
|
||||||
|
)
|
||||||
|
assert captured["auth"] == "Bearer tok-abc"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_사이트맵_제출_성공은_아무것도_돌려주지_않는다(monkeypatch):
|
||||||
|
"""검증: 2xx 응답(빈 본문).
|
||||||
|
기대결과: 예외 없이 끝난다 — 반환값은 None."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200)
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
async with client:
|
||||||
|
assert await client.submit_sitemap(PROPERTY, SITEMAP) is None
|
||||||
|
|
||||||
|
|
||||||
|
# ── 2) URL 검사 ───────────────────────────────────────────────────────────
|
||||||
|
async def test_URL_검사는_indexStatusResult만_돌려준다(monkeypatch):
|
||||||
|
"""검증: 응답에 indexStatusResult 외에 mobileUsabilityResult 등 다른 필드도 있다.
|
||||||
|
기대결과: indexStatusResult 만 뽑아 돌려준다."""
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
assert request.method == "POST"
|
||||||
|
assert scc.INSPECT_URL in str(request.url)
|
||||||
|
return httpx.Response(200, json={
|
||||||
|
"inspectionResult": {
|
||||||
|
"indexStatusResult": {"verdict": "PASS", "coverageState": "Submitted and indexed"},
|
||||||
|
"mobileUsabilityResult": {"verdict": "PASS"},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
async with client:
|
||||||
|
result = await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert result == {"verdict": "PASS", "coverageState": "Submitted and indexed"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_URL_검사_요청_본문은_inspectionUrl과_siteUrl이다(monkeypatch):
|
||||||
|
"""검증: 검사 요청 본문.
|
||||||
|
기대결과: {"inspectionUrl": 검사할 페이지, "siteUrl": 프로퍼티} 그대로."""
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
captured["body"] = request.content
|
||||||
|
return httpx.Response(200, json={"inspectionResult": {"indexStatusResult": {"verdict": "PASS"}}})
|
||||||
|
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert _json.loads(captured["body"]) == {"inspectionUrl": PAGE, "siteUrl": PROPERTY}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_inspectionResult가_없으면_미색인으로_넘겨짚지_않는다(monkeypatch):
|
||||||
|
"""검증: ★ 응답 본문이 비어 있다({}).
|
||||||
|
기대결과: SearchConsoleError("missing_inspection_result") — 빈 dict 를 돌려주지 않는다.
|
||||||
|
(호출측이 빈 dict 를 "미색인"으로 오판할 수 있으므로 여기서 예외로 끊는다.)"""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200, json={})
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "missing_inspection_result"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_indexStatusResult가_없으면_예외(monkeypatch):
|
||||||
|
"""검증: inspectionResult 는 있는데 indexStatusResult 가 없다(다른 결과만 있음).
|
||||||
|
기대결과: SearchConsoleError("missing_index_status_result")."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200, json={"inspectionResult": {"mobileUsabilityResult": {}}})
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "missing_index_status_result"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_indexStatusResult가_빈_객체면_예외(monkeypatch):
|
||||||
|
"""검증: indexStatusResult 는 있지만 빈 dict({}) — 실제 검사가 안 된 응답이다.
|
||||||
|
기대결과: SearchConsoleError("missing_index_status_result") — 빈 결과를 색인 상태로 돌려주지 않는다."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200, json={"inspectionResult": {"indexStatusResult": {}}})
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "missing_index_status_result"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_비정상_JSON_본문은_invalid_json(monkeypatch):
|
||||||
|
"""검증: 200 인데 본문이 JSON 이 아니다.
|
||||||
|
기대결과: SearchConsoleError("invalid_json") — 파싱 실패가 조용히 넘어가지 않는다."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200, text="<html>not json</html>")
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "invalid_json"
|
||||||
|
|
||||||
|
|
||||||
|
# ── 3) HTTP 상태 코드 정규화 ─────────────────────────────────────────────
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("status", "code"),
|
||||||
|
[(401, "unauthorized"), (403, "forbidden"), (429, "rate_limited"), (500, "server_error"), (503, "server_error")],
|
||||||
|
)
|
||||||
|
async def test_HTTP_오류_상태코드는_code로_정규화된다(monkeypatch, status, code):
|
||||||
|
"""검증: 401/403/429/5xx 응답.
|
||||||
|
기대결과: SearchConsoleError.code 가 상태별로 정규화되고, Google 응답 본문은 code 에 섞이지 않는다."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(status, text="google 응답 본문(비밀은 아니지만 새면 안 된다)")
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert exc.value.code == code
|
||||||
|
assert "google 응답 본문" not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 4) 전송 오류 ─────────────────────────────────────────────────────────
|
||||||
|
async def test_타임아웃은_timeout으로_정규화(monkeypatch):
|
||||||
|
"""검증: 요청이 타임아웃된다.
|
||||||
|
기대결과: SearchConsoleError("timeout")."""
|
||||||
|
def handler(request):
|
||||||
|
raise httpx.ReadTimeout("timed out", request=request)
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "timeout"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_연결_실패는_transport_error로_정규화(monkeypatch):
|
||||||
|
"""검증: 연결 자체가 끊긴다(DNS 실패 등).
|
||||||
|
기대결과: SearchConsoleError("transport_error")."""
|
||||||
|
def handler(request):
|
||||||
|
raise httpx.ConnectError("연결 실패", request=request)
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert exc.value.code == "transport_error"
|
||||||
|
|
||||||
|
|
||||||
|
# ── 5) 인증 실패 ─────────────────────────────────────────────────────────
|
||||||
|
async def test_키파일_로딩_실패는_invalid_credentials_file(monkeypatch):
|
||||||
|
"""검증: 서비스 계정 키 파일을 못 읽는다(없음·손상).
|
||||||
|
기대결과: SearchConsoleError("invalid_credentials_file") — 원본 예외 메시지는 안 실린다."""
|
||||||
|
def handler(request):
|
||||||
|
raise AssertionError("인증에 실패했으면 네트워크를 타면 안 된다")
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch, load_error=ValueError("키 파일 내용: super-secret-key-material"))
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert exc.value.code == "invalid_credentials_file"
|
||||||
|
assert "super-secret-key-material" not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_토큰_갱신_실패는_auth_failed(monkeypatch):
|
||||||
|
"""검증: 키 파일은 읽었지만 Google 토큰 발급이 거부된다(폐기된 키 등).
|
||||||
|
기대결과: SearchConsoleError("auth_failed") — 원본 예외 메시지는 안 실린다."""
|
||||||
|
def handler(request):
|
||||||
|
raise AssertionError("인증에 실패했으면 네트워크를 타면 안 된다")
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch, refresh_error=RuntimeError("invalid_grant: token revoked=xyz"))
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.inspect_url(PROPERTY, PAGE)
|
||||||
|
|
||||||
|
assert exc.value.code == "auth_failed"
|
||||||
|
assert "revoked=xyz" not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_토큰이_비면_auth_failed(monkeypatch):
|
||||||
|
"""검증: 갱신은 예외 없이 끝났지만 credentials.token 이 비어 있다.
|
||||||
|
기대결과: SearchConsoleError("auth_failed") — 빈 토큰으로 요청을 보내지 않는다."""
|
||||||
|
def handler(request):
|
||||||
|
raise AssertionError("빈 토큰으로 네트워크를 타면 안 된다")
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch, token="")
|
||||||
|
with pytest.raises(SearchConsoleError) as exc:
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert exc.value.code == "auth_failed"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_인증정보_로딩과_유효한_토큰_갱신은_한_번만_한다(monkeypatch):
|
||||||
|
"""검증: 같은 클라이언트로 두 번 호출한다.
|
||||||
|
기대결과: 키 파일 로딩 1회 · 토큰 갱신 1회 — 두 번째 호출은 여전히 유효한(`credentials.valid`)
|
||||||
|
토큰을 그대로 재사용한다."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200)
|
||||||
|
|
||||||
|
state = _auth(monkeypatch)
|
||||||
|
client = SearchConsoleClient("dummy-credentials.json", transport=httpx.MockTransport(handler))
|
||||||
|
async with client:
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
await client.submit_sitemap(PROPERTY, SITEMAP)
|
||||||
|
|
||||||
|
assert state["loads"] == 1
|
||||||
|
assert state["refreshes"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_동시_호출은_토큰_갱신을_한_번만_한다(monkeypatch):
|
||||||
|
"""검증: 아직 토큰이 없는 클라이언트를 두 요청이 동시에 부른다.
|
||||||
|
기대결과: 갱신 1회 — 잠금 없이 두 번째 요청이 갱신 중인 자격을 다시 갱신하면
|
||||||
|
Google 토큰 엔드포인트를 요청 수만큼 때리게 된다."""
|
||||||
|
import time as _time
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200)
|
||||||
|
|
||||||
|
state = _auth(monkeypatch)
|
||||||
|
|
||||||
|
def slow_refresh(creds):
|
||||||
|
_time.sleep(0.05)
|
||||||
|
state["refreshes"] += 1
|
||||||
|
creds.token = "tok"
|
||||||
|
creds.valid = True
|
||||||
|
|
||||||
|
monkeypatch.setattr(scc, "_refresh_sync", slow_refresh)
|
||||||
|
|
||||||
|
client = SearchConsoleClient("dummy-credentials.json", transport=httpx.MockTransport(handler))
|
||||||
|
async with client:
|
||||||
|
await asyncio.gather(
|
||||||
|
client.submit_sitemap(PROPERTY, SITEMAP),
|
||||||
|
client.submit_sitemap(PROPERTY, SITEMAP),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert state["refreshes"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
# ── 6) 닫기 ──────────────────────────────────────────────────────────────
|
||||||
|
async def test_async_컨텍스트매니저는_내부_httpx_클라이언트를_닫는다(monkeypatch):
|
||||||
|
"""검증: `async with` 블록을 빠져나간다.
|
||||||
|
기대결과: 내부 httpx.AsyncClient 가 닫힌다 — 커넥션을 남겨두지 않는다."""
|
||||||
|
def handler(request):
|
||||||
|
return httpx.Response(200)
|
||||||
|
|
||||||
|
client = _client(handler, monkeypatch)
|
||||||
|
async with client:
|
||||||
|
pass
|
||||||
|
|
||||||
|
assert client._client.is_closed is True
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import AsyncMock
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.database.model.models import places, sites, site_versions, site_search_status
|
||||||
|
from crud import search_console_crud as store
|
||||||
|
from services import search_console_service as service
|
||||||
|
from services.search_console_client import SearchConsoleError
|
||||||
|
from services.search_console_alerts import alert_reason, send_alert
|
||||||
|
from services.search_console_settings import SearchConsoleSettings, belongs_to_property, load_settings
|
||||||
|
|
||||||
|
NOW = datetime.now(timezone.utc)
|
||||||
|
SETTINGS = SearchConsoleSettings("https://example.com/", "/test/key.json")
|
||||||
|
|
||||||
|
|
||||||
|
def status(**changes):
|
||||||
|
return SimpleNamespace(site_id=uuid.uuid4(), page_url="https://example.com/s/stay",
|
||||||
|
property_url=SETTINGS.property_url, published_at=NOW - timedelta(days=8),
|
||||||
|
sitemap_submitted_at=None, inspected_at=None, inspection=None,
|
||||||
|
first_indexed_at=None, error_code=None, failures=0, alerted_at=None,
|
||||||
|
next_check_at=NOW, **changes)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("url,prop,expected", [
|
||||||
|
("https://example.com/s/a", "https://example.com/", True),
|
||||||
|
("https://example.com.evil.test/s/a", "https://example.com/", False),
|
||||||
|
("https://sub.example.com/s/a", "sc-domain:example.com", True),
|
||||||
|
("https://notexample.com/s/a", "sc-domain:example.com", False),
|
||||||
|
("http://example.com/s/a", "sc-domain:example.com", False),
|
||||||
|
("https://example.com/s/a?secret=x", "sc-domain:example.com", False),
|
||||||
|
])
|
||||||
|
def test_property_scope(url, prop, expected):
|
||||||
|
assert belongs_to_property(url, prop) is expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_needs_no_credentials(monkeypatch):
|
||||||
|
monkeypatch.delenv("GSC_ENABLED", raising=False)
|
||||||
|
assert load_settings() is None
|
||||||
|
monkeypatch.setenv("GSC_ENABLED", "1")
|
||||||
|
monkeypatch.delenv("GSC_PROPERTY_URL", raising=False)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_submit_and_inspect_are_separate(monkeypatch):
|
||||||
|
row = status()
|
||||||
|
client = SimpleNamespace(submit_sitemap=AsyncMock(), inspect_url=AsyncMock(return_value={"verdict": "NEUTRAL"}))
|
||||||
|
monkeypatch.setattr(service, "read_sitemap", AsyncMock(return_value={row.page_url}))
|
||||||
|
monkeypatch.setattr(service.site_payload, "publish_origin", lambda: "https://example.com")
|
||||||
|
await service.check_site(client, row, SETTINGS, set())
|
||||||
|
assert row.sitemap_submitted_at
|
||||||
|
assert row.inspected_at
|
||||||
|
assert row.first_indexed_at is None
|
||||||
|
assert row.next_check_at > NOW
|
||||||
|
assert row.error_code is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_missing_sitemap_url_retries_without_google_call(monkeypatch):
|
||||||
|
row = status()
|
||||||
|
client = SimpleNamespace(submit_sitemap=AsyncMock(), inspect_url=AsyncMock())
|
||||||
|
monkeypatch.setattr(service, "read_sitemap", AsyncMock(return_value=set()))
|
||||||
|
await service.check_site(client, row, SETTINGS, set())
|
||||||
|
assert row.error_code == "URL_NOT_IN_SITEMAP"
|
||||||
|
assert row.sitemap_submitted_at is None
|
||||||
|
assert row.failures == 1
|
||||||
|
client.submit_sitemap.assert_not_awaited()
|
||||||
|
client.inspect_url.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_one_sitemap_submission_per_batch(monkeypatch):
|
||||||
|
client = SimpleNamespace(submit_sitemap=AsyncMock())
|
||||||
|
monkeypatch.setattr(service, "read_sitemap", AsyncMock(return_value={status().page_url}))
|
||||||
|
seen = set()
|
||||||
|
await service.submit_sitemap(client, status(), seen)
|
||||||
|
await service.submit_sitemap(client, status(), seen)
|
||||||
|
client.submit_sitemap.assert_awaited_once()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_inspection_failure_preserves_previous_observation():
|
||||||
|
row = status()
|
||||||
|
row.sitemap_submitted_at = NOW
|
||||||
|
row.inspection = {"verdict": "PASS"}
|
||||||
|
row.inspected_at = NOW - timedelta(days=1)
|
||||||
|
client = SimpleNamespace(inspect_url=AsyncMock(side_effect=SearchConsoleError("HTTP_429")))
|
||||||
|
await service.check_site(client, row, SETTINGS, set())
|
||||||
|
assert row.inspection == {"verdict": "PASS"}
|
||||||
|
assert row.inspected_at < NOW
|
||||||
|
assert row.error_code == "HTTP_429"
|
||||||
|
assert row.failures == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_indexed_is_observation_time_not_google_crawl_time():
|
||||||
|
row = status()
|
||||||
|
service.record_inspection(row, {"verdict": "PASS", "lastCrawlTime": "2020-01-01T00:00:00Z"}, NOW)
|
||||||
|
service.record_inspection(row, {"verdict": "PASS"}, NOW + timedelta(days=1))
|
||||||
|
assert row.first_indexed_at == NOW
|
||||||
|
|
||||||
|
|
||||||
|
def test_alert_cooldown_and_backoff():
|
||||||
|
row = status()
|
||||||
|
assert alert_reason(row, NOW, 7)
|
||||||
|
row.alerted_at = NOW
|
||||||
|
assert alert_reason(row, NOW, 7) is None
|
||||||
|
for _ in range(30):
|
||||||
|
service.record_error(row, "HTTP_503", NOW)
|
||||||
|
assert row.next_check_at == NOW + timedelta(days=1)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_failed_alert_does_not_mark_delivered(monkeypatch):
|
||||||
|
row = status()
|
||||||
|
row.sitemap_submitted_at = NOW
|
||||||
|
client = SimpleNamespace(inspect_url=AsyncMock(return_value={"verdict": "NEUTRAL"}))
|
||||||
|
send = AsyncMock(return_value=False)
|
||||||
|
monkeypatch.setattr(service, "send_alert", send)
|
||||||
|
await service.check_site(client, row, SETTINGS, set())
|
||||||
|
send.assert_awaited_once()
|
||||||
|
assert row.alerted_at is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_empty_alert_url_never_calls_network():
|
||||||
|
assert not await send_alert("", "https://example.com/s/a", "delayed")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_disabled_cron_never_opens_database(monkeypatch):
|
||||||
|
monkeypatch.delenv("GSC_ENABLED", raising=False)
|
||||||
|
call = AsyncMock()
|
||||||
|
monkeypatch.setattr(service.DB_SESSION_MNG, "execute_lambda_write", call)
|
||||||
|
await service.run_scheduled_check()
|
||||||
|
call.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def seed_site(session, *, state=3):
|
||||||
|
place = places(place_id=uuid.uuid4(), owner_user_id=uuid.uuid4(), name="숙소", category=1)
|
||||||
|
site = sites(site_id=uuid.uuid4(), place_id=place.place_id, status=state,
|
||||||
|
domain="stay", published_at=NOW)
|
||||||
|
version = site_versions(site_version_id=uuid.uuid4(), site_id=site.site_id, version=1, build_status=2)
|
||||||
|
site.current_version_id = version.site_version_id
|
||||||
|
session.add_all([place, site, version])
|
||||||
|
await session.flush()
|
||||||
|
return site, place, version
|
||||||
|
|
||||||
|
|
||||||
|
async def test_registration_survives_restart_and_resets_on_publish(db_engine, monkeypatch):
|
||||||
|
monkeypatch.setattr(service.site_payload, "publish_origin", lambda: "https://example.com")
|
||||||
|
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||||
|
site, _, _ = await seed_site(session)
|
||||||
|
await service.register_publications(session, SETTINGS)
|
||||||
|
await session.commit()
|
||||||
|
row = await session.get(site_search_status, site.site_id)
|
||||||
|
row.sitemap_submitted_at = NOW
|
||||||
|
row.first_indexed_at = NOW
|
||||||
|
await session.commit()
|
||||||
|
await service.register_publications(session, SETTINGS)
|
||||||
|
assert row.first_indexed_at == NOW
|
||||||
|
site.published_at = NOW + timedelta(seconds=1)
|
||||||
|
await session.commit()
|
||||||
|
await service.register_publications(session, SETTINGS)
|
||||||
|
await session.commit()
|
||||||
|
await session.refresh(row)
|
||||||
|
assert row.first_indexed_at is None
|
||||||
|
assert row.sitemap_submitted_at is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_unpublished_and_deleted_places_are_not_checked(db_engine, monkeypatch):
|
||||||
|
monkeypatch.setattr(service.site_payload, "publish_origin", lambda: "https://example.com")
|
||||||
|
async with AsyncSession(db_engine) as session:
|
||||||
|
site, place, _ = await seed_site(session)
|
||||||
|
await service.register_publications(session, SETTINGS)
|
||||||
|
assert len(await store.due_sites(session, SETTINGS.property_url)) == 1
|
||||||
|
site.status = 5
|
||||||
|
await session.flush()
|
||||||
|
assert not await store.due_sites(session, SETTINGS.property_url)
|
||||||
|
site.status = 3
|
||||||
|
place.deleted = True
|
||||||
|
await session.flush()
|
||||||
|
assert not await store.due_sites(session, SETTINGS.property_url)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_batch_lock_excludes_second_process(db_engine):
|
||||||
|
async with AsyncSession(db_engine) as first, AsyncSession(db_engine) as second:
|
||||||
|
assert await store.lock_batch(first)
|
||||||
|
assert not await store.lock_batch(second)
|
||||||
|
await first.rollback()
|
||||||
|
assert await store.lock_batch(second)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_full_batch_commits_and_does_not_repeat_same_day(db_engine, monkeypatch):
|
||||||
|
monkeypatch.setattr(service.site_payload, "publish_origin", lambda: "https://example.com")
|
||||||
|
monkeypatch.setattr(service, "read_sitemap", AsyncMock(return_value={status().page_url}))
|
||||||
|
client = SimpleNamespace(submit_sitemap=AsyncMock(), inspect_url=AsyncMock(return_value={"verdict": "PASS"}))
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, *_):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return client
|
||||||
|
|
||||||
|
async def __aexit__(self, *_):
|
||||||
|
pass
|
||||||
|
|
||||||
|
monkeypatch.setattr(service, "SearchConsoleClient", FakeClient)
|
||||||
|
async with AsyncSession(db_engine) as session:
|
||||||
|
site, _, _ = await seed_site(session)
|
||||||
|
sid = site.site_id
|
||||||
|
await session.commit()
|
||||||
|
await service.run_batch(session, SETTINGS)
|
||||||
|
await session.commit()
|
||||||
|
async with AsyncSession(db_engine) as session:
|
||||||
|
row = await session.get(site_search_status, sid)
|
||||||
|
assert row.sitemap_submitted_at
|
||||||
|
assert row.first_indexed_at
|
||||||
|
await service.run_batch(session, SETTINGS)
|
||||||
|
await session.commit()
|
||||||
|
client.submit_sitemap.assert_awaited_once()
|
||||||
|
client.inspect_url.assert_awaited_once()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cron_failure_is_isolated(monkeypatch):
|
||||||
|
monkeypatch.setattr(service, "load_settings", lambda: SETTINGS)
|
||||||
|
monkeypatch.setattr(service.DB_SESSION_MNG, "execute_lambda_write", AsyncMock(side_effect=RuntimeError("db")))
|
||||||
|
await service.run_scheduled_check()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_sitemap_http_parser(monkeypatch):
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
real_client = httpx.AsyncClient
|
||||||
|
transport = httpx.MockTransport(lambda request: httpx.Response(200, text='''
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
<url><loc>https://example.com/s/stay</loc></url></urlset>'''))
|
||||||
|
monkeypatch.setattr(service.httpx, "AsyncClient", lambda **kw: real_client(transport=transport, **kw))
|
||||||
|
assert await service.read_sitemap("https://example.com/sitemap.xml") == {status().page_url}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_sitemap_redirect_is_not_followed(monkeypatch):
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
real_client = httpx.AsyncClient
|
||||||
|
transport = httpx.MockTransport(lambda request: httpx.Response(302, headers={"location": "http://internal/"}))
|
||||||
|
monkeypatch.setattr(service.httpx, "AsyncClient", lambda **kw: real_client(transport=transport, **kw))
|
||||||
|
with pytest.raises(SearchConsoleError, match="SITEMAP_UNAVAILABLE"):
|
||||||
|
await service.read_sitemap("https://example.com/sitemap.xml")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("enabled,count", [("0", 0), ("1", 1)])
|
||||||
|
def test_existing_scheduler_registers_optional_job(monkeypatch, enabled, count):
|
||||||
|
import scheduler
|
||||||
|
|
||||||
|
instance = SimpleNamespace(add_job=lambda *a, **kw: jobs.append((a, kw)),
|
||||||
|
start=lambda: None, get_jobs=lambda: jobs)
|
||||||
|
jobs = []
|
||||||
|
monkeypatch.setattr(scheduler, "_scheduler", None)
|
||||||
|
monkeypatch.setattr(scheduler, "AsyncIOScheduler", lambda **kw: instance)
|
||||||
|
monkeypatch.setenv("SCHEDULER_ENABLED", "1")
|
||||||
|
monkeypatch.setenv("GSC_ENABLED", enabled)
|
||||||
|
scheduler.start_scheduler()
|
||||||
|
assert len(jobs) == count
|
||||||
|
if jobs:
|
||||||
|
assert jobs[0][1]["minutes"] == 10
|
||||||
|
assert jobs[0][1]["max_instances"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_migration_matches_fresh_database_schema():
|
||||||
|
from pathlib import Path
|
||||||
|
root = Path(__file__).resolve().parents[3]
|
||||||
|
migration = (root / "postgres-init/migrations/0014_search_console.sql").read_text()
|
||||||
|
ddl = migration[migration.index("CREATE TABLE"):].strip()
|
||||||
|
assert ddl in (root / "postgres-init/init-data/init.sql").read_text()
|
||||||
@@ -23,7 +23,7 @@ def _reply(content: str, search_results=None) -> dict:
|
|||||||
# ── 프롬프트 ────────────────────────────────────────────────────────────
|
# ── 프롬프트 ────────────────────────────────────────────────────────────
|
||||||
def test_프롬프트는_shared_산출물에서_온다():
|
def test_프롬프트는_shared_산출물에서_온다():
|
||||||
"""여섯 종이 모두 있고, 지역명이 빈칸 없이 박힌다."""
|
"""여섯 종이 모두 있고, 지역명이 빈칸 없이 박힌다."""
|
||||||
assert set(prompts.kinds()) == {"songs", "daily", "people", "chronicle", "postcard", "quiz"}
|
assert set(prompts.kinds()) == {"songs", "daily", "people", "chronicle", "reading", "postcard", "quiz"}
|
||||||
text = prompts.build_prompt("songs", "전북 군산시")
|
text = prompts.build_prompt("songs", "전북 군산시")
|
||||||
assert "[지역] 전북 군산시" in text
|
assert "[지역] 전북 군산시" in text
|
||||||
assert "[지역]을 노래한 대중가요" in text # task 원문
|
assert "[지역]을 노래한 대중가요" in text # task 원문
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
from services.weather_notes import weather_notes
|
||||||
|
from services.site_payload import _weather
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_weather_cases_have_five_unique_lines():
|
||||||
|
notes = weather_notes()
|
||||||
|
assert set(notes["noteSets"]) == {"맑음", "구름많음", "흐림", "비", "눈"}
|
||||||
|
assert set(notes["tempNoteSets"]) == {"혹서", "더움", "선선", "쌀쌀", "추움"}
|
||||||
|
lines = [line for key in ("noteSets", "tempNoteSets") for group in notes[key].values() for line in group]
|
||||||
|
assert len(lines) == len(set(lines)) == 50
|
||||||
|
|
||||||
|
|
||||||
|
def test_templates_are_not_mutated_by_a_payload():
|
||||||
|
notes = weather_notes()
|
||||||
|
notes["noteSets"]["비"].clear()
|
||||||
|
assert len(weather_notes()["noteSets"]["비"]) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_payload_attaches_notes_only_to_real_observations():
|
||||||
|
assert _weather({"body": {}}) is None
|
||||||
|
weather = _weather({"body": {"temperature": 0, "weather_code": 71, "observed_at": "2026-09-15T12:00"}})
|
||||||
|
assert weather["condition"] == "눈"
|
||||||
|
assert weather["temperature"] == 0
|
||||||
|
assert len(weather["tempNoteSets"]["추움"]) == 5
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
JobType.BUILD ✓ services/build_service.run_build — 정적 빌드 + 발행 검수 게이트
|
JobType.BUILD ✓ services/build_service.run_build — 정적 빌드 + 발행 검수 게이트
|
||||||
JobType.LOCAL_SYNC ✓ services/story_service.run_local_sync — 지역 이야기 생성(지역당 1회)
|
JobType.LOCAL_SYNC ✓ services/story_service.run_local_sync — 지역 이야기 생성(지역당 1회)
|
||||||
JobType.SONG ✓ services/song_service.run_song — 이 숙소의 노래 한 곡(가사 Gemini → 작곡 Suno)
|
JobType.SONG ✓ services/song_service.run_song — 이 숙소의 노래 한 곡(가사 Gemini → 작곡 Suno)
|
||||||
|
JobType.ROLLBACK ✓ services/rollback_service.run_rollback — 예전 버전으로 공개 주소를 되돌림
|
||||||
JobType.AI_CHECK → reports 모듈이 붙을 때
|
JobType.AI_CHECK → reports 모듈이 붙을 때
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -82,6 +83,7 @@ def _register_builtin():
|
|||||||
from services.copy_service import run_copy
|
from services.copy_service import run_copy
|
||||||
from services.story_service import run_local_sync
|
from services.story_service import run_local_sync
|
||||||
from services.song_service import run_song
|
from services.song_service import run_song
|
||||||
|
from services.rollback_service import run_rollback
|
||||||
from services.vision_service import run_vision
|
from services.vision_service import run_vision
|
||||||
|
|
||||||
if JobType.COLLECT.value not in HANDLERS:
|
if JobType.COLLECT.value not in HANDLERS:
|
||||||
@@ -96,6 +98,8 @@ def _register_builtin():
|
|||||||
HANDLERS[JobType.LOCAL_SYNC.value] = run_local_sync
|
HANDLERS[JobType.LOCAL_SYNC.value] = run_local_sync
|
||||||
if JobType.SONG.value not in HANDLERS:
|
if JobType.SONG.value not in HANDLERS:
|
||||||
HANDLERS[JobType.SONG.value] = run_song
|
HANDLERS[JobType.SONG.value] = run_song
|
||||||
|
if JobType.ROLLBACK.value not in HANDLERS:
|
||||||
|
HANDLERS[JobType.ROLLBACK.value] = run_rollback
|
||||||
|
|
||||||
|
|
||||||
_register_builtin()
|
_register_builtin()
|
||||||
@@ -4,10 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
useMutation,
|
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -20,8 +17,8 @@ import type {
|
|||||||
UseMutationOptions,
|
UseMutationOptions,
|
||||||
UseMutationResult,
|
UseMutationResult,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
HTTPValidationError,
|
HTTPValidationError,
|
||||||
@@ -31,429 +28,576 @@ import type {
|
|||||||
ReqUpdateMe,
|
ReqUpdateMe,
|
||||||
ResLogin,
|
ResLogin,
|
||||||
ResMe,
|
ResMe,
|
||||||
ResRefreshToken
|
ResRefreshToken,
|
||||||
} from '.././model';
|
} from ".././model";
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* id/pw 로 로그인하고 JWT 토큰을 발급한다.
|
* id/pw 로 로그인하고 JWT 토큰을 발급한다.
|
||||||
* @summary 로그인
|
* @summary 로그인
|
||||||
*/
|
*/
|
||||||
export const login = (
|
export const login = (
|
||||||
reqLogin: ReqLogin,
|
reqLogin: ReqLogin,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResLogin>(
|
||||||
|
{
|
||||||
return customFetch<ResLogin>(
|
url: `/v1/auth/login`,
|
||||||
{url: `/v1/auth/login`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqLogin, signal
|
data: reqLogin,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLoginMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof login>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqLogin },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof login>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqLogin },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["login"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getLoginMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof login>>, TError,{data: ReqLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof login>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof login>>, TError,{data: ReqLogin}, TContext> => {
|
{ data: ReqLogin }
|
||||||
|
> = (props) => {
|
||||||
|
const { data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['login'];
|
return login(data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LoginMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof login>>
|
||||||
|
>;
|
||||||
|
export type LoginMutationBody = ReqLogin;
|
||||||
|
export type LoginMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof login>>, {data: ReqLogin}> = (props) => {
|
/**
|
||||||
const {data} = props ?? {};
|
|
||||||
|
|
||||||
return login(data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type LoginMutationResult = NonNullable<Awaited<ReturnType<typeof login>>>
|
|
||||||
export type LoginMutationBody = ReqLogin
|
|
||||||
export type LoginMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 로그인
|
* @summary 로그인
|
||||||
*/
|
*/
|
||||||
export const useLogin = <TError = void | HTTPValidationError,
|
export const useLogin = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof login>>, TError,{data: ReqLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof login>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{data: ReqLogin},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof login>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ data: ReqLogin },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof login>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqLogin },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getLoginMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getLoginMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* id/pw 로 가입한다. 회사(테넌트) 1개가 함께 생기고, 성공하면 곧바로 로그인 토큰을 발급한다.
|
* id/pw 로 가입한다. 회사(테넌트) 1개가 함께 생기고, 성공하면 곧바로 로그인 토큰을 발급한다.
|
||||||
* @summary 회원가입
|
* @summary 회원가입
|
||||||
*/
|
*/
|
||||||
export const signup = (
|
export const signup = (
|
||||||
reqSignup: ReqSignup,
|
reqSignup: ReqSignup,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResLogin>(
|
||||||
|
{
|
||||||
return customFetch<ResLogin>(
|
url: `/v1/auth/signup`,
|
||||||
{url: `/v1/auth/signup`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqSignup, signal
|
data: reqSignup,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getSignupMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof signup>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqSignup },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof signup>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqSignup },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["signup"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getSignupMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof signup>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext> => {
|
{ data: ReqSignup }
|
||||||
|
> = (props) => {
|
||||||
|
const { data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['signup'];
|
return signup(data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SignupMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof signup>>
|
||||||
|
>;
|
||||||
|
export type SignupMutationBody = ReqSignup;
|
||||||
|
export type SignupMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof signup>>, {data: ReqSignup}> = (props) => {
|
/**
|
||||||
const {data} = props ?? {};
|
|
||||||
|
|
||||||
return signup(data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type SignupMutationResult = NonNullable<Awaited<ReturnType<typeof signup>>>
|
|
||||||
export type SignupMutationBody = ReqSignup
|
|
||||||
export type SignupMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 회원가입
|
* @summary 회원가입
|
||||||
*/
|
*/
|
||||||
export const useSignup = <TError = void | HTTPValidationError,
|
export const useSignup = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof signup>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{data: ReqSignup},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof signup>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ data: ReqSignup },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof signup>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqSignup },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getSignupMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getSignupMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 구글 ID 토큰(GIS credential)을 검증하고 JWT 토큰을 발급한다. 처음 온 계정은 그 자리에서 만든다.
|
* 구글 ID 토큰(GIS credential)을 검증하고 JWT 토큰을 발급한다. 처음 온 계정은 그 자리에서 만든다.
|
||||||
* @summary 구글 로그인
|
* @summary 구글 로그인
|
||||||
*/
|
*/
|
||||||
export const googleLogin = (
|
export const googleLogin = (
|
||||||
reqGoogleLogin: ReqGoogleLogin,
|
reqGoogleLogin: ReqGoogleLogin,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResLogin>(
|
||||||
|
{
|
||||||
return customFetch<ResLogin>(
|
url: `/v1/auth/google`,
|
||||||
{url: `/v1/auth/google`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqGoogleLogin, signal
|
data: reqGoogleLogin,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getGoogleLoginMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof googleLogin>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqGoogleLogin },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof googleLogin>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqGoogleLogin },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["googleLogin"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getGoogleLoginMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof googleLogin>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext> => {
|
{ data: ReqGoogleLogin }
|
||||||
|
> = (props) => {
|
||||||
|
const { data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['googleLogin'];
|
return googleLogin(data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GoogleLoginMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof googleLogin>>
|
||||||
|
>;
|
||||||
|
export type GoogleLoginMutationBody = ReqGoogleLogin;
|
||||||
|
export type GoogleLoginMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof googleLogin>>, {data: ReqGoogleLogin}> = (props) => {
|
/**
|
||||||
const {data} = props ?? {};
|
|
||||||
|
|
||||||
return googleLogin(data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type GoogleLoginMutationResult = NonNullable<Awaited<ReturnType<typeof googleLogin>>>
|
|
||||||
export type GoogleLoginMutationBody = ReqGoogleLogin
|
|
||||||
export type GoogleLoginMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 구글 로그인
|
* @summary 구글 로그인
|
||||||
*/
|
*/
|
||||||
export const useGoogleLogin = <TError = void | HTTPValidationError,
|
export const useGoogleLogin = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof googleLogin>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{data: ReqGoogleLogin},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof googleLogin>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ data: ReqGoogleLogin },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof googleLogin>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqGoogleLogin },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getGoogleLoginMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getGoogleLoginMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* refresh 토큰으로 access 토큰을 재발급한다.
|
* refresh 토큰으로 access 토큰을 재발급한다.
|
||||||
* @summary 액세스 토큰 갱신
|
* @summary 액세스 토큰 갱신
|
||||||
*/
|
*/
|
||||||
export const refreshToken = (
|
export const refreshToken = (
|
||||||
|
options?: SecondParameter<typeof customFetch>,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResRefreshToken>(
|
||||||
|
{ url: `/v1/auth/refresh_token`, method: "POST", signal },
|
||||||
return customFetch<ResRefreshToken>(
|
options,
|
||||||
{url: `/v1/auth/refresh_token`, method: 'POST', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getRefreshTokenMutationOptions = <
|
||||||
|
TError = void,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof refreshToken>>,
|
||||||
|
TError,
|
||||||
|
void,
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof refreshToken>>,
|
||||||
|
TError,
|
||||||
|
void,
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["refreshToken"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getRefreshTokenMutationOptions = <TError = void,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof refreshToken>>, TError,void, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof refreshToken>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof refreshToken>>, TError,void, TContext> => {
|
void
|
||||||
|
> = () => {
|
||||||
|
return refreshToken(requestOptions);
|
||||||
|
};
|
||||||
|
|
||||||
const mutationKey = ['refreshToken'];
|
return { mutationFn, ...mutationOptions };
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
export type RefreshTokenMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof refreshToken>>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type RefreshTokenMutationError = void;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof refreshToken>>, void> = () => {
|
/**
|
||||||
|
|
||||||
|
|
||||||
return refreshToken(requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type RefreshTokenMutationResult = NonNullable<Awaited<ReturnType<typeof refreshToken>>>
|
|
||||||
|
|
||||||
export type RefreshTokenMutationError = void
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 액세스 토큰 갱신
|
* @summary 액세스 토큰 갱신
|
||||||
*/
|
*/
|
||||||
export const useRefreshToken = <TError = void,
|
export const useRefreshToken = <TError = void, TContext = unknown>(
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof refreshToken>>, TError,void, TContext>, request?: SecondParameter<typeof customFetch>}
|
options?: {
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
mutation?: UseMutationOptions<
|
||||||
Awaited<ReturnType<typeof refreshToken>>,
|
Awaited<ReturnType<typeof refreshToken>>,
|
||||||
TError,
|
TError,
|
||||||
void,
|
void,
|
||||||
TContext
|
TContext
|
||||||
> => {
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof refreshToken>>,
|
||||||
|
TError,
|
||||||
|
void,
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getRefreshTokenMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getRefreshTokenMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 유효한 access 토큰이 있어야 호출 가능. 토큰의 유저+회사 정보를 반환한다.
|
* 유효한 access 토큰이 있어야 호출 가능. 토큰의 유저+회사 정보를 반환한다.
|
||||||
* @summary 내 정보
|
* @summary 내 정보
|
||||||
*/
|
*/
|
||||||
export const me = (
|
export const me = (
|
||||||
|
options?: SecondParameter<typeof customFetch>,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResMe>(
|
||||||
|
{ url: `/v1/auth/me`, method: "GET", signal },
|
||||||
return customFetch<ResMe>(
|
options,
|
||||||
{url: `/v1/auth/me`, method: 'GET', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const getMeQueryKey = () => {
|
export const getMeQueryKey = () => {
|
||||||
return [
|
return [`/v1/auth/me`] as const;
|
||||||
`/v1/auth/me`
|
};
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
export const getMeQueryOptions = <
|
||||||
export const getMeQueryOptions = <TData = Awaited<ReturnType<typeof me>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof me>>,
|
||||||
) => {
|
TError = void,
|
||||||
|
>(options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
const queryKey = queryOptions?.queryKey ?? getMeQueryKey();
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getMeQueryKey();
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof me>>> = ({ signal }) =>
|
||||||
|
me(requestOptions, signal);
|
||||||
|
|
||||||
|
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof me>>,
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof me>>> = ({ signal }) => me(requestOptions, signal);
|
TError,
|
||||||
|
TData
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
|
||||||
}
|
|
||||||
|
|
||||||
export type MeQueryResult = NonNullable<Awaited<ReturnType<typeof me>>>
|
|
||||||
export type MeQueryError = void
|
|
||||||
|
|
||||||
|
export type MeQueryResult = NonNullable<Awaited<ReturnType<typeof me>>>;
|
||||||
|
export type MeQueryError = void;
|
||||||
|
|
||||||
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
||||||
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>> & Pick<
|
options: {
|
||||||
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof me>>,
|
Awaited<ReturnType<typeof me>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof me>>
|
Awaited<ReturnType<typeof me>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>> & Pick<
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof me>>,
|
Awaited<ReturnType<typeof me>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof me>>
|
Awaited<ReturnType<typeof me>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
options?: {
|
||||||
, queryClient?: QueryClient
|
query?: Partial<
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary 내 정보
|
* @summary 내 정보
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
export function useMe<TData = Awaited<ReturnType<typeof me>>, TError = void>(
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
options?: {
|
||||||
, queryClient?: QueryClient
|
query?: Partial<
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
UseQueryOptions<Awaited<ReturnType<typeof me>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getMeQueryOptions(options);
|
||||||
|
|
||||||
const queryOptions = getMeQueryOptions(options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 본인 이름/이메일/연락처/비밀번호를 수정한다(권한·소속·ID 변경 불가).
|
* 본인 이름/이메일/연락처/비밀번호를 수정한다(권한·소속·ID 변경 불가).
|
||||||
* @summary 내 정보 수정
|
* @summary 내 정보 수정
|
||||||
*/
|
*/
|
||||||
export const updateMe = (
|
export const updateMe = (
|
||||||
reqUpdateMe: ReqUpdateMe,
|
reqUpdateMe: ReqUpdateMe,
|
||||||
options?: SecondParameter<typeof customFetch>,) => {
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
) => {
|
||||||
|
return customFetch<ResMe>(
|
||||||
return customFetch<ResMe>(
|
{
|
||||||
{url: `/v1/auth/me`, method: 'PATCH',
|
url: `/v1/auth/me`,
|
||||||
headers: {'Content-Type': 'application/json', },
|
method: "PATCH",
|
||||||
data: reqUpdateMe
|
headers: { "Content-Type": "application/json" },
|
||||||
|
data: reqUpdateMe,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUpdateMeMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof updateMe>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqUpdateMe },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof updateMe>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqUpdateMe },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["updateMe"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getUpdateMeMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateMe>>, TError,{data: ReqUpdateMe}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof updateMe>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof updateMe>>, TError,{data: ReqUpdateMe}, TContext> => {
|
{ data: ReqUpdateMe }
|
||||||
|
> = (props) => {
|
||||||
|
const { data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['updateMe'];
|
return updateMe(data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdateMeMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof updateMe>>
|
||||||
|
>;
|
||||||
|
export type UpdateMeMutationBody = ReqUpdateMe;
|
||||||
|
export type UpdateMeMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof updateMe>>, {data: ReqUpdateMe}> = (props) => {
|
/**
|
||||||
const {data} = props ?? {};
|
|
||||||
|
|
||||||
return updateMe(data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type UpdateMeMutationResult = NonNullable<Awaited<ReturnType<typeof updateMe>>>
|
|
||||||
export type UpdateMeMutationBody = ReqUpdateMe
|
|
||||||
export type UpdateMeMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 내 정보 수정
|
* @summary 내 정보 수정
|
||||||
*/
|
*/
|
||||||
export const useUpdateMe = <TError = void | HTTPValidationError,
|
export const useUpdateMe = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateMe>>, TError,{data: ReqUpdateMe}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof updateMe>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{data: ReqUpdateMe},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof updateMe>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ data: ReqUpdateMe },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof updateMe>>,
|
||||||
|
TError,
|
||||||
|
{ data: ReqUpdateMe },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getUpdateMeMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getUpdateMeMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -4,9 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useQuery } from "@tanstack/react-query";
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -16,105 +14,163 @@ import type {
|
|||||||
QueryKey,
|
QueryKey,
|
||||||
UndefinedInitialDataOptions,
|
UndefinedInitialDataOptions,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @summary Healthz
|
* @summary Healthz
|
||||||
*/
|
*/
|
||||||
export const healthzHealthzGet = (
|
export const healthzHealthzGet = (
|
||||||
|
options?: SecondParameter<typeof customFetch>,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<unknown>(
|
||||||
|
{ url: `/healthz`, method: "GET", signal },
|
||||||
return customFetch<unknown>(
|
options,
|
||||||
{url: `/healthz`, method: 'GET', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const getHealthzHealthzGetQueryKey = () => {
|
export const getHealthzHealthzGetQueryKey = () => {
|
||||||
return [
|
return [`/healthz`] as const;
|
||||||
`/healthz`
|
};
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
export const getHealthzHealthzGetQueryOptions = <
|
||||||
export const getHealthzHealthzGetQueryOptions = <TData = Awaited<ReturnType<typeof healthzHealthzGet>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
) => {
|
TError = void,
|
||||||
|
>(options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
const queryKey = queryOptions?.queryKey ?? getHealthzHealthzGetQueryKey();
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getHealthzHealthzGetQueryKey();
|
const queryFn: QueryFunction<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>
|
||||||
|
> = ({ signal }) => healthzHealthzGet(requestOptions, signal);
|
||||||
|
|
||||||
|
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
};
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof healthzHealthzGet>>> = ({ signal }) => healthzHealthzGet(requestOptions, signal);
|
export type HealthzHealthzGetQueryResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>
|
||||||
|
>;
|
||||||
|
export type HealthzHealthzGetQueryError = void;
|
||||||
|
|
||||||
|
export function useHealthzHealthzGet<
|
||||||
|
TData = Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
options: {
|
||||||
}
|
query: Partial<
|
||||||
|
UseQueryOptions<
|
||||||
export type HealthzHealthzGetQueryResult = NonNullable<Awaited<ReturnType<typeof healthzHealthzGet>>>
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
export type HealthzHealthzGetQueryError = void
|
TError,
|
||||||
|
TData
|
||||||
|
>
|
||||||
export function useHealthzHealthzGet<TData = Awaited<ReturnType<typeof healthzHealthzGet>>, TError = void>(
|
> &
|
||||||
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData>> & Pick<
|
Pick<
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof healthzHealthzGet>>
|
Awaited<ReturnType<typeof healthzHealthzGet>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useHealthzHealthzGet<TData = Awaited<ReturnType<typeof healthzHealthzGet>>, TError = void>(
|
},
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData>> & Pick<
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useHealthzHealthzGet<
|
||||||
|
TData = Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof healthzHealthzGet>>
|
Awaited<ReturnType<typeof healthzHealthzGet>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useHealthzHealthzGet<TData = Awaited<ReturnType<typeof healthzHealthzGet>>, TError = void>(
|
},
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
queryClient?: QueryClient,
|
||||||
, queryClient?: QueryClient
|
): UseQueryResult<TData, TError> & {
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useHealthzHealthzGet<
|
||||||
|
TData = Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary Healthz
|
* @summary Healthz
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useHealthzHealthzGet<TData = Awaited<ReturnType<typeof healthzHealthzGet>>, TError = void>(
|
export function useHealthzHealthzGet<
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof healthzHealthzGet>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
, queryClient?: QueryClient
|
TError = void,
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof healthzHealthzGet>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getHealthzHealthzGetQueryOptions(options);
|
||||||
|
|
||||||
const queryOptions = getHealthzHealthzGetQueryOptions(options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -4,10 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
useMutation,
|
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -20,8 +17,8 @@ import type {
|
|||||||
UseMutationOptions,
|
UseMutationOptions,
|
||||||
UseMutationResult,
|
UseMutationResult,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
HTTPValidationError,
|
HTTPValidationError,
|
||||||
@@ -32,407 +29,595 @@ import type {
|
|||||||
ResCategorySchema,
|
ResCategorySchema,
|
||||||
ResExtractFacts,
|
ResExtractFacts,
|
||||||
ResFact,
|
ResFact,
|
||||||
ResFactList
|
ResFactList,
|
||||||
} from '.././model';
|
} from ".././model";
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 이 사업장의 업종에 존재하는 fact 필드 정의. 관리 화면이 입력 폼을 그리는 데 쓴다.
|
* 이 사업장의 업종에 존재하는 fact 필드 정의. 관리 화면이 입력 폼을 그리는 데 쓴다.
|
||||||
* @summary 업종 fact 스키마
|
* @summary 업종 fact 스키마
|
||||||
*/
|
*/
|
||||||
export const getSchema = (
|
export const getSchema = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResCategorySchema>(
|
||||||
|
{ url: `/v1/place/${placeId}/fact/schema`, method: "GET", signal },
|
||||||
return customFetch<ResCategorySchema>(
|
options,
|
||||||
{url: `/v1/place/${placeId}/fact/schema`, method: 'GET', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getGetSchemaQueryKey = (placeId?: string) => {
|
||||||
|
return [`/v1/place/${placeId}/fact/schema`] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getGetSchemaQueryOptions = <
|
||||||
export const getGetSchemaQueryKey = (placeId?: string,) => {
|
TData = Awaited<ReturnType<typeof getSchema>>,
|
||||||
return [
|
TError = void | HTTPValidationError,
|
||||||
`/v1/place/${placeId}/fact/schema`
|
>(
|
||||||
] as const;
|
placeId: string,
|
||||||
}
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>
|
||||||
export const getGetSchemaQueryOptions = <TData = Awaited<ReturnType<typeof getSchema>>, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
) => {
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
const queryKey = queryOptions?.queryKey ?? getGetSchemaQueryKey(placeId);
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getGetSchemaQueryKey(placeId);
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof getSchema>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => getSchema(placeId, requestOptions, signal);
|
||||||
|
|
||||||
|
return {
|
||||||
|
queryKey,
|
||||||
|
queryFn,
|
||||||
|
enabled: !!placeId,
|
||||||
|
...queryOptions,
|
||||||
|
} as UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getSchema>>> = ({ signal }) => getSchema(placeId, requestOptions, signal);
|
export type GetSchemaQueryResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof getSchema>>
|
||||||
|
>;
|
||||||
|
export type GetSchemaQueryError = void | HTTPValidationError;
|
||||||
|
|
||||||
|
export function useGetSchema<
|
||||||
|
TData = Awaited<ReturnType<typeof getSchema>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
placeId: string,
|
||||||
}
|
options: {
|
||||||
|
query: Partial<
|
||||||
export type GetSchemaQueryResult = NonNullable<Awaited<ReturnType<typeof getSchema>>>
|
UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>
|
||||||
export type GetSchemaQueryError = void | HTTPValidationError
|
> &
|
||||||
|
Pick<
|
||||||
|
|
||||||
export function useGetSchema<TData = Awaited<ReturnType<typeof getSchema>>, TError = void | HTTPValidationError>(
|
|
||||||
placeId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof getSchema>>,
|
Awaited<ReturnType<typeof getSchema>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof getSchema>>
|
Awaited<ReturnType<typeof getSchema>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useGetSchema<TData = Awaited<ReturnType<typeof getSchema>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>> & Pick<
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useGetSchema<
|
||||||
|
TData = Awaited<ReturnType<typeof getSchema>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof getSchema>>,
|
Awaited<ReturnType<typeof getSchema>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof getSchema>>
|
Awaited<ReturnType<typeof getSchema>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useGetSchema<TData = Awaited<ReturnType<typeof getSchema>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
queryClient?: QueryClient,
|
||||||
, queryClient?: QueryClient
|
): UseQueryResult<TData, TError> & {
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useGetSchema<
|
||||||
|
TData = Awaited<ReturnType<typeof getSchema>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary 업종 fact 스키마
|
* @summary 업종 fact 스키마
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useGetSchema<TData = Awaited<ReturnType<typeof getSchema>>, TError = void | HTTPValidationError>(
|
export function useGetSchema<
|
||||||
placeId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof getSchema>>,
|
||||||
, queryClient?: QueryClient
|
TError = void | HTTPValidationError,
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
>(
|
||||||
|
placeId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getSchema>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getGetSchemaQueryOptions(placeId, options);
|
||||||
|
|
||||||
const queryOptions = getGetSchemaQueryOptions(placeId,options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만.
|
* publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만.
|
||||||
* @summary fact 목록
|
* @summary fact 목록
|
||||||
*/
|
*/
|
||||||
export const listFacts = (
|
export const listFacts = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
params?: ListFactsParams,
|
params?: ListFactsParams,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFactList>(
|
||||||
|
{ url: `/v1/place/${placeId}/fact/list`, method: "GET", params, signal },
|
||||||
return customFetch<ResFactList>(
|
options,
|
||||||
{url: `/v1/place/${placeId}/fact/list`, method: 'GET',
|
);
|
||||||
params, signal
|
};
|
||||||
},
|
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getListFactsQueryKey = (
|
||||||
|
placeId?: string,
|
||||||
export const getListFactsQueryKey = (placeId?: string,
|
params?: ListFactsParams,
|
||||||
params?: ListFactsParams,) => {
|
|
||||||
return [
|
|
||||||
`/v1/place/${placeId}/fact/list`, ...(params ? [params]: [])
|
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export const getListFactsQueryOptions = <TData = Awaited<ReturnType<typeof listFacts>>, TError = void | HTTPValidationError>(placeId: string,
|
|
||||||
params?: ListFactsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
|
||||||
) => {
|
) => {
|
||||||
|
return [
|
||||||
|
`/v1/place/${placeId}/fact/list`,
|
||||||
|
...(params ? [params] : []),
|
||||||
|
] as const;
|
||||||
|
};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
export const getListFactsQueryOptions = <
|
||||||
|
TData = Awaited<ReturnType<typeof listFacts>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFactsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getListFactsQueryKey(placeId,params);
|
const queryKey =
|
||||||
|
queryOptions?.queryKey ?? getListFactsQueryKey(placeId, params);
|
||||||
|
|
||||||
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof listFacts>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => listFacts(placeId, params, requestOptions, signal);
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listFacts>>> = ({ signal }) => listFacts(placeId,params, requestOptions, signal);
|
return {
|
||||||
|
queryKey,
|
||||||
|
queryFn,
|
||||||
|
enabled: !!placeId,
|
||||||
|
...queryOptions,
|
||||||
|
} as UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListFactsQueryResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof listFacts>>
|
||||||
|
>;
|
||||||
|
export type ListFactsQueryError = void | HTTPValidationError;
|
||||||
|
|
||||||
|
export function useListFacts<
|
||||||
|
TData = Awaited<ReturnType<typeof listFacts>>,
|
||||||
return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
TError = void | HTTPValidationError,
|
||||||
}
|
>(
|
||||||
|
placeId: string,
|
||||||
export type ListFactsQueryResult = NonNullable<Awaited<ReturnType<typeof listFacts>>>
|
params: undefined | ListFactsParams,
|
||||||
export type ListFactsQueryError = void | HTTPValidationError
|
options: {
|
||||||
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>
|
||||||
export function useListFacts<TData = Awaited<ReturnType<typeof listFacts>>, TError = void | HTTPValidationError>(
|
> &
|
||||||
placeId: string,
|
Pick<
|
||||||
params: undefined | ListFactsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listFacts>>,
|
Awaited<ReturnType<typeof listFacts>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listFacts>>
|
Awaited<ReturnType<typeof listFacts>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListFacts<TData = Awaited<ReturnType<typeof listFacts>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListFactsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>> & Pick<
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useListFacts<
|
||||||
|
TData = Awaited<ReturnType<typeof listFacts>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFactsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listFacts>>,
|
Awaited<ReturnType<typeof listFacts>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listFacts>>
|
Awaited<ReturnType<typeof listFacts>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListFacts<TData = Awaited<ReturnType<typeof listFacts>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListFactsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
): UseQueryResult<TData, TError> & {
|
||||||
, queryClient?: QueryClient
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
};
|
||||||
|
export function useListFacts<
|
||||||
|
TData = Awaited<ReturnType<typeof listFacts>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFactsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary fact 목록
|
* @summary fact 목록
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useListFacts<TData = Awaited<ReturnType<typeof listFacts>>, TError = void | HTTPValidationError>(
|
export function useListFacts<
|
||||||
placeId: string,
|
TData = Awaited<ReturnType<typeof listFacts>>,
|
||||||
params?: ListFactsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient
|
>(
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
placeId: string,
|
||||||
|
params?: ListFactsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFacts>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getListFactsQueryOptions(placeId, params, options);
|
||||||
|
|
||||||
const queryOptions = getListFactsQueryOptions(placeId,params,options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 같은 key 의 활성 fact 는 EXPIRED 로 밀리고 새 행이 들어간다(값 이력 보존). ★ 자동 수집(api/crawl/llm)은 사장님 수정본(CORRECTED)을 덮어쓸 수 없다.
|
* 같은 key 의 활성 fact 는 EXPIRED 로 밀리고 새 행이 들어간다(값 이력 보존). ★ 자동 수집(api/crawl/llm)은 사장님 수정본(CORRECTED)을 덮어쓸 수 없다.
|
||||||
* @summary fact 기록
|
* @summary fact 기록
|
||||||
*/
|
*/
|
||||||
export const upsertFact = (
|
export const upsertFact = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
reqUpsertFact: ReqUpsertFact,
|
reqUpsertFact: ReqUpsertFact,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFact>(
|
||||||
|
{
|
||||||
return customFetch<ResFact>(
|
url: `/v1/place/${placeId}/fact`,
|
||||||
{url: `/v1/place/${placeId}/fact`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqUpsertFact, signal
|
data: reqUpsertFact,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUpsertFactMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof upsertFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqUpsertFact },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof upsertFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqUpsertFact },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["upsertFact"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getUpsertFactMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof upsertFact>>, TError,{placeId: string;data: ReqUpsertFact}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof upsertFact>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof upsertFact>>, TError,{placeId: string;data: ReqUpsertFact}, TContext> => {
|
{ placeId: string; data: ReqUpsertFact }
|
||||||
|
> = (props) => {
|
||||||
|
const { placeId, data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['upsertFact'];
|
return upsertFact(placeId, data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpsertFactMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof upsertFact>>
|
||||||
|
>;
|
||||||
|
export type UpsertFactMutationBody = ReqUpsertFact;
|
||||||
|
export type UpsertFactMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof upsertFact>>, {placeId: string;data: ReqUpsertFact}> = (props) => {
|
/**
|
||||||
const {placeId,data} = props ?? {};
|
|
||||||
|
|
||||||
return upsertFact(placeId,data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type UpsertFactMutationResult = NonNullable<Awaited<ReturnType<typeof upsertFact>>>
|
|
||||||
export type UpsertFactMutationBody = ReqUpsertFact
|
|
||||||
export type UpsertFactMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary fact 기록
|
* @summary fact 기록
|
||||||
*/
|
*/
|
||||||
export const useUpsertFact = <TError = void | HTTPValidationError,
|
export const useUpsertFact = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof upsertFact>>, TError,{placeId: string;data: ReqUpsertFact}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof upsertFact>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{placeId: string;data: ReqUpsertFact},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof upsertFact>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ placeId: string; data: ReqUpsertFact },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof upsertFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqUpsertFact },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getUpsertFactMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getUpsertFactMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS). CORRECTED 로 갈 때는 value 가 필수다.
|
* 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS). CORRECTED 로 갈 때는 value 가 필수다.
|
||||||
* @summary 검증 상태 전이
|
* @summary 검증 상태 전이
|
||||||
*/
|
*/
|
||||||
export const transitionFact = (
|
export const transitionFact = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
factId: string,
|
factId: string,
|
||||||
reqTransitionFact: ReqTransitionFact,
|
reqTransitionFact: ReqTransitionFact,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFact>(
|
||||||
|
{
|
||||||
return customFetch<ResFact>(
|
url: `/v1/place/${placeId}/fact/${factId}/transition`,
|
||||||
{url: `/v1/place/${placeId}/fact/${factId}/transition`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqTransitionFact, signal
|
data: reqTransitionFact,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getTransitionFactMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof transitionFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; factId: string; data: ReqTransitionFact },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof transitionFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; factId: string; data: ReqTransitionFact },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["transitionFact"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getTransitionFactMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof transitionFact>>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof transitionFact>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof transitionFact>>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext> => {
|
{ placeId: string; factId: string; data: ReqTransitionFact }
|
||||||
|
> = (props) => {
|
||||||
|
const { placeId, factId, data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['transitionFact'];
|
return transitionFact(placeId, factId, data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TransitionFactMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof transitionFact>>
|
||||||
|
>;
|
||||||
|
export type TransitionFactMutationBody = ReqTransitionFact;
|
||||||
|
export type TransitionFactMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof transitionFact>>, {placeId: string;factId: string;data: ReqTransitionFact}> = (props) => {
|
/**
|
||||||
const {placeId,factId,data} = props ?? {};
|
|
||||||
|
|
||||||
return transitionFact(placeId,factId,data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type TransitionFactMutationResult = NonNullable<Awaited<ReturnType<typeof transitionFact>>>
|
|
||||||
export type TransitionFactMutationBody = ReqTransitionFact
|
|
||||||
export type TransitionFactMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 검증 상태 전이
|
* @summary 검증 상태 전이
|
||||||
*/
|
*/
|
||||||
export const useTransitionFact = <TError = void | HTTPValidationError,
|
export const useTransitionFact = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof transitionFact>>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof transitionFact>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{placeId: string;factId: string;data: ReqTransitionFact},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof transitionFact>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ placeId: string; factId: string; data: ReqTransitionFact },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof transitionFact>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; factId: string; data: ReqTransitionFact },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getTransitionFactMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getTransitionFactMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 사장님이 붙여넣은 소개글·안내문에서 업종 스키마 fact 를 뽑는다. ★ 뽑은 값의 **근거 문장이 원문에 실제로 있는지 대조**해 통과한 것만 저장한다. 저장된 값은 전부 후보(UNVERIFIED)라 사장님이 확인해야 사이트에 나간다. 버려진 항목은 사유와 함께 돌려준다.
|
* 사장님이 붙여넣은 소개글·안내문에서 업종 스키마 fact 를 뽑는다. ★ 뽑은 값의 **근거 문장이 원문에 실제로 있는지 대조**해 통과한 것만 저장한다. 저장된 값은 전부 후보(UNVERIFIED)라 사장님이 확인해야 사이트에 나간다. 버려진 항목은 사유와 함께 돌려준다.
|
||||||
* @summary 붙여넣은 텍스트에서 fact 추출
|
* @summary 붙여넣은 텍스트에서 fact 추출
|
||||||
*/
|
*/
|
||||||
export const extractFactsFromText = (
|
export const extractFactsFromText = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
reqExtractFacts: ReqExtractFacts,
|
reqExtractFacts: ReqExtractFacts,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResExtractFacts>(
|
||||||
|
{
|
||||||
return customFetch<ResExtractFacts>(
|
url: `/v1/place/${placeId}/fact/extract`,
|
||||||
{url: `/v1/place/${placeId}/fact/extract`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqExtractFacts, signal
|
data: reqExtractFacts,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getExtractFactsFromTextMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof extractFactsFromText>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqExtractFacts },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof extractFactsFromText>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqExtractFacts },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["extractFactsFromText"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getExtractFactsFromTextMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof extractFactsFromText>>, TError,{placeId: string;data: ReqExtractFacts}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof extractFactsFromText>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof extractFactsFromText>>, TError,{placeId: string;data: ReqExtractFacts}, TContext> => {
|
{ placeId: string; data: ReqExtractFacts }
|
||||||
|
> = (props) => {
|
||||||
|
const { placeId, data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['extractFactsFromText'];
|
return extractFactsFromText(placeId, data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ExtractFactsFromTextMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof extractFactsFromText>>
|
||||||
|
>;
|
||||||
|
export type ExtractFactsFromTextMutationBody = ReqExtractFacts;
|
||||||
|
export type ExtractFactsFromTextMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof extractFactsFromText>>, {placeId: string;data: ReqExtractFacts}> = (props) => {
|
/**
|
||||||
const {placeId,data} = props ?? {};
|
|
||||||
|
|
||||||
return extractFactsFromText(placeId,data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type ExtractFactsFromTextMutationResult = NonNullable<Awaited<ReturnType<typeof extractFactsFromText>>>
|
|
||||||
export type ExtractFactsFromTextMutationBody = ReqExtractFacts
|
|
||||||
export type ExtractFactsFromTextMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 붙여넣은 텍스트에서 fact 추출
|
* @summary 붙여넣은 텍스트에서 fact 추출
|
||||||
*/
|
*/
|
||||||
export const useExtractFactsFromText = <TError = void | HTTPValidationError,
|
export const useExtractFactsFromText = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof extractFactsFromText>>, TError,{placeId: string;data: ReqExtractFacts}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof extractFactsFromText>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{placeId: string;data: ReqExtractFacts},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof extractFactsFromText>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ placeId: string; data: ReqExtractFacts },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof extractFactsFromText>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqExtractFacts },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getExtractFactsFromTextMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getExtractFactsFromTextMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -4,10 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
useMutation,
|
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -20,8 +17,8 @@ import type {
|
|||||||
UseMutationOptions,
|
UseMutationOptions,
|
||||||
UseMutationResult,
|
UseMutationResult,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
HTTPValidationError,
|
HTTPValidationError,
|
||||||
@@ -29,248 +26,356 @@ import type {
|
|||||||
ReqCreateFaq,
|
ReqCreateFaq,
|
||||||
ReqTransitionFaq,
|
ReqTransitionFaq,
|
||||||
ResFaq,
|
ResFaq,
|
||||||
ResFaqList
|
ResFaqList,
|
||||||
} from '.././model';
|
} from ".././model";
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만. 기본은 승인 대기(UNVERIFIED)까지 함께 준다 — 승인할 대상을 봐야 하기 때문이다.
|
* publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만. 기본은 승인 대기(UNVERIFIED)까지 함께 준다 — 승인할 대상을 봐야 하기 때문이다.
|
||||||
* @summary FAQ 목록
|
* @summary FAQ 목록
|
||||||
*/
|
*/
|
||||||
export const listFaqs = (
|
export const listFaqs = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
params?: ListFaqsParams,
|
params?: ListFaqsParams,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFaqList>(
|
||||||
|
{ url: `/v1/place/${placeId}/faq/list`, method: "GET", params, signal },
|
||||||
return customFetch<ResFaqList>(
|
options,
|
||||||
{url: `/v1/place/${placeId}/faq/list`, method: 'GET',
|
);
|
||||||
params, signal
|
};
|
||||||
},
|
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getListFaqsQueryKey = (
|
||||||
|
placeId?: string,
|
||||||
export const getListFaqsQueryKey = (placeId?: string,
|
params?: ListFaqsParams,
|
||||||
params?: ListFaqsParams,) => {
|
|
||||||
return [
|
|
||||||
`/v1/place/${placeId}/faq/list`, ...(params ? [params]: [])
|
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export const getListFaqsQueryOptions = <TData = Awaited<ReturnType<typeof listFaqs>>, TError = void | HTTPValidationError>(placeId: string,
|
|
||||||
params?: ListFaqsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
|
||||||
) => {
|
) => {
|
||||||
|
return [
|
||||||
|
`/v1/place/${placeId}/faq/list`,
|
||||||
|
...(params ? [params] : []),
|
||||||
|
] as const;
|
||||||
|
};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
export const getListFaqsQueryOptions = <
|
||||||
|
TData = Awaited<ReturnType<typeof listFaqs>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFaqsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getListFaqsQueryKey(placeId,params);
|
const queryKey =
|
||||||
|
queryOptions?.queryKey ?? getListFaqsQueryKey(placeId, params);
|
||||||
|
|
||||||
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof listFaqs>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => listFaqs(placeId, params, requestOptions, signal);
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listFaqs>>> = ({ signal }) => listFaqs(placeId,params, requestOptions, signal);
|
return {
|
||||||
|
queryKey,
|
||||||
|
queryFn,
|
||||||
|
enabled: !!placeId,
|
||||||
|
...queryOptions,
|
||||||
|
} as UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListFaqsQueryResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof listFaqs>>
|
||||||
|
>;
|
||||||
|
export type ListFaqsQueryError = void | HTTPValidationError;
|
||||||
|
|
||||||
|
export function useListFaqs<
|
||||||
|
TData = Awaited<ReturnType<typeof listFaqs>>,
|
||||||
return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
TError = void | HTTPValidationError,
|
||||||
}
|
>(
|
||||||
|
placeId: string,
|
||||||
export type ListFaqsQueryResult = NonNullable<Awaited<ReturnType<typeof listFaqs>>>
|
params: undefined | ListFaqsParams,
|
||||||
export type ListFaqsQueryError = void | HTTPValidationError
|
options: {
|
||||||
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>
|
||||||
export function useListFaqs<TData = Awaited<ReturnType<typeof listFaqs>>, TError = void | HTTPValidationError>(
|
> &
|
||||||
placeId: string,
|
Pick<
|
||||||
params: undefined | ListFaqsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listFaqs>>,
|
Awaited<ReturnType<typeof listFaqs>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listFaqs>>
|
Awaited<ReturnType<typeof listFaqs>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListFaqs<TData = Awaited<ReturnType<typeof listFaqs>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListFaqsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>> & Pick<
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useListFaqs<
|
||||||
|
TData = Awaited<ReturnType<typeof listFaqs>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFaqsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listFaqs>>,
|
Awaited<ReturnType<typeof listFaqs>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listFaqs>>
|
Awaited<ReturnType<typeof listFaqs>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListFaqs<TData = Awaited<ReturnType<typeof listFaqs>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListFaqsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
): UseQueryResult<TData, TError> & {
|
||||||
, queryClient?: QueryClient
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
};
|
||||||
|
export function useListFaqs<
|
||||||
|
TData = Awaited<ReturnType<typeof listFaqs>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListFaqsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary FAQ 목록
|
* @summary FAQ 목록
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useListFaqs<TData = Awaited<ReturnType<typeof listFaqs>>, TError = void | HTTPValidationError>(
|
export function useListFaqs<
|
||||||
placeId: string,
|
TData = Awaited<ReturnType<typeof listFaqs>>,
|
||||||
params?: ListFaqsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient
|
>(
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
placeId: string,
|
||||||
|
params?: ListFaqsParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listFaqs>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getListFaqsQueryOptions(placeId, params, options);
|
||||||
|
|
||||||
const queryOptions = getListFaqsQueryOptions(placeId,params,options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 사장님이 직접 쓴 FAQ. fact 의 owner 입력과 같이 바로 노출값(VERIFIED)이 된다 — 사람이 곧 출처다. 출처(generated_by)는 서버가 OWNER 로 고정한다.
|
* 사장님이 직접 쓴 FAQ. fact 의 owner 입력과 같이 바로 노출값(VERIFIED)이 된다 — 사람이 곧 출처다. 출처(generated_by)는 서버가 OWNER 로 고정한다.
|
||||||
* @summary FAQ 직접 추가
|
* @summary FAQ 직접 추가
|
||||||
*/
|
*/
|
||||||
export const createFaq = (
|
export const createFaq = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
reqCreateFaq: ReqCreateFaq,
|
reqCreateFaq: ReqCreateFaq,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFaq>(
|
||||||
|
{
|
||||||
return customFetch<ResFaq>(
|
url: `/v1/place/${placeId}/faq`,
|
||||||
{url: `/v1/place/${placeId}/faq`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqCreateFaq, signal
|
data: reqCreateFaq,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCreateFaqMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof createFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqCreateFaq },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof createFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqCreateFaq },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["createFaq"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getCreateFaqMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createFaq>>, TError,{placeId: string;data: ReqCreateFaq}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof createFaq>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof createFaq>>, TError,{placeId: string;data: ReqCreateFaq}, TContext> => {
|
{ placeId: string; data: ReqCreateFaq }
|
||||||
|
> = (props) => {
|
||||||
|
const { placeId, data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['createFaq'];
|
return createFaq(placeId, data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateFaqMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof createFaq>>
|
||||||
|
>;
|
||||||
|
export type CreateFaqMutationBody = ReqCreateFaq;
|
||||||
|
export type CreateFaqMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof createFaq>>, {placeId: string;data: ReqCreateFaq}> = (props) => {
|
/**
|
||||||
const {placeId,data} = props ?? {};
|
|
||||||
|
|
||||||
return createFaq(placeId,data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type CreateFaqMutationResult = NonNullable<Awaited<ReturnType<typeof createFaq>>>
|
|
||||||
export type CreateFaqMutationBody = ReqCreateFaq
|
|
||||||
export type CreateFaqMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary FAQ 직접 추가
|
* @summary FAQ 직접 추가
|
||||||
*/
|
*/
|
||||||
export const useCreateFaq = <TError = void | HTTPValidationError,
|
export const useCreateFaq = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createFaq>>, TError,{placeId: string;data: ReqCreateFaq}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof createFaq>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{placeId: string;data: ReqCreateFaq},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof createFaq>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ placeId: string; data: ReqCreateFaq },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof createFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; data: ReqCreateFaq },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getCreateFaqMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getCreateFaqMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
/**
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS — fact 와 같은 표). CORRECTED 로 갈 때는 고친 question/answer 중 하나 이상이 필요하고, 그 뒤로는 ★ 잠긴 상태라 재생성이 덮어쓰지 못한다.
|
* 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS — fact 와 같은 표). CORRECTED 로 갈 때는 고친 question/answer 중 하나 이상이 필요하고, 그 뒤로는 ★ 잠긴 상태라 재생성이 덮어쓰지 못한다.
|
||||||
* @summary 검증 상태 전이(승인·정정·반려)
|
* @summary 검증 상태 전이(승인·정정·반려)
|
||||||
*/
|
*/
|
||||||
export const transitionFaq = (
|
export const transitionFaq = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
faqId: string,
|
faqId: string,
|
||||||
reqTransitionFaq: ReqTransitionFaq,
|
reqTransitionFaq: ReqTransitionFaq,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResFaq>(
|
||||||
|
{
|
||||||
return customFetch<ResFaq>(
|
url: `/v1/place/${placeId}/faq/${faqId}/transition`,
|
||||||
{url: `/v1/place/${placeId}/faq/${faqId}/transition`, method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/json', },
|
headers: { "Content-Type": "application/json" },
|
||||||
data: reqTransitionFaq, signal
|
data: reqTransitionFaq,
|
||||||
|
signal,
|
||||||
},
|
},
|
||||||
options);
|
options,
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getTransitionFaqMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof transitionFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; faqId: string; data: ReqTransitionFaq },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof transitionFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; faqId: string; data: ReqTransitionFaq },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["transitionFaq"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getTransitionFaqMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof transitionFaq>>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof transitionFaq>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof transitionFaq>>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext> => {
|
{ placeId: string; faqId: string; data: ReqTransitionFaq }
|
||||||
|
> = (props) => {
|
||||||
|
const { placeId, faqId, data } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['transitionFaq'];
|
return transitionFaq(placeId, faqId, data, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TransitionFaqMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof transitionFaq>>
|
||||||
|
>;
|
||||||
|
export type TransitionFaqMutationBody = ReqTransitionFaq;
|
||||||
|
export type TransitionFaqMutationError = void | HTTPValidationError;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof transitionFaq>>, {placeId: string;faqId: string;data: ReqTransitionFaq}> = (props) => {
|
/**
|
||||||
const {placeId,faqId,data} = props ?? {};
|
|
||||||
|
|
||||||
return transitionFaq(placeId,faqId,data,requestOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type TransitionFaqMutationResult = NonNullable<Awaited<ReturnType<typeof transitionFaq>>>
|
|
||||||
export type TransitionFaqMutationBody = ReqTransitionFaq
|
|
||||||
export type TransitionFaqMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary 검증 상태 전이(승인·정정·반려)
|
* @summary 검증 상태 전이(승인·정정·반려)
|
||||||
*/
|
*/
|
||||||
export const useTransitionFaq = <TError = void | HTTPValidationError,
|
export const useTransitionFaq = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof transitionFaq>>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof transitionFaq>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{placeId: string;faqId: string;data: ReqTransitionFaq},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof transitionFaq>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ placeId: string; faqId: string; data: ReqTransitionFaq },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof transitionFaq>>,
|
||||||
|
TError,
|
||||||
|
{ placeId: string; faqId: string; data: ReqTransitionFaq },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getTransitionFaqMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getTransitionFaqMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
/**
|
||||||
|
* Generated by orval v7.21.0 🍺
|
||||||
|
* Do not edit manually.
|
||||||
|
* Web4Ai API
|
||||||
|
* OpenAPI spec version: 0.1.0
|
||||||
|
*/
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type {
|
||||||
|
DataTag,
|
||||||
|
DefinedInitialDataOptions,
|
||||||
|
DefinedUseQueryResult,
|
||||||
|
QueryClient,
|
||||||
|
QueryFunction,
|
||||||
|
QueryKey,
|
||||||
|
UndefinedInitialDataOptions,
|
||||||
|
UseQueryOptions,
|
||||||
|
UseQueryResult,
|
||||||
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
|
import type { HTTPValidationError, RelayParams } from ".././model";
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 인증을 요구하지 않는다. 발행본은 로그인 없이 열리는 정적 페이지이고, 여기서 나가는
|
||||||
|
것은 **그 페이지가 이미 화면에 싣고 있는 사진**뿐이다(allowlist 가 그걸 보장한다).
|
||||||
|
* @summary 사진 중계 — 캔버스 오염을 피하려고 같은 오리진으로 흘려보낸다
|
||||||
|
*/
|
||||||
|
export const relay = (
|
||||||
|
params: RelayParams,
|
||||||
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) => {
|
||||||
|
return customFetch<unknown>(
|
||||||
|
{ url: `/v1/image/relay`, method: "GET", params, signal },
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRelayQueryKey = (params?: RelayParams) => {
|
||||||
|
return [`/v1/image/relay`, ...(params ? [params] : [])] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getRelayQueryOptions = <
|
||||||
|
TData = Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError = HTTPValidationError,
|
||||||
|
>(
|
||||||
|
params: RelayParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof relay>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
|
const queryKey = queryOptions?.queryKey ?? getRelayQueryKey(params);
|
||||||
|
|
||||||
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof relay>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => relay(params, requestOptions, signal);
|
||||||
|
|
||||||
|
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RelayQueryResult = NonNullable<Awaited<ReturnType<typeof relay>>>;
|
||||||
|
export type RelayQueryError = HTTPValidationError;
|
||||||
|
|
||||||
|
export function useRelay<
|
||||||
|
TData = Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError = HTTPValidationError,
|
||||||
|
>(
|
||||||
|
params: RelayParams,
|
||||||
|
options: {
|
||||||
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof relay>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
|
DefinedInitialDataOptions<
|
||||||
|
Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError,
|
||||||
|
Awaited<ReturnType<typeof relay>>
|
||||||
|
>,
|
||||||
|
"initialData"
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useRelay<
|
||||||
|
TData = Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError = HTTPValidationError,
|
||||||
|
>(
|
||||||
|
params: RelayParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof relay>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
|
UndefinedInitialDataOptions<
|
||||||
|
Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError,
|
||||||
|
Awaited<ReturnType<typeof relay>>
|
||||||
|
>,
|
||||||
|
"initialData"
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useRelay<
|
||||||
|
TData = Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError = HTTPValidationError,
|
||||||
|
>(
|
||||||
|
params: RelayParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof relay>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* @summary 사진 중계 — 캔버스 오염을 피하려고 같은 오리진으로 흘려보낸다
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function useRelay<
|
||||||
|
TData = Awaited<ReturnType<typeof relay>>,
|
||||||
|
TError = HTTPValidationError,
|
||||||
|
>(
|
||||||
|
params: RelayParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof relay>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getRelayQueryOptions(params, options);
|
||||||
|
|
||||||
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
|
return query;
|
||||||
|
}
|
||||||
@@ -4,10 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
useMutation,
|
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -20,268 +17,374 @@ import type {
|
|||||||
UseMutationOptions,
|
UseMutationOptions,
|
||||||
UseMutationResult,
|
UseMutationResult,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import type {
|
import type { HTTPValidationError, ResJob, ResJobOps } from ".././model";
|
||||||
HTTPValidationError,
|
|
||||||
ResJob,
|
|
||||||
ResJobOps
|
|
||||||
} from '.././model';
|
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 상태별 카운트 + 큐 지연 + 최근 1시간 DEAD + 좀비(stuck). 내부 운영 전용.
|
* 상태별 카운트 + 큐 지연 + 최근 1시간 DEAD + 좀비(stuck). 내부 운영 전용.
|
||||||
* @summary 큐 운영 스냅샷
|
* @summary 큐 운영 스냅샷
|
||||||
*/
|
*/
|
||||||
export const jobOps = (
|
export const jobOps = (
|
||||||
|
options?: SecondParameter<typeof customFetch>,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResJobOps>(
|
||||||
|
{ url: `/v1/job/ops`, method: "GET", signal },
|
||||||
return customFetch<ResJobOps>(
|
options,
|
||||||
{url: `/v1/job/ops`, method: 'GET', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const getJobOpsQueryKey = () => {
|
export const getJobOpsQueryKey = () => {
|
||||||
return [
|
return [`/v1/job/ops`] as const;
|
||||||
`/v1/job/ops`
|
};
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
export const getJobOpsQueryOptions = <
|
||||||
export const getJobOpsQueryOptions = <TData = Awaited<ReturnType<typeof jobOps>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof jobOps>>,
|
||||||
) => {
|
TError = void,
|
||||||
|
>(options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
const queryKey = queryOptions?.queryKey ?? getJobOpsQueryKey();
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getJobOpsQueryKey();
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof jobOps>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => jobOps(requestOptions, signal);
|
||||||
|
|
||||||
|
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||||
|
Awaited<ReturnType<typeof jobOps>>,
|
||||||
|
TError,
|
||||||
|
TData
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
};
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof jobOps>>> = ({ signal }) => jobOps(requestOptions, signal);
|
export type JobOpsQueryResult = NonNullable<Awaited<ReturnType<typeof jobOps>>>;
|
||||||
|
export type JobOpsQueryError = void;
|
||||||
|
|
||||||
|
export function useJobOps<
|
||||||
|
TData = Awaited<ReturnType<typeof jobOps>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
options: {
|
||||||
}
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>
|
||||||
export type JobOpsQueryResult = NonNullable<Awaited<ReturnType<typeof jobOps>>>
|
> &
|
||||||
export type JobOpsQueryError = void
|
Pick<
|
||||||
|
|
||||||
|
|
||||||
export function useJobOps<TData = Awaited<ReturnType<typeof jobOps>>, TError = void>(
|
|
||||||
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof jobOps>>,
|
Awaited<ReturnType<typeof jobOps>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof jobOps>>
|
Awaited<ReturnType<typeof jobOps>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useJobOps<TData = Awaited<ReturnType<typeof jobOps>>, TError = void>(
|
},
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>> & Pick<
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useJobOps<
|
||||||
|
TData = Awaited<ReturnType<typeof jobOps>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof jobOps>>,
|
Awaited<ReturnType<typeof jobOps>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof jobOps>>
|
Awaited<ReturnType<typeof jobOps>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useJobOps<TData = Awaited<ReturnType<typeof jobOps>>, TError = void>(
|
},
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
queryClient?: QueryClient,
|
||||||
, queryClient?: QueryClient
|
): UseQueryResult<TData, TError> & {
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useJobOps<
|
||||||
|
TData = Awaited<ReturnType<typeof jobOps>>,
|
||||||
|
TError = void,
|
||||||
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary 큐 운영 스냅샷
|
* @summary 큐 운영 스냅샷
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useJobOps<TData = Awaited<ReturnType<typeof jobOps>>, TError = void>(
|
export function useJobOps<
|
||||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof jobOps>>,
|
||||||
, queryClient?: QueryClient
|
TError = void,
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
>(
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof jobOps>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getJobOpsQueryOptions(options);
|
||||||
|
|
||||||
const queryOptions = getJobOpsQueryOptions(options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @summary 잡 상태 조회(폴링)
|
* @summary 잡 상태 조회(폴링)
|
||||||
*/
|
*/
|
||||||
export const getJob = (
|
export const getJob = (
|
||||||
jobId: string,
|
jobId: string,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResJob>(
|
||||||
|
{ url: `/v1/job/${jobId}`, method: "GET", signal },
|
||||||
return customFetch<ResJob>(
|
options,
|
||||||
{url: `/v1/job/${jobId}`, method: 'GET', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getGetJobQueryKey = (jobId?: string) => {
|
||||||
|
return [`/v1/job/${jobId}`] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getGetJobQueryOptions = <
|
||||||
export const getGetJobQueryKey = (jobId?: string,) => {
|
TData = Awaited<ReturnType<typeof getJob>>,
|
||||||
return [
|
TError = void | HTTPValidationError,
|
||||||
`/v1/job/${jobId}`
|
>(
|
||||||
] as const;
|
jobId: string,
|
||||||
}
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>
|
||||||
export const getGetJobQueryOptions = <TData = Awaited<ReturnType<typeof getJob>>, TError = void | HTTPValidationError>(jobId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
) => {
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
const queryKey = queryOptions?.queryKey ?? getGetJobQueryKey(jobId);
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getGetJobQueryKey(jobId);
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof getJob>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => getJob(jobId, requestOptions, signal);
|
||||||
|
|
||||||
|
return {
|
||||||
|
queryKey,
|
||||||
|
queryFn,
|
||||||
|
enabled: !!jobId,
|
||||||
|
...queryOptions,
|
||||||
|
} as UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getJob>>> = ({ signal }) => getJob(jobId, requestOptions, signal);
|
export type GetJobQueryResult = NonNullable<Awaited<ReturnType<typeof getJob>>>;
|
||||||
|
export type GetJobQueryError = void | HTTPValidationError;
|
||||||
|
|
||||||
|
export function useGetJob<
|
||||||
|
TData = Awaited<ReturnType<typeof getJob>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
return { queryKey, queryFn, enabled: !!(jobId), ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
jobId: string,
|
||||||
}
|
options: {
|
||||||
|
query: Partial<
|
||||||
export type GetJobQueryResult = NonNullable<Awaited<ReturnType<typeof getJob>>>
|
UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>
|
||||||
export type GetJobQueryError = void | HTTPValidationError
|
> &
|
||||||
|
Pick<
|
||||||
|
|
||||||
export function useGetJob<TData = Awaited<ReturnType<typeof getJob>>, TError = void | HTTPValidationError>(
|
|
||||||
jobId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof getJob>>,
|
Awaited<ReturnType<typeof getJob>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof getJob>>
|
Awaited<ReturnType<typeof getJob>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useGetJob<TData = Awaited<ReturnType<typeof getJob>>, TError = void | HTTPValidationError>(
|
},
|
||||||
jobId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>> & Pick<
|
queryClient?: QueryClient,
|
||||||
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useGetJob<
|
||||||
|
TData = Awaited<ReturnType<typeof getJob>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
jobId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof getJob>>,
|
Awaited<ReturnType<typeof getJob>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof getJob>>
|
Awaited<ReturnType<typeof getJob>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useGetJob<TData = Awaited<ReturnType<typeof getJob>>, TError = void | HTTPValidationError>(
|
},
|
||||||
jobId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
queryClient?: QueryClient,
|
||||||
, queryClient?: QueryClient
|
): UseQueryResult<TData, TError> & {
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useGetJob<
|
||||||
|
TData = Awaited<ReturnType<typeof getJob>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
jobId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary 잡 상태 조회(폴링)
|
* @summary 잡 상태 조회(폴링)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useGetJob<TData = Awaited<ReturnType<typeof getJob>>, TError = void | HTTPValidationError>(
|
export function useGetJob<
|
||||||
jobId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TData = Awaited<ReturnType<typeof getJob>>,
|
||||||
, queryClient?: QueryClient
|
TError = void | HTTPValidationError,
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
>(
|
||||||
|
jobId: string,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof getJob>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getGetJobQueryOptions(jobId, options);
|
||||||
|
|
||||||
const queryOptions = getGetJobQueryOptions(jobId,options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* max_attempts 를 소진해 dead-letter 로 간 잡을 다시 대기로 돌린다. 내부 운영 전용.
|
* max_attempts 를 소진해 dead-letter 로 간 잡을 다시 대기로 돌린다. 내부 운영 전용.
|
||||||
* @summary DEAD 잡 재큐
|
* @summary DEAD 잡 재큐
|
||||||
*/
|
*/
|
||||||
export const requeueJob = (
|
export const requeueJob = (
|
||||||
jobId: string,
|
jobId: string,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResJob>(
|
||||||
|
{ url: `/v1/job/${jobId}/requeue`, method: "POST", signal },
|
||||||
return customFetch<ResJob>(
|
options,
|
||||||
{url: `/v1/job/${jobId}/requeue`, method: 'POST', signal
|
);
|
||||||
},
|
};
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getRequeueJobMutationOptions = <
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
TContext = unknown,
|
||||||
|
>(options?: {
|
||||||
|
mutation?: UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof requeueJob>>,
|
||||||
|
TError,
|
||||||
|
{ jobId: string },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
}): UseMutationOptions<
|
||||||
|
Awaited<ReturnType<typeof requeueJob>>,
|
||||||
|
TError,
|
||||||
|
{ jobId: string },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationKey = ["requeueJob"];
|
||||||
|
const { mutation: mutationOptions, request: requestOptions } = options
|
||||||
|
? options.mutation &&
|
||||||
|
"mutationKey" in options.mutation &&
|
||||||
|
options.mutation.mutationKey
|
||||||
|
? options
|
||||||
|
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||||
|
: { mutation: { mutationKey }, request: undefined };
|
||||||
|
|
||||||
export const getRequeueJobMutationOptions = <TError = void | HTTPValidationError,
|
const mutationFn: MutationFunction<
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof requeueJob>>, TError,{jobId: string}, TContext>, request?: SecondParameter<typeof customFetch>}
|
Awaited<ReturnType<typeof requeueJob>>,
|
||||||
): UseMutationOptions<Awaited<ReturnType<typeof requeueJob>>, TError,{jobId: string}, TContext> => {
|
{ jobId: string }
|
||||||
|
> = (props) => {
|
||||||
|
const { jobId } = props ?? {};
|
||||||
|
|
||||||
const mutationKey = ['requeueJob'];
|
return requeueJob(jobId, requestOptions);
|
||||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
};
|
||||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
|
||||||
options
|
|
||||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
|
||||||
: {mutation: { mutationKey, }, request: undefined};
|
|
||||||
|
|
||||||
|
return { mutationFn, ...mutationOptions };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RequeueJobMutationResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof requeueJob>>
|
||||||
|
>;
|
||||||
|
|
||||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof requeueJob>>, {jobId: string}> = (props) => {
|
export type RequeueJobMutationError = void | HTTPValidationError;
|
||||||
const {jobId} = props ?? {};
|
|
||||||
|
|
||||||
return requeueJob(jobId,requestOptions)
|
/**
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return { mutationFn, ...mutationOptions }}
|
|
||||||
|
|
||||||
export type RequeueJobMutationResult = NonNullable<Awaited<ReturnType<typeof requeueJob>>>
|
|
||||||
|
|
||||||
export type RequeueJobMutationError = void | HTTPValidationError
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @summary DEAD 잡 재큐
|
* @summary DEAD 잡 재큐
|
||||||
*/
|
*/
|
||||||
export const useRequeueJob = <TError = void | HTTPValidationError,
|
export const useRequeueJob = <
|
||||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof requeueJob>>, TError,{jobId: string}, TContext>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient): UseMutationResult<
|
TContext = unknown,
|
||||||
Awaited<ReturnType<typeof requeueJob>>,
|
>(
|
||||||
TError,
|
options?: {
|
||||||
{jobId: string},
|
mutation?: UseMutationOptions<
|
||||||
TContext
|
Awaited<ReturnType<typeof requeueJob>>,
|
||||||
> => {
|
TError,
|
||||||
|
{ jobId: string },
|
||||||
|
TContext
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseMutationResult<
|
||||||
|
Awaited<ReturnType<typeof requeueJob>>,
|
||||||
|
TError,
|
||||||
|
{ jobId: string },
|
||||||
|
TContext
|
||||||
|
> => {
|
||||||
|
const mutationOptions = getRequeueJobMutationOptions(options);
|
||||||
|
|
||||||
const mutationOptions = getRequeueJobMutationOptions(options);
|
return useMutation(mutationOptions, queryClient);
|
||||||
|
};
|
||||||
return useMutation(mutationOptions, queryClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -4,9 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import {
|
import { useQuery } from "@tanstack/react-query";
|
||||||
useQuery
|
|
||||||
} from '@tanstack/react-query';
|
|
||||||
import type {
|
import type {
|
||||||
DataTag,
|
DataTag,
|
||||||
DefinedInitialDataOptions,
|
DefinedInitialDataOptions,
|
||||||
@@ -16,120 +14,174 @@ import type {
|
|||||||
QueryKey,
|
QueryKey,
|
||||||
UndefinedInitialDataOptions,
|
UndefinedInitialDataOptions,
|
||||||
UseQueryOptions,
|
UseQueryOptions,
|
||||||
UseQueryResult
|
UseQueryResult,
|
||||||
} from '@tanstack/react-query';
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
HTTPValidationError,
|
HTTPValidationError,
|
||||||
ListMediaParams,
|
ListMediaParams,
|
||||||
ResMediaList
|
ResMediaList,
|
||||||
} from '.././model';
|
} from ".././model";
|
||||||
|
|
||||||
import { customFetch } from '../../mutator/custom-fetch';
|
|
||||||
|
|
||||||
|
import { customFetch } from "../../mutator/custom-fetch";
|
||||||
|
|
||||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* publishable_only=true 면 ★ 사이트에 실제로 나갈 수 있는 것(승인 + alt 있음)만 — 빌드 스냅샷과 같은 기준이다. unit_id 를 주면 그 객실·메뉴 사진만. ★ 응답에는 항상 source_type(owner/crawl)과 origin_url 이 실린다 — 크롤링 이미지 재게시 권리가 미결이라(docs/DECISIONS.md 1-2) 결론에 따라 CRAWL 을 통째로 걸러내야 하고, 화면이 출처를 모르면 그 판단을 못 한다.
|
* publishable_only=true 면 ★ 사이트에 실제로 나갈 수 있는 것(승인 + alt 있음)만 — 빌드 스냅샷과 같은 기준이다. unit_id 를 주면 그 객실·메뉴 사진만. ★ 응답에는 항상 source_type(owner/crawl)과 origin_url 이 실린다 — 크롤링 이미지 재게시 권리가 미결이라(docs/DECISIONS.md 1-2) 결론에 따라 CRAWL 을 통째로 걸러내야 하고, 화면이 출처를 모르면 그 판단을 못 한다.
|
||||||
* @summary 사진 목록
|
* @summary 사진 목록
|
||||||
*/
|
*/
|
||||||
export const listMedia = (
|
export const listMedia = (
|
||||||
placeId: string,
|
placeId: string,
|
||||||
params?: ListMediaParams,
|
params?: ListMediaParams,
|
||||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
options?: SecondParameter<typeof customFetch>,
|
||||||
|
signal?: AbortSignal,
|
||||||
) => {
|
) => {
|
||||||
|
return customFetch<ResMediaList>(
|
||||||
|
{ url: `/v1/place/${placeId}/media/list`, method: "GET", params, signal },
|
||||||
return customFetch<ResMediaList>(
|
options,
|
||||||
{url: `/v1/place/${placeId}/media/list`, method: 'GET',
|
);
|
||||||
params, signal
|
};
|
||||||
},
|
|
||||||
options);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
export const getListMediaQueryKey = (
|
||||||
|
placeId?: string,
|
||||||
export const getListMediaQueryKey = (placeId?: string,
|
params?: ListMediaParams,
|
||||||
params?: ListMediaParams,) => {
|
|
||||||
return [
|
|
||||||
`/v1/place/${placeId}/media/list`, ...(params ? [params]: [])
|
|
||||||
] as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export const getListMediaQueryOptions = <TData = Awaited<ReturnType<typeof listMedia>>, TError = void | HTTPValidationError>(placeId: string,
|
|
||||||
params?: ListMediaParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
|
||||||
) => {
|
) => {
|
||||||
|
return [
|
||||||
|
`/v1/place/${placeId}/media/list`,
|
||||||
|
...(params ? [params] : []),
|
||||||
|
] as const;
|
||||||
|
};
|
||||||
|
|
||||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
export const getListMediaQueryOptions = <
|
||||||
|
TData = Awaited<ReturnType<typeof listMedia>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListMediaParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||||
|
|
||||||
const queryKey = queryOptions?.queryKey ?? getListMediaQueryKey(placeId,params);
|
const queryKey =
|
||||||
|
queryOptions?.queryKey ?? getListMediaQueryKey(placeId, params);
|
||||||
|
|
||||||
|
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMedia>>> = ({
|
||||||
|
signal,
|
||||||
|
}) => listMedia(placeId, params, requestOptions, signal);
|
||||||
|
|
||||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMedia>>> = ({ signal }) => listMedia(placeId,params, requestOptions, signal);
|
return {
|
||||||
|
queryKey,
|
||||||
|
queryFn,
|
||||||
|
enabled: !!placeId,
|
||||||
|
...queryOptions,
|
||||||
|
} as UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListMediaQueryResult = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof listMedia>>
|
||||||
|
>;
|
||||||
|
export type ListMediaQueryError = void | HTTPValidationError;
|
||||||
|
|
||||||
|
export function useListMedia<
|
||||||
|
TData = Awaited<ReturnType<typeof listMedia>>,
|
||||||
return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
TError = void | HTTPValidationError,
|
||||||
}
|
>(
|
||||||
|
placeId: string,
|
||||||
export type ListMediaQueryResult = NonNullable<Awaited<ReturnType<typeof listMedia>>>
|
params: undefined | ListMediaParams,
|
||||||
export type ListMediaQueryError = void | HTTPValidationError
|
options: {
|
||||||
|
query: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>
|
||||||
export function useListMedia<TData = Awaited<ReturnType<typeof listMedia>>, TError = void | HTTPValidationError>(
|
> &
|
||||||
placeId: string,
|
Pick<
|
||||||
params: undefined | ListMediaParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>> & Pick<
|
|
||||||
DefinedInitialDataOptions<
|
DefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listMedia>>,
|
Awaited<ReturnType<typeof listMedia>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listMedia>>
|
Awaited<ReturnType<typeof listMedia>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListMedia<TData = Awaited<ReturnType<typeof listMedia>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListMediaParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>> & Pick<
|
): DefinedUseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
|
export function useListMedia<
|
||||||
|
TData = Awaited<ReturnType<typeof listMedia>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListMediaParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>
|
||||||
|
> &
|
||||||
|
Pick<
|
||||||
UndefinedInitialDataOptions<
|
UndefinedInitialDataOptions<
|
||||||
Awaited<ReturnType<typeof listMedia>>,
|
Awaited<ReturnType<typeof listMedia>>,
|
||||||
TError,
|
TError,
|
||||||
Awaited<ReturnType<typeof listMedia>>
|
Awaited<ReturnType<typeof listMedia>>
|
||||||
> , 'initialData'
|
>,
|
||||||
>, request?: SecondParameter<typeof customFetch>}
|
"initialData"
|
||||||
, queryClient?: QueryClient
|
>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
request?: SecondParameter<typeof customFetch>;
|
||||||
export function useListMedia<TData = Awaited<ReturnType<typeof listMedia>>, TError = void | HTTPValidationError>(
|
},
|
||||||
placeId: string,
|
queryClient?: QueryClient,
|
||||||
params?: ListMediaParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
): UseQueryResult<TData, TError> & {
|
||||||
, queryClient?: QueryClient
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
};
|
||||||
|
export function useListMedia<
|
||||||
|
TData = Awaited<ReturnType<typeof listMedia>>,
|
||||||
|
TError = void | HTTPValidationError,
|
||||||
|
>(
|
||||||
|
placeId: string,
|
||||||
|
params?: ListMediaParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* @summary 사진 목록
|
* @summary 사진 목록
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export function useListMedia<TData = Awaited<ReturnType<typeof listMedia>>, TError = void | HTTPValidationError>(
|
export function useListMedia<
|
||||||
placeId: string,
|
TData = Awaited<ReturnType<typeof listMedia>>,
|
||||||
params?: ListMediaParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
|
TError = void | HTTPValidationError,
|
||||||
, queryClient?: QueryClient
|
>(
|
||||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
placeId: string,
|
||||||
|
params?: ListMediaParams,
|
||||||
|
options?: {
|
||||||
|
query?: Partial<
|
||||||
|
UseQueryOptions<Awaited<ReturnType<typeof listMedia>>, TError, TData>
|
||||||
|
>;
|
||||||
|
request?: SecondParameter<typeof customFetch>;
|
||||||
|
},
|
||||||
|
queryClient?: QueryClient,
|
||||||
|
): UseQueryResult<TData, TError> & {
|
||||||
|
queryKey: DataTag<QueryKey, TData, TError>;
|
||||||
|
} {
|
||||||
|
const queryOptions = getListMediaQueryOptions(placeId, params, options);
|
||||||
|
|
||||||
const queryOptions = getListMediaQueryOptions(placeId,params,options)
|
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||||
|
TData,
|
||||||
|
TError
|
||||||
|
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||||
|
|
||||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
query.queryKey = queryOptions.queryKey;
|
||||||
|
|
||||||
query.queryKey = queryOptions.queryKey ;
|
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { AuditCheckDataRecommendation } from './auditCheckDataRecommendation';
|
import type { AuditCheckDataRecommendation } from "./auditCheckDataRecommendation";
|
||||||
|
|
||||||
export interface AuditCheckData {
|
export interface AuditCheckData {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -12,8 +12,7 @@
|
|||||||
이으려면 "먼저 가입한 쪽의 소유"를 증명받아야 하는데, 그 증명 없이 이메일만 보고 이으면
|
이으려면 "먼저 가입한 쪽의 소유"를 증명받아야 하는데, 그 증명 없이 이메일만 보고 이으면
|
||||||
남이 먼저 만들어 둔 계정에 내 구글 로그인이 들어간다(계정 선점). 보류 사유는 DECISIONS.md 1절.
|
남이 먼저 만들어 둔 계정에 내 구글 로그인이 들어간다(계정 선점). 보류 사유는 DECISIONS.md 1절.
|
||||||
*/
|
*/
|
||||||
export type AuthProvider = typeof AuthProvider[keyof typeof AuthProvider];
|
export type AuthProvider = (typeof AuthProvider)[keyof typeof AuthProvider];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const AuthProvider = {
|
export const AuthProvider = {
|
||||||
|
|||||||
@@ -8,8 +8,7 @@
|
|||||||
/**
|
/**
|
||||||
* site_versions.build_status 코드값. 정적 빌드는 개별 재빌드 단위로 돈다.
|
* site_versions.build_status 코드값. 정적 빌드는 개별 재빌드 단위로 돈다.
|
||||||
*/
|
*/
|
||||||
export type BuildStatus = typeof BuildStatus[keyof typeof BuildStatus];
|
export type BuildStatus = (typeof BuildStatus)[keyof typeof BuildStatus];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const BuildStatus = {
|
export const BuildStatus = {
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type CheckSlugParams = {
|
export type CheckSlugParams = {
|
||||||
/**
|
/**
|
||||||
* 쓰고 싶은 주소(예: doflo)
|
* 쓰고 싶은 주소(예: doflo)
|
||||||
*/
|
*/
|
||||||
slug: string;
|
slug: string;
|
||||||
};
|
};
|
||||||
@@ -4,9 +4,9 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { ErrorInfoSuccess } from './errorInfoSuccess';
|
import type { ErrorInfoSuccess } from "./errorInfoSuccess";
|
||||||
import type { ErrorInfoCode } from './errorInfoCode';
|
import type { ErrorInfoCode } from "./errorInfoCode";
|
||||||
import type { ErrorInfoDesc } from './errorInfoDesc';
|
import type { ErrorInfoDesc } from "./errorInfoDesc";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다.
|
* 모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다.
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
카카오는 안정적인 고유 place id 를 준다 → 그걸로 중복 등록을 막는다.
|
카카오는 안정적인 고유 place id 를 준다 → 그걸로 중복 등록을 막는다.
|
||||||
네이버는 고유 id 가 없다(응답의 link 는 업체 홈페이지다) → 상호명+도로명주소로 막는다.
|
네이버는 고유 id 가 없다(응답의 link 는 업체 홈페이지다) → 상호명+도로명주소로 막는다.
|
||||||
*/
|
*/
|
||||||
export type ExternalPlaceSource = typeof ExternalPlaceSource[keyof typeof ExternalPlaceSource];
|
export type ExternalPlaceSource =
|
||||||
|
(typeof ExternalPlaceSource)[keyof typeof ExternalPlaceSource];
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const ExternalPlaceSource = {
|
export const ExternalPlaceSource = {
|
||||||
|
|||||||
@@ -4,17 +4,17 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { FactDataUnitId } from './factDataUnitId';
|
import type { FactDataUnitId } from "./factDataUnitId";
|
||||||
import type { FactDataValue } from './factDataValue';
|
import type { FactDataValue } from "./factDataValue";
|
||||||
import type { FactDataSummary } from './factDataSummary';
|
import type { FactDataSummary } from "./factDataSummary";
|
||||||
import type { FactDataUnit } from './factDataUnit';
|
import type { FactDataUnit } from "./factDataUnit";
|
||||||
import type { SourceType } from './sourceType';
|
import type { SourceType } from "./sourceType";
|
||||||
import type { FactDataSourceUrl } from './factDataSourceUrl';
|
import type { FactDataSourceUrl } from "./factDataSourceUrl";
|
||||||
import type { FactDataCollectedAt } from './factDataCollectedAt';
|
import type { FactDataCollectedAt } from "./factDataCollectedAt";
|
||||||
import type { FactDataVerifiedBy } from './factDataVerifiedBy';
|
import type { FactDataVerifiedBy } from "./factDataVerifiedBy";
|
||||||
import type { FactDataVerifiedAt } from './factDataVerifiedAt';
|
import type { FactDataVerifiedAt } from "./factDataVerifiedAt";
|
||||||
import type { FactStatus } from './factStatus';
|
import type { FactStatus } from "./factStatus";
|
||||||
import type { FactDataExpiresAt } from './factDataExpiresAt';
|
import type { FactDataExpiresAt } from "./factDataExpiresAt";
|
||||||
|
|
||||||
export interface FactData {
|
export interface FactData {
|
||||||
fact_id: string;
|
fact_id: string;
|
||||||
|
|||||||
@@ -9,8 +9,7 @@
|
|||||||
* facts.status / faqs.status / routes.status 공용 검증 상태.
|
* facts.status / faqs.status / routes.status 공용 검증 상태.
|
||||||
★ VERIFIED 와 CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES).
|
★ VERIFIED 와 CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES).
|
||||||
*/
|
*/
|
||||||
export type FactStatus = typeof FactStatus[keyof typeof FactStatus];
|
export type FactStatus = (typeof FactStatus)[keyof typeof FactStatus];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const FactStatus = {
|
export const FactStatus = {
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
* fact 기록 결과. 재수집(업데이트)이 무엇을 했는지 호출측이 알아야 한다 —
|
* fact 기록 결과. 재수집(업데이트)이 무엇을 했는지 호출측이 알아야 한다 —
|
||||||
특히 사이트 재빌드가 필요한 경우(PUBLISHED_REPLACED)를 구분해야 한다.
|
특히 사이트 재빌드가 필요한 경우(PUBLISHED_REPLACED)를 구분해야 한다.
|
||||||
*/
|
*/
|
||||||
export type FactWriteOutcome = typeof FactWriteOutcome[keyof typeof FactWriteOutcome];
|
export type FactWriteOutcome =
|
||||||
|
(typeof FactWriteOutcome)[keyof typeof FactWriteOutcome];
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const FactWriteOutcome = {
|
export const FactWriteOutcome = {
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { FaqDataSourceFactIds } from './faqDataSourceFactIds';
|
import type { FaqDataSourceFactIds } from "./faqDataSourceFactIds";
|
||||||
import type { SourceType } from './sourceType';
|
import type { SourceType } from "./sourceType";
|
||||||
import type { FactStatus } from './factStatus';
|
import type { FactStatus } from "./factStatus";
|
||||||
import type { FaqDataCreatedAt } from './faqDataCreatedAt';
|
import type { FaqDataCreatedAt } from "./faqDataCreatedAt";
|
||||||
import type { FaqDataUpdatedAt } from './faqDataUpdatedAt';
|
import type { FaqDataUpdatedAt } from "./faqDataUpdatedAt";
|
||||||
|
|
||||||
export interface FaqData {
|
export interface FaqData {
|
||||||
faq_id: string;
|
faq_id: string;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { FieldSpecDataUnit } from './fieldSpecDataUnit';
|
import type { FieldSpecDataUnit } from "./fieldSpecDataUnit";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 업종 스키마의 필드 정의 — 관리 화면이 입력 폼을 그리는 데 쓴다.
|
* 업종 스키마의 필드 정의 — 관리 화면이 입력 폼을 그리는 데 쓴다.
|
||||||
|
|||||||
+3
-1
@@ -5,4 +5,6 @@
|
|||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export type ReqSyncFestivalsAreaCode = string | null;
|
export type GetGuideParams = {
|
||||||
|
place_id: string;
|
||||||
|
};
|
||||||
@@ -6,19 +6,19 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type GetWeatherParams = {
|
export type GetWeatherParams = {
|
||||||
/**
|
/**
|
||||||
* @minLength 1
|
* @minLength 1
|
||||||
* @maxLength 10
|
* @maxLength 10
|
||||||
*/
|
*/
|
||||||
region_code: string;
|
region_code: string;
|
||||||
/**
|
/**
|
||||||
* @minimum -90
|
* @minimum -90
|
||||||
* @maximum 90
|
* @maximum 90
|
||||||
*/
|
*/
|
||||||
latitude: number;
|
latitude: number;
|
||||||
/**
|
/**
|
||||||
* @minimum -180
|
* @minimum -180
|
||||||
* @maximum 180
|
* @maximum 180
|
||||||
*/
|
*/
|
||||||
longitude: number;
|
longitude: number;
|
||||||
};
|
};
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { ValidationError } from './validationError';
|
import type { ValidationError } from "./validationError";
|
||||||
|
|
||||||
export interface HTTPValidationError {
|
export interface HTTPValidationError {
|
||||||
detail?: ValidationError[];
|
detail?: ValidationError[];
|
||||||
|
|||||||
@@ -5,318 +5,333 @@
|
|||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export * from './auditCheckData';
|
export * from "./auditCheckData";
|
||||||
export * from './auditCheckDataRecommendation';
|
export * from "./auditCheckDataRecommendation";
|
||||||
export * from './authProvider';
|
export * from "./authProvider";
|
||||||
export * from './buildStatus';
|
export * from "./buildStatus";
|
||||||
export * from './checkSlugParams';
|
export * from "./checkSlugParams";
|
||||||
export * from './errorInfo';
|
export * from "./errorInfo";
|
||||||
export * from './errorInfoCode';
|
export * from "./errorInfoCode";
|
||||||
export * from './errorInfoDesc';
|
export * from "./errorInfoDesc";
|
||||||
export * from './errorInfoSuccess';
|
export * from "./errorInfoSuccess";
|
||||||
export * from './externalPlaceSource';
|
export * from "./externalPlaceSource";
|
||||||
export * from './factData';
|
export * from "./factData";
|
||||||
export * from './factDataCollectedAt';
|
export * from "./factDataCollectedAt";
|
||||||
export * from './factDataExpiresAt';
|
export * from "./factDataExpiresAt";
|
||||||
export * from './factDataSourceUrl';
|
export * from "./factDataSourceUrl";
|
||||||
export * from './factDataSummary';
|
export * from "./factDataSummary";
|
||||||
export * from './factDataUnit';
|
export * from "./factDataUnit";
|
||||||
export * from './factDataUnitId';
|
export * from "./factDataUnitId";
|
||||||
export * from './factDataValue';
|
export * from "./factDataValue";
|
||||||
export * from './factDataVerifiedAt';
|
export * from "./factDataVerifiedAt";
|
||||||
export * from './factDataVerifiedBy';
|
export * from "./factDataVerifiedBy";
|
||||||
export * from './factStatus';
|
export * from "./factStatus";
|
||||||
export * from './factWriteOutcome';
|
export * from "./factWriteOutcome";
|
||||||
export * from './faqData';
|
export * from "./faqData";
|
||||||
export * from './faqDataCreatedAt';
|
export * from "./faqDataCreatedAt";
|
||||||
export * from './faqDataSourceFactIds';
|
export * from "./faqDataSourceFactIds";
|
||||||
export * from './faqDataUpdatedAt';
|
export * from "./faqDataUpdatedAt";
|
||||||
export * from './fieldSpecData';
|
export * from "./fieldSpecData";
|
||||||
export * from './fieldSpecDataUnit';
|
export * from "./fieldSpecDataUnit";
|
||||||
export * from './getWeatherParams';
|
export * from "./getGuideParams";
|
||||||
export * from './hTTPValidationError';
|
export * from "./getWeatherParams";
|
||||||
export * from './jobData';
|
export * from "./hTTPValidationError";
|
||||||
export * from './jobDataCreatedAt';
|
export * from "./jobData";
|
||||||
export * from './jobDataLastError';
|
export * from "./jobDataCreatedAt";
|
||||||
export * from './jobDataResult';
|
export * from "./jobDataLastError";
|
||||||
export * from './jobDataRunAfter';
|
export * from "./jobDataResult";
|
||||||
export * from './jobDataRunStartedAt';
|
export * from "./jobDataRunAfter";
|
||||||
export * from './jobDataUpdatedAt';
|
export * from "./jobDataRunStartedAt";
|
||||||
export * from './jobStatus';
|
export * from "./jobDataUpdatedAt";
|
||||||
export * from './jobType';
|
export * from "./jobStatus";
|
||||||
export * from './linkChannel';
|
export * from "./jobType";
|
||||||
export * from './linkData';
|
export * from "./linkChannel";
|
||||||
export * from './linkDataConfirmedAt';
|
export * from "./linkData";
|
||||||
export * from './linkDataDiscoveredAt';
|
export * from "./linkDataConfirmedAt";
|
||||||
export * from './linkDataTitle';
|
export * from "./linkDataDiscoveredAt";
|
||||||
export * from './listContentsParams';
|
export * from "./linkDataTitle";
|
||||||
export * from './listFactsParams';
|
export * from "./listContentsParams";
|
||||||
export * from './listFaqsParams';
|
export * from "./listFactsParams";
|
||||||
export * from './listLinksParams';
|
export * from "./listFaqsParams";
|
||||||
export * from './listMediaParams';
|
export * from "./listLinksParams";
|
||||||
export * from './listMySitesParams';
|
export * from "./listMediaParams";
|
||||||
export * from './listPlacesParams';
|
export * from "./listMySitesParams";
|
||||||
export * from './listShowcaseParams';
|
export * from "./listPlacesParams";
|
||||||
export * from './localContentData';
|
export * from "./listShowcaseParams";
|
||||||
export * from './localContentDataBody';
|
export * from "./localContentData";
|
||||||
export * from './localContentDataCollectedAt';
|
export * from "./localContentDataBody";
|
||||||
export * from './localContentDataDisplayEndAt';
|
export * from "./localContentDataCollectedAt";
|
||||||
export * from './localContentDataDisplayStartAt';
|
export * from "./localContentDataDisplayEndAt";
|
||||||
export * from './localContentDataExternalId';
|
export * from "./localContentDataDisplayStartAt";
|
||||||
export * from './localContentDataPublishedAt';
|
export * from "./localContentDataExternalId";
|
||||||
export * from './localContentDataTitle';
|
export * from "./localContentDataPublishedAt";
|
||||||
export * from './localContentStatus';
|
export * from "./localContentDataTitle";
|
||||||
export * from './localContentType';
|
export * from "./localContentStatus";
|
||||||
export * from './localSource';
|
export * from "./localContentType";
|
||||||
export * from './mediaData';
|
export * from "./localSource";
|
||||||
export * from './mediaDataAltText';
|
export * from "./mediaData";
|
||||||
export * from './mediaDataCreatedAt';
|
export * from "./mediaDataAltText";
|
||||||
export * from './mediaDataHeight';
|
export * from "./mediaDataCreatedAt";
|
||||||
export * from './mediaDataLabel';
|
export * from "./mediaDataHeight";
|
||||||
export * from './mediaDataOriginUrl';
|
export * from "./mediaDataLabel";
|
||||||
export * from './mediaDataSourceUrl';
|
export * from "./mediaDataOriginUrl";
|
||||||
export * from './mediaDataUnitId';
|
export * from "./mediaDataSourceUrl";
|
||||||
export * from './mediaDataVisionConfidence';
|
export * from "./mediaDataUnitId";
|
||||||
export * from './mediaDataWidth';
|
export * from "./mediaDataVisionConfidence";
|
||||||
export * from './mediaStatus';
|
export * from "./mediaDataWidth";
|
||||||
export * from './mySiteData';
|
export * from "./mediaStatus";
|
||||||
export * from './mySiteDataCreatedAt';
|
export * from "./mySiteData";
|
||||||
export * from './mySiteDataDomain';
|
export * from "./mySiteDataCreatedAt";
|
||||||
export * from './mySiteDataPublishedAt';
|
export * from "./mySiteDataDomain";
|
||||||
export * from './mySiteDataThumbnailUrl';
|
export * from "./mySiteDataPublishedAt";
|
||||||
export * from './mySiteDataRoadAddress';
|
export * from "./mySiteDataRoadAddress";
|
||||||
export * from './mySiteDataSiteId';
|
export * from "./mySiteDataSiteId";
|
||||||
export * from './mySiteDataStatus';
|
export * from "./mySiteDataStatus";
|
||||||
export * from './mySiteDataTemplateId';
|
export * from "./mySiteDataTemplateId";
|
||||||
export * from './placeCandidate';
|
export * from "./mySiteDataThumbnailUrl";
|
||||||
export * from './placeCandidateAddress';
|
export * from "./placeCandidate";
|
||||||
export * from './placeCandidateCategoryName';
|
export * from "./placeCandidateAddress";
|
||||||
export * from './placeCandidateExternalPlaceId';
|
export * from "./placeCandidateCategoryName";
|
||||||
export * from './placeCandidateLatitude';
|
export * from "./placeCandidateExternalPlaceId";
|
||||||
export * from './placeCandidateLongitude';
|
export * from "./placeCandidateLatitude";
|
||||||
export * from './placeCandidateNaverPlaceUrl';
|
export * from "./placeCandidateLongitude";
|
||||||
export * from './placeCandidatePhone';
|
export * from "./placeCandidateNaverPlaceUrl";
|
||||||
export * from './placeCandidatePlaceUrl';
|
export * from "./placeCandidatePhone";
|
||||||
export * from './placeCandidateRoadAddress';
|
export * from "./placeCandidatePlaceUrl";
|
||||||
export * from './placeCategory';
|
export * from "./placeCandidateRoadAddress";
|
||||||
export * from './placeData';
|
export * from "./placeCategory";
|
||||||
export * from './placeDataAddress';
|
export * from "./placeContentData";
|
||||||
export * from './placeDataContentUpdatedAt';
|
export * from "./placeContentDataBody";
|
||||||
export * from './placeDataCreatedAt';
|
export * from "./placeContentDataCollectedAt";
|
||||||
export * from './placeDataExternalPlaceId';
|
export * from "./placeContentDataDisplayEndAt";
|
||||||
export * from './placeDataExternalSource';
|
export * from "./placeData";
|
||||||
export * from './placeDataLatitude';
|
export * from "./placeDataAddress";
|
||||||
export * from './placeDataLongitude';
|
export * from "./placeDataContentUpdatedAt";
|
||||||
export * from './placeDataOwnerUserId';
|
export * from "./placeDataCreatedAt";
|
||||||
export * from './placeDataPhone';
|
export * from "./placeDataExternalPlaceId";
|
||||||
export * from './placeDataRegionCode';
|
export * from "./placeDataExternalSource";
|
||||||
export * from './placeDataRoadAddress';
|
export * from "./placeDataLatitude";
|
||||||
export * from './placeDataVerifiedAt';
|
export * from "./placeDataLongitude";
|
||||||
export * from './placeSearchItem';
|
export * from "./placeDataOwnerUserId";
|
||||||
export * from './placeSearchItemCategory';
|
export * from "./placeDataPhone";
|
||||||
export * from './placeSearchItemCategoryName';
|
export * from "./placeDataRegionCode";
|
||||||
export * from './placeSearchItemRoadAddress';
|
export * from "./placeDataRoadAddress";
|
||||||
export * from './placeStatus';
|
export * from "./placeDataVerifiedAt";
|
||||||
export * from './publishAction';
|
export * from "./placeSearchItem";
|
||||||
export * from './publishLogData';
|
export * from "./placeSearchItemCategory";
|
||||||
export * from './publishLogDataCreatedAt';
|
export * from "./placeSearchItemCategoryName";
|
||||||
export * from './publishLogDataDetail';
|
export * from "./placeSearchItemNaverPlaceUrl";
|
||||||
export * from './publishLogDataRejectReason';
|
export * from "./placeSearchItemRoadAddress";
|
||||||
export * from './publishRejectReason';
|
export * from "./placeStatus";
|
||||||
export * from './publishResult';
|
export * from "./publishAction";
|
||||||
export * from './renderStatusData';
|
export * from "./publishLogData";
|
||||||
export * from './renderStatusDataError';
|
export * from "./publishLogDataCreatedAt";
|
||||||
export * from './renderStatusDataRenderedAt';
|
export * from "./publishLogDataDetail";
|
||||||
export * from './renderStatusDataRenderedVersion';
|
export * from "./publishLogDataRejectReason";
|
||||||
export * from './reqCreateFaq';
|
export * from "./publishRejectReason";
|
||||||
export * from './reqCreateFaqSortOrder';
|
export * from "./publishResult";
|
||||||
export * from './reqCreateLink';
|
export * from "./relayParams";
|
||||||
export * from './reqCreateLinkTitle';
|
export * from "./renderStatusData";
|
||||||
export * from './reqCreatePlace';
|
export * from "./renderStatusDataError";
|
||||||
export * from './reqCreatePlaceOwnerUserId';
|
export * from "./renderStatusDataRenderedAt";
|
||||||
export * from './reqCreateUnit';
|
export * from "./renderStatusDataRenderedVersion";
|
||||||
export * from './reqExtractFacts';
|
export * from "./reqCreateFaq";
|
||||||
export * from './reqGoogleLogin';
|
export * from "./reqCreateFaqSortOrder";
|
||||||
export * from './reqLogin';
|
export * from "./reqCreateLink";
|
||||||
export * from './reqPublishLocalContent';
|
export * from "./reqCreateLinkTitle";
|
||||||
export * from './reqSignup';
|
export * from "./reqCreatePlace";
|
||||||
export * from './reqSignupName';
|
export * from "./reqCreateUnit";
|
||||||
export * from './reqSiteSlug';
|
export * from "./reqExtractFacts";
|
||||||
export * from './reqSiteStatus';
|
export * from "./reqGoogleLogin";
|
||||||
export * from './reqSiteTemplate';
|
export * from "./reqHidePlaceContent";
|
||||||
export * from './reqSiteTheme';
|
export * from "./reqLogin";
|
||||||
export * from './reqSiteThemeTheme';
|
export * from "./reqPublishLocalContent";
|
||||||
export * from './reqStartBuild';
|
export * from "./reqRollback";
|
||||||
export * from './reqStartCollect';
|
export * from "./reqSignup";
|
||||||
export * from './reqStartCopy';
|
export * from "./reqSignupName";
|
||||||
export * from './reqStartVision';
|
export * from "./reqSiteSlug";
|
||||||
export * from './reqSyncFestivals';
|
export * from "./reqSiteStatus";
|
||||||
export * from './reqSyncFestivalsAreaCode';
|
export * from "./reqSiteTemplate";
|
||||||
export * from './reqSyncFestivalsStartDate';
|
export * from "./reqSiteTheme";
|
||||||
export * from './reqTransitionFact';
|
export * from "./reqSiteThemeTheme";
|
||||||
export * from './reqTransitionFactValue';
|
export * from "./reqStartBuild";
|
||||||
export * from './reqTransitionFaq';
|
export * from "./reqStartCollect";
|
||||||
export * from './reqTransitionFaqAnswer';
|
export * from "./reqStartCopy";
|
||||||
export * from './reqTransitionFaqQuestion';
|
export * from "./reqStartVision";
|
||||||
export * from './reqUpdateLocalContent';
|
export * from "./reqTransitionFact";
|
||||||
export * from './reqUpdateLocalContentBody';
|
export * from "./reqTransitionFactValue";
|
||||||
export * from './reqUpdateLocalContentBodyAnyOf';
|
export * from "./reqTransitionFaq";
|
||||||
export * from './reqUpdateLocalContentDisplayEndAt';
|
export * from "./reqTransitionFaqAnswer";
|
||||||
export * from './reqUpdateLocalContentDisplayStartAt';
|
export * from "./reqTransitionFaqQuestion";
|
||||||
export * from './reqUpdateLocalContentTitle';
|
export * from "./reqUpdateLocalContent";
|
||||||
export * from './reqUpdateMe';
|
export * from "./reqUpdateLocalContentBody";
|
||||||
export * from './reqUpdateMeContactNumber';
|
export * from "./reqUpdateLocalContentBodyAnyOf";
|
||||||
export * from './reqUpdateMeEmail';
|
export * from "./reqUpdateLocalContentDisplayEndAt";
|
||||||
export * from './reqUpdateMeName';
|
export * from "./reqUpdateLocalContentDisplayStartAt";
|
||||||
export * from './reqUpdateMePassword';
|
export * from "./reqUpdateLocalContentTitle";
|
||||||
export * from './reqUpdatePlace';
|
export * from "./reqUpdateMe";
|
||||||
export * from './reqUpdatePlaceName';
|
export * from "./reqUpdateMeContactNumber";
|
||||||
export * from './reqUpdatePlaceOwnerUserId';
|
export * from "./reqUpdateMeEmail";
|
||||||
export * from './reqUpdatePlaceStatus';
|
export * from "./reqUpdateMeName";
|
||||||
export * from './reqUpsertFact';
|
export * from "./reqUpdateMePassword";
|
||||||
export * from './reqUpsertFactExpiresAt';
|
export * from "./reqUpdatePlace";
|
||||||
export * from './reqUpsertFactSourceUrl';
|
export * from "./reqUpdatePlaceName";
|
||||||
export * from './reqUpsertFactUnitId';
|
export * from "./reqUpdatePlaceStatus";
|
||||||
export * from './reqUpsertFactValue';
|
export * from "./reqUpsertFact";
|
||||||
export * from './reqVerifyPlace';
|
export * from "./reqUpsertFactExpiresAt";
|
||||||
export * from './reqVerifyPlaceAddress';
|
export * from "./reqUpsertFactSourceUrl";
|
||||||
export * from './reqVerifyPlaceByUrl';
|
export * from "./reqUpsertFactUnitId";
|
||||||
export * from './reqVerifyPlaceLatitude';
|
export * from "./reqUpsertFactValue";
|
||||||
export * from './reqVerifyPlaceLongitude';
|
export * from "./reqVerifyPlace";
|
||||||
export * from './reqVerifyPlacePhone';
|
export * from "./reqVerifyPlaceAddress";
|
||||||
export * from './reqVerifyPlacePlaceUrl';
|
export * from "./reqVerifyPlaceByUrl";
|
||||||
export * from './reqVerifyPlaceRegionCode';
|
export * from "./reqVerifyPlaceCategoryName";
|
||||||
export * from './reqVerifyPlaceRoadAddress';
|
export * from "./reqVerifyPlaceLatitude";
|
||||||
export * from './resCategorySchema';
|
export * from "./reqVerifyPlaceLongitude";
|
||||||
export * from './resCategorySchemaCategory';
|
export * from "./reqVerifyPlacePhone";
|
||||||
export * from './resCategorySchemaLabel';
|
export * from "./reqVerifyPlacePlaceUrl";
|
||||||
export * from './resCategorySchemaMsg';
|
export * from "./reqVerifyPlaceRegionCode";
|
||||||
export * from './resExtractFacts';
|
export * from "./reqVerifyPlaceRoadAddress";
|
||||||
export * from './resExtractFactsMsg';
|
export * from "./resCategorySchema";
|
||||||
export * from './resExtractedFact';
|
export * from "./resCategorySchemaCategory";
|
||||||
export * from './resExtractedFactReason';
|
export * from "./resCategorySchemaLabel";
|
||||||
export * from './resExtractedFactUnitName';
|
export * from "./resCategorySchemaMsg";
|
||||||
export * from './resFact';
|
export * from "./resExtractFacts";
|
||||||
export * from './resFactFact';
|
export * from "./resExtractFactsMsg";
|
||||||
export * from './resFactList';
|
export * from "./resExtractedFact";
|
||||||
export * from './resFactListMsg';
|
export * from "./resExtractedFactReason";
|
||||||
export * from './resFactMsg';
|
export * from "./resExtractedFactUnitName";
|
||||||
export * from './resFactOutcome';
|
export * from "./resFact";
|
||||||
export * from './resFaq';
|
export * from "./resFactFact";
|
||||||
export * from './resFaqFaq';
|
export * from "./resFactList";
|
||||||
export * from './resFaqList';
|
export * from "./resFactListMsg";
|
||||||
export * from './resFaqListMsg';
|
export * from "./resFactMsg";
|
||||||
export * from './resFaqMsg';
|
export * from "./resFactOutcome";
|
||||||
export * from './resJob';
|
export * from "./resFaq";
|
||||||
export * from './resJobJob';
|
export * from "./resFaqFaq";
|
||||||
export * from './resJobMsg';
|
export * from "./resFaqList";
|
||||||
export * from './resJobOps';
|
export * from "./resFaqListMsg";
|
||||||
export * from './resJobOpsMsg';
|
export * from "./resFaqMsg";
|
||||||
export * from './resLink';
|
export * from "./resJob";
|
||||||
export * from './resLinkLink';
|
export * from "./resJobJob";
|
||||||
export * from './resLinkList';
|
export * from "./resJobMsg";
|
||||||
export * from './resLinkListMsg';
|
export * from "./resJobOps";
|
||||||
export * from './resLinkMsg';
|
export * from "./resJobOpsMsg";
|
||||||
export * from './resLocalContentList';
|
export * from "./resLink";
|
||||||
export * from './resLocalContentListMsg';
|
export * from "./resLinkLink";
|
||||||
export * from './resLogin';
|
export * from "./resLinkList";
|
||||||
export * from './resLoginMsg';
|
export * from "./resLinkListMsg";
|
||||||
export * from './resMe';
|
export * from "./resLinkMsg";
|
||||||
export * from './resMeContactNumber';
|
export * from "./resLocalContentList";
|
||||||
export * from './resMeEmail';
|
export * from "./resLocalContentListMsg";
|
||||||
export * from './resMeMsg';
|
export * from "./resLocalGuide";
|
||||||
export * from './resMeName';
|
export * from "./resLocalGuideAttractionsItem";
|
||||||
export * from './resMediaList';
|
export * from "./resLocalGuideCoursesItem";
|
||||||
export * from './resMediaListMsg';
|
export * from "./resLocalGuideFestivalsItem";
|
||||||
export * from './resMySites';
|
export * from "./resLocalGuideItinerariesItem";
|
||||||
export * from './resMySitesMsg';
|
export * from "./resLocalGuideMsg";
|
||||||
export * from './resPlace';
|
export * from "./resLocalGuideRestaurantsItem";
|
||||||
export * from './resPlaceList';
|
export * from "./resLocalGuideSyncedAt";
|
||||||
export * from './resPlaceListMsg';
|
export * from "./resLogin";
|
||||||
export * from './resPlaceMsg';
|
export * from "./resLoginMsg";
|
||||||
export * from './resPlacePlace';
|
export * from "./resMe";
|
||||||
export * from './resPlaceSearch';
|
export * from "./resMeContactNumber";
|
||||||
export * from './resPlaceSearchMsg';
|
export * from "./resMeEmail";
|
||||||
export * from './resPlaceSearchSource';
|
export * from "./resMeMsg";
|
||||||
export * from './resPublishLogs';
|
export * from "./resMeName";
|
||||||
export * from './resPublishLogsMsg';
|
export * from "./resMediaList";
|
||||||
export * from './resRefreshToken';
|
export * from "./resMediaListMsg";
|
||||||
export * from './resRefreshTokenMsg';
|
export * from "./resMySites";
|
||||||
export * from './resSeoAudit';
|
export * from "./resMySitesMsg";
|
||||||
export * from './resSeoAuditMsg';
|
export * from "./resPlace";
|
||||||
export * from './resSeoAuditSummary';
|
export * from "./resPlaceContentList";
|
||||||
export * from './resSeoAuditVisibility';
|
export * from "./resPlaceContentListMsg";
|
||||||
export * from './resShowcase';
|
export * from "./resPlaceList";
|
||||||
export * from './resShowcaseMsg';
|
export * from "./resPlaceListMsg";
|
||||||
export * from './resSite';
|
export * from "./resPlaceMsg";
|
||||||
export * from './resSiteCurrentVersion';
|
export * from "./resPlacePlace";
|
||||||
export * from './resSiteMsg';
|
export * from "./resPlaceSearch";
|
||||||
export * from './resSiteSite';
|
export * from "./resPlaceSearchMsg";
|
||||||
export * from './resSiteSlug';
|
export * from "./resPlaceSearchSource";
|
||||||
export * from './resSiteSlugMsg';
|
export * from "./resPublishLogs";
|
||||||
export * from './resSiteSlugReason';
|
export * from "./resPublishLogsMsg";
|
||||||
export * from './resSiteSlugSite';
|
export * from "./resRefreshToken";
|
||||||
export * from './resSiteSlugSuggestion';
|
export * from "./resRefreshTokenMsg";
|
||||||
export * from './resSiteVersions';
|
export * from "./resSeoAudit";
|
||||||
export * from './resSiteVersionsMsg';
|
export * from "./resSeoAuditMsg";
|
||||||
export * from './resSlugCheck';
|
export * from "./resSeoAuditSummary";
|
||||||
export * from './resSlugCheckMsg';
|
export * from "./resSeoAuditVisibility";
|
||||||
export * from './resSlugCheckReason';
|
export * from "./resShowcase";
|
||||||
export * from './resSlugCheckSuggestion';
|
export * from "./resShowcaseMsg";
|
||||||
export * from './resStartBuild';
|
export * from "./resSite";
|
||||||
export * from './resStartBuildJobId';
|
export * from "./resSiteCurrentVersion";
|
||||||
export * from './resStartBuildMsg';
|
export * from "./resSiteMsg";
|
||||||
export * from './resStartBuildStatus';
|
export * from "./resSiteSite";
|
||||||
export * from './resStartCollect';
|
export * from "./resSiteSlug";
|
||||||
export * from './resStartCollectJobId';
|
export * from "./resSiteSlugMsg";
|
||||||
export * from './resStartCollectMsg';
|
export * from "./resSiteSlugReason";
|
||||||
export * from './resStartCollectStatus';
|
export * from "./resSiteSlugSite";
|
||||||
export * from './resStartCopy';
|
export * from "./resSiteSlugSuggestion";
|
||||||
export * from './resStartCopyJobId';
|
export * from "./resSiteVersions";
|
||||||
export * from './resStartCopyMsg';
|
export * from "./resSiteVersionsMsg";
|
||||||
export * from './resStartCopyStatus';
|
export * from "./resSlugCheck";
|
||||||
export * from './resStartVision';
|
export * from "./resSlugCheckMsg";
|
||||||
export * from './resStartVisionJobId';
|
export * from "./resSlugCheckReason";
|
||||||
export * from './resStartVisionMsg';
|
export * from "./resSlugCheckSuggestion";
|
||||||
export * from './resStartVisionStatus';
|
export * from "./resStartBuild";
|
||||||
export * from './resSyncFestivals';
|
export * from "./resStartBuildJobId";
|
||||||
export * from './resSyncFestivalsMsg';
|
export * from "./resStartBuildMsg";
|
||||||
export * from './resUnit';
|
export * from "./resStartBuildStatus";
|
||||||
export * from './resUnitList';
|
export * from "./resStartCollect";
|
||||||
export * from './resUnitListMsg';
|
export * from "./resStartCollectJobId";
|
||||||
export * from './resUnitMsg';
|
export * from "./resStartCollectMsg";
|
||||||
export * from './resUnitUnit';
|
export * from "./resStartCollectStatus";
|
||||||
export * from './resVerifyCandidates';
|
export * from "./resStartCopy";
|
||||||
export * from './resVerifyCandidatesMsg';
|
export * from "./resStartCopyJobId";
|
||||||
export * from './resVerifyCandidatesReason';
|
export * from "./resStartCopyMsg";
|
||||||
export * from './resVerifyCandidatesSource';
|
export * from "./resStartCopyStatus";
|
||||||
export * from './resWeather';
|
export * from "./resStartVision";
|
||||||
export * from './resWeatherMsg';
|
export * from "./resStartVisionJobId";
|
||||||
export * from './resWeatherWeather';
|
export * from "./resStartVisionMsg";
|
||||||
export * from './searchPlacesPublicParams';
|
export * from "./resStartVisionStatus";
|
||||||
export * from './showcaseItem';
|
export * from "./resSyncPlace";
|
||||||
export * from './showcaseItemRegion';
|
export * from "./resSyncPlaceMsg";
|
||||||
export * from './showcaseItemThumbnailUrl';
|
export * from "./resUnit";
|
||||||
export * from './siteData';
|
export * from "./resUnitList";
|
||||||
export * from './siteDataCurrentVersionId';
|
export * from "./resUnitListMsg";
|
||||||
export * from './siteDataDomain';
|
export * from "./resUnitMsg";
|
||||||
export * from './siteDataPublishedAt';
|
export * from "./resUnitUnit";
|
||||||
export * from './siteDataTemplateId';
|
export * from "./resVerifyCandidates";
|
||||||
export * from './siteDataTheme';
|
export * from "./resVerifyCandidatesMsg";
|
||||||
export * from './siteDataThemeAnyOf';
|
export * from "./resVerifyCandidatesReason";
|
||||||
export * from './siteDataThumbnailUrl';
|
export * from "./resVerifyCandidatesSource";
|
||||||
export * from './siteStatus';
|
export * from "./resWeather";
|
||||||
export * from './siteVersionData';
|
export * from "./resWeatherMsg";
|
||||||
export * from './siteVersionDataBuildError';
|
export * from "./resWeatherWeather";
|
||||||
export * from './siteVersionDataBuiltAt';
|
export * from "./searchPlacesPublicParams";
|
||||||
export * from './siteVersionDataCreatedAt';
|
export * from "./showcaseItem";
|
||||||
export * from './sourceType';
|
export * from "./showcaseItemRegion";
|
||||||
export * from './unitData';
|
export * from "./showcaseItemThumbnailUrl";
|
||||||
export * from './userRole';
|
export * from "./siteData";
|
||||||
export * from './validationError';
|
export * from "./siteDataCurrentVersionId";
|
||||||
export * from './validationErrorCtx';
|
export * from "./siteDataDomain";
|
||||||
export * from './validationErrorLocItem';
|
export * from "./siteDataPublishedAt";
|
||||||
export * from './verifyCandidatesParams';
|
export * from "./siteDataTemplateId";
|
||||||
export * from './weatherData';
|
export * from "./siteDataTheme";
|
||||||
export * from './weatherDataTimezone';
|
export * from "./siteDataThemeAnyOf";
|
||||||
export * from './weatherDataWindSpeed';
|
export * from "./siteDataThumbnailUrl";
|
||||||
|
export * from "./siteStatus";
|
||||||
|
export * from "./siteVersionData";
|
||||||
|
export * from "./siteVersionDataBuildError";
|
||||||
|
export * from "./siteVersionDataBuiltAt";
|
||||||
|
export * from "./siteVersionDataCreatedAt";
|
||||||
|
export * from "./sourceType";
|
||||||
|
export * from "./unitData";
|
||||||
|
export * from "./userRole";
|
||||||
|
export * from "./validationError";
|
||||||
|
export * from "./validationErrorCtx";
|
||||||
|
export * from "./validationErrorLocItem";
|
||||||
|
export * from "./verifyCandidatesParams";
|
||||||
|
export * from "./weatherData";
|
||||||
|
export * from "./weatherDataTimezone";
|
||||||
|
export * from "./weatherDataWindSpeed";
|
||||||
@@ -4,14 +4,14 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { JobType } from './jobType';
|
import type { JobType } from "./jobType";
|
||||||
import type { JobStatus } from './jobStatus';
|
import type { JobStatus } from "./jobStatus";
|
||||||
import type { JobDataResult } from './jobDataResult';
|
import type { JobDataResult } from "./jobDataResult";
|
||||||
import type { JobDataLastError } from './jobDataLastError';
|
import type { JobDataLastError } from "./jobDataLastError";
|
||||||
import type { JobDataRunAfter } from './jobDataRunAfter';
|
import type { JobDataRunAfter } from "./jobDataRunAfter";
|
||||||
import type { JobDataRunStartedAt } from './jobDataRunStartedAt';
|
import type { JobDataRunStartedAt } from "./jobDataRunStartedAt";
|
||||||
import type { JobDataCreatedAt } from './jobDataCreatedAt';
|
import type { JobDataCreatedAt } from "./jobDataCreatedAt";
|
||||||
import type { JobDataUpdatedAt } from './jobDataUpdatedAt';
|
import type { JobDataUpdatedAt } from "./jobDataUpdatedAt";
|
||||||
|
|
||||||
export interface JobData {
|
export interface JobData {
|
||||||
job_id: string;
|
job_id: string;
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
전이는 전부 조건부 원자 UPDATE(CAS)로만 한다. 실패는 재시도 가능하면
|
전이는 전부 조건부 원자 UPDATE(CAS)로만 한다. 실패는 재시도 가능하면
|
||||||
PENDING(run_after=백오프)으로 되돌리고, 소진되면 DEAD(dead-letter).
|
PENDING(run_after=백오프)으로 되돌리고, 소진되면 DEAD(dead-letter).
|
||||||
*/
|
*/
|
||||||
export type JobStatus = typeof JobStatus[keyof typeof JobStatus];
|
export type JobStatus = (typeof JobStatus)[keyof typeof JobStatus];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const JobStatus = {
|
export const JobStatus = {
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
무거운 잡(브라우저 필요)과 가벼운 잡(HTTP API 만)을 코드로 갈라 둔다 —
|
무거운 잡(브라우저 필요)과 가벼운 잡(HTTP API 만)을 코드로 갈라 둔다 —
|
||||||
크롤링 법무 결론이 나면 무거운 잡만 별도 워커 이미지로 분리한다.
|
크롤링 법무 결론이 나면 무거운 잡만 별도 워커 이미지로 분리한다.
|
||||||
*/
|
*/
|
||||||
export type JobType = typeof JobType[keyof typeof JobType];
|
export type JobType = (typeof JobType)[keyof typeof JobType];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const JobType = {
|
export const JobType = {
|
||||||
@@ -22,4 +21,6 @@ export const JobType = {
|
|||||||
BUILD: 4,
|
BUILD: 4,
|
||||||
LOCAL_SYNC: 5,
|
LOCAL_SYNC: 5,
|
||||||
AI_CHECK: 6,
|
AI_CHECK: 6,
|
||||||
|
SONG: 7,
|
||||||
|
ROLLBACK: 8,
|
||||||
} as const;
|
} as const;
|
||||||
@@ -6,10 +6,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* place_links.channel 코드값. Perplexity 가 발견하는 채널 종류.
|
* place_channels.channel 코드값. Perplexity 가 발견하는 채널 종류.
|
||||||
*/
|
*/
|
||||||
export type LinkChannel = typeof LinkChannel[keyof typeof LinkChannel];
|
export type LinkChannel = (typeof LinkChannel)[keyof typeof LinkChannel];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const LinkChannel = {
|
export const LinkChannel = {
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { LinkChannel } from './linkChannel';
|
import type { LinkChannel } from "./linkChannel";
|
||||||
import type { LinkDataTitle } from './linkDataTitle';
|
import type { LinkDataTitle } from "./linkDataTitle";
|
||||||
import type { SourceType } from './sourceType';
|
import type { SourceType } from "./sourceType";
|
||||||
import type { LinkDataDiscoveredAt } from './linkDataDiscoveredAt';
|
import type { LinkDataDiscoveredAt } from "./linkDataDiscoveredAt";
|
||||||
import type { LinkDataConfirmedAt } from './linkDataConfirmedAt';
|
import type { LinkDataConfirmedAt } from "./linkDataConfirmedAt";
|
||||||
|
|
||||||
export interface LinkData {
|
export interface LinkData {
|
||||||
link_id: string;
|
link_id: string;
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { LocalContentStatus } from './localContentStatus';
|
import type { LocalContentStatus } from "./localContentStatus";
|
||||||
|
|
||||||
export type ListContentsParams = {
|
export type ListContentsParams = {
|
||||||
status?: LocalContentStatus | null;
|
status?: LocalContentStatus | null;
|
||||||
region_code?: string | null;
|
region_code?: string | null;
|
||||||
};
|
};
|
||||||
@@ -6,9 +6,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListFactsParams = {
|
export type ListFactsParams = {
|
||||||
/**
|
/**
|
||||||
* 객실·메뉴·프로그램 단위 fact 만
|
* 객실·메뉴·프로그램 단위 fact 만
|
||||||
*/
|
*/
|
||||||
unit_id?: string | null;
|
unit_id?: string | null;
|
||||||
publishable_only?: boolean;
|
publishable_only?: boolean;
|
||||||
};
|
};
|
||||||
@@ -6,5 +6,5 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListFaqsParams = {
|
export type ListFaqsParams = {
|
||||||
publishable_only?: boolean;
|
publishable_only?: boolean;
|
||||||
};
|
};
|
||||||
@@ -6,5 +6,5 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListLinksParams = {
|
export type ListLinksParams = {
|
||||||
confirmed_only?: boolean;
|
confirmed_only?: boolean;
|
||||||
};
|
};
|
||||||
@@ -6,9 +6,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListMediaParams = {
|
export type ListMediaParams = {
|
||||||
/**
|
/**
|
||||||
* 객실·메뉴 단위 사진만
|
* 객실·메뉴 단위 사진만
|
||||||
*/
|
*/
|
||||||
unit_id?: string | null;
|
unit_id?: string | null;
|
||||||
publishable_only?: boolean;
|
publishable_only?: boolean;
|
||||||
};
|
};
|
||||||
@@ -6,13 +6,13 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListMySitesParams = {
|
export type ListMySitesParams = {
|
||||||
/**
|
/**
|
||||||
* @minimum 1
|
* @minimum 1
|
||||||
*/
|
*/
|
||||||
page?: number;
|
page?: number;
|
||||||
/**
|
/**
|
||||||
* @minimum 1
|
* @minimum 1
|
||||||
* @maximum 100
|
* @maximum 100
|
||||||
*/
|
*/
|
||||||
size?: number;
|
size?: number;
|
||||||
};
|
};
|
||||||
@@ -4,29 +4,29 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { PlaceCategory } from './placeCategory';
|
import type { PlaceCategory } from "./placeCategory";
|
||||||
import type { PlaceStatus } from './placeStatus';
|
import type { PlaceStatus } from "./placeStatus";
|
||||||
|
|
||||||
export type ListPlacesParams = {
|
export type ListPlacesParams = {
|
||||||
/**
|
/**
|
||||||
* 상호명·주소 부분일치
|
* 상호명·주소 부분일치
|
||||||
*/
|
*/
|
||||||
search?: string | null;
|
search?: string | null;
|
||||||
/**
|
/**
|
||||||
* 업종
|
* 업종
|
||||||
*/
|
*/
|
||||||
category?: PlaceCategory | null;
|
category?: PlaceCategory | null;
|
||||||
/**
|
/**
|
||||||
* 상태
|
* 상태
|
||||||
*/
|
*/
|
||||||
status?: PlaceStatus | null;
|
status?: PlaceStatus | null;
|
||||||
/**
|
/**
|
||||||
* @minimum 1
|
* @minimum 1
|
||||||
*/
|
*/
|
||||||
page?: number;
|
page?: number;
|
||||||
/**
|
/**
|
||||||
* @minimum 1
|
* @minimum 1
|
||||||
* @maximum 100
|
* @maximum 100
|
||||||
*/
|
*/
|
||||||
size?: number;
|
size?: number;
|
||||||
};
|
};
|
||||||
@@ -6,10 +6,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export type ListShowcaseParams = {
|
export type ListShowcaseParams = {
|
||||||
/**
|
/**
|
||||||
* 가져올 개수
|
* 가져올 개수
|
||||||
* @minimum 1
|
* @minimum 1
|
||||||
* @maximum 48
|
* @maximum 48
|
||||||
*/
|
*/
|
||||||
limit?: number;
|
limit?: number;
|
||||||
};
|
};
|
||||||
@@ -4,16 +4,16 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { LocalContentType } from './localContentType';
|
import type { LocalContentType } from "./localContentType";
|
||||||
import type { LocalSource } from './localSource';
|
import type { LocalSource } from "./localSource";
|
||||||
import type { LocalContentDataExternalId } from './localContentDataExternalId';
|
import type { LocalContentDataExternalId } from "./localContentDataExternalId";
|
||||||
import type { LocalContentDataTitle } from './localContentDataTitle';
|
import type { LocalContentDataTitle } from "./localContentDataTitle";
|
||||||
import type { LocalContentDataBody } from './localContentDataBody';
|
import type { LocalContentDataBody } from "./localContentDataBody";
|
||||||
import type { LocalContentStatus } from './localContentStatus';
|
import type { LocalContentStatus } from "./localContentStatus";
|
||||||
import type { LocalContentDataCollectedAt } from './localContentDataCollectedAt';
|
import type { LocalContentDataCollectedAt } from "./localContentDataCollectedAt";
|
||||||
import type { LocalContentDataPublishedAt } from './localContentDataPublishedAt';
|
import type { LocalContentDataPublishedAt } from "./localContentDataPublishedAt";
|
||||||
import type { LocalContentDataDisplayStartAt } from './localContentDataDisplayStartAt';
|
import type { LocalContentDataDisplayStartAt } from "./localContentDataDisplayStartAt";
|
||||||
import type { LocalContentDataDisplayEndAt } from './localContentDataDisplayEndAt';
|
import type { LocalContentDataDisplayEndAt } from "./localContentDataDisplayEndAt";
|
||||||
|
|
||||||
export interface LocalContentData {
|
export interface LocalContentData {
|
||||||
local_content_id: string;
|
local_content_id: string;
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
/**
|
/**
|
||||||
* 운영 관리자가 검수하는 지역 콘텐츠 발행 상태.
|
* 운영 관리자가 검수하는 지역 콘텐츠 발행 상태.
|
||||||
*/
|
*/
|
||||||
export type LocalContentStatus = typeof LocalContentStatus[keyof typeof LocalContentStatus];
|
export type LocalContentStatus =
|
||||||
|
(typeof LocalContentStatus)[keyof typeof LocalContentStatus];
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const LocalContentStatus = {
|
export const LocalContentStatus = {
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
/**
|
/**
|
||||||
* local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류.
|
* local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류.
|
||||||
*/
|
*/
|
||||||
export type LocalContentType = typeof LocalContentType[keyof typeof LocalContentType];
|
export type LocalContentType =
|
||||||
|
(typeof LocalContentType)[keyof typeof LocalContentType];
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const LocalContentType = {
|
export const LocalContentType = {
|
||||||
@@ -17,4 +17,6 @@ export const LocalContentType = {
|
|||||||
FESTIVAL: 2,
|
FESTIVAL: 2,
|
||||||
ATTRACTION: 3,
|
ATTRACTION: 3,
|
||||||
RESTAURANT: 4,
|
RESTAURANT: 4,
|
||||||
|
COURSE: 5,
|
||||||
|
STORY: 6,
|
||||||
} as const;
|
} as const;
|
||||||
@@ -8,8 +8,7 @@
|
|||||||
/**
|
/**
|
||||||
* local_contents.source 코드값. 어느 외부 API 에서 왔는지.
|
* local_contents.source 코드값. 어느 외부 API 에서 왔는지.
|
||||||
*/
|
*/
|
||||||
export type LocalSource = typeof LocalSource[keyof typeof LocalSource];
|
export type LocalSource = (typeof LocalSource)[keyof typeof LocalSource];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const LocalSource = {
|
export const LocalSource = {
|
||||||
@@ -17,4 +16,6 @@ export const LocalSource = {
|
|||||||
TOUR_API: 2,
|
TOUR_API: 2,
|
||||||
KAKAO_LOCAL: 3,
|
KAKAO_LOCAL: 3,
|
||||||
OFFICIAL_WEB: 4,
|
OFFICIAL_WEB: 4,
|
||||||
|
LLM: 5,
|
||||||
|
NAVER_CRAWL: 6,
|
||||||
} as const;
|
} as const;
|
||||||
@@ -4,17 +4,17 @@
|
|||||||
* Web4Ai API
|
* Web4Ai API
|
||||||
* OpenAPI spec version: 0.1.0
|
* OpenAPI spec version: 0.1.0
|
||||||
*/
|
*/
|
||||||
import type { MediaDataUnitId } from './mediaDataUnitId';
|
import type { MediaDataUnitId } from "./mediaDataUnitId";
|
||||||
import type { MediaDataOriginUrl } from './mediaDataOriginUrl';
|
import type { MediaDataOriginUrl } from "./mediaDataOriginUrl";
|
||||||
import type { SourceType } from './sourceType';
|
import type { SourceType } from "./sourceType";
|
||||||
import type { MediaDataSourceUrl } from './mediaDataSourceUrl';
|
import type { MediaDataSourceUrl } from "./mediaDataSourceUrl";
|
||||||
import type { MediaDataLabel } from './mediaDataLabel';
|
import type { MediaDataLabel } from "./mediaDataLabel";
|
||||||
import type { MediaDataAltText } from './mediaDataAltText';
|
import type { MediaDataAltText } from "./mediaDataAltText";
|
||||||
import type { MediaDataVisionConfidence } from './mediaDataVisionConfidence';
|
import type { MediaDataVisionConfidence } from "./mediaDataVisionConfidence";
|
||||||
import type { MediaStatus } from './mediaStatus';
|
import type { MediaStatus } from "./mediaStatus";
|
||||||
import type { MediaDataWidth } from './mediaDataWidth';
|
import type { MediaDataWidth } from "./mediaDataWidth";
|
||||||
import type { MediaDataHeight } from './mediaDataHeight';
|
import type { MediaDataHeight } from "./mediaDataHeight";
|
||||||
import type { MediaDataCreatedAt } from './mediaDataCreatedAt';
|
import type { MediaDataCreatedAt } from "./mediaDataCreatedAt";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 사진 1건.
|
* 사진 1건.
|
||||||
|
|||||||
@@ -8,8 +8,7 @@
|
|||||||
/**
|
/**
|
||||||
* media.status 코드값. 비전 결과 신뢰도가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 둔다.
|
* media.status 코드값. 비전 결과 신뢰도가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 둔다.
|
||||||
*/
|
*/
|
||||||
export type MediaStatus = typeof MediaStatus[keyof typeof MediaStatus];
|
export type MediaStatus = (typeof MediaStatus)[keyof typeof MediaStatus];
|
||||||
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||||
export const MediaStatus = {
|
export const MediaStatus = {
|
||||||
|
|||||||
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user