service.py 150 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 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
"""库存补货流程(确定性状态机,不依赖大模型)。单据页按钮、控制台按钮、定时任务、智能体工具都调这里。

定时补货(出库驱动;由 15:00 定时任务或后台「立即执行补货」触发,企微里不能发起 / 确认;同一天可能有定时 + 手动各一张):
  start ─▶ scanning(取数端:零件出库明细 → 按分类表 / 近 N 月 SO 单分组 → 查库存·在途·可订·全国仓)
        ─▶ awaiting_confirm(群里推一条链接;页面上填期望、勾选;取数成功起 confirm_valid_seconds 秒内有效)
             ⇄ refreshing(页面「刷新」:整条链路重跑一遍,人填的勾选 / 期望保留)
        ─▶ creating ─▶ screenshotting(DMS 页面截图失败 → 接口数据渲染兜底图 / 文字明细)
        ─▶ awaiting_submit(单据页点「确认提交」,不过期)─▶ submitting ─▶ done
  失败:scan_retry(每 N 分钟自动重试,截单前 M 分钟停止)→ error;截单 → expired;页面「今天不订」→ cancelled;
        页面「先不提交」→ cancelled(DMS 草稿保留「待提交」)
单次补货(会话里一句话「零件号 数量」):一个会话(单聊或一个群)= 一个用户,群里谁 @机器人 都算这个用户说的;
  每个会话同时只开一单(trigger_target_id),会话里的「订 / 确认提交」只可能对应这一单;各会话互不影响,消息只发回所属会话。
  single_request ─▶ scanning(查库存 / 在途 / 可订 / 广州仓·华南仓)─▶ awaiting_confirm(回「订」,不过期)
        ─▶ creating ─▶ screenshotting ─▶ awaiting_submit(@机器人 明确回「确认提交」,不过期)
        ─▶ submitting ─▶ done;待确认提交时回「订 / 好的 / 确认」不会提交(必须含「提交」)。
        回「不订」→ cancelled;回「不提交」→ cancelled(DMS 草稿保留)
  建单结果未知 → create_unknown(建单异常):会话里一切补货操作暂停;RECONCILE_WAIT_S 秒后系统自动下发 restock.find_po 核实,
        失败按技能参数 unknown_retry_min 重试:1 张 → 接管(截图 → 待确认提交);0 张 → 回到待确认(不自动重建);
        多张 / 状态异常 → error 转人工。超过技能参数 unknown_remind_min 还没核实完:告警升级 + 会话里提醒;后台可人工核实后关闭。
批量补货(会话里一次发多个「零件号 数量」,见 multi_service.py):复用单次补货的查询,结果做成单据页链接;
  multi_request ─▶ scanning ─▶ awaiting_confirm(页面勾选 / 改数量,同定时补货有效期,过期先刷新)⇄ refreshing
        ─▶ creating ─▶ screenshotting(截图放进页面)─▶ awaiting_submit(页面「确认提交」)─▶ submitting ─▶ done。
  建单结果未知同定时补货(回到待确认并标记,自动 / 再确认时先到 DMS 核实);消息只发回所属会话。
提交成功后再截一次采购单(列表「已提交」+ 详情全部页)作审计留档:只存 po.submit_shots,在后台看,不发群里。
确认提交前先下发 restock.po_status 查 DMS 里这张单现在的状态:待提交 / 已提交 → 走提交(已提交的只回查不重复提交);
  已被删除 → cancelled;其他状态(如已完成)→ done,如实回复,不提交。取数端版本不支持查询时直接走提交(提交前本来就会核对)。
定时补货建单结果未知(请求可能已到 DMS):回到 awaiting_confirm 并记 create_unknown_at,不自动重试;
  RECONCILE_WAIT_S 秒后再确认 → 先下发 restock.find_po 按采购单备注里的补货单号核实:
  1 张 → 接管(截图 → 待确认提交);0 张 → 重新建单;多张 / 状态异常 → error;核实失败 → 不建单、回到待确认。
提交:按建单时 DMS 返回的单据 id 直接提交(不在列表里找「最新一张」),取数端提交前再核对 id / 单号 / SO / 明细。
订单类型固定 SO(config.ORDER_TYPE)。业务开关(取数端运行参数):单次 / 定时各自「允许建单」「允许提交」。
DMS 相关动作全部下发给门店取数端(services.edge),这里只编排、算量、发消息、落库、留痕、告警。
审计:每次推给用户 / 刷新后的清单、用户确认时提交的清单都存快照(restock_run_snapshots);
每轮出库明细原样存(restock_outbound_rows);人每个动作写操作日志(改前 / 改后);聊天记录带 ref 关联到补货单。
"""
from __future__ import annotations

import asyncio
import csv
import datetime as dt
import io
import logging
import math
import secrets

from ... import features
from ...core import clock, db
from ...core.config import C
from ...core.db import and_, func, insert, select, update
from ...core.types import Actor, EdgeError, EdgeTimeout
from ...models import evidence_t, lines_t, outbound_rows_t, po_t, runs_t, snapshots_t
from ...services import alerts, audit, dms, edge, events, im, links, notify, settings, stores, texts
from . import categories, history, planner
from .config import ORDER_TYPE, RestockConfig
from .multi_service import MultiMixin
from .single_service import SingleMixin
from .states import (BUSY, CHAT_KINDS, CONFIRM_GRACE, ETA_SECONDS, KIND_CN, OPEN, PAGE_KINDS,  # noqa: F401
                     PUSH_WAIT_S, RECONCILE_LOOKBACK_MIN,
                     RECONCILE_WAIT_S, SCHED_RECONCILE_RETRY_MIN, SCHED_UNKNOWN_STATES, STAGE_CN, SUBMIT_EXACT,
                     SCHED_RECONCILE_DAYS, TERMINABLE, TERMINAL, TRIGGER_CN, UNKNOWN_REMIND_EVERY_MIN, VIA_CN,
                     _bool, _money, _ts, at, eta_text, explicit_submit, window_of)

log = logging.getLogger("server.restock")
KEY = "restock"
DOC_PREFIX = {"scheduled": "RP", "single": "SP", "multi": "MP"}


