test_system.py 38.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
"""系统:表注释、默认账号与登录、配置加密与云端下发、取数端协议、DMS 登录状态告警、企微接收对象路由、
话术模板、智能助手人设与试聊。"""
from __future__ import annotations

import asyncio
import datetime as dt
import json

from sqlalchemy import inspect, select

from app.core import clock, db
from app.models import im_targets_t, settings_t, store_dms_t
from app.services import agent, alerts, edge, im, settings, stores, texts
from tests.conftest import StoreKit, fake_now, login


def test_every_table_and_column_has_comment(client):
    insp = inspect(db.engine())
    for name in insp.get_table_names():
        if name == db.VERSION_TABLE:
            continue
        assert insp.get_table_comment(name).get("text"), f"表 {name} 没有注释"
        for col in insp.get_columns(name):
            assert col.get("comment"), f"{name}.{col['name']} 没有注释"


def test_every_table_is_atrs_prefixed(client):
    names = inspect(db.engine()).get_table_names()
    assert db.VERSION_TABLE in names
    assert [n for n in names if not n.startswith("atrs_")] == []


def test_healthz_and_default_admin(client):
    assert client.get("/healthz").json()["ok"]
    r = client.post("/api/auth/login", json={"username": "admin", "password": "admin123"}).json()
    assert r["user"]["default_password"] is True
    me = client.get("/api/me", headers={"Authorization": "Bearer " + r["access_token"]}).json()
    assert me["store"]["code"] == "STORE-001" and me["features"][0]["key"] == "restock"


def test_login_lockout_and_password_change(client):
    uid = stores.create_user("ops", "ops-pass-1")
    for _ in range(5):
        assert client.post("/api/auth/login", json={"username": "ops", "password": "wrong"}).status_code == 401
    assert client.post("/api/auth/login", json={"username": "ops", "password": "ops-pass-1"}).status_code == 429
    from app.api import auth
    auth._fails.clear()
    h = login(client, "ops", "ops-pass-1")
    r = client.post("/api/me/password", json={"old_password": "ops-pass-1", "new_password": "ops-pass-2"}, headers=h)
    assert r.status_code == 200 and r.json()["user"]["default_password"] is False
    assert client.get("/api/me", headers=h).status_code == 401                    # 旧令牌失效
    assert client.get("/api/me", headers={"Authorization": "Bearer " + r.json()["access_token"]}).status_code == 200
    db.q(stores.users_t.delete().where(stores.users_t.c.id == uid))


def test_operator_account_from_env(client, monkeypatch):
    from app import bootstrap
    monkeypatch.setenv("OPERATOR_USERNAME", "user")
    monkeypatch.setenv("OPERATOR_PASSWORD", "123456")
    bootstrap.ensure_operator()
    h = login(client, "user", "123456")
    assert client.get("/api/me", headers=h).json()["user"]["role"] == "operator"
    monkeypatch.setenv("OPERATOR_PASSWORD", "654321")                          # 改 .env 重启后同步新密码
    bootstrap.ensure_operator()
    assert client.post("/api/auth/login", json={"username": "user", "password": "123456"}).status_code == 401
    login(client, "user", "654321")
    db.q(stores.users_t.delete().where(stores.users_t.c.username == "user"))


def test_admin_password_synced_from_env(client, monkeypatch):
    """库里已有管理员时:.env 填了 ADMIN_PASSWORD 就每次启动按它同步;没填不动。"""
    from app import bootstrap
    from app.api import auth
    auth._fails.clear()
    u = stores.user_by_name("admin")
    old_hash, old_ver = u["password_hash"], u["token_version"]
    try:
        bootstrap.ensure_admin()                                                   # 没填 ADMIN_PASSWORD:不动
        assert stores.user_by_name("admin")["password_hash"] == old_hash
        monkeypatch.setenv("ADMIN_PASSWORD", "admin@123")
        bootstrap.ensure_admin()
        login(client, "admin", "admin@123")
        ver = stores.user_by_name("admin")["token_version"]
        bootstrap.ensure_admin()                                                   # 已一致:不重复改(不踢登录)
        assert stores.user_by_name("admin")["token_version"] == ver
    finally:
        db.q(stores.users_t.update().where(stores.users_t.c.username == "admin")
             .values(password_hash=old_hash, token_version=old_ver))
        auth._fails.clear()


def test_demo_mode_generates_edge_token(client, monkeypatch):
    """演示模式:云端自动登记演示取数端,令牌写到 data/demo_edge_token;重启不重复登记;非演示模式什么都不做。"""
    from app import bootstrap
    from app.core.config import C
    f = C.data_dir / "demo_edge_token"
    f.unlink(missing_ok=True)
    sid = stores.stores()[0]["id"]
    bootstrap.ensure_demo(sid)
    assert not f.exists()
    monkeypatch.setenv("DEMO_MOCK_DMS", "true")
    bootstrap.ensure_demo(sid)
    tok = f.read_text(encoding="utf-8")
    assert edge.device_by_token(tok)["store_id"] == sid
    assert db.one(select(store_dms_t.c.id).where(store_dms_t.c.store_id == sid))      # 模拟 DMS 账号已填
    bootstrap.ensure_demo(sid)
    assert f.read_text(encoding="utf-8") == tok
    f.unlink()


