actions.py 95 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
# -*- coding: utf-8 -*-
"""取数端的业务动作。菜单(本地独立运行)和云端任务共用同一套实现;每个动作都把结果落到本地结果目录。

动作只有:自检 / 零件出库明细(定时补货候选)/ 查库存·主数据·全国仓 / 近期 SO 单同步 / 建采购单(待提交)/
截图采购单(DMS 页面截图失败时用接口数据渲染兜底)/ 提交采购单(人工确认后「检查并提交」)/
历史数据导出(全量库存、某年采购单及明细)。**没有删除采购单的实现**。
订单类型固定 SO(ORDER_TYPE),任何参数都改不了。

每个动作都接受 steps(core.tasks.TaskContext;本地菜单用 NullSteps):按步骤上报进度、套用云端下发的步骤超时。
"""
import datetime
import json
import logging
import math
import os
import re
import time

from .browser import cdp, screenshot
from .connectors.gtmc.api import ApiError, NetworkError, build_po_detail, build_po_payload
from .core.tasks import NullSteps, TaskError
from .infra import netdiag
from .infra.localstore import RunDir
from .infra.logs import scrub

log = logging.getLogger("edge")

STOCK_COLUMNS = ["partNo", "partName", "locationNo", "mfrType", "stockFlag", "partTypeMain", "partTypeStore",
                 "storageLevel", "storageQty", "transShippedQty", "abnormalPartQty", "partPresentQty",
                 "optimalStockQty", "mad", "srpPrice", "partStockCostWithTax", "warehouseAge", "partReplaceCode",
                 "remark"]
# 采购单列表行 / 明细行的字段(来自 HAR:get-parts-po-page / get-parts-po-detail-page 的返回)
PO_COLUMNS = ["id", "orderNo", "orderType", "orderStatus", "orderSource", "supplierCode", "supplierName",
              "dealerCode", "dealerName", "createTime", "createByName", "createBy", "applyTime", "applyOperator",
              "updateTime", "updateByName", "updateBy", "lastReceiveDate", "itemNum", "partItemNum", "passItemNum",
              "requiredItem", "requiredItemNum", "totalAmount", "oldTotalAmount", "remark", "sourceNo",
              "salesOrderNo", "salesOrderType", "workOrderNo", "licensePlateNumber", "archiveFlag", "delFlag",
              "version"]
PO_LINE_COLUMNS = ["id", "orderId", "orderNo", "itemNo", "partNo", "partName", "partType", "partUnit", "partSource",
                   "partStatus", "mfrType", "keyFlag", "purchaseQty", "unitPrice", "totalPrice", "totalPriceSum",
                   "receivedQty", "receivedCordQty", "receivedType", "receiveId", "receiveNo", "unreceivedQty",
                   "cancelledQty", "transShippedQty", "storageQty", "minPurchaseQty", "limitType",
                   "dailyOrderLimit", "dailyPurchasedCount", "dailyStorageLimit", "dailySurplusPurQty",
                   "processStatus", "tempStatus", "generateInstructionStatus", "instructionsGenerateQty", "isTotal",
                   "operater", "saName", "remark", "salesOrderNo", "salesOrderType", "sourceNo",
                   "licensePlateNumber", "createTime", "createByName", "createBy", "updateTime", "updateByName",
                   "updateBy", "delFlag", "version"]


class ActionError(TaskError):
    def __init__(self, message, code="action_error", result=None):
        super(ActionError, self).__init__(message, code, result)


class UnknownResult(ActionError):
    """建单请求已经发出,但不知道 DMS 有没有建成(网络中断等):绝不重试,提示人工核实。"""

    def __init__(self, message, result=None):
        super(UnknownResult, self).__init__(message, "unknown_result", dict(result or {}, unknown=True))


IN_TRANSIT_LABEL = {"trans_shipped": "调拨在途", "unreceived": "未收货", "max": "两者取大"}
ORDER_TYPE = "S"            # 订单类型写死 SO(库存补充订单):云端 / 菜单 / 智能体都不能改
KIND_CN = {"single": "单次补货", "scheduled": "定时补货"}


def _allowed(cfg, action, kind):
    """云端运行参数里的业务开关:action = create / submit,kind = single / scheduled(不认识的按单次补货)。"""
    kind = kind if kind in KIND_CN else "single"
    return bool(getattr(cfg, "allow_%s_%s" % (action, kind), True)), KIND_CN[kind]


def pick_in_transit(trans_shipped, unreceived, field):
    """在途口径:两个原始字段都保存,计算时按配置取一个(默认调拨在途)。"""
    if field == "unreceived":
        return unreceived
    if field == "max":
        return max(trans_shipped, unreceived)
    return trans_shipped


def _num(v, default=0.0):
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def _int_or_none(v):
    try:
        return None if v is None or v == "" else int(float(v))
    except (TypeError, ValueError):
        return None


def _po_item_count(lines):
    """采购单明细的「项数」。分批收货的行 DMS 按每张收货单各返回一行(同 itemNo、同零件,receiveNo 不同),
    而订单头 itemNum 按 itemNo 计,所以和 itemNum 比对要按 itemNo 去重;任何一行缺 itemNo 就按行数算。"""
    nos = [ln.get("itemNo") for ln in lines]
    return len(lines) if any(n in (None, "") for n in nos) else len({str(n) for n in nos})


# ====================================================================== 自检
def diag_table(rd, diag):
    rd.table("网络诊断(DNS → TCP → TLS → HTTP,每个目标测多轮)", diag,
             ["name", "host", "success", "dns", "tcp", "tls", "http", "failures"],
             ["目标", "地址", "成功轮数", "DNS", "TCP", "TLS", "HTTP GET", "失败原因"])


def attach_debug(rd):
    """截图失败时,把浏览器当时的画面(debug_*.png)和诊断信息(debug_*.json)放进结果页。"""
    import glob
    import os
    for png in sorted(glob.glob(rd.file("debug_*.png"))):
        rd.image("截图失败时浏览器的画面(%s)" % os.path.basename(png)[6:-4], os.path.basename(png))
    for js in sorted(glob.glob(rd.file("debug_*.json"))):
        rd.files.append(os.path.basename(js))
        try:
            with open(js, encoding="utf-8") as f:
                info = json.load(f)
        except Exception:  # noqa: BLE001
            continue
        rows = [{"k": k, "v": info.get(k)} for k in ("strategy", "error", "href", "title", "local_storage_keys",
                                                     "session_storage_keys", "cookies")]
        rows += [{"k": "%s %s" % (p.get("time"), p.get("kind")), "v": "%s %s" % (p.get("url"), p.get("detail"))}
                 for p in info.get("problems") or []]
        rd.table("截图诊断(%s)" % info.get("strategy"), rows, ["k", "v"], ["项", "值"])


AUDIT_PATTERNS = ("audit.*", "*.har", "debug_*", "ui_*.png", "summary.json", "index.html", "login_trace.json")


def attach_audit(rd):
    """结果页里挂上审计时间线和抓包文件的链接。"""
    import os
    names = [n for n in ("audit.html", "audit.jsonl", "browser.har", "http.har") if os.path.exists(rd.file(n))]
    if names:
        rd.files += names
        rd.sections.append(("审计与抓包", "<p>%s(HAR 可用 Chrome 开发者工具 Network 面板导入查看;密码、token、Cookie 值已打码)</p>"
                            % " ".join('<a href="%s" target=_blank>%s</a>' % (n, n) for n in names)))


def upload_audit(cfg, ctx, rd, ok, uploader=None):
    """按云端运行参数 upload_audit(never / on_failure / always)把审计包打成 zip 作为任务证据上传。"""
    import glob
    import os
    import zipfile
    mode = getattr(cfg, "upload_audit", "on_failure")
    up = uploader or getattr(ctx, "upload", None)
    if mode == "never" or (mode == "on_failure" and ok) or not up or not getattr(ctx, "task_id", None):
        return None
    files = sorted({f for p in AUDIT_PATTERNS for f in glob.glob(rd.file(p))})
    if not files:
        return None
    path = os.path.join(rd.path, "..", "audit_%s_%s.zip" % (rd.action, os.path.basename(rd.path)))
    try:
        with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
            for f in files:
                z.write(f, os.path.basename(f))
        eid = up(path, "file")
        log.info("审计包已上传云端(%d 个文件%s)", len(files), ",证据 id %s" % eid if eid else "")
        return eid
    except Exception as e:  # noqa: BLE001  上传失败不影响任务结果
        log.warning("审计包上传失败:%s", e)
        return None
    finally:
        try:
            os.remove(path)
        except OSError:
            pass


def write_login_trace(rd, sess):
    """把最近的 HTTP 请求轨迹(已脱敏)写进结果目录:login_trace.json + 页面表格。"""
    rows = []
    for t in getattr(sess.client, "trace", []):
        r = dict(t)
        for k in ("url", "location", "error", "resp_snippet"):
            if r.get(k):
                r[k] = scrub(r[k])
        r["cookie_names"] = ",".join(r.get("cookie_names") or [])
        r["resp_headers"] = ",".join(r.get("resp_headers") or [])
        r["req_headers"] = ",".join(r.get("req_headers") or [])
        rows.append(r)
    rd.write_json("login_trace.json", rows)
    rd.table("登录请求轨迹(按时间顺序,已脱敏)", rows,
             ["time", "method", "url", "status", "elapsed", "error", "cookie_names", "cookie_header_len",
              "sent_bytes", "resp_bytes", "location"],
             ["时间", "方法", "地址", "状态", "耗时", "错误", "发出的 Cookie", "Cookie 字节", "请求体字节",
              "响应字节", "跳转到"])


def check(cfg, sess, parts, steps=None, take_screenshot=True):
    """只读自检:登录态、库存 1 页、期望件 master/全国仓、采购单列表 1 页、列表页截图。不建单。

    登录这一步**不强制重新登录**:已有可用的登录态就复用(用一次接口验证),失效才输密码。
    以前每次自检都重新登录,14:00 / 14:45 两次预检就是两次密码登录。"""
    ctx = steps or NullSteps()
    rd = RunDir(cfg.data_dir, "check")
    steps = []

    def step(name, fn, code="check", detail="", on_timeout=None):
        t0 = time.time()
        try:
            with ctx.step(code, detail or name, on_timeout=on_timeout):
                msg = fn()
            steps.append({"step": name, "ok": True, "detail": msg, "seconds": round(time.time() - t0, 1)})
            log.info("[自检] [通过] %s:%s", name, msg)
            return True
        except Exception as e:  # noqa: BLE001
            steps.append({"step": name, "ok": False, "detail": "%s: %s" % (type(e).__name__, e),
                          "seconds": round(time.time() - t0, 1)})
            log.error("[自检] [失败] %s:%s: %s", name, type(e).__name__, e)
            return False

    def login_step():
        how = sess.ensure_valid()
        left = sess.token.left_seconds() if sess.token else None
        return "%s,token 还剩约 %s 小时,今日已登录 %s 次" % (
            {"reused": "复用已有登录", "login": "新登录成功", "relogin": "原登录失效,已重新登录"}.get(how, how),
            "%.1f" % (left / 3600.0) if left is not None else "?", sess.stats.get("today_logins"))
    if not step("登录 DMS", login_step, "login"):
        rd.table("自检步骤", steps, ["step", "ok", "detail", "seconds"], ["步骤", "通过", "说明", "耗时(秒)"])
        write_login_trace(rd, sess)
        log.info("[自检] 登录失败,做一次网络诊断(不登录、不发密码)……")
        diag = netdiag.run(cfg, sess.client)
        diag_table(rd, diag)
        rd.write_json("netdiag.json", diag)
        rd.finish(False, {"message": "登录失败,后面的检查没有执行(页面下方有登录请求轨迹和网络诊断)",
                          "steps": steps, "netdiag": diag})
        return {"ok": False, "steps": steps, "dir": rd.path}

    def stock1():
        total, rows = sess.stock_page(1, 5)
        rd.write_json("stock_page1.json", rows)
        return "库存总条数 %d,样例 %s" % (total, rows[0].get("partNo") if rows else "无")
    step("库存查询(第 1 页)", stock1, "query_part", "库存第 1 页")

    for p in parts:
        pn = p["part_no"]

        def one(pn=pn):
            rows, total = sess.stock_of(pn)
            m = sess.part_master(ORDER_TYPE, cfg.supplier_code, pn, 1)
            nat = sess.national_inventory(pn)
            rd.write_json("check_%s.json" % pn, {"stock_rows": rows, "master": m, "national": nat})
            wh = {r.get("dsn"): r.get("balSales") for r in nat if r.get("dsn") in cfg.warehouses}
            return "%s 库存行 %d,名称 %s,当日剩余可订 %s,单价 %s,关注仓 %s" % (
                pn, len(rows), m.get("partName"), m.get("dailySurplusPurQty"), m.get("unitPrice"), wh or "未找到")
        step("配件 %s 库存/主数据/全国仓" % pn, one, "query_part", pn)

    holder = {}

    def po1():
        total, rows = sess.po_page(1, 5)
        holder["rows"] = rows
        rd.write_json("po_page1.json", rows)
        return "采购单总数 %s,最新 %s(状态 %s)" % (total, rows[0].get("orderNo") if rows else "无",
                                                rows[0].get("orderStatus") if rows else "-")
    step("采购单列表(第 1 页)", po1, "verify_po", "采购单列表第 1 页")

    def shot():
        rows = holder.get("rows") or []
        must = [rows[0]["orderNo"]] if rows and rows[0].get("orderNo") else []
        ok = False
        try:
            files = screenshot.capture(cfg, sess, [("check_po_list.png", screenshot.po_list_url(cfg), must)], rd.path)
            ok = True
        finally:
            attach_debug(rd)
            attach_audit(rd)
            upload_audit(cfg, ctx, rd, ok)
        rd.image("采购订单管理页截图", "check_po_list.png")
        return "已截图 %s" % files[0]
    if take_screenshot:
        cdp.CANCEL.clear()
        step("截图「采购订单管理」页(只读)", shot, "screenshot", "采购订单管理页", cdp.kill_active)

    ok = all(s["ok"] for s in steps)
    rd.table("自检步骤", steps, ["step", "ok", "detail", "seconds"], ["步骤", "通过", "说明", "耗时(秒)"])
    rd.finish(ok, {"message": "全部通过" if ok else "有检查项失败,见下表", "steps": steps})
    return {"ok": ok, "steps": steps, "dir": rd.path}