class RestockService(SingleMixin, MultiMixin):
    def __init__(self) -> None:
        self._locks: dict[int, asyncio.Lock] = {}
        self._bg: set[asyncio.Task] = set()
        self._reconciling: set[int] = set()        # 正在自动核实的单次补货(建单异常)
        self._reconcile_tries: dict[int, int] = {}  # 自动核实第几次(重启后从 1 重新数)
        self._submit_shooting: set[int] = set()     # 正在截「提交后截图」的补货单

    # ====================================================================== 基础
    def lock(self, sid: int) -> asyncio.Lock:
        return self._locks.setdefault(sid, asyncio.Lock())

    def cfg(self, sid: int) -> RestockConfig:
        return features.config(sid, KEY)

    def now(self, sid: int) -> dt.datetime:
        """全系统只有一个时钟:clock.now()(服务器 / 容器时区 Asia/Shanghai),和写库的 db.now() 是同一个。
        门店时区字段不再参与计算(一套系统服务一个门店,时间口径统一)。"""
        return clock.now()

    def emit(self, msg: str, level: str = "info", *, store_id: int, ref: str = "") -> None:
        events.emit(msg, level, store_id=store_id, source="flow", ref=ref)

    def audit(self, sid: int, actor: Actor, action: str, **kw) -> None:
        audit.record(sid, actor, f"restock.{action}", **kw)

    async def edge_run(self, sid: int, type: str, params: dict, **kw) -> dict:
        return await edge.run(sid, type, params, feature=KEY, dms_code=dms.primary_dms(sid), **kw)

    def spawn(self, coro, name: str = "") -> asyncio.Task:
        t = asyncio.create_task(coro, name=name or None)
        self._bg.add(t)
        t.add_done_callback(self._bg.discard)
        return t

    async def drain(self) -> None:
        """测试用:等所有后台流程跑完(包括等待期间新派生的)。
        只等还没结束的任务:已结束的直接移出集合。不能对已结束的任务反复 gather——它会立即返回、不让出事件循环,
        任务「结束后把自己移出集合」的回调就永远轮不到执行,变成死循环。"""
        while True:
            self._bg.difference_update({t for t in self._bg if t.done()})
            if not self._bg:
                return
            await asyncio.gather(*list(self._bg), return_exceptions=True)

    @staticmethod
    def ref(rid: int) -> str:
        return f"restock:run:{rid}"

    def run(self, rid: int) -> dict | None:
        return db.one(select(runs_t).where(runs_t.c.id == rid))

    def run_by_token(self, token: str) -> dict | None:
        return db.one(select(runs_t).where(runs_t.c.token == token)) if token else None

    def current(self, sid: int, day: dt.date | None = None) -> dict | None:
        """今天的定时补货单(单次补货不算)。"""
        day = day or self.now(sid).date()
        return db.one(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.biz_date == day,
                                           runs_t.c.kind == "scheduled", runs_t.c.status != "superseded")
                      .order_by(runs_t.c.id.desc()).limit(1))

    def submitted_today(self, sid: int, day: dt.date | None = None) -> bool:
        """今天有没有一张定时补货单已经走完建单(已提交,或提交开关关着、建好草稿交给人工)。"""
        return any(o["status"] == "done" for o in self.orders_today(sid, day))

    def ordered_today(self, sid: int, day: dt.date | None = None) -> dict | None:
        """今天最近一张建过单的定时补货(单次补货不算)。"""
        orders = self.orders_today(sid, day)
        return orders[-1] if orders else None

    def orders_today(self, sid: int, day: dt.date | None = None, exclude: int | None = None) -> list[dict]:
        """今天建过单的定时补货(定时 + 手动补充可能各有一张),按时间先后。"""
        day = day or self.now(sid).date()
        st = select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.biz_date == day, runs_t.c.kind == "scheduled",
                                  runs_t.c.order_no.isnot(None)).order_by(runs_t.c.id)
        if exclude:
            st = st.where(runs_t.c.id != exclude)
        return db.rows(st)

    @staticmethod
    def session_of(actor: Actor) -> int | None:
        """说这句话的会话(企微接收对象 id)。智能体收到消息时放在 actor.extra["target_id"]。"""
        tid = (actor.extra or {}).get("target_id")
        return int(tid) if tid else None

    def single_open(self, sid: int, target_id: int | None = None) -> dict | None:
        """这个会话还没走完的单次补货(查询 / 待确认 / 建单 / 建单异常 / 待确认提交 / 提交中)。每个会话同时只允许一张,
        这样会话里的「订」「确认提交」只可能对应这一张。trigger_target_id 为空的是上线前的老单,所有会话都能看到。
        target_id 不传(后台 / 测试)= 本门店最近一张,不分会话。"""
        st = select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "single", runs_t.c.status.in_(OPEN))
        if target_id:
            st = st.where((runs_t.c.trigger_target_id == target_id) | runs_t.c.trigger_target_id.is_(None))
        return db.one(st.order_by(runs_t.c.id.desc()).limit(1))

    def single_last_closed(self, sid: int, target_id: int | None, hours: int = 12) -> dict | None:
        """这个会话最近一张已结束的单次补货(最近 hours 小时内结束的)。本会话没有进行中的单时拼进【当前状态】,
        让大模型知道聊天记录里关于它的通知已经过时(被作废的报价不算:那是发了新单自动作废的)。"""
        since = db.now() - dt.timedelta(hours=hours)
        st = select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "single",
                                  runs_t.c.status.in_(tuple(s for s in TERMINAL if s != "superseded")),
                                  runs_t.c.updated_at >= since)
        if target_id:
            st = st.where(runs_t.c.trigger_target_id == target_id)
        return db.one(st.order_by(runs_t.c.id.desc()).limit(1))

    def describe_ref(self, sid: int, ref: str) -> str:
        """聊天记录里一条消息关联的补货单现在怎样了(给大模型看):「关于 SP-…(采购单 S…),这张单现在:不订(…)」。"""
        head, _, rid = (ref or "").rpartition(":")
        if head != "restock:run" or not rid.isdigit():
            return ""
        run = self.run(int(rid))
        if not run or run["store_id"] != sid:
            return ""
        po = f"(采购单 {run['order_no']})" if run.get("order_no") else ""
        stage = STAGE_CN.get(run["status"], run["status"])
        why = (run.get("message") or "").strip()
        tail = f"({why[:60]})" if run["status"] in TERMINAL and why else ""
        return f"关于{KIND_CN.get(run['kind'], '')} {run['doc_no']}{po},这张单现在:{stage}{tail}"

    def unknown_runs(self, sid: int) -> list[str]:
        """建单异常(正在自动核实)的单次补货单号。部署自检用。"""
        return [r["doc_no"] for r in db.rows(select(runs_t.c.doc_no).where(
            runs_t.c.store_id == sid, runs_t.c.kind == "single", runs_t.c.status == "create_unknown"))]

    def scheduled_awaiting_submit(self, sid: int) -> list[dict]:
        """等着在单据页确认提交的定时补货单(定时 + 手动补充可能各有一张;确认提交不过期,所以不限今天)。"""
        return db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "scheduled",
                                            runs_t.c.status == "awaiting_submit")
                       .order_by(runs_t.c.id))

    def scheduled_targets(self, sid: int) -> list[dict]:
        """群里问到定时补货时要给链接的单:所有待确认提交的 + 待确认的清单(截单只提示后,以前没确认的清单要等
        下一张定时补货单生成时才作废,所以不限今天),按先后。"""
        out = self.scheduled_awaiting_submit(sid)
        seen = {r["id"] for r in out}
        out += [r for r in db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "scheduled",
                                                        runs_t.c.status == "awaiting_confirm")) if r["id"] not in seen]
        return sorted(out, key=lambda r: r["id"])

    def scheduled_others(self, sid: int, exclude: int | None = None) -> list[dict]:
        """除了 exclude 之外还要人留意的定时补货单:今天建过采购单 / 还没走完的,加上以前没确认提交 / 没确认的。"""
        today = self.now(sid).date()
        rows = db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind == "scheduled",
                                            runs_t.c.status != "superseded").where(
            runs_t.c.status.in_(("awaiting_submit", "awaiting_confirm")) | (runs_t.c.biz_date == today))
            .order_by(runs_t.c.id))
        return [r for r in rows if r["id"] != exclude and
                (r["status"] == "awaiting_submit" or r["order_no"] or r["status"] in OPEN)]

    def link_item(self, r: dict) -> dict:
        """一张定时补货单在群消息里的一行:单号、触发方式、阶段、采购单、链接(不是今天的带上日期)。"""
        return {"doc_no": r["doc_no"], "trigger_cn": TRIGGER_CN.get(r["trigger"], ""), "stage": r["status"],
                "stage_cn": STAGE_CN.get(r["status"], r["status"]), "order_no": r["order_no"] or "",
                "biz_date": "" if r["biz_date"] == self.now(r["store_id"]).date() else str(r["biz_date"]),
                "link": self.link(r)}

    def use_link_text(self, sid: int, targets: list[dict], cancel: bool = False) -> str:
        """引导去单据页的回复:一张时给这一张的链接;两张及以上时明确提示,并把每张的链接都列出来。"""
        t = targets[-1]
        return (self.t(sid, "msg_scheduled_use_link", link=self.link(t), stage=t["status"], order_no=t["order_no"] or "",
                       items=[self.link_item(r) for r in targets], cancel=cancel)
                + self._late_tail(self.stale_hint(t)) + self._late_tail(self.late_hint(sid)))

    def po_of(self, rid: int) -> dict | None:
        return db.one(select(po_t).where(po_t.c.run_id == rid).order_by(po_t.c.id.desc()).limit(1))

    # ---------------------------------------------------------------- 未提交的采购单(只提示,不参与计算)
    def local_drafts(self, sid: int, exclude: int | None = None) -> list[dict]:
        """本系统里建了还没提交的单(定时 / 单次,不限日期)+ 近 7 天建单结果未知、还没核实清楚的单。
        DMS 查不了时就用它提示;DMS 查到时用它给 DMS 草稿标出是本系统哪张补货单。"""
        out = []
        for r in db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.status == "awaiting_submit")
                         .order_by(runs_t.c.id)):
            if r["id"] == exclude:
                continue
            po = self.po_of(r["id"]) or {}
            exp = db.jload(po.get("expect"), None) or {}
            out.append({"source": "system", "doc_no": r["doc_no"], "kind": r["kind"], "order_no": r["order_no"] or "",
                        "order_id": r["order_id"] or "", "create_by": r["triggered_by"] or "",
                        "create_time": _ts(po.get("created_at")), "unknown": False, "note": "",
                        "lines": [{"part_no": str(x.get("part_no") or "").strip().upper(), "qty": x.get("qty")}
                                  for x in exp.get("lines") or []],
                        "link": self.link(r) if r["kind"] in PAGE_KINDS else ""})
        since = self.now(sid).date() - dt.timedelta(days=7)
        for r in db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.create_unknown_at.isnot(None),
                                              runs_t.c.status.notin_(("done", "cancelled")), runs_t.c.biz_date >= since)
                         .order_by(runs_t.c.id)):
            if r["id"] == exclude:
                continue
            out.append({"source": "system", "doc_no": r["doc_no"], "kind": r["kind"], "order_no": "",
                        "order_id": r["order_id"] or "", "create_by": r["confirmed_by"] or r["triggered_by"] or "",
                        "create_time": _ts(r["create_unknown_at"]), "unknown": True, "note": "建单结果未知",
                        "lines": [{"part_no": l.part_no, "qty": l.final_qty} for l in self.lines(r["id"]) if l.orderable],
                        "link": self.link(r) if r["kind"] in PAGE_KINDS else ""})
        return out

    async def fetch_drafts(self, run: dict, cfg: RestockConfig) -> dict:
        """定时补货取数时到 DMS 查所有「待提交」的采购单(含他人在 DMS 手工建的),和本系统的未提交 / 结果未知单合并。
        只用来提示(推送消息、单据页),不参与计算;查不到也不阻断清单,只说明原因并退回本系统数据。"""
        sid = run["store_id"]
        local = self.local_drafts(sid, exclude=run["id"])
        out = {"checked_at": _ts(self.now(sid)), "source": "system", "error": "", "truncated": False,
               "filter_trusted": None, "items": []}
        rows = None
        if not edge.supports(sid, "restock.list_drafts"):
            out["error"] = "门店取数端版本还不支持查询 DMS 里的待提交采购单,下面只列本系统的单,他人在 DMS 建的请到 DMS 自查"
        else:
            since = self.now(sid) - dt.timedelta(days=cfg.drafts_lookback_days)
            try:
                r = await self.edge_run(sid, "restock.list_drafts", {
                    "supplier_code": cfg.supplier_code, "since": _ts(since), "max_detail": 50},
                    timeout=cfg.task_timeouts.submit, ref=self.ref(run["id"]), step_timeouts=cfg.step_timeouts.model_dump())
                rows = r.get("drafts") or []
                out.update(source="dms", truncated=bool(r.get("truncated")), filter_trusted=r.get("filter_trusted"))
            except (EdgeError, EdgeTimeout) as e:
                out["error"] = (f"没能查到 DMS 里的待提交采购单({str(e)[:100]}),下面只列本系统的单,"
                                "请到 DMS「采购订单管理」自查")
        if rows is None:
            out["items"] = local
            return out
        by_order = {d["order_no"]: d for d in local if d["order_no"]}
        by_doc = {d["doc_no"]: d for d in local}
        matched: set[str] = set()
        for d in rows:
            mine = by_order.get(str(d.get("order_no") or "")) or by_doc.get(str(d.get("doc_no") or ""))
            if mine:
                matched.add(mine["doc_no"])
            det = d.get("details")
            out["items"].append({
                "source": "dms", "order_no": str(d.get("order_no") or ""), "order_id": str(d.get("order_id") or ""),
                "create_by": d.get("create_by") or "", "create_time": str(d.get("create_time") or ""),
                "doc_no": (mine or {}).get("doc_no") or str(d.get("doc_no") or ""), "kind": (mine or {}).get("kind") or "",
                "unknown": bool(mine and mine["unknown"]),
                "note": "建单结果未知,DMS 里确实有这张单" if mine and mine["unknown"] else "",
                "lines": None if det is None else [{"part_no": str(x.get("part_no") or "").strip().upper(),
                                                    "qty": x.get("qty")} for x in det],
                "link": (mine or {}).get("link") or ""})
        for m in local:                         # 本系统的单在 DMS 待提交里没对上:结果未知的单独列出,其余说明可能已在 DMS 处理
            if m["doc_no"] in matched:
                continue
            out["items"].append(dict(m, note="建单结果未知,DMS 待提交里暂未找到" if m["unknown"] else
                                     "本系统记录是待确认提交,DMS 待提交里没找到(可能已在 DMS 处理过)"))
        return out

    def drafts_of(self, run: dict | None) -> dict | None:
        """这张定时补货单最近一轮取数时记下的未提交采购单。"""
        return ((db.jload((run or {}).get("outbound_stats"), None) or {}).get("drafts")) if run else None

    def drafts_for_reply(self, sid: int) -> dict:
        """群里问到定时补货时提示用:今天最近一轮取数查过 DMS 就用那份,否则只用本系统数据。"""
        cur = self.current(sid)
        d = self.drafts_of(cur)
        if d and str(d.get("checked_at", ""))[:10] == str(self.now(sid).date()):
            return d
        return {"source": "system", "error": "", "items": self.local_drafts(sid), "checked_at": ""}

    def drafts_text(self, sid: int, drafts: dict | None) -> str:
        if not drafts or not (drafts.get("items") or drafts.get("error")):
            return ""
        return self.t(sid, "drafts_hint", d=drafts)

    @staticmethod
    def draft_parts(drafts: dict | None) -> dict[str, list[dict]]:
        """零件号 → 出现在哪些未提交采购单里(单据页零件行的徽标用)。"""
        out: dict[str, list[dict]] = {}
        for it in (drafts or {}).get("items") or []:
            for ln in it.get("lines") or []:
                pn = str(ln.get("part_no") or "").strip().upper()
                if pn:
                    out.setdefault(pn, []).append({"order_no": it.get("order_no") or "", "doc_no": it.get("doc_no") or "",
                                                   "create_by": it.get("create_by") or "", "qty": ln.get("qty"),
                                                   "unknown": bool(it.get("unknown"))})
        return out

    @staticmethod
    def allowed(kind: str, action: str) -> bool:
        """取数端运行参数里的业务开关:action = create / submit。"""
        rt = settings.get("edge_runtime")
        return bool(getattr(rt, f"allow_{action}_{'scheduled' if kind == 'scheduled' else 'single'}", True))

    @staticmethod
    def switches() -> dict:
        rt = settings.get("edge_runtime")
        return {k: getattr(rt, k) for k in ("allow_create_single", "allow_submit_single", "allow_create_scheduled",
                                            "allow_submit_scheduled")}

    def _set(self, rid: int, status: str, **kw) -> None:
        if status in TERMINAL:
            kw.setdefault("closed_at", db.now())
        db.q(update(runs_t).where(runs_t.c.id == rid).values(status=status, updated_at=db.now(), **kw))
        r = self.run(rid)
        self.emit(f"{KIND_CN.get(r['kind'], '')} {r['doc_no']} → {STAGE_CN.get(status, status)}"
                  + (f"({kw['message']})" if kw.get("message") else ""), store_id=r["store_id"], ref=self.ref(rid))

    def _transition(self, rid: int, status: str, expect: tuple[str, ...], **kw) -> bool:
        """按原状态条件更新:只有当前状态在 expect 里才改成 status。异步结果(取数 / 截图完成)回来时单子可能已经被作废、
        被新单替换或被人处理过,不能把它改回去。返回是否改成功;没改成功调用方应丢弃这次结果、不再发消息。"""
        if status in TERMINAL:
            kw.setdefault("closed_at", db.now())
        n = db.q(update(runs_t).where(runs_t.c.id == rid, runs_t.c.status.in_(expect))
                 .values(status=status, updated_at=db.now(), **kw)).rowcount
        r = self.run(rid)
        if not n:
            self.emit(f"{KIND_CN.get(r['kind'], '')} {r['doc_no']} 当前是「{STAGE_CN.get(r['status'], r['status'])}」,"
                      f"不再改成「{STAGE_CN.get(status, status)}」(这次结果不再处理)", "warn", store_id=r["store_id"],
                      ref=self.ref(rid))
            return False
        self.emit(f"{KIND_CN.get(r['kind'], '')} {r['doc_no']} → {STAGE_CN.get(status, status)}"
                  + (f"({kw['message']})" if kw.get("message") else ""), store_id=r["store_id"], ref=self.ref(rid))
        return True

    def late_hint(self, sid: int, now: dt.datetime | None = None) -> str:
        """截单风险提示(截单只提示、不拦):离截单不到 urgent_before_min 分钟 / 已过截单时返回一句话,否则空串。
        关闭「每天自动执行」时不提示截单(截单相关的提醒一并关闭)。"""
        cfg = self.cfg(sid)
        if not cfg.auto_push:
            return ""
        now = now or self.now(sid)
        cut = at(now.date(), cfg.cutoff)
        if now >= cut:
            return self.t(sid, "late_hint", after=True, cutoff=cfg.cutoff, minutes=0)
        left = int(math.ceil((cut - now).total_seconds() / 60))
        if cfg.urgent_before_min and left <= cfg.urgent_before_min:
            return self.t(sid, "late_hint", after=False, cutoff=cfg.cutoff, minutes=left)
        return ""

    def stale_hint(self, run: dict) -> str:
        """不是今天的定时补货清单(截单只提示后,旧清单要等下一张定时补货单生成时才作废):提示是哪天的。"""
        if run.get("kind") != "scheduled" or run.get("status") not in ("awaiting_confirm", "refreshing", "scan_retry"):
            return ""
        if run["biz_date"] == self.now(run["store_id"]).date():
            return ""
        return self.t(run["store_id"], "stale_hint", biz_date=f"{run['biz_date']:%m月%d日}", doc=run["doc_no"])

    CHANGES_LISTED = 5

    def changes_text(self, sid: int, lines: list[planner.Line]) -> str:
        """确认消息后面的「其中改了 N 处」:改了期望,或勾选和系统默认不一样的零件,最多列 5 条;没改过返回空。"""
        changed = [l for l in lines if l.changed]
        if not changed:
            return ""
        return self.t(sid, "confirm_changes", count=len(changed), more=max(len(changed) - self.CHANGES_LISTED, 0),
                      changes=[{"name": l.name, "part_no": l.part_no, "text": l.change_text}
                               for l in changed[:self.CHANGES_LISTED]])

    @staticmethod
    def _late_tail(text: str) -> str:
        return f"\n{text}" if text else ""

    def link(self, run: dict) -> str:
        return links.public_url(f"/m/restock/order/{run['token']}")

    def t(self, sid: int, key: str, **kw) -> str:
        return texts.render(f"restock.{key}", **kw)

    def session_target(self, run: dict) -> dict | None:
        """单次 / 批量补货所属的会话(接收对象);定时补货、老单没记会话、会话已删除 / 停用 / 不再用于补货对话 → None。"""
        tid = run.get("trigger_target_id")
        if run.get("kind") not in CHAT_KINDS or not tid:
            return None
        t = im.target(int(tid))
        if t and t["store_id"] == run["store_id"] and "chat" in t["purposes"] and t["enabled"] and t.get("bot_enabled"):
            return t
        self.emit(f"{KIND_CN.get(run['kind'], '')} {run['doc_no']} 所属的企微会话已删除或停用,消息改发到门店所有补货对话对象", "warn",
                  store_id=run["store_id"], ref=self.ref(run["id"]))
        return None

    async def say(self, run: dict, text: str, at_planners: bool = False) -> bool:
        """发给这张单该通知的人:单次补货只发回所属会话;定时补货(和找不到会话的单次补货)发给门店所有补货对话对象。"""
        ref = self.ref(run["id"]) if run.get("id") else ""
        t = self.session_target(run)
        if t:
            ok, _ = await asyncio.to_thread(im.send_to, t, text, im.at_list(t) if at_planners else None, "chat", None, ref)
            return ok
        return await im.broadcast(run["store_id"], text, at_planners, ref=ref)

    async def say_image(self, run: dict, evidence_id: int) -> bool:
        ref = self.ref(run["id"])
        t = self.session_target(run)
        if t:
            ev = db.one(select(evidence_t).where(evidence_t.c.id == evidence_id))
            if not ev or ev["store_id"] != run["store_id"]:
                return False
            ok, _ = await asyncio.to_thread(im.send_image_to, t, C.data_dir / "evidence" / ev["path"],
                                            links.evidence_url(evidence_id), ref)
            return ok
        return await im.broadcast_image(run["store_id"], evidence_id, links.evidence_url(evidence_id), ref=ref)

    def lines(self, rid: int) -> list[planner.Line]:
        return self.lines_many([rid]).get(rid, [])

    def lines_many(self, rids: list[int]) -> dict[int, list[planner.Line]]:
        """一次查出多张单的清单行(列表页汇总用,避免逐张查)。"""
        out: dict[int, list[planner.Line]] = {}
        if not rids:
            return out
        for r in db.rows(select(lines_t).where(lines_t.c.run_id.in_(rids)).order_by(lines_t.c.id)):
            out.setdefault(r["run_id"], []).append(planner.Line(
                part_no=r["part_no"], name=r["name"] or "", grp=r["grp"] or "stock", category=r["category"] or "",
                so_hit=db.jload(r["so_hit"], None), outbound_qty=r["outbound_qty"] or 0,
                outbound_rows=r["outbound_rows"] or 0, stock=r["stock"] or 0, trans_shipped=r["trans_shipped"] or 0,
                unreceived=r["unreceived"] or 0, in_transit=r["in_transit"] or 0, mad=r["mad"], cap=r["cap"],
                min_qty=r["min_qty"] or 1, pack_qty=r["pack_qty"] or 1, storage_limit=r["storage_limit"],
                purchased_today=r["purchased_today"], unit_price=r["unit_price"] or 0, wh=db.jload(r["wh"], {}) or {},
                national_queried=bool(db.jload(r["wh"], {})), checked=bool(r["checked"]),
                default_expected=r["default_expected"] or 0, default_source=r["default_source"] or "recommend",
                last_expected=r["last_expected"], last_at=_ts(r["last_at"]) or None, last_by=r["last_by"] or "",
                expected=r["expected"] or 0, modified=bool(r["modified"]), suggested=r["suggested"] or 0,
                final_qty=r["final_qty"] or 0, tag=r["tag"] or "normal", note=r["note"] or "",
                error=r["error"] or "", seq=r["seq"]))
        return out

    def persist(self, rid: int, sid: int, lines: list[planner.Line]) -> None:
        with db.tx() as c:
            c.execute(lines_t.delete().where(lines_t.c.run_id == rid))
            if lines:
                c.execute(insert(lines_t), [{
                    "run_id": rid, "store_id": sid, "seq": l.seq, "part_no": l.part_no, "name": l.name[:100],
                    "grp": l.grp, "category": l.category or None, "so_hit": l.so_hit, "outbound_qty": l.outbound_qty,
                    "outbound_rows": l.outbound_rows, "mad": l.mad, "checked": l.checked,
                    "default_expected": l.default_expected, "default_source": l.default_source,
                    "last_expected": l.last_expected,
                    "last_at": dt.datetime.fromisoformat(l.last_at) if l.last_at else None,
                    "last_by": (l.last_by or "")[:80] or None, "modified": l.modified, "expected": l.expected,
                    "stock": l.stock, "trans_shipped": l.trans_shipped, "unreceived": l.unreceived,
                    "in_transit": l.in_transit, "suggested": l.suggested, "cap": l.cap, "min_qty": l.min_qty,
                    "pack_qty": l.pack_qty, "storage_limit": l.storage_limit, "purchased_today": l.purchased_today,
                    "final_qty": l.final_qty,
                    "tag": l.tag, "note": l.note[:300], "unit_price": l.unit_price, "wh": l.wh,
                    "error": l.error or None} for l in lines])

    def snapshot(self, run: dict, kind: str, lines: list[planner.Line], actor: Actor | None = None,
                 extra: dict | None = None) -> None:
        """给用户看过 / 用户提交的清单原样留存(只追加)。"""
        db.q(insert(snapshots_t).values(
            run_id=run["id"], store_id=run["store_id"], kind=kind, fetch_seq=run.get("fetch_seq"),
            data={"lines": [l.to_dict() for l in lines], "summary": planner.summary(lines), **(extra or {})},
            actor=(actor.name if actor else "")[:80] or None, ip=(actor.ip if actor else "") or None,
            created_at=db.now()))

    def _stop_at(self, sid: int, day: dt.date) -> dt.datetime:
        c = self.cfg(sid)
        return at(day, c.cutoff) - dt.timedelta(minutes=c.scan_retry_stop_before_min)

    def _new_run(self, sid: int, kind: str, trigger: str, actor: Actor, text: str = "", **kw) -> int:
        now = self.now(sid)
        n = (db.scalar(select(func.count()).select_from(runs_t).where(
            runs_t.c.store_id == sid, runs_t.c.biz_date == now.date(), runs_t.c.kind == kind)) or 0) + 1
        doc = f"{DOC_PREFIX.get(kind, 'SP')}-{now:%Y%m%d}-{sid}-{n:02d}"
        return db.q(insert(runs_t).values(
            store_id=sid, biz_date=now.date(), doc_no=doc, token=secrets.token_urlsafe(12), kind=kind,
            trigger=trigger, triggered_by=actor.name[:80],
            trigger_target_id=self.session_of(actor) if kind in CHAT_KINDS else None,
            trigger_text=(text or "")[:500],
            status="scanning", scan_attempts=0, reminder_count=0, urgent_sent=False, fetch_seq=0, refresh_count=0,
            created_at=db.now(), updated_at=db.now(), **kw)).inserted_primary_key[0]

    # ====================================================================== 定时补货 1. 触发
    async def start(self, sid: int, trigger: str, actor: Actor) -> str:
        """定时补货只能由定时推送(schedule)或后台按钮(console,手动补充)触发。

        手动补充不影响每天的定时推送:定时推送到点照常按全天出库窗口重新算一张(手动单待确认就作废它,
        手动单还在跑就等它跑完再开始);手动补充也不能作废待确认的定时单。
        截单只提示风险(cutoff_hard 关)时,旧清单不会到点作废:新的定时补货单生成时,之前日期还没确认 / 还在等重试的
        定时补货单一并作废(带建单结果未知标记的照样出现在「未提交采购单」提示里,并继续自动核实)。"""
        if trigger not in ("schedule", "console"):
            raise ValueError("定时补货只能由定时推送或后台「立即执行补货」触发")
        async with self.lock(sid):
            cfg = self.cfg(sid)
            now = self.now(sid)
            cur = self.current(sid, now.date())
            if cur and cur["status"] in BUSY:
                return "busy"
            if trigger == "console" and cur and cur["trigger"] == "schedule" and cur["status"] == "awaiting_confirm":
                return "schedule_pending"
            if cur and cur["status"] == "awaiting_confirm":
                why = "定时推送重新按全天出库计算" if trigger == "schedule" else f"{actor.name} 在后台重新执行补货"
                self._set(cur["id"], "superseded", message=f"{why},旧清单作废")
            ws, we = window_of(now.date(), cfg.window_cut)
            rid = self._new_run(sid, "scheduled", trigger, actor, window_start=ws, window_end=we)
            run = self.run(rid)
            stale = self._supersede_stale(run, actor)
            self.audit(sid, actor, "run.start", target_type="run", target_id=str(rid), ref=self.ref(rid),
                       detail={"kind": "scheduled", "trigger": trigger, "doc_no": run["doc_no"],
                               "window": [_ts(ws), _ts(we)], "superseded_stale": stale})
            self.emit(f"开始定时补货({TRIGGER_CN.get(trigger, trigger)},{actor.name}),单据 {run['doc_no']},"
                      f"出库窗口 {_ts(ws)} ~ {_ts(we)}", store_id=sid, ref=self.ref(rid))
            msg = self.t(sid, "msg_start", now=now.strftime("%H:%M"), cutoff=cfg.cutoff, trigger=trigger,
                         eta=eta_text(ETA_SECONDS))
            if stale:
                msg += "\n" + self.t(sid, "msg_stale_superseded", doc=run["doc_no"], old="、".join(stale))
            msg += self._late_tail(self.late_hint(sid, now))
            await self.say(run, msg, at_planners=trigger == "schedule")
        self.spawn(self._scan_guard(rid), f"restock-scan-{rid}")
        return "started"

    def _supersede_stale(self, run: dict, actor: Actor) -> list[str]:
        """新的定时补货单生成时,作废之前日期还没确认 / 还在等重试取数的定时补货单(调用方持锁)。返回被作废的单号。"""
        rows = db.rows(select(runs_t).where(runs_t.c.store_id == run["store_id"], runs_t.c.kind == "scheduled",
                                            runs_t.c.id != run["id"], runs_t.c.biz_date < run["biz_date"],
                                            runs_t.c.status.in_(("awaiting_confirm", "scan_retry"))).order_by(runs_t.c.id))
        out = []
        for r in rows:
            if self._transition(r["id"], "superseded", ("awaiting_confirm", "scan_retry"),
                                message=f"已有新的定时补货单 {run['doc_no']},旧清单作废"):
                out.append(r["doc_no"])
                self.audit(run["store_id"], actor, "run.supersede", target_type="run", target_id=str(r["id"]),
                           ref=self.ref(r["id"]), detail={"reason": "新的定时补货单生成", "new_doc": run["doc_no"],
                                                          "create_unknown_at": _ts(r.get("create_unknown_at"))})
        return out

    async def _scan_guard(self, rid: int, state: dict | None = None) -> None:
        try:
            await self._collect(rid, state)
        except asyncio.CancelledError:
            raise
        except (EdgeError, EdgeTimeout) as e:
            await self._scan_failed(rid, str(e), refresh=state is not None)
        except Exception as e:  # noqa: BLE001
            log.exception("补货取数出错")
            await self._scan_failed(rid, f"{type(e).__name__}: {e}", refresh=state is not None)

    def _last_values(self, sid: int, part_nos: list[str]) -> dict[str, dict]:
        """每个零件「上次人工修改」的期望值:已确认的补货单里 modified=1 的最近一行(永久保留最近一次,不做台账)。"""
        if not part_nos:
            return {}
        rows = db.rows(select(lines_t.c.part_no, lines_t.c.expected, runs_t.c.confirmed_at, runs_t.c.confirmed_by)
                       .select_from(lines_t.join(runs_t, runs_t.c.id == lines_t.c.run_id))
                       .where(and_(lines_t.c.store_id == sid, lines_t.c.part_no.in_(part_nos),
                                   lines_t.c.modified.is_(True), runs_t.c.confirmed_at.isnot(None)))
                       .order_by(runs_t.c.confirmed_at.desc()))
        out = {}
        for r in rows:
            out.setdefault(r["part_no"], {"expected": r["expected"], "at": r["confirmed_at"],
                                          "by": r["confirmed_by"] or ""})
        return out

    async def _collect(self, rid: int, state: dict | None = None) -> None:
        """定时补货取数(首次 / 刷新都整条链路重跑):出库明细 → 分组 → 查库存·在途·可订·全国仓 → 算量 → 快照。
        state:刷新时页面带上来的人工填写 {part_no: {checked, expected, modified}},重算后保留。"""
        run = self.run(rid)
        sid = run["store_id"]
        cfg = self.cfg(sid)
        ref = self.ref(rid)
        refresh = state is not None
        attempt = (run["scan_attempts"] or 0) + (0 if refresh else 1)
        db.q(update(runs_t).where(runs_t.c.id == rid).values(status="refreshing" if refresh else "scanning",
                                                             scan_attempts=attempt, next_retry_at=None,
                                                             updated_at=db.now()))
        online, info = await edge.wait_online(sid, 30)
        if not online:
            age = info.get("last_seen_age")
            raise EdgeError("门店取数端不在线" + (f"(最后联系 {int(age // 60)} 分钟前)" if age else
                                             "(还没有连接过云端)" if not info.get("registered") else ""))
        seq = (run["fetch_seq"] or 0) + 1
        # 1) 零件出库明细
        ob = await self.edge_run(sid, "restock.outbound", {
            "window_start": _ts(run["window_start"]), "window_end": _ts(run["window_end"]),
            "pure_label": cfg.pure_label, "known_mfr": cfg.known_mfr},
            timeout=cfg.task_timeouts.outbound, ref=ref, step_timeouts=cfg.step_timeouts.model_dump())
        stats, recon = ob.get("stats") or {}, ob.get("reconcile") or {}
        self._save_outbound(run, seq, ob.get("rows") or [])
        self.emit(ob.get("message") or "出库明细已取回", store_id=sid, ref=ref)
        if stats.get("unknown_mfr"):
            await alerts.open_alert(sid, "restock.unknown_mfr", f"day:{run['biz_date']}", "warn",
                                    "出库明细里出现未知的厂家分类",
                                    f"补货单 {run['doc_no']}:厂家分类出现 {'、'.join(stats['unknown_mfr'])}"
                                    f"(分布 {stats.get('mfr_counts')}),这些行没有参与补货,请核对「纯牌」的取值配置。")
        if recon and not recon.get("ok"):
            await alerts.open_alert(sid, "restock.outbound_mismatch", f"run:{rid}", "warn", "出库明细对账不一致",
                                    f"补货单 {run['doc_no']}:{recon}(明细金额合计与 DMS 合计接口不一致,可能漏页)")
        # 2) 分组:在库分类表(常备分类)∪ 近 N 个月 SO 单
        cats, so = categories.mapping(sid), history.mapping(sid)
        cand = [p for p in ob.get("parts") or [] if float(p.get("qty") or 0) > 0]
        lines = []
        for p in cand:
            pn = str(p["part_no"]).strip().upper()
            cat, hit = cats.get(pn, ""), so.get(pn)
            grp = "stock" if (cat in cfg.stock_categories or hit) else "other"
            lines.append(planner.Line(part_no=pn, name=p.get("name") or "", grp=grp, category=cat, so_hit=hit,
                                      outbound_qty=float(p.get("qty") or 0), outbound_rows=int(p.get("rows") or 0),
                                      checked=grp == "stock"))
        # 刷新:保留人工勾选 / 修改
        st = state or {}
        for l in lines:
            s = st.get(l.part_no)
            if s:
                l.checked = _bool(s.get("checked"))
                if _bool(s.get("modified")) and s.get("expected") is not None:
                    l.modified, l.expected = True, max(int(s["expected"]), 0)
        # 3) 查库存 / 在途 / 可订 / 全国仓(常备件和已勾选的件查全国仓)
        items = {}
        if lines:
            q = await self.edge_run(sid, "restock.quote", {
                "parts": [{"part_no": l.part_no, "name": l.name, "national": l.grp == "stock" or l.checked}
                          for l in lines],
                "warehouses": cfg.warehouses, "supplier_code": cfg.supplier_code, "order_type": ORDER_TYPE,
                "in_transit_field": cfg.in_transit_field},
                timeout=cfg.task_timeouts.scan(len(lines)), ref=ref, step_timeouts=cfg.step_timeouts.model_dump())
            items = {str(it.get("part_no")).strip().upper(): it for it in q.get("items") or []}
        # 4) DMS 里所有「待提交」的采购单(含他人创建):只提示,不参与计算;查不到不阻断清单
        try:
            drafts = await self.fetch_drafts(run, cfg)
        except Exception as e:  # noqa: BLE001
            log.exception("查询未提交采购单出错")
            drafts = {"checked_at": _ts(self.now(sid)), "source": "system", "items": [],
                      "error": f"查询未提交采购单出错({type(e).__name__}),请到 DMS「采购订单管理」自查"}
        last = self._last_values(sid, [l.part_no for l in lines])
        for l in lines:
            planner.fill_facts(l, items.get(l.part_no) or {"error": "取数端没有返回这个零件"}, cfg.in_transit_field)
            lv = last.get(l.part_no)
            if lv:
                l.last_expected, l.last_at, l.last_by = lv["expected"], _ts(lv["at"]), lv["by"]
            planner.apply_defaults(l)
            planner.compute(l)
        planner.number(lines)
        self.persist(rid, sid, lines)
        db.q(update(runs_t).where(runs_t.c.id == rid).values(
            fetch_seq=seq, data_fetched_at=self.now(sid), outbound_stats=dict(stats, reconcile=recon, drafts=drafts),
            message=None))
        run = self.run(rid)
        self.snapshot(run, "refreshed" if refresh else "pushed", lines,
                      extra={"window": [_ts(run["window_start"]), _ts(run["window_end"])], "outbound": stats,
                             "reconcile": recon, "kept_state": st, "drafts": drafts})
        for l in lines:
            self.emit(f"[{planner.GROUP_LABEL.get(l.grp)}] {l.name} {l.part_no}:出库 {l.outbound_qty:g},库存 {l.stock:g},"
                      f"在途 {l.in_transit:g},期望 {l.expected}({l.source_label})→ 补 {l.final_qty}"
                      + (f"({l.note})" if l.note else ""), "error" if l.error else "info", store_id=sid, ref=ref)
        s = planner.summary(lines)
        await alerts.resolve_alert(sid, "restock.scan_failed", f"day:{run['biz_date']}", "取数已成功")
        if s["errors"] and len(s["errors"]) / max(1, s["total"]) >= cfg.query_fail_alert_ratio:
            await alerts.open_alert(sid, "restock.query_failed", f"run:{rid}", "warn", "部分零件查询失败",
                                    f"补货单 {run['doc_no']}:{len(s['errors'])}/{s['total']} 个零件查询失败:"
                                    + "、".join(s["errors"][:10]))
        # 收尾按原状态条件更新:取数期间单子被作废 / 被新单替换的,结果丢弃、不再推消息
        if refresh:
            self._transition(rid, "awaiting_confirm", ("refreshing",))
            return
        if not lines:
            if self._transition(rid, "done", ("scanning",), message="窗口内没有纯牌零件出库,不用补货",
                                listed_at=db.now()):
                await self.say(run, self.t(sid, "msg_no_candidates", window=self.window_text(run), stats=stats))
            return
        if not self._transition(rid, "awaiting_confirm", ("scanning",), listed_at=db.now()):
            return
        # DMS 里还有没提交的采购单(含他人创建、本系统建单结果未知的):醒目提示,不参与计算
        await self.say(run, self.t(sid, "msg_list", window=self.window_text(run), s=s, link=self.link(run),
                                   cutoff=cfg.cutoff) + self._late_tail(self.drafts_text(sid, drafts))
                       + self._late_tail(self.late_hint(sid)), at_planners=True)

    def window_text(self, run: dict) -> str:
        ws, we = run.get("window_start"), run.get("window_end")
        return f"{ws:%m/%d %H:%M} — {we:%m/%d %H:%M}" if ws and we else ""

    def _save_outbound(self, run: dict, seq: int, rows: list[dict]) -> None:
        if not rows:
            return

        def f(v):
            try:
                return float(v)
            except (TypeError, ValueError):
                return None
        with db.tx() as c:
            c.execute(insert(outbound_rows_t), [{
                "run_id": run["id"], "store_id": run["store_id"], "fetch_seq": seq, "ship_id": str(r.get("id") or "")[:40],
                "shipment_date": str(r.get("shipmentDate") or "")[:20], "work_order_no": (r.get("workOrderNo") or "")[:40],
                "shipment_batch_no": (r.get("shipmentBatchNo") or "")[:40],
                "license_plate": (r.get("licensePlateNumber") or "")[:20], "mfr": (r.get("mfr") or "")[:20],
                "part_no": (r.get("partNo") or "")[:40], "part_name": (r.get("partName") or "")[:100],
                "settl_status": str(r.get("settlStatus") or "")[:10], "qty": f(r.get("reqQty")),
                "unit_price": f(r.get("partUnitPrice")), "amount": f(r.get("totalAmount")),
                "cost_price": f(r.get("costPrice")), "cost_amount": f(r.get("totalCostPrice")), "raw": r} for r in rows])

    async def _scan_failed(self, rid: int, reason: str, refresh: bool = False) -> None:
        run = self.run(rid)
        sid = run["store_id"]
        cfg = self.cfg(sid)
        if run["status"] in TERMINAL:
            return
        if run["kind"] in CHAT_KINDS and not refresh:      # 单次 / 批量补货查询失败:结束,请对方重新发
            self._set(rid, "error", message=reason[:500])
            await self.say(run, self.t(sid, "msg_single_failed", reason=reason[:200]))
            return
        if refresh:
            # 刷新失败:回到待确认,但数据时间不变(已过期),页面提示再刷新
            if self._transition(rid, "awaiting_confirm", ("refreshing",), message="刷新失败:" + reason[:400]):
                self.audit(sid, Actor.system(), "run.refresh_failed", target_type="run", target_id=str(rid),
                           ref=self.ref(rid), detail={"reason": reason})
            return
        now = self.now(sid)
        nxt = now + dt.timedelta(minutes=cfg.scan_retry_interval_min)
        stop_at = self._stop_at(sid, run["biz_date"])
        key = f"day:{run['biz_date']}"
        cut = at(now.date(), cfg.cutoff)
        left_min = int(math.ceil((cut - now).total_seconds() / 60)) if cfg.auto_push and now < cut else None
        if nxt < stop_at:
            if not self._transition(rid, "scan_retry", ("scanning",), message=reason[:500], next_retry_at=nxt):
                return
            await self.say(run, self.t(sid, "msg_retry", reason=reason[:200], minutes=cfg.scan_retry_interval_min,
                                       attempt=run["scan_attempts"] or 1, stop_at=stop_at.strftime("%H:%M"),
                                       left_min=left_min, cutoff=cfg.cutoff,
                                       tight=left_min is not None and left_min <= 30), at_planners=True)
            await alerts.open_alert(sid, "restock.scan_failed", key, "error", "补货取数失败(自动重试中)",
                                    f"补货单 {run['doc_no']} 第 {run['scan_attempts'] or 1} 次取数失败:{reason}\n"
                                    f"{cfg.scan_retry_interval_min} 分钟后自动重试,{stop_at:%H:%M} 前一直重试。")
        else:
            if not self._transition(rid, "error", ("scanning",), message=reason[:500]):
                return
            await self.say(run, self.t(sid, "msg_scan_failed", reason=reason[:200], late=self.late_hint(sid, now)),
                           at_planners=True)
            await alerts.open_alert(sid, "restock.scan_failed", key, "critical", "补货取数失败,需要人工介入",
                                    f"补货单 {run['doc_no']} 取数失败且已停止自动重试:{reason}\n"
                                    f"截单时间 {cfg.cutoff}。请检查门店电脑和取数端,或在后台「立即执行补货」重跑;"
                                    "来不及的话请直接到 DMS 下单。")

    # ====================================================================== 定时补货 2. 页面:刷新 / 确认 / 不订
    def seconds_left(self, run: dict) -> int:
        """离确认有效期结束还有几秒(没取过数 / 已过期为 0)。"""
        if not run.get("data_fetched_at"):
            return 0
        sid = run["store_id"]
        valid = self.cfg(sid).confirm_valid_seconds
        return max(0, int(valid - (self.now(sid) - run["data_fetched_at"]).total_seconds()))

    @staticmethod
    def _state_of(raw: list[dict] | None) -> dict:
        out = {}
        for x in raw or []:
            pn = str(x.get("part_no") or "").strip().upper()
            if pn:
                out[pn] = {"checked": _bool(x.get("checked")), "expected": x.get("expected"),
                           "modified": _bool(x.get("modified"))}
        return out

    async def refresh(self, token: str, actor: Actor, raw_state: list[dict] | None) -> tuple[bool, str]:
        run = self.run_by_token(token)
        if not run or run["kind"] not in PAGE_KINDS:
            return False, "单据不存在"
        sid = run["store_id"]
        async with self.lock(sid):
            run = self.run(run["id"])
            if run["status"] != "awaiting_confirm":
                return False, f"这张单当前不能刷新({STAGE_CN.get(run['status'], run['status'])})"
            cfg = self.cfg(sid)
            now = self.now(sid)
            if run["kind"] == "scheduled" and self._after_cutoff_blocked(run, cfg, now):
                return False, self.t(sid, "msg_after_cutoff", cutoff=cfg.cutoff)
            state = self._state_of(raw_state)
            db.q(update(runs_t).where(runs_t.c.id == run["id"]).values(
                status="refreshing", refresh_count=(run["refresh_count"] or 0) + 1, updated_at=db.now()))
            self.audit(sid, actor, "run.refresh", target_type="run", target_id=str(run["id"]), ref=self.ref(run["id"]),
                       detail={"seconds_left": self.seconds_left(run), "state": state,
                               "refresh_count": (run["refresh_count"] or 0) + 1})
            what = ("重新查库存 / 在途 / 可订 / 全国仓" if run["kind"] == "multi" else
                    "整条链路重新取数(出库明细 → 库存 / 在途 / 可订 / 全国仓)")
            self.emit(f"{actor.name} 点了刷新:{what}", store_id=sid, ref=self.ref(run["id"]))
        if run["kind"] == "multi":
            self.spawn(self._multi_guard(run["id"], state=state, refresh=True), f"restock-refresh-{run['id']}")
        else:
            self.spawn(self._scan_guard(run["id"], state), f"restock-refresh-{run['id']}")
        return True, "正在重新取数"

    async def confirm(self, token: str, actor: Actor, via: str, raw_state: list[dict] | None) -> tuple[bool, str]:
        """页面确认:服务端校验有效期(取数成功后 confirm_valid_seconds 秒内),按页面提交的勾选 / 期望重算后建单。
        批量补货的「期望」就是数量(planner.compute 按 grp 转给 compute_multi),不能超过单个零件的数量上限。"""
        run = self.run_by_token(token)
        if not run or run["kind"] not in PAGE_KINDS:
            return False, "单据不存在"
        sid = run["store_id"]
        async with self.lock(sid):
            cfg = self.cfg(sid)
            now = self.now(sid)
            run = self.run(run["id"])
            if run["status"] != "awaiting_confirm":
                return False, f"这张清单当前不能确认({STAGE_CN.get(run['status'], run['status'])})"
            if run["kind"] == "scheduled" and self._after_cutoff_blocked(run, cfg, now):
                return False, self.t(sid, "msg_after_cutoff", cutoff=cfg.cutoff)
            age = (now - run["data_fetched_at"]).total_seconds() if run["data_fetched_at"] else 1e9
            if age > cfg.confirm_valid_seconds + CONFIRM_GRACE:
                self.audit(sid, actor, "run.confirm_rejected", target_type="run", target_id=str(run["id"]),
                           ref=self.ref(run["id"]), detail={"reason": "expired", "age_seconds": round(age, 1)})
                return False, (f"库存数据是 {int(age)} 秒前取的,已超过 {cfg.confirm_valid_seconds} 秒有效期,"
                               "请先刷新重新计算再确认")
            state = self._state_of(raw_state)
            lines = self.lines(run["id"])
            changes = []
            for l in lines:
                s = state.get(l.part_no)
                if s is None:
                    continue
                before = {"checked": l.checked, "expected": l.expected, "modified": l.modified}
                l.checked = s["checked"]
                exp = s.get("expected")
                if exp is not None and str(exp).strip() != "":
                    exp = max(int(float(exp)), 0)
                    l.modified = s["modified"] or exp != l.default_expected
                    l.expected = exp if l.modified else l.default_expected
                planner.compute(l)
                after = {"checked": l.checked, "expected": l.expected, "modified": l.modified}
                if before != after:
                    changes.append({"part_no": l.part_no, "name": l.name, "grp": l.grp, "before": before,
                                    "after": after, "default_expected": l.default_expected,
                                    "default_source": l.default_source, "final_qty": l.final_qty})
            planner.number(lines)
            if run["kind"] == "multi":
                top = self.single_cfg(sid).max_qty
                over = [f"{l.part_no} × {l.expected}" for l in lines if l.checked and (l.expected or 0) > top]
                if over:
                    return False, f"{'、'.join(over)} 超过单个零件的数量上限 {top} 个,请改小数量再确认"
            ok = [l for l in lines if l.orderable]
            if not ok:
                self.persist(run["id"], sid, lines)
                return False, ("没有要订的零件(都没勾选、数量为 0 或今天订不了);不订的话请点「不订了」"
                               if run["kind"] == "multi" else
                               "没有要订的零件(都没勾选、填了 0 或库存够用);如果今天不订,请点「今天不订」")
            if not self.allowed(run["kind"], "create"):
                self.audit(sid, actor, "run.create_blocked", target_type="run", target_id=str(run["id"]),
                           ref=self.ref(run["id"]), detail={"via": via, "switches": self.switches()})
                return False, self.t(sid, "msg_create_disabled", kind_cn=KIND_CN[run["kind"]])
            if not edge.online(sid)[0]:
                return False, ("门店取数端不在线,暂时不能建单(已通知运维)。需要人工介入:请检查门店电脑和取数端是否开机、联网;"
                               "来不及的话请直接到 DMS 下单")
            gate = self._reconcile_gate(run, actor, via)
            if gate:
                self.persist(run["id"], sid, lines)
                return False, gate
            self.persist(run["id"], sid, lines)
            self._set(run["id"], "creating", confirmed_by=actor.name[:80], confirmed_via=via, confirmed_at=db.now())
            s = planner.summary(lines)
            run = self.run(run["id"])
            self.snapshot(run, "confirmed", lines, actor, extra={"submitted": state, "changes": changes,
                                                                 "age_seconds": round(age, 1)})
            self.audit(sid, actor, "run.confirm", target_type="run", target_id=str(run["id"]), ref=self.ref(run["id"]),
                       detail={"via": via, "age_seconds": round(age, 1), "changes": changes,
                               "order_count": s["order_count"], "order_qty": s["order_qty"], "amount": s["amount"],
                               "lines": [{"part_no": l.part_no, "name": l.name, "grp": l.grp, "expected": l.expected,
                                          "source": l.source_label, "stock": l.stock, "in_transit": l.in_transit,
                                          "qty": l.final_qty} for l in ok]})
        await self.say(run, self.t(sid, "msg_confirmed", s=s, by=actor.name, eta=eta_text(ETA_SECONDS))
                       + self._late_tail(self.changes_text(sid, lines))
                       + self._late_tail(self.late_hint(sid) if run["kind"] == "scheduled" else ""))
        self.spawn(self._create_guard(run["id"]), f"restock-create-{run['id']}")
        return True, "已确认,正在 DMS 建单"

    @staticmethod
    def _after_cutoff_blocked(run: dict, cfg: RestockConfig, now: dt.datetime) -> bool:
        """旧规则(cutoff_hard 打开):过了截单 / 不是当天的清单不能刷新、确认。默认截单只提示风险,不拦。"""
        return bool(cfg.cutoff_hard) and (now >= at(run["biz_date"], cfg.cutoff) or now.date() != run["biz_date"])

    async def cancel(self, token: str, actor: Actor, via: str) -> tuple[bool, str]:
        run = self.run_by_token(token)
        if not run:
            return False, "单据不存在"
        sid = run["store_id"]
        async with self.lock(sid):
            run = self.run(run["id"])
            if run["status"] == "awaiting_submit":
                return await self._hold(run, actor, via)
            if run["status"] != "awaiting_confirm":
                return False, "当前没有待确认的补货清单"
            self._set(run["id"], "cancelled", message=f"{actor.name}:不订")
            self.audit(sid, actor, "run.cancel", target_type="run", target_id=str(run["id"]),
                       ref=self.ref(run["id"]), detail={"via": via, "text": actor.extra.get("text", ""),
                                                        "create_unknown_at": _ts(run.get("create_unknown_at"))})
        key = {"scheduled": "msg_cancelled", "multi": "msg_multi_cancelled"}.get(run["kind"], "msg_single_cancelled")
        await self.say(run, self.t(sid, key, doc=run["doc_no"]))
        if run.get("create_unknown_at"):               # 之前有一次建单结果未知:DMS 里可能已经有单,告警不关,提醒人工核实
            await self.say(run, self.t(sid, "msg_unknown_left", doc=run["doc_no"]))
        if run["kind"] == "scheduled":
            await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}", "计划员确认今天不订")
        return True, "已取消"

    # ====================================================================== 后台:强制终止 / 作废
    def _cancel_bg(self, rid: int) -> int:
        """取消这张单在本进程里正在跑的取数 / 刷新 / 单次查询(建单、提交、核实不在这里取消)。返回取消了几个。"""
        names = {f"restock-scan-{rid}", f"restock-refresh-{rid}", f"restock-single-{rid}", f"restock-multi-{rid}"}
        n = 0
        for task in list(self._bg):
            if task.get_name() in names and not task.done():
                task.cancel()
                n += 1
        return n

    def _not_terminable(self, run: dict) -> str:
        st = run["status"]
        if st in TERMINAL:
            return f"这张单已经是「{STAGE_CN.get(st, st)}」,不用再操作"
        if st == "create_unknown":
            return "建单异常:DMS 里可能已经建成,不能强制终止。请先到 DMS 按备注单号核实,再点「人工核实后关闭」"
        if st == "awaiting_submit":
            return ("已经在 DMS 建好采购单、等确认提交:" + ("请在单据页点「先不提交」" if run["kind"] in PAGE_KINDS
                                                         else "请用「不提交(保留 DMS 草稿)」"))
        return f"正在{STAGE_CN.get(st, st)},DMS 那边的结果可能还不确定,不能强制终止;等这一步结束后再操作"

    async def terminate(self, rid: int, actor: Actor, reason: str) -> tuple[bool, str]:
        """后台「强制终止」:取数中 / 取数失败等待重试 / 刷新中 / 待确认(单次补货:查询中 / 待确认)的单直接结束为
        terminated,不再自动重试;取消正在跑的取数,作废取数端还没领走的任务,关掉这张单的取数告警,在会话里通知。
        建单 / 截图 / 提交中、建单异常、待确认提交的不能强停(DMS 结果可能未知或已有草稿)。"""
        reason = (reason or "").strip()
        if not reason:
            return False, "请填写终止原因"
        run = self.run(rid)
        if not run:
            return False, "单据不存在"
        sid = run["store_id"]
        async with self.lock(sid):
            run = self.run(rid)
            allowed = TERMINABLE.get(run["kind"], ())
            if run["status"] not in allowed:
                return False, self._not_terminable(run)
            if not self._transition(rid, "terminated", allowed, message=f"{actor.name} 后台强制终止:{reason}"[:500],
                                    next_retry_at=None):
                return False, "单子状态刚刚变了,请刷新后再看"
            stopped = self._cancel_bg(rid)
            expired = edge.expire_queued(sid, self.ref(rid), f"补货单 {run['doc_no']} 已在后台强制终止")
            self.audit(sid, actor, "run.terminate", target_type="run", target_id=str(rid), ref=self.ref(rid),
                       detail={"reason": reason, "before": run["status"], "scan_attempts": run["scan_attempts"],
                               "stopped_tasks": stopped, "expired_edge_tasks": expired, "ip": actor.ip,
                               "create_unknown_at": _ts(run.get("create_unknown_at"))})
        why = f"{actor.name} 后台强制终止 {run['doc_no']}:{reason}"
        await alerts.resolve_alert(sid, "restock.scan_failed", f"day:{run['biz_date']}", why)
        await alerts.resolve_alert(sid, "restock.query_failed", f"run:{rid}", why)
        if run["kind"] == "scheduled":
            await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}", why)
        await self.say(run, self.t(sid, "msg_terminated", doc=run["doc_no"], by=actor.name, reason=reason,
                                   kind=run["kind"], kind_cn=KIND_CN.get(run["kind"], "")))
        if run.get("create_unknown_at"):               # 之前有一次建单结果未知:DMS 里可能已经有单,提醒人工核实
            await self.say(run, self.t(sid, "msg_unknown_left", doc=run["doc_no"]))
        return True, "已强制终止,不会再自动重试"

    async def void(self, rid: int, actor: Actor, reason: str) -> tuple[bool, str]:
        """后台「作废」单次补货:查询中 → 同强制终止;待确认(只报了价,DMS 里没有单)→ superseded 已作废;
        待确认提交(DMS 已建草稿)→ 不提交(cancelled,DMS 草稿保留「待提交」)。都在所属会话里通知。"""
        reason = (reason or "").strip()
        if not reason:
            return False, "请填写作废原因"
        run = self.run(rid)
        if not run:
            return False, "单据不存在"
        if run["kind"] not in CHAT_KINDS:
            return False, "定时补货请用「今天不订」或「强制终止」"
        if run["status"] in ("scanning", "refreshing"):
            return await self.terminate(rid, actor, reason)
        sid = run["store_id"]
        async with self.lock(sid):
            run = self.run(rid)
            order_no = ""
            if run["status"] == "awaiting_confirm":
                ok = self._transition(rid, "superseded", ("awaiting_confirm",),
                                      message=f"{actor.name} 后台作废:{reason}"[:500])
            elif run["status"] == "awaiting_submit":
                order_no = run["order_no"] or ""
                ok = self._transition(rid, "cancelled", ("awaiting_submit",),
                                      message=f"{actor.name} 后台作废、不提交(DMS 草稿 {order_no} 保留待提交):{reason}"[:500])
            else:
                return False, self._not_terminable(run)
            if not ok:
                return False, "单子状态刚刚变了,请刷新后再看"
            self.audit(sid, actor, "run.void", target_type="run", target_id=str(rid), ref=self.ref(rid),
                       detail={"reason": reason, "before": run["status"], "order_no": order_no,
                               "order_id": run["order_id"] or "", "ip": actor.ip})
        await self.say(run, self.t(sid, "msg_voided", doc=run["doc_no"], by=actor.name, reason=reason, order_no=order_no))
        return True, "已作废" + (f",DMS 草稿 {order_no} 保留待提交" if order_no else "")

    def page_event(self, token: str, actor: Actor, kind: str, detail: dict) -> bool:
        """单据页埋点(打开页面、展开其他组、勾选 / 改期望的每一处修改、倒计时归零……)写操作日志。"""
        run = self.run_by_token(token)
        if not run:
            return False
        kind = "".join(ch for ch in (kind or "event") if ch.isalnum() or ch in "_.")[:40] or "event"
        self.audit(run["store_id"], actor, f"page.{kind}", target_type="run", target_id=str(run["id"]),
                   ref=self.ref(run["id"]), detail=dict(detail or {}, status=run["status"],
                                                        seconds_left=self.seconds_left(run)))
        return True

    # ====================================================================== 建单 → 截图 → 待确认提交(定时 / 单次共用)
    async def _create_guard(self, rid: int) -> None:
        try:
            await self._create(rid)
        except asyncio.CancelledError:
            raise
        except Exception as e:  # noqa: BLE001
            log.exception("建单流程出错")
            run = self.run(rid)
            reason = f"{type(e).__name__}: {e}"
            if run["status"] == "creating":
                # 建单请求可能已经发出:按结果未知处理(再确认时先核实),绝不当成没建成
                await self._create_failed(run, reason, True, {"stage": "cloud_exception"})
                return
            self._set(rid, "error", message=reason)
            await self.say(run, self.t(run["store_id"], "msg_po_failed", reason=str(e)[:200], unknown=True,
                                       kind=run["kind"], doc=run["doc_no"], wait_min=RECONCILE_WAIT_S // 60))
            await alerts.open_alert(run["store_id"], "restock.po_unknown", f"run:{rid}", "critical",
                                    "建单流程出错,请人工到 DMS 核实", f"补货单 {run['doc_no']} 建单流程出错:{e}")

    def po_remark(self, run: dict, cfg: RestockConfig | None = None) -> str:
        """采购单备注:配置的备注 +(单次 / 定时)+ 补货单号。单号放在末尾,结果未知时按它到 DMS 精确核实。"""
        cfg = cfg or self.cfg(run["store_id"])
        how = {"single": "单次", "multi": "批量"}.get(run["kind"], "定时")
        return f"{cfg.po_remark}({how}){run['doc_no']}"

    def _reconcile_gate(self, run: dict, actor: Actor, via: str) -> str:
        """上次建单结果未知时,再确认之前的检查(调用方持锁):返回拒绝原因,空串 = 可以继续(建单前会先核实)。"""
        if not run.get("create_unknown_at"):
            return ""
        sid, rid = run["store_id"], run["id"]
        waited = (self.now(sid) - run["create_unknown_at"]).total_seconds()
        reason, msg = "", ""
        if rid in self._reconciling:              # 定时补货:系统正在自动核实,核实完再确认(防止和自动核实同时建单 / 接管)
            reason = "系统正在自动核实上次建单结果"
            msg = "系统正在自动到 DMS 核实上次建单结果,请稍等一两分钟再确认(核实完会在群里通知)。"
        elif waited < RECONCILE_WAIT_S:
            left = int(RECONCILE_WAIT_S - waited) + 1
            reason, msg = f"上次建单结果未知,还要等 {left} 秒", self.t(sid, "msg_reconcile_wait", seconds=left)
        elif not edge.supports(sid, "restock.find_po"):
            reason = "取数端版本不支持核实(restock.find_po)"
            msg = (f"上次建单结果未知,门店取数端版本太旧,不能自动到 DMS 核实,为防止重复建单这次不建单。"
                   f"请先升级取数端,或到 DMS「采购订单管理」按备注里的单号 {run['doc_no']} 人工核实。")
        if not reason:
            return ""
        self.audit(sid, actor, "run.confirm_rejected", target_type="run", target_id=str(rid), ref=self.ref(rid),
                   detail={"reason": reason, "via": via, "text": actor.extra.get("text", ""),
                           "create_unknown_at": _ts(run["create_unknown_at"]), "waited_seconds": round(waited, 1)})
        return msg

    async def _reconcile(self, run: dict, cfg: RestockConfig, ok_lines: list[planner.Line],
                         auto: bool = False, attempt: int = 0) -> tuple[str, dict]:
        """上次建单结果未知:先到 DMS 按备注里的补货单号核实。
        auto = 单次补货建单异常的自动核实(tick 发起):核实失败不改状态、不在会话里刷屏,返回 "retry" 等下次;
        核实回来时单已经不是建单异常(如后台人工关闭了)返回 "stop",结果不再处理。
        返回 ("adopt", 那张单) / ("none", {}) 没建成 / ("stop", {}) 已收口(核实失败 / 多张 / 状态异常) / ("retry", {})。"""
        sid, rid, ref = run["store_id"], run["id"], self.ref(run["id"])
        sched_auto = auto and run["kind"] in PAGE_KINDS
        since = (run["created_at"] or self.now(sid)) - dt.timedelta(minutes=RECONCILE_LOOKBACK_MIN)
        q = {"supplier_code": cfg.supplier_code, "doc_no": run["doc_no"], "since": _ts(since)}
        if run.get("order_id"):                 # 上次结果未知但取数端带回了 DMS 单据 id:先按 id 找(新版取数端),再按备注单号
            q["order_id"] = run["order_id"]
        sysa = Actor.system("建单核实")
        self.audit(sid, sysa, "po.reconcile_start", target_type="run", target_id=str(rid), ref=ref,
                   detail=dict(q, create_unknown_at=_ts(run["create_unknown_at"]), remark=self.po_remark(run, cfg),
                               auto=auto, attempt=attempt or None))
        self.emit(f"上次建单结果未知,{'自动' if auto else '先'}到 DMS 核实(备注单号 {run['doc_no']},从 {q['since']} 起"
                  + (f",第 {attempt} 次" if attempt else "") + ")", store_id=sid, ref=ref)
        if not auto:
            await self.say(run, self.t(sid, "msg_reconciling", doc=run["doc_no"]))
        try:
            r = await self.edge_run(sid, "restock.find_po", q, timeout=cfg.task_timeouts.submit, ref=ref,
                                    step_timeouts=cfg.step_timeouts.model_dump())
        except (EdgeError, EdgeTimeout) as e:
            if sched_auto:                       # 定时补货自动核实失败:不改状态,隔一会儿再试
                nxt = self.now(sid) + dt.timedelta(minutes=SCHED_RECONCILE_RETRY_MIN)
                db.q(update(runs_t).where(runs_t.c.id == rid, runs_t.c.create_unknown_at.isnot(None)).values(
                    next_retry_at=nxt))
                self.audit(sid, sysa, "po.reconcile_result", target_type="run", target_id=str(rid), ref=ref,
                           detail={"outcome": "failed", "reason": str(e), "query": q, "auto": True,
                                   "attempt": attempt, "next_at": _ts(nxt)})
                self.emit(f"自动核实 {run['doc_no']} 失败(第 {attempt} 次):{e};{nxt:%H:%M} 再试", "warn",
                          store_id=sid, ref=ref)
                return "retry", {}
            if auto:
                nxt = self.now(sid) + dt.timedelta(minutes=self.single_cfg(sid).unknown_retry_min)
                db.q(update(runs_t).where(runs_t.c.id == rid, runs_t.c.status == "create_unknown").values(
                    next_retry_at=nxt, message=("建单异常,自动核实失败(第 %d 次,%s 再试):%s"
                                                % (attempt, nxt.strftime("%H:%M"), e))[:500]))
                self.audit(sid, sysa, "po.reconcile_result", target_type="run", target_id=str(rid), ref=ref,
                           detail={"outcome": "failed", "reason": str(e), "query": q, "auto": True,
                                   "attempt": attempt, "next_at": _ts(nxt)})
                self.emit(f"自动核实 {run['doc_no']} 失败(第 {attempt} 次):{e};{nxt:%H:%M} 再试", "warn",
                          store_id=sid, ref=ref)
                return "retry", {}
            self.audit(sid, sysa, "po.reconcile_result", target_type="run", target_id=str(rid), ref=ref,
                       detail={"outcome": "failed", "reason": str(e), "query": q})
            self._set(rid, "awaiting_confirm", message=("核实上次建单结果失败(这次没有建单):" + str(e))[:500])
            await self.say(run, self.t(sid, "msg_reconcile_failed", reason=str(e)[:200], kind=run["kind"],
                                       doc=run["doc_no"]))
            return "stop", {}
        found = r.get("found") or []
        summary = [{"order_id": f.get("order_id"), "order_no": f.get("order_no"),
                    "remark": (f.get("row") or {}).get("remark"), "status": (f.get("row") or {}).get("orderStatus"),
                    "create_time": (f.get("row") or {}).get("createTime"),
                    "details": [{"part_no": d.get("partNo"), "qty": d.get("purchaseQty")} for d in f.get("details") or []]}
                   for f in found]
        bad_status = [f for f in found if str((f.get("row") or {}).get("orderStatus")) not in ("1", "2")]
        outcome = "none" if not found else "multi" if len(found) > 1 else "bad_status" if bad_status else "adopt"
        self.audit(sid, sysa, "po.reconcile_result", target_type="run", target_id=str(rid), ref=ref,
                   task_id=r.get("_task_id") or "",
                   detail={"outcome": outcome, "query": q, "scanned": r.get("scanned"), "found": summary,
                           "evidence": r.get("evidence") or [], "auto": auto, "attempt": attempt or None})
        if sched_auto:
            now_run = self.run(rid) or {}
            if not now_run.get("create_unknown_at") or now_run.get("status") not in SCHED_UNKNOWN_STATES:
                self.emit(f"自动核实 {run['doc_no']} 回来时单据已有变化({STAGE_CN.get(now_run.get('status'), '')}),结果不再处理",
                          "warn", store_id=sid, ref=ref)
                return "stop", {}
            if outcome == "none":                # 定时补货:没建成 → 只清掉标记,状态不动,不自动重建
                db.q(update(runs_t).where(runs_t.c.id == rid).values(create_unknown_at=None, next_retry_at=None))
                await alerts.resolve_alert(sid, "restock.po_unknown", f"run:{rid}", "自动核实:DMS 里没有本单的采购单")
                self.emit(f"自动核实结果:DMS 里没有 {run['doc_no']} 的采购单(上次没建成),不自动重建", store_id=sid, ref=ref)
                await self.say(run, self.t(sid, "msg_reconcile_none", doc=run["doc_no"], kind=run["kind"], auto=True,
                                           stage=now_run.get("status")), at_planners=True)
                return "none", {}
        elif auto and (self.run(rid) or {}).get("status") != "create_unknown":     # 核实期间后台人工关闭了:结果不再处理
            self.emit(f"自动核实 {run['doc_no']} 回来时单据已不是建单异常({STAGE_CN.get(self.run(rid)['status'])}),结果不再处理",
                      "warn", store_id=sid, ref=ref)
            return "stop", {}
        if outcome == "none" and auto:              # 单次补货:没建成 → 回到待确认,不自动重建(系统异常后不自动重做写操作)
            self._set(rid, "awaiting_confirm", create_unknown_at=None, next_retry_at=None,
                      message="核实结果:DMS 里没有建成,回到待确认(需要的话会话里再回「订」)")
            await alerts.resolve_alert(sid, "restock.po_unknown", f"run:{rid}", "核实 DMS 里没有本单的采购单,回到待确认")
            self.emit(f"核实结果:DMS 里没有 {run['doc_no']} 的采购单,回到待确认(不自动重建)", store_id=sid, ref=ref)
            await self.say(run, self.t(sid, "msg_reconcile_none", doc=run["doc_no"], kind=run["kind"]))
            return "none", {}
        if outcome == "none":
            db.q(update(runs_t).where(runs_t.c.id == rid).values(create_unknown_at=None))
            await alerts.resolve_alert(sid, "restock.po_unknown", f"run:{rid}", "核实 DMS 里没有本单的采购单,重新建单")
            self.emit(f"核实结果:DMS 里没有 {run['doc_no']} 的采购单,重新建单", store_id=sid, ref=ref)
            await self.say(run, self.t(sid, "msg_reconcile_none", doc=run["doc_no"], kind=run["kind"]))
            return "none", {}
        if outcome != "adopt":
            nos = "、".join(str(f.get("order_no")) for f in found)
            why = (f"DMS 里有 {len(found)} 张本单的采购单({nos})" if outcome == "multi" else
                   f"DMS 里本单的采购单 {nos} 状态是 {(bad_status[0].get('row') or {}).get('orderStatus')},不是待提交 / 已提交")
            self._set(rid, "error", message=("核实上次建单结果:" + why + ",请人工处理")[:500], next_retry_at=None)
            await alerts.open_alert(sid, "restock.po_unknown", f"run:{rid}", "critical", "核实建单结果异常,请人工到 DMS 处理",
                                    f"补货单 {run['doc_no']}:{why}。系统不会建单也不会提交。")
            if run["kind"] == "single":
                await self.say(run, self.t(sid, "msg_reconcile_manual", reason=why, doc=run["doc_no"]))
            else:
                await self.say(run, self.t(sid, "msg_reconcile_multi", n=len(found), doc=run["doc_no"], order_nos=nos)
                               if outcome == "multi" else
                               f"❌ {why},系统不会建单也不会提交。需要人工介入:请到 DMS「采购订单管理」按备注单号 "
                               f"{run['doc_no']} 核对这张单后人工处理。", at_planners=True)
            return "stop", {}
        f = found[0]
        db.q(update(runs_t).where(runs_t.c.id == rid).values(create_unknown_at=None, next_retry_at=None))
        await alerts.resolve_alert(sid, "restock.po_unknown", f"run:{rid}", f"核实:上次已建成 {f.get('order_no')},已接管")
        return "adopt", f

    async def _create(self, rid: int) -> None:
        run = self.run(rid)
        sid = run["store_id"]
        cfg = self.cfg(sid)
        ok_lines = [l for l in self.lines(rid) if l.orderable]
        ref = self.ref(rid)
        remark = self.po_remark(run, cfg)
        if run["create_unknown_at"]:
            outcome, found = await self._reconcile(run, cfg, ok_lines)
            if outcome == "stop":
                return
            if outcome == "adopt":
                await self._adopt(run, cfg, ok_lines, found)
                return
            run = self.run(rid)
        expect = {"lines": [{"part_no": l.part_no, "qty": l.final_qty} for l in ok_lines],
                  "supplier_code": cfg.supplier_code, "remark": remark}
        try:
            res = await self.edge_run(sid, "restock.create_po", {
                "lines": [{"part_no": l.part_no, "name": l.name, "qty": l.final_qty} for l in ok_lines],
                "supplier_code": cfg.supplier_code, "order_type": ORDER_TYPE, "kind": run["kind"],
                "remark": remark},
                timeout=cfg.task_timeouts.create(len(ok_lines)), ref=ref, step_timeouts=cfg.step_timeouts.model_dump(),
                idempotency_key=f"restock:po:{rid}:{run['confirmed_at']:%Y%m%d%H%M%S}")
        except EdgeTimeout as e:
            # 只有「取数端一直没领取」(任务已原子地置为过期)才确定没发出去;领了没回结果 = 结果未知
            await self._create_failed(run, str(e), e.unknown, {"stage": "cloud_wait", "unknown": e.unknown})
            return
        except EdgeError as e:
            result = e.result or {}
            # 白名单:只有取数端明确说「建单请求没发出去」(sent=False)或「DMS 明确拒绝」(rejected=True)才算没建成;
            # 旧版取数端没有这两个标记,一律按结果未知
            sent, rejected = result.get("sent"), result.get("rejected") is True
            await self._create_failed(run, str(e), sent is not False and not rejected,
                                      {"code": e.code, "sent": sent, "rejected": rejected,
                                       "order_id": result.get("order_id"), "order_no": result.get("order_no"),
                                       "task_id": result.get("_task_id")})
            return
        await self._after_created(run, cfg, res, ok_lines, expect)

    async def _adopt(self, run: dict, cfg: RestockConfig, ok_lines: list[planner.Line], found: dict) -> None:
        """核实发现上次其实已建成:接管这张单(不再建单),按 DMS 实际明细走截图 → 待确认提交。"""
        sid, rid = run["store_id"], run["id"]
        row = found.get("row") or {}
        details = found.get("details") or []
        got = {str(d.get("partNo")): _money(d.get("purchaseQty")) for d in details}
        want = {l.part_no: float(l.final_qty) for l in ok_lines}
        mismatch = [f"{pn} 本次清单 {q:g},DMS 里 {got[pn]:g}" if pn in got else f"{pn} 本次清单 {q:g},DMS 里没有"
                    for pn, q in want.items() if got.get(pn) != q]
        mismatch += [f"{pn} DMS 里有 {q:g},本次清单没有" for pn, q in got.items() if pn not in want]
        # 提交前核对按 DMS 里这张单的实际内容(人会先看截图再确认提交)
        expect = {"lines": [{"part_no": pn, "qty": q} for pn, q in got.items()],
                  "supplier_code": row.get("supplierCode") or cfg.supplier_code, "remark": row.get("remark") or ""}
        res = {"order_id": found.get("order_id"), "order_no": found.get("order_no"), "row": row, "details": details,
               "mismatch": mismatch, "_task_id": None, "evidence": []}
        self.snapshot(run, "adopted", self.lines(rid), extra={"order_no": found.get("order_no"),
                                                              "order_id": found.get("order_id"),
                                                              "dms_details": details, "mismatch": mismatch})
        self.audit(sid, Actor.system("建单核实"), "po.adopted", target_type="purchase_order",
                   target_id=str(found.get("order_no")), ref=self.ref(rid),
                   detail={"order_no": found.get("order_no"), "order_id": found.get("order_id"),
                           "remark": row.get("remark"), "create_time": row.get("createTime"),
                           "status": row.get("orderStatus"), "dms_details": details, "mismatch": mismatch,
                           "this_list": [{"part_no": l.part_no, "qty": l.final_qty} for l in ok_lines]})
        self.emit(f"核实结果:上次已建成采购单 {found.get('order_no')},接管(不重复建单)", "warn", store_id=sid,
                  ref=self.ref(rid))
        await self.say(run, self.t(sid, "msg_po_adopted", order_no=found.get("order_no"), mismatch=";".join(mismatch)))
        await self._after_created(run, cfg, res, ok_lines, expect, adopted=True)

    async def _after_created(self, run: dict, cfg: RestockConfig, res: dict, ok_lines: list[planner.Line],
                             expect: dict, adopted: bool = False) -> None:
        """采购单已在 DMS 里(新建 / 核实接管):落库 → 截图 → 发回执 → 待确认提交(定时 / 单次共用)。"""
        sid, rid, ref = run["store_id"], run["id"], self.ref(run["id"])
        row = res.get("row") or {}
        order_no = res.get("order_no")
        po_id = db.q(insert(po_t).values(run_id=rid, store_id=sid, order_id=res.get("order_id"), order_no=order_no,
                                         supplier_code=row.get("supplierCode"), order_type=row.get("orderType"),
                                         status="待提交", item_num=str(row.get("itemNum") or ""),
                                         total_amount=row.get("totalAmount"), lines=res.get("details"),
                                         mismatch=res.get("mismatch") or [], shots=[], expect=expect,
                                         create_task_id=res.get("_task_id"), created_at=db.now())).inserted_primary_key[0]
        self._set(rid, "screenshotting", order_no=order_no, order_id=res.get("order_id"))
        if not adopted:
            self.audit(sid, Actor("edge", "", "门店取数端"), "po.created", target_type="purchase_order",
                       target_id=str(order_no), ref=ref, task_id=res.get("_task_id") or "",
                       detail={"order_no": order_no, "order_id": res.get("order_id"), "amount": row.get("totalAmount"),
                               "remark": expect.get("remark"),
                               "lines": [{"part_no": l.part_no, "qty": l.final_qty} for l in ok_lines],
                               "mismatch": res.get("mismatch") or [], "evidence": res.get("evidence") or []})
        if res.get("mismatch"):
            await alerts.open_alert(sid, "restock.po_mismatch", f"run:{rid}", "warn", "采购单明细与请求不一致",
                                    f"采购单 {order_no}:" + ";".join(res["mismatch"]))
        shot_err, shots, fallback, fb_reason, fb_text = "", [], "", "", ""
        try:
            sres = await self.edge_run(sid, "restock.screenshot_po", {
                "order_no": order_no, "row": row, "part_nos": [l.part_no for l in ok_lines]},
                timeout=cfg.task_timeouts.screenshot(cfg.step_timeouts.screenshot, len(ok_lines))
                + cfg.step_timeouts.screenshot_fallback, ref=ref, step_timeouts=cfg.step_timeouts.model_dump())
            shots = [int(x) for x in (sres.get("evidence") or [])]
            fallback = sres.get("fallback") or ""
            if sres.get("detail_complete") is False:     # 详情翻页没截全:取数端已追加接口数据渲染的完整明细图
                self.audit(sid, Actor("edge", "", "门店取数端"), "po.screenshot_incomplete", target_type="purchase_order",
                           target_id=str(order_no), ref=ref,
                           detail={"pages": sres.get("detail_pages"), "missing": sres.get("detail_missing") or [],
                                   "evidence": shots})
                self.emit(f"采购单 {order_no} 详情翻页截图没截全(缺 {len(sres.get('detail_missing') or [])} 项),"
                          "已追加接口数据渲染的完整明细图", "warn", store_id=sid, ref=ref)
            if fallback:
                fb_reason = (sres.get("fallback_reason") or "")[:300]
                fb_text = "\n".join("· %s %s ×%s ¥%s" % (d.get("partNo"), d.get("partName") or "", d.get("purchaseQty"),
                                                          d.get("totalPriceSum") or d.get("totalPrice") or "")
                                    for d in sres.get("details") or [])
            if not shots and fallback != "text":
                shot_err = "取数端说截图成功,但没有收到图片文件"
        except (EdgeError, EdgeTimeout) as e:
            shot_err = str(e)
        db.q(update(po_t).where(po_t.c.id == po_id).values(shots=shots, shots_fallback=fallback or None,
                                                         fallback_reason=fb_reason or None))
        if fallback:
            self.audit(sid, Actor("edge", "", "门店取数端"), "po.screenshot_fallback", target_type="purchase_order",
                       target_id=str(order_no), ref=ref, detail={"mode": fallback, "reason": fb_reason,
                                                                 "evidence": shots})
            await self.say(run, self.t(sid, "msg_shot_fallback", mode=fallback, reason=fb_reason[:120], n=len(shots),
                                       details=fb_text))
            await alerts.open_alert(sid, "restock.screenshot_failed", f"run:{rid}", "warn", "DMS 页面截图失败(已兜底)",
                                    f"采购单 {order_no} 已创建;DMS 页面截图失败:{fb_reason}\n"
                                    f"已{'用接口数据渲染兜底截图' if fallback == 'image' else '发送文字明细'}。")
        sent = 0
        for eid in shots:
            sent += await self.say_image(run, eid)
        if shots and sent < len(shots) and not shot_err:
            shot_err = "截图已生成,但发企微失败"
        if shot_err:
            await alerts.open_alert(sid, "restock.screenshot_failed", f"run:{rid}", "warn", "采购单截图失败",
                                    f"采购单 {order_no} 已创建,但截图失败:{shot_err}\n单据页:{self.link(run)}")
        # 截图发完 → 等人确认提交(定时:单据页按钮;单次:会话里回「确认提交」),不过期。先改状态再发消息:人回得再快也能对上
        can_submit = self.allowed(run["kind"], "submit")
        shot_note = ("截图失败:" + shot_err) if shot_err else ("截图兜底(接口数据渲染)" if fallback else "截图已发")
        what = "接管已建好的" if adopted else "已建单"
        if can_submit:
            if not self._transition(rid, "awaiting_submit", ("screenshotting",),
                                    message=f"{what} {order_no},{shot_note},等确认提交"):
                return
        else:
            if not self._transition(rid, "done", ("screenshotting",),
                                    message=f"{what} {order_no}({shot_note});提交开关关闭,需人工到 DMS 提交"):
                return
            self.audit(sid, Actor.system(), "run.submit_blocked", target_type="run", target_id=str(rid), ref=ref,
                       detail={"order_no": order_no, "reason": "建单后提交开关是关的", "switches": self.switches()})
            if run["kind"] == "scheduled":
                await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}",
                                           f"已建单 {order_no}(提交开关关闭,人工提交)")
        details = res.get("details") or []
        count = len(details) if adopted else len(ok_lines)
        qty = sum(_money(d.get("purchaseQty")) for d in details) if adopted else sum(l.final_qty for l in ok_lines)
        sched = run["kind"] == "scheduled"
        await self.say(run, self.t(sid, "msg_po_done", kind=run["kind"], order_no=order_no, count=count,
                                   qty=qty, amount=_money(row.get("totalAmount")),
                                   shots=sent, fallback=fallback, shot_err=shot_err[:120],
                                   mismatch=";".join(res.get("mismatch") or []), link=self.link(run),
                                   can_submit=can_submit, owner=run["triggered_by"] or "",
                                   late=self.late_hint(sid) if sched else ""), at_planners=sched and bool(shot_err))

    async def _create_failed(self, run: dict, reason: str, unknown: bool, info: dict | None = None) -> None:
        """建单失败。明确没建成(请求没发出去)→ 回到待确认,可以重新确认;
        结果未知 · 单次补货 → create_unknown(建单异常):会话里暂停一切补货操作,系统自动到 DMS 核实;
        结果未知 · 定时补货 → 回到待确认并记下 create_unknown_at:再确认时先到 DMS 核实,已建成就接管、没建成才重建。"""
        sid, rid = run["store_id"], run["id"]
        info = dict(info or {})
        # 结果未知但取数端带回了 DMS 单据 id(建成了、只是回查单号失败):记在补货单上,核实时先按 id 找
        known = {"order_id": str(info["order_id"])[:40]} if unknown and info.get("order_id") else {}
        if unknown and run["kind"] == "single":
            now = self.now(sid)
            self._set(rid, "create_unknown", message=("建单异常(结果未知,正在自动到 DMS 核实):" + reason)[:500],
                      create_unknown_at=now, next_retry_at=now + dt.timedelta(seconds=RECONCILE_WAIT_S),
                      reminder_count=0, last_reminded_at=None, **known)
            self._reconcile_tries.pop(rid, None)
            await alerts.open_alert(sid, "restock.po_unknown", f"run:{rid}", "error", "单次补货建单异常,正在自动核实",
                                    f"补货单 {run['doc_no']}:{reason}\nDMS 里可能已经建成。系统 {RECONCILE_WAIT_S} 秒后自动到 DMS "
                                    f"按备注里的单号 {run['doc_no']} 核实:已建成就接管,没建成回到待确认(不自动重建),"
                                    "期间这个会话暂停补货操作。请不要到 DMS 手工重建。")
            self.audit(sid, Actor.system(), "po.create_unknown", target_type="run", target_id=str(rid),
                       ref=self.ref(rid), detail=dict(info, reason=reason, unknown=True,
                                                      reconcile_at=_ts(now + dt.timedelta(seconds=RECONCILE_WAIT_S))))
            await self.say(run, self.t(sid, "msg_create_unknown", reason=reason[:120], doc=run["doc_no"]))
            return
        if unknown:
            now = self.now(sid)
            kw = {"create_unknown_at": now, **known}
            if run["kind"] in PAGE_KINDS:
                kw["data_fetched_at"] = None
                kw["next_retry_at"] = now + dt.timedelta(seconds=RECONCILE_WAIT_S)     # 到点自动核实(_scheduled_unknown_tick)
            self._set(rid, "awaiting_confirm", message=("建单结果未知(系统会自动到 DMS 核实,不会重复建单):" + reason)[:500],
                      **kw)
            await alerts.open_alert(sid, "restock.po_unknown", f"run:{rid}", "critical",
                                    "建单结果未知,DMS 里可能已经建成",
                                    f"补货单 {run['doc_no']}:{reason}\n系统不会自动重建。{RECONCILE_WAIT_S} 秒后系统自动到 DMS 按备注里的单号 "
                                    f"{run['doc_no']} 核实:已建成就接管(发截图等确认提交),没建成会通知计划员。"
                                    "请不要到 DMS 手工重建。")
        else:
            self._set(rid, "awaiting_confirm", message="建单失败:" + reason[:400],
                      **({"data_fetched_at": None} if run["kind"] in PAGE_KINDS else {}))
            await alerts.open_alert(sid, "restock.po_failed", f"run:{rid}", "error", "创建采购单失败",
                                    f"补货单 {run['doc_no']}:{reason}\nDMS 里没有建成(建单请求没有发出)," +
                                    ("请在页面刷新后重新确认。" if run["kind"] in PAGE_KINDS else "可以重新回「订」。"))
        self.audit(sid, Actor.system(), "po.create_unknown" if unknown else "po.failed", target_type="run",
                   target_id=str(rid), ref=self.ref(rid), detail=dict(info, reason=reason, unknown=unknown))
        sched = run["kind"] == "scheduled"
        await self.say(run, self.t(sid, "msg_po_failed", reason=reason[:200], unknown=unknown, kind=run["kind"],
                                   doc=run["doc_no"], wait_min=RECONCILE_WAIT_S // 60,
                                   late=self.late_hint(sid) if sched else ""), at_planners=sched)

    # ====================================================================== 确认提交(建单截图之后,不过期)
    async def _po_check(self, run: dict) -> tuple[str, dict]:
        """到 DMS 查这张补货单建的采购单现在的状态(只读,调用方不要持门店锁:取数端可能要跑几十秒)。
        返回 (结论, 取数端结果):pending 待提交 / submitted 已提交 / other 其他状态 / missing 已删除 /
        unknown 查不了(取数端不在线、版本不支持、查询失败)。"""
        sid, rid = run["store_id"], run["id"]
        if not run.get("order_id") or not run.get("order_no"):
            return "unknown", {"message": "没有 DMS 采购单信息"}
        if not edge.online(sid)[0] or not edge.supports(sid, "restock.po_status"):
            return "unknown", {"message": "取数端不在线或版本不支持查询采购单状态"}
        cfg = self.cfg(sid)
        since = (run["created_at"] or self.now(sid)) - dt.timedelta(minutes=RECONCILE_LOOKBACK_MIN)
        try:
            res = await self.edge_run(sid, "restock.po_status", {
                "order_id": run["order_id"], "order_no": run["order_no"], "since": _ts(since),
                "supplier_code": cfg.supplier_code}, timeout=cfg.task_timeouts.submit, ref=self.ref(rid),
                step_timeouts=cfg.step_timeouts.model_dump())
        except (EdgeError, EdgeTimeout) as e:
            self.emit(f"查询采购单 {run['order_no']} 状态失败:{e}", "warn", store_id=sid, ref=self.ref(rid))
            return "unknown", {"message": str(e)}
        status = str(res.get("status") or "")
        verdict = ("missing" if not res.get("exists") else "pending" if status == "1"
                   else "submitted" if status == "2" else "other")
        self.audit(sid, Actor("edge", "", "门店取数端"), "po.status", target_type="purchase_order",
                   target_id=str(run["order_no"]), ref=self.ref(rid), task_id=res.get("_task_id") or "",
                   detail={"order_no": run["order_no"], "order_id": run["order_id"], "verdict": verdict,
                           "status": status, "status_cn": res.get("status_cn"), "run_status": run["status"]})
        return verdict, res

    async def _po_gone(self, run: dict, by: str = "", quiet: bool = False) -> str:
        """DMS 里这张采购单已经被删除:补货单收口(不订),不再提交。返回发到群里的话。"""
        sid, rid = run["store_id"], run["id"]
        po = self.po_of(rid)
        if po:
            db.q(update(po_t).where(po_t.c.id == po["id"]).values(status="已删除"))
        self._set(rid, "cancelled", message=f"DMS 里采购单 {run['order_no']} 已被删除,不再提交")
        self.audit(sid, Actor.system("DMS 状态核对"), "run.po_deleted", target_type="run", target_id=str(rid),
                   ref=self.ref(rid), detail={"order_no": run["order_no"], "order_id": run["order_id"], "by": by})
        await alerts.resolve_alert(sid, "restock.submit_failed", f"run:{rid}", f"DMS 里 {run['order_no']} 已删除")
        msg = self.t(sid, "msg_po_deleted", order_no=run["order_no"], kind=run["kind"])
        if not quiet:                             # quiet:发新单次补货时收口,由调用方合并成一条回复
            await self.say(run, msg)
        return msg

    async def _po_other(self, run: dict, status_cn: str, by: str = "", quiet: bool = False) -> str:
        """DMS 里这张采购单已经不是待提交(被别人提交 / 审核 / 已完成……):补货单收口(完成),不再提交。"""
        sid, rid = run["store_id"], run["id"]
        po = self.po_of(rid)
        if po:
            db.q(update(po_t).where(po_t.c.id == po["id"]).values(status=(status_cn or "")[:20] or None))
        self._set(rid, "done", message=f"DMS 里采购单 {run['order_no']} 当前是「{status_cn}」,不再提交")
        self.audit(sid, Actor.system("DMS 状态核对"), "run.po_not_pending", target_type="run", target_id=str(rid),
                   ref=self.ref(rid), detail={"order_no": run["order_no"], "status_cn": status_cn, "by": by})
        await alerts.resolve_alert(sid, "restock.submit_failed", f"run:{rid}", f"DMS 里 {run['order_no']} 是{status_cn}")
        if run["kind"] == "scheduled":
            await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}",
                                       f"DMS 里 {run['order_no']} 是{status_cn}")
        msg = self.t(sid, "msg_po_status_other", order_no=run["order_no"], status_cn=status_cn, kind=run["kind"])
        if not quiet:
            await self.say(run, msg)
        return msg

    async def submit(self, token: str, actor: Actor, via: str) -> tuple[bool, str]:
        """确认提交(定时:单据页按钮,token 定位;单次:会话里回「确认提交」,single_open 按会话定位)。

        按建单时 DMS 返回的单据 id 提交,不在列表里找「最新一张」;取数端提交前再核对一遍这张单。
        返回 (是否已开始提交, 回复)。每一步(定位、身份、开关、确认、结果)都写操作日志。"""
        run = self.run_by_token(token)
        if not run:
            return False, "单据不存在"
        sid, rid = run["store_id"], run["id"]
        async with self.lock(sid):
            run = self.run(rid)
            ref = self.ref(rid)
            route = {"via": via, "kind": run["kind"], "doc_no": run["doc_no"], "order_no": run["order_no"],
                     "order_id": run["order_id"], "status": run["status"], "sender_id": actor.id,
                     "sender": actor.name, "ip": actor.ip, "text": actor.extra.get("text", ""),
                     "located_by": "单据页链接 token" if via == "order_page" else "本会话唯一一张未走完的单次补货"}
            if run["status"] != "awaiting_submit":
                self.audit(sid, actor, "run.submit_rejected", target_type="run", target_id=str(rid), ref=ref,
                           detail=dict(route, reason="状态不是待确认提交"))
                return False, f"这张单当前不能提交({STAGE_CN.get(run['status'], run['status'])})"
            po = self.po_of(rid)
            if not run["order_id"] or not po:
                self.audit(sid, actor, "run.submit_rejected", target_type="run", target_id=str(rid), ref=ref,
                           detail=dict(route, reason="没有 DMS 采购单信息"))
                return False, "找不到这张单的 DMS 采购单信息,不能提交,请到 DMS 人工处理"
            if not self.allowed(run["kind"], "submit"):
                self.audit(sid, actor, "run.submit_blocked", target_type="run", target_id=str(rid), ref=ref,
                           detail=dict(route, reason="提交开关关闭", switches=self.switches()))
                return False, self.t(sid, "msg_submit_disabled", kind_cn=KIND_CN.get(run["kind"], ""),
                                     order_no=run["order_no"])
            if not edge.online(sid)[0]:
                self.audit(sid, actor, "run.submit_blocked", target_type="run", target_id=str(rid), ref=ref,
                           detail=dict(route, reason="取数端不在线"))
                if run["kind"] not in PAGE_KINDS:
                    return False, "门店取数端不在线,暂时不能提交(已通知运维),恢复后再确认一次"
                return False, (f"门店取数端不在线,暂时不能提交(已通知运维)。需要人工介入:请检查门店电脑和取数端,恢复后再点一次;"
                               f"来不及的话请直接到 DMS 人工提交 {run['order_no']}")
            if not edge.supports(sid, "restock.submit_po"):
                self.audit(sid, actor, "run.submit_blocked", target_type="run", target_id=str(rid), ref=ref,
                           detail=dict(route, reason="取数端版本不支持提交"))
                return False, (f"门店取数端版本太旧,还不支持提交采购单,请先升级取数端;"
                               f"DMS 里 {run['order_no']} 仍是「待提交」,也可以到 DMS 人工提交")
            self.audit(sid, actor, "run.submit_route", target_type="run", target_id=str(rid), ref=ref, detail=route)
            self._set(rid, "submitting", submitted_by=actor.name[:80], submitted_via=via, submitted_at=db.now())
            run = self.run(rid)
            self.snapshot(run, "submit_confirmed", self.lines(rid), actor,
                          extra={"route": route, "expect": db.jload(po["expect"], None)})
            self.audit(sid, actor, "run.submit_confirm", target_type="run", target_id=str(rid), ref=ref,
                       detail=dict(route, expect=db.jload(po["expect"], None)))
        msg = self.t(sid, "msg_submitting", order_no=run["order_no"], by=actor.name,
                     via_cn=VIA_CN.get(via, ""), kind=run["kind"],
                     late=self.late_hint(sid) if run["kind"] == "scheduled" else "")
        if via != "chat":                         # 单据页上点的:群里也说一声(群里回复的由工具直接回)
            await self.say(run, msg)
        self.spawn(self._submit_guard(rid), f"restock-submit-{rid}")
        return True, msg

    async def _submit_guard(self, rid: int) -> None:
        try:
            await self._submit(rid)
        except asyncio.CancelledError:
            raise
        except Exception as e:  # noqa: BLE001
            log.exception("提交流程出错")
            await self._submit_failed(self.run(rid), f"{type(e).__name__}: {e}", True)

    async def _submit(self, rid: int) -> None:
        run = self.run(rid)
        sid = run["store_id"]
        cfg = self.cfg(sid)
        ref = self.ref(rid)
        po = self.po_of(rid)
        expect = db.jload(po["expect"], None) or {
            "lines": [{"part_no": l.part_no, "qty": l.final_qty} for l in self.lines(rid) if l.orderable],
            "supplier_code": po["supplier_code"], "remark": ""}
        # 先查 DMS 里这张单现在的状态:被删了 / 已经不是待提交(且不是已提交)就如实回复,不提交;
        # 待提交 / 已提交 / 查不了 → 走提交(取数端提交前会再核对;已提交的只回查不重复提交)
        verdict, st = await self._po_check(run)
        if verdict == "missing":
            await self._po_gone(run, by=run["submitted_by"] or "")
            return
        if verdict == "other":
            await self._po_other(run, st.get("status_cn") or "", by=run["submitted_by"] or "")
            return
        try:
            res = await self.edge_run(sid, "restock.submit_po", {
                "kind": run["kind"], "order_id": run["order_id"], "order_no": run["order_no"], "expect": expect},
                timeout=cfg.task_timeouts.submit, ref=ref, step_timeouts=cfg.step_timeouts.model_dump(),
                idempotency_key=f"restock:submit:{rid}:{run['submitted_at']:%Y%m%d%H%M%S}")
        except EdgeTimeout as e:
            await self._submit_failed(run, str(e), e.unknown)
            return
        except EdgeError as e:
            if e.code == "po_missing":            # 取数端核对时整张单都找不到:按已删除收口
                await self._po_gone(run, by=run["submitted_by"] or "")
                return
            await self._submit_failed(run, str(e), bool((e.result or {}).get("unknown")) or e.code == "unknown_result",
                                      e.code)
            return
        details = res.get("details") or []
        lines = [{"part_no": d.get("partNo"), "name": d.get("partName") or "", "qty": _money(d.get("purchaseQty")),
                  "amount": _money(d.get("totalPrice"))} for d in details]
        amount = _money(res.get("total_amount")) or sum(x["amount"] for x in lines) or _money(po["total_amount"])
        db.q(update(po_t).where(po_t.c.id == po["id"]).values(
            status="已提交", submit_task_id=res.get("_task_id"), submitted_by=run["submitted_by"],
            submitted_at=db.now(), apply_operator=(res.get("apply_operator") or "")[:80] or None,
            apply_time=str(res.get("apply_time") or "")[:30] or None, submit_lines=details, submit_error=None))
        op = res.get("apply_operator") or ""
        self._set(rid, "done", message=f"已提交 {run['order_no']}(DMS 提交人 {op or '?'},"
                                       f"{run['submitted_by']} {VIA_CN.get(run['submitted_via'] or '', '')}确认)")
        self.audit(sid, Actor("edge", "", "门店取数端"), "po.submitted", target_type="purchase_order",
                   target_id=str(run["order_no"]), ref=ref, task_id=res.get("_task_id") or "",
                   detail={"order_no": run["order_no"], "order_id": run["order_id"], "apply_operator": op,
                           "apply_time": res.get("apply_time"), "amount": amount, "already": bool(res.get("already")),
                           "confirmed_by": run["submitted_by"], "confirmed_via": run["submitted_via"],
                           "lines": lines, "evidence": res.get("evidence") or []})
        await alerts.resolve_alert(sid, "restock.submit_failed", f"run:{rid}", f"已提交 {run['order_no']}")
        if run["kind"] == "scheduled":
            await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}", f"已提交 {run['order_no']}")
        self.spawn(self._submit_shots_guard(rid), f"restock-submit-shots-{rid}")   # 审计留档截图:不发群里
        await self.say(run, self.t(sid, "msg_po_submitted", kind=run["kind"], order_no=run["order_no"], lines=lines,
                                   count=len(lines), qty=sum(x["qty"] for x in lines), amount=amount,
                                   by=op or run["submitted_by"] or "", confirmed_by=run["submitted_by"] or "",
                                   already=bool(res.get("already")), link=self.link(run)))

    # ---------------------------------------------------------------- 提交后截图(审计留档,只在后台看)
    SUBMIT_SHOT_TRIES = 2

    async def _submit_shots_guard(self, rid: int) -> None:
        try:
            await self.submit_shots(rid)
        except asyncio.CancelledError:
            raise
        except Exception:  # noqa: BLE001  留档截图失败不影响补货单(已提交)
            log.exception("提交后截图出错")

    async def submit_shots(self, rid: int, actor: Actor | None = None) -> tuple[bool, str]:
        """提交成功后再截一次采购单:「采购订单管理」列表(能看到已提交状态、提交人 / 时间)+ 详情全部页。
        只存 po.submit_shots(审计留档),不发群里、单据页也不显示。失败自动再试一次;后台可手动重新截。"""
        run = self.run(rid)
        po = self.po_of(rid) if run else None
        if not run or not po or po["status"] != "已提交":
            return False, "这张单的采购单还没提交成功,不用截提交后截图"
        if rid in self._submit_shooting:
            return False, "正在截图,请稍后刷新"
        sid, ref = run["store_id"], self.ref(rid)
        cfg = self.cfg(sid)
        by = actor or Actor.system("提交后截图")
        part_nos = [str(d.get("partNo") or "") for d in (db.jload(po["submit_lines"], []) or [])] or \
                   [x["part_no"] for x in (db.jload(po["expect"], {}) or {}).get("lines") or []]
        self._submit_shooting.add(rid)
        err = ""
        try:
            for attempt in range(1, self.SUBMIT_SHOT_TRIES + 1):
                try:
                    # row 不传:取数端按单号重新查列表行,截到的是提交之后的状态
                    res = await self.edge_run(sid, "restock.screenshot_po", {
                        "order_no": run["order_no"], "row": None, "part_nos": [p for p in part_nos if p],
                        "purpose": "submitted"},
                        timeout=cfg.task_timeouts.screenshot(cfg.step_timeouts.screenshot, len(part_nos))
                        + cfg.step_timeouts.screenshot_fallback, ref=ref, step_timeouts=cfg.step_timeouts.model_dump())
                    shots = [int(x) for x in (res.get("evidence") or [])]
                    if not shots:
                        raise EdgeError("取数端没有回传截图文件" + (
                            "(DMS 页面截图失败,兜底也没能生成图片)" if res.get("fallback") == "text" else ""))
                    db.q(update(po_t).where(po_t.c.id == po["id"]).values(
                        submit_shots=shots, submit_shots_fallback=res.get("fallback") or None, submit_shots_error=None,
                        submit_shots_at=db.now()))
                    self.audit(sid, by, "po.submit_screenshot", target_type="purchase_order",
                               target_id=str(run["order_no"]), ref=ref, task_id=res.get("_task_id") or "",
                               detail={"order_no": run["order_no"], "evidence": shots, "attempt": attempt,
                                       "fallback": res.get("fallback") or "",
                                       "fallback_reason": (res.get("fallback_reason") or "")[:300],
                                       "detail_complete": res.get("detail_complete"),
                                       "detail_missing": res.get("detail_missing") or []})
                    self.emit(f"采购单 {run['order_no']} 提交后截图已留档({len(shots)} 张)", "ok", store_id=sid, ref=ref)
                    return True, f"已截图 {len(shots)} 张"
                except (EdgeError, EdgeTimeout) as e:
                    err = str(e)
                    self.emit(f"采购单 {run['order_no']} 提交后截图失败(第 {attempt} 次):{e}", "warn", store_id=sid,
                              ref=ref)
            db.q(update(po_t).where(po_t.c.id == po["id"]).values(submit_shots_error=err[:2000],
                                                                 submit_shots_at=db.now()))
            self.audit(sid, by, "po.submit_screenshot_failed", target_type="purchase_order",
                       target_id=str(run["order_no"]), ref=ref, detail={"order_no": run["order_no"], "reason": err,
                                                                        "tries": self.SUBMIT_SHOT_TRIES})
            return False, "截图失败:" + err[:200]
        finally:
            self._submit_shooting.discard(rid)

    def submit_shots_state(self, rid: int) -> dict:
        """后台单据详情:提交后截图(签名链接)。"""
        po = self.po_of(rid) or {}
        ids = db.jload(po.get("submit_shots"), []) or []
        return {"shots": [{"id": e, "url": links.evidence_url(e)} for e in ids],
                "fallback": po.get("submit_shots_fallback") or "", "error": po.get("submit_shots_error") or "",
                "at": _ts(po.get("submit_shots_at")), "running": rid in self._submit_shooting,
                "can_retry": po.get("status") == "已提交" and rid not in self._submit_shooting}

    async def _submit_failed(self, run: dict, reason: str, unknown: bool, code: str = "") -> None:
        """提交失败:明确没提交(检查没通过等)→ 回到待确认提交,可处理后再确认;
        核对发现单据被改过 → 出错收口(不能再用这张单提交);结果未知 → 出错 + 紧急告警,绝不重试。"""
        sid, rid = run["store_id"], run["id"]
        ref = self.ref(rid)
        po = self.po_of(rid)
        if po:
            db.q(update(po_t).where(po_t.c.id == po["id"]).values(submit_error=reason[:2000]))
        if unknown:
            self._set(rid, "error", message="提交结果未知:" + reason[:400])
            await alerts.open_alert(sid, "restock.submit_unknown", f"run:{rid}", "critical",
                                    "提交结果未知,请人工到 DMS 核实",
                                    f"补货单 {run['doc_no']} 提交采购单 {run['order_no']}:{reason}\n"
                                    "请到 DMS「采购订单管理」看它是不是「已提交」;系统不会重试提交。")
        elif code == "verify_failed":
            self._set(rid, "error", message="提交前核对未通过:" + reason[:400])
            await alerts.open_alert(sid, "restock.submit_failed", f"run:{rid}", "error", "采购单核对不一致,未提交",
                                    f"补货单 {run['doc_no']}:{reason}\nDMS 里的单据和建单时不一致,系统不会提交,请人工处理。")
        else:
            self._set(rid, "awaiting_submit", message="提交失败:" + reason[:400])
            await alerts.open_alert(sid, "restock.submit_failed", f"run:{rid}", "error", "提交采购单失败",
                                    f"补货单 {run['doc_no']} 提交 {run['order_no']} 失败:{reason}\n"
                                    "DMS 里仍是「待提交」,处理后可以再确认提交,或到 DMS 人工提交。")
        self.audit(sid, Actor.system(), "po.submit_unknown" if unknown else "po.submit_failed",
                   target_type="purchase_order", target_id=str(run["order_no"]), ref=ref,
                   detail={"reason": reason, "unknown": unknown, "code": code, "confirmed_by": run["submitted_by"],
                           "confirmed_via": run["submitted_via"]})
        sched = run["kind"] == "scheduled"
        await self.say(run, self.t(sid, "msg_submit_failed", reason=reason[:300], unknown=unknown,
                                   retry=not unknown and code != "verify_failed", kind=run["kind"],
                                   order_no=run["order_no"], link=self.link(run),
                                   late=self.late_hint(sid) if sched else ""), at_planners=sched)

    async def _hold(self, run: dict, actor: Actor, via: str) -> tuple[bool, str]:
        """「先不提交 / 不提交」:调用方已持锁。DMS 草稿保留「待提交」,由人工删除或提交。"""
        sid, rid = run["store_id"], run["id"]
        self._set(rid, "cancelled", message=f"{actor.name}:先不提交(DMS 草稿 {run['order_no']} 保留待提交)")
        self.audit(sid, actor, "run.submit_cancel", target_type="run", target_id=str(rid), ref=self.ref(rid),
                   detail={"via": via, "order_no": run["order_no"], "order_id": run["order_id"], "sender_id": actor.id,
                           "ip": actor.ip, "text": actor.extra.get("text", "")})
        msg = self.t(sid, "msg_submit_cancelled", order_no=run["order_no"], by=actor.name, kind=run["kind"])
        await self.say(run, msg)
        if run["kind"] == "scheduled":
            await alerts.resolve_alert(sid, "restock.not_ordered", f"day:{run['biz_date']}",
                                       f"{actor.name} 确认先不提交 {run['order_no']}")
        return True, "已标记为先不提交,DMS 草稿保留"

    # ====================================================================== 查询 / 页面数据
    def status_text(self, sid: int, target_id: int | None = None, with_single: bool = True) -> str:
        """补货进度(定时补货 + 本会话的单次补货)。with_single=False 只说定时补货(技能「定时补货」用)。"""
        r = self.current(sid)
        single = self.single_open(sid, target_id) if with_single else None
        others = [self.link_item(x) for x in self.scheduled_others(sid, exclude=r["id"] if r else None)]
        if not r and not single and not others:
            return self.t(sid, "msg_no_run", push_time=self.cfg(sid).push_time)
        po = self.po_of(r["id"]) if r else None
        return (self.t(sid, "msg_status", stage=STAGE_CN.get(r["status"], r["status"]) if r else "",
                       order_no=(r or {}).get("order_no"), po_status=(po or {}).get("status") or "",
                       link=self.link(r) if r else "", others=others,
                       single=single and {"doc": single["doc_no"], "stage": STAGE_CN.get(single["status"]),
                                          "order_no": single["order_no"] or ""})
                + self._late_tail(self.drafts_text(sid, self.drafts_for_reply(sid)))
                + (self._late_tail(self.late_hint(sid)) if r and r["status"] in OPEN else ""))

    def page_state(self, token: str) -> dict | None:
        r = self.run_by_token(token)
        if not r:
            return None
        sid = r["store_id"]
        cfg = self.cfg(sid)
        lines = self.lines(r["id"])
        po = db.one(select(po_t).where(po_t.c.run_id == r["id"]).order_by(po_t.c.id.desc()).limit(1))
        shots = [{"id": e, "url": links.evidence_url(e)} for e in (db.jload(po["shots"], []) if po else [])]
        now = self.now(sid)
        store = stores.store_info(sid)
        before_cut = not self._after_cutoff_blocked(r, cfg, now)       # 默认截单只提示,不拦
        left = self.seconds_left(r) if r["status"] == "awaiting_confirm" else 0
        page = r["kind"] in PAGE_KINDS
        if r["kind"] != "scheduled":
            before_cut = True                                           # 截单只管定时补货
        drafts = self.drafts_of(r) if r["kind"] == "scheduled" else None
        if r["kind"] == "scheduled" and drafts is None:
            drafts = {"source": "system", "error": "", "items": self.local_drafts(sid, exclude=r["id"]), "checked_at": ""}
        in_drafts = self.draft_parts(drafts)
        line_dicts = []
        for l in lines:
            d = l.to_dict()
            d["in_drafts"] = in_drafts.get(l.part_no, [])
            line_dicts.append(d)
        open_ = r["status"] in OPEN
        return {"run": db.plain({k: v for k, v in r.items() if k not in ("token",)}),
                "store": {"name": store.name, "brand": store.brand},
                "stage_cn": STAGE_CN.get(r["status"], r["status"]), "kind_cn": KIND_CN.get(r["kind"], ""),
                "window": self.window_text(r),
                "now": now.strftime("%Y-%m-%d %H:%M:%S"),
                "valid_seconds": cfg.confirm_valid_seconds, "seconds_left": left,
                "can_confirm": page and r["status"] == "awaiting_confirm" and before_cut and left > 0,
                "can_refresh": page and r["status"] == "awaiting_confirm" and before_cut,
                "can_cancel": page and r["status"] == "awaiting_confirm",
                "can_submit": page and r["status"] == "awaiting_submit",
                "can_hold": page and r["status"] == "awaiting_submit",
                "can_close_unknown": r["kind"] == "single" and r["status"] == "create_unknown",
                "can_terminate": r["status"] in TERMINABLE.get(r["kind"], ()),
                "can_void": r["kind"] in CHAT_KINDS and r["status"] in ("awaiting_confirm", "awaiting_submit"),
                "submitted_via_cn": VIA_CN.get(r.get("submitted_via") or "", ""),
                "late_hint": self.late_hint(sid, now) if r["kind"] == "scheduled" and open_ else "",
                "stale_hint": self.stale_hint(r), "cutoff_hard": bool(cfg.cutoff_hard),
                "hide_zero": r["kind"] == "scheduled" and bool(cfg.hide_zero_lines),
                "drafts": drafts,
                "lines": line_dicts, "summary": planner.summary(lines),
                "po": db.plain({k: v for k, v in po.items() if not k.startswith("submit_shots")}) if po else None,
                "shots": shots,
                "today_orders": [{"doc_no": o["doc_no"], "order_no": o["order_no"],
                                  "trigger_cn": TRIGGER_CN.get(o["trigger"], ""),
                                  "stage_cn": STAGE_CN.get(o["status"], o["status"]),
                                  "link": f"/m/restock/order/{o['token']}"}      # 同站相对链接:页面上直接跳过去
                                 for o in (self.orders_today(sid, r["biz_date"], exclude=r["id"])
                                           if r["kind"] == "scheduled" else [])],
                "shots_fallback": (po or {}).get("shots_fallback") or "",
                "cutoff": cfg.cutoff, "stock_categories": cfg.stock_categories, "so_months": cfg.so_months,
                "in_transit_label": planner.IN_TRANSIT_LABEL.get(cfg.in_transit_field, "在途数量"),
                "max_qty": self.single_cfg(sid).max_qty if r["kind"] == "multi" else None}

    # ====================================================================== 时间线(定时任务 + 每轮 tick)
    def _probe_part(self, sid: int) -> list[dict]:
        """预检用的一个零件:SO 常备件 / 分类表里的第一个。"""
        so = history.parts(sid, size=1)["rows"]
        if so:
            return [{"part_no": so[0]["part_no"], "name": so[0]["name"] or ""}]
        cats = categories.paged(sid, size=1)["rows"]
        return [{"part_no": cats[0]["part_no"], "name": cats[0]["name"] or ""}] if cats else []

    async def preflight(self, sid: int, now: dt.datetime, slot: str) -> None:
        cfg = self.cfg(sid)
        if not cfg.auto_push:                                  # 预检是为定时推送服务的,关了每天自动执行就不查
            return
        key = f"day:{now.date()}"
        online, info = await edge.wait_online(sid, 90)        # 云端刚重启时取数端可能正在重连
        title = "补货预检失败:今天的补货可能受影响"
        if not online:
            age = info.get("last_seen_age")
            await alerts.open_alert(sid, "restock.preflight_failed", key, "error", title,
                                    f"{slot} 预检:门店取数端不在线" + (f"(最后联系 {int(age // 60)} 分钟前)" if age else "")
                                    + f"。{cfg.push_time} 的补货推送需要取数端在线,截单 {cfg.cutoff}。")
            return
        try:
            r = await self.edge_run(sid, "sys.check", {"parts": self._probe_part(sid), "screenshot": False},
                                    timeout=cfg.task_timeouts.preflight, ref=f"restock:preflight:{now.date()}",
                                    step_timeouts=cfg.step_timeouts.model_dump())
        except (EdgeError, EdgeTimeout) as e:
            await alerts.open_alert(sid, "restock.preflight_failed", key, "error", title, f"{slot} 预检:{e}")
            return
        if not r.get("ok", False):
            bad = [f"{s.get('step')}:{s.get('detail')}" for s in r.get("steps") or [] if not s.get("ok")]
            await alerts.open_alert(sid, "restock.preflight_failed", key, "error", title,
                                    f"{slot} 预检未通过:" + (";".join(bad[:5]) or r.get("message") or "原因见任务详情"))
            return
        self.emit(f"{slot} 预检通过(取数端在线、DMS 登录正常)", "ok", store_id=sid)
        await alerts.resolve_alert(sid, "restock.preflight_failed", key, f"{slot} 预检通过")

    async def push(self, sid: int, now: dt.datetime, slot: str) -> None:
        """定时推送:手动补货还在跑就等它跑完再开始(到当天结束还没跑完才放弃;旧规则 cutoff_hard 下到截单就放弃),
        不会因为手动补充被跳过。"""
        cfg = self.cfg(sid)
        if not cfg.auto_push:
            return
        stop = at(now.date(), cfg.cutoff) if cfg.cutoff_hard else at(now.date(), "23:59")
        waited = False
        while True:
            res = await self.start(sid, "schedule", Actor.system("定时推送"))
            if res != "busy":
                return
            cur = self.current(sid, now.date())
            if self.now(sid) >= stop:
                self.emit(f"定时推送没能开始:到 {stop:%H:%M} 补货单 {cur['doc_no'] if cur else ''} 还在进行中",
                          "warn", store_id=sid)
                return
            if not waited:
                waited = True
                self.emit(f"到点定时推送:补货单 {cur['doc_no'] if cur else ''} 还在进行中,等它结束后开始", store_id=sid)
            await asyncio.sleep(PUSH_WAIT_S)

    async def so_sync(self, sid: int, now: dt.datetime, slot: str) -> None:
        await history.sync(sid, "schedule", Actor.system("每周 SO 单同步"), now.date())

    async def close(self, sid: int, now: dt.datetime, slot: str) -> None:
        """截单那一刻。默认(截单只提示风险):今天的定时补货单还没走完就在群里提醒一次「已过截单,仍可继续,
        但实际提交会超过截单时间」,不作废(旧清单等下一张定时补货单生成时才作废);关闭每天自动执行时不提醒。
        旧规则(cutoff_hard):今天还没完成的定时补货单作废(不顺延到明天)。小结另按「每日小结」时间发(summary)。"""
        cfg = self.cfg(sid)
        cur = self.current(sid, now.date())
        if not cfg.cutoff_hard:
            if cfg.auto_push and cur and cur["status"] in OPEN:
                await self.say(cur, self.t(sid, "msg_cutoff_passed", cutoff=cfg.cutoff, doc=cur["doc_no"],
                                           stage=STAGE_CN.get(cur["status"], cur["status"]), link=self.link(cur)))
            return
        expiring = ("awaiting_confirm", "scan_retry", "scanning", "refreshing")
        if cur and cur["status"] in expiring:
            if not self._transition(cur["id"], "expired", expiring, message=f"到 {cfg.cutoff} 截单仍未完成"):
                return
            await self.say(cur, self.t(sid, "msg_closed", cutoff=cfg.cutoff, doc=cur["doc_no"],
                                       stage=STAGE_CN.get(cur["status"], cur["status"])))
            self.audit(sid, Actor.system("截单收口"), "run.expire", target_type="run", target_id=str(cur["id"]),
                       ref=self.ref(cur["id"]), detail={"create_unknown_at": _ts(cur.get("create_unknown_at"))})
            if cur.get("create_unknown_at"):
                await self.say(cur, self.t(sid, "msg_unknown_left", doc=cur["doc_no"]))

    async def summary(self, sid: int, now: dt.datetime, slot: str) -> None:
        """今日补货小结:定时补货(含手动补充)+ 单次补货,按「每日小结」的时间发(须晚于截单,截单已收口)。"""
        cfg = self.cfg(sid)
        cur = self.current(sid, now.date())
        orders = self.orders_today(sid, now.date())
        if orders:
            def po_state(o: dict) -> str:
                st = (self.po_of(o["id"]) or {}).get("status") or "待提交"
                return st if st == "已提交" else f"{st},{STAGE_CN.get(o['status'], o['status'])},请到 DMS 核对"
            text = "今日定时补货:" + "、".join(f"采购单 {o['order_no']}({TRIGGER_CN.get(o['trigger'], '')},{po_state(o)})"
                                         for o in orders)
        elif cur and cur["status"] == "done":
            text = "今日补货完成:" + (cur["message"] or "无需补货")
        elif cur and cur["status"] == "cancelled":
            text = f"今日不订({cur['message'] or '计划员确认'})"
        elif cur and cur["status"] == "terminated":
            text = f"今日定时补货已在后台终止({cur['message'] or ''})"
        elif cur:
            text = f"今日未完成下单({STAGE_CN.get(cur['status'], cur['status'])}:{cur['message'] or ''})"
        else:
            text = "今日没有运行定时补货" + ("(每天自动执行已关闭)" if not cfg.auto_push else "")
        for kind in ("single", "multi"):
            singles = db.rows(select(runs_t.c.doc_no, runs_t.c.order_no, runs_t.c.status, runs_t.c.submitted_at).where(
                runs_t.c.store_id == sid, runs_t.c.biz_date == now.date(), runs_t.c.kind == kind))
            if singles:
                text += ";%s %d 次(建单 %d 张,已提交 %d 张)" % (
                    KIND_CN[kind], len(singles), sum(1 for x in singles if x["order_no"]),
                    sum(1 for x in singles if x["order_no"] and x["status"] == "done" and x["submitted_at"]))
        unknown = db.rows(select(runs_t.c.doc_no).where(runs_t.c.store_id == sid, runs_t.c.biz_date == now.date(),
                                                        runs_t.c.create_unknown_at.isnot(None)
                                                        | (runs_t.c.status == "create_unknown")))
        if unknown:
            text += ";⚠ 建单结果未知、还没核实(DMS 里可能已有采购单,备注带单号):" + "、".join(x["doc_no"] for x in unknown)
        await notify.send(sid, "restock.daily_summary", "info", "今日补货小结", text)

    async def tick(self, sid: int, now: dt.datetime) -> None:
        cfg = self.cfg(sid)
        today = now.date()
        cutoff = at(today, cfg.cutoff)
        cur = self.current(sid, today)
        # 截单只提示风险时,过了截单照样重试取数 / 提醒(旧规则 cutoff_hard 下截单后不再处理)
        if cur and (now < cutoff or not cfg.cutoff_hard):
            if cur["status"] == "scan_retry" and cur["next_retry_at"] and now >= cur["next_retry_at"]:
                if db.q(update(runs_t).where(runs_t.c.id == cur["id"], runs_t.c.status == "scan_retry").values(
                        status="scanning", updated_at=db.now())).rowcount:
                    self.emit(f"自动重试取数(第 {(cur['scan_attempts'] or 0) + 1} 次)", store_id=sid,
                              ref=self.ref(cur["id"]))
                    self.spawn(self._scan_guard(cur["id"]), f"restock-scan-{cur['id']}")
            elif cfg.auto_push and cur["status"] == "awaiting_confirm" and (cur["reminder_count"] or 0) < cfg.remind_max:
                # 未确认提醒(关闭每天自动执行时不提醒)
                base = cur["last_reminded_at"] or cur["listed_at"]
                if base and now >= base + dt.timedelta(minutes=cfg.remind_interval_min):
                    n = (cur["reminder_count"] or 0) + 1
                    db.q(update(runs_t).where(runs_t.c.id == cur["id"]).values(reminder_count=n, last_reminded_at=now))
                    await self.say(cur, self.t(sid, "msg_reminder", doc=cur["doc_no"], n=n, max=cfg.remind_max,
                                               cutoff=cfg.cutoff, link=self.link(cur), late=self.late_hint(sid, now)),
                                   at_planners=True)
                    self.audit(sid, Actor.system("提醒"), "run.remind", target_type="run", target_id=str(cur["id"]),
                               ref=self.ref(cur["id"]), detail={"n": n})
        # 单次补货的查询结果、建单后的确认提交都不过期(不再在 tick 里收口);建单异常的自动核实 / 提醒
        await self._unknown_tick(sid, now)
        # 定时补货建单结果未知:到点自动到 DMS 核实(不用等人再点确认)
        await self._scheduled_unknown_tick(sid, now)
        # 截单前还没提交 → 紧急告警(企微 + 邮件按路由),每天一次;关闭每天自动执行时不告警
        if cfg.auto_push and cfg.urgent_before_min \
                and cutoff - dt.timedelta(minutes=cfg.urgent_before_min) <= now < cutoff \
                and not self.submitted_today(sid, today):
            push_passed = now >= at(today, cfg.push_time)
            need = (cur is not None and cur["status"] not in ("done", "cancelled", "terminated")) or \
                   (cur is None and cfg.auto_push and push_passed)
            if need and not (cur and cur["urgent_sent"]):
                if cur:
                    db.q(update(runs_t).where(runs_t.c.id == cur["id"]).values(urgent_sent=True))
                stage = STAGE_CN.get(cur["status"], cur["status"]) if cur else "今天还没有运行"
                await alerts.open_alert(sid, "restock.not_ordered", f"day:{today}", "critical",
                                        f"距截单还剩 {cfg.urgent_before_min} 分钟,今天的定时补货还没有提交",
                                        f"补货单 {cur['doc_no'] if cur else '—'}:{stage}。"
                                        + (f"{cfg.cutoff} 截单后今天就订不了货了,请立即处理。" if cfg.cutoff_hard else
                                           f"时间已经不多:{cfg.cutoff} 截单后仍可确认 / 提交,但实际提交时间会超过截单时间,"
                                           "请尽快处理。")
                                        + (f"\n单据:{self.link(cur)}" if cur else ""),
                                        renotify_minutes=24 * 60)

    async def _scheduled_unknown_tick(self, sid: int, now: dt.datetime) -> None:
        """定时补货建单结果未知:满 RECONCILE_WAIT_S 秒(next_retry_at)后自动到 DMS 核实,范围是最近两天、
        还在待确认 / 已作废 / 已过期的单(作废的单 DMS 里也可能有草稿)。人点确认时如果正在自动核实会先挡住。"""
        since = now.date() - dt.timedelta(days=SCHED_RECONCILE_DAYS)
        for run in db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.kind.in_(PAGE_KINDS),
                                                runs_t.c.create_unknown_at.isnot(None),
                                                runs_t.c.status.in_(SCHED_UNKNOWN_STATES), runs_t.c.biz_date >= since)):
            rid = run["id"]
            due = run["next_retry_at"] or (run["create_unknown_at"] + dt.timedelta(seconds=RECONCILE_WAIT_S))
            if rid in self._reconciling or now < due:
                continue
            self._reconciling.add(rid)
            self.spawn(self._auto_reconcile_scheduled(rid), f"restock-reconcile-{rid}")

    async def _auto_reconcile_scheduled(self, rid: int) -> None:
        """定时补货建单结果未知的自动核实(一次;失败隔 SCHED_RECONCILE_RETRY_MIN 分钟由 tick 再发起)。
        1 张 → 接管(截图 → 待确认提交);0 张 → 清掉标记、状态不动(不自动重建);多张 / 状态异常 → 出错转人工。"""
        try:
            run = self.run(rid)
            if not run or not run["create_unknown_at"] or run["status"] not in SCHED_UNKNOWN_STATES:
                return
            sid = run["store_id"]
            cfg = self.cfg(sid)
            attempt = self._reconcile_tries[rid] = self._reconcile_tries.get(rid, 0) + 1
            why = ("门店取数端不在线" if not edge.online(sid)[0] else
                   "门店取数端版本太旧,不支持核实(restock.find_po)" if not edge.supports(sid, "restock.find_po") else "")
            if why:
                nxt = self.now(sid) + dt.timedelta(minutes=SCHED_RECONCILE_RETRY_MIN)
                db.q(update(runs_t).where(runs_t.c.id == rid).values(next_retry_at=nxt))
                self.emit(f"自动核实 {run['doc_no']} 暂时做不了(第 {attempt} 次):{why};{nxt:%H:%M} 再试", "warn",
                          store_id=sid, ref=self.ref(rid))
                return
            ok_lines = [l for l in self.lines(rid) if l.orderable]
            outcome, found = await self._reconcile(run, cfg, ok_lines, auto=True, attempt=attempt)
            if outcome == "adopt":
                await self._adopt(self.run(rid), cfg, ok_lines, found)
            if outcome != "retry":
                self._reconcile_tries.pop(rid, None)
        except asyncio.CancelledError:
            raise
        except Exception as e:  # noqa: BLE001  出错也不能让单子卡死:下轮再试
            log.exception("定时补货自动核实出错")
            run = self.run(rid) or {}
            if run.get("create_unknown_at"):
                nxt = self.now(run["store_id"]) + dt.timedelta(minutes=SCHED_RECONCILE_RETRY_MIN)
                db.q(update(runs_t).where(runs_t.c.id == rid).values(next_retry_at=nxt))
                self.emit(f"自动核实 {run['doc_no']} 出错:{type(e).__name__}: {e}", "error", store_id=run["store_id"],
                          ref=self.ref(rid))
        finally:
            self._reconciling.discard(rid)

    async def recover(self) -> None:
        """服务重启:取数中的改为立即重试(单次补货直接结束);刷新中的回到待确认(数据已过期,须再刷新);
        建单中的结果未知 → 单次补货进入建单异常(自动核实);定时补货回到待确认并标记,系统自动到 DMS 核实(绝不直接重建);
        提交中的结果未知(告警,绝不重试);最近 24 小时已提交、还没有提交后截图的补截;截图中的:定时 / 批量补货转为待确认提交(采购单已建好、信息已落库,截图记为没发出),
        单次补货直接结束(草稿留在 DMS 待人工处理);待确认提交的保持不变(不过期)。"""
        history.recover()
        since = db.now() - dt.timedelta(hours=24)
        for po in db.rows(select(po_t.c.run_id).where(po_t.c.status == "已提交", po_t.c.submitted_at >= since,
                                                      po_t.c.submit_shots.is_(None),
                                                      po_t.c.submit_shots_error.is_(None))):
            self.spawn(self._submit_shots_guard(po["run_id"]), f"restock-submit-shots-{po['run_id']}")
        for r in db.rows(select(runs_t).where(runs_t.c.status.in_(("scanning", "refreshing", "creating",
                                                                   "screenshotting", "submitting")))):
            if r["status"] == "scanning" and r["kind"] == "scheduled":
                db.q(update(runs_t).where(runs_t.c.id == r["id"]).values(status="scan_retry", next_retry_at=db.now(),
                                                                         message="服务重启,自动重新取数"))
            elif r["status"] == "scanning":
                self._set(r["id"], "error", message="服务重启时正在查询,请重新发一次")
            elif r["status"] == "refreshing":
                self._set(r["id"], "awaiting_confirm", message="服务重启时正在刷新,请再刷新一次", data_fetched_at=None)
            elif r["status"] == "creating":
                # 结果未知:单次补货进入建单异常(自动核实);定时补货回到待确认并标记,再确认时先核实,绝不直接重建
                await self._create_failed(r, "服务重启时正在建单,结果未知", True, {"stage": "server_restart"})
            elif r["status"] == "submitting":
                self._set(r["id"], "error", message=f"服务重启时正在提交 {r['order_no']},结果未知,请到 DMS 核实")
                self.audit(r["store_id"], Actor.system("服务重启"), "po.submit_unknown", target_type="purchase_order",
                           target_id=str(r["order_no"]), ref=self.ref(r["id"]), detail={"reason": "服务重启时正在提交"})
                await alerts.open_alert(r["store_id"], "restock.submit_unknown", f"run:{r['id']}", "critical",
                                        "提交结果未知,请人工到 DMS 核实",
                                        f"补货单 {r['doc_no']}:云端重启时正在提交采购单 {r['order_no']},系统不会重试,"
                                        "请到 DMS「采购订单管理」看它是不是「已提交」。")
            elif r["kind"] in PAGE_KINDS and r["order_id"] and self.po_of(r["id"]):
                # 采购单已在 DMS 建好、信息已落库:转为待确认提交,计划员在单据页核对后照常确认提交
                self._set(r["id"], "awaiting_submit",
                          message=f"截图阶段服务重启,截图没发出;采购单 {r['order_no']} 已建好,等确认提交")
                self.audit(r["store_id"], Actor.system("服务重启"), "run.recover_screenshot", target_type="run",
                           target_id=str(r["id"]), ref=self.ref(r["id"]), detail={"order_no": r["order_no"]})
                await self.say(r, self.t(r["store_id"], "msg_recover_shot", order_no=r["order_no"], doc=r["doc_no"],
                                         link=self.link(r)), at_planners=True)
            else:
                self._set(r["id"], "done", message=f"截图阶段服务重启,截图未发出;采购单 {r['order_no']} 留在 DMS「待提交」,请人工处理")

    # ====================================================================== 留痕表
    def trace_rows(self, sid: int, since: dt.date, until: dt.date) -> list[dict]:
        runs = db.rows(select(runs_t).where(runs_t.c.store_id == sid, runs_t.c.biz_date >= since,
                                            runs_t.c.biz_date <= until, runs_t.c.status != "superseded")
                       .order_by(runs_t.c.id))
        out = []
        for r in runs:
            po = db.one(select(po_t).where(po_t.c.run_id == r["id"]).order_by(po_t.c.id.desc()).limit(1))
            for l in self.lines(r["id"]):
                out.append({"业务日期": str(r["biz_date"]), "类型": KIND_CN.get(r["kind"], r["kind"]),
                            "补货单号": r["doc_no"], "补货单状态": STAGE_CN.get(r["status"], r["status"]),
                            "采购单号": (po or {}).get("order_no") or "", "分组": planner.GROUP_LABEL.get(l.grp, l.grp),
                            "零件分类": l.category, "SO 命中": (l.so_hit or {}).get("order_count") or "",
                            "配件码": l.part_no, "名称": l.name, "出库": l.outbound_qty, "库存": l.stock,
                            "在途": l.in_transit, "月均": l.mad if l.mad is not None else "", "可订": l.cap if l.cap is not None else "",
                            "默认期望": l.default_expected, "默认来源": planner.SOURCE_LABEL.get(l.default_source, ""),
                            "期望": l.expected, "人工修改": "是" if l.modified else "", "勾选": "是" if l.checked else "",
                            "订购量": l.final_qty if l.orderable and po else 0,
                            "未订原因": "" if (l.orderable and po) else (l.note or planner.TAG_LABEL.get(l.tag, "") or
                                                                        STAGE_CN.get(r["status"], "")),
                            "触发方式": TRIGGER_CN.get(r["trigger"], r["trigger"] or ""), "确认人": r["confirmed_by"] or "",
                            "确认时间": str(r["confirmed_at"] or ""), "建单时间": str((po or {}).get("created_at") or ""),
                            "采购单状态": (po or {}).get("status") or "", "确认提交人": r["submitted_by"] or "",
                            "确认提交方式": VIA_CN.get(r["submitted_via"] or "", ""),
                            "DMS 提交人": (po or {}).get("apply_operator") or "",
                            "DMS 提交时间": (po or {}).get("apply_time") or ""})
        return out

    @staticmethod
    def to_csv(rows: list[dict]) -> str:
        buf = io.StringIO()
        if rows:
            w = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
            w.writeheader()
            w.writerows(rows)
        return "" + buf.getvalue()


svc = RestockService()