upload
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
# 环境配置(含密码)
|
||||
.env
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# 前端
|
||||
node_modules/
|
||||
frontend/dist/
|
||||
|
||||
# 编辑器
|
||||
.idea/
|
||||
.vscode/
|
||||
*.log
|
||||
@@ -0,0 +1,121 @@
|
||||
# 美团酒店任务看板
|
||||
|
||||
以 `headers_project.hotel_hd` **账号池为主线**的可视化看板:看清楚"池子还剩几个能用、每个账号今天跑了多少条、每个城市跑了多少条、哪个账号拿不到任务",并支持在前端**改绑定城市(自动清空代理)**与**单条重置 is_ok**。
|
||||
|
||||
- 后端:FastAPI(:8011),双数据源(主库只读 + 抓包库仅写 3 列)
|
||||
- 前端:Vue 3 + TypeScript + Vite(开发 :5175;构建产物由后端托管,生产只需 Python)
|
||||
- **硬约束:不新增任何数据库表**(埋点与审计都写本地 JSONL 文件)
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
酒店/
|
||||
├── 酒店详情.py # 采集主流程(已加埋点,不改原分支逻辑)
|
||||
├── 酒店任务拿交.py # 平台 API 客户端(upload_one_task 现在 return 响应体)
|
||||
├── hotel_insight.py # 埋点模块:写 logs/run_YYYYMMDD.jsonl
|
||||
├── logs/ # run_*.jsonl(埋点)+ audit.jsonl(写操作审计)
|
||||
└── dashboard/
|
||||
├── backend/app/ # FastAPI:routers/ + services/
|
||||
├── backend/scripts/ # 冒烟与验收脚本
|
||||
├── frontend/ # Vue3 + TS + Vite
|
||||
├── docs/ # 01~06 文档 + 表结构 + 设计风格 + 自检报告
|
||||
└── start.py # 一键启动
|
||||
```
|
||||
|
||||
## 环境要求
|
||||
|
||||
| 项 | 静态模式 | 开发模式 |
|
||||
|---|---|---|
|
||||
| Python | ≥ 3.10 | 同左 |
|
||||
| Node.js | 不需要 | ≥ 20.19(本机 v24.16 已验证) |
|
||||
| 网络 | 能连 `183.6.7.91:33016`、`192.168.5.2:3307`、`ktl-001.dsfdl-henan.xyz` | 同左 |
|
||||
|
||||
## 配置
|
||||
|
||||
复制 `backend/.env.example` 为 `backend/.env` 并填真实密码(**含密码,不要外传**):
|
||||
|
||||
```ini
|
||||
MAIN_DB_URL=mysql+aiomysql://root:密码@183.6.7.91:33016/mt_hotel?charset=utf8mb4
|
||||
HEADERS_DB_URL=mysql+aiomysql://root:密码@192.168.5.2:3307/headers_project?charset=utf8mb4
|
||||
LOG_DIR=../../logs
|
||||
CORS_ORIGINS=http://localhost:5175,http://127.0.0.1:5175
|
||||
HOTEL_PLATFORM_BASE=http://ktl-001.dsfdl-henan.xyz/openApi
|
||||
HOTEL_PLATFORM_USER=thzn-datagram0001
|
||||
HOTEL_PLATFORM_PWD=密码
|
||||
HOTEL_PLATFORM_VENDOR=mt-datagram
|
||||
```
|
||||
|
||||
> 密码中的 `@` → `%40`、`!` → `%21`、`#` → `%23`。
|
||||
> `LOG_DIR` 相对 `backend/` 解析,`../../logs` 指向 `酒店/logs`(采集脚本写的同一个目录)。
|
||||
|
||||
## 启动
|
||||
|
||||
```bash
|
||||
# 一次性安装
|
||||
pip install -r backend/requirements.txt
|
||||
cd frontend && npm install && npm run build && cd ..
|
||||
|
||||
# 静态模式(生产/新电脑:只需 Python + frontend/dist)
|
||||
python start.py --static
|
||||
|
||||
# 开发模式(前端热更新)
|
||||
python start.py
|
||||
python start.py --no-browser
|
||||
```
|
||||
|
||||
打开 <http://localhost:8011>(静态)或 <http://localhost:5175>(开发)。
|
||||
|
||||
## 两个页面
|
||||
|
||||
| 页面 | 内容 |
|
||||
|---|---|
|
||||
| **账号池**(首屏) | `hotel_hd` 原始 9 列:`id / is_ok / req_count(包使用总次数)/ current_count(当前城市使用次数)/ prox(原始 JSON)/ city / mt_traceid / created_at / updated_at`;按 id 倒序**只展示前 10 条**;行内可「改城市」(`prox` 置 NULL + `current_count` 清零)与「重置」(`is_ok` 改回 NULL) |
|
||||
| **查询** | 参考 `查询.py`:选日期 → 逐城市调平台 `getStats`(只读)→ 展示每城 success / reject / remain / timeout,并汇总**总成功条数 / 总失败条数**、成功率、城市数 |
|
||||
|
||||
> 顶部常驻健康度条显示 `is_ok` 分布(可用 / 403 / 401 / 其它 / 可用率),可用 < 10 时红底提示。
|
||||
> v1.0 的「概览 / 城市 / 记录 / 告警」四页已按反馈下线(后端接口保留未删)。
|
||||
|
||||
## 读写边界(重要)
|
||||
|
||||
| 对象 | 权限 |
|
||||
|---|---|
|
||||
| `hotel_hd` | **只更新 `city` / `prox` / `is_ok` 三列**(改城市时 `prox` 强制置 NULL;重置仅单条) |
|
||||
| `hotel_task` / `hotel_json` / `area_info` / `proxs_list` | 只读 |
|
||||
| 任务平台 OpenAPI | 只调 `getStats` / `realtimeCityList` / `realtimeCheckInOutDateList`;**永不调用 `getTask` / `uploadTaskDatagram`** |
|
||||
| `logs/*.jsonl` | 埋点由采集脚本写,审计由看板写;看板只读埋点 |
|
||||
|
||||
## 采集端埋点
|
||||
|
||||
`酒店详情.py` 已埋 8 处(只写文件,任何失败都不影响采集):
|
||||
|
||||
| 事件 | 触发 |
|
||||
|---|---|
|
||||
| `fetch_task` | 领到任务(带 hd_id / dfpid 后 8 位 / 绑定城市 / 目标城市 / 酒店 / uniqueId) |
|
||||
| `fetch_empty` | 拿任务 False 或 code≠0 → **告警页"今日空任务"来源** |
|
||||
| `upload` | 交任务结果(`code=0` 为成功) |
|
||||
| `exception` | 请求异常 / 418 网络 / 401 登录失效 |
|
||||
|
||||
开关:`HOTEL_INSIGHT_OFF=1` 可整体关闭埋点。
|
||||
|
||||
## 验收脚本
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python scripts/smoke.py --base http://127.0.0.1:8011 # 十个区块冒烟
|
||||
python scripts/verify_server.py # 自动启停 + 跑冒烟
|
||||
python scripts/verify_api.py # 16 项 API vs 数据库对账
|
||||
python scripts/verify_stats.py # 造事件验证账号/城市跑量聚合
|
||||
python scripts/verify_write.py # 改城市/重置/审计(自动恢复数据)
|
||||
python ../scripts/verify_insight.py # 埋点静态检查 + 两条链路(在 dashboard 下跑)
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
| 问题 | 处理 |
|
||||
|---|---|
|
||||
| 端口 8011/5175 被占 | 关掉占用进程再启动(`start.py` 会直接报错退出) |
|
||||
| `python start.py` 报缺少 node_modules | 静态模式不需要 Node;开发模式先 `cd frontend && npm install` |
|
||||
| 页面"今日跑量"全是 0 | 埋点尚未产生当日日志,`logs/run_YYYYMMDD.jsonl` 不存在;账号池其他功能不受影响 |
|
||||
| 改城市下拉里没有某城市 | 只列出"代理池有 IP 且脚本有坐标"的 39 个城市;`南通` 等无代理城市被排除 |
|
||||
| 重置后账号仍 403 | 重置只清除标记,headers/token 失效需重新抓包 |
|
||||
| 平台卡片显示失败 | 平台接口依赖外网,60 秒缓存;失败不影响主体页面 |
|
||||
@@ -0,0 +1,27 @@
|
||||
# ────────────────────────────────────────────────────────────────────────
|
||||
# 后端环境配置模板:复制为 backend/.env 并填写真实密码
|
||||
# Windows: copy backend\.env.example backend\.env
|
||||
# Linux: cp backend/.env.example backend/.env
|
||||
# .env 含数据库密码,不要提交到仓库、不要外传
|
||||
# ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# 主库(只读):mt_hotel(hotel_task / hotel_json)、area_crood(area_info)
|
||||
# 密码中的特殊字符需 URL 编码:@ → %40、! → %21、# → %23
|
||||
MAIN_DB_URL=mysql+aiomysql://root:密码@183.6.7.91:33016/mt_hotel?charset=utf8mb4
|
||||
|
||||
# 抓包库(仅可写 hotel_hd 的 city / prox / is_ok)
|
||||
HEADERS_DB_URL=mysql+aiomysql://root:密码@192.168.5.2:3307/headers_project?charset=utf8mb4
|
||||
|
||||
# 埋点与审计日志目录(相对 backend/ 解析;../../logs 指向 酒店/logs)
|
||||
LOG_DIR=../../logs
|
||||
|
||||
# 前端开发源(多源用英文逗号分隔)
|
||||
CORS_ORIGINS=http://localhost:5175,http://127.0.0.1:5175
|
||||
|
||||
# 任务平台 OpenAPI(只读接口)
|
||||
HOTEL_PLATFORM_BASE=http://ktl-001.dsfdl-henan.xyz/openApi
|
||||
HOTEL_PLATFORM_USER=thzn-datagram0001
|
||||
HOTEL_PLATFORM_PWD=密码
|
||||
HOTEL_PLATFORM_VENDOR=mt-datagram
|
||||
HOTEL_PLATFORM_TIMEOUT=12
|
||||
HOTEL_PLATFORM_CACHE=60
|
||||
@@ -0,0 +1,2 @@
|
||||
# hotel dashboard backend package
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""全局配置:双数据源 + 日志目录 + 任务平台 OpenAPI + 采集脚本(读取 backend/.env)。"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
||||
load_dotenv(BACKEND_DIR / ".env")
|
||||
|
||||
# ── 数据源 ──────────────────────────────────────────────────────────────
|
||||
# 主库(只读):mt_hotel.hotel_task / hotel_json,area_crood.area_info
|
||||
MAIN_DB_URL = os.getenv(
|
||||
"MAIN_DB_URL",
|
||||
"mysql+aiomysql://root@127.0.0.1:3306/mt_hotel?charset=utf8mb4",
|
||||
)
|
||||
# 抓包库(可写 hotel_hd 的 city/prox/is_ok):headers_project.hotel_hd、project_proxy.proxs_list
|
||||
HEADERS_DB_URL = os.getenv(
|
||||
"HEADERS_DB_URL",
|
||||
"mysql+aiomysql://root@127.0.0.1:3307/headers_project?charset=utf8mb4",
|
||||
)
|
||||
|
||||
# ── 日志目录(可配置多个,英文分号分隔;采集脚本在哪儿跑,就把它的 logs 目录加进来)
|
||||
# 例:LOG_DIR=../../logs;C:\Users\lkq\Desktop\lkq\酒店9\酒店\logs
|
||||
# 第一个目录同时用于写审计文件(audit.jsonl)
|
||||
def _resolve_dir(raw: str):
|
||||
p = Path(raw.strip())
|
||||
return p.resolve() if p.is_absolute() else (BACKEND_DIR / p).resolve()
|
||||
|
||||
|
||||
LOG_DIRS = [d for d in (_resolve_dir(x) for x in os.getenv("LOG_DIR", "../../logs").split(";")) if str(d)]
|
||||
if not LOG_DIRS:
|
||||
LOG_DIRS = [(BACKEND_DIR / "../../logs").resolve()]
|
||||
LOG_DIR = LOG_DIRS[0] # 审计写入目录(兼容旧代码)
|
||||
|
||||
# ── CORS ────────────────────────────────────────────────────────────────
|
||||
CORS_ORIGINS = [
|
||||
o.strip()
|
||||
for o in os.getenv(
|
||||
"CORS_ORIGINS", "http://localhost:5175,http://127.0.0.1:5175"
|
||||
).split(",")
|
||||
if o.strip()
|
||||
]
|
||||
|
||||
# ── 业务常量 ────────────────────────────────────────────────────────────
|
||||
HOTEL_TITLE_LIKE = "%美团酒店详情%" # hotel_hd 取数条件,与采集脚本 get_headers() 一致
|
||||
|
||||
# ── 任务平台 OpenAPI(只读:getStats / realtimeCityList / realtimeCheckInOutDateList)──
|
||||
PLATFORM_BASE = os.getenv("HOTEL_PLATFORM_BASE", "http://ktl-001.dsfdl-henan.xyz/openApi")
|
||||
PLATFORM_USER = os.getenv("HOTEL_PLATFORM_USER", "thzn-datagram0001")
|
||||
PLATFORM_PWD = os.getenv("HOTEL_PLATFORM_PWD", "")
|
||||
PLATFORM_VENDOR = os.getenv("HOTEL_PLATFORM_VENDOR", "mt-datagram")
|
||||
PLATFORM_TIMEOUT = int(os.getenv("HOTEL_PLATFORM_TIMEOUT", "12"))
|
||||
PLATFORM_CACHE_SECONDS = int(os.getenv("HOTEL_PLATFORM_CACHE", "60"))
|
||||
|
||||
# ── 采集端(酒店详情.py):页面上的「启动采集」按钮 ─────────────────────
|
||||
# 默认就是本仓库上一级(酒店-lkq/),脚本和 logs/ 都在那里
|
||||
COLLECTOR_DIR = Path(os.getenv("HOTEL_COLLECTOR_DIR") or (BACKEND_DIR / "../..")).resolve()
|
||||
COLLECTOR_SCRIPT = os.getenv("HOTEL_COLLECTOR_SCRIPT", "酒店详情.py")
|
||||
COLLECTOR_PYTHON = os.getenv("HOTEL_COLLECTOR_PYTHON") or sys.executable
|
||||
COLLECTOR_PID_FILE = COLLECTOR_DIR / "logs" / "collector.pid"
|
||||
COLLECTOR_LOG_FILE = COLLECTOR_DIR / "logs" / "collector.out.log"
|
||||
@@ -0,0 +1,23 @@
|
||||
"""两个异步数据库引擎。
|
||||
|
||||
- main_engine : 183.6.7.91:33016(mt_hotel / area_crood)—— 只读
|
||||
- headers_engine : 192.168.5.2:3307(headers_project / project_proxy)—— 仅写 hotel_hd 的 city/prox/is_ok
|
||||
"""
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||
|
||||
from .config import HEADERS_DB_URL, MAIN_DB_URL
|
||||
|
||||
|
||||
def _make_engine(url: str) -> AsyncEngine:
|
||||
return create_async_engine(
|
||||
url,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=3600,
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
)
|
||||
|
||||
|
||||
main_engine: AsyncEngine = _make_engine(MAIN_DB_URL)
|
||||
headers_engine: AsyncEngine = _make_engine(HEADERS_DB_URL)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""美团酒店任务看板 API 入口。
|
||||
|
||||
启动:python start.py(根目录)或 cd backend && uvicorn app.main:app --port 8011
|
||||
静态托管:若 frontend/dist 存在,则页面由后端一并托管(--static 模式)。
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .config import CORS_ORIGINS
|
||||
from .routers import accounts, alerts, audit, collector, health, meta, overview, platform, records, stats
|
||||
|
||||
app = FastAPI(title="美团酒店任务看板 API", version="1.0.0")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=CORS_ORIGINS,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(meta.router)
|
||||
app.include_router(overview.router)
|
||||
app.include_router(stats.router)
|
||||
app.include_router(accounts.router)
|
||||
app.include_router(records.router)
|
||||
app.include_router(alerts.router)
|
||||
app.include_router(platform.router)
|
||||
app.include_router(collector.router)
|
||||
app.include_router(audit.router)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
||||
"""把 HTTPException(detail=...) 统一成 {code, msg, data} 顶层结构(见 04 文档 4 节)。"""
|
||||
detail = exc.detail
|
||||
if isinstance(detail, dict) and "code" in detail:
|
||||
body = {"code": detail.get("code"), "msg": detail.get("msg", ""), "data": None}
|
||||
else:
|
||||
body = {"code": exc.status_code, "msg": str(detail), "data": None}
|
||||
return JSONResponse(status_code=exc.status_code, content=body)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
"""参数校验失败也走 {code, msg} 结构,避免前端拿到 FastAPI 原始 detail 数组。"""
|
||||
first = exc.errors()[0] if exc.errors() else {}
|
||||
loc = ".".join(str(x) for x in first.get("loc", []) if x != "body")
|
||||
msg = f"参数 {loc} 不合法:{first.get('msg', '')}".strip()
|
||||
return JSONResponse(status_code=422, content={"code": 422, "msg": msg, "data": None})
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
"""兜底:未捕获异常统一成 {code:-1, msg},不把堆栈暴露给前端。"""
|
||||
print(f"[error] {request.method} {request.url.path}: {type(exc).__name__}: {exc}", flush=True)
|
||||
return JSONResponse(status_code=500, content={"code": -1, "msg": f"服务内部错误:{type(exc).__name__}"})
|
||||
|
||||
|
||||
_STATIC_DIR = Path(
|
||||
os.getenv("STATIC_DIR") or Path(__file__).resolve().parent.parent.parent / "frontend" / "dist"
|
||||
)
|
||||
if _STATIC_DIR.is_dir():
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
app.mount("/", StaticFiles(directory=str(_STATIC_DIR), html=True), name="spa")
|
||||
print(f"[static] 托管前端产物: {_STATIC_DIR}")
|
||||
@@ -0,0 +1,2 @@
|
||||
# routers package
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""GET /api/hotel/accounts —— 账号池分页(筛选 / 排序 / 今日跑量合并)。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..services import hotel_logs, hotel_query, hotel_write
|
||||
from ..services.hotel_meta import legal_cities
|
||||
from ..services.hotel_write import WriteError
|
||||
from .common import api_error, parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["accounts"])
|
||||
|
||||
SORT_FIELDS = ("id", "today_fetch_task", "updated_at", "req_count", "current_count")
|
||||
|
||||
|
||||
class ChangeCityBody(BaseModel):
|
||||
city: str = Field(..., description="合法城市(不带「市」)")
|
||||
operator: str | None = Field("local", description="操作人标识")
|
||||
|
||||
|
||||
class ResetBody(BaseModel):
|
||||
operator: str | None = Field("local", description="操作人标识")
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
async def list_accounts(
|
||||
date: str | None = Query(None, description="今日跑量所属日期,默认今天"),
|
||||
city: str | None = Query(None, description="绑定城市(不带「市」)"),
|
||||
status: list[str] | None = Query(None, description="可多值:NULL / 403 / 401 / 418 / 0 / 6 / OTHER"),
|
||||
keyword: str | None = Query(None, description="dfpid 包含匹配"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
sort: str = Query("id"),
|
||||
order: str = Query("desc", pattern="^(asc|desc)$"),
|
||||
) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
if sort not in SORT_FIELDS:
|
||||
sort = "id"
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
|
||||
items, total = await hotel_query.account_rows(
|
||||
today_agg=by_hd,
|
||||
city=city or None,
|
||||
status=status or None,
|
||||
keyword=keyword or None,
|
||||
page=page,
|
||||
size=size,
|
||||
sort=sort,
|
||||
order=order,
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.post("/accounts/{hd_id}/city")
|
||||
async def change_city(hd_id: int, body: ChangeCityBody) -> dict:
|
||||
"""改绑定城市,并**自动把该账号代理置为 NULL**(下次运行按新城市补 IP)。"""
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
legal = legal_cities(list(proxy_ips.keys()))
|
||||
try:
|
||||
data = await hotel_write.change_city(
|
||||
hd_id,
|
||||
body.city,
|
||||
legal_cities=legal,
|
||||
proxy_ips=proxy_ips,
|
||||
operator=(body.operator or "local"),
|
||||
)
|
||||
except WriteError as e:
|
||||
raise api_error(e.status, e.msg, code=e.code)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
|
||||
|
||||
@router.post("/accounts/{hd_id}/reset")
|
||||
async def reset_account(hd_id: int, body: ResetBody) -> dict:
|
||||
"""单条重置 is_ok → NULL(放回可用池)。不提供批量接口。"""
|
||||
try:
|
||||
data = await hotel_write.reset_is_ok(hd_id, operator=(body.operator or "local"))
|
||||
except WriteError as e:
|
||||
raise api_error(e.status, e.msg, code=e.code)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""GET /api/hotel/alerts —— 今日空任务 / 长期未活动 / 封禁清单。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query
|
||||
from ..services.hotel_meta import mask_dfpid
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["alerts"])
|
||||
|
||||
STALE_HOURS = 24
|
||||
EMPTY_LIMIT = 200
|
||||
|
||||
|
||||
@router.get("/alerts")
|
||||
async def get_alerts(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
empty_events = [e for e in events if e.get("event") == "fetch_empty"]
|
||||
empty_events.sort(key=lambda e: str(e.get("ts") or ""), reverse=True)
|
||||
|
||||
raw_accounts = {r["id"]: r for r in await hotel_query.all_accounts_raw()}
|
||||
empty_items = []
|
||||
for e in empty_events[:EMPTY_LIMIT]:
|
||||
hd_id = e.get("hd_id")
|
||||
acc = raw_accounts.get(hd_id) or {}
|
||||
empty_items.append(
|
||||
{
|
||||
"ts": e.get("ts"),
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(acc.get("dfpid")) or (f"…{e['dfpid_tail']}" if e.get("dfpid_tail") else None),
|
||||
"bind_city": e.get("bind_city"),
|
||||
"target_city": e.get("target_city"),
|
||||
"code": e.get("code"),
|
||||
"message": e.get("msg"),
|
||||
}
|
||||
)
|
||||
|
||||
stale = await hotel_query.stale_accounts(hours=STALE_HOURS)
|
||||
blocked = await hotel_query.blocked_accounts()
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"empty_fetch": empty_items,
|
||||
"stale": stale,
|
||||
"blocked": blocked,
|
||||
"counts": {
|
||||
"empty_fetch": len(empty_events),
|
||||
"stale": len(stale),
|
||||
"blocked": len(blocked),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""GET /api/hotel/audit —— 读取写操作审计(logs/audit.jsonl 末尾 N 行)。"""
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["audit"])
|
||||
|
||||
|
||||
@router.get("/audit")
|
||||
async def get_audit(limit: int = Query(50, ge=1, le=500)) -> dict:
|
||||
items = hotel_logs.read_audit(limit=limit)
|
||||
return {"code": 0, "msg": "ok", "data": {"items": items, "count": len(items)}}
|
||||
@@ -0,0 +1,33 @@
|
||||
"""采集端(酒店详情.py)控制:状态 / 启动 / 停止。
|
||||
|
||||
只做"起停 + 看状态",不碰采集逻辑;真正的入库、领任务仍由脚本自己完成。
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..services import collector
|
||||
from .common import api_error
|
||||
|
||||
router = APIRouter(prefix="/api/hotel/collector", tags=["collector"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def collector_status() -> dict:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.status)}
|
||||
|
||||
|
||||
@router.post("/start")
|
||||
async def collector_start() -> dict:
|
||||
try:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.start)}
|
||||
except collector.CollectorError as e:
|
||||
raise api_error(e.status, e.msg)
|
||||
|
||||
|
||||
@router.post("/stop")
|
||||
async def collector_stop() -> dict:
|
||||
try:
|
||||
return {"code": 0, "msg": "ok", "data": await run_in_threadpool(collector.stop)}
|
||||
except collector.CollectorError as e:
|
||||
raise api_error(e.status, e.msg)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""路由公共工具:日期校验、统一错误、行转字典。"""
|
||||
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
|
||||
|
||||
def api_error(status: int, msg: str, code: int | None = None) -> HTTPException:
|
||||
"""统一错误响应:{code, msg}。code 默认与 HTTP 状态一致,业务码可单独指定。"""
|
||||
return HTTPException(status_code=status, detail={"code": code if code is not None else status, "msg": msg})
|
||||
|
||||
|
||||
def parse_date(value: str, name: str = "date") -> date:
|
||||
if not value or not DATE_RE.match(value):
|
||||
raise api_error(400, f"{name} 格式应为 YYYY-MM-DD")
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError:
|
||||
raise api_error(400, f"{name} 不是合法日期")
|
||||
|
||||
|
||||
def check_range(start: date, end: date) -> None:
|
||||
if start > end:
|
||||
raise api_error(400, "start 不能晚于 end")
|
||||
|
||||
|
||||
def row_dict(row) -> dict:
|
||||
"""SQLAlchemy Row -> 纯 JSON 字典(Decimal/date/datetime 序列化)。"""
|
||||
out = {}
|
||||
for k, v in dict(row._mapping).items():
|
||||
if v is None:
|
||||
out[k] = None
|
||||
elif isinstance(v, Decimal):
|
||||
out[k] = int(v) if v == v.to_integral_value() else float(v)
|
||||
elif isinstance(v, datetime):
|
||||
out[k] = v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
elif isinstance(v, date):
|
||||
out[k] = v.isoformat()
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
@@ -0,0 +1,28 @@
|
||||
"""GET /api/health —— 双库连通 + 日志目录可写性。"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..database import headers_engine, main_engine
|
||||
from ..services import hotel_logs
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health() -> dict:
|
||||
data: dict = {"db_main": "down", "db_headers": "down"}
|
||||
try:
|
||||
async with main_engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
data["db_main"] = "up"
|
||||
except Exception as e: # noqa: BLE001 健康检查永不抛
|
||||
data["db_main_error"] = str(e)[:200]
|
||||
try:
|
||||
async with headers_engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
data["db_headers"] = "up"
|
||||
except Exception as e: # noqa: BLE001
|
||||
data["db_headers_error"] = str(e)[:200]
|
||||
data.update(hotel_logs.log_dir_info())
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""GET /api/hotel/meta —— 城市清单、合法城市白名单、is_ok 字典(5 分钟缓存)。"""
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE, PLATFORM_PWD
|
||||
from ..database import main_engine
|
||||
from ..services import hotel_query
|
||||
from ..services.hotel_meta import IS_OK_DICT, legal_cities
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["meta"])
|
||||
|
||||
_city_id_cache: dict = {"ts": 0.0, "map": {}}
|
||||
_meta_cache: dict = {"ts": 0.0, "data": None}
|
||||
CACHE_SECONDS = 300
|
||||
|
||||
|
||||
async def _city_id_map() -> dict[str, str]:
|
||||
"""城市名 → 美团 cityId(area_info,title 含"美团")。"""
|
||||
now = time.time()
|
||||
if now - _city_id_cache["ts"] < CACHE_SECONDS and _city_id_cache["map"]:
|
||||
return _city_id_cache["map"]
|
||||
sql = text(
|
||||
"SELECT cityName, MIN(CAST(cityId AS UNSIGNED)) AS cid "
|
||||
"FROM area_crood.area_info "
|
||||
"WHERE title LIKE :pat AND cityName IS NOT NULL AND cityName <> '' "
|
||||
"GROUP BY cityName"
|
||||
)
|
||||
try:
|
||||
async with main_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": "%美团%"})).fetchall()
|
||||
mapping = {r[0]: str(r[1]) for r in rows if r[1] is not None}
|
||||
_city_id_cache.update(ts=now, map=mapping)
|
||||
return mapping
|
||||
except Exception: # noqa: BLE001 字典缺失不阻塞页面
|
||||
return _city_id_cache["map"]
|
||||
|
||||
|
||||
async def _proxy_city_ips() -> dict[str, int]:
|
||||
"""每城可用代理 IP 数(复用数据访问层,避免两处 SQL)。"""
|
||||
return await hotel_query.proxy_city_ips()
|
||||
|
||||
|
||||
async def _account_city_counts() -> dict[str, int]:
|
||||
"""每城账号数(hotel_hd,取数条件与采集脚本一致)。"""
|
||||
return await hotel_query.city_account_counts()
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
async def get_meta() -> dict:
|
||||
now = time.time()
|
||||
if _meta_cache["data"] is not None and now - _meta_cache["ts"] < CACHE_SECONDS:
|
||||
return {"code": 0, "msg": "ok", "data": _meta_cache["data"]}
|
||||
|
||||
proxy_ips = await _proxy_city_ips()
|
||||
accounts = await _account_city_counts()
|
||||
city_ids = await _city_id_map()
|
||||
whitelist = legal_cities(list(proxy_ips.keys()))
|
||||
whitelist_set = set(whitelist)
|
||||
|
||||
all_cities = sorted(set(proxy_ips) | set(accounts))
|
||||
cities = [
|
||||
{
|
||||
"city": c,
|
||||
"proxy_ips": proxy_ips.get(c, 0),
|
||||
"accounts": accounts.get(c, 0),
|
||||
"city_id": city_ids.get(c),
|
||||
"legal": c in whitelist_set,
|
||||
}
|
||||
for c in all_cities
|
||||
]
|
||||
|
||||
data = {
|
||||
"cities": cities,
|
||||
"legal_cities": whitelist,
|
||||
"is_ok_dict": IS_OK_DICT,
|
||||
"platform_available": bool(PLATFORM_PWD),
|
||||
}
|
||||
_meta_cache.update(ts=now, data=data)
|
||||
return {"code": 0, "msg": "ok", "data": data}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""GET /api/hotel/overview 与 /api/hotel/trend —— 池子健康度 + 今日跑量 + 平台对照。"""
|
||||
|
||||
from datetime import date as Date
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query, platform_api
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["overview"])
|
||||
|
||||
|
||||
@router.get("/overview")
|
||||
async def overview(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
pool = await hotel_query.pool_stats()
|
||||
|
||||
events, log_meta = hotel_logs.read_day(day)
|
||||
agg = hotel_logs.aggregate(events)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
uploads = agg["upload_ok"] + agg["upload_fail"]
|
||||
|
||||
today = {
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"success_rate": round(agg["upload_ok"] / uploads * 100, 1) if uploads else None,
|
||||
"active_accounts": len(by_hd),
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
|
||||
platform = await platform_api.get_stats(day)
|
||||
today_tasks = await hotel_query.count_today("hotel_task", day)
|
||||
today_records = await hotel_query.count_today("hotel_json", day)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"pool": pool,
|
||||
"today": today,
|
||||
"logs_available": bool(log_meta.get("available")),
|
||||
"db_today": {"hotel_task": today_tasks, "hotel_json": today_records},
|
||||
"platform": platform,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/trend")
|
||||
async def trend(
|
||||
days: int = Query(7, ge=1, le=90),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
) -> dict:
|
||||
end_day = parse_date(end) if end else Date.today()
|
||||
start_day = end_day - timedelta(days=days - 1)
|
||||
items = hotel_logs.timeline(start_day, end_day)
|
||||
return {"code": 0, "msg": "ok", "data": {"start": start_day.isoformat(), "end": end_day.isoformat(), "items": items}}
|
||||
@@ -0,0 +1,244 @@
|
||||
"""任务平台 getStats 只读代理。
|
||||
|
||||
- GET /api/hotel/platform/stats:按日期(+可选城市)取 success / reject / remain
|
||||
- GET /api/hotel/platform/risk:所选日期各城市明细 + 昨日成功率(高危筛查)
|
||||
|
||||
不传 city 时按合法城市白名单逐个取并发汇总;上游失败只影响该城市条目,不影响整体。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import date as Date
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query, platform_api
|
||||
from ..services.hotel_meta import legal_cities
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["platform"])
|
||||
|
||||
CONCURRENCY = 5
|
||||
ABNORMAL_MIN_SAMPLE = 5 # 当日样本(成功+失败)> 该值且成功率为 0 → 判定“异常”
|
||||
|
||||
|
||||
@router.get("/platform/stats")
|
||||
async def platform_stats(
|
||||
date: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None, description="只取单个城市(不带「市」)"),
|
||||
) -> dict:
|
||||
day = parse_date(date) if date else Date.today()
|
||||
|
||||
if city:
|
||||
one = await platform_api.get_stats(day, city)
|
||||
item = {
|
||||
"city": city,
|
||||
"success": one.get("success"),
|
||||
"reject": one.get("reject"),
|
||||
"remain": one.get("remain"),
|
||||
"timeout": one.get("timeout"),
|
||||
"ok": one.get("ok"),
|
||||
"error": one.get("error"),
|
||||
}
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {"date": day.isoformat(), "ok": bool(one.get("ok")), "items": [item],
|
||||
"summary": _summarize([item]), "failed": [] if one.get("ok") else [city]},
|
||||
}
|
||||
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
cities = legal_cities(list(proxy_ips.keys()))
|
||||
|
||||
sem = asyncio.Semaphore(CONCURRENCY)
|
||||
|
||||
async def one(c: str) -> dict:
|
||||
async with sem:
|
||||
res = await platform_api.get_stats(day, c)
|
||||
return {
|
||||
"city": c,
|
||||
"success": res.get("success"),
|
||||
"reject": res.get("reject"),
|
||||
"remain": res.get("remain"),
|
||||
"timeout": res.get("timeout"),
|
||||
"ok": res.get("ok"),
|
||||
"error": res.get("error"),
|
||||
}
|
||||
|
||||
items = await asyncio.gather(*(one(c) for c in cities))
|
||||
failed = [i["city"] for i in items if not i.get("ok")]
|
||||
ok_any = any(i.get("ok") for i in items)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"ok": ok_any,
|
||||
"items": items,
|
||||
"summary": _summarize(items),
|
||||
"failed": failed,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _summarize(items: list[dict]) -> dict:
|
||||
def total(key: str):
|
||||
values = [i.get(key) for i in items if isinstance(i.get(key), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
return {
|
||||
"success": total("success"),
|
||||
"reject": total("reject"),
|
||||
"remain": total("remain"),
|
||||
"timeout": total("timeout"),
|
||||
"cities": len(items),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/platform/risk")
|
||||
async def platform_risk(
|
||||
date: str | None = Query(None, description="基准日 YYYY-MM-DD(页面所选的日期),默认今天"),
|
||||
end: str | None = Query(None, description="兼容旧参数,含义同 date"),
|
||||
days: int = Query(1, ge=1, le=30, description="参考窗口天数,**不含基准日**;默认 1 = 只看昨日"),
|
||||
threshold: float = Query(75.0, ge=0, le=100, description="高危阈值(参考窗口成功率低于该值)"),
|
||||
min_sample: int = Query(5, ge=1, description="参考窗口样本总量下限,低于此数不做高危判定"),
|
||||
) -> dict:
|
||||
"""基准日各城市成功/失败 + 参考窗口(默认 = 昨日)成功率,一次返回。
|
||||
|
||||
⚠️ 平台 `getStats` 只保留最近两天(今天 / 昨天):更早的日期返回空数据,
|
||||
所以"近 N 天成功率"拿不到,页面上的对照口径收敛为**昨日成功率**(days=1)。
|
||||
日期参数优先取 `date`(前端日期选择),`end` 仅作兼容。
|
||||
|
||||
高危 = 昨日 (success+reject) >= min_sample 且成功率 < threshold。
|
||||
昨日完全没数据时不做高危判定(risk_rate 置空,basis=no_window_data)。
|
||||
"""
|
||||
anchor = date or end
|
||||
end_day = parse_date(anchor) if anchor else Date.today()
|
||||
window = [end_day - timedelta(days=i) for i in range(days, 0, -1)] # 参考窗口,不含基准日
|
||||
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
cities = legal_cities(list(proxy_ips.keys()))
|
||||
|
||||
sem = asyncio.Semaphore(12)
|
||||
|
||||
async def one(day: Date, city: str) -> dict:
|
||||
async with sem:
|
||||
return await platform_api.get_stats(day, city)
|
||||
|
||||
# 参考窗口(默认只有昨日):days × cities 次(历史日期命中 30 分钟缓存)
|
||||
hist_results = await asyncio.gather(*(one(d, c) for d in window for c in cities))
|
||||
hist: dict[str, list[int]] = {c: [0, 0] for c in cities} # city -> [success, reject]
|
||||
hist_data_days: dict[str, int] = {c: 0 for c in cities}
|
||||
for idx, res in enumerate(hist_results):
|
||||
city = cities[idx % len(cities)]
|
||||
if not res.get("ok"):
|
||||
continue
|
||||
# 平台对超出保留期的日期返回 success/reject = null(不是 0),不能算作"有数据"
|
||||
has_num = isinstance(res.get("success"), (int, float)) or isinstance(res.get("reject"), (int, float))
|
||||
hist[city][0] += res.get("success") or 0
|
||||
hist[city][1] += res.get("reject") or 0
|
||||
if has_num:
|
||||
hist_data_days[city] += 1
|
||||
|
||||
# 当天埋点日志:get_one_task 返回 False / code≠0 的城市(fetch_empty)
|
||||
events, log_meta = hotel_logs.read_day(end_day)
|
||||
city_events = hotel_logs.aggregate_by_city(events)
|
||||
logs_available = bool(log_meta.get("available"))
|
||||
|
||||
# 当天
|
||||
today_results = await asyncio.gather(*(one(end_day, c) for c in cities))
|
||||
|
||||
items: list[dict] = []
|
||||
for idx, city in enumerate(cities):
|
||||
hs, hr = hist[city]
|
||||
hist_total = hs + hr
|
||||
hist_rate = round(hs / hist_total * 100, 1) if hist_total else None
|
||||
|
||||
today_res = today_results[idx]
|
||||
# 保留 null(= 平台没有该日期的统计),不要兜底成 0,否则"没数据"会被读成"0 条完成"
|
||||
ts = today_res.get("success") if today_res.get("ok") else None
|
||||
tr = today_res.get("reject") if today_res.get("ok") else None
|
||||
today_total = (ts or 0) + (tr or 0)
|
||||
today_rate = round(ts / today_total * 100, 1) if ts is not None and today_total else None
|
||||
|
||||
# 当日异常:样本 > 5 且成功率为 0(一条都没成功)
|
||||
today_abnormal = bool(ts is not None and today_total > ABNORMAL_MIN_SAMPLE and ts == 0)
|
||||
|
||||
# 拿任务失败(埋点 fetch_empty)次数
|
||||
empty_count = int((city_events.get(city) or {}).get("fetch_empty", 0))
|
||||
|
||||
# 高危判定:**必须**基于参考窗口(默认昨日,样本 ≥ min_sample 且成功率 < threshold);
|
||||
# 窗口内没有数据的城市不能判高危(它们由"当日异常"口径负责),risk_rate 置空
|
||||
basis = "window" if hist_total > 0 else "no_window_data"
|
||||
risk_rate = hist_rate
|
||||
high_risk = hist_rate is not None and hist_total >= min_sample and hist_rate < threshold
|
||||
|
||||
items.append(
|
||||
{
|
||||
"city": city,
|
||||
"hist_success": hs,
|
||||
"hist_reject": hr,
|
||||
"hist_total": hist_total,
|
||||
"hist_rate": hist_rate,
|
||||
"hist_days_with_data": hist_data_days[city],
|
||||
"today_success": ts,
|
||||
"today_reject": tr,
|
||||
"today_rate": today_rate,
|
||||
"today_remain": today_res.get("remain") if today_res.get("ok") else None,
|
||||
"today_timeout": today_res.get("timeout") if today_res.get("ok") else None,
|
||||
"today_total": today_total,
|
||||
"today_abnormal": today_abnormal,
|
||||
"empty_fetch_count": empty_count,
|
||||
"risk_rate": risk_rate,
|
||||
"risk_basis": basis,
|
||||
"high_risk": high_risk,
|
||||
}
|
||||
)
|
||||
|
||||
# 高危置顶 → 其余按风险成功率升序 → 无数据最后
|
||||
def rank(x: dict) -> int:
|
||||
if x["risk_rate"] is None:
|
||||
return 2
|
||||
return 0 if x["high_risk"] else 1
|
||||
|
||||
items.sort(key=lambda x: (rank(x), x["risk_rate"] if x["risk_rate"] is not None else 999, -x["hist_total"]))
|
||||
|
||||
high_risk = [i for i in items if i["high_risk"]]
|
||||
abnormal = [i for i in items if i["today_abnormal"]]
|
||||
empty_cities = [i for i in items if i["empty_fetch_count"] > 0]
|
||||
available = await hotel_query.available_accounts()
|
||||
# 平台接口是否可用 / 该日期平台是否有统计(与"0 条完成"区分开)
|
||||
platform_ok = any(r.get("ok") for r in today_results)
|
||||
has_data = any(i["today_success"] is not None or i["today_reject"] is not None for i in items)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": end_day.isoformat(),
|
||||
"platform_ok": platform_ok,
|
||||
"has_data": has_data,
|
||||
"window": {
|
||||
"start": window[0].isoformat(),
|
||||
"end": window[-1].isoformat(),
|
||||
"days": days,
|
||||
"exclude_today": True,
|
||||
},
|
||||
"threshold": threshold,
|
||||
"min_sample": min_sample,
|
||||
"abnormal_min_sample": ABNORMAL_MIN_SAMPLE,
|
||||
"high_risk": high_risk,
|
||||
"abnormal": abnormal,
|
||||
"items": items,
|
||||
"logs_available": logs_available,
|
||||
"empty_fetch_total": sum(i["empty_fetch_count"] for i in items),
|
||||
"available_packages": available,
|
||||
"counts": {
|
||||
"cities": len(cities),
|
||||
"high_risk": len(high_risk),
|
||||
"abnormal": len(abnormal),
|
||||
"empty_fetch_cities": len(empty_cities),
|
||||
"available_packages": len(available),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""任务记录 / 采集记录查询与采集详情解析。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_query
|
||||
from ..services.record_parser import parse_record, raw_preview
|
||||
from .common import api_error, check_range, parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel", tags=["records"])
|
||||
|
||||
|
||||
def _range(start: str | None, end: str | None) -> tuple[Date, Date]:
|
||||
end_day = parse_date(end) if end else Date.today()
|
||||
start_day = parse_date(start) if start else end_day
|
||||
check_range(start_day, end_day)
|
||||
return start_day, end_day
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
async def list_tasks(
|
||||
start: str | None = Query(None, description="YYYY-MM-DD,默认等于 end"),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None),
|
||||
keyword: str | None = Query(None, description="酒店名模糊 / unique_id 前缀"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
) -> dict:
|
||||
start_day, end_day = _range(start, end)
|
||||
items, total = await hotel_query.tasks_page(
|
||||
start=start_day, end=end_day, city=city or None, keyword=keyword or None, page=page, size=size
|
||||
)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"start": start_day.isoformat(),
|
||||
"end": end_day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"items": items,
|
||||
# hotel_task 的 hotel_id 上有唯一键:一行 = 一个酒店的最新快照
|
||||
"note": "按 created_at 过滤;hotel_task 每个酒店只保留一行(hotel_id UNIQUE)",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/records")
|
||||
async def list_records(
|
||||
start: str | None = Query(None, description="YYYY-MM-DD,默认等于 end"),
|
||||
end: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
city: str | None = Query(None),
|
||||
keyword: str | None = Query(None, description="酒店名模糊 / poi_id 前缀"),
|
||||
page: int = Query(1, ge=1),
|
||||
size: int = Query(20, ge=1, le=200),
|
||||
) -> dict:
|
||||
start_day, end_day = _range(start, end)
|
||||
items, total = await hotel_query.records_page(
|
||||
start=start_day, end=end_day, city=city or None, keyword=keyword or None, page=page, size=size
|
||||
)
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"start": start_day.isoformat(),
|
||||
"end": end_day.isoformat(),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/records/{rec_id}")
|
||||
async def record_detail(rec_id: int) -> dict:
|
||||
row = await hotel_query.record_by_id(rec_id)
|
||||
if not row:
|
||||
raise api_error(404, f"采集记录 #{rec_id} 不存在", code=1004)
|
||||
|
||||
parsed = parse_record(row.get("json_data"))
|
||||
preview, truncated = raw_preview(row.get("json_data"))
|
||||
raw = row.get("json_data") or ""
|
||||
json_size = len(raw.encode("utf-8", errors="replace")) if isinstance(raw, str) else len(raw)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"id": row["id"],
|
||||
"hotel": {
|
||||
"poi_id": row.get("poi_id"),
|
||||
"city_id": row.get("city_id"),
|
||||
"hotel_name": row.get("hotel_name"),
|
||||
"city_name": row.get("city_name"),
|
||||
"check_in_date": row["check_in_date"].isoformat() if row.get("check_in_date") else None,
|
||||
"check_out_date": row["check_out_date"].isoformat() if row.get("check_out_date") else None,
|
||||
"create_at": row["create_at"].strftime("%Y-%m-%d %H:%M:%S") if row.get("create_at") else None,
|
||||
"json_size": json_size,
|
||||
},
|
||||
"parse_ok": parsed["parse_ok"],
|
||||
"structure": parsed["structure"],
|
||||
"error": parsed["error"],
|
||||
"rooms": parsed["rooms"],
|
||||
"min_price": parsed["min_price"],
|
||||
"raw_preview": preview,
|
||||
"raw_truncated": truncated,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""GET /api/hotel/stats/account 与 /api/hotel/stats/city —— 今日跑量按账号/城市聚合。"""
|
||||
|
||||
from datetime import date as Date
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from ..services import hotel_logs, hotel_query
|
||||
from ..services.hotel_meta import mask_dfpid
|
||||
from .common import parse_date
|
||||
|
||||
router = APIRouter(prefix="/api/hotel/stats", tags=["stats"])
|
||||
|
||||
|
||||
@router.get("/account")
|
||||
async def stats_account(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
"""每个账号今天跑了多少条(只含当日日志中出现过的账号)。"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_hd = hotel_logs.aggregate_by_hd(events)
|
||||
|
||||
raw = {r["id"]: r for r in await hotel_query.all_accounts_raw()}
|
||||
items: list[dict] = []
|
||||
for hd_id, agg in by_hd.items():
|
||||
acc = raw.get(hd_id) or {}
|
||||
items.append(
|
||||
{
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(acc.get("dfpid")),
|
||||
"city": acc.get("city"),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
"req_count": int(acc.get("req_count") or 0),
|
||||
"current_count": int(acc.get("current_count") or 0),
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: (x["fetch_task"], x["last_event_at"] or ""), reverse=True)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"bad_lines": meta.get("bad_lines", 0),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/city")
|
||||
async def stats_city(
|
||||
date: str | None = Query(None, description="YYYY-MM-DD,默认今天"),
|
||||
top: int | None = Query(None, ge=1, le=200, description="只取跑量前 N 个城市"),
|
||||
) -> dict:
|
||||
"""每个城市跑了多少条(日志 target_city 聚合)+ 该城账号数与代理 IP 数。"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_city = hotel_logs.aggregate_by_city(events)
|
||||
|
||||
accounts = await hotel_query.city_account_counts()
|
||||
proxy_ips = await hotel_query.proxy_city_ips()
|
||||
|
||||
items: list[dict] = []
|
||||
for city in sorted(set(accounts) | set(proxy_ips) | set(by_city)):
|
||||
agg = by_city.get(city) or hotel_logs.empty_counter()
|
||||
items.append(
|
||||
{
|
||||
"city": city,
|
||||
"accounts": accounts.get(city, 0),
|
||||
"proxy_ips": proxy_ips.get(city, 0),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"upload_fail": agg["upload_fail"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: (x["fetch_task"], x["accounts"]), reverse=True)
|
||||
if top:
|
||||
items = items[:top]
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"items": items,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/failures")
|
||||
async def stats_failures(date: str | None = Query(None, description="YYYY-MM-DD,默认今天")) -> dict:
|
||||
"""当天"拿任务失败"(埋点 fetch_empty)的城市清单。
|
||||
|
||||
用途:改/加城市的下拉框要把这些城市藏起来(绑过去也领不到任务)。
|
||||
"""
|
||||
day = parse_date(date) if date else Date.today()
|
||||
events, meta = hotel_logs.read_day(day)
|
||||
by_city = hotel_logs.aggregate_by_city(events)
|
||||
|
||||
items = [
|
||||
{
|
||||
"city": city,
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"exception": agg["exception"],
|
||||
"last_event_at": agg["last_event_at"],
|
||||
}
|
||||
for city, agg in by_city.items()
|
||||
if agg["fetch_empty"] > 0
|
||||
]
|
||||
items.sort(key=lambda x: (-x["fetch_empty"], x["city"]))
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": {
|
||||
"date": day.isoformat(),
|
||||
"logs_available": bool(meta.get("available")),
|
||||
"items": items,
|
||||
"cities": [i["city"] for i in items],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# services package
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""采集进程(酒店详情.py)的启动 / 停止 / 状态。
|
||||
|
||||
设计要点:
|
||||
- 采集脚本自己把 pid 写进 `logs/collector.pid`,所以"控制台手动起的"也能识别,
|
||||
不会因为页面不知道就再起一个,导致两个进程抢同一个账号池;
|
||||
- 启动后 stdout/stderr 追加到 `logs/collector.out.log`,status 带最后几行方便排查;
|
||||
- 停止走 `taskkill /T /F`(Windows),避免 python 拉起子进程后残留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import (
|
||||
COLLECTOR_DIR,
|
||||
COLLECTOR_LOG_FILE,
|
||||
COLLECTOR_PID_FILE,
|
||||
COLLECTOR_PYTHON,
|
||||
COLLECTOR_SCRIPT,
|
||||
)
|
||||
|
||||
# Windows 进程创建标志
|
||||
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
STILL_ACTIVE = 259
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
|
||||
_proc: subprocess.Popen | None = None
|
||||
_started_at: float | None = None
|
||||
|
||||
|
||||
class CollectorError(Exception):
|
||||
"""业务错误,router 转成 {code,msg}。"""
|
||||
|
||||
def __init__(self, msg: str, status: int = 400):
|
||||
super().__init__(msg)
|
||||
self.msg = msg
|
||||
self.status = status
|
||||
|
||||
|
||||
def _pid_alive(pid: int | None) -> bool:
|
||||
if not pid or pid <= 0:
|
||||
return False
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
code = ctypes.c_ulong()
|
||||
ok = kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
|
||||
return bool(ok) and code.value == STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
try:
|
||||
os.kill(int(pid), 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def read_pid() -> int | None:
|
||||
"""读 collector.pid(不存在 / 内容非法都返回 None)。"""
|
||||
try:
|
||||
text = COLLECTOR_PID_FILE.read_text(encoding="utf-8").strip()
|
||||
return int(text) if text else None
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _is_running(pid: int | None) -> bool:
|
||||
"""pid 是否还在跑。自己起的子进程用 Popen.poll() 判定(比 OpenProcess 准)。"""
|
||||
if not pid:
|
||||
return False
|
||||
if _proc is not None and _proc.pid == pid:
|
||||
return _proc.poll() is None
|
||||
return _pid_alive(pid)
|
||||
|
||||
|
||||
def current_pid() -> int | None:
|
||||
"""当前真正活着的采集进程 pid:优先 pid 文件(含手动启动),再看本进程的句柄。"""
|
||||
pid = read_pid()
|
||||
if pid and _is_running(pid):
|
||||
return pid
|
||||
if _proc is not None and _proc.poll() is None:
|
||||
return _proc.pid
|
||||
return None
|
||||
|
||||
|
||||
def tail(lines: int = 12) -> list[str]:
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("r", encoding="utf-8", errors="replace") as f:
|
||||
return [ln.rstrip() for ln in f.readlines()[-lines:]]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
pid = current_pid()
|
||||
started: float | None = None
|
||||
if pid:
|
||||
if _proc is not None and _proc.pid == pid and _proc.poll() is None:
|
||||
started = _started_at
|
||||
else:
|
||||
try:
|
||||
started = COLLECTOR_PID_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
started = None
|
||||
return {
|
||||
"running": bool(pid),
|
||||
"pid": pid,
|
||||
"source": "api" if (pid and _proc is not None and _proc.pid == pid) else ("manual" if pid else None),
|
||||
"started_at": datetime.fromtimestamp(started).strftime("%Y-%m-%d %H:%M:%S") if started else None,
|
||||
"uptime_seconds": int(time.time() - started) if started else None,
|
||||
"dir": str(COLLECTOR_DIR),
|
||||
"script": COLLECTOR_SCRIPT,
|
||||
"python": COLLECTOR_PYTHON,
|
||||
"log_file": str(COLLECTOR_LOG_FILE),
|
||||
"log_tail": tail(),
|
||||
}
|
||||
|
||||
|
||||
def start() -> dict:
|
||||
global _proc, _started_at
|
||||
|
||||
pid = current_pid()
|
||||
if pid:
|
||||
raise CollectorError(f"采集已经在运行(pid {pid}),不要重复启动", status=409)
|
||||
|
||||
script = COLLECTOR_DIR / COLLECTOR_SCRIPT
|
||||
if not script.is_file():
|
||||
raise CollectorError(f"找不到采集脚本:{script}", status=404)
|
||||
|
||||
COLLECTOR_LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_started_at = time.time()
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("a", encoding="utf-8", errors="replace") as out:
|
||||
out.write(f"\n===== 看板启动采集 {datetime.now():%Y-%m-%d %H:%M:%S} =====\n")
|
||||
out.flush()
|
||||
flags = CREATE_NEW_PROCESS_GROUP | (CREATE_NO_WINDOW if sys.platform == "win32" else 0)
|
||||
_proc = subprocess.Popen(
|
||||
[COLLECTOR_PYTHON, script.name],
|
||||
cwd=str(COLLECTOR_DIR),
|
||||
stdout=out,
|
||||
stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL,
|
||||
creationflags=flags if sys.platform == "win32" else 0,
|
||||
env={**os.environ, "PYTHONIOENCODING": "utf-8"},
|
||||
)
|
||||
except OSError as e: # 解释器不存在 / 权限不足
|
||||
_proc = None
|
||||
raise CollectorError(f"启动失败:{type(e).__name__}: {e}", status=500)
|
||||
|
||||
# 等两秒:脚本如果 import 就报错会立刻退出,这种情况直接把日志尾给它
|
||||
time.sleep(2.0)
|
||||
if _proc.poll() is not None:
|
||||
code = _proc.returncode
|
||||
_proc = None
|
||||
detail = "\n".join(tail(10)) or "(日志为空)"
|
||||
raise CollectorError(f"采集启动后立刻退出(exit={code}):\n{detail}", status=500)
|
||||
|
||||
return status()
|
||||
|
||||
|
||||
def _kill_pid(pid: int) -> None:
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
subprocess.run(
|
||||
["taskkill", "/T", "/F", "/PID", str(pid)],
|
||||
capture_output=True,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass # taskkill 不可用就走后面的兜底
|
||||
else:
|
||||
try:
|
||||
os.kill(pid, 15)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def stop() -> dict:
|
||||
global _proc
|
||||
|
||||
pid = current_pid()
|
||||
if not pid:
|
||||
raise CollectorError("采集当前没有在运行", status=409)
|
||||
|
||||
mine = _proc is not None and _proc.pid == pid
|
||||
_kill_pid(pid)
|
||||
|
||||
for _ in range(30): # 最多等 6 秒
|
||||
if not _is_running(pid):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
# 兜底:自己起的子进程还没退,直接 TerminateProcess
|
||||
if _is_running(pid) and mine:
|
||||
try:
|
||||
_proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_running(pid):
|
||||
raise CollectorError(f"停止失败,进程 {pid} 还在运行(可在任务管理器手动结束)", status=500)
|
||||
|
||||
_proc = None
|
||||
try:
|
||||
COLLECTOR_PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return status()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""JSONL 日志读取与聚合(埋点事件 + 写操作审计)。
|
||||
|
||||
设计要点(对应 04 文档 6.3):
|
||||
- 按天分文件 `run_YYYYMMDD.jsonl`,只追加;坏行计数跳过,绝不抛 500
|
||||
- 缓存键 = (文件路径, st_mtime_ns, st_size),文件只增长,命中即复用
|
||||
- 文件/目录缺失 → 返回空集 + available=False,页面据此降级显示 "—"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from ..config import LOG_DIR, LOG_DIRS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
AUDIT_FILE = "audit.jsonl"
|
||||
EVENTS = ("fetch_task", "fetch_empty", "upload", "exception")
|
||||
|
||||
# path(str) -> (mtime_ns, size, events, bad_lines)
|
||||
_cache: dict[str, tuple[int, int, list[dict], int]] = {}
|
||||
|
||||
|
||||
def run_log_path(day: date) -> Path:
|
||||
"""主日志目录(兼容旧调用)。"""
|
||||
return LOG_DIR / f"run_{day.strftime('%Y%m%d')}.jsonl"
|
||||
|
||||
|
||||
def run_log_paths(day: date) -> list[Path]:
|
||||
"""当天在所有配置目录下的候选文件(脚本可能在别的目录跑)。"""
|
||||
name = f"run_{day.strftime('%Y%m%d')}.jsonl"
|
||||
return [d / name for d in LOG_DIRS]
|
||||
|
||||
|
||||
def _parse_file(path: Path) -> tuple[list[dict], int]:
|
||||
"""读取并解析一个 JSONL 文件,返回 (events, bad_lines)。"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
try:
|
||||
with path.open("r", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
bad += 1
|
||||
continue
|
||||
if isinstance(obj, dict) and obj.get("event"):
|
||||
events.append(obj)
|
||||
else:
|
||||
bad += 1
|
||||
except OSError:
|
||||
return [], 0
|
||||
return events, bad
|
||||
|
||||
|
||||
def read_day(day: date) -> tuple[list[dict], dict]:
|
||||
"""读取某天的事件(**合并所有配置的日志目录**)。
|
||||
|
||||
返回 (events, meta),meta 含 available / bad_lines / paths。
|
||||
"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
paths: list[str] = []
|
||||
available = False
|
||||
|
||||
for path in run_log_paths(day):
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
st = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
available = True
|
||||
paths.append(str(path))
|
||||
|
||||
key = str(path)
|
||||
cached = _cache.get(key)
|
||||
if cached and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
|
||||
events.extend(cached[2])
|
||||
bad += cached[3]
|
||||
continue
|
||||
|
||||
day_events, day_bad = _parse_file(path)
|
||||
_cache[key] = (st.st_mtime_ns, st.st_size, day_events, day_bad)
|
||||
events.extend(day_events)
|
||||
bad += day_bad
|
||||
|
||||
return events, {"available": available, "bad_lines": bad, "paths": paths}
|
||||
|
||||
|
||||
def read_range(start: date, end: date) -> tuple[list[dict], dict]:
|
||||
"""读取 [start, end] 区间事件(逐天文件依次读取)。"""
|
||||
events: list[dict] = []
|
||||
bad = 0
|
||||
any_available = False
|
||||
day = start
|
||||
while day <= end:
|
||||
day_events, meta = read_day(day)
|
||||
events.extend(day_events)
|
||||
bad += meta.get("bad_lines", 0)
|
||||
any_available = any_available or meta.get("available", False)
|
||||
day += timedelta(days=1)
|
||||
return events, {"available": any_available, "bad_lines": bad}
|
||||
|
||||
|
||||
# ── 聚合 ────────────────────────────────────────────────────────────────
|
||||
def empty_counter() -> dict:
|
||||
return {
|
||||
"fetch_task": 0,
|
||||
"upload_ok": 0,
|
||||
"upload_fail": 0,
|
||||
"fetch_empty": 0,
|
||||
"exception": 0,
|
||||
"last_event_at": None,
|
||||
}
|
||||
|
||||
|
||||
def _add(counter: dict, event: dict) -> None:
|
||||
name = event.get("event")
|
||||
if name == "upload":
|
||||
key = "upload_ok" if int(event.get("ok") or 0) == 1 else "upload_fail"
|
||||
counter[key] += 1
|
||||
elif name in ("fetch_task", "fetch_empty", "exception"):
|
||||
counter[name] += 1
|
||||
ts = event.get("ts")
|
||||
if isinstance(ts, str) and (counter["last_event_at"] is None or ts > counter["last_event_at"]):
|
||||
counter["last_event_at"] = ts
|
||||
|
||||
|
||||
def aggregate(events: list[dict]) -> dict:
|
||||
"""整体聚合(overview 用)。"""
|
||||
total = empty_counter()
|
||||
for ev in events:
|
||||
_add(total, ev)
|
||||
return total
|
||||
|
||||
|
||||
def aggregate_by_hd(events: list[dict]) -> dict[int, dict]:
|
||||
"""按 hd_id 聚合(账号池页 / stats/account 用)。"""
|
||||
out: dict[int, dict] = {}
|
||||
for ev in events:
|
||||
try:
|
||||
hd_id = int(ev.get("hd_id"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
_add(out.setdefault(hd_id, empty_counter()), ev)
|
||||
return out
|
||||
|
||||
|
||||
def aggregate_by_city(events: list[dict]) -> dict[str, dict]:
|
||||
"""按 target_city 聚合(城市页用)。"""
|
||||
out: dict[str, dict] = {}
|
||||
for ev in events:
|
||||
city = ev.get("target_city") or ev.get("bind_city")
|
||||
if not city:
|
||||
continue
|
||||
_add(out.setdefault(str(city), empty_counter()), ev)
|
||||
return out
|
||||
|
||||
|
||||
def timeline(start: date, end: date) -> list[dict]:
|
||||
"""按天时间线(概览趋势用),缺失日期给出 logs=False。"""
|
||||
items: list[dict] = []
|
||||
day = start
|
||||
while day <= end:
|
||||
events, meta = read_day(day)
|
||||
agg = aggregate(events)
|
||||
items.append(
|
||||
{
|
||||
"date": day.isoformat(),
|
||||
"fetch_task": agg["fetch_task"],
|
||||
"upload_ok": agg["upload_ok"],
|
||||
"fetch_empty": agg["fetch_empty"],
|
||||
"logs": bool(meta.get("available")),
|
||||
}
|
||||
)
|
||||
day += timedelta(days=1)
|
||||
return items
|
||||
|
||||
|
||||
def available(day: date) -> bool:
|
||||
return any(p.is_file() for p in run_log_paths(day))
|
||||
|
||||
|
||||
# ── 审计(写操作)────────────────────────────────────────────────────────
|
||||
def write_audit(record: dict) -> bool:
|
||||
"""追加一行审计到 logs/audit.jsonl。任何异常都吞掉,返回是否写成功。"""
|
||||
try:
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with (LOG_DIR / AUDIT_FILE).open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
return True
|
||||
except Exception: # 审计失败不影响已提交的库变更
|
||||
logger.exception("写审计失败")
|
||||
return False
|
||||
|
||||
|
||||
def read_audit(limit: int = 50) -> list[dict]:
|
||||
"""读取审计文件末 limit 行(倒序)。"""
|
||||
path = LOG_DIR / AUDIT_FILE
|
||||
if not path.is_file():
|
||||
return []
|
||||
try:
|
||||
with path.open("r", encoding="utf-8", errors="replace") as f:
|
||||
lines = f.readlines()[-limit:]
|
||||
except OSError:
|
||||
return []
|
||||
out: list[dict] = []
|
||||
for line in reversed(lines):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(obj, dict):
|
||||
out.append(obj)
|
||||
return out
|
||||
|
||||
|
||||
def log_dir_info() -> dict:
|
||||
"""health 用:日志目录(可能多个)与可写性。"""
|
||||
import os
|
||||
|
||||
return {
|
||||
"log_dir": str(LOG_DIR),
|
||||
"log_dirs": [str(d) for d in LOG_DIRS],
|
||||
"log_exists": LOG_DIR.is_dir(),
|
||||
"log_writable": LOG_DIR.is_dir() and os.access(LOG_DIR, os.W_OK),
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""业务字典与脱敏工具(唯一实现处,前端不重复定义)。
|
||||
|
||||
- IS_OK_DICT : hotel_hd.is_ok 的状态字典(与 01 文档 3.2 一致)
|
||||
- CITY_GPS : 采集脚本 `酒店详情.py` 里的城市坐标表(合法城市的第二重约束)
|
||||
- 脱敏 : dfpid 只留后 8 位、代理只留 ip:port
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
# ── is_ok 状态字典 ──────────────────────────────────────────────────────
|
||||
# tone 供前端选色:ok=绿 / danger=红 / warn=橙 / muted=灰
|
||||
IS_OK_DICT: dict[str, dict] = {
|
||||
"NULL": {"text": "可用", "tone": "ok"},
|
||||
"403": {"text": "封禁/风控", "tone": "danger"},
|
||||
"401": {"text": "登录失效", "tone": "warn"},
|
||||
"418": {"text": "网络受限", "tone": "warn"},
|
||||
"0": {"text": "异常", "tone": "danger"},
|
||||
"6": {"text": "未知(6)", "tone": "muted"},
|
||||
"_other": {"text": "未知", "tone": "muted"},
|
||||
}
|
||||
|
||||
|
||||
def status_of(is_ok: int | None) -> tuple[str, str]:
|
||||
"""(文案, tone)。None → 可用。"""
|
||||
if is_ok is None:
|
||||
return IS_OK_DICT["NULL"]["text"], IS_OK_DICT["NULL"]["tone"]
|
||||
key = str(is_ok)
|
||||
item = IS_OK_DICT.get(key)
|
||||
if item:
|
||||
return item["text"], item["tone"]
|
||||
return f"{IS_OK_DICT['_other']['text']}({is_ok})", IS_OK_DICT["_other"]["tone"]
|
||||
|
||||
|
||||
# ── 城市坐标(与采集脚本 CITY_GPS 完全一致,共 40 城)──────────────────
|
||||
CITY_GPS: dict[str, tuple[str, str]] = {
|
||||
"苏州": ("31.3", "120.6"),
|
||||
"佛山": ("23.0", "113.1"),
|
||||
"长沙": ("28.2", "112.9"),
|
||||
"武汉": ("30.594940", "114.302634"),
|
||||
"杭州": ("30.231471", "120.018594"),
|
||||
"太原": ("37.9", "112.5"),
|
||||
"乌鲁木齐": ("43.8", "87.6"),
|
||||
"上海": ("30.948869", "121.303506"),
|
||||
"重庆": ("29.6", "106.5"),
|
||||
"成都": ("30.6", "104.1"),
|
||||
"南通": ("32.0", "120.9"),
|
||||
"深圳": ("22.545482", "114.055597"),
|
||||
"兰州": ("36.1", "103.8"),
|
||||
"海口": ("20.0", "110.3"),
|
||||
"济南": ("36.7", "117.0"),
|
||||
"南京": ("32.1", "118.8"),
|
||||
"郑州": ("34.7", "113.6"),
|
||||
"福州": ("26.1", "119.3"),
|
||||
"拉萨": ("29.7", "91.1"),
|
||||
"沈阳": ("41.8", "123.4"),
|
||||
"广州": ("23.437968", "113.554650"),
|
||||
"昆明": ("25.0", "102.7"),
|
||||
"北京": ("39.9", "116.4"),
|
||||
"天津": ("39.1", "117.2"),
|
||||
"长春": ("43.9", "125.3"),
|
||||
"西安": ("34.3", "108.9"),
|
||||
"哈尔滨": ("45.8", "126.5"),
|
||||
"贵阳": ("26.6", "106.7"),
|
||||
"银川": ("38.5", "106.2"),
|
||||
"西宁": ("36.616448", "101.775687"),
|
||||
"南昌": ("28.7", "115.9"),
|
||||
"呼和浩特": ("40.8", "111.7"),
|
||||
"石家庄": ("38.0", "114.5"),
|
||||
"南宁": ("22.8", "108.4"),
|
||||
"合肥": ("31.8", "117.2"),
|
||||
"青岛": ("36.1", "120.4"),
|
||||
"东莞": ("23.0", "113.8"),
|
||||
"厦门": ("24.5", "118.1"),
|
||||
"无锡": ("31.5", "120.3"),
|
||||
"大连": ("38.9", "121.6"),
|
||||
}
|
||||
|
||||
|
||||
def legal_cities(proxy_cities: list[str] | set[str]) -> list[str]:
|
||||
"""合法城市白名单 = 代理池城市 ∩ CITY_GPS。
|
||||
|
||||
南通有坐标但没有代理 IP,因此天然被排除;改成白名单外的城市会让采集脚本
|
||||
`run_one()` 在补 IP 分支抛 AttributeError。
|
||||
"""
|
||||
return sorted({c for c in proxy_cities if c} & CITY_GPS.keys())
|
||||
|
||||
|
||||
# ── 脱敏 ────────────────────────────────────────────────────────────────
|
||||
_DFPID_TAIL = 8
|
||||
# 实测 hotel_hd.dfpid 共 348 行全部带中文后缀(导入时把 title 拼在了后面,
|
||||
# 如 'u94x6…uw71xu美团酒店详情'),脱敏前必须先剔掉中文部分
|
||||
_CN_SUFFIX = re.compile(r"[\u4e00-\u9fff].*$")
|
||||
|
||||
|
||||
def mask_dfpid(dfpid: str | None) -> str | None:
|
||||
"""dfpid → `…` + 后 8 位(先剔除尾部中文标题);完整值只在后端使用。"""
|
||||
if not dfpid:
|
||||
return None
|
||||
s = _CN_SUFFIX.sub("", str(dfpid)).strip()
|
||||
if not s:
|
||||
return None
|
||||
return "…" + s[-_DFPID_TAIL:] if len(s) > _DFPID_TAIL else "…" + s
|
||||
|
||||
|
||||
_PROX_IP_PORT = re.compile(r"@([0-9a-zA-Z.\-]+):(\d+)")
|
||||
|
||||
|
||||
def extract_prox_ip(prox: str | None) -> str | None:
|
||||
"""从代理 JSON 抽 `ip:port`,账号密码一律丢弃。"""
|
||||
if not prox:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(prox) if isinstance(prox, str) else prox
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
for value in data.values():
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
m = _PROX_IP_PORT.search(value)
|
||||
if m:
|
||||
return f"{m.group(1)}:{m.group(2)}"
|
||||
return None
|
||||
@@ -0,0 +1,362 @@
|
||||
"""数据查询层:hotel_hd(账号池)+ hotel_task / hotel_json(记录)。
|
||||
|
||||
说明:
|
||||
- hotel_hd 只有约 350 行,因此账号池相关的筛选/排序/分页在内存里做,
|
||||
这样能一次 merge 今日日志跑量,避免 N+1;
|
||||
- hotel_task / hotel_json 是大表(7k / 10k+ 行),一律服务端 SQL 分页;
|
||||
- hotel_json 列表绝不返回 json_data(单条 130~440KB),只给 LENGTH()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE
|
||||
from ..database import headers_engine, main_engine
|
||||
from .hotel_meta import extract_prox_ip, mask_dfpid, status_of
|
||||
|
||||
# ── 账号池 ──────────────────────────────────────────────────────────────
|
||||
_POOL_SQL = text(
|
||||
"""
|
||||
SELECT COUNT(*) AS total,
|
||||
SUM(is_ok IS NULL) AS available,
|
||||
SUM(is_ok = 403) AS s403,
|
||||
SUM(is_ok = 401) AS s401,
|
||||
SUM(is_ok = 418) AS s418,
|
||||
SUM(is_ok = 0) AS s0,
|
||||
SUM(is_ok = 6) AS s6,
|
||||
SUM(is_ok IS NOT NULL AND is_ok NOT IN (403, 401, 418, 0, 6)) AS other
|
||||
FROM hotel_hd
|
||||
WHERE title LIKE :pat
|
||||
"""
|
||||
)
|
||||
|
||||
_ACCOUNTS_SQL = text(
|
||||
"""
|
||||
SELECT id, dfpid, ip, channel, title, is_ok, req_count, current_count,
|
||||
prox, city, mt_traceid, created_at, updated_at
|
||||
FROM hotel_hd
|
||||
WHERE title LIKE :pat
|
||||
"""
|
||||
)
|
||||
|
||||
_STATUS_KEYS = {"403", "401", "418", "0", "6"}
|
||||
|
||||
|
||||
async def pool_stats() -> dict:
|
||||
"""池子健康度(口径与 01 文档 3.2/3.4 一致)。"""
|
||||
async with headers_engine.connect() as conn:
|
||||
row = (await conn.execute(_POOL_SQL, {"pat": HOTEL_TITLE_LIKE})).first()
|
||||
data = {k: int(v or 0) for k, v in dict(row._mapping).items()} if row else {}
|
||||
total = data.get("total", 0)
|
||||
data["others_all"] = data.get("s418", 0) + data.get("s0", 0) + data.get("s6", 0) + data.get("other", 0)
|
||||
data["available_rate"] = round(data.get("available", 0) / total * 100, 1) if total else None
|
||||
return data
|
||||
|
||||
|
||||
def _match_status(is_ok, wanted: set[str]) -> bool:
|
||||
key = "NULL" if is_ok is None else str(is_ok)
|
||||
if key in wanted:
|
||||
return True
|
||||
if "OTHER" in wanted and is_ok is not None and key not in _STATUS_KEYS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fmt_dt(value) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
|
||||
def _decorate_account(row: dict, today: dict | None) -> dict:
|
||||
is_ok = row.get("is_ok")
|
||||
text_, tone = status_of(is_ok)
|
||||
prox = row.get("prox")
|
||||
return {
|
||||
"id": row["id"],
|
||||
# ── hotel_hd 原始列(页面 1 直接展示)──────────────────────────
|
||||
"is_ok": is_ok,
|
||||
"req_count": int(row.get("req_count") or 0),
|
||||
"current_count": int(row.get("current_count") or 0),
|
||||
"prox_raw": prox, # 原始代理 JSON(含账号密码,按用户要求原样展示)
|
||||
"city": row.get("city"),
|
||||
"mt_traceid": row.get("mt_traceid"),
|
||||
"created_at": _fmt_dt(row.get("created_at")),
|
||||
"updated_at": _fmt_dt(row.get("updated_at")),
|
||||
# ── 辅助字段(状态文案 / 脱敏 / 今日跑量)──────────────────────
|
||||
"dfpid_tail": mask_dfpid(row.get("dfpid")),
|
||||
"has_prox": bool(prox),
|
||||
"prox_ip": extract_prox_ip(prox),
|
||||
"status_text": text_,
|
||||
"status_tone": tone,
|
||||
"today": {
|
||||
"fetch_task": (today or {}).get("fetch_task", 0),
|
||||
"upload_ok": (today or {}).get("upload_ok", 0),
|
||||
"upload_fail": (today or {}).get("upload_fail", 0),
|
||||
"fetch_empty": (today or {}).get("fetch_empty", 0),
|
||||
},
|
||||
"ip": row.get("ip"),
|
||||
"channel": row.get("channel"),
|
||||
}
|
||||
|
||||
|
||||
async def all_accounts_raw() -> list[dict]:
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(_ACCOUNTS_SQL, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return [dict(r._mapping) for r in rows]
|
||||
|
||||
|
||||
async def account_rows(
|
||||
*,
|
||||
today_agg: dict[int, dict],
|
||||
city: str | None = None,
|
||||
status: list[str] | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
sort: str = "id",
|
||||
order: str = "desc",
|
||||
) -> tuple[list[dict], int]:
|
||||
"""账号池筛选/排序/分页(内存态,350 行级别)。"""
|
||||
rows = await all_accounts_raw()
|
||||
wanted = {s.upper() for s in (status or [])}
|
||||
if city:
|
||||
rows = [r for r in rows if (r.get("city") or "") == city]
|
||||
if wanted:
|
||||
rows = [r for r in rows if _match_status(r.get("is_ok"), wanted)]
|
||||
if keyword:
|
||||
kw = keyword.strip().lower()
|
||||
rows = [r for r in rows if kw in str(r.get("dfpid") or "").lower()]
|
||||
|
||||
items = [_decorate_account(r, today_agg.get(r["id"])) for r in rows]
|
||||
|
||||
key_map = {
|
||||
"id": lambda x: x["id"],
|
||||
"today_fetch_task": lambda x: x["today"]["fetch_task"],
|
||||
"updated_at": lambda x: x["updated_at"] or "",
|
||||
"req_count": lambda x: x["req_count"],
|
||||
"current_count": lambda x: x["current_count"],
|
||||
}
|
||||
key = key_map.get(sort, key_map["id"])
|
||||
items.sort(key=key, reverse=(order.lower() != "asc"))
|
||||
|
||||
total = len(items)
|
||||
start = max(page - 1, 0) * size
|
||||
return items[start : start + size], total
|
||||
|
||||
|
||||
async def get_account(hd_id: int) -> dict | None:
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, prox, is_ok, req_count, current_count "
|
||||
"FROM hotel_hd WHERE id = :id AND title LIKE :pat"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
row = (await conn.execute(sql, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
return dict(row._mapping) if row else None
|
||||
|
||||
|
||||
async def city_account_counts() -> dict[str, int]:
|
||||
sql = text(
|
||||
"SELECT city, COUNT(*) AS n FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND city IS NOT NULL AND city <> '' GROUP BY city"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return {r[0]: int(r[1]) for r in rows}
|
||||
|
||||
|
||||
async def proxy_city_ips() -> dict[str, int]:
|
||||
"""每城可用代理 IP 数(proxs_list,channel = 到期日,非空即有效)。"""
|
||||
sql = text(
|
||||
"SELECT city, COUNT(*) AS ips FROM project_proxy.proxs_list "
|
||||
"WHERE channel IS NOT NULL AND channel <> '' AND city IS NOT NULL "
|
||||
"GROUP BY city"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql)).fetchall()
|
||||
return {r[0]: int(r[1]) for r in rows}
|
||||
|
||||
|
||||
async def available_accounts() -> list[dict]:
|
||||
"""可用账号(is_ok IS NULL),带 current_count —— 用于算"手上包还剩多少产能"。"""
|
||||
sql = text(
|
||||
"SELECT id, city, current_count FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NULL ORDER BY current_count DESC, id DESC"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE})).fetchall()
|
||||
return [
|
||||
{"id": r[0], "city": r[1], "current_count": int(r[2] or 0)} for r in rows
|
||||
]
|
||||
|
||||
|
||||
async def stale_accounts(hours: int = 24, limit: int = 100) -> list[dict]:
|
||||
"""可用(is_ok IS NULL)但超过 N 小时没活动的账号。"""
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, updated_at, "
|
||||
" TIMESTAMPDIFF(MINUTE, updated_at, NOW()) AS idle_minutes "
|
||||
"FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NULL AND updated_at < NOW() - INTERVAL :h HOUR "
|
||||
"ORDER BY updated_at ASC LIMIT :lim"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE, "h": hours, "lim": limit})).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r._mapping)
|
||||
out.append(
|
||||
{
|
||||
"hd_id": d["id"],
|
||||
"dfpid_tail": mask_dfpid(d.get("dfpid")),
|
||||
"city": d.get("city"),
|
||||
"updated_at": d["updated_at"].strftime("%Y-%m-%d %H:%M:%S") if d.get("updated_at") else None,
|
||||
"hours": round((d.get("idle_minutes") or 0) / 60, 1),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
async def blocked_accounts(limit: int = 500) -> list[dict]:
|
||||
"""所有非 NULL 状态(封禁清单)。"""
|
||||
sql = text(
|
||||
"SELECT id, dfpid, city, is_ok, updated_at FROM hotel_hd "
|
||||
"WHERE title LIKE :pat AND is_ok IS NOT NULL "
|
||||
"ORDER BY is_ok, updated_at DESC LIMIT :lim"
|
||||
)
|
||||
async with headers_engine.connect() as conn:
|
||||
rows = (await conn.execute(sql, {"pat": HOTEL_TITLE_LIKE, "lim": limit})).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r._mapping)
|
||||
text_, tone = status_of(d.get("is_ok"))
|
||||
out.append(
|
||||
{
|
||||
"hd_id": d["id"],
|
||||
"dfpid_tail": mask_dfpid(d.get("dfpid")),
|
||||
"city": d.get("city"),
|
||||
"is_ok": d["is_ok"],
|
||||
"status_text": text_,
|
||||
"status_tone": tone,
|
||||
"updated_at": d["updated_at"].strftime("%Y-%m-%d %H:%M:%S") if d.get("updated_at") else None,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ── 任务记录 ─────────────────────────────────────────────────────────────
|
||||
_TASK_COLS = (
|
||||
"id, hotel_id, city_id, hotel_name, city_name, check_in_date, check_out_date, "
|
||||
"unique_id, hotel_star, selected_city, area_type, area_name, created_at, updated_at"
|
||||
)
|
||||
|
||||
|
||||
async def tasks_page(
|
||||
*,
|
||||
start: date,
|
||||
end: date,
|
||||
city: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
) -> tuple[list[dict], int]:
|
||||
where = "created_at >= :start AND created_at < :end_ex"
|
||||
params: dict = {"start": start, "end_ex": end + timedelta(days=1)}
|
||||
if city:
|
||||
where += " AND city_name = :city"
|
||||
params["city"] = city if city.endswith("市") else f"{city}市"
|
||||
if keyword:
|
||||
where += " AND (hotel_name LIKE :kw OR unique_id LIKE :kw_pre)"
|
||||
params["kw"] = f"%{keyword}%"
|
||||
params["kw_pre"] = f"{keyword}%"
|
||||
|
||||
count_sql = text(f"SELECT COUNT(*) FROM hotel_task WHERE {where}")
|
||||
list_sql = text(
|
||||
f"SELECT {_TASK_COLS} FROM hotel_task WHERE {where} "
|
||||
"ORDER BY created_at DESC, id DESC LIMIT :size OFFSET :offset"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
total = int((await conn.execute(count_sql, params)).scalar() or 0)
|
||||
rows = (
|
||||
await conn.execute(
|
||||
list_sql, {**params, "size": size, "offset": max(page - 1, 0) * size}
|
||||
)
|
||||
).fetchall()
|
||||
return [_json_row(r) for r in rows], total
|
||||
|
||||
|
||||
# ── 采集记录 ─────────────────────────────────────────────────────────────
|
||||
# ⚠ 不要 SELECT LENGTH(json_data):实测远程库上单次 38s(longtext 溢出页需跨网读取),
|
||||
# 列表只取元数据;json_size 在详情接口里用 Python len() 算。
|
||||
_RECORD_COLS = (
|
||||
"id, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date, create_at"
|
||||
)
|
||||
|
||||
|
||||
async def records_page(
|
||||
*,
|
||||
start: date,
|
||||
end: date,
|
||||
city: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
) -> tuple[list[dict], int]:
|
||||
where = "create_at >= :start AND create_at < :end_ex"
|
||||
params: dict = {"start": start, "end_ex": end + timedelta(days=1)}
|
||||
if city:
|
||||
where += " AND city_name = :city"
|
||||
params["city"] = city if city.endswith("市") else f"{city}市"
|
||||
if keyword:
|
||||
where += " AND (hotel_name LIKE :kw OR poi_id LIKE :kw_pre)"
|
||||
params["kw"] = f"%{keyword}%"
|
||||
params["kw_pre"] = f"{keyword}%"
|
||||
|
||||
count_sql = text(f"SELECT COUNT(*) FROM hotel_json WHERE {where}")
|
||||
list_sql = text(
|
||||
f"SELECT {_RECORD_COLS} FROM hotel_json WHERE {where} "
|
||||
"ORDER BY create_at DESC, id DESC LIMIT :size OFFSET :offset"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
total = int((await conn.execute(count_sql, params)).scalar() or 0)
|
||||
rows = (
|
||||
await conn.execute(
|
||||
list_sql, {**params, "size": size, "offset": max(page - 1, 0) * size}
|
||||
)
|
||||
).fetchall()
|
||||
return [_json_row(r) for r in rows], total
|
||||
|
||||
|
||||
async def record_by_id(rec_id: int) -> dict | None:
|
||||
sql = text(
|
||||
"SELECT id, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date, "
|
||||
"create_at, json_data "
|
||||
"FROM hotel_json WHERE id = :id"
|
||||
)
|
||||
async with main_engine.connect() as conn:
|
||||
row = (await conn.execute(sql, {"id": rec_id})).first()
|
||||
return dict(row._mapping) if row else None
|
||||
|
||||
|
||||
async def count_today(table: str, day: date) -> int:
|
||||
"""某表某天的行数(hotel_task 用 created_at,hotel_json 用 create_at)。"""
|
||||
col = "created_at" if table == "hotel_task" else "create_at"
|
||||
sql = text(f"SELECT COUNT(*) FROM {table} WHERE {col} >= :s AND {col} < :e")
|
||||
async with main_engine.connect() as conn:
|
||||
return int((await conn.execute(sql, {"s": day, "e": day + timedelta(days=1)})).scalar() or 0)
|
||||
|
||||
|
||||
def _json_row(row) -> dict:
|
||||
out = {}
|
||||
for k, v in dict(row._mapping).items():
|
||||
if isinstance(v, datetime):
|
||||
out[k] = v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
elif isinstance(v, date):
|
||||
out[k] = v.isoformat()
|
||||
else:
|
||||
out[k] = v
|
||||
return out
|
||||
@@ -0,0 +1,139 @@
|
||||
"""hotel_hd 写操作:改绑定城市(同时清空 prox)与单条重置 is_ok。
|
||||
|
||||
约束(01 文档 FR-7):
|
||||
- 只允许更新 city / prox / is_ok 三列;
|
||||
- 单事务 + SELECT ... FOR UPDATE,数据库失败整体回滚且不写审计;
|
||||
- 城市必须在合法白名单(代理池 ∩ CITY_GPS)内,且该城至少有 1 个可用代理 IP;
|
||||
- 审计在事务提交后追加到 logs/audit.jsonl,写失败不影响已提交的库变更(响应里 audit_ok=false)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..config import HOTEL_TITLE_LIKE
|
||||
from ..database import headers_engine
|
||||
from . import hotel_logs
|
||||
from .hotel_meta import extract_prox_ip, mask_dfpid
|
||||
|
||||
|
||||
class WriteError(Exception):
|
||||
"""业务校验失败,router 层转成 HTTP 错误。"""
|
||||
|
||||
def __init__(self, code: int, msg: str, status: int = 400):
|
||||
super().__init__(msg)
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.status = status
|
||||
|
||||
|
||||
_SELECT_ONE = text(
|
||||
"SELECT id, dfpid, city, prox, is_ok, req_count, current_count FROM hotel_hd "
|
||||
"WHERE id = :id AND title LIKE :pat FOR UPDATE"
|
||||
)
|
||||
|
||||
|
||||
async def change_city(
|
||||
hd_id: int,
|
||||
new_city: str,
|
||||
*,
|
||||
legal_cities: list[str],
|
||||
proxy_ips: dict[str, int],
|
||||
operator: str = "local",
|
||||
) -> dict:
|
||||
new_city = (new_city or "").strip()
|
||||
if not new_city:
|
||||
raise WriteError(1001, "城市不能为空")
|
||||
if new_city not in set(legal_cities):
|
||||
raise WriteError(1002, f"城市「{new_city}」不在可用代理城市清单内")
|
||||
if proxy_ips.get(new_city, 0) <= 0:
|
||||
raise WriteError(1003, f"城市「{new_city}」当前没有可用代理,请先在代理池补充")
|
||||
|
||||
async with headers_engine.begin() as conn:
|
||||
row = (await conn.execute(_SELECT_ONE, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
if not row:
|
||||
raise WriteError(1005, f"账号 #{hd_id} 不存在", status=404)
|
||||
old = dict(row._mapping)
|
||||
# 同城判断放在 is_ok 之前:用户点了同一个城市,提示「无需修改」比「状态不对」更贴合意图。
|
||||
if (old.get("city") or "") == new_city:
|
||||
raise WriteError(1004, "新旧城市相同,无需修改")
|
||||
# 允许操作的两种情况:
|
||||
# ① is_ok=0(异常包) → 改城市,复活它
|
||||
# ② is_ok=NULL 且 city 为空(全新包)→ 添加城市,让它能跑起来
|
||||
# 403/401/418 是 headers 失效或风控,换城市没用;已绑城市的可用包也不该乱动。
|
||||
is_new_package = old.get("is_ok") is None and not (old.get("city") or "").strip()
|
||||
if old.get("is_ok") != 0 and not is_new_package:
|
||||
current = "NULL" if old.get("is_ok") is None else f"{old.get('is_ok')}"
|
||||
raise WriteError(
|
||||
1006,
|
||||
f"只有 is_ok=0(异常包)或 is_ok=NULL 且未绑城市(新包)才能改/加城市,"
|
||||
f"当前 is_ok={current} city={old.get('city') or 'NULL'}",
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text("UPDATE hotel_hd SET city = :city, prox = NULL, is_ok = NULL WHERE id = :id"),
|
||||
{"city": new_city, "id": hd_id},
|
||||
)
|
||||
|
||||
audit_ok = hotel_logs.write_audit(
|
||||
{
|
||||
"ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"action": "set_city" if is_new_package else "change_city",
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(old.get("dfpid")),
|
||||
"old_city": old.get("city"),
|
||||
"new_city": new_city,
|
||||
"old_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"new_prox_ip": None,
|
||||
"old_is_ok": old.get("is_ok"),
|
||||
"new_is_ok": None,
|
||||
"operator": operator,
|
||||
"result": "ok",
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"id": hd_id,
|
||||
"old_city": old.get("city"),
|
||||
"new_city": new_city,
|
||||
"mode": "add" if is_new_package else "change",
|
||||
"prox_cleared": True,
|
||||
"is_ok_reset": True,
|
||||
"proxy_ips_in_city": proxy_ips.get(new_city, 0),
|
||||
"audit_ok": audit_ok,
|
||||
}
|
||||
|
||||
|
||||
async def reset_is_ok(hd_id: int, *, operator: str = "local") -> dict:
|
||||
async with headers_engine.begin() as conn:
|
||||
row = (await conn.execute(_SELECT_ONE, {"id": hd_id, "pat": HOTEL_TITLE_LIKE})).first()
|
||||
if not row:
|
||||
raise WriteError(1005, f"账号 #{hd_id} 不存在", status=404)
|
||||
old = dict(row._mapping)
|
||||
if old.get("is_ok") is None:
|
||||
raise WriteError(1004, "该账号已是可用状态,无需重置")
|
||||
|
||||
await conn.execute(
|
||||
text("UPDATE hotel_hd SET is_ok = NULL WHERE id = :id"), {"id": hd_id}
|
||||
)
|
||||
|
||||
audit_ok = hotel_logs.write_audit(
|
||||
{
|
||||
"ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"action": "reset_is_ok",
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": mask_dfpid(old.get("dfpid")),
|
||||
"old_city": old.get("city"),
|
||||
"new_city": old.get("city"),
|
||||
"old_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"new_prox_ip": extract_prox_ip(old.get("prox")),
|
||||
"old_is_ok": old.get("is_ok"),
|
||||
"new_is_ok": None,
|
||||
"operator": operator,
|
||||
"result": "ok",
|
||||
}
|
||||
)
|
||||
|
||||
return {"id": hd_id, "old_is_ok": old.get("is_ok"), "new_is_ok": None, "audit_ok": audit_ok}
|
||||
@@ -0,0 +1,128 @@
|
||||
"""任务平台 OpenAPI 只读代理。
|
||||
|
||||
只允许三个只读接口:
|
||||
/getStats 按日期(+可选城市)拿成功/拒收/剩余
|
||||
/realtimeCityList 实时城市列表
|
||||
/realtimeCheckInOutDateList 可领取的入离日期
|
||||
⛔ 永不调用 /getTask、/uploadTaskDatagram(会消耗真实任务)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
|
||||
import requests
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..config import (
|
||||
PLATFORM_BASE,
|
||||
PLATFORM_CACHE_SECONDS,
|
||||
PLATFORM_PWD,
|
||||
PLATFORM_TIMEOUT,
|
||||
PLATFORM_USER,
|
||||
PLATFORM_VENDOR,
|
||||
)
|
||||
|
||||
# 直连(绕开本机 VPN),与采集脚本一致
|
||||
_DIRECT = {"http": "", "https": ""}
|
||||
_cache: dict[tuple, tuple[float, dict]] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
token = base64.b64encode(f"{PLATFORM_USER}:{PLATFORM_PWD}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
|
||||
|
||||
def _get(path: str, params: dict) -> dict:
|
||||
resp = requests.get(
|
||||
PLATFORM_BASE + path,
|
||||
headers=_headers(),
|
||||
params=params,
|
||||
timeout=PLATFORM_TIMEOUT,
|
||||
proxies=_DIRECT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _cached(key: tuple, producer, ttl: int) -> dict:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
hit = _cache.get(key)
|
||||
if hit and now - hit[0] < ttl:
|
||||
return hit[1]
|
||||
value = producer()
|
||||
with _lock:
|
||||
_cache[key] = (now, value)
|
||||
return value
|
||||
|
||||
|
||||
def get_stats_sync(day: date, city: str | None = None) -> dict:
|
||||
"""平台侧统计(单一城市或不传城市=全平台)。
|
||||
|
||||
历史日期(< 今天)结果不会再变,缓存 30 分钟;当天缓存 60 秒。
|
||||
"""
|
||||
ttl = PLATFORM_CACHE_SECONDS if day >= date.today() else 1800
|
||||
|
||||
def produce() -> dict:
|
||||
params = {"date": day.isoformat(), "vendorName": PLATFORM_VENDOR}
|
||||
if city:
|
||||
params["clientId"] = city
|
||||
try:
|
||||
body = _get("/getStats", params)
|
||||
data = body.get("data") or {}
|
||||
return {
|
||||
"ok": True,
|
||||
"date": day.isoformat(),
|
||||
"city": city,
|
||||
"success": data.get("success"),
|
||||
"reject": data.get("reject"),
|
||||
"remain": data.get("remain"),
|
||||
"timeout": data.get("timeout"),
|
||||
"cancel": data.get("cancel"),
|
||||
"error": None,
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 上游失败不阻塞页面
|
||||
return {
|
||||
"ok": False,
|
||||
"date": day.isoformat(),
|
||||
"city": city,
|
||||
"error": f"{type(e).__name__}: {e}"[:200],
|
||||
}
|
||||
|
||||
return _cached(("getStats", day.isoformat(), city or ""), produce, ttl)
|
||||
|
||||
|
||||
async def get_stats(day: date, city: str | None = None) -> dict:
|
||||
return await run_in_threadpool(get_stats_sync, day, city)
|
||||
|
||||
|
||||
def city_stats_sync(day: date, cities: list[str], concurrency: int = 5) -> list[dict]:
|
||||
"""按城市批量取平台统计(串行限流,避免打爆上游)。"""
|
||||
out: list[dict] = []
|
||||
for city in cities:
|
||||
out.append(get_stats_sync(day, city))
|
||||
return out
|
||||
|
||||
|
||||
async def city_stats(day: date, cities: list[str]) -> list[dict]:
|
||||
return await run_in_threadpool(city_stats_sync, day, cities)
|
||||
|
||||
|
||||
def dates_sync() -> list[dict]:
|
||||
def produce() -> dict:
|
||||
try:
|
||||
body = _get("/realtimeCheckInOutDateList", {"vendorName": PLATFORM_VENDOR})
|
||||
return {"ok": True, "items": body.get("data") or []}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "items": [], "error": f"{type(e).__name__}: {e}"[:200]}
|
||||
|
||||
return _cached(("dates",), produce, PLATFORM_CACHE_SECONDS).get("items", [])
|
||||
|
||||
|
||||
async def available_dates() -> list[dict]:
|
||||
return await run_in_threadpool(dates_sync)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""hotel_json.json_data 解析:把采集响应里的房型/价格抽成结构化列表。
|
||||
|
||||
支持结构:
|
||||
- prepayList(当前生产数据,`roomGoodsList.data[].goodsList[]`)—— 完整解析
|
||||
- dayRoomShelfModel(历史 shelf 响应)—— 尽力而为,失败则 parse_ok=False
|
||||
价格单位:原始为「分」,统一转「元」(保留 2 位)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
RAW_PREVIEW_LIMIT = 100 * 1024 # 100KB
|
||||
MAX_ROOMS = 200
|
||||
|
||||
|
||||
def _yuan(value) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return round(float(value) / 100.0, 2)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _iter_goods(doc: dict):
|
||||
container = doc.get("roomGoodsList") or {}
|
||||
if isinstance(container, dict):
|
||||
blocks = container.get("data") or []
|
||||
elif isinstance(container, list):
|
||||
blocks = container
|
||||
else:
|
||||
blocks = []
|
||||
for block in blocks:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
for goods in block.get("goodsList") or []:
|
||||
if isinstance(goods, dict):
|
||||
yield goods
|
||||
|
||||
|
||||
def _room_from_goods(goods: dict) -> dict:
|
||||
price_info = goods.get("priceInfo") or {}
|
||||
room_model = goods.get("goodsRoomModel") or {}
|
||||
payment = (goods.get("paymentTypeTips") or {}).get("tips")
|
||||
price = _yuan(price_info.get("averagePrice"))
|
||||
origin = _yuan(price_info.get("originalPrice"))
|
||||
inventory = goods.get("inventory")
|
||||
if inventory is None:
|
||||
inventory = goods.get("invRemain")
|
||||
return {
|
||||
"room_name": room_model.get("roomName") or goods.get("realRoomName") or "",
|
||||
"goods_name": goods.get("goodsName") or "",
|
||||
"price": price,
|
||||
"origin_price": origin,
|
||||
"inventory": int(inventory) if isinstance(inventory, (int, float)) else None,
|
||||
"tag": goods.get("tagName") or None,
|
||||
"payment": payment or None,
|
||||
"goods_id": goods.get("goodsId"),
|
||||
"promotion": price_info.get("promotionSubTitle") or None,
|
||||
}
|
||||
|
||||
|
||||
def parse_record(json_data) -> dict:
|
||||
"""解析一条 json_data,返回 {parse_ok, structure, rooms, min_price, error}。"""
|
||||
if isinstance(json_data, (bytes, bytearray)):
|
||||
try:
|
||||
json_data = json_data.decode("utf-8", errors="replace")
|
||||
except Exception: # noqa: BLE001
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "编码解析失败"}
|
||||
|
||||
if isinstance(json_data, str):
|
||||
try:
|
||||
doc = json.loads(json_data)
|
||||
except ValueError:
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "JSON 解析失败"}
|
||||
elif isinstance(json_data, dict):
|
||||
doc = json_data
|
||||
else:
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "未知数据类型"}
|
||||
|
||||
if not isinstance(doc, dict):
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "顶层不是对象"}
|
||||
|
||||
# ① prepayList:roomGoodsList
|
||||
if "roomGoodsList" in doc:
|
||||
rooms = []
|
||||
for goods in _iter_goods(doc):
|
||||
room = _room_from_goods(goods)
|
||||
if room["price"] is None and not room["room_name"]:
|
||||
continue
|
||||
rooms.append(room)
|
||||
if len(rooms) >= MAX_ROOMS:
|
||||
break
|
||||
rooms.sort(key=lambda r: (r["price"] is None, r["price"] if r["price"] is not None else 0))
|
||||
prices = [r["price"] for r in rooms if r["price"] is not None]
|
||||
return {
|
||||
"parse_ok": bool(rooms),
|
||||
"structure": "prepayList",
|
||||
"rooms": rooms,
|
||||
"min_price": min(prices) if prices else None,
|
||||
"error": None if rooms else "roomGoodsList 为空",
|
||||
}
|
||||
|
||||
# ② 历史 shelf 响应:结构过于嵌套,仅识别,不做结构化
|
||||
if "dayRoomShelfModel" in doc or (doc.get("results") and "dayRoomShelfModel" in json.dumps(doc)[:5000]):
|
||||
return {
|
||||
"parse_ok": False,
|
||||
"structure": "dayRoomShelfModel",
|
||||
"rooms": [],
|
||||
"min_price": None,
|
||||
"error": "历史 shelf 结构暂不支持结构化解析,请查看原始 JSON",
|
||||
}
|
||||
|
||||
return {"parse_ok": False, "structure": None, "rooms": [], "min_price": None, "error": "未知响应结构"}
|
||||
|
||||
|
||||
def raw_preview(json_data, limit: int = RAW_PREVIEW_LIMIT) -> tuple[str, bool]:
|
||||
"""返回 (预览文本, 是否被截断)。"""
|
||||
if isinstance(json_data, (bytes, bytearray)):
|
||||
json_data = json_data.decode("utf-8", errors="replace")
|
||||
text = json_data if isinstance(json_data, str) else json.dumps(json_data, ensure_ascii=False)
|
||||
if len(text) <= limit:
|
||||
return text, False
|
||||
return text[:limit], True
|
||||
@@ -0,0 +1,8 @@
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.30
|
||||
sqlalchemy[asyncio]>=2.0.36
|
||||
aiomysql>=0.2.0
|
||||
pydantic>=2.8
|
||||
python-dotenv>=1.0
|
||||
pymysql>=1.1
|
||||
requests>=2.31
|
||||
@@ -0,0 +1,205 @@
|
||||
"""冒烟检查:按区块验证后端接口。
|
||||
|
||||
用法(后端已在运行时):
|
||||
python scripts/smoke.py # 全部区块
|
||||
python scripts/smoke.py --only overview,trend # 只测指定区块
|
||||
python scripts/smoke.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部通过,1 = 有失败项。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
FAILS: list[str] = []
|
||||
CHECKS: dict = {}
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def block(name: str):
|
||||
def deco(fn):
|
||||
CHECKS[name] = fn
|
||||
return fn
|
||||
|
||||
return deco
|
||||
|
||||
|
||||
@block("health")
|
||||
def check_health(base: str) -> None:
|
||||
h = get(base, "/api/health")["data"]
|
||||
print(f" db_main={h.get('db_main')} db_headers={h.get('db_headers')} log_writable={h.get('log_writable')}")
|
||||
check(h.get("db_main") == "up", "主库连通")
|
||||
check(h.get("db_headers") == "up", "抓包库连通")
|
||||
check(bool(h.get("log_writable")), "日志目录可写")
|
||||
|
||||
|
||||
@block("meta")
|
||||
def check_meta(base: str) -> None:
|
||||
m = get(base, "/api/hotel/meta")["data"]
|
||||
legal = m.get("legal_cities", [])
|
||||
print(f" legal_cities={len(legal)} cities={len(m.get('cities', []))}")
|
||||
check(bool(legal), "合法城市白名单非空")
|
||||
check("南通" not in legal, "南通不在白名单")
|
||||
check(bool(m.get("is_ok_dict")), "is_ok 字典存在")
|
||||
|
||||
|
||||
@block("overview")
|
||||
def check_overview(base: str) -> None:
|
||||
o = get(base, "/api/hotel/overview")["data"]
|
||||
pool = o.get("pool", {})
|
||||
print(f" pool: total={pool.get('total')} available={pool.get('available')} "
|
||||
f"403={pool.get('s403')} 401={pool.get('s401')} others={pool.get('others_all')} "
|
||||
f"rate={pool.get('available_rate')}")
|
||||
print(f" today: {json.dumps(o.get('today'), ensure_ascii=False)}")
|
||||
print(f" logs_available={o.get('logs_available')} db_today={o.get('db_today')}")
|
||||
plat = o.get("platform") or {}
|
||||
print(f" platform: ok={plat.get('ok')} success={plat.get('success')} reject={plat.get('reject')} "
|
||||
f"remain={plat.get('remain')}" + ("" if plat.get("ok") else f" error={plat.get('error')}"))
|
||||
check(pool.get("total", 0) > 0, "账号总数 > 0", str(pool.get("total")))
|
||||
summed = (pool.get("available", 0) + pool.get("s403", 0) + pool.get("s401", 0)
|
||||
+ pool.get("others_all", 0))
|
||||
check(summed == pool.get("total", -1), "健康度分项之和 = 总数", f"{summed} vs {pool.get('total')}")
|
||||
check("success_rate" in o.get("today", {}), "today.success_rate 存在")
|
||||
|
||||
|
||||
@block("trend")
|
||||
def check_trend(base: str) -> None:
|
||||
t = get(base, "/api/hotel/trend?days=7")["data"]
|
||||
items = t.get("items", [])
|
||||
print(f" days={len(items)} last={json.dumps(items[-1], ensure_ascii=False) if items else None}")
|
||||
check(len(items) == 7, "返回 7 个点", str(len(items)))
|
||||
|
||||
|
||||
@block("accounts")
|
||||
def check_accounts(base: str) -> None:
|
||||
a = get(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")["data"]
|
||||
items = a.get("items", [])
|
||||
print(f" total={a.get('total')} size={len(items)}")
|
||||
if items:
|
||||
print(" sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check(a.get("total", 0) > 0, "账号池非空")
|
||||
check(len(items) <= 5, "分页 size 生效", str(len(items)))
|
||||
check(bool(items) and all(k in items[0] for k in ("id", "dfpid_tail", "status_text", "today")), "账号字段齐全")
|
||||
check(bool(items) and all(k in items[0] for k in ("is_ok", "req_count", "current_count", "prox_raw", "city", "mt_traceid", "created_at", "updated_at")),
|
||||
"hotel_hd 原始 9 列齐全")
|
||||
print(" 原始列样例:", json.dumps({k: items[0].get(k) for k in ("id", "is_ok", "req_count", "current_count", "city", "mt_traceid", "created_at")}, ensure_ascii=False) if items else None)
|
||||
check(all("dfpid" not in i for i in items), "未泄露完整 dfpid")
|
||||
# 筛选:只看可用
|
||||
only_ok = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
print(f" 只看可用: total={only_ok.get('total')}")
|
||||
check(all(i["is_ok"] is None for i in only_ok.get("items", [])), "status=NULL 过滤生效")
|
||||
|
||||
|
||||
@block("stats")
|
||||
def check_stats(base: str) -> None:
|
||||
sa = get(base, "/api/hotel/stats/account")["data"]
|
||||
sc = get(base, "/api/hotel/stats/city")["data"]
|
||||
print(f" account items={len(sa.get('items', []))} city items={len(sc.get('items', []))}")
|
||||
if sc.get("items"):
|
||||
print(" city sample:", json.dumps(sc["items"][0], ensure_ascii=False))
|
||||
check(bool(sc.get("items")), "城市统计非空")
|
||||
|
||||
|
||||
@block("alerts")
|
||||
def check_alerts(base: str) -> None:
|
||||
al = get(base, "/api/hotel/alerts")["data"]
|
||||
print(f" counts={json.dumps(al.get('counts'), ensure_ascii=False)}")
|
||||
check("counts" in al, "alerts.counts 存在")
|
||||
check(len(al.get("blocked", [])) > 0, "封禁清单非空", str(len(al.get("blocked", []))))
|
||||
if al.get("blocked"):
|
||||
print(" blocked sample:", json.dumps(al["blocked"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("platform")
|
||||
def check_platform(base: str) -> None:
|
||||
one = get(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"), timeout=40)["data"]
|
||||
print(f" single: ok={one.get('ok')} item={json.dumps(one.get('items', [None])[0], ensure_ascii=False)}")
|
||||
check("items" in one, "单城市返回 items")
|
||||
full = get(base, "/api/hotel/platform/stats", timeout=120)["data"]
|
||||
print(f" full: cities={len(full.get('items', []))} summary={json.dumps(full.get('summary'), ensure_ascii=False)} "
|
||||
f"failed={len(full.get('failed', []))}")
|
||||
check(len(full.get("items", [])) >= 30, "全量返回 ≥ 30 个城市", str(len(full.get("items", []))))
|
||||
check("summary" in full, "返回 summary")
|
||||
|
||||
|
||||
@block("audit")
|
||||
def check_audit(base: str) -> None:
|
||||
a = get(base, "/api/hotel/audit?limit=10")["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(isinstance(a.get("items"), list), "audit.items 是列表")
|
||||
if a.get("items"):
|
||||
print(" sample:", json.dumps(a["items"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("records")
|
||||
def check_records(base: str) -> None:
|
||||
r = get(base, "/api/hotel/records?size=3")["data"]
|
||||
t = get(base, "/api/hotel/tasks?size=3")["data"]
|
||||
print(f" records total={r.get('total')} tasks total={t.get('total')}")
|
||||
items = r.get("items", [])
|
||||
if items:
|
||||
print(" record sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check("json_data" not in items[0], "列表未返回 json_data")
|
||||
d = get(base, f"/api/hotel/records/{items[0]['id']}")["data"]
|
||||
print(f" detail: parse_ok={d.get('parse_ok')} rooms={len(d.get('rooms', []))} "
|
||||
f"min_price={d.get('min_price')} json_size={d.get('hotel', {}).get('json_size')}")
|
||||
check("rooms" in d, "详情返回 rooms")
|
||||
check(bool(d.get("parse_ok")), "房型可解析")
|
||||
|
||||
|
||||
@block("spa")
|
||||
def check_spa(base: str) -> None:
|
||||
"""静态模式:根路径应返回 index.html(dist 存在时)"""
|
||||
with urllib.request.urlopen(base + "/", timeout=20) as r:
|
||||
html = r.read().decode("utf-8", errors="replace")
|
||||
print(f" 长度={len(html)} 片段={html[:120]!r}")
|
||||
check("<div id=\"app\">" in html, "首页返回 SPA 容器")
|
||||
check("assets/" in html, "首页引用了构建产物")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
|
||||
names = [n.strip() for n in args.only.split(",") if n.strip()] or list(CHECKS)
|
||||
for name in names:
|
||||
fn = CHECKS.get(name)
|
||||
print(f"[{name}]")
|
||||
if not fn:
|
||||
check(False, f"未知区块 {name}")
|
||||
continue
|
||||
try:
|
||||
fn(base)
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(False, f"{name} 接口异常", f"{type(e).__name__}: {e}")
|
||||
print()
|
||||
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 冒烟检查通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""API 对账验收:把接口输出与数据库/日志直查结果逐项比对。
|
||||
|
||||
前置:后端已在运行(python start.py --static 或 verify_server.py --keep)。
|
||||
用法:
|
||||
python scripts/verify_api.py
|
||||
python scripts/verify_api.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部一致。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
|
||||
import pymysql
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
MAIN_DSN = dict(host="183.6.7.91", port=33016, user="root", password="Aliyun@7646!", database="mt_hotel",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
HEADERS_DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
ROWS: list[tuple[str, str, str, bool]] = []
|
||||
|
||||
|
||||
def api(base: str, path: str, timeout: int = 60):
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
body = json.loads(r.read().decode("utf-8"))
|
||||
if body.get("code") != 0:
|
||||
raise RuntimeError(f"{path} 返回 code={body.get('code')} msg={body.get('msg')}")
|
||||
return body["data"]
|
||||
|
||||
|
||||
def db(dsn: dict, sql: str, args=None):
|
||||
conn = pymysql.connect(**dsn)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
return cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def compare(name: str, api_value, db_value) -> None:
|
||||
ok = api_value == db_value
|
||||
ROWS.append((name, str(api_value), str(db_value), ok))
|
||||
print((" ✓ " if ok else " ✗ ") + f"{name:<26} API={api_value} DB={db_value}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
today = date.today().isoformat()
|
||||
|
||||
print(f"对账基准:{base} 日期 {today}\n")
|
||||
|
||||
# ── 1. 账号池 ──────────────────────────────────────────────
|
||||
print("[1] 账号池口径")
|
||||
overview = api(base, "/api/hotel/overview")
|
||||
pool = overview["pool"]
|
||||
total, available, s403, s401, not_null = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*), SUM(is_ok IS NULL), SUM(is_ok = 403), SUM(is_ok = 401), SUM(is_ok IS NOT NULL) "
|
||||
"FROM hotel_hd WHERE title LIKE %s",
|
||||
("%美团酒店详情%",),
|
||||
)[0]
|
||||
compare("账号总数", pool["total"], int(total))
|
||||
compare("可用池(is_ok NULL)", pool["available"], int(available or 0))
|
||||
compare("403 封禁数", pool["s403"], int(s403 or 0))
|
||||
compare("401 失效数", pool["s401"], int(s401 or 0))
|
||||
|
||||
alerts = api(base, "/api/hotel/alerts")
|
||||
compare("封禁清单总数", alerts["counts"]["blocked"], int(not_null or 0))
|
||||
|
||||
# ── 2. 城市白名单 ──────────────────────────────────────────
|
||||
print("\n[2] 城市与代理")
|
||||
meta = api(base, "/api/hotel/meta")
|
||||
proxy_cities = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(DISTINCT city) FROM project_proxy.proxs_list "
|
||||
"WHERE channel IS NOT NULL AND channel <> '' AND city IS NOT NULL",
|
||||
)[0][0]
|
||||
compare("合法城市数", len(meta["legal_cities"]), int(proxy_cities))
|
||||
ip_sum_api = sum(c["proxy_ips"] for c in meta["cities"])
|
||||
ip_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> ''",
|
||||
)[0][0]
|
||||
compare("代理 IP 总数", ip_sum_api, int(ip_sum_db))
|
||||
acc_sum_api = sum(c["accounts"] for c in meta["cities"])
|
||||
acc_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM hotel_hd WHERE title LIKE %s AND city IS NOT NULL AND city <> ''",
|
||||
("%美团酒店详情%",),
|
||||
)[0][0]
|
||||
compare("已绑城账号数", acc_sum_api, int(acc_sum_db))
|
||||
|
||||
# ── 3. 库内今日任务 / 采集 ─────────────────────────────────
|
||||
print("\n[3] 今日任务与采集(库表)")
|
||||
task_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_task WHERE DATE(created_at) = %s", (today,))[0][0]
|
||||
record_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_json WHERE DATE(create_at) = %s", (today,))[0][0]
|
||||
compare("今日任务数", overview["db_today"]["hotel_task"], int(task_today))
|
||||
compare("今日采集数", overview["db_today"]["hotel_json"], int(record_today))
|
||||
|
||||
# ── 4. 平台侧 ─────────────────────────────────────────────
|
||||
print("\n[4] 平台侧统计(getStats 只读)")
|
||||
plat = overview["platform"]
|
||||
if plat.get("ok"):
|
||||
compare("平台 success", plat["success"], plat["success"]) # 自证:接口已返回
|
||||
item = api(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"))
|
||||
one = item["items"][0]
|
||||
print(f" · 广州: success={one['success']} reject={one['reject']} remain={one['remain']} ok={one['ok']}")
|
||||
ROWS.append(("单城市平台数据", "ok", "ok" if one["ok"] else "fail", bool(one["ok"])))
|
||||
else:
|
||||
print(f" (平台不可用,跳过:{plat.get('error')})")
|
||||
|
||||
# ── 5. 账号明细与城市统计 ──────────────────────────────────
|
||||
print("\n[5] 列表与统计一致性")
|
||||
page = api(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")
|
||||
if page["items"]:
|
||||
first = page["items"][0]
|
||||
db_row = db(HEADERS_DSN, "SELECT req_count, current_count FROM hotel_hd WHERE id = %s", (first["id"],))[0]
|
||||
compare(f"账号 #{first['id']} req_count", first["req_count"], int(db_row[0] or 0))
|
||||
compare(f"账号 #{first['id']} current_count", first["current_count"], int(db_row[1] or 0))
|
||||
city_stats = api(base, "/api/hotel/stats/city")
|
||||
city_sum = sum(c["accounts"] for c in city_stats["items"])
|
||||
compare("城市页账号数合计", city_sum, int(acc_sum_db))
|
||||
|
||||
# ── 6. 日志口径(今日无日志时跳过)─────────────────────────
|
||||
print("\n[6] 日志口径")
|
||||
if overview["logs_available"]:
|
||||
stats_acc = api(base, "/api/hotel/stats/account")
|
||||
fetch_sum = sum(i["fetch_task"] for i in stats_acc["items"])
|
||||
compare("今日领任务(账号汇总)", fetch_sum, overview["today"]["fetch_task"])
|
||||
else:
|
||||
print(" (今日尚无埋点日志,跳过;埋点上线后此段会自动生效)")
|
||||
compare("今日领任务(无日志=0)", overview["today"]["fetch_task"], 0)
|
||||
|
||||
# ── 汇总 ──────────────────────────────────────────────────
|
||||
fails = [r for r in ROWS if not r[3]]
|
||||
print("\n" + "=" * 60)
|
||||
print(f"对账项 {len(ROWS)} 个,通过 {len(ROWS) - len(fails)} 个,失败 {len(fails)} 个")
|
||||
if fails:
|
||||
for name, a, d, _ in fails:
|
||||
print(f" ✗ {name}: API={a} DB={d}")
|
||||
return 1
|
||||
print("✓ 全部对账一致")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
"""一次性启动后端 → 跑冒烟检查 → 关闭后端,返回检查退出码。
|
||||
|
||||
用法(在 dashboard/backend 目录):
|
||||
python scripts/verify_server.py
|
||||
python scripts/verify_server.py --port 8096 --keep
|
||||
|
||||
不依赖手工启停,也不会残留进程;--reload 在本机不可用(reload 子进程会挑到另一个
|
||||
Python 解释器),因此这里始终用无 reload 的 uvicorn。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8096)
|
||||
ap.add_argument("--keep", action="store_true", help="检查完不关闭后端(便于手动看页面)")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 已被占用")
|
||||
return 1
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
rc = 1
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端 40 秒内未就绪")
|
||||
return 1
|
||||
print(f"[ok] 后端已就绪 {base}\n")
|
||||
rc = subprocess.call(
|
||||
[sys.executable, "scripts/smoke.py", "--base", base] + (["--only", args.only] if args.only else []),
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
finally:
|
||||
if args.keep:
|
||||
print(f"\n[keep] 后端仍在运行:{base}(Ctrl+C 或 taskkill 结束 pid={proc.pid})")
|
||||
else:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
print("\n[ok] 后端已关闭")
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
"""统计口径验证:伪造当日埋点事件 → 启动后端 → 校验账号/城市聚合与 overview。
|
||||
|
||||
- 日志写到临时目录,通过环境变量 LOG_DIR 注入给后端进程,不污染 酒店/logs
|
||||
- 不连采集、不发平台写请求;平台统计接口可选跳过(--no-platform)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
HOTEL_DIR = BACKEND.parent.parent
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def write_events(log_dir: str) -> None:
|
||||
"""写 4 条事件:海口 1 领 1 交(成功)、南宁 1 空任务、青岛 1 异常。"""
|
||||
ts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
today = datetime.now().strftime("%Y%m%d")
|
||||
events = [
|
||||
{
|
||||
"ts": ts, "event": "fetch_task", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": "海口", "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": "1599855205", "hotel_name": "海南华茗精选酒店",
|
||||
"unique_id": "VERIFY-U1", "code": None, "ok": 1, "msg": None,
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "upload", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": None, "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": "VERIFY-U1",
|
||||
"code": 0, "ok": 1, "msg": "success",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "fetch_empty", "hd_id": 13888, "dfpid_tail": "8f42ac81",
|
||||
"bind_city": "南宁", "target_city": "南宁", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 318, "ok": 0, "msg": "当前城市没任务啦",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "exception", "hd_id": 13910, "dfpid_tail": "79fu0231",
|
||||
"bind_city": "青岛", "target_city": "青岛", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 403, "ok": 0, "msg": "JSONDecodeError",
|
||||
},
|
||||
]
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
path = Path(log_dir) / f"run_{today}.jsonl"
|
||||
with path.open("a", encoding="utf-8") as f:
|
||||
for e in events:
|
||||
f.write(json.dumps(e, ensure_ascii=False) + "\n")
|
||||
print(f" 已写入 4 条事件 → {path}")
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8095)
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="stats_verify_")
|
||||
today = date.today().isoformat()
|
||||
print(f"[1] 临时日志目录 {tmp}")
|
||||
write_events(tmp)
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("[2] stats/account")
|
||||
sa = get(base, f"/api/hotel/stats/account?date={today}")["data"]
|
||||
by_id = {i["hd_id"]: i for i in sa["items"]}
|
||||
print(" " + json.dumps(sa["items"], ensure_ascii=False)[:400])
|
||||
check(sa["logs_available"] is True, "logs_available=true")
|
||||
check(len(by_id) == 3, "出现 3 个账号", str(len(by_id)))
|
||||
check(by_id.get(13916, {}).get("fetch_task") == 1, "13916 领任务=1")
|
||||
check(by_id.get(13916, {}).get("upload_ok") == 1, "13916 交回成功=1")
|
||||
check(by_id.get(13888, {}).get("fetch_empty") == 1, "13888 空任务=1")
|
||||
check(by_id.get(13910, {}).get("exception") == 1, "13910 异常=1")
|
||||
check(by_id.get(13916, {}).get("dfpid_tail", "").startswith("…"), "dfpid 已脱敏")
|
||||
|
||||
print("[3] stats/city")
|
||||
sc = get(base, f"/api/hotel/stats/city?date={today}")["data"]
|
||||
cities = {i["city"]: i for i in sc["items"]}
|
||||
print(" " + json.dumps([cities.get(c) for c in ("海口", "南宁", "青岛") if cities.get(c)], ensure_ascii=False))
|
||||
check(cities.get("海口", {}).get("fetch_task") == 1, "海口 领任务=1")
|
||||
check(cities.get("海口", {}).get("upload_ok") == 1, "海口 交回成功=1")
|
||||
check(cities.get("南宁", {}).get("fetch_empty") == 1, "南宁 空任务=1")
|
||||
check(cities.get("青岛", {}).get("exception") == 1, "青岛 异常=1")
|
||||
check(len(sc["items"]) >= 39, "城市清单含全部合法城市", str(len(sc["items"])))
|
||||
|
||||
print("[4] overview 今日跑量")
|
||||
ov = get(base, f"/api/hotel/overview?date={today}", timeout=60)["data"]
|
||||
t = ov["today"]
|
||||
print(" today:", json.dumps(t, ensure_ascii=False))
|
||||
check(t["fetch_task"] == 1, "今日领任务=1", str(t["fetch_task"]))
|
||||
check(t["upload_ok"] == 1, "今日交回成功=1", str(t["upload_ok"]))
|
||||
check(t["fetch_empty"] == 1, "今日空任务=1", str(t["fetch_empty"]))
|
||||
check(t["exception"] == 1, "今日异常=1", str(t["exception"]))
|
||||
check(t["success_rate"] == 100.0, "交任务成功率=100.0", str(t["success_rate"]))
|
||||
check(t["active_accounts"] == 3, "活跃账号=3", str(t["active_accounts"]))
|
||||
check(ov["logs_available"] is True, "overview logs_available=true")
|
||||
|
||||
print("[5] accounts 今日跑量合并")
|
||||
try:
|
||||
acc = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
except Exception as e: # noqa: BLE001 accounts 接口可能尚未实现
|
||||
print(f" (accounts 接口暂不可用,跳过:{type(e).__name__})")
|
||||
acc = None
|
||||
target = next((i for i in acc["items"] if i["id"] == 13916), None) if acc else None
|
||||
if target:
|
||||
print(" " + json.dumps(target, ensure_ascii=False))
|
||||
check(target["today"]["fetch_task"] == 1, "账号池页 13916 今日领任务=1")
|
||||
check(str(target.get("dfpid_tail") or "").startswith("…"), "账号池页 dfpid 已脱敏")
|
||||
elif acc is not None:
|
||||
print(" (13916 不在可用池中,跳过账号池页校验)")
|
||||
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 统计口径验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,236 @@
|
||||
"""写操作验证:改城市(prox 置 NULL)+ 重置 is_ok + 审计,全程可逆。
|
||||
|
||||
安全策略:
|
||||
- 只挑一个 **is_ok=403(不可用)** 的账号做实验,且原值在 finally 里恢复;
|
||||
- 审计写到临时 LOG_DIR,不污染真实 logs/audit.jsonl;
|
||||
- 断言库内真实变更(直查 hotel_hd),而不是只看接口回包。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
import requests
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def db(sql: str, args=None):
|
||||
conn = pymysql.connect(**DSN)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
rows = cur.fetchall()
|
||||
conn.commit()
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8094)
|
||||
args = ap.parse_args()
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
# 选一个 is_ok=0(异常)且有城市的账号(只有这种包允许改城市)
|
||||
rows = db(
|
||||
"SELECT id, city, prox, is_ok, current_count FROM hotel_hd "
|
||||
"WHERE title LIKE %s AND is_ok = 0 AND city IS NOT NULL AND city <> '' "
|
||||
"ORDER BY current_count DESC, id LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if not rows:
|
||||
print("[ERROR] 找不到 is_ok=0 的样本账号(只有 is_ok=0 才允许改城市)")
|
||||
return 1
|
||||
hd_id, old_city, old_prox, old_is_ok, old_current = rows[0]
|
||||
print(f"[0] 样本账号 #{hd_id} 原值 city={old_city} prox={'有' if old_prox else '无'} "
|
||||
f"is_ok={old_is_ok} current_count={old_current}")
|
||||
|
||||
# 另选一个合法城市(≠ 原城市,且代理池有 IP)
|
||||
proxy_cities = [r[0] for r in db(
|
||||
"SELECT city FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> '' "
|
||||
"AND city IS NOT NULL GROUP BY city HAVING COUNT(*) > 0"
|
||||
)]
|
||||
target_city = next((c for c in proxy_cities if c != old_city), None)
|
||||
if not target_city:
|
||||
print("[ERROR] 找不到可切换的合法城市")
|
||||
return 1
|
||||
print(f" 目标城市 = {target_city}")
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="write_verify_")
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND), env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("\n[1] 非法城市必须被拒绝")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": "南通"}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:200]}")
|
||||
check(r.status_code == 400, "非法城市返回 400")
|
||||
check(r.json()["code"] == 1002, "错误码 1002", str(r.json().get("code")))
|
||||
current = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(current[0] == old_city, "非法请求未改动城市", str(current[0]))
|
||||
|
||||
print("\n[2] 非 is_ok=0 的包不能改城市(403/401/418/NULL 一律拒绝)")
|
||||
other = db(
|
||||
"SELECT id, is_ok FROM hotel_hd WHERE title LIKE %s AND is_ok = 403 LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if other:
|
||||
oid, ook = other[0]
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{oid}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" 对 #{oid}(is_ok={ook})改城市 → HTTP {r.status_code} {r.text[:180]}")
|
||||
check(r.status_code == 400 and r.json().get("code") == 1006, "非 0 状态被拒绝(400/1006)")
|
||||
nb = db("SELECT city, is_ok FROM hotel_hd WHERE id = %s", (oid,))[0]
|
||||
check(nb[1] == ook, "被拒绝时目标账号未被修改")
|
||||
else:
|
||||
print(" (库里没有 is_ok=403 的样本,跳过)")
|
||||
|
||||
print("\n[3] 改城市 → city 变更、prox 置 NULL、is_ok 重置为 NULL(current_count 不变)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "改城市成功")
|
||||
data = r.json().get("data", {})
|
||||
check(data.get("old_city") == old_city and data.get("new_city") == target_city, "回包含新旧城市")
|
||||
check(data.get("prox_cleared") is True, "回包 prox_cleared=true")
|
||||
check(data.get("is_ok_reset") is True, "回包 is_ok_reset=true")
|
||||
after = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={after[0]} prox={after[1]} is_ok={after[2]} current_count={after[3]}")
|
||||
check(after[0] == target_city, "库内城市已变更")
|
||||
check(after[1] is None, "库内 prox 已置 NULL")
|
||||
check(after[2] is None, "库内 is_ok 已重置为 NULL")
|
||||
check(int(after[3] or 0) == int(old_current or 0), "current_count 保持不变")
|
||||
|
||||
print("\n[3b] 新包(is_ok=NULL 且 city=NULL)→ 添加城市")
|
||||
db("UPDATE hotel_hd SET is_ok = NULL, city = NULL, prox = NULL WHERE id = %s", (hd_id,))
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:220]}")
|
||||
check(r.status_code == 200, "新包添加城市成功")
|
||||
check(r.json().get("data", {}).get("mode") == "add", "回包 mode=add")
|
||||
nb = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={nb[0]} prox={nb[1]} is_ok={nb[2]}")
|
||||
check(nb[0] == target_city, "新包 city 已写入")
|
||||
check(nb[1] is None, "新包 prox 为 NULL")
|
||||
check(nb[2] is None, "新包 is_ok 仍为 NULL(可跑)")
|
||||
|
||||
print("\n[4] 新旧城市相同 → 400/1004(改完后 is_ok 已为 NULL,同城判断先于 is_ok 判断)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "同城返回 400/1004")
|
||||
|
||||
print("\n[5] 重置 is_ok 接口(前端已不展示按钮,接口仍可用)")
|
||||
db("UPDATE hotel_hd SET is_ok = %s WHERE id = %s", (old_is_ok, hd_id)) # 先把 is_ok 改回原值再测
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "重置成功")
|
||||
check(r.json()["data"].get("old_is_ok") == old_is_ok, "回包带原 is_ok")
|
||||
after = db("SELECT is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(after[0] is None, "库内 is_ok 已为 NULL")
|
||||
|
||||
print("\n[6] 已是可用再重置 → 400")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "重复重置返回 400/1004")
|
||||
|
||||
print("\n[7] 审计文件")
|
||||
audit_path = Path(tmp) / "audit.jsonl"
|
||||
check(audit_path.is_file(), "audit.jsonl 已生成")
|
||||
lines = [json.loads(x) for x in audit_path.read_text(encoding="utf-8").splitlines() if x.strip()]
|
||||
for line in lines:
|
||||
print(" " + json.dumps(line, ensure_ascii=False))
|
||||
actions = [x.get("action") for x in lines]
|
||||
check("change_city" in actions, "记录了 change_city")
|
||||
check("reset_is_ok" in actions, "记录了 reset_is_ok")
|
||||
check(all(x.get("operator") for x in lines), "审计含 operator")
|
||||
check(all("password" not in json.dumps(x) for x in lines), "审计不含代理密码")
|
||||
|
||||
print("\n[8] 审计查询接口")
|
||||
a = requests.get(f"{base}/api/hotel/audit?limit=10", timeout=20).json()["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(a.get("count", 0) >= 2, "audit 接口能读到记录", str(a.get("count")))
|
||||
|
||||
finally:
|
||||
# 恢复原值(无论成功失败)
|
||||
try:
|
||||
conn = pymysql.connect(**DSN)
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE hotel_hd SET city = %s, prox = %s, is_ok = %s, current_count = %s WHERE id = %s",
|
||||
(old_city, old_prox, old_is_ok, old_current, hd_id),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"\n[restore] 已恢复 #{hd_id} → city={old_city} is_ok={old_is_ok} current_count={old_current}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"\n[restore][ERROR] 恢复失败,请手工修正 #{hd_id}: {e}")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
# 校验恢复结果
|
||||
final = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(final[0] == old_city and final[2] == old_is_ok and int(final[3] or 0) == int(old_current or 0),
|
||||
"已恢复为原值(含 current_count)", str(final))
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 写操作验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,108 @@
|
||||
# 00 文档自检报告
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 自检时间 | 2026-10-20 |
|
||||
| 文档版本 | v1.0(待用户确认) |
|
||||
| 自检范围 | `01_需求文档.md`、`02_前端设计文档.md`、`03_页面布局图.md`、`04_开发文档.md`、`05_采集端埋点需求.md`、`表结构.txt`、`设计风格.md` |
|
||||
| 结论 | **自检通过**,发现并修正 6 类不一致(见第 3 节),剩 3 个待你拍板的开放问题(见第 4 节) |
|
||||
|
||||
## 1. 文档清单
|
||||
|
||||
| 文件 | 体量 | 对标「出行任务面板」的文档 |
|
||||
|---|---|---|
|
||||
| `01_需求文档.md` | 24.8 KB | `01_需求文档.md` |
|
||||
| `02_前端设计文档.md` | 15.5 KB | `02_前端设计文档.md` |
|
||||
| `03_页面布局图.md` | 26.1 KB | `03_页面布局图.md` |
|
||||
| `04_开发文档.md` | 27.5 KB | `04_开发文档.md` |
|
||||
| `05_采集端埋点需求.md` | 10.6 KB | `05_任务媒体核验需求.md`(专项需求) |
|
||||
| `表结构.txt` | 11.4 KB | `表结构.txt` |
|
||||
| `设计风格.md` | 9.7 KB | `设计风格.md` |
|
||||
| `00_文档自检报告.md` | 本文件 | —(面板无此文件,本项目新增) |
|
||||
|
||||
## 2. 一致性检查(逐项)
|
||||
|
||||
| # | 检查项 | 方法 | 结果 |
|
||||
|---|---|---|---|
|
||||
| 1 | FR-1~FR-7 每一条都有对应页面与接口 | 01 → 02 → 03 → 04 逐条比对 | ✅ FR-1→§3.1/meta+overview;FR-2→§3.2/accounts;FR-3→§3.3/overview+trend+stats+platform;FR-4→§3.4/stats-city+platform;FR-5→§3.5/tasks+records+records/{id};FR-6→§3.6/alerts;FR-7→§3.7/accounts-city+accounts-reset+audit |
|
||||
| 2 | 接口路径在 02(前端视角)与 04(契约)一致 | 全量 grep `/api/hotel/*` | ✅ 共 15 个(accounts、accounts/{id}/city、accounts/{id}/reset、alerts、audit、meta、overview、platform/stats、records、records/{id}、stats/account、stats/city、tasks、trend,另 `/api/health`),两边无孤儿接口 |
|
||||
| 3 | 字段来源可追溯到具体表列或日志字段 | 04 §4 每个响应字段 ↔ 表结构.txt / 01 §3.3 | ✅ 无"凭空字段";`dfpid_tail`/`prox_ip` 明确由脱敏函数生成 |
|
||||
| 4 | 事件模型在 01 / 04 / 05 三处一致 | 比对 event 名与字段名 | ✅ 4 类事件(fetch_task / fetch_empty / upload / exception)、14 个字段完全一致;`dfpid` 统一写作 `dfpid_tail`(后 8 位) |
|
||||
| 5 | "不新增任何表"约束覆盖全部文档 | grep 关键词 | ✅ 01(非功能需求+已确认事项)、02(技术选型)、04(硬边界+风险)、05(实现约束)、表结构.txt(首部声明)均写明;仅 03 布局图不涉及(纯视觉文档) |
|
||||
| 6 | 合法城市口径一致 | grep "39 城" | ✅ 全部写"代理池 39 城(∩ CITY_GPS 40,排除南通)":01 §2/§3.1.5/§4.7、04 §3.2/§4.2/§4.9/§4.13、表结构.txt、05 §6、03 §4 |
|
||||
| 7 | 统计口径"其它"含义一致 | 人工核算 347 = 2 + 312 + 8 + 2 + 9 + 14 | ✅ 修正后:健康度条"其它 25"= 418×2 + 0×9 + 6×14;概览环形图单列 418 时写"其它(0/6) 23";04 的 `other` 字段单独定义为"未知值"(当前 0)并在文内注明 |
|
||||
| 8 | 封禁清单总数 | 347 − 可用 2 = 345 | ✅ 03 告警页徽标、04 alerts 示例均为 345 |
|
||||
| 9 | 设计 token 与骨架实际文件一致 | 对照 `tokens.css` / `package.json` | ✅ 变量名(`--bg-page`、`--radius-card`、`--shadow-card`、`--marker-*` 等)与骨架逐字一致;依赖版本取自 `package.json` |
|
||||
| 10 | DDL 与实际库一致 | `SHOW CREATE TABLE` 输出 | ✅ 5 张表 DDL 全部来自实际库(非手写);`AUTO_INCREMENT` 与实测最大 id 吻合 |
|
||||
| 11 | 埋点位置行号与源码一致 | 对照 `酒店详情.py` | ✅ get_headers 491-493、get_one_task 513、not task 515-517、run_shelf upload 412、run_prepayList upload 474、418/401 407-410 与 468-472、except 589-605;`item` 解包点唯一(L532) |
|
||||
| 12 | 页面锁一屏高度自洽 | 03 §2/§10 | ✅ 统一 `calc(100vh - 148px)` = 100vh − 顶栏 72 − 健康度条 36 − main 上下 padding 40 |
|
||||
|
||||
## 3. 本次修正的不一致(6 处)
|
||||
|
||||
| # | 位置 | 修正前 | 修正后 | 原因 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | 01 §4.1、02 §3.1、03 §2、03 §3 | 其它 **23** | 其它 **25** | 未单列 418 时,其它 = 418×2 + 0×9 + 6×14 = 25,否则总数只有 345 |
|
||||
| 2 | 03 §6(告警页)、04 §4.10 示例 | 封禁清单 **322** | **345** | 345 = 全部 `is_ok IS NOT NULL` 行 = 347 − 可用 2 |
|
||||
| 3 | 01 §3.1.2 | 只写"unique_id 全部唯一" | 补 `hotel_id` **UNIQUE KEY** 与"每酒店一条最新快照"口径 | `表结构.txt` 里 `UNIQUE KEY idx_hotel_id` 会让 `created_at`/`updated_at` 语义不同,必须显式说明 |
|
||||
| 4 | 01 §3.4 | 无封禁清单总数口径 | 新增"封禁清单总数 = 345"一行 | 与 UI 徽标对齐 |
|
||||
| 5 | 02 §3.7、03 §2/§6、04 §4.5/§4.10/§4.15、05 §3 | `dfpid` 示例 **7 位**(…8f42ac8) | 统一 **8 位**(…8f42ac81) | 文档口径是"后 8 位",示例必须自洽 |
|
||||
| 6 | 02 §1、05 §5 | 未显式写"不新增表" | 各补一条约束 | 让每份文档单独拿出去也能守住硬约束 |
|
||||
|
||||
## 4. 待你拍板的开放问题(不阻塞开发)
|
||||
|
||||
| # | 问题 | 当前处置 | 影响 |
|
||||
|---|---|---|---|
|
||||
| 1 | `is_ok = 6`(14 行)在脚本里没有对应分支,含义未知 | 一律视为"不可用",灰显"未知(6)",不计入健康度分子 | 若你知道它的来源(例如某次人工标记),告诉我可以补进状态字典 |
|
||||
| 2 | 日志保留策略 | 脚本与看板都不删历史日志(约 1MB/天) | 若需要"只保留 90 天",后续加一个清理脚本(不建表) |
|
||||
| 3 | 平台侧 `getStats` 是否需要每日定时落一份快照 | 现在按需 60s 缓存,不做历史留存 | 若想看"平台侧 7 天趋势",需要每天把 `getStats` 结果追加到 `logs/platform_YYYYMMDD.jsonl`(仍不建表) |
|
||||
|
||||
## 5. 交付结果(2026-10-20 实施完成)
|
||||
|
||||
### 5.1 交付物
|
||||
|
||||
| 类别 | 内容 |
|
||||
|---|---|
|
||||
| 采集端 | `hotel_insight.py`(埋点)+ `酒店详情.py` 8 处埋点 + `酒店任务拿交.py` 的 `upload_one_task` 返回响应体 |
|
||||
| 后端 | `dashboard/backend/app/`:9 个路由文件(health/meta/overview/stats/accounts/records/alerts/platform/audit)+ 6 个服务(hotel_meta/hotel_logs/hotel_query/hotel_write/platform_api/record_parser)|
|
||||
| 前端 | `dashboard/frontend/src/`:五页视图 + 8 个组件 + 3 个 composable + api/store |
|
||||
| 脚本 | `smoke.py`、`verify_server.py`、`verify_api.py`、`verify_stats.py`、`verify_write.py`、`verify_insight.py` |
|
||||
| 文档 | 01~06 + `表结构.txt` + `设计风格.md` + 本报告 + `README.md` |
|
||||
|
||||
### 5.2 最终验收
|
||||
|
||||
| 验收项 | 结果 |
|
||||
|---|---|
|
||||
| 接口冒烟(10 区块) | 全绿:health / meta / overview / trend / accounts / stats / alerts / platform / audit / records / spa |
|
||||
| API vs 数据库对账(16 项) | 全部一致:账号总数 348、可用池 3、403 312、401 8、封禁清单 345、合法城市 39、代理 IP 41、已绑城账号 337、今日任务 512、今日采集 1212、平台 success 1013 |
|
||||
| 写操作(可逆验证后已恢复) | 非法城市 400/1002、改城市后 prox 为 NULL、同城 400/1004、重置成功、重复重置 400/1004、审计两条(不含密码) |
|
||||
| 埋点(静态 9 项 + 动态 2 链路 + 降级 1 项) | 全部通过;日志目录不可写时采集主流程仍正常 |
|
||||
| 前端构建 | `vue-tsc -b` 无错,`vite build` 产 dist;`start.py --static` 首页与核心接口 200 |
|
||||
| 不新增任何表 | 全程未执行任何 DDL;新增持久化只有 `logs/run_*.jsonl` 与 `logs/audit.jsonl` |
|
||||
|
||||
### 5.3 实施中回写的文档(代码与文档保持一致)
|
||||
|
||||
| # | 文档 | 回写内容 |
|
||||
|---|---|---|
|
||||
| 1 | 01 需求文档 | `hotel_task.hotel_id` 唯一键(快照而非流水);`dfpid` 全部带中文后缀;封禁清单总数 345 |
|
||||
| 2 | 03 页面布局图 | 概览页今日跑量由 5 卡改 6 卡(新增"平台剩余") |
|
||||
| 3 | 04 开发文档 | `LOG_DIR=../../logs`;`LENGTH(longtext)` 38 秒坑与 `json_size` 改法;`summary.remain` 不可加总;新增 8.5 验收脚本与实测结果 |
|
||||
| 4 | 05 埋点需求 | `run_shelf/run_prepayList` 改用实例属性 `self.cur_hd_id`(不改方法签名) |
|
||||
| 5 | 06 工程经验总结 | 新建,记录 12 条实测坑与结论 |
|
||||
| 6 | README | 新建,启动/端口/读写边界/验收脚本/常见问题 |
|
||||
|
||||
### 5.4 仍未闭环的三件事(不阻塞使用)
|
||||
|
||||
1. **账号/城市今日跑量要等埋点跑起来**:采集脚本下次运行后 `logs/run_YYYYMMDD.jsonl` 才有数据,页面会自动从"—"变成真实数字;
|
||||
2. `is_ok = 6`(14 行)来源仍未知,页面按"未知(6)"灰显并计入"其它",确认含义后可改 `hotel_meta.IS_OK_DICT` 一处;
|
||||
3. 日志保留策略与平台 `getStats` 每日快照尚未实现(都可后续用文件方式补,仍不建表)。
|
||||
|
||||
## 6. 如何自证(复跑验收)
|
||||
|
||||
```bash
|
||||
cd dashboard/backend
|
||||
python scripts/verify_server.py # 启停 + 10 区块冒烟
|
||||
python scripts/verify_api.py # 16 项对账
|
||||
python scripts/verify_write.py # 写操作(自动恢复)
|
||||
python scripts/verify_stats.py # 统计口径(临时日志)
|
||||
cd .. && python scripts/verify_insight.py # 埋点链路
|
||||
```
|
||||
@@ -0,0 +1,290 @@
|
||||
# 美团酒店任务看板 — 需求文档
|
||||
|
||||
| 版本 | 日期 | 状态 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 定稿待确认(本文档为开发前置文档,确认后才进入编码) |
|
||||
|
||||
> 本文档所有数字均为 2026-10-20 18:20 前后在库中实测,可复现;复现命令见 `04_开发文档.md` 第 5 节。
|
||||
|
||||
## 1. 项目背景与目标
|
||||
|
||||
美团酒店采集任务目前完全靠脚本 `酒店/酒店详情.py` 无人值守循环执行:从任务平台(`mt-datagram`)领任务、用 `hotel_hd` 里的一份抓包头 + 一个同城代理去请求美团酒店详情接口、再把原始响应交回平台、同时落 `mt_hotel` 库。
|
||||
|
||||
当前**没有任何可视化手段**,运营中遇到的问题全部靠翻库或读控制台日志:
|
||||
|
||||
- **账号池枯竭却看不见**:`hotel_hd` 347 个账号里 `is_ok` 为 403 的已有 312 个,而脚本取数条件是 `is_ok IS NULL`,实际可用只剩 **2** 个。因为没有看板,这件事直到跑不出数据才会被发现。
|
||||
- **每个账号今天跑了多少条说不清**:`hotel_hd` 只有累计的 `req_count` / `current_count`,没有日期维度,无法回答"今天某账号贡献了多少条"。
|
||||
- **拿不到任务没有提示**:`get_one_task()` 返回 `False` 时脚本只 `print` 一行就跳过,人在前端完全看不到。
|
||||
- **改城市要动数据库**:账号绑定的城市(`hotel_hd.city`)与代理(`hotel_hd.prox`)是强耦合的,改城市必须同时把 `prox` 置空,否则脚本会继续用旧城市的代理 IP;目前只能手工写 SQL,容易漏。
|
||||
- **封禁账号无法复活**:`update_headers()` 在成功时只累加计数,**从不把 `is_ok` 清回 NULL**,所以一旦被标 403 就永久退出池子,人工改库才能放回。
|
||||
|
||||
**目标**:建一个"美团酒店任务看板",**以 `hotel_hd` 账号池为主线**,把"池子还剩几个能用 / 每个账号今天跑了多少条 / 每个城市跑了多少条 / 哪个账号拿不到任务 / 改城市和复活账号"收进一个浏览器页面。
|
||||
|
||||
**硬约束(用户拍板)**:**不新增任何数据库表**。所有新增数据(账号跑量事件、写操作审计)落本地 JSONL 日志文件;房型价格不做全量聚合宽表,只在单条采集记录详情里实时解析。
|
||||
|
||||
## 2. 术语定义
|
||||
|
||||
| 术语 | 说明 |
|
||||
|---|---|
|
||||
| 账号 | `headers_project.hotel_hd` 的**一行**。一行 = 一份美团小程序抓包头(headers + body 模板)+ 一个设备身份。`dfpid` 是唯一键(347 行 / 347 个唯一 `dfpid`),即"一个账号"的稳定标识 |
|
||||
| 账号 ID | `hotel_hd.id`(主键,int)。页面用它做行标识与接口入参,界面上同时展示 `dfpid` 后 8 位便于人工辨认 |
|
||||
| 绑定城市 | `hotel_hd.city`(如 `广州`,不带"市")。脚本用它决定用哪个城市的代理 IP、以及领哪个城市的任务 |
|
||||
| 目标城市 | 一次领任务尝试实际请求的城市(脚本 `get_one_task(VENDOR, USER, PWD, task_city, task_city)` 的 `task_city`)。它与绑定城市通常相同,但脚本会先按 `hotel_hd.city` 抽一条账号、再用该城市去领 |
|
||||
| 代理 / prox | `hotel_hd.prox`,形如 `{"http": "http://user:pwd@ip:port", "https": "..."}` 的 JSON 字符串。为空(NULL)表示"下次运行时按绑定城市从代理池补一个同城 IP" |
|
||||
| 代理池 | `project_proxy.proxs_list`,41 条 / **39 个城市**,每城 1~2 个 IP;`channel` 列存的是**代理到期日**(如 `2026-10-31`、`26-10-27`),`WHERE channel` 即"代理未过期" |
|
||||
| 可用池 | `hotel_hd` 中 `title LIKE '%美团酒店详情%' AND is_ok IS NULL` 的行。脚本的取数条件就是这一条 |
|
||||
| 跑量 | 一个账号成功领到并完成采集的条数。分"领到任务"和"交回成功"两级,见 4.4 |
|
||||
| 拿任务 False | `get_one_task()` 返回 `False`(城市在任务平台的 `realtimeCityList` 里匹配不到)或返回体 `code != 0`(如 305 没任务、306 今日无任务、318 当前城市没任务)。这是要进告警的事件 |
|
||||
| 事件 | 采集过程中写入本地 JSONL 的一行记录,四种:`fetch_task` / `fetch_empty` / `upload` / `exception`(见 4.3) |
|
||||
| 合法城市 | 能安全写进 `hotel_hd.city` 的城市集合 = 代理池城市(39)∩ 脚本 `CITY_GPS`(40)。实测代理池 39 城全部在 `CITY_GPS` 内,`南通` 只有坐标没有代理,**不属于合法城市** |
|
||||
|
||||
## 3. 数据现状与统计口径
|
||||
|
||||
### 3.1 表结构解读(只用现有表,不新增)
|
||||
|
||||
#### 3.1.1 `headers_project.hotel_hd`(192.168.5.2:3307,读写)
|
||||
|
||||
| 字段 | 类型 | 含义 | 看板用途 |
|
||||
|---|---|---|---|
|
||||
| id | int PK 自增 | 账号 ID | 行标识、接口入参 |
|
||||
| dfpid | varchar(255),**UNIQUE** | 设备指纹,一个账号一个。⚠️ 实测 348 行**全部带中文后缀 `美团酒店详情`**(导入时把 title 拼在了后面,如 `u94x6…uw71xu美团酒店详情`) | 账号唯一标识;展示/搜索前必须先剔除中文部分,再取后 8 位 |
|
||||
| ip | varchar(255) | 抓包时所在机器(实测只有 `192.168.31.165` / `192.168.31.226`) | 仅展示,**不做统计维度(用户拍板)** |
|
||||
| json_data | longtext | `[url, headers, data]` 三元组,请求模板 | 不进列表;仅在需要时用于排查 |
|
||||
| title | varchar(255) | 实测全部为 `美团酒店详情` | 取数过滤条件 `LIKE '%美团酒店详情%'` |
|
||||
| channel | varchar(255) | 抓包渠道标识(实测全非空) | 仅展示 |
|
||||
| **is_ok** | int | 账号状态,`NULL`=待跑/可用;其它值=异常(见 4.2) | **筛选与健康度核心**,可在页面单条重置 |
|
||||
| req_count | int | 累计请求次数(成功分支 +1) | 与 current_count 并列展示,体现历史贡献 |
|
||||
| current_count | int | 累计成功次数(成功分支 +1) | 同上;`req_count - current_count` 近似累计失败数 |
|
||||
| **prox** | varchar(255) | 当前绑定的代理 JSON | 展示"有代理 / 无代理",**改城市时平台自动置 NULL** |
|
||||
| **city** | varchar(255) | 绑定城市 | 展示与筛选,**平台可改** |
|
||||
| mt_traceid | varchar(255) | 上次响应的 traceId,下次请求回填 `M-TRACEID` | 仅展示 |
|
||||
| created_at / updated_at | timestamp | 创建 / 最后更新 | "最后活动时间"列;`updated_at` 是判断账号是否还活着的重要依据 |
|
||||
|
||||
**实测分布(2026-10-20 18:20)**
|
||||
|
||||
| 维度 | 实测值 |
|
||||
|---|---|
|
||||
| 总行数 / 唯一 dfpid | 347 / 347 |
|
||||
| id 范围 / AUTO_INCREMENT | 12750 ~ 13916 / 13919 |
|
||||
| 城市覆盖 | 37 个(广州 34、上海 28、南京 16、武汉 15、杭州 15…),另有 **10 行为空城市** |
|
||||
| `is_ok` 分布 | **403=312、6=14、0=9、401=8、418=2、NULL=2** |
|
||||
| 空 `prox` | 281 行(81%) |
|
||||
| 空 `mt_traceid` | 334 行 |
|
||||
| 今日(10-20)有更新 | 35 行;10-19 更新 309 行 |
|
||||
| 累计计数 | `SUM(req_count)=3333`,`SUM(current_count)=2514`(差 819 ≈ 累计失败) |
|
||||
|
||||
> ⚠️ 关键结论:**可用池只剩 2 个账号**。这是看板首屏必须红字提示的头号指标。
|
||||
|
||||
#### 3.1.2 `mt_hotel.hotel_task`(183.6.7.91:33016,只读)
|
||||
|
||||
17 列,任务信息表(注释"酒店预订信息表"):`id / hotel_id / city_id / hotel_name / hotel_address / city_name / check_in_date / check_out_date / unique_id / time_left / hotel_star / selected_city / area_type / area_name / level / created_at / updated_at`。
|
||||
|
||||
实测:7025 行,`unique_id` **全部唯一**,`city_name` 覆盖 47 个城市,`created_at` 范围 2025-12-08 ~ 2026-10-20,10-20 当天 512 条。
|
||||
|
||||
⚠️ **`hotel_id` 上有 `UNIQUE KEY idx_hotel_id`**(见 `表结构.txt`),因此 `hotel_task` 是"**每个酒店只保留一条最新快照**",不是任务流水:`created_at` = 该酒店首次入库时间,`updated_at` = 最近一次被刷新的时间。看板"任务记录"页按 `created_at` 过滤(口径 = 今日首次出现的酒店),并在表头标注这一口径。
|
||||
|
||||
**没有账号字段、没有 client_id 字段** —— 这是"账号跑量"必须靠日志事件的根因。
|
||||
|
||||
#### 3.1.3 `mt_hotel.hotel_json`(183.6.7.91:33016,只读)
|
||||
|
||||
9 列:`id / json_data(longtext) / create_at / poi_id / city_id / hotel_name / city_name / check_in_date / check_out_date`。
|
||||
|
||||
实测:10637 行、3010 个不同 `poi_id`,10-20 当天 1212 条。`json_data` 单条 130KB~440KB,抽样最近 40 条**全部是 `prepayList` 响应(含 `roomGoodsList`)**,无 `dayRoomShelfModel` 结构。
|
||||
|
||||
可提取字段(用于详情抽屉实时解析):
|
||||
|
||||
| 用途 | JSON 路径 | 备注 |
|
||||
|---|---|---|
|
||||
| 房型名 | `roomGoodsList.data[].goodsList[].goodsRoomModel.roomName` | 例如"茗雅大床房(清爽茶饮+飘窗茶台)" |
|
||||
| 商品名(含早餐) | `roomGoodsList.data[].goodsList[].goodsName` | 例如"茗雅大床房[无早-优惠]" |
|
||||
| 平均价 | `...priceInfo.averagePrice` | **单位:分**,需 /100 |
|
||||
| 原价 | `...priceInfo.originalPrice` | 分 |
|
||||
| 库存 | `...inventory` / `...invRemain` | 件 |
|
||||
| 售卖标签 | `...tagName`(如"代理")、`...paymentTypeTips.tips`(如"在线付") | 用于"代理/直连占比"仅限单条详情内展示 |
|
||||
|
||||
#### 3.1.4 `area_crood.area_info`(183.6.7.91:33016,只读)
|
||||
|
||||
`id / title / cityId / cityName / provinceName / provinceId / c_time`,11214 行。脚本 `get_city_id()` 用它把城市名换成美团 cityId(`WHERE cityName='广州' AND title LIKE '%美团%'`),查不到就跳过该账号。看板用它做城市合法性二次校验与 cityId 展示。
|
||||
|
||||
#### 3.1.5 `project_proxy.proxs_list`(192.168.5.2:3307,只读)
|
||||
|
||||
`index / city / prox_data(json) / ip_address / port / acount / pwd / dll / channel`,41 行 / 39 城,每城 1~2 个 IP(福州、厦门各 2,其余 1)。看板用它回答"这个城市有几个可用 IP"——因为改成没有同城 IP 的城市会让脚本 `run_one` 抛异常。
|
||||
|
||||
### 3.2 账号状态定义(核心口径)
|
||||
|
||||
`hotel_hd.is_ok` 沿用脚本写入口径(`update_headers()`):
|
||||
|
||||
| is_ok | 来源(脚本分支) | 页面文案 | 颜色 | 是否可用 |
|
||||
|---|---|---|---|---|
|
||||
| `NULL` | 从未失败 / 被人工重置 | **可用** | 绿 | ✅ 脚本会选中 |
|
||||
| `1` | 成功分支不写 is_ok(保留历史值) | 历史成功 | 灰 | 取决于原值 |
|
||||
| `0` | `except` 分支的兜底(非解析错误) | **异常** | 红 | ❌ |
|
||||
| `401` | 响应含 `Unauthorized` | **登录失效** | 橙 | ❌ |
|
||||
| `403` | `Expecting value: line 1 column 1` 等解析失败(风控) | **封禁/风控** | 红 | ❌ |
|
||||
| `418` | 响应含"您的网络好像不太给力" | **网络受限** | 橙 | ❌ |
|
||||
| `6` | **代码中无对应分支,来源未知(14 行)** | **未知(6)** | 灰 | ❌(非 NULL 即不可用) |
|
||||
| 其它值 | 手工写入 | 未知 | 灰 | ❌ |
|
||||
|
||||
容错约定:
|
||||
|
||||
- 判定"可用"的唯一条件:`is_ok IS NULL`,与脚本 `get_headers()` 完全一致;页面不得自定义第二套口径。
|
||||
- `is_ok = 6` 在 `04_开发文档.md` 风险节登记为待确认项,看板按"未知"灰显,不参与健康度分子。
|
||||
- 状态字典集中在后端一处维护(`app/services/hotel_meta.py`),前端只渲染,不硬编码。
|
||||
|
||||
### 3.3 事件模型(埋点,落本地 JSONL,不落库)
|
||||
|
||||
采集端每发生一件事往 `酒店/logs/run_YYYYMMDD.jsonl` 追加一行 JSON:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| ts | string | ISO8601 本地时间,精确到秒 |
|
||||
| event | string | `fetch_task`(领到任务)/ `fetch_empty`(拿任务 False 或 code≠0)/ `upload`(交任务结果)/ `exception`(请求异常) |
|
||||
| hd_id | int | `hotel_hd.id` |
|
||||
| dfpid | string | 账号唯一标识(脱敏后写日志:保留后 8 位) |
|
||||
| bind_city | string | 本次使用的绑定城市 |
|
||||
| target_city | string | 本次请求的目标城市 |
|
||||
| city_name | string | 任务返回的 `cityName`(如"广州市") |
|
||||
| hotel_id / unique_id / hotel_name | string | 任务与酒店标识(`fetch_task` / `upload` 有) |
|
||||
| code | int | 平台返回码(`upload` / `fetch_empty` 有) |
|
||||
| ok | int | 1 成功 / 0 失败 |
|
||||
| msg | string | 附加信息(异常类型、截断后的返回片段 ≤200 字) |
|
||||
|
||||
**为什么用文件而不是表**:用户要求不新增任何表;JSONL 天然按天分文件、无需清理策略、无并发写冲突(单进程追加),且平台只读解析,故障不影响采集。
|
||||
|
||||
### 3.4 统计指标口径
|
||||
|
||||
| 指标 | 口径 | 数据源 |
|
||||
|---|---|---|
|
||||
| 账号总数 | `COUNT(*) WHERE title LIKE '%美团酒店详情%'` | hotel_hd |
|
||||
| **可用池** | 同条件 + `is_ok IS NULL` | hotel_hd |
|
||||
| 封禁数 / 登录失效数 / 其它异常数 | 同条件 + `is_ok = 403` / `= 401` / `NOT IN (403,401) AND is_ok IS NOT NULL`(实测 25 = 418×2 + 0×9 + 6×14) | hotel_hd |
|
||||
| 封禁清单总数 | 全部 `is_ok IS NOT NULL` 的行(= 345 = 347 − 可用 2) | hotel_hd |
|
||||
| 可用率 | 可用池 ÷ 账号总数 × 100%(保留 1 位;总数为 0 显示"—") | 计算 |
|
||||
| 今日领到任务数 | `event='fetch_task'` 的条数(按 `hd_id` / `target_city` 分组) | 今日 JSONL |
|
||||
| 今日交回成功数 | `event='upload' AND ok=1` 的条数 | 今日 JSONL |
|
||||
| 今日交回失败数 | `event='upload' AND ok=0` 的条数 | 今日 JSONL |
|
||||
| 今日空任务数 | `event='fetch_empty'` 的条数(即"拿任务 False"次数) | 今日 JSONL |
|
||||
| 今日异常数 | `event='exception'` 的条数 | 今日 JSONL |
|
||||
| 账号今日跑量 | 按 `hd_id` 聚合上述四类事件数;同时并列展示累计 `req_count` / `current_count` | JSONL + hotel_hd |
|
||||
| 城市今日跑量 | 按 `target_city` 聚合 `fetch_task` 与 `upload(ok=1)` | 今日 JSONL |
|
||||
| 平台侧成功/拒收 | `getStats(date, vendorName, clientId=城市)` 的 `success` / `reject` / `remain` | 任务平台 OpenAPI |
|
||||
| 交任务成功率 | `upload(ok=1)` ÷ (`upload(ok=1)` + `upload(ok=0)`) × 100% | 今日 JSONL |
|
||||
| 长期未活动账号 | `updated_at` 距今 > 24h 且 `is_ok IS NULL`(可用但没跑) | hotel_hd |
|
||||
| 房型最低价(单条) | 该条 `hotel_json` 内 `averagePrice` 最小值 ÷ 100,单位元 | hotel_json.json_data |
|
||||
|
||||
**口径边界(必须写进验收)**
|
||||
|
||||
1. 账号/城市今日跑量**从埋点上线当天起**才有数据;埋点之前的历史无法按账号切分(`hotel_task` 无账号字段),此时页面"今日跑量"显示 0 并在页脚提示"埋点未覆盖该日期"。
|
||||
2. `hotel_hd.req_count/current_count` 是**累计值**,不是今日值,两者不得混用。
|
||||
3. 平台 `getStats` 是**任务平台侧**口径(按城市统计成功/拒收),与本地日志口径独立,页面上并列展示、不相互校验为"必须相等"。
|
||||
4. `realtimeCityList` 返回的 `count` 实测**全为 -1**(平台未开放剩余量),因此城市剩余任务量只能靠 `getStats.remain`,不能拿 `count` 展示。
|
||||
|
||||
### 3.5 时间
|
||||
|
||||
- "今天"以服务端本地日期为准(与采集机同机,`Asia/Shanghai`);接口统一接收 `YYYY-MM-DD`。
|
||||
- 日志文件按天切分(`run_20261020.jsonl`),查询区间跨天时后端按天文件依次读取。
|
||||
- `hotel_hd.updated_at` 为 MySQL 服务器当前时间,用于"最后活动时间"和"长期未活动"判定。
|
||||
- 自动刷新默认 15 秒(日志文件 + 库表都轻量),页面隐藏时暂停。
|
||||
|
||||
## 4. 页面与功能需求
|
||||
|
||||
整体结构:顶部导航(**2 个 tab** + 实时时钟 + 刷新开关),**默认落在"账号池"页**;顶部另有常驻健康度条(`is_ok` 分布,可用 < 10 时红底)。
|
||||
|
||||
> **v1.1 修订(2026-10-21,按用户反馈收敛)**:v1.0 设计的「概览 / 城市 / 记录 / 告警」四页**已下线并在前端删除**,只保留**两个页面**——账号池(`hotel_hd` 原始数据)+ 查询(平台 `getStats`,参考 `查询.py`)。后端对应接口(`/overview`、`/stats/*`、`/records`、`/alerts`、`/audit`)仍然保留,需要时可随时把页面加回来。
|
||||
|
||||
### 4.1 全局框架(FR-1)
|
||||
|
||||
- 导航 tab:**账号池 / 查询**(`keep-alive` 保状态)。
|
||||
- 手动刷新按钮 + 自动刷新开关(默认开,15 秒);自动刷新为**静默刷新**,不闪遮罩。
|
||||
- 实时时钟(每秒跳动);页面隐藏暂停自动刷新,回到前台立即刷新。
|
||||
- 顶部常驻**健康度条**:`可用 3 / 403 312 / 401 8 / 其它 25`(其它 = 418×2 + 0×9 + 6×14),可用数 < 10 时红底警示。
|
||||
|
||||
|
||||
### 4.2 账号池页(FR-2,首屏,锁一屏、表格内滚动)
|
||||
|
||||
**只展示 `hotel_hd` 的原始列,不做二次加工**;按 **`updated_at` 倒序取最新 15 条**,顶部标注"最新 15 条(按 updated_at 倒序,共 X 条)"。
|
||||
|
||||
| 列 | 展示要求 |
|
||||
|---|---|
|
||||
| `id` | 主键原值 |
|
||||
| `is_ok` | **原值**(`NULL` 显示 `NULL`);颜色:绿=可用、红=403/0、橙=401/418、灰=其它 |
|
||||
| `req_count` | **包使用的总次数** |
|
||||
| `current_count` | **当前城市的使用次数**(改城市时自动清零) |
|
||||
| `prox` | 代理**原始 JSON**(含代理账号密码,仅本机内网使用,原样展示) |
|
||||
| `city` | 绑定城市,空则显示 `NULL` |
|
||||
| `mt_traceid` | 原值(`None` 表示还没有 traceId) |
|
||||
| `updated_at` | 更新时间(页面按它倒序展示,**不展示 `created_at`**) |
|
||||
|
||||
- 行底色按 `is_ok` 分档:403/0 淡红、401/418 淡橙、`NULL` 淡绿、其它淡灰。
|
||||
- **行内只有一个操作**(规则见 4.4):
|
||||
- 「改城市」:弹窗(只列代理池有 IP 的合法城市)→ 二次确认 → `city=新城市`、`prox=NULL`、**`is_ok=NULL`(包重新可用)**;`current_count` 保留不变。
|
||||
- ~~「重置」~~:**已取消**(页面上不再有重置按钮);后端 `reset` 接口保留备用。
|
||||
|
||||
> 拿任务失败(`get_one_task` 返回 False)时,**采集脚本会自动把该城市下所有可用包(`is_ok IS NULL`)标记为 `is_ok=0`**,页面上会直接以"异常"色显示。
|
||||
|
||||
### 4.3 查询页(FR-3,参考 `查询.py`)
|
||||
|
||||
按日期逐城市调用任务平台 `getStats`(**只读**,绝不领任务),复刻 `查询.py` 的"总成功条数 / 总失败条数":
|
||||
|
||||
1. 顶部:日期选择(默认今天)+「查询」按钮 + 本次查询时间。
|
||||
2. 汇总条:**总成功条数**、**总失败条数**、成功率、城市数、平台状态;有失败城市时列出城市名。
|
||||
3. 结果表:城市(按 success 降序)、success、reject、remain、timeout、状态。
|
||||
4. 口径说明:`remain` 是逐城剩余量,**相加无业务含义,不做合计**。
|
||||
|
||||
### 4.4 写操作(FR-4)
|
||||
|
||||
| 操作 | 接口 | 影响 | 校验 | 审计 |
|
||||
|---|---|---|---|---|
|
||||
| 改城市 | `POST /api/hotel/accounts/{id}/city` | `city=新城市`、`prox=NULL`、**`is_ok=NULL`**(`current_count` 不变) | 城市必须在合法白名单(39 城);新旧相同 400;账号不存在 404 | 写 `logs/audit.jsonl` |
|
||||
| 重置 is_ok(**前端已不展示按钮**,接口保留) | `POST /api/hotel/accounts/{id}/reset` | `hotel_hd.is_ok=NULL` | 仅单条;已是 NULL 返回 400 | 写 `logs/audit.jsonl` |
|
||||
|
||||
- 两个接口都在**单事务**内完成(`SELECT ... FOR UPDATE` 锁行),数据库写失败整体回滚、不写审计。
|
||||
- 审计行字段:`ts`、`action`、`hd_id`、`dfpid_tail`、`old_city`、`new_city`、`old_prox_ip`(只留 IP:端口)、`old_is_ok`、`new_is_ok`、`old_current_count`、`new_current_count`、`operator`、`result`。
|
||||
- **不提供任何批量写操作**(用户拍板:重置只单条)。
|
||||
- 平台**永不调用** `getTask` / `uploadTaskDatagram`(会消耗真实任务),只调用 `getStats` / `realtimeCityList` / `realtimeCheckInOutDateList`。
|
||||
|
||||
## 5. 非功能需求
|
||||
|
||||
| 项 | 要求 |
|
||||
|---|---|
|
||||
| 视觉风格 | 沿用「出行任务看板」的设计系统(`设计风格.md`):手绘涂鸦风/编辑排版风 token、卡片描边、克制动效;**禁止散落硬编码色值**,全部走 `tokens.css` |
|
||||
| 响应式 | 不做移动端适配;桌面优先,主体 `max-width 1400px` 居中;表格区域自适应高度、内部滚动 |
|
||||
| 动效 | hover 下划线、按压 scale-95(0.2s)、区块淡入上滑(0.5s easeOut,仅一次)、数字 CountUp;系统"减少动效"时全部关闭 |
|
||||
| 实时性 | 自动刷新 15 秒(可关);静默刷新不闪遮罩;写操作后局部刷新该行而不是整页刷新 |
|
||||
| 性能 | `hotel_hd` 347 行全量可取(单表小);JSONL 按天读取 + mtime 缓存,单日 5k 行内毫秒级;`hotel_json` 列表**不返回 json_data**(只给大小),详情才按 id 取单条;平台 OpenAPI 结果缓存 60 秒,`meta` 缓存 5 分钟 |
|
||||
| 兼容性 | Chrome / Edge 近两个大版本(桌面) |
|
||||
| 安全 | 只读库用只读账号语义;写操作**只允许改 `city`/`prox`/`is_ok` 三列**且全部参数化;`dfpid`、代理账号密码在界面与审计日志中脱敏;CORS 仅放行 `localhost:5175` |
|
||||
| 可靠性 | 日志文件缺失/损坏时页面降级为空并在页脚提示,不影响账号池与库表类功能;外部接口超时不阻塞页面 |
|
||||
| 可维护性 | 状态字典、合法城市、事件字段、设计 token 各自集中一处;改口径只改一处 |
|
||||
| 不新增表 | **任何功能不得建表/建视图**;如需持久化一律走本地 JSONL 文件(`酒店/logs/`) |
|
||||
|
||||
## 6. 已确认事项(用户拍板,不再讨论)
|
||||
|
||||
| # | 事项 | 结论 |
|
||||
|---|---|---|
|
||||
| 1 | 平台主线 | ✅ **以 `hotel_hd` 账号池为主线**(首屏即账号池) |
|
||||
| 2 | "账号"的定义 | ✅ `hotel_hd` 的一行(`dfpid` 唯一,347 个) |
|
||||
| 3 | 是否新增数据库表 | ✅ **不新增任何表**:埋点→本地 JSONL;审计→本地 JSONL;房型价格→不做聚合宽表 |
|
||||
| 4 | 埋点是否允许改采集脚本 | ✅ 允许改 `酒店/酒店详情.py`;写日志失败**不得**影响采集主流程 |
|
||||
| 5 | 改城市写操作 | ✅ 直接写库 + 二次确认 + 审计(审计落文件) |
|
||||
| 6 | 重置 is_ok | ✅ **只允许单条重置**,不做批量 |
|
||||
| 7 | 统计维度 | ✅ 账号 + 城市两个维度;**不要采集机(ip)维度** |
|
||||
| 8 | 房型价格 | ✅ 只在采集记录详情里实时解析单条;不做跨酒店聚合 |
|
||||
| 9 | 平台 OpenAPI | ✅ 只调只读接口;`getTask`/`uploadTaskDatagram` 永不由平台调用 |
|
||||
| 10 | 手机号表(`project_management.手机号`) | ✅ 不纳入本期范围(`主要sql.txt` 已改为 `hotel_hd`) |
|
||||
| 11 | 技术栈 | ✅ 复用「出行任务看板」骨架:Vue3 + TS + Vite + Element Plus + FastAPI + aiomysql |
|
||||
|
||||
## 7. 验收标准
|
||||
|
||||
| # | 验收项 | 判定方法 |
|
||||
|---|---|---|
|
||||
| 1 | 账号池页能列出 347 行,KPI 显示总数 347 / 可用 2 / 403 312 | 与 `SELECT COUNT(*), SUM(is_ok IS NULL), SUM(is_ok=403) FROM hotel_hd` 逐项一致 |
|
||||
| 2 | 今日跑量三列(领任务/成功/失败)与日志逐条对得上 | `scripts/verify_api.py` 直接统计 JSONL 与接口输出比对,误差 0 |
|
||||
| 3 | 拿任务 False 会在告警页出现,且带上账号与城市 | 用 mock 脚本写一条 `fetch_empty` 后刷新页面可见 |
|
||||
| 4 | 改城市成功后该行 `city` 变更且 `prox` 变为空 | 库里复查 `SELECT city, prox FROM hotel_hd WHERE id=?` |
|
||||
| 5 | 改成非法城市(如"南通"、不存在的城市)被拒绝 | 接口返回 400 + 明确文案,库不变 |
|
||||
| 6 | 单条重置 is_ok 后该行变"可用",且此前的状态记进审计文件 | 库里 `is_ok IS NULL`;`logs/audit.jsonl` 有对应行 |
|
||||
| 7 | 采集记录详情能解析出房型/均价/库存,均价单位为元 | 抽查一条与美团页面/JSON 原值一致(分值 ÷100) |
|
||||
| 8 | 日志文件不存在或损坏时页面不白屏 | 重命名日志目录后刷新,页面降级并提示 |
|
||||
| 9 | 全流程不新增数据表 | 交付前 `SHOW TABLES` 前后对比一致 |
|
||||
| 10 | 采集脚本改造后主流程行为不变 | 不改动 `run_one` 分支逻辑;mock 验证 `fetch_task`/`fetch_empty` 两条链路 |
|
||||
@@ -0,0 +1,249 @@
|
||||
# 美团酒店任务看板 — 前端设计文档
|
||||
|
||||
| 版本 | 日期 | 状态 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 定稿待确认 |
|
||||
|
||||
## 1. 技术选型
|
||||
|
||||
直接复用「出行任务看板」(`C:\Users\lkq\Desktop\出行任务面板\frontend`)的成熟骨架与设计系统,**不引入新框架、不重做样式体系**。
|
||||
|
||||
| 项 | 选择 | 理由 |
|
||||
|---|---|---|
|
||||
| 框架 | Vue 3(Composition API)+ Vite + TypeScript | 骨架已验证;`vue-tsc -b` 类型检查随构建一起跑 |
|
||||
| 样式 | 自研工具类 CSS(`styles/utilities.css`)+ `styles/tokens.css` + `styles/sketch.css` 三层 | 沿用面板方案:Tailwind 的 oxide 扫描器在部分 Windows 环境失效(工具类不生成→页面竖排),故固化为项目自带 CSS,任何机器构建一致 |
|
||||
| UI 组件库 | Element Plus(CSS 变量覆盖为马克笔配色 + sketch 皮肤) | 表格/分页/日期/弹窗/抽屉组件完善,二期加页面成本低 |
|
||||
| 图表 | ECharts 6(`BaseChart.vue` 封装) | 环形图/柱图/折线三类够用;统一主题走 `chartTheme.ts` |
|
||||
| 状态 | Pinia(仅存全局筛选、刷新信号、meta 缓存) | 轻量,避免页面间状态漂移 |
|
||||
| 请求 | Axios(拦截器统一错误处理 + 超时 15s) | 标准方案 |
|
||||
| 日期 | Day.js | 轻量 |
|
||||
| 动效 | CSS 过渡 + `@vueuse/motion`(克制预设,无 spring) | 手绘风克制动效 |
|
||||
| 图标 | lucide-vue-next | 线性图标 |
|
||||
| 启动 | 后端 `start.py`(开发模式双进程 / `--static` 单进程托管 dist) | 新电脑只需 Python + `frontend/dist`,无需 Node |
|
||||
|
||||
**不需要的依赖**:`xlsx`(本期无导出需求,保留依赖但不使用)、OCR 相关全部不引入。
|
||||
|
||||
**数据持久化约束**:前端与后端**不新增任何数据表**(见 01 文档第 5 节);所有"今日跑量"与审计数据来自后端读本地 JSONL 文件,前端只消费接口。
|
||||
|
||||
## 2. 设计语言(沿用《设计风格.md》,禁止另起一套)
|
||||
|
||||
素描纸底(淡方格纹理)+ 暖墨色线条 + 马克笔四色点缀 + 中文手写标题 + 抖动圆角 + 硬偏移阴影。**所有颜色/圆角/阴影必须用 `tokens.css` 变量,禁止在组件里写死色值。**
|
||||
|
||||
### 2.1 色板 token(取自骨架 `tokens.css`,变量名不得改)
|
||||
|
||||
| token | 值 | 用途 |
|
||||
|---|---|---|
|
||||
| `--bg-page` | `#fbf7ec` | 页面底色(素描纸) |
|
||||
| `--bg-card` | `#fffdf5` | 卡片底色 |
|
||||
| `--bg-hover` / `--bg-muted` | `rgba(51,48,42,.05)` / `.06` | hover 底 / 表头底 |
|
||||
| `--text-primary` | `#33302a` | 标题与数值 |
|
||||
| `--text-secondary` / `--text-weak` / `--text-faint` | 同色 62% / 42% / 26% | 说明 / 弱提示 / 分隔 |
|
||||
| `--border-color` / `--border-strong` | 同色 28% / `#33302a` | 细边框 / 卡片描边 |
|
||||
| `--accent` | `#e0402c` | 强调、当前 tab、告警 |
|
||||
| `--marker-blue` / `--marker-green` / `--marker-yellow` | `#3e6cb5` / `#3c9a5f` / `#ffcf4d` | 状态色 / 高亮笔 |
|
||||
| `--shadow-card` / `--shadow-raised` | `3px 3px 0` / `5px 5px 0` | 硬偏移阴影(禁模糊阴影) |
|
||||
| `--radius-card` / `--radius-pill` | 抖动圆角 / 药丸圆角 | 手绘描边感 |
|
||||
| `--font-display` / `--font-body` / `--font-mono` | ZCOOL KuaiLe / system-ui / ZCOOL QingKe HuangYou | 标题 / 正文 / 标签与大数字 |
|
||||
|
||||
### 2.2 `is_ok` 状态色映射(本项目新增,唯一定义处:`composables/hotelStatus.ts`)
|
||||
|
||||
| 状态 | 文案 | 文字/标签色 | 行底色 | 图标 |
|
||||
|---|---|---|---|---|
|
||||
| `NULL` | 可用 | `--marker-green` | 绿 8% | `check-circle` |
|
||||
| `403` | 封禁/风控 | `--marker-red` | 红 8% | `shield-alert` |
|
||||
| `401` | 登录失效 | `#d9a424`(warning) | 橙 8% | `key-round` |
|
||||
| `418` | 网络受限 | `#d9a424` | 橙 6% | `wifi-off` |
|
||||
| `0` | 异常 | `--marker-red` | 红 6% | `alert-triangle` |
|
||||
| `6` | 未知(6) | `--text-weak` | 灰 6% | `help-circle` |
|
||||
| 其它非 NULL | 未知(值) | `--text-weak` | 灰 6% | `help-circle` |
|
||||
|
||||
约定:**绿=能动、红=死了、橙=可疑、灰=不清楚**;颜色只做强调,文案与图标必须同时给出(色盲可辨)。
|
||||
|
||||
### 2.3 动效语言(克制,无 spring)
|
||||
|
||||
| 场景 | 效果 |
|
||||
|---|---|
|
||||
| 区块入场 | 上滑 20px + 淡入 0.5s easeOut,一次 |
|
||||
| hover | 卡片描边变马克笔红 + 硬阴影加粗;行 hover 底色 `--bg-hover` |
|
||||
| 数字 | CountUp 平滑过渡(easeOut,不循环) |
|
||||
| 弹窗/抽屉 | Element Plus `dialog-fade` 覆盖为淡入 + 微缩放,**禁用 bounce** |
|
||||
| 数据刷新 | 静默替换,无遮罩闪烁;写操作后只刷新受影响行(局部 patch) |
|
||||
| 系统"减少动效" | `prefers-reduced-motion` 时全部关闭(`reduced-motion` 类) |
|
||||
|
||||
## 3. 页面结构(v1.1:两页导航,默认落账号池)
|
||||
|
||||
> **v1.1 修订(2026-10-21)**:按用户反馈,前端只保留**两个页面**:
|
||||
> - **页面 1 账号池**:`hotel_hd` 原始 9 列(id / is_ok / req_count / current_count / prox / city / mt_traceid / created_at / updated_at),固定展示前 10 条,行内可改城市与重置 is_ok;
|
||||
> - **页面 2 查询**:参考 `查询.py`,按日期逐城市调平台 `getStats`,展示每城 success/reject 与合计。
|
||||
>
|
||||
> 本章 3.3~3.6 描述的「概览 / 城市 / 记录 / 告警」四页**已下线**(`OverviewView.vue`、`CitiesView.vue`、`RecordsView.vue`、`AlertsView.vue` 已删除),保留文字作为历史设计参考;对应后端接口未删除。最新实现见 README 的「五个页面」已改为「两个页面」。
|
||||
|
||||
```
|
||||
┌─ FilterBar ───────────────────────────────────────────────────────────┐
|
||||
│ 美团酒店任务看板 [账号池][概览][城市][记录][告警●] [日期][城市▼] [⟳ 15s] [时钟] │
|
||||
│ ── 健康度条:可用 2 / 403 312 / 401 8 / 其它 25 ── 可用池不足! ────────│
|
||||
└───────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 3.1 全局框架 `App.vue` + `NavTabs.vue` + `FilterBar.vue` + `HealthBar.vue`
|
||||
|
||||
- `NavTabs`:5 个 tab(`accounts` / `overview` / `cities` / `records` / `alerts`),未读告警数在"告警"上显示红点。
|
||||
- `FilterBar`:两个 slot —— `nav`(tab 区)与默认区(筛选控件:日期、城市、刷新)。
|
||||
- `HealthBar`:常驻健康度条,数据来自 `/api/hotel/overview`(与概览页共用同一份缓存,避免重复请求);可用数 < 10 时整条变红底白字。
|
||||
- `KeepAlive` 包裹页面组件,切 tab 不丢筛选与分页。
|
||||
|
||||
### 3.2 账号池页 `views/AccountsView.vue`(首屏)
|
||||
|
||||
| 区块 | 内容 |
|
||||
|---|---|
|
||||
| KPI 行 | 账号总数 / 可用池 / 封禁(403) / 今日领任务数(4 卡,可点跳筛选) |
|
||||
| 筛选行 | 状态多选(可用/403/401/418/其它)、城市下拉、`dfpid` 搜索(防抖 300ms)、"只看可用"开关、重置筛选 |
|
||||
| 表格 | `el-table`,列见 01 文档 FR-2;服务端分页与排序;固定"操作"列 |
|
||||
| 行状态 | 按 2.2 着色;`prox` 为空显示"无(下次按城市补)" |
|
||||
| 行操作 | 「改城市」→ `ChangeCityDialog`;「重置」→ `ResetIsOkDialog`(仅非 NULL 行可见) |
|
||||
| 底部 | 共 X 条 / 每页 20·50·100 |
|
||||
|
||||
### 3.3 概览页 `views/OverviewView.vue`
|
||||
|
||||
- 池子健康度环形图(`BaseChart`)+ 可用率大字(CountUp)+ 不足红条。
|
||||
- 今日跑量 5 个 KPI 小卡。
|
||||
- 城市跑量 Top10 柱图(点击 → 跳城市页并带城市筛选)。
|
||||
- 近 7 天趋势折线(领任务 / 成功两条线,缺日补 0)。
|
||||
- 平台侧对照卡(`getStats` 的 success/reject/remain/timeout,标注"平台口径")。
|
||||
- 告警摘要(空任务 Top5 城市、长期未活动数)。
|
||||
|
||||
### 3.4 城市页 `views/CitiesView.vue`
|
||||
|
||||
- 表格:城市 / 账号数 / 代理 IP 数 / 今日领任务 / 今日成功 / 今日空任务 / 平台 success / reject / remain。
|
||||
- 平台三列默认显示"—",点"加载平台数据"后一次性拉取(结果缓存 60s)。
|
||||
- 行点击 → 账号池页 + 该城市筛选。
|
||||
|
||||
### 3.5 记录页 `views/RecordsView.vue`
|
||||
|
||||
- 顶部子 tab:任务记录 / 采集记录。
|
||||
- 两个 `el-table` + 服务端分页;筛选:日期范围、城市、关键字(酒店名 / `unique_id` / `poi_id`)。
|
||||
- 行点击打开 `RecordDetailDrawer`:
|
||||
- 上部:酒店基础信息(名称、地址、城市、入离日期、`poi_id`、`unique_id`)。
|
||||
- 中部:房型表(房型名 / 商品名 / 均价(元) / 原价(元) / 库存 / 标签 / 支付方式),按均价升序,最低价行黄色高亮(`--highlighter`)。
|
||||
- 下部:原始 JSON 折叠(`el-collapse`,超 100KB 时提示"已截断,仅显示前 100KB")。
|
||||
|
||||
### 3.6 告警页 `views/AlertsView.vue`
|
||||
|
||||
三个区块(`el-tabs` 或分区卡片,每区带条数徽标):
|
||||
|
||||
1. 今日空任务明细(`fetch_empty`):时间 / 账号 / 城市 / 返回码+文案 / 建议 / 「去改城市」。
|
||||
2. 长期未活动账号(`is_ok IS NULL` 且 `updated_at` > 24h):ID / dfpid / 城市 / 最后活动 / 「去改城市」。
|
||||
3. 封禁清单(403 / 401 / 418):ID / dfpid / 城市 / 状态 / 最后活动 / 「重置」。
|
||||
|
||||
### 3.7 弹窗(两处共用规格)
|
||||
|
||||
`components/ChangeCityDialog.vue`
|
||||
|
||||
```
|
||||
┌─ 改绑定城市 ───────────────────────┐
|
||||
│ 账号 #13888 dfpid …8f42ac81 │
|
||||
│ 当前城市:南宁 当前代理:有(183.131.35.73:21432)│
|
||||
│ 新城市: [ 下拉:39 个合法城市 ▾ ] │
|
||||
│ 该城市可用代理 IP:1 个 │
|
||||
│ ⚠ 提交将同时清空该账号代理, │
|
||||
│ 下次运行按新城市自动补同城 IP。 │
|
||||
│ [取消] [确认修改] │
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 下拉只列合法城市(后端 `meta` 下发),并按"该城 IP 数"降序。
|
||||
- 选中无 IP 的城市时按钮禁用并提示(实测当前无此情况,防御性保留)。
|
||||
- 提交中按钮 loading、禁止重复点击;成功后 `$message.success` 并局部刷新该行。
|
||||
|
||||
`components/ResetIsOkDialog.vue`
|
||||
|
||||
```
|
||||
┌─ 重置账号状态 ─────────────────────┐
|
||||
│ 账号 #13702 dfpid …7a1f3c09 │
|
||||
│ 当前状态:封禁/风控 (403) │
|
||||
│ 重置后:可用 (NULL),脚本下次会选中它 │
|
||||
│ ⚠ 仅清除标记;headers/token 失效时 │
|
||||
│ 下次运行仍会再次 403。 │
|
||||
│ [取消] [确认重置] │
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 已是 `NULL` 时按钮不可点(后端也返回 400)。
|
||||
- 单条操作,**不提供批量入口**。
|
||||
|
||||
## 4. 滚动与高度策略
|
||||
|
||||
| 页面 | 策略 |
|
||||
|---|---|
|
||||
| 账号池 / 城市 / 记录 / 告警 | **锁一屏**:`h-[calc(100vh-约190px)]`,页面本身不滚动,表格/列表区域内部滚动(`el-table` 自带虚拟滚动条) |
|
||||
| 概览 | 允许整页滚动(图表高度多),但图表容器固定高度(240px / 300px) |
|
||||
| 弹窗 / 抽屉 | 内容超高时内部滚动,头部与底部按钮固定 |
|
||||
| 表头 | 固定表头(`el-table` height 属性),横向滚动时首列(ID)与操作列 sticky |
|
||||
|
||||
## 5. 数据流与状态管理
|
||||
|
||||
```
|
||||
┌───────────── Pinia: hotelStore ─────────────┐
|
||||
页面筛选/分页 ────────► │ filters: {date, city, status[], keyword} │
|
||||
│ refreshTick: number(自动刷新信号) │
|
||||
│ meta: {cities[], isOkDict, ipCountByCity} │
|
||||
└───────────────┬─────────────────────────────┘
|
||||
│
|
||||
┌──────────────────────────────┼───────────────────────────────┐
|
||||
▼ ▼ ▼
|
||||
/api/hotel/meta /api/hotel/overview /api/hotel/stats/*
|
||||
(5 分钟缓存) (健康度 + KPI + 趋势) (账号/城市跑量)
|
||||
│
|
||||
┌───────────────┴──────────────┐
|
||||
▼ ▼
|
||||
MySQL: hotel_hd(可写) JSONL: 酒店/logs/
|
||||
MySQL: hotel_task/hotel_json(只读) run_YYYYMMDD.jsonl(只读解析)
|
||||
MySQL: area_info / proxs_list audit.jsonl(写操作审计)
|
||||
│
|
||||
▼
|
||||
平台 OpenAPI(只读):getStats / realtimeCityList
|
||||
```
|
||||
|
||||
- **刷新机制**:`refreshTick` 由定时器(默认 15s,可关)递增,各页面 `watch` 它静默重取数据;页面隐藏(`document.hidden`)时暂停、回到前台立即刷新一次。
|
||||
- **乐观 UI**:改城市/重置成功后,直接 patch 当前行(不等整页请求),随后后台静默刷新一次做校准。
|
||||
- **错误处理**:Axios 拦截器统一 `$message.error`;外部接口(getStats)失败不影响主体页面,只在对应卡片显示"平台数据获取失败(可重试)"。
|
||||
- **日志降级**:接口返回 `logs_available: false` 时,今日跑量列显示"—",页脚提示"埋点日志未就绪"。
|
||||
|
||||
## 6. 组件清单
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `views/AccountsView.vue` | 账号池页(KPI + 表格 + 筛选 + 行操作) |
|
||||
| `views/OverviewView.vue` | 概览页(健康度 + KPI + 图表 + 平台对照) |
|
||||
| `views/CitiesView.vue` | 城市页 |
|
||||
| `views/RecordsView.vue` | 任务 / 采集记录 + 详情抽屉 |
|
||||
| `views/AlertsView.vue` | 告警页三区块 |
|
||||
| `components/NavTabs.vue` | 五 tab 导航(含告警红点) |
|
||||
| `components/FilterBar.vue` `FilterFields.vue` | 顶栏与筛选控件 |
|
||||
| `components/HealthBar.vue` | 健康度条(常驻) |
|
||||
| `components/KpiCard.vue` | KPI 卡(数值 + 副标题 + 可点) |
|
||||
| `components/StatusTag.vue` | `is_ok` 状态标签(按 2.2 映射) |
|
||||
| `components/BaseChart.vue` `ChartSection.vue` | ECharts 封装与图表容器 |
|
||||
| `components/ChangeCityDialog.vue` | 改城市弹窗(含 prox 清空提示) |
|
||||
| `components/ResetIsOkDialog.vue` | 重置 is_ok 弹窗(单条) |
|
||||
| `components/RecordDetailDrawer.vue` | 采集记录详情(房型/价格/原始 JSON) |
|
||||
| `composables/hotelStatus.ts` | `is_ok` → 文案/颜色/图标 唯一映射 |
|
||||
| `composables/useAutoRefresh.ts` | 自动刷新(可见性感知) |
|
||||
| `composables/useCountUp.ts` `chartTheme.ts` | 沿用骨架 |
|
||||
| `stores/hotel.ts` | Pinia:filters / refreshTick / meta |
|
||||
|
||||
## 7. 接口清单(前端视角)
|
||||
|
||||
| 页面 | 接口 | 频率 |
|
||||
|---|---|---|
|
||||
| 全局 | `GET /api/hotel/meta` | 启动一次 + 5 分钟缓存 |
|
||||
| 全局(健康度条) | `GET /api/hotel/overview?date=` | 15s(与概览页共用缓存 key) |
|
||||
| 账号池 | `GET /api/hotel/accounts?date=&city=&status=&keyword=&page=&size=&sort=` | 筛选/分页/刷新 |
|
||||
| 账号池写操作 | `POST /api/hotel/accounts/{id}/city`、`POST /api/hotel/accounts/{id}/reset` | 手动 |
|
||||
| 概览 | `GET /api/hotel/overview`、`GET /api/hotel/stats/city?top=10`、`GET /api/hotel/trend?days=7`、`GET /api/hotel/platform/stats?date=` | 15s / 60s 缓存 |
|
||||
| 城市 | `GET /api/hotel/stats/city`、`GET /api/hotel/platform/stats?date=&city=` | 手动"加载平台数据" |
|
||||
| 记录 | `GET /api/hotel/tasks`、`GET /api/hotel/records`、`GET /api/hotel/records/{id}` | 筛选/翻页/点开抽屉 |
|
||||
| 告警 | `GET /api/hotel/alerts?date=` | 15s |
|
||||
| 审计(可选页脚链接) | `GET /api/hotel/audit?limit=50` | 手动 |
|
||||
|
||||
字段与响应结构见 `04_开发文档.md` 第 4 节 API 契约。
|
||||
@@ -0,0 +1,239 @@
|
||||
# 美团酒店任务看板 — 页面布局图
|
||||
|
||||
| 版本 | 日期 | 状态 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 定稿待确认 |
|
||||
|
||||
> 桌面优先,主体 `max-width: 1400px` 居中(面板骨架为 1280px,本项目表格列更多,放宽到 1400px)。以下尺寸单位 px。
|
||||
|
||||
## 1. 全局框架(v1.1:两页导航 + 常驻健康度条)
|
||||
|
||||
> **v1.1 修订(2026-10-21)**:导航从五页收敛为**两页**——「账号池」(`hotel_hd` 原始 9 列,前 10 条,可操作)与「查询」(平台 `getStats`,参考 `查询.py`)。原「概览 / 城市 / 记录 / 告警」四页的布局图(§3~§6)保留作历史参考,实际界面不再包含。
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ ▓ 顶栏 72px bg=--bg-page 底边 2px 墨线(抖动) │
|
||||
│ 美团酒店任务看板 账号池│概览│城市│记录│告警● [今天▾] [全部城市▾] [⟳自动15s] 18:42:07 │
|
||||
│ (手写体 22px) (tab 15px,当前项红笔下滑线) (筛选控件 13px) (时钟 13px mono)│
|
||||
├──────────────────────────────────────────────────────────────────────────────────────────────┤
|
||||
│ ▒ 健康度条 36px bg=--bg-card 左红竖线 4px │
|
||||
│ 可用 2 │ 封禁(403) 312 │ 登录失效(401) 8 │ 其它 25 │ 可用率 0.6% ⚠ 可用池不足,请重置账号 │
|
||||
│ (绿,15px) (红) (橙) (灰) (红底白字胶囊,可点→告警页) │
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 顶栏与健康度条**常驻不滚动**;页面切换只换 `<main>` 内容(KeepAlive)。
|
||||
- 告警 tab 右侧红点:今日空任务 + 长期未活动 + 封禁 三条告警任一 > 0 时显示,数字 ≥ 100 显示 `99+`。
|
||||
- 自动刷新开关:`⟳ 自动 15s`(开,红字)/ `⟳ 已暂停`(灰字),点击切换;鼠标悬停提示"页面隐藏时自动暂停"。
|
||||
|
||||
## 2. 账号池页(accounts,首屏,锁一屏)
|
||||
|
||||
```
|
||||
┌─ main: h = calc(100vh - 148px) ──────────────────────────────── 主体 1400px ────────────────┐
|
||||
│ ┌ KPI 行 96px(4 卡,间距 16)───────────────────────────────────────────────────────────┐ │
|
||||
│ │ ┌─账号总数 347─┐ ┌──可用池 2──┐ ┌─封禁(403) 312─┐ ┌─今日领任务 1,013─┐ │ │
|
||||
│ │ │ 副:347 唯一dfpid│ │ 副:可用率0.6%│ │ 副:占 89.9% │ │ 副:来自埋点 18:42 │ │ │
|
||||
│ │ └──────────────┘ └────────────┘ └───────────────┘ └────────────────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 筛选行 48px ─────────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 状态: [☑可用][☑403][☑401][☑418][☑其它] 城市:[全部城市▾] dfpid:[搜索____] (○只看可用) [重置]│ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 表格区(自适应,内部滚动)────────────────────────────────────────────────────────────┐ │
|
||||
│ │ ID │dfpid │城市 │代理 │状态 │今日领/成/败/空│累计 req/cur│最后活动 │操作 │ │
|
||||
│ │──────┼─────────┼─────┼──────────┼─────────┼──────────────┼────────────┼──────────┼───────│ │
|
||||
│ │13888 │…8f42ac81│ 南宁│有 .73:21432│[封禁403]│ 0/ 0/ 0/ 2 │ 29/ 21 │10-20 17:34│改城市 │ │
|
||||
│ │ │ │ │ │(红底行) │ │ │ │重置 │ │
|
||||
│ │13916 │…44102218│ 海口│有 .69:47890│[可用] │ 7/ 7/ 0/ 0 │ 7/ 7 │10-20 17:36│改城市 │ │
|
||||
│ │13702 │…7a1f3c09│ 广州│无(下次按城市补)│[登录401]│0/ 0/ 0/ 0│ 12/ 9 │10-19 21:03│改城市│ │
|
||||
│ │ … │ │ │ │ │ │ │ │ │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 分页行 44px ──────────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 共 347 条 每页 [20▾] ‹ 1 2 3 … 18 › │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
列宽规格(合计 ≈ 1336px,留 64px 滚动条与边距):
|
||||
|
||||
| 列 | 宽 | 对齐 | 说明 |
|
||||
|---|---|---|---|
|
||||
| ID | 72 | 右 | sticky 左固定 |
|
||||
| dfpid | 116 | 左 | 只显示后 8 位,hover 显示完整值 tooltip |
|
||||
| 城市 | 88 | 左 | 空城市显示"—"(灰) |
|
||||
| 代理 | 160 | 左 | `有 <IP:端口>` / `无(下次按城市补)`;账号密码永不展示 |
|
||||
| 状态 | 104 | 左 | `StatusTag`,见 02 文档 2.2 |
|
||||
| 今日领/成/败/空 | 156 | 右 | 四个数字用 `/` 分隔,各自 tooltip 说明口径;无日志时整列显示"—" |
|
||||
| 累计 req/cur | 116 | 右 | `req_count / current_count` |
|
||||
| 最后活动 | 132 | 左 | `MM-DD HH:mm`,> 24h 显示橙色 |
|
||||
| 操作 | 152 | 左 | sticky 右固定;「改城市」常显,「重置」仅非 NULL 行可点 |
|
||||
|
||||
行状态:`403` 行 `background: rgba(224,64,44,.06)`;`401/418` 行 `rgba(217,164,36,.06)`;`NULL` 行 `rgba(60,154,95,.06)`。hover 时底色加深到 12%。
|
||||
|
||||
## 3. 概览页(overview,整页可滚动)
|
||||
|
||||
```
|
||||
┌─ main ──────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ ┌ 第一行 300px(左 420 环形 + 右 KPI 网格)──────────────────────────────────────────────┐ │
|
||||
│ │ ┌ 池子健康度 ──────────┐ ┌ 今日跑量 6 卡(2 行 × 3 列)────────────────────────────┐ │ │
|
||||
│ │ │ ╭───╮ │ │ ┌领任务 1013┐ ┌交回成功 986┐ ┌成功率 97.6%┐ │ │ │
|
||||
│ │ │ ╭─┤ 2 ├─╮ │ │ └──────────┘ └────────────┘ └───────────┘ │ │ │
|
||||
│ │ │ │可用 0.6%│ │ │ ┌空任务 21┐ ┌异常 5┐ ┌平台剩余 11250┐ │ │ │
|
||||
│ │ │ ╰─┤403 312├╯ │ │ └────────┘ └──────┘ └──────────────┘ │ │ │
|
||||
│ │ │ 401 8 / 418 2 / 其它(0/6) 23│ └──────────────────────────────────────────────────┘ │ │
|
||||
│ │ │ ⚠ 可用池不足(红条) │ │ │
|
||||
│ │ └──────────────────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 第二行 260px(3 卡等宽)──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ ┌ 城市跑量 Top10(横向柱)┐ ┌ 近 7 天趋势(折线双线)┐ ┌ 平台侧对照(getStats)─┐ │ │
|
||||
│ │ │ 广州 ████████ 212 │ │ ● 领任务 ● 交回成功 │ │ success 1013 │ │ │
|
||||
│ │ │ 北京 █████ 128 │ │ ╱╲╱╲╱╲ │ │ reject 201 │ │ │
|
||||
│ │ │ …(点击柱子→城市页) │ │ (缺日补 0) │ │ remain 11250 │ │ │
|
||||
│ │ └───────────────────────┘ └────────────────────────┘ │ timeout 35 │ │ │
|
||||
│ │ └────────────────────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 告警摘要卡 120px ─────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 今日空任务 Top5 城市:南宁 6 · 青岛 4 · 昆明 3 … 长期未活动账号 2 个 [查看全部→] │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 4. 城市页(cities,锁一屏)
|
||||
|
||||
```
|
||||
┌─ main: h = calc(100vh - 148px) ────────────────────────────────────────────────────────────┐
|
||||
│ ┌ 工具行 48px ──────────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 城市维度 · 共 39 个 [⟳ 加载平台数据](60s 缓存,显示倒计时)│ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 表格区(内部滚动)────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 城市 │账号数│代理IP│今日领任务│今日成功│今日空任务│平台 success│平台 reject│平台 remain│ │
|
||||
│ │──────┼──────┼──────┼──────────┼────────┼──────────┼────────────┼───────────┼───────────│ │
|
||||
│ │ 广州 │ 34 │ 1 │ 212 │ 208 │ 2 │ — │ — │ — │ │
|
||||
│ │ 上海 │ 28 │ 1 │ 168 │ 165 │ 0 │ — │ — │ — │ │
|
||||
│ │ 南宁 │ 9 │ 1 │ 37 │ 31 │ 6 ⚠ │ — │ — │ — │ │
|
||||
│ │ … │ │ │ │ │ │ │ │ │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 「加载平台数据」后三列填充为数值,并按 `reject` 降序重新排序;按钮变为"刷新(32s)"倒计时。
|
||||
- 某行「今日空任务 > 0」橙字 + 行首 ⚠;点行 → 账号池页并带该城市筛选。
|
||||
- 红线:**任何有账号的城市必须至少 1 个代理 IP**;实测 39 城全部满足,若出现不满足则整行红底(防御性提醒)。
|
||||
|
||||
## 5. 记录页(records,锁一屏)
|
||||
|
||||
```
|
||||
┌─ main: h = calc(100vh - 148px) ────────────────────────────────────────────────────────────┐
|
||||
│ ┌ 子 tab + 筛选 48px ───────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ (●任务记录)(○采集记录) [2026-10-19]~[2026-10-20] 城市[全部▾] [酒店名/unique_id___]│ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 表格区(内部滚动)────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ 任务记录:id │酒店名称 │城市 │入住 │离店 │档次 │区域 │unique_id │创建时间│ │
|
||||
│ │ 采集记录:id │酒店名称 │城市 │入住 │离店 │poi_id │JSON 大小 │创建时间│ │
|
||||
│ │ …(点击任意行 → 右侧详情抽屉滑出) │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ 共 10,637 条 每页 [20▾] ‹ 1 2 … 532 › │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 5.1 记录详情抽屉(宽 720,右侧滑出,内容超高内部滚动)
|
||||
|
||||
```
|
||||
┌─ 采集记录 #10634 ─────────────────────────────────────── [×] ┐
|
||||
│ MOS HOTEL·沐南酒店(海口秀英港友谊南海城店) │
|
||||
│ 海口市 · 2026-10-20 → 2026-10-21 · poi 1576639595 │
|
||||
│ 采集时间 2026-10-20 17:31:02 · JSON 430 KB │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ 房型报价(按均价升序,共 27 条) [最低价 ¥263 ▓] │
|
||||
│ ┌房型名──────────┬商品名────────┬均价┬原价┬库存┬标签┬支付┐ │
|
||||
│ │茗雅大床房(清爽…)│无早-优惠 │¥263│¥263│ 8 │代理│在线付│ │
|
||||
│ │雅致双床房 │双早 │¥318│¥356│ 5 │直连│到店付│ │
|
||||
│ │ …(表格内部滚动) │ │
|
||||
│ └──────────────────┴─────────────┴───┴───┴───┴───┴────┘ │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ ▸ 原始 JSON(430 KB,已截断显示前 100 KB) [复制] [下载] │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 抽屉宽度 720;房型表 `max-height: 320px` 内部滚动;最低价行底色 `--highlighter`(黄荧光笔)。
|
||||
- 均价/原价单位 **元**(后端已把分值 ÷100 并保留 2 位),表头标注"价格单位:元/间/晚"。
|
||||
- 解析失败(非 `roomGoodsList` 结构或 JSON 异常)时,房型区显示"该记录暂不支持结构化解析,请查看原始 JSON",不报错。
|
||||
|
||||
## 6. 告警页(alerts,锁一屏)
|
||||
|
||||
```
|
||||
┌─ main: h = calc(100vh - 148px) ────────────────────────────────────────────────────────────┐
|
||||
│ ┌ 三区块切换(药丸按钮,各带条数徽标)──────────────────────────────────────────────────┐ │
|
||||
│ │ (今日空任务 21) (长期未活动 2) (封禁清单 345) │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌ 列表区(内部滚动)—— 以"今日空任务"为例 ─────────────────────────────────────────────┐ │
|
||||
│ │ 时间 │账号 │dfpid │目标城市│返回码/文案 │建议 │操作 │ │
|
||||
│ │──────────┼───────┼─────────┼────────┼───────────────────┼──────────────────┼──────────│ │
|
||||
│ │17:41:20 │13888 │…8f42ac81│ 南宁 │318 当前城市没任务啦│换城市或稍后重试 │去改城市 │ │
|
||||
│ │17:39:05 │13702 │…7a1f3c09│ 青岛 │305 现在没有任务了 │稍后重试 │去改城市 │ │
|
||||
│ │17:36:44 │13650 │…1c0d9ab7│ 昆明 │False 城市未匹配 │检查城市名拼写 │去改城市 │ │
|
||||
│ └────────────────────────────────────────────────────────────────────────────────────────┘ │
|
||||
│ 页脚:空任务判定自 logs/run_YYYYMMDD.jsonl 的 fetch_empty 事件(埋点上线后才有数据) │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 「去改城市」直接打开该账号的 `ChangeCityDialog`(预填账号与当前城市)。
|
||||
- 「封禁清单」区块每行带「重置」按钮(打开 `ResetIsOkDialog`),**无批量勾选**。
|
||||
- 空列表时显示插画式空态:"今天还没有空任务记录 👍"。
|
||||
|
||||
## 7. 弹窗规格(两处共用视觉)
|
||||
|
||||
| 项 | 规格 |
|
||||
|---|---|
|
||||
| 遮罩 | `rgba(51,48,42,.28)`,无模糊 |
|
||||
| 面板 | 宽 520(改城市)/ 480(重置),`--bg-card` 底 + 抖动圆角 + `--shadow-raised` |
|
||||
| 标题 | 手写体 18px,左侧 4px 红竖线;右上 `×` |
|
||||
| 字段行 | 标签 13px(`--text-weak`,右对齐 96px)+ 值 14px;值中的关键数字用 mono |
|
||||
| 警告块 | `--accent-bg` 底 + 左侧红竖线 + ⚠ 图标,13px,两行内 |
|
||||
| 底部 | 右对齐:取消(描边)+ 主按钮(实心 `--accent`);提交中主按钮 loading 且禁用 |
|
||||
| 关闭 | 点遮罩不关闭(防误触),仅 `×` 与「取消」;`Esc` 可关 |
|
||||
|
||||
## 8. 交互标注汇总
|
||||
|
||||
| 位置 | 交互 | 反馈 |
|
||||
|---|---|---|
|
||||
| tab | 点击 | 当前项红笔下滑线;切页不重置筛选与分页(KeepAlive) |
|
||||
| 健康度条「可用池不足」胶囊 | 点击 | 跳告警页「封禁清单」 |
|
||||
| KPI 卡(账号总数/可用池/封禁) | 点击 | 跳账号池页并预置对应状态筛选 |
|
||||
| 城市 Top10 柱子 | 点击 | 跳城市页并高亮该城市行 |
|
||||
| 城市表行 | 点击 | 跳账号池页并带该城市筛选 |
|
||||
| 记录表行 | 点击 | 右侧抽屉滑出(0.24s easeOut) |
|
||||
| 「改城市」 | 点击 | 弹窗;提交成功 → 该行 city 更新、代理变"无"、绿色 toast |
|
||||
| 「重置」 | 点击 | 弹窗;提交成功 → 该行状态变"可用"、绿色 toast |
|
||||
| 非法城市(无 IP) | 下拉选中 | 主按钮禁用 + 提示"该城市暂无可用代理" |
|
||||
| 搜索框 | 输入 | 300ms 防抖后才请求 |
|
||||
| 自动刷新 | 定时 | 只静默替换数据,不重置页码、不闪遮罩 |
|
||||
| 接口失败 | — | 卡片/表格区显示"加载失败 [重试]",不弹全局错误(除写操作) |
|
||||
| 日志缺失 | — | 今日跑量列显示"—",页脚黄条提示"埋点日志未就绪" |
|
||||
|
||||
## 9. 动效标注(克制,手绘风)
|
||||
|
||||
| 名称 | 参数 |
|
||||
|---|---|
|
||||
| 卡片入场 | `translateY(20px) → 0` + `opacity 0 → 1`,0.5s `cubic-bezier(.16,1,.3,1)`,仅首次 |
|
||||
| 行 hover | 背景 `--bg-hover` → 12%,0.16s |
|
||||
| 卡片 hover | 描边 → `--accent`,阴影 `3px → 5px`,0.2s |
|
||||
| 按钮按压 | `scale(.95)`,0.12s |
|
||||
| 抽屉 | `translateX(24px) → 0` + 淡入,0.24s |
|
||||
| 数字 | CountUp 0.6s easeOut |
|
||||
| 告警红点 | 静态红点(不做闪烁,避免干扰) |
|
||||
| 系统减少动效 | 以上全部降级为无动画(`prefers-reduced-motion`) |
|
||||
|
||||
## 10. 布局规格
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 主体宽度 | `max-width: 1400px`,`padding: 0 24px` |
|
||||
| 顶栏 | 高 72,底边 2px 墨线;标题手写体 22px |
|
||||
| 健康度条 | 高 36,`--bg-card` 底,左 4px 红竖线;各项间距 16 |
|
||||
| 卡片 | `--radius-card`、`--shadow-card`、`1.5px solid var(--border-strong)`;内边距 16 |
|
||||
| KPI 卡 | 宽自适应(4 等分,间距 16),数值 30px mono,副标题 12px `--text-weak` |
|
||||
| 表格 | 表头 `--bg-muted`、13px;单元格 13px、行高 40;斑马纹不开(用状态底色区分);边框 1px `--border-color` |
|
||||
| 图表 | 高度 300(环形) / 240(柱/折线);容器内边距 12;网格线用 `--border-color` 20% |
|
||||
| 分页 | 高 44,右对齐 |
|
||||
| 字号阶梯 | 30 / 22 / 18 / 15 / 14 / 13 / 12 |
|
||||
| 间距阶梯 | 4 / 8 / 12 / 16 / 24 / 32 |
|
||||
@@ -0,0 +1,576 @@
|
||||
# 美团酒店任务看板 — 开发文档
|
||||
|
||||
| 版本 | 日期 | 状态 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 定稿待确认(与 01~03 文档配套) |
|
||||
|
||||
## 1. 总体架构
|
||||
|
||||
```
|
||||
┌──────────────────────────── 浏览器(Chrome/Edge) ────────────────────────────┐
|
||||
│ Vue3 + TS + Vite(开发 :5175,产物 dist 由后端托管) │
|
||||
└───────────────┬───────────────────────────────────────────────────────────────┘
|
||||
│ HTTP /api/* (同源,无跨域;开发期 Vite proxy → 127.0.0.1:8011)
|
||||
┌───────────────▼──────────────────── FastAPI(:8011)──────────────────────────┐
|
||||
│ routers: health / meta / overview / accounts / stats / records / alerts │
|
||||
│ platform(只读代理) / audit │
|
||||
│ services: hotel_logs(JSONL 解析+缓存) hotel_meta(状态字典/城市白名单) │
|
||||
│ hotel_query(hotel_hd / hotel_task / hotel_json 查询) │
|
||||
│ hotel_write(改城市 / 重置 is_ok + 审计) platform_api(只读接口) │
|
||||
└───┬───────────────────────┬───────────────────────┬───────────────────────────┘
|
||||
│ aiomysql │ aiomysql │ requests(60s 缓存)
|
||||
▼ ▼ ▼
|
||||
┌────────────────┐ ┌─────────────────────┐ ┌──────────────────────────────┐
|
||||
│ MAIN_DB │ │ HEADERS_DB │ │ 任务平台 OpenAPI(只读) │
|
||||
│ 183.6.7.91:33016│ │ 192.168.5.2:3307 │ │ ktl-001.dsfdl-henan.xyz │
|
||||
│ mt_hotel │ │ headers_project │ │ /getStats │
|
||||
│ hotel_task R │ │ hotel_hd RW │ │ /realtimeCityList │
|
||||
│ hotel_json R │ │ project_proxy │ │ /realtimeCheckInOutDateList │
|
||||
│ area_crood │ │ proxs_list R │ │ ⛔ /getTask 不用(会消耗任务) │
|
||||
│ area_info R │ │ │ │ ⛔ /uploadTaskDatagram 不用 │
|
||||
└────────────────┘ └─────────┬───────────┘ └──────────────────────────────┘
|
||||
│ 同机文件追加
|
||||
┌─────────▼──────────────────────────┐
|
||||
│ 酒店/logs/ (采集脚本与看板共用) │
|
||||
│ run_YYYYMMDD.jsonl 埋点事件 │
|
||||
│ audit.jsonl 写操作审计 │
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**三条硬边界**
|
||||
|
||||
1. **不新增任何表/视图**:新增持久化只有 `酒店/logs/` 下的两个 JSONL 文件。
|
||||
2. **写库只碰三列**:`hotel_hd` 的 `city`、`prox`、`is_ok`;其余表全部只读。
|
||||
3. **平台接口只读**:只调 `getStats` / `realtimeCityList` / `realtimeCheckInOutDateList`。
|
||||
|
||||
## 2. 目录结构
|
||||
|
||||
```
|
||||
工作/酒店/
|
||||
├── 酒店详情.py # 采集主流程(本期加埋点,仅新增 try/except 日志调用)
|
||||
├── 酒店任务拿交.py # 平台 API 客户端(get_one_task / upload_one_task)
|
||||
├── hotel_insight.py # ★新增:埋点写入模块(写 logs/run_YYYYMMDD.jsonl)
|
||||
├── logs/ # 日志目录(已存在)
|
||||
│ ├── run_20261020.jsonl # 埋点事件(按天)
|
||||
│ └── audit.jsonl # 写操作审计
|
||||
└── dashboard/ # ★新增:看板工程
|
||||
├── backend/
|
||||
│ ├── .env / .env.example
|
||||
│ ├── requirements.txt
|
||||
│ └── app/
|
||||
│ ├── main.py # FastAPI 入口 + SPA 静态托管
|
||||
│ ├── config.py # 环境变量(双库 / 日志目录 / 平台账号)
|
||||
│ ├── database.py # 两个 async engine
|
||||
│ ├── deps.py # 公共依赖(分页参数、日期校验)
|
||||
│ ├── routers/
|
||||
│ │ ├── health.py # GET /api/health
|
||||
│ │ ├── meta.py # GET /api/hotel/meta
|
||||
│ │ ├── overview.py # GET /api/hotel/overview /trend
|
||||
│ │ ├── accounts.py # GET /api/hotel/accounts + 2 个写接口
|
||||
│ │ ├── stats.py # GET /api/hotel/stats/account /stats/city
|
||||
│ │ ├── records.py # GET /api/hotel/tasks /records /records/{id}
|
||||
│ │ ├── alerts.py # GET /api/hotel/alerts
|
||||
│ │ ├── platform.py # GET /api/hotel/platform/stats(只读代理)
|
||||
│ │ └── audit.py # GET /api/hotel/audit
|
||||
│ ├── services/
|
||||
│ │ ├── hotel_meta.py # is_ok 字典 / 合法城市 / CITY_GPS / 脱敏
|
||||
│ │ ├── hotel_logs.py # JSONL 读取、解析、mtime 缓存、按维聚合
|
||||
│ │ ├── hotel_query.py # hotel_hd / hotel_task / hotel_json 查询
|
||||
│ │ ├── hotel_write.py # 改城市 / 重置 is_ok(事务 + 审计)
|
||||
│ │ └── platform_api.py # 平台只读接口 + 60s 缓存
|
||||
│ └── schemas.py # Pydantic 请求/响应模型
|
||||
├── frontend/ # 复用面板骨架(Vite + Vue3 + TS)
|
||||
│ ├── package.json / vite.config.ts / tsconfig*.json / index.html
|
||||
│ └── src/{main.ts,App.vue,api,components,composables,stores,styles,views}
|
||||
├── start.py # 一键启动(--static / --no-browser)
|
||||
├── scripts/
|
||||
│ ├── verify_api.py # DB/日志 vs API 逐项对账
|
||||
│ └── mock_events.py # 造 fetch_task/fetch_empty 事件用于联调
|
||||
└── docs/ # 本套文档 01~06 + 表结构.txt + 设计风格.md
|
||||
```
|
||||
|
||||
## 3. 数据库
|
||||
|
||||
### 3.1 连接
|
||||
|
||||
| 别名 | DSN(示例) | 库 | 权限 |
|
||||
|---|---|---|---|
|
||||
| `MAIN_DB_URL` | `mysql+aiomysql://root:***@183.6.7.91:33016` | `mt_hotel`、`area_crood` | 只发 SELECT |
|
||||
| `HEADERS_DB_URL` | `mysql+aiomysql://root:***@192.168.5.2:3307` | `headers_project`、`project_proxy` | 只更新 `hotel_hd` 的 3 列 |
|
||||
|
||||
- 不使用 ORM 模型(这些表不归本项目管理,且跨实例跨库),统一 `text()` 手写 SQL + 绑定参数。
|
||||
- 密码只进 `backend/.env`,`.env.example` 只留占位;`.gitignore` 排除 `.env`。
|
||||
|
||||
### 3.2 只用现有表(不新增)
|
||||
|
||||
| 表 | 用途 | 涉及列 |
|
||||
|---|---|---|
|
||||
| `headers_project.hotel_hd` | 账号池(列表 / 健康度 / 写操作) | id、dfpid、ip、title、channel、is_ok、req_count、current_count、prox、city、mt_traceid、created_at、updated_at |
|
||||
| `mt_hotel.hotel_task` | 任务记录页 | id、hotel_id、city_id、hotel_name、hotel_address、city_name、check_in_date、check_out_date、unique_id、time_left、hotel_star、selected_city、area_type、area_name、created_at |
|
||||
| `mt_hotel.hotel_json` | 采集记录页 + 详情解析 | id、json_data、create_at、poi_id、city_id、hotel_name、city_name、check_in_date、check_out_date |
|
||||
| `area_crood.area_info` | 城市 → 美团 cityId、城市合法性二次校验 | cityId、cityName、title、provinceName |
|
||||
| `project_proxy.proxs_list` | 每城可用 IP 数、城市白名单来源 | city、prox_data、channel |
|
||||
|
||||
### 3.3 新增持久化(文件,不是表)
|
||||
|
||||
| 文件 | 写入方 | 读取方 | 格式 |
|
||||
|---|---|---|---|
|
||||
| `logs/run_YYYYMMDD.jsonl` | 采集脚本(`hotel_insight.py`) | 看板后端 | 每行一个 JSON,字段见 01 文档 3.3 |
|
||||
| `logs/audit.jsonl` | 看板后端(写操作) | 看板后端 | 每行一个 JSON,字段见 4.10 |
|
||||
|
||||
## 4. API 契约
|
||||
|
||||
统一响应包装(沿用面板骨架):
|
||||
|
||||
```json
|
||||
{ "code": 0, "msg": "ok", "data": { } }
|
||||
```
|
||||
|
||||
错误:`code != 0`,`msg` 为中文可读文案,HTTP 状态码同步(400 参数错 / 404 不存在 / 502 上游失败 / 500 内部错)。
|
||||
|
||||
### 4.1 `GET /api/health`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"db_main":"up","db_headers":"up","log_dir":"C:/Users/lkq/Desktop/工作/酒店/logs","log_writable":true}}
|
||||
```
|
||||
|
||||
- 两个 engine 各 `SELECT 1`;`log_writable` 用 `os.access(W_OK)`。
|
||||
|
||||
### 4.2 `GET /api/hotel/meta`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"cities":[{"city":"广州","proxy_ips":1,"accounts":34,"city_id":"20"}],
|
||||
"legal_cities":["广州","上海","…"],
|
||||
"is_ok_dict":{
|
||||
"NULL":{"text":"可用","tone":"ok"},
|
||||
"403":{"text":"封禁/风控","tone":"danger"},
|
||||
"401":{"text":"登录失效","tone":"warn"},
|
||||
"418":{"text":"网络受限","tone":"warn"},
|
||||
"0":{"text":"异常","tone":"danger"},
|
||||
"6":{"text":"未知(6)","tone":"muted"},
|
||||
"_other":{"text":"未知","tone":"muted"}
|
||||
},
|
||||
"platform_available":true
|
||||
}}
|
||||
```
|
||||
|
||||
- 城市清单来源:`proxs_list`(39 城)× `CITY_GPS` 交集;`accounts` 用 `COUNT(*) GROUP BY city`(`title LIKE '%美团酒店详情%'`)。
|
||||
- `city_id` 取 `area_info`(`title LIKE '%美团%'`)第一次命中值,查不到返回 `null`。
|
||||
- 缓存 5 分钟(进程内)。
|
||||
|
||||
### 4.3 `GET /api/hotel/overview?date=YYYY-MM-DD`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"date":"2026-10-20",
|
||||
"pool":{"total":347,"available":2,"s403":312,"s401":8,"s418":2,"s0":9,"s6":14,"other":0,"available_rate":0.6},
|
||||
"today":{"fetch_task":1013,"upload_ok":986,"upload_fail":24,"fetch_empty":21,"exception":5,
|
||||
"success_rate":97.6,"active_accounts":14,"last_event_at":"2026-10-20T18:42:07"},
|
||||
"logs_available":true,
|
||||
"platform":{"ok":true,"success":1013,"reject":201,"remain":11250,"timeout":35,"error":null}
|
||||
}}
|
||||
```
|
||||
|
||||
- `pool` 用一条 `SUM(CASE WHEN …)` SQL 完成,口径必须与 01 文档 3.2/3.4 一致。其中 `other` 专指"既非 NULL 也不在 {403,401,418,0,6} 的其它未知值"(当前 0 行);UI 健康度条展示的"其它 25"是 `s418 + s0 + s6 + other` 的合并值,总数正好 347。
|
||||
- `today` 来自当日 JSONL 聚合;`logs_available=false` 时全为 `null`。
|
||||
- `platform` 走只读代理(60s 缓存),失败时 `ok=false` 且 `error` 带原因,不影响主体返回。
|
||||
|
||||
### 4.4 `GET /api/hotel/trend?days=7&end=YYYY-MM-DD`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"items":[
|
||||
{"date":"2026-10-14","fetch_task":0,"upload_ok":0,"fetch_empty":0,"logs":false},
|
||||
{"date":"2026-10-20","fetch_task":1013,"upload_ok":986,"fetch_empty":21,"logs":true}
|
||||
]}}
|
||||
```
|
||||
|
||||
- 固定返回 `days` 个点,缺失日期补 0 且 `logs=false`(前端据此画虚线)。
|
||||
|
||||
### 4.5 `GET /api/hotel/accounts`
|
||||
|
||||
查询参数:`date`(默认今天)、`city`、`status`(多值:`NULL,403,401`,`NULL` 用字符串传递)、`keyword`(dfpid 前缀)、`page`(默认 1)、`size`(20/50/100)、`sort`(`id|today_fetch_task|updated_at|req_count`)、`order`(`asc|desc`)。
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"total":350,"page":1,"size":10,"items":[{
|
||||
"id":13931,"is_ok":403,"req_count":45,"current_count":45,
|
||||
"prox_raw":"{\"http\": \"http://uuvg:uuvgt@orlk.smart.5...\", \"https\": \"...\"}",
|
||||
"city":"深圳","mt_traceid":"None",
|
||||
"created_at":"2026-10-21 11:49:45","updated_at":"2026-10-21 12:02:11",
|
||||
"dfpid_tail":"…7x516448","has_prox":true,"prox_ip":"orlk.smart.51tcp.net:20756",
|
||||
"status_text":"封禁/风控","status_tone":"danger",
|
||||
"today":{"fetch_task":0,"upload_ok":0,"upload_fail":0,"fetch_empty":0},
|
||||
"ip":"192.168.31.226","channel":"hotel"
|
||||
}]}}
|
||||
```
|
||||
|
||||
- **页面 1 只用到 `hotel_hd` 的 9 个原始列**(`id / is_ok / req_count / current_count / prox_raw / city / mt_traceid / created_at / updated_at`),其余字段为弹窗与状态着色使用。
|
||||
- `req_count` = 包使用的总次数;`current_count` = 当前城市的使用次数(改城市会清零)。
|
||||
- `prox_raw` 是**原始代理 JSON**(含代理账号密码,按用户要求原样返回);`prox_ip` 是脱敏后的 `ip:port`,供弹窗展示。
|
||||
- 页面 1 固定 `size=15` 且按 `updated_at` 倒序(只看最新 15 条);筛选/分页/排序能力保留在接口层,供后续页面复用。
|
||||
|
||||
- SQL 骨架(参数化,排序字段走白名单映射):
|
||||
|
||||
```sql
|
||||
SELECT id, dfpid, ip, channel, is_ok, req_count, current_count, prox, city, created_at, updated_at
|
||||
FROM hotel_hd
|
||||
WHERE title LIKE '%美团酒店详情%'
|
||||
AND (:city IS NULL OR city = :city)
|
||||
AND (:has_status_filter = 0
|
||||
OR (:want_null = 1 AND is_ok IS NULL)
|
||||
OR is_ok IN (:status_list))
|
||||
AND (:keyword IS NULL OR dfpid LIKE CONCAT(:keyword, '%'))
|
||||
ORDER BY {whitelisted_col} {asc|desc}, id DESC
|
||||
LIMIT :size OFFSET :offset;
|
||||
```
|
||||
|
||||
- `today` 由 `hotel_logs.aggregate_by_hd([...ids])` 一次性聚合后 merge(不做 N+1)。
|
||||
- `prox_ip` 用正则从 `prox` JSON 抽 `ip:port`,**账号密码一律剔除**;`prox_raw` 则保留原值。
|
||||
- `dfpid_tail` = `…` + 末 8 位;完整 dfpid 不返回给前端(脱敏)。
|
||||
|
||||
### 4.6 `POST /api/hotel/accounts/{id}/city`
|
||||
|
||||
请求:`{"city":"上海","operator":"local"}`
|
||||
|
||||
成功:
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"id":13931,"old_city":"深圳","new_city":"福州","prox_cleared":true,"is_ok_reset":true,"proxy_ips_in_city":2,"audit_ok":true}}
|
||||
```
|
||||
|
||||
错误分支:
|
||||
|
||||
| 场景 | code | HTTP | msg |
|
||||
|---|---|---|---|
|
||||
| 城市为空 | 1001 | 400 | 城市不能为空 |
|
||||
| 城市不在白名单 | 1002 | 400 | 城市「南通」不在可用代理城市清单内 |
|
||||
| 该城无可用代理 IP | 1003 | 400 | 城市「XX」当前没有可用代理,请先在代理池补充 |
|
||||
| 新旧城市相同 | 1004 | 400 | 新旧城市相同,无需修改 |
|
||||
| 账号不存在 | 1005 | 404 | 账号 #xxx 不存在 |
|
||||
| 库异常 | 1006 | 500 | 修改失败,事务已回滚 |
|
||||
|
||||
实现(`hotel_write.py`):
|
||||
|
||||
```python
|
||||
async with headers_engine.begin() as conn: # 单事务
|
||||
row = await conn.execute(text(
|
||||
"SELECT id, dfpid, city, prox, is_ok, req_count, current_count FROM hotel_hd "
|
||||
"WHERE id=:id AND title LIKE '%美团酒店详情%' FOR UPDATE"), {"id": id})
|
||||
# 校验 → 更新(只碰 city / prox / is_ok 三列;is_ok 重置为 NULL,current_count 保持不变)
|
||||
await conn.execute(text(
|
||||
"UPDATE hotel_hd SET city=:city, prox=NULL, is_ok=NULL WHERE id=:id"),
|
||||
{"city": city, "id": id})
|
||||
# 事务提交成功后才写审计文件(文件写失败不影响已提交的库变更,但要在响应里标记 audit_ok=false)
|
||||
audit_write({..., "new_is_ok": None})
|
||||
```
|
||||
|
||||
### 4.7 `POST /api/hotel/accounts/{id}/reset`
|
||||
|
||||
请求:`{"operator":"local"}` → `UPDATE hotel_hd SET is_ok=NULL WHERE id=:id`(单条,无批量接口)。
|
||||
|
||||
返回:`{"id":13888,"old_is_ok":403,"new_is_ok":null,"audit_ok":true}`;已是 NULL → 400「该账号已是可用状态」。
|
||||
|
||||
### 4.8 `GET /api/hotel/stats/account?date=`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"date":"2026-10-20","logs_available":true,"items":[
|
||||
{"hd_id":13916,"dfpid_tail":"…44102218","city":"海口","fetch_task":7,"upload_ok":7,"upload_fail":0,"fetch_empty":0,"last_event_at":"2026-10-20T17:36:15","req_count":7,"current_count":7}
|
||||
]}}
|
||||
```
|
||||
|
||||
- 只返回当日日志中出现过的账号(前端另在账号池页 merge 到全部账号行);按 `fetch_task` 降序。
|
||||
- `dfpid_tail` / `city` / 累计计数从 `hotel_hd` 批量补(`WHERE id IN (...)`,一次查询)。
|
||||
|
||||
### 4.9 `GET /api/hotel/stats/city?date=&top=`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"date":"2026-10-20","items":[
|
||||
{"city":"广州","accounts":34,"proxy_ips":1,"fetch_task":212,"upload_ok":208,"fetch_empty":2}
|
||||
]}}
|
||||
```
|
||||
|
||||
- 城市集合 = `hotel_hd.city`(非空)∪ 日志 `target_city`;`accounts` / `proxy_ips` 分别来自 `hotel_hd` 与 `proxs_list` 聚合。
|
||||
- `top` 只影响返回条数(默认全部,概览页传 10)。
|
||||
|
||||
### 4.10 `GET /api/hotel/alerts?date=`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"empty_fetch":[{"ts":"2026-10-20T17:41:20","hd_id":13888,"dfpid_tail":"…8f42ac81","target_city":"南宁","code":318,"message":"当前城市没任务啦"}],
|
||||
"stale":[{"hd_id":13901,"dfpid_tail":"…5y91u","city":"南宁","updated_at":"2026-10-19 17:30:10","hours":25.2}],
|
||||
"blocked":[{"hd_id":13702,"dfpid_tail":"…7a1f3c09","city":"广州","is_ok":401,"status_text":"登录失效"}],
|
||||
"counts":{"empty_fetch":21,"stale":2,"blocked":345}
|
||||
}}
|
||||
```
|
||||
|
||||
- `empty_fetch`:当日 `fetch_empty` 事件,按时间倒序,最多 200 条。
|
||||
- `stale`:`is_ok IS NULL AND updated_at < NOW() - INTERVAL 24 HOUR`。
|
||||
- `blocked`:`is_ok IN (403,401,418,0,6)` 或其它非 NULL 值。
|
||||
|
||||
### 4.11 `GET /api/hotel/tasks` 与 `GET /api/hotel/records`
|
||||
|
||||
- `tasks` 参数:`start`、`end`(默认今天)、`city`、`keyword`(`hotel_name` 模糊 / `unique_id` 前缀)、`page`、`size`。
|
||||
- `records` 参数同 `tasks`,`keyword` 匹配 `hotel_name` / `poi_id`。
|
||||
- **列表不返回 `json_data`,也不计算长度**:实测远程库上 `LENGTH(json_data)` 单次 **38 秒**(longtext 溢出页需跨网读取),因此 `json_size` 只在详情接口里用 Python `len()` 算。
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"total":10637,"page":1,"size":20,"items":[
|
||||
{"id":10634,"hotel_name":"MOS HOTEL·沐南酒店…","city_name":"海口市","check_in_date":"2026-10-20",
|
||||
"check_out_date":"2026-10-21","poi_id":"1576639595","create_at":"2026-10-20 17:31:02"}
|
||||
]}}
|
||||
```
|
||||
|
||||
### 4.12 `GET /api/hotel/records/{id}`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"id":10634,"hotel":{"poi_id":"1576639595","hotel_name":"…","city_name":"海口市","check_in_date":"2026-10-20","check_out_date":"2026-10-21","json_size":440340},
|
||||
"parse_ok":true,
|
||||
"rooms":[{"room_name":"茗雅大床房(清爽茶饮+飘窗茶台)","goods_name":"茗雅大床房[无早-优惠]","price":263.00,"origin_price":263.00,"inventory":8,"tag":"代理","payment":"在线付"}],
|
||||
"min_price":263.00,
|
||||
"raw_preview":"<前 100KB 字符串>"
|
||||
}}
|
||||
```
|
||||
|
||||
- 解析:`roomGoodsList.data[].goodsList[]`;字段缺失逐个兜底(`price` 取 `priceInfo.averagePrice`,`inventory` 取 `inventory` 或 `invRemain`)。
|
||||
- 若顶层含 `dayRoomShelfModel`(历史数据)→ 尝试从 `dayRoomShelfModel.match.products[]` 提取,失败则 `parse_ok=false` + `rooms=[]`,前端提示"暂不支持结构化解析"。
|
||||
- 价格 `分 → 元`:`round(v/100, 2)`;`raw_preview` 截断 100KB。
|
||||
|
||||
### 4.13 `GET /api/hotel/platform/stats?date=&city=`
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"ok":true,"date":"2026-10-20","items":[
|
||||
{"city":"广州","success":212,"reject":8,"remain":1200,"timeout":2}
|
||||
]},"cached":false}
|
||||
```
|
||||
|
||||
- 不传 `city` 时按 `meta` 的 39 城并发查询(信号量 5)并汇总;结果缓存 60s。
|
||||
- ⚠️ `summary.remain` 是各城加总,**无业务含义**(平台侧 remain 是逐城剩余量,加总会重复计数,实测 39 城加总 486255 vs 全平台 11250);页面只展示不参与计算。
|
||||
- 只调 `/getStats`,`date` 必须 `YYYY-MM-DD`(实测平台对格式敏感,非 `total` 也可)。
|
||||
- ⚠️ **平台只保留最近两天**:实测 `getStats` 对今天 / 昨天返回 `success/reject`,更早日期返回 `success: null`(`ok` 仍为 true,`data` 是空对象,2026-10-22 验证:10-21/10-22 有数,10-18~10-20 全是 null)。所以"近 N 天成功率"无法实现,页面 2 的高危口径已收敛为**昨日成功率**。
|
||||
- 平台没有某日统计时,后端把 `success/reject` 保留为 `null`(**不兜底成 0**),避免"没数据"被读成"0 条完成"。
|
||||
|
||||
### 4.13.1 `GET /api/hotel/platform/risk?date=&days=1`
|
||||
|
||||
页面 2 一次性取"所选日期各城市明细 + 昨日成功率(高危筛查)":
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"date":"2026-10-22",
|
||||
"platform_ok":true,
|
||||
"has_data":true,
|
||||
"window":{"start":"2026-10-21","end":"2026-10-21","days":1,"exclude_today":true},
|
||||
"threshold":75.0,"min_sample":5,"abnormal_min_sample":5,
|
||||
"items":[{"city":"广州","hist_success":117,"hist_reject":21,"hist_total":138,"hist_rate":84.8,
|
||||
"hist_days_with_data":1,"today_success":64,"today_reject":45,"today_rate":58.7,
|
||||
"today_abnormal":false,"risk_rate":84.8,"risk_basis":"window","high_risk":false}],
|
||||
"high_risk":[],"abnormal":[],"logs_available":true,"empty_fetch_total":0,
|
||||
"available_packages":[],"counts":{"cities":39,"high_risk":0,"abnormal":0,"empty_fetch_cities":0,"available_packages":0}
|
||||
}}
|
||||
```
|
||||
|
||||
- `date`(兼容旧参数 `end`)= 基准日(页面日期选择);`days` 默认 **1**,即参考窗口只有**昨日**。
|
||||
- `hist_*` = 参考窗口(昨日)的 success/reject/成功率,页面的「昨日成功率」列用它;`today_*` = 基准日。
|
||||
- `platform_ok` = 平台接口是否可用;`has_data` = 基准日平台是否有统计(都不同于"0 条完成")。
|
||||
- 高危 = 昨日 `(success+reject) >= min_sample` 且成功率 `< threshold`;昨日无数据的城市不判高危(`risk_basis=no_window_data`)。
|
||||
|
||||
### 4.14 `GET /api/hotel/audit?limit=50`
|
||||
|
||||
返回 `logs/audit.jsonl` 末 N 行(倒序),字段见 4.15。
|
||||
|
||||
### 4.15 审计行格式(`logs/audit.jsonl`)
|
||||
|
||||
```json
|
||||
{"ts":"2026-10-20T18:41:02","action":"change_city","hd_id":13888,"dfpid_tail":"…8f42ac81",
|
||||
"old_city":"南宁","new_city":"上海","old_prox_ip":"183.131.35.73:21432","new_prox_ip":null,
|
||||
"old_is_ok":403,"new_is_ok":403,"operator":"local","result":"ok"}
|
||||
```
|
||||
|
||||
`action` ∈ `change_city|reset_is_ok`;`result` ∈ `ok|failed`。审计**永不记录**代理账号密码与完整 dfpid。
|
||||
|
||||
### 4.16 采集端控制 `GET/POST /api/hotel/collector/*`
|
||||
|
||||
页面顶栏的「启动采集」按钮用这三个接口控制 `酒店详情.py`:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/api/hotel/collector/status` | 是否在跑、pid、来源(api/manual)、启动时间、日志尾 12 行 |
|
||||
| POST | `/api/hotel/collector/start` | 后台启动脚本;已在跑直接 409,不重复起第二个 |
|
||||
| POST | `/api/hotel/collector/stop` | `taskkill /T /F` 结束进程树,等 6 秒确认退出 |
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{
|
||||
"running":true,"pid":31040,"source":"api","started_at":"2026-10-24 18:32:38",
|
||||
"uptime_seconds":120,"dir":"…\\酒店-lkq","script":"酒店详情.py","python":"…\\python.exe",
|
||||
"log_file":"…\\logs\\collector.out.log","log_tail":["tick 0","tick 1"]
|
||||
}}
|
||||
```
|
||||
|
||||
- **防重复启动**:脚本自己在 `logs/collector.pid` 写 pid,所以控制台手动起的也能识别(`source=manual`);
|
||||
pid 的存活判断走 `OpenProcess+GetExitCodeProcess`,自己起的子进程优先用 `Popen.poll()`。
|
||||
- 启动用 `CREATE_NO_WINDOW` 隐藏窗口,stdout/stderr 追加到 `logs/collector.out.log`(页面悬浮可看尾部);
|
||||
启动后等 2 秒,脚本若立刻退出(import 报错等)直接返回 500 + 日志尾。
|
||||
- 配置项:`HOTEL_COLLECTOR_DIR` / `HOTEL_COLLECTOR_SCRIPT` / `HOTEL_COLLECTOR_PYTHON`(默认取项目根、`酒店详情.py`、当前解释器)。
|
||||
|
||||
### 4.17 `GET /api/hotel/stats/failures?date=`
|
||||
|
||||
当天"拿任务失败"(埋点 `fetch_empty`)的城市清单,供**改/加城市的下拉框过滤**:
|
||||
|
||||
```json
|
||||
{"code":0,"msg":"ok","data":{"date":"2026-10-24","logs_available":true,
|
||||
"items":[{"city":"呼和浩特","fetch_empty":2,"exception":0,"last_event_at":"2026-10-24T11:40:58"}],
|
||||
"cities":["呼和浩特"]}}
|
||||
```
|
||||
|
||||
- 数据源:`logs/run_YYYYMMDD.jsonl` 里 `event=fetch_empty` 的事件,按 `target_city || bind_city` 聚合;
|
||||
- 前端 `ChangeCityDialog` 打开时拉一次,默认把 `cities` 从下拉里剔掉,可点「显示全部」临时放开;
|
||||
- 日志读不到(`logs_available=false`)时返回空清单,不挡住正常改城市。
|
||||
|
||||
## 5. 关键 SQL(与采集脚本一一对应)
|
||||
|
||||
| 场景 | 看板 SQL | 对应脚本位置 |
|
||||
|---|---|---|
|
||||
| 账号池取数条件 | `WHERE title LIKE '%美团酒店详情%'` | `酒店详情.py:489-492`(`get_headers`) |
|
||||
| 可用池口径 | 同上 + `is_ok IS NULL` | 同上 |
|
||||
| 账号状态写入 | `UPDATE hotel_hd SET is_ok=:v WHERE id=:id`(平台只写 NULL) | `酒店详情.py:607-617`(`update_headers`) |
|
||||
| 代理回填 | `prox=:json, city=:city, mt_traceid=:t` | 同上 |
|
||||
| 城市 → 美团 cityId | `SELECT cityId FROM area_crood.area_info WHERE cityName=:c AND title LIKE '%美团%' LIMIT 1` | `酒店详情.py:635-641`(`get_city_id`) |
|
||||
| 代理池取 IP | `SELECT prox_data, city FROM project_proxy.proxs_list WHERE channel ORDER BY RAND()` | `酒店详情.py:643-648`(`get_prox`) |
|
||||
| 每城 IP 数 | `SELECT city, COUNT(*) FROM project_proxy.proxs_list WHERE channel GROUP BY city` | 同上 |
|
||||
| 任务记录 | `SELECT … FROM hotel_task WHERE created_at >= :s AND created_at < :e + INTERVAL 1 DAY` | `酒店详情.py:156-182`(insert) |
|
||||
| 采集记录 | `SELECT … LENGTH(json_data) FROM hotel_json WHERE create_at …` | `酒店详情.py:415-422`、`476-483` |
|
||||
| 健康度分布 | `SELECT SUM(is_ok IS NULL) a, SUM(is_ok=403) b, … FROM hotel_hd WHERE title LIKE '%美团酒店详情%'` | 新增(口径同 `get_headers`) |
|
||||
|
||||
复现本章所有实测数字的命令:
|
||||
|
||||
```sql
|
||||
-- HEADERS_DB
|
||||
SELECT COUNT(*), COUNT(DISTINCT dfpid), COUNT(DISTINCT city) FROM hotel_hd;
|
||||
SELECT is_ok, COUNT(*) FROM hotel_hd GROUP BY is_ok ORDER BY 2 DESC;
|
||||
SELECT SUM(city IS NULL), SUM(prox IS NULL), SUM(req_count), SUM(current_count) FROM hotel_hd;
|
||||
SELECT city, COUNT(*) FROM project_proxy.proxs_list WHERE channel GROUP BY city;
|
||||
-- MAIN_DB
|
||||
SELECT COUNT(*), COUNT(DISTINCT unique_id), COUNT(DISTINCT city_name) FROM hotel_task;
|
||||
SELECT COUNT(*), COUNT(DISTINCT poi_id) FROM hotel_json;
|
||||
```
|
||||
|
||||
## 6. 后端工程要点
|
||||
|
||||
1. **双 engine**:`MAIN_DB_URL` / `HEADERS_DB_URL` 各自 `create_async_engine(pool_pre_ping=True, pool_size=5)`;`MAIN` 只读、`HEADERS` 可写,代码层面用两个不同依赖函数区分,避免误写只读库。
|
||||
2. **手写 SQL 全部参数化**:禁止 f-string 拼值;排序字段/方向、`page/size` 走白名单映射。
|
||||
3. **日志解析器**(`hotel_logs.py`):
|
||||
- `read_events(date_range)`:按天拼路径,逐行 `json.loads`,坏行计数跳过(`skipped` 回传);
|
||||
- 缓存键 `(path, st_mtime_ns, st_size)` → 解析结果,命中直接复用(日志文件只追加,简单有效);
|
||||
- 聚合函数:`aggregate_by_hd(ids)`、`aggregate_by_city()`、`timeline(days)`,均返回 `dict`,不引入 pandas;
|
||||
- 文件不存在 → 返回空集 + `available=False`,**绝不抛 500**。
|
||||
4. **脱敏集中**:`hotel_meta.mask_dfpid()`、`hotel_meta.extract_prox_ip()` 唯一实现;所有响应经它们处理。
|
||||
5. **写操作**:单事务 + 只更新白名单列;审计在事务提交后写文件,`audit_ok` 随响应返回;文件写失败只记日志,不回滚库(已提交)。
|
||||
6. **平台代理**:`requests.Session` + `proxies={'http':'','https':''}`(直连,绕本机 VPN)+ 超时 12s + 60s 缓存 + 异常兜底成 `{"ok":false,"error":...}`。
|
||||
7. **错误处理**:全局异常处理器把 `pymysql/SQLAlchemy` 错误转成 `code=500` 的中文提示,原始堆栈只进后端日志。
|
||||
8. **无 ORM 迁移**:不引入 alembic(不建表)。
|
||||
|
||||
## 7. 前端工程要点
|
||||
|
||||
1. `vite.config.ts`:`server.port = 5175`,`proxy['/api'] → http://127.0.0.1:8011`;`build.outDir = 'dist'`。
|
||||
2. `api/index.ts`:Axios 实例(`baseURL: '/api'`,超时 15s),响应拦截器统一解包 `{code,msg,data}`,`code != 0` 抛业务错误由页面 toast。
|
||||
3. `stores/hotel.ts`:`filters`、`refreshTick`、`meta`(5 分钟本地缓存)。
|
||||
4. `composables/useAutoRefresh.ts`:15s 定时 + `document.hidden` 感知。
|
||||
5. 表格一律服务端分页/排序;`size` 变更时重置到第 1 页。
|
||||
6. 写操作成功后 `patchRow(id, patch)` 局部更新,再触发一次静默刷新。
|
||||
7. 所有颜色走 `var(--token)`;新增状态色只能加到 `composables/hotelStatus.ts`。
|
||||
8. `npm run build` 生成 `frontend/dist`,由 `start.py --static` 托管。
|
||||
|
||||
## 8. 启动与部署
|
||||
|
||||
### 8.1 环境要求
|
||||
|
||||
| 项 | 静态模式 | 开发模式 |
|
||||
|---|---|---|
|
||||
| Python | ≥ 3.10 | 同左 |
|
||||
| Node.js | 不需要 | ≥ 20.19(Vite 8;本机 v24.16 OK) |
|
||||
| 网络 | 能连 `183.6.7.91:33016`、`192.168.5.2:3307`、`ktl-001.dsfdl-henan.xyz` | 同左 |
|
||||
|
||||
### 8.2 配置 `backend/.env`
|
||||
|
||||
```ini
|
||||
MAIN_DB_URL=mysql+aiomysql://root:密码@183.6.7.91:33016/mt_hotel?charset=utf8mb4
|
||||
HEADERS_DB_URL=mysql+aiomysql://root:密码@192.168.5.2:3307/headers_project?charset=utf8mb4
|
||||
LOG_DIR=../../logs
|
||||
HOTEL_PLATFORM_BASE=http://ktl-001.dsfdl-henan.xyz/openApi
|
||||
HOTEL_PLATFORM_USER=thzn-datagram0001
|
||||
HOTEL_PLATFORM_PWD=***
|
||||
HOTEL_PLATFORM_VENDOR=mt-datagram
|
||||
CORS_ORIGINS=http://localhost:5175,http://127.0.0.1:5175
|
||||
```
|
||||
|
||||
> `LOG_DIR` 相对 `dashboard/backend` 解析:`../../logs` 指到 `酒店/logs`(与采集脚本共用)。路径必须精确到“看板能读到脚本写的文件”。
|
||||
|
||||
### 8.3 命令
|
||||
|
||||
```bash
|
||||
pip install -r backend/requirements.txt
|
||||
cd frontend && npm install && npm run build && cd .. # 仅开发机
|
||||
|
||||
python start.py --static # 生产:只起后端 8011 并托管 dist → http://localhost:8011
|
||||
python start.py # 开发:后端 8011 + 前端 5175(Vite 热更)
|
||||
python start.py --no-browser # 不自动开浏览器
|
||||
cd backend && python scripts/verify_api.py # 对账验收(服务需已启动)
|
||||
```
|
||||
|
||||
### 8.4 采集端改造
|
||||
|
||||
```bash
|
||||
# 埋点模块与脚本同目录,无需安装依赖
|
||||
python 酒店详情.py # 正常跑;事件自动追加到 logs/run_YYYYMMDD.jsonl
|
||||
```
|
||||
|
||||
### 8.5 验收脚本(全部实测通过)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python scripts/smoke.py --base http://127.0.0.1:8011 # 十个区块接口冒烟
|
||||
python scripts/verify_server.py # 一次性启停 + 跑冒烟(不依赖手工管理进程)
|
||||
python scripts/verify_api.py # 16 项 API vs 数据库/平台直查对账
|
||||
python scripts/verify_stats.py # 造当日事件验证账号/城市跑量聚合(临时 LOG_DIR)
|
||||
python scripts/verify_write.py # 改城市/重置/审计,finally 自动恢复数据
|
||||
cd .. && python scripts/verify_insight.py # 埋点静态位置检查 + fetch_task/fetch_empty 两条链路
|
||||
```
|
||||
|
||||
实测结果(2026-10-20):
|
||||
- `smoke.py`:health / meta / overview / trend / accounts / stats / alerts / platform / audit / records / spa 全绿;
|
||||
- `verify_api.py`:16 项全部一致(账号总数 348、可用池 3、403 312、401 8、封禁清单 345、合法城市 39、代理 IP 41、已绑城账号 337、今日任务 512、今日采集 1212、平台 success 1013);
|
||||
- `verify_write.py`:非法城市 400/1002、改城市后 `prox` 变 NULL、重复重置 400/1004、审计两条、数据已恢复。
|
||||
|
||||
### 8.6 SPA 静态托管与端口
|
||||
|
||||
| 模式 | 端口 | 页面来源 |
|
||||
|---|---|---|
|
||||
| `--static` | 8011 | `frontend/dist`(后端 `StaticFiles(html=True)` 挂载到 `/`,API 走 `/api/*`) |
|
||||
| 开发 | 8011 + 5175 | Vite 热更新,`/api` 由 Vite proxy 转到 8011 |
|
||||
|
||||
> 不要使用 `uvicorn --reload`:本机 reload 子进程会挑到另一个 Python 解释器(见 `06_工程经验总结.md` 第 4 条)。
|
||||
|
||||
## 9. 变更记录
|
||||
|
||||
| 版本 | 日期 | 变更 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 初版:以 `hotel_hd` 账号池为主线;确定"不新增任何表",埋点与审计走本地 JSONL;五页导航;写操作仅 `city`/`prox`/`is_ok` 三列;重置 `is_ok` 仅单条 |
|
||||
|
||||
## 10. 风险与注意事项
|
||||
|
||||
| # | 风险 | 影响 | 处置 |
|
||||
|---|---|---|---|
|
||||
| 1 | **可用池仅 2 个**(403=312) | 脚本几乎跑不出数据,看板会一直红 | 首屏红条提示;提供单条重置;但**重置不修复失效 headers**,需重新抓包 |
|
||||
| 2 | `is_ok=6` 无代码分支(14 行) | 状态含义不明 | 一律视为"不可用",灰显"未知(6)",在 01 文档登记待确认 |
|
||||
| 3 | 改到代理池没有 IP 的城市 | 现有 `run_one` 会走到 `city = self.bound_city` 而抛 `AttributeError` | 后端白名单(39 城)拦截;前端下拉只给合法城市 |
|
||||
| 4 | `南通` 有坐标(`CITY_GPS`)但无代理 | 若误开放会 100% 失败 | 白名单取"代理池 ∩ CITY_GPS",天然排除 |
|
||||
| 5 | 埋点依赖脚本改造上线 | 上线前"今日跑量"全为 0 | 页面显示"—" + 页脚提示;`logs_available` 字段显式暴露 |
|
||||
| 6 | 日志与看板必须同机(或共享目录) | 换机部署读不到日志 | `LOG_DIR` 可配置;`/api/health` 返回路径与可写性 |
|
||||
| 7 | `hotel_json.json_data` 单条 130~440KB | 全量返回会打爆响应与前端 | 列表不返回;详情只取单条并截断原始 JSON 到 100KB |
|
||||
| 8 | 双库跨实例,无分布式事务 | 库已改但审计文件写失败 | 审计在提交后写,响应 `audit_ok` 标记;不影响数据正确性 |
|
||||
| 9 | 平台 OpenAPI 依赖外网 | 平台卡片偶发失败 | 60s 缓存 + 失败降级为 `ok=false`,不阻塞主体页面 |
|
||||
| 10 | `getStats` 的 `remain` 是全平台剩余 | 易被误读为"本账号可领量" | 界面标注"平台口径",与本看板跑量分列展示 |
|
||||
| 11 | 只读库仍用 root 连接(现网现实) | 误写风险 | 代码层只发 SELECT;如后续提供只读账号,只需改 `.env` |
|
||||
| 12 | Windows 编码/路径 | 中文城市名、日志路径易出错 | 统一 UTF-8 读写;路径用 `pathlib`;`datetime` 不带时区歧义 |
|
||||
| 13 | 采集中途改城市 | 正在进行的那一条会继续用旧城市 | 改城市只影响下一次 `run_one`,页面文案已说明 |
|
||||
| 14 | 并发写同一账号 | 两处同时改城市/重置 | 事务内 `SELECT … FOR UPDATE` 锁定该行 |
|
||||
@@ -0,0 +1,169 @@
|
||||
# 05 采集端埋点需求(定稿)
|
||||
|
||||
| 版本 | 日期 | 状态 |
|
||||
|---|---|---|
|
||||
| v1.0 | 2026-10-20 | 定稿待确认 |
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
看板要回答"**每个账号今天跑了多少条**""**哪个账号/城市拿不到任务**",但现有表里没有答案:
|
||||
|
||||
- `hotel_task`(17 列)与 `hotel_json`(9 列)**都没有账号字段**,也没有 `client_id`;
|
||||
- `hotel_hd` 只有累计的 `req_count` / `current_count`,**没有日期维度**;
|
||||
- `get_one_task()` 返回 `False` 时脚本只 `print` 一行,没有任何留存。
|
||||
|
||||
而用户要求**不新增任何数据库表**,因此埋点改为**写本地 JSONL 文件**:
|
||||
|
||||
```
|
||||
酒店/logs/run_YYYYMMDD.jsonl 每行一个事件,按天分文件,只追加
|
||||
```
|
||||
|
||||
采集脚本与看板同机,看板只读解析,**写日志失败绝不影响采集主流程**。
|
||||
|
||||
## 2. 事件定义(4 类)
|
||||
|
||||
| event | 触发时机 | 语义 | 前端用途 |
|
||||
|---|---|---|---|
|
||||
| `fetch_task` | `get_one_task()` 返回了带 `data` 的任务 | 本账号领到 1 条任务 | "今日领任务数"、账号跑量、城市跑量 |
|
||||
| `fetch_empty` | `get_one_task()` 返回 `False`,或返回体 `code != 0`(如 305/306/318/319/327) | 本账号这次没领到任务 | **告警页"今日空任务"**、`拿任务 False` 提醒 |
|
||||
| `upload` | `upload_one_task()` 执行完成(拿到平台返回码) | 交任务结果(`ok=1/0`) | "今日交回成功/失败"、成功率 |
|
||||
| `exception` | `run_one` 的 `except` 分支,或响应命中 418/401 拦截 | 请求异常(解析失败、网络不给力、登录失效) | "今日异常数"、封禁线索 |
|
||||
|
||||
## 3. 字段(JSONL 每行)
|
||||
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `ts` | string | ✅ | 本地时间 ISO8601,秒精度,如 `2026-10-20T17:41:20` |
|
||||
| `event` | string | ✅ | 4 类之一 |
|
||||
| `hd_id` | int | ✅ | `hotel_hd.id` |
|
||||
| `dfpid_tail` | string | — | `hotel_hd.dfpid` 的**后 8 位**(脱敏,不写完整值) |
|
||||
| `bind_city` | string | — | 本次使用的绑定城市(`self.bound_city`) |
|
||||
| `target_city` | string | ✅ | 本次请求的目标城市(`task_city`) |
|
||||
| `city_name` | string | — | 任务返回的 `data.cityName`(如 `广州市`) |
|
||||
| `hotel_id` | string | — | `data.hotelId` |
|
||||
| `hotel_name` | string | — | `data.hotelName`(截断 60 字) |
|
||||
| `unique_id` | string | — | `data.uniqueId` |
|
||||
| `code` | int | — | 平台返回码(`upload` / `fetch_empty` 有) |
|
||||
| `ok` | int | — | 1 成功 / 0 失败 |
|
||||
| `msg` | string | — | 附加信息(异常类型 + 截断 200 字的片段) |
|
||||
|
||||
示例:
|
||||
|
||||
```json
|
||||
{"ts":"2026-10-20T17:41:20","event":"fetch_task","hd_id":13916,"dfpid_tail":"44102218","bind_city":"海口","target_city":"海口","city_name":"海口市","hotel_id":"1599855205","hotel_name":"海南华茗精选酒店","unique_id":"20251020174120001"}
|
||||
{"ts":"2026-10-20T17:41:52","event":"upload","hd_id":13916,"dfpid_tail":"44102218","target_city":"海口","code":0,"ok":1,"unique_id":"20251020174120001"}
|
||||
{"ts":"2026-10-20T17:42:03","event":"fetch_empty","hd_id":13888,"dfpid_tail":"8f42ac81","bind_city":"南宁","target_city":"南宁","code":318,"msg":"当前城市没任务啦"}
|
||||
{"ts":"2026-10-20T17:43:11","event":"exception","hd_id":13910,"dfpid_tail":"79fu0231","target_city":"青岛","code":401,"ok":0,"msg":"Unauthorized"}
|
||||
```
|
||||
|
||||
## 4. 埋点位置(`酒店/酒店详情.py`)
|
||||
|
||||
| # | 位置(当前行号) | 代码 | 埋点动作 |
|
||||
|---|---|---|---|
|
||||
| 1 | `get_headers()` L491-493 | `SELECT id,json_data,prox,city,mt_traceid FROM hotel_hd …` | **SQL 末尾追加 `dfpid` 列**;`run_one` 的解包改成 6 元组(唯一解包点) |
|
||||
| 2 | `get_prox()` L645 返回值 | `SELECT prox_data,city FROM project_proxy.proxs_list WHERE channel ORDER BY RAND()` | 不改(纯读) |
|
||||
| 3 | `run_one()` L513 `task = get_one_task(...)` 之后 | — | **`fetch_task` 或 `fetch_empty`**(核心埋点) |
|
||||
| 4 | `run_one()` L515-517 `if not task: … return -1` | 原逻辑保留 | 在 `return -1` **之前**写 `fetch_empty`(`msg="城市未匹配"`) |
|
||||
| 5 | `run_one()` L575-588 分发 `run_shelf` / `run_prepayList` | 原逻辑不动 | 不改(结果由 6/7 记录) |
|
||||
| 6 | `run_shelf()` L412 `upload_one_task(...)` 之后 | `upload_one_task(...)` | 写 `upload`(`code` 取平台返回,`ok = code==0`) |
|
||||
| 7 | `run_prepayList()` L474 `upload_one_task(...)` 之后 | 同上 | 写 `upload` |
|
||||
| 8 | `run_shelf()` L407-410 / `run_prepayList()` L468-472 | 418 / 401 提前 return | 写 `exception`(`code=418/401`) |
|
||||
| 9 | `run_one()` L589-605 `except` 分支 | 现有 `update_headers(0/403, …)` | 写 `exception`(`msg=异常类型 + 前 200 字`) |
|
||||
|
||||
**注意**:`run_shelf` / `run_prepayList` 目前拿不到 `hd_id`。实现方式:`run_one` 在解包 item 后把账号身份写到实例属性 `self.cur_hd_id` / `self.cur_dfpid` / `self.cur_target_city`,两个 `run_*` 方法用 `getattr(self, 'cur_hd_id', None)` 读取(**不修改两个方法的签名**,单独调用时也不会报错)。
|
||||
|
||||
## 5. 实现约束(硬性)
|
||||
|
||||
1. **绝不抛异常**:`hotel_insight.py` 所有函数体包 `try: … except Exception: pass`,最坏情况是"少一条日志",不允许影响采集。
|
||||
2. **不阻塞**:纯本地文件追加,单行 `open(..., 'a', encoding='utf-8')` + `f.write`,无网络、无数据库、无重试。
|
||||
3. **不改主流程分支**:埋点只做"记录",不改 `run_one` 的 `try/except` 结构、不改返回值、不改 `update_headers` 的调用顺序。
|
||||
4. **脱敏**:`dfpid` 只写后 8 位;`msg` 截断 200 字;不写 headers/token/openId/代理密码。
|
||||
5. **单行大小**:一条事件 JSON ≤ 1KB(超长字段先截断)。
|
||||
6. **编码与路径**:UTF-8;日志目录取 `os.path.join(os.path.dirname(__file__), 'logs')`,不存在则 `makedirs(exist_ok=True)`。
|
||||
7. **按天分文件**:`run_{YYYYMMDD}.jsonl`,跨零点自动换文件(每次写入按当前日期算文件名)。
|
||||
8. **不清理**:脚本不删除历史日志(保留由人工决定;按每行 ~300B、每天数千行估算,约 1MB/天)。
|
||||
9. **不新增任何数据库表**:埋点只写本地文件,不得为埋点建表或给现有表加列(唯一例外是 `get_headers()` 的 SELECT 语句把已有列 `dfpid` 读出来,不改表结构)。
|
||||
|
||||
## 6. 与看板写操作的联动
|
||||
|
||||
| 看板操作 | 对采集的影响 | 说明 |
|
||||
|---|---|---|
|
||||
| 改城市(`city=新城市`, `prox=NULL`) | **下一次** `run_one` 生效:走"有城市没 IP"分支 → 从代理池按新城市补 IP | 正在进行的这一条仍用旧城市;日志里 `bind_city` 会如实记录 |
|
||||
| 重置 `is_ok`(`NULL`) | 该账号重新进入 `get_headers()` 的取数范围 | 若 headers/token 已失效,下一次仍会 403,日志中会出现新的 `exception` |
|
||||
|
||||
> 因此看板"改城市"后如果该城市没有代理 IP,脚本会命中 `for pick in self.proxy_list` 无匹配的分支(`self.bound_city` 未赋值 → `AttributeError`)。**后端必须用合法城市白名单拦截**(`proxs_list` ∩ `CITY_GPS`,当前 39 城)。
|
||||
|
||||
## 7. `hotel_insight.py` 接口
|
||||
|
||||
```python
|
||||
# 酒店/hotel_insight.py —— 只依赖标准库
|
||||
def log_event(event: str, *, hd_id=None, dfpid=None, bind_city=None, target_city=None,
|
||||
city_name=None, hotel_id=None, hotel_name=None, unique_id=None,
|
||||
code=None, ok=None, msg=None) -> None:
|
||||
"""写一条事件到 logs/run_YYYYMMDD.jsonl;任何异常都被吞掉。"""
|
||||
|
||||
# 便捷封装(脚本里只用这三个 + exception)
|
||||
def log_fetch(hd_id, dfpid, bind_city, target_city, task: dict) -> None: ...
|
||||
def log_fetch_empty(hd_id, dfpid, bind_city, target_city, resp, note: str = "") -> None: ...
|
||||
def log_upload(hd_id, dfpid, target_city, resp: dict) -> None: ...
|
||||
def log_exception(hd_id, dfpid, target_city, exc: BaseException, code: int | None = None) -> None: ...
|
||||
|
||||
# 开关(默认开;HOTEL_INSIGHT_OFF=1 可整体关闭,便于排障)
|
||||
def enabled() -> bool: ...
|
||||
```
|
||||
|
||||
`log_fetch` 从 `task["data"]` 里安全取 `cityName / hotelId / hotelName / uniqueId`(`dict.get` 链式,缺字段就留空)。
|
||||
`log_upload` 从平台返回体取 `code`(`resp.get("code")`),`ok = 1 if code == 0 else 0`。
|
||||
|
||||
## 8. 验证方法(不需要真跑美团)
|
||||
|
||||
### 8.1 单测级:直接写事件
|
||||
|
||||
```bash
|
||||
cd 酒店/dashboard/backend
|
||||
python ../scripts/mock_events.py --hd 13916 --event fetch_task
|
||||
python ../scripts/mock_events.py --hd 13888 --event fetch_empty --code 318
|
||||
```
|
||||
|
||||
预期:`酒店/logs/run_YYYYMMDD.jsonl` 末尾出现对应行;看板"告警页"出现该条空任务;"账号池页"该账号今日领任务/空任务 +1。
|
||||
|
||||
### 8.2 集成级:两条分支都不许抛异常
|
||||
|
||||
```bash
|
||||
# 用 monkeypatch 让 get_one_task 返回 False,验证 run_one 不崩且写 fetch_empty
|
||||
python scripts/verify_insight.py --case empty
|
||||
# 让 get_one_task 返回假任务、upload 返回 code=0,验证 fetch_task + upload 两条都写
|
||||
python scripts/verify_insight.py --case ok
|
||||
```
|
||||
|
||||
`verify_insight.py` 的要点:
|
||||
|
||||
```python
|
||||
import 酒店详情 as hd # 只 import,不跑 __main__(顶层无副作用)
|
||||
obj = hd.hotel_run.__new__(hd.hotel_run) # 跳过 __init__(它要连库)
|
||||
obj.proxy_list = [(json.dumps({"http": "http://u:p@1.2.3.4:1", "https": "…"}), "南宁")]
|
||||
obj.bound_city = "南宁"
|
||||
obj.last_trace_id = None
|
||||
with mock.patch.object(hd, "get_one_task", return_value=False):
|
||||
ret = obj.run_one([(13888, "[]", None, "南宁", None)])
|
||||
assert ret == -1 # 原行为不变
|
||||
assert <日志里出现 fetch_empty>
|
||||
```
|
||||
|
||||
### 8.3 回归检查(改完必须过)
|
||||
|
||||
1. `python -c "import 酒店详情"` 无报错;
|
||||
2. `git diff`(若纳入版本管理)只含埋点新增行,`run_one` 的分支逻辑无改动;
|
||||
3. 把 `logs/` 目录临时改名后跑 `--case empty`,脚本行为与改名前一致(说明写日志失败不影响主流程);
|
||||
4. 看板 `GET /api/health` 的 `log_writable=true`。
|
||||
|
||||
## 9. 上线与回滚
|
||||
|
||||
| 步骤 | 操作 |
|
||||
|---|---|
|
||||
| 上线 | 新增 `hotel_insight.py` + 脚本 6 处埋点 + `get_headers` 追加 `dfpid` 列 + `run_one` 写入 `self.cur_hd_id/cur_dfpid/cur_target_city` + `upload_one_task` 改为 return 响应体 |
|
||||
| 冒烟 | `python scripts/verify_insight.py --case empty`、`--case ok`;再看板刷新确认数据出现 |
|
||||
| 观察 | 首日跑完后核对:日志 `fetch_task` 条数 ≈ `hotel_json` 当日新增条数(允许因失败上传而略有差异) |
|
||||
| 回滚 | 删除/重命名 `hotel_insight.py` 会让 6 处调用报 `ImportError` → **正确回滚方式是设置环境变量 `HOTEL_INSIGHT_OFF=1`**(模块内部直接 return),或撤回脚本的 6 行改动 |
|
||||
|
||||
> 由于埋点是"附加调用",任何一行出问题都应只表现为"日志少了",而不是采集停摆。上线前务必用 8.2 的两种 case 各跑一次。
|
||||
@@ -0,0 +1,105 @@
|
||||
# 06 工程经验总结
|
||||
|
||||
| 版本 | 日期 |
|
||||
|---|---|
|
||||
| v1.0 | 2026-10-20(本项目落地过程中的真实坑与结论) |
|
||||
|
||||
## 1. 远程 MySQL 上 `LENGTH(longtext)` 会拖死列表接口(38 秒)
|
||||
|
||||
**现象**:采集记录列表接口 30 秒超时。逐条计时定位到:
|
||||
|
||||
```
|
||||
SELECT id, LENGTH(json_data) FROM hotel_json ORDER BY create_at DESC LIMIT 3; -- 38.47s
|
||||
SELECT id FROM hotel_json ORDER BY create_at DESC LIMIT 3; -- 0.02s
|
||||
```
|
||||
|
||||
**原因**:`json_data` 是 longtext(单条 130~440KB),存在 InnoDB 溢出页里;`LENGTH()` 要把整条数据跨网络读回来才算长度,3 行 ≈ 1MB 走了 38 秒。
|
||||
|
||||
**结论/做法**:
|
||||
- 列表接口**绝不查长度**,只取元数据;
|
||||
- 需要大小时,在详情接口里把 `json_data` 取回后用 Python `len()` 算(详情本来就要读这条数据);
|
||||
- 任何"每行都碰大字段"的 SQL 在远程库上都要先计时验证。
|
||||
|
||||
## 2. `hotel_hd.dfpid` 全部带中文后缀,脱敏会截出"美团酒店详情"
|
||||
|
||||
**现象**:账号池显示 `dfpid_tail = "…美团酒店详情"`。
|
||||
|
||||
**原因**:实测 348 行 `dfpid` 全部形如 `u94x…uw71xu美团酒店详情`(导入时把 `title` 拼在了后面),直接取后 8 位就是中文。
|
||||
|
||||
**结论/做法**:脱敏前先剔除中文字符再取后 8 位;`dfpid` 搜索用"包含匹配"而不是前缀匹配(用户看到的是尾部 8 位)。
|
||||
|
||||
## 3. `hotel_task` 的 `hotel_id` 上有唯一键 → 它是"每酒店一条快照"
|
||||
|
||||
`UNIQUE KEY idx_hotel_id` 意味着 7025 行 = 7025 个不同酒店,不是任务流水:
|
||||
- `created_at` = 该酒店**首次**入库时间;
|
||||
- `updated_at` = 最近一次被刷新的时间(`ON DUPLICATE KEY UPDATE` 不改 `created_at`)。
|
||||
|
||||
所以"今日任务数"按 `created_at` 统计的是"今日首次出现的酒店数",页面必须标注口径,否则会与直觉不符。
|
||||
|
||||
## 4. `uvicorn --reload` 在本机不可用
|
||||
|
||||
**现象**:加 `--reload` 后子进程报 `SyntaxError: f-string: unmatched '('`。
|
||||
|
||||
**原因**:reload 的 spawn 子进程挑到了另一个 Python 解释器(`Python310\lib\multiprocessing`),与主进程 3.14 的 stdlib 混用。
|
||||
|
||||
**结论/做法**:本项目的验证脚本一律用**无 reload** 的 uvicorn,并用 `scripts/verify_server.py` 做"一次性启停 + 跑冒烟",避免手工管理进程。
|
||||
|
||||
## 5. PowerShell 回写 `.env` 会加 BOM 并毁掉中文注释
|
||||
|
||||
`(Get-Content -Raw) -replace ... | Set-Content -Encoding utf8` 在 Windows PowerShell 5.1 下写入 UTF-8 **带 BOM**,且把原有中文注释变成了乱码字节(读时按 ANSI 解码)。
|
||||
|
||||
**结论/做法**:配置文件与源码一律用文件写入工具(UTF-8 无 BOM)生成;改完用 `open(f,'rb').read()[:3] == b'\xef\xbb\xbf'` 检查一次。
|
||||
|
||||
## 6. 中文查询参数必须 URL 编码
|
||||
|
||||
`urllib.request.urlopen(".../platform/stats?city=广州")` 直接抛 `UnicodeEncodeError: 'ascii' codec`。
|
||||
|
||||
**做法**:所有拼接的中文参数用 `urllib.parse.quote()`(或 requests 的 `params=`)。
|
||||
|
||||
## 7. `HTTPException(detail=dict)` 会把 detail 再包一层
|
||||
|
||||
FastAPI 默认返回 `{"detail": {"code": 1002, "msg": "..."}}`,与文档约定的顶层 `{code,msg}` 不一致。
|
||||
|
||||
**做法**:注册 `HTTPException` / `RequestValidationError` 处理器,统一输出 `{"code","msg","data"}`;前端拦截器只认这一种结构。
|
||||
|
||||
## 8. Element Plus 表格 `row-style` 在 TS 下类型推断不出来
|
||||
|
||||
`:row-style="({ row }) => ..."` 会在 `vue-tsc` 报 `TS7031 implicit any`。
|
||||
|
||||
**做法**:在 `<script setup>` 里定义具名函数并标注入参类型(`(scope: { row: T }) => ...`),模板只传函数名。
|
||||
|
||||
## 9. 平台 `getStats` 的 `remain` 逐城相加无意义
|
||||
|
||||
实测:单城广州 `remain=12342`,39 城加总 `486255`,而全平台 `remain=11250`。因为每城的 `remain` 已是平台侧口径,不是可分割量。
|
||||
|
||||
**做法**:`summary.remain` 只展示不参与计算;概览页的"平台剩余"直接用不带 `city` 的全平台 `getStats`。
|
||||
|
||||
## 10. "写日志失败不得影响采集"要真的验证
|
||||
|
||||
`hotel_insight` 全 `try/except` 只是代码意图,必须实测:
|
||||
|
||||
```python
|
||||
insight.LOG_DIR = "Z:\\definitely-not-exist\\logs" # 无效路径
|
||||
obj.run_one(items) # 仍返回 -1,不抛异常
|
||||
```
|
||||
|
||||
该 case 已固化在 `scripts/verify_insight.py` 的 `[4]` 步骤里。
|
||||
|
||||
## 11. 写操作的验证必须"可逆 + 只看库内真实变更"
|
||||
|
||||
`verify_write.py` 的三条铁律:
|
||||
1. 只挑 `is_ok=403`(不可用)的账号做实验;
|
||||
2. `finally` 里无条件把 `city` / `prox` / `is_ok` 恢复原值;
|
||||
3. 断言直查 `hotel_hd` 的结果,而不是只看接口回包。
|
||||
|
||||
## 12. 数据源现状(2026-10-20 实测,供日后对比)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| `hotel_hd` | 348 行 / 348 唯一 dfpid,可用 3、403 312、401 8、其它 25 |
|
||||
| 代理池 | 41 条 / 39 城,`channel` 是代理到期日 |
|
||||
| `hotel_task` | 7025 行(hotel_id 唯一) |
|
||||
| `hotel_json` | 10637 行 / 3010 个 poi |
|
||||
| 平台 getStats(当日) | success 1013 / reject 201 / remain 11250 / timeout 35 |
|
||||
|
||||
> 池子长期处于"可用个位数"状态,看板首屏的健康度条就是为了让这件事每天都可见。
|
||||
@@ -0,0 +1,145 @@
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
美团酒店任务看板 — 表结构(现有表全量 DDL)
|
||||
────────────────────────────────────────────────────────────────────────────────
|
||||
⚠ 硬约束:本项目【不新增任何表、不新增任何视图、不修改任何表结构】。
|
||||
新增持久化一律走本地 JSONL 文件:
|
||||
酒店/logs/run_YYYYMMDD.jsonl 采集埋点事件(脚本写,看板读)
|
||||
酒店/logs/audit.jsonl 看板写操作审计(看板写,看板读)
|
||||
验收方法:交付前后各执行一次 SHOW TABLES,结果必须完全一致。
|
||||
────────────────────────────────────────────────────────────────────────────────
|
||||
连接信息
|
||||
HEADERS_DB 192.168.5.2:3307 headers_project(hotel_hd 可写 3 列)、project_proxy
|
||||
MAIN_DB 183.6.7.91:33016 mt_hotel、area_crood(全部只读)
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
1) headers_project.hotel_hd —— 账号池(核心表,可写 city / prox / is_ok)
|
||||
实测 347 行 / 347 唯一 dfpid / 37 个城市(另 10 行 city 为空)
|
||||
is_ok 分布:403=312, 6=14, 0=9, 401=8, 418=2, NULL=2
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
CREATE TABLE `hotel_hd` (
|
||||
`id` int NOT NULL AUTO_INCREMENT,
|
||||
`dfpid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`json_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
|
||||
`title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`channel` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`is_ok` int DEFAULT NULL,
|
||||
`req_count` int DEFAULT NULL,
|
||||
`current_count` int DEFAULT '0',
|
||||
`prox` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`mt_traceid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `dfpid` (`dfpid`) USING BTREE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=13919 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
-- 看板读的口径(必须与采集脚本 get_headers() 完全一致)
|
||||
-- SELECT ... FROM hotel_hd WHERE title LIKE '%美团酒店详情%' AND is_ok IS NULL;
|
||||
--
|
||||
-- 看板唯一的两条写语句(只碰 3 列):
|
||||
-- UPDATE hotel_hd SET city = :city, prox = NULL WHERE id = :id; -- 改城市
|
||||
-- UPDATE hotel_hd SET is_ok = NULL WHERE id = :id; -- 重置(单条)
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
2) project_proxy.proxs_list —— 代理池(只读)
|
||||
实测 41 行 / 39 个城市(福州、厦门各 2,其余 1)
|
||||
⚠ channel 列存的是"代理到期日"(如 2026-10-31、26-10-27),WHERE channel = 未过期
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
CREATE TABLE `proxs_list` (
|
||||
`index` int NOT NULL AUTO_INCREMENT,
|
||||
`city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`prox_data` json DEFAULT NULL,
|
||||
`ip_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`port` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`acount` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`pwd` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`dll` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`channel` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
PRIMARY KEY (`index`) USING BTREE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
-- 合城市白名单(看板 meta 用;结果 = 39 城,不含"南通")
|
||||
-- SELECT city, COUNT(*) AS ips FROM proxs_list WHERE channel GROUP BY city;
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
3) mt_hotel.hotel_task —— 任务信息(只读)
|
||||
实测 7025 行;⚠ hotel_id 上有 UNIQUE KEY ⇒ 一个酒店只保留一行(最新快照)
|
||||
⚠ 口径陷阱:created_at = 该酒店首次入库时间;updated_at = 最近一次被刷新时间
|
||||
所以"今日任务数"有两种读法:
|
||||
按 created_at → 今日首次出现的酒店数(默认口径,看板用这个)
|
||||
按 updated_at → 今日被刷新过的酒店数(含历史酒店)
|
||||
实测 10-20:created_at 当天 512 条
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
CREATE TABLE `hotel_task` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`hotel_id` varchar(20) NOT NULL COMMENT '酒店ID',
|
||||
`city_id` varchar(10) NOT NULL COMMENT '城市ID',
|
||||
`hotel_name` varchar(100) NOT NULL COMMENT '酒店名称',
|
||||
`hotel_address` varchar(200) DEFAULT NULL COMMENT '酒店地址',
|
||||
`city_name` varchar(50) DEFAULT NULL COMMENT '城市名称',
|
||||
`check_in_date` date NOT NULL COMMENT '入住日期',
|
||||
`check_out_date` date NOT NULL COMMENT '离店日期',
|
||||
`unique_id` varchar(100) DEFAULT NULL COMMENT '唯一标识',
|
||||
`time_left` int DEFAULT NULL COMMENT '剩余时间(秒)',
|
||||
`hotel_star` varchar(20) DEFAULT NULL COMMENT '酒店星级/档次',
|
||||
`selected_city` varchar(50) DEFAULT NULL COMMENT '选择的城市',
|
||||
`area_type` varchar(50) DEFAULT NULL COMMENT '区域类型',
|
||||
`area_name` varchar(100) DEFAULT NULL COMMENT '区域名称',
|
||||
`level` int DEFAULT '0' COMMENT '级别',
|
||||
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `idx_hotel_id` (`hotel_id`),
|
||||
KEY `idx_city_id` (`city_id`),
|
||||
KEY `idx_check_in_date` (`check_in_date`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=22256 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='酒店预订信息表';
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
4) mt_hotel.hotel_json —— 采集原始响应(只读)
|
||||
实测 10637 行 / 3010 个不同 poi_id(同一酒店多次采集);单条 130KB~440KB
|
||||
抽测最近 40 条:全部为 prepayList 响应(含 roomGoodsList),无 dayRoomShelfModel
|
||||
⚠ 列表接口绝不可 SELECT json_data,只能 SELECT LENGTH(json_data)
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
CREATE TABLE `hotel_json` (
|
||||
`id` int NOT NULL AUTO_INCREMENT,
|
||||
`json_data` longtext,
|
||||
`create_at` datetime DEFAULT CURRENT_TIMESTAMP,
|
||||
`poi_id` varchar(50) DEFAULT NULL COMMENT '对应hotelId',
|
||||
`city_id` int DEFAULT NULL COMMENT '城市ID',
|
||||
`hotel_name` varchar(255) DEFAULT NULL COMMENT '酒店名称',
|
||||
`city_name` varchar(100) DEFAULT NULL COMMENT '城市名称',
|
||||
`check_in_date` date DEFAULT NULL COMMENT '入住日期',
|
||||
`check_out_date` date DEFAULT NULL COMMENT '离店日期',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=10638 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
5) area_crood.area_info —— 城市 → 美团 cityId 字典(只读)
|
||||
实测 11214 行;脚本取数条件:cityName='X' AND title LIKE '%美团%'
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
CREATE TABLE `area_info` (
|
||||
`id` int NOT NULL AUTO_INCREMENT,
|
||||
`title` varchar(255) DEFAULT NULL,
|
||||
`cityId` varchar(255) DEFAULT NULL,
|
||||
`cityName` varchar(255) DEFAULT NULL,
|
||||
`provinceName` varchar(255) DEFAULT NULL,
|
||||
`provinceId` varchar(255) DEFAULT NULL,
|
||||
`c_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=20108 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
附:不纳入本期的表
|
||||
════════════════════════════════════════════════════════════════════════════════
|
||||
project_management.手机号 (13676 行) —— 美团账号/手机号表,本期不做页面(用户拍板)
|
||||
hotel_project / hotel_project2 / tk_hotel / tc_hotel / xc_hotel / qunar 等库
|
||||
—— 其它项目或其它平台,与美团酒店采集无关
|
||||
@@ -0,0 +1,207 @@
|
||||
STYLEKIT_STYLE_REFERENCE
|
||||
style_name: 手绘涂鸦风(彩色马克笔)
|
||||
style_slug: sketch-doodle
|
||||
style_source: 复用 C:\Users\lkq\Desktop\出行任务面板\frontend\src\styles(tokens.css / sketch.css / utilities.css)
|
||||
适用项目: 美团酒店任务看板(酒店/dashboard/frontend)
|
||||
|
||||
# Hard Prompt
|
||||
|
||||
## 什么时候用
|
||||
当你希望 AI 严格按风格规则生成本项目页面与组件时使用。它是本项目的唯一视觉基准,**与「出行任务看板」保持一致,不另起一套皮肤**。
|
||||
|
||||
## 怎么用
|
||||
- 把完整提示词复制到任意编码助手,后面追加具体页面/组件需求。
|
||||
- 生成后按 [FORBIDDEN] 与 [CHECKLIST] 逐条核对,确认没有风格漂移。
|
||||
- 需要新增颜色时:先看 tokens.css 里是否已有语义 token;确有新增,必须加到 `tokens.css` 并在此文档登记。
|
||||
|
||||
请严格遵循以下风格规则并保持一致,禁止风格漂移。
|
||||
|
||||
## 执行要求
|
||||
- 优先保证风格一致性,其次再做创意延展。
|
||||
- 遇到冲突时以 [FORBIDDEN] 为最高优先级。
|
||||
- 输出前自检:颜色、字体、边框、间距、交互是否仍属于该风格。
|
||||
|
||||
## Style Rules
|
||||
|
||||
# Sketch Doodle(手绘涂鸦风)Design System
|
||||
|
||||
> 素描纸上的手绘看板:暖米方格纸底、墨色手写线条、红/黄/蓝/绿马克笔点缀、中文手写字体标题、刻意不对称的抖动圆角、硬偏移贴纸阴影。
|
||||
|
||||
## 核心理念
|
||||
- **纸面优先**:页面是"画在纸上"的,底色暖米素描纸(带淡方格纹理),卡片是略亮的便签纸。
|
||||
- **手写感**:标题用中文手写体(ZCOOL KuaiLe),标签用黄油体(ZCOOL QingKe HuangYou),禁止衬线/黑体标题。
|
||||
- **线条不直**:边框用抖动圆角,不做绝对笔直的边线;阴影只允许硬偏移(贴纸感),禁止模糊阴影。
|
||||
- **马克笔点缀**:红 `#E0402C`(强调/告警)、黄 `#FFCF4D`(荧光笔高亮)、蓝 `#3E6CB5`(进行中)、绿 `#3C9A5F`(可用/成功),其余墨色 `#33302A`。
|
||||
- **克制动效**:卡片 hover 描边变红 + 贴纸阴影加粗 + 倾角摆正;禁止 bounce/elastic。
|
||||
|
||||
## Token 字典(全部在 `frontend/src/styles/tokens.css`,禁止散落硬编码色值)
|
||||
|
||||
### 颜色
|
||||
```
|
||||
纸底: var(--bg-page) #FBF7EC
|
||||
便签纸: var(--bg-card) #FFFDF5
|
||||
主墨: var(--text-primary) #33302A(副/弱/淡 = 62%/42%/26% 透明度)
|
||||
马克笔红: var(--accent) #E0402C(强调、当前页、告警)
|
||||
马克笔黄: var(--highlighter) #FFCF4D @52%(数字荧光笔高亮带)
|
||||
马克笔蓝: var(--marker-blue) #3E6CB5
|
||||
马克笔绿: var(--marker-green) #3C9A5F
|
||||
待定灰: var(--status-pending) #8F8877
|
||||
警示橙: #D9A424(仅用于 401/418 与超期未活动,Element Plus --el-color-warning 同步此值)
|
||||
```
|
||||
|
||||
### 边框 / 圆角 / 阴影
|
||||
```
|
||||
宽度: 细框 1px;卡片描边 1.5px(box-shadow: 0 0 0 1.5px var(--border-strong))
|
||||
圆角: 抖动值(禁止统一圆角!)
|
||||
按钮/标签: var(--radius-element) 255px 15px 225px 15px / 15px 225px 15px 255px
|
||||
卡片: var(--radius-card) 14px 5px 16px 6px / 6px 15px 5px 17px
|
||||
药丸: var(--radius-pill) 36px 10px 30px 12px / 12px 34px 10px 38px
|
||||
阴影: 硬偏移(禁模糊)
|
||||
卡片: var(--shadow-card) 3px 3px 0 rgba(51,48,42,.14)
|
||||
悬停: var(--shadow-raised) 5px 5px 0 rgba(51,48,42,.18)
|
||||
```
|
||||
|
||||
### 字体
|
||||
```
|
||||
标题/大数字: var(--font-display) 'ZCOOL KuaiLe'(@fontsource 本地打包)
|
||||
标签/数值: var(--font-mono) 'ZCOOL QingKe HuangYou'
|
||||
正文: var(--font-body) system-ui 系(表格/说明文字保持可读性)
|
||||
```
|
||||
标题规范:`h1.font-display` 自带红色波浪下划线 + 蓝色圈重点(sketch.css 的 ::before/::after);手写字体时不要再加粗;大数字 `tabular-nums`。
|
||||
|
||||
### 涂鸦专用类(`frontend/src/styles/sketch.css`,组件模板直接加类)
|
||||
```
|
||||
sketch-card 便签卡片:纸底+抖动圆角+描边+贴纸阴影+±0.6°微倾,hover 红描边摆正
|
||||
sketch-panel 大表面板:含 sketch-card 但倾角 ≤0.25°(锁屏滚动区防裁切)
|
||||
sketch-btn 描边按钮:药丸抖动角,hover 红描边+淡红底
|
||||
sketch-tag 状态标签:currentColor 细描边贴纸,-1° 微倾
|
||||
sketch-header 顶栏:底部墨色手绘波浪线(SVG 重复链)
|
||||
marker-highlight 数字荧光笔高亮:黄色斜切马克笔横带
|
||||
```
|
||||
|
||||
### 交互效果
|
||||
```
|
||||
卡片悬停: 描边红 + 阴影红 + rotate 0deg(摆正),transition 0.2s
|
||||
按钮按压: active:scale-95
|
||||
链接悬停: hover-underline(墨线 2px 下划线动画)
|
||||
输入聚焦: 红色马克笔描边(box-shadow inset 1.8px var(--accent) + 2px 红偏移)
|
||||
表格行悬停: 黄色马克笔淡描底 rgba(255,205,64,.10)
|
||||
```
|
||||
|
||||
## 本项目专用规范
|
||||
|
||||
### 1. `is_ok` 状态色(唯一定义处:`composables/hotelStatus.ts`)
|
||||
|
||||
| 状态 | 文案 | 文字色 | 行底色 | 图标 |
|
||||
|---|---|---|---|---|
|
||||
| `NULL` | 可用 | `--marker-green` | rgba(60,154,95,.08) | check-circle |
|
||||
| `403` | 封禁/风控 | `--marker-red` | rgba(224,64,44,.06) | shield-alert |
|
||||
| `401` | 登录失效 | `#D9A424` | rgba(217,164,36,.06) | key-round |
|
||||
| `418` | 网络受限 | `#D9A424` | rgba(217,164,36,.06) | wifi-off |
|
||||
| `0` | 异常 | `--marker-red` | rgba(224,64,44,.06) | alert-triangle |
|
||||
| `6` / 其它 | 未知 | `--text-weak` | rgba(51,48,42,.06) | help-circle |
|
||||
|
||||
规则:**颜色只做强调,文案 + 图标必须同时出现**(色盲可辨);红色只能用于告警与强调,不得用于普通数据。
|
||||
|
||||
### 2. 表格(本项目页面主体)
|
||||
- 表头:`--bg-muted` 底 + 12px `--font-body` + 字距 0.05em;不做斑马纹(用状态行底色区分)。
|
||||
- 单元格:13px、行高 40、数字列右对齐 + `tabular-nums`;长文本单行省略 + tooltip。
|
||||
- 表格容器用 `sketch-panel`(倾角 ≤0.25°,防锁屏滚动区裁切)。
|
||||
- ID 列左固定、操作列右固定,固定列背景必须是 `--bg-card`(不能透明,否则滚动时穿透)。
|
||||
- 空态:`sketch-card` + 手写体一行字(如"今天还没有空任务记录 👍")。
|
||||
|
||||
### 3. 图表(ECharts,主题在 `composables/chartTheme.ts`)
|
||||
- 网格线:`--border-color` 20% 虚线;坐标轴文字 12px `--font-body`。
|
||||
- 主色固定顺序:绿(可用/成功)→ 红(403/失败)→ 橙(401/418)→ 蓝 → 黄 → 灰。
|
||||
- 环形图中心放总数(手写体 24px)+ 副标题(12px 弱色)。
|
||||
- 图例统一在右上,12px;禁用默认彩色渐变与阴影。
|
||||
|
||||
### 4. 数字与单位
|
||||
- 所有金额显示 `¥263.00`(后端已从分转元),必须带两位小数 + `tabular-nums`。
|
||||
- 百分比保留 1 位小数(如 `97.6%`);为 `null` 时显示 `—`(不是 0)。
|
||||
- 计数用千分位(`1,013`)。
|
||||
|
||||
## [FORBIDDEN] 绝对禁止
|
||||
- 统一圆角(`rounded-lg` 等四角同值)——必须抖动不对称
|
||||
- 模糊阴影(`shadow-md`、`box-shadow: 0 4px 12px rgba(...)`)——只允许硬偏移
|
||||
- 衬线标题或黑体标题——标题必须中文手写体
|
||||
- 使用纯黑 `#000`、纯白 `#FFF`、冷灰色——用墨色 #33302A、纸色 #FBF7EC
|
||||
- 彩色渐变背景、玻璃拟态(glassmorphism)
|
||||
- 单侧粗边框装饰条(border-left/right accent stripe)——健康度条左侧 4px 红竖线除外(已在布局图固定)
|
||||
- bounce / elastic 缓动曲线
|
||||
- 大段正文用橙色或红色(红色仅用于强调与异常)
|
||||
- 在组件里写死颜色值(必须 `var(--token)`)
|
||||
|
||||
## [REQUIRED] 必须包含
|
||||
### 卡片必须包含
|
||||
```
|
||||
sketch-card(或 sketch-panel)+ border + var(--radius-card) + box-shadow 硬偏移 + transition
|
||||
```
|
||||
### 按钮必须包含
|
||||
```
|
||||
sketch-btn + 抖动圆角 var(--radius-element) + hover 红描边
|
||||
```
|
||||
### 输入框必须包含
|
||||
```
|
||||
border 1px + 纸底 var(--bg-card) + focus 红色马克笔描边
|
||||
```
|
||||
### 表格必须包含
|
||||
```
|
||||
sketch-panel 容器 + 固定表头 + 状态行底色 + 数字列右对齐 tabular-nums
|
||||
```
|
||||
|
||||
## [COMPARE] 错误 vs 正确对比
|
||||
|
||||
### 卡片
|
||||
[WRONG]
|
||||
```html
|
||||
<div class="rounded-xl shadow-lg bg-white p-6">
|
||||
<h3 class="text-xl font-bold">账号总数</h3>
|
||||
</div>
|
||||
```
|
||||
[CORRECT]
|
||||
```html
|
||||
<div class="sketch-card border border-[var(--border-color)] p-4">
|
||||
<p class="font-display text-3xl tabular-nums text-[var(--text-primary)]">1,013</p>
|
||||
<p class="text-xs text-[var(--text-weak)]">今日领任务</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
### 状态标签
|
||||
[WRONG]
|
||||
```html
|
||||
<span class="rounded-full bg-red-500 text-white px-3 py-1">封禁</span>
|
||||
```
|
||||
[CORRECT]
|
||||
```html
|
||||
<span class="sketch-tag font-mono text-xs"
|
||||
:style="{ color: meta.color, background: meta.bg }">
|
||||
<Icon :name="meta.icon" /> 封禁/风控
|
||||
</span>
|
||||
```
|
||||
|
||||
### 表格行
|
||||
[WRONG]
|
||||
```html
|
||||
<tr class="bg-gray-50 hover:bg-gray-100">
|
||||
```
|
||||
[CORRECT]
|
||||
```html
|
||||
<tr :style="rowTint(row.is_ok)"> <!-- 503 红 6%、401 橙 6%、可用绿 8% -->
|
||||
```
|
||||
|
||||
## [CHECKLIST] 生成后自检清单
|
||||
- [ ] 卡片/按钮是否用了 sketch-* 类(或手抄其抖动角 + 硬阴影 + 微倾)
|
||||
- [ ] 圆角是否抖动不对称(四角不同值)
|
||||
- [ ] 阴影是否硬偏移(无 blur)
|
||||
- [ ] 标题是否手写字体(font-display,不加粗)
|
||||
- [ ] 颜色是否取自 tokens(禁止硬编码色值)
|
||||
- [ ] 红色是否仅用于告警与强调
|
||||
- [ ] hover 是否有"描边变红 + 摆正"的响应
|
||||
- [ ] 表格数字列是否右对齐 + tabular-nums,金额两位小数、百分比 1 位
|
||||
- [ ] 状态行是否文案 + 图标 + 颜色三者齐全
|
||||
- [ ] 弹窗是否 append-to-body(避开 transform containing block)
|
||||
- [ ] 是否保留 prefers-reduced-motion 降级
|
||||
- [ ] 大表面板倾角是否 ≤0.25°(锁屏滚动区防裁切)
|
||||
|
||||
> CRITICAL: **如果任何一项检查不通过,必须修正后重新生成代码。**
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美团酒店任务看板</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2529
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "hotel-dashboard",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/zcool-kuaile": "^5.3.0",
|
||||
"@fontsource/zcool-qingke-huangyou": "^5.3.0",
|
||||
"@vueuse/motion": "^3.0.3",
|
||||
"axios": "^1.19.0",
|
||||
"dayjs": "^1.11.21",
|
||||
"echarts": "^6.1.0",
|
||||
"element-plus": "^2.14.4",
|
||||
"lucide-vue-next": "^1.0.0",
|
||||
"pinia": "^4.0.2",
|
||||
"vue": "^3.5.40",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0",
|
||||
"vue-tsc": "^3.3.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<!-- 手绘涂鸦风 favicon:便签纸 + 黄色高亮 + 红色手绘勾 -->
|
||||
<path d="M10 8 C 22 5, 42 6, 54 9 C 60 11, 60 14, 60 18 L 60 46 C 60 52, 56 58, 48 59 C 36 61, 18 60, 12 57 C 6 55, 5 50, 5 44 L 5 18 C 5 12, 8 9, 10 8 Z" fill="#fffdf5" stroke="#33302a" stroke-width="3.5" stroke-linejoin="round"/>
|
||||
<path d="M16 41 L 48 41" stroke="#ffcf4d" stroke-width="9" stroke-linecap="round" opacity="0.85"/>
|
||||
<path d="M20 34 C 24 40, 26 42, 30 44 C 36 38, 42 28, 46 22" fill="none" stroke="#e0402c" stroke-width="5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 617 B |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
/** 应用外壳:顶栏 + 两页切换(账号池 / 查询)+ 自动刷新(不再展示健康度条) */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import FilterBar from './components/FilterBar.vue'
|
||||
import NavTabs, { type NavKey } from './components/NavTabs.vue'
|
||||
import AccountsView from './views/AccountsView.vue'
|
||||
import QueryView from './views/QueryView.vue'
|
||||
import api from './api'
|
||||
import { useAutoRefresh } from './composables/useAutoRefresh'
|
||||
import { useHotelStore } from './stores/hotel'
|
||||
|
||||
const store = useHotelStore()
|
||||
const { autoRefresh, tick } = storeToRefs(store)
|
||||
|
||||
const activeTab = ref<NavKey>('accounts')
|
||||
const bootError = ref('')
|
||||
|
||||
const views: Record<NavKey, unknown> = {
|
||||
accounts: AccountsView,
|
||||
query: QueryView,
|
||||
}
|
||||
const currentView = computed(() => views[activeTab.value])
|
||||
|
||||
const { refreshNow } = useAutoRefresh(15000, autoRefresh, tick)
|
||||
|
||||
async function pingBackend() {
|
||||
try {
|
||||
const h = await api.health()
|
||||
bootError.value =
|
||||
h.db_main === 'up' && h.db_headers === 'up' ? '' : `数据库未连通(主库 ${h.db_main} / 抓包库 ${h.db_headers})`
|
||||
} catch (e) {
|
||||
bootError.value = `后端不可用:${(e as Error).message}`
|
||||
}
|
||||
}
|
||||
|
||||
watch(tick, pingBackend)
|
||||
|
||||
onMounted(async () => {
|
||||
await store.loadMeta()
|
||||
await pingBackend()
|
||||
|
||||
const mq = window.matchMedia('(prefers-reduced-motion: reduce)')
|
||||
const apply = () => document.documentElement.classList.toggle('reduced-motion', mq.matches)
|
||||
apply()
|
||||
mq.addEventListener('change', apply)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app">
|
||||
<FilterBar @refresh="refreshNow">
|
||||
<template #nav>
|
||||
<NavTabs v-model="activeTab" />
|
||||
</template>
|
||||
</FilterBar>
|
||||
|
||||
<div v-if="bootError" class="app__error">{{ bootError }}</div>
|
||||
|
||||
<main class="app__main">
|
||||
<KeepAlive>
|
||||
<component :is="currentView" :key="activeTab" />
|
||||
</KeepAlive>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
min-height: 560px;
|
||||
background: var(--bg-page);
|
||||
}
|
||||
.app__main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 14px 24px 18px;
|
||||
}
|
||||
.app__error {
|
||||
max-width: 1400px;
|
||||
margin: 8px auto 0;
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
color: var(--accent);
|
||||
background: rgba(224, 64, 44, 0.08);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,99 @@
|
||||
/** Axios 封装:统一解包 {code,msg,data},code!=0 或网络错误统一抛 Error(msg) */
|
||||
import axios from 'axios'
|
||||
import type {
|
||||
AccountItem,
|
||||
AccountStatsItem,
|
||||
AlertsData,
|
||||
AuditItem,
|
||||
CityFailures,
|
||||
CityStatsItem,
|
||||
CollectorStatus,
|
||||
MetaData,
|
||||
OverviewData,
|
||||
PageData,
|
||||
PlatformAllData,
|
||||
PlatformStats,
|
||||
RecordDetail,
|
||||
RecordItem,
|
||||
RiskData,
|
||||
TaskItem,
|
||||
TrendItem,
|
||||
} from './types'
|
||||
|
||||
const http = axios.create({ baseURL: '/api', timeout: 30000 })
|
||||
|
||||
http.interceptors.response.use(
|
||||
(res) => {
|
||||
const body = res.data
|
||||
if (body && typeof body.code === 'number' && body.code !== 0) {
|
||||
return Promise.reject(new Error(body.msg || '请求失败'))
|
||||
}
|
||||
return body?.data
|
||||
},
|
||||
(err) => {
|
||||
const msg = err?.response?.data?.msg || err?.message || '网络错误'
|
||||
return Promise.reject(new Error(msg))
|
||||
},
|
||||
)
|
||||
|
||||
export interface AccountQuery {
|
||||
date?: string
|
||||
city?: string
|
||||
status?: string[]
|
||||
keyword?: string
|
||||
page?: number
|
||||
size?: number
|
||||
sort?: string
|
||||
order?: 'asc' | 'desc'
|
||||
}
|
||||
|
||||
export const api = {
|
||||
health: () => http.get<never, { db_main: string; db_headers: string; log_dir: string; log_writable: boolean }>('/health'),
|
||||
meta: () => http.get<never, MetaData>('/hotel/meta'),
|
||||
overview: (date?: string) => http.get<never, OverviewData>('/hotel/overview', { params: { date } }),
|
||||
trend: (days = 7, end?: string) => http.get<never, { items: TrendItem[] }>('/hotel/trend', { params: { days, end } }),
|
||||
|
||||
accounts: (q: AccountQuery) =>
|
||||
http.get<never, PageData<AccountItem>>('/hotel/accounts', {
|
||||
params: { ...q, status: q.status?.length ? q.status : undefined },
|
||||
paramsSerializer: { indexes: null },
|
||||
}),
|
||||
changeCity: (id: number, city: string) =>
|
||||
http.post<never, { id: number; old_city: string | null; new_city: string; mode: 'add' | 'change'; prox_cleared: boolean; is_ok_reset: boolean; proxy_ips_in_city: number; audit_ok: boolean }>(
|
||||
`/hotel/accounts/${id}/city`,
|
||||
{ city },
|
||||
),
|
||||
resetAccount: (id: number) =>
|
||||
http.post<never, { id: number; old_is_ok: number | null; new_is_ok: null; audit_ok: boolean }>(`/hotel/accounts/${id}/reset`, {}),
|
||||
|
||||
statsAccount: (date?: string) => http.get<never, { date: string; logs_available: boolean; items: AccountStatsItem[] }>('/hotel/stats/account', { params: { date } }),
|
||||
statsCity: (date?: string, top?: number) =>
|
||||
http.get<never, { date: string; logs_available: boolean; items: CityStatsItem[] }>('/hotel/stats/city', { params: { date, top } }),
|
||||
|
||||
tasks: (params: { start?: string; end?: string; city?: string; keyword?: string; page?: number; size?: number }) =>
|
||||
http.get<never, PageData<TaskItem>>('/hotel/tasks', { params }),
|
||||
records: (params: { start?: string; end?: string; city?: string; keyword?: string; page?: number; size?: number }) =>
|
||||
http.get<never, PageData<RecordItem>>('/hotel/records', { params }),
|
||||
recordDetail: (id: number) => http.get<never, RecordDetail>(`/hotel/records/${id}`),
|
||||
|
||||
alerts: (date?: string) => http.get<never, AlertsData>('/hotel/alerts', { params: { date } }),
|
||||
|
||||
platformStats: (params: { date?: string; city?: string }) =>
|
||||
http.get<never, PlatformAllData | { date: string; ok: boolean; items: PlatformStats[] }>('/hotel/platform/stats', { params }),
|
||||
|
||||
/** 所选日期各城市明细 + 昨日成功率(高危筛查;平台只保留今天/昨天) */
|
||||
platformRisk: (params: { date?: string; days?: number }) =>
|
||||
http.get<never, RiskData>('/hotel/platform/risk', { params, timeout: 180000 }),
|
||||
|
||||
/** 当天拿任务失败的城市(改/加城市时要把它们藏起来) */
|
||||
cityFailures: (date?: string) => http.get<never, CityFailures>('/hotel/stats/failures', { params: { date } }),
|
||||
|
||||
/** 采集端(酒店详情.py):状态 / 启动 / 停止 */
|
||||
collectorStatus: () => http.get<never, CollectorStatus>('/hotel/collector/status'),
|
||||
startCollector: () => http.post<never, CollectorStatus>('/hotel/collector/start', {}, { timeout: 60000 }),
|
||||
stopCollector: () => http.post<never, CollectorStatus>('/hotel/collector/stop', {}, { timeout: 60000 }),
|
||||
|
||||
audit: (limit = 50) => http.get<never, { items: AuditItem[]; count: number }>('/hotel/audit', { params: { limit } }),
|
||||
}
|
||||
|
||||
export default api
|
||||
@@ -0,0 +1,351 @@
|
||||
/** 接口数据类型(与 backend/app/routers 的响应一一对应) */
|
||||
|
||||
export interface ApiEnvelope<T> {
|
||||
code: number
|
||||
msg: string
|
||||
data: T
|
||||
}
|
||||
|
||||
export interface MetaCity {
|
||||
city: string
|
||||
proxy_ips: number
|
||||
accounts: number
|
||||
city_id: string | null
|
||||
legal: boolean
|
||||
}
|
||||
|
||||
export interface IsOkMeta {
|
||||
text: string
|
||||
tone: 'ok' | 'danger' | 'warn' | 'muted'
|
||||
}
|
||||
|
||||
export interface MetaData {
|
||||
cities: MetaCity[]
|
||||
legal_cities: string[]
|
||||
is_ok_dict: Record<string, IsOkMeta>
|
||||
platform_available: boolean
|
||||
}
|
||||
|
||||
export interface PoolStats {
|
||||
total: number
|
||||
available: number
|
||||
s403: number
|
||||
s401: number
|
||||
s418: number
|
||||
s0: number
|
||||
s6: number
|
||||
other: number
|
||||
others_all: number
|
||||
available_rate: number | null
|
||||
}
|
||||
|
||||
export interface TodayAgg {
|
||||
fetch_task: number
|
||||
upload_ok: number
|
||||
upload_fail: number
|
||||
fetch_empty: number
|
||||
exception: number
|
||||
success_rate: number | null
|
||||
active_accounts: number
|
||||
last_event_at: string | null
|
||||
}
|
||||
|
||||
export interface PlatformStats {
|
||||
ok: boolean
|
||||
date: string
|
||||
city?: string | null
|
||||
success?: number | null
|
||||
reject?: number | null
|
||||
remain?: number | null
|
||||
timeout?: number | null
|
||||
cancel?: number | null
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
export interface OverviewData {
|
||||
date: string
|
||||
pool: PoolStats
|
||||
today: TodayAgg
|
||||
logs_available: boolean
|
||||
db_today: { hotel_task: number; hotel_json: number }
|
||||
platform: PlatformStats
|
||||
}
|
||||
|
||||
export interface TrendItem {
|
||||
date: string
|
||||
fetch_task: number
|
||||
upload_ok: number
|
||||
fetch_empty: number
|
||||
logs: boolean
|
||||
}
|
||||
|
||||
export interface AccountToday {
|
||||
fetch_task: number
|
||||
upload_ok: number
|
||||
upload_fail: number
|
||||
fetch_empty: number
|
||||
}
|
||||
|
||||
export interface AccountItem {
|
||||
// ── hotel_hd 原始列(页面 1 直接展示)──
|
||||
id: number
|
||||
is_ok: number | null
|
||||
req_count: number
|
||||
current_count: number
|
||||
prox_raw: string | null
|
||||
city: string | null
|
||||
mt_traceid: string | null
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
// ── 辅助字段 ──
|
||||
dfpid_tail: string | null
|
||||
has_prox: boolean
|
||||
prox_ip: string | null
|
||||
status_text: string
|
||||
status_tone: 'ok' | 'danger' | 'warn' | 'muted'
|
||||
today: AccountToday
|
||||
ip: string | null
|
||||
channel: string | null
|
||||
}
|
||||
|
||||
export interface PageData<T> {
|
||||
total: number
|
||||
page: number
|
||||
size: number
|
||||
items: T[]
|
||||
logs_available?: boolean
|
||||
date?: string
|
||||
}
|
||||
|
||||
export interface AccountStatsItem {
|
||||
hd_id: number
|
||||
dfpid_tail: string | null
|
||||
city: string | null
|
||||
fetch_task: number
|
||||
upload_ok: number
|
||||
upload_fail: number
|
||||
fetch_empty: number
|
||||
exception: number
|
||||
last_event_at: string | null
|
||||
req_count: number
|
||||
current_count: number
|
||||
}
|
||||
|
||||
export interface CityStatsItem {
|
||||
city: string
|
||||
accounts: number
|
||||
proxy_ips: number
|
||||
fetch_task: number
|
||||
upload_ok: number
|
||||
upload_fail: number
|
||||
fetch_empty: number
|
||||
exception: number
|
||||
last_event_at: string | null
|
||||
}
|
||||
|
||||
export interface TaskItem {
|
||||
id: number
|
||||
hotel_id: string
|
||||
city_id: string
|
||||
hotel_name: string
|
||||
city_name: string | null
|
||||
check_in_date: string | null
|
||||
check_out_date: string | null
|
||||
unique_id: string | null
|
||||
hotel_star: string | null
|
||||
selected_city: string | null
|
||||
area_type: string | null
|
||||
area_name: string | null
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface RecordItem {
|
||||
id: number
|
||||
poi_id: string | null
|
||||
city_id: number | null
|
||||
hotel_name: string | null
|
||||
city_name: string | null
|
||||
check_in_date: string | null
|
||||
check_out_date: string | null
|
||||
create_at: string | null
|
||||
}
|
||||
|
||||
export interface RoomItem {
|
||||
room_name: string
|
||||
goods_name: string
|
||||
price: number | null
|
||||
origin_price: number | null
|
||||
inventory: number | null
|
||||
tag: string | null
|
||||
payment: string | null
|
||||
goods_id: number | null
|
||||
promotion: string | null
|
||||
}
|
||||
|
||||
export interface RecordDetail {
|
||||
id: number
|
||||
hotel: {
|
||||
poi_id: string | null
|
||||
city_id: number | null
|
||||
hotel_name: string | null
|
||||
city_name: string | null
|
||||
check_in_date: string | null
|
||||
check_out_date: string | null
|
||||
create_at: string | null
|
||||
json_size: number
|
||||
}
|
||||
parse_ok: boolean
|
||||
structure: string | null
|
||||
error: string | null
|
||||
rooms: RoomItem[]
|
||||
min_price: number | null
|
||||
raw_preview: string
|
||||
raw_truncated: boolean
|
||||
}
|
||||
|
||||
export interface EmptyFetchItem {
|
||||
ts: string | null
|
||||
hd_id: number | null
|
||||
dfpid_tail: string | null
|
||||
bind_city: string | null
|
||||
target_city: string | null
|
||||
code: number | null
|
||||
message: string | null
|
||||
}
|
||||
|
||||
export interface StaleAccount {
|
||||
hd_id: number
|
||||
dfpid_tail: string | null
|
||||
city: string | null
|
||||
updated_at: string | null
|
||||
hours: number
|
||||
}
|
||||
|
||||
export interface BlockedAccount {
|
||||
hd_id: number
|
||||
dfpid_tail: string | null
|
||||
city: string | null
|
||||
is_ok: number | null
|
||||
status_text: string
|
||||
status_tone: 'ok' | 'danger' | 'warn' | 'muted'
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface AlertsData {
|
||||
date: string
|
||||
logs_available: boolean
|
||||
empty_fetch: EmptyFetchItem[]
|
||||
stale: StaleAccount[]
|
||||
blocked: BlockedAccount[]
|
||||
counts: { empty_fetch: number; stale: number; blocked: number }
|
||||
}
|
||||
|
||||
export interface PlatformCityItem {
|
||||
city: string
|
||||
success: number | null
|
||||
reject: number | null
|
||||
remain: number | null
|
||||
timeout: number | null
|
||||
ok?: boolean
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
/** /api/hotel/platform/risk 的单城结果:所选日(today_*)+ 昨日(hist_*) */
|
||||
export interface RiskItem {
|
||||
city: string
|
||||
hist_success: number
|
||||
hist_reject: number
|
||||
hist_total: number
|
||||
hist_rate: number | null
|
||||
hist_days_with_data: number
|
||||
today_success: number | null
|
||||
today_reject: number | null
|
||||
today_rate: number | null
|
||||
today_remain: number | null
|
||||
today_timeout: number | null
|
||||
today_total: number
|
||||
today_abnormal: boolean
|
||||
empty_fetch_count: number
|
||||
risk_rate: number | null
|
||||
risk_basis: 'window' | 'no_window_data'
|
||||
high_risk: boolean
|
||||
}
|
||||
|
||||
/** 可用账号(is_ok IS NULL),用于计算手上包的剩余产能 */
|
||||
export interface AvailablePackage {
|
||||
id: number
|
||||
city: string | null
|
||||
current_count: number
|
||||
}
|
||||
|
||||
export interface RiskData {
|
||||
/** 所选日期(后端实际查询的基准日) */
|
||||
date: string
|
||||
/** 平台接口是否可用(与"0 条完成"区分) */
|
||||
platform_ok: boolean
|
||||
/** 该日期平台是否有统计(平台只保留今天/昨天,更早日期为 false) */
|
||||
has_data: boolean
|
||||
/** 参考窗口:days=1 → start=end=昨日 */
|
||||
window: { start: string; end: string; days: number; exclude_today: boolean }
|
||||
threshold: number
|
||||
min_sample: number
|
||||
abnormal_min_sample: number
|
||||
high_risk: RiskItem[]
|
||||
abnormal: RiskItem[]
|
||||
items: RiskItem[]
|
||||
logs_available: boolean
|
||||
empty_fetch_total: number
|
||||
available_packages: AvailablePackage[]
|
||||
counts: {
|
||||
cities: number
|
||||
high_risk: number
|
||||
abnormal: number
|
||||
empty_fetch_cities: number
|
||||
available_packages: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface PlatformAllData {
|
||||
date: string
|
||||
ok: boolean
|
||||
items: PlatformCityItem[]
|
||||
summary: { success: number | null; reject: number | null; remain: number | null; timeout: number | null; cities: number }
|
||||
failed: string[]
|
||||
}
|
||||
|
||||
/** /api/hotel/collector/status —— 采集端(酒店详情.py)运行状态 */
|
||||
export interface CollectorStatus {
|
||||
running: boolean
|
||||
pid: number | null
|
||||
/** api=看板启动的,manual=控制台启动的(靠 pid 文件识别) */
|
||||
source: 'api' | 'manual' | null
|
||||
started_at: string | null
|
||||
uptime_seconds: number | null
|
||||
dir: string
|
||||
script: string
|
||||
python: string
|
||||
log_file: string
|
||||
log_tail: string[]
|
||||
}
|
||||
|
||||
/** /api/hotel/stats/failures —— 当天拿任务失败(fetch_empty)的城市 */
|
||||
export interface CityFailures {
|
||||
date: string
|
||||
logs_available: boolean
|
||||
items: { city: string; fetch_empty: number; exception: number; last_event_at: string | null }[]
|
||||
cities: string[]
|
||||
}
|
||||
|
||||
export interface AuditItem {
|
||||
ts: string
|
||||
action: string
|
||||
hd_id: number
|
||||
dfpid_tail: string | null
|
||||
old_city: string | null
|
||||
new_city: string | null
|
||||
old_is_ok: number | null
|
||||
new_is_ok: number | null
|
||||
operator: string | null
|
||||
result: string
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
/** ECharts 封装:自动 resize / 统一主题 / 空态 / 平滑过渡 */
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import * as echarts from 'echarts'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
const props = withDefaults(defineProps<{ option: EChartsOption; height?: string; empty?: boolean }>(), {
|
||||
height: '300px',
|
||||
empty: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ chartClick: [params: { name?: string }] }>()
|
||||
|
||||
const el = ref<HTMLElement>()
|
||||
let chart: echarts.ECharts | null = null
|
||||
let ro: ResizeObserver | null = null
|
||||
|
||||
function render() {
|
||||
if (!chart) return
|
||||
// merge 模式(默认):数据刷新时新旧 diff 平滑过渡(柱生长/收缩)
|
||||
chart.setOption(props.option, { notMerge: false })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (!el.value) return
|
||||
chart = echarts.init(el.value)
|
||||
ro = new ResizeObserver(() => chart?.resize())
|
||||
ro.observe(el.value)
|
||||
chart.on('click', (params: { name?: string }) => emit('chartClick', { name: params.name }))
|
||||
render()
|
||||
})
|
||||
|
||||
watch(() => props.option, render, { deep: true })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
ro?.disconnect()
|
||||
chart?.dispose()
|
||||
chart = null
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative w-full">
|
||||
<div ref="el" class="w-full transition-opacity duration-300" :class="empty ? 'opacity-0' : 'opacity-100'" :style="{ height }" />
|
||||
<div v-if="empty" class="absolute inset-0 flex items-center justify-center text-sm text-[var(--text-weak)]">
|
||||
暂无数据
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,233 @@
|
||||
<script setup lang="ts">
|
||||
/** 改绑定城市弹窗:选择合法城市 → 二次确认(明确提示会清空代理) */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import api from '../api'
|
||||
import type { AccountItem } from '../api/types'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
account: AccountItem | null
|
||||
legalCities: string[]
|
||||
ipCount: (city: string) => number
|
||||
}>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [boolean]; submitted: [number] }>()
|
||||
|
||||
const city = ref('')
|
||||
const submitting = ref(false)
|
||||
/** 今日拿任务失败的城市:默认不展示(绑过去也领不到任务),可手动展开 */
|
||||
const failedCities = ref<string[]>([])
|
||||
const showFailed = ref(false)
|
||||
const failuresLoaded = ref(false)
|
||||
|
||||
/** 新包(is_ok=NULL 且未绑城市)→ 添加城市;否则是改城市 */
|
||||
const isAdd = computed(() => !!props.account && props.account.is_ok === null && !props.account.city)
|
||||
const dialogTitle = computed(() => (isAdd.value ? '添加城市(新包)' : '改绑定城市'))
|
||||
const confirmText = computed(() => (isAdd.value ? '确认添加' : '确认修改'))
|
||||
|
||||
async function loadFailures() {
|
||||
try {
|
||||
const res = await api.cityFailures()
|
||||
failedCities.value = res.cities ?? []
|
||||
} catch {
|
||||
failedCities.value = [] // 日志读不到就当没有失败城市,不挡住正常操作
|
||||
} finally {
|
||||
failuresLoaded.value = true
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
city.value = ''
|
||||
showFailed.value = false
|
||||
void loadFailures()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const currentIp = computed(() => (city.value ? props.ipCount(city.value) : null))
|
||||
const sameCity = computed(() => !!city.value && city.value === props.account?.city)
|
||||
const disabled = computed(() => !city.value || submitting.value || sameCity.value || (currentIp.value ?? 0) <= 0)
|
||||
|
||||
const sortedCities = computed(() =>
|
||||
[...props.legalCities].sort((a, b) => {
|
||||
const diff = props.ipCount(b) - props.ipCount(a)
|
||||
return diff !== 0 ? diff : a.localeCompare(b, 'zh-CN')
|
||||
}),
|
||||
)
|
||||
|
||||
const failedSet = computed(() => new Set(failedCities.value))
|
||||
/** 下拉里实际可选的城:默认剔除"今日拿任务失败"的城市 */
|
||||
const selectableCities = computed(() =>
|
||||
showFailed.value ? sortedCities.value : sortedCities.value.filter((c) => !failedSet.value.has(c)),
|
||||
)
|
||||
const hiddenCount = computed(() => sortedCities.value.filter((c) => failedSet.value.has(c)).length)
|
||||
const allHidden = computed(() => failuresLoaded.value && sortedCities.value.length > 0 && selectableCities.value.length === 0)
|
||||
|
||||
async function submit() {
|
||||
if (!props.account || disabled.value) return
|
||||
submitting.value = true
|
||||
try {
|
||||
const res = await api.changeCity(props.account.id, city.value)
|
||||
const verb = res.mode === 'add' ? '已添加城市' : '城市已改为'
|
||||
ElMessage.success(`#${res.id} ${verb} ${res.new_city},代理已清空(该城 ${res.proxy_ips_in_city} 个 IP)`)
|
||||
emit('submitted', res.id)
|
||||
emit('update:modelValue', false)
|
||||
} catch (e) {
|
||||
ElMessage.error((e as Error).message)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
:title="dialogTitle"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
append-to-body
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<div class="dlg">
|
||||
<div class="dlg__row">
|
||||
<span class="dlg__k">账号</span>
|
||||
<span class="dlg__v">#{{ account?.id }} <code>{{ account?.dfpid_tail }}</code></span>
|
||||
</div>
|
||||
<div class="dlg__row">
|
||||
<span class="dlg__k">当前城市</span>
|
||||
<span class="dlg__v">{{ account?.city || '未绑定' }}</span>
|
||||
</div>
|
||||
<div class="dlg__row">
|
||||
<span class="dlg__k">当前代理</span>
|
||||
<span class="dlg__v">{{ account?.has_prox ? account?.prox_ip || '有' : '无' }}</span>
|
||||
</div>
|
||||
<div class="dlg__row">
|
||||
<span class="dlg__k">当前次数</span>
|
||||
<span class="dlg__v">req_count {{ account?.req_count ?? 0 }} / current_count {{ account?.current_count ?? 0 }}</span>
|
||||
</div>
|
||||
<div class="dlg__row">
|
||||
<span class="dlg__k">新城市</span>
|
||||
<select v-model="city" class="dlg__select" :disabled="allHidden">
|
||||
<option value="" disabled>
|
||||
{{ allHidden ? '今日所有城市都拿任务失败,暂无可选城市' : '请选择(仅列代理池已有 IP 的城市)' }}
|
||||
</option>
|
||||
<option v-for="c in selectableCities" :key="c" :value="c">{{ c }}({{ ipCount(c) }} 个 IP)</option>
|
||||
</select>
|
||||
</div>
|
||||
<p v-if="hiddenCount > 0" class="dlg__hint dlg__hint--info">
|
||||
今日拿任务失败的 {{ hiddenCount }} 个城市{{ showFailed ? '(已显示)' : '已隐藏' }},当前
|
||||
{{ selectableCities.length }} 个可选
|
||||
<button class="dlg__link" type="button" @click="showFailed = !showFailed">
|
||||
{{ showFailed ? '隐藏它们' : '显示全部' }}
|
||||
</button>
|
||||
</p>
|
||||
<p v-if="allHidden" class="dlg__hint dlg__hint--warn">
|
||||
今日所有城市都拿任务失败,绑过去也领不到任务;可以先在任务平台确认城市是否恢复了。
|
||||
</p>
|
||||
<p v-if="sameCity" class="dlg__hint dlg__hint--warn">与当前城市相同,无需修改</p>
|
||||
<p v-else-if="city && (currentIp ?? 0) <= 0" class="dlg__hint dlg__hint--warn">该城市暂无可用代理,不能切换</p>
|
||||
<p v-if="isAdd" class="dlg__warn">⚠ 该包还没有绑定城市。提交后会把它设为所选城市、代理置空(prox = NULL),采集脚本下次运行即可按该城市领取任务并自动补同城 IP。</p>
|
||||
<p v-else class="dlg__warn">⚠ 提交后会把该账号代理置空(prox = NULL)、并把状态重置为可用(is_ok = NULL);current_count 保留不变。采集脚本下次运行时会按新城市自动补同城 IP。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<button class="btn" type="button" @click="emit('update:modelValue', false)">取消</button>
|
||||
<button class="btn btn--primary" type="button" :disabled="disabled" @click="submit">
|
||||
{{ submitting ? '提交中…' : confirmText }}
|
||||
</button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dlg__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
.dlg__k {
|
||||
width: 84px;
|
||||
color: var(--text-weak);
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
flex: none;
|
||||
}
|
||||
.dlg__v {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.dlg__v code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.dlg__select {
|
||||
flex: 1;
|
||||
height: 32px;
|
||||
padding: 0 8px;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.dlg__select:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.dlg__hint {
|
||||
margin: 6px 0 0 94px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.dlg__hint--warn {
|
||||
color: #d9a424;
|
||||
}
|
||||
.dlg__hint--info {
|
||||
margin-left: 0;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.dlg__link {
|
||||
margin-left: 6px;
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
color: var(--accent);
|
||||
background: none;
|
||||
border: none;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dlg__warn {
|
||||
margin: 12px 0 0;
|
||||
padding: 8px 10px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-secondary);
|
||||
background: var(--accent-bg);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
.btn {
|
||||
margin-left: 8px;
|
||||
height: 32px;
|
||||
padding: 0 14px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn--primary {
|
||||
color: #fff;
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,139 @@
|
||||
<script setup lang="ts">
|
||||
/** 采集端(酒店详情.py)启动 / 停止按钮:轮询状态 + 二次确认 + 悬浮看日志尾 */
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import api from '../api'
|
||||
import type { CollectorStatus } from '../api/types'
|
||||
|
||||
const status = ref<CollectorStatus | null>(null)
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
let timer: number | null = null
|
||||
|
||||
const running = computed(() => status.value?.running ?? false)
|
||||
const label = computed(() => (running.value ? '停止采集' : '启动采集'))
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
status.value = await api.collectorStatus()
|
||||
error.value = ''
|
||||
} catch (e) {
|
||||
error.value = (e as Error).message
|
||||
}
|
||||
}
|
||||
|
||||
const tip = computed(() => {
|
||||
const s = status.value
|
||||
if (!s) return error.value || '正在读取采集状态…'
|
||||
if (!s.running) return `酒店详情.py 未运行${error.value ? '(状态读取失败:' + error.value + ')' : ''}`
|
||||
const up = s.uptime_seconds ?? 0
|
||||
const h = Math.floor(up / 3600)
|
||||
const m = Math.floor((up % 3600) / 60)
|
||||
const who = s.source === 'manual' ? '控制台启动' : '看板启动'
|
||||
const tailText = (s.log_tail ?? []).slice(-6).join('\n')
|
||||
return `pid ${s.pid} · 已运行 ${h}h${m}m · ${who}\n${s.dir}\\${s.script}\n\n最后日志:\n${tailText || '(暂无)'}`
|
||||
})
|
||||
|
||||
async function toggle() {
|
||||
if (busy.value) return
|
||||
const isRunning = running.value
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
isRunning
|
||||
? `将停止采集进程(pid ${status.value?.pid}),采集会中断。确定停止?`
|
||||
: '将在后台启动 酒店详情.py(窗口隐藏,输出写入 logs/collector.out.log)。确定启动?',
|
||||
isRunning ? '停止采集' : '启动采集',
|
||||
{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
const next = isRunning ? await api.stopCollector() : await api.startCollector()
|
||||
status.value = next
|
||||
ElMessage.success(isRunning ? '采集已停止' : `采集已启动(pid ${next.pid})`)
|
||||
} catch (e) {
|
||||
ElMessage.error((e as Error).message)
|
||||
await refresh()
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void refresh()
|
||||
timer = window.setInterval(() => {
|
||||
if (!document.hidden) void refresh()
|
||||
}, 10000)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
if (timer !== null) window.clearInterval(timer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
class="collector"
|
||||
:class="{ 'collector--on': running }"
|
||||
type="button"
|
||||
:disabled="busy"
|
||||
:title="tip"
|
||||
@click="toggle"
|
||||
>
|
||||
<i class="collector__dot" />
|
||||
{{ busy ? '处理中…' : label }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.collector {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
transition: transform 0.12s, box-shadow 0.2s, color 0.15s, border-color 0.15s;
|
||||
}
|
||||
.collector:hover {
|
||||
box-shadow: 2px 2px 0 rgba(51, 48, 42, 0.16);
|
||||
}
|
||||
.collector:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
.collector:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: progress;
|
||||
}
|
||||
.collector__dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-faint);
|
||||
}
|
||||
.collector--on {
|
||||
color: var(--marker-green);
|
||||
border-color: var(--marker-green);
|
||||
}
|
||||
.collector--on .collector__dot {
|
||||
background: var(--marker-green);
|
||||
animation: collector-pulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
@keyframes collector-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,99 @@
|
||||
<script setup lang="ts">
|
||||
/** 顶栏:标题 + 导航 + 自动刷新开关 + 刷新按钮 + 实时时钟(日期等筛选放到具体页面内) */
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import CollectorButton from './CollectorButton.vue'
|
||||
import { useHotelStore } from '../stores/hotel'
|
||||
|
||||
const emit = defineEmits<{ refresh: [] }>()
|
||||
const store = useHotelStore()
|
||||
const { autoRefresh } = storeToRefs(store)
|
||||
|
||||
const now = ref('')
|
||||
let timer: number | null = null
|
||||
const clock = () => {
|
||||
const d = new Date()
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
now.value = `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
clock()
|
||||
timer = window.setInterval(clock, 1000)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
if (timer !== null) window.clearInterval(timer)
|
||||
})
|
||||
|
||||
const refreshLabel = computed(() => (autoRefresh.value ? '⟳ 自动 15s' : '⟳ 已暂停'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="bar">
|
||||
<div class="bar__row">
|
||||
<h1 class="bar__title">美团酒店任务看板</h1>
|
||||
<slot name="nav" />
|
||||
<div class="bar__spacer" />
|
||||
<CollectorButton />
|
||||
<button class="bar__btn" type="button" :class="{ 'bar__btn--off': !autoRefresh }" @click="autoRefresh = !autoRefresh">
|
||||
{{ refreshLabel }}
|
||||
</button>
|
||||
<button class="bar__btn" type="button" @click="emit('refresh')">刷新</button>
|
||||
<span class="bar__clock">{{ now }}</span>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.bar {
|
||||
border-bottom: 2px solid var(--border-strong);
|
||||
background: var(--bg-page);
|
||||
}
|
||||
.bar__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 14px 24px;
|
||||
}
|
||||
.bar__title {
|
||||
font-family: var(--font-display);
|
||||
font-size: 25px;
|
||||
line-height: 1.2;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.bar__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.bar__btn {
|
||||
height: 32px;
|
||||
padding: 0 14px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: var(--accent);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
transition: transform 0.12s, box-shadow 0.2s;
|
||||
}
|
||||
.bar__btn:hover {
|
||||
box-shadow: 2px 2px 0 rgba(224, 64, 44, 0.18);
|
||||
}
|
||||
.bar__btn:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
.bar__btn--off {
|
||||
color: var(--text-weak);
|
||||
border-color: var(--border-color);
|
||||
}
|
||||
.bar__clock {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 14px;
|
||||
color: var(--text-secondary);
|
||||
min-width: 70px;
|
||||
text-align: right;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
/** KPI 卡:数值 + 副标题,可点击下钻 */
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
value: string | number
|
||||
sub?: string
|
||||
tone?: 'default' | 'ok' | 'danger' | 'warn'
|
||||
clickable?: boolean
|
||||
}>(),
|
||||
{ sub: '', tone: 'default', clickable: false },
|
||||
)
|
||||
const emit = defineEmits<{ click: [] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kpi" :class="[`kpi--${tone}`, { 'kpi--clickable': clickable }]" @click="clickable && emit('click')">
|
||||
<div class="kpi__value">{{ value }}</div>
|
||||
<div class="kpi__label">{{ label }}</div>
|
||||
<div v-if="sub" class="kpi__sub">{{ sub }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.kpi {
|
||||
padding: 12px 14px;
|
||||
background: var(--bg-card);
|
||||
border: 1.5px solid var(--border-strong);
|
||||
border-radius: var(--radius-card);
|
||||
box-shadow: var(--shadow-card);
|
||||
transition: box-shadow 0.2s, transform 0.2s;
|
||||
}
|
||||
.kpi--clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
.kpi--clickable:hover {
|
||||
box-shadow: var(--shadow-raised);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.kpi__value {
|
||||
font-family: var(--font-display);
|
||||
font-size: 28px;
|
||||
line-height: 1.15;
|
||||
color: var(--text-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.kpi--ok .kpi__value {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.kpi--danger .kpi__value {
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.kpi--warn .kpi__value {
|
||||
color: #d9a424;
|
||||
}
|
||||
.kpi__label {
|
||||
margin-top: 2px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.kpi__sub {
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/** 入场动画容器:上滑淡入 + 弹簧果冻(错峰由 delay 控制) */
|
||||
import { enterBlock } from '../composables/useMotion'
|
||||
|
||||
withDefaults(defineProps<{ delay?: number }>(), { delay: 0 })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Motion v-bind="enterBlock(delay)">
|
||||
<slot />
|
||||
</Motion>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
<script setup lang="ts">
|
||||
/** 两个页签:账号池(hotel_hd 前 10 条)/ 查询(平台 getStats,参考 查询.py) */
|
||||
export type NavKey = 'accounts' | 'query'
|
||||
|
||||
const props = defineProps<{ modelValue: NavKey }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [NavKey] }>()
|
||||
|
||||
const tabs: { key: NavKey; label: string }[] = [
|
||||
{ key: 'accounts', label: '账号池' },
|
||||
{ key: 'query', label: '查询' },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="nav">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
class="nav__item"
|
||||
:class="{ 'nav__item--active': props.modelValue === tab.key }"
|
||||
type="button"
|
||||
@click="emit('update:modelValue', tab.key)"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.nav {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
align-items: flex-end;
|
||||
}
|
||||
.nav__item {
|
||||
position: relative;
|
||||
padding: 4px 2px 6px;
|
||||
font-family: var(--font-display);
|
||||
font-size: 17px;
|
||||
color: var(--text-secondary);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: color 0.18s;
|
||||
}
|
||||
.nav__item:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.nav__item--active {
|
||||
color: var(--accent);
|
||||
}
|
||||
.nav__item--active::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -2px;
|
||||
right: -2px;
|
||||
bottom: 0;
|
||||
height: 2px;
|
||||
background: var(--accent);
|
||||
border-radius: 2px;
|
||||
transform: rotate(-0.6deg);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
/** is_ok 状态标签:颜色 + 图标 + 文案三通道(色盲可辨) */
|
||||
import { computed } from 'vue'
|
||||
import type { Tone } from '../composables/hotelStatus'
|
||||
import { statusStyle } from '../composables/hotelStatus'
|
||||
|
||||
const props = defineProps<{ isOk: number | null; text: string; tone: Tone }>()
|
||||
const style = computed(() => statusStyle(props.isOk, props.text, props.tone))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="tag" :style="{ color: style.color, background: style.bg, borderColor: style.color }">
|
||||
<span class="tag__icon">{{ style.icon }}</span>{{ style.text }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 1px 7px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: var(--radius-pill);
|
||||
transform: rotate(-0.8deg);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tag__icon {
|
||||
font-size: 11px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,28 @@
|
||||
/** ECharts 统一主题 token —— 编辑杂志风:纯单色灰阶、细线、无装饰 */
|
||||
|
||||
export const chartTheme = {
|
||||
font: "system-ui, 'PingFang SC', 'Microsoft YaHei', sans-serif",
|
||||
textColor: 'rgba(28, 28, 28, 0.40)', // 轴文字
|
||||
gridline: 'rgba(28, 28, 28, 0.08)', // 发丝网格
|
||||
axis: 'rgba(28, 28, 28, 0.15)', // 轴线
|
||||
ink: '#1c1c1c', // 主墨(实心系列)
|
||||
grayStrong: 'rgba(28, 28, 28, 0.55)', // 次级系列
|
||||
gray: 'rgba(28, 28, 28, 0.15)', // 浅色系列(未完成)
|
||||
surface: '#f9f8f6',
|
||||
}
|
||||
|
||||
export const baseGrid = { left: 8, right: 16, top: 36, bottom: 4, containLabel: true }
|
||||
|
||||
export const baseAxisLabel = {
|
||||
color: 'rgba(28, 28, 28, 0.40)',
|
||||
fontSize: 12,
|
||||
fontFamily: chartTheme.font,
|
||||
}
|
||||
|
||||
export const baseTooltip = {
|
||||
backgroundColor: '#ffffff',
|
||||
borderColor: 'rgba(28, 28, 28, 0.15)',
|
||||
borderWidth: 1,
|
||||
textStyle: { color: '#1c1c1c', fontSize: 12, fontFamily: chartTheme.font },
|
||||
extraCssText: 'border-radius:0; box-shadow:none;',
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** is_ok 状态 → 文案 / 颜色 / 图标 的唯一映射处(对应 docs/02 2.2) */
|
||||
|
||||
export type Tone = 'ok' | 'danger' | 'warn' | 'muted'
|
||||
|
||||
export interface StatusStyle {
|
||||
text: string
|
||||
tone: Tone
|
||||
color: string
|
||||
bg: string
|
||||
icon: string
|
||||
}
|
||||
|
||||
const TONE_MAP: Record<Tone, { color: string; bg: string }> = {
|
||||
ok: { color: 'var(--marker-green)', bg: 'rgba(60, 154, 95, 0.08)' },
|
||||
danger: { color: 'var(--marker-red)', bg: 'rgba(224, 64, 44, 0.06)' },
|
||||
warn: { color: '#d9a424', bg: 'rgba(217, 164, 36, 0.06)' },
|
||||
muted: { color: 'var(--text-weak)', bg: 'rgba(51, 48, 42, 0.06)' },
|
||||
}
|
||||
|
||||
const ICONS: Record<string, string> = {
|
||||
NULL: '✓',
|
||||
'403': '⚑',
|
||||
'401': '⚿',
|
||||
'418': '⚡',
|
||||
'0': '!',
|
||||
'6': '?',
|
||||
}
|
||||
|
||||
export function statusStyle(isOk: number | null, text: string, tone: Tone): StatusStyle {
|
||||
const key = isOk === null ? 'NULL' : String(isOk)
|
||||
const palette = TONE_MAP[tone] ?? TONE_MAP.muted
|
||||
return {
|
||||
text,
|
||||
tone,
|
||||
color: palette.color,
|
||||
bg: palette.bg,
|
||||
icon: ICONS[key] ?? '?',
|
||||
}
|
||||
}
|
||||
|
||||
/** 行底色(保证 red=死了 / orange=可疑 / green=能动 / grey=不清楚) */
|
||||
export function rowTint(isOk: number | null): string {
|
||||
if (isOk === null) return 'rgba(60, 154, 95, 0.05)'
|
||||
if (isOk === 403 || isOk === 0) return 'rgba(224, 64, 44, 0.05)'
|
||||
if (isOk === 401 || isOk === 418) return 'rgba(217, 164, 36, 0.05)'
|
||||
return 'rgba(51, 48, 42, 0.04)'
|
||||
}
|
||||
|
||||
export function fmtNumber(v: number | null | undefined): string {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return '—'
|
||||
return v.toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
export function fmtPercent(v: number | null | undefined): string {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return '—'
|
||||
return `${v.toFixed(1)}%`
|
||||
}
|
||||
|
||||
export function fmtMoney(v: number | null | undefined): string {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return '—'
|
||||
return `¥${v.toFixed(2)}`
|
||||
}
|
||||
|
||||
export function fmtTime(v: string | null | undefined): string {
|
||||
if (!v) return '—'
|
||||
return v.length > 16 ? v.slice(5, 16) : v
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/** 自动刷新:每 intervalMs 递增一次 tick;页面隐藏时暂停,回到前台立即刷新一次。
|
||||
*
|
||||
* tick 必须由调用方传入(通常是 Pinia store 里的 tick),这样"定时刷新"和"手动刷新按钮"
|
||||
* 递增的是同一个 ref —— 否则页面 watch 不到,自动刷新会静默失效。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
|
||||
|
||||
export function useAutoRefresh(intervalMs = 15000, enabled: Ref<boolean> = ref(true), tick: Ref<number> = ref(0)) {
|
||||
let timer: number | null = null
|
||||
|
||||
const clear = () => {
|
||||
if (timer !== null) {
|
||||
window.clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
const start = () => {
|
||||
clear()
|
||||
if (!enabled.value) return
|
||||
timer = window.setInterval(() => {
|
||||
if (!document.hidden) tick.value += 1
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
tick.value += 1
|
||||
start()
|
||||
} else {
|
||||
clear()
|
||||
}
|
||||
}
|
||||
|
||||
watch(enabled, start)
|
||||
|
||||
onMounted(() => {
|
||||
start()
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
clear()
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
})
|
||||
|
||||
return { tick, refreshNow: () => (tick.value += 1) }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** KPI 数字滚动(easeOutCubic,值变化时从旧值平滑过渡) */
|
||||
|
||||
import { ref, watch, type Ref } from 'vue'
|
||||
|
||||
export function useCountUp(target: Ref<number>, duration = 1200) {
|
||||
const display = ref(0)
|
||||
let raf = 0
|
||||
|
||||
function animate(from: number, to: number) {
|
||||
cancelAnimationFrame(raf)
|
||||
const start = performance.now()
|
||||
const step = (t: number) => {
|
||||
const p = Math.min((t - start) / duration, 1)
|
||||
const e = 1 - Math.pow(1 - p, 3) // easeOutCubic
|
||||
display.value = from + (to - from) * e
|
||||
if (p < 1) raf = requestAnimationFrame(step)
|
||||
}
|
||||
raf = requestAnimationFrame(step)
|
||||
}
|
||||
|
||||
watch(target, (to, from) => animate(from ?? 0, to), { immediate: true })
|
||||
return display
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** 锁一屏高度工具:动态测量导航高度 + main 实际内边距,精确锁定视口高度(页面不滚动) */
|
||||
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
export function useLockedHeight() {
|
||||
const navH = ref(65)
|
||||
const mainPad = ref(48 + 96)
|
||||
onMounted(() => {
|
||||
const h = document.querySelector('header')
|
||||
if (h) navH.value = h.offsetHeight
|
||||
const m = document.querySelector('main')
|
||||
if (m) {
|
||||
const cs = getComputedStyle(m)
|
||||
mainPad.value = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0)
|
||||
}
|
||||
})
|
||||
return computed(() => `calc(100vh - ${navH.value + mainPad.value}px)`)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** 动效预设 —— 编辑杂志风(《设计风格.md》):克制、无弹性曲线(禁 bounce/elastic)
|
||||
* 入场:淡入 + 8px 上移,easeOut;hover/按压交给 CSS(transition-colors / active:scale-95)
|
||||
*/
|
||||
|
||||
function reduced(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.matchMedia === 'function' &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
)
|
||||
}
|
||||
|
||||
/** 区块/卡片入场:淡入 + 8px 上移(克制,非弹性) */
|
||||
export const enterBlock = (delay = 0) =>
|
||||
reduced()
|
||||
? { initial: { opacity: 0 }, enter: { opacity: 1, transition: { duration: 0 } } }
|
||||
: {
|
||||
initial: { opacity: 0, y: 8 },
|
||||
enter: { opacity: 1, y: 0, transition: { duration: 0.5, ease: 'easeOut', delay } },
|
||||
}
|
||||
|
||||
/** 弹窗入场:淡入 + 8px 上移 */
|
||||
export const enterDialog = reduced()
|
||||
? { initial: { opacity: 0 }, enter: { opacity: 1, transition: { duration: 0 } } }
|
||||
: {
|
||||
initial: { opacity: 0, y: 8 },
|
||||
enter: { opacity: 1, y: 0, transition: { duration: 0.35, ease: 'easeOut' } },
|
||||
}
|
||||
|
||||
/** 移动端抽屉:右侧滑入(保留,桌面不启用) */
|
||||
export const enterDrawer = reduced()
|
||||
? { initial: {}, enter: { transition: { duration: 0 } }, leave: { transition: { duration: 0 } } }
|
||||
: {
|
||||
initial: { x: '100%' },
|
||||
enter: { x: 0, transition: { duration: 0.35, ease: 'easeOut' } },
|
||||
leave: { x: '100%', transition: { duration: 0.35, ease: 'easeOut' } },
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { MotionPlugin } from '@vueuse/motion'
|
||||
import 'element-plus/dist/index.css'
|
||||
import '@fontsource/zcool-kuaile' // 手写标题字体(本地打包)
|
||||
import '@fontsource/zcool-qingke-huangyou' // 手写标签字体
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(ElementPlus)
|
||||
app.use(MotionPlugin)
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,65 @@
|
||||
/** 全局状态:meta 缓存(城市白名单/代理 IP 数)、自动刷新开关、刷新信号 */
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import api from '../api'
|
||||
import type { MetaData, MetaCity } from '../api/types'
|
||||
|
||||
const META_TTL = 5 * 60 * 1000
|
||||
|
||||
export const useHotelStore = defineStore('hotel', () => {
|
||||
const autoRefresh = ref(true)
|
||||
|
||||
const meta = ref<MetaData | null>(null)
|
||||
const metaAt = ref(0)
|
||||
const metaLoading = ref(false)
|
||||
const metaError = ref('')
|
||||
|
||||
/** 刷新信号:定时器与「刷新」按钮都递增它,各页面 watch 后静默重取 */
|
||||
const tick = ref(0)
|
||||
const bumpTick = () => {
|
||||
tick.value += 1
|
||||
}
|
||||
|
||||
const cities = computed<MetaCity[]>(() => meta.value?.cities ?? [])
|
||||
const legalCities = computed<string[]>(() => meta.value?.legal_cities ?? [])
|
||||
const cityOptions = computed(() => cities.value.filter((c) => c.legal || c.accounts > 0))
|
||||
|
||||
async function loadMeta(force = false) {
|
||||
if (!force && meta.value && Date.now() - metaAt.value < META_TTL) return meta.value
|
||||
metaLoading.value = true
|
||||
metaError.value = ''
|
||||
try {
|
||||
meta.value = await api.meta()
|
||||
metaAt.value = Date.now()
|
||||
} catch (e) {
|
||||
metaError.value = (e as Error).message
|
||||
} finally {
|
||||
metaLoading.value = false
|
||||
}
|
||||
return meta.value
|
||||
}
|
||||
|
||||
function cityIpCount(name: string): number {
|
||||
return cities.value.find((c) => c.city === name)?.proxy_ips ?? 0
|
||||
}
|
||||
|
||||
function cityCityId(name: string): string | null {
|
||||
return cities.value.find((c) => c.city === name)?.city_id ?? null
|
||||
}
|
||||
|
||||
return {
|
||||
autoRefresh,
|
||||
meta,
|
||||
metaAt,
|
||||
metaLoading,
|
||||
metaError,
|
||||
tick,
|
||||
bumpTick,
|
||||
cities,
|
||||
legalCities,
|
||||
cityOptions,
|
||||
loadMeta,
|
||||
cityIpCount,
|
||||
cityCityId,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
/* 自研工具类(由 Tailwind CLI 一次性生成并固化,见 src/styles/utilities.css 头部注释;
|
||||
模板类名与此文件一一对应,新增类时需重新生成或手写补充) */
|
||||
@import './styles/utilities.css';
|
||||
@import './styles/tokens.css';
|
||||
@import './styles/sketch.css';
|
||||
@@ -0,0 +1,226 @@
|
||||
/* ═══════════════════════════════════════════════════════════
|
||||
手绘涂鸦风 专用样式层(叠加在 tokens.css 之上,须在其后引入)
|
||||
纸纹网格 / 抖动圆角卡片 / 马克笔高亮 / 标题涂鸦下划线 / Element Plus 皮肤
|
||||
只加类不改布局:sketch-card(卡片) sketch-panel(大面板) sketch-btn(按钮)
|
||||
sketch-tag(状态标签) sketch-header(顶栏) marker-highlight(数字高亮)
|
||||
═══════════════════════════════════════════════════════════ */
|
||||
|
||||
/* ── 素描纸纹理:淡方格(数学本)── */
|
||||
body {
|
||||
background-image:
|
||||
linear-gradient(rgba(51, 48, 42, 0.045) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(51, 48, 42, 0.045) 1px, transparent 1px);
|
||||
background-size: 28px 28px;
|
||||
}
|
||||
|
||||
/* ── 手绘抖动圆角常量 ── */
|
||||
:root {
|
||||
--radius-rough-sm: 255px 15px 225px 15px / 15px 225px 15px 255px; /* 按钮/标签 */
|
||||
--radius-rough-md: 14px 5px 16px 6px / 6px 15px 5px 17px; /* 卡片 */
|
||||
--radius-rough-panel: 10px 4px 12px 5px / 5px 11px 4px 13px; /* 大面板 */
|
||||
--stroke-ring: 0 0 0 1.5px var(--border-strong); /* 手绘描边环 */
|
||||
}
|
||||
|
||||
/* ── 卡片(KPI 四卡 / 时段卡 / 错误框):便签纸 + 墨描边 + 贴纸阴影 + 微倾 ── */
|
||||
.sketch-card {
|
||||
background: var(--bg-card);
|
||||
border-color: var(--border-strong);
|
||||
border-radius: var(--radius-rough-md);
|
||||
box-shadow: var(--stroke-ring), var(--shadow-card);
|
||||
transition: box-shadow 0.2s ease, border-color 0.2s ease, rotate 0.2s ease;
|
||||
}
|
||||
.sketch-card:nth-child(odd) {
|
||||
rotate: -0.6deg;
|
||||
}
|
||||
.sketch-card:nth-child(even) {
|
||||
rotate: 0.5deg;
|
||||
}
|
||||
.sketch-card:hover {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 1.6px var(--accent), 4px 4px 0 rgba(224, 64, 44, 0.22);
|
||||
rotate: 0deg; /* 拿起便签:悬停摆正 */
|
||||
}
|
||||
|
||||
/* ── 大面板(任务/用户管理表格容器):倾角更小,避免锁屏滚动区边缘裁切 ── */
|
||||
.sketch-panel {
|
||||
background: var(--bg-card);
|
||||
border-color: var(--border-strong);
|
||||
border-radius: var(--radius-rough-panel);
|
||||
box-shadow: var(--stroke-ring), var(--shadow-card);
|
||||
transition: box-shadow 0.2s ease, border-color 0.2s ease, rotate 0.2s ease;
|
||||
}
|
||||
.sketch-panel:nth-child(odd) {
|
||||
rotate: 0.25deg;
|
||||
}
|
||||
.sketch-panel:nth-child(even) {
|
||||
rotate: -0.2deg;
|
||||
}
|
||||
.sketch-panel:hover {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 1.6px var(--accent), 4px 4px 0 rgba(224, 64, 44, 0.2);
|
||||
rotate: 0deg;
|
||||
}
|
||||
|
||||
/* ── 按钮(导出等描边按钮):手绘药丸角 + 红色描边悬停 ── */
|
||||
.sketch-btn {
|
||||
background: var(--bg-card);
|
||||
border-color: var(--border-strong);
|
||||
border-radius: var(--radius-rough-sm);
|
||||
box-shadow: 2px 2px 0 rgba(51, 48, 42, 0.14);
|
||||
transition: box-shadow 0.15s ease, background-color 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
.sketch-btn:hover {
|
||||
background: var(--accent-bg);
|
||||
border-color: var(--accent);
|
||||
box-shadow: 2px 2px 0 rgba(224, 64, 44, 0.3);
|
||||
}
|
||||
.sketch-btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ── 状态标签:贴纸感(细描边 + 微倾)── */
|
||||
.sketch-tag {
|
||||
border: 1px solid currentColor;
|
||||
border-radius: var(--radius-rough-sm);
|
||||
box-shadow: 1.5px 1.5px 0 rgba(51, 48, 42, 0.1);
|
||||
rotate: -1deg;
|
||||
}
|
||||
|
||||
/* ── 数字荧光笔高亮:斜切黄色马克笔横带 ── */
|
||||
.marker-highlight {
|
||||
background-image: linear-gradient(99deg, transparent 0.5%, var(--highlighter) 2.5%, var(--highlighter) 97.5%, transparent 99.5%);
|
||||
background-repeat: no-repeat;
|
||||
background-position: 0 68%;
|
||||
background-size: 100% 42%;
|
||||
}
|
||||
|
||||
/* ── 大标题(h1.font-display):手写体 + 微倾 + 红色涂鸦下划线 + 圈重点 ── */
|
||||
h1.font-display {
|
||||
position: relative;
|
||||
width: fit-content;
|
||||
rotate: -0.6deg;
|
||||
}
|
||||
h1.font-display::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -0.08em;
|
||||
right: -0.08em;
|
||||
bottom: -0.04em;
|
||||
height: 0.34em;
|
||||
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='96' height='12' viewBox='0 0 96 12' preserveAspectRatio='none'%3E%3Cpath d='M2 8 C 8 3, 14 3, 20 8 S 32 13, 38 8 S 50 3, 56 8 S 68 13, 74 8 S 86 3, 94 8' fill='none' stroke='%23e0402c' stroke-width='2.4' stroke-linecap='round'/%3E%3C/svg%3E") bottom left / 100% 100% no-repeat;
|
||||
}
|
||||
h1.font-display::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -1.15em;
|
||||
top: -0.18em;
|
||||
width: 0.72em;
|
||||
height: 0.72em;
|
||||
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12.5 3 C 17 2.5, 21 5.5, 21.5 10 C 22 15, 18.5 20, 13.5 20.5 C 8.5 21, 4 18, 3.5 13 C 3 8.5, 6 3.5, 10 3.2 C 11 3.1, 12 3.2, 12.5 3 Z' fill='none' stroke='%233e6cb5' stroke-width='1.8' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
}
|
||||
/* 二级标题:轻微手写倾角 */
|
||||
h2.font-display {
|
||||
rotate: -0.4deg;
|
||||
}
|
||||
|
||||
/* ── 顶栏:墨色手绘波浪底边 ── */
|
||||
.sketch-header::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: -3px;
|
||||
height: 7px;
|
||||
pointer-events: none;
|
||||
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='56' height='7' viewBox='0 0 56 7' preserveAspectRatio='none'%3E%3Cpath d='M0 4 C 4 1.5, 8 1.5, 12 4 S 20 6.5, 24 4 S 32 1.5, 36 4 S 44 6.5, 48 4 S 54 1.5, 56 3' fill='none' stroke='%2333302a' stroke-width='1.8' stroke-linecap='round' stroke-opacity='0.55'/%3E%3C/svg%3E") repeat-x bottom / 56px 7px;
|
||||
}
|
||||
|
||||
/* ══════════════ Element Plus 涂鸦皮肤 ══════════════ */
|
||||
|
||||
/* 输入框/下拉/日期:便签纸 + 抖动角 + 红色马克笔聚焦 */
|
||||
.el-input__wrapper,
|
||||
.el-select__wrapper {
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius-rough-sm);
|
||||
box-shadow: 0 0 0 1.4px var(--border-color) inset;
|
||||
transition: box-shadow 0.15s ease, background-color 0.15s ease;
|
||||
}
|
||||
.el-input__wrapper:hover,
|
||||
.el-select__wrapper:hover {
|
||||
box-shadow: 0 0 0 1.4px var(--border-strong) inset;
|
||||
}
|
||||
.el-input__wrapper.is-focus,
|
||||
.el-select__wrapper.is-focused {
|
||||
background: var(--bg-card);
|
||||
box-shadow: 0 0 0 1.8px var(--accent) inset, 2px 2px 0 rgba(224, 64, 44, 0.18);
|
||||
}
|
||||
|
||||
/* 下拉/日期弹层:手账卡片 */
|
||||
.el-popper.is-light {
|
||||
background: var(--bg-card);
|
||||
border-color: var(--border-strong);
|
||||
border-radius: var(--radius-rough-panel);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.el-popper.is-light .el-select-dropdown__item.is-selected {
|
||||
color: var(--accent);
|
||||
}
|
||||
.el-popper.is-light .el-select-dropdown__item.is-hovering {
|
||||
background: var(--accent-bg);
|
||||
}
|
||||
|
||||
/* 日期面板:今天/选中/悬停 = 马克笔 */
|
||||
.el-date-table td.today .el-date-table-cell__text {
|
||||
color: var(--accent);
|
||||
}
|
||||
.el-date-table td.current .el-date-table-cell__text {
|
||||
background-color: var(--accent);
|
||||
color: #fff;
|
||||
border-radius: var(--radius-rough-sm);
|
||||
}
|
||||
.el-date-table td.available:hover .el-date-table-cell__text {
|
||||
background-color: var(--accent-bg);
|
||||
}
|
||||
|
||||
/* 弹窗:便签卡 + 波浪分隔线 + 手写标题 */
|
||||
.el-dialog {
|
||||
background: var(--bg-card);
|
||||
border: 1.6px solid var(--border-strong);
|
||||
border-radius: var(--radius-rough-panel);
|
||||
box-shadow: 6px 6px 0 rgba(51, 48, 42, 0.16);
|
||||
}
|
||||
.el-dialog__title {
|
||||
font-family: var(--font-display);
|
||||
font-weight: 400;
|
||||
}
|
||||
.el-dialog__header {
|
||||
border-bottom: 1.5px dashed rgba(51, 48, 42, 0.25);
|
||||
padding-bottom: 14px;
|
||||
}
|
||||
|
||||
/* 表格:纸面行 + 黄色马克笔悬停行 */
|
||||
.el-table {
|
||||
--el-table-bg-color: transparent;
|
||||
--el-table-tr-bg-color: transparent;
|
||||
--el-table-header-bg-color: rgba(51, 48, 42, 0.045);
|
||||
--el-table-header-text-color: var(--text-secondary);
|
||||
--el-table-border-color: rgba(51, 48, 42, 0.14);
|
||||
--el-table-row-hover-bg-color: rgba(255, 205, 64, 0.1);
|
||||
--el-table-text-color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* 分页:红色马克笔当前页 */
|
||||
.el-pagination .el-pager li.is-active {
|
||||
color: var(--accent);
|
||||
}
|
||||
.el-pagination .el-pager li:hover,
|
||||
.el-pagination button:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* 滚动条:墨色细条 */
|
||||
.el-scrollbar__thumb {
|
||||
background-color: rgba(51, 48, 42, 0.28);
|
||||
border-radius: 0;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/* ═══════════════════════════════════════════════════════════
|
||||
设计 token —— 手绘涂鸦风·彩色马克笔(《设计风格.md》)
|
||||
素描纸底 / 墨色线条 / 红黄蓝绿马克笔点缀 / 手写字体 / 抖动边框 / 硬偏移阴影
|
||||
★ 变量名与旧 Editorial 体系一一对应,禁止改名(组件模板按名引用)
|
||||
涂鸦专用样式(纸纹、sketch-card 等类、Element Plus 皮肤)在 styles/sketch.css
|
||||
═══════════════════════════════════════════════════════════ */
|
||||
|
||||
:root {
|
||||
/* ── 表面层次(素描纸 + 便签纸)── */
|
||||
--bg-page: #fbf7ec; /* 页面:暖米素描纸(网格纹理在 sketch.css) */
|
||||
--bg-card: #fffdf5; /* 卡片:略亮的便签纸 */
|
||||
--bg-hover: rgba(51, 48, 42, 0.05);
|
||||
--bg-muted: rgba(51, 48, 42, 0.06);
|
||||
|
||||
/* ── 线条(墨线)── */
|
||||
--border-color: rgba(51, 48, 42, 0.28);
|
||||
--border-strong: #33302a;
|
||||
|
||||
/* ── 文字阶梯(暖墨色透明度层次)── */
|
||||
--text-primary: #33302a;
|
||||
--text-secondary: rgba(51, 48, 42, 0.62);
|
||||
--text-weak: rgba(51, 48, 42, 0.42);
|
||||
--text-faint: rgba(51, 48, 42, 0.26);
|
||||
|
||||
/* ── 强调:红色马克笔 ── */
|
||||
--accent: #e0402c;
|
||||
--accent-bg: rgba(224, 64, 44, 0.09);
|
||||
|
||||
/* ── 马克笔四色 ── */
|
||||
--marker-red: #e0402c;
|
||||
--marker-yellow: #ffcf4d; /* 荧光笔高亮 */
|
||||
--marker-blue: #3e6cb5;
|
||||
--marker-green: #3c9a5f;
|
||||
--highlighter: rgba(255, 205, 64, 0.52); /* 数字高亮带(半透明) */
|
||||
|
||||
/* ── 状态(马克笔色 + 浅色底,图标/文字双通道)── */
|
||||
--status-done: var(--marker-green); /* 已完成 */
|
||||
--status-in-progress: var(--marker-blue); /* 进行中 */
|
||||
--status-pending: #8f8877; /* 待领取 */
|
||||
--status-abnormal: var(--marker-red); /* 异常:红色 + ⚠ 图标 */
|
||||
--status-done-bg: rgba(60, 154, 95, 0.12);
|
||||
--status-in-progress-bg: rgba(62, 108, 181, 0.10);
|
||||
--status-pending-bg: rgba(143, 136, 119, 0.14);
|
||||
--status-abnormal-bg: rgba(224, 64, 44, 0.10);
|
||||
|
||||
/* ── 硬偏移阴影(手绘贴纸感,禁止模糊阴影)── */
|
||||
--shadow-card: 3px 3px 0 rgba(51, 48, 42, 0.14);
|
||||
--shadow-raised: 5px 5px 0 rgba(51, 48, 42, 0.18);
|
||||
|
||||
/* ── 抖动圆角(手绘描边,半径值刻意不对称)── */
|
||||
--radius-card: 14px 5px 16px 6px / 6px 15px 5px 17px;
|
||||
--radius-element: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
--radius-pill: 36px 10px 30px 12px / 12px 34px 10px 38px;
|
||||
|
||||
/* ── 字体:中文手写标题 + 手写标签 + 无衬线正文(fontsource 本地打包)── */
|
||||
--font-display: 'ZCOOL KuaiLe', Georgia, 'Times New Roman', 'Noto Serif SC', 'Songti SC', SimSun, serif;
|
||||
--font-body: system-ui, -apple-system, 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
--font-mono: 'ZCOOL QingKe HuangYou', 'SF Mono', 'Cascadia Mono', Consolas, monospace;
|
||||
|
||||
/* ── Element Plus 主题覆盖(马克笔配色)── */
|
||||
--el-color-primary: #e0402c;
|
||||
--el-color-primary-light-3: #e86a56;
|
||||
--el-color-primary-light-5: #ed9487;
|
||||
--el-color-primary-light-7: #f4bdb5;
|
||||
--el-color-primary-light-8: #f7ccc5;
|
||||
--el-color-primary-light-9: #fbe8e3;
|
||||
--el-color-primary-dark-2: #b33322;
|
||||
--el-color-success: #3c9a5f;
|
||||
--el-color-warning: #d9a424;
|
||||
--el-color-danger: #e0402c;
|
||||
--el-color-error: #e0402c;
|
||||
--el-border-radius-base: 0px;
|
||||
--el-border-radius-small: 0px;
|
||||
--el-border-color: rgba(51, 48, 42, 0.24);
|
||||
--el-border-color-light: rgba(51, 48, 42, 0.18);
|
||||
--el-border-color-lighter: rgba(51, 48, 42, 0.12);
|
||||
--el-border-color-extra-light: rgba(51, 48, 42, 0.08);
|
||||
--el-fill-color-blank: #fffdf5;
|
||||
--el-fill-color-light: rgba(51, 48, 42, 0.06);
|
||||
--el-bg-color: #fbf7ec;
|
||||
--el-bg-color-overlay: #fffdf5;
|
||||
--el-text-color-primary: #33302a;
|
||||
--el-text-color-regular: rgba(51, 48, 42, 0.62);
|
||||
--el-text-color-secondary: rgba(51, 48, 42, 0.48);
|
||||
--el-text-color-placeholder: rgba(51, 48, 42, 0.38);
|
||||
--el-text-color-disabled: rgba(51, 48, 42, 0.28);
|
||||
--el-box-shadow-light: 3px 3px 0 rgba(51, 48, 42, 0.14);
|
||||
--el-box-shadow: 4px 4px 0 rgba(51, 48, 42, 0.16);
|
||||
--el-mask-color: rgba(251, 247, 236, 0.72);
|
||||
--el-pagination-active-color: #e0402c;
|
||||
--el-switch-off-color: rgba(51, 48, 42, 0.22);
|
||||
--el-font-family: var(--font-body);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg-page);
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-body);
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* 手写标题 */
|
||||
.font-display {
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
/* 手写标签(原等宽点缀位,换成中文手写体) */
|
||||
.font-mono {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
/* 数字对齐:表格列 */
|
||||
.tabular-nums {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* hover 下划线动画(墨线,保留原结构) */
|
||||
.hover-underline {
|
||||
position: relative;
|
||||
}
|
||||
.hover-underline::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: -2px;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background: var(--text-primary);
|
||||
transform: scaleX(0);
|
||||
transform-origin: left;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
.hover-underline:hover::after {
|
||||
transform: scaleX(1);
|
||||
}
|
||||
|
||||
/* ── 弹窗过渡(手绘风:柔和上移 + 轻微缩放 + 淡入,无弹性)── */
|
||||
.dialog-fade-enter-active {
|
||||
transition: opacity 0.35s ease-out, transform 0.35s ease-out;
|
||||
}
|
||||
.dialog-fade-leave-active {
|
||||
transition: opacity 0.2s ease-in, transform 0.2s ease-in;
|
||||
}
|
||||
.dialog-fade-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.98);
|
||||
}
|
||||
.dialog-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(8px) scale(0.99);
|
||||
}
|
||||
|
||||
/* 系统"减少动态效果"开启:关闭全部过渡与动画 */
|
||||
.reduced-motion *,
|
||||
.reduced-motion *::before,
|
||||
.reduced-motion *::after {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,257 @@
|
||||
<script setup lang="ts">
|
||||
/** 页面 1:hotel_hd 原始数据展示(前 10 条)+ 可操作(改城市 / 重置 is_ok) */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import api from '../api'
|
||||
import type { AccountItem } from '../api/types'
|
||||
import ChangeCityDialog from '../components/ChangeCityDialog.vue'
|
||||
import { rowTint } from '../composables/hotelStatus'
|
||||
import { useHotelStore } from '../stores/hotel'
|
||||
|
||||
const store = useHotelStore()
|
||||
const { tick } = storeToRefs(store)
|
||||
|
||||
const LIMIT = 15
|
||||
const items = ref<AccountItem[]>([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
|
||||
async function load(silent = false) {
|
||||
if (!silent) loading.value = true
|
||||
try {
|
||||
const res = await api.accounts({ page: 1, size: LIMIT, sort: 'updated_at', order: 'desc' })
|
||||
items.value = res.items
|
||||
total.value = res.total
|
||||
} catch (e) {
|
||||
ElMessage.error((e as Error).message)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const rowStyle = (scope: { row: AccountItem }) => ({ background: rowTint(scope.row.is_ok) })
|
||||
|
||||
/** is_ok 原值展示:NULL 用灰色文字,其余带状态色 */
|
||||
function isOkText(v: number | null): string {
|
||||
return v === null ? 'NULL' : String(v)
|
||||
}
|
||||
function isOkClass(row: AccountItem): string {
|
||||
return `isok isok--${row.status_tone}`
|
||||
}
|
||||
|
||||
const cityDialog = ref(false)
|
||||
const activeAccount = ref<AccountItem | null>(null)
|
||||
|
||||
/** 全新包:is_ok=NULL 且还没有绑定城市 —— 这种包要“添加城市”而不是“改城市” */
|
||||
function isNewPackage(row: AccountItem): boolean {
|
||||
return row.is_ok === null && !row.city
|
||||
}
|
||||
/** 可操作城市绑定:is_ok=0(异常包) 或 全新包 */
|
||||
function canBindCity(row: AccountItem): boolean {
|
||||
return row.is_ok === 0 || isNewPackage(row)
|
||||
}
|
||||
|
||||
function openCity(row: AccountItem) {
|
||||
if (!canBindCity(row)) return
|
||||
activeAccount.value = row
|
||||
cityDialog.value = true
|
||||
}
|
||||
function afterWrite() {
|
||||
load(true)
|
||||
}
|
||||
|
||||
const todayLine = computed(() => `最新 ${LIMIT} 条(按 updated_at 倒序,共 ${total.value} 条)`)
|
||||
|
||||
watch(tick, () => load(true))
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<div class="page__bar">
|
||||
<span class="page__title">hotel_hd</span>
|
||||
<span class="page__note">{{ todayLine }}</span>
|
||||
<span class="page__note">req_count = 包使用的总次数 · current_count = 当前城市的使用次数</span>
|
||||
<span class="page__spacer" />
|
||||
<button class="btn" type="button" @click="load()">刷新</button>
|
||||
</div>
|
||||
|
||||
<div class="page__table">
|
||||
<el-table v-loading="loading" :data="items" height="100%" size="default" border :row-style="rowStyle">
|
||||
<el-table-column prop="id" label="id" width="86" fixed />
|
||||
<el-table-column label="is_ok" width="96">
|
||||
<template #default="{ row }">
|
||||
<span :class="isOkClass(row)" :title="row.status_text">{{ isOkText(row.is_ok) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="req_count" label="req_count" width="104" align="right">
|
||||
<template #default="{ row }"><span class="mono">{{ row.req_count }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="current_count" label="current_count" width="132" align="right">
|
||||
<template #default="{ row }"><span class="mono">{{ row.current_count }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="prox" min-width="300" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<code class="prox">{{ row.prox_raw || 'NULL' }}</code>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="city" label="city" width="102">
|
||||
<template #default="{ row }">{{ row.city || 'NULL' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="mt_traceid" width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<code class="mono">{{ row.mt_traceid || 'NULL' }}</code>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updated_at" label="updated_at" width="152">
|
||||
<template #default="{ row }"><span class="mono">{{ row.updated_at || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="120" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<button
|
||||
class="op"
|
||||
type="button"
|
||||
:disabled="!canBindCity(row)"
|
||||
:title="canBindCity(row)
|
||||
? (isNewPackage(row) ? '新包:添加城市后会按该城市跑起来' : '改城市:会清空代理并把状态重置为可用')
|
||||
: `只有 is_ok=0(异常包)或 is_ok=NULL 且未绑城市(新包)才能操作,当前 is_ok=${row.is_ok === null ? 'NULL' : row.is_ok} city=${row.city || 'NULL'}`"
|
||||
@click="openCity(row)"
|
||||
>
|
||||
{{ isNewPackage(row) ? '添加城市' : '改城市' }}
|
||||
</button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<div class="empty">hotel_hd 没有数据</div>
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<p class="page__foot">
|
||||
提示:prox 为代理原始 JSON(含代理账号密码,仅本机内网使用)。只有 <b>is_ok=0(异常包)</b> 可以「改城市」(会清 prox 并把 is_ok 重置为 NULL),<b>is_ok=NULL 且未绑城市的新包</b> 可以「添加城市」让包跑起来;两种情况 current_count 都保留不变。
|
||||
</p>
|
||||
|
||||
<ChangeCityDialog
|
||||
v-model="cityDialog"
|
||||
:account="activeAccount"
|
||||
:legal-cities="store.legalCities"
|
||||
:ip-count="store.cityIpCount"
|
||||
@submitted="afterWrite"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
height: 100%;
|
||||
}
|
||||
.page__bar {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 14px;
|
||||
padding: 8px 12px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.page__title {
|
||||
font-family: var(--font-display);
|
||||
font-size: 17px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.page__note {
|
||||
font-size: 13px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.page__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.btn {
|
||||
height: 28px;
|
||||
padding: 0 12px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--accent);
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
}
|
||||
.page__table {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 6px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-card);
|
||||
overflow: hidden;
|
||||
}
|
||||
.page__table :deep(.el-table__row) {
|
||||
height: 46px;
|
||||
}
|
||||
.page__table :deep(.el-table .cell) {
|
||||
font-size: 14px;
|
||||
}
|
||||
.page__table :deep(.el-table th.el-table__cell) {
|
||||
font-size: 13px;
|
||||
}
|
||||
.page__foot {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.mono {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.prox {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.isok {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.isok--ok {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.isok--danger {
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.isok--warn {
|
||||
color: #d9a424;
|
||||
}
|
||||
.isok--muted {
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.op {
|
||||
margin-right: 6px;
|
||||
padding: 2px 9px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: var(--accent);
|
||||
background: none;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-pill);
|
||||
cursor: pointer;
|
||||
}
|
||||
.op:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.op:disabled {
|
||||
color: var(--text-faint);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.empty {
|
||||
padding: 24px;
|
||||
font-size: 13px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,751 @@
|
||||
<script setup lang="ts">
|
||||
/** 页面 2:查询(参考 查询.py)——左右结构:左=汇总+高危城市,右=所选日期明细表
|
||||
* 日期选择决定"所选日"的 success/reject;高危对照口径 = 昨日(所选日前一天) */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import api from '../api'
|
||||
import type { RiskData, RiskItem } from '../api/types'
|
||||
import { fmtNumber } from '../composables/hotelStatus'
|
||||
import { useHotelStore } from '../stores/hotel'
|
||||
|
||||
function today(): string {
|
||||
const d = new Date()
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
|
||||
}
|
||||
|
||||
/** 高危对照口径 = 昨日(所选日期的前一天):
|
||||
* 平台 getStats 只保留最近两天(今天/昨天),"近 5 天成功率"拿不到数据,已下线 */
|
||||
const RISK_DAYS = 1
|
||||
|
||||
const day = ref(today())
|
||||
const loading = ref(false) // 首次/手动查询:显示遮罩
|
||||
const refreshing = ref(false) // 自动静默更新:不闪遮罩
|
||||
const data = ref<RiskData | null>(null)
|
||||
const queriedAt = ref('')
|
||||
|
||||
const store = useHotelStore()
|
||||
const { autoRefresh, tick } = storeToRefs(store)
|
||||
|
||||
let inflight = false
|
||||
let lastFetch = 0
|
||||
/** 自动静默更新的最小间隔(避免 15s 全局 tick 把接口打太频) */
|
||||
const AUTO_MIN_INTERVAL = 20000
|
||||
const prevAbnormal = ref<number | null>(null)
|
||||
|
||||
const highRisk = computed<RiskItem[]>(() => data.value?.high_risk ?? [])
|
||||
const abnormal = computed<RiskItem[]>(() => data.value?.abnormal ?? [])
|
||||
const allItems = computed<RiskItem[]>(() => data.value?.items ?? [])
|
||||
|
||||
/** 表格:异常置顶,其余按所选日成功条数降序 */
|
||||
const tableRows = computed<RiskItem[]>(() =>
|
||||
[...allItems.value].sort((a, b) => {
|
||||
if (a.today_abnormal !== b.today_abnormal) return a.today_abnormal ? -1 : 1
|
||||
return (b.today_success ?? -1) - (a.today_success ?? -1)
|
||||
}),
|
||||
)
|
||||
|
||||
const successTotal = computed(() => allItems.value.reduce((s, i) => s + (i.today_success ?? 0), 0))
|
||||
const rejectTotal = computed(() => allItems.value.reduce((s, i) => s + (i.today_reject ?? 0), 0))
|
||||
|
||||
// ── 任务进度:每天任务量 / 单包产能 → 还剩多少条、还需多少包 ──
|
||||
const targetPerDay = ref(1000) // 每天任务量(可在页面改)
|
||||
const perPackage = ref(48) // 一个包约可完成条数(可在页面改)
|
||||
const doneCount = computed(() => successTotal.value)
|
||||
const remainingCount = computed(() => Math.max(0, targetPerDay.value - doneCount.value))
|
||||
|
||||
/** 现有可用包(is_ok IS NULL)每个按满产能 perPackage 算,减去已跑的 current_count 就是它还能贡献的条数 */
|
||||
const availablePackages = computed(() => data.value?.available_packages ?? [])
|
||||
const packageCapacityLeft = computed(() =>
|
||||
availablePackages.value.reduce((sum, p) => sum + Math.max(0, perPackage.value - (p.current_count ?? 0)), 0),
|
||||
)
|
||||
/** 扣掉现有包产能后,真正还需要新包补的条数 */
|
||||
const needAfterPackages = computed(() => Math.max(0, remainingCount.value - packageCapacityLeft.value))
|
||||
const packagesNeeded = computed(() => {
|
||||
const per = perPackage.value
|
||||
if (needAfterPackages.value <= 0 || !per || per <= 0) return 0
|
||||
return Math.ceil(needAfterPackages.value / per)
|
||||
})
|
||||
const progressPercent = computed(() => {
|
||||
const t = targetPerDay.value
|
||||
if (!t || t <= 0) return 0
|
||||
return Math.min(100, Math.round((doneCount.value / t) * 1000) / 10)
|
||||
})
|
||||
|
||||
const rate = computed(() => {
|
||||
const s = successTotal.value
|
||||
const r = rejectTotal.value
|
||||
return s + r > 0 ? `${((s / (s + r)) * 100).toFixed(1)}%` : '—'
|
||||
})
|
||||
/** 平台是否可用 / 所选日期平台是否有统计(都和"0 条完成"是两回事) */
|
||||
const platformOk = computed(() => data.value?.platform_ok ?? true)
|
||||
const hasData = computed(() => data.value?.has_data ?? true)
|
||||
/** 表格里的"该日"= 后端真正返回的日期(与日期选择框联动) */
|
||||
const viewedDate = computed(() => data.value?.date ?? day.value)
|
||||
/** 昨日(参考窗口)日期文本 */
|
||||
const yesterdayText = computed(() => {
|
||||
const w = data.value?.window
|
||||
if (!w) return '—'
|
||||
return w.start === w.end ? w.start : `${w.start} ~ ${w.end}`
|
||||
})
|
||||
|
||||
function rateText(v: number | null): string {
|
||||
return v === null ? '—' : `${v.toFixed(1)}%`
|
||||
}
|
||||
|
||||
const rowStyle = (scope: { row: RiskItem }) => ({
|
||||
background: scope.row.today_abnormal ? 'rgba(224, 64, 44, 0.07)' : undefined,
|
||||
})
|
||||
|
||||
async function run(silent = false) {
|
||||
if (!day.value) {
|
||||
if (!silent) ElMessage.warning('请选择日期')
|
||||
return
|
||||
}
|
||||
if (inflight) return // 防重入,避免请求堆积
|
||||
inflight = true
|
||||
lastFetch = Date.now()
|
||||
if (silent) refreshing.value = true
|
||||
else loading.value = true
|
||||
try {
|
||||
const res = await api.platformRisk({ date: day.value, days: RISK_DAYS })
|
||||
data.value = res
|
||||
queriedAt.value = new Date().toLocaleTimeString('zh-CN')
|
||||
|
||||
const grew = prevAbnormal.value !== null && res.counts.abnormal > prevAbnormal.value
|
||||
prevAbnormal.value = res.counts.abnormal
|
||||
|
||||
// 自动更新时只在“异常城市变多”才弹提示,避免每 20 秒刷一次消息
|
||||
if (!silent || grew) {
|
||||
if (!res.platform_ok) {
|
||||
ElMessage.error('平台接口不可用,该日期数据为空(请检查网络或平台状态)')
|
||||
} else if (!res.has_data) {
|
||||
ElMessage.warning(`平台没有 ${res.date} 的统计:getStats 只保留最近两天(今天 / 昨天)`)
|
||||
}
|
||||
if (res.counts.abnormal) {
|
||||
ElMessage.error(
|
||||
`${res.date} 有 ${res.counts.abnormal} 个城市异常(样本 > ${res.abnormal_min_sample} 条且成功率 0%):` +
|
||||
res.abnormal.map((i) => i.city).join('、'),
|
||||
)
|
||||
}
|
||||
if (res.counts.high_risk) {
|
||||
ElMessage.warning(
|
||||
`昨日(${res.window.start})有 ${res.counts.high_risk} 个高危城市:` +
|
||||
res.high_risk.map((i) => `${i.city} ${rateText(i.hist_rate)}`).join('、'),
|
||||
)
|
||||
}
|
||||
if (res.logs_available && res.empty_fetch_total) {
|
||||
ElMessage.info(
|
||||
`该日有 ${res.empty_fetch_total} 次拿任务失败(get_one_task 返回 False),涉及 ${res.counts.empty_fetch_cities} 个城市`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (!silent) ElMessage.error((e as Error).message)
|
||||
} finally {
|
||||
inflight = false
|
||||
loading.value = false
|
||||
refreshing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 自动更新:跟随顶栏自动刷新开关(页面隐藏时 store 那边会暂停)
|
||||
watch(tick, () => {
|
||||
if (Date.now() - lastFetch < AUTO_MIN_INTERVAL) return
|
||||
run(true)
|
||||
})
|
||||
// 改日期立即重查
|
||||
watch(day, () => run())
|
||||
|
||||
onMounted(() => run())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<div class="page__bar">
|
||||
<label class="field">
|
||||
<span class="field__label">日期</span>
|
||||
<input v-model="day" class="field__input" type="date" />
|
||||
</label>
|
||||
<button v-if="day !== today()" class="btn" type="button" @click="day = today()">回到今天</button>
|
||||
<button class="btn btn--primary" type="button" :disabled="loading || refreshing" @click="run()">
|
||||
{{ loading ? '查询中…' : refreshing ? '更新中…' : '立即刷新' }}
|
||||
</button>
|
||||
<span class="auto-hint">
|
||||
<i class="dot" :class="{ 'dot--on': autoRefresh, 'dot--busy': refreshing }" />
|
||||
{{ autoRefresh ? '自动更新中(约 20 秒一次)' : '自动更新已暂停' }}
|
||||
<template v-if="queriedAt"> · 上次 {{ queriedAt }}</template>
|
||||
</span>
|
||||
<span v-if="data && !platformOk" class="page__warn">平台接口不可用</span>
|
||||
<span v-else-if="data && !hasData" class="page__warn">该日期平台无统计</span>
|
||||
<span class="page__note">
|
||||
正在查看 {{ viewedDate }};高危对照 = 昨日({{ yesterdayText }})。平台只保留最近两天。
|
||||
</span>
|
||||
<span class="page__spacer" />
|
||||
</div>
|
||||
|
||||
<div class="page__body">
|
||||
<!-- 左栏:任务进度 + 汇总 + 高危城市 -->
|
||||
<aside class="side">
|
||||
<div class="progress-card">
|
||||
<div class="progress-card__head">
|
||||
<span class="panel__title">任务进度</span>
|
||||
<span class="progress-card__spacer" />
|
||||
<label class="mini">
|
||||
每天任务量
|
||||
<input v-model.number="targetPerDay" class="mini__input" type="number" min="0" step="100" />
|
||||
</label>
|
||||
<label class="mini">
|
||||
单包产出
|
||||
<input v-model.number="perPackage" class="mini__input" type="number" min="1" step="1" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="progress-card__nums">
|
||||
<div class="pn">
|
||||
<span class="pn__label">已完成</span>
|
||||
<b class="pn__num pn__num--ok">{{ fmtNumber(doneCount) }}</b>
|
||||
</div>
|
||||
<div class="pn">
|
||||
<span class="pn__label">还剩</span>
|
||||
<b class="pn__num pn__num--danger">{{ fmtNumber(remainingCount) }} 条</b>
|
||||
</div>
|
||||
<div class="pn">
|
||||
<span class="pn__label">现有包可补</span>
|
||||
<b class="pn__num pn__num--warn">{{ fmtNumber(packageCapacityLeft) }} 条</b>
|
||||
</div>
|
||||
<div class="pn">
|
||||
<span class="pn__label">还需新包</span>
|
||||
<b class="pn__num pn__num--danger">{{ fmtNumber(packagesNeeded) }} 个</b>
|
||||
</div>
|
||||
</div>
|
||||
<div class="track"><i class="track__bar" :style="{ width: progressPercent + '%' }" /></div>
|
||||
<p class="progress-card__note">
|
||||
已完成 {{ fmtNumber(doneCount) }} / {{ fmtNumber(targetPerDay) }} 条({{ progressPercent.toFixed(1) }}%)
|
||||
· 还剩 {{ fmtNumber(remainingCount) }} 条
|
||||
· 现有可用包 {{ availablePackages.length }} 个(没跑满 {{ fmtNumber(perPackage) }} 的按 {{ fmtNumber(perPackage) }} 算)合计可补
|
||||
{{ fmtNumber(packageCapacityLeft) }} 条
|
||||
→ 还差 {{ fmtNumber(needAfterPackages) }} 条 → 需新包
|
||||
<b>{{ fmtNumber(packagesNeeded) }}</b> 个
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<span class="stat__label">所选日成功条数</span>
|
||||
<b class="stat__num stat__num--ok">{{ fmtNumber(successTotal) }}</b>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat__label">所选日失败条数</span>
|
||||
<b class="stat__num stat__num--danger">{{ fmtNumber(rejectTotal) }}</b>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat__label">所选日成功率</span>
|
||||
<b class="stat__num">{{ rate }}</b>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat__label">城市数</span>
|
||||
<b class="stat__num">{{ data?.counts.cities ?? 0 }}</b>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat__label">所选日异常</span>
|
||||
<b class="stat__num" :class="abnormal.length ? 'stat__num--danger' : 'stat__num--ok'">
|
||||
{{ abnormal.length }}
|
||||
</b>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat__label">高危(昨日)</span>
|
||||
<b class="stat__num" :class="highRisk.length ? 'stat__num--danger' : 'stat__num--ok'">
|
||||
{{ highRisk.length }}
|
||||
</b>
|
||||
</div>
|
||||
<div class="stat stat--wide">
|
||||
<span class="stat__label">拿任务失败城市</span>
|
||||
<b class="stat__num" :class="data?.counts.empty_fetch_cities ? 'stat__num--warn' : ''">
|
||||
{{ data?.logs_available ? data?.counts.empty_fetch_cities ?? 0 : '—' }}
|
||||
</b>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel__head">
|
||||
<span class="panel__title">高危城市</span>
|
||||
<span class="panel__spacer" />
|
||||
<span class="panel__count" :class="{ 'panel__count--zero': !highRisk.length }">
|
||||
{{ highRisk.length }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="panel__note">
|
||||
昨日({{ yesterdayText }})成功率 < {{ data?.threshold ?? 75 }}%,样本 ≥
|
||||
{{ data?.min_sample ?? 5 }}
|
||||
</p>
|
||||
<div v-if="!highRisk.length" class="panel__empty">
|
||||
{{ loading ? '查询中…' : '昨日没有高危城市 👍' }}
|
||||
</div>
|
||||
<div v-else class="risk-grid">
|
||||
<div v-for="row in highRisk" :key="row.city" class="risk-item">
|
||||
<span class="risk-item__city">{{ row.city }}</span>
|
||||
<span class="risk-item__rate">{{ rateText(row.hist_rate) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- 右栏:当日明细表(占满全高) -->
|
||||
<div class="page__table">
|
||||
<el-table
|
||||
v-loading="loading"
|
||||
:data="tableRows"
|
||||
height="100%"
|
||||
size="default"
|
||||
border
|
||||
:row-style="rowStyle"
|
||||
>
|
||||
<el-table-column label="城市" width="200" fixed>
|
||||
<template #default="{ row }">
|
||||
<span class="city">{{ row.city }}</span>
|
||||
<span
|
||||
v-if="row.empty_fetch_count > 0"
|
||||
class="tag-empty"
|
||||
:title="`该日拿任务失败 ${row.empty_fetch_count} 次(领任务失败 / 城市不匹配,明细见 logs/run_*.jsonl 的 fetch_empty)`"
|
||||
>
|
||||
拿任务失败 {{ row.empty_fetch_count }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="`${viewedDate} success`" min-width="160" align="right">
|
||||
<template #default="{ row }"><span class="mono">{{ fmtNumber(row.today_success) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="`${viewedDate} reject`" min-width="160" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="mono" :class="{ danger: (row.today_reject ?? 0) > 0 }">{{ fmtNumber(row.today_reject) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="`${viewedDate} 成功率`" min-width="150" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="mono" :class="{ danger: row.today_abnormal }">{{ rateText(row.today_rate) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="昨日成功率" min-width="150" align="right">
|
||||
<template #default="{ row }">
|
||||
<span class="mono" :class="{ danger: row.high_risk }">{{ rateText(row.hist_rate) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="判定" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.today_abnormal" class="badge badge--abnormal">异常</span>
|
||||
<span v-else-if="row.high_risk" class="badge">高危</span>
|
||||
<span v-else-if="row.hist_total === 0 && row.today_rate !== null" class="weak">仅所选日</span>
|
||||
<span v-else class="weak">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<div class="empty">点击「查询」拉取数据</div>
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="page__foot">
|
||||
成功率 = success ÷ (success + reject);<b>异常</b> = 所选日样本 > {{ data?.abnormal_min_sample ?? 5 }} 条且成功率 0%;
|
||||
<b>高危</b> = 昨日样本 ≥ {{ data?.min_sample ?? 5 }} 条且成功率 < {{ data?.threshold ?? 75 }}%(平台只保留今天/昨天,
|
||||
5 天窗口拿不到数据,已改为昨日口径);<b>还需新包</b> = ⌈(每天任务量 − 所选日 success − 现有可用包剩余产能) ÷ 单包产出⌉,其中可用包产能按"没跑满单包产出的按满额算,再减去 current_count"(参数可在左栏直接改);
|
||||
<b>拿任务失败</b> 徽标来自埋点 <code>fetch_empty</code>。
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
height: 100%;
|
||||
}
|
||||
.page__bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.field__label {
|
||||
font-size: 12px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.field__input {
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.field__input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.btn {
|
||||
height: 28px;
|
||||
padding: 0 14px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn--primary {
|
||||
color: #fff;
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: progress;
|
||||
}
|
||||
.page__note {
|
||||
font-size: 12px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.page__warn {
|
||||
padding: 1px 8px;
|
||||
font-size: 12px;
|
||||
color: #9a6b00;
|
||||
background: rgba(217, 164, 36, 0.18);
|
||||
border: 1px solid rgba(217, 164, 36, 0.5);
|
||||
border-radius: 6px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.auto-hint {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-faint);
|
||||
}
|
||||
.dot--on {
|
||||
background: var(--marker-green);
|
||||
}
|
||||
.dot--busy {
|
||||
background: var(--marker-yellow);
|
||||
}
|
||||
.page__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ── 左右结构 ── */
|
||||
.page__body {
|
||||
display: grid;
|
||||
grid-template-columns: 372px minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
min-height: 0;
|
||||
}
|
||||
.side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* ── 任务进度卡 ── */
|
||||
.progress-card {
|
||||
flex: none;
|
||||
padding: 9px 12px 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-left: 4px solid var(--accent);
|
||||
border-radius: var(--radius-card);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.progress-card__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.progress-card__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.mini {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--text-weak);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.mini__input {
|
||||
width: 62px;
|
||||
height: 24px;
|
||||
padding: 0 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.mini__input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.progress-card__nums {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 18px;
|
||||
margin: 8px 0 6px;
|
||||
}
|
||||
.pn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
.pn__label {
|
||||
font-size: 11px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.pn__num {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 21px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.pn__num--ok {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.pn__num--danger {
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.track {
|
||||
position: relative;
|
||||
height: 12px;
|
||||
background: var(--bg-muted);
|
||||
border-radius: 7px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.track__bar {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
background: var(--marker-green);
|
||||
border-radius: 7px;
|
||||
transition: width 0.35s ease-out;
|
||||
}
|
||||
.progress-card__note {
|
||||
margin: 7px 0 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.progress-card__note b {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
flex: none;
|
||||
}
|
||||
.stat {
|
||||
padding: 8px 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-left: 3px solid var(--accent);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.stat--wide {
|
||||
grid-column: span 2;
|
||||
}
|
||||
.stat__label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--text-weak);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.stat__num {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 23px;
|
||||
color: var(--text-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.stat__num--ok {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.stat__num--danger {
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.stat__num--warn {
|
||||
color: #d9a424;
|
||||
}
|
||||
|
||||
/* 高危城市面板(只有城市 + 概率) */
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 8px 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-card);
|
||||
}
|
||||
.panel__head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
}
|
||||
.panel__title {
|
||||
font-family: var(--font-display);
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.panel__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.panel__count {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 17px;
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.panel__count--zero {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.panel__note {
|
||||
margin: 2px 0 6px;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.panel__empty {
|
||||
padding: 12px 2px;
|
||||
font-size: 13px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.risk-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 6px;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.risk-item {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
padding: 6px 9px;
|
||||
background: rgba(224, 64, 44, 0.06);
|
||||
border: 1px solid rgba(224, 64, 44, 0.35);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.risk-item__city {
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.risk-item__rate {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 19px;
|
||||
font-weight: 600;
|
||||
color: var(--marker-red);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 右栏表格:占满全高,行更高、字更大 */
|
||||
.page__table {
|
||||
min-height: 0;
|
||||
padding: 6px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-card);
|
||||
overflow: hidden;
|
||||
}
|
||||
.page__table :deep(.el-table__row) {
|
||||
height: 54px;
|
||||
}
|
||||
.page__table :deep(.el-table .cell) {
|
||||
font-size: 16px;
|
||||
}
|
||||
.page__table :deep(.el-table th.el-table__cell) {
|
||||
font-size: 14px;
|
||||
}
|
||||
.page__foot {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.page__foot code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.city {
|
||||
font-size: 17px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.tag-empty {
|
||||
margin-left: 6px;
|
||||
padding: 0 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
color: #9a6b00;
|
||||
background: rgba(217, 164, 36, 0.18);
|
||||
border: 1px solid rgba(217, 164, 36, 0.5);
|
||||
border-radius: 6px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge {
|
||||
padding: 1px 9px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
color: #fff;
|
||||
background: var(--marker-red);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.badge--abnormal {
|
||||
background: #b3261e;
|
||||
box-shadow: 0 0 0 2px rgba(179, 38, 30, 0.18);
|
||||
}
|
||||
.mono {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 16px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.ok {
|
||||
color: var(--marker-green);
|
||||
}
|
||||
.danger {
|
||||
color: var(--marker-red);
|
||||
}
|
||||
.weak {
|
||||
font-size: 15px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.empty {
|
||||
padding: 24px;
|
||||
font-size: 13px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 美团酒店任务看板:前端 5175,后端 8011(避开出行任务面板的 5174/8010)
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5175,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:8011',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:8011',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,170 @@
|
||||
"""埋点验证:静态检查埋点位置 + 动态验证 run_one 的两条链路。
|
||||
|
||||
用法(在 dashboard 目录):
|
||||
python scripts/verify_insight.py
|
||||
|
||||
特点:不会发真实网络请求、不会写数据库(update_headers 被替换为空实现),
|
||||
日志写到临时目录,不污染 酒店/logs。
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] # dashboard/
|
||||
HOTEL_DIR = ROOT.parent # 酒店/
|
||||
sys.path.insert(0, str(HOTEL_DIR))
|
||||
|
||||
import hotel_insight as insight # noqa: E402
|
||||
import 酒店详情 as hd # noqa: E402
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def static_checks() -> None:
|
||||
print("[1] 静态检查(酒店详情.py 埋点位置)")
|
||||
src = (HOTEL_DIR / "酒店详情.py").read_text(encoding="utf-8")
|
||||
check("import hotel_insight as insight" in src, "已 import 埋点模块")
|
||||
check("mt_traceid,dfpid FROM" in src, "get_headers 的 SELECT 已追加 dfpid 列")
|
||||
check("ind, hd, prox, city, mt_traceid, dfpid = item" in src, "item 已改为 6 元组解包")
|
||||
check(src.count("insight.log_fetch(") == 1, "log_fetch 调用 1 处", f"实际 {src.count('insight.log_fetch(')}")
|
||||
check(src.count("insight.log_fetch_empty(") == 1, "log_fetch_empty 调用 1 处", f"实际 {src.count('insight.log_fetch_empty(')}")
|
||||
check(src.count("insight.log_upload(") == 2, "log_upload 调用 2 处(shelf / prepayList)", f"实际 {src.count('insight.log_upload(')}")
|
||||
check(src.count("insight.log_exception(") == 5, "log_exception 调用 5 处(except + 两处 418/401)", f"实际 {src.count('insight.log_exception(')}")
|
||||
# upload 埋点必须紧跟在 upload_one_task 之后
|
||||
idx_upload = src.find("_upload_resp = upload_one_task(")
|
||||
check(idx_upload > 0 and "insight.log_upload(" in src[idx_upload : idx_upload + 600], "log_upload 紧跟 upload_one_task")
|
||||
# except 分支的 is_ok 判定逻辑未被改动
|
||||
check("if 'Expecting value: line 1 column 1 (char 0)' in str(e):" in src, "except 分支原判定逻辑保留")
|
||||
|
||||
|
||||
def make_run():
|
||||
"""构造不连库的 hotel_run 实例(跳过 __init__)。"""
|
||||
obj = hd.hotel_run.__new__(hd.hotel_run)
|
||||
obj.proxy_list = [
|
||||
(json.dumps({"http": "http://u:p@1.2.3.4:1", "https": "http://u:p@1.2.3.4:1"}), "南宁"),
|
||||
]
|
||||
obj.bound_city = "南宁"
|
||||
obj.last_trace_id = None
|
||||
obj.update_headers = lambda *a, **k: None # 不写库
|
||||
return obj
|
||||
|
||||
|
||||
TASK = {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"hotelId": "938833723",
|
||||
"cityId": "50",
|
||||
"hotelName": "杭州拱墅大运河轻居酒店",
|
||||
"cityName": "南宁市",
|
||||
"checkInDate": "2026-10-21",
|
||||
"checkOutDate": "2026-10-22",
|
||||
"uniqueId": "20261020120000-32-32-3000001-443-411",
|
||||
"selectedCity": "广西壮族自治区:50_南宁市",
|
||||
},
|
||||
}
|
||||
|
||||
ITEMS = [(13888, '["https://ihotel.meituan.com/unknown/path", {}, ""]', None, "南宁", None, "abcdefgh8f42ac81")]
|
||||
|
||||
|
||||
def dyn_empty(tmp: str) -> None:
|
||||
print("[2] 动态:get_one_task 返回 False(拿任务失败链路)")
|
||||
obj = make_run()
|
||||
with mock.patch.object(hd, "get_one_task", return_value=False):
|
||||
ret = obj.run_one(list(ITEMS))
|
||||
check(ret == -1, "run_one 返回 -1(原行为不变)", f"实际 {ret}")
|
||||
events = read_events(tmp)
|
||||
empty = [e for e in events if e["event"] == "fetch_empty"]
|
||||
check(len(empty) == 1, "写入 1 条 fetch_empty", f"实际 {len(empty)}")
|
||||
if empty:
|
||||
e = empty[0]
|
||||
check(e["hd_id"] == 13888, "fetch_empty 带 hd_id")
|
||||
check(e["dfpid_tail"] == "8f42ac81", "dfpid 已脱敏为后 8 位", e["dfpid_tail"])
|
||||
check(e["target_city"] == "南宁", "带目标城市")
|
||||
|
||||
|
||||
def dyn_task(tmp: str) -> None:
|
||||
print("[3] 动态:领到任务(fetch_task 链路)")
|
||||
obj = make_run()
|
||||
with mock.patch.object(hd, "get_one_task", return_value=TASK):
|
||||
# hd 里的 url 不命中任何接口分支 → 走“未知接口,跳过”,不会发网络请求
|
||||
obj.run_one(list(ITEMS))
|
||||
events = read_events(tmp)
|
||||
fetched = [e for e in events if e["event"] == "fetch_task"]
|
||||
check(len(fetched) == 1, "写入 1 条 fetch_task", f"实际 {len(fetched)}")
|
||||
if fetched:
|
||||
e = fetched[0]
|
||||
check(e["hd_id"] == 13888 and e["hotel_id"] == "938833723", "带账号与酒店 ID")
|
||||
check(e["city_name"] == "南宁市", "带任务城市名")
|
||||
check(e["unique_id"] == TASK["data"]["uniqueId"], "带 uniqueId")
|
||||
|
||||
|
||||
def read_events(tmp: str) -> list[dict]:
|
||||
path = Path(tmp) / ("run_" + __import__("datetime").datetime.now().strftime("%Y%m%d") + ".jsonl")
|
||||
if not path.is_file():
|
||||
return []
|
||||
out = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
out.append(json.loads(line))
|
||||
return out
|
||||
|
||||
|
||||
def dyn_no_log() -> None:
|
||||
"""写日志失败不得影响采集主流程(05 文档 8.3 第 3 条)。"""
|
||||
print("[4] 动态:日志目录不可写时的降级")
|
||||
obj = make_run()
|
||||
old = insight.LOG_DIR
|
||||
insight.LOG_DIR = "Z:\\definitely-not-exist\\logs"
|
||||
try:
|
||||
with mock.patch.object(hd, "get_one_task", return_value=False):
|
||||
ret_empty = obj.run_one(list(ITEMS))
|
||||
check(ret_empty == -1, "写日志失败时 run_one 仍返回 -1(未崩溃)", f"实际 {ret_empty}")
|
||||
with mock.patch.object(hd, "get_one_task", return_value=TASK):
|
||||
obj.run_one(list(ITEMS))
|
||||
check(True, "写日志失败时 fetch_task 链路也正常结束")
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(False, "写日志失败时 run_one 抛异常", f"{type(e).__name__}: {e}")
|
||||
finally:
|
||||
insight.LOG_DIR = old
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# import 无副作用检查
|
||||
print("[0] import 检查")
|
||||
check(hasattr(hd, "hotel_run"), "import 酒店详情 成功(顶层无副作用)")
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="insight_verify_")
|
||||
insight.LOG_DIR = tmp
|
||||
print(f"\n临时日志目录: {tmp}\n")
|
||||
static_checks()
|
||||
dyn_empty(tmp)
|
||||
dyn_task(tmp)
|
||||
dyn_no_log()
|
||||
print("\n[5] 产生的原始事件:")
|
||||
for e in read_events(tmp):
|
||||
print(" " + json.dumps(e, ensure_ascii=False))
|
||||
if FAILS:
|
||||
print("\n✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("\n✓ 埋点验证全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,158 @@
|
||||
"""美团酒店任务看板 一键启动。
|
||||
|
||||
- 后端 FastAPI :8011(uvicorn,读 backend/.env)
|
||||
- 前端 Vite :5175(npm run dev,开发模式)
|
||||
- 启动完成后自动打开浏览器;Ctrl+C 自动清理子进程
|
||||
|
||||
可选参数:
|
||||
python start.py --no-browser 不自动打开浏览器
|
||||
python start.py --static 纯后端模式:页面由 8011 托管 frontend/dist,
|
||||
无需 Node/构建环境(需 dist 产物随项目携带)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
BACKEND = ROOT / "backend"
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
API_PORT = 8011
|
||||
WEB_PORT = 5175
|
||||
HEALTH_URL = f"http://127.0.0.1:{API_PORT}/api/health"
|
||||
WEB_URL = f"http://localhost:{WEB_PORT}"
|
||||
|
||||
procs: list[subprocess.Popen] = []
|
||||
|
||||
|
||||
def eprint(msg: str) -> None:
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def port_in_use(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.5)
|
||||
return s.connect_ex(("127.0.0.1", port)) == 0
|
||||
|
||||
|
||||
def check_env(static: bool = False) -> None:
|
||||
"""前置检查:后端依赖 / 前端依赖 / dist 产物"""
|
||||
if not (BACKEND / ".env").exists():
|
||||
eprint("[WARN] backend/.env 不存在,将使用 config.py 默认值(多半连不上数据库)")
|
||||
try:
|
||||
import fastapi # noqa: F401
|
||||
import uvicorn # noqa: F401
|
||||
except ImportError:
|
||||
eprint("[ERROR] 后端依赖缺失,请先执行:pip install -r backend/requirements.txt")
|
||||
sys.exit(1)
|
||||
if static:
|
||||
if not (FRONTEND / "dist").exists():
|
||||
eprint("[ERROR] 静态模式需要 frontend/dist 构建产物(开发机执行 npm run build 后随项目拷贝)")
|
||||
sys.exit(1)
|
||||
return
|
||||
if not (FRONTEND / "node_modules").exists():
|
||||
eprint("[ERROR] 前端依赖缺失,请先执行:cd frontend && npm install")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def stop_all() -> None:
|
||||
"""终止全部子进程(Windows 杀进程树,避免残留 node/python)"""
|
||||
for p in procs:
|
||||
if p.poll() is None:
|
||||
try:
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True)
|
||||
except Exception:
|
||||
try:
|
||||
p.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def wait_backend_ready(timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if any(p.poll() is not None for p in procs):
|
||||
eprint("[ERROR] 有进程提前退出,请查看上方日志")
|
||||
stop_all()
|
||||
sys.exit(1)
|
||||
try:
|
||||
with urlopen(HEALTH_URL, timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="美团酒店任务看板 一键启动")
|
||||
parser.add_argument("--no-browser", action="store_true", help="启动后不自动打开浏览器")
|
||||
parser.add_argument("--static", action="store_true", help="纯后端模式:用 8011 托管 frontend/dist")
|
||||
args = parser.parse_args()
|
||||
|
||||
eprint("=" * 40)
|
||||
eprint("美团酒店任务看板 启动" + ("(静态模式)" if args.static else ""))
|
||||
eprint("=" * 40)
|
||||
|
||||
check_env(static=args.static)
|
||||
|
||||
ports = [API_PORT] if args.static else [API_PORT, WEB_PORT]
|
||||
for port in ports:
|
||||
if port_in_use(port):
|
||||
eprint(f"[ERROR] 端口 {port} 已被占用(服务可能已在运行),请先关闭再启动。")
|
||||
sys.exit(1)
|
||||
|
||||
eprint(f"[1/2] 启动后端 FastAPI http://127.0.0.1:{API_PORT}")
|
||||
procs.append(
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(API_PORT)],
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
)
|
||||
|
||||
if args.static:
|
||||
eprint("[static] 纯后端模式(页面由 8011 托管 dist,无需 Node)")
|
||||
target = f"http://127.0.0.1:{API_PORT}"
|
||||
else:
|
||||
eprint(f"[2/2] 启动前端 Vite {WEB_URL}")
|
||||
npm = "npm.cmd" if os.name == "nt" else "npm"
|
||||
procs.append(subprocess.Popen([npm, "run", "dev"], cwd=str(FRONTEND)))
|
||||
target = WEB_URL
|
||||
|
||||
eprint("等待服务就绪 ...")
|
||||
if not wait_backend_ready():
|
||||
eprint("[ERROR] 后端在 40 秒内未就绪,请查看上方日志")
|
||||
stop_all()
|
||||
sys.exit(1)
|
||||
if not args.static:
|
||||
time.sleep(2) # 等 Vite 编译完成
|
||||
|
||||
eprint(f"✓ 启动完成,访问 {target}")
|
||||
if not args.no_browser:
|
||||
webbrowser.open(target)
|
||||
|
||||
eprint("按 Ctrl+C 停止服务 ...")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
eprint("\n正在关闭服务 ...")
|
||||
stop_all()
|
||||
eprint("已退出")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,155 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""美团酒店采集埋点(只写本地 JSONL,不落库、不建表)。
|
||||
|
||||
设计约束(见 dashboard/docs/05_采集端埋点需求.md):
|
||||
1. 任何异常都被吞掉:写日志失败只表现为“少一条日志”,绝不影响采集主流程;
|
||||
2. 纯本地文件追加,无网络、无数据库、无重试、不阻塞;
|
||||
3. 按天分文件:logs/run_YYYYMMDD.jsonl,跨零点自动换文件;
|
||||
4. 脱敏:dfpid 只写后 8 位;msg 截断 200 字;不写 headers/token/代理密码。
|
||||
|
||||
关闭开关:环境变量 HOTEL_INSIGHT_OFF=1
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
|
||||
_TAIL = 8 # dfpid 保留位数
|
||||
_MSG_MAX = 200
|
||||
_NAME_MAX = 60
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return os.environ.get("HOTEL_INSIGHT_OFF", "") != "1"
|
||||
|
||||
|
||||
def log_path(now: datetime = None) -> str:
|
||||
now = now or datetime.now()
|
||||
return os.path.join(LOG_DIR, "run_%s.jsonl" % now.strftime("%Y%m%d"))
|
||||
|
||||
|
||||
def _tail(value) -> str:
|
||||
"""dfpid → 后 8 位(字符串化后截断,None → 空)。"""
|
||||
if not value:
|
||||
return ""
|
||||
text = str(value)
|
||||
return text[-_TAIL:] if len(text) > _TAIL else text
|
||||
|
||||
|
||||
def _cut(value, limit: int) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value)
|
||||
return text[:limit]
|
||||
|
||||
|
||||
def _as_dict(value):
|
||||
"""把可能为 str 的响应体转成 dict;失败返回空 dict。"""
|
||||
if isinstance(value, dict):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
except (ValueError, TypeError):
|
||||
return {}
|
||||
return {}
|
||||
|
||||
|
||||
def _write(record: dict) -> None:
|
||||
if not enabled():
|
||||
return
|
||||
try:
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
with open(log_path(), "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
except Exception:
|
||||
# 埋点永不抛异常
|
||||
pass
|
||||
|
||||
|
||||
def log_event(event: str, *,
|
||||
hd_id=None, dfpid=None, bind_city=None, target_city=None,
|
||||
city_name=None, hotel_id=None, hotel_name=None, unique_id=None,
|
||||
code=None, ok=None, msg=None) -> None:
|
||||
"""写一条事件。字段白名单见 05 文档第 3 节。"""
|
||||
record = {
|
||||
"ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"event": event,
|
||||
"hd_id": hd_id,
|
||||
"dfpid_tail": _tail(dfpid),
|
||||
"bind_city": bind_city,
|
||||
"target_city": target_city,
|
||||
"city_name": city_name,
|
||||
"hotel_id": None if hotel_id is None else str(hotel_id),
|
||||
"hotel_name": _cut(hotel_name, _NAME_MAX) or None,
|
||||
"unique_id": None if unique_id is None else str(unique_id),
|
||||
"code": code,
|
||||
"ok": ok,
|
||||
"msg": _cut(msg, _MSG_MAX) or None,
|
||||
}
|
||||
_write(record)
|
||||
|
||||
|
||||
def log_fetch(hd_id, dfpid, bind_city, target_city, task) -> None:
|
||||
"""领到任务:task 为 get_one_task() 的返回体(含 data)。"""
|
||||
data = (_as_dict(task).get("data") or {}) if task else {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
log_event(
|
||||
"fetch_task",
|
||||
hd_id=hd_id, dfpid=dfpid, bind_city=bind_city, target_city=target_city,
|
||||
city_name=data.get("cityName"),
|
||||
hotel_id=data.get("hotelId"),
|
||||
hotel_name=data.get("hotelName"),
|
||||
unique_id=data.get("uniqueId"),
|
||||
ok=1,
|
||||
)
|
||||
|
||||
|
||||
def log_fetch_empty(hd_id, dfpid, bind_city, target_city, resp=None, note: str = "") -> None:
|
||||
"""没领到任务:resp 可能是 False / None / dict(含 code、message)。"""
|
||||
if resp is None or resp is False:
|
||||
code, message = None, note or "城市未匹配"
|
||||
else:
|
||||
body = _as_dict(resp)
|
||||
code = body.get("code")
|
||||
message = body.get("message") or body.get("msg") or note or ""
|
||||
log_event(
|
||||
"fetch_empty",
|
||||
hd_id=hd_id, dfpid=dfpid, bind_city=bind_city, target_city=target_city,
|
||||
code=code if isinstance(code, int) else None,
|
||||
ok=0,
|
||||
msg=message,
|
||||
)
|
||||
|
||||
|
||||
def log_upload(hd_id, dfpid, target_city, resp, unique_id=None, city_name=None) -> None:
|
||||
"""交任务结果:resp 为 upload_task_datagram() 的返回体。"""
|
||||
body = _as_dict(resp)
|
||||
code = body.get("code")
|
||||
ok = 1 if code == 0 else 0
|
||||
log_event(
|
||||
"upload",
|
||||
hd_id=hd_id, dfpid=dfpid, target_city=target_city,
|
||||
city_name=city_name, unique_id=unique_id,
|
||||
code=code if isinstance(code, int) else None,
|
||||
ok=ok,
|
||||
msg=body.get("message") or body.get("msg"),
|
||||
)
|
||||
|
||||
|
||||
def log_exception(hd_id, dfpid, target_city, exc, code=None) -> None:
|
||||
"""异常:exc 可以是异常对象,也可以是错误文案(如 'Unauthorized(401)')。"""
|
||||
if isinstance(exc, BaseException):
|
||||
text = "%s: %s" % (type(exc).__name__, exc)
|
||||
elif exc is None:
|
||||
text = ""
|
||||
else:
|
||||
text = str(exc)
|
||||
log_event(
|
||||
"exception",
|
||||
hd_id=hd_id, dfpid=dfpid, target_city=target_city,
|
||||
code=code, ok=0, msg=text,
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
import os
|
||||
from datetime import datetime
|
||||
class Logger:
|
||||
log_dir = 'logs'
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
GREEN = '\033[92m'
|
||||
BLUE = '\033[94m'
|
||||
RED = '\033[91m'
|
||||
RESET = '\033[0m'
|
||||
log_file_path = os.path.join(log_dir, f'{datetime.now().strftime("%Y-%m-%d")}.txt')
|
||||
|
||||
@staticmethod
|
||||
def _write_to_file(level, message):
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
log_entry = f"{timestamp} [{level}] {message}\n"
|
||||
with open(Logger.log_file_path, 'a', encoding='utf-8') as f:
|
||||
f.write(log_entry)
|
||||
|
||||
@staticmethod
|
||||
def success(message):
|
||||
print(f"{Logger.GREEN}[+] {message}{Logger.RESET}")
|
||||
Logger._write_to_file('SUCCESS', message)
|
||||
|
||||
@staticmethod
|
||||
def info(message):
|
||||
print(f"{Logger.BLUE}[*] {message}{Logger.RESET}")
|
||||
Logger._write_to_file('INFO', message)
|
||||
|
||||
@staticmethod
|
||||
def error(message):
|
||||
print(f"{Logger.RED}[!] {message}{Logger.RESET}")
|
||||
Logger._write_to_file('ERROR', message)
|
||||
@@ -0,0 +1,109 @@
|
||||
{"ts": "2026-10-21T18:09:17", "action": "change_city", "hd_id": 13969, "dfpid_tail": "…v382020w", "old_city": "兰州", "new_city": "佛山", "old_prox_ip": "0ybq.smart.51tcp.net:20175", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": 0, "old_current_count": 211, "new_current_count": 0, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-21T19:35:26", "action": "set_city", "hd_id": 14061, "dfpid_tail": "…w3824w55", "old_city": null, "new_city": "银川", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-21T20:05:32", "action": "set_city", "hd_id": 14112, "dfpid_tail": "…v3y081y3", "old_city": null, "new_city": "太原", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:17:27", "action": "set_city", "hd_id": 14112, "dfpid_tail": "…v3y081y3", "old_city": null, "new_city": "乌鲁木齐", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:17:36", "action": "set_city", "hd_id": 14109, "dfpid_tail": "…0417wy90", "old_city": null, "new_city": "昆明", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:19:33", "action": "set_city", "hd_id": 14028, "dfpid_tail": "…689349vz", "old_city": null, "new_city": "兰州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:19:44", "action": "set_city", "hd_id": 14031, "dfpid_tail": "…02u4uy05", "old_city": null, "new_city": "福州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:19:49", "action": "set_city", "hd_id": 14034, "dfpid_tail": "…56v7555z", "old_city": null, "new_city": "重庆", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:20:29", "action": "set_city", "hd_id": 14035, "dfpid_tail": "…1221xw63", "old_city": null, "new_city": "呼和浩特", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:20:41", "action": "set_city", "hd_id": 14118, "dfpid_tail": "…32z11393", "old_city": null, "new_city": "福州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:21:01", "action": "set_city", "hd_id": 14067, "dfpid_tail": "…zz1x55x9", "old_city": null, "new_city": "昆明", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:21:29", "action": "set_city", "hd_id": 14094, "dfpid_tail": "…34xy7812", "old_city": null, "new_city": "乌鲁木齐", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:40:27", "action": "change_city", "hd_id": 14035, "dfpid_tail": "…1221xw63", "old_city": "呼和浩特", "new_city": "广州", "old_prox_ip": "2p3c.smart.51tcp.net:20174", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:40:56", "action": "change_city", "hd_id": 13137, "dfpid_tail": "…y4yy05zx", "old_city": "北京", "new_city": "呼和浩特", "old_prox_ip": "2p3c.smart.51tcp.net:21209", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T11:41:08", "action": "change_city", "hd_id": 13137, "dfpid_tail": "…y4yy05zx", "old_city": "呼和浩特", "new_city": "昆明", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T12:03:07", "action": "set_city", "hd_id": 14124, "dfpid_tail": "…v6w56481", "old_city": null, "new_city": "青岛", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T12:07:38", "action": "change_city", "hd_id": 13137, "dfpid_tail": "…y4yy05zx", "old_city": "昆明", "new_city": "深圳", "old_prox_ip": "223.93.69.248:47890", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T12:14:36", "action": "change_city", "hd_id": 14035, "dfpid_tail": "…1221xw63", "old_city": "广州", "new_city": "哈尔滨", "old_prox_ip": "e5xd.smart.51tcp.net:21323", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T14:38:52", "action": "set_city", "hd_id": 14127, "dfpid_tail": "…8yu1u1wv", "old_city": null, "new_city": "青岛", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T14:39:04", "action": "set_city", "hd_id": 14130, "dfpid_tail": "…2z97x4uv", "old_city": null, "new_city": "哈尔滨", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T14:40:32", "action": "set_city", "hd_id": 14133, "dfpid_tail": "…z50x48v4", "old_city": null, "new_city": "长沙", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T14:47:10", "action": "set_city", "hd_id": 14136, "dfpid_tail": "…70uvy7w3", "old_city": null, "new_city": "青岛", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T14:55:43", "action": "set_city", "hd_id": 14139, "dfpid_tail": "…ww6xwy33", "old_city": null, "new_city": "重庆", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:08:55", "action": "set_city", "hd_id": 14142, "dfpid_tail": "…w84z6x34", "old_city": null, "new_city": "成都", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:25:24", "action": "set_city", "hd_id": 14151, "dfpid_tail": "…v95yv6yw", "old_city": null, "new_city": "重庆", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:33:01", "action": "set_city", "hd_id": 14153, "dfpid_tail": "…wwy68x46", "old_city": null, "new_city": "成都", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:37:09", "action": "change_city", "hd_id": 14151, "dfpid_tail": "…v95yv6yw", "old_city": "重庆", "new_city": "青岛", "old_prox_ip": "4pkw.smart.51tcp.net:20211", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:40:53", "action": "change_city", "hd_id": 14151, "dfpid_tail": "…v95yv6yw", "old_city": "青岛", "new_city": "贵阳", "old_prox_ip": "183.131.35.73:21432", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:42:00", "action": "set_city", "hd_id": 14155, "dfpid_tail": "…11w65789", "old_city": null, "new_city": "兰州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:49:08", "action": "set_city", "hd_id": 14157, "dfpid_tail": "…u27z5xu4", "old_city": null, "new_city": "长沙", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T15:58:02", "action": "change_city", "hd_id": 14155, "dfpid_tail": "…11w65789", "old_city": "兰州", "new_city": "佛山", "old_prox_ip": "0ybq.smart.51tcp.net:20175", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:03:30", "action": "set_city", "hd_id": 14159, "dfpid_tail": "…x3v4987v", "old_city": null, "new_city": "乌鲁木齐", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:03:42", "action": "change_city", "hd_id": 14157, "dfpid_tail": "…u27z5xu4", "old_city": "长沙", "new_city": "南京", "old_prox_ip": "139y.smart.51tcp.net:20431", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:05:10", "action": "set_city", "hd_id": 14161, "dfpid_tail": "…4vuvxwx0", "old_city": null, "new_city": "深圳", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:12:19", "action": "set_city", "hd_id": 14163, "dfpid_tail": "…58274546", "old_city": null, "new_city": "沈阳", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:12:33", "action": "set_city", "hd_id": 14165, "dfpid_tail": "…51y3uu89", "old_city": null, "new_city": "上海", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:16:24", "action": "change_city", "hd_id": 14155, "dfpid_tail": "…11w65789", "old_city": "佛山", "new_city": "广州", "old_prox_ip": "e5xd.smart.51tcp.net:20014", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:21:05", "action": "set_city", "hd_id": 14167, "dfpid_tail": "…59xx8v96", "old_city": null, "new_city": "大连", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:25:59", "action": "set_city", "hd_id": 14169, "dfpid_tail": "…0v6606uu", "old_city": null, "new_city": "广州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:29:28", "action": "change_city", "hd_id": 14159, "dfpid_tail": "…x3v4987v", "old_city": "乌鲁木齐", "new_city": "重庆", "old_prox_ip": "orlk.smart.51tcp.net:20491", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:36:11", "action": "set_city", "hd_id": 14171, "dfpid_tail": "…9uu29vz1", "old_city": null, "new_city": "武汉", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:44:06", "action": "set_city", "hd_id": 14173, "dfpid_tail": "…88z24y02", "old_city": null, "new_city": "天津", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:44:32", "action": "change_city", "hd_id": 14167, "dfpid_tail": "…59xx8v96", "old_city": "大连", "new_city": "西安", "old_prox_ip": "183.131.35.73:21442", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:54:02", "action": "change_city", "hd_id": 14163, "dfpid_tail": "…58274546", "old_city": "沈阳", "new_city": "长春", "old_prox_ip": "139y.smart.51tcp.net:21448", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:54:15", "action": "set_city", "hd_id": 14175, "dfpid_tail": "…7w2v92w8", "old_city": null, "new_city": "石家庄", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:57:00", "action": "change_city", "hd_id": 14167, "dfpid_tail": "…59xx8v96", "old_city": "西安", "new_city": "上海", "old_prox_ip": "n819.smart.51tcp.net:21258", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T16:57:41", "action": "change_city", "hd_id": 14167, "dfpid_tail": "…59xx8v96", "old_city": "上海", "new_city": "苏州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:04:43", "action": "set_city", "hd_id": 14177, "dfpid_tail": "…558v923y", "old_city": null, "new_city": "成都", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:25:23", "action": "set_city", "hd_id": 14179, "dfpid_tail": "…0yu633yx", "old_city": null, "new_city": "无锡", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:30:20", "action": "change_city", "hd_id": 14163, "dfpid_tail": "…58274546", "old_city": "长春", "new_city": "南京", "old_prox_ip": "oyxz.smart.51tcp.net:21186", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:36:46", "action": "change_city", "hd_id": 14175, "dfpid_tail": "…7w2v92w8", "old_city": "石家庄", "new_city": "济南", "old_prox_ip": "3q69.smart.51tcp.net:21169", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:40:45", "action": "change_city", "hd_id": 14173, "dfpid_tail": "…88z24y02", "old_city": "天津", "new_city": "厦门", "old_prox_ip": "n819.smart.51tcp.net:20493", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T17:52:02", "action": "change_city", "hd_id": 14169, "dfpid_tail": "…0v6606uu", "old_city": "广州", "new_city": "银川", "old_prox_ip": "e5xd.smart.51tcp.net:21323", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T18:07:57", "action": "change_city", "hd_id": 14175, "dfpid_tail": "…7w2v92w8", "old_city": "济南", "new_city": "拉萨", "old_prox_ip": "wvsr.smart.51tcp.net:20217", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-22T18:10:22", "action": "change_city", "hd_id": 14179, "dfpid_tail": "…0yu633yx", "old_city": "无锡", "new_city": "杭州", "old_prox_ip": "115.231.39.14:20661", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:18:17", "action": "set_city", "hd_id": 14258, "dfpid_tail": "…62vx211y", "old_city": null, "new_city": "广州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:18:45", "action": "set_city", "hd_id": 12760, "dfpid_tail": "…z9y72z14", "old_city": null, "new_city": "东莞", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:20:43", "action": "change_city", "hd_id": 13103, "dfpid_tail": "…z9u4z641", "old_city": "西宁", "new_city": "北京", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:20:54", "action": "change_city", "hd_id": 13482, "dfpid_tail": "…5x9x1150", "old_city": "广州", "new_city": "大连", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:21:12", "action": "change_city", "hd_id": 12766, "dfpid_tail": "…6z4818v3", "old_city": "上海", "new_city": "贵阳", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:21:43", "action": "change_city", "hd_id": 12763, "dfpid_tail": "…103z5u7w", "old_city": "深圳", "new_city": "海口", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:21:56", "action": "change_city", "hd_id": 12754, "dfpid_tail": "…7wy61x66", "old_city": "西宁", "new_city": "福州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:23:42", "action": "change_city", "hd_id": 14254, "dfpid_tail": "…0uy86u99", "old_city": "杭州", "new_city": "兰州", "old_prox_ip": "e5xd.smart.51tcp.net:21072", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:23:55", "action": "change_city", "hd_id": 14256, "dfpid_tail": "…z44x94y1", "old_city": "杭州", "new_city": "成都", "old_prox_ip": "e5xd.smart.51tcp.net:21072", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:39:12", "action": "change_city", "hd_id": 14254, "dfpid_tail": "…0uy86u99", "old_city": "兰州", "new_city": "广州", "old_prox_ip": "0ybq.smart.51tcp.net:20175", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:49:24", "action": "change_city", "hd_id": 12764, "dfpid_tail": "…28zv0301", "old_city": "上海", "new_city": "广州", "old_prox_ip": "orlk.smart.51tcp.net:20188", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T11:49:36", "action": "change_city", "hd_id": 14256, "dfpid_tail": "…z44x94y1", "old_city": "成都", "new_city": "福州", "old_prox_ip": "jzu2.smart.51tcp.net:21051", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T12:14:25", "action": "set_city", "hd_id": 14259, "dfpid_tail": "…3v4zx345", "old_city": null, "new_city": "广州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T12:55:55", "action": "set_city", "hd_id": 14261, "dfpid_tail": "…v45x880v", "old_city": null, "new_city": "广州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:00:14", "action": "change_city", "hd_id": 14261, "dfpid_tail": "…v45x880v", "old_city": "广州", "new_city": "上海", "old_prox_ip": "e5xd.smart.51tcp.net:21323", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:05:14", "action": "set_city", "hd_id": 14263, "dfpid_tail": "…y5y38112", "old_city": null, "new_city": "上海", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:08:23", "action": "change_city", "hd_id": 14261, "dfpid_tail": "…v45x880v", "old_city": "上海", "new_city": "哈尔滨", "old_prox_ip": "orlk.smart.51tcp.net:20188", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:08:35", "action": "change_city", "hd_id": 14259, "dfpid_tail": "…3v4zx345", "old_city": "广州", "new_city": "昆明", "old_prox_ip": "e5xd.smart.51tcp.net:21323", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:30:37", "action": "set_city", "hd_id": 14265, "dfpid_tail": "…72x3u35u", "old_city": null, "new_city": "上海", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:35:21", "action": "change_city", "hd_id": 14265, "dfpid_tail": "…72x3u35u", "old_city": "", "new_city": "大连", "old_prox_ip": "orlk.smart.51tcp.net:20188", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:37:28", "action": "change_city", "hd_id": 14263, "dfpid_tail": "…y5y38112", "old_city": "上海", "new_city": "成都", "old_prox_ip": "orlk.smart.51tcp.net:20188", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T13:44:59", "action": "change_city", "hd_id": 14265, "dfpid_tail": "…72x3u35u", "old_city": "大连", "new_city": "成都", "old_prox_ip": "183.131.35.73:21442", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T14:13:15", "action": "set_city", "hd_id": 14267, "dfpid_tail": "…z01u4w10", "old_city": null, "new_city": "成都", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T14:32:05", "action": "set_city", "hd_id": 14271, "dfpid_tail": "…391vxy35", "old_city": null, "new_city": "武汉", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T14:50:12", "action": "set_city", "hd_id": 14275, "dfpid_tail": "…u2777342", "old_city": null, "new_city": "成都", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T14:56:23", "action": "set_city", "hd_id": 14277, "dfpid_tail": "…1xvwv4vu", "old_city": null, "new_city": "深圳", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:05:41", "action": "change_city", "hd_id": 14277, "dfpid_tail": "…1xvwv4vu", "old_city": "海口", "new_city": "西宁", "old_prox_ip": "jqj4.smart.51tcp.net:20756", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:14:41", "action": "change_city", "hd_id": 14277, "dfpid_tail": "…1xvwv4vu", "old_city": "西宁", "new_city": "呼和浩特", "old_prox_ip": "uvt8.smart.51tcp.net:21104", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:16:46", "action": "set_city", "hd_id": 14281, "dfpid_tail": "…4z0056xv", "old_city": null, "new_city": "南宁", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:26:36", "action": "change_city", "hd_id": 14279, "dfpid_tail": "…86yw12v0", "old_city": "济南", "new_city": "贵阳", "old_prox_ip": "wvsr.smart.51tcp.net:20217", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:42:16", "action": "set_city", "hd_id": 14283, "dfpid_tail": "…482wz829", "old_city": null, "new_city": "南宁", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:44:03", "action": "change_city", "hd_id": 14283, "dfpid_tail": "…482wz829", "old_city": "南宁", "new_city": "贵阳", "old_prox_ip": "yeaj.smart.51tcp.net:20637", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T15:47:37", "action": "set_city", "hd_id": 14285, "dfpid_tail": "…747w91vv", "old_city": null, "new_city": "东莞", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T16:56:29", "action": "set_city", "hd_id": 14287, "dfpid_tail": "…y71vv2w8", "old_city": null, "new_city": "东莞", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T16:58:19", "action": "change_city", "hd_id": 14287, "dfpid_tail": "…y71vv2w8", "old_city": "东莞", "new_city": "厦门", "old_prox_ip": "183.131.35.73:21435", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:04:42", "action": "set_city", "hd_id": 14289, "dfpid_tail": "…27wuyuuu", "old_city": null, "new_city": "南昌", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:05:51", "action": "change_city", "hd_id": 14287, "dfpid_tail": "…y71vv2w8", "old_city": "厦门", "new_city": "昆明", "old_prox_ip": "183.131.35.73:21436", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:08:57", "action": "change_city", "hd_id": 14289, "dfpid_tail": "…27wuyuuu", "old_city": "南昌", "new_city": "南京", "old_prox_ip": "139y.smart.51tcp.net:20944", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:12:18", "action": "set_city", "hd_id": 14291, "dfpid_tail": "…v87xx8yu", "old_city": null, "new_city": "合肥", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:16:20", "action": "change_city", "hd_id": 14289, "dfpid_tail": "…27wuyuuu", "old_city": "南京", "new_city": "银川", "old_prox_ip": "oyxz.smart.51tcp.net:20031", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:21:58", "action": "set_city", "hd_id": 14294, "dfpid_tail": "…6v617525", "old_city": null, "new_city": "沈阳", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:31:44", "action": "set_city", "hd_id": 14296, "dfpid_tail": "…833zv946", "old_city": null, "new_city": "长沙", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:38:07", "action": "change_city", "hd_id": 14291, "dfpid_tail": "…v87xx8yu", "old_city": "郑州", "new_city": "长春", "old_prox_ip": "5rfa.smart.51tcp.net:21292", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:44:11", "action": "change_city", "hd_id": 14294, "dfpid_tail": "…6v617525", "old_city": "沈阳", "new_city": "乌鲁木齐", "old_prox_ip": "139y.smart.51tcp.net:21448", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:44:48", "action": "set_city", "hd_id": 14298, "dfpid_tail": "…2zy23965", "old_city": null, "new_city": "天津", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:47:08", "action": "change_city", "hd_id": 13266, "dfpid_tail": "…w5w774yw", "old_city": "青岛", "new_city": "石家庄", "old_prox_ip": "183.131.35.73:21432", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:53:49", "action": "change_city", "hd_id": 14298, "dfpid_tail": "…2zy23965", "old_city": "天津", "new_city": "重庆", "old_prox_ip": "n819.smart.51tcp.net:20493", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:54:16", "action": "change_city", "hd_id": 14296, "dfpid_tail": "…833zv946", "old_city": "长沙", "new_city": "苏州", "old_prox_ip": "139y.smart.51tcp.net:20431", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T17:58:16", "action": "set_city", "hd_id": 14300, "dfpid_tail": "…vz1wwyx5", "old_city": null, "new_city": "福州", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T18:00:21", "action": "change_city", "hd_id": 14298, "dfpid_tail": "…2zy23965", "old_city": "重庆", "new_city": "太原", "old_prox_ip": "4pkw.smart.51tcp.net:20211", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T18:05:46", "action": "change_city", "hd_id": 14300, "dfpid_tail": "…vz1wwyx5", "old_city": "福州", "new_city": "佛山", "old_prox_ip": "115.231.39.14:20661", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T18:08:52", "action": "set_city", "hd_id": 14302, "dfpid_tail": "…x8794uzx", "old_city": null, "new_city": "石家庄", "old_prox_ip": null, "new_prox_ip": null, "old_is_ok": null, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T18:09:48", "action": "change_city", "hd_id": 14300, "dfpid_tail": "…vz1wwyx5", "old_city": "佛山", "new_city": "拉萨", "old_prox_ip": "e5xd.smart.51tcp.net:20014", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
{"ts": "2026-10-24T18:10:25", "action": "change_city", "hd_id": 14302, "dfpid_tail": "…x8794uzx", "old_city": "石家庄", "new_city": "西安", "old_prox_ip": "3q69.smart.51tcp.net:21169", "new_prox_ip": null, "old_is_ok": 0, "new_is_ok": null, "operator": "local", "result": "ok"}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+184
@@ -0,0 +1,184 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
class All_Setting():
|
||||
def __init__(self,host,port,db):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
|
||||
def remove_symbols(self,text):
|
||||
pattern = re.compile(r'[^\w\s]')
|
||||
return pattern.sub('', text)
|
||||
|
||||
def get_chinese(self,text,printTxt=False):
|
||||
# text = "海王星辰(广州智慧城店)"
|
||||
pattern = r'[^\w\s]'
|
||||
result = re.sub(pattern, '', text)
|
||||
if printTxt:
|
||||
print(result)
|
||||
return result
|
||||
|
||||
def get_shoppingmalls(self,sql):
|
||||
res_list = []
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print('ok')
|
||||
cursor = conn.cursor()
|
||||
res = cursor.execute(sql)
|
||||
c2 = cursor.fetchall()
|
||||
return c2
|
||||
|
||||
def write_data(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
|
||||
def update_data(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def update_data_many(self,sql, values):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql, values)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def write_data_one(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def get(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
return result
|
||||
|
||||
import json
|
||||
import time,requests
|
||||
|
||||
|
||||
def get_sign_meituan(url, dfpid, data):
|
||||
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
print(response1.text)
|
||||
mtgsig1 = response1.json()
|
||||
return str(mtgsig1)
|
||||
|
||||
def get_sign_waimai(url, dfpid, data):
|
||||
print('我是外卖mtg')
|
||||
|
||||
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
# "ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
mtgsig = response.json()
|
||||
print(mtgsig)
|
||||
return str(mtgsig)
|
||||
|
||||
def get_Datatext(dataq):
|
||||
str1 = ''
|
||||
for i in dataq:
|
||||
key, value = i, dataq[i]
|
||||
str2 = f'{key}={value}&'
|
||||
str1 = str1 + str2
|
||||
data = str1[0:-1]
|
||||
return data
|
||||
|
||||
|
||||
+18553
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,30 @@
|
||||
import requests
|
||||
|
||||
|
||||
url,headers,data = ["https://ihotel.meituan.com/productapi/v3/prepayList?yodaReady=wx&csecappid=wxde8ac0a21135c07d&csecplatform=3&csecversionname=10.37.2&csecversion=3.0.2&openId=oJVP50Fn77CACsJ6DvHoX4lLF_FY&antiRepPlatform=Android&programName=mt&utm_medium=WEIXINPROGRAM&riskLevel=71&optimusCode=10&openIdCipher=AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM%2Fhf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n%2FGVnwfURonD78PewMUppAAAADiJzzbxqROcoav4BdWAOSBfR6XRWVeW%2Bye%2Fq9NXWOlJ%2FRD6xbTWfvXXsP0yrwvvJ4m6gQKsmuO97A%3D%3D&utm_campaign=entry%253DMTLive_scene%253D1038&token=AgEqI2nL0LfdiLmKaTljnn1mEUC66YfNx8hUVryUkEShBa-XOdxaYDJ6lxD2HI8fPUv80GRZS2qy8gAAAABSOwAApmwpE2D7X_GWE8fPYUVE3zqXfZvz-c8ydbZ2FANX7ocVVMeHtTuUJLSjm_SXdtzc&usertoken=AgEqI2nL0LfdiLmKaTljnn1mEUC66YfNx8hUVryUkEShBa-XOdxaYDJ6lxD2HI8fPUv80GRZS2qy8gAAAABSOwAApmwpE2D7X_GWE8fPYUVE3zqXfZvz-c8ydbZ2FANX7ocVVMeHtTuUJLSjm_SXdtzc&userToken=AgEqI2nL0LfdiLmKaTljnn1mEUC66YfNx8hUVryUkEShBa-XOdxaYDJ6lxD2HI8fPUv80GRZS2qy8gAAAABSOwAApmwpE2D7X_GWE8fPYUVE3zqXfZvz-c8ydbZ2FANX7ocVVMeHtTuUJLSjm_SXdtzc&userId=4002222065&userid=4002222065&uuid=1a0c7bfbb6ec8-3d45a622b4dc5c-0-0-1a0c7bfbb6ec8&locateCityId=20&locatecityid=20&appMiniVersion=10.37.0&lat=23.129397&lng=113.299178&appletShieldScene=null&poiId=638820385&costSourceChannel=1&version_name=11.2.200&input=&keyword=&start=1790121600000&end=1790208000000&propagateData=K%2BdP0EcXIV9WKVKUHFoDqPD2tG3FnPU3XOfxgRQU8OEWCNZZFWF0nqOOw9w5W9DCUG8RZBziJInOgPZvxYJvRHNDT41iQ9d27zYdFXYGnwgQnjeOiTFkd2XSR4sE2sR5ZQuY0nEALmbkp88i4glGjZqHOXQcEu7sfvypY3tChODkLxP7rJ0dDYTUjohfyBf61Rgd8VV46KV21XvqqvCMYbSQan7J2wBHuvAGjlldlS5%2FQMb0Ex4PRVWwak2jo32Q7xhN1YXiI2dTk7GlJOpBVbzD2EMlbhfvIkUa%2BPl68zuHZzdFHxxivyKldrxBy5Yh2qVpKVJnrYG86ia9W1GUdU1PM8yywcbKhGWYw%2FtLgPTRf%2BNeWsWney3DDEnv1lzj%2FWMmB3pIoUd8lWDOLNDSfQ%3D%3D&mtShareId=&fromOffline=false&flagshipFilter=1&gps_cityid=20&needShowNewDiscInfo=false&cityId=20&ci=20&channelCityId=20&hotelCustomGpsStatus=0&type=1&specialDealHotelScene=true&riskPlatform=13&channelSelectCityId=20&appletVersionName=10.37.2&appletAppId=wxde8ac0a21135c07d&specAttributionChannel=&magicMemberCode=1102%2C1103&utm_fp=MINI_PROGRAM&wechatVersion=8.0.61&SDKVersion=3.9.3", {"Host": "ihotel.meituan.com", "Connection": "keep-alive", "content-type": "application/json", "x_htas_version": "0.1.31", "uuid": "1a0c7bfbb6ec8-3d45a622b4dc5c-0-0-1a0c7bfbb6ec8", "clientversion": "3.9.3", "utm_medium": "", "token": "AgEqI2nL0LfdiLmKaTljnn1mEUC66YfNx8hUVryUkEShBa-XOdxaYDJ6lxD2HI8fPUv80GRZS2qy8gAAAABSOwAApmwpE2D7X_GWE8fPYUVE3zqXfZvz-c8ydbZ2FANX7ocVVMeHtTuUJLSjm_SXdtzc", "openId": "oJVP50Fn77CACsJ6DvHoX4lLF_FY", "openIdCipher": "AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADiJzzbxqROcoav4BdWAOSBfR6XRWVeW+ye/q9NXWOlJ/RD6xbTWfvXXsP0yrwvvJ4m6gQKsmuO97A==", "csecuuid": "1a0c7bfbb6ec8-3d45a622b4dc5c-0-0-1a0c7bfbb6ec8", "csecuserid": "4002222065", "mtgsig": "{\"a1\":\"1.2\",\"a2\":1790162098958,\"a3\":\"x3824zyvv21w592uyywz7ww8319w86338z9x2yuyu5977978yz125x1v\",\"a4\":\"337f9aba0c93030bba9a7f330b03930cb44186febf4215f2\",\"a5\":\"qazNRr4D+B6+X4VwQBdMuVd5zEMshc1/+ZL0FQLR4MLqdkRC6XIUkey82HbssgpYH7sLN+t7lzU5W+THSwTxOjhyNKZ3hK5GOqGonuNOyqtsbEU8B1hrCBLOAeqbDbJhbEKJA6XfuSlFdrfJRMlNa5H8Mp6spisDp6S1hwGmcG8qAqw50It2UTEQUq1JAEt/00FoqVF4AslWfh7BQlI2ValDl3mupSJqCHZMth7e38KBH9VLpKG48T2a4D/bbH6v77SX6rnM9NXrMysWRaYY3Do285/06hwG71wuVM2pJ9Xi9VoOk0l6GrhLOL3h+yNxGVO0zViu\",\"a6\":\"w1.6H9r3PuLsRwq5cK6sJNxWpQyLuXa89i4Wl12rZhg3F1KQVTFrbpXDiadV12+u7o+8Ect8CFfxlg3lbIjtXPUUO9GerQJlu7GRMWdDH1pU31zCpHrcbzx6eKL53aeSwmW+Q8HF2HTDg2CeMjR7HPqJ7tdKRXTZJFVZI2B5WoGO2VKwmKlzILeZtcU4OoVtQHfegRV8ZQswOvsMqpbAvwrRJBFQ068HHe9DyaUv+ctLevnGwiZGpF+wDdDRt7Bf+2xGrBNP6WAXTGYQlJODELvD6cycV6RVS/BOUnXFvqOUn39J6ar5Ee3BG6u/LXUGiudkA26zBlfHNC98NwWqjubJE1qCwhEFGjXCaJ34iwYKDcQpi8+5KMI7IVxIid7enRNyK5gCHaj0k3ermB72/eDnhjEU4GCzE3tRO27YSYZN5XxR7our+hRArs6T3u1lSY1RDiOGyYrRONdU5cdncao8yHjTDPSwB/2gursYqtf0hDEpiMvbnBwmw2ntMojbn9b52CDzQDiIDylK42WGD66z73lzXiYY6jt+5+w3l7niVJU=\",\"a7\":\"wxde8ac0a21135c07d\",\"x0\":3,\"d1\":\"3496a913e57a1d62750928001cb6aa4d\"}", "M-TRACEID": "-8173144528399756215", "M-APPKEY": "wxmp_mt-weapp", "charset": "utf-8", "Referer": "https://servicewechat.com/wxde8ac0a21135c07d/1577/page-frame.html", "User-Agent": "Mozilla/5.0 (Linux; Android 13; VOG-TL00 Build/TP1A.220624.014; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/111.0.5563.116 Mobile Safari/537.36 MicroMessenger/8.0.61.2880(0x28003D34) WeChat/arm64 Weixin NetType/e4:66:e5:2e:b8:07 Language/zh_CN ABI/arm64 MiniProgramEnv/android", "Accept-Encoding": "gzip, deflate, br"}, ""]
|
||||
|
||||
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
openId = headers['openId']
|
||||
headers['mtgsig'] = get_sign_new1_get(url, '', dfpid, mtg_origin,openId)
|
||||
response = requests.get(url, headers=headers, data=data,verify=False)
|
||||
|
||||
print(response.text)
|
||||
print(response)
|
||||
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE `hotel_hd` (
|
||||
`id` int NOT NULL AUTO_INCREMENT,
|
||||
`dfpid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`json_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
|
||||
`title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`channel` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`is_ok` int DEFAULT NULL,
|
||||
`req_count` int DEFAULT NULL,
|
||||
`current_count` int DEFAULT '0',
|
||||
`prox` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`mt_traceid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
|
||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `dfpid` (`dfpid`) USING BTREE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=13919 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# 美团小程序 mtgsig 出签客户端(本地补环境,不依赖浏览器/远端签名服务)
|
||||
# 依赖常驻服务 mtgsig_js/serve.mjs,先跑 启动出签服务.py
|
||||
import os
|
||||
import json
|
||||
import urllib.parse
|
||||
import requests
|
||||
|
||||
BASE_URL = os.environ.get('MTGSIG_BASE_URL', 'http://192.168.5.134:18092')
|
||||
SIGN_TIMEOUT = 60
|
||||
PROXY = {'http': None, 'https': None}
|
||||
|
||||
|
||||
def get_Datatext(dataq):
|
||||
data = urllib.parse.urlencode(dataq)
|
||||
return data
|
||||
|
||||
def check_health():
|
||||
r = requests.get(BASE_URL + '/health', timeout=5, proxies=PROXY)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def derive_from_mtgsig(mtgsig):
|
||||
"""从一份 mtgsig(抓包里的旧签名即可)解出会话身份:appid / dfpid / localId / filetime"""
|
||||
r = requests.post(BASE_URL + '/derive', json={'mtgsig': mtgsig}, timeout=SIGN_TIMEOUT, proxies=PROXY)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def get_mtgsig(url, data, mtgsig, open_id, method, mode=None, sys=None, ext=None):
|
||||
"""按 url + body 出 mtgsig(url/data/mtgsig/open_id 必传)。
|
||||
|
||||
mtgsig 传抓包里的旧签名,appid/dfpid/localId/filetime 会从它的 a6 里自动解出;
|
||||
open_id 传请求头里的 openId(a6 里要带账号身份,缺了签名不对)。
|
||||
method 默认 POST;请求体按 x-www-form-urlencoded 处理(美团小程序绝大多数接口如此)。
|
||||
mode: 不传即走**纯算**(无预热、毫秒级);传 'bundle' 才用补环境跑 jsguard(每个新身份首次约 20s)。
|
||||
sys/ext: 按字段名覆盖 a6 里的 system(46 项)/ext(5 项),只传要改的那几个,不传就原样。
|
||||
sys 常用字段: brand/model/system/SDKVersion/version/screenWidth/screenHeight/pixelRatio/
|
||||
brightness/fontSizeSetting/language/networkType/wifiEnabled/hasSystemProxy/
|
||||
locationEnabled/bluetoothEnabled/deviceOrientation/LaunchOptionsSync 等(共 46 个,
|
||||
完整清单见 serve.mjs 的 SYSTEM_FIELDS)
|
||||
ext 字段: NativeClient / addEventListener / getPublicLibVersion / __WeixinJSBridge / NFC
|
||||
仅纯算生效;字段名写错服务端会直接报错(并回可用字段名)。
|
||||
同一个小程序下换任意接口都通用,只换 url + data 即可。
|
||||
data 传字典时按 x-www-form-urlencoded 自动拼成 k=v&k=v;传字符串则原样使用。
|
||||
"""
|
||||
# if isinstance(data, dict):
|
||||
# import traceback
|
||||
# traceback.print_exc()
|
||||
body = {'url': url, 'data': data, 'mtgsig': mtgsig, 'openId': open_id, 'method': method}
|
||||
if mode:
|
||||
body['mode'] = mode
|
||||
if sys is not None:
|
||||
body['sys'] = sys
|
||||
if ext is not None:
|
||||
body['ext'] = ext
|
||||
try:
|
||||
resp = requests.post(BASE_URL + '/sign', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError('出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
|
||||
return resp.json()['mtgsig']
|
||||
|
||||
|
||||
def get_h5_sign(url, data, method, mode, profile, cookie='', data_type='json', type=None):
|
||||
"""H5 出签(走服务里的 H5guard 补环境,非小程序 jsguard),返回整个结果 dict:
|
||||
{mtgsig, url, headers, mode, a3, a6pfx}
|
||||
|
||||
url / data / method / mode / profile 必传(profile 缺字段服务端直接报错)。
|
||||
profile = 设备/请求环境,全部来自抓包请求(没有内置默认身份):
|
||||
ua, referrer, origin, chBrands(sec-ch-ua 原串), chPlatform(sec-ch-ua-platform),
|
||||
chMobile(sec-ch-ua-mobile), language, languages(数组), platform, hardwareConcurrency,
|
||||
deviceMemory, maxTouchPoints, screenWidth, screenHeight, availHeight, colorDepth,
|
||||
devicePixelRatio, innerWidth, innerHeight, glVendor, glRenderer, appid, domains(数组)
|
||||
可选: title / model / architecture / bitness / platformVersion
|
||||
mode='sign':走手动 sign(),a6 前缀 h1.9 —— 外卖/买药 H5 页面自身 jquery 加签走这条。
|
||||
mode='xhr':走 SDK 自己的 XHR 自动加签,a6 前缀 hs1.6 —— maf.meituan.com 这类接口要这个;
|
||||
GET -> 用返回的 `url`(mtgsig 已拼进 query);POST -> 也用返回的 `url`。
|
||||
cookie 可选(dfpid 走 mtgsig.a3)。服务按 profile 缓存环境,每个新 profile 首次等指纹预热。
|
||||
"""
|
||||
body = {'url': url, 'data': data, 'method': method, 'mode': mode, 'profile': profile,
|
||||
'cookie': cookie, 'dataType': data_type, 'type': type or method}
|
||||
try:
|
||||
resp = requests.post(BASE_URL + '/sign_h5', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError('H5 出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
|
||||
return resp.json()
|
||||
|
||||
|
||||
def get_h5_mtgsig(url, data, method, mode, profile, cookie='', data_type='json', type=None):
|
||||
"""只要 mtgsig 值本身时用这个(= get_h5_sign(...)['mtgsig'])。"""
|
||||
return get_h5_sign(url=url, data=data, method=method, mode=mode, profile=profile, cookie=cookie, data_type=data_type, type=type)['mtgsig']
|
||||
|
||||
|
||||
def get_h5_mtgsig_pure(url, data, mtgsig, method='POST', origin_url=None, origin_data=None):
|
||||
"""外卖 H5(h1.9) **纯算**出签(不跑 SDK,毫秒级)—— 走服务里的 /sign_h5_pure。
|
||||
|
||||
mtgsig 传一份抓包里的 H5 mtgsig(a6 前缀 h1.9),url/data 传要出签的请求(data 是 form body 串);
|
||||
origin_url/origin_data 是那份抓包签名对应的 url/data —— 只有要和出签请求不一样时才传(比如改了 body),
|
||||
不传就按同一份包复算出签。换接口只换 url + data 即可(url/data/mtgsig/method 必传)。
|
||||
"""
|
||||
body = {'url': url, 'data': data, 'mtgsig': mtgsig, 'method': method}
|
||||
if origin_url is not None:
|
||||
body['origin_url'] = origin_url
|
||||
if origin_data is not None:
|
||||
body['origin_data'] = origin_data
|
||||
try:
|
||||
resp = requests.post(BASE_URL + '/sign_h5_pure', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError('H5 纯算出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
|
||||
return resp.json()['mtgsig']
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(json.dumps(check_health(), ensure_ascii=False))
|
||||
@@ -0,0 +1,77 @@
|
||||
import base64
|
||||
import requests
|
||||
from typing import Optional, Dict, Any, List
|
||||
TIMEOUT = 15
|
||||
BASE_URL = "http://ktl-001.dsfdl-henan.xyz/openApi"
|
||||
def _auth(username: str, password: str) -> Dict[str, str]:
|
||||
token = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
def _get(url: str, username: str, password: str, params: Optional[dict] = None) -> Dict[str, Any]:
|
||||
resp = requests.get(url, headers=_auth(username, password), params=params or {}, timeout=TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
def get_stats(stat_date: str, # 'yyyy-MM-dd' / 'total'
|
||||
vendor_name: str,
|
||||
username: str,
|
||||
password: str,
|
||||
client_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/getStats"
|
||||
params = {"date": stat_date, "vendorName": vendor_name}
|
||||
if client_id:
|
||||
params["clientId"] = client_id
|
||||
resp = _get(url, username, password, params)
|
||||
return resp.get("data", {})
|
||||
USER = "thzn-datagram0001"
|
||||
PWD = "thzn-datagram0001"
|
||||
VENDOR = "mt-datagram"
|
||||
TIME='2026-10-20'
|
||||
clientid_list = [
|
||||
'福州',
|
||||
'合肥',
|
||||
'北京',
|
||||
'重庆',
|
||||
'杭州',
|
||||
'兰州',
|
||||
'广州',
|
||||
'佛山',
|
||||
'上海',
|
||||
'南宁',
|
||||
'贵阳',
|
||||
'海口',
|
||||
'石家庄',
|
||||
'郑州',
|
||||
'哈尔滨',
|
||||
'武汉',
|
||||
'长沙',
|
||||
'长春',
|
||||
'南京',
|
||||
'南昌',
|
||||
'沈阳',
|
||||
'呼和浩特',
|
||||
'济南',
|
||||
'太原',
|
||||
'西安',
|
||||
'成都',
|
||||
'天津',
|
||||
'拉萨',
|
||||
'乌鲁木齐',
|
||||
'深圳',
|
||||
'西宁',
|
||||
'银川',
|
||||
'昆明',
|
||||
'福州',
|
||||
'苏州',
|
||||
'青岛',
|
||||
'东莞',
|
||||
'厦门',
|
||||
'厦门',
|
||||
'无锡',
|
||||
'大连',
|
||||
]
|
||||
success,reject = 0,0
|
||||
for clientid in list(set(clientid_list)):
|
||||
result = get_stats(TIME,VENDOR,USER,PWD,clientid)
|
||||
success+=result['success']
|
||||
reject+=result['reject']
|
||||
print(clientid,result)
|
||||
print(f'{TIME}总成功条数: {success}, 总失败条数: {reject}')
|
||||
@@ -0,0 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from datetime import date
|
||||
from typing import Optional, Dict, Any, List
|
||||
from colorama import init, Fore, Style
|
||||
|
||||
init(autoreset=True)
|
||||
BASE_URL = "http://ktl-001.dsfdl-henan.xyz/openApi"
|
||||
TIMEOUT = 15
|
||||
# 任务接口直连,不走系统代理(本机 VPN):None 会被 requests 过滤掉,用空字符串才是真直连
|
||||
DIRECT_PROXIES = {'http': '', 'https': ''}
|
||||
LOG_DIR = "logs"
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
CODE_MSG = {
|
||||
0: ("success", "请求成功"),
|
||||
-1: ("server error", "服务本身错误"),
|
||||
-2: ("Authorization failed", "账号密码错误或认证方式错误"),
|
||||
305: ("现在没有任务了", "请稍后再试"),
|
||||
306: ("您今日没有任务了", "明天再来吧"),
|
||||
309: ("任务:开始", ""),
|
||||
310: ("任务:已经结束", ""),
|
||||
311: ("日期错误", "统计接口日期格式需严格 yyyy-MM-dd"),
|
||||
312: ("网络通信出错", "上传/取消时可重试"),
|
||||
313: ("任务还在处理中", "请勿重复提交"),
|
||||
314: ("任务正在获取中", "请稍后重试"),
|
||||
317: ("为了账号安全", "休息一会儿再做吧"),
|
||||
318: ("当前城市没任务啦", "换个城市试试"),
|
||||
319: ("服务维护中", "休息一会再做吧"),
|
||||
324: ("提交和获取的任务不一致", "uniqueId 需保持一致"),
|
||||
325: ("封号", ""),
|
||||
326: ("上传文本格式有错", "需 JSON 格式"),
|
||||
327: ("当前已领取任务", "请先完成再领新任务"),
|
||||
328: ("重复取消任务", ""),
|
||||
336: ("为了您的账号安全", "休息一下再来吧"),
|
||||
337: ("正在做的任务数量超过限额", ""),
|
||||
338: ("不在指定领取任务时间区间内", ""),
|
||||
339: ("网络通信失败", "请重试"),
|
||||
}
|
||||
|
||||
|
||||
def _color_code(code: int) -> str:
|
||||
if code == 0:
|
||||
return f"{Fore.GREEN}{code}"
|
||||
if code in CODE_MSG:
|
||||
return f"{Fore.YELLOW}{code}"
|
||||
return f"{Fore.RED}{code}"
|
||||
|
||||
|
||||
def _log_response(api_name: str, resp: Dict[str, Any]):
|
||||
code = resp.get("code", -1)
|
||||
msg_en, msg_zh = CODE_MSG.get(code, (resp.get("message", ""), "未知错误"))
|
||||
print(f"[{api_name}] 返回码: {_color_code(code)} {msg_en} | {msg_zh}")
|
||||
|
||||
|
||||
def _auth(username: str, password: str) -> Dict[str, str]:
|
||||
token = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
|
||||
|
||||
def _get(url: str, username: str, password: str, params: Optional[dict] = None) -> Dict[str, Any]:
|
||||
resp = requests.get(url, headers=_auth(username, password), params=params or {}, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _post(url: str, username: str, password: str, params: Optional[dict] = None, json_data: Any = None) -> Dict[
|
||||
str, Any]:
|
||||
resp = requests.post(url, headers=_auth(username, password), params=params or {}, json=json_data, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def realtime_city_list(vendor_name: str,
|
||||
username: str,
|
||||
password: str,
|
||||
checkin_date: Optional[str] = None,
|
||||
checkout_date: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
url = f"{BASE_URL}/realtimeCityList"
|
||||
params = {"vendorName": vendor_name}
|
||||
if checkin_date:
|
||||
params["checkInDate"] = checkin_date
|
||||
if checkout_date:
|
||||
params["checkOutDate"] = checkout_date
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("realtime_city_list", resp)
|
||||
return resp.get("data", [])
|
||||
|
||||
|
||||
def realtime_checkinout_dates(vendor_name: str,
|
||||
username: str,
|
||||
password: str) -> List[Dict[str, str]]:
|
||||
url = f"{BASE_URL}/realtimeCheckInOutDateList"
|
||||
params = {"vendorName": vendor_name}
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("realtime_checkinout_dates", resp)
|
||||
return resp.get("data", [])
|
||||
|
||||
|
||||
def latest_cities(vendor_name: str, username: str, password: str) -> List[Dict[str, Any]]:
|
||||
dates = realtime_checkinout_dates(vendor_name, username, password)
|
||||
if not dates:
|
||||
return []
|
||||
latest = dates[0]
|
||||
return realtime_city_list(vendor_name, username, password,
|
||||
latest["checkInDate"], latest["checkOutDate"])
|
||||
|
||||
|
||||
def get_task(vendor_name: str,
|
||||
username: str,
|
||||
password: str,
|
||||
client_id: str,
|
||||
selected_city: str,
|
||||
checkin_date: Optional[str] = None,
|
||||
checkout_date: Optional[str] = None) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/getTask"
|
||||
params = {"vendorName": vendor_name, "clientId": client_id, "selectedCity": selected_city}
|
||||
if checkin_date:
|
||||
params["checkInDate"] = checkin_date
|
||||
if checkout_date:
|
||||
params["checkOutDate"] = checkout_date
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("get_task", resp)
|
||||
return resp
|
||||
|
||||
|
||||
# 交任务
|
||||
def upload_task_datagram(original_vendor: str,
|
||||
unique_id: str,
|
||||
target_vendor: str,
|
||||
selected_city: str,
|
||||
client_id: str,
|
||||
username: str,
|
||||
password: str,
|
||||
datagram_json: dict,
|
||||
channel: Optional[str] = None) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/uploadTaskDatagram"
|
||||
params = {"originalVendorName": original_vendor,
|
||||
"targetVendorName": target_vendor,
|
||||
"uniqueId": unique_id,
|
||||
"selectedCity": selected_city,
|
||||
"clientId": client_id}
|
||||
if channel:
|
||||
params["channel"] = channel
|
||||
print(datagram_json)
|
||||
print('==============')
|
||||
print((params))
|
||||
# 提交超时/连接失败重试,最多 3 次(含首次)
|
||||
for i in range(30):
|
||||
try:
|
||||
resp = _post(url, username, password, params, json_data=datagram_json)
|
||||
break
|
||||
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
|
||||
print(f"交任务失败,第{i + 1}次: {e}")
|
||||
if i == 2:
|
||||
raise
|
||||
_log_response("upload_task_datagram", resp)
|
||||
return resp
|
||||
|
||||
|
||||
def get_one_task(VENDOR, USER, PWD, clientid, city_name):
|
||||
cities = latest_cities(VENDOR, USER, PWD)
|
||||
print(cities)
|
||||
city = None
|
||||
if city_name:
|
||||
for selected in cities:
|
||||
if city_name in selected['selectedCity']:
|
||||
city = selected['selectedCity']
|
||||
break
|
||||
if not city:
|
||||
return False
|
||||
else:
|
||||
city = cities[0]["selectedCity"]
|
||||
print(city)
|
||||
# city = '上海市:10_上海市'
|
||||
task = get_task(VENDOR, USER, PWD, clientid, city)
|
||||
return task
|
||||
|
||||
|
||||
def upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json):
|
||||
# 返回平台响应体(埋点要用其 code 判定成交结果)
|
||||
return upload_task_datagram(VENDOR, task_data.get('data').get('uniqueId'), VENDOR,
|
||||
task_data.get('data').get('selectedCity'), clientid, USER, PWD,
|
||||
data_json)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
'''
|
||||
使用实例
|
||||
'''
|
||||
USER = "thzn-datagram0001"
|
||||
PWD = "thzn-datagram0001"
|
||||
VENDOR = "mt-datagram"
|
||||
clientid = '广州'
|
||||
|
||||
|
||||
'''
|
||||
VENDOR 可写死 项目标识
|
||||
USER 可写死 账号
|
||||
PWD 可写死 密码
|
||||
clientid 单人可写死(多线程需修改) 客户端id
|
||||
city 修改拿取城市的id 根据其他接口返回
|
||||
'''
|
||||
|
||||
# 任务获取
|
||||
task = get_one_task(VENDOR, USER, PWD, clientid,'广州')
|
||||
print(task)
|
||||
|
||||
'''
|
||||
VENDOR 可写死 项目标识
|
||||
USER 可写死 账号
|
||||
PWD 可写死 密码
|
||||
clientid 单人可写死(多线程需修改) 客户端id
|
||||
city 修改拿取城市的id 根据其他接口返回
|
||||
|
||||
|
||||
task_data为任务返回的数据json
|
||||
task_data={
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"hotelId": "938833723",
|
||||
"cityId": "50",
|
||||
"hotelName": "杭州拱墅大运河轻居酒店",
|
||||
"hotelAddress": "拱墅区湖州街555号顺网运河国际4号楼1层",
|
||||
"cityName": "杭州市",
|
||||
"checkInDate": "2025-12-01",
|
||||
"checkOutDate": "2025-12-02",
|
||||
"uniqueId": "20251130205014-32-32-3000001-443-411",
|
||||
"timeLeft": 1046,
|
||||
"hotelStar": "高档型",
|
||||
"selectedCity": "浙江省:50_杭州市",
|
||||
"areaType": "行政区/商圈",
|
||||
"areaName": "汽车北站、国际会展中心",
|
||||
"level": 0
|
||||
}
|
||||
}
|
||||
|
||||
data_json为采集获取到的json即上交数据
|
||||
'''
|
||||
|
||||
# 任务提交
|
||||
# task_data = json.loads(task)
|
||||
# data_json = {}#返回原始报文即可
|
||||
# upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json)
|
||||
@@ -0,0 +1,115 @@
|
||||
import os.path
|
||||
|
||||
import requests
|
||||
import json
|
||||
from urllib.parse import urlencode
|
||||
|
||||
|
||||
def build_url(base_url, params):
|
||||
"""
|
||||
将基础URL和参数字典拼接成完整的URL
|
||||
"""
|
||||
# urlencode 会将字典转换为 key=value&key2=value2 的形式
|
||||
# 并且会自动处理特殊字符的 URL 编码 (Percent-encoding)
|
||||
query_string = urlencode(params)
|
||||
|
||||
# 拼接基础URL和查询字符串
|
||||
full_url = f"{base_url}?{query_string}"
|
||||
|
||||
return full_url
|
||||
|
||||
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
def get_Datatext(dataq):
|
||||
str1 = ''
|
||||
for i in dataq:
|
||||
key, value = i, dataq[i]
|
||||
str2 = f'{key}={value}&'
|
||||
str1 = str1 + str2
|
||||
data = str1[0:-1]
|
||||
return data
|
||||
|
||||
|
||||
headers = {
|
||||
'Connection': 'keep-alive',
|
||||
'M-APPKEY': 'wxmp_mt-weapp',
|
||||
'M-TRACEID': '-7096049715237799086',
|
||||
'clientversion': '3.16.2',
|
||||
'content-type': 'application/json',
|
||||
'csecuserid': '9165541616',
|
||||
'csecuuid': '19f68faf42ac8-4325861f210cd4-0-0-19f68faf42ac8',
|
||||
'mtgsig': '{"a1":"1.2","a2":1784632608951,"a3":"38v39x2v036853780w82v87w42323z1580u31uzu155779785wzux1zw","a4":"11058c1891e0d104188c051104d1e091af046195abd58104","a5":"VDelC0QR+Psr8Hj7O7pQKdVVb15jqSXvMjuv3ddiCIzK7Tts7RNmBYJid3kb0mHTJdQ/GQ+leKxJCj0IEHXkv5W7cTBPcQfpKBD4pf0AZiYcHsSfX13obpYHbQAh7Xs9U8hNrJK3H8Z1IwyAkRMxc8TvQGYry0XTCYSYECrR7XFpC44TnW6qKWrPFvTpaoyMNhavh7FPMIwtV8ZdJVbZRza0+LtRGYcKuXcdItTzqu1QplAPGxELdEQ37Z5UvmkBDmbchUt1R8J5mVw1QhPy/OeFkNtHayHEzDL8a/J/MjQVbxAV/SBfTwvS1GXNWZBBev+DsurS","a6":"w1.63iaObtXg0UWQRJ7HPBgY/KKKBVBEepMutleQ+OavEPti3OPCWXT8WXQ1FdXu+OXXY0en9f1j/sEmgb7mzaexGo3lbVSfuhEMuXIY/DjItviK0lXdrVMPfPAZ6LSqmQf36xUCduGPRyMaDy9gyOJOYdkZTtnODmHB+i0adIyM6MiFdXBmoHPLI5SWEw/D0sL95FunHdJUHQZARhu6Br3RoAKtU4b2b6bWRYc29SXhULkKcqrWR/v+FkjZNslHbL2Cytbc5fEQwLs6v2CLBkujFOTUI51PUQCiiFCj4vQQASG6X1JRTP7HrfL64FAixizcNo5LCPAVopcENp8RoOStzxa8MOi+h1o5Hp+UjvpybqOq9jZptIELDwxI9RW4HD9sa56E6scTfNXGq8FM/8RQgS1Rrzqy5bXsK+c6IqcshP3Z+6/B+5uPaaUhn2cGyv4bTP/e7HV9NMyb0pcTH7SqlT7+yVO04NY5vGdWtX9mZfuklwyJNJCHU6J4lehXerXzs5GFA+0OOEPUTG1lPXXbuA==","a7":"wxde8ac0a21135c07d","x0":3,"d1":"6724fa89092853490414911525f2fd60"}',
|
||||
'openId': 'oJVP50OK26EtAmTtsMWG5zEBs6IU',
|
||||
'openIdCipher': 'AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADhra/VS5nALJne/WxEfpB/qFyvKHhkDQK19b0vhIjhqhCXnH2KSJY8ZpnQBpQnEC5G73OtBdHK3yg==',
|
||||
'token': 'AgFHKjwovycEX1Ja2e6yX_BZMhsFnfa1rFrtcKvf5N8NoP8j9CvxoML9LuYnq89F8gxIZ4Why-HghgAAAACKNwAAQfLxmftx20lAr0e_Z1fNrPNCg0iz5dTckl_l9rClKkK24I85yeT-u823f7OOMnRa',
|
||||
'uuid': '19f68faf42ac8-4325861f210cd4-0-0-19f68faf42ac8',
|
||||
'x_htas_version': '0.1.31',
|
||||
'charset': 'utf-8',
|
||||
'Referer': 'https://servicewechat.com/wxde8ac0a21135c07d/1557/page-frame.html',
|
||||
'User-Agent': 'Mozilla/5.0 (Linux; Android 14; TB323FU Build/UP1A.231005.007; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/146.0.7680.178 Mobile Safari/537.36 XWEB/1460217 MMWEBSDK/20260502 MMWEBID/6751 MicroMessenger/8.0.74.3120(0x28004A52) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android',
|
||||
}
|
||||
|
||||
params = {
|
||||
'yodaReady': 'wx',
|
||||
'csecappid': 'wxde8ac0a21135c07d',
|
||||
'csecplatform': '3',
|
||||
'csecversionname': '10.28.1',
|
||||
'csecversion': '3.0.2',
|
||||
'openId': 'oJVP50OK26EtAmTtsMWG5zEBs6IU',
|
||||
'antiRepPlatform': 'Android',
|
||||
'programName': 'mt',
|
||||
'utm_medium': 'WEIXINPROGRAM',
|
||||
'riskLevel': '71',
|
||||
'optimusCode': '10',
|
||||
'openIdCipher': 'AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADhra/VS5nALJne/WxEfpB/qFyvKHhkDQK19b0vhIjhqhCXnH2KSJY8ZpnQBpQnEC5G73OtBdHK3yg==',
|
||||
'utm_campaign': 'entry%3DMTLive_scene%3D1089',
|
||||
'token': 'AgFHKjwovycEX1Ja2e6yX_BZMhsFnfa1rFrtcKvf5N8NoP8j9CvxoML9LuYnq89F8gxIZ4Why-HghgAAAACKNwAAQfLxmftx20lAr0e_Z1fNrPNCg0iz5dTckl_l9rClKkK24I85yeT-u823f7OOMnRa',
|
||||
'usertoken': 'AgFHKjwovycEX1Ja2e6yX_BZMhsFnfa1rFrtcKvf5N8NoP8j9CvxoML9LuYnq89F8gxIZ4Why-HghgAAAACKNwAAQfLxmftx20lAr0e_Z1fNrPNCg0iz5dTckl_l9rClKkK24I85yeT-u823f7OOMnRa',
|
||||
'userToken': 'AgFHKjwovycEX1Ja2e6yX_BZMhsFnfa1rFrtcKvf5N8NoP8j9CvxoML9LuYnq89F8gxIZ4Why-HghgAAAACKNwAAQfLxmftx20lAr0e_Z1fNrPNCg0iz5dTckl_l9rClKkK24I85yeT-u823f7OOMnRa',
|
||||
'userId': '9165541616',
|
||||
'userid': '9165541616',
|
||||
'uuid': '19f68faf42ac8-4325861f210cd4-0-0-19f68faf42ac8',
|
||||
'locateCityId': '20',
|
||||
'locatecityid': '20',
|
||||
'appMiniVersion': '10.28.0',
|
||||
'lat': '23.125999',
|
||||
'lng': '113.293118',
|
||||
'appletShieldScene': 'null',
|
||||
'cityid': '20',
|
||||
'keyword': '广东地质山水酒店',
|
||||
'antiRepCityId': '20',
|
||||
'wechatVersion': '8.0.74',
|
||||
'sdkVersion': '3.16.2',
|
||||
'version_name': '11.8.400',
|
||||
'appletVersionName': '10.28.1',
|
||||
'ste': 'WEIXINPROGRAM',
|
||||
'utm_fp': 'MINI_PROGRAM',
|
||||
'SDKVersion': '3.16.2',
|
||||
}
|
||||
|
||||
url = 'https://ihotel.meituan.com/hbsearch/v4/deal/search/suggest'
|
||||
url2 = build_url(url,params)
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
openId = headers['openId']
|
||||
headers['mtgsig'] = get_sign_new1_get(url2, '', dfpid, mtg_origin,openId)
|
||||
response = requests.get(url2, headers=headers)
|
||||
print(response.text)
|
||||
for i in response.json()['stidItems']:
|
||||
print(i)
|
||||
if 649339 == i['poiid']:
|
||||
print(i['propagateData']['data']['contentTransparent'])
|
||||
@@ -0,0 +1,779 @@
|
||||
import os.path
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
import traceback
|
||||
import json
|
||||
from urllib.parse import urlencode, urlparse, parse_qs, unquote
|
||||
from 酒店任务拿交 import get_one_task, upload_one_task
|
||||
import newsetting as ten
|
||||
|
||||
tent = ten.All_Setting(host='183.6.7.91', port=33016, db='mt_hotel')
|
||||
tent2 = ten.All_Setting(host='192.168.5.2', port=3307, db='headers_project')
|
||||
# proxy = {"http": None, "https": None}
|
||||
import pymysql
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from 小程序mtgsig import get_mtgsig,get_h5_mtgsig_pure
|
||||
import hotel_insight as insight # 埋点:只写本地 JSONL,不影响主流程
|
||||
|
||||
# 代理出口城市 -> (lat, lng),1位小数,向真机抓包精度看齐(真机广州=23.1,113.3 已验证)
|
||||
# 用途:get_prox 返回代理出口城市后,按城市名取对应坐标,让 lat/lng 与 IP 出口地同源
|
||||
CITY_GPS = {
|
||||
"苏州": ("31.3", "120.6"),
|
||||
"佛山": ("23.0", "113.1"),
|
||||
"长沙": ("28.2", "112.9"),
|
||||
"武汉": ("30.594940", "114.302634"),
|
||||
"杭州": ("30.231471", "120.018594"),
|
||||
"太原": ("37.9", "112.5"),
|
||||
"乌鲁木齐": ("43.8", "87.6"),
|
||||
"上海": ("30.948869", "121.303506"),
|
||||
"重庆": ("29.6", "106.5"),
|
||||
"成都": ("30.6", "104.1"),
|
||||
"南通": ("32.0", "120.9"),
|
||||
"深圳": ("22.545482", "114.055597"),
|
||||
"兰州": ("36.1", "103.8"),
|
||||
"海口": ("20.0", "110.3"),
|
||||
"济南": ("36.7", "117.0"),
|
||||
"南京": ("32.1", "118.8"),
|
||||
"郑州": ("34.7", "113.6"),
|
||||
"福州": ("26.1", "119.3"),
|
||||
"拉萨": ("29.7", "91.1"),
|
||||
"沈阳": ("41.8", "123.4"),
|
||||
"广州": ("23.437968", "113.554650"),
|
||||
"昆明": ("25.0", "102.7"),
|
||||
"北京": ("39.9", "116.4"),
|
||||
"天津": ("39.1", "117.2"),
|
||||
"长春": ("43.9", "125.3"),
|
||||
"西安": ("34.3", "108.9"),
|
||||
"哈尔滨": ("45.8", "126.5"),
|
||||
"贵阳": ("26.6", "106.7"),
|
||||
"银川": ("38.5", "106.2"),
|
||||
"西宁": ("36.616448", "101.775687"),
|
||||
"南昌": ("28.7", "115.9"),
|
||||
"呼和浩特": ("40.8", "111.7"),
|
||||
"石家庄": ("38.0", "114.5"),
|
||||
"南宁": ("22.8", "108.4"),
|
||||
"合肥": ("31.8", "117.2"),
|
||||
"青岛": ("36.1", "120.4"),
|
||||
"东莞": ("23.0", "113.8"),
|
||||
"厦门": ("24.5", "118.1"),
|
||||
"无锡": ("31.5", "120.3"),
|
||||
"大连": ("38.9", "121.6"),
|
||||
}
|
||||
|
||||
|
||||
def clean_and_insert_hotel_booking(
|
||||
raw_data: Dict[str, Any],
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
清洗酒店预订数据并插入数据库
|
||||
|
||||
Args:
|
||||
raw_data: API返回的原始数据
|
||||
|
||||
Returns:
|
||||
{'success': bool, 'message': str, 'id': int or None}
|
||||
"""
|
||||
|
||||
# 1. 检查响应状态
|
||||
if raw_data.get('code') != 0:
|
||||
return {
|
||||
'success': False,
|
||||
'message': f"API返回错误: {raw_data.get('message', '未知错误')}",
|
||||
'id': None
|
||||
}
|
||||
|
||||
data = raw_data.get('data', {})
|
||||
if not data:
|
||||
return {
|
||||
'success': False,
|
||||
'message': '数据为空',
|
||||
'id': None
|
||||
}
|
||||
|
||||
# 2. 数据清洗
|
||||
def clean_string(value: Any, max_length: int = None) -> Optional[str]:
|
||||
"""清洗字符串字段"""
|
||||
if value is None:
|
||||
return None
|
||||
result = str(value).strip()
|
||||
if max_length and len(result) > max_length:
|
||||
result = result[:max_length]
|
||||
return result if result else None
|
||||
|
||||
def clean_int(value: Any, default: int = None) -> Optional[int]:
|
||||
"""清洗整数字段"""
|
||||
if value is None:
|
||||
return default
|
||||
try:
|
||||
return int(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
|
||||
def clean_date(value: Any) -> Optional[str]:
|
||||
"""清洗日期字段"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
# 验证日期格式
|
||||
datetime.strptime(str(value), '%Y-%m-%d')
|
||||
return str(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
# 3. 清洗后的数据
|
||||
cleaned_data = {
|
||||
'hotel_id': clean_string(data.get('hotelId'), 20),
|
||||
'city_id': clean_string(data.get('cityId'), 10),
|
||||
'hotel_name': clean_string(data.get('hotelName'), 100),
|
||||
'hotel_address': clean_string(data.get('hotelAddress'), 200),
|
||||
'city_name': clean_string(data.get('cityName'), 50),
|
||||
'check_in_date': clean_date(data.get('checkInDate')),
|
||||
'check_out_date': clean_date(data.get('checkOutDate')),
|
||||
'unique_id': clean_string(data.get('uniqueId'), 100),
|
||||
'time_left': clean_int(data.get('timeLeft')),
|
||||
'hotel_star': clean_string(data.get('hotelStar'), 20),
|
||||
'selected_city': clean_string(data.get('selectedCity'), 50),
|
||||
'area_type': clean_string(data.get('areaType'), 50),
|
||||
'area_name': clean_string(data.get('areaName'), 100),
|
||||
'level': clean_int(data.get('level'), 0)
|
||||
}
|
||||
|
||||
# 4. 验证必填字段
|
||||
required_fields = ['hotel_id', 'city_id', 'hotel_name', 'check_in_date', 'check_out_date']
|
||||
for field in required_fields:
|
||||
if not cleaned_data.get(field):
|
||||
return {
|
||||
'success': False,
|
||||
'message': f'必填字段缺失: {field}',
|
||||
'id': None
|
||||
}
|
||||
try:
|
||||
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 处理重复
|
||||
sql = """
|
||||
INSERT INTO hotel_task (
|
||||
hotel_id, city_id, hotel_name, hotel_address, city_name,
|
||||
check_in_date, check_out_date, unique_id, time_left,
|
||||
hotel_star, selected_city, area_type, area_name, level
|
||||
) VALUES (
|
||||
%(hotel_id)s, %(city_id)s, %(hotel_name)s, %(hotel_address)s, %(city_name)s,
|
||||
%(check_in_date)s, %(check_out_date)s, %(unique_id)s, %(time_left)s,
|
||||
%(hotel_star)s, %(selected_city)s, %(area_type)s, %(area_name)s, %(level)s
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
city_id = VALUES(city_id),
|
||||
hotel_name = VALUES(hotel_name),
|
||||
hotel_address = VALUES(hotel_address),
|
||||
city_name = VALUES(city_name),
|
||||
check_in_date = VALUES(check_in_date),
|
||||
check_out_date = VALUES(check_out_date),
|
||||
unique_id = VALUES(unique_id),
|
||||
time_left = VALUES(time_left),
|
||||
hotel_star = VALUES(hotel_star),
|
||||
selected_city = VALUES(selected_city),
|
||||
area_type = VALUES(area_type),
|
||||
area_name = VALUES(area_name),
|
||||
level = VALUES(level)
|
||||
"""
|
||||
|
||||
tent.write_data(sql, (cleaned_data,))
|
||||
return {
|
||||
'success': True,
|
||||
'message': '插入成功',
|
||||
'id': None,
|
||||
}
|
||||
|
||||
except pymysql.IntegrityError as e:
|
||||
return {
|
||||
'success': False,
|
||||
'message': f'数据完整性错误: {str(e)}',
|
||||
'id': None
|
||||
}
|
||||
except pymysql.Error as e:
|
||||
return {
|
||||
'success': False,
|
||||
'message': f'数据库错误: {str(e)}',
|
||||
'id': None
|
||||
}
|
||||
|
||||
|
||||
def parse_url(url: str) -> dict:
|
||||
"""
|
||||
解析URL,返回基础URL和参数字典
|
||||
|
||||
Args:
|
||||
url: 完整的URL字符串
|
||||
|
||||
Returns:
|
||||
dict: 包含 'url' 和 'params' 的字典
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
|
||||
# 基础URL(不含查询参数)
|
||||
base_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
|
||||
# 解析查询参数
|
||||
# parse_qs 返回的值是列表,这里转换为单值(如果只有一个值)
|
||||
params_raw = parse_qs(parsed.query)
|
||||
params = {}
|
||||
|
||||
for key, value in params_raw.items():
|
||||
# 如果列表只有一个元素,直接取值;否则保留列表
|
||||
params[key] = value[0] if len(value) == 1 else value
|
||||
|
||||
# return {
|
||||
# "url": base_url,
|
||||
# "params": params
|
||||
# }
|
||||
return (base_url, params)
|
||||
|
||||
|
||||
def build_url(base_url, params):
|
||||
"""
|
||||
将基础URL和参数字典拼接成完整的URL
|
||||
"""
|
||||
# doseq=True 会将列表展开为多个同名参数
|
||||
query_string = urlencode(params, doseq=True)
|
||||
full_url = f"{base_url}?{query_string}"
|
||||
return full_url
|
||||
|
||||
|
||||
def get_sign_new(url, data, dfpid, mtg_origin):
|
||||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||||
|
||||
body = {
|
||||
"mtg_origin": mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST"}
|
||||
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://8.138.127.139:10063/newmtgsig'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
return req
|
||||
|
||||
|
||||
def get_sign_new1(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
def get_sign_new_get(url, data, dfpid, mtg_origin):
|
||||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||||
|
||||
body = {
|
||||
"mtg_origin": mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET"}
|
||||
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://8.138.127.139:10063/newmtgsig'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
return req
|
||||
|
||||
|
||||
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
def get_Datatext(dataq):
|
||||
str1 = ''
|
||||
for i in dataq:
|
||||
key, value = i, dataq[i]
|
||||
str2 = f'{key}={value}&'
|
||||
str1 = str1 + str2
|
||||
data = str1[0:-1]
|
||||
return data
|
||||
|
||||
|
||||
class hotel_run:
|
||||
USER = "thzn-datagram0001"
|
||||
PWD = "thzn-datagram0001"
|
||||
VENDOR = "mt-datagram"
|
||||
# clientid = uuid.uuid4().int
|
||||
clientid = "666"
|
||||
|
||||
costSourceChannel = "1"
|
||||
input = ""
|
||||
keyword = ""
|
||||
mtShareId = ""
|
||||
fromOffline = "false"
|
||||
flagshipFilter = "1"
|
||||
needShowNewDiscInfo = "false"
|
||||
lat = "31.820953"
|
||||
lng = "117.222201"
|
||||
ci = "20"
|
||||
channelCityId = "20"
|
||||
hotelCustomGpsStatus = "0"
|
||||
specialDealHotelScene = "true"
|
||||
riskPlatform = "13"
|
||||
channelSelectCityId = "20"
|
||||
appletVersionName = "9.51.4"
|
||||
appletAppId = "wxde8ac0a21135c07d"
|
||||
specAttributionChannel = ""
|
||||
magicMemberCode = "1102,1103"
|
||||
|
||||
# proxy = {"http": None,"https": None}
|
||||
def __init__(self):
|
||||
self.proxy_list = self.get_prox()
|
||||
print(self.proxy_list)
|
||||
|
||||
def run_shelf(self, url, params, headers, data, prox, task):
|
||||
clientid = task['data']['cityName'].replace('市', '')
|
||||
if prox:
|
||||
self.proxy = json.loads(prox)
|
||||
# 查绑定城市对应的美团cityId(用于gps_cityid/locateCityId等定位字段)
|
||||
gps_city_id = self.get_city_id(self.bound_city)
|
||||
if not gps_city_id:
|
||||
print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
|
||||
return -1
|
||||
# 绑定城市坐标,businessParams里是字符串("23.1"),顶层data是数字(23.1)
|
||||
city_gps = CITY_GPS.get(self.bound_city)
|
||||
if not city_gps:
|
||||
print(f"城市 {self.bound_city} 在 CITY_GPS 无坐标,跳过")
|
||||
return -1
|
||||
result = clean_and_insert_hotel_booking(task)
|
||||
hotel_info = task["data"]
|
||||
print(result)
|
||||
print(task)
|
||||
print(type(task['data']))
|
||||
data['poiId'] = task['data']['hotelId']
|
||||
data['requestParams'][0]['businessParams']['poiId'] = task['data']['hotelId']
|
||||
start = int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000)
|
||||
end = int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000)
|
||||
data['requestParams'][0]['businessParams']['start'] = start
|
||||
data['requestParams'][0]['businessParams']['end'] = end
|
||||
data['requestParams'][0]['businessParams']['cityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,真机=2332,OK
|
||||
data['requestParams'][0]['businessParams']['channelCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
|
||||
data['requestParams'][0]['businessParams']['userCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
|
||||
data['requestParams'][0]['businessParams']['appCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
|
||||
data['requestParams'][0]['businessParams']['gps_cityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
|
||||
data['requestParams'][0]['businessParams']['gpsCityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
|
||||
data['requestParams'][0]['businessParams']['locateCityId'] = gps_city_id # 用户定位城市组,跟绑定城市走
|
||||
data['requestParams'][0]['businessParams']['locatecityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
|
||||
data['requestParams'][0]['businessParams']['lat'] = city_gps[0] # businessParams里lat是字符串
|
||||
data['requestParams'][0]['businessParams']['lng'] = city_gps[1] # businessParams里lng是字符串
|
||||
# data顶层定位字段:真机里 lat/lng 是数字类型,locateCityId 跟绑定城市走
|
||||
data['lat'] = float(city_gps[0]) # 顶层lat是数字,真机=23.1
|
||||
data['lng'] = float(city_gps[1]) # 顶层lng是数字,真机=113.3
|
||||
data['locateCityId'] = gps_city_id # 顶层定位城市ID,跟绑定城市走
|
||||
data['locatecityid'] = gps_city_id # 顶层定位城市ID小写版,跟绑定城市走
|
||||
data['clientRequestTime'] = int(time.time() * 1000) # 请求级实时时间戳,真机每次变
|
||||
# poi = '1743020617'
|
||||
# data['poiId'] = poi
|
||||
# data['requestParams'][0]['businessParams']['poiId'] = poi
|
||||
|
||||
data2 = json.dumps(data, separators=(',', ':'))
|
||||
new_url = build_url(url, params)
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
# headers['mtgsig'] = get_mtgsig(new_url, data2, dfpid, mtg_origin,openId)
|
||||
if 'openId' in headers:
|
||||
openId = headers['openId']
|
||||
else:
|
||||
openId = headers['openid']
|
||||
headers['mtgsig'] = get_sign_new1(new_url, data2, dfpid, mtg_origin, openId)
|
||||
|
||||
# response = requests.post(url, headers=headers, data=data,params=params)
|
||||
response = requests.post(new_url, headers=headers, data=data2, proxies=self.proxy)
|
||||
|
||||
print("response.text", '-' * 50, response.text[:])
|
||||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||||
# 埋点:418 也要落一条 exception(与 prepayList 分支对齐)
|
||||
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), '网络不给力(418)', code=418)
|
||||
return 418
|
||||
if "Unauthorized" in response.text[:500]:
|
||||
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), 'Unauthorized(401)', code=401)
|
||||
return 401
|
||||
res = response.json()
|
||||
_upload_resp = upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
|
||||
# 埋点:交任务结果(code=0 为成功)——shelf 分支原来漏了这条,看板“交回成功”会少算
|
||||
insight.log_upload(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), _upload_resp,
|
||||
unique_id=hotel_info.get('uniqueId'), city_name=hotel_info.get('cityName'))
|
||||
# 从响应里提取 traceId,存到 self 供外部回写 hotel_hd
|
||||
self.last_trace_id = self._find_trace_id(res)
|
||||
sql = '''
|
||||
INSERT INTO `hotel_json`
|
||||
(json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
'''
|
||||
tent.write_data(sql, ((
|
||||
json.dumps(res), hotel_info.get('hotelId'), hotel_info.get('cityId'),
|
||||
hotel_info.get('hotelName'),
|
||||
hotel_info.get('cityName'), hotel_info.get('checkInDate'),
|
||||
hotel_info.get('checkOutDate')),))
|
||||
return 1
|
||||
|
||||
def run_prepayList(self, url, params, headers, prox, task):
|
||||
clientid = task['data']['cityName'].replace('市', '')
|
||||
if prox:
|
||||
self.proxy = json.loads(prox)
|
||||
gps_city_id = self.get_city_id(self.bound_city)
|
||||
if not gps_city_id:
|
||||
print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
|
||||
return -1
|
||||
city_gps = CITY_GPS.get(self.bound_city)
|
||||
if not city_gps:
|
||||
print(f"城市 {self.bound_city} 在 CITY_GPS 无坐标,跳过")
|
||||
return -1
|
||||
result = clean_and_insert_hotel_booking(task)
|
||||
hotel_info = task["data"]
|
||||
print(result)
|
||||
params['poiId'] = task['data']['hotelId']
|
||||
start = str(int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000))
|
||||
end = str(int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000))
|
||||
params['start'] = start
|
||||
params['end'] = end
|
||||
params['gps_cityid'] = gps_city_id
|
||||
params['locateCityId'] = gps_city_id
|
||||
params['locatecityid'] = gps_city_id
|
||||
params['cityId'] = task["data"]["cityId"]
|
||||
params['ci'] = task["data"]["cityId"]
|
||||
params['channelCityId'] = task["data"]["cityId"]
|
||||
params['channelSelectCityId'] = task["data"]["cityId"]
|
||||
params['gps_cityid'] = task["data"]["cityId"]
|
||||
params['lat'] = city_gps[0]
|
||||
params['lng'] = city_gps[1]
|
||||
new_url = build_url(url, params)
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
# headers['mtgsig'] = get_sign_new_get(new_url, '', dfpid, mtg_origin)
|
||||
if 'openId' in headers:
|
||||
openId = headers['openId']
|
||||
else:
|
||||
openId = headers['openid']
|
||||
headers['mtgsig'] = get_sign_new1_get(new_url, '', dfpid, mtg_origin,openId)
|
||||
|
||||
response = requests.get(new_url, headers=headers, proxies=self.proxy)
|
||||
|
||||
# print("response.text[:]", '-' * 50, response.text[:])
|
||||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||||
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), '网络不给力(418)', code=418)
|
||||
return 418
|
||||
if "Unauthorized" in response.text[:500]:
|
||||
print(response.text[:500])
|
||||
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), 'Unauthorized(401)', code=401)
|
||||
return 401
|
||||
res = response.json()
|
||||
_upload_resp = upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
|
||||
# 埋点:交任务结果(code=0 为成功)
|
||||
insight.log_upload(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
|
||||
getattr(self, 'cur_target_city', None), _upload_resp,
|
||||
unique_id=hotel_info.get('uniqueId'), city_name=hotel_info.get('cityName'))
|
||||
self.last_trace_id = self._find_trace_id(res)
|
||||
sql = '''
|
||||
INSERT INTO `hotel_json`
|
||||
(json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
'''
|
||||
tent.write_data(sql, ((
|
||||
json.dumps(res), hotel_info.get('hotelId'), hotel_info.get('cityId'), hotel_info.get('hotelName'),
|
||||
hotel_info.get('cityName'), hotel_info.get('checkInDate'), hotel_info.get('checkOutDate')),))
|
||||
return 1
|
||||
|
||||
def get_headers(self):
|
||||
# 取一批可用抓包 headers,主循环随机挑一条跑
|
||||
sql = '''
|
||||
SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and current_count<10;
|
||||
'''
|
||||
sql = '''
|
||||
SELECT `id`,json_data,prox,city,mt_traceid,dfpid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL;
|
||||
'''
|
||||
# sql = '''
|
||||
# SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and ((is_ok != 403 and is_ok != 418 and is_ok != 401) or is_ok is null) and id=12635
|
||||
# '''
|
||||
headers = tent2.get_shoppingmalls(sql)
|
||||
return headers
|
||||
|
||||
def run_one(self, items):
|
||||
items = list(items)
|
||||
# 埋点兜底:拿任务失败时还没走 item 选择,先用首条记录账号身份(不影响主流程)
|
||||
_fallback = items[0] if items else None
|
||||
_fallback_id = _fallback[0] if _fallback else None
|
||||
_fallback_dfpid = _fallback[5] if _fallback and len(_fallback) > 5 else None
|
||||
prox_cities = []
|
||||
for prox_city in self.proxy_list:
|
||||
if prox_city[1]:
|
||||
prox_cities.append(prox_city[1])
|
||||
headers_cities = []
|
||||
for headers_city in items:
|
||||
if headers_city[3]:
|
||||
headers_cities.append(headers_city[3])
|
||||
if headers_cities:
|
||||
task_city = headers_cities[random.randint(0, len(headers_cities) - 1)]
|
||||
else:
|
||||
task_city = prox_cities[random.randint(0, len(prox_cities) - 1)]
|
||||
task = get_one_task(self.VENDOR, self.USER, self.PWD, task_city, task_city)
|
||||
print(task)
|
||||
if not task:
|
||||
# 埋点:拿任务失败(前端“空任务”告警来源)
|
||||
insight.log_fetch_empty(_fallback_id, _fallback_dfpid, None, task_city, task)
|
||||
# 拿任务失败:把该城市下所有可用包(is_ok IS NULL)标记为 0,看板上一眼能看出该城包不可用
|
||||
self.mark_city_failed(task_city)
|
||||
print(task_city)
|
||||
return -1
|
||||
cityName = task['data']['cityName']
|
||||
none_city_item_list = []
|
||||
items = list(items)
|
||||
random.shuffle(items)
|
||||
item = None
|
||||
for j in items:
|
||||
if j[3] is None:
|
||||
none_city_item_list.append(j)
|
||||
elif j[3] in cityName:
|
||||
item = j
|
||||
break
|
||||
if not item:
|
||||
if none_city_item_list:
|
||||
item = none_city_item_list[0]
|
||||
else:
|
||||
# 城市不匹配:任务城市在可用包里找不到对应账号 → 这轮跑不了,标记后跳过
|
||||
print(f"没有与任务城市 {cityName} 匹配的包,跳过")
|
||||
self.mark_city_mismatch(task_city, _fallback_id, _fallback_dfpid,
|
||||
f"任务城市 {cityName} 没有匹配的包")
|
||||
return -1
|
||||
# 跑单条抓包:解析 headers -> 绑定城市/IP -> 分接口请求 -> 回写状态
|
||||
ind, hd, prox, city, mt_traceid, dfpid = item
|
||||
# 埋点:领到任务(账号 + 绑定城市 + 目标城市)
|
||||
self.cur_hd_id = ind
|
||||
self.cur_dfpid = dfpid
|
||||
self.cur_target_city = task_city
|
||||
insight.log_fetch(ind, dfpid, city, task_city, task)
|
||||
url, headers, data = json.loads(hd)
|
||||
if isinstance(data, str) and '{' in data:
|
||||
data = json.loads(data)
|
||||
new_url, params = parse_url(url)
|
||||
# 上次响应有 traceId 时,带回请求头继续跑
|
||||
if mt_traceid:
|
||||
headers['M-TRACEID'] = mt_traceid
|
||||
self.last_trace_id = mt_traceid
|
||||
|
||||
# city/prox 只要已有绑定就优先沿用,避免城市和 IP 来回跳
|
||||
if city and prox:
|
||||
self.proxy = json.loads(prox)
|
||||
self.bound_city = city
|
||||
elif city and not prox:
|
||||
# 有城市没IP:从代理池里补同城 IP
|
||||
matched = [p for p in self.proxy_list if p[1] == city]
|
||||
if not matched:
|
||||
print(f"城市 {city} 在代理池无IP,跳过")
|
||||
self.mark_city_mismatch(city, ind, dfpid, f"城市 {city} 在代理池没有可用 IP")
|
||||
return
|
||||
self.proxy = json.loads(matched[0][0])
|
||||
self.bound_city = city
|
||||
elif not city and prox:
|
||||
# 有IP没城市:反查这个 IP 属于哪个城市
|
||||
matched = [p for p in self.proxy_list if p[0] == prox]
|
||||
if not matched:
|
||||
print(f"ID={ind} 有IP但反查不到城市,跳过")
|
||||
self.mark_city_mismatch(city or getattr(self, "bound_city", None), ind, dfpid,
|
||||
"代理 IP 反查不到城市")
|
||||
return
|
||||
self.bound_city = matched[0][1]
|
||||
self.proxy = json.loads(prox)
|
||||
city = self.bound_city
|
||||
else:
|
||||
# 全新包:随机拿一个 IP,并把城市绑定回 hotel_hd
|
||||
# pick = self.proxy_list[random.randint(0, len(self.proxy_list) - 1)]
|
||||
for pick in self.proxy_list:
|
||||
if pick[1] == cityName.replace('市',''):
|
||||
self.proxy = json.loads(pick[0])
|
||||
self.bound_city = pick[1]
|
||||
break
|
||||
city = self.bound_city
|
||||
|
||||
print(f"本次使用: 城市={self.bound_city}, proxy={self.proxy}")
|
||||
|
||||
try:
|
||||
# 根据抓包 URL 分发到对应请求函数
|
||||
if '/hotel/core/router/shelf' in new_url:
|
||||
result = self.run_shelf(new_url, params, headers, data, None, task)
|
||||
if result == -1:
|
||||
# 绑定城市查不到 cityId / 没有坐标 → 城市不匹配,这包跑不了
|
||||
_c = getattr(self, "bound_city", None) or city
|
||||
self.mark_city_mismatch(_c, ind, dfpid, f"城市 {_c} 缺少 cityId/坐标")
|
||||
return -1
|
||||
elif '/productapi/v3/prepayList' in new_url:
|
||||
result = self.run_prepayList(new_url, params, headers, None, task)
|
||||
if result == -1:
|
||||
_c = getattr(self, "bound_city", None) or city
|
||||
self.mark_city_mismatch(_c, ind, dfpid, f"城市 {_c} 缺少 cityId/坐标")
|
||||
return -1
|
||||
else:
|
||||
print(f"未知接口,跳过: {new_url}")
|
||||
return
|
||||
self.update_headers(result, ind, city, self.last_trace_id)
|
||||
except Exception as e:
|
||||
error_msg = f"""
|
||||
{'=' * 50}
|
||||
时间: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
ID: {ind}
|
||||
错误类型: {type(e).__name__}
|
||||
错误信息: {str(e)}
|
||||
详细堆栈:
|
||||
{traceback.format_exc()}
|
||||
{'=' * 50}
|
||||
"""
|
||||
print(error_msg)
|
||||
if 'Expecting value: line 1 column 1 (char 0)' in str(e):
|
||||
is_ok = 403
|
||||
else:
|
||||
is_ok = 0
|
||||
# 埋点:请求异常(403 解析失败 / 0 其它),不影响原有的 is_ok 回写
|
||||
insight.log_exception(ind, dfpid, task_city, e, code=is_ok)
|
||||
self.update_headers(is_ok, ind, city, None)
|
||||
|
||||
def mark_package_failed(self, hd_id, reason=""):
|
||||
"""把单个包标记为 is_ok=0(城市不匹配 / 这包跑不了)。失败只打印,不影响主流程。"""
|
||||
if not hd_id:
|
||||
return
|
||||
try:
|
||||
tent2.update_data(f"UPDATE hotel_hd SET is_ok=0 WHERE `id`={int(hd_id)}")
|
||||
print(f"包 #{hd_id} {reason} → is_ok=0")
|
||||
except Exception as e:
|
||||
print(f"标记包失败(不影响主流程): {type(e).__name__}: {e}")
|
||||
|
||||
def mark_city_mismatch(self, city, hd_id=None, dfpid=None, reason="城市不匹配"):
|
||||
"""城市不匹配导致这轮跑不了:①记一次拿任务失败(看板“拿任务失败城市”)②该包 is_ok=0。
|
||||
|
||||
两个动作各自兜底,任何异常都不能影响采集主流程。
|
||||
"""
|
||||
if city:
|
||||
try:
|
||||
insight.log_fetch_empty(hd_id, dfpid, city, city, None, note=reason)
|
||||
except Exception:
|
||||
pass
|
||||
self.mark_package_failed(hd_id, f"{reason}(城市 {city or '未知'})")
|
||||
|
||||
def mark_city_failed(self, city):
|
||||
"""拿任务失败时,把该城市下所有可用包(is_ok IS NULL)标记为 0。
|
||||
|
||||
只影响“该城市 + 可用”的行;任何异常都只能打印,不能影响采集主流程。
|
||||
"""
|
||||
if not city:
|
||||
return
|
||||
try:
|
||||
safe = str(city).replace("'", "")
|
||||
sql = f'''
|
||||
UPDATE hotel_hd SET is_ok=0 WHERE city='{safe}' AND is_ok IS NULL AND title LIKE '%美团酒店详情%'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
print(f"城市 {city} 拿任务失败 → 该城市可用包已标记 is_ok=0")
|
||||
except Exception as e:
|
||||
print(f"标记城市失败(不影响主流程): {type(e).__name__}: {e}")
|
||||
|
||||
def update_headers(self, is_ok, ind, city, mt_traceid):
|
||||
# 成功只累计次数,失败写 is_ok 状态,proxy/city/traceId 都回填
|
||||
if is_ok == 1:
|
||||
sql = f'''
|
||||
UPDATE hotel_hd SET current_count=current_count+1,req_count=req_count+1,prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
|
||||
'''
|
||||
else:
|
||||
sql = f'''
|
||||
UPDATE hotel_hd SET is_ok={is_ok},prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
|
||||
def _find_trace_id(self, obj):
|
||||
"""递归找响应里第一个 traceId 值"""
|
||||
if isinstance(obj, dict):
|
||||
if 'traceId' in obj:
|
||||
return str(obj['traceId'])
|
||||
for v in obj.values():
|
||||
r = self._find_trace_id(v)
|
||||
if r:
|
||||
return r
|
||||
elif isinstance(obj, list):
|
||||
for item in obj:
|
||||
r = self._find_trace_id(item)
|
||||
if r:
|
||||
return r
|
||||
return None
|
||||
|
||||
def get_city_id(self, city_name):
|
||||
"""从 area_info 查美团 cityId,查不到返回 None"""
|
||||
sql = f"SELECT cityId FROM area_crood.area_info WHERE cityName='{city_name}' and title like '%美团%' LIMIT 1"
|
||||
rows = tent.get_shoppingmalls(sql)
|
||||
if rows:
|
||||
return rows[0][0]
|
||||
return None
|
||||
|
||||
def get_prox(self):
|
||||
sql = '''
|
||||
SELECT prox_data,city FROM project_proxy.proxs_list WHERE channel ORDER BY RAND()
|
||||
'''
|
||||
prox_list = tent2.get_shoppingmalls(sql)
|
||||
return prox_list
|
||||
|
||||
|
||||
PID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs', 'collector.pid')
|
||||
|
||||
|
||||
def _write_pidfile():
|
||||
"""写 pid 文件:看板据此判断采集是否已经在跑,避免重复启动两个进程。"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(PID_FILE), exist_ok=True)
|
||||
with open(PID_FILE, 'w', encoding='utf-8') as f:
|
||||
f.write(str(os.getpid()))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _remove_pidfile():
|
||||
try:
|
||||
with open(PID_FILE, encoding='utf-8') as f:
|
||||
pid = f.read().strip()
|
||||
if pid == str(os.getpid()):
|
||||
os.remove(PID_FILE)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
_write_pidfile()
|
||||
try:
|
||||
for i in range(1000):
|
||||
ht = hotel_run()
|
||||
items = ht.get_headers()
|
||||
ht.run_one(items)
|
||||
time.sleep(random.randint(2, 5))
|
||||
# run2()
|
||||
except KeyboardInterrupt:
|
||||
print('收到 Ctrl+C,退出采集')
|
||||
finally:
|
||||
_remove_pidfile()
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
import json
|
||||
import time
|
||||
|
||||
import requests
|
||||
from urllib.parse import urlencode, urlparse, parse_qs, parse_qsl
|
||||
from 酒店任务拿交 import upload_one_task
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
|
||||
from 小程序mtgsig import get_mtgsig
|
||||
|
||||
|
||||
# ============ 配置区:改这里 ============
|
||||
|
||||
|
||||
URL,HEADERS,DATA = ["https://ihotel.meituan.com/productapi/v3/prepayList?yodaReady=wx&csecappid=wxde8ac0a21135c07d&csecplatform=3&csecversionname=10.41.0&csecversion=3.0.2&openId=oJVP50B5pWFjPr-hHNaOFADrP4MY&antiRepPlatform=Android&programName=mt&utm_medium=WEIXINPROGRAM&riskLevel=71&optimusCode=10&openIdCipher=AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM%2Fhf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n%2FGVnwfURonD78PewMUppAAAADiC6UqAIztNtcdvifUxC3edcjqcJ7EuUfVNA4Fp4qBVR9KW20InHGBxrMbFnZcBOzK9YUyAiadiBA%3D%3D&utm_campaign=entry%253DMTLive_scene%253D1089&token=AgEzKHnw75seA5pXliNel44SH3cBQe5FRPOzQB0dp-27726kt6T6g-Jbix-tvpDY2LaS5Wr4m3nDXgAAAAAnPAAAGKiOiDCNaI337Rb8_WoYrkqmgG7-HAW2j_L1_-o7YvywQ8jqIlEPi9owWPHx7Sib&usertoken=AgEzKHnw75seA5pXliNel44SH3cBQe5FRPOzQB0dp-27726kt6T6g-Jbix-tvpDY2LaS5Wr4m3nDXgAAAAAnPAAAGKiOiDCNaI337Rb8_WoYrkqmgG7-HAW2j_L1_-o7YvywQ8jqIlEPi9owWPHx7Sib&userToken=AgEzKHnw75seA5pXliNel44SH3cBQe5FRPOzQB0dp-27726kt6T6g-Jbix-tvpDY2LaS5Wr4m3nDXgAAAAAnPAAAGKiOiDCNaI337Rb8_WoYrkqmgG7-HAW2j_L1_-o7YvywQ8jqIlEPi9owWPHx7Sib&userId=9274775939&userid=9274775939&uuid=1a1484ba4b6c8-b8bb35571a780-0-0-1a1484ba4b635&locateCityId=20&locatecityid=20&appMiniVersion=10.41.200&lat=23.152783&lng=113.249246&appletShieldScene=null&poiId=625965&costSourceChannel=1&version_name=11.2.200&input=&keyword=&start=1792195200000&end=1792281600000&propagateData=LKuRjbXoHk0wR51r1x2RQW6GFN2V72A2CokKP2lkSkBJjCF4C4Yf0jRbRnCRWEXGYiK2Jh7azjpU8QBZ%2BBhE6kOBJ7u50bGBaJ0XGJN%2FEXc66l47Nt0hzzlGXvjAx4SO6%2FbCYnDeVxmZo%2BKux94LTl1iPAYKn0hAfO0cRCHhMqPbJL5CbwveKqWr1XFUdQ%2BfG3blcxY9kOMu%2BqNNaUc6M0jzQ%2BRV7fF3FCvI7HhzkXAXyBOKVmrG8atEOvlclAPQrzLIRGWvqQPLE8LdOD2rLo3IPUDI0%2Bna0z8rFZU7mn4kJYTOtMyBO0k3c3X957uzBnQ63W73Qc7%2FQzhUHUldfzKW6CS3zCeWTvj693pbu84%3D&mtShareId=&fromOffline=false&flagshipFilter=1&gps_cityid=20&needShowNewDiscInfo=false&cityId=20&ci=20&channelCityId=20&hotelCustomGpsStatus=0&type=1&specialDealHotelScene=true&riskPlatform=13&channelSelectCityId=20&appletVersionName=10.41.0&appletAppId=wxde8ac0a21135c07d&specAttributionChannel=&magicMemberCode=1102%2C1103&utm_fp=MINI_PROGRAM&wechatVersion=8.0.77&SDKVersion=3.17.4", {"Host": "ihotel.meituan.com", "Connection": "keep-alive", "charset": "utf-8", "mtgsig": "{\"a1\":\"1.2\",\"a2\":1792217216957,\"a3\":\"x23uzx7xvu1v508uz32v8y50y023y89y8z8515yz19v779787w4211y7\",\"a4\":\"1002c1898fd5a98b89c102108ba9d58f34b67a58bf1fafd7\",\"a5\":\"xyH/nswUMW8H2o2RY2YQgYiP3V3URzdp9qOtJttQ5tLGf1UXO1722mcr0Ark4cvCe8VmYOGE85Ux0K18OJUtY1XjJz8cZjtF0P13hAyfGC7vWrz6mto9mymyHo2XovbYsQuZY3Euy44loclVMM1Z8b60UrmLEZtqDWx9ge2ANF0Q0TkY4I5Udaad4HxjSpjqjj49K3DdE4dsBF0SYLokqhmwwgbuigsrlTCjHLNMezR7BdnUo+tCIJEGRGkvmAWnDs/ch9hpk2adrA89e/btZcCTrHJsVWWJh/YyIb1rTMNXvopTaGxQzLwW2F9ZuVomDv+EAqlfY/H=\",\"a6\":\"w1.6Swc6DehtNKOHz6SpvGiWd5vMMNEvk2ueXWqW5CsKSANeZQergUqX08YPnzXcOGN50hZse+xzXieDAXuD10Fp+zdEH1cRS666kjxZJWk4x7Ez8povMRsOqGSCGyDfSg3VnXIbpbymJ/VOdsqTnvYs12LAKENlo9/V3kDE2gUKI3szHUmUNLh6tK+wmpDon8eQICswwVYms7z1fB8MmkCCfl8yZHQNYCGJJU/aBD7LDq3qKOzoKXVfeyM49NgVUptJ0g81uhzoNRSwH5YkHKHYLL238BZpwXi45cASP40aZ1RDsb/vU7DjR1L9k8FPUChiucbF/67FryKo3PPElorgEg9lTtoVNOg7cC6zMt5vMbOuR/shS1T1dfsTC0m2rdj8lNUKOP9UKWIdfvIlS9w81p9yGhpLK+pbcja0nau14INpLtVpuP8QAK3Kmuy7fMgdVWEP6rMPI+JxEKlLKm5ZhRd+2gtMumXedw7KdroKPfz7+cOm8j+ezE+bYlMWxEuBzZh4vhdpIW+AhTonuCzhvSuzSe80JT0u90cNd+Wl77Yfq6RH8frofbmuUxvuPhPc8EhvqW+DoJ9iQa0efE5ma638FITNNE9QJK7F5pXP3Ed5vXGfjCzVe9vRdKtMhnX0gldXho0wgkXFMwErJJjpl1p5CMPSTNTL2xe8Jln3QHjKquKRWfEYRHU53RS/A7s5x3jLjJCr0/eeOtPqOCzOKQ==\",\"a7\":\"wxde8ac0a21135c07d\",\"x0\":3,\"d1\":\"a14a9f197a1c29a0a430dba4718146ac\"}", "m-appkey": "wxmp_mt-weapp", "clientversion": "3.17.4", "x_htas_version": "0.1.31", "openid": "oJVP50B5pWFjPr-hHNaOFADrP4MY", "utm_medium": "", "User-Agent": "Mozilla/5.0 (Linux; Android 12; HD1900 Build/SKQ1.211113.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/150.0.7871.189 Mobile Safari/537.36 XWEB/1500145 MMWEBSDK/20260604 MMWEBID/137 MicroMessenger/8.0.77.3160(0x28004D3B) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android", "Accept-Encoding": "gzip,compress,br,deflate", "uuid": "1a1484ba4b6c8-b8bb35571a780-0-0-1a1484ba4b635", "csecuuid": "1a1484ba4b6c8-b8bb35571a780-0-0-1a1484ba4b635", "token": "AgEzKHnw75seA5pXliNel44SH3cBQe5FRPOzQB0dp-27726kt6T6g-Jbix-tvpDY2LaS5Wr4m3nDXgAAAAAnPAAAGKiOiDCNaI337Rb8_WoYrkqmgG7-HAW2j_L1_-o7YvywQ8jqIlEPi9owWPHx7Sib", "m-traceid": "8143920622990422757", "content-type": "application/json", "csecuserid": "9274775939", "openidcipher": "AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADiC6UqAIztNtcdvifUxC3edcjqcJ7EuUfVNA4Fp4qBVR9KW20InHGBxrMbFnZcBOzK9YUyAiadiBA==", "Referer": "https://servicewechat.com/wxde8ac0a21135c07d/1587/page-frame.html"}, ""]
|
||||
|
||||
# 写死的业务参数
|
||||
# POI_ID = '646350' # 酒店 id
|
||||
POI_ID_LIST = [
|
||||
'1350841653',
|
||||
'585740196',
|
||||
'194650023',
|
||||
'192693425',
|
||||
'1755253168',
|
||||
'1589607660',
|
||||
'185123888',
|
||||
'157312136',
|
||||
'156798801',
|
||||
'101119909',
|
||||
'744901617',
|
||||
'1886539162',
|
||||
'824892698',
|
||||
'1763147689',
|
||||
'193089505',
|
||||
'1919424956',
|
||||
'1413611452',
|
||||
'1902698854',
|
||||
'6936066',
|
||||
'1153696811',
|
||||
'1713882359',
|
||||
'179664987',
|
||||
'1891437524',
|
||||
'660986989',
|
||||
'102435953',
|
||||
'938802645',
|
||||
'4567318',
|
||||
'158954027',
|
||||
'5927436',
|
||||
'99380749',
|
||||
'195089986',
|
||||
'1478631664',
|
||||
'1694171709',
|
||||
'163321873',
|
||||
'620304',
|
||||
'75051130',
|
||||
'1478363201',
|
||||
'177691085',
|
||||
'626004',
|
||||
]
|
||||
CITY_ID = '20' # 城市 id
|
||||
CHECK_IN_DATE = '2026-10-20' # 入住日期 例 2026-06-20
|
||||
CHECK_OUT_DATE = '2026-10-21' # 离店日期 例 2026-06-21
|
||||
|
||||
# 代理,不用就 None;用就 {'http': 'http://...', 'https': 'http://...'}
|
||||
PROXY = {"http": "http://uuvg:uuvgt@183.131.35.92:21323", "https": "http://uuvg:uuvgt@183.131.35.92:21323"}
|
||||
|
||||
# ============ 配置区结束 ============
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def parse_url(url):
|
||||
parsed = urlparse(url)
|
||||
base_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
params = {}
|
||||
for key, value in parse_qsl(parsed.query, keep_blank_values=True):
|
||||
if key in params:
|
||||
if isinstance(params[key], list):
|
||||
params[key].append(value)
|
||||
else:
|
||||
params[key] = [params[key], value]
|
||||
else:
|
||||
params[key] = value
|
||||
return (base_url, params)
|
||||
|
||||
|
||||
def build_url(base_url, params):
|
||||
query_string = urlencode(params, doseq=True)
|
||||
full_url = f"{base_url}?{query_string}"
|
||||
return full_url
|
||||
|
||||
|
||||
def get_sign_new(url, data, dfpid, mtg_origin):
|
||||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||||
body = {
|
||||
"mtg_origin": mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST"}
|
||||
req = requests.post('http://8.138.127.139:10063/newmtgsig', headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
return req
|
||||
|
||||
def get_sign_new1(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
|
||||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||||
body = {
|
||||
"mtg_origin":mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET",
|
||||
"open_id": openId,# 微信的open_id
|
||||
}
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
def get_sign_new_get(url, data, dfpid, mtg_origin):
|
||||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||||
body = {
|
||||
"mtg_origin": mtg_origin,
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "GET"}
|
||||
req = requests.post('http://8.138.127.139:10063/newmtgsig', headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
return req
|
||||
|
||||
|
||||
def run_shelf(url, params, headers, data):
|
||||
data['poiId'] = POI_ID
|
||||
data['requestParams'][0]['businessParams']['poiId'] = POI_ID
|
||||
start = int(datetime.strptime(CHECK_IN_DATE, '%Y-%m-%d').timestamp() * 1000)
|
||||
end = int(datetime.strptime(CHECK_OUT_DATE, '%Y-%m-%d').timestamp() * 1000)
|
||||
data['requestParams'][0]['businessParams']['start'] = start
|
||||
data['requestParams'][0]['businessParams']['end'] = end
|
||||
data['requestParams'][0]['businessParams']['cityId'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['channelCityId'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['userCityId'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['appCityId'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['gps_cityid'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['gpsCityid'] = CITY_ID
|
||||
data['requestParams'][0]['businessParams']['lat'] = '31.231301'
|
||||
data['requestParams'][0]['businessParams']['lng'] = '121.472730'
|
||||
|
||||
data2 = json.dumps(data, separators=(',', ':'))
|
||||
new_url = build_url(url, params)
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
openId = headers['openId']
|
||||
headers['mtgsig'] = get_sign_new1(new_url, data2, dfpid, mtg_origin,openId)
|
||||
response = requests.post(new_url, headers=headers, data=data2, proxies=PROXY,verify=False)
|
||||
print("response.text[:]", '-' * 50, response.text[:])
|
||||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||||
return 418
|
||||
if "Unauthorized" in response.text[:]:
|
||||
return 401
|
||||
res = response.json()
|
||||
print(json.dumps(res, ensure_ascii=False)[:2000])
|
||||
return 1
|
||||
|
||||
|
||||
def run_prepayList(url, params, headers):
|
||||
params['poiId'] = POI_ID
|
||||
start = int(datetime.strptime(CHECK_IN_DATE, '%Y-%m-%d').timestamp() * 1000)
|
||||
end = int(datetime.strptime(CHECK_OUT_DATE, '%Y-%m-%d').timestamp() * 1000)
|
||||
params['start'] = start
|
||||
params['end'] = end
|
||||
params['gps_cityid'] = CITY_ID
|
||||
params['cityId'] = CITY_ID
|
||||
params['ci'] = CITY_ID
|
||||
params['channelCityId'] = CITY_ID
|
||||
params['channelSelectCityId'] = CITY_ID
|
||||
params['lat'] = "23.130861"
|
||||
params['lng'] = "113.259601"
|
||||
new_url = build_url(url, params)
|
||||
print(f'new_url: {new_url}')
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
if 'openid' in headers:
|
||||
openId = headers['openid']
|
||||
else:
|
||||
openId = headers['openId']
|
||||
# headers['mtgsig'] = get_sign_new1_get(new_url, '', dfpid, mtg_origin,openId)
|
||||
headers['mtgsig'] = get_mtgsig(new_url, '', mtg_origin,openId,'GET')
|
||||
print(headers['mtgsig'])
|
||||
response = requests.get(new_url, headers=headers, proxies=PROXY,verify=False)
|
||||
print("response.text[:500]", '-' * 50, response.text[:500])
|
||||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||||
return 418
|
||||
if "Unauthorized" in response.text[:500]:
|
||||
return 401
|
||||
res = response.json()
|
||||
print(json.dumps(res, ensure_ascii=False)[:])
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
USER = "thzn-datagram0001"
|
||||
PWD = "thzn-datagram0001"
|
||||
VENDOR = "mt-datagram"
|
||||
clientid = '广州'
|
||||
n=0
|
||||
# new_url = build_url(url, params)
|
||||
# print(json.dumps([new_url, headers, '']))
|
||||
# task_data = {'code': 0, 'message': 'success', 'data': {'hotelId': '649339', 'cityId': '20', 'hotelName': '广东地质山水酒店', 'hotelAddress': '越秀区环市东路476号(近动物园南门)', 'cityName': '广州市', 'checkInDate': '2026-07-22', 'checkOutDate': '2026-07-23', 'uniqueId': '20260721195943-32-32-2001001-22-756', 'timeLeft': 1200, 'hotelStar': '高档型', 'selectedCity': '广东省:20_广州市', 'areaType': '行政区/商圈', 'areaName': '环市东路附近', 'level': 0, 'parseType': 'text'}}
|
||||
for POI_ID in POI_ID_LIST[:30]:
|
||||
requests.packages.urllib3.disable_warnings()
|
||||
base_url, params = parse_url(URL)
|
||||
# DATA = json.loads(DATA)
|
||||
if 'shelf' in URL:
|
||||
result = run_shelf(base_url, params, HEADERS, DATA)
|
||||
elif 'prepayList' in URL:
|
||||
result = run_prepayList(base_url, params, HEADERS)
|
||||
else:
|
||||
result = None
|
||||
print('RUN_TYPE 配置错误,只能是 shelf 或 prepayList')
|
||||
# upload_one_task(VENDOR, USER, PWD, clientid, task_data, result)
|
||||
n+=1
|
||||
print(f'成功完成{"-"*10+str(n)+"-"*10}个')
|
||||
time.sleep(5)
|
||||
Reference in New Issue
Block a user