# ====================================================================== 历史数据导出(只读)
def _stock_dump(cfg, sess, rd):
    """分页拉全量库存写 stock_full.csv。返回 (统计, 问题列表);数量对不上只记进问题列表,不抛异常。"""
    f, w = rd.open_csv_writer("stock_full.csv", STOCK_COLUMNS)
    t0 = time.time()
    size = cfg.page_size
    fetched, first_total, last_total, page = 0, None, None, 1
    keys = set()
    dup = 0
    try:
        while page <= cfg.max_pages:
            total, rows = sess.stock_page(page, size)
            if first_total is None:
                first_total = total
                if rows and len(rows) < min(size, total):
                    log.warning("服务端每页最多返回 %d 条(请求 %d),改用 %d", len(rows), size, len(rows))
                    size = len(rows)
            last_total = total
            for r in rows:
                w.writerow(["" if r.get(c) is None else r.get(c) for c in STOCK_COLUMNS])
                k = (r.get("partNo"), r.get("locationNo"))
                dup += k in keys
                keys.add(k)
            fetched += len(rows)
            if page % 10 == 0 or not rows or fetched >= total:
                log.info("全量库存:第 %d 页,已取 %d / %d(%.0f 秒)", page, fetched, total, time.time() - t0)
            if not rows or fetched >= total:
                break
            page += 1
    finally:
        f.close()
    problems = []
    if first_total != last_total:
        problems.append("拉取期间总数变化 %s → %s" % (first_total, last_total))
    if fetched != last_total:
        problems.append("导出 %d 行 ≠ 接口总数 %s" % (fetched, last_total))
    if dup:
        problems.append("(partNo, locationNo) 重复 %d 行" % dup)
    return {"rows": fetched, "total": last_total, "pages": page, "seconds": round(time.time() - t0)}, problems


def _year_of(row):
    return str(row.get("createTime") or "")[:4]


def _po_dump(cfg, sess, rd, year):
    """指定年份的采购单列表 + 每张单的明细 → po_headers_<年>.csv / po_lines_<年>.csv。"""
    year, t0 = str(year), time.time()
    problems, all_n, mine, seen, last_total = [], 0, [], set(), None
    fh, hw = rd.open_csv_writer("po_headers_%s.csv" % year, PO_COLUMNS)
    try:
        for total, page, rows in sess.po_iter_all(cfg.page_size, cfg.max_pages):
            last_total = total
            all_n += len(rows)
            for r in rows:
                if _year_of(r) == year and r.get("orderNo") not in seen:
                    seen.add(r.get("orderNo"))
                    hw.writerow(["" if r.get(c) is None else r.get(c) for c in PO_COLUMNS])
                    mine.append(r)
            if page % 5 == 0 or not rows:
                log.info("采购单列表:第 %d 页,已读 %d / %s,%s 年 %d 张", page, all_n, total, year, len(mine))
    finally:
        fh.close()
    if last_total is not None and all_n != int(last_total):
        problems.append("采购单列表读到 %d 张 ≠ 接口总数 %s" % (all_n, last_total))
    log.info("采购单共读取 %d 张,其中 %s 年 %d 张;开始取明细(约 %d 分钟)", all_n, year, len(mine),
             int(len(mine) * cfg.request_interval / 60) + 1)
    lh, lw = rd.open_csv_writer("po_lines_%s.csv" % year, PO_LINE_COLUMNS)
    lines_n, bad = 0, []
    try:
        for i, h in enumerate(mine, 1):
            total, lines = sess.po_detail_all(h)
            for ln in lines:
                ln.setdefault("orderNo", h.get("orderNo"))
                ln.setdefault("orderId", h.get("id"))
                lw.writerow(["" if ln.get(c) is None else ln.get(c) for c in PO_LINE_COLUMNS])
            lines_n += len(lines)
            want, items = _int_or_none(h.get("itemNum")), _po_item_count(lines)
            if (total is not None and total != len(lines)) or (want is not None and want != items):
                bad.append("%s 明细 %d 行 %d 项(接口 total=%s,订单头 itemNum=%s)" % (h.get("orderNo"), len(lines), items,
                                                                              total, want))
            if i % 20 == 0:
                log.info("明细进度:%d / %d 张,累计 %d 行(%.0f 秒)", i, len(mine), lines_n, time.time() - t0)
    finally:
        lh.close()
    if bad:
        problems.append("明细行数与订单头不一致 %d 张:%s%s" % (len(bad), ";".join(bad[:10]),
                                                       " …" if len(bad) > 10 else ""))
    return {"year": year, "po_all": all_n, "po_year": len(mine), "po_line_rows": lines_n,
            "seconds": round(time.time() - t0)}, problems


def export_history(cfg, sess, kind, year=None, steps=None, uploader=None):
    """一次性导出(只读 DMS):kind=stock 全量库存 / po 指定年份(默认今年)的采购单头 + 明细。
    文件写在本地结果目录;uploader(path, kind) 给了就上传云端(后台「数据导出」里下载)。"""
    ctx = steps or NullSteps()
    if kind not in ("stock", "po"):
        raise ActionError("导出内容只能是 stock / po")
    year = str(year or datetime.date.today().year)
    rd = RunDir(cfg.data_dir, "export_" + kind)
    with ctx.step("login"):
        sess.ensure_valid()
    try:
        with ctx.step("export", "全量库存" if kind == "stock" else "%s 年采购单" % year):
            if kind == "stock":
                stats, problems = _stock_dump(cfg, sess, rd)
                files = [rd.file("stock_full.csv")]
                msg = "全量库存 %d 行(接口总数 %s),耗时 %s 秒" % (stats["rows"], stats["total"], stats["seconds"])
            else:
                stats, problems = _po_dump(cfg, sess, rd, year)
                files = [rd.file("po_headers_%s.csv" % year), rd.file("po_lines_%s.csv" % year)]
                msg = "%s 年采购单 %d 张(列表共 %d 张)、明细 %d 行,耗时 %s 秒" % (
                    year, stats["po_year"], stats["po_all"], stats["po_line_rows"], stats["seconds"])
    except BaseException as e:
        rd.note("失败", "%s: %s" % (type(e).__name__, e), "err")
        rd.finish(False, {"message": str(e)})
        raise
    if problems:
        msg += ";" + ";".join(problems)
    rd.note("结论", msg, "warn" if problems else "ok")
    rd.finish(True, {"message": msg, "stats": stats, "problems": problems})
    log.info(msg)
    evidence = []
    if uploader:
        with ctx.step("upload", "上传 %d 个文件" % len(files), timeout=600):
            for f in files:
                eid = uploader(f, "export")
                if eid:
                    evidence.append(eid)
    return {"ok": True, "status": "partial" if problems else "success", "message": msg, "problems": problems,
            "summary": dict(stats, problems=problems), "files": files, "evidence": evidence, "dir": rd.path}


# ====================================================================== 零件出库明细(批量补货的候选来源)
TIME_FMT = "%Y-%m-%d %H:%M:%S"
SHIP_COLUMNS = ["id", "shipmentDate", "workOrderNo", "shipmentBatchNo", "licensePlateNumber", "mfr", "partNo",
                "partName", "settlStatus", "reqQty", "partUnitPrice", "totalAmount", "costPrice", "totalCostPrice"]
PART_COLUMNS = ["part_no", "name", "qty", "rows", "amount"]


def is_subtotal(r):
    """出库明细接口在每个工单后面插一行小计:id / partNo / shipmentDate 都为空,partName =「小计(工单号)」。"""
    return not r.get("id") and not r.get("partNo")


def fetch_outbound(sess, day_from, day_to, size=100, max_pages=500):
    """按出库日期(只到天)拉全部出库明细。返回 (明细行, 统计)。

    分页按**工单**计数(pageSize=100 → 100 个工单的明细 + 各自的小计行):页数 × pageSize >= total 即取完;
    剔除小计行、按 id 去重;服务端忽略页码(连续两页完全相同)时立即停止。"""
    rows, seen, pages, subtotals, dup, total, last_ids, page = [], set(), 0, 0, 0, None, None, 1
    while page <= max_pages:
        total, batch = sess.shipment_page(day_from, day_to, page, size)
        pages += 1
        details = [r for r in batch if not is_subtotal(r)]
        subtotals += len(batch) - len(details)
        ids = [r.get("id") for r in details]
        if details and ids == last_ids:
            log.warning("出库明细第 %d 页与上一页完全相同(服务端可能忽略了页码),停止翻页", page)
            break
        last_ids = ids
        for r in details:
            if r.get("id") in seen:
                dup += 1
                continue
            seen.add(r.get("id"))
            rows.append(r)
        if not details or (total is not None and page * size >= total):
            break
        page += 1
    return rows, {"pages": pages, "page_size": size, "work_orders": total, "detail_rows": len(rows),
                  "subtotal_rows": subtotals, "dup_rows": dup}


