test_restock_flow.py 118 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 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
"""库存补货全流程(取数端打桩,按任务类型返回结果):

定时补货(出库驱动):15:00 定时 / 后台按钮触发、出库 → 分组(在库分类表 ∪ 近 N 月 SO 单)→ 默认期望(推荐 / 上次)、
页面确认(有效期由服务端校验)、刷新整条链路重跑并保留人工修改、群里不能发起 / 确认、建单 + 截图(含兜底)→
单据页「确认提交」/「先不提交」、失败重试、提醒、紧急告警、截单收口、预检、审计(快照 / 出库明细 / 时间线);
单次补货:会话里「零件号 数量」→ 查询 → 回「订」→ 建单截图 → 回「确认提交」提交(一个会话 = 一个用户,谁回都行;
每个会话同时一张,各会话互不影响;建单结果未知 → 建单异常,自动核实),不影响当天定时补货;
分类表维护、每周 SO 同步、调度器。"""
from __future__ import annotations

import asyncio
import datetime as dt
from urllib.parse import urlsplit

import pytest
from sqlalchemy import select

from app import features
from app.core import clock, db
from app.core.types import Actor, EdgeError, EdgeTimeout
from app.features.restock import service as restock_service
from app.models import (ai_traces_t, alerts_t, api_calls_t, notify_logs_t, outbound_rows_t, po_t, runs_t,
                        schedule_marks_t, snapshots_t, so_orders_t, so_parts_t, so_syncs_t)
from app.services import audit, edge, stores
from app.services.agent import assistant
from app.services.scheduler import scheduler
from tests.conftest import StoreKit, fake_now

PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
# 出库明细(取数端已按零件汇总的纯牌净出库):机油、机滤在分类表里属常备分类;用户手册不在分类表、但近 3 个月 SO 里补过;
# 传感器固定件是钣喷件、银粉定色剂未分类 → 其他组;空调滤净出库 -1(退货冲销)→ 不进候选
PARTS = [
    {"part_no": "0888080463", "name": "0W20机油4L装", "qty": 5, "rows": 5},
    {"part_no": "90915YZZM3", "name": "机油滤清器滤芯", "qty": 18, "rows": 22},
    {"part_no": "019990A115", "name": "用户手册", "qty": 2, "rows": 2},
    {"part_no": "8934806270", "name": "后车角超声波传感器固", "qty": 3, "rows": 1},
    {"part_no": "GPDL0WM001", "name": "银粉定色剂", "qty": 28, "rows": 2},
    {"part_no": "8713906140", "name": "空调滤清器滤芯分总成", "qty": -1, "rows": 1},
]
FACTS = {
    "0888080463": {"stock": 8, "trans_shipped": 0, "daily_surplus": 30, "unit_price": 338, "mad": 20.3},
    "90915YZZM3": {"stock": 12, "trans_shipped": 0, "daily_surplus": 25, "unit_price": 39, "mad": 18.7},
    "019990A115": {"stock": 0, "trans_shipped": 0, "daily_surplus": 4, "unit_price": 18.8, "mad": 4.0},
    "8934806270": {"stock": 2, "trans_shipped": 0, "daily_surplus": 5, "unit_price": 31, "mad": 11.0},
    "GPDL0WM001": {"stock": 485, "trans_shipped": 0, "daily_surplus": None, "unit_price": 460, "mad": 139.7},
    "8713902280": {"stock": 6, "trans_shipped": 2, "daily_surplus": 30, "unit_price": 53.3, "mad": 15.3},
}
ROWS = [{"id": f"r{i}", "shipmentDate": "2026-10-22 09:0%d:00" % i, "workOrderNo": "P44BH0008454",
         "shipmentBatchNo": f"44BH0{i}", "licensePlateNumber": "粤B-X739A", "mfr": "纯牌", "partNo": p["part_no"],
         "partName": p["name"], "settlStatus": "1", "reqQty": "%.6f" % p["qty"], "partUnitPrice": 10.0,
         "totalAmount": 10.0, "costPrice": 5.0, "totalCostPrice": 5.0} for i, p in enumerate(PARTS)]
ROWS.append(dict(ROWS[0], id="r9", mfr="非纯", partNo="ZCT001", partName="非纯养护品"))


class FakeEdge:
    def __init__(self) -> None:
        self.calls: list[str] = []
        self.by_store: list[tuple[int, str]] = []
        self.params: list[dict] = []
        self.timeouts: dict[str, float] = {}
        self.fail_scan = 0
        self.check_ok = True
        self.po_error: Exception | None = None
        self.shot_fallback = ""
        self.facts = {k: dict(v) for k, v in FACTS.items()}
        self.parts = PARTS
        self.so_details: dict | None = None
        self.submit_error: Exception | None = None
        self.submitted: list[str] = []
        self.found: list[dict] = []                  # restock.find_po 返回的命中单
        self.find_error: Exception | None = None
        self.po_state = "pending"                    # restock.po_status:pending / submitted / other / missing / error
        self.drafts: list[dict] = []                 # restock.list_drafts 返回的 DMS 待提交采购单
        self.drafts_error: Exception | None = None
        self.hang = False                            # True:出库明细一直不返回(模拟取数中,测强制终止)

    async def __call__(self, store_id, type, params, *, timeout, feature="", ref="", step_timeouts=None,
                       idempotency_key=None, dms_code=""):
        self.calls.append(type)
        self.by_store.append((store_id, type))
        self.params.append(dict(params, _dms=dms_code, _ref=ref))
        self.timeouts[type] = timeout
        if type == "restock.outbound":
            if self.hang:
                await asyncio.sleep(3600)
            assert step_timeouts and step_timeouts["login"] == 90 and step_timeouts["query_outbound"] == 300
            if self.fail_scan:
                self.fail_scan -= 1
                raise EdgeError("DMS 登录失败(模拟)")
            return {"ok": True, "message": "出库明细 7 行", "rows": ROWS, "parts": self.parts,
                    "stats": {"window_rows": 7, "pure_rows": 6, "mfr_counts": {"纯牌": 6, "非纯": 1}, "unknown_mfr": []},
                    "reconcile": {"ok": True}, "_task_id": "o" * 32}
        if type == "restock.quote":
            items = []
            for p in params["parts"]:
                f = self.facts.get(p["part_no"], {})
                items.append(dict(f, part_no=p["part_no"], name=p.get("name") or "示例", unreceived=0,
                                  national_queried=p["national"],
                                  warehouses={"GTMC广州": 0, "华南GTMC": 1095} if p["national"] else {}))
            return {"ok": True, "items": items, "_task_id": "q" * 32}
        if type == "restock.so_sync" and self.so_details is not None:
            heads = [{"orderNo": no, "createTime": "2026-10-%02d 09:00:00" % (i + 1), "orderStatus": "3",
                      "fp": "fp-" + no} for i, no in enumerate(sorted(self.so_details))]
            fetched = {no: v for no, v in self.so_details.items() if params["known"].get(no) != "fp-" + no}
            return {"ok": True, "message": "SO 同步完成", "orders": heads, "details": fetched, "parts": [],
                    "stats": {"orders": len(heads), "trusted": True, "fetched": len(fetched),
                              "reused": len(heads) - len(fetched)}, "_task_id": "s" * 32}
        if type == "restock.so_sync":
            return {"ok": True, "message": "SO 同步完成", "parts": [
                {"part_no": "019990A115", "name": "用户手册", "order_count": 3, "qty_sum": 9, "order_nos": ["S1", "S2", "S3"],
                 "last_order_no": "S3", "last_order_date": "2026-10-20 09:00:00"}],
                    "stats": {"orders": 3, "lines": 3, "trusted": False, "pages": 18}, "_task_id": "s" * 32}
        if type == "restock.create_po":
            if self.po_error:
                raise self.po_error
            return {"order_id": "9001", "order_no": "S2026102201", "_task_id": "t" * 32,
                    "row": {"supplierCode": "APC40", "orderType": "S", "itemNum": len(params["lines"]), "totalAmount": 80.0},
                    "details": [{"partNo": l["part_no"], "purchaseQty": l["qty"]} for l in params["lines"]], "mismatch": []}
        if type == "restock.screenshot_po":
            names = ("po_list_fallback.png", "po_detail_fallback.png") if self.shot_fallback else ("po_list.png", "po_detail.png")
            ids = [edge.save_evidence(store_id, None, n, PNG, "screenshot", "image/png")["id"] for n in names]
            out = {"evidence": ids, "fallback": self.shot_fallback or False}
            if self.shot_fallback:
                out.update(fallback_reason="浏览器登录超时", details=[{"partNo": "90915YZZM3", "purchaseQty": 18}])
            return out
        if type == "restock.submit_po":
            if self.submit_error:
                raise self.submit_error
            self.submitted.append(params["order_id"])
            return {"ok": True, "order_id": params["order_id"], "order_no": params["order_no"], "status": "已提交",
                    "already": False, "apply_operator": "邹新", "apply_time": "2026-10-22 15:23:01",
                    "total_amount": 106.6, "_task_id": "u" * 32, "evidence": [],
                    "details": [{"partNo": l["part_no"], "partName": "空调滤清器滤芯分总成" if l["part_no"] == "8713902280"
                                 else "零件" + l["part_no"][-3:], "purchaseQty": float(l["qty"]), "totalPrice": "53.3"}
                                for l in params["expect"]["lines"]]}
        if type == "restock.find_po":
            if self.find_error:
                raise self.find_error
            return {"ok": True, "found": self.found, "scanned": 7, "evidence": [], "_task_id": "f" * 32}
        if type == "restock.po_status":
            if self.po_state == "error":
                raise EdgeError("DMS 采购单列表查询失败(模拟)")
            status, cn = {"pending": ("1", "待提交"), "submitted": ("2", "已提交"), "other": ("4", "状态码 4"),
                          "missing": ("", "已删除")}[self.po_state]
            return {"ok": True, "exists": self.po_state != "missing", "status": status, "status_cn": cn,
                    "row": {"id": params["order_id"], "orderNo": params["order_no"], "orderStatus": status}
                    if self.po_state != "missing" else None, "message": cn, "evidence": [], "_task_id": "p" * 32}
        if type == "restock.list_drafts":
            if self.drafts_error:
                raise self.drafts_error
            return {"ok": True, "drafts": self.drafts, "scanned": len(self.drafts), "filter_trusted": True,
                    "truncated": False, "_task_id": "d" * 32}
        if type == "sys.check":
            return {"ok": self.check_ok, "steps": [{"step": "登录 DMS", "ok": self.check_ok, "detail": "x"}]}
        raise AssertionError(type)


@pytest.fixture()
def fake_edge(monkeypatch):
    f = FakeEdge()
    monkeypatch.setattr(edge, "run", f)
    return f


def setup_store(client, admin, so=True, **cfg) -> StoreKit:
    k = StoreKit(client, admin)
    if so:                                         # 近 3 个月 SO 单里补过用户手册
        db.q(so_parts_t.insert().values(store_id=k.store_id, part_no="019990A115", name="用户手册", order_count=3,
                                        qty_sum=9, order_nos=["S1"], last_order_no="S1", last_order_date="2026-10-01"))
    if cfg:
        assert client.put("/api/restock/config", json={"values": cfg}, headers=admin).status_code == 200
    return k


def say(k: StoreKit, text: str, sender="zhangsan") -> dict:
    return k.call(assistant.handle, k.target(), sender, "张三", text)


def settle(k: StoreKit) -> None:
    k.call(k.svc().drain)


def group_msgs(k, outbox):
    return outbox.to(k.group)


def open_alerts(k, kind=None):
    st = select(alerts_t).where(alerts_t.c.store_id == k.store_id, alerts_t.c.status == "open")
    if kind:
        st = st.where(alerts_t.c.kind == kind)
    return db.rows(st)


def push(k, hh=15, mm=0):
    t = fake_now(hh=hh, mm=mm)
    k.heartbeat()
    k.call(k.svc().push, k.store_id, t, "15:00")
    settle(k)
    return k.svc().current(k.store_id)


def page(client, token) -> dict:
    r = client.get(f"/api/public/restock/orders/{token}")
    assert r.status_code == 200, r.text
    return r.json()


def state_of(st: dict, **changes) -> list[dict]:
    """页面提交的整体状态:默认按页面当前值;changes = {part_no: {checked, expected}}(改了期望即 modified)。"""
    out = []
    for l in st["lines"]:
        c = changes.get(l["part_no"], {})
        out.append({"part_no": l["part_no"], "checked": c.get("checked", l["checked"]),
                    "expected": c.get("expected", l["expected"]), "modified": "expected" in c or l["modified"]})
    return out


def confirm(client, token, lines):
    return client.post(f"/api/public/restock/orders/{token}/confirm", json={"lines": lines})


def submit(client, token):
    return client.post(f"/api/public/restock/orders/{token}/submit")


