✓ 个人文档授权成功
云端已获得读取「我的云文档」的权限,之后的同步不再依赖本机 Mac。
可以关闭本页。
""", 200)
@app.route("/api/kdocs/files", methods=["GET"])
def kdocs_files():
"""列出个人文档(扁平),供管理员确认数据集与文件的对应关系。"""
import kdocs_cloud
try:
files = kdocs_cloud.list_files(exts=request.args.get("exts", "xlsx"))
except Exception as e:
return jsonify({"error": str(e)[:300]}), 400
slim = [{"file_token": kdocs_cloud._token(f),
"fname": kdocs_cloud._fname(f),
"mtime": f.get("mtime"),
"fsize": f.get("fsize") or f.get("size")} for f in files]
return jsonify({"count": len(slim), "files": slim})
@app.route("/api/kdocs/mapping", methods=["GET", "PUT"])
def kdocs_mapping():
"""数据集 → 个人文档 的显式映射(文件名不像 ds.name 时用它兜底)。"""
conn = get_conn()
try:
if request.method == "PUT":
body = request.get_json(silent=True) or {}
cfg = _load_cfg(conn)
m = cfg.get("kdocs_files")
if not isinstance(m, dict):
m = {}
for ds_id, info in (body.get("files") or {}).items():
if not isinstance(info, dict):
continue
m[ds_id] = {"file_token": info.get("file_token") or "",
"fname": info.get("fname") or ""}
cfg["kdocs_files"] = m
_save_cfg(conn, cfg)
return jsonify({"ok": True, "count": len(m)})
return jsonify(_load_cfg(conn).get("kdocs_files") or {})
finally:
conn.close()
# ---------- 云端同步状态(谁在跑、跑得怎么样、历史留了多少) ----------
@app.route("/api/sync/scheduler", methods=["GET"])
def sync_scheduler_status():
"""一眼看清"云端到底在不在同步"。
这个端点的存在理由:之前数据停滞 15 天没人发现,因为"调度器在跑"和
"真的抓到数据了"是两件事,而界面上看不出区别。
"""
import os as _os
import sync_engine as se
conn = get_conn()
try:
cfg = _load_cfg(conn)
finally:
conn.close()
try:
interval = int(cfg.get("sync_interval_min") or se.DEFAULT_INTERVAL_MIN)
except Exception:
interval = se.DEFAULT_INTERVAL_MIN
runs = cfg.get("sync_runs") or []
hist = cfg.get("dataset_history") or {}
return jsonify({
"enabled": _os.environ.get("SYNC_DISABLED") != "1",
"interval_min": interval,
"wps_ready": se._kdocs_ready(), # 个人空间凭证是否就位
"dingtalk_ready": bool(se._dt_ready()
if hasattr(se, "_dt_ready") else False),
"last_run": se.last_run(),
"recent_runs": runs[-8:],
"history": {
"datasets_tracked": len(hist),
"points": sum(len(v) for v in hist.values() if isinstance(v, list)),
"latest": {k: (v[-1] if isinstance(v, list) and v else None)
for k, v in list(hist.items())[:20]},
},
"note": ("抓取端凭证齐备后,云端每 "
f"{interval} 分钟自动抓一次,不再依赖本机 Mac"),
})
_HEALTH_CACHE = {"at": 0.0, "data": None}
_HEALTH_TTL = 30.0
def _probe_db(timeout: float = 1.5):
"""带硬超时的数据库探针。
返回 {"ok":bool,"err":str} 或 None(超时)。
为什么要另开线程:容器冷启动后第一次算门店要解析 98 个数据集(实测 41 秒),
这期间 GIL 被占、数据库连接也被占,健康检查里的 SELECT 会一直排队。
平台 30 秒探不到就判定"服务挂了"→ 重启 → 又冷启动 → 死循环。
给探针 1.5 秒硬上限,超时就当"忙",但**进程是活的**,不该被杀。
"""
res: Dict[str, Any] = {"ok": False, "err": ""}
def _run():
try:
conn = get_conn()
try:
conn.execute("SELECT id FROM stores LIMIT 1").fetchall()
res["ok"] = True
finally:
conn.close()
except Exception as e: # noqa: BLE001
res["err"] = str(e)[:120]
th = threading.Thread(target=_run, daemon=True)
th.start()
th.join(timeout)
return None if th.is_alive() else res
@app.route("/api/health")
def health():
"""健康检查 + 部署诊断。
⚠️ 三条硬约束(11-19 / 11-20 两次事故后加的,别改回去):
1) **30 秒缓存**。部署平台每分钟探好几次,一次要查 4 张表。
2) **数据库探针 1.5 秒硬超时**。冷启动解析 98 个数据集要 41 秒,
这段时间探针会排队;超时也只是"忙",不是"死"。
3) **数据库慢/忙一律返回 200**。503 会直接触发平台重启,
而重启只会让它再冷启动一次 —— 越重启越慢,这就是 504 的循环。
"""
_t = time.time()
_hit = _HEALTH_CACHE.get("data")
if _hit is not None and (_t - _HEALTH_CACHE.get("at", 0)) < _HEALTH_TTL:
return jsonify(_hit)
info = {"ok": True, "time": now_str(),
# 部署核对标记:改了代码但线上行为没变时,先看这里确认是不是
# 容器根本没换成新版本(11-20 排查拉数问题就靠它排除了一大嫌疑)
"build": "2026-11-20-1545"}
warn = []
# 1) 数据库连通(带硬超时,只探一张最小的表)
_p = _probe_db(1.5)
if _p is None:
# 忙(多半在解析数据集):仍然 200,让平台知道"进程活着"
info["db"] = "busy"
warn.append("数据库探针超时(服务可能在预热,稍等)")
info["warnings"] = warn
_HEALTH_CACHE["at"] = _t
_HEALTH_CACHE["data"] = info
return jsonify(info)
if not _p["ok"]:
info["db"] = "degraded: %s" % _p["err"]
warn.append("数据库暂时不可用,接口可能失败")
info["warnings"] = warn
_HEALTH_CACHE["at"] = _t
_HEALTH_CACHE["data"] = info
return jsonify(info)
# 2) 业务状态
try:
conn = get_conn()
# 同样避开 COUNT(*),改成把行拉回来在Python 里数
_ds = conn.execute("SELECT id, fetched_at FROM datasets").fetchall()
info["datasets"] = len(_ds)
info["datasets_with_data"] = len([r for r in _ds if r.get("fetched_at")])
if not _ds:
warn.append("尚未接入任何数据集,看板将为空")
elif not info["datasets_with_data"]:
warn.append("数据集均未抓取到数据,请检查同步器与凭证")
_st = conn.execute("SELECT id FROM stores").fetchall()
info["stores"] = len(_st)
if not _st:
warn.append("尚未创建门店,看板按门店维度显示会为空")
cred = conn.execute("SELECT platform FROM platform_credentials").fetchall()
info["credential_platforms"] = [r["platform"] for r in cred]
conn.close()
except Exception as e:
warn.append(f"读取状态失败:{e}")
# 3) 同步器
info["sync_running"] = bool(
sync_engine.SyncScheduler._thread and sync_engine.SyncScheduler._thread.is_alive()
)
info["sync_interval_min"] = sync_engine.DEFAULT_INTERVAL_MIN
if not info["sync_running"] and sync_engine.DEFAULT_INTERVAL_MIN > 0 \
and os.environ.get("SYNC_DISABLED") != "1":
warn.append("同步器未运行,数据不会自动更新")
# 4) 加密密钥
if not os.environ.get("DASHBOARD_SECRET"):
info["secret_source"] = "data/.secret_key(或未生成)"
warn.append("未配置 DASHBOARD_SECRET 环境变量:密钥随部署包走,多实例部署会导致凭证互相解密失败")
else:
info["secret_source"] = "env"
# 5) 到店客流(子项目开放接口):只报状态,不报明细
try:
_c = get_conn()
try:
_tcfg = tfa.load_cfg(_c)
finally:
_c.close()
_tst = tfa.cache_state()
info["traffic"] = {
"enabled": bool(_tcfg.get("enabled")),
"mode": _tcfg.get("mode"),
"visits_cached": _tst.get("rows") or 0,
"cache_age_sec": _tst.get("age_sec"),
"error": (_tst.get("error") or "")[:160],
}
if _tcfg.get("enabled") and _tst.get("error"):
warn.append("客流接口异常:%s" % (_tst.get("error") or "")[:80])
except Exception as e:
info["traffic"] = {"enabled": False, "error": str(e)[:120]}
if warn:
info["warnings"] = warn
_HEALTH_CACHE["at"] = _t
_HEALTH_CACHE["data"] = info
return jsonify(info)
# ==================== 预警类型与规则 ====================
@app.route("/api/alert-types", methods=["GET", "POST"])
def alert_types():
conn = get_conn()
if request.method == "POST":
data = request.json
name = (data.get("name") or "").strip()
if not name:
conn.close()
return jsonify({"error": "预警类型名称不能为空"}), 400
tid = "at_" + str(int(__import__("time").time() * 1000))
conn.execute(
"INSERT INTO alert_types(id, name, icon, color) VALUES(?,?,?,?)",
(tid, name, data.get("icon", "ratio"), data.get("color", "#F0AD4E")),
)
conn.commit()
conn.close()
return jsonify({"id": tid, "name": name})
rows = conn.execute("SELECT * FROM alert_types ORDER BY created_at").fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route("/api/alert-types/