def summarize_outbound(rows, win_start, win_end, pure_label="纯牌", known_mfr=("纯牌", "非纯")):
    """按 [win_start, win_end) 切窗(出库日带时分秒,转成时间再比)、筛厂家分类 = 纯牌、按零件号汇总净出库量。

    数量是字符串,可能为负(退货冲销):按净额算,净额 <= 0 的零件不进候选(在 nonpositive_parts 里列出)。
    返回 {"window_rows": 窗口内全部明细(所有厂家分类), "parts": 纯牌零件汇总(按净出库量倒序), "stats": 统计}。"""
    start = datetime.datetime.strptime(win_start, TIME_FMT)
    end = datetime.datetime.strptime(win_end, TIME_FMT)
    window, bad = [], []
    for r in rows:
        try:
            t = datetime.datetime.strptime(str(r.get("shipmentDate") or "")[:19], TIME_FMT)
        except ValueError:
            bad.append(r.get("id"))
            continue
        if start <= t < end:
            window.append(r)
    mfr = {}
    for r in window:
        k = str(r.get("mfr") or "").strip() or "(空)"
        mfr[k] = mfr.get(k, 0) + 1
    pure = [r for r in window if str(r.get("mfr") or "").strip() == pure_label]
    agg, neg = {}, 0
    for r in pure:
        pn = str(r.get("partNo") or "").strip()
        q = _num(r.get("reqQty"))
        neg += q < 0
        a = agg.get(pn)
        if a is None:
            a = agg[pn] = {"part_no": pn, "name": r.get("partName") or "", "qty": 0.0, "rows": 0, "amount": 0.0,
                           "ids": []}
        a["qty"] += q
        a["rows"] += 1
        a["amount"] += _num(r.get("totalAmount"))
        a["ids"].append(r.get("id"))
        a["name"] = a["name"] or r.get("partName") or ""
    parts = sorted(agg.values(), key=lambda a: (-a["qty"], a["part_no"]))
    for a in parts:
        a["qty"], a["amount"] = round(a["qty"], 3), round(a["amount"], 2)
    stats = {"window_start": win_start, "window_end": win_end, "fetched_rows": len(rows), "window_rows": len(window),
             "pure_rows": len(pure), "nonpure_rows": len(window) - len(pure), "mfr_counts": mfr,
             "unknown_mfr": sorted(k for k in mfr if k not in known_mfr), "negative_rows": neg,
             "bad_date_rows": len(bad), "pure_parts": len(parts), "candidates": sum(1 for a in parts if a["qty"] > 0),
             "nonpositive_parts": [a["part_no"] for a in parts if a["qty"] <= 0]}
    return {"window_rows": window, "parts": parts, "stats": stats}


def outbound(cfg, sess, window_start, window_end, pure_label="纯牌", known_mfr=("纯牌", "非纯"), steps=None):
    """批量补货第 1 步(只读):零件出库明细 → 切 15:00 窗口 → 筛纯牌 → 按零件净额汇总 → 与合计接口对账。

    window_start / window_end:「yyyy-MM-dd HH:mm:ss」,左闭右开。按日期查「起始日 ~ 结束日」,再按出库时间精确切窗。"""
    ctx = steps or NullSteps()
    day_from, day_to = window_start[:10], window_end[:10]
    with ctx.step("login"):
        sess.ensure_valid()
    rd = RunDir(cfg.data_dir, "outbound")
    with ctx.step("query_outbound", "出库明细 %s ~ %s" % (day_from, day_to)):
        rows, fstats = fetch_outbound(sess, day_from, day_to, cfg.page_size, cfg.max_pages)
        totals = sess.shipment_total(day_from, day_to)
    detail_amount = round(sum(_num(r.get("totalAmount")) for r in rows), 2)
    detail_cost = round(sum(_num(r.get("totalCostPrice")) for r in rows), 2)
    recon = {"days": "%s ~ %s" % (day_from, day_to), "detail_amount": detail_amount,
             "api_amount": totals["total_amount"], "detail_cost": detail_cost, "api_cost": totals["total_cost"]}
    recon["ok"] = (totals["total_amount"] is not None and abs(detail_amount - totals["total_amount"]) < 0.05
                   and (totals["total_cost"] is None or abs(detail_cost - totals["total_cost"]) < 0.05))
    res = summarize_outbound(rows, window_start, window_end, pure_label, known_mfr)
    stats = dict(fstats, **res["stats"])
    rd.write_csv("outbound_rows.csv", rows, SHIP_COLUMNS)
    rd.write_csv("outbound_parts.csv", res["parts"], PART_COLUMNS)
    rd.write_json("outbound_stats.json", {"stats": stats, "reconcile": recon})
    rd.table("纯牌零件净出库(窗口 %s ~ %s)" % (window_start, window_end), res["parts"], PART_COLUMNS,
             ["零件号", "名称", "净出库", "明细行数", "销售金额"])
    rd.note("对账", "明细销售金额合计 %s,合计接口 %s;成本 %s / %s → %s" % (
        detail_amount, totals["total_amount"], detail_cost, totals["total_cost"], "一致" if recon["ok"] else "不一致"),
        "ok" if recon["ok"] else "warn")
    msg = "出库明细 %d 行(%s 个工单、%d 页),窗口内 %d 行,纯牌 %d 行 → %d 种零件,其中净出库 > 0 的 %d 种;对账%s" % (
        len(rows), fstats["work_orders"] if fstats["work_orders"] is not None else "?", fstats["pages"],
        stats["window_rows"], stats["pure_rows"], stats["pure_parts"], stats["candidates"],
        "一致" if recon["ok"] else "不一致")
    if stats["unknown_mfr"]:
        msg += ";出现未知的厂家分类:%s" % "、".join(stats["unknown_mfr"])
    rd.finish(True, {"message": msg, "stats": stats, "reconcile": recon})
    log.info(msg)
    return {"ok": True, "message": msg, "rows": res["window_rows"], "parts": res["parts"], "stats": stats,
            "reconcile": recon, "dir": rd.path}


# ====================================================================== 查库存 / 主数据 / 全国仓(批量、刷新、单次共用)
def quote(cfg, sess, parts, warehouses=None, supplier_code=None, order_type=None, in_transit_field=None, steps=None):
    """parts: [{part_no, name, national}]。逐件(串行,走全局节拍)查:
      库存(精确匹配 partNo、多库位汇总,带月均 MAD)+ 订货主数据(当日剩余可订 / 单价 / 未收货 / 起订量 / 包装数)
      + national=True 的查全国仓(只取关注仓)。
    只采集事实,分组、期望和补货量由云端算。单个配件出错不影响其它配件(带 error 回传)。
    order_type 参数只为兼容旧云端保留,一律按 ORDER_TYPE(SO)查。"""
    ctx = steps or NullSteps()
    warehouses = warehouses or cfg.warehouses
    supplier_code = supplier_code or cfg.supplier_code
    order_type = ORDER_TYPE
    field = in_transit_field or cfg.in_transit_field
    with ctx.step("login"):
        sess.ensure_valid()
    rd = RunDir(cfg.data_dir, "quote")
    items, errors, raw = [], [], {}
    for p in parts:
        pn = str(p["part_no"]).strip()
        it = {"part_no": pn, "name": p.get("name") or "", "error": "", "warnings": [],
              "national_queried": bool(p.get("national"))}
        try:
            with ctx.step("query_part", pn):
                _quote_one(sess, it, pn, raw, warehouses, supplier_code, order_type, field, bool(p.get("national")))
        except Exception as e:  # noqa: BLE001
            it["error"] = "%s: %s" % (type(e).__name__, e)
            errors.append("%s %s" % (pn, it["error"]))
            log.error("查询 %s 失败:%s", pn, it["error"])
        items.append(it)
        log.info("查询 %s %s:库存 %s 在途 %s 月均 %s 可订 %s %s", pn, it.get("name"), it.get("stock"),
                 it.get("in_transit"), it.get("mad"), it.get("daily_surplus"), it.get("warehouses") or "")
    return _quote_finish(rd, items, errors, raw, warehouses, field)


def _quote_one(sess, it, pn, raw, warehouses, supplier_code, order_type, field, national):
    rows, _ = sess.stock_of(pn)
    raw[pn] = {"stock_rows": rows}
    if not rows:
        it["warnings"].append("库存查询里没有这个配件,按库存 0 处理")
    it["stock"] = sum(_num(r.get("storageQty")) for r in rows)
    it["trans_shipped"] = sum(_num(r.get("transShippedQty")) for r in rows)
    mads = [_num(r.get("mad")) for r in rows if r.get("mad") not in (None, "")]
    it["mad"] = max(mads) if mads else None
    it["locations"] = ",".join(sorted({str(r.get("locationNo") or "") for r in rows} - {""}))
    if rows and rows[0].get("partName"):
        it["name"] = it["name"] or rows[0]["partName"]
    m = sess.part_master(order_type, supplier_code, pn, 1)
    raw[pn]["master"] = m
    it["name_dms"] = m.get("partName") or ""
    it["name"] = it["name"] or it["name_dms"]
    it["unreceived"] = _num(m.get("unreceivedQty"))
    it["daily_surplus"] = _int_or_none(m.get("dailySurplusPurQty"))
    it["daily_limit"] = _int_or_none(m.get("dailyOrderLimit"))
    it["storage_limit"] = _int_or_none(m.get("dailyStorageLimit"))        # 库存超过它时 DMS 当日可订为 0
    it["purchased_today"] = _int_or_none(m.get("dailyPurchasedCount"))
    it["unit_price"] = _num(m.get("unitPrice"))
    it["min_qty"] = _int_or_none(m.get("minPurchaseQty")) or 1
    it["pack_qty"] = _int_or_none(m.get("packagesQty")) or 1
    it["in_transit"] = pick_in_transit(it["trans_shipped"], it["unreceived"], field)
    it["in_transit_field"] = field
    it["warehouses"] = {}
    if national:
        nat = sess.national_inventory(pn)
        raw[pn]["national"] = nat
        found = {r.get("dsn"): _num(r.get("balSales")) for r in nat if r.get("dsn") in warehouses}
        missing = [w for w in warehouses if w not in found]
        if missing:
            raise ActionError("全国仓库查询结果里找不到仓库 %s(返回的仓:%s)" % (
                "、".join(missing), "、".join(str(r.get("dsn")) for r in nat) or "无"))
        it["warehouses"] = found


def _quote_finish(rd, items, errors, raw, warehouses, field):
    rd.write_json("quote_raw.json", raw)
    view = []
    for it in items:
        v = dict(it)
        v["warehouses"] = ";".join("%s=%g" % kv for kv in (it.get("warehouses") or {}).items())
        v["warnings"] = ";".join(it.get("warnings") or [])
        view.append(v)
    cols = ["part_no", "name", "stock", "trans_shipped", "unreceived", "in_transit", "mad", "daily_surplus",
            "storage_limit", "min_qty", "pack_qty", "unit_price", "warehouses", "warnings", "error"]
    labels = ["配件码", "名称", "库存", "调拨在途", "未收货", "在途(按 %s)" % IN_TRANSIT_LABEL.get(field, field), "月均",
              "当日剩余可订", "库存上限", "起订量", "包装数", "单价", "关注仓库存", "提示", "错误"]
    rd.table("库存 / 主数据 / 关注仓(%s)" % "、".join(warehouses), view, cols, labels)
    rd.write_csv("quote.csv", view, cols)
    ok = not errors
    msg = "查询 %d 个配件%s" % (len(items), ";错误:" + ";".join(errors) if errors else "")
    rd.finish(ok, {"message": msg, "items": items})
    return {"ok": ok, "items": items, "errors": errors, "dir": rd.path}


# ====================================================================== 近 N 个月 SO 采购单(每周同步一次)
def _po_lists(sess, size, max_pages, since, filters, first=None):
    """按 filters 翻采购单列表(服务端按创建时间倒序):整页都早于 since 就停。逐页产出 (page, rows)。

    first:探测时已经取到的第 1 页 (total, rows),直接复用不再重取。
    每页条数以服务端实际返回为准(DMS 限制 pageSize 时第 1 页会少于请求数,不能当成最后一页)。"""
    page, last_ids, fetched = 1, None, 0
    while page <= max_pages:
        if page == 1 and first is not None:
            total, rows = first
        else:
            total, rows = sess.po_page(page, size, **filters)
        if page == 1 and rows and total and len(rows) < min(size, int(total)):
            log.warning("采购单列表每页最多返回 %d 条(请求 %d),改用 %d", len(rows), size, len(rows))
            size = len(rows)
        ids = [r.get("id") or r.get("orderNo") for r in rows]
        if rows and ids == last_ids:
            log.warning("采购单列表第 %d 页与上一页完全相同(服务端可能忽略了页码),停止翻页", page)
            return
        last_ids = ids
        fetched += len(rows)
        yield page, rows
        if not rows or all(str(r.get("createTime") or "") < since for r in rows):
            return
        if (total is not None and fetched >= int(total)) or (total is None and len(rows) < size):
            return
        page += 1