# ====================================================================== 定时补货全流程
def test_scheduled_flow_end_to_end(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    assert run["kind"] == "scheduled" and run["trigger"] == "schedule" and run["status"] == "awaiting_confirm"
    assert (run["window_start"], run["window_end"]) == (dt.datetime(2026, 10, 21, 15), dt.datetime(2026, 10, 22, 15))
    ob = fake_edge.params[0]
    assert ob["window_start"] == "2026-10-21 15:00:00" and ob["window_end"] == "2026-10-22 15:00:00"
    assert ob["pure_label"] == "纯牌" and ob["_dms"] == "gtmc" and ob["_ref"] == f"restock:run:{run['id']}"
    # 分组:分类表常备分类 ∪ SO 单 → 常备件(查全国仓);其余不查全国仓;净出库 <= 0 的不进候选
    q = {p["part_no"]: p["national"] for p in fake_edge.params[1]["parts"]}
    assert q == {"0888080463": True, "90915YZZM3": True, "019990A115": True, "8934806270": False, "GPDL0WM001": False}
    msgs = group_msgs(k, outbox)
    assert msgs[0].startswith("⏰ 到点了,正在拉今天的出库明细")
    assert "请点开链接确认,不确认不会生成采购单" in msgs[1] and "/m/restock/order/" in msgs[1]
    assert "共 5 种纯牌零件,其中常备件 3 种" in msgs[1] and "· " not in msgs[1]       # 群里不列清单
    assert outbox.texts[-1]["at"] == ["zhangsan"]
    st = page(client, run["token"])
    lines = {l["part_no"]: l for l in st["lines"]}
    oil, filt, manual = lines["0888080463"], lines["90915YZZM3"], lines["019990A115"]
    assert (oil["grp"], oil["category"], oil["checked"], oil["default_source"]) == ("stock", "机油", True, "recommend")
    assert (oil["expected"], oil["final_qty"]) == (13, 5)                 # 推荐 = 库存 8 + 出库 5
    assert (filt["expected"], filt["final_qty"]) == (30, 18)
    assert manual["grp"] == "stock" and manual["so_hit"]["order_count"] == 3 and manual["final_qty"] == 2
    assert (lines["8934806270"]["grp"], lines["8934806270"]["checked"], lines["8934806270"]["tag"]) == ("other", False, "unchecked")
    # 没勾选的其他零件也算出「勾选后会补多少」(只给页面显示,不下单)
    assert (lines["8934806270"]["final_qty"], lines["8934806270"]["preview_qty"]) == (0, 3)
    assert oil["preview_qty"] == oil["final_qty"] == 5 and st["hide_zero"] is False
    assert lines["GPDL0WM001"]["category"] == "未分类"
    assert st["can_confirm"] and 55 <= st["seconds_left"] <= 60 and st["valid_seconds"] == 60
    assert st["summary"]["order_count"] == 3 and st["window"] == "10/21 15:00 — 10/22 15:00"
    # 审计:出库明细原样存(含非纯)、推送的清单快照
    assert len(db.rows(select(outbound_rows_t).where(outbound_rows_t.c.run_id == run["id"]))) == 7
    snaps = db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"]))
    assert [s["kind"] for s in snaps] == ["pushed"]
    # 群里回「确认」不会建单(定时补货必须走页面)
    d = say(k, "确认")
    assert d["calls"][0]["tool"] == "confirm_order" and "请点开链接确认" in group_msgs(k, outbox)[-1]
    assert "restock.create_po" not in fake_edge.calls
    # 页面确认:改了机滤的期望、勾选了传感器固定件
    clock.advance(seconds=20)
    r = confirm(client, run["token"], state_of(st, **{"90915YZZM3": {"expected": 20},
                                                      "8934806270": {"checked": True}}))
    assert r.status_code == 200, r.text
    settle(k)
    run = k.svc().run(run["id"])
    assert run["status"] == "awaiting_submit" and run["order_no"] == "S2026102201" and run["confirmed_via"] == "order_page"
    cp = next(p for p in fake_edge.params if "lines" in p and "remark" in p)          # restock.create_po
    lines_po = {l["part_no"]: l["qty"] for l in cp["lines"]}
    assert lines_po == {"0888080463": 5, "90915YZZM3": 8, "019990A115": 2, "8934806270": 3}
    assert cp["order_type"] == "S" and cp["kind"] == "scheduled"
    assert "(定时)" in cp["remark"]
    done_msg = group_msgs(k, outbox)[-1]
    assert len(outbox.images) == 2 and "单建好了:S2026102201(待提交)" in done_msg and "点「确认提交」" in done_msg
    # 群里回「确认」不会提交定时补货(只回链接)
    say(k, "确认提交")
    assert "群里回复不会提交" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
    st = page(client, run["token"])
    assert st["can_submit"] and st["can_hold"] and "submit_seconds_left" not in st      # 确认提交不过期
    r = submit(client, run["token"])
    assert r.status_code == 200, r.text
    settle(k)
    run = k.svc().run(run["id"])
    assert run["status"] == "done" and run["submitted_via"] == "order_page" and fake_edge.submitted == ["9001"]
    sp = next(p for p in fake_edge.params if "expect" in p)
    assert sp["order_id"] == "9001" and sp["order_no"] == "S2026102201" and sp["kind"] == "scheduled"
    assert {l["part_no"]: l["qty"] for l in sp["expect"]["lines"]} == lines_po and sp["expect"]["supplier_code"] == "APC40"
    po = db.one(select(po_t).where(po_t.c.run_id == run["id"]))
    assert po["status"] == "已提交" and po["apply_operator"] == "邹新" and po["submit_task_id"] == "u" * 32
    receipt = group_msgs(k, outbox)[-1]
    assert receipt.startswith("已提交 ✅") and "PO 单号 S2026102201" in receipt and "提交人 邹新" in receipt
    assert "共 4 项 / 18 件" in receipt and "状态 已提交" in receipt
    assert any("在单据页确认提交,正在 DMS 提交 S2026102201" in m for m in group_msgs(k, outbox))
    assert submit(client, run["token"]).status_code == 409                  # 已提交的不能再提交
    conf = db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"], snapshots_t.c.kind == "confirmed"))
    changes = {c["part_no"]: c for c in db.jload(conf[0]["data"], {})["changes"]}
    assert changes["90915YZZM3"]["after"]["expected"] == 20 and changes["8934806270"]["after"]["checked"] is True
    acts = [r["action"] for r in audit.query(store_ids=[k.store_id], limit=500)[1]]
    for a in ("restock.run.start", "restock.run.confirm", "restock.po.created", "restock.run.chat_confirm_blocked",
              "restock.run.submit_route", "restock.run.submit_confirm", "restock.po.submitted"):
        assert a in acts, a
    # 建过单后还能手动补充:重新按全天出库算;已提交的单算在途,不再当成「未提交的采购单」提示
    assert k.call(k.svc().start, k.store_id, "console", Actor("user", "1", "店长")) == "started"
    settle(k)
    assert "补货推荐已生成" in group_msgs(k, outbox)[-1] and "没提交的采购单" not in group_msgs(k, outbox)[-1]
    extra = k.svc().current(k.store_id)
    assert page(client, extra["token"])["today_orders"][0]["order_no"] == "S2026102201"
    # 审计时间线:聊天、操作、流程、快照都在
    tl = client.get(f"/api/restock/runs/{run['id']}/timeline?size=200", headers=k.h).json()["items"]
    kinds = {x["kind"] for x in tl}
    assert {"chat", "audit", "event", "snapshot"} <= kinds
    assert any(x["kind"] == "chat" and "请点开链接确认" in x["text"] for x in tl)   # 群里的引导回复也串进来了
    assert any(x["kind"] == "audit" and "群里回确认" in x["title"] for x in tl)
    assert client.get(f"/api/restock/runs/{run['id']}/timeline.csv", headers=k.h).status_code == 200
    sid_ = next(x for x in tl if x["kind"] == "snapshot")["detail"]["snapshot_id"]
    assert client.get(f"/api/restock/runs/{run['id']}/snapshots/{sid_}", headers=k.h).json()["kind"] == "pushed"
    ob = client.get(f"/api/restock/runs/{run['id']}/outbound", headers=k.h).json()
    assert len(ob["rows"]) == 7 and ob["fetch_seq"] == 1
    # 第二天:机滤带「上次」人工修改的值 20
    fake_now(d=23, hh=15)
    k.heartbeat()
    k.call(k.svc().push, k.store_id, clock.now(), "15:00")
    settle(k)
    st2 = page(client, k.svc().current(k.store_id)["token"])
    filt2 = next(l for l in st2["lines"] if l["part_no"] == "90915YZZM3")
    assert (filt2["default_source"], filt2["expected"], filt2["last_expected"]) == ("last", 20, 20)
    oil2 = next(l for l in st2["lines"] if l["part_no"] == "0888080463")
    assert oil2["default_source"] == "recommend"                    # 没改过的不会变成「上次」


def test_confirm_expires_and_refresh_reruns_chain(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    st = page(client, run["token"])
    mine = state_of(st, **{"0888080463": {"expected": 20}})
    clock.advance(seconds=70)                                       # 超过 60 秒有效期
    st = page(client, run["token"])
    assert st["seconds_left"] == 0 and not st["can_confirm"] and st["can_refresh"]
    r = confirm(client, run["token"], mine)
    assert r.status_code == 409 and "有效期" in r.json()["detail"]
    fake_edge.facts["0888080463"]["trans_shipped"] = 4               # 有人下午手工补过一单:在途变了
    r = client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": mine})
    assert r.status_code == 200, r.text
    settle(k)
    assert fake_edge.calls.count("restock.outbound") == 2 and fake_edge.calls.count("restock.quote") == 2
    run = k.svc().run(run["id"])
    assert (run["fetch_seq"], run["refresh_count"], run["status"]) == (2, 1, "awaiting_confirm")
    st = page(client, run["token"])
    oil = next(l for l in st["lines"] if l["part_no"] == "0888080463")
    assert (oil["expected"], oil["modified"], oil["in_transit"], oil["final_qty"]) == (20, True, 4, 8)   # 人改的保留
    assert st["seconds_left"] >= 55
    kinds = [s["kind"] for s in db.rows(select(snapshots_t).where(snapshots_t.c.run_id == run["id"]))]
    assert kinds == ["pushed", "refreshed"]
    assert len(db.rows(select(outbound_rows_t).where(outbound_rows_t.c.run_id == run["id"]))) == 14   # 两轮都留
    assert confirm(client, run["token"], state_of(st)).status_code == 200
    settle(k)
    acts = [r["action"] for r in audit.query(store_ids=[k.store_id], actor_type="public", limit=50)[1]]
    assert {"restock.run.confirm_rejected", "restock.run.refresh", "restock.run.confirm"} <= set(acts)
    # 确认消息列出用户改过的零件;后台详情 / 列表的「改过」按同一口径
    done = next(m for m in group_msgs(k, outbox) if "已确认,正在 DMS 建单" in m)
    assert "其中改了 1 处" in done and "0888080463" in done and f"期望 {oil['default_expected']}→20" in done
    detail = client.get(f"/api/restock/runs/{run['id']}", headers=k.h).json()
    assert detail["summary"]["changed_count"] == 1
    assert [l["part_no"] for l in detail["lines"] if l["changed"]] == ["0888080463"]


def test_chat_cannot_start_scheduled(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    fake_now(hh=15)
    k.heartbeat()
    d = say(k, "现在3点了,帮我查一下库存补货信息")
    assert d["calls"][0]["tool"] == "scheduled_link"
    assert "不能在群里发起" in group_msgs(k, outbox)[-1] and fake_edge.calls == []
    with pytest.raises(ValueError):
        k.call(k.svc().start, k.store_id, "chat", Actor("planner_im", "x", "张三"))


def test_manual_run_does_not_affect_schedule(client, admin, outbox, fake_edge, monkeypatch):
    """手动补充(10:00 已建单)不影响 15:00 定时:定时照常按全天出库窗口新开一张,还能确认建单。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    assert client.post("/api/restock/runs/start", headers=k.h).json()["result"] == "started"
    settle(k)
    manual = k.svc().current(k.store_id)
    assert manual["trigger"] == "console" and manual["status"] == "awaiting_confirm"
    assert confirm(client, manual["token"], state_of(page(client, manual["token"]))).status_code == 200
    settle(k)
    assert k.svc().run(manual["id"])["order_no"] == "S2026102201"
    fake_edge.drafts = [{"order_id": "9001", "order_no": "S2026102201", "create_by": "管理员",
                         "create_time": "2026-10-22 10:01:00", "doc_no": manual["doc_no"],
                         "details": [{"part_no": "90915YZZM3", "qty": 18}]}]
    run = push(k)
    assert run["id"] != manual["id"] and run["trigger"] == "schedule" and run["status"] == "awaiting_confirm"
    assert (run["window_start"], run["window_end"]) == (dt.datetime(2026, 10, 21, 15), dt.datetime(2026, 10, 22, 15))
    pushed = group_msgs(k, outbox)[-1]
    assert "DMS 里还有 1 张没提交的采购单" in pushed and "S2026102201" in pushed and manual["doc_no"] in pushed
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"
    assert submit(client, run["token"]).status_code == 200                    # 两张单各自按 token 提交
    settle(k)
    assert k.svc().run(run["id"])["status"] == "done" and k.svc().run(manual["id"])["status"] == "awaiting_submit"
    sent = []

    async def fake_send(sid, kind, severity, title, text, **kw):
        sent.append(text)
    monkeypatch.setattr(restock_service.notify, "send", fake_send)
    k.call(k.svc().close, k.store_id, fake_now(hh=16), "16:00")
    assert sent == []                                                         # 截单只收口,小结按自己的时间发
    k.call(k.svc().summary, k.store_id, fake_now(hh=16, mm=30), "16:30")
    assert "(手动补充,待提交" in sent[-1] and "(定时推送,已提交)" in sent[-1]


def test_two_scheduled_orders_prompt_with_both_links(client, admin, outbox, fake_edge):
    """一天出现两张定时补货单(手动补充 + 定时推送)都待确认提交:推送、群里回提交 / 确认 / 不提交、问进度、单据页,
    都明确提示有两张,并给出两张各自的链接。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    assert client.post("/api/restock/runs/start", headers=k.h).json()["result"] == "started"
    settle(k)
    manual = k.svc().current(k.store_id)
    assert confirm(client, manual["token"], state_of(page(client, manual["token"]))).status_code == 200
    settle(k)
    fake_edge.drafts = [{"order_id": "9001", "order_no": "S2026102201", "create_by": "管理员",
                         "create_time": "2026-10-22 10:01:00", "doc_no": manual["doc_no"],
                         "details": [{"part_no": "90915YZZM3", "qty": 18}]}]
    run = push(k)
    pushed = group_msgs(k, outbox)[-1]
    assert "没提交的采购单" in pushed and manual["token"] in pushed and run["token"] in pushed
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    assert [r["id"] for r in k.svc().scheduled_awaiting_submit(k.store_id)] == [manual["id"], run["id"]]
    for text, word in (("提交", "群里回复不会提交"), ("确认", "群里回复不会提交"), ("不提交", "「先不提交」")):
        say(k, text)
        m = group_msgs(k, outbox)[-1]
        assert "现在有 2 张定时补货单" in m and word in m, text
        assert manual["doc_no"] in m and run["doc_no"] in m and manual["token"] in m and run["token"] in m, text
    assert "restock.submit_po" not in fake_edge.calls
    say(k, "补货到哪一步了")
    m = group_msgs(k, outbox)[-1]
    assert "另外还有 1 张定时补货单" in m and manual["token"] in m and run["token"] in m
    st = page(client, run["token"])
    assert st["today_orders"][0]["link"] == f"/m/restock/order/{manual['token']}"
    assert st["today_orders"][0]["stage_cn"] == "待确认提交"


def test_old_scheduled_draft_still_listed_next_day(client, admin, outbox, fake_edge):
    """定时补货确认提交不过期:昨天没提交的单,今天在群里问到时也列出来(带日期和链接)。"""
    k = setup_store(client, admin)
    run = push(k)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    fake_now(d=23, hh=9)
    k.heartbeat()
    say(k, "提交")
    m = group_msgs(k, outbox)[-1]
    assert run["token"] in m and "群里回复不会提交" in m
    say(k, "补货到哪一步了")
    m = group_msgs(k, outbox)[-1]
    assert "2026-10-22" in m and run["token"] in m


def test_schedule_supersedes_pending_manual_and_waits_busy(client, admin, outbox, fake_edge, monkeypatch):
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    client.post("/api/restock/runs/start", headers=k.h)
    settle(k)
    manual = k.svc().current(k.store_id)
    run = push(k)                                                  # 手动单还在等确认 → 作废,定时单覆盖全天
    assert k.svc().run(manual["id"])["status"] == "superseded" and run["trigger"] == "schedule"
    r = client.post("/api/restock/runs/start", headers=k.h).json()   # 手动不能作废待确认的定时单
    assert r["result"] == "schedule_pending" and k.svc().run(run["id"])["status"] == "awaiting_confirm"
    # 第二天:到点时手动单还在跑 → 等它跑完再开始,不会被丢掉
    fake_now(d=23, hh=14, mm=59)
    k.heartbeat()
    busy = k.svc()._new_run(k.store_id, "scheduled", "console", Actor("user", "1", "店长"))
    slept = []

    async def fake_sleep(sec):
        slept.append(sec)
        db.q(runs_t.update().where(runs_t.c.id == busy).values(status="done"))
    monkeypatch.setattr(restock_service.asyncio, "sleep", fake_sleep)
    t = fake_now(d=23, hh=15)
    k.heartbeat()
    k.call(k.svc().push, k.store_id, t, "15:00")
    settle(k)
    run2 = k.svc().current(k.store_id)
    assert slept and run2["id"] != busy and run2["trigger"] == "schedule" and run2["status"] == "awaiting_confirm"


def test_console_run_now_and_no_candidates(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    fake_edge.parts = []
    r = client.post("/api/restock/runs/start", headers=k.h).json()
    assert r["result"] == "started"
    settle(k)
    run = k.svc().current(k.store_id)
    assert run["trigger"] == "console" and run["status"] == "done"
    assert "没有纯牌零件出库" in group_msgs(k, outbox)[-1]


def test_page_events_and_cancel(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    r = client.post(f"/api/public/restock/orders/{run['token']}/events",
                    json={"kind": "edit", "detail": {"part_no": "90915YZZM3", "field": "expected", "before": 30, "after": 25}})
    assert r.status_code == 200
    rows = audit.query(store_ids=[k.store_id], action="restock.page.edit", limit=5)[1]
    assert rows and rows[0]["detail"]["after"] == 25 and rows[0]["ip"]
    assert client.post(f"/api/public/restock/orders/{run['token']}/cancel").status_code == 200
    assert k.svc().run(run["id"])["status"] == "cancelled"
    assert client.get("/api/public/restock/orders/notatoken").status_code == 404


# ====================================================================== 截图兜底
def test_screenshot_fallback(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    fake_edge.shot_fallback = "image"
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    msgs = group_msgs(k, outbox)
    note = next(m for m in msgs if "DMS 页面截图失败" in m)
    assert "接口实际返回的数据渲染" in note and "不是 DMS 原页面" in note
    assert "(接口数据渲染)" in msgs[-1] and len(outbox.images) == 2
    po = db.one(select(po_t).where(po_t.c.run_id == run["id"]))
    assert po["shots_fallback"] == "image" and po["fallback_reason"] == "浏览器登录超时"
    assert open_alerts(k, "restock.screenshot_failed")


# ====================================================================== 单次补货
def test_single_restock_flow(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    d = say(k, "@配件订货员 8713902280 空调滤 2 个")
    assert d["calls"][0]["tool"] == "single_restock" and d["calls"][0]["args"] == {"part_no": "8713902280", "qty": 2}
    settle(k)
    q = fake_edge.params[0]
    assert q["parts"] == [{"part_no": "8713902280", "name": "", "national": True}]
    msg = group_msgs(k, outbox)[-1]
    assert "查到 8713902280" in msg and "广州仓 0 · 华南仓 1095" in msg and "当日剩余可订 30" in msg and "回「订」建单" in msg
    assert "GTMC" not in msg
    single = k.svc().single_open(k.store_id)
    assert single["kind"] == "single" and single["status"] == "awaiting_confirm"
    assert single["trigger_target_id"] == k.target_id                # 单据记下所属会话
    k.call(assistant.handle, k.target(), "lisi", "李四", "订")         # 一个会话 = 一个用户:群里别人回「订」照样建单
    settle(k)
    run = k.svc().run(single["id"])
    assert run["status"] == "awaiting_submit" and run["confirmed_via"] == "chat" and run["order_no"] == "S2026102201"
    assert run["confirmed_by"] == "李四"                              # 留痕记的是真实说话人
    conf = audit.query(store_ids=[k.store_id], action="restock.run.confirm", limit=1)[1][0]
    assert conf["actor_id"] == "lisi" and conf["actor_name"] == "李四"
    po = next(p for p in fake_edge.params if "lines" in p)
    assert [(x["part_no"], x["qty"]) for x in po["lines"]] == [("8713902280", 2)] and po["remark"].endswith("(单次)" + run["doc_no"])
    assert po["order_type"] == "S" and po["kind"] == "single"
    done_msg = group_msgs(k, outbox)[-1]
    assert "单建好了:S2026102201(待提交)" in done_msg and "没问题 @我 回「确认提交」" in done_msg
    assert "张三" not in done_msg
    say(k, "0888080463 5个")                                         # 待确认提交:先查 DMS,仍是待提交 → 不接新单
    assert "刚到 DMS 查过,这张单还是「待提交」" in group_msgs(k, outbox)[-1]
    assert "回「确认提交」提交,或回「不提交」" in group_msgs(k, outbox)[-1]
    assert k.svc().single_open(k.store_id)["id"] == single["id"]
    for t in ("订", "好的", "确认", "OK"):                             # 待确认提交时没明确说「提交」:不提交
        d = say(k, t)
        assert d["calls"][0]["tool"] == "confirm_order", t
        assert "@我 回「确认提交」" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
    rej = audit.query(store_ids=[k.store_id], action="restock.run.submit_rejected", limit=1)[1][0]
    assert rej["detail"]["reason"] == "未明确说提交"
    for t in ("可以,提交吧", "提交吧", "没问题提交"):                 # 提交只认「提交」「确认提交」,其他说法只回提示
        d = say(k, t)
        assert d["route"] == "llm" and d["calls"][0]["tool"] == "submit_order", t
        assert "只有回「确认提交」才会提交" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
    d = say(k, "确认提交")
    assert d["calls"][0]["tool"] == "submit_order"
    settle(k)
    run = k.svc().run(single["id"])
    assert run["status"] == "done" and run["submitted_via"] == "chat" and run["submitted_by"] == "张三"
    assert (run["confirmed_by"], run["submitted_by"]) == ("李四", "张三")     # 李四建单、张三提交:都记真实的人
    msgs = group_msgs(k, outbox)
    assert "收到,正在 DMS 提交 S2026102201" in msgs[-2]
    assert msgs[-1] == ("已提交 ✅\n——————————————\nPO 单号 S2026102201\n\n空调滤清器滤芯分总成 × 2\n\n"
                        "金额 ¥ 106.60\n——————————————\n提交人 邹新\n状态 已提交")
    say(k, "确认")
    assert "没有待确认的单次补货" in group_msgs(k, outbox)[-1] and fake_edge.calls.count("restock.submit_po") == 1
    # 单次补货不影响当天的定时补货
    assert k.svc().ordered_today(k.store_id) is None and k.svc().current(k.store_id) is None
    run_b = push(k, hh=15, mm=30)
    assert run_b["status"] == "awaiting_confirm"
    # 再来一单单次(不限次数),回「不订」取消
    say(k, "8713902280 1个")
    settle(k)
    say(k, "不订")
    assert "这单不订了" in group_msgs(k, outbox)[-1]
    dec = db.rows(select(ai_traces_t).order_by(ai_traces_t.c.id.desc()).limit(1))[0]
    assert dec["ref"] and dec["ref"].startswith("restock:run:")         # 处理记录挂到单据上,时间线能看到
    acts = [r["action"] for r in audit.query(store_ids=[k.store_id], limit=200)[1]]
    assert acts.count("restock.run.start") == 3


def test_single_cancel_while_querying(client, admin, outbox, fake_edge):
    """查询还没出结果就回「不订」:直接取消,查询结果回来后丢弃,不再推「回订 / 不订」。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    actor = Actor("planner_im", "zhangsan", "张三")
    k.call(k.svc().single_request, k.store_id, actor, "8713902280", 2, "8713902280 2个")
    single = k.svc().single_open(k.store_id)
    assert single["status"] == "scanning"
    assert k.call(k.svc().single_cancel, k.store_id, actor) == ""
    assert k.svc().run(single["id"])["status"] == "cancelled"
    n = len(group_msgs(k, outbox))
    settle(k)
    assert k.svc().run(single["id"])["status"] == "cancelled"
    assert not any("回「订」建单" in m for m in group_msgs(k, outbox)[n:])


def test_single_restock_never_expires_and_capped(client, admin, outbox, fake_edge):
    """单次补货的查询结果不过期:隔了很久(tick 也跑过)再回「订」照常按查询结果建单。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    say(k, "8713902280 40个")
    settle(k)
    assert "你要 40 个" in group_msgs(k, outbox)[-1] and "只能按 30 个下单" in group_msgs(k, outbox)[-1]
    t = clock.advance(hours=3)
    k.call(k.svc().tick, k.store_id, t)
    run = k.svc().single_open(k.store_id)
    assert run and run["status"] == "awaiting_confirm"
    k.heartbeat()
    say(k, "订")
    settle(k)
    assert "restock.create_po" in fake_edge.calls
    lines = next(p for p in fake_edge.params if "lines" in p)["lines"]
    assert [(l["part_no"], l["qty"]) for l in lines] == [("8713902280", 30)]
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"


# ====================================================================== 确认提交(建单截图之后)
def single_created(k, outbox, text="8713902280 2个"):
    """单次补货走到「待确认提交」:报价 → 回「订」→ 建单截图。"""
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, text)
    settle(k)
    say(k, "订")
    settle(k)
    run = k.svc().single_open(k.store_id)
    assert run["status"] == "awaiting_submit"
    return run


@pytest.fixture()
def switches():
    from app.services import settings
    yield lambda **kw: settings.save("edge_runtime", kw, "test")
    settings.save("edge_runtime", {"allow_create_single": True, "allow_submit_single": True,
                                   "allow_create_scheduled": True, "allow_submit_scheduled": True}, "test")


def test_single_not_submit_keeps_draft(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    d = k.call(assistant.handle, k.target(), "lisi", "李四", "先不提交了")   # 同一个会话里谁说都算
    assert d["calls"][0]["tool"] == "cancel_order"
    r = k.svc().run(run["id"])
    assert r["status"] == "cancelled" and "草稿" in r["message"]
    assert "S2026102201 先不提交" in group_msgs(k, outbox)[-1] and "人工删除或提交" in group_msgs(k, outbox)[-1]
    assert "restock.submit_po" not in fake_edge.calls
    assert audit.query(store_ids=[k.store_id], action="restock.run.submit_cancel", limit=1)[1]


def test_submit_never_expires_and_checks_dms_first(client, admin, outbox, fake_edge):
    """建单后的确认提交不过期:两天后回「确认提交」照常提交,提交前先查 DMS 状态。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    done_msg = group_msgs(k, outbox)[-1]                       # 回执不写截止时间(单次补货话术已简化,不再写「不过期」)
    assert "前有效" not in done_msg and "回「确认提交」" in done_msg
    t = clock.advance(days=2)
    k.call(k.svc().tick, k.store_id, t)
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"
    assert not open_alerts(k, "restock.submit_expired")
    k.heartbeat()
    say(k, "确认提交")
    settle(k)
    assert fake_edge.calls.index("restock.po_status") < fake_edge.calls.index("restock.submit_po")
    assert k.svc().run(run["id"])["status"] == "done" and fake_edge.submitted == ["9001"]
    assert audit.query(store_ids=[k.store_id], action="restock.po.status", limit=1)[1]


def test_submit_when_po_deleted_in_dms(client, admin, outbox, fake_edge):
    """DMS 里这张采购单已被删除:不提交,补货单收口(不订),群里如实说。之后可以发新的单次补货。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    fake_edge.po_state = "missing"
    say(k, "确认提交")
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "cancelled" and "已被删除" in r["message"]
    assert "restock.submit_po" not in fake_edge.calls
    assert "在 DMS 里已经被删除" in group_msgs(k, outbox)[-1]
    assert k.svc().po_of(run["id"])["status"] == "已删除"
    assert k.svc().single_open(k.store_id) is None


def test_submit_when_po_not_pending_in_dms(client, admin, outbox, fake_edge):
    """DMS 里这张单已经不是待提交(被别人处理过,如已完成):不提交,补货单收口(完成),回复当前状态。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    fake_edge.po_state = "other"
    say(k, "确认提交")
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "done" and "状态码 4" in r["message"]
    assert "restock.submit_po" not in fake_edge.calls
    assert "现在是「状态码 4」" in group_msgs(k, outbox)[-1]


def test_submit_when_po_already_submitted_or_status_unknown(client, admin, outbox, fake_edge):
    """已被别人提交 → 照样走 submit_po(取数端只回查不重复提交);查状态失败 → 也走 submit_po(提交前取数端会再核对)。"""
    for state in ("submitted", "error"):
        k = setup_store(client, admin)
        fake_edge.calls.clear()
        fake_edge.submitted.clear()
        run = single_created(k, outbox)
        fake_edge.po_state = state
        say(k, "确认提交")
        settle(k)
        assert "restock.submit_po" in fake_edge.calls, state
        assert k.svc().run(run["id"])["status"] == "done", state
        fake_edge.po_state = "pending"


def _new_single_after(k, outbox, fake_edge, state):
    """上一单已建单待确认提交,DMS 里这张单处于 state 时,再发一单新的单次补货。返回 (旧单, 发完后的群消息)。"""
    run = single_created(k, outbox)
    fake_edge.po_state = state
    n = len(group_msgs(k, outbox))
    say(k, "0888080463 5个")
    settle(k)
    return run, group_msgs(k, outbox)[n:]


def test_new_single_when_prev_po_deleted(client, admin, outbox, fake_edge):
    """上一单在 DMS 里已被删除:上一单收口(不订),提示一句,接着给新零件报价。"""
    k = setup_store(client, admin)
    run, msgs = _new_single_after(k, outbox, fake_edge, "missing")
    r = k.svc().run(run["id"])
    assert r["status"] == "cancelled" and "已被删除" in r["message"]
    assert any("上一单的采购单 S2026102201" in m and "已经被删除" in m and "收到,查一下 0888080463" in m for m in msgs)
    new = k.svc().single_open(k.store_id)
    assert new["id"] != run["id"] and new["status"] == "awaiting_confirm"
    assert "restock.submit_po" not in fake_edge.calls


def test_new_single_when_prev_po_submitted_by_others(client, admin, outbox, fake_edge):
    """上一单在 DMS 里已经被别人提交:上一单收口(完成),说明状态,接着建新单;不会再去提交。"""
    k = setup_store(client, admin)
    run, msgs = _new_single_after(k, outbox, fake_edge, "submitted")
    r = k.svc().run(run["id"])
    assert r["status"] == "done" and "已提交" in r["message"]
    assert any("在 DMS 里已经是「已提交」" in m for m in msgs)
    assert k.svc().single_open(k.store_id)["id"] != run["id"]
    assert "restock.submit_po" not in fake_edge.calls


def test_new_single_refused_when_prev_still_pending_or_unknown(client, admin, outbox, fake_edge):
    """上一单 DMS 里还是待提交 / 查不到状态:拒绝新单,上一单不动。"""
    for state, word in (("pending", "刚到 DMS 查过,这张单还是「待提交」"), ("error", "暂时查不到 DMS 里这张单的状态")):
        k = setup_store(client, admin)
        run, msgs = _new_single_after(k, outbox, fake_edge, state)
        assert word in msgs[-1] and "这次没有新建" in msgs[-1], state
        assert k.svc().single_open(k.store_id)["id"] == run["id"], state
        assert audit.query(store_ids=[k.store_id], action="restock.run.start_blocked", limit=1)[1], state
        fake_edge.po_state = "pending"


def test_new_single_supersedes_pending_quote(client, admin, outbox, fake_edge):
    """上一单只报了价(DMS 里没有单):发新的就作废旧报价,接着查新零件;旧单之后回「订」也不会建单。"""
    k = setup_store(client, admin)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)
    old = k.svc().single_open(k.store_id)
    assert old["status"] == "awaiting_confirm"
    k.call(assistant.handle, k.target(), "lisi", "李四", "0888080463 5个")   # 同一个会话里别人发新零件:旧报价作废
    settle(k)
    assert k.svc().run(old["id"])["status"] == "superseded"
    assert any("(张三 发的)" in m and "已作废" in m for m in group_msgs(k, outbox))
    new = k.svc().single_open(k.store_id)
    assert new["id"] != old["id"] and new["triggered_by"] == "李四" and new["trigger_target_id"] == k.target_id
    assert "restock.po_status" not in fake_edge.calls and "restock.create_po" not in fake_edge.calls


def test_single_typo_confirm_by_rule(client, admin, outbox, fake_edge):
    """截图里的对话:「帮我定:零件号*数量」→ 回「定」(「订」的错字):规则直接建单,不会被当成定时补货。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    d = say(k, "帮我定:8713902280*2")
    assert d["route"] == "llm" and d["calls"][0]["tool"] == "single_restock"
    settle(k)
    run = k.svc().single_open(k.store_id)
    assert run["status"] == "awaiting_confirm"
    quote = group_msgs(k, outbox)[-1]
    assert "月均" not in quote and quote.endswith("👉 @我 回「订」建单\n👉 @我 回「不订」取消")
    d = say(k, "定")
    assert d["route"] == "llm" and d["calls"][0]["tool"] == "confirm_order"
    settle(k)
    assert "restock.create_po" in fake_edge.calls
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"


def _fake_llm(monkeypatch, fn):
    """给大模型打桩:fn(system, user, tools, call) -> 最终回复。返回每次收到的 (system, user)。"""
    seen: list[tuple[str, str]] = []

    async def run(self, store_id, system, user, sender, tools, call):
        seen.append((system, user))
        by_name = {t.name: (k_, t) for k_, t in tools}
        return await fn(system, user, by_name, call), [{"ms": 1, "tokens_in": 100, "tokens_out": 3, "thinking": "",
                                                         "text": "", "tool_calls": []}]
    monkeypatch.setattr(type(assistant), "_run_llm", run)
    return seen


def test_llm_sees_quote_and_state(client, admin, outbox, fake_edge, monkeypatch):
    """规则识别不了的口语交给大模型:它收到的上下文里有【当前状态】和刚才异步推送的报价,能判断是在回应「要不要订」。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)

    async def decide(system, user, tools, call):
        assert "按 2 个下单" in user and "待确认" in user and "本会话的单次补货" in user
        assert "谁 @你 都算同一个用户" in user
        await call(*tools["confirm_order"], {})
        await call(*tools["confirm_order"], {})                       # 模型重复调用:只执行一次
        return "__NO_REPLY__"
    seen = _fake_llm(monkeypatch, decide)
    d = say(k, "没毛病,整吧")
    assert d["route"] == "llm" and d["result"] == "tool" and len(seen) == 1
    assert [c.get("duplicate", False) for c in d["calls"]] == [False, True]
    assert "single_restock" in seen[0][0] and "【最近聊天记录】" in seen[0][1] and d["rounds"]
    settle(k)
    run = k.svc().single_open(k.store_id)
    assert run["status"] == "awaiting_submit" and fake_edge.calls.count("restock.create_po") == 1
    tr = client.get(f"/api/wecom/logs/{d['log_id']}/trace", headers=admin).json()
    assert tr["ref"] == f"restock:run:{run['id']}" and "【最近聊天记录】" in tr["context"] and "single_restock" in tr["prompt"]
    assert tr["rounds"] and tr["tokens_in"] == 100 and tr["calls"][0]["tool"] == "confirm_order"


def test_llm_guards(client, admin, outbox, fake_edge, monkeypatch):
    """防误操作:模型编的零件号不查 DMS(自由回复不再按数字拦截,见 test_free_reply_with_numbers_is_sent)。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()

    async def fake_part(system, user, tools, call):
        await call(*tools["single_restock"], {"part_no": "99999999", "qty": 3})
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, fake_part)
    d = say(k, "帮我看看那个机油滤芯")
    assert "都没有出现" in d["calls"][0]["result"] and k.svc().single_open(k.store_id) is None
    assert "restock.quote" not in fake_edge.calls


def test_chat_linked_to_run_and_message_logs(client, admin, outbox, fake_edge):
    """每句话都精确挂到它说的那张单上:两张单的对话不混;没关联单的对话在「消息记录」里照样能看到处理摘要。"""
    from app.features.restock import timeline
    k = setup_store(client, admin)
    say(k, "你好", sender="wangwu")                                  # 会话里没有进行中的单:不关联任何单
    a = single_created(k, outbox)
    say(k, "确认提交")
    settle(k)
    say(k, "0888080463 5个", sender="lisi")
    settle(k)
    say(k, "订", sender="lisi")
    settle(k)
    b = k.svc().single_open(k.store_id)
    assert b and b["id"] != a["id"] and b["status"] == "awaiting_submit"

    def got(run_id):
        return [x["text"] for x in timeline.build(k.svc().run(run_id))
                if x["kind"] == "chat" and x["title"].startswith("收到") and "未关联" not in x["title"]]
    assert got(a["id"]) == ["8713902280 2个", "订", "确认提交"]          # lisi 的「订」只在 B 单上
    assert got(b["id"]) == ["0888080463 5个", "订"]
    r = client.get("/api/wecom/logs?category=chat,ignored&size=100", headers=admin).json()
    ins = [x for x in r["rows"] if x["direction"] == "in"]
    hello = next(x for x in ins if x["content"] == "你好")
    assert hello["run"] is None and hello["trace"]["route"] == "llm" and "prompt" not in hello["trace"]
    sub = next(x for x in ins if x["content"] == "确认提交")
    assert sub["run"]["run_id"] == a["id"] and sub["trace"]["route"] == "llm"
    tl = timeline.build(k.svc().run(a["id"]))
    assert any(x["title"].startswith("智能助手:处理") and x["detail"]["log_id"] == sub["id"] for x in tl)
    assert client.get("/api/wecom/logs/999999999/trace", headers=admin).status_code == 404
    assert any(x["direction"] == "out" and "查到 8713902280" in x["content"] for x in r["rows"])


def test_hide_zero_lines_switch(client, admin, outbox, fake_edge):
    """补货规则「自动过滤补货数量为 0 的零件」:单据页拿到开关(页面按 preview_qty 隐藏),计算和建单不受影响。"""
    k = setup_store(client, admin, hide_zero_lines=True)
    run = push(k)
    st = page(client, run["token"])
    assert st["hide_zero"] is True and all("preview_qty" in l for l in st["lines"])
    assert st["summary"]["order_count"] == 3


def test_single_multi_parts_in_one_sentence(client, admin, outbox, fake_edge, monkeypatch):
    """一句话里发了多个「零件号 数量」:只查第一个,回复里说明一次只能订一个并列出其余零件;
    模型把它拆成两次调用时第二次不执行、不再回「上一单还没处理完」。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()

    async def both(system, user, tools, call):
        await call(*tools["single_restock"], {"part_no": "591819818", "qty": 2})
        await call(*tools["single_restock"], {"part_no": "5198192123", "qty": 10})
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, both)
    before = len(group_msgs(k, outbox))
    d = say(k, "帮我订:591819818*2,5198192123*10")
    assert d["result"] == "tool" and d["calls"][1]["replied"] and "不要再调用" in d["calls"][1]["result"]
    settle(k)
    sent = group_msgs(k, outbox)[before:]
    assert len(sent) == 2 and "查一下 591819818(要 2 个)" in sent[0] and "查到 591819818" in sent[1]   # 回执 + 报价
    assert "一次只能订 1 个零件,这次只查了 591819818" in sent[0] and "· 5198192123 × 10" in sent[0]
    assert not any("上一单" in m for m in sent)
    assert k.svc().single_open(k.store_id)["trigger_text"] == "帮我订:591819818*2,5198192123*10"


def test_free_reply_with_numbers_is_sent(client, admin, outbox, fake_edge, monkeypatch):
    """直接回复(reply_text)复述这句原话里的零件号:有出处,照常发出,记成「助手直接回复」。"""
    k = setup_store(client, admin)
    fake_now(hh=10)

    async def chat(system, user, tools, call):
        assert "reply_text" in system and "【最高优先级规则】" in system
        await call(*tools["reply_text"], {"text": "单次补货一次只能订一个零件,先发 591819818*2 吧"})
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, chat)
    d = say(k, "591819818*2 和 5198192123*10 一起订行吗")
    assert d["result"] == "free_reply" and group_msgs(k, outbox)[-1] == "单次补货一次只能订一个零件,先发 591819818*2 吧"
    row = db.one(select(notify_logs_t).where(notify_logs_t.c.direction == "out").order_by(notify_logs_t.c.id.desc()))
    assert row["event"] == "assistant"                                  # 助手自己说的话,和业务工具发的分开


# ---------------------------------------------------------------- 照抄旧通知、不调工具(2026-11-12 sit 事故)
STALE = "上一单单次补货还没处理完(空调滤清器滤芯分总成 8713902280 × 2,待确认提交,采购单 {po}),这次没有新建。"


def test_text_without_tool_is_never_sent(client, admin, outbox, fake_edge, monkeypatch):
    """模型一个工具都没调、直接输出文字(照抄聊天记录里的旧通知):不发,回固定引导语,处理记录 no_tool_text 并记告警事件。"""
    from app.models import events_t
    from app.services import events
    k = setup_store(client, admin)
    run = single_created(k, outbox)

    async def parrot(system, user, tools, call):
        return STALE.format(po=run["order_no"])
    _fake_llm(monkeypatch, parrot)
    before = len(group_msgs(k, outbox))
    d = say(k, "0888080463 5个")
    sent = group_msgs(k, outbox)[before:]
    assert d["result"] == "no_tool_text" and d["blocked_reply"].startswith("上一单单次补货还没处理完")
    assert len(sent) == 1 and "这个我帮不上" in sent[0] and run["order_no"] not in sent[0]
    events.flush()
    assert db.one(select(events_t).where(events_t.c.msg.like("%没调工具就直接回复%")))


def test_reply_text_cannot_claim_business_state(client, admin, outbox, fake_edge, monkeypatch):
    """reply_text 冒充业务通知(单号不在【当前状态】/ 原话里、下了「先不提交」这类结论):不发,原因交回模型,
    模型改调业务工具后由工具回复;模型不改就回固定引导语(reply_blocked)。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    errs: list[str] = []

    async def fake_cancel(system, user, tools, call):
        res = await call(*tools["reply_text"], {"text": f"好,{run['order_no']} 先不提交。"})
        errs.append(res.text)
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, fake_cancel)
    before = len(group_msgs(k, outbox))
    d = say(k, "不提交")
    assert d["result"] == "reply_blocked" and "业务结论" in errs[0]
    assert len(group_msgs(k, outbox)) == before + 1 and "这个我帮不上" in group_msgs(k, outbox)[-1]
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"          # 没有被模型「说」成取消

    async def retry(system, user, tools, call):
        res = await call(*tools["reply_text"], {"text": f"好,{run['order_no']} 先不提交。"})
        assert not res.replied
        await call(*tools["cancel_order"], {})
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, retry)
    d = say(k, "不提交")
    assert d["result"] == "tool" and k.svc().run(run["id"])["status"] == "cancelled"
    assert f"好,{run['order_no']} 先不提交。DMS 里这张单还是" in group_msgs(k, outbox)[-1]


def test_reply_text_ungrounded_number_blocked():
    """出处校验:编号 / 数字只认【当前状态】和这句原话,聊天记录里的不算;业务结论一律不行。"""
    from app.features.guards import check_reply
    g = "- 本会话现在没有进行中的单次补货。\n叶落无痕:17801F0060*1 车架号LVGBXA729LG010472"
    assert check_reply("你好,我是配件补货助手,可以帮你查库存、单次补货。", g) == ""
    assert check_reply("收到 17801F0060,要订几个?", g) == ""
    assert "S20261112001" in check_reply("采购单 S20261112001 在 DMS 里", g)
    assert "业务结论" in check_reply("上一单还没处理完,请先回「确认提交」", g)
    assert "业务结论" in check_reply("好的,已经取消", g)
    assert check_reply("单价 ¥89.30", g)


def test_incident_replay_after_hold_new_single(client, admin, outbox, fake_edge, monkeypatch):
    """事故复现:建单 → 不提交(已取消)→ 又说不提交 → 发新零件。模型看到的上下文里:【当前状态】说清上一单已结束,
    聊天记录里那几条旧通知标着「这张单现在:不订」;按意图调工具后真的新建了单次补货。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox, text="17801F0060 1个")
    say(k, "不提交")
    assert k.svc().run(run["id"])["status"] == "cancelled"
    seen = []
    from tests import fake_llm

    async def watch(system, user, tools, call):
        seen.append(user)
        hit = fake_llm.pick(fake_llm.sentence(user))
        await call(*tools[hit[0]], hit[1])
        return "__NO_REPLY__"
    _fake_llm(monkeypatch, watch)
    d = say(k, "不提交")
    assert d["result"] == "tool" and d["calls"][0]["tool"] == "cancel_order"
    assert run["order_no"] not in group_msgs(k, outbox)[-1]              # 不会再说「S… 先不提交」
    d = say(k, "17801F0060*1  车架号LVGBXA729LG010472")
    ctx = seen[-1]
    assert "本会话现在没有进行中的单次补货" in ctx and f"本会话上一张单次补货 {run['doc_no']}" in ctx and "已结束:不订" in ctx
    assert f"〔系统通知·关于单次补货 {run['doc_no']}(采购单 {run['order_no']}),这张单现在:不订" in ctx
    assert "禁止照抄" in ctx
    assert d["calls"][0]["tool"] == "single_restock" and d["calls"][0]["args"] == {"part_no": "17801F0060", "qty": 1}
    new = k.svc().single_open(k.store_id)
    assert new and new["id"] != run["id"]
    assert "LVGBXA729LG010472" not in group_msgs(k, outbox)[-1]          # 车架号不再被当成「没处理的零件」


def test_llm_call_kwargs():
    """第一轮强制选工具,之后 auto;DashScope 显式关思考(思考模式会忽略 tool_choice=required)。"""
    from app.services.agent import first_round_kwargs, llm_generate_kwargs
    tools = [{"type": "function"}]
    assert first_round_kwargs({"tools": tools}, True)["tool_choice"] == "required"
    assert "tool_choice" not in first_round_kwargs({"tools": tools}, False)
    assert "tool_choice" not in first_round_kwargs({"tools": []}, True)
    assert llm_generate_kwargs("https://dashscope.aliyuncs.com/compatible-mode/v1", 0.2) == {
        "temperature": 0.2, "extra_body": {"enable_thinking": False}}
    assert llm_generate_kwargs("https://api.openai.com/v1", 0.2) == {"temperature": 0.2}


def test_single_pending_text_while_scanning(client, admin, outbox, fake_edge):
    """上一单还在查询(还没有明细行)时又发新的:提示里也要带上零件号和数量,不能是「( ×,取数中)」。"""
    from app.core.types import Actor
    k = setup_store(client, admin)
    fake_now(hh=10)
    svc = k.svc()
    rid = svc._new_run(k.store_id, "single", "chat", Actor("planner_im", "zhangsan", "张三"), "帮我定:041520V010*10")
    msg = svc._single_pending_text(svc.run(rid))
    assert "041520V010 × 10" in msg and "( ×" not in msg


def test_submit_po_missing_from_edge_verify(client, admin, outbox, fake_edge):
    """老流程兜底:取数端提交前核对时整张单找不到(po_missing)→ 也按已删除收口。"""
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    fake_edge.po_state = "error"
    fake_edge.submit_error = EdgeError("提交前核对未通过,没有提交:DMS 采购单列表里找不到", code="po_missing")
    say(k, "确认提交")
    settle(k)
    assert k.svc().run(run["id"])["status"] == "cancelled"
    assert "在 DMS 里已经被删除" in group_msgs(k, outbox)[-1]


def test_scheduled_hold_and_expire(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    d = say(k, "不提交")                                               # 群里说不提交:定时补货只引导去页面
    assert "先不提交" in group_msgs(k, outbox)[-1] and "/m/restock/order/" in group_msgs(k, outbox)[-1]
    assert k.svc().run(run["id"])["status"] == "awaiting_submit" and d["calls"][0]["tool"] == "cancel_order"
    assert client.post(f"/api/public/restock/orders/{run['token']}/hold").status_code == 200
    assert k.svc().run(run["id"])["status"] == "cancelled"
    assert submit(client, run["token"]).status_code == 409
    assert client.post(f"/api/public/restock/orders/{run['token']}/hold").status_code == 409


def test_submit_switches(client, admin, outbox, fake_edge, switches):
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    switches(allow_submit_single=False)                              # 建单后、确认前关掉提交
    say(k, "确认提交")
    assert "单次补货的提交功能已关闭" in group_msgs(k, outbox)[-1] and "restock.submit_po" not in fake_edge.calls
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"
    blocked = audit.query(store_ids=[k.store_id], action="restock.run.submit_blocked", limit=1)[1][0]
    assert blocked["detail"]["switches"]["allow_submit_single"] is False
    switches(allow_submit_single=True)
    say(k, "确认提交")
    settle(k)
    assert k.svc().run(run["id"])["status"] == "done"
    # 建单开关:关掉单次补货的建单,回「订」不建单;定时补货不受影响
    switches(allow_create_single=False)
    say(k, "8713902280 1个")
    settle(k)
    say(k, "订")
    assert "单次补货的建单功能已关闭" in group_msgs(k, outbox)[-1]
    assert fake_edge.calls.count("restock.create_po") == 1
    # 提交开关在建单时就是关的:建好单就结束,告诉人到 DMS 人工提交
    switches(allow_submit_scheduled=False)
    run2 = push(k, hh=15, mm=30)
    assert confirm(client, run2["token"], state_of(page(client, run2["token"]))).status_code == 200
    settle(k)
    assert k.svc().run(run2["id"])["status"] == "done" and "提交功能已关闭" in group_msgs(k, outbox)[-1]


def test_submit_check_failed_then_retry(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    fake_edge.submit_error = EdgeError("DMS 检查未通过,没有提交:accountBalanceFlag=false(疑似账户余额不足)",
                                       "check_failed")
    say(k, "确认提交")
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_submit" and "疑似账户余额不足" in r["message"]
    assert "没提交成功" in group_msgs(k, outbox)[-1] and "👉 @我 再回「确认提交」" in group_msgs(k, outbox)[-1]
    assert open_alerts(k, "restock.submit_failed")
    fake_edge.submit_error = None
    clock.advance(seconds=5)
    say(k, "确认提交")
    settle(k)
    assert k.svc().run(run["id"])["status"] == "done" and fake_edge.calls.count("restock.submit_po") == 2
    assert not open_alerts(k, "restock.submit_failed")
    keys = [p for p in fake_edge.params if "expect" in p]
    assert len(keys) == 2


def test_submit_unknown_and_verify_failed(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    fake_edge.submit_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
    say(k, "确认提交")
    settle(k)
    assert k.svc().run(run["id"])["status"] == "error"
    assert open_alerts(k, "restock.submit_unknown")[0]["severity"] == "critical"
    assert "系统不会自动重试" in group_msgs(k, outbox)[-1]
    # 核对不一致(DMS 里的单被人改过):不提交,出错收口
    fake_now(d=23, hh=10)
    run2 = single_created(k, outbox, "8713902280 3个")
    fake_edge.submit_error = EdgeError("提交前核对未通过,没有提交:8713902280 建单时 3 个,DMS 现在 5 个", "verify_failed")
    say(k, "确认提交")
    settle(k)
    assert k.svc().run(run2["id"])["status"] == "error"
    assert "和建单时不一致" in group_msgs(k, outbox)[-1]


def test_recover_submitting_is_unknown(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = single_created(k, outbox)
    db.q(runs_t.update().where(runs_t.c.id == run["id"]).values(status="submitting"))
    k.call(k.svc().recover)
    assert k.svc().run(run["id"])["status"] == "error"
    assert open_alerts(k, "restock.submit_unknown")


def test_explicit_submit_words():
    """提交只认原话正好是「提交 / 确认提交」(去掉空格标点),大模型怎么选工具都绕不过去。"""
    from app.features.restock.service import explicit_submit
    assert [explicit_submit(t) for t in ("提交", "确认提交", "确认提交。", " 提 交 ")] == [True] * 4
    assert not any(explicit_submit(t) for t in ("提交吧", "可以,提交", "没问题提交", "不提交", "先不提交", "确认"))


def test_warehouse_labels():
    from app.features.restock import planner
    assert planner.wh_cn({"GTMC广州": 0, "华南GTMC": 5, "GTMC北京": 1}) == {"广州仓": 0, "华南仓": 5, "GTMC北京": 1}
    ln = planner.plan_single({"part_no": "X1234567", "name": "x", "stock": 0, "warehouses": {"GTMC广州": 0, "华南GTMC": 0},
                              "national_queried": True, "daily_surplus": 10, "unit_price": 1}, 2, "trans_shipped")
    assert ln.tag == "oos" and "关注仓(广州仓/华南仓)都没货" in ln.note


# ====================================================================== 重试 / 提醒 / 紧急 / 收口
def test_schedule_retry_remind_urgent_close(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    t = fake_now(hh=15, mm=0)
    k.heartbeat()
    fake_edge.fail_scan = 2
    k.call(k.svc().push, k.store_id, t, "15:00")
    settle(k)
    run = k.svc().current(k.store_id)
    assert run["status"] == "scan_retry" and run["trigger"] == "schedule"
    assert "10 分钟后自动重试" in group_msgs(k, outbox)[1] and "距截单 16:00 还有 60 分钟" in group_msgs(k, outbox)[1]
    assert open_alerts(k, "restock.scan_failed")
    for _ in range(2):                                          # 第 2 次失败,第 3 次成功(每 10 分钟重试一次)
        t = clock.advance(minutes=10)
        k.heartbeat()
        k.call(k.svc().tick, k.store_id, t)
        settle(k)
    run = k.svc().current(k.store_id)
    assert run["status"] == "awaiting_confirm" and run["scan_attempts"] == 3
    assert not open_alerts(k, "restock.scan_failed")
    reminders = []
    for _ in range(5):
        t = clock.advance(minutes=5)
        k.call(k.svc().tick, k.store_id, t)
        reminders = [m for m in group_msgs(k, outbox) if m.startswith("⏰ 今天的补货推荐还没确认")]
    assert len(reminders) == 3 and "第 3/3 次提醒" in reminders[-1] and "/m/restock/order/" in reminders[-1]
    clock.set_fake(dt.datetime(2026, 10, 22, 15, 46))
    k.call(k.svc().tick, k.store_id, clock.now())
    k.call(k.svc().tick, k.store_id, clock.now())
    urgent = [m for m in outbox.to(k.contact) if "今天的定时补货还没有提交" in m]
    assert len(urgent) == 1 and "紧急" in urgent[0] and "实际提交时间会超过截单时间" in urgent[0]
    # 截单只提示风险:过了截单仍可刷新 / 确认,清单不作废
    clock.set_fake(dt.datetime(2026, 10, 22, 16, 0))
    r = confirm(client, run["token"], [])
    assert r.status_code == 409 and "截单" not in r.json()["detail"] and "有效期" in r.json()["detail"]
    k.call(k.svc().close, k.store_id, clock.now(), "16:00")
    assert k.svc().run(run["id"])["status"] == "awaiting_confirm"
    assert any("已到截单时间 16:00" in m and "仍可继续确认" in m for m in group_msgs(k, outbox))
    k.heartbeat()
    assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
    settle(k)
    st = page(client, run["token"])
    assert st["can_confirm"] and "已过截单时间 16:00" in st["late_hint"]
    assert confirm(client, run["token"], state_of(st)).status_code == 200
    settle(k)
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"
    assert any("已过截单时间 16:00" in m for m in group_msgs(k, outbox) if "单建好了" in m)


def test_cutoff_hard_keeps_old_rule(client, admin, outbox, fake_edge):
    """「截单后禁止确认(旧规则)」打开:过了截单不能确认,截单时作废。"""
    k = setup_store(client, admin, cutoff_hard=True)
    run = push(k)
    clock.set_fake(dt.datetime(2026, 10, 22, 16, 0))
    r = confirm(client, run["token"], [])
    assert r.status_code == 409 and "截单" in r.json()["detail"]
    assert not page(client, run["token"])["can_refresh"]
    k.call(k.svc().close, k.store_id, clock.now(), "16:00")
    assert k.svc().run(run["id"])["status"] == "expired"
    assert any("截单时间" in m for m in group_msgs(k, outbox))


def test_stale_list_superseded_by_next_scheduled_run(client, admin, outbox, fake_edge):
    """截单只提示:昨天没确认的清单跨天不作废(群里、页面都提示是哪天的),今天生成新的定时补货单时才作废。"""
    k = setup_store(client, admin)
    old = push(k)
    fake_now(d=23, hh=10)
    k.heartbeat()
    k.call(k.svc().tick, k.store_id, clock.now())
    assert k.svc().run(old["id"])["status"] == "awaiting_confirm"
    st = page(client, old["token"])
    assert "10月22日" in st["stale_hint"] and st["can_refresh"]
    say(k, "确认")
    m = group_msgs(k, outbox)[-1]
    assert old["token"] in m and "10月22日" in m
    t = fake_now(d=23, hh=15)                                        # 23 号 15:00 新单
    k.heartbeat()
    k.call(k.svc().push, k.store_id, t, "15:00")
    settle(k)
    run = k.svc().current(k.store_id)
    assert run["id"] != old["id"] and k.svc().run(old["id"])["status"] == "superseded"
    assert any(f"之前没确认的定时补货清单 {old['doc_no']} 已作废" in x for x in group_msgs(k, outbox))


def test_drafts_listed_on_push_and_page(client, admin, outbox, fake_edge):
    """推送清单时列出 DMS 里所有待提交的采购单(含他人创建),单据页零件行标出在哪张草稿里;不参与计算。"""
    k = setup_store(client, admin)
    fake_edge.drafts = [{"order_id": "8001", "order_no": "S2026102109", "create_by": "李四",
                         "create_time": "2026-10-21 11:00:00", "doc_no": "",
                         "details": [{"part_no": "90915YZZM3", "qty": 6}]}]
    run = push(k)
    pushed = group_msgs(k, outbox)[-1]
    assert "DMS 里还有 1 张没提交的采购单(含他人创建的)" in pushed and "S2026102109 李四" in pushed
    lp = next(p for p in fake_edge.params if "max_detail" in p)
    assert lp["supplier_code"] == "APC40" and lp["since"].startswith("2026-09-22")
    st = page(client, run["token"])
    filt = next(l for l in st["lines"] if l["part_no"] == "90915YZZM3")
    assert filt["in_drafts"][0]["order_no"] == "S2026102109" and filt["final_qty"] == 18      # 不参与计算
    assert st["drafts"]["source"] == "dms"
    say(k, "补货到哪一步了")
    assert "没提交的采购单" in group_msgs(k, outbox)[-1]
    # DMS 查不了:不阻断清单,说明原因,退回本系统数据
    fake_edge.drafts_error = EdgeError("DMS 采购单列表查询失败(模拟)")
    assert client.post(f"/api/public/restock/orders/{run['token']}/cancel").status_code == 200
    assert k.call(k.svc().start, k.store_id, "console", Actor("user", "1", "店长")) == "started"
    settle(k)
    m = group_msgs(k, outbox)[-1]
    assert "补货推荐已生成" in m and "没能查到 DMS 里的待提交采购单" in m


def test_po_unknown_scheduled_auto_reconcile(client, admin, outbox, fake_edge):
    """定时补货建单结果未知:不用等人再点确认,到点系统自动到 DMS 核实;核实到就接管进入待确认提交。"""
    k = setup_store(client, admin)
    run = push(k)
    fake_edge.po_error = EdgeError("建单已成功(id=9001),但回查失败", "unknown_result", {"order_id": "9001"})
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] and r["order_id"] == "9001"
    assert any("不要到 DMS 手工重建" in m for m in group_msgs(k, outbox))
    fake_edge.po_error = None
    first = next(p for p in fake_edge.params if "lines" in p and "remark" in p)
    _tick(k, seconds=30)                                           # 没到 120 秒:不核实
    assert "restock.find_po" not in fake_edge.calls
    fake_edge.found = [_dms_po(run, first["lines"])]
    _tick(k, seconds=100)
    assert fake_edge.calls.count("restock.find_po") == 1
    fp = next(p for p in fake_edge.params if "doc_no" in p and "since" in p and "max_detail" not in p)
    assert fp["order_id"] == "9001"                                 # 先按 DMS 单据 id 找
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_submit" and r["order_no"] == "S2026102201" and r["create_unknown_at"] is None
    assert fake_edge.calls.count("restock.create_po") == 1
    assert any("上次其实已经建成采购单 S2026102201" in m for m in group_msgs(k, outbox))


def test_po_unknown_scheduled_auto_reconcile_none(client, admin, outbox, fake_edge):
    """定时补货自动核实:DMS 里没有 → 清掉标记、通知,不自动重建;之后人再确认就正常建单。"""
    k = setup_store(client, admin)
    run = push(k)
    fake_edge.po_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    fake_edge.po_error = None
    _tick(k, seconds=130)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] is None
    assert any("自动核实完成:DMS 里没有本单" in m for m in group_msgs(k, outbox))
    assert fake_edge.calls.count("restock.create_po") == 1


def test_scan_final_failure_near_cutoff(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    fake_now(hh=15, mm=28)
    k.heartbeat()
    fake_edge.fail_scan = 9
    k.call(k.svc().start, k.store_id, "console", Actor("user", "1", "店长"))
    settle(k)
    run = k.svc().current(k.store_id)
    assert run["status"] == "error"
    al = open_alerts(k, "restock.scan_failed")
    assert al and al[0]["severity"] == "critical"
    assert "已停止自动重试" in [m for m in group_msgs(k, outbox) if m.startswith("❌")][-1]


def test_edge_offline_at_push_retries(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    t = fake_now(hh=15)                                         # 设备从来没心跳 → 不在线
    k.call(k.svc().push, k.store_id, t, "15:00")
    settle(k)
    assert k.svc().current(k.store_id)["status"] == "scan_retry"
    assert any("门店取数端不在线" in m for m in group_msgs(k, outbox))
    assert fake_edge.calls == []


def _dms_po(run, lines, order_no="S2026102201", status="1"):
    """restock.find_po 命中的一张 DMS 采购单(备注以补货单号结尾)。"""
    return {"order_id": "9001", "order_no": order_no,
            "row": {"remark": "补货Agent自动创建(定时)" + run["doc_no"], "orderStatus": status, "supplierCode": "APC40",
                    "orderType": "S", "itemNum": len(lines), "totalAmount": 80.0, "createTime": "2026-10-22 15:01:00"},
            "details": [{"partNo": l["part_no"], "purchaseQty": float(l["qty"])} for l in lines]}


def test_po_unknown_reconcile_adopts_existing(client, admin, outbox, fake_edge):
    """定时补货建单结果未知:不终止、不自动重试;等够时间再确认 → 先核实,DMS 里已有就接管,不重复建单。"""
    k = setup_store(client, admin)
    run = push(k)
    fake_edge.po_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] and r["data_fetched_at"] is None
    assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "critical"
    assert any("不要到 DMS 手工重建" in m and run["doc_no"] in m for m in group_msgs(k, outbox))
    assert audit.query(store_ids=[k.store_id], action="restock.po.create_unknown", limit=1)[1]
    first = next(p for p in fake_edge.params if "lines" in p)
    assert first["remark"].endswith("(定时)" + run["doc_no"])
    fake_edge.po_error = None
    # 刷新后马上再确认:没等够 RECONCILE_WAIT_S,拒绝(防 DMS 晚落库)
    assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
    settle(k)
    resp = confirm(client, run["token"], state_of(page(client, run["token"])))
    assert resp.status_code == 409 and "秒后再确认" in resp.json()["detail"]
    rej = audit.query(store_ids=[k.store_id], action="restock.run.confirm_rejected", limit=1)[1][0]
    assert "还要等" in rej["detail"]["reason"]
    # 等够时间、刷新、再确认 → 核实命中 1 张 → 接管
    clock.advance(seconds=125)
    assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
    settle(k)
    fake_edge.found = [_dms_po(run, first["lines"])]
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_submit" and r["order_no"] == "S2026102201" and r["create_unknown_at"] is None
    assert fake_edge.calls.count("restock.create_po") == 1 and fake_edge.calls.count("restock.find_po") == 1
    fp = next(p for p in fake_edge.params if "doc_no" in p)
    assert fp["doc_no"] == run["doc_no"] and fp["supplier_code"] == "APC40"
    assert not open_alerts(k, "restock.po_unknown")
    assert any("上次其实已经建成采购单 S2026102201" in m for m in group_msgs(k, outbox))
    res = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_result", limit=1)[1][0]
    assert res["detail"]["outcome"] == "adopt" and res["detail"]["found"][0]["order_no"] == "S2026102201"
    assert audit.query(store_ids=[k.store_id], action="restock.po.adopted", limit=1)[1]
    # 接管后照常确认提交,提交前核对按 DMS 里这张单的实际明细
    assert submit(client, run["token"]).status_code == 200
    settle(k)
    assert k.svc().run(run["id"])["status"] == "done"
    sp = next(p for p in fake_edge.params if "expect" in p)
    assert sorted((x["part_no"], x["qty"]) for x in sp["expect"]["lines"]) == \
        sorted((x["part_no"], float(x["qty"])) for x in first["lines"])


BUSY = "⚠️ 系统异常,正在自动核实,暂停补货操作"


def _single_unknown(k, fake_edge, text="8713902280 2个"):
    """单次补货:回「订」后建单结果未知 → 建单异常(自动核实)。"""
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, text)
    settle(k)
    fake_edge.po_error = EdgeTimeout("取数端已领取任务,但没有回传结果", unknown=True)
    say(k, "订")
    settle(k)
    fake_edge.po_error = None
    run = k.svc().single_open(k.store_id)
    assert run["status"] == "create_unknown" and run["create_unknown_at"] and run["next_retry_at"]
    return run


def _tick(k, heartbeat=True, **advance):
    t = clock.advance(**advance)
    if heartbeat:
        k.heartbeat()
    k.call(k.svc().tick, k.store_id, t)
    settle(k)
    return t


def test_po_unknown_single_blocks_everything_then_adopts(client, admin, outbox, fake_edge):
    """单次补货建单结果未知:明确告诉会话系统异常;期间发新零件 / 订 / 确认提交 / 不订一律不执行(留痕);
    系统到点自动核实,DMS 里已有就接管,不重复建单。"""
    k = setup_store(client, admin)
    run = _single_unknown(k, fake_edge)
    assert group_msgs(k, outbox)[-1] == "⚠️ 系统异常(取数端已领取任务,但没有回传结果),正在自动核实,暂停补货操作"
    assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "error"
    assert audit.query(store_ids=[k.store_id], action="restock.po.create_unknown", limit=1)[1]
    for t in ("0888080463 5个", "订", "确认提交", "不订", "好的"):
        say(k, t, sender="lisi")
        assert group_msgs(k, outbox)[-1] == BUSY, t
        assert k.svc().run(run["id"])["status"] == "create_unknown", t
    blocked = audit.query(store_ids=[k.store_id], action="restock.run.op_blocked_unknown", limit=20)[1]
    assert sorted(b["detail"]["action"] for b in blocked) == ["cancel", "confirm", "confirm", "request", "submit"]
    assert all(b["detail"]["sender_id"] == "lisi" for b in blocked)
    assert fake_edge.calls.count("restock.quote") == 1 and fake_edge.calls.count("restock.create_po") == 1
    _tick(k, seconds=60)                                             # 没等够 RECONCILE_WAIT_S:不核实
    assert "restock.find_po" not in fake_edge.calls
    po = next(p for p in fake_edge.params if "lines" in p)
    fake_edge.found = [_dms_po(run, po["lines"])]
    _tick(k, seconds=65)                                             # 到点:系统自动核实,不用人回「订」
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_submit" and r["order_no"] == "S2026102201" and r["create_unknown_at"] is None
    assert fake_edge.calls.count("restock.find_po") == 1 and fake_edge.calls.count("restock.create_po") == 1
    assert any("上次其实已经建成采购单 S2026102201" in m for m in group_msgs(k, outbox))
    assert not open_alerts(k, "restock.po_unknown")
    res = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_result", limit=1)[1][0]
    assert res["detail"]["outcome"] == "adopt" and res["detail"]["auto"] is True and res["detail"]["attempt"] == 1
    say(k, "确认提交")                                                # 接管后照常提交
    settle(k)
    assert k.svc().run(run["id"])["status"] == "done"


def test_po_unknown_single_reconcile_none_back_to_confirm(client, admin, outbox, fake_edge):
    """自动核实 DMS 里没有:回到待确认,不自动重建;会话里再回「订」才建。"""
    k = setup_store(client, admin)
    run = _single_unknown(k, fake_edge)
    fake_edge.found = []
    _tick(k, seconds=125)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_confirm" and r["create_unknown_at"] is None
    assert group_msgs(k, outbox)[-1] == "🔎 核实完成:没有建成,需要的话 @我 回「订」"
    assert fake_edge.calls.count("restock.create_po") == 1                       # 系统异常后不自动重做写操作
    assert not open_alerts(k, "restock.po_unknown")
    say(k, "订")
    settle(k)
    r = k.svc().run(run["id"])
    assert r["status"] == "awaiting_submit" and fake_edge.calls.count("restock.create_po") == 2
    assert fake_edge.calls.count("restock.find_po") == 1                         # 已经核实清楚,再订不再核实


def test_po_unknown_reconcile_failed_retries_then_multi(client, admin, outbox, fake_edge):
    """核实失败:状态不变、不刷屏,按间隔重试并留痕;之后核实到多张 → 出错转人工,会话解锁。"""
    k = setup_store(client, admin)
    run = _single_unknown(k, fake_edge)
    n = len(group_msgs(k, outbox))
    fake_edge.find_error = EdgeError("访问 DMS 网络失败:timeout", "network")
    _tick(k, seconds=125)
    r = k.svc().run(run["id"])
    assert r["status"] == "create_unknown" and "第 1 次" in r["message"]
    assert len(group_msgs(k, outbox)) == n                                       # 核实失败不在会话里刷屏
    res = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_result", limit=1)[1][0]
    assert res["detail"]["outcome"] == "failed" and res["detail"]["attempt"] == 1 and res["detail"]["next_at"]
    _tick(k, seconds=30)                                                          # 还没到重试间隔(2 分钟)
    assert fake_edge.calls.count("restock.find_po") == 1
    fake_edge.find_error = None
    lines = [{"part_no": "8713902280", "qty": 2}]
    fake_edge.found = [_dms_po(run, lines), _dms_po(run, lines, order_no="S2026102202")]
    _tick(k, seconds=100)
    r = k.svc().run(run["id"])
    assert r["status"] == "error" and fake_edge.calls.count("restock.find_po") == 2
    assert fake_edge.calls.count("restock.create_po") == 1
    assert group_msgs(k, outbox)[-1].startswith("❌ 核实异常(DMS 里有 2 张本单的采购单") and "已转人工处理" in group_msgs(k, outbox)[-1]
    assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "critical"
    assert k.svc().single_open(k.store_id, k.target_id) is None                  # 会话解锁,可以发新单


def test_po_unknown_old_edge_cannot_reconcile(client, admin, outbox, fake_edge, monkeypatch):
    k = setup_store(client, admin)
    run = _single_unknown(k, fake_edge)
    monkeypatch.setattr(edge, "supports", lambda sid, t: t != "restock.find_po")
    _tick(k, seconds=125)
    r = k.svc().run(run["id"])
    assert r["status"] == "create_unknown" and "版本太旧" in r["message"]
    assert "restock.find_po" not in fake_edge.calls and fake_edge.calls.count("restock.create_po") == 1
    skip = audit.query(store_ids=[k.store_id], action="restock.po.reconcile_skip", limit=1)[1][0]
    assert "版本太旧" in skip["detail"]["reason"] and skip["detail"]["attempt"] == 1


def test_po_unknown_remind_and_manual_close(client, admin, outbox, fake_edge):
    """取数端一直离线、核实不了:超过设定时长提醒一次并升级告警(之后 2 小时内不再提醒);
    后台人工核实后关闭(必须填结论),会话恢复可以补货。"""
    k = setup_store(client, admin)
    run = _single_unknown(k, fake_edge)
    _tick(k, heartbeat=False, minutes=29)                                         # 取数端离线:只记日志,不提醒
    assert not any("仍在核实" in m for m in group_msgs(k, outbox))
    assert audit.query(store_ids=[k.store_id], action="restock.po.reconcile_skip", limit=1)[1]
    _tick(k, heartbeat=False, minutes=2)
    assert group_msgs(k, outbox)[-1] == "⚠️ 系统异常仍在核实(已 31 分钟),暂停补货操作"
    assert open_alerts(k, "restock.po_unknown")[0]["severity"] == "critical"
    n = len(group_msgs(k, outbox))
    _tick(k, heartbeat=False, minutes=30)
    assert len(group_msgs(k, outbox)) == n                                       # 2 小时内不重复提醒
    assert audit.query(store_ids=[k.store_id], action="restock.run.unknown_remind", limit=5)[0] == 1
    assert "restock.find_po" not in fake_edge.calls
    st = client.get(f"/api/restock/runs/{run['id']}", headers=admin).json()
    assert st["can_close_unknown"] is True
    r = client.post(f"/api/restock/runs/{run['id']}/unknown-close", json={"conclusion": " "}, headers=admin)
    assert r.status_code == 409 and "核实结论" in r.json()["detail"]
    r = client.post(f"/api/restock/runs/{run['id']}/unknown-close", json={"conclusion": "DMS 里没有这张单"},
                    headers=admin)
    assert r.status_code == 200, r.text
    r = k.svc().run(run["id"])
    assert r["status"] == "cancelled" and "人工核实后关闭:DMS 里没有这张单" in r["message"]
    assert group_msgs(k, outbox)[-1] == "✅ 已人工处理,可以继续补货"
    assert not open_alerts(k, "restock.po_unknown")
    closed = audit.query(store_ids=[k.store_id], action="restock.run.unknown_closed", limit=1)[1][0]
    assert closed["detail"]["conclusion"] == "DMS 里没有这张单"
    k.heartbeat()
    say(k, "0888080463 5个")
    settle(k)
    assert "查到 0888080463" in group_msgs(k, outbox)[-1]


def test_po_error_without_sent_flag_is_unknown(client, admin, outbox, fake_edge):
    """旧版取数端 / 请求发出后的任何错误(没有 sent=False 标记):一律按结果未知,不让直接重建。"""
    k = setup_store(client, admin)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)
    fake_edge.po_error = EdgeError("DMS 接口报错:create-parts-po 返回非 JSON(HTTP 504)", "dms_error")
    say(k, "订")
    settle(k)
    run = k.svc().single_open(k.store_id)
    assert run["status"] == "create_unknown" and run["create_unknown_at"]
    det = audit.query(store_ids=[k.store_id], action="restock.po.create_unknown", limit=1)[1][0]["detail"]
    assert det["code"] == "dms_error" and det["unknown"] is True


def test_recover_creating_single_is_unknown(client, admin, outbox, fake_edge):
    """服务重启时单次补货正在建单:进入建单异常(自动核实),不是直接出错,也不会重建。"""
    k = setup_store(client, admin)
    fake_now(d=23, hh=10)
    k.heartbeat()
    say(k, "8713902280 1个")
    settle(k)
    r2 = k.svc().single_open(k.store_id)
    db.q(runs_t.update().where(runs_t.c.id == r2["id"]).values(status="creating"))
    k.call(k.svc().recover)
    r2 = k.svc().run(r2["id"])
    assert r2["status"] == "create_unknown" and r2["create_unknown_at"]
    assert group_msgs(k, outbox)[-1].startswith("⚠️ 系统异常(服务重启时正在建单,结果未知)")


# ====================================================================== 一个会话 = 一个用户,各会话互不影响
def _second_group(k) -> dict:
    bot = k.target()["bot_ref"]
    r = k.c.post("/api/wecom/targets", json={"name": "二号群", "bot_ref": bot, "kind": "group", "contact_id": "group-b",
                                             "bot_names": "补货助手", "purposes": ["chat"]}, headers=k.h)
    assert r.status_code == 200, r.text
    from app.services import im
    return im.target(r.json()["id"])


def test_sessions_are_independent(client, admin, outbox, fake_edge):
    """两个会话各有一张单(同一个零件也行):B 会话回「订」不动 A 的单;报价、截图、回执只发回所属会话。"""
    k = setup_store(client, admin)
    b = _second_group(k)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)
    a_run = k.svc().single_open(k.store_id, k.target_id)
    assert a_run["status"] == "awaiting_confirm" and a_run["trigger_target_id"] == k.target_id
    assert not any("查到" in m for m in outbox.to("group-b"))                     # A 的报价不发到 B
    d = k.call(assistant.handle, b, "wangwu", "王五", "订")                         # B 没有单:不动 A 的
    assert "没有待确认的单次补货" in outbox.to("group-b")[-1]
    assert k.svc().run(a_run["id"])["status"] == "awaiting_confirm" and d["calls"][0]["tool"] == "confirm_order"
    k.call(assistant.handle, b, "wangwu", "王五", "8713902280 3个")                # B 订同一个零件:允许,各管各的
    settle(k)
    b_run = k.svc().single_open(k.store_id, b["id"])
    assert b_run["id"] != a_run["id"] and b_run["trigger_target_id"] == b["id"]
    assert k.svc().run(a_run["id"])["status"] == "awaiting_confirm"              # 没有被 B 的新单作废
    assert any("查到 8713902280" in m for m in outbox.to("group-b"))
    say(k, "订")
    settle(k)
    assert k.svc().run(a_run["id"])["status"] == "awaiting_submit"
    assert k.svc().run(b_run["id"])["status"] == "awaiting_confirm"
    assert any("单建好了" in m for m in group_msgs(k, outbox))
    assert not any("单建好了" in m for m in outbox.to("group-b"))
    assert {i["to"] for i in outbox.images} == {k.group}                         # 截图只发 A
    # 各自的【当前状态】只有自己会话的单
    from app.services import agent
    a_state = agent.state_text(agent._contexts(k.store_id, "zhangsan", "张三", target_id=k.target_id), "张三")
    b_state = agent.state_text(agent._contexts(k.store_id, "wangwu", "王五", target_id=b["id"]), "王五")
    assert a_run["doc_no"] in a_state and b_run["doc_no"] not in a_state
    assert b_run["doc_no"] in b_state and a_run["doc_no"] not in b_state
    assert "谁 @你 都算同一个用户" in a_state


def test_legacy_single_without_session_visible_to_all(client, admin, outbox, fake_edge):
    """上线前就在跑的老单(没记会话):本门店任何会话都能接着处理,走完即止。"""
    k = setup_store(client, admin)
    b = _second_group(k)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)
    run = k.svc().single_open(k.store_id, k.target_id)
    db.q(runs_t.update().where(runs_t.c.id == run["id"]).values(trigger_target_id=None))
    assert k.svc().single_open(k.store_id, b["id"])["id"] == run["id"]
    k.call(assistant.handle, b, "wangwu", "王五", "不订")
    assert k.svc().run(run["id"])["status"] == "cancelled"
    assert "这单不订了" in outbox.to("group-b")[-1]


def test_session_deleted_falls_back_to_broadcast(client, admin, outbox, fake_edge):
    """所属会话被删掉 / 停用:单次补货的异步消息退回发给门店所有补货对话对象,并记一条提醒。"""
    k = setup_store(client, admin)
    b = _second_group(k)
    fake_now(hh=15, mm=20)
    k.heartbeat()
    k.call(assistant.handle, b, "wangwu", "王五", "8713902280 2个")
    settle(k)
    run = k.svc().single_open(k.store_id, b["id"])
    assert any("查到 8713902280" in m for m in outbox.to("group-b"))
    assert not any("查到 8713902280" in m for m in group_msgs(k, outbox))
    assert client.delete(f"/api/wecom/targets/{b['id']}", headers=admin).status_code == 200
    assert k.call(k.svc().say, k.svc().run(run["id"]), "测试:会话删除后的异步消息")
    assert group_msgs(k, outbox)[-1] == "测试:会话删除后的异步消息"


def test_po_definite_failure_requires_refresh(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    fake_edge.po_error = EdgeError("建单前校验未通过:订购数不是包装数的整数倍", "action_error", {"sent": False})
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    st = page(client, run["token"])
    assert st["run"]["status"] == "awaiting_confirm" and not st["can_confirm"]       # 数据作废,须刷新
    assert "在页面刷新后重新确认" in group_msgs(k, outbox)[-1] and "需要人工处理" in group_msgs(k, outbox)[-1]
    fake_edge.po_error = None
    assert client.post(f"/api/public/restock/orders/{run['token']}/refresh", json={"lines": []}).status_code == 200
    settle(k)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    assert k.svc().run(run["id"])["status"] == "awaiting_submit"


# ====================================================================== 任务整体超时(页面可配)
def test_task_timeouts(client, admin, outbox, fake_edge):
    k = setup_store(client, admin, task_timeouts={"scan_base": 500, "scan_per_part": 10, "create_base": 200,
                                                  "create_per_line": 5, "screenshot_extra": 30, "outbound": 700})
    run = push(k)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    assert fake_edge.timeouts["restock.outbound"] == 700
    assert fake_edge.timeouts["restock.quote"] == 500 + 10 * 5
    assert fake_edge.timeouts["restock.create_po"] == 200 + 5 * 3
    assert fake_edge.timeouts["restock.screenshot_po"] == 30 + 2 * 90 + 180
    assert client.put("/api/restock/config", json={"values": {"task_timeouts": {"scan_per_part": 0}}},
                      headers=admin).status_code in (400, 422)


# ====================================================================== 预检
def test_preflight(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    t = fake_now(hh=14)
    k.call(k.svc().preflight, k.store_id, t, "14:00")
    assert open_alerts(k, "restock.preflight_failed") and "不在线" in outbox.to(k.contact)[-1]
    k.heartbeat()
    fake_edge.check_ok = False
    k.call(k.svc().preflight, k.store_id, clock.advance(minutes=45), "14:45")
    k.heartbeat()
    fake_edge.check_ok = True
    k.call(k.svc().preflight, k.store_id, clock.advance(minutes=1), "14:46")
    assert fake_edge.params[-1]["parts"] == [{"part_no": "019990A115", "name": "用户手册"}]    # 用 SO 常备件自检
    assert not open_alerts(k, "restock.preflight_failed")
    assert "已恢复" in outbox.to(k.contact)[-1]


# ====================================================================== 在库分类表 / SO 同步 / 留痕
def test_categories_seed_and_maintain(client, admin):
    k = setup_store(client, admin)
    r = client.get("/api/restock/categories", headers=k.h).json()
    assert r["total"] == 234 and len(r["rows"]) == 50
    assert client.get("/api/restock/categories?page=5&size=50", headers=k.h).json()["rows"][-1]["part_no"]
    assert r["counts"] == {"保养零件": 113, "机油": 7, "轮胎": 10, "养护品": 8, "钣喷件": 10, "未分类": 86}
    assert client.post("/api/restock/categories", json={"part_no": "gpdl0wm001", "name": "银粉定色剂", "category": "养护品"},
                       headers=k.h).status_code == 200
    assert next(x for x in client.get("/api/restock/categories?q=GPDL0WM001", headers=k.h).json()["rows"])["category"] == "养护品"
    r = client.post("/api/restock/categories/import",
                    json={"text": "零件号码,名称,分类\nA1,刹车片,保养零件\nB2\t机油格\t#N/A\nbad"}, headers=k.h).json()
    assert r["imported"] == 2 and len(r["errors"]) == 1
    assert next(x for x in client.get("/api/restock/categories?q=B2", headers=k.h).json()["rows"])["category"] == "未分类"
    assert client.delete("/api/restock/categories/A1", headers=k.h).status_code == 200
    assert "银粉定色剂" in client.get("/api/restock/categories.csv", headers=k.h).text
    acts = {r["action"] for r in audit.query(store_ids=[k.store_id], action="restock.category", limit=50)[1]}
    assert {"restock.category.seed", "restock.category.upsert", "restock.category.delete"} <= acts


def test_so_sync_replaces_table(client, admin, outbox, fake_edge):
    k = setup_store(client, admin, so=False)
    db.q(so_parts_t.insert().values(store_id=k.store_id, part_no="OLD", name="旧", order_count=1))
    t = fake_now(y=2026, m=11, d=2, hh=9)                      # 周一
    k.heartbeat()
    k.call(k.svc().so_sync, k.store_id, t, "09:00")
    p = next(x for x in fake_edge.params if "since" in x)
    assert p["since"] == "2026-08-02" and p["order_type"] == "S" and p["exclude_status"] == ["1"]
    parts = db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))
    assert [x["part_no"] for x in parts] == ["019990A115"]
    sync = db.one(select(so_syncs_t).where(so_syncs_t.c.store_id == k.store_id))
    assert sync["status"] == "done" and sync["filter_trusted"] is False and sync["parts"] == 1
    st = client.get("/api/restock/so", headers=k.h).json()
    assert st["schedule"] == {"weekdays": [0], "time": "09:00", "months": 3} and st["last"]["status"] == "done"
    assert st["part_count"] == 1 and not st["running"]
    lst = client.get("/api/restock/so/syncs?page=1&size=10", headers=k.h).json()
    assert lst["total"] == 1 and "stats" not in lst["rows"][0]
    assert client.get(f"/api/restock/so/syncs/{lst['rows'][0]['id']}", headers=k.h).json()["stats"]["pages"] == 18
    assert client.get("/api/restock/so/parts?q=0199", headers=k.h).json()["total"] == 1


def test_so_sync_incremental_merges_cache(client, admin, outbox, fake_edge):
    k = setup_store(client, admin, so=False)
    fake_edge.so_details = {"S1": [{"part_no": "A1", "name": "甲", "qty": 2}],
                            "S2": [{"part_no": "A1", "name": "甲", "qty": 3}, {"part_no": "B2", "name": "乙", "qty": 1}]}
    t = fake_now(y=2026, m=11, d=2, hh=9)
    k.heartbeat()
    k.call(k.svc().so_sync, k.store_id, t, "09:00")
    parts = {x["part_no"]: x for x in db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))}
    assert (parts["A1"]["order_count"], parts["A1"]["qty_sum"], parts["A1"]["last_order_no"]) == (2, 5, "S2")
    # 第二次:两张单都没变 → 不再取明细(known 带上指纹),S1 不在范围了 → 缓存删掉;新单 S3 只取它
    fake_edge.so_details = {"S2": fake_edge.so_details["S2"], "S3": [{"part_no": "C3", "name": "丙", "qty": 4}]}
    k.call(k.svc().so_sync, k.store_id, t, "09:00")
    known = [x for x in fake_edge.params if "known" in x][-1]["known"]
    assert known == {"S1": "fp-S1", "S2": "fp-S2"}
    parts = {x["part_no"]: x for x in db.rows(select(so_parts_t).where(so_parts_t.c.store_id == k.store_id))}
    assert set(parts) == {"A1", "B2", "C3"} and parts["A1"]["qty_sum"] == 3
    cached = {r["order_no"] for r in db.rows(select(so_orders_t).where(so_orders_t.c.store_id == k.store_id))}
    assert cached == {"S2", "S3"}


def test_api_calls_saved_from_task_result(client, admin):
    k = setup_store(client, admin)
    k.heartbeat()
    tid = edge.submit(k.store_id, "restock.quote", {"parts": []}, timeout=60, feature="restock", ref="restock:run:1")
    task = client.get("/api/edge/v1/tasks/next?wait=1", headers=k.eh).json()["task"]
    assert task["id"] == tid
    res = {"items": [], "api_trace_evidence": 7, "api_calls": [
        {"seq": 1, "ts": "2026-10-22 15:00:01", "endpoint": "queryByPage", "method": "POST", "status": 200,
         "code": "10000000", "message": "成功", "trace_id": "abc", "elapsed": 0.153, "rows": 1, "ok": True, "error": ""}]}
    r = client.post(f"/api/edge/v1/tasks/{tid}/result", json={"ok": True, "result": res}, headers=k.eh)
    assert r.status_code == 200, r.text
    rows = db.rows(select(api_calls_t).where(api_calls_t.c.task_id == tid))
    assert len(rows) == 1 and rows[0]["trace_id"] == "abc" and rows[0]["elapsed_ms"] == 153 and rows[0]["evidence_id"] == 7


def test_api_calls_clock_corrected(client, admin):
    """旧版取数端用本机时间记流水:本机时钟快了(流水时间晚于云端收到结果的时间)→ 整体往回挪;新版已对时的原样保存。"""
    k = setup_store(client, admin)
    clock.set_fake(dt.datetime(2026, 10, 22, 13, 40, 20))
    k.heartbeat()

    def send(res):
        tid = edge.submit(k.store_id, "restock.quote", {"parts": []}, timeout=60, feature="restock", ref="restock:run:1")
        client.get("/api/edge/v1/tasks/next?wait=1", headers=k.eh)
        assert client.post(f"/api/edge/v1/tasks/{tid}/result", json={"ok": True, "result": res},
                           headers=k.eh).status_code == 200
        return [r["ts"] for r in db.rows(select(api_calls_t).where(api_calls_t.c.task_id == tid)
                                         .order_by(api_calls_t.c.seq))]

    def call(seq, ts):
        return {"seq": seq, "ts": ts, "endpoint": "queryByPage", "method": "POST", "status": 200, "ok": True}
    calls = [call(1, "2026-10-22 13:40:22"), call(2, "2026-10-22 13:40:24")]
    assert send({"api_calls": calls}) == [dt.datetime(2026, 10, 22, 13, 40, 18), dt.datetime(2026, 10, 22, 13, 40, 20)]
    assert send({"api_calls": calls, "api_clock": "cloud"})[1] == dt.datetime(2026, 10, 22, 13, 40, 24)


def test_trace_csv(client, admin, outbox, fake_edge):
    k = setup_store(client, admin)
    run = push(k)
    assert confirm(client, run["token"], state_of(page(client, run["token"]))).status_code == 200
    settle(k)
    text = client.get("/api/restock/trace.csv", headers=k.h).text
    assert "订购量" in text and "历史常备件" in text and "默认来源" in text
    rows = k.svc().trace_rows(k.store_id, dt.date(2026, 1, 1), dt.date(2026, 12, 31))
    filt = next(r for r in rows if r["配件码"] == "90915YZZM3")
    assert (filt["订购量"], filt["采购单号"], filt["默认来源"]) == (18, "S2026102201", "推荐")
    st = page(client, run["token"])
    u = urlsplit(st["shots"][0]["url"])
    assert client.get(u.path + "?" + u.query).status_code == 200               # 带签名的公开截图链接
    assert client.get(u.path + "?sig=bad").status_code == 404


def test_config_validation_and_gating(client, admin):
    k = setup_store(client, admin)
    r = client.put("/api/restock/config", json={"values": {"push_time": "25:00"}}, headers=admin)
    assert r.status_code == 400 and "push_time" in r.json()["detail"]
    r = client.put("/api/restock/config", json={"values": {"push_time": "14:30", "confirm_valid_seconds": 90,
                                                           "so_sync_weekdays": [0, 3], "warehouses": ["GTMC广州"]}},
                   headers=admin)
    assert r.status_code == 200 and r.json()["config"]["push_time"] == "14:30"
    cfg = features.config(k.store_id, "restock")
    assert (cfg.warehouses, cfg.confirm_valid_seconds, cfg.so_sync_weekdays) == (["GTMC广州"], 90, [0, 3])
    assert client.put("/api/restock/config", json={"values": {"so_sync_weekdays": [7]}}, headers=admin).status_code == 400
    # 时间线硬冲突:推送 / 预检不早于截单就永远不会触发,保存被拒
    r = client.put("/api/restock/config", json={"values": {"push_time": "16:30"}}, headers=admin)
    assert r.status_code == 400 and "push_time" in r.json()["detail"]
    r = client.put("/api/restock/config", json={"values": {"preflight_times": ["14:00", "16:00"]}}, headers=admin)
    assert r.status_code == 400 and "preflight_times" in r.json()["detail"]
    assert client.put("/api/restock/config", json={"values": {"push_time": "16:30", "auto_push": False,
                                                           "preflight_times": ["16:00"]}},
                      headers=admin).status_code == 200                       # 关了每天自动执行就不管推送 / 预检时间
    # 每日小结须晚于截单
    r = client.put("/api/restock/config", json={"values": {"summary_time": "16:00"}}, headers=admin)
    assert r.status_code == 400 and "summary_time" in r.json()["detail"]
    assert client.put("/api/restock/config", json={"values": {"summary_time": "16:00", "summary_enabled": False}},
                      headers=admin).status_code == 200
    today = client.get("/api/restock/today", headers=admin).json()
    assert [s["kind"] for s in today["timeline"] if s["kind"] in ("preflight", "push", "summary")] == []
    # 功能开通在系统设置:只切换开通,不校验参数
    assert client.put("/api/system/features/nope", json={"enabled": False}, headers=admin).status_code == 404
    r = client.put("/api/system/features/restock", json={"enabled": False}, headers=admin)
    assert r.status_code == 200 and r.json()["features"][0]["enabled"] is False
    assert client.get("/api/system/features", headers=admin).json()[0]["enabled"] is False
    assert client.get("/api/restock/categories", headers=admin).status_code == 403
    assert client.get("/api/restock/today", headers=admin).json()["enabled"] is False
    assert features.config(k.store_id, "restock").push_time == "16:30"       # 切换开通不动参数
    assert client.put("/api/system/features/restock", json={"enabled": True}, headers=admin).status_code == 200
    assert client.get("/api/restock/categories", headers=admin).status_code == 200


def test_history_export(client, admin, monkeypatch):
    k = setup_store(client, admin)
    k.heartbeat()

    async def fake_wait(tid, timeout):
        info = edge.save_evidence(k.store_id, tid, "stock_full.csv", "配件码,库存\nA,1\n".encode(), "export", "text/csv")
        edge.db.q(edge.update(edge.tasks_t).where(edge.tasks_t.c.id == tid).values(
            status="done", result=db.jdump({"evidence": [info["id"]], "summary": {"rows": 1, "total": 1}})))
        return edge.task(tid)
    monkeypatch.setattr(edge, "wait", fake_wait)
    r = client.post("/api/restock/exports", json={"kind": "stock"}, headers=k.h)
    assert r.status_code == 200, r.text
    k.call(lambda: __import__("asyncio").sleep(0.3))
    rows = client.get("/api/restock/exports", headers=k.h).json()["rows"]
    assert rows[0]["status"] == "done" and rows[0]["files"][0]["name"] == "stock_full.csv"
    assert client.post("/api/restock/exports", json={"kind": "po"}, headers=k.h).status_code == 409   # 缺年份


# ====================================================================== 调度器:只对开通的门店、每天只触发一次、按星期
def test_scheduler_fires_once_and_respects_feature(client, admin, outbox, fake_edge):
    a = setup_store(client, admin)
    other = stores.create_store("STORE-B", "没开通补货的门店")          # 预留的多门店:没开通就不派发
    fake_now(hh=14, mm=0)
    a.heartbeat()
    a.call(scheduler.tick, True)
    a.call(scheduler.tick, True)
    marks = db.rows(select(schedule_marks_t))
    assert [(m["store_id"], m["job_key"], m["slot"]) for m in marks] == [(a.store_id, "preflight", "14:00")]
    assert fake_edge.by_store.count((a.store_id, "sys.check")) == 1
    assert not [x for x in fake_edge.by_store if x[0] == other]


def test_scheduler_auto_off_skips_preflight_and_push_keeps_close_summary(client, admin, outbox, fake_edge, monkeypatch):
    a = setup_store(client, admin, auto_push=False)
    sent = []

    async def fake_send(sid, kind, severity, title, text, **kw):
        sent.append((kind, text))
    monkeypatch.setattr(restock_service.notify, "send", fake_send)
    a.heartbeat()
    for hh, mm in ((14, 0), (15, 0), (16, 0), (16, 30)):
        fake_now(hh=hh, mm=mm)
        a.call(scheduler.tick, True)
    keys = [m["job_key"] for m in db.rows(select(schedule_marks_t).where(schedule_marks_t.c.store_id == a.store_id))]
    assert "preflight" not in keys and "push" not in keys and {"close", "summary"} <= set(keys)
    assert "sys.check" not in fake_edge.calls and db.rows(select(runs_t)) == []
    assert any(k == "restock.daily_summary" and "每天自动执行已关闭" in t for k, t in sent)


def test_scheduler_weekly_so_sync(client, admin, outbox, fake_edge):
    a = setup_store(client, admin, so=False)
    fake_now(y=2026, m=10, d=27, hh=9, mm=0)                    # 周二:不同步
    a.heartbeat()
    a.call(scheduler.tick, True)
    assert "restock.so_sync" not in fake_edge.calls
    fake_now(y=2026, m=11, d=2, hh=9, mm=1)                     # 周一 09:00 后:同步一次
    a.heartbeat()
    a.call(scheduler.tick, True)
    a.call(scheduler.tick, True)
    assert fake_edge.calls.count("restock.so_sync") == 1
    assert db.rows(select(runs_t)) == []


# ====================================================================== 后台强制终止 / 作废
def test_terminate_stops_scheduled_retry(client, admin, outbox, fake_edge):
    """取数一直失败、一直自动重试的定时补货单:后台强制终止 → 已终止,不再重试,取数告警关闭,群里有通知;之后可以重新执行。"""
    k = setup_store(client, admin)
    t = fake_now(hh=15)
    k.call(k.svc().push, k.store_id, t, "15:00")                # 取数端不在线 → 等待重试
    settle(k)
    run = k.svc().current(k.store_id)
    assert run["status"] == "scan_retry" and open_alerts(k, "restock.scan_failed")
    st = client.get(f"/api/restock/runs/{run['id']}", headers=admin).json()
    assert st["can_terminate"] and not st["can_void"]
    r = client.post(f"/api/restock/runs/{run['id']}/terminate", json={"reason": " "}, headers=admin)
    assert r.status_code == 409 and "原因" in r.json()["detail"]
    r = client.post(f"/api/restock/runs/{run['id']}/terminate", json={"reason": "取数端一直离线"}, headers=admin)
    assert r.status_code == 200, r.text
    run = k.svc().run(run["id"])
    assert run["status"] == "terminated" and run["next_retry_at"] is None and "取数端一直离线" in run["message"]
    assert run["closed_at"] is not None
    assert not open_alerts(k, "restock.scan_failed")
    last = group_msgs(k, outbox)[-1]
    assert "在后台终止(取数端一直离线)" in last and "不再自动重试" in last
    act = audit.query(store_ids=[k.store_id], action="restock.run.terminate", limit=1)[1][0]
    assert act["detail"]["before"] == "scan_retry" and act["detail"]["reason"] == "取数端一直离线"
    k.heartbeat()
    k.call(k.svc().tick, k.store_id, clock.advance(minutes=15))  # 到了原来的重试时间:不再重试
    settle(k)
    assert k.svc().run(run["id"])["status"] == "terminated" and fake_edge.calls == []
    st = client.get(f"/api/restock/runs/{run['id']}", headers=admin).json()
    assert st["stage_cn"] == "已终止" and not st["can_terminate"]
    r = client.post(f"/api/restock/runs/{run['id']}/terminate", json={"reason": "再点一次"}, headers=admin)
    assert r.status_code == 409 and "已终止" in r.json()["detail"]
    assert client.get("/api/restock/runs?status=terminated", headers=admin).json()["total"] == 1
    assert client.post("/api/restock/runs/start", headers=admin).json()["result"] == "started"   # 终止后可以重新执行
    settle(k)


def test_terminate_refused_while_creating_or_unknown(client, admin, outbox, fake_edge):
    """建单 / 提交中、建单异常、待确认提交:DMS 结果可能未知或已有草稿,不能强制终止。"""
    k = setup_store(client, admin)
    run = push(k)
    assert run["status"] == "awaiting_confirm"
    for status, word in (("creating", "不能强制终止"), ("submitting", "不能强制终止"),
                         ("create_unknown", "人工核实后关闭"), ("awaiting_submit", "先不提交")):
        db.q(runs_t.update().where(runs_t.c.id == run["id"]).values(status=status))
        r = client.post(f"/api/restock/runs/{run['id']}/terminate", json={"reason": "试试"}, headers=admin)
        assert r.status_code == 409 and word in r.json()["detail"], (status, r.json())
        assert k.svc().run(run["id"])["status"] == status
    db.q(runs_t.update().where(runs_t.c.id == run["id"]).values(status="awaiting_confirm"))
    assert client.post(f"/api/restock/runs/{run['id']}/terminate", json={"reason": "今天人工下单"},
                       headers=admin).status_code == 200
    assert page(client, run["token"])["can_confirm"] is False


def test_terminate_while_scanning_discards_result(client, admin, outbox, fake_edge):
    """取数中强制终止:取消正在跑的取数,结果不再推送。"""
    k = setup_store(client, admin)
    fake_now(hh=15)
    k.heartbeat()
    fake_edge.hang = True
    assert k.call(k.svc().start, k.store_id, "console", Actor.system("测试")) == "started"
    run = k.svc().current(k.store_id)
    assert run["status"] == "scanning"
    n = len(group_msgs(k, outbox))
    ok, msg = k.call(k.svc().terminate, run["id"], Actor("admin", "1", "管理员"), "测试终止")
    assert ok, msg
    settle(k)
    assert k.svc().run(run["id"])["status"] == "terminated"
    later = group_msgs(k, outbox)[n:]
    assert len(later) == 1 and "后台终止" in later[0]


def test_single_void_quote_and_draft(client, admin, outbox, fake_edge):
    """单次补货作废:只报了价的 → 已作废;已建 DMS 草稿的 → 不提交(草稿保留);都在会话里通知,会话可以继续发新单。"""
    k = setup_store(client, admin)
    fake_now(hh=10)
    k.heartbeat()
    say(k, "8713902280 2个")
    settle(k)
    single = k.svc().single_open(k.store_id)
    assert single["status"] == "awaiting_confirm"
    st = client.get(f"/api/restock/runs/{single['id']}", headers=admin).json()
    assert st["can_void"] and st["can_terminate"]
    r = client.post(f"/api/restock/runs/{single['id']}/void", json={"reason": "计划员说不要了"}, headers=admin)
    assert r.status_code == 200 and r.json()["message"] == "已作废"
    assert k.svc().run(single["id"])["status"] == "superseded"
    assert "在后台作废(计划员说不要了),DMS 里没有建单" in group_msgs(k, outbox)[-1]
    assert k.svc().single_open(k.store_id) is None
    say(k, "8713902280 1个")
    settle(k)
    say(k, "订")
    settle(k)
    single = k.svc().single_open(k.store_id)
    assert single["status"] == "awaiting_submit" and single["order_no"]
    r = client.post(f"/api/restock/runs/{single['id']}/terminate", json={"reason": "x"}, headers=admin)
    assert r.status_code == 409 and "不提交(保留 DMS 草稿)" in r.json()["detail"]
    r = client.post(f"/api/restock/runs/{single['id']}/void", json={"reason": "改为人工下单"}, headers=admin)
    assert r.status_code == 200 and single["order_no"] in r.json()["message"]
    run = k.svc().run(single["id"])
    assert run["status"] == "cancelled" and "DMS 草稿" in run["message"]
    assert f"DMS 草稿 {single['order_no']} 保留「待提交」" in group_msgs(k, outbox)[-1]
    assert "restock.submit_po" not in fake_edge.calls
    assert audit.query(store_ids=[k.store_id], action="restock.run.void", limit=5)[0] == 2
    sched = push(k, hh=15)
    r = client.post(f"/api/restock/runs/{sched['id']}/void", json={"reason": "x"}, headers=admin)
    assert r.status_code == 409 and "定时补货" in r.json()["detail"]