def test_requires_login(client):
    for path in ("/api/system/settings", "/api/client/overview", "/api/wecom/overview", "/api/restock/today"):
        assert client.get(path).status_code == 401, path


# ====================================================================== 配置:加密保存、打码返回、云端下发
def test_secret_settings_encrypted_and_masked(client, admin, kit):
    r = client.put("/api/system/settings", json={"llm_api_key": "sk-abcdef123456", "llm_model": "qwen-max"},
                   headers=admin)
    assert r.status_code == 200
    raw = json.loads(db.one(select(settings_t.c.v).where(settings_t.c.k == "system"))["v"])
    assert raw["llm_api_key"].startswith("enc:") and "abcdef" not in raw["llm_api_key"]
    vals = client.get("/api/system/settings", headers=admin).json()["values"]
    assert vals["llm_model"] == "qwen-max" and "abcdef" not in vals["llm_api_key"] and "•" in vals["llm_api_key"]
    client.put("/api/system/settings", json={"llm_api_key": vals["llm_api_key"]}, headers=admin)   # 回传打码串 = 不改
    settings.invalidate()
    assert settings.get().llm_api_key == "sk-abcdef123456"


def test_edge_monitor_timeouts_configurable(client, admin):
    """无进度告警秒数、告警重复提醒间隔从写死改为系统设置里可配(带范围校验)。"""
    vals = client.get("/api/system/settings", headers=admin).json()["values"]
    assert vals["edge_no_progress_after"] == 180 and vals["alert_renotify_minutes"] == 30
    r = client.put("/api/system/settings", json={"edge_no_progress_after": 240, "alert_renotify_minutes": 10},
                   headers=admin)
    assert r.status_code == 200
    settings.invalidate()
    assert settings.get().edge_no_progress_after == 240 and settings.get().alert_renotify_minutes == 10
    bad = client.put("/api/system/settings", json={"edge_no_progress_after": 5}, headers=admin)
    assert bad.status_code in (400, 422)


def test_dms_account_pushed_to_edge(client, admin, kit):
    row = db.one(select(store_dms_t).where(store_dms_t.c.store_id == kit.store_id))
    assert row["password_enc"].startswith("enc:") and "dms-pass-1" not in row["password_enc"]
    cfg = client.get("/api/edge/v1/config", headers=kit.eh).json()
    assert cfg["store"]["code"] == "STORE-001"
    acc = cfg["dms"][0]
    assert (acc["dms"], acc["username"], acc["password"]) == ("gtmc", "dms_user", "dms-pass-1")
    assert acc["options"]["iam_base"].startswith("https://iam.gtmc.com.cn")
    assert cfg["runtime"]["login_min_interval"] == 60
    v1 = cfg["version"]
    assert kit.heartbeat()["config_version"] == v1
    # 后台改账号(密码留空 = 不改)→ 版本号 +1,取数端拉到新账号、旧密码
    r = client.put("/api/client/dms/gtmc", json={"username": "dms_user2", "password": "",
                                                 "options": {"verify_ssl": True}}, headers=admin)
    assert r.status_code == 200
    assert kit.heartbeat()["config_version"] == v1 + 1
    acc = client.get("/api/edge/v1/config", headers=kit.eh).json()["dms"][0]
    assert (acc["username"], acc["password"], acc["options"]["verify_ssl"]) == ("dms_user2", "dms-pass-1", True)
    ov = client.get("/api/client/overview", headers=admin).json()
    g = next(a for a in ov["dms"] if a["dms"] == "gtmc")
    assert g["password_set"] and "dms-pass-1" not in json.dumps(ov)
    # 运行参数(所有门店共用)→ 版本号再 +1
    assert client.put("/api/client/runtime", json={"page_timeout": 60, "strategies": ["token"]},
                      headers=admin).status_code == 200
    cfg = client.get("/api/edge/v1/config", headers=kit.eh).json()
    assert cfg["version"] == v1 + 2 and cfg["runtime"]["page_timeout"] == 60 and cfg["runtime"]["strategies"] == ["token"]
    assert client.put("/api/client/runtime", json={"strategies": ["bogus"]}, headers=admin).status_code == 400