def _po_fingerprint(h):
    """订单头指纹:状态 / 项数 / 金额 / 更新时间都没变,明细就当没变(云端下发上次的指纹)。"""
    return "%s|%s|%s|%s" % (h.get("orderStatus"), h.get("itemNum"), h.get("totalAmount"),
                            h.get("updateTime") or h.get("updateDate") or "")


def _po_summary(lines):
    """一张单的明细按零件汇总:[{part_no, name, qty}](分批收货的多行数量累加,扣除取消数量)。"""
    out = {}
    for ln in lines:
        pn = str(ln.get("partNo") or "").strip()
        if not pn:
            continue
        p = out.get(pn)
        if p is None:
            p = out[pn] = {"part_no": pn, "name": ln.get("partName") or "", "qty": 0.0}
        p["qty"] = round(p["qty"] + _num(ln.get("purchaseQty")) - _num(ln.get("cancelledQty")), 3)
    return list(out.values())


def so_sync(cfg, sess, since, order_type=ORDER_TYPE, exclude_status=("1",), steps=None, known=None):
    """近 N 个月 SO(库存补充)采购单 + 明细 → 按零件汇总(定时补货「历史常备件」判定用,云端每周同步一次)。

    known:云端缓存过明细的单 {单号: 订单头指纹}。指纹没变的单不再取明细(增量),结果里 details 只含新取的单,
    云端用缓存合并后再汇总;不传 known(本地菜单)时 details 含全部单。

    since:「yyyy-MM-dd」,只要创建时间 >= since 的单;exclude_status:排除的订单状态(默认 1 = 待提交)。
    先用服务端过滤(orderType + 创建日期起止):第 1 页返回全是该类型才信任;DMS 报错(如「特殊异常」)或过滤没生效,
    都退回不带过滤的全量列表(按创建时间倒序,整页早于 since 即停)+ 本地筛选。过滤参数、报错、第 1 页类型分布、
    是否退回、翻页数、停在哪页全部写进结果(云端存表)和日志,出问题直接看这里改。"""
    ctx = steps or NullSteps()
    order_type = ORDER_TYPE
    with ctx.step("login"):
        sess.ensure_valid()
    rd = RunDir(cfg.data_dir, "so_sync")
    size = cfg.page_size
    excl = set(str(x) for x in (exclude_status or ()))
    # 与 DMS 前端「采购订单管理」一致:创建日期是区间,起止成对、都是 YYYY-MM-DD(只传起始日期 DMS 报「特殊异常」)
    filters = {"orderType": order_type, "createDateBegin": since,
               "createDateEnd": datetime.date.today().strftime("%Y-%m-%d")}
    probe = {"filters": dict(filters)}
    known = known or {}
    orders, scanned, pages, stop_page, lines_n, bad, parts = [], 0, 0, None, 0, [], {}
    details, reused = {}, 0
    note = getattr(ctx, "note", None) or (lambda detail: None)
    with ctx.step("so_sync", "近期 %s 单(%s 起)" % (order_type, since)):
        try:
            first_total, first = sess.po_page(1, size, **filters)
        except ApiError as e:                # 服务端不认这组过滤参数:不让同步失败,退回全量翻页(与菜单里的请求一致)
            first_total, first = None, None
            probe["filter_error"] = str(e)
            log.warning("采购单列表带过滤查询报错(%s),改为全量翻页 + 本地筛选", e)
        types = {}
        for r in first or ():
            types[str(r.get("orderType"))] = types.get(str(r.get("orderType")), 0) + 1
        trusted = bool(first) and set(types) == {order_type}
        probe.update(first_page_types=types, first_page_rows=len(first or ()), trusted=trusted, fallback=not trusted)
        if not trusted:
            if first is not None:
                log.warning("采购单列表的 orderType 过滤没有生效(第 1 页类型分布 %s),改为全量翻页 + 本地筛选", types)
            filters = {}
        seen = set()
        reuse_first = (first_total, first) if trusted else None
        for page, rows in _po_lists(sess, size, cfg.max_pages, since, filters, reuse_first):
            pages, stop_page = page, page
            for r in rows:
                scanned += 1
                no = r.get("orderNo")
                if no in seen or str(r.get("orderType")) != order_type or str(r.get("createTime") or "") < since:
                    continue
                if str(r.get("orderStatus")) in excl:
                    continue
                seen.add(no)
                orders.append(r)
        fps = dict((h.get("orderNo"), _po_fingerprint(h)) for h in orders)   # 不能写进 h:取明细时整行原样回传给 DMS
        todo = [h for h in orders if known.get(h.get("orderNo")) != fps[h.get("orderNo")]]
        reused = len(orders) - len(todo)
        log.info("采购单列表翻了 %d 页、读 %d 张,其中 %s 起的 %s 单 %d 张;%d 张明细没变直接复用,%d 张要取明细",
                 pages, scanned, since, order_type, len(orders), reused, len(todo))
        note("取明细 0 / %d 张(%d 张没变,复用上次)" % (len(todo), reused))
        for i, h in enumerate(todo, 1):
            total, lines = sess.po_detail_all(h)
            details[h.get("orderNo")] = _po_summary(lines)
            lines_n += len(lines)
            want, items = _int_or_none(h.get("itemNum")), _po_item_count(lines)
            if (total is not None and total != len(lines)) or (want is not None and want != items):
                bad.append("%s 明细 %d 行 %d 项(接口 total=%s,订单头 itemNum=%s)" % (h.get("orderNo"), len(lines), items,
                                                                              total, want))
            in_order = set()
            for ln in lines:
                pn = str(ln.get("partNo") or "").strip()
                if not pn:
                    continue
                qty = _num(ln.get("purchaseQty")) - _num(ln.get("cancelledQty"))
                p = parts.get(pn)
                if p is None:
                    p = parts[pn] = {"part_no": pn, "name": ln.get("partName") or "", "order_count": 0,
                                     "qty_sum": 0.0, "order_nos": [], "last_order_no": "", "last_order_date": ""}
                p["qty_sum"] = round(p["qty_sum"] + qty, 3)               # 分批收货的多行数量要累加
                if pn not in in_order:                                    # 但同一张单里的同一零件只算出现 1 次
                    in_order.add(pn)
                    p["order_count"] += 1
                    p["order_nos"].append(h.get("orderNo"))
                ct = str(h.get("createTime") or "")
                if ct >= p["last_order_date"]:
                    p["last_order_no"], p["last_order_date"] = h.get("orderNo"), ct
            if i % 10 == 0 or i == len(todo):
                note("取明细 %d / %d 张(%d 张没变,复用上次)" % (i, len(todo), reused))
            if i % 20 == 0:
                log.info("SO 明细进度:%d / %d 张,累计 %d 行", i, len(todo), lines_n)
    plist = sorted(parts.values(), key=lambda p: p["part_no"])
    for p in plist:
        p["order_nos"] = p["order_nos"][-20:]
    heads = [dict({k: h.get(k) for k in ("orderNo", "orderType", "orderStatus", "createTime", "itemNum", "totalAmount")},
                  fp=fps.get(h.get("orderNo"))) for h in orders]
    stats = dict(probe, since=since, order_type=order_type, exclude_status=sorted(excl), pages=pages,
                 stop_page=stop_page, scanned=scanned, orders=len(orders), lines=lines_n, parts=len(plist),
                 fetched=len(details), reused=reused, detail_mismatch=bad[:50])
    rd.write_csv("so_orders.csv", heads, ["orderNo", "orderType", "orderStatus", "createTime", "itemNum", "totalAmount"])
    rd.write_csv("so_parts.csv", plist, ["part_no", "name", "order_count", "qty_sum", "last_order_no", "last_order_date"])
    rd.write_json("so_stats.json", stats)
    msg = "SO 同步:%s 起 %s 单 %d 张(新取明细 %d 张、复用 %d 张)、明细 %d 行(%s,翻 %d 页、读 %d 张)%s" % (
        since, order_type, len(orders), len(details), reused, lines_n,
        "服务端过滤" if trusted else "服务端过滤报错,全量翻页" if probe.get("filter_error") else "服务端过滤未生效,全量翻页",
        pages, scanned, ";明细与订单头不一致 %d 张" % len(bad) if bad else "")
    rd.finish(True, {"message": msg, "stats": stats})
    log.info(msg)
    return {"ok": True, "message": msg, "orders": heads, "parts": plist, "details": details, "stats": stats,
            "dir": rd.path}


# ====================================================================== 建采购单(待提交)
def create_po(cfg, sess, lines, supplier_code=None, order_type=None, remark="", steps=None, uploader=None,
              kind="single", on_sent=None):
    """lines: [{part_no, qty}]。只调用一次 create-parts-po(orderStatus=1 待提交),不提交、不删除。
    kind:single 单次补货 / scheduled 定时补货(按业务各自的「允许建单」开关把关)。
    order_type 参数只为兼容旧云端保留,一律按 ORDER_TYPE(SO)建单。
    uploader(path, kind):把建单请求 / 响应快照作为证据上传云端(审计用)。
    on_sent():建单请求发出前一刻调用(plugins.restock 据此区分「请求没发出 → 确定没建成」和「发出后出错 → 结果未知」)。"""
    ctx = steps or NullSteps()
    up = uploader or (lambda path, kind: None)
    supplier_code = supplier_code or cfg.supplier_code
    order_type = ORDER_TYPE
    remark = remark or cfg.po_remark
    rd = RunDir(cfg.data_dir, "create_po")
    ok, kind_cn = _allowed(cfg, "create", kind)
    if not ok:
        rd.finish(False, {"message": "云端运行参数「%s · 允许建单」已关闭,已拒绝建单" % kind_cn})
        raise ActionError("云端运行参数「%s · 允许建单」已关闭(企业后台 → 取数端 → 运行参数),取数端拒绝建单" % kind_cn,
                          "disabled")
    lines = [l for l in lines if int(l.get("qty") or 0) > 0]
    if not lines:
        raise ActionError("没有数量大于 0 的配件,不建单")
    with ctx.step("login"):
        sess.ensure_valid()
    # 1) 逐个取订货主数据并校验(只读)
    masters, problems = {}, []
    with ctx.step("query_part", "建单前校验 %d 项" % len(lines), scale=len(lines) + 2):
        _validate(sess, lines, masters, problems, supplier_code, order_type)
    part_nos = [l["part_no"] for l in lines]
    replace = {r.get("partNo"): (r.get("orderablePartNo") or "") for r in sess.replace_relationship(part_nos)}
    for pn, alt in replace.items():
        if alt and alt != pn:
            problems.append("%s 存在可订替代件 %s,需人工确认" % (pn, alt))
    dealer = next((m.get("dealerCode") for m in masters.values() if m.get("dealerCode")), "")
    inactive = {r.get("partNo"): r.get("partsInactiveFlag") for r in sess.inactive_check(part_nos, dealer)}
    return _create_after_validate(cfg, sess, ctx, up, rd, lines, masters, problems, inactive, supplier_code,
                                  order_type, remark, on_sent)


def _validate(sess, lines, masters, problems, supplier_code, order_type):
    for l in lines:
        m = sess.part_master(order_type, supplier_code, l["part_no"], int(l["qty"]))
        masters[l["part_no"]] = m
        qty = int(l["qty"])
        mn = _int_or_none(m.get("minPurchaseQty")) or 1
        pk = _int_or_none(m.get("packagesQty")) or 1
        cap = _int_or_none(m.get("dailySurplusPurQty"))
        if qty < mn:
            problems.append("%s 订购数 %d 小于最小订购量 %d" % (l["part_no"], qty, mn))
        if pk > 1 and qty % pk:
            problems.append("%s 订购数 %d 不是包装数 %d 的整数倍" % (l["part_no"], qty, pk))
        if cap is not None and qty > cap:
            problems.append("%s 订购数 %d 超过当日剩余可订 %d" % (l["part_no"], qty, cap))


READ_RETRY_WAIT = 3              # 只读回查失败的重试间隔(秒)


