Merge remote-tracking branch 'origin/main' into main-2
# Conflicts: # docs/SERVERS.md
This commit is contained in:
commit
840188e4ae
82 files changed
+4185
-78
No files matched your search
@@ -191,6 +191,8 @@ services:
|
||||
exec npm run dev -w @o2o/frontend
|
||||
environment:
|
||||
PORT: 3001
|
||||
# 컨테이너 안에서 백엔드에 닿는 주소 — vite.config.ts 의 /v1 프록시가 쓴다(호스트에서 돌리면 127.0.0.1:9800).
|
||||
DEV_API_PROXY: http://solution-backend:9800
|
||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
||||
VITE_PUBLISH_HOST: ${SITE_PUBLIC_HOST:-localhost}
|
||||
# ★ 이 둘은 **브라우저가** 부르는 주소다. 컨테이너 안에서 보는 주소가 아니라
|
||||
|
||||
@@ -267,6 +267,31 @@ Gemini 가 쓰고, 곡은 Suno 가 붙인다.
|
||||
화면의 반려 카드가 이 사유 코드로 문구를 고른다 — 전부 "렌더 실패" 로 뭉개면 사장님이
|
||||
손댈 곳을 모른다.
|
||||
|
||||
### `site_crawler_hits` — 봇 요청 기록 (2026-10-07)
|
||||
|
||||
nginx 가 `/s/…`·`/robots.txt`·`/sitemap.xml` 요청을 mirror 로 `/internal/track/hit` 에 넘기고,
|
||||
백엔드가 UA 로 봇만 골라 **1건 = 1행**으로 쌓는다(`services/track_service.py`). 집계 표는 없다 —
|
||||
사이트관리 통계가 조회 때 `GROUP BY` 한다. 기한 없이 보관한다.
|
||||
|
||||
- `purpose`: `training` · `search` · `user-fetch` · `search-engine` · `other`(목록 밖 봇). 목록은
|
||||
`services/crawler_detect.py` — AEORanking 과 같게 둔다.
|
||||
- `site_id`: 슬러그를 `site_payload.publish_slug()` 로 만든 표에서 찾는다. robots·sitemap·없는 슬러그는 NULL.
|
||||
- `ip`: 목록 봇만. 사람 요청은 저장하지 않는다.
|
||||
|
||||
### `site_page_views` — 사람 페이지뷰 (2026-10-12)
|
||||
|
||||
발행 사이트 부트 코드(`solution/site/src/lib/visit-beacon.ts`)가 hydrate 직후 `/v1/track/view` 로
|
||||
비콘을 한 번 보내고, 백엔드가 **1건 = 1행**으로 쌓는다(`services/visit_service.py`). 미리보기는 보내지 않는다.
|
||||
|
||||
- 쿠키·식별자를 브라우저에 두지 않는다. `visitor_hash = sha256(JWT_ACCESS_SECRET|IP|UA|KST 월)` —
|
||||
달이 바뀌면 같은 사람도 새 방문자다(Umami 와 같다). **IP 원문은 저장하지 않는다.**
|
||||
- 봇(`crawler_detect`)과 HeadlessChrome(우리 목업 검증 스크립트)은 세지 않는다.
|
||||
- `path` 는 발행 경로 + 탭(`/s/<slug>#/stay`). 하위 페이지가 해시 탭이라 비콘이 `hashchange` 때도 다시 나간다.
|
||||
`#/`(홈)·문서 안 앵커는 탭으로 치지 않고, 끝 슬래시는 걷는다.
|
||||
- IP 는 `X-Forwarded-For` 의 **뒤에서 두 번째**(Apache → nginx 두 프록시가 덧붙인 값) — 첫 값은 손님이 위조할 수 있다.
|
||||
- 같은 해시+경로는 10초 안에 한 번만. IP 당 분당 120건까지(상한 있는 메모리 표).
|
||||
- 기한 없이 보관. 사이트관리 통계가 조회 때 `GROUP BY` 한다.
|
||||
|
||||
### `jobs` — 작업 큐 (PostgreSQL 을 큐로)
|
||||
|
||||
COPY 단계는 `jobs.progress`(JSONB)의 `steps`·`attempt`에 기록한다.
|
||||
|
||||
@@ -241,3 +241,31 @@ docker compose exec solution-worker python scripts/republish_all.py
|
||||
`out/` 은 재생성물이라 백업이 필요 없다. 문제가 생기면
|
||||
`docker compose restart solution-prerender` → 전체 재굽기 → `republish_all.py`.
|
||||
지켜야 할 건 **DB 와 `out/payloads/`** 뿐이다.
|
||||
|
||||
## 6. 방문·크롤러 통계 배포
|
||||
|
||||
### 6-1. 크롤러 기록 — nginx mirror (2026-10-07)
|
||||
|
||||
`nginx/site.conf` 의 `/s/`·`/robots.txt`·`/sitemap.xml` 이 요청 복사본을 `/_track_hit` →
|
||||
백엔드 `/internal/track/hit` 로 보낸다. 봇만 `site_crawler_hits` 에 쌓인다(사이트관리 → 전체 통계).
|
||||
|
||||
★ **`nginx/site.conf` 는 레포에 없다**(예제만 추적). 서버의 파일에 `site.conf.example` 의
|
||||
`map $request_uri $track_skip`·`mirror` 줄·`location = /_track_hit` 를 **손으로 옮긴다.**
|
||||
옮긴 뒤 `docker compose exec solution-site nginx -t` → `docker compose exec solution-site nginx -s reload`.
|
||||
설정 파일은 마운트라 이미지 재빌드는 필요 없다.
|
||||
|
||||
★ 표가 비어 있으면 순서대로 본다: 마이그레이션 `0024` 적용 여부 → `nginx -t` → 백엔드 로그의 `[track]` 경고.
|
||||
|
||||
### 6-2. 방문 기록 — 발행 사이트 비콘 (2026-10-12)
|
||||
|
||||
발행 페이지가 열리면 브라우저가 `/v1/track/view` 로 비콘을 한 번 보낸다(`solution/site/src/lib/visit-beacon.ts`).
|
||||
기존 `/v1/` 프록시로 닿으므로 **nginx 설정은 손대지 않는다.** 사람 방문만 `site_page_views` 에 쌓인다
|
||||
(마이그레이션 `0025`).
|
||||
|
||||
★ **기존 발행 사이트는 재발행해야 집계가 시작된다.** 9/15 발행 버전 전환 뒤로 기동은 공용 자산만 깔고
|
||||
(`prerender --seed-assets`) 이미 구워진 HTML 의 번들 주소는 바꾸지 않는다 — 비콘이 든 새 번들은 깔리지만,
|
||||
옛 HTML 은 옛 번들을 계속 부른다. 사이트마다 **다시 발행**(빌더의 발행 — 새 버전을 굽는다)해야 한다.
|
||||
★ `scripts/republish_all.py` 는 굽지 않는다 — 이미 구운 `out/` 을 Azure 로 다시 올릴 뿐이라 비콘이 안 들어간다.
|
||||
전체 재굽기는 0절이 금지한다(배포 때 기존 HTML 을 고치지 않는다).
|
||||
|
||||
★ 운영자가 자기 방문을 빼려면 그 브라우저 콘솔에서 `localStorage.setItem('web4ai.stats.disabled', '1')`.
|
||||
@@ -13,6 +13,14 @@
|
||||
# ★ 산출물은 named volume(site-out)으로 들어온다. 프리렌더가 쓰고 여기서 읽기만 한다 —
|
||||
# 호스트 경로가 등장하지 않으므로 재배포로 코드를 갈아엎어도 사이트가 죽지 않는다.
|
||||
|
||||
# 크롤러 기록에서 뺄 요청 — /s/ 아래의 사진·스크립트·JSON 같은 파일.
|
||||
# ★ $uri 가 아니라 $request_uri 를 본다. mirror 하위 요청 안에서 $uri 는 `/_track_hit` 이 된다.
|
||||
# ★ 정규식에 `{n}` 수량자를 쓰지 않는다 — nginx 가 `{` 를 블록 구분자로 먼저 읽는다.
|
||||
map $request_uri $track_skip {
|
||||
default 0;
|
||||
"~^/s/[^?]*\.[A-Za-z0-9]+(\?.*)?$" 1;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
@@ -82,6 +90,9 @@ server {
|
||||
|
||||
# ^~ 로 잡아 아래 정규식 location 들이 끼어들지 못하게 한다.
|
||||
location ^~ /s/ {
|
||||
# 봇 요청을 백엔드에 한 부 복사한다(크롤러 통계). 응답은 기다리지 않고 나간다.
|
||||
mirror /_track_hit;
|
||||
mirror_request_body off;
|
||||
# ★ `/s/<slug>/`(끝 슬래시) 를 위해 필요하다. try_files 의 첫 인자 `$uri` 가 끝
|
||||
# 슬래시면 nginx 는 **디렉토리 검사**로 읽고, 디렉토리가 있으면 거기서 멈춘다 —
|
||||
# index 지시자가 없으면 그 순간 403 이다(=404 로도 안 떨어진다).
|
||||
@@ -128,15 +139,41 @@ server {
|
||||
# 발행하면 곧바로 반영되어야 한다. 길게 캐시하면 새 사업장이 사이트맵에 들어가도
|
||||
# 크롤러가 옛 파일을 계속 본다.
|
||||
location = /robots.txt {
|
||||
mirror /_track_hit;
|
||||
mirror_request_body off;
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /sitemap.xml {
|
||||
mirror /_track_hit;
|
||||
mirror_request_body off;
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── 크롤러 기록 (mirror 수신) ──────────────────────────────
|
||||
# 크롤러는 JS 를 실행하지 않아 브라우저 트래커로는 안 잡힌다. 요청 시점에 복사본을 백엔드로
|
||||
# 넘기고 UA 판별·저장은 백엔드가 한다(services/track_service.py).
|
||||
# ★ /internal 은 아래 API location(^/(v1/|…))에 안 걸리므로 밖에서 직접 부를 길이 없다.
|
||||
# ★ nginx 는 같은 연결의 다음 요청 전에 mirror 가 끝나길 기다린다 — 타임아웃을 짧게 둔다.
|
||||
location = /_track_hit {
|
||||
internal;
|
||||
access_log off;
|
||||
if ($track_skip) {
|
||||
return 204;
|
||||
}
|
||||
proxy_pass $api/internal/track/hit;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header X-Original-URI $request_uri;
|
||||
proxy_set_header User-Agent $http_user_agent;
|
||||
# 앞단 Apache 가 붙인 값을 그대로 넘긴다 — $remote_addr 는 늘 Apache 다.
|
||||
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_read_timeout 2s;
|
||||
}
|
||||
|
||||
# ── API ────────────────────────────────────────────────────
|
||||
# 앱과 같은 오리진이라 프리플라이트가 아예 발생하지 않는다.
|
||||
location ^~ /v1/social/ {
|
||||
|
||||
Generated
+417
-72
@@ -23,9 +23,6 @@
|
||||
"admin": {
|
||||
"name": "@o2o/admin",
|
||||
"version": "0.0.0",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@o2o/shared": "*",
|
||||
"@tailwindcss/vite": "^4.1.14",
|
||||
@@ -176,6 +173,7 @@
|
||||
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.29.7",
|
||||
"@babel/generator": "^7.29.7",
|
||||
@@ -637,6 +635,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -1624,9 +1623,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1963,6 +1959,42 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit": {
|
||||
"version": "2.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.13.0.tgz",
|
||||
"integrity": "sha512-f6jwVRfwW30+tnllz4YcsHHpPYYOE7abcHkyUCovD+P7DyhdAI5prz2Fh/8TLhakjpN+7aIEion1s5L/tvlYlA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@standard-schema/utils": "^0.3.0",
|
||||
"immer": "^11.0.0",
|
||||
"redux": "^5.0.1",
|
||||
"redux-thunk": "^3.1.0",
|
||||
"reselect": "^5.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
|
||||
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-redux": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit/node_modules/immer": {
|
||||
"version": "11.1.21",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.21.tgz",
|
||||
"integrity": "sha512-bZSadeCPGdaY5/qRLgr6mDSH1ra21rD3rqpiWk7+QTr4ayYPTE9qZYdLh/NdPhMe0wSrTvHD/Lk8q5EwhUs0aw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/immer"
|
||||
}
|
||||
},
|
||||
"node_modules/@remix-run/node-fetch-server": {
|
||||
"version": "0.13.3",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/node-fetch-server/-/node-fetch-server-0.13.3.tgz",
|
||||
@@ -2062,9 +2094,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2078,9 +2107,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2094,9 +2120,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2110,9 +2133,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2126,9 +2146,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2142,9 +2159,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2158,9 +2172,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2174,9 +2185,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2190,9 +2198,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2206,9 +2211,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2222,9 +2224,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2238,9 +2237,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2254,9 +2250,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2402,8 +2395,8 @@
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@standard-schema/utils": {
|
||||
"version": "0.3.0",
|
||||
@@ -2857,9 +2850,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2876,9 +2866,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2895,9 +2882,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -2914,9 +2898,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -3083,6 +3064,69 @@
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
|
||||
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-color": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-ease": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
|
||||
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-interpolate": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
|
||||
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-color": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-path": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
|
||||
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-scale": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
|
||||
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-time": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-shape": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz",
|
||||
"integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-path": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-time": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
|
||||
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-timer": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
|
||||
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
@@ -3139,6 +3183,7 @@
|
||||
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
@@ -3167,6 +3212,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/use-sync-external-store": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
|
||||
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.68.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.68.0.tgz",
|
||||
@@ -3212,6 +3263,7 @@
|
||||
"integrity": "sha512-fHq2VC1kpyYfvEcbiMjOpySY4WS7voEp89yAThrHRX5sm9j2lzYppCb2umFMEed4fWcyeLjHxrz0mpjNBaBxMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.68.0",
|
||||
"@typescript-eslint/types": "8.68.0",
|
||||
@@ -3602,6 +3654,7 @@
|
||||
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -3625,6 +3678,7 @@
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -3657,6 +3711,7 @@
|
||||
"integrity": "sha512-V3wD15YHfHz6y0KdhYFjyy9vWtEVALT9UrxfN3zqlI6dMioHnJrqOYfyPKol3oqrnCM9uwkcdCwkJ0WUcbLMTQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"ajv": "^8.0.1"
|
||||
}
|
||||
@@ -3667,6 +3722,7 @@
|
||||
"integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ajv": "^8.0.0"
|
||||
},
|
||||
@@ -3901,6 +3957,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.11.12",
|
||||
"caniuse-lite": "^1.0.30001809",
|
||||
@@ -4118,6 +4175,7 @@
|
||||
"integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
@@ -4185,6 +4243,127 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"internmap": "1 - 2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-color": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
|
||||
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-ease": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
|
||||
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-format": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
|
||||
"integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-interpolate": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
|
||||
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-path": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
|
||||
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-scale": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
|
||||
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "2.10.0 - 3",
|
||||
"d3-format": "1 - 3",
|
||||
"d3-interpolate": "1.2.0 - 3",
|
||||
"d3-time": "2.1.1 - 3",
|
||||
"d3-time-format": "2 - 4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-shape": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
|
||||
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-path": "^3.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-time": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
|
||||
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "2 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-time-format": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
|
||||
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-time": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-timer": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
|
||||
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/data-view-buffer": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
|
||||
@@ -4257,6 +4436,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js-light": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
|
||||
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dedent": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz",
|
||||
@@ -4373,7 +4558,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -4632,6 +4818,18 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/es-toolkit": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz",
|
||||
"integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"docs",
|
||||
"benchmarks",
|
||||
"tests/types",
|
||||
"tests/browser-compat"
|
||||
]
|
||||
},
|
||||
"node_modules/es6-promise": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz",
|
||||
@@ -4710,6 +4908,7 @@
|
||||
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -4912,6 +5111,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventemitter3": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
|
||||
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/execa": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
|
||||
@@ -5629,6 +5834,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/internmap": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
|
||||
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/is-array-buffer": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
|
||||
@@ -6112,6 +6326,7 @@
|
||||
"integrity": "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.16.0"
|
||||
}
|
||||
@@ -6392,9 +6607,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -6415,9 +6627,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -6438,9 +6647,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -6461,9 +6667,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -7489,6 +7692,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
|
||||
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -7498,6 +7702,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
|
||||
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@@ -7510,6 +7715,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.86.0.tgz",
|
||||
"integrity": "sha512-4kbWJrh5jPZt1+YqVcXcGKffGcXV/XVbozknLh0Yjh0KhpoAkus21TAQhzRYqNwFkkObmnSvRlZZ3GT+ehoIrA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -7521,6 +7727,37 @@
|
||||
"react": "^16.8.0 || ^17 || ^18 || ^19"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.0.tgz",
|
||||
"integrity": "sha512-UpMYezM4v5/18F28aC66AEsjXIgE02kyEMH6yLdgLXu/UTfa1Ntwck/nNLrbqJsEXW7gPb0coNO9FQse9WTovA==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/react-redux": {
|
||||
"version": "9.3.0",
|
||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
|
||||
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/use-sync-external-store": "^0.0.6",
|
||||
"use-sync-external-store": "^1.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.2.25 || ^19",
|
||||
"react": "^18.0 || ^19",
|
||||
"redux": "^5.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"redux": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-refresh": {
|
||||
"version": "0.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
|
||||
@@ -7536,6 +7773,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.3.tgz",
|
||||
"integrity": "sha512-gyXgtdr5uACJ5b1Q4udzjVV+tb/rlHIMJKuJ0e89R4Kzgz47z/rgP0dIKxktqIEUhDHluGTPJJH/wRha7CyqsA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
"set-cookie-parser": "^2.6.0"
|
||||
@@ -7567,6 +7805,62 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/recharts": {
|
||||
"version": "3.10.1",
|
||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.10.1.tgz",
|
||||
"integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"www"
|
||||
],
|
||||
"dependencies": {
|
||||
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
|
||||
"clsx": "^2.1.1",
|
||||
"decimal.js-light": "^2.5.1",
|
||||
"es-toolkit": "^1.39.3",
|
||||
"eventemitter3": "^5.0.1",
|
||||
"immer": "^11.1.8",
|
||||
"react-redux": "8.x.x || 9.x.x",
|
||||
"reselect": "5.2.0",
|
||||
"tiny-invariant": "^1.3.3",
|
||||
"use-sync-external-store": "^1.2.2",
|
||||
"victory-vendor": "^37.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/recharts/node_modules/immer": {
|
||||
"version": "11.1.21",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.21.tgz",
|
||||
"integrity": "sha512-bZSadeCPGdaY5/qRLgr6mDSH1ra21rD3rqpiWk7+QTr4ayYPTE9qZYdLh/NdPhMe0wSrTvHD/Lk8q5EwhUs0aw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/immer"
|
||||
}
|
||||
},
|
||||
"node_modules/redux": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/redux-thunk": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
|
||||
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"redux": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect.getprototypeof": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
||||
@@ -7641,6 +7935,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reselect": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
|
||||
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/resolve-from": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
||||
@@ -8301,6 +8601,12 @@
|
||||
"url": "https://opencollective.com/webpack"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-invariant": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
@@ -8356,6 +8662,7 @@
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -8540,6 +8847,7 @@
|
||||
"integrity": "sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@gerrit0/mini-shiki": "^3.23.0",
|
||||
"lunr": "^2.3.9",
|
||||
@@ -8629,6 +8937,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -8752,6 +9061,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/use-sync-external-store": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
|
||||
"integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/utility-types": {
|
||||
"version": "3.11.0",
|
||||
"resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",
|
||||
@@ -8768,6 +9086,7 @@
|
||||
"integrity": "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"typescript": ">=5"
|
||||
},
|
||||
@@ -8787,11 +9106,34 @@
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/victory-vendor": {
|
||||
"version": "37.3.6",
|
||||
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
|
||||
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
|
||||
"license": "MIT AND ISC",
|
||||
"dependencies": {
|
||||
"@types/d3-array": "^3.0.3",
|
||||
"@types/d3-ease": "^3.0.0",
|
||||
"@types/d3-interpolate": "^3.0.1",
|
||||
"@types/d3-scale": "^4.0.2",
|
||||
"@types/d3-shape": "^3.1.0",
|
||||
"@types/d3-time": "^3.0.0",
|
||||
"@types/d3-timer": "^3.0.0",
|
||||
"d3-array": "^3.1.6",
|
||||
"d3-ease": "^3.0.1",
|
||||
"d3-interpolate": "^3.0.1",
|
||||
"d3-scale": "^4.0.2",
|
||||
"d3-shape": "^3.1.0",
|
||||
"d3-time": "^3.0.0",
|
||||
"d3-timer": "^3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -8913,6 +9255,7 @@
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -9271,6 +9614,7 @@
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
|
||||
"integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
@@ -9338,6 +9682,7 @@
|
||||
"react-dom": "^19.0.1",
|
||||
"react-hook-form": "^7.79.0",
|
||||
"react-router": "^7.17.0",
|
||||
"recharts": "^3.10.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
|
||||
@@ -357,6 +357,34 @@ CREATE TABLE IF NOT EXISTS public.alert_outbox (
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.site_crawler_hits (
|
||||
hit_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
site_id uuid NULL, -- robots·sitemap·없는 슬러그는 NULL
|
||||
path TEXT NOT NULL,
|
||||
kind VARCHAR(10) NOT NULL, -- page · robots · sitemap
|
||||
bot VARCHAR(40) NULL, -- 목록 밖(other)이면 NULL
|
||||
vendor VARCHAR(40) NULL,
|
||||
purpose VARCHAR(20) NOT NULL, -- training · search · user-fetch · search-engine · other
|
||||
user_agent TEXT NOT NULL,
|
||||
ip VARCHAR(45) NULL, -- 목록 봇만(migrations/0024)
|
||||
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.site_page_views (
|
||||
view_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
site_id uuid NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
visitor_hash VARCHAR(64) NOT NULL, -- sha256(비밀값|IP|UA|KST 월), IP 원문 미저장(migrations/0025)
|
||||
referrer_domain VARCHAR(255) NULL,
|
||||
utm_source VARCHAR(100) NULL,
|
||||
device VARCHAR(10) NOT NULL, -- desktop · mobile · tablet
|
||||
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.place_posts (
|
||||
post_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
place_id uuid NOT NULL,
|
||||
@@ -584,6 +612,15 @@ CREATE INDEX IF NOT EXISTS ix_alert_outbox_pending ON public.alert_outbox (statu
|
||||
CREATE INDEX IF NOT EXISTS ix_alert_outbox_dedupe ON public.alert_outbox (dedupe_key, created_at DESC)
|
||||
WHERE dedupe_key IS NOT NULL;
|
||||
|
||||
-- site_crawler_hits — 사이트별 기간 조회 · 전체 기간 조회 · 봇별 조회(migrations/0024).
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_site ON public.site_crawler_hits (site_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_created ON public.site_crawler_hits (created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_bot ON public.site_crawler_hits (bot, created_at);
|
||||
|
||||
-- site_page_views — 사이트별·전체 기간 조회(migrations/0025).
|
||||
CREATE INDEX IF NOT EXISTS ix_site_page_views_site ON public.site_page_views (site_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_page_views_created ON public.site_page_views (created_at);
|
||||
|
||||
-- ============================================================
|
||||
-- 마이그레이션 기준선(baseline)
|
||||
-- ============================================================
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
-- 0024 · site_crawler_hits — 봇 요청 기록(사이트 트래픽 통계 1단계)
|
||||
--
|
||||
-- ★ 크롤러는 JS 를 실행하지 않아 브라우저 트래커로는 안 잡힌다. nginx 가 /s/·robots.txt·
|
||||
-- sitemap.xml 요청을 mirror 로 백엔드에 넘기고(nginx/site.conf `_track_hit`), 백엔드가 UA 로
|
||||
-- 봇만 골라 여기에 1건 = 1행으로 쌓는다. 집계 표는 두지 않는다 — 조회 때 GROUP BY 한다.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.site_crawler_hits (
|
||||
hit_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
site_id uuid NULL,
|
||||
path TEXT NOT NULL,
|
||||
kind VARCHAR(10) NOT NULL,
|
||||
bot VARCHAR(40) NULL,
|
||||
vendor VARCHAR(40) NULL,
|
||||
purpose VARCHAR(20) NOT NULL,
|
||||
user_agent TEXT NOT NULL,
|
||||
ip VARCHAR(45) NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN public.site_crawler_hits.site_id IS
|
||||
'robots·sitemap 과 없는 슬러그는 NULL';
|
||||
COMMENT ON COLUMN public.site_crawler_hits.kind IS 'page · robots · sitemap';
|
||||
COMMENT ON COLUMN public.site_crawler_hits.purpose IS
|
||||
'training · search · user-fetch · search-engine · other(목록 밖 봇)';
|
||||
COMMENT ON COLUMN public.site_crawler_hits.ip IS
|
||||
'목록 봇만 저장 — other 에는 봇을 흉내 낸 사람이 섞일 수 있다';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_site ON public.site_crawler_hits (site_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_created ON public.site_crawler_hits (created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_bot ON public.site_crawler_hits (bot, created_at);
|
||||
@@ -0,0 +1,24 @@
|
||||
-- 0025 · site_page_views — 사람 페이지뷰(사이트 트래픽 통계 2단계)
|
||||
--
|
||||
-- ★ 발행 사이트 부트 코드가 hydrate 직후 /v1/track/view 로 비콘을 보낸다. 쿠키·식별자를 브라우저에
|
||||
-- 두지 않고, 방문자 구분은 sha256(비밀값|IP|UA|KST 월) 해시로만 한다 — IP 원문은 저장하지 않는다.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.site_page_views (
|
||||
view_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
site_id uuid NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
visitor_hash VARCHAR(64) NOT NULL,
|
||||
referrer_domain VARCHAR(255) NULL,
|
||||
utm_source VARCHAR(100) NULL,
|
||||
device VARCHAR(10) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN public.site_page_views.visitor_hash IS
|
||||
'sha256(비밀값|IP|UA|KST 월) — IP 원문은 저장하지 않는다';
|
||||
COMMENT ON COLUMN public.site_page_views.device IS 'desktop · mobile · tablet';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_site_page_views_site ON public.site_page_views (site_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS ix_site_page_views_created ON public.site_page_views (created_at);
|
||||
@@ -447,6 +447,48 @@ class alert_outbox(MainTableMixin, MAIN_BASE):
|
||||
resolved_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
|
||||
class site_crawler_hits(MainTableMixin, MAIN_BASE):
|
||||
"""봇 요청 1건 = 1행 — nginx mirror 가 /internal/track/hit 로 넘긴 것. 기한 없이 보관한다(Umami 와 같다)."""
|
||||
|
||||
__tablename__ = "site_crawler_hits"
|
||||
__table_args__ = (
|
||||
Index("ix_site_crawler_hits_site", "site_id", "created_at"),
|
||||
Index("ix_site_crawler_hits_created", "created_at"),
|
||||
Index("ix_site_crawler_hits_bot", "bot", "created_at"),
|
||||
)
|
||||
|
||||
hit_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
# robots·sitemap 은 오리진 공용이라, 없는 슬러그는 사이트를 못 찾아서 NULL 이다.
|
||||
site_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
path = Column(Text, nullable=False)
|
||||
kind = Column(String(10), nullable=False) # page · robots · sitemap
|
||||
bot = Column(String(40), nullable=True) # 목록 밖(other)이면 NULL
|
||||
vendor = Column(String(40), nullable=True)
|
||||
purpose = Column(String(20), nullable=False) # training · search · user-fetch · search-engine · other
|
||||
user_agent = Column(Text, nullable=False)
|
||||
# 목록 봇만 남긴다 — other 에는 봇 UA 를 흉내 낸 사람이 섞일 수 있다.
|
||||
ip = Column(String(45), nullable=True)
|
||||
|
||||
|
||||
class site_page_views(MainTableMixin, MAIN_BASE):
|
||||
"""사람 페이지뷰 1건 = 1행 — 발행 사이트 비콘(/v1/track/view). 쿠키 없이, IP 원문 없이 쌓는다."""
|
||||
|
||||
__tablename__ = "site_page_views"
|
||||
__table_args__ = (
|
||||
Index("ix_site_page_views_site", "site_id", "created_at"),
|
||||
Index("ix_site_page_views_created", "created_at"),
|
||||
)
|
||||
|
||||
view_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
site_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
path = Column(Text, nullable=False)
|
||||
# sha256(비밀값|IP|UA|KST 월) — 달이 바뀌면 같은 사람도 새 방문자다(Umami 와 같다). IP 는 저장하지 않는다.
|
||||
visitor_hash = Column(String(64), nullable=False)
|
||||
referrer_domain = Column(String(255), nullable=True)
|
||||
utm_source = Column(String(100), nullable=True)
|
||||
device = Column(String(10), nullable=False) # desktop · mobile · tablet
|
||||
|
||||
|
||||
class site_sections(MainTableMixin, MAIN_BASE):
|
||||
"""섹션 하나의 콘텐츠."""
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import and_, distinct, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, site_crawler_hits, sites
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from services.crawler_detect import AI_PURPOSES
|
||||
|
||||
|
||||
class ICrawlerHitCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
||||
"""(ErrorType, [Row(place_id, name, site_id, domain)]) — 슬러그 → site_id 표 재료."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]:
|
||||
"""기간 [start, end) 집계. 키: summary·daily·bots + (overall) sites·root_files·others | (사이트) pages·recent."""
|
||||
pass
|
||||
|
||||
|
||||
class CrawlerHitCRUD(ICrawlerHitCRUD):
|
||||
async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, hit)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
query = (
|
||||
select(places.place_id, places.name, sites.site_id, sites.domain)
|
||||
.join(sites, and_(sites.place_id == places.place_id, sites.deleted == False)) # noqa: E712
|
||||
.where(places.deleted == False) # noqa: E712
|
||||
)
|
||||
return await DB_SESSION_MNG.execute(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]:
|
||||
try:
|
||||
h = site_crawler_hits
|
||||
where = and_(h.deleted == False, h.created_at >= start, h.created_at < end) # noqa: E712
|
||||
if site_id is not None:
|
||||
where = and_(where, h.site_id == site_id)
|
||||
hits = func.count().label("hits")
|
||||
ai_hits = func.count().filter(h.purpose.in_(AI_PURPOSES)).label("ai_hits")
|
||||
last_at = func.max(h.created_at).label("last_at")
|
||||
# GROUP BY 는 라벨("day")로 건다 — 같은 식을 두 번 쓰면 'Asia/Seoul' 이 다른 바인드 파라미터가 돼
|
||||
# Postgres 가 "must appear in the GROUP BY clause" 로 거부한다.
|
||||
day = func.date(func.timezone("Asia/Seoul", h.created_at)).label("day")
|
||||
|
||||
queries = {
|
||||
"summary": select(hits, ai_hits, func.count(distinct(h.bot)).label("bots"), last_at).where(where),
|
||||
"daily": select(day, h.purpose, hits).where(where).group_by("day", h.purpose).order_by("day", h.purpose),
|
||||
"bots": (
|
||||
select(h.bot, h.vendor, h.purpose, hits, last_at)
|
||||
.where(where, h.bot.isnot(None))
|
||||
.group_by(h.bot, h.vendor, h.purpose)
|
||||
.order_by(func.count().desc())
|
||||
.limit(50)
|
||||
),
|
||||
}
|
||||
if overall:
|
||||
queries["sites"] = (
|
||||
select(h.site_id, places.place_id, places.name, hits, ai_hits, last_at)
|
||||
.join(sites, sites.site_id == h.site_id)
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.where(where)
|
||||
.group_by(h.site_id, places.place_id, places.name)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
)
|
||||
queries["root_files"] = (
|
||||
select(h.kind, h.bot, h.purpose, hits, last_at)
|
||||
.where(where, h.kind.in_(("robots", "sitemap")))
|
||||
.group_by(h.kind, h.bot, h.purpose)
|
||||
.order_by(h.kind, func.count().desc())
|
||||
)
|
||||
queries["others"] = (
|
||||
select(h.user_agent, hits, last_at)
|
||||
.where(where, h.purpose == "other")
|
||||
.group_by(h.user_agent)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
)
|
||||
else:
|
||||
queries["pages"] = (
|
||||
select(h.path, hits, last_at)
|
||||
.where(where, h.kind == "page")
|
||||
.group_by(h.path)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
)
|
||||
queries["recent"] = (
|
||||
select(h.created_at, h.kind, h.bot, h.vendor, h.purpose, h.path)
|
||||
.where(where)
|
||||
.order_by(h.created_at.desc())
|
||||
.limit(50)
|
||||
)
|
||||
|
||||
out: dict = {}
|
||||
for key, query in queries.items():
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
out[key] = list(rows)
|
||||
return ErrorType.SUCCESS, out
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
@@ -0,0 +1,91 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import and_, distinct, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, site_page_views, sites
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
class IVisitCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, realtime_since: datetime, site_id,
|
||||
overall: bool) -> Tuple[ErrorType, dict]:
|
||||
"""기간 [start, end) 집계 + realtime_since 이후 고유 방문자. 키: realtime·summary·daily·referrers·devices + (overall) sites | (사이트) pages·utm."""
|
||||
pass
|
||||
|
||||
|
||||
class VisitCRUD(IVisitCRUD):
|
||||
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, view)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, realtime_since: datetime, site_id,
|
||||
overall: bool) -> Tuple[ErrorType, dict]:
|
||||
try:
|
||||
v = site_page_views
|
||||
scope = v.deleted == False # noqa: E712
|
||||
if site_id is not None:
|
||||
scope = and_(scope, v.site_id == site_id)
|
||||
where = and_(scope, v.created_at >= start, v.created_at < end)
|
||||
views = func.count().label("views")
|
||||
visitors = func.count(distinct(v.visitor_hash)).label("visitors")
|
||||
# GROUP BY 는 라벨로 — 같은 식 두 번이면 'Asia/Seoul' 바인드가 갈라져 Postgres 가 거부한다(크롤러 통계와 같은 이유).
|
||||
day = func.date(func.timezone("Asia/Seoul", v.created_at)).label("day")
|
||||
queries = {
|
||||
# 실시간은 기간 선택과 무관하다 — "지금 몇 명" 을 묻는 숫자다.
|
||||
"realtime": select(func.count(distinct(v.visitor_hash)).label("n")).where(scope, v.created_at >= realtime_since),
|
||||
"summary": select(views, visitors, func.max(v.created_at).label("last_at")).where(where),
|
||||
"daily": select(day, views, visitors).where(where).group_by("day").order_by("day"),
|
||||
"referrers": (
|
||||
select(v.referrer_domain, views)
|
||||
.where(where, v.referrer_domain.isnot(None))
|
||||
.group_by(v.referrer_domain)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
),
|
||||
"devices": select(v.device, views).where(where).group_by(v.device).order_by(func.count().desc()),
|
||||
}
|
||||
if overall:
|
||||
queries["sites"] = (
|
||||
select(v.site_id, places.place_id, places.name, views, visitors)
|
||||
.join(sites, sites.site_id == v.site_id)
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.where(where)
|
||||
.group_by(v.site_id, places.place_id, places.name)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
)
|
||||
else:
|
||||
queries["pages"] = (
|
||||
select(v.path, views, visitors).where(where).group_by(v.path).order_by(func.count().desc()).limit(20)
|
||||
)
|
||||
queries["utm"] = (
|
||||
select(v.utm_source, views)
|
||||
.where(where, v.utm_source.isnot(None))
|
||||
.group_by(v.utm_source)
|
||||
.order_by(func.count().desc())
|
||||
.limit(20)
|
||||
)
|
||||
|
||||
out: dict = {}
|
||||
for key, query in queries.items():
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, {}
|
||||
out[key] = list(rows)
|
||||
return ErrorType.SUCCESS, out
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
@@ -26,6 +26,7 @@ import router.v1.site.post
|
||||
import router.v1.site.review
|
||||
import router.v1.local.local
|
||||
import router.v1.ops.ops
|
||||
import router.v1.track.track
|
||||
import router.v1.social.social
|
||||
import router.v1.social.oauth
|
||||
import router.v1.agent.kakao
|
||||
@@ -127,6 +128,10 @@ app.include_router(router.v1.site.review.router)
|
||||
app.include_router(router.v1.local.local.router)
|
||||
app.include_router(router.v1.local.local.weather_router)
|
||||
app.include_router(router.v1.ops.ops.router)
|
||||
# nginx mirror 전용 수집점(/internal — 외부 비노출).
|
||||
app.include_router(router.v1.track.track.router)
|
||||
# 발행 사이트 방문 비콘(공개).
|
||||
app.include_router(router.v1.track.track.public_router)
|
||||
|
||||
app.include_router(router.v1.social.social.router)
|
||||
app.include_router(router.v1.social.oauth.router)
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.models.gmodel import PageParams
|
||||
from router.v1.validator.dependencies import RemoveNoneResponse, RequireDeveloper
|
||||
from services.crawler_stats_service import CrawlerStatsService
|
||||
from services.ops_service import OpsService
|
||||
from .protocol import Res_OpsSites, Res_OpsUsers
|
||||
from services.visit_stats_service import VisitStatsService
|
||||
from .protocol import Res_CrawlerStats, Res_OpsSites, Res_OpsUsers, Res_VisitStats
|
||||
|
||||
# 내부 운영(개발자) 전용 조회 — 회사 스코프를 걷어낸 전 계정 사이트·유저 목록.
|
||||
router = APIRouter(prefix="/v1/ops", tags=["Ops"])
|
||||
@@ -28,3 +33,47 @@ async def list_users(
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.list_users(pg, search))
|
||||
|
||||
|
||||
@router.get(path="/stats/crawlers", response_model=Res_CrawlerStats, summary="전체 크롤러 통계(개발자 전용)")
|
||||
async def crawler_stats(
|
||||
service: CrawlerStatsService = Depends(),
|
||||
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
|
||||
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.overall(date_from, date_to))
|
||||
|
||||
|
||||
@router.get(path="/sites/{place_id}/stats/crawlers", response_model=Res_CrawlerStats,
|
||||
summary="사이트별 크롤러 통계(개발자 전용)")
|
||||
async def site_crawler_stats(
|
||||
place_id: uuid.UUID,
|
||||
service: CrawlerStatsService = Depends(),
|
||||
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
|
||||
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.for_place(place_id, date_from, date_to))
|
||||
|
||||
|
||||
@router.get(path="/stats/visits", response_model=Res_VisitStats, summary="전체 방문 통계(개발자 전용)")
|
||||
async def visit_stats(
|
||||
service: VisitStatsService = Depends(),
|
||||
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
|
||||
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.overall(date_from, date_to))
|
||||
|
||||
|
||||
@router.get(path="/sites/{place_id}/stats/visits", response_model=Res_VisitStats,
|
||||
summary="사이트별 방문 통계(개발자 전용)")
|
||||
async def site_visit_stats(
|
||||
place_id: uuid.UUID,
|
||||
service: VisitStatsService = Depends(),
|
||||
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
|
||||
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
|
||||
_user=Depends(RequireDeveloper),
|
||||
):
|
||||
return RemoveNoneResponse(await service.for_place(place_id, date_from, date_to))
|
||||
@@ -1,9 +1,11 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import AuthProvider, PlaceCategory, PlaceStatus, SiteStatus, UserRole, UserStatus
|
||||
from common.models.gmodel import Res_PageProtocol, WebPacketProtocol
|
||||
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class OpsSiteData(WebPacketProtocol):
|
||||
@@ -49,3 +51,133 @@ class OpsUserData(WebPacketProtocol):
|
||||
|
||||
class Res_OpsUsers(Res_PageProtocol):
|
||||
users: list[OpsUserData] = []
|
||||
|
||||
|
||||
class CrawlerSummary(WebPacketProtocol):
|
||||
total: int = 0
|
||||
ai: int = 0 # training + search + user-fetch
|
||||
bots: int = 0 # 서로 다른 목록 봇 수
|
||||
last_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class CrawlerDaily(WebPacketProtocol):
|
||||
day: date # KST
|
||||
purpose: str
|
||||
hits: int
|
||||
|
||||
|
||||
class CrawlerBotRow(WebPacketProtocol):
|
||||
bot: Optional[str] = None
|
||||
vendor: Optional[str] = None
|
||||
purpose: str
|
||||
hits: int
|
||||
last_at: datetime
|
||||
|
||||
|
||||
class CrawlerSiteRow(WebPacketProtocol):
|
||||
site_id: uuid.UUID
|
||||
place_id: uuid.UUID
|
||||
name: str
|
||||
hits: int
|
||||
ai_hits: int
|
||||
last_at: datetime
|
||||
|
||||
|
||||
class CrawlerRootRow(WebPacketProtocol):
|
||||
kind: str # robots · sitemap
|
||||
bot: Optional[str] = None
|
||||
purpose: str
|
||||
hits: int
|
||||
last_at: datetime
|
||||
|
||||
|
||||
class CrawlerUaRow(WebPacketProtocol):
|
||||
user_agent: str
|
||||
hits: int
|
||||
last_at: datetime
|
||||
|
||||
|
||||
class CrawlerPathRow(WebPacketProtocol):
|
||||
path: str
|
||||
hits: int
|
||||
last_at: datetime
|
||||
|
||||
|
||||
class CrawlerHitRow(WebPacketProtocol):
|
||||
created_at: datetime
|
||||
kind: str
|
||||
bot: Optional[str] = None
|
||||
vendor: Optional[str] = None
|
||||
purpose: str
|
||||
path: str
|
||||
|
||||
|
||||
class Res_CrawlerStats(Res_WebPacketProtocol):
|
||||
"""전체(sites·root_files·others)와 사이트별(pages·recent)이 같은 모델을 쓴다 — 해당 없는 칸은 비어 있다."""
|
||||
|
||||
date_from: Optional[date] = None
|
||||
date_to: Optional[date] = None
|
||||
summary: CrawlerSummary = Field(default_factory=CrawlerSummary)
|
||||
daily: list[CrawlerDaily] = []
|
||||
bots: list[CrawlerBotRow] = []
|
||||
sites: list[CrawlerSiteRow] = []
|
||||
root_files: list[CrawlerRootRow] = []
|
||||
others: list[CrawlerUaRow] = []
|
||||
pages: list[CrawlerPathRow] = []
|
||||
recent: list[CrawlerHitRow] = []
|
||||
|
||||
|
||||
class VisitSummary(WebPacketProtocol):
|
||||
views: int = 0
|
||||
visitors: int = 0
|
||||
last_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class VisitDaily(WebPacketProtocol):
|
||||
day: date # KST
|
||||
views: int
|
||||
visitors: int
|
||||
|
||||
|
||||
class VisitSiteRow(WebPacketProtocol):
|
||||
site_id: uuid.UUID
|
||||
place_id: uuid.UUID
|
||||
name: str
|
||||
views: int
|
||||
visitors: int
|
||||
|
||||
|
||||
class VisitPathRow(WebPacketProtocol):
|
||||
path: str
|
||||
views: int
|
||||
visitors: int
|
||||
|
||||
|
||||
class VisitReferrerRow(WebPacketProtocol):
|
||||
domain: str
|
||||
views: int
|
||||
|
||||
|
||||
class VisitUtmRow(WebPacketProtocol):
|
||||
source: str
|
||||
views: int
|
||||
|
||||
|
||||
class VisitDeviceRow(WebPacketProtocol):
|
||||
device: str
|
||||
views: int
|
||||
|
||||
|
||||
class Res_VisitStats(Res_WebPacketProtocol):
|
||||
"""전체(sites)와 사이트별(pages·utm)이 같은 모델을 쓴다 — 해당 없는 칸은 비어 있다."""
|
||||
|
||||
date_from: Optional[date] = None
|
||||
date_to: Optional[date] = None
|
||||
realtime: int = 0 # 최근 5분 고유 방문자(기간 선택과 무관)
|
||||
summary: VisitSummary = Field(default_factory=VisitSummary)
|
||||
daily: list[VisitDaily] = []
|
||||
sites: list[VisitSiteRow] = []
|
||||
pages: list[VisitPathRow] = []
|
||||
referrers: list[VisitReferrerRow] = []
|
||||
utm: list[VisitUtmRow] = []
|
||||
devices: list[VisitDeviceRow] = []
|
||||
Whitespace-only changes.
@@ -0,0 +1,61 @@
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Request, Response
|
||||
|
||||
from common.logger import LOG
|
||||
from services.track_service import TrackService
|
||||
from services.visit_service import MAX_BEACON_BODY, VisitService
|
||||
|
||||
# nginx mirror 전용. /v1 밖에 두는 이유: nginx 는 /v1/ 만 백엔드로 넘기므로 밖에서 이 경로를 부를 길이 없다.
|
||||
# include_in_schema=False — orval 이 이 경로로 클라이언트를 만들지 않게.
|
||||
router = APIRouter(prefix="/internal/track", include_in_schema=False)
|
||||
|
||||
|
||||
async def _record(service: TrackService, uri: str, user_agent: str | None, xff: str | None) -> None:
|
||||
try:
|
||||
await service.record_hit(uri=uri, user_agent=user_agent, xff=xff)
|
||||
except Exception as ex: # noqa: BLE001 — 기록 실패가 크롤링 응답을 늦추거나 깨면 안 된다
|
||||
LOG.w(f"[track] 크롤러 기록 실패: {type(ex).__name__}: {ex}")
|
||||
|
||||
|
||||
# mirror 는 원래 요청의 메서드를 그대로 쓴다 — 봇의 HEAD 요청도 받는다.
|
||||
# ★ 저장은 응답을 보낸 **뒤** 백그라운드로 돈다. nginx 는 mirror 하위 요청이 끝나기 전까지 같은 연결의
|
||||
# 다음 요청을 읽지 않으므로, DB 를 기다렸다 204 를 주면 DB 가 느릴 때 그 연결의 다른 요청까지 늦어진다.
|
||||
@router.api_route("/hit", methods=["GET", "HEAD"], status_code=204)
|
||||
async def record_hit(request: Request, background: BackgroundTasks, service: TrackService = Depends()):
|
||||
background.add_task(
|
||||
_record,
|
||||
service,
|
||||
request.headers.get("x-original-uri", ""),
|
||||
request.headers.get("user-agent"),
|
||||
request.headers.get("x-forwarded-for"),
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# 발행 사이트 비콘 — 공개(인증 없음). nginx 가 /v1/ 를 백엔드로 넘기므로 발행 페이지와 같은 오리진이다.
|
||||
public_router = APIRouter(prefix="/v1/track", include_in_schema=False)
|
||||
|
||||
|
||||
async def _record_view(service: VisitService, body: bytes, user_agent: str | None, xff: str | None,
|
||||
client_host: str | None) -> None:
|
||||
try:
|
||||
await service.record_view(body, user_agent, xff, client_host)
|
||||
except Exception as ex: # noqa: BLE001 — 통계 실패가 방문자에게 오류로 보이면 안 된다
|
||||
LOG.w(f"[visit] 방문 기록 실패: {type(ex).__name__}: {ex}")
|
||||
|
||||
|
||||
# ★ sendBeacon 은 응답을 읽지 않는다 — 저장은 응답 뒤 백그라운드로(수집점 hit 과 같은 이유).
|
||||
@public_router.post("/view", status_code=204)
|
||||
async def record_view(request: Request, background: BackgroundTasks, service: VisitService = Depends()):
|
||||
# 크기 검사는 **읽기 전에** 한다 — 다 읽고 버리면 20MB 본문(nginx 상한)도 매번 메모리에 오른다.
|
||||
body = b""
|
||||
async for chunk in request.stream():
|
||||
body += chunk
|
||||
if len(body) > MAX_BEACON_BODY:
|
||||
return Response(status_code=204)
|
||||
background.add_task(
|
||||
_record_view, service, body,
|
||||
request.headers.get("user-agent"),
|
||||
request.headers.get("x-forwarded-for"),
|
||||
request.client.host if request.client else None,
|
||||
)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""자칭 크롤러 판별 — UA 만 본다.
|
||||
|
||||
UA 는 위조할 수 있다. 여기서 세는 것은 "자칭 크롤러"이고 IP 대역으로 진위를 확인하지 않는다.
|
||||
목록은 AEORanking(킹서버 AEORankingPlatform/frontend/src/lib/analytics/ai-crawlers.ts)과 같게 둔다 —
|
||||
두 서비스의 통계를 나란히 놓고 볼 때 분류가 갈리면 비교가 안 된다.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
# training: 모델 학습 수집 · search: AI 답변 엔진 색인 · user-fetch: 사용자가 물어서 그 자리에서 여는 요청
|
||||
# search-engine: 전통 검색 크롤러(AI 답변에도 쓰인다) · other: 목록 밖이지만 스스로 봇이라 밝힌 것
|
||||
AI_PURPOSES = ("training", "search", "user-fetch")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CrawlerMatch:
|
||||
bot: str | None
|
||||
vendor: str | None
|
||||
purpose: str
|
||||
|
||||
|
||||
_KNOWN: tuple[tuple[str, str, str, re.Pattern], ...] = tuple(
|
||||
(bot, vendor, purpose, re.compile(pattern, re.IGNORECASE))
|
||||
for bot, vendor, purpose, pattern in (
|
||||
("GPTBot", "OpenAI", "training", r"\bGPTBot\b"),
|
||||
("OAI-SearchBot", "OpenAI", "search", r"\bOAI-SearchBot\b"),
|
||||
("ChatGPT-User", "OpenAI", "user-fetch", r"\bChatGPT-User\b"),
|
||||
("ClaudeBot", "Anthropic", "training", r"\bClaudeBot\b"),
|
||||
("Claude-SearchBot", "Anthropic", "search", r"\bClaude-SearchBot\b"),
|
||||
("Claude-User", "Anthropic", "user-fetch", r"\bClaude-User\b"),
|
||||
("PerplexityBot", "Perplexity", "search", r"\bPerplexityBot\b"),
|
||||
("Perplexity-User", "Perplexity", "user-fetch", r"\bPerplexity-User\b"),
|
||||
("meta-externalagent", "Meta", "training", r"\bmeta-externalagent\b"),
|
||||
("meta-externalfetcher", "Meta", "user-fetch", r"\bmeta-externalfetcher\b"),
|
||||
("MistralAI-User", "Mistral", "user-fetch", r"\bMistralAI-User\b"),
|
||||
("DuckAssistBot", "DuckDuckGo", "search", r"\bDuckAssistBot\b"),
|
||||
("Amazonbot", "Amazon", "search", r"\bAmazonbot\b"),
|
||||
("Bytespider", "ByteDance", "training", r"\bBytespider\b"),
|
||||
("CCBot", "Common Crawl", "training", r"\bCCBot\b"),
|
||||
("Googlebot", "Google", "search-engine", r"\bGooglebot\b"),
|
||||
("bingbot", "Microsoft", "search-engine", r"\bbingbot\b"),
|
||||
("Applebot", "Apple", "search-engine", r"\bApplebot\b"),
|
||||
("Yeti", "Naver", "search-engine", r"\bYeti/"),
|
||||
)
|
||||
)
|
||||
|
||||
# 목록에 없는 새 봇을 놓치지 않으려고 둔다 — 쌓인 UA 를 보고 목록에 올린다.
|
||||
# HeadlessChrome 은 일부러 안 넣는다: 우리 목업 검증 스크립트가 그 UA 로 돈다.
|
||||
_GENERIC = re.compile(r"bot|crawl|spider|slurp|externalhit|fetch", re.IGNORECASE)
|
||||
|
||||
_OTHER = CrawlerMatch(None, None, "other")
|
||||
|
||||
|
||||
def classify(user_agent: str | None) -> CrawlerMatch | None:
|
||||
if not user_agent:
|
||||
return None
|
||||
for bot, vendor, purpose, pattern in _KNOWN:
|
||||
if pattern.search(user_agent):
|
||||
return CrawlerMatch(bot, vendor, purpose)
|
||||
if _GENERIC.search(user_agent):
|
||||
return _OTHER
|
||||
return None
|
||||
@@ -0,0 +1,93 @@
|
||||
"""사이트관리 크롤러 통계 — 기간을 KST 날짜로 해석하고 CRUD 집계를 응답 모델로 옮긴다."""
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import site_crawler_hits, sites
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
|
||||
from crud.site_crud import ISiteCRUD, SiteCRUD
|
||||
from router.v1.ops.protocol import (
|
||||
CrawlerBotRow, CrawlerDaily, CrawlerHitRow, CrawlerPathRow, CrawlerRootRow, CrawlerSiteRow,
|
||||
CrawlerSummary, CrawlerUaRow, Res_CrawlerStats,
|
||||
)
|
||||
|
||||
# 한국은 서머타임이 없다 — zoneinfo(Windows 에선 tzdata 패키지가 따로 필요)를 쓰지 않고 고정 오프셋으로 둔다.
|
||||
KST = timezone(timedelta(hours=9))
|
||||
DEFAULT_DAYS = 7
|
||||
MAX_DAYS = 366
|
||||
|
||||
|
||||
def resolve_range(date_from: date | None, date_to: date | None, today: date | None = None) -> tuple[date, date] | None:
|
||||
"""빈 값은 '오늘(KST)까지 7일'. 뒤집혔거나 366일을 넘으면 None — 원본 GROUP BY 라 무한정 넓히지 않는다."""
|
||||
to = date_to or today or datetime.now(KST).date()
|
||||
frm = date_from or (to - timedelta(days=DEFAULT_DAYS - 1))
|
||||
if frm > to or (to - frm).days >= MAX_DAYS:
|
||||
return None
|
||||
return frm, to
|
||||
|
||||
|
||||
def _bounds(frm: date, to: date) -> tuple[datetime, datetime]:
|
||||
return datetime.combine(frm, time.min, tzinfo=KST), datetime.combine(to + timedelta(days=1), time.min, tzinfo=KST)
|
||||
|
||||
|
||||
class CrawlerStatsService:
|
||||
def __init__(self, crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD), site_crud: ISiteCRUD = Depends(SiteCRUD)):
|
||||
self.crud = crud
|
||||
self.site_crud = site_crud
|
||||
|
||||
async def overall(self, date_from: date | None, date_to: date | None) -> Res_CrawlerStats:
|
||||
return await self._build(date_from, date_to, site_id=None, overall=True)
|
||||
|
||||
async def for_place(self, place_id, date_from: date | None, date_to: date | None) -> Res_CrawlerStats:
|
||||
err_type, site = await DB_SESSION_MNG.execute_lambda(
|
||||
sites.DBType(), DBWRType.DB_READ.value, lambda s: self.site_crud.get_site_by_place(s, place_id)
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res = Res_CrawlerStats()
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
if site is None:
|
||||
# 사이트를 아직 안 만든 사업장 — 크롤링될 주소가 없으니 빈 통계가 맞는 답이다.
|
||||
rng = resolve_range(date_from, date_to)
|
||||
return Res_CrawlerStats(date_from=rng[0], date_to=rng[1]) if rng else self._invalid()
|
||||
return await self._build(date_from, date_to, site_id=site.site_id, overall=False)
|
||||
|
||||
@staticmethod
|
||||
def _invalid() -> Res_CrawlerStats:
|
||||
res = Res_CrawlerStats()
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
async def _build(self, date_from, date_to, site_id, overall: bool) -> Res_CrawlerStats:
|
||||
rng = resolve_range(date_from, date_to)
|
||||
if rng is None:
|
||||
return self._invalid()
|
||||
frm, to = rng
|
||||
start, end = _bounds(frm, to)
|
||||
err_type, data = await DB_SESSION_MNG.execute_lambda(
|
||||
site_crawler_hits.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.stats(s, start, end, site_id, overall),
|
||||
)
|
||||
res = Res_CrawlerStats(date_from=frm, date_to=to)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
summary = data["summary"][0]
|
||||
res.summary = CrawlerSummary(total=summary.hits, ai=summary.ai_hits, bots=summary.bots, last_at=summary.last_at)
|
||||
res.daily = [CrawlerDaily(day=r.day, purpose=r.purpose, hits=r.hits) for r in data["daily"]]
|
||||
res.bots = [CrawlerBotRow(bot=r.bot, vendor=r.vendor, purpose=r.purpose, hits=r.hits, last_at=r.last_at)
|
||||
for r in data["bots"]]
|
||||
if overall:
|
||||
res.sites = [CrawlerSiteRow(site_id=r.site_id, place_id=r.place_id, name=r.name, hits=r.hits,
|
||||
ai_hits=r.ai_hits, last_at=r.last_at) for r in data["sites"]]
|
||||
res.root_files = [CrawlerRootRow(kind=r.kind, bot=r.bot, purpose=r.purpose, hits=r.hits, last_at=r.last_at)
|
||||
for r in data["root_files"]]
|
||||
res.others = [CrawlerUaRow(user_agent=r.user_agent, hits=r.hits, last_at=r.last_at) for r in data["others"]]
|
||||
else:
|
||||
res.pages = [CrawlerPathRow(path=r.path, hits=r.hits, last_at=r.last_at) for r in data["pages"]]
|
||||
res.recent = [CrawlerHitRow(created_at=r.created_at, kind=r.kind, bot=r.bot, vendor=r.vendor,
|
||||
purpose=r.purpose, path=r.path) for r in data["recent"]]
|
||||
return res
|
||||
@@ -0,0 +1,111 @@
|
||||
"""nginx mirror 가 넘긴 요청 중 봇 요청을 기록한다(사이트 트래픽 통계 1단계)."""
|
||||
import re
|
||||
import time
|
||||
import unicodedata
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import site_crawler_hits
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
|
||||
from services.crawler_detect import classify
|
||||
from services.site_payload import publish_slug
|
||||
|
||||
# 발행·이름 변경이 반영되는 데 이 정도 늦어도 통계에는 문제가 없다.
|
||||
_SLUG_TTL_SEC = 60.0
|
||||
# 없는 슬러그(오타·내린 사이트)를 두드리는 봇이 매번 표를 다시 읽게 하지 않는다.
|
||||
_SLUG_RETRY_SEC = 5.0
|
||||
# nginx 가 1차로 끊지만(site.conf `$track_skip`), 설정이 어긋나도 사진 요청이 "페이지" 로 쌓이지 않게 한 번 더 본다.
|
||||
_FILE_EXT = re.compile(r"\.[A-Za-z0-9]+$")
|
||||
|
||||
|
||||
def hit_kind(uri: str) -> str | None:
|
||||
path = urlsplit(uri or "").path
|
||||
if path == "/robots.txt":
|
||||
return "robots"
|
||||
if path == "/sitemap.xml":
|
||||
return "sitemap"
|
||||
if path.startswith("/s/") and len(path) > 3 and not _FILE_EXT.search(path):
|
||||
return "page"
|
||||
return None
|
||||
|
||||
|
||||
def slug_of(uri: str) -> str | None:
|
||||
segment = urlsplit(uri or "").path[3:].split("/", 1)[0]
|
||||
if not segment:
|
||||
return None
|
||||
# 발행 슬러그는 NFC 다(site_payload.slugify). 브라우저·봇이 NFD 로 보내도 같은 사이트로 묶는다.
|
||||
return unicodedata.normalize("NFC", unquote(segment))
|
||||
|
||||
|
||||
def client_ip(xff: str | None) -> str | None:
|
||||
# 앞단 Apache 를 거치므로 nginx 의 $remote_addr 는 늘 Apache 다 — 첫 XFF 값이 실제 요청자다.
|
||||
first = (xff or "").split(",")[0].strip()
|
||||
return first[:45] or None
|
||||
|
||||
|
||||
class TrackService:
|
||||
# 요청마다 새 인스턴스(Depends)라 캐시는 클래스에 둔다.
|
||||
_slug_map: dict = {}
|
||||
_slug_loaded_at: float = float("-inf")
|
||||
|
||||
def __init__(self, crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD)):
|
||||
self.crud = crud
|
||||
|
||||
@classmethod
|
||||
def reset_cache(cls) -> None:
|
||||
cls._slug_map = {}
|
||||
cls._slug_loaded_at = float("-inf")
|
||||
|
||||
async def record_hit(self, uri: str, user_agent: str | None, xff: str | None) -> None:
|
||||
kind = hit_kind(uri)
|
||||
if kind is None:
|
||||
return
|
||||
match = classify(user_agent)
|
||||
if match is None:
|
||||
return
|
||||
site_id = await self.site_id_for(slug_of(uri)) if kind == "page" else None
|
||||
hit = site_crawler_hits(
|
||||
site_id=site_id,
|
||||
path=unquote(uri),
|
||||
kind=kind,
|
||||
bot=match.bot,
|
||||
vendor=match.vendor,
|
||||
purpose=match.purpose,
|
||||
user_agent=user_agent or "",
|
||||
ip=client_ip(xff) if match.bot else None,
|
||||
)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[site_crawler_hits.DBType()], [lambda s: self.crud.add_hit(s, hit)]
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[track] 크롤러 기록 저장 실패: {err.name} {match.bot or 'other'} {kind}")
|
||||
|
||||
async def site_id_for(self, slug: str | None):
|
||||
"""발행 슬러그 → site_id. 방문 비콘도 같은 표를 쓴다."""
|
||||
if not slug:
|
||||
return None
|
||||
cls = TrackService
|
||||
age = time.monotonic() - cls._slug_loaded_at
|
||||
if age > _SLUG_TTL_SEC or (slug not in cls._slug_map and age > _SLUG_RETRY_SEC):
|
||||
await self._reload_slugs()
|
||||
return cls._slug_map.get(slug)
|
||||
|
||||
async def _reload_slugs(self) -> None:
|
||||
cls = TrackService
|
||||
# 실패해도 시각은 옮긴다 — DB 가 죽은 동안 요청마다 다시 읽으러 가지 않게.
|
||||
cls._slug_loaded_at = time.monotonic()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
site_crawler_hits.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.list_site_slugs(s)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[track] 슬러그 표를 못 읽어 이전 표를 쓴다: {err.name}")
|
||||
return
|
||||
# 발행 주소와 같은 함수로 만든다 — domain 이 빈 사이트는 <이름>-<place_id 앞 8자> 로 발행된다.
|
||||
cls._slug_map = {
|
||||
publish_slug({"place_id": str(r.place_id), "name": r.name}, {"domain": r.domain}): r.site_id
|
||||
for r in rows
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
"""사람 방문 비콘의 판별 — DB 를 모르는 순수 함수."""
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from services.crawler_detect import classify
|
||||
|
||||
_KST = timezone(timedelta(hours=9))
|
||||
# 봇 목록에는 일부러 안 넣은 UA — 우리 목업 검증 스크립트가 이걸로 돈다(crawler_detect 주석).
|
||||
# 크롤러 통계에선 "사람" 쪽으로 빠지지만, 방문으로 세면 숫자가 부풀려진다.
|
||||
_NOT_A_VISITOR = re.compile(r"HeadlessChrome|Lighthouse|PageSpeed", re.IGNORECASE)
|
||||
_TABLET = re.compile(r"iPad|Tablet|Android(?!.*Mobile)", re.IGNORECASE)
|
||||
_MOBILE = re.compile(r"Mobi|iPhone|iPod|Android", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_human(user_agent: str | None) -> bool:
|
||||
if not user_agent:
|
||||
return False
|
||||
return classify(user_agent) is None and not _NOT_A_VISITOR.search(user_agent)
|
||||
|
||||
|
||||
def device_of(user_agent: str) -> str:
|
||||
if _TABLET.search(user_agent):
|
||||
return "tablet"
|
||||
if _MOBILE.search(user_agent):
|
||||
return "mobile"
|
||||
return "desktop"
|
||||
|
||||
|
||||
def referrer_domain(referrer: str | None) -> str | None:
|
||||
try:
|
||||
host = (urlsplit(referrer or "").hostname or "").lower()
|
||||
except ValueError:
|
||||
# "http://[" 같은 값 — 손님 브라우저가 보낸 값이라 깨져 있어도 유입만 비울 뿐이다.
|
||||
return None
|
||||
if not host or "." not in host:
|
||||
return None
|
||||
# www. 만 걷는다 — m.search.naver.com 같은 하위 도메인은 유입 경로를 가르는 정보다.
|
||||
return (host[4:] if host.startswith("www.") else host)[:255]
|
||||
|
||||
|
||||
def visitor_hash(secret: str, ip: str, user_agent: str, now: datetime) -> str:
|
||||
month = now.astimezone(_KST).strftime("%Y-%m")
|
||||
return hashlib.sha256(f"{secret}|{ip}|{user_agent}|{month}".encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""발행 사이트 비콘(/v1/track/view) → 사람 페이지뷰 1건 저장(사이트 트래픽 통계 2단계)."""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import site_page_views
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
|
||||
from crud.visit_crud import IVisitCRUD, VisitCRUD
|
||||
from services.track_service import TrackService, slug_of
|
||||
from services.visit_detect import device_of, is_human, referrer_domain, visitor_hash
|
||||
|
||||
# 비콘 본문은 경로·리퍼러·utm 셋뿐이다 — 이보다 크면 정상 요청이 아니다(라우터가 읽기 전에 끊는다).
|
||||
MAX_BEACON_BODY = 2048
|
||||
# 공개 엔드포인트라 표를 채우는 남용을 막는다(사람은 분당 이만큼 페이지를 넘기지 않는다).
|
||||
_IP_LIMIT_PER_MIN = 120
|
||||
# 새로고침 연타·뒤로가기 왕복을 한 번으로 본다.
|
||||
_DEDUPE_SEC = 10.0
|
||||
# 아래 두 메모리 표의 상한 — 넘치면 만료분을 걷고, 그래도 넘치면 오래된 절반을 버린다.
|
||||
_TABLE_MAX_KEYS = 20_000
|
||||
# 운영 경로는 Apache → nginx → 백엔드다. 두 프록시가 X-Forwarded-For 끝에 하나씩 덧붙이므로
|
||||
# 뒤에서 두 번째가 실제 손님이다. 첫 값은 손님이 마음대로 넣을 수 있다 — 그걸 쓰면 요청마다 새 방문자가 된다.
|
||||
_PROXY_HOPS = 2
|
||||
_TAB_MAX = 100
|
||||
|
||||
|
||||
def real_client_ip(xff: str | None, client_host: str | None) -> str:
|
||||
parts = [p.strip() for p in (xff or "").split(",") if p.strip()]
|
||||
if len(parts) >= _PROXY_HOPS:
|
||||
return parts[-_PROXY_HOPS][:45]
|
||||
# 프록시가 하나뿐인 환경(로컬 nginx·개발 서버) — 붙은 값이 곧 손님이다.
|
||||
return (parts[0] if parts else (client_host or ""))[:45]
|
||||
|
||||
|
||||
def page_path(raw: str) -> str | None:
|
||||
"""발행 경로 + 탭(#/…). 끝 슬래시는 같은 페이지라 걷는다. 발행 경로가 아니면 None."""
|
||||
try:
|
||||
parts = urlsplit(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
base = unquote(parts.path).rstrip("/")
|
||||
if not base.startswith("/s/") or len(base) <= 3:
|
||||
return None
|
||||
# 발행 사이트의 하위 페이지는 해시 탭(#/stay)이다. #/ 는 홈, 그 밖의 해시는 문서 안 앵커다.
|
||||
tab = f"#{parts.fragment}" if parts.fragment.startswith("/") and parts.fragment != "/" else ""
|
||||
return base + tab[:_TAB_MAX]
|
||||
|
||||
|
||||
def _shrink(table: dict, alive) -> dict:
|
||||
kept = {k: v for k, v in table.items() if alive(v)}
|
||||
if len(kept) > _TABLE_MAX_KEYS:
|
||||
# 만료분을 걷어도 넘친다 = 짧은 시간에 서로 다른 키가 쏟아졌다. 삽입 순서상 오래된 절반을 버린다.
|
||||
kept = dict(list(kept.items())[-(_TABLE_MAX_KEYS // 2):])
|
||||
return kept
|
||||
|
||||
|
||||
class VisitService:
|
||||
# 요청마다 새 인스턴스(Depends)라 상태는 클래스에 둔다. common.utils.rate_limit 은 키를 지우지 않아
|
||||
# 공개 엔드포인트의 IP·방문자 키로 쓰면 메모리가 끝없이 는다 — 그래서 상한이 있는 작은 표를 따로 둔다.
|
||||
_recent: dict[str, float] = {}
|
||||
_ip_hits: dict[str, tuple[float, int]] = {}
|
||||
|
||||
def __init__(self, crud: IVisitCRUD = Depends(VisitCRUD), hit_crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD)):
|
||||
self.crud = crud
|
||||
self.slugs = TrackService(hit_crud)
|
||||
|
||||
@classmethod
|
||||
def reset_dedupe(cls) -> None:
|
||||
cls._recent = {}
|
||||
cls._ip_hits = {}
|
||||
|
||||
@classmethod
|
||||
def _seen_recently(cls, key: str) -> bool:
|
||||
now = time.monotonic()
|
||||
if len(cls._recent) > _TABLE_MAX_KEYS:
|
||||
cls._recent = _shrink(cls._recent, lambda t: now - t < _DEDUPE_SEC)
|
||||
last = cls._recent.get(key)
|
||||
if last is not None and now - last < _DEDUPE_SEC:
|
||||
return True
|
||||
cls._recent[key] = now
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _ip_allowed(cls, ip: str) -> bool:
|
||||
now = time.monotonic()
|
||||
if len(cls._ip_hits) > _TABLE_MAX_KEYS:
|
||||
cls._ip_hits = _shrink(cls._ip_hits, lambda v: now - v[0] < 60.0)
|
||||
start, count = cls._ip_hits.get(ip, (now, 0))
|
||||
if now - start >= 60.0:
|
||||
start, count = now, 0
|
||||
if count >= _IP_LIMIT_PER_MIN:
|
||||
return False
|
||||
cls._ip_hits[ip] = (start, count + 1)
|
||||
return True
|
||||
|
||||
async def record_view(self, body: bytes, user_agent: str | None, xff: str | None, client_host: str | None) -> None:
|
||||
if not is_human(user_agent) or len(body) > MAX_BEACON_BODY:
|
||||
return
|
||||
try:
|
||||
data = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
return
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
path = page_path(str(data.get("path") or ""))
|
||||
if path is None:
|
||||
return
|
||||
ip = real_client_ip(xff, client_host)
|
||||
if not self._ip_allowed(ip):
|
||||
return
|
||||
site_id = await self.slugs.site_id_for(slug_of(path.split("#", 1)[0]))
|
||||
if site_id is None:
|
||||
return
|
||||
# 비밀값은 후기 IP 해시(review_service._ip_hash)와 같은 것을 쓴다 — 새 비밀을 하나 더 관리하지 않는다.
|
||||
hashed = visitor_hash(os.environ.get("JWT_ACCESS_SECRET", ""), ip, user_agent or "", datetime.now(timezone.utc))
|
||||
if self._seen_recently(f"{hashed}|{path}"):
|
||||
return
|
||||
utm = str(data.get("utm_source") or "").strip()[:100] or None
|
||||
view = site_page_views(
|
||||
site_id=site_id,
|
||||
path=path[:2000],
|
||||
visitor_hash=hashed,
|
||||
referrer_domain=referrer_domain(str(data.get("referrer") or "")),
|
||||
utm_source=utm,
|
||||
device=device_of(user_agent or ""),
|
||||
)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[site_page_views.DBType()], [lambda s: self.crud.add_view(s, view)]
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[visit] 방문 기록 저장 실패: {err.name}")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""사이트관리 방문 통계 — 기간 해석은 크롤러 통계와 같은 규칙(KST, 기본 7일, 366일 상한)."""
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import site_page_views, sites
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from crud.site_crud import ISiteCRUD, SiteCRUD
|
||||
from crud.visit_crud import IVisitCRUD, VisitCRUD
|
||||
from router.v1.ops.protocol import (
|
||||
Res_VisitStats, VisitDaily, VisitDeviceRow, VisitPathRow, VisitReferrerRow, VisitSiteRow, VisitSummary, VisitUtmRow,
|
||||
)
|
||||
# 같은 규칙을 복제하면 두 통계의 날짜 경계가 언젠가 갈라진다 — 크롤러 통계의 것을 그대로 쓴다.
|
||||
from services.crawler_stats_service import _bounds, resolve_range
|
||||
|
||||
REALTIME_WINDOW = timedelta(minutes=5)
|
||||
|
||||
|
||||
class VisitStatsService:
|
||||
def __init__(self, crud: IVisitCRUD = Depends(VisitCRUD), site_crud: ISiteCRUD = Depends(SiteCRUD)):
|
||||
self.crud = crud
|
||||
self.site_crud = site_crud
|
||||
|
||||
async def overall(self, date_from: date | None, date_to: date | None) -> Res_VisitStats:
|
||||
return await self._build(date_from, date_to, site_id=None, overall=True)
|
||||
|
||||
async def for_place(self, place_id, date_from: date | None, date_to: date | None) -> Res_VisitStats:
|
||||
err_type, site = await DB_SESSION_MNG.execute_lambda(
|
||||
sites.DBType(), DBWRType.DB_READ.value, lambda s: self.site_crud.get_site_by_place(s, place_id)
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res = Res_VisitStats()
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
if site is None:
|
||||
# 사이트를 아직 안 만든 사업장 — 방문될 주소가 없으니 빈 통계가 맞는 답이다.
|
||||
rng = resolve_range(date_from, date_to)
|
||||
return Res_VisitStats(date_from=rng[0], date_to=rng[1]) if rng else self._invalid()
|
||||
return await self._build(date_from, date_to, site_id=site.site_id, overall=False)
|
||||
|
||||
@staticmethod
|
||||
def _invalid() -> Res_VisitStats:
|
||||
res = Res_VisitStats()
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
async def _build(self, date_from, date_to, site_id, overall: bool) -> Res_VisitStats:
|
||||
rng = resolve_range(date_from, date_to)
|
||||
if rng is None:
|
||||
return self._invalid()
|
||||
frm, to = rng
|
||||
start, end = _bounds(frm, to)
|
||||
since = datetime.now(timezone.utc) - REALTIME_WINDOW
|
||||
err_type, data = await DB_SESSION_MNG.execute_lambda(
|
||||
site_page_views.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.stats(s, start, end, since, site_id, overall),
|
||||
)
|
||||
res = Res_VisitStats(date_from=frm, date_to=to)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.realtime = int(data["realtime"][0] or 0)
|
||||
s = data["summary"][0]
|
||||
res.summary = VisitSummary(views=s.views, visitors=s.visitors, last_at=s.last_at)
|
||||
res.daily = [VisitDaily(day=r.day, views=r.views, visitors=r.visitors) for r in data["daily"]]
|
||||
res.referrers = [VisitReferrerRow(domain=r.referrer_domain, views=r.views) for r in data["referrers"]]
|
||||
res.devices = [VisitDeviceRow(device=r.device, views=r.views) for r in data["devices"]]
|
||||
if overall:
|
||||
res.sites = [VisitSiteRow(site_id=r.site_id, place_id=r.place_id, name=r.name, views=r.views,
|
||||
visitors=r.visitors) for r in data["sites"]]
|
||||
else:
|
||||
res.pages = [VisitPathRow(path=r.path, views=r.views, visitors=r.visitors) for r in data["pages"]]
|
||||
res.utm = [VisitUtmRow(source=r.utm_source, views=r.views) for r in data["utm"]]
|
||||
return res
|
||||
@@ -0,0 +1,52 @@
|
||||
import pytest
|
||||
|
||||
from services.crawler_detect import CrawlerMatch, classify
|
||||
|
||||
KNOWN = [
|
||||
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot",
|
||||
CrawlerMatch("OAI-SearchBot", "OpenAI", "search")),
|
||||
("Mozilla/5.0 (compatible; Yeti/1.1; +https://naver.me/spd)", CrawlerMatch("Yeti", "Naver", "search-engine")),
|
||||
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko; compatible; Yeti/1.1; +https://naver.me/spd) Chrome/131.0.0.0 Safari/537.36",
|
||||
CrawlerMatch("Yeti", "Naver", "search-engine")),
|
||||
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 (compatible; meta-externalagent/1.1 (+https://developers.facebook.com/docs/sharing/webmasters/crawler))",
|
||||
CrawlerMatch("meta-externalagent", "Meta", "training")),
|
||||
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/116.0.1938.76 Safari/537.36",
|
||||
CrawlerMatch("bingbot", "Microsoft", "search-engine")),
|
||||
("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", CrawlerMatch("Googlebot", "Google", "search-engine")),
|
||||
("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
|
||||
CrawlerMatch("Googlebot", "Google", "search-engine")),
|
||||
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)", CrawlerMatch("GPTBot", "OpenAI", "training")),
|
||||
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ChatGPT-User/1.0; +https://openai.com/bot)", CrawlerMatch("ChatGPT-User", "OpenAI", "user-fetch")),
|
||||
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)", CrawlerMatch("PerplexityBot", "Perplexity", "search")),
|
||||
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)", CrawlerMatch("ClaudeBot", "Anthropic", "training")),
|
||||
]
|
||||
|
||||
OTHER = [
|
||||
"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
|
||||
"AIO2O-Bot/1.0 (+https://aio2o.com/bot)",
|
||||
]
|
||||
|
||||
HUMAN_OR_TOOL = [
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 16; SM-F731N Build/BP4A.251005.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/140.0.0.0 Mobile Safari/537.36 BizWebView KAKAOTALK/26.1.0 (PFINAPP)",
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1 NAVER(inapp; search; 2100; 12.10.5; 16)",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36",
|
||||
"curl/8.5.0",
|
||||
"",
|
||||
None,
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ua,expected", KNOWN)
|
||||
def test_목록_봇은_이름_회사_용도를_붙인다(ua, expected):
|
||||
assert classify(ua) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ua", OTHER)
|
||||
def test_목록_밖_봇은_기타로_남긴다(ua):
|
||||
assert classify(ua) == CrawlerMatch(None, None, "other")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ua", HUMAN_OR_TOOL)
|
||||
def test_사람과_도구는_버린다(ua):
|
||||
assert classify(ua) is None
|
||||
@@ -0,0 +1,111 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import UserRole
|
||||
from services.crawler_stats_service import resolve_range
|
||||
|
||||
|
||||
async def _site(client, auth_headers, db_engine, name):
|
||||
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
|
||||
pid = (await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})).json()["place"]["place_id"]
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"),
|
||||
{"p": pid})
|
||||
sid = (await conn.execute(text("SELECT site_id::text FROM sites WHERE place_id = :p AND deleted = false"),
|
||||
{"p": pid})).scalar_one()
|
||||
return pid, sid
|
||||
|
||||
|
||||
async def _hit(db_engine, at, *, site_id=None, kind="page", bot="OAI-SearchBot", vendor="OpenAI",
|
||||
purpose="search", path="/s/x", ua="ua"):
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"INSERT INTO site_crawler_hits (hit_id, site_id, path, kind, bot, vendor, purpose, user_agent, created_at) "
|
||||
"VALUES (gen_random_uuid(), :site_id, :path, :kind, :bot, :vendor, :purpose, :ua, :at)"
|
||||
), {"site_id": site_id, "path": path, "kind": kind, "bot": bot, "vendor": vendor,
|
||||
"purpose": purpose, "ua": ua, "at": datetime.fromisoformat(at)})
|
||||
|
||||
|
||||
def test_기간_기본값은_오늘까지_7일():
|
||||
assert resolve_range(None, None, today=date(2026, 10, 7)) == (date(2026, 10, 1), date(2026, 10, 7))
|
||||
|
||||
|
||||
def test_뒤집힌_기간과_366일_넘는_기간은_거부한다():
|
||||
assert resolve_range(date(2026, 10, 7), date(2026, 10, 1)) is None
|
||||
assert resolve_range(date(2025, 1, 1), date(2026, 10, 7)) is None
|
||||
|
||||
|
||||
async def test_일별_집계는_KST_날짜로_자른다(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev1", role=UserRole.DEVELOPER.value)
|
||||
await _hit(db_engine, "2026-10-06T14:59:00+00:00") # KST 10-06 23:59
|
||||
await _hit(db_engine, "2026-10-06T15:30:00+00:00") # KST 10-07 00:30
|
||||
|
||||
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
|
||||
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
|
||||
assert body["result"]["success"] is True
|
||||
assert body["summary"]["total"] == 1
|
||||
assert body["daily"] == [{"day": "2026-10-07", "purpose": "search", "hits": 1}]
|
||||
|
||||
|
||||
async def test_전체_통계는_봇_사이트_공용파일_기타를_모은다(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev2", role=UserRole.DEVELOPER.value)
|
||||
pid, sid = await _site(client, auth_headers, db_engine, "통계카페")
|
||||
at = "2026-10-07T03:00:00+00:00"
|
||||
await _hit(db_engine, at, site_id=sid)
|
||||
await _hit(db_engine, at, site_id=sid, bot="Googlebot", vendor="Google", purpose="search-engine")
|
||||
await _hit(db_engine, at, kind="robots", path="/robots.txt")
|
||||
await _hit(db_engine, at, bot=None, vendor=None, purpose="other", ua="AIO2O-Bot/1.0")
|
||||
|
||||
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
|
||||
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
|
||||
assert body["summary"]["total"] == 4
|
||||
assert body["summary"]["ai"] == 2 # search 2건(사이트 1 + robots 1). search-engine·other 는 AI 아님
|
||||
assert body["summary"]["bots"] == 2 # OAI-SearchBot, Googlebot
|
||||
assert {(b["bot"], b["hits"]) for b in body["bots"]} == {("OAI-SearchBot", 2), ("Googlebot", 1)}
|
||||
[site] = body["sites"]
|
||||
assert (site["place_id"], site["name"], site["hits"], site["ai_hits"]) == (pid, "통계카페", 2, 1)
|
||||
assert [(r["kind"], r["bot"], r["hits"]) for r in body["root_files"]] == [("robots", "OAI-SearchBot", 1)]
|
||||
assert [(o["user_agent"], o["hits"]) for o in body["others"]] == [("AIO2O-Bot/1.0", 1)]
|
||||
assert "pages" not in body or body["pages"] == []
|
||||
|
||||
|
||||
async def test_사이트별_통계는_그_사이트_것만_본다(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev3", role=UserRole.DEVELOPER.value)
|
||||
pid, sid = await _site(client, auth_headers, db_engine, "내가게")
|
||||
_, other_sid = await _site(client, auth_headers, db_engine, "남의가게")
|
||||
await _hit(db_engine, "2026-10-07T01:00:00+00:00", site_id=sid, path="/s/mine")
|
||||
await _hit(db_engine, "2026-10-07T02:00:00+00:00", site_id=sid, path="/s/mine/blog/1")
|
||||
await _hit(db_engine, "2026-10-07T02:00:00+00:00", site_id=other_sid, path="/s/other")
|
||||
|
||||
body = (await client.get(f"/v1/ops/sites/{pid}/stats/crawlers", headers=dev,
|
||||
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
|
||||
assert body["summary"]["total"] == 2
|
||||
assert sorted(p["path"] for p in body["pages"]) == ["/s/mine", "/s/mine/blog/1"]
|
||||
assert [r["path"] for r in body["recent"]] == ["/s/mine/blog/1", "/s/mine"] # 최신순
|
||||
|
||||
|
||||
async def test_사이트가_없는_사업장은_빈_통계(client, auth_headers):
|
||||
dev = await auth_headers("dev4", role=UserRole.DEVELOPER.value)
|
||||
owner = await auth_headers("owner4")
|
||||
pid = (await client.post("/v1/place", headers=owner, json={"name": "새가게", "category": 2})).json()["place"]["place_id"]
|
||||
body = (await client.get(f"/v1/ops/sites/{pid}/stats/crawlers", headers=dev)).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["summary"]["total"] == 0
|
||||
|
||||
|
||||
async def test_뒤집힌_기간은_실패_결과(client, auth_headers):
|
||||
dev = await auth_headers("dev5", role=UserRole.DEVELOPER.value)
|
||||
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
|
||||
params={"from": "2026-10-07", "to": "2026-10-01"})).json()
|
||||
assert body["result"]["success"] is False
|
||||
|
||||
|
||||
async def test_개발자가_아니면_403(client, auth_headers):
|
||||
owner = await auth_headers("owner5", role=UserRole.OWNER.value)
|
||||
assert (await client.get("/v1/ops/stats/crawlers", headers=owner)).status_code == 403
|
||||
assert (await client.get(f"/v1/ops/sites/{uuid.uuid4()}/stats/crawlers", headers=owner)).status_code == 403
|
||||
@@ -0,0 +1,171 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from services.track_service import TrackService
|
||||
|
||||
OAI = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot"
|
||||
CHROME = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
FB = "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_slug_cache():
|
||||
# 슬러그 표는 프로세스 캐시다 — 테스트마다 DB 를 비우므로 캐시도 비운다.
|
||||
TrackService.reset_cache()
|
||||
yield
|
||||
TrackService.reset_cache()
|
||||
|
||||
|
||||
async def _place(client, auth_headers, name):
|
||||
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
|
||||
r = await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})
|
||||
return r.json()["place"]["place_id"]
|
||||
|
||||
|
||||
async def _site(db_engine, place_id, domain):
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"),
|
||||
{"p": place_id},
|
||||
)
|
||||
await conn.execute(text("UPDATE sites SET domain = :d WHERE place_id = :p AND deleted = false"),
|
||||
{"d": domain, "p": place_id})
|
||||
row = (await conn.execute(text("SELECT site_id FROM sites WHERE place_id = :p AND deleted = false"),
|
||||
{"p": place_id})).first()
|
||||
return str(row[0])
|
||||
|
||||
|
||||
async def _hits(db_engine):
|
||||
async with db_engine.begin() as conn:
|
||||
rows = (await conn.execute(text(
|
||||
"SELECT site_id::text, path, kind, bot, vendor, purpose, user_agent, ip FROM site_crawler_hits ORDER BY created_at"
|
||||
))).mappings().all()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def _send(client, uri, ua, xff="203.0.113.7"):
|
||||
return await client.get("/internal/track/hit",
|
||||
headers={"X-Original-URI": uri, "User-Agent": ua, "X-Forwarded-For": xff})
|
||||
|
||||
|
||||
async def test_봇_요청을_사이트에_묶어_저장한다(client, auth_headers, db_engine):
|
||||
pid = await _place(client, auth_headers, "머뭄")
|
||||
site_id = await _site(db_engine, pid, "mermum")
|
||||
|
||||
r = await _send(client, "/s/mermum", OAI, "203.0.113.7, 10.0.0.1")
|
||||
|
||||
assert r.status_code == 204
|
||||
[hit] = await _hits(db_engine)
|
||||
assert hit["site_id"] == site_id
|
||||
assert (hit["kind"], hit["bot"], hit["vendor"], hit["purpose"]) == ("page", "OAI-SearchBot", "OpenAI", "search")
|
||||
assert hit["path"] == "/s/mermum"
|
||||
assert hit["ip"] == "203.0.113.7"
|
||||
|
||||
|
||||
async def test_사람_요청은_저장하지_않는다(client, db_engine):
|
||||
r = await _send(client, "/s/mermum", CHROME)
|
||||
assert r.status_code == 204
|
||||
assert await _hits(db_engine) == []
|
||||
|
||||
|
||||
async def test_한글_슬러그와_하위경로를_같은_사이트로_묶는다(client, auth_headers, db_engine):
|
||||
pid = await _place(client, auth_headers, "스테이머뭄")
|
||||
site_id = await _site(db_engine, pid, "스테이머뭄")
|
||||
|
||||
await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/", OAI)
|
||||
await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/blog/1?utm_source=x", OAI)
|
||||
|
||||
hits = await _hits(db_engine)
|
||||
assert [h["site_id"] for h in hits] == [site_id, site_id]
|
||||
assert hits[1]["path"] == "/s/스테이머뭄/blog/1?utm_source=x"
|
||||
|
||||
|
||||
async def test_domain_없는_사이트는_이름_슬러그로_찾는다(client, auth_headers, db_engine):
|
||||
pid = await _place(client, auth_headers, "검색 카페")
|
||||
site_id = await _site(db_engine, pid, None)
|
||||
|
||||
# 헤더는 ASCII 만 실린다(httpx 도 nginx 의 $request_uri 도) — 한글 슬러그는 퍼센트 인코딩으로 온다.
|
||||
await _send(client, "/s/" + quote(f"검색-카페-{pid[:8]}"), OAI)
|
||||
|
||||
[hit] = await _hits(db_engine)
|
||||
assert hit["site_id"] == site_id
|
||||
|
||||
|
||||
async def test_없는_슬러그는_사이트_없이_남긴다(client, db_engine):
|
||||
await _send(client, "/s/no-such-site", OAI)
|
||||
[hit] = await _hits(db_engine)
|
||||
assert hit["site_id"] is None
|
||||
assert hit["kind"] == "page"
|
||||
|
||||
|
||||
async def test_robots_sitemap_은_kind_로_가른다(client, db_engine):
|
||||
await _send(client, "/robots.txt", OAI)
|
||||
await _send(client, "/sitemap.xml", OAI)
|
||||
assert [(h["kind"], h["site_id"]) for h in await _hits(db_engine)] == [("robots", None), ("sitemap", None)]
|
||||
|
||||
|
||||
async def test_확장자_붙은_요청과_범위_밖_경로는_버린다(client, db_engine):
|
||||
await _send(client, "/s/mermum/img/abc.jpg", OAI)
|
||||
await _send(client, "/s/mermum/assets/x.js?v=1", OAI)
|
||||
await _send(client, "/builder", OAI)
|
||||
await _send(client, "/s", OAI)
|
||||
assert await _hits(db_engine) == []
|
||||
|
||||
|
||||
async def test_기타_봇은_UA는_남기고_IP는_남기지_않는다(client, db_engine):
|
||||
await _send(client, "/s/mermum", FB)
|
||||
[hit] = await _hits(db_engine)
|
||||
assert (hit["bot"], hit["purpose"], hit["ip"]) == (None, "other", None)
|
||||
assert hit["user_agent"] == FB
|
||||
|
||||
|
||||
async def test_DB_오류여도_204(client, monkeypatch):
|
||||
async def boom(*args, **kwargs):
|
||||
raise RuntimeError("db down")
|
||||
|
||||
monkeypatch.setattr(TrackService, "record_hit", boom)
|
||||
r = await _send(client, "/s/mermum", OAI)
|
||||
assert r.status_code == 204
|
||||
|
||||
|
||||
async def test_응답은_기록이_끝나기_전에_나간다(monkeypatch):
|
||||
# nginx 는 mirror 하위 요청이 끝나기 전까지 같은 연결의 다음 요청을 읽지 않는다 —
|
||||
# 저장(DB)을 기다렸다 204 를 주면 DB 가 느릴 때 그 연결의 다른 요청까지 같이 늦어진다.
|
||||
from router.router import app
|
||||
|
||||
done = asyncio.Event()
|
||||
response_sent_before_done = []
|
||||
|
||||
async def slow_record_hit(self, uri, user_agent, xff):
|
||||
await asyncio.sleep(0.2)
|
||||
done.set()
|
||||
|
||||
monkeypatch.setattr(TrackService, "record_hit", slow_record_hit)
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": b"", "more_body": False}
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.body" and not message.get("more_body"):
|
||||
response_sent_before_done.append(not done.is_set())
|
||||
|
||||
scope = {
|
||||
"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
|
||||
"path": "/internal/track/hit", "raw_path": b"/internal/track/hit", "query_string": b"",
|
||||
"headers": [(b"x-original-uri", b"/robots.txt"), (b"user-agent", b"OAI-SearchBot/1.3")],
|
||||
"client": ("127.0.0.1", 1), "server": ("test", 80),
|
||||
}
|
||||
await app(scope, receive, send)
|
||||
|
||||
assert response_sent_before_done == [True]
|
||||
assert done.is_set() # 응답 뒤에도 기록은 끝까지 돈다
|
||||
|
||||
|
||||
async def test_HEAD_요청도_받는다(client, db_engine):
|
||||
r = await client.head("/internal/track/hit", headers={"X-Original-URI": "/robots.txt", "User-Agent": OAI})
|
||||
assert r.status_code == 204
|
||||
assert len(await _hits(db_engine)) == 1
|
||||
@@ -0,0 +1,91 @@
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import UserRole
|
||||
|
||||
|
||||
async def _site(client, auth_headers, db_engine, name):
|
||||
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
|
||||
pid = (await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})).json()["place"]["place_id"]
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"), {"p": pid})
|
||||
sid = (await conn.execute(text("SELECT site_id::text FROM sites WHERE place_id = :p AND deleted = false"), {"p": pid})).scalar_one()
|
||||
return pid, sid
|
||||
|
||||
|
||||
async def _view(db_engine, at, site_id, *, visitor="v1", path="/s/x", ref=None, utm=None, device="desktop"):
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"INSERT INTO site_page_views (view_id, site_id, path, visitor_hash, referrer_domain, utm_source, device, created_at) "
|
||||
"VALUES (gen_random_uuid(), :s, :p, :v, :r, :u, :d, :at)"
|
||||
), {"s": site_id, "p": path, "v": visitor.ljust(64, "0"), "r": ref, "u": utm, "d": device, "at": at})
|
||||
|
||||
|
||||
async def test_실시간은_최근_5분_고유_방문자(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev1", role=UserRole.DEVELOPER.value)
|
||||
_, sid = await _site(client, auth_headers, db_engine, "실시간가게")
|
||||
now = datetime.now(timezone.utc)
|
||||
await _view(db_engine, now - timedelta(minutes=1), sid, visitor="a")
|
||||
await _view(db_engine, now - timedelta(minutes=2), sid, visitor="a", path="/s/x/2")
|
||||
await _view(db_engine, now - timedelta(minutes=3), sid, visitor="b")
|
||||
await _view(db_engine, now - timedelta(minutes=9), sid, visitor="c")
|
||||
body = (await client.get("/v1/ops/stats/visits", headers=dev)).json()
|
||||
assert body["realtime"] == 2
|
||||
|
||||
|
||||
async def test_전체_방문_통계(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev2", role=UserRole.DEVELOPER.value)
|
||||
pid, sid = await _site(client, auth_headers, db_engine, "방문카페")
|
||||
at = datetime(2026, 10, 7, 3, 0, tzinfo=timezone.utc)
|
||||
await _view(db_engine, at, sid, visitor="a", ref="google.com", device="mobile")
|
||||
await _view(db_engine, at, sid, visitor="a", path="/s/x/2", device="mobile")
|
||||
await _view(db_engine, at, sid, visitor="b", ref="google.com")
|
||||
body = (await client.get("/v1/ops/stats/visits", headers=dev, params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert (body["summary"]["views"], body["summary"]["visitors"]) == (3, 2)
|
||||
assert body["daily"] == [{"day": "2026-10-07", "views": 3, "visitors": 2}]
|
||||
[site] = body["sites"]
|
||||
assert (site["place_id"], site["name"], site["views"], site["visitors"]) == (pid, "방문카페", 3, 2)
|
||||
assert body["referrers"] == [{"domain": "google.com", "views": 2}]
|
||||
assert {(d["device"], d["views"]) for d in body["devices"]} == {("mobile", 2), ("desktop", 1)}
|
||||
|
||||
|
||||
async def test_일별은_KST_날짜(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev3", role=UserRole.DEVELOPER.value)
|
||||
_, sid = await _site(client, auth_headers, db_engine, "날짜가게")
|
||||
await _view(db_engine, datetime(2026, 10, 6, 14, 59, tzinfo=timezone.utc), sid) # KST 10-06 23:59
|
||||
await _view(db_engine, datetime(2026, 10, 6, 15, 30, tzinfo=timezone.utc), sid) # KST 10-07 00:30
|
||||
body = (await client.get("/v1/ops/stats/visits", headers=dev, params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
assert body["daily"] == [{"day": "2026-10-07", "views": 1, "visitors": 1}]
|
||||
|
||||
|
||||
async def test_사이트별_방문_통계(client, auth_headers, db_engine):
|
||||
dev = await auth_headers("dev4", role=UserRole.DEVELOPER.value)
|
||||
pid, sid = await _site(client, auth_headers, db_engine, "내가게")
|
||||
_, other = await _site(client, auth_headers, db_engine, "남의가게")
|
||||
at = datetime(2026, 10, 7, 3, 0, tzinfo=timezone.utc)
|
||||
await _view(db_engine, at, sid, visitor="a", path="/s/mine", utm="chatgpt.com")
|
||||
await _view(db_engine, at, sid, visitor="b", path="/s/mine")
|
||||
await _view(db_engine, at, sid, visitor="a", path="/s/mine/rooms")
|
||||
await _view(db_engine, at, other, visitor="z", path="/s/other")
|
||||
body = (await client.get(f"/v1/ops/sites/{pid}/stats/visits", headers=dev, params={"from": "2026-10-07", "to": "2026-10-07"})).json()
|
||||
assert (body["summary"]["views"], body["summary"]["visitors"]) == (3, 2)
|
||||
assert body["pages"][0] == {"path": "/s/mine", "views": 2, "visitors": 2}
|
||||
assert body["utm"] == [{"source": "chatgpt.com", "views": 1}]
|
||||
assert "sites" not in body or body["sites"] == []
|
||||
|
||||
|
||||
async def test_사이트가_없는_사업장은_빈_통계(client, auth_headers):
|
||||
dev = await auth_headers("dev5", role=UserRole.DEVELOPER.value)
|
||||
owner = await auth_headers("owner5")
|
||||
pid = (await client.post("/v1/place", headers=owner, json={"name": "새가게", "category": 2})).json()["place"]["place_id"]
|
||||
body = (await client.get(f"/v1/ops/sites/{pid}/stats/visits", headers=dev)).json()
|
||||
assert body["result"]["success"] is True and body["summary"]["views"] == 0 and body["realtime"] == 0
|
||||
|
||||
|
||||
async def test_개발자가_아니면_403(client, auth_headers):
|
||||
owner = await auth_headers("owner6", role=UserRole.OWNER.value)
|
||||
assert (await client.get("/v1/ops/stats/visits", headers=owner)).status_code == 403
|
||||
assert (await client.get(f"/v1/ops/sites/{uuid.uuid4()}/stats/visits", headers=owner)).status_code == 403
|
||||
@@ -0,0 +1,236 @@
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.utils import rate_limit
|
||||
from services.track_service import TrackService
|
||||
from services.visit_detect import device_of, is_human, referrer_domain, visitor_hash
|
||||
from services.visit_service import VisitService
|
||||
|
||||
CHROME = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1"
|
||||
IPAD = "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
|
||||
ANDROID_TAB = "Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
GPTBOT = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)"
|
||||
HEADLESS = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36"
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_state():
|
||||
TrackService.reset_cache()
|
||||
VisitService.reset_dedupe()
|
||||
rate_limit.reset()
|
||||
yield
|
||||
TrackService.reset_cache()
|
||||
VisitService.reset_dedupe()
|
||||
rate_limit.reset()
|
||||
|
||||
|
||||
def test_사람과_봇_판별():
|
||||
assert is_human(CHROME) and is_human(IPHONE)
|
||||
assert not is_human(GPTBOT)
|
||||
assert not is_human(HEADLESS) # 우리 목업 검증 스크립트 — 사람 방문으로 세면 안 된다
|
||||
assert not is_human("") and not is_human(None)
|
||||
|
||||
|
||||
def test_기기_분류():
|
||||
assert device_of(CHROME) == "desktop"
|
||||
assert device_of(IPHONE) == "mobile"
|
||||
assert device_of(IPAD) == "tablet"
|
||||
assert device_of(ANDROID_TAB) == "tablet"
|
||||
|
||||
|
||||
def test_유입_도메인():
|
||||
assert referrer_domain("https://www.google.com/search?q=x") == "google.com"
|
||||
assert referrer_domain("https://m.search.naver.com/search.naver?q=x") == "m.search.naver.com"
|
||||
assert referrer_domain("") is None
|
||||
assert referrer_domain("not a url") is None
|
||||
|
||||
|
||||
def test_방문자_해시는_달이_바뀌면_달라진다():
|
||||
sep = datetime(2026, 9, 30, 23, 0, tzinfo=KST)
|
||||
oct_ = datetime(2026, 10, 1, 0, 30, tzinfo=KST)
|
||||
a = visitor_hash("s", "203.0.113.7", CHROME, sep)
|
||||
assert a == visitor_hash("s", "203.0.113.7", CHROME, sep + timedelta(minutes=30))
|
||||
assert a != visitor_hash("s", "203.0.113.7", CHROME, oct_)
|
||||
assert len(a) == 64 and "203.0.113.7" not in a
|
||||
|
||||
|
||||
async def _site(client, auth_headers, db_engine, name, domain):
|
||||
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
|
||||
pid = (await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})).json()["place"]["place_id"]
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"), {"p": pid})
|
||||
await conn.execute(text("UPDATE sites SET domain = :d WHERE place_id = :p AND deleted = false"), {"d": domain, "p": pid})
|
||||
sid = (await conn.execute(text("SELECT site_id::text FROM sites WHERE place_id = :p AND deleted = false"), {"p": pid})).scalar_one()
|
||||
return sid
|
||||
|
||||
|
||||
async def _views(db_engine):
|
||||
async with db_engine.begin() as conn:
|
||||
rows = (await conn.execute(text(
|
||||
"SELECT site_id::text, path, visitor_hash, referrer_domain, utm_source, device FROM site_page_views ORDER BY created_at"
|
||||
))).mappings().all()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def _beacon(client, body, ua=CHROME, xff="203.0.113.7"):
|
||||
raw = body if isinstance(body, (bytes, str)) else json.dumps(body)
|
||||
return await client.post("/v1/track/view", content=raw,
|
||||
headers={"User-Agent": ua, "X-Forwarded-For": xff, "Content-Type": "text/plain"})
|
||||
|
||||
|
||||
async def test_사람_방문을_사이트에_묶어_저장한다(client, auth_headers, db_engine):
|
||||
sid = await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
r = await _beacon(client, {"path": "/s/mermum/rooms", "referrer": "https://www.google.com/", "utm_source": "chatgpt.com"}, ua=IPHONE)
|
||||
assert r.status_code == 204
|
||||
[v] = await _views(db_engine)
|
||||
assert (v["site_id"], v["path"], v["referrer_domain"], v["utm_source"], v["device"]) == \
|
||||
(sid, "/s/mermum/rooms", "google.com", "chatgpt.com", "mobile")
|
||||
assert len(v["visitor_hash"]) == 64
|
||||
|
||||
|
||||
async def test_IP_원문은_어디에도_남지_않는다(client, auth_headers, db_engine):
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
await _beacon(client, {"path": "/s/mermum"}, xff="198.51.100.23")
|
||||
async with db_engine.begin() as conn:
|
||||
dump = (await conn.execute(text("SELECT row_to_json(v)::text FROM site_page_views v"))).scalar_one()
|
||||
assert "198.51.100.23" not in dump
|
||||
|
||||
|
||||
async def test_봇과_헤드리스는_세지_않는다(client, auth_headers, db_engine):
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
await _beacon(client, {"path": "/s/mermum"}, ua=GPTBOT)
|
||||
await _beacon(client, {"path": "/s/mermum"}, ua=HEADLESS)
|
||||
assert await _views(db_engine) == []
|
||||
|
||||
|
||||
async def test_없는_사이트와_범위_밖_경로는_버린다(client, db_engine):
|
||||
await _beacon(client, {"path": "/s/no-such-site"})
|
||||
await _beacon(client, {"path": "/builder"})
|
||||
await _beacon(client, {"path": "/preview"})
|
||||
assert await _views(db_engine) == []
|
||||
|
||||
|
||||
async def test_깨진_본문도_204(client, db_engine):
|
||||
r = await _beacon(client, b"{not json")
|
||||
assert r.status_code == 204
|
||||
r = await _beacon(client, json.dumps(["list"]))
|
||||
assert r.status_code == 204
|
||||
assert await _views(db_engine) == []
|
||||
|
||||
|
||||
async def test_10초_안_같은_경로는_한_번만(client, auth_headers, db_engine):
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
for _ in range(3):
|
||||
await _beacon(client, {"path": "/s/mermum"})
|
||||
await _beacon(client, {"path": "/s/mermum/rooms"})
|
||||
assert [v["path"] for v in await _views(db_engine)] == ["/s/mermum", "/s/mermum/rooms"]
|
||||
|
||||
|
||||
async def test_IP당_분당_한도를_넘으면_버린다(client, auth_headers, db_engine, monkeypatch):
|
||||
import services.visit_service as vs
|
||||
monkeypatch.setattr(vs, "_IP_LIMIT_PER_MIN", 2)
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
for p in ("/s/mermum/a", "/s/mermum/b", "/s/mermum/c"):
|
||||
await _beacon(client, {"path": p})
|
||||
assert len(await _views(db_engine)) == 2
|
||||
|
||||
|
||||
async def test_응답은_저장이_끝나기_전에_나간다(monkeypatch):
|
||||
from router.router import app
|
||||
|
||||
done = asyncio.Event()
|
||||
sent_before_done = []
|
||||
|
||||
async def slow(self, body, user_agent, xff, client_host):
|
||||
await asyncio.sleep(0.2)
|
||||
done.set()
|
||||
|
||||
monkeypatch.setattr(VisitService, "record_view", slow)
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": b'{"path":"/s/x"}', "more_body": False}
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.body" and not message.get("more_body"):
|
||||
sent_before_done.append(not done.is_set())
|
||||
|
||||
scope = {
|
||||
"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST", "scheme": "http",
|
||||
"path": "/v1/track/view", "raw_path": b"/v1/track/view", "query_string": b"",
|
||||
"headers": [(b"user-agent", CHROME.encode()), (b"content-type", b"text/plain")],
|
||||
"client": ("127.0.0.1", 1), "server": ("test", 80),
|
||||
}
|
||||
await app(scope, receive, send)
|
||||
assert sent_before_done == [True]
|
||||
assert done.is_set()
|
||||
|
||||
|
||||
# ── 최종 리뷰 반영(2026-10-12) ─────────────────────────────────────────────
|
||||
|
||||
|
||||
async def test_위조한_XFF_앞부분은_무시한다(client, auth_headers, db_engine):
|
||||
# 운영 경로는 Apache → nginx → 백엔드라 끝의 두 값(실제 손님, Apache)만 믿을 수 있다.
|
||||
# 앞부분은 손님이 마음대로 붙인 값 — 그걸 IP 로 쓰면 요청마다 새 방문자가 된다.
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
await _beacon(client, {"path": "/s/mermum"}, xff="1.1.1.1, 203.0.113.7, 10.0.0.1")
|
||||
await _beacon(client, {"path": "/s/mermum"}, xff="2.2.2.2, 203.0.113.7, 10.0.0.1")
|
||||
assert len(await _views(db_engine)) == 1
|
||||
|
||||
|
||||
async def test_탭_이동도_페이지로_센다(client, auth_headers, db_engine):
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
await _beacon(client, {"path": "/s/mermum"})
|
||||
await _beacon(client, {"path": "/s/mermum#/stay"})
|
||||
await _beacon(client, {"path": "/s/mermum#/"}) # 홈 탭 = 첫 화면
|
||||
await _beacon(client, {"path": "/s/mermum#reviews"}) # 탭이 아닌 문서 안 앵커
|
||||
assert [v["path"] for v in await _views(db_engine)] == ["/s/mermum", "/s/mermum#/stay"]
|
||||
|
||||
|
||||
async def test_끝_슬래시는_같은_페이지(client, auth_headers, db_engine):
|
||||
await _site(client, auth_headers, db_engine, "머뭄", "mermum")
|
||||
await _beacon(client, {"path": "/s/mermum/"})
|
||||
await _beacon(client, {"path": "/s/mermum"})
|
||||
assert [v["path"] for v in await _views(db_engine)] == ["/s/mermum"]
|
||||
|
||||
|
||||
async def test_큰_본문은_읽지_않고_버린다(client, monkeypatch):
|
||||
called = []
|
||||
|
||||
async def spy(self, body, user_agent, xff, client_host):
|
||||
called.append(len(body))
|
||||
|
||||
monkeypatch.setattr(VisitService, "record_view", spy)
|
||||
r = await _beacon(client, {"path": "/s/mermum", "pad": "x" * 5000})
|
||||
assert r.status_code == 204
|
||||
assert called == []
|
||||
|
||||
|
||||
async def test_깨진_주소값도_조용히_버린다():
|
||||
# urlsplit 은 "http://[" 같은 값에서 ValueError 를 던진다 — 밖에서 경고 로그를 마음대로 찍게 두지 않는다.
|
||||
assert referrer_domain("http://[") is None
|
||||
# 깨진 경로는 DB 를 부르기 전에 버린다(crud 가 없어도 예외 없이 끝나야 한다).
|
||||
service = VisitService(crud=None, hit_crud=None)
|
||||
await service.record_view(json.dumps({"path": "http://["}).encode(), CHROME, "203.0.113.7", None)
|
||||
|
||||
|
||||
def test_중복_제거_표는_상한을_지킨다(monkeypatch):
|
||||
import services.visit_service as vs
|
||||
monkeypatch.setattr(vs, "_TABLE_MAX_KEYS", 10)
|
||||
for i in range(50):
|
||||
VisitService._seen_recently(f"k{i}")
|
||||
assert len(VisitService._recent) <= 10
|
||||
|
||||
|
||||
def test_IP_한도_표도_상한을_지킨다(monkeypatch):
|
||||
import services.visit_service as vs
|
||||
monkeypatch.setattr(vs, "_TABLE_MAX_KEYS", 10)
|
||||
for i in range(50):
|
||||
VisitService._ip_allowed(f"198.51.100.{i}")
|
||||
assert len(VisitService._ip_hits) <= 10
|
||||
@@ -29,6 +29,7 @@
|
||||
"react-dom": "^19.0.1",
|
||||
"react-hook-form": "^7.79.0",
|
||||
"react-router": "^7.17.0",
|
||||
"recharts": "^3.10.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { CrawlerBotRowBot } from "./crawlerBotRowBot";
|
||||
import type { CrawlerBotRowVendor } from "./crawlerBotRowVendor";
|
||||
|
||||
export interface CrawlerBotRow {
|
||||
bot?: CrawlerBotRowBot;
|
||||
vendor?: CrawlerBotRowVendor;
|
||||
purpose: string;
|
||||
hits: number;
|
||||
last_at: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerBotRowBot = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerBotRowVendor = string | null;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface CrawlerDaily {
|
||||
day: string;
|
||||
purpose: string;
|
||||
hits: number;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { CrawlerHitRowBot } from "./crawlerHitRowBot";
|
||||
import type { CrawlerHitRowVendor } from "./crawlerHitRowVendor";
|
||||
|
||||
export interface CrawlerHitRow {
|
||||
created_at: string;
|
||||
kind: string;
|
||||
bot?: CrawlerHitRowBot;
|
||||
vendor?: CrawlerHitRowVendor;
|
||||
purpose: string;
|
||||
path: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerHitRowBot = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerHitRowVendor = string | null;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface CrawlerPathRow {
|
||||
path: string;
|
||||
hits: number;
|
||||
last_at: string;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { CrawlerRootRowBot } from "./crawlerRootRowBot";
|
||||
|
||||
export interface CrawlerRootRow {
|
||||
kind: string;
|
||||
bot?: CrawlerRootRowBot;
|
||||
purpose: string;
|
||||
hits: number;
|
||||
last_at: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerRootRowBot = string | null;
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface CrawlerSiteRow {
|
||||
site_id: string;
|
||||
place_id: string;
|
||||
name: string;
|
||||
hits: number;
|
||||
ai_hits: number;
|
||||
last_at: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerStatsParams = {
|
||||
/**
|
||||
* KST 날짜, 기본 to-6일
|
||||
*/
|
||||
from?: string | null;
|
||||
/**
|
||||
* KST 날짜, 기본 오늘
|
||||
*/
|
||||
to?: string | null;
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { CrawlerSummaryLastAt } from "./crawlerSummaryLastAt";
|
||||
|
||||
export interface CrawlerSummary {
|
||||
total?: number;
|
||||
ai?: number;
|
||||
bots?: number;
|
||||
last_at?: CrawlerSummaryLastAt;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type CrawlerSummaryLastAt = string | null;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface CrawlerUaRow {
|
||||
user_agent: string;
|
||||
hits: number;
|
||||
last_at: string;
|
||||
}
|
||||
@@ -14,6 +14,21 @@ export * from "./buildStatus";
|
||||
export * from "./checkSlugParams";
|
||||
export * from "./confirm";
|
||||
export * from "./confirmArgs";
|
||||
export * from "./crawlerBotRow";
|
||||
export * from "./crawlerBotRowBot";
|
||||
export * from "./crawlerBotRowVendor";
|
||||
export * from "./crawlerDaily";
|
||||
export * from "./crawlerHitRow";
|
||||
export * from "./crawlerHitRowBot";
|
||||
export * from "./crawlerHitRowVendor";
|
||||
export * from "./crawlerPathRow";
|
||||
export * from "./crawlerRootRow";
|
||||
export * from "./crawlerRootRowBot";
|
||||
export * from "./crawlerSiteRow";
|
||||
export * from "./crawlerStatsParams";
|
||||
export * from "./crawlerSummary";
|
||||
export * from "./crawlerSummaryLastAt";
|
||||
export * from "./crawlerUaRow";
|
||||
export * from "./decision";
|
||||
export * from "./editRedirectParams";
|
||||
export * from "./errorInfo";
|
||||
@@ -258,6 +273,10 @@ export * from "./resCategorySchema";
|
||||
export * from "./resCategorySchemaCategory";
|
||||
export * from "./resCategorySchemaLabel";
|
||||
export * from "./resCategorySchemaMsg";
|
||||
export * from "./resCrawlerStats";
|
||||
export * from "./resCrawlerStatsDateFrom";
|
||||
export * from "./resCrawlerStatsDateTo";
|
||||
export * from "./resCrawlerStatsMsg";
|
||||
export * from "./resExtractFacts";
|
||||
export * from "./resExtractFactsMsg";
|
||||
export * from "./resExtractedFact";
|
||||
@@ -382,6 +401,10 @@ export * from "./resVerifyCandidates";
|
||||
export * from "./resVerifyCandidatesMsg";
|
||||
export * from "./resVerifyCandidatesReason";
|
||||
export * from "./resVerifyCandidatesSource";
|
||||
export * from "./resVisitStats";
|
||||
export * from "./resVisitStatsDateFrom";
|
||||
export * from "./resVisitStatsDateTo";
|
||||
export * from "./resVisitStatsMsg";
|
||||
export * from "./resWeather";
|
||||
export * from "./resWeatherMsg";
|
||||
export * from "./resWeatherWeather";
|
||||
@@ -391,6 +414,7 @@ export * from "./searchPlacesPublicParams";
|
||||
export * from "./showcaseItem";
|
||||
export * from "./showcaseItemRegion";
|
||||
export * from "./showcaseItemThumbnailUrl";
|
||||
export * from "./siteCrawlerStatsParams";
|
||||
export * from "./siteData";
|
||||
export * from "./siteDataCurrentVersionId";
|
||||
export * from "./siteDataDomain";
|
||||
@@ -404,6 +428,7 @@ export * from "./siteVersionData";
|
||||
export * from "./siteVersionDataBuildError";
|
||||
export * from "./siteVersionDataBuiltAt";
|
||||
export * from "./siteVersionDataCreatedAt";
|
||||
export * from "./siteVisitStatsParams";
|
||||
export * from "./sourceType";
|
||||
export * from "./testPost";
|
||||
export * from "./unitData";
|
||||
@@ -413,6 +438,15 @@ export * from "./validationError";
|
||||
export * from "./validationErrorCtx";
|
||||
export * from "./validationErrorLocItem";
|
||||
export * from "./verifyCandidatesParams";
|
||||
export * from "./visitDaily";
|
||||
export * from "./visitDeviceRow";
|
||||
export * from "./visitPathRow";
|
||||
export * from "./visitReferrerRow";
|
||||
export * from "./visitSiteRow";
|
||||
export * from "./visitStatsParams";
|
||||
export * from "./visitSummary";
|
||||
export * from "./visitSummaryLastAt";
|
||||
export * from "./visitUtmRow";
|
||||
export * from "./weatherData";
|
||||
export * from "./weatherDataTimezone";
|
||||
export * from "./weatherDataWindSpeed";
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { ErrorInfo } from "./errorInfo";
|
||||
import type { ResCrawlerStatsMsg } from "./resCrawlerStatsMsg";
|
||||
import type { ResCrawlerStatsDateFrom } from "./resCrawlerStatsDateFrom";
|
||||
import type { ResCrawlerStatsDateTo } from "./resCrawlerStatsDateTo";
|
||||
import type { CrawlerSummary } from "./crawlerSummary";
|
||||
import type { CrawlerDaily } from "./crawlerDaily";
|
||||
import type { CrawlerBotRow } from "./crawlerBotRow";
|
||||
import type { CrawlerSiteRow } from "./crawlerSiteRow";
|
||||
import type { CrawlerRootRow } from "./crawlerRootRow";
|
||||
import type { CrawlerUaRow } from "./crawlerUaRow";
|
||||
import type { CrawlerPathRow } from "./crawlerPathRow";
|
||||
import type { CrawlerHitRow } from "./crawlerHitRow";
|
||||
|
||||
/**
|
||||
* 전체(sites·root_files·others)와 사이트별(pages·recent)이 같은 모델을 쓴다 — 해당 없는 칸은 비어 있다.
|
||||
*/
|
||||
export interface ResCrawlerStats {
|
||||
result?: ErrorInfo;
|
||||
msg?: ResCrawlerStatsMsg;
|
||||
date_from?: ResCrawlerStatsDateFrom;
|
||||
date_to?: ResCrawlerStatsDateTo;
|
||||
summary?: CrawlerSummary;
|
||||
daily?: CrawlerDaily[];
|
||||
bots?: CrawlerBotRow[];
|
||||
sites?: CrawlerSiteRow[];
|
||||
root_files?: CrawlerRootRow[];
|
||||
others?: CrawlerUaRow[];
|
||||
pages?: CrawlerPathRow[];
|
||||
recent?: CrawlerHitRow[];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResCrawlerStatsDateFrom = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResCrawlerStatsDateTo = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResCrawlerStatsMsg = string | null;
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { ErrorInfo } from "./errorInfo";
|
||||
import type { ResVisitStatsMsg } from "./resVisitStatsMsg";
|
||||
import type { ResVisitStatsDateFrom } from "./resVisitStatsDateFrom";
|
||||
import type { ResVisitStatsDateTo } from "./resVisitStatsDateTo";
|
||||
import type { VisitSummary } from "./visitSummary";
|
||||
import type { VisitDaily } from "./visitDaily";
|
||||
import type { VisitSiteRow } from "./visitSiteRow";
|
||||
import type { VisitPathRow } from "./visitPathRow";
|
||||
import type { VisitReferrerRow } from "./visitReferrerRow";
|
||||
import type { VisitUtmRow } from "./visitUtmRow";
|
||||
import type { VisitDeviceRow } from "./visitDeviceRow";
|
||||
|
||||
/**
|
||||
* 전체(sites)와 사이트별(pages·utm)이 같은 모델을 쓴다 — 해당 없는 칸은 비어 있다.
|
||||
*/
|
||||
export interface ResVisitStats {
|
||||
result?: ErrorInfo;
|
||||
msg?: ResVisitStatsMsg;
|
||||
date_from?: ResVisitStatsDateFrom;
|
||||
date_to?: ResVisitStatsDateTo;
|
||||
realtime?: number;
|
||||
summary?: VisitSummary;
|
||||
daily?: VisitDaily[];
|
||||
sites?: VisitSiteRow[];
|
||||
pages?: VisitPathRow[];
|
||||
referrers?: VisitReferrerRow[];
|
||||
utm?: VisitUtmRow[];
|
||||
devices?: VisitDeviceRow[];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResVisitStatsDateFrom = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResVisitStatsDateTo = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResVisitStatsMsg = string | null;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type SiteCrawlerStatsParams = {
|
||||
/**
|
||||
* KST 날짜, 기본 to-6일
|
||||
*/
|
||||
from?: string | null;
|
||||
/**
|
||||
* KST 날짜, 기본 오늘
|
||||
*/
|
||||
to?: string | null;
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type SiteVisitStatsParams = {
|
||||
/**
|
||||
* KST 날짜, 기본 to-6일
|
||||
*/
|
||||
from?: string | null;
|
||||
/**
|
||||
* KST 날짜, 기본 오늘
|
||||
*/
|
||||
to?: string | null;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitDaily {
|
||||
day: string;
|
||||
views: number;
|
||||
visitors: number;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitDeviceRow {
|
||||
device: string;
|
||||
views: number;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitPathRow {
|
||||
path: string;
|
||||
views: number;
|
||||
visitors: number;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitReferrerRow {
|
||||
domain: string;
|
||||
views: number;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitSiteRow {
|
||||
site_id: string;
|
||||
place_id: string;
|
||||
name: string;
|
||||
views: number;
|
||||
visitors: number;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type VisitStatsParams = {
|
||||
/**
|
||||
* KST 날짜, 기본 to-6일
|
||||
*/
|
||||
from?: string | null;
|
||||
/**
|
||||
* KST 날짜, 기본 오늘
|
||||
*/
|
||||
to?: string | null;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { VisitSummaryLastAt } from "./visitSummaryLastAt";
|
||||
|
||||
export interface VisitSummary {
|
||||
views?: number;
|
||||
visitors?: number;
|
||||
last_at?: VisitSummaryLastAt;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type VisitSummaryLastAt = string | null;
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export interface VisitUtmRow {
|
||||
source: string;
|
||||
views: number;
|
||||
}
|
||||
@@ -18,11 +18,17 @@ import type {
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type {
|
||||
CrawlerStatsParams,
|
||||
HTTPValidationError,
|
||||
ListSitesParams,
|
||||
ListUsersParams,
|
||||
ResCrawlerStats,
|
||||
ResOpsSites,
|
||||
ResOpsUsers,
|
||||
ResVisitStats,
|
||||
SiteCrawlerStatsParams,
|
||||
SiteVisitStatsParams,
|
||||
VisitStatsParams,
|
||||
} from ".././model";
|
||||
|
||||
import { customFetch } from "../../mutator/custom-fetch";
|
||||
@@ -312,3 +318,641 @@ export function useListUsers<
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 전체 크롤러 통계(개발자 전용)
|
||||
*/
|
||||
export const crawlerStats = (
|
||||
params?: CrawlerStatsParams,
|
||||
options?: SecondParameter<typeof customFetch>,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return customFetch<ResCrawlerStats>(
|
||||
{ url: `/v1/ops/stats/crawlers`, method: "GET", params, signal },
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
export const getCrawlerStatsQueryKey = (params?: CrawlerStatsParams) => {
|
||||
return [`/v1/ops/stats/crawlers`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getCrawlerStatsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: CrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof crawlerStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getCrawlerStatsQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof crawlerStats>>> = ({
|
||||
signal,
|
||||
}) => crawlerStats(params, requestOptions, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type CrawlerStatsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof crawlerStats>>
|
||||
>;
|
||||
export type CrawlerStatsQueryError = HTTPValidationError;
|
||||
|
||||
export function useCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: undefined | CrawlerStatsParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof crawlerStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof crawlerStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: CrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof crawlerStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof crawlerStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: CrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof crawlerStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary 전체 크롤러 통계(개발자 전용)
|
||||
*/
|
||||
|
||||
export function useCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof crawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: CrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof crawlerStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getCrawlerStatsQueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 사이트별 크롤러 통계(개발자 전용)
|
||||
*/
|
||||
export const siteCrawlerStats = (
|
||||
placeId: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
options?: SecondParameter<typeof customFetch>,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return customFetch<ResCrawlerStats>(
|
||||
{
|
||||
url: `/v1/ops/sites/${placeId}/stats/crawlers`,
|
||||
method: "GET",
|
||||
params,
|
||||
signal,
|
||||
},
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
export const getSiteCrawlerStatsQueryKey = (
|
||||
placeId?: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
) => {
|
||||
return [
|
||||
`/v1/ops/sites/${placeId}/stats/crawlers`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getSiteCrawlerStatsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getSiteCrawlerStatsQueryKey(placeId, params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>
|
||||
> = ({ signal }) => siteCrawlerStats(placeId, params, requestOptions, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!placeId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type SiteCrawlerStatsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>
|
||||
>;
|
||||
export type SiteCrawlerStatsQueryError = HTTPValidationError;
|
||||
|
||||
export function useSiteCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params: undefined | SiteCrawlerStatsParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useSiteCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useSiteCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary 사이트별 크롤러 통계(개발자 전용)
|
||||
*/
|
||||
|
||||
export function useSiteCrawlerStats<
|
||||
TData = Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteCrawlerStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteCrawlerStats>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getSiteCrawlerStatsQueryOptions(
|
||||
placeId,
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 전체 방문 통계(개발자 전용)
|
||||
*/
|
||||
export const visitStats = (
|
||||
params?: VisitStatsParams,
|
||||
options?: SecondParameter<typeof customFetch>,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return customFetch<ResVisitStats>(
|
||||
{ url: `/v1/ops/stats/visits`, method: "GET", params, signal },
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
export const getVisitStatsQueryKey = (params?: VisitStatsParams) => {
|
||||
return [`/v1/ops/stats/visits`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getVisitStatsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof visitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: VisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof visitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getVisitStatsQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof visitStats>>> = ({
|
||||
signal,
|
||||
}) => visitStats(params, requestOptions, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof visitStats>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type VisitStatsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof visitStats>>
|
||||
>;
|
||||
export type VisitStatsQueryError = HTTPValidationError;
|
||||
|
||||
export function useVisitStats<
|
||||
TData = Awaited<ReturnType<typeof visitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: undefined | VisitStatsParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof visitStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof visitStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof visitStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useVisitStats<
|
||||
TData = Awaited<ReturnType<typeof visitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: VisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof visitStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof visitStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof visitStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useVisitStats<
|
||||
TData = Awaited<ReturnType<typeof visitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: VisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof visitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary 전체 방문 통계(개발자 전용)
|
||||
*/
|
||||
|
||||
export function useVisitStats<
|
||||
TData = Awaited<ReturnType<typeof visitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: VisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof visitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getVisitStatsQueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 사이트별 방문 통계(개발자 전용)
|
||||
*/
|
||||
export const siteVisitStats = (
|
||||
placeId: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
options?: SecondParameter<typeof customFetch>,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return customFetch<ResVisitStats>(
|
||||
{
|
||||
url: `/v1/ops/sites/${placeId}/stats/visits`,
|
||||
method: "GET",
|
||||
params,
|
||||
signal,
|
||||
},
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
export const getSiteVisitStatsQueryKey = (
|
||||
placeId?: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
) => {
|
||||
return [
|
||||
`/v1/ops/sites/${placeId}/stats/visits`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getSiteVisitStatsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof siteVisitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getSiteVisitStatsQueryKey(placeId, params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof siteVisitStats>>> = ({
|
||||
signal,
|
||||
}) => siteVisitStats(placeId, params, requestOptions, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!placeId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type SiteVisitStatsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof siteVisitStats>>
|
||||
>;
|
||||
export type SiteVisitStatsQueryError = HTTPValidationError;
|
||||
|
||||
export function useSiteVisitStats<
|
||||
TData = Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params: undefined | SiteVisitStatsParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof siteVisitStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof siteVisitStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useSiteVisitStats<
|
||||
TData = Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof siteVisitStats>>, TError, TData>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof siteVisitStats>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useSiteVisitStats<
|
||||
TData = Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof siteVisitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary 사이트별 방문 통계(개발자 전용)
|
||||
*/
|
||||
|
||||
export function useSiteVisitStats<
|
||||
TData = Awaited<ReturnType<typeof siteVisitStats>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
placeId: string,
|
||||
params?: SiteVisitStatsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof siteVisitStats>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customFetch>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getSiteVisitStatsQueryOptions(placeId, params, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {Bar, BarChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis} from 'recharts';
|
||||
import type {CrawlerDaily} from '@/api';
|
||||
import {PURPOSE_COLOR, PURPOSES, purposeLabel} from './labels';
|
||||
import {daysBetween} from './range';
|
||||
|
||||
// recharts 는 행 하나를 {day, search: n, training: n, …} 로 받는다.
|
||||
type Row = Record<string, string | number>;
|
||||
|
||||
function pivot(daily: CrawlerDaily[], from: string, to: string): Row[] {
|
||||
const rows = new Map<string, Row>(daysBetween(from, to).map((day) => [day, {day}]));
|
||||
for (const {day, purpose, hits} of daily) {
|
||||
const row = rows.get(day);
|
||||
if (row) row[purpose] = Number(row[purpose] ?? 0) + hits;
|
||||
}
|
||||
return [...rows.values()];
|
||||
}
|
||||
|
||||
/** recharts 를 이 파일에만 둔다 — CrawlerStatsPanel 이 lazy() 로 불러 사장님 화면 번들에 안 들어간다. */
|
||||
export default function CrawlerDailyChart({daily, from, to}: {daily: CrawlerDaily[]; from: string; to: string}) {
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={240}>
|
||||
<BarChart data={pivot(daily, from, to)} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="day" tickFormatter={(day: string) => day.slice(5)} fontSize={11} />
|
||||
<YAxis allowDecimals={false} fontSize={11} width={32} />
|
||||
<Tooltip formatter={(value, name) => [value, purposeLabel(String(name))]} />
|
||||
<Legend formatter={(value) => purposeLabel(String(value))} wrapperStyle={{fontSize: 11}} />
|
||||
{PURPOSES.map((purpose) => (
|
||||
<Bar key={purpose} dataKey={purpose} stackId="hits" fill={PURPOSE_COLOR[purpose]} />
|
||||
))}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import {lazy, Suspense, type ReactNode} from 'react';
|
||||
import {Link} from 'react-router';
|
||||
import {Bot, Loader2} from 'lucide-react';
|
||||
import type {ResCrawlerStats} from '@/api';
|
||||
import {EmptyState} from '@/components/layout/AppShell';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {formatKst, purposeLabel} from './labels';
|
||||
import {RANGE_DAYS, type RangeDays} from './range';
|
||||
|
||||
const CrawlerDailyChart = lazy(() => import('./CrawlerDailyChart'));
|
||||
|
||||
export function RangeTabs({value, onChange}: {value: RangeDays; onChange: (days: RangeDays) => void}) {
|
||||
return (
|
||||
<div className="flex gap-1.5">
|
||||
{RANGE_DAYS.map((days) => (
|
||||
<button
|
||||
key={days}
|
||||
type="button"
|
||||
onClick={() => onChange(days)}
|
||||
className={cn(
|
||||
'h-8 cursor-pointer rounded-md border px-3 text-xs font-medium transition-colors',
|
||||
value === days ? 'border-foreground bg-foreground text-background' : 'border-border hover:bg-muted',
|
||||
)}
|
||||
>
|
||||
최근 {days}일
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Stat({label, value}: {label: string; value: ReactNode}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="mt-1 text-xl font-semibold tabular-nums">{value}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function Section({title, children}: {title: string; children: ReactNode}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>{children}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function Table({head, rows}: {head: string[]; rows: ReactNode[][]}) {
|
||||
if (rows.length === 0) return <p className="text-xs text-muted-foreground">기록이 없습니다.</p>;
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left text-muted-foreground">
|
||||
{head.map((h) => (
|
||||
<th key={h} className="py-2 pr-3 font-medium">
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((cells, i) => (
|
||||
<tr key={i} className="border-b border-border last:border-0">
|
||||
{cells.map((cell, j) => (
|
||||
<td key={j} className="py-2 pr-3 align-top">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 크롤링 탭 본문. scope 에 따라 아래쪽 표가 갈린다 — 전체: 사이트 순위·공용 파일·기타 UA / 사이트: 페이지·최근 기록. */
|
||||
export function CrawlerStatsPanel({data, scope}: {data: ResCrawlerStats; scope: 'overall' | 'site'}) {
|
||||
const summary = data.summary;
|
||||
if (!summary?.total) {
|
||||
return <EmptyState icon={Bot} title="아직 크롤링 기록이 없습니다" description="선택한 기간에 들어온 봇 요청이 없습니다." />;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<Stat label="총 요청" value={summary.total ?? 0} />
|
||||
<Stat label="AI 봇 요청" value={summary.ai ?? 0} />
|
||||
<Stat label="봇 종류" value={summary.bots ?? 0} />
|
||||
<Stat label="마지막 크롤링" value={<span className="text-base">{formatKst(summary.last_at)}</span>} />
|
||||
</div>
|
||||
|
||||
<Section title="일별 요청 (용도별)">
|
||||
{data.date_from && data.date_to && (
|
||||
<Suspense fallback={<Loader2 className="mx-auto size-5 animate-spin text-muted-foreground" />}>
|
||||
<CrawlerDailyChart daily={data.daily ?? []} from={data.date_from} to={data.date_to} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="봇별">
|
||||
<Table
|
||||
head={['봇', '회사', '용도', '요청', '마지막']}
|
||||
rows={(data.bots ?? []).map((b) => [
|
||||
b.bot,
|
||||
b.vendor ?? '—',
|
||||
<Badge key="p" variant="outline">
|
||||
{purposeLabel(b.purpose)}
|
||||
</Badge>,
|
||||
b.hits,
|
||||
formatKst(b.last_at),
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
{scope === 'overall' ? (
|
||||
<>
|
||||
<Section title="크롤링이 많은 사이트">
|
||||
<Table
|
||||
head={['사이트', '요청', 'AI 봇', '마지막']}
|
||||
rows={(data.sites ?? []).map((s) => [
|
||||
<Link key="n" to={`/ops/sites/${s.place_id}/stats`} className="font-medium hover:underline">
|
||||
{s.name}
|
||||
</Link>,
|
||||
s.hits,
|
||||
s.ai_hits,
|
||||
formatKst(s.last_at),
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="robots.txt · sitemap.xml">
|
||||
<Table
|
||||
head={['파일', '봇', '용도', '요청', '마지막']}
|
||||
rows={(data.root_files ?? []).map((r) => [
|
||||
r.kind === 'robots' ? 'robots.txt' : 'sitemap.xml',
|
||||
r.bot ?? '기타',
|
||||
purposeLabel(r.purpose),
|
||||
r.hits,
|
||||
formatKst(r.last_at),
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="목록 밖 봇 (기타) — 자주 보이면 목록에 올린다">
|
||||
<Table
|
||||
head={['User-Agent', '요청', '마지막']}
|
||||
rows={(data.others ?? []).map((o) => [
|
||||
<span key="ua" className="font-mono text-[11px] break-all">
|
||||
{o.user_agent}
|
||||
</span>,
|
||||
o.hits,
|
||||
formatKst(o.last_at),
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Section title="많이 읽힌 페이지">
|
||||
<Table
|
||||
head={['경로', '요청', '마지막']}
|
||||
rows={(data.pages ?? []).map((p) => [
|
||||
<span key="p" className="break-all">
|
||||
{p.path}
|
||||
</span>,
|
||||
p.hits,
|
||||
formatKst(p.last_at),
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="최근 크롤링 50건">
|
||||
<Table
|
||||
head={['시각', '봇', '용도', '경로']}
|
||||
rows={(data.recent ?? []).map((r) => [
|
||||
formatKst(r.created_at),
|
||||
r.bot ?? '기타',
|
||||
purposeLabel(r.purpose),
|
||||
<span key="p" className="break-all">
|
||||
{r.path}
|
||||
</span>,
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
export type StatsKind = 'visits' | 'crawlers';
|
||||
|
||||
const KINDS: ReadonlyArray<readonly [StatsKind, string]> = [
|
||||
['visits', '방문'],
|
||||
['crawlers', '크롤링'],
|
||||
];
|
||||
|
||||
/** 통계 종류 — 사람 방문과 봇 크롤링은 세는 방법이 달라 한 화면에 섞지 않는다. */
|
||||
export function KindTabs({kind, onChange}: {kind: StatsKind; onChange: (kind: StatsKind) => void}) {
|
||||
return (
|
||||
<div className="inline-flex rounded-md border border-border p-0.5">
|
||||
{KINDS.map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => onChange(value)}
|
||||
className={cn(
|
||||
'h-7 cursor-pointer rounded px-3 text-xs font-medium transition-colors',
|
||||
kind === value ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {useState} from 'react';
|
||||
import {keepPreviousData} from '@tanstack/react-query';
|
||||
import {Loader2} from 'lucide-react';
|
||||
import {useCrawlerStats} from '@/api';
|
||||
import {EmptyState} from '@/components/layout/AppShell';
|
||||
import {CrawlerStatsPanel, RangeTabs} from './CrawlerStatsPanel';
|
||||
import {rangeParams, type RangeDays} from './range';
|
||||
|
||||
export function OverallCrawlerStats() {
|
||||
const [days, setDays] = useState<RangeDays>(7);
|
||||
const {data, isLoading, isError, error} = useCrawlerStats(rangeParams(days), {
|
||||
query: {placeholderData: keepPreviousData},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold">크롤링 (전체 사이트)</h2>
|
||||
<RangeTabs value={days} onChange={setDays} />
|
||||
</div>
|
||||
{isLoading && (
|
||||
<div className="flex justify-center py-20 text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{(isError || data?.result?.success === false) && (
|
||||
<EmptyState
|
||||
title="통계를 불러오지 못했습니다"
|
||||
description={(error as Error)?.message ?? data?.result?.desc ?? '잠시 후 다시 시도해 주세요.'}
|
||||
/>
|
||||
)}
|
||||
{data?.result?.success && <CrawlerStatsPanel data={data} scope="overall" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {useState} from 'react';
|
||||
import {KindTabs, type StatsKind} from './KindTabs';
|
||||
import {OverallCrawlerStats} from './OverallCrawlerStats';
|
||||
import {OverallVisitStats} from './OverallVisitStats';
|
||||
|
||||
/** 사이트관리 "전체 통계" 탭 본문 — 방문과 크롤링을 하위 탭으로 가른다. */
|
||||
export function OverallStats() {
|
||||
const [kind, setKind] = useState<StatsKind>('visits');
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<KindTabs kind={kind} onChange={setKind} />
|
||||
{kind === 'visits' ? <OverallVisitStats /> : <OverallCrawlerStats />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {useState} from 'react';
|
||||
import {keepPreviousData} from '@tanstack/react-query';
|
||||
import {Loader2} from 'lucide-react';
|
||||
import {useVisitStats} from '@/api';
|
||||
import {EmptyState} from '@/components/layout/AppShell';
|
||||
import {RangeTabs} from './CrawlerStatsPanel';
|
||||
import {rangeParams, type RangeDays} from './range';
|
||||
import {VisitStatsPanel} from './VisitStatsPanel';
|
||||
|
||||
/** 실시간 숫자는 30초마다 다시 부른다 — "지금 몇 명" 은 화면을 열어 둔 채 보는 숫자다. */
|
||||
const REFRESH_MS = 30_000;
|
||||
|
||||
export function OverallVisitStats() {
|
||||
const [days, setDays] = useState<RangeDays>(7);
|
||||
const {data, isLoading, isError, error} = useVisitStats(rangeParams(days), {
|
||||
query: {placeholderData: keepPreviousData, refetchInterval: REFRESH_MS},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold">방문 (전체 사이트)</h2>
|
||||
<RangeTabs value={days} onChange={setDays} />
|
||||
</div>
|
||||
{isLoading && (
|
||||
<div className="flex justify-center py-20 text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{(isError || data?.result?.success === false) && (
|
||||
<EmptyState
|
||||
title="통계를 불러오지 못했습니다"
|
||||
description={(error as Error)?.message ?? data?.result?.desc ?? '잠시 후 다시 시도해 주세요.'}
|
||||
/>
|
||||
)}
|
||||
{data?.result?.success && <VisitStatsPanel data={data} scope="overall" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
export type SitesTab = 'list' | 'stats';
|
||||
|
||||
const TABS: ReadonlyArray<readonly [SitesTab, string]> = [
|
||||
['list', '목록'],
|
||||
['stats', '전체 통계'],
|
||||
];
|
||||
|
||||
/** 사이트관리 상단 탭 — 현재 탭은 URL(?tab=)이 들고 있다. */
|
||||
export function SitesTabs({tab, onChange}: {tab: SitesTab; onChange: (tab: SitesTab) => void}) {
|
||||
return (
|
||||
<div className="mb-4 flex gap-4 border-b border-border text-sm">
|
||||
{TABS.map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => onChange(value)}
|
||||
className={cn(
|
||||
'-mb-px cursor-pointer border-b-2 px-1 pb-2 font-medium transition-colors',
|
||||
tab === value
|
||||
? 'border-foreground text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {Bar, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis} from 'recharts';
|
||||
import type {VisitDaily} from '@/api';
|
||||
import {daysBetween} from './range';
|
||||
|
||||
const LABEL: Record<string, string> = {views: '페이지뷰', visitors: '방문자'};
|
||||
|
||||
/** recharts 는 이 파일에만 둔다 — VisitStatsPanel 이 lazy() 로 부른다. */
|
||||
export default function VisitDailyChart({daily, from, to}: {daily: VisitDaily[]; from: string; to: string}) {
|
||||
const byDay = new Map(daily.map((d) => [d.day, d]));
|
||||
const rows = daysBetween(from, to).map((day) => ({
|
||||
day,
|
||||
views: byDay.get(day)?.views ?? 0,
|
||||
visitors: byDay.get(day)?.visitors ?? 0,
|
||||
}));
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={240}>
|
||||
<ComposedChart data={rows} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="day" tickFormatter={(day: string) => day.slice(5)} fontSize={11} />
|
||||
<YAxis allowDecimals={false} fontSize={11} width={32} />
|
||||
<Tooltip formatter={(value, name) => [value, LABEL[String(name)] ?? name]} />
|
||||
<Legend formatter={(value) => LABEL[String(value)] ?? value} wrapperStyle={{fontSize: 11}} />
|
||||
<Bar dataKey="views" fill="#93c5fd" />
|
||||
<Line dataKey="visitors" stroke="#2563eb" strokeWidth={2} dot={false} />
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {lazy, Suspense} from 'react';
|
||||
import {Link} from 'react-router';
|
||||
import {Loader2, Users} from 'lucide-react';
|
||||
import type {ResVisitStats} from '@/api';
|
||||
import {EmptyState} from '@/components/layout/AppShell';
|
||||
import {Section, Stat, Table} from './CrawlerStatsPanel';
|
||||
import {formatKst} from './labels';
|
||||
|
||||
const VisitDailyChart = lazy(() => import('./VisitDailyChart'));
|
||||
|
||||
const DEVICE_LABEL: Record<string, string> = {desktop: '데스크톱', mobile: '모바일', tablet: '태블릿'};
|
||||
|
||||
/** 방문 탭 본문. 전체: 사이트 순위 / 사이트별: 페이지·캠페인. 유입·기기는 공통. */
|
||||
export function VisitStatsPanel({data, scope}: {data: ResVisitStats; scope: 'overall' | 'site'}) {
|
||||
const summary = data.summary;
|
||||
const realtime = data.realtime ?? 0;
|
||||
// 기간 안에 기록이 없어도 지금 들어와 있는 사람이 있으면 그 숫자는 보여 준다.
|
||||
if (!summary?.views && !realtime) {
|
||||
return <EmptyState icon={Users} title="아직 방문 기록이 없습니다" description="선택한 기간에 들어온 방문이 없습니다." />;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<Stat label="실시간 방문자 (최근 5분)" value={realtime} />
|
||||
<Stat label="페이지뷰" value={summary?.views ?? 0} />
|
||||
<Stat label="방문자" value={summary?.visitors ?? 0} />
|
||||
<Stat label="마지막 방문" value={<span className="text-base">{formatKst(summary?.last_at)}</span>} />
|
||||
</div>
|
||||
|
||||
<Section title="일별 방문자 · 페이지뷰">
|
||||
{data.date_from && data.date_to && (
|
||||
<Suspense fallback={<Loader2 className="mx-auto size-5 animate-spin text-muted-foreground" />}>
|
||||
<VisitDailyChart daily={data.daily ?? []} from={data.date_from} to={data.date_to} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{scope === 'overall' ? (
|
||||
<Section title="방문이 많은 사이트">
|
||||
<Table
|
||||
head={['사이트', '페이지뷰', '방문자']}
|
||||
rows={(data.sites ?? []).map((s) => [
|
||||
<Link key="n" to={`/ops/sites/${s.place_id}/stats`} className="font-medium hover:underline">
|
||||
{s.name}
|
||||
</Link>,
|
||||
s.views,
|
||||
s.visitors,
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
) : (
|
||||
<>
|
||||
<Section title="많이 본 페이지">
|
||||
<Table
|
||||
head={['경로', '페이지뷰', '방문자']}
|
||||
rows={(data.pages ?? []).map((p) => [
|
||||
<span key="p" className="break-all">
|
||||
{p.path}
|
||||
</span>,
|
||||
p.views,
|
||||
p.visitors,
|
||||
])}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="캠페인 (utm_source)">
|
||||
<Table head={['출처', '페이지뷰']} rows={(data.utm ?? []).map((u) => [u.source, u.views])} />
|
||||
</Section>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Section title="유입 도메인">
|
||||
<Table head={['도메인', '페이지뷰']} rows={(data.referrers ?? []).map((r) => [r.domain, r.views])} />
|
||||
</Section>
|
||||
<Section title="기기">
|
||||
<Table
|
||||
head={['기기', '페이지뷰']}
|
||||
rows={(data.devices ?? []).map((d) => [DEVICE_LABEL[d.device] ?? d.device, d.views])}
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** 용도 순서 — 누적 막대의 아래→위, 표의 정렬 기준. AI 쪽을 아래에 깐다(이 화면이 보려는 것). */
|
||||
export const PURPOSES = ['search', 'user-fetch', 'training', 'search-engine', 'other'] as const;
|
||||
export type Purpose = (typeof PURPOSES)[number];
|
||||
|
||||
export const PURPOSE_LABEL: Record<Purpose, string> = {
|
||||
search: 'AI 검색 색인',
|
||||
'user-fetch': 'AI 실시간 조회',
|
||||
training: 'AI 학습',
|
||||
'search-engine': '검색엔진',
|
||||
other: '기타',
|
||||
};
|
||||
|
||||
export const PURPOSE_COLOR: Record<Purpose, string> = {
|
||||
search: '#2563eb',
|
||||
'user-fetch': '#7c3aed',
|
||||
training: '#0d9488',
|
||||
'search-engine': '#f59e0b',
|
||||
other: '#9ca3af',
|
||||
};
|
||||
|
||||
export function purposeLabel(value: string): string {
|
||||
return PURPOSE_LABEL[value as Purpose] ?? value;
|
||||
}
|
||||
|
||||
/** 서버 시각(UTC ISO)을 KST 로 읽는다 — 운영자가 한국에 있지 않아도 같은 숫자를 본다. */
|
||||
export function formatKst(iso?: string | null): string {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString('ko-KR', {
|
||||
timeZone: 'Asia/Seoul',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export const RANGE_DAYS = [7, 30, 90] as const;
|
||||
export type RangeDays = (typeof RANGE_DAYS)[number];
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const KST_OFFSET_MS = 9 * 3_600_000;
|
||||
|
||||
/** 서버가 KST 날짜로 자르므로 KST 오늘을 기준으로 만든다(브라우저 시간대와 무관하게). */
|
||||
export function rangeParams(days: RangeDays): {from: string; to: string} {
|
||||
const kstNow = Date.now() + KST_OFFSET_MS;
|
||||
const to = new Date(kstNow).toISOString().slice(0, 10);
|
||||
const from = new Date(kstNow - (days - 1) * DAY_MS).toISOString().slice(0, 10);
|
||||
return {from, to};
|
||||
}
|
||||
|
||||
/** from~to 의 모든 날짜 — 요청이 없던 날도 막대 자리를 비워 둬야 추이가 왜곡되지 않는다. */
|
||||
export function daysBetween(from: string, to: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let t = Date.parse(`${from}T00:00:00Z`); t <= Date.parse(`${to}T00:00:00Z`); t += DAY_MS) {
|
||||
out.push(new Date(t).toISOString().slice(0, 10));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {useState} from 'react';
|
||||
import {Link, Navigate, useParams} from 'react-router';
|
||||
import {keepPreviousData} from '@tanstack/react-query';
|
||||
import {ArrowLeft, Loader2} from 'lucide-react';
|
||||
import {UserRole, useSiteCrawlerStats, useSiteVisitStats} from '@/api';
|
||||
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
||||
import {CrawlerStatsPanel, RangeTabs} from '@/features/ops-stats/CrawlerStatsPanel';
|
||||
import {KindTabs, type StatsKind} from '@/features/ops-stats/KindTabs';
|
||||
import {rangeParams, type RangeDays} from '@/features/ops-stats/range';
|
||||
import {VisitStatsPanel} from '@/features/ops-stats/VisitStatsPanel';
|
||||
import {useAuthStore} from '@/stores/auth';
|
||||
|
||||
/** 실시간 방문자는 30초마다 다시 부른다(전체 통계와 같은 주기). */
|
||||
const REFRESH_MS = 30_000;
|
||||
|
||||
/** 사이트별 통계 — 개발자(DEVELOPER) 전용. */
|
||||
export function OpsSiteStatsPage() {
|
||||
const {placeId = ''} = useParams();
|
||||
const isRestoring = useAuthStore((s) => s.isRestoring);
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const [days, setDays] = useState<RangeDays>(7);
|
||||
const [kind, setKind] = useState<StatsKind>('visits');
|
||||
// enabled: OpsSitesPage 와 같은 이유 — role 확정 전 요청이 403 토스트를 먼저 띄운다. 보이는 탭만 부른다.
|
||||
const ready = role === UserRole.DEVELOPER && !!placeId;
|
||||
const params = rangeParams(days);
|
||||
const visits = useSiteVisitStats(placeId, params, {
|
||||
query: {placeholderData: keepPreviousData, enabled: ready && kind === 'visits', refetchInterval: REFRESH_MS},
|
||||
});
|
||||
const crawlers = useSiteCrawlerStats(placeId, params, {
|
||||
query: {placeholderData: keepPreviousData, enabled: ready && kind === 'crawlers'},
|
||||
});
|
||||
const current = kind === 'visits' ? visits : crawlers;
|
||||
|
||||
if (isRestoring) return null;
|
||||
if (role !== UserRole.DEVELOPER) return <Navigate to="/sites" replace />;
|
||||
|
||||
return (
|
||||
<AppShell>
|
||||
<PageContainer
|
||||
title="사이트 통계"
|
||||
description="이 사이트의 사람 방문과 봇 요청입니다. 봇은 자칭 크롤러(UA 기준)이며 IP 대역으로 진위를 확인하지 않습니다."
|
||||
actions={
|
||||
<Link
|
||||
to="/ops/sites"
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
>
|
||||
<ArrowLeft className="size-3.5" />
|
||||
사이트관리
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<KindTabs kind={kind} onChange={setKind} />
|
||||
<RangeTabs value={days} onChange={setDays} />
|
||||
</div>
|
||||
{current.isLoading && (
|
||||
<div className="flex justify-center py-20 text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{(current.isError || current.data?.result?.success === false) && (
|
||||
<EmptyState
|
||||
title="통계를 불러오지 못했습니다"
|
||||
description={
|
||||
(current.error as Error)?.message ?? current.data?.result?.desc ?? '잠시 후 다시 시도해 주세요.'
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{kind === 'visits' && visits.data?.result?.success && <VisitStatsPanel data={visits.data} scope="site" />}
|
||||
{kind === 'crawlers' && crawlers.data?.result?.success && (
|
||||
<CrawlerStatsPanel data={crawlers.data} scope="site" />
|
||||
)}
|
||||
</PageContainer>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
// 라우트 모듈은 default export 를 요구한다(routes.ts 가 이 파일을 가리킨다).
|
||||
export default OpsSiteStatsPage;
|
||||
@@ -1,13 +1,15 @@
|
||||
import {useState} from 'react';
|
||||
import {Link, Navigate} from 'react-router';
|
||||
import {Link, Navigate, useSearchParams} from 'react-router';
|
||||
import {keepPreviousData} from '@tanstack/react-query';
|
||||
import {Building2, ChevronLeft, ChevronRight, ExternalLink, Loader2, Newspaper, Pencil, Search, Trash2, X} from 'lucide-react';
|
||||
import {BarChart3, Building2, ChevronLeft, ChevronRight, ExternalLink, Loader2, Newspaper, Pencil, Search, Trash2, X} from 'lucide-react';
|
||||
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
|
||||
import {changeStatus, deletePlace, PublishAction, UserRole, useListSites, type OpsSiteData} from '@/api';
|
||||
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
||||
import {Badge} from '@/components/ui/badge';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {OverallStats} from '@/features/ops-stats/OverallStats';
|
||||
import {SitesTabs, type SitesTab} from '@/features/ops-stats/SitesTabs';
|
||||
import {notify, notifyApiError} from '@/lib/notify';
|
||||
import {PUBLISH_HOST} from '@/lib/site';
|
||||
import {cn} from '@/lib/utils';
|
||||
@@ -45,11 +47,15 @@ export function OpsSitesPage() {
|
||||
const [search, setSearch] = useState('');
|
||||
const [category, setCategory] = useState<number | null>(null);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
// 탭을 URL 에 둔다 — 사이트별 통계에서 뒤로 오면 보던 탭으로 돌아온다.
|
||||
const [params, setParams] = useSearchParams();
|
||||
const tab: SitesTab = params.get('tab') === 'stats' ? 'stats' : 'list';
|
||||
const changeTab = (next: SitesTab) => setParams(next === 'list' ? {} : {tab: next});
|
||||
const size = 20;
|
||||
// enabled: role 이 확정되기 전엔 요청하지 않는다 — 어차피 백엔드가 403 으로 막지만, 사장님 화면에서 실패 토스트가 먼저 뜨는 것과 새로고침 때 잠깐의 오탐 리다이렉트를 막는다.
|
||||
const {data, isLoading, isError, error, refetch} = useListSites(
|
||||
{page, size, search: search || undefined, category: category ?? undefined},
|
||||
{query: {placeholderData: keepPreviousData, enabled: role === UserRole.DEVELOPER}},
|
||||
{query: {placeholderData: keepPreviousData, enabled: role === UserRole.DEVELOPER && tab === 'list'}},
|
||||
);
|
||||
|
||||
// RequireAuth 와 같은 이유 — 복구가 끝나기 전에 판단하면 새로고침마다 리다이렉트가 한 번 번쩍인다.
|
||||
@@ -85,6 +91,17 @@ export function OpsSitesPage() {
|
||||
if (isRestoring) return null;
|
||||
if (role !== UserRole.DEVELOPER) return <Navigate to="/sites" replace />;
|
||||
|
||||
if (tab === 'stats') {
|
||||
return (
|
||||
<AppShell>
|
||||
<PageContainer title="사이트관리" description="전 계정 사이트 발행 현황입니다. 회사 스코프 없이 전부 보입니다.">
|
||||
<SitesTabs tab={tab} onChange={changeTab} />
|
||||
<OverallStats />
|
||||
</PageContainer>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
const rows = data?.sites ?? [];
|
||||
const total = data?.total ?? 0;
|
||||
const lastPage = Math.max(1, Math.ceil(total / size));
|
||||
@@ -121,6 +138,7 @@ export function OpsSitesPage() {
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SitesTabs tab={tab} onChange={changeTab} />
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
{[null, ...Object.keys(CATEGORY_LABEL).map(Number)].map((value) => (
|
||||
<button
|
||||
@@ -193,6 +211,13 @@ export function OpsSitesPage() {
|
||||
<Newspaper className="size-3.5" />
|
||||
미니블로그
|
||||
</Link>
|
||||
<Link
|
||||
to={`/ops/sites/${row.place_id}/stats`}
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
|
||||
>
|
||||
<BarChart3 className="size-3.5" />
|
||||
통계
|
||||
</Link>
|
||||
{url ? (
|
||||
<a
|
||||
href={url}
|
||||
|
||||
@@ -23,6 +23,7 @@ export default [
|
||||
// "내 사이트" 카드의 관리 메뉴에서 온다(?placeId= 로 어느 사이트인지 받는다) — 사장님 여럿이 사이트 여럿을 가질 수 있어 전역 메뉴 하나로는 못 고른다.
|
||||
route('blog', 'pages/BlogPostsPage.tsx'),
|
||||
route('ops/sites', 'pages/OpsSitesPage.tsx'),
|
||||
route('ops/sites/:placeId/stats', 'pages/OpsSiteStatsPage.tsx'),
|
||||
route('ops/users', 'pages/OpsUsersPage.tsx'),
|
||||
]),
|
||||
|
||||
|
||||
@@ -33,11 +33,24 @@ export default defineConfig({
|
||||
target: 'http://127.0.0.1:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
// 빌더 미리보기 iframe(SitePreview 의 /preview?placeId=…) — 발행본 번들을 띄우는 셸이 :3001 에 있다.
|
||||
// 없으면 이 경로가 빌더 라우터로 떨어져 미리보기 칸에 빌더 자신의 404 가 뜬다(운영은 nginx `location = /preview`).
|
||||
'^/preview(?:[/?]|$)': {
|
||||
target: 'http://127.0.0.1:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
/** 발행본의 JS·CSS 번들. */
|
||||
'^/assets/': {
|
||||
target: 'http://127.0.0.1:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
// 발행 페이지(/s/…)는 같은 오리진의 상대 경로 /v1/… 로 부른다(운영은 nginx 가 넘긴다).
|
||||
// 개발 서버엔 그 길이 없어 날씨·후기·방문 비콘이 이 포트에서만 죽었다. 빌더는 VITE_API_BASE_URL 로
|
||||
// 백엔드를 직접 부르므로 이 규칙에 걸리지 않는다.
|
||||
'^/v1/': {
|
||||
target: process.env.DEV_API_PROXY ?? 'http://127.0.0.1:9800',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
// 도커(Mac) 바인드마운트는 네이티브 inotify 가 컨테이너로 전파되지 않아 파일 감시를 polling 으로 해야 호스트 변경이 감지된다.
|
||||
watch: {usePolling: true, interval: 300},
|
||||
|
||||
@@ -2,6 +2,7 @@ import {StrictMode, useEffect} from 'react';
|
||||
import {createRoot, hydrateRoot} from 'react-dom/client';
|
||||
import {templateOf, type SitePayload} from '@o2o/shared';
|
||||
import {App} from './App';
|
||||
import {sendVisit} from './lib/visit-beacon';
|
||||
import {fontHref, themeVars} from '@site/seo/head';
|
||||
import './index.css';
|
||||
|
||||
@@ -79,6 +80,8 @@ if (injected) {
|
||||
<App payload={injected} />
|
||||
</StrictMode>,
|
||||
);
|
||||
// 발행 페이지에서만 센다 — 미리보기(renderPreview)·개발 픽스처 분기는 보내지 않는다.
|
||||
sendVisit();
|
||||
} else if (previewPlaceId) {
|
||||
void renderPreview(previewPlaceId).catch((ex: unknown) => {
|
||||
container.textContent = `미리보기를 불러오지 못했습니다 — ${ex instanceof Error ? ex.message : String(ex)}`;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {buildVisitPayload, isOptedOut} from './visit-beacon';
|
||||
|
||||
describe('buildVisitPayload', () => {
|
||||
it('발행 페이지의 경로·리퍼러·utm_source 를 싣는다', () => {
|
||||
const payload = buildVisitPayload(
|
||||
{pathname: '/s/mermum/rooms', search: '?utm_source=chatgpt.com&x=1'},
|
||||
'https://www.google.com/',
|
||||
);
|
||||
expect(payload).toEqual({path: '/s/mermum/rooms', referrer: 'https://www.google.com/', utm_source: 'chatgpt.com'});
|
||||
});
|
||||
|
||||
it('utm 이 없으면 빈 값', () => {
|
||||
expect(buildVisitPayload({pathname: '/s/mermum', search: ''}, '')).toEqual({
|
||||
path: '/s/mermum',
|
||||
referrer: '',
|
||||
utm_source: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('탭(#/…)도 경로에 싣는다 — 발행 사이트의 하위 페이지는 해시 탭이다', () => {
|
||||
expect(buildVisitPayload({pathname: '/s/mermum', search: '', hash: '#/stay'}, '')?.path).toBe('/s/mermum#/stay');
|
||||
expect(buildVisitPayload({pathname: '/s/mermum', search: '', hash: '#/'}, '')?.path).toBe('/s/mermum');
|
||||
expect(buildVisitPayload({pathname: '/s/mermum', search: '', hash: '#reviews'}, '')?.path).toBe('/s/mermum');
|
||||
});
|
||||
|
||||
it('발행 경로가 아니면 보내지 않는다(미리보기·빌더)', () => {
|
||||
expect(buildVisitPayload({pathname: '/preview', search: '?placeId=1'}, '')).toBeNull();
|
||||
expect(buildVisitPayload({pathname: '/builder', search: ''}, '')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isOptedOut', () => {
|
||||
it('플래그가 1 이면 빠진다', () => {
|
||||
expect(isOptedOut({getItem: () => '1'})).toBe(true);
|
||||
expect(isOptedOut({getItem: () => null})).toBe(false);
|
||||
});
|
||||
|
||||
it('저장소 접근이 막혀도 던지지 않는다', () => {
|
||||
expect(
|
||||
isOptedOut({
|
||||
getItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/** 사람 방문 비콘 — 쿠키·식별자를 남기지 않는다. 방문자 구분은 서버가 IP·UA·월로 해시해 한다. */
|
||||
|
||||
const ENDPOINT = '/v1/track/view';
|
||||
/** 운영자가 자기 방문을 빼고 싶을 때 콘솔에서 `localStorage.setItem('web4ai.stats.disabled', '1')`. */
|
||||
const OPT_OUT_KEY = 'web4ai.stats.disabled';
|
||||
|
||||
type Loc = {pathname: string; search: string; hash?: string};
|
||||
type Store = {getItem(key: string): string | null};
|
||||
|
||||
export type VisitPayload = {path: string; referrer: string; utm_source: string};
|
||||
|
||||
export function buildVisitPayload(loc: Loc, referrer: string): VisitPayload | null {
|
||||
// 발행 페이지(/s/<slug>…)만 센다 — 같은 번들이 /preview 에서도 돈다.
|
||||
if (!loc.pathname.startsWith('/s/')) return null;
|
||||
// 하위 페이지는 HTML 이 따로 없고 해시 탭(#/stay)이다(layouts/*/Frame.tsx). 탭을 빼면 "많이 본 페이지" 가
|
||||
// 첫 화면 한 줄로 뭉친다. #/ 는 홈, #/ 로 시작하지 않는 해시는 문서 안 앵커라 경로가 아니다.
|
||||
const hash = loc.hash ?? '';
|
||||
const tab = hash.startsWith('#/') && hash !== '#/' ? hash : '';
|
||||
const utm = new URLSearchParams(loc.search).get('utm_source') ?? '';
|
||||
return {path: loc.pathname + tab, referrer, utm_source: utm};
|
||||
}
|
||||
|
||||
export function isOptedOut(store: Store | undefined): boolean {
|
||||
try {
|
||||
return store?.getItem(OPT_OUT_KEY) === '1';
|
||||
} catch {
|
||||
// 사파리 비공개 창 등에서 저장소 접근이 막히면 그냥 센다 — 통계 때문에 페이지가 깨지면 안 된다.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 페이지가 열릴 때, 그리고 탭(#/…)을 옮길 때마다. 실패해도 조용히 지나간다 — 통계가 손님 화면을 막으면 안 된다. */
|
||||
export function sendVisit(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
let store: Store | undefined;
|
||||
try {
|
||||
store = window.localStorage;
|
||||
} catch {
|
||||
store = undefined;
|
||||
}
|
||||
if (isOptedOut(store)) return;
|
||||
sendOnce();
|
||||
window.addEventListener('hashchange', sendOnce);
|
||||
}
|
||||
|
||||
function sendOnce(): void {
|
||||
const payload = buildVisitPayload(window.location, document.referrer);
|
||||
if (!payload) return;
|
||||
const body = JSON.stringify(payload);
|
||||
// text/plain — sendBeacon 이 프리플라이트 없이 보낼 수 있는 형식이다.
|
||||
const blob = new Blob([body], {type: 'text/plain;charset=UTF-8'});
|
||||
if (navigator.sendBeacon?.(ENDPOINT, blob)) return;
|
||||
// 전송 실패는 손님에게 보일 일이 아니다 — 결과를 버린다.
|
||||
void fetch(ENDPOINT, {method: 'POST', body, keepalive: true, headers: {'Content-Type': 'text/plain'}}).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user