def test_edge_auth_and_task_lifecycle(client, admin, kit, caplog):
    assert client.get("/api/edge/v1/config", headers={"X-Edge-Token": "edg_bad"}).status_code == 401
    kit.heartbeat()
    r = client.post(f"/api/client/devices/{kit.device_id}/check", headers=admin)
    assert r.status_code == 200
    t = client.get("/api/edge/v1/tasks/next?wait=1", headers=kit.eh).json()["task"]
    assert t["type"] == "sys.check" and t["params"]["dms"] == "gtmc" and t["params"]["store"]["code"] == "STORE-001"
    assert client.post(f"/api/edge/v1/tasks/{t['id']}/progress", json={"step": "login", "status": "start", "timeout": 90},
                       headers=kit.eh).status_code == 200
    client.post(f"/api/edge/v1/tasks/{t['id']}/progress", json={"step": "login", "status": "ok"}, headers=kit.eh)
    png = b"\x89PNG\r\n\x1a\n" + b"0" * 32
    f = client.post(f"/api/edge/v1/tasks/{t['id']}/file?name=po_list.png&kind=screenshot", content=png,
                    headers=kit.eh).json()
    assert client.post(f"/api/edge/v1/tasks/{t['id']}/result", json={"ok": True, "result": {"ok": True}},
                       headers=kit.eh).status_code == 200
    det = client.get(f"/api/client/tasks/{t['id']}", headers=admin).json()
    assert det["task"]["status"] == "done" and det["steps"][0]["status"] == "ok"
    assert det["evidence"][0]["id"] == f["id"]
    assert client.get(f"/api/evidence/{f['id']}", headers=admin).content == png
    # 证据下载计量:每次下载记一行(字节数 / 状态),排查浏览器「下载失败」用
    caplog.clear()
    with caplog.at_level("INFO", logger="server.download"):
        assert client.get(f"/api/evidence/{f['id']}?download=1", headers=admin).status_code == 200
        assert client.get("/api/evidence/999999", headers=admin).status_code == 404
    msgs = [r.getMessage() for r in caplog.records if r.name == "server.download"]
    assert any("po_list.png" in m and f"完成 HTTP 200,{len(png)}/{len(png)} 字节" in m for m in msgs), msgs
    assert any("HTTP 404" in m for m in msgs), msgs
    # 停用设备后拒绝连接
    client.post(f"/api/client/devices/{kit.device_id}/status", json={"status": "disabled"}, headers=admin)
    assert client.post("/api/edge/v1/heartbeat", json={}, headers=kit.eh).status_code == 403


def test_ui_strategy_diag_logs_and_confirm_extension(client, admin, kit):
    # 截图登录方式:默认 ui 在最前;可以调整顺序 / 停用某种(只发启用的、按顺序)
    assert client.get("/api/client/runtime", headers=admin).json()["defaults"]["strategies"] == ["ui", "token", "sso"]
    assert client.put("/api/client/runtime", json={"strategies": ["sso", "UI", "sso"], "ui_confirm_timeout": 300},
                      headers=admin).status_code == 200
    rt = client.get("/api/edge/v1/config", headers=kit.eh).json()["runtime"]
    assert rt["strategies"] == ["sso", "ui"] and rt["ui_confirm"] is True and rt["ui_confirm_timeout"] == 300
    assert rt["browser_relay"] is True and rt["upload_audit"] == "on_failure"
    # 收集诊断:下发 sys.collect_diag,参数夹在范围内
    kit.heartbeat()
    assert client.post(f"/api/client/devices/{kit.device_id}/collect-diag", json={"days": 99, "rounds": 3}, headers=admin).status_code == 200
    t = client.get("/api/edge/v1/tasks/next?wait=1", headers=kit.eh).json()["task"]
    assert t["type"] == "sys.collect_diag" and t["params"]["days"] == 30 and t["params"]["rounds"] == 3
    # 等人工确认:confirm 步骤的超时累加到任务超时上(不算任务超时)
    before = edge.task(t["id"])["timeout_s"]
    client.post(f"/api/edge/v1/tasks/{t['id']}/progress", json={"step": "confirm", "status": "start", "timeout": 180},
                headers=kit.eh)
    assert edge.task(t["id"])["timeout_s"] == before + 180
    assert edge._extend.get(t["id"]) == 180
    # 日志:时间正序(旧的在前);按任务过滤;after_id 增量从最早的开始、不跳行;before_id 加载更早
    lines = [{"seq": 1000 + i, "ts": "2026-10-29 10:00:0%d" % i, "level": "INFO", "logger": "edge",
              "task_id": t["id"] if i % 2 else None, "msg": "line %d" % i} for i in range(4)]
    assert client.post("/api/edge/v1/logs", json={"lines": lines}, headers=kit.eh).status_code == 200
    all_ = client.get("/api/client/logs?limit=10", headers=admin).json()
    assert [x["msg"] for x in all_][-4:] == ["line 0", "line 1", "line 2", "line 3"]
    mine = client.get(f"/api/client/logs?task_id={t['id']}", headers=admin).json()
    assert [x["msg"] for x in mine] == ["line 1", "line 3"]
    base = all_[-4]["id"]
    newer = client.get(f"/api/client/logs?after_id={base}&limit=2", headers=admin).json()
    assert [x["msg"] for x in newer] == ["line 1", "line 2"]          # 超过 limit 时给最早的那几条,前端接着翻
    older = client.get(f"/api/client/logs?before_id={all_[-1]['id']}&limit=2", headers=admin).json()
    assert [x["msg"] for x in older] == ["line 1", "line 2"]


def test_cli_set_dms(kit, monkeypatch, capsys):
    import io
    from app import cli
    monkeypatch.setattr("sys.stdin", io.StringIO("cli-pass-9\n"))
    assert cli.main(["set-dms", "gtmc", "44BH0_cli", "--store", str(kit.store_id)]) == 0
    row = db.one(select(store_dms_t).where(store_dms_t.c.store_id == kit.store_id))
    assert row["username"] == "44BH0_cli" and "cli-pass-9" not in row["password_enc"]
    from app.services import dms
    assert dms.for_edge(kit.store_id)[0]["password"] == "cli-pass-9"
    assert "44BH0_cli" in capsys.readouterr().out