def _read_retry(fn, what, tries=3, final=None):
    """只读接口(列表 / 明细回查)遇到网络 / 接口错误重试几次:只读,重试不会造成任何副作用。
    final(e) 为真的错误(如详情接口明确说单据不存在)不重试,直接抛出。"""
    for i in range(tries):
        try:
            return fn()
        except (NetworkError, ApiError) as e:
            if i == tries - 1 or (final and final(e)):
                raise
            log.warning("%s失败(第 %d 次,%d 秒后重试):%s", what, i + 1, READ_RETRY_WAIT, e)
            time.sleep(READ_RETRY_WAIT)


# ====================================================================== 找单(建单回查 / 核实 / 提交前核对共用)
# 统一顺序:先按 id 查(info-parts-po)→ 再按创建时间倒序翻列表,最多 PO_LOOKBACK_ROWS 条 → 都没有才算没有
PO_LOOKBACK_ROWS = 200
PO_SCAN_PAGE = 20                # 翻列表找单时每页请求条数
LOCATE_TRIES = 3                 # 建单后找单的轮数(列表可能稍有延迟)
LOCATE_WAIT = 2                  # 两轮之间的间隔(秒)


class _RetryPages(object):
    """把 sess.po_page 包一层只读重试(给 _po_lists 用)。"""

    def __init__(self, sess, what):
        self.sess, self.what = sess, what

    def po_page(self, *a, **kw):
        return _read_retry(lambda: self.sess.po_page(*a, **kw), self.what)


def _po_scan(sess, filters=None, since="", max_rows=PO_LOOKBACK_ROWS, stats=None):
    """按创建时间倒序翻采购单列表,最多 max_rows 条(给了 since 时整页都早于 since 也停)。逐页产出 (page, rows),
    rows 已截到上限以内。stats(dict):写入 scanned(读了几条)、pages、truncated(是否因为条数上限停下)。"""
    st = stats if stats is not None else {}
    st.update(scanned=0, pages=0, truncated=False)
    for page, rows in _po_lists(sess, PO_SCAN_PAGE, max_rows, since or "", dict(filters or {})):
        rows = rows[:max_rows - st["scanned"]]
        st["scanned"] += len(rows)
        st["pages"] = page
        yield page, rows
        if st["scanned"] >= max_rows:
            st["truncated"] = True
            log.info("采购单列表已翻到 %d 条上限,停止", max_rows)
            return


def _scan_by_id(sess, order_id, filters=None, since="", stats=None, note=None):
    """翻列表(最多 PO_LOOKBACK_ROWS 条)按 id 找行;找不到返回 None。查询失败直接抛出。"""
    for page, rows in _po_scan(sess, filters, since, PO_LOOKBACK_ROWS, stats):
        if note:
            note(page)
        row = next((r for r in rows if str(r.get("id")) == order_id), None)
        if row is not None:
            return row
    return None


def _row_by_no(sess, order_no, order_id):
    """按单号过滤查列表第 1 页,只认 id 完全相同的行(DMS 单号过滤是否模糊匹配未验证)。"""
    if not order_no:
        return None
    _, rows = sess.po_page(1, 20, orderNo=order_no)
    return next((r for r in rows if str(r.get("id")) == order_id), None)


def _info_missing(e):
    """详情接口的异常是不是「DMS 明确说单据不存在」:只有带业务错误码的 ApiError 才算;
    网络失败、网关错误页(非 JSON,没有错误码)都不算,要直接抛出,不能当成已删除。"""
    return isinstance(e, ApiError) and getattr(e, "code", None) is not None


def _row_from_info(order_id, info):
    """详情能查到、列表里找不到行时,用详情拼一个最小的列表行(单号 / 备注 / 创建时间 / 项数 / 金额)。"""
    dets = info.get("details") or []
    return {"id": order_id, "orderNo": info.get("orderNo"), "orderType": info.get("orderType"),
            "remark": info.get("remark"), "createTime": info.get("createTime"), "createByName": info.get("createByName"),
            "itemNum": str(len(dets)), "totalAmount": info.get("totalPriceSum"), "_from": "info"}


def _locate_created(sess, order_id):
    """建单成功(只拿到 id)后找这张单。返回 (row, info, how):how = list(列表行)/ info(只在详情里找到)/ None。

    每轮:详情接口按 id 拿单号 → 按单号过滤取列表行 → 还没有就按创建时间倒序翻列表最多 PO_LOOKBACK_ROWS 条按 id 找。
    详情 / 列表查询都是只读的,失败自动重试;详情接口失败不影响翻列表。最多 LOCATE_TRIES 轮。"""
    info = None
    pages = _RetryPages(sess, "建单后回查采购单列表")
    for i in range(LOCATE_TRIES):
        try:
            info = _read_retry(lambda: sess.po_info(order_id), "建单后按 id 查采购单详情", final=_info_missing)
        except Exception as e:  # noqa: BLE001  详情接口失败:退回翻列表
            log.warning("建单后按 id=%s 查详情失败(%s),改为翻采购单列表找", order_id, e)
            info = None
        no = str((info or {}).get("orderNo") or "").strip()
        row = _row_by_no(pages, no, order_id) if no else None
        if row is None:
            row = _scan_by_id(pages, order_id)
        if row is not None:
            return row, info, "list"
        if no:                   # 详情确认单已建成、知道单号,只是列表里没有这一行:用详情兜底,不再等
            log.warning("采购单 id=%s(%s)详情能查到,列表前 %d 条里没有,用详情数据核对", order_id, no, PO_LOOKBACK_ROWS)
            return _row_from_info(order_id, info), info, "info"
        if i < LOCATE_TRIES - 1:
            time.sleep(LOCATE_WAIT)
    return None, info, None


def _create_after_validate(cfg, sess, ctx, up, rd, lines, masters, problems, inactive, supplier_code, order_type,
                           remark, on_sent=None):
    if problems:
        rd.note("校验未通过,未建单", "\n".join(problems), "err")
        rd.finish(False, {"message": "校验未通过:" + ";".join(problems)})
        raise ActionError("建单前校验未通过:" + ";".join(problems))

    details = [build_po_detail(masters[l["part_no"]], int(l["qty"]), False, inactive.get(l["part_no"]), order_type)
               for l in lines]
    payload = build_po_payload(supplier_code, order_type, details, remark)
    _try_upload(up, rd.write_json("po_request.json", payload), "request")

    # 2) 建单:只发一次
    log.warning("即将在 DMS 创建采购单(待提交):供应商 %s 类型 %s,%s", supplier_code, order_type,
                ",".join("%s×%s" % (l["part_no"], l["qty"]) for l in lines))
    t_before = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 120))
    with ctx.step("create_po", "%d 项" % len(lines)):              # 已发出的请求不中途放弃(不传 on_timeout)
        if on_sent:
            on_sent()
        rd.note("建单请求已发出", "备注:%s" % remark, "warn")
        try:
            body = sess.create_po(payload)
        except (NetworkError, ApiError) as e:
            # DMS 明确返回业务错误码 = 没建成;网络断了 / 网关错误页(非 JSON,没有错误码)= DMS 可能已经建成
            if isinstance(e, ApiError) and getattr(e, "code", None) is not None:
                msg = "DMS 拒绝建单:%s" % e
                rd.note("DMS 明确拒绝,未建成", msg, "err")
                rd.finish(False, {"message": msg})
                raise ActionError(msg, "dms_rejected", {"rejected": True, "error": str(e)})
            msg = "建单请求异常(%s),DMS 可能已经建成功也可能没有;不会重试,请到 DMS「采购订单管理」核实" % e
            cands = _recent_candidates(sess, supplier_code, t_before, len(lines))
            rd.write_json("po_unknown_candidates.json", cands)
            rd.note("结果未知", msg, "err")
            rd.finish(False, {"message": msg, "unknown": True, "candidates": cands})
            raise UnknownResult(msg, {"candidates": cands})
    _try_upload(up, rd.write_json("po_response.json", body), "response")
    if not isinstance(body, dict) or not body.get("id"):
        rd.finish(False, {"message": "建单接口没有返回单据 id:%r" % (body,)})
        raise ActionError("建单接口没有返回单据 id:%r" % (body,))
    if body.get("validFlag") is False:
        rd.finish(False, {"message": "DMS 校验不通过(validFlag=false):%r" % (body,)})
        raise ActionError("DMS 校验不通过(validFlag=false),详情见 po_response.json")
    order_id = str(body["id"])
    log.info("建单成功,单据 id=%s,回查单号…", order_id)

    # 3) 回查单号 + 核对明细(单已经建成:这里任何失败都只能报「结果未知」,带上 order_id)
    #    建单响应只有 id:先按 id 查详情拿单号,再按单号取列表行;拿不到再按创建时间翻列表最多 PO_LOOKBACK_ROWS 条按 id 找
    row = None
    try:
        with ctx.step("verify_po", "回查单号 id=%s" % order_id):
            row, info, how = _locate_created(sess, order_id)
            if not row:
                msg = ("建单已成功(id=%s),但按 id 查详情、翻采购单列表前 %d 条都没找到,单号未知,请到 DMS 核实"
                       % (order_id, PO_LOOKBACK_ROWS))
                rd.finish(False, {"message": msg, "order_id": order_id})
                raise UnknownResult(msg, {"order_id": order_id})
            if how == "info":            # 详情能查到、列表里找不到行:明细用详情接口返回的(与列表明细同字段名)
                details_back = list(info.get("details") or [])
                total_back = None
            else:                        # 明细分页(每页 50),超过 50 项必须翻页取全
                total_back, details_back = _read_retry(lambda: sess.po_detail_all(row), "建单后回查采购单明细")
    except UnknownResult:
        raise
    except Exception as e:  # noqa: BLE001
        msg = "建单已成功(id=%s),但回查失败(%s: %s),单号未知;不会重试,请到 DMS 核实" % (order_id, type(e).__name__, e)
        rd.note("结果未知", msg, "err")
        rd.finish(False, {"message": msg, "order_id": order_id, "unknown": True})
        raise UnknownResult(msg, {"order_id": order_id, "order_no": (row or {}).get("orderNo")})
    rd.write_json("po_row.json", row)
    rd.write_json("po_detail.json", details_back)
    got = {str(d.get("partNo")): _num(d.get("purchaseQty")) for d in details_back}
    mismatch = ["%s 期望 %s 实际 %s" % (l["part_no"], l["qty"], got.get(l["part_no"]))
                for l in lines if got.get(l["part_no"]) != float(l["qty"])]
    asked = {l["part_no"] for l in lines}
    mismatch += ["%s 不在订购内容里,DMS 明细却有(数量 %s)" % (pn, q) for pn, q in got.items() if pn not in asked]
    if total_back is not None and total_back != len(details_back):
        mismatch.append("DMS 明细总数 %s,实际取到 %d 行" % (total_back, len(details_back)))
    view = [{"partNo": d.get("partNo"), "partName": d.get("partName"), "purchaseQty": d.get("purchaseQty"),
             "unitPrice": d.get("unitPrice"), "totalPriceSum": d.get("totalPriceSum")} for d in details_back]
    rd.table("采购单 %s 明细(DMS 回查)" % row.get("orderNo"), view,
             ["partNo", "partName", "purchaseQty", "unitPrice", "totalPriceSum"], ["配件码", "名称", "数量", "单价", "金额"])
    msg = "已创建采购单 %s(待提交,%s 项,金额 %s)%s" % (
        row.get("orderNo"), row.get("itemNum"), row.get("totalAmount"),
        ";[注意] 明细与请求不一致:" + ";".join(mismatch) if mismatch else ",明细核对一致")
    rd.note("结论(真实单据,演示完请人工到 DMS 删除)", msg, "warn" if mismatch else "ok")
    rd.finish(True, {"message": msg, "order_id": order_id, "order_no": row.get("orderNo")})
    log.info(msg)
    return {"ok": True, "order_id": order_id, "order_no": row.get("orderNo"), "row": row,
            "details": details_back, "mismatch": mismatch, "dir": rd.path}


def _try_upload(up, path, kind):
    try:
        up(path, kind)
    except Exception as e:  # noqa: BLE001  证据上传失败不影响建单
        log.warning("建单快照上传失败(%s):%s", kind, e)


def _recent_candidates(sess, supplier_code, since, item_num):
    try:
        _, rows = sess.po_page(1, 20)
    except Exception as e:  # noqa: BLE001
        return [{"error": "回查失败: %s" % e}]
    return [r for r in rows if r.get("supplierCode") == supplier_code and str(r.get("createTime") or "") >= since
            and str(r.get("itemNum")) == str(item_num)]


# ====================================================================== 核实采购单是否已建(只读)
def remark_has_doc(remark, doc_no):
    """采购单备注是否以这张补货单的单号结尾(云端建单时把单号放在备注末尾)。
    只认结尾:SP-..-1-01 不能匹配 SP-..-1-010。"""
    doc_no = str(doc_no or "").strip()
    return bool(doc_no) and str(remark or "").strip().endswith(doc_no)


SCAN_KEYS = ("id", "orderNo", "orderStatus", "supplierCode", "createTime", "itemNum", "totalAmount", "remark")


def _find_by_id(sess, order_id, supplier_code):
    """find_po 的「先按 id 查」:详情确认存在 → 按单号 / 翻列表拿行 + 全明细。返回 (found 项或 None, 说明)。
    详情接口明确说不存在 → (None, 说明);网络 / 接口异常直接抛出(云端据此不建单)。"""
    try:
        info = _read_retry(lambda: sess.po_info(order_id), "核实采购单详情", final=_info_missing)
    except ApiError as e:
        if not _info_missing(e):
            raise
        return None, "按 id=%s 查详情:%s" % (order_id, e)
    no = str(info.get("orderNo") or "").strip()
    row = _row_by_no(sess, no, order_id) or _scan_by_id(sess, order_id, {"supplierCode": supplier_code})
    if row is None:              # 详情能查到、列表里没找到行:用详情数据回传(单确实建成了)
        row = _row_from_info(order_id, info)
        details = list(info.get("details") or [])
    else:
        _, details = _read_retry(lambda: sess.po_detail_all(row), "核实采购单明细")
    return {"order_id": order_id, "order_no": row.get("orderNo") or no, "row": row, "details": details,
            "matched_by": "id"}, "按 id=%s 找到采购单 %s" % (order_id, row.get("orderNo") or no)


def find_po(cfg, sess, supplier_code, doc_no, since, steps=None, uploader=None, order_id=None):
    """上次建单结果未知时,云端再确认前先调这里(只读)。
    给了 order_id(建单响应拿到过 id):先按 id 查详情确认存在,再从列表拿行 + 明细,命中直接返回;
    否则(或按 id 没有)按创建时间倒序翻采购单列表直到 since、最多 PO_LOOKBACK_ROWS 条,找备注以补货单号结尾的单,
    每张取全明细。查询失败直接抛异常(云端据此不建单)。
    返回 {ok, found: [{order_id, order_no, row, details}], scanned, truncated}。"""
    ctx = steps or NullSteps()
    up = uploader or (lambda path, kind: None)
    supplier_code = supplier_code or cfg.supplier_code
    order_id = str(order_id or "").strip()
    rd = RunDir(cfg.data_dir, "find_po")
    query = {"supplier_code": supplier_code, "doc_no": doc_no, "since": since, "order_id": order_id or None}
    with ctx.step("login"):
        sess.ensure_valid()
    scanned, hits, found, st, by_id = [], [], [], {}, ""
    with ctx.step("find_po", "核实 %s" % doc_no):
        if order_id:
            ctx.note("核实 %s:按 id=%s 查" % (doc_no, order_id))
            hit, by_id = _find_by_id(sess, order_id, supplier_code)
            if hit:
                found.append(hit)
        if not found:
            for page, rows in _po_scan(sess, {"supplierCode": supplier_code}, since, PO_LOOKBACK_ROWS, st):
                ctx.note("核实 %s:第 %d 页" % (doc_no, page))
                for r in rows:
                    scanned.append({k: r.get(k) for k in SCAN_KEYS})
                    if remark_has_doc(r.get("remark"), doc_no) and str(r.get("createTime") or "") >= since:
                        hits.append(r)
            for r in hits:
                _, details = _read_retry(lambda r=r: sess.po_detail_all(r), "核实采购单明细")
                found.append({"order_id": str(r.get("id")), "order_no": r.get("orderNo"), "row": r,
                              "details": details, "matched_by": "remark"})
    truncated = bool(st.get("truncated"))
    _try_upload(up, rd.write_json("find_po_query.json", {"query": query, "by_id": by_id, "scanned": scanned,
                                                         "truncated": truncated}), "find_po_query")
    _try_upload(up, rd.write_json("find_po_result.json", {"query": query, "found": found}), "find_po_result")
    if found and found[0].get("matched_by") == "id":
        msg = "核实 %s:%s" % (doc_no, by_id)
    else:
        msg = "核实 %s:%s扫了 %d 张采购单%s,备注带本单号的 %d 张%s" % (
            doc_no, ("%s;" % by_id) if by_id else "", len(scanned),
            "(已到 %d 条上限)" % PO_LOOKBACK_ROWS if truncated else "", len(found),
            ("(%s)" % "、".join(str(f["order_no"]) for f in found)) if found else "")
    rd.note("结论", msg, "warn" if found else "ok")
    rd.finish(True, {"message": msg})
    log.info(msg)
    return {"ok": True, "found": found, "scanned": len(scanned), "truncated": truncated, "message": msg,
            "dir": rd.path}


PO_STATUS_CN = {"1": "待提交", "2": "已提交"}


def po_status(cfg, sess, order_id, order_no, since, supplier_code=None, steps=None, uploader=None):
    """只读:查云端建的这张采购单在 DMS 里现在的状态(确认提交前 / 发新单次补货前先查)。
    先按单号精确找(只认 id 完全相同的行);找不到再按创建时间翻列表到 since 为止按 id 找,
    防止「单号过滤没生效」被误判成已删除。查询失败直接抛异常(云端据此不做任何动作)。
    返回 {ok, exists, status, status_cn, row, message}。"""
    ctx = steps or NullSteps()
    up = uploader or (lambda path, kind: None)
    order_id, order_no = str(order_id or "").strip(), str(order_no or "").strip()
    if not order_id or not order_no:
        raise ActionError("缺少采购单 id / 单号,无法查询状态", "bad_params")
    supplier_code = supplier_code or cfg.supplier_code
    rd = RunDir(cfg.data_dir, "po_status")
    with ctx.step("login"):
        sess.ensure_valid()
    st = {}
    with ctx.step("po_status", "查询 %s" % order_no):
        row = _find_po_row(sess, order_no, order_id)
        if row is None and since:        # 再按供应商过滤 + since 翻一遍(最多 PO_LOOKBACK_ROWS 条)
            row = _scan_by_id(sess, order_id, {"supplierCode": supplier_code}, since, st,
                              lambda page: ctx.note("查询 %s:第 %d 页" % (order_no, page)))
    scanned = st.get("scanned", 0)
    status = str(row.get("orderStatus")) if row else ""
    status_cn = PO_STATUS_CN.get(status) or ("状态码 %s" % status if row else "已删除")
    msg = ("采购单 %s 在 DMS 里是「%s」" % (order_no, status_cn)) if row else (
        "DMS 里找不到采购单 %s(id=%s,按单号精确查 + 翻列表 %d 张都没有),按已删除处理" % (order_no, order_id, scanned))
    _try_upload(up, rd.write_json("po_status.json", {"order_id": order_id, "order_no": order_no, "since": since,
                                                     "scanned": scanned, "row": row}), "po_status")
    rd.note("结论", msg, "ok" if status == "1" else "warn")
    rd.finish(True, {"message": msg})
    log.info(msg)
    return {"ok": True, "exists": row is not None, "status": status, "status_cn": status_cn, "row": row,
            "message": msg, "dir": rd.path}


# ====================================================================== 已创建未提交的采购单(定时补货触发时提示用)
# 补货单号放在采购单备注末尾:RP-(定时)/ SP-(单次),如「补货Agent自动创建(定时)RP-20261108-1-01」
DOC_NO_RE = re.compile(r"(?<![A-Za-z0-9])((?:RP|SP)-[A-Za-z0-9-]+)\s*$")
DRAFT_STATUS = "1"


def doc_no_of(remark):
    """备注末尾的补货单号(RP- / SP- 开头),没有返回空串。"""
    m = DOC_NO_RE.search(str(remark or ""))
    return m.group(1) if m else ""


def list_drafts(cfg, sess, supplier_code=None, since="", max_detail=50, steps=None, uploader=None):
    """只读:列出 DMS 里「已创建未提交」(orderStatus=1)的采购单,包括别人手工建的(只做提示,不参与计算)。

    按 {supplierCode, orderStatus=1} 翻采购单列表(服务端按创建时间倒序)到 since 为止;本地再按状态 = 1 过滤一遍,
    返回的行里出现别的状态就说明服务端状态过滤没生效(filter_trusted=False)。前 max_detail 张取明细,其余 details=None。
    返回 {ok, drafts: [{order_id, order_no, create_by, create_time, remark, item_num, total_amount, doc_no, details}],
          scanned, filter_trusted, truncated, message}。查询列表失败直接抛异常。"""
    ctx = steps or NullSteps()
    up = uploader or (lambda path, kind: None)
    supplier_code = supplier_code or cfg.supplier_code
    since = str(since or "")
    try:
        max_detail = max(0, int(max_detail))
    except (TypeError, ValueError):
        max_detail = 50
    rd = RunDir(cfg.data_dir, "list_drafts")
    filters = {"supplierCode": supplier_code, "orderStatus": DRAFT_STATUS}
    query = {"supplier_code": supplier_code, "since": since, "max_detail": max_detail, "filters": filters}
    with ctx.step("login"):
        sess.ensure_valid()
    rows_ok, seen, scanned, other_status, other_supplier, pages = [], set(), 0, {}, 0, 0
    drafts, detail_errors = [], []
    with ctx.step("list_drafts", "已创建未提交的采购单(%s 起)" % (since or "全部")):
        for page, rows in _po_lists(sess, getattr(cfg, "page_size", 50), getattr(cfg, "max_pages", 50), since,
                                    filters):
            pages = page
            ctx.note("已创建未提交的采购单:第 %d 页" % page)
            for r in rows:
                scanned += 1
                st = str(r.get("orderStatus"))
                if st != DRAFT_STATUS:
                    other_status[st] = other_status.get(st, 0) + 1
                    continue
                if since and str(r.get("createTime") or "") < since:
                    continue
                sc = str(r.get("supplierCode") or "")
                if supplier_code and sc and sc != supplier_code:
                    other_supplier += 1
                    continue
                key = str(r.get("id") or r.get("orderNo"))
                if key in seen:
                    continue
                seen.add(key)
                rows_ok.append(r)
        if other_status:
            log.warning("采购单列表的 orderStatus 过滤没有生效(返回了其它状态 %s),已在本地筛选", other_status)
        for i, r in enumerate(rows_ok):
            details = None
            if i < max_detail:
                ctx.note("取明细 %d / %d 张" % (i + 1, min(len(rows_ok), max_detail)))
                try:
                    _, lines = _read_retry(lambda r=r: sess.po_detail_all(r), "取未提交采购单明细")
                    details = _po_summary(lines)
                except Exception as e:  # noqa: BLE001  只是提示:单张取明细失败不影响整体
                    detail_errors.append("%s: %s" % (r.get("orderNo"), e))
                    log.warning("取未提交采购单 %s 明细失败:%s", r.get("orderNo"), e)
            drafts.append({"order_id": str(r.get("id") or ""), "order_no": r.get("orderNo") or "",
                           "create_by": r.get("createByName") or "", "create_time": r.get("createTime") or "",
                           "remark": r.get("remark") or "", "item_num": r.get("itemNum"),
                           "total_amount": r.get("totalAmount"), "doc_no": doc_no_of(r.get("remark")),
                           "details": details})
    trusted = not other_status
    truncated = len(drafts) > max_detail
    msg = "已创建未提交的采购单 %d 张(%s 起,翻 %d 页、读 %d 张%s)%s%s" % (
        len(drafts), since or "全部", pages, scanned,
        "" if trusted else ",服务端状态过滤没生效,已本地筛选",
        ";只取了前 %d 张的明细" % max_detail if truncated else "",
        ";%d 张取明细失败" % len(detail_errors) if detail_errors else "")
    view = [dict(d, details=";".join("%s×%g" % (x["part_no"], x["qty"]) for x in d["details"])
                 if d["details"] is not None else "(未取)") for d in drafts]
    rd.table("已创建未提交的采购单", view,
             ["order_no", "create_by", "create_time", "doc_no", "item_num", "total_amount", "remark", "details"],
             ["单号", "创建人", "创建时间", "补货单号", "项数", "金额", "备注", "明细"])
    _try_upload(up, rd.write_json("list_drafts.json", {"query": query, "drafts": drafts, "scanned": scanned,
                                                       "other_status": other_status, "other_supplier": other_supplier,
                                                       "detail_errors": detail_errors}), "list_drafts")
    rd.note("结论", msg, "warn" if drafts else "ok")
    rd.finish(True, {"message": msg})
    log.info(msg)
    return {"ok": True, "drafts": drafts, "scanned": scanned, "filter_trusted": trusted, "truncated": truncated,
            "detail_errors": detail_errors, "message": msg, "dir": rd.path}


# ====================================================================== 提交采购单(人工确认后「检查并提交」)
# check-parts-po 只抓到过「完全干净」的成功样本:submitFlag=true、accountBalanceFlag=true、各 *Details 为 []、
# *Num 为 0、noAuthPartNoList=null、packageFlag=false。失败时这些字段的含义只能按字段名推断(标「疑似」),
# 所以只要和干净样本有任何不同就不提交,原字段名 + 原始内容照搬给人看。
#
# 【2026-11-06 去掉「疑似重复订货」检查(repeatDetails / repeatNum)】
# 原因:repeatDetails 命中的是 DMS 里「别人」建的单(如 S20261106007,未提交的草稿,同零件同数量),
# 不是我们自己重复建的单;这种重复不属于我们的问题,却会把正常提交一直挡住(报 repeatDetails(疑似重复订货))。
# 所以 check_problems 不再看这两个字段:repeatDetails 非空也照常提交。其余检查项(submitFlag / 余额 / 停用 / 限购 /
# 替代件 / 无权限 / 包装数)保持不变。若以后要恢复,把下面这一行加回 CHECK_LISTS 即可:
#     ("repeatDetails", "repeatNum", "疑似重复订货"),
# 注意:提交前核对 _verify_for_submit 仍会确认 DMS 里这张单的明细和云端建单时完全一致,不受影响。
CHECK_LISTS = (("inactiveDetails", "inactiveNum", "疑似停用件"), ("limitedDetails", "limitNum", "疑似限购"),
               ("replaceDetails", None, "疑似有替代件"),
               ("noAuthPartNoList", None, "疑似无订货权限"), ("pakckageList", None, "疑似包装数问题"))


def check_problems(body):
    """check-parts-po 的返回 → 不能提交的原因(空列表 = 完全干净,可以提交)。"""
    body = body if isinstance(body, dict) else {}
    out = []
    if body.get("submitFlag") is not True:
        out.append("submitFlag=%s(DMS 不允许提交)" % json.dumps(body.get("submitFlag")))
    if body.get("accountBalanceFlag") is not True:
        out.append("accountBalanceFlag=%s(疑似账户余额不足)" % json.dumps(body.get("accountBalanceFlag")))
    if body.get("packageFlag"):
        out.append("packageFlag=%s(疑似包装数问题)" % json.dumps(body.get("packageFlag")))
    for key, num_key, label in CHECK_LISTS:
        v = body.get(key)
        n = _num(body.get(num_key)) if num_key else 0
        if v or n > 0:
            cnt = len(v) if isinstance(v, list) and v else int(n or 1)
            out.append("%s(%s)%d 项:%s" % (key, label, cnt,
                                             json.dumps(v, ensure_ascii=False)[:300] if v else "%s=%g" % (num_key, n)))
    return out


class PoLookupError(ActionError):
    """详情接口说这张单存在,但采购单列表前 PO_LOOKBACK_ROWS 条里找不到它的行:不能当成已删除。"""

    def __init__(self, message, result=None):
        super(PoLookupError, self).__init__(message, "po_lookup_failed", result)


def _find_po_row(sess, order_no, order_id):
    """找采购单列表行(提交前核对 / 查状态 / 提交后回查共用),只认 id 完全相同的那一行。

    1. 按单号过滤查(DMS 单号过滤是否模糊匹配未验证);
    2. 没找到:按 id 查详情确认单据是否存在(详情里的单号和给的不同时再按它过滤一次);
    3. 再按创建时间倒序翻列表兜底,最多 PO_LOOKBACK_ROWS 条按 id 找。
    只有「详情接口明确返回单据不存在」且列表里也没有才返回 None(调用方据此按已删除处理);
    网络 / 接口异常直接抛出;详情说存在但列表里找不到 → PoLookupError(不能当成已删除)。"""
    order_id = str(order_id)
    row = _row_by_no(sess, order_no, order_id)
    if row is not None:
        return row
    try:
        info = sess.po_info(order_id)
    except ApiError as e:
        if not _info_missing(e):
            raise
        info, missing, why = None, True, str(e)
    else:
        missing, why = False, ""
        no = str(info.get("orderNo") or "").strip()
        if no and no != order_no:
            row = _row_by_no(sess, no, order_id)
            if row is not None:
                return row
    st = {}
    row = _scan_by_id(sess, order_id, stats=st)
    if row is not None or missing:
        if row is None:
            log.info("采购单 %s(id=%s)详情接口返回不存在(%s),列表前 %d 条里也没有", order_no, order_id, why,
                     st.get("scanned", 0))
        return row
    raise PoLookupError("DMS 详情显示采购单 %s(id=%s)存在,但采购单列表前 %d 条里找不到它;请到 DMS 核实"
                        % (order_no, order_id, st.get("scanned", 0)), {"order_id": order_id, "order_no": order_no})


def _verify_for_submit(sess, order_id, order_no, expect):
    """提交前核对:DMS 里这张单就是云端建的那张(id / 单号 / SO / 供应商 / 备注 / 逐项明细)且还是待提交。"""
    problems = []
    row = _find_po_row(sess, order_no, order_id)
    if not row:
        return None, [], ["DMS 采购单列表里找不到单号 %s、id=%s 的单" % (order_no, order_id)]
    if str(row.get("orderNo")) != order_no:
        problems.append("单号不一致:云端 %s,DMS %s" % (order_no, row.get("orderNo")))
    if str(row.get("orderType")) != ORDER_TYPE:
        problems.append("订单类型是 %s,不是 SO" % row.get("orderType"))
    status = str(row.get("orderStatus"))
    if status not in ("1", "2"):
        problems.append("订单状态是 %s,不是「待提交」" % status)
    sc = expect.get("supplier_code")
    if sc and str(row.get("supplierCode") or "") != sc:
        problems.append("供应商不一致:建单时 %s,DMS 现在 %s" % (sc, row.get("supplierCode")))
    rm = expect.get("remark")
    if rm and str(row.get("remark") or "") != rm:
        problems.append("备注不一致:建单时「%s」,DMS 现在「%s」" % (rm, row.get("remark")))
    _, details = sess.po_detail_all(row)
    want = {}
    for l in expect.get("lines") or []:
        pn = str(l.get("part_no") or "").strip()
        want[pn] = want.get(pn, 0.0) + float(l.get("qty") or 0)
    if not want:
        problems.append("云端没有给出建单明细,无法核对")
    got = {}
    for d in details:
        pn = str(d.get("partNo") or "").strip()
        got[pn] = got.get(pn, 0.0) + _num(d.get("purchaseQty"))
    for pn, q in sorted(want.items()):
        if got.get(pn) != q:
            problems.append("%s 建单时 %g 个,DMS 现在 %s" % (pn, q, "%g 个" % got[pn] if pn in got else "没有这一项"))
    for pn, q in sorted(got.items()):
        if pn not in want:
            problems.append("DMS 明细多出 %s × %g(建单时没有)" % (pn, q))
    return row, details, problems


def submit_po(cfg, sess, order_id, order_no, expect=None, kind="single", steps=None, uploader=None):
    """人工确认后提交采购单:核对 → check-parts-po → submit-parts-po(只发一次)→ 回查列表状态 + info-parts-po。

    expect:云端建单时记下的 {lines:[{part_no, qty}], supplier_code, remark}。DMS 里这张单任何一项对不上
    (被人改过 / 不是我们建的)都不提交。已经是「已提交」的直接回查(幂等)。submit 网络异常时回查:已提交算成功,
    否则结果未知、绝不重发。每一步的请求 / 响应 / 核对结果都存本地结果目录,并作为证据上传云端。"""
    ctx = steps or NullSteps()
    up = uploader or (lambda path, kind: None)
    expect = expect or {}
    order_id, order_no = str(order_id or "").strip(), str(order_no or "").strip()
    rd = RunDir(cfg.data_dir, "submit_po")
    ok, kind_cn = _allowed(cfg, "submit", kind)
    if not ok:
        msg = "云端运行参数「%s · 允许提交」已关闭(企业后台 → 取数端 → 运行参数),取数端拒绝提交" % kind_cn
        rd.finish(False, {"message": msg})
        raise ActionError(msg, "disabled")
    if not order_id or not order_no:
        rd.finish(False, {"message": "缺少采购单 id / 单号"})
        raise ActionError("缺少采购单 id / 单号,不提交")
    with ctx.step("login"):
        sess.ensure_valid()

    # 1) 核对这张单(只读)
    with ctx.step("verify_po", "核对 %s" % order_no):
        row, details, problems = _verify_for_submit(sess, order_id, order_no, expect)
    _try_upload(up, rd.write_json("submit_verify.json", {"order_id": order_id, "order_no": order_no, "kind": kind,
                                                         "expect": expect, "row": row, "details": details,
                                                         "problems": problems}), "submit_verify")
    if problems:
        msg = "提交前核对未通过,没有提交:" + ";".join(problems)
        rd.note("核对未通过", "\n".join(problems), "err")
        rd.finish(False, {"message": msg})
        # 整张单都找不到(多半是在 DMS 里被删了)单独给错误码,云端据此按「已删除」收口
        raise ActionError(msg, "po_missing" if row is None else "verify_failed", {"problems": problems})

    already = str(row.get("orderStatus")) == "2"
    chk, body = None, None
    if already:
        log.warning("采购单 %s 在 DMS 里已经是「已提交」,不再提交,直接回查", order_no)
        rd.note("已提交过", "DMS 里这张单已经是「已提交」,没有再调用提交接口", "warn")
    else:
        # 2) 检查(只读)
        with ctx.step("submit_check", order_no):
            chk = sess.po_check(order_id)
        _try_upload(up, rd.write_json("submit_check.json", chk), "submit_check")
        bad = check_problems(chk)
        if bad:
            msg = "DMS 检查未通过,没有提交:" + ";".join(bad)
            rd.note("检查未通过", "\n".join(bad), "err")
            rd.finish(False, {"message": msg})
            raise ActionError(msg, "check_failed", {"problems": bad, "check": chk})
        version = chk.get("version") if chk.get("version") is not None else row.get("version")

        # 3) 提交:只发一次
        log.warning("即将在 DMS 提交采购单 %s(id=%s,version=%s,%s)", order_no, order_id, version, kind_cn)
        with ctx.step("submit_po", order_no):              # 已发出的请求不中途放弃(不传 on_timeout)
            try:
                body = sess.po_submit(order_id, version)
            except (NetworkError, ApiError) as e:
                # 网络断了 / 网关错误页(非 JSON):DMS 可能已经提交了 → 回查;DMS 明确返回错误码:没提交
                ambiguous = isinstance(e, NetworkError) or getattr(e, "code", None) is None
                try:
                    after, lookup_err = _find_po_row(sess, order_no, order_id) or {}, ""
                except Exception as e2:  # noqa: BLE001  回查也失败:状态未知(ambiguous 时按结果未知处理)
                    after, lookup_err = {}, "%s: %s" % (type(e2).__name__, e2)
                st = str(after.get("orderStatus") or "")
                rd.write_json("submit_error.json", {"error": "%s: %s" % (type(e).__name__, e), "ambiguous": ambiguous,
                                                    "row_after": after, "lookup_error": lookup_err})
                if st == "2":
                    body = {"recovered": True, "error": str(e)}
                elif ambiguous:
                    msg = ("提交请求异常(%s),DMS 回查状态 %s,可能已经提交也可能没有;不会重试,"
                           "请到 DMS「采购订单管理」核实" % (e, st or "未知"))
                    rd.note("结果未知", msg, "err")
                    rd.finish(False, {"message": msg, "unknown": True})
                    raise UnknownResult(msg, {"order_no": order_no, "status_after": st})
                else:
                    msg = "DMS 拒绝提交:%s" % e
                    rd.finish(False, {"message": msg})
                    raise ActionError(msg, "submit_rejected", {"error": str(e)})
        _try_upload(up, rd.write_json("submit_response.json", body), "submit_response")
        if not isinstance(body, dict) or (not body.get("recovered") and body.get("submitFlag") is not True):
            after = _find_po_row(sess, order_no, order_id) or {}
            if str(after.get("orderStatus")) != "2":
                msg = "DMS 提交接口没有返回成功(%s),回查状态 %s,没有提交成功" % (
                    json.dumps(body, ensure_ascii=False)[:200], after.get("orderStatus"))
                rd.finish(False, {"message": msg})
                raise ActionError(msg, "submit_rejected", {"response": body})

    # 4) 回查:列表状态必须变成 2(已提交);info 取提交人 / 提交时间 / 明细(info 失败不影响结论)
    final = None
    with ctx.step("verify_po", "回查 %s" % order_no):
        for i in range(3):
            r = _find_po_row(sess, order_no, order_id)
            if r and str(r.get("orderStatus")) == "2":
                final = r
                break
            if i < 2:
                time.sleep(2)
        try:
            info = sess.po_info(order_id)
        except Exception as e:  # noqa: BLE001
            log.warning("提交后回查详情失败:%s", e)
            info = {"_error": "%s: %s" % (type(e).__name__, e)}
    _try_upload(up, rd.write_json("submit_info.json", {"row": final, "info": info}), "submit_info")
    if not final:
        msg = "提交接口返回成功,但回查采购单 %s 的状态不是「已提交」;不会重试,请到 DMS 核实" % order_no
        rd.note("结果未知", msg, "err")
        rd.finish(False, {"message": msg, "unknown": True})
        raise UnknownResult(msg, {"order_no": order_no, "response": body})
    lines = [{"partNo": d.get("partNo"), "partName": d.get("partName"), "purchaseQty": d.get("purchaseQty"),
              "unitPrice": d.get("unitPrice"), "totalPrice": d.get("totalPrice") or d.get("totalPriceSum")}
             for d in (info.get("details") or details or [])]
    rd.table("已提交采购单 %s 明细(DMS 回查)" % order_no, lines,
             ["partNo", "partName", "purchaseQty", "unitPrice", "totalPrice"], ["配件码", "名称", "数量", "单价", "金额"])
    operator = info.get("applyOperator") or final.get("applyOperator") or ""
    apply_time = info.get("applyTime") or final.get("applyTime") or ""
    total = info.get("totalPriceSum") if info.get("totalPriceSum") is not None else final.get("totalAmount")
    msg = "采购单 %s 已提交(%s,提交人 %s,提交时间 %s,金额 %s)" % (
        order_no, "之前已提交" if already else kind_cn, operator or "?", apply_time or "?", total)
    rd.note("结论", msg, "ok")
    rd.finish(True, {"message": msg, "order_id": order_id, "order_no": order_no})
    log.info(msg)
    return {"ok": True, "order_id": order_id, "order_no": order_no, "status": "已提交", "already": already,
            "apply_operator": operator, "apply_time": apply_time, "total_amount": total,
            "supplier_name": info.get("supplierName") or "", "details": lines, "row": final, "check": chk,
            "response": body, "message": msg, "dir": rd.path}


# ====================================================================== 截图
# 详情页分页显示:第 1 页等单号 + 前几个零件号出现就截,然后逐页点「下一页」截到最后一页(screenshot._page_through),
# 所有页截到的零件号要覆盖接口回查的全部明细;覆盖不全(翻页失败 / 超过页数上限)再追加一张接口数据渲染的完整明细图。
DETAIL_WAIT_PARTS = 3
DETAIL_PAGE_GUESS = 10          # 估算详情每页几项(步骤超时按页数加时间用,与云端 TaskTimeouts 一致)


def screenshot_po(cfg, sess, order_no=None, row=None, part_nos=(), steps=None, purpose=""):
    """截「采购订单管理」列表页 + 该采购单详情页(全部页)。row 不给就按单号在列表第 1 页里找(提交后的留档截图
    都不给 row,截到的是提交之后的状态)。purpose = submitted:提交后的审计留档截图(结果目录名不同,便于区分)。

    找单放在登录之后(capture 登录成功再调 targets()):ui 方式查列表用的就是浏览器刚拿到的 token,
    不会因为本地存的接口 token 失效而在开浏览器之前先输一次密码。"""
    ctx = steps or NullSteps()
    rd = RunDir(cfg.data_dir, "screenshot_submitted" if purpose == "submitted" else "screenshot")
    found = {"row": row, "details": None}
    detail = {"paged": True, "parts": []}

    def targets():
        r = found["row"]
        if r is None:
            _, rows = sess.po_page(1, 20)
            r = found["row"] = next((x for x in rows if not order_no or x.get("orderNo") == order_no), None)
            if not r:
                raise ActionError("采购单列表第 1 页没找到单号 %s" % order_no)
        no = r.get("orderNo")
        try:                                    # 全部明细(DMS 顺序):逐页翻页时核对每个零件都截到了
            _, found["details"] = sess.po_detail_all(r)
            parts = [str(d.get("partNo") or "").strip().upper() for d in found["details"] if d.get("partNo")]
        except Exception as e:  # noqa: BLE001
            log.warning("截图前查采购单明细失败(%s),按云端给的零件号核对", e)
            parts = [str(p).strip().upper() for p in part_nos if str(p).strip()]
        detail["parts"] = parts
        return [("po_list.png", screenshot.po_list_url(cfg), [no]),
                ("po_detail.png", screenshot.po_detail_url(cfg, r), [no] + parts[:DETAIL_WAIT_PARTS], detail)]

    pages_guess = max(int(math.ceil(len(part_nos or ()) / float(DETAIL_PAGE_GUESS))), 1)
    cdp.CANCEL.clear()
    try:
        with ctx.step("screenshot", "采购单 %s" % ((row or {}).get("orderNo") or order_no or "(最新一张)"),
                      on_timeout=cdp.kill_active, scale=2 + (pages_guess - 1) / 3.0):
            files = screenshot.capture(cfg, sess, targets, rd.path)
    except Exception as e:
        rd.note("截图失败", "%s: %s" % (type(e).__name__, e), "err")
        attach_debug(rd)
        attach_audit(rd)
        upload_audit(cfg, ctx, rd, False)
        fb = _fallback_shots(cfg, sess, ctx, rd, found, order_no, e) if getattr(cfg, "screenshot_fallback", True) else None
        if fb is None:
            rd.finish(False, {"message": str(e), "order_no": (found["row"] or {}).get("orderNo") or order_no})
            raise
        return fb
    order_no = found["row"].get("orderNo")
    res = detail.get("result") or {}
    pages = int(res.get("pages") or 1)
    missing = list(res.get("missing") or [])
    rd.image("采购订单管理(列表)", "po_list.png")
    for i, f in enumerate(files[1:], 1):
        rd.image("采购订单详情 %s%s" % (order_no, "(第 %d/%d 页)" % (i, pages) if pages > 1 else ""),
                 os.path.basename(f))
    extra = []
    if missing:
        why = "DMS 详情翻页截图只截到 %d/%d 个零件(%d 页%s),缺 %s" % (
            len(detail["parts"]) - len(missing), len(detail["parts"]), pages, "" if res.get("pager") else ",没找到分页器",
            "、".join(missing[:10]) + (" 等" if len(missing) > 10 else ""))
        rd.note("详情截图不完整", why + ";追加一张接口数据渲染的完整明细", "warn")
        log.warning("%s;追加一张接口数据渲染的完整明细", why)
        try:
            from .browser import fallback_page
            details = found["details"] if found["details"] is not None else sess.po_detail_all(found["row"])[1]
            path = fallback_page.capture_detail(cfg, found["row"], details, rd.path, why)
            extra.append(path)
            rd.image("采购订单详情 %s 完整明细(接口数据渲染)" % order_no, os.path.basename(path))
        except Exception as e:  # noqa: BLE001
            rd.note("完整明细渲染失败", "%s: %s" % (type(e).__name__, e), "err")
    attach_audit(rd)
    rd.finish(True, {"message": "已截图采购单 %s(详情 %d 页%s)" % (order_no, pages, "" if not missing else ",不完整"),
                     "order_no": order_no})
    upload_audit(cfg, ctx, rd, True)
    return {"ok": True, "order_no": order_no, "files": files + extra, "rendered": extra, "fallback": False,
            "dir": rd.path, "detail_pages": pages, "detail_complete": not missing, "detail_missing": missing}


def _fallback_shots(cfg, sess, ctx, rd, found, order_no, err):
    """DMS 页面截图失败的兜底:用接口回查的真实数据(列表行 + 明细)渲染仿 DMS 页面再截图,页面顶部醒目注明。
    本机浏览器也起不来时只回传数据(fallback=text),由云端发文字明细。查不到单据返回 None(调用方照原错误失败)。"""
    from .browser import fallback_page
    reason = "%s: %s" % (type(err).__name__, err)
    try:
        with ctx.step("screenshot_fallback", "截图失败,用接口数据渲染兜底截图"):
            row = found["row"]
            if row is None:
                _, rows = sess.po_page(1, 20)
                row = next((x for x in rows if not order_no or x.get("orderNo") == order_no), None)
                if not row:
                    raise ActionError("采购单列表第 1 页没找到单号 %s" % order_no)
            _, details = sess.po_detail_all(row)
    except Exception as e2:  # noqa: BLE001
        log.error("截图兜底:查采购单数据失败(%s),放弃兜底", e2)
        rd.note("截图兜底失败", "查采购单数据失败:%s" % e2, "err")
        return None
    no = row.get("orderNo")
    rd.write_json("po_row.json", row)
    rd.write_json("po_detail.json", details)
    files, mode = [], "image"
    try:
        shots = fallback_page.capture(cfg, row, details, rd.path, reason)
        files = [p for p, _ in shots]
        for p, title in shots:
            rd.image(title, os.path.basename(p))
    except Exception as e3:  # noqa: BLE001
        mode = "text"
        log.error("截图兜底:本机浏览器渲染也失败(%s),只回传数据,由云端发文字明细", e3)
        rd.note("兜底渲染失败", "%s: %s" % (type(e3).__name__, e3), "err")
    msg = "DMS 页面截图失败(%s);已用接口实际返回数据%s" % (reason[:200], "渲染兜底截图" if files else "回传明细(未能渲染图片)")
    rd.note("截图兜底", msg, "warn")
    rd.finish(True, {"message": msg, "order_no": no, "fallback": mode})
    log.warning(msg)
    return {"ok": True, "order_no": no, "files": files, "fallback": mode, "fallback_reason": reason[:500],
            "row": row, "details": details, "dir": rd.path}


__all__ = ["check", "outbound", "quote", "so_sync", "create_po", "screenshot_po", "export_history", "find_po",
           "po_status", "submit_po", "list_drafts", "PO_LOOKBACK_ROWS", "ActionError", "UnknownResult",
           "PoLookupError", "ApiError"]