def test_dms_login_rejected_alert(client, admin, kit, outbox):
    fake_now(hh=10)
    kit.heartbeat(dms_login={"gtmc": {"state": "rejected", "username": "dms_user", "error": "用户名或密码错误"}})
    al = [a for a in alerts.listing(kit.store_id, "open", size=200)["rows"] if a["kind"] == "edge.dms_login_rejected"]
    assert al and al[0]["severity"] == "critical"
    assert any("暂停登录" in m for m in outbox.to(kit.group))
    kit.heartbeat(dms_login={"gtmc": {"state": "ok", "username": "dms_user"}})
    assert not [a for a in alerts.listing(kit.store_id, "open", size=200)["rows"] if a["kind"] == "edge.dms_login_rejected"]


# ====================================================================== 企业微信
def test_wecom_targets_routing(client, admin, kit, outbox):
    bot2 = client.post("/api/wecom/bots", json={"name": "告警机器人", "bot_id": "bot-2"}, headers=admin).json()["id"]
    assert client.post("/api/wecom/bots", json={"name": "重复", "bot_id": "bot-2"}, headers=admin).status_code == 400
    r = client.post("/api/wecom/targets", json={"name": "运维张工", "bot_ref": bot2, "kind": "single",
                                                "contact_id": "u-ops", "purposes": ["alert"], "alert_min": "error"},
                    headers=admin)
    assert r.status_code == 200
    assert client.post("/api/wecom/targets", json={"name": "x", "bot_ref": bot2, "contact_id": "c", "purposes": []},
                       headers=admin).status_code == 400
    # 告警:warn 只到群(群的阈值是 warn),error 群和运维都收到
    kit.call(alerts.open_alert, kit.store_id, "test.warn", "k1", "warn", "注意级告警", "x")
    kit.call(alerts.open_alert, kit.store_id, "test.err", "k2", "error", "异常级告警", "y")
    assert len(outbox.to("u-ops")) == 1 and "异常级告警" in outbox.to("u-ops")[0]
    assert len(outbox.to(kit.group)) == 2
    assert next(m for m in outbox.texts if m["to"] == "u-ops")["bot"] == "bot-2"
    # 补货对话只发给 chat 用途的对象
    assert [t["contact_id"] for t in im.chat_targets(kit.store_id)] == [kit.group]
    # 测试发送 + 收发记录
    assert client.post(f"/api/wecom/targets/{kit.target_id}/test", headers=admin).json()["ok"]
    logs = client.get("/api/wecom/logs", headers=admin).json()["rows"]
    assert logs[0]["event"] == "test" and logs[0]["target_name"] == "配件计划群"
    # 机器人还在被使用时不能删
    assert client.delete(f"/api/wecom/bots/{bot2}", headers=admin).status_code == 409


def test_wecom_contacts_picker(client, admin, kit, monkeypatch):
    """从网关通讯录选群 / 选人:只开放四种类型;不选类型时四种首尾相接分页;标出已配置的对象。"""
    from app.services import imhub
    data = {"ww_group_external": [{"contact_id": kit.group, "contact_name": "配件计划群", "owner": "张三", "member_count": 7},
                                  {"contact_id": "R:2", "contact_name": "外部群2"}],
            "ww_group_internal": [{"contact_id": "R:3", "contact_name": "内部群"}],
            "ww_colleague": [{"contact_id": "1688", "contact_name": "李四"}],
            "ww_customer": [{"contact_id": "7881", "contact_name": "王五"}]}
    calls = []

    def fake(bot, ctype, name="", limit=20, offset=0):
        calls.append((bot["bot_id"], ctype, name, limit, offset))
        rows = [c for c in data[ctype] if name in c["contact_name"]]
        return {"contacts": rows[offset:offset + limit], "total": len(rows)}, ""
    monkeypatch.setattr(imhub, "fetch_contacts", fake)
    bot_ref = kit.target()["bot_ref"]
    ov = client.get("/api/wecom/overview", headers=admin).json()
    assert set(ov["contact_types"]) == {"ww_group_external", "ww_group_internal", "ww_colleague", "ww_customer"}
    # 指定类型 + 名称;已配置的群标出接收对象名称,类型映射成 group
    r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&type=ww_group_external&keyword=配件", headers=admin).json()
    assert r["total"] == 1 and r["rows"][0]["kind"] == "group" and r["rows"][0]["configured"] == "配件计划群"
    assert calls[-1][1:3] == ("ww_group_external", "配件")
    # 不选类型:第 2 页(每页 2 条)跨过外部群,拿到内部群 + 同事,总数是四种之和
    r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&page=2&size=2", headers=admin).json()
    assert r["total"] == 5 and [x["contact_id"] for x in r["rows"]] == ["R:3", "1688"]
    assert [x["kind"] for x in r["rows"]] == ["group", "single"] and r["rows"][1]["type_text"] == "企微同事"
    # 白名单外的类型、未知机器人都拒绝
    assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&type=group_member", headers=admin).status_code == 400
    assert client.get("/api/wecom/contacts?bot_ref=99999", headers=admin).status_code == 400
    monkeypatch.setattr(imhub, "fetch_contacts", lambda *a, **k: (None, "网关不可达:x"))
    assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}", headers=admin).status_code == 502


# ====================================================================== 助手设置 / 提示词 / 试聊
def test_assistant_settings_prompt(client, admin, kit):
    """后台能改的只有提示词:保存 / 预览 / 恢复默认;话术只用代码版本,库里旧的覆盖行不再生效。"""
    from app.models import texts_t
    r = client.get("/api/assistant/settings", headers=admin).json()
    assert not r["prompt"]["changed"] and "【判断原则】" in r["prompt"]["content"]
    assert "single_restock" not in r["prompt"]["content"]              # 各技能的流程说明在技能的提示词片段里
    assert "targets" not in r and "max_iters" not in r["values"]        # 群里 @ 的昵称只在「消息通道 → 接收对象」里配
    body = {"values": {"name": "小配", "free_reply": True}, "prompt": "你是{{ persona.name }},测试提示词"}
    r = client.put("/api/assistant/settings", json=body, headers=admin).json()
    assert r["prompt"]["changed"] and r["values"]["name"] == "小配" and r["prompt"]["updated_by"]
    p = agent.system_prompt(kit.store_id)
    assert p.startswith("你是小配,测试提示词") and "【可用工具】" in p and "single_restock" in p
    assert "【单次补货】" in p and "【定时补货】" in p and "scheduled_status" in p   # 技能片段 + 工具清单自动拼上
    assert client.put("/api/assistant/settings", json={"prompt": "{% if %}"}, headers=admin).status_code == 400
    pv = client.post("/api/assistant/prompt/preview", json={"content": "预览{{ persona.name }}"}, headers=admin).json()
    assert pv["ok"] and pv["system"].startswith("预览小配") and "【当前状态】" in pv["context"]
    r = client.put("/api/assistant/settings", json={"prompt": ""}, headers=admin).json()      # 清空 = 恢复默认
    assert not r["prompt"]["changed"] and agent.system_prompt(kit.store_id).startswith("你是")
    # 旧版本在库里存过的话术覆盖不再读取(避免旧话术盖住新版本)
    db.q(texts_t.insert().values(key="restock.msg_no_run", content="旧话术", updated_by="x", updated_at=db.now()))
    assert "旧话术" not in texts.render("restock.msg_no_run", push_time="15:00")


def test_rehearse_flow(client, admin, kit, outbox):
    """试聊走和企微一样的流程(大模型选工具;测试里是假大模型);沙盒工具按真实话术回复,不发企微、不下发任务。"""
    client.put("/api/assistant/settings", json={"values": {"name": "小配"}}, headers=admin)

    def say_(text):
        return client.post("/api/assistant/rehearse", json={"text": text, "session": "t1"}, headers=admin).json()
    out = say_("订")
    assert out["mode"] == "llm" and out["calls"][0]["tool"] == "confirm_order"
    assert "没有待确认的单次补货" in out["messages"][0]["text"]
    out = say_("帮我查一下库存补货信息")
    assert out["mode"] == "llm" and out["calls"][0]["tool"] == "scheduled_link"
    assert "不能在群里发起" in out["messages"][0]["text"]
    out = say_("帮我定:8713902280*2")
    assert out["mode"] == "llm" and out["calls"][0]["args"] == {"part_no": "8713902280", "qty": 2}
    box = out["sandbox"][0]
    assert box["status"] == "awaiting_confirm" and box["lines"][0]["part_no"] == "8713902280"
    assert any("回「订」建单" in m["text"] for m in out["messages"])
    out = say_("定")
    assert out["calls"][0]["tool"] == "confirm_order" and out["sandbox"][0]["status"] == "awaiting_submit"
    assert any("SANDBOX-PO-" in m["text"] and "回「确认提交」" in m["text"] for m in out["messages"])
    out = say_("好的")                                                # 待确认提交时口语确认:不提交
    assert out["calls"][0]["tool"] == "confirm_order" and out["sandbox"][0]["status"] == "awaiting_submit"
    out = say_("可以,提交吧")                                        # 不是「提交 / 确认提交」:不提交
    assert out["calls"][0]["tool"] == "submit_order" and out["sandbox"][0]["status"] == "awaiting_submit"
    assert "只有回「确认提交」才会提交" in out["messages"][0]["text"]
    out = say_("确认提交")
    assert out["sandbox"][0]["status"] == "done" and any(m["text"].startswith("已提交 ✅") for m in out["messages"])
    assert outbox.texts == [] and not edge.tasks(kit.store_id, 10, type_prefix="restock.")
    assert client.delete("/api/assistant/rehearse/t1", headers=admin).status_code == 200
    out = say_("你好")
    assert out["result"] == "refused" and "小配" in out["messages"][0]["text"] and out["sandbox"] == []
    assert agent.persona()["name"] == "小配"


def test_group_at_gating(client, admin, kit, monkeypatch):
    """群聊一律必须 @ 机器人:没 @ 到机器人昵称不处理(但照样记进消息记录);@ 了就处理,且 @昵称 不交给智能体。"""
    assert im.strip_at_bot("@补货助手 \u2005帮我查补货", "补货助手") == "帮我查补货"
    assert im.strip_at_bot("帮我查补货", "补货助手") is None
    assert im.strip_at_bot("@补货助手", "补货助手") == ""
    assert im.strip_at_bot("@小补 确认", "补货助手,小补") == "确认"          # 多个别名
    # 群聊用于补货对话却没填昵称:保存被拒(否则群里永远没有回复)
    body = {"name": "g2", "bot_ref": kit.target()["bot_ref"], "kind": "group", "contact_id": "group-2",
            "purposes": ["chat"]}
    r = client.post("/api/wecom/targets", json=body, headers=admin)
    assert r.status_code == 400 and "昵称" in r.json()["detail"]
    r = client.post("/api/wecom/targets", json=body | {"bot_names": "补货助手"}, headers=admin)
    assert r.status_code == 200
    t = im.target(r.json()["id"])
    assert t["bot_names"] == "补货助手" and "require_at" not in t       # 字段已删除:群聊一律必须 @
    # 单聊 / 只做告警的群,不需要昵称
    r = client.post("/api/wecom/targets", json=body | {"contact_id": "u1", "kind": "single"}, headers=admin)
    assert r.status_code == 200
    r = client.post("/api/wecom/targets", json=body | {"contact_id": "g-alert", "purposes": ["alert"]}, headers=admin)
    assert r.status_code == 200

    import datetime as dt
    now = dt.datetime.now()
    seen: list[str] = []
    p = im.Poller(None, None)
    monkeypatch.setattr(p, "dispatch", lambda t_, sid, sname, text, msg_id="": seen.append(text))

    def msg(i, text):
        return {"msg_id": f"m{i}", "sender_type": 0, "sender_id": "u9", "sender": "张三", "text": text,
                "msg_type": "text", "msg_time": now.isoformat()}

    batches = iter([[msg(1, "历史消息")], [msg(2, "大家好"), msg(3, "@补货助手 \u2005帮我查补货"), msg(4, "@补货助手")]])
    monkeypatch.setattr(im.imhub, "fetch_msgs", lambda bot, contact, start, end: next(batches))
    assert p.poll_one(t) == 0                        # 首次接入:历史消息标为已读
    assert p.poll_one(t) == 1 and seen == ["帮我查补货"]
    # 没 @ 的、只 @ 没内容的:不处理,但都记进消息记录(防止事后扯皮)
    from app.models import notify_logs_t
    ign = db.rows(select(notify_logs_t).where(notify_logs_t.c.event == "chat_ignored").order_by(notify_logs_t.c.id))
    assert [(x["content"], x["error"], x["msg_id"]) for x in ign] == [("大家好", "未@机器人", "m2"),
                                                                      ("@补货助手", "只@了机器人没有内容", "m4")]
    # 老数据里没填昵称的群(以前没开 @):消息全部忽略、记录原因,并告警一次
    db.q(im_targets_t.update().where(im_targets_t.c.id == t["id"]).values(bot_names=None))
    t = im.target(t["id"])
    loop = asyncio.new_event_loop()
    p.loop = loop
    batches = iter([[msg(5, "订")]])
    assert p.poll_one(t) == 0 and seen == ["帮我查补货"]
    loop.run_until_complete(asyncio.sleep(0.2))
    loop.close()
    last = db.rows(select(notify_logs_t).where(notify_logs_t.c.event == "chat_ignored").order_by(notify_logs_t.c.id.desc()))[0]
    assert (last["content"], last["error"]) == ("订", "没填机器人昵称")
    assert t["id"] in p._warned_no_names
    assert alerts._find_open(kit.store_id, "im.bot_names_missing", f"target:{t['id']}")


def test_delete_device_and_log_date_filter(client, admin, kit):
    # 在线的设备不让删;停用后可以删,历史日志保留
    kit.heartbeat()
    r = client.delete(f"/api/client/devices/{kit.device_id}", headers=admin)
    assert r.status_code == 409 and "停用" in r.json()["detail"]
    kit.c.post(f"/api/edge/v1/logs", json={"lines": [
        {"seq": 1, "ts": "2026-10-20 10:00:00", "level": "INFO", "msg": "老日志"},
        {"seq": 2, "ts": "2026-10-22 10:00:00", "level": "INFO", "msg": "新日志"}]}, headers=kit.eh)
    allm = [x["msg"] for x in client.get("/api/client/logs", headers=admin).json()]
    assert allm == ["老日志", "新日志"]
    only = client.get("/api/client/logs?since=2026-10-22&until=2026-10-22", headers=admin).json()
    assert [x["msg"] for x in only] == ["新日志"]
    assert [x["msg"] for x in client.get("/api/client/logs?until=2026-10-21", headers=admin).json()] == ["老日志"]
    assert client.post(f"/api/client/devices/{kit.device_id}/status", json={"status": "disabled"}, headers=admin).status_code == 200
    assert client.delete(f"/api/client/devices/{kit.device_id}", headers=admin).status_code == 200
    assert all(d["id"] != kit.device_id for d in client.get("/api/client/overview", headers=admin).json()["devices"])
    assert client.delete(f"/api/client/devices/{kit.device_id}", headers=admin).status_code == 404


def test_edge_wait_timeout_counts_from_claim(client, kit):
    """取数端排队时间不算执行时间:领取后重新按 timeout 计,刚领取的任务不会被误判为「结果未知」;
    一直没人领取 = 过期(确定没执行)。"""
    from app.core import clock
    from app.core.types import EdgeTimeout
    from app.models import tasks_t
    kit.heartbeat()

    async def go():
        tid = edge.submit(kit.store_id, "sys.ping", {}, timeout=4)
        w = asyncio.create_task(edge.wait(tid, 4))
        await asyncio.sleep(3.0)                                    # 排队 3 秒才被领取
        db.q(tasks_t.update().where(tasks_t.c.id == tid).values(status="dispatched", dispatched_at=clock.now()))
        edge._wakeups[tid].set()
        await asyncio.sleep(1.5)                                    # 从下发算已 4.5 秒(超过 4 秒),从领取算才 1.5 秒
        alive = not w.done()
        db.q(tasks_t.update().where(tasks_t.c.id == tid).values(status="done", result="{}", finished_at=clock.now()))
        edge._wakeups[tid].set()
        row = await asyncio.wait_for(w, 5)
        tid2 = edge.submit(kit.store_id, "sys.ping", {}, timeout=1)
        try:
            await edge.wait(tid2, 1)
            expired = None
        except EdgeTimeout as e:
            expired = (e.unknown, edge.task(tid2)["status"])
        return alive, row["status"], expired
    alive, status, expired = kit.call(go)
    assert alive and status == "done"
    assert expired == (False, "expired")


def test_selfcheck_schema_and_stale_texts(client, kit, capsys):
    """部署自检:迁移版本到最新;后台改过的话术里有「只认发起人」之类的旧说法、库里有已废弃的话术键,都列出来。"""
    from app import cli
    from app.models import texts_t
    cur, head = cli.schema_version()
    assert cur == head == "0002_llm_model_qwen37"
    db.q(texts_t.insert().values(key="restock.msg_po_done", content="👉 没问题请 {{ owner }} @我 回「确认提交」",
                                 updated_by="test", updated_at=db.now()))
    db.q(texts_t.insert().values(key="restock.msg_confirm_not_owner", content="只有发起人本人能确认",
                                 updated_by="test", updated_at=db.now()))
    texts._cache.clear()
    old, gone = cli.stale_texts()
    assert old == ["restock.msg_po_done"] and gone == ["restock.msg_confirm_not_owner"]
    cli.selfcheck()
    out = capsys.readouterr().out
    assert "restock.msg_po_done" in out and "旧说法" in out and "restock.msg_confirm_not_owner" in out
    assert "数据库迁移版本" not in out


def test_migrate_syncs_schema_with_models(client, monkeypatch):
    """部署升级:库是旧结构(多了旧字段 / 旧表、少了字段 / 表 / 索引、注释旧),迁移版本记的是已删除的迁移文件
    → 启动迁移后表结构和代码完全一致;不是 atrs_ 开头的表不动;DB_SYNC_DROP=false 时只加不删。"""
    from sqlalchemy import text

    from app import cli
    with db.engine().begin() as c:
        c.execute(text("ALTER TABLE atrs_restock_plan ADD COLUMN said_time VARCHAR(20) NULL COMMENT '旧字段'"))
        c.execute(text("CREATE TABLE atrs_restock_part_query (id INT PRIMARY KEY) COMMENT '旧表'"))
        c.execute(text("ALTER TABLE atrs_im_target DROP COLUMN contact_name"))
        c.execute(text("DROP INDEX ix_atrs_restock_plan_trigger_target_id ON atrs_restock_plan"))
        c.execute(text("DROP TABLE atrs_ai_prompt"))
        c.execute(text("ALTER TABLE atrs_restock_plan MODIFY COLUMN next_retry_at DATETIME NULL COMMENT '旧注释'"))
        c.execute(text("CREATE TABLE zz_other_keep (id INT PRIMARY KEY)"))
        c.execute(text(f"UPDATE `{db.VERSION_TABLE}` SET version_num = '0002_device_token_enc'"))
    try:
        before = set(db.schema_diff())
        assert {"删字段 atrs_restock_plan.said_time", "删表 atrs_restock_part_query", "建表 atrs_ai_prompt",
                "加字段 atrs_im_target.contact_name", "改字段 atrs_restock_plan.next_retry_at(注释)",
                "建索引 atrs_restock_plan.ix_atrs_restock_plan_trigger_target_id"} <= before
        assert not any("zz_other_keep" in d for d in before)

        monkeypatch.setenv("DB_SYNC_DROP", "false")             # 只加不删
        db.migrate()
        assert set(db.schema_diff()) == {"删字段 atrs_restock_plan.said_time", "删表 atrs_restock_part_query"}
        assert cli.schema_version() == ("0002_llm_model_qwen37", "0002_llm_model_qwen37")

        monkeypatch.delenv("DB_SYNC_DROP")
        db.migrate()
        assert db.schema_diff() == []
        insp = inspect(db.engine())
        assert "zz_other_keep" in insp.get_table_names()
        assert {c["name"]: c["comment"] for c in insp.get_columns("atrs_restock_plan")}["next_retry_at"] != "旧注释"
        db.migrate()                                            # 重复执行不出错
    finally:
        with db.engine().begin() as c:
            c.execute(text("DROP TABLE IF EXISTS zz_other_keep"))


# ====================================================================== 告警:分状态 / 大类筛选、一键处理、恢复通知
def test_alert_filters_and_bulk_resolve(client, admin, kit, outbox):
    t0 = fake_now(m=11, d=6, hh=9, mm=2)
    kit.call(alerts.open_alert, kit.store_id, "edge.outdated", "a1", "warn", "取数端版本过旧", "x")
    kit.call(alerts.open_alert, kit.store_id, "restock.po_failed", "a2", "error", "创建采购单失败", "y")
    kit.call(alerts.open_alert, kit.store_id, "restock.scan_failed", "a3", "critical", "补货取数失败", "z")
    kit.call(alerts.open_alert, kit.store_id, "edge.clock_skew", "a4", "warn", "取数端电脑时间不准", "w")
    # 跨天恢复:通知写起止时间 + 「天 小时」,不写「94 小时」
    clock.set_fake(t0 + dt.timedelta(hours=94, minutes=6))
    kit.call(alerts.resolve_alert, kit.store_id, "edge.clock_skew", "a4", "时间已校准")
    msg = outbox.to(kit.group)[-1]
    assert "11-06 09:02 至 11-10 07:08" in msg and "3 天 22 小时" in msg and "94 小时" not in msg

    get = lambda q: client.get(f"/api/alerts?{q}", headers=admin).json()   # noqa: E731
    r = get("status=open")
    assert r["counts"] == {"open": 3, "recovered": 1, "closed": 0, "all": 4} and r["groups"]["edge"] == "取数端"
    assert {x["kind"] for x in get("status=open&group=restock")["rows"]} == {"restock.po_failed", "restock.scan_failed"}
    assert [x["kind"] for x in get("status=open&severity=error,critical&group=restock&keyword=取数")["rows"]] == ["restock.scan_failed"]
    # 勾选关闭:只关这一条
    one = get("status=open&group=edge")["rows"][0]
    assert client.post("/api/alerts/resolve-all", json={"ids": [one["id"]]}, headers=admin).json()["count"] == 1
    # 一键处理:按当前筛选关掉剩下的
    assert client.post("/api/alerts/resolve-all", json={"group": "restock", "note": "已确认"}, headers=admin).json()["count"] == 2
    r = get("status=closed")
    assert r["counts"]["open"] == 0 and r["counts"]["closed"] == 3 and all(x["manual"] for x in r["rows"])
    assert "一键处理" in r["rows"][0]["resolved_note"]
    assert [x["kind"] for x in get("status=recovered")["rows"]] == ["edge.clock_skew"]
    assert get("status=resolved")["total"] == 4                         # 旧链接:已恢复 = 自动 + 人工
    assert client.post("/api/alerts/resolve-all", json={}, headers=admin).json()["count"] == 0


def test_msg_log_extra_filters(client, admin, kit):
    im.log_msg(kit.store_id, "out", "alert", "配件计划群", kit.group, "紧急:补货取数失败", ok=False, err="网关超时",
               severity="critical")
    im.log_msg(kit.store_id, "out", "alert", "ops@x.com", "ops@x.com", "异常告警邮件", kind="email", severity="error")
    im.log_msg(kit.store_id, "out", "chat", "配件计划群", kit.group, "今日补货清单", ref="restock:run:999999")
    get = lambda q: client.get(f"/api/wecom/logs?{q}", headers=admin).json()["rows"]   # noqa: E731
    assert [x["content"] for x in get("result=failed")] == ["紧急:补货取数失败"]
    assert [x["content"] for x in get("channel=email")] == ["异常告警邮件"]
    assert {x["content"] for x in get("severity=error,critical")} == {"紧急:补货取数失败", "异常告警邮件"}
    assert get("doc_no=不存在的单号") == []
    assert client.get("/api/wecom/logs?channel=xx", headers=admin).status_code == 400


def test_edit_single_target_with_null_fields(client, admin, kit):
    """单人对象库里 at_ids / bot_names 是 NULL,编辑时原样提交回来也要能保存(以前报 Input should be a valid string)。"""
    bot_ref = client.get("/api/wecom/overview", headers=admin).json()["targets"][0]["bot_ref"]
    r = client.post("/api/wecom/targets", json={"name": "张工", "bot_ref": bot_ref, "kind": "single", "contact_id": "u-zg",
                                                "purposes": ["chat"]}, headers=admin)
    tid = r.json()["id"]
    t = next(x for x in client.get("/api/wecom/overview", headers=admin).json()["targets"] if x["id"] == tid)
    assert t["at_ids"] is None and t["bot_names"] is None
    body = {k: t[k] for k in ("name", "bot_ref", "kind", "contact_id", "contact_name", "at_ids", "bot_names", "purposes",
                              "alert_min", "enabled")} | {"name": "张工2"}
    r = client.put(f"/api/wecom/targets/{tid}", json=body, headers=admin)
    assert r.status_code == 200, r.text