@whyshu/argent-engine 0.8.0-rc.3 → 0.8.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,6 +74,14 @@ def _load_env():
74
74
 
75
75
  _load_env()
76
76
  # lark-cli shebang「/usr/bin/env node」需 node 在 PATH(launchd/ssh 最小 PATH 兼容)
77
+ try:
78
+ from erp_invoice_shadow import shadow_record, append_shadow # noqa: E402
79
+ except Exception: # 半坏机器/旧包没有该模块时只关闭 shadow,不影响 lip
80
+ shadow_record = append_shadow = None
81
+ try:
82
+ from erp_invoice_writeback import write_fields as erp_write_fields, upload_and_finalize as erp_upload_and_finalize # noqa: E402
83
+ except Exception: # ERP 写回模块缺失时只在 erp 模式报错
84
+ erp_write_fields = erp_upload_and_finalize = None
77
85
  _EXTRA_PATH = [p for p in (f"{HOME}/.local/bin", f"{HOME}/node/bin",
78
86
  "/opt/homebrew/bin", "/usr/local/bin")
79
87
  if p not in (os.environ.get("PATH") or "").split(":")]
@@ -97,6 +105,9 @@ F_HS = "HS编码"
97
105
  F_MAT = "材质"
98
106
  F_FILE = "发票文件"
99
107
  F_LABEL = "大货标签"
108
+
109
+ def _writeback_mode() -> str:
110
+ return (os.environ.get("ARGENT_WRITEBACK") or "lip").strip().lower()
100
111
  F_ERR = "发票错误信息"
101
112
  F_FULL_ST = "FULL状态"
102
113
  F_SKU = "SKU"
@@ -351,6 +362,22 @@ def lip_update(rids, patch):
351
362
  _audit_write(rids, patch, False, f"越界字段: {bad}")
352
363
  raise SystemExit(f"❌ 拒绝写回:{bad} 不在发票字段白名单 {sorted(WRITE_FIELDS)} 内"
353
364
  f"(只允许改发票相关字段,其余字段由运营/其他流程负责)")
365
+ mode = _writeback_mode()
366
+ if mode == "erp":
367
+ if erp_write_fields is None:
368
+ raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 写回模块不可用(缺 erp_invoice_writeback.py)")
369
+ try:
370
+ ok = erp_write_fields(rids, patch)
371
+ except Exception as e:
372
+ _audit_write(rids, patch, False, str(e)[:200])
373
+ raise SystemExit(f"❌ ERP 发票写回失败:{e}")
374
+ _audit_write(rids, patch, ok, "" if ok else "ERP invoice-finalize 失败")
375
+ return ok
376
+ if mode == "shadow" and shadow_record is not None:
377
+ try:
378
+ append_shadow(shadow_record(rids, patch, source="lip_update"), DATA)
379
+ except Exception as e:
380
+ log(f"ERP shadow 记录失败(不影响 lip 写回): {e}")
354
381
  d = _cli("base", "+record-batch-update", "--base-token", BASE_TOKEN,
355
382
  "--table-id", TABLE_ID,
356
383
  "--json", json.dumps({"record_id_list": rids, "patch": patch}, ensure_ascii=False))
@@ -460,6 +487,22 @@ def lip_upload_attachment(rid, field, path, row=None):
460
487
  上传标签时查不到自己那条 ⇒ 归一失效、附件越挂越多)。
461
488
  """
462
489
  path = Path(path)
490
+ if _writeback_mode() == "erp":
491
+ if erp_upload_and_finalize is None:
492
+ raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 附件写回模块不可用")
493
+ try:
494
+ ok = erp_upload_and_finalize(rid, field, path)
495
+ except Exception as e:
496
+ _audit_write([rid], {field: path.name}, False, str(e)[:200])
497
+ raise SystemExit(f"❌ ERP 附件写回失败:{e}")
498
+ _audit_write([rid], {field: path.name}, ok, "" if ok else "ERP 附件写回失败")
499
+ return ok
500
+ if _writeback_mode() == "shadow" and shadow_record is not None:
501
+ try:
502
+ append_shadow(shadow_record([rid], {}, source="lip_upload_attachment",
503
+ attachments=[{"field": field, "filename": path.name}]), DATA)
504
+ except Exception as e:
505
+ log(f"ERP shadow 附件记录失败(不影响 lip 上传): {e}")
463
506
  same = _same_name_attachments(row, field, path.name)
464
507
  if row is not None and same and not _needs_refresh(same, path):
465
508
  if len(same) > 1:
@@ -59,6 +59,9 @@ export const PLUGIN_PACKAGES = [
59
59
  // · 发布流水线(`scripts/npm-publish-argent.mjs --only argent-shell`)按本清单认包
60
60
  // —— 不登记 ⇒ Lead 用**官方**发布脚本发不出它。
61
61
  { id: 'argent-shell', npm: `${NPM_SCOPE}/argent-shell` },
62
+ // Desktop 端 ERP 连接器(2026-10-29):单 bundle + 单 insert,只做 office/ERP 通道
63
+ // (快照/对话/建会话/本地任务),不装 core/skin/flow/gateway ⇒ 与 web 端套装解耦。
64
+ { id: 'argent-desktop', npm: `${NPM_SCOPE}/argent-desktop` },
62
65
  ]
63
66
 
64
67
  /**
@@ -2545,6 +2545,19 @@ FALLBACK_DATE_JS = r"""() => {
2545
2545
  }
2546
2546
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2547
2547
  }
2548
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2549
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2550
+ const viewMonth = viewMonths[0];
2551
+ const viewDate = new Date(viewYear, viewMonth, 1);
2552
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2553
+ if (viewDate > targetMonthDate) {
2554
+ for (let i = 0; i < n; i++) {
2555
+ const t = (days[i].textContent || '').trim();
2556
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2557
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2558
+ }
2559
+ }
2560
+ }
2548
2561
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2549
2562
  }
2550
2563
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -7270,6 +7283,16 @@ class RunState:
7270
7283
  terminal_evidence: str = ""
7271
7284
 
7272
7285
 
7286
+ class NullFeishu:
7287
+ """ERP-only 记录源:不读写 lip,所有 Feishu 写操作 no-op。"""
7288
+ dry_run = True
7289
+
7290
+ def __getattr__(self, name):
7291
+ if name == "build_card":
7292
+ return lambda *a, **k: {}
7293
+ return lambda *a, **k: None
7294
+
7295
+
7273
7296
  class Orchestrator:
7274
7297
  """8 步 FULL 货件流程编排器。"""
7275
7298
 
@@ -7279,7 +7302,10 @@ class Orchestrator:
7279
7302
  self.sel = selectors
7280
7303
  self.args = args or argparse.Namespace(no_lock=False)
7281
7304
  self.browser = build_browser_client(cfg, selectors) # KB-085:ZINIAO_MODE=selenium 用 SeleniumClient
7282
- self.feishu = FeishuClient(cfg)
7305
+ if getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", None):
7306
+ self.feishu = NullFeishu()
7307
+ else:
7308
+ self.feishu = FeishuClient(cfg)
7283
7309
  self.state = RunState()
7284
7310
  # 2026-09-19:点 Generar etiquetas **之前**页面是否已有「Declara al menos」提示。
7285
7311
  # 点击前就有 = 残留文案(页面流转留下的旧校验),**不能**当作"checkbox 未生效"的证据;
@@ -9610,6 +9636,52 @@ class Orchestrator:
9610
9636
  "why": (verdict.get("lift") or {}).get("reason") or "",
9611
9637
  })
9612
9638
 
9639
+ async def _open_appointment_via_hub(self) -> None:
9640
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9641
+
9642
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9643
+ """
9644
+ sid = str(self.state.shipment_id or "")
9645
+ if not sid:
9646
+ return
9647
+ try:
9648
+ url = self.browser.page.url or ""
9649
+ except Exception: # noqa: BLE001
9650
+ url = ""
9651
+ if "appointment" in url:
9652
+ return
9653
+ if "/hub" not in url:
9654
+ try:
9655
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9656
+ except Exception: # noqa: BLE001
9657
+ clicked = "notfound"
9658
+ if clicked != "clicked":
9659
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9660
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9661
+ else:
9662
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9663
+ for _ in range(10):
9664
+ try:
9665
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9666
+ break
9667
+ except Exception: # noqa: BLE001
9668
+ pass
9669
+ await asyncio.sleep(1)
9670
+ try:
9671
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9672
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9673
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9674
+ except Exception as exc: # noqa: BLE001
9675
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9676
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9677
+ for _ in range(15):
9678
+ try:
9679
+ if "appointment" in (self.browser.page.url or ""):
9680
+ return
9681
+ except Exception: # noqa: BLE001
9682
+ pass
9683
+ await asyncio.sleep(1)
9684
+
9613
9685
  async def step4_appointment(self) -> None:
9614
9686
  self._log("步骤4 货件预约时间")
9615
9687
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9650,6 +9722,10 @@ class Orchestrator:
9650
9722
  f"{(_cap.get('lift') or {}).get('reason')}")
9651
9723
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9652
9724
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9725
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9726
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9727
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9728
+ await self._open_appointment_via_hub()
9653
9729
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9654
9730
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9655
9731
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9675,6 +9751,7 @@ class Orchestrator:
9675
9751
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9676
9752
  await self.browser.visit_plan_page("appointment-v2",
9677
9753
  self.state.shipment_id, step=4)
9754
+ await self._open_appointment_via_hub()
9678
9755
  for attempt in range(3): # 同一日期内的时段重试
9679
9756
  if attempt > 0:
9680
9757
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -11607,6 +11684,14 @@ class Orchestrator:
11607
11684
 
11608
11685
  async def step7_box_labels(self) -> None:
11609
11686
  self._log("步骤7 打印箱唛")
11687
+ # 续跑/并发:hub-v2 已确认箱唛下载完成时,不再重复生成/勾 fragile;
11688
+ # 80908724 实测:agent 已生成箱唛,orchestrator 再进 volumes 找不到 fragile checkbox。
11689
+ truth = await self._hub_truth()
11690
+ truth_items = truth.get("items") if isinstance(truth, dict) else {}
11691
+ if isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11692
+ self._log(" 🛰️ hub 已确认箱唛下载完成,跳过步骤7重复生成")
11693
+ self._mark_done(7)
11694
+ return
11610
11695
  await self.browser.visit_plan_page("volumes", self.state.shipment_id, step=7)
11611
11696
  await asyncio.sleep(3)
11612
11697
  # 7.0 页面就绪验证:确认在箱数填写页(volumes)。8/18 并发实测 visit 后被
@@ -11660,6 +11745,12 @@ class Orchestrator:
11660
11745
  r = await self.browser.click_checkboxes(
11661
11746
  '[data-testid="checkbox-fragils-consolidation"]', step=7, wait_after=1.0)
11662
11747
  if not r.startswith("checked"):
11748
+ truth2 = await self._hub_truth()
11749
+ truth2_items = truth2.get("items") if isinstance(truth2, dict) else {}
11750
+ if isinstance(truth2_items, dict) and truth2_items.get("boxLabels") is True:
11751
+ self._log(" 🛰️ 箱唛已下载完成(hub 复核),跳过 fragile 收口")
11752
+ self._mark_done(7)
11753
+ return
11663
11754
  raise StepError(7, "selector_not_found", f"未找到 fragile checkbox ({r})",
11664
11755
  recovery_attempted=["fiber_onChange"])
11665
11756
  # 7g. 等加载旋转层消失再点 Continuar(箱唛生成后约5秒loading)
@@ -12870,7 +12961,7 @@ class Orchestrator:
12870
12961
  dry_run = mode == "dry-run"
12871
12962
  # ⑧:dry-run 期间所有字段写入在 update_field 里被拦(唯一写入口)
12872
12963
  try:
12873
- self.feishu.dry_run = bool(dry_run)
12964
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
12874
12965
  except Exception: # noqa: BLE001
12875
12966
  pass
12876
12967
  record_ids = [r.strip() for r in str(self.args.records).split(",") if r.strip()]
@@ -13084,7 +13175,58 @@ class Orchestrator:
13084
13175
  # 定向重跑),店铺从记录字段取(store_name),无需 --store-name;若同时给
13085
13176
  # --store-name 且不匹配则报错提示;
13086
13177
  # --store-name:过滤查询第一条店铺名匹配的 Pending+就绪;缺省:第一条 Pending+就绪
13087
- if record_id:
13178
+ _record_json = getattr(self.args, "record_json", "") or ""
13179
+ if _record_json:
13180
+ try:
13181
+ _raw = json.loads(_record_json)
13182
+ except Exception as exc: # noqa: BLE001
13183
+ return {"status": "failed", "record_id": None, "shipment_id": None,
13184
+ "sku": None, "completed_steps": [], "failed_step": None,
13185
+ "error": {"step": None, "type": "business",
13186
+ "message": f"--record-json 解析失败: {exc}",
13187
+ "recovery_attempted": []},
13188
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13189
+ "write_steps": list(WRITE_STEPS)}
13190
+
13191
+ def _s(*keys):
13192
+ for _k in keys:
13193
+ if _raw.get(_k) not in (None, ""):
13194
+ return str(_raw.get(_k))
13195
+ return ""
13196
+
13197
+ rec = {
13198
+ "record_id": _s("record_id", "sourceRecordId") or "erp-record",
13199
+ "sku": _s("sku"),
13200
+ "qty": _s("qty", "quantity"),
13201
+ "box": _s("box", "boxCount"),
13202
+ "name": _s("name", "productName") or _s("sku"),
13203
+ "store_name": _s("store_name", "store") or (store_name or ""),
13204
+ "shipment_id": _s("shipment_id", "shipmentNo"),
13205
+ }
13206
+ _missing = [k for k in ("sku", "qty", "box", "store_name") if not rec[k]]
13207
+ if _missing:
13208
+ return {"status": "failed", "record_id": rec["record_id"], "shipment_id": None,
13209
+ "sku": rec["sku"], "completed_steps": [], "failed_step": None,
13210
+ "error": {"step": None, "type": "business",
13211
+ "message": f"--record-json 缺字段: {_missing}",
13212
+ "recovery_attempted": []},
13213
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13214
+ "write_steps": list(WRITE_STEPS)}
13215
+ if store_name and rec["store_name"] != store_name:
13216
+ raise StepError(0, "business",
13217
+ f"--record-json 的店铺 {rec['store_name']} "
13218
+ f"与 --store-name {store_name} 不匹配")
13219
+ self._log(f"🎯 ERP-only 记录 {rec['record_id']}(店铺:{rec['store_name']})")
13220
+ self.state.record_id = rec["record_id"]
13221
+ self.state.name = rec["name"]
13222
+ self.state.store_name = rec["store_name"]
13223
+ self.state.sku = rec["sku"]
13224
+ self.state.qty = rec["qty"]
13225
+ self.state.box = rec["box"]
13226
+ if rec["shipment_id"] and rec["shipment_id"] not in ("None", "null"):
13227
+ self.state.shipment_id = rec["shipment_id"]
13228
+ self._log(f" 已有货件号 {rec['shipment_id']},从步骤4继续")
13229
+ elif record_id:
13088
13230
  rec = self.feishu.get_record(record_id)
13089
13231
  if rec is None:
13090
13232
  self._log(f"记录 {record_id} 不存在或无法读取,本轮退出。")
@@ -13167,7 +13309,7 @@ class Orchestrator:
13167
13309
 
13168
13310
  dry_run = mode == "dry-run"
13169
13311
  try: # ⑧:dry-run 写闸门
13170
- self.feishu.dry_run = bool(dry_run)
13312
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
13171
13313
  except Exception: # noqa: BLE001
13172
13314
  pass
13173
13315
  # 启动标记(状态=运行中)必须与打开店铺在同一 protected 区域:后续任何异常
@@ -13230,7 +13372,31 @@ class Orchestrator:
13230
13372
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13231
13373
  step_summaries={}, dry_run=dry_run)
13232
13374
 
13233
- steps = [step_filter] if step_filter else list(range(1, 9))
13375
+ if self.state.shipment_id and not step_filter:
13376
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13377
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13378
+ try:
13379
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13380
+ _v = self._hub_verdict_of(_hub)
13381
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13382
+ f"{_v.get('reason') or '不可用'}")
13383
+ if _v.get("operationally_complete"):
13384
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13385
+ for _s in range(1, 9):
13386
+ self._mark_done(_s)
13387
+ steps = []
13388
+ else:
13389
+ for _s in (1, 2, 3):
13390
+ self._mark_done(_s)
13391
+ steps = [4, 5, 6, 7, 8]
13392
+ except Exception as exc: # noqa: BLE001
13393
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13394
+ f"{type(exc).__name__}: {exc}")
13395
+ for _s in (1, 2, 3):
13396
+ self._mark_done(_s)
13397
+ steps = [4, 5, 6, 7, 8]
13398
+ else:
13399
+ steps = [step_filter] if step_filter else list(range(1, 9))
13234
13400
  step_summaries: dict[int, Any] = {}
13235
13401
 
13236
13402
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -13821,6 +13987,8 @@ def build_parser() -> argparse.ArgumentParser:
13821
13987
  p.add_argument("--allow-write", action="store_true",
13822
13988
  help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
13823
13989
  p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
13990
+ p.add_argument("--record-json", help="ERP-only:合成记录 JSON(record_id/sourceRecordId、sku、qty/quantity、box/boxCount、name、store_name/store、shipment_id/shipmentNo)")
13991
+ p.add_argument("--no-lip", action="store_true", help="不读写 lip(Feishu 写操作 no-op);常与 --record-json 使用")
13824
13992
  p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
13825
13993
  p.add_argument("--qty", help="数量(配合 --record-id 使用)")
13826
13994
  p.add_argument("--box", help="箱数(配合 --record-id 使用)")
@@ -2562,6 +2562,19 @@ FALLBACK_DATE_JS = r"""() => {
2562
2562
  }
2563
2563
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2564
2564
  }
2565
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2566
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2567
+ const viewMonth = viewMonths[0];
2568
+ const viewDate = new Date(viewYear, viewMonth, 1);
2569
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2570
+ if (viewDate > targetMonthDate) {
2571
+ for (let i = 0; i < n; i++) {
2572
+ const t = (days[i].textContent || '').trim();
2573
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2574
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2575
+ }
2576
+ }
2577
+ }
2565
2578
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2566
2579
  }
2567
2580
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -9627,6 +9640,52 @@ class Orchestrator:
9627
9640
  "why": (verdict.get("lift") or {}).get("reason") or "",
9628
9641
  })
9629
9642
 
9643
+ async def _open_appointment_via_hub(self) -> None:
9644
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9645
+
9646
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9647
+ """
9648
+ sid = str(self.state.shipment_id or "")
9649
+ if not sid:
9650
+ return
9651
+ try:
9652
+ url = self.browser.page.url or ""
9653
+ except Exception: # noqa: BLE001
9654
+ url = ""
9655
+ if "appointment" in url:
9656
+ return
9657
+ if "/hub" not in url:
9658
+ try:
9659
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9660
+ except Exception: # noqa: BLE001
9661
+ clicked = "notfound"
9662
+ if clicked != "clicked":
9663
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9664
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9665
+ else:
9666
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9667
+ for _ in range(10):
9668
+ try:
9669
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9670
+ break
9671
+ except Exception: # noqa: BLE001
9672
+ pass
9673
+ await asyncio.sleep(1)
9674
+ try:
9675
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9676
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9677
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9678
+ except Exception as exc: # noqa: BLE001
9679
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9680
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9681
+ for _ in range(15):
9682
+ try:
9683
+ if "appointment" in (self.browser.page.url or ""):
9684
+ return
9685
+ except Exception: # noqa: BLE001
9686
+ pass
9687
+ await asyncio.sleep(1)
9688
+
9630
9689
  async def step4_appointment(self) -> None:
9631
9690
  self._log("步骤4 货件预约时间")
9632
9691
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9667,6 +9726,10 @@ class Orchestrator:
9667
9726
  f"{(_cap.get('lift') or {}).get('reason')}")
9668
9727
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9669
9728
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9729
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9730
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9731
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9732
+ await self._open_appointment_via_hub()
9670
9733
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9671
9734
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9672
9735
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9692,6 +9755,7 @@ class Orchestrator:
9692
9755
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9693
9756
  await self.browser.visit_plan_page("appointment-v2",
9694
9757
  self.state.shipment_id, step=4)
9758
+ await self._open_appointment_via_hub()
9695
9759
  for attempt in range(3): # 同一日期内的时段重试
9696
9760
  if attempt > 0:
9697
9761
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -13247,7 +13311,31 @@ class Orchestrator:
13247
13311
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13248
13312
  step_summaries={}, dry_run=dry_run)
13249
13313
 
13250
- steps = [step_filter] if step_filter else list(range(1, 9))
13314
+ if self.state.shipment_id and not step_filter:
13315
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13316
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13317
+ try:
13318
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13319
+ _v = self._hub_verdict_of(_hub)
13320
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13321
+ f"{_v.get('reason') or '不可用'}")
13322
+ if _v.get("operationally_complete"):
13323
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13324
+ for _s in range(1, 9):
13325
+ self._mark_done(_s)
13326
+ steps = []
13327
+ else:
13328
+ for _s in (1, 2, 3):
13329
+ self._mark_done(_s)
13330
+ steps = [4, 5, 6, 7, 8]
13331
+ except Exception as exc: # noqa: BLE001
13332
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13333
+ f"{type(exc).__name__}: {exc}")
13334
+ for _s in (1, 2, 3):
13335
+ self._mark_done(_s)
13336
+ steps = [4, 5, 6, 7, 8]
13337
+ else:
13338
+ steps = [step_filter] if step_filter else list(range(1, 9))
13251
13339
  step_summaries: dict[int, Any] = {}
13252
13340
 
13253
13341
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -50,9 +50,8 @@ def _default_orchestrator() -> Path:
50
50
  profile_home / "scripts/orchestrator.py",
51
51
  profile_home / "roles/ml-fulfillment/scripts/orchestrator.py",
52
52
  profile_home / "skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
- Path.home() / "Code/argent-ml-seller/scripts/orchestrator.py",
54
- Path.home() / "Code/argent-ml/roles/ml-fulfillment/scripts/orchestrator.py",
55
- Path.home() / "Code/argent-ml/skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
+ # 2026-10-29:legacy 仓(argent-ml / argent-ml-seller)已归档;只认当前主线仓
54
+ Path.home() / "Code/argent-dsh/scripts/orchestrator.py",
56
55
  ]
57
56
  for c in candidates:
58
57
  if c.is_file():
@@ -31,6 +31,7 @@ const TESTS = [
31
31
  'scripts/tests/argent-datadir.test.mjs',
32
32
  'scripts/tests/datadir-literal-gate.test.mjs',
33
33
  'scripts/tests/datadir-writes-gate.test.mjs',
34
+ 'scripts/tests/agentic-no-lip.test.mjs',
34
35
  'scripts/tests/core-mcp-shared.test.mjs',
35
36
  'scripts/tests/mcp-tool-annotations.test.mjs',
36
37
  'scripts/tests/mcp-collapse.test.mjs',
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env python3
2
+ """SkuFlow bulkLabel 发票适配器(鑫中航;复用既有 invoice_runner/invoice_stageb)。
3
+
4
+ 输入:--record-json '<json>'(SkuFlow task.context)
5
+ 输出:stdout 最后一行 JSON {ok, invoicePath, bulkLabelPath, orderNo} 或 {ok:false,error}
6
+ 注意:默认会调用既有鑫中航上传/下载流程;离线只生成用 --generate-only。
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ HERE = Path(__file__).resolve().parent
15
+ sys.path.insert(0, str(HERE))
16
+ DATA = Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
17
+
18
+ from invoice_runner import load_mapping, generate_invoice # noqa: E402
19
+
20
+
21
+ def build_record(ctx: dict) -> dict:
22
+ return {
23
+ '货件号': str(ctx.get('shipmentNo') or ''),
24
+ '店铺名称': str(ctx.get('store') or ''),
25
+ '品名': str(ctx.get('productName') or ctx.get('sku') or ''),
26
+ '数量': int(ctx.get('quantity') or 0),
27
+ '箱数': int(ctx.get('boxCount') or 0),
28
+ '国内收货仓库': '深圳仓',
29
+ '备注': str(ctx.get('content') or 'SkuFlow'),
30
+ '到达时间': str(ctx.get('shipDate') or ''),
31
+ 'sku_data': {
32
+ '品名英文': str(ctx.get('nameEn') or ctx.get('productName') or ctx.get('sku') or ''),
33
+ '海关编码': str(ctx.get('hsCode') or ''),
34
+ '材质英文': str(ctx.get('materialEn') or ''),
35
+ '材质中文': str(ctx.get('material') or ''),
36
+ '重量(kg/箱)': ctx.get('weight') or '',
37
+ '长(cm)': ctx.get('length') or '',
38
+ '宽(cm)': ctx.get('width') or '',
39
+ '高(cm)': ctx.get('height') or '',
40
+ },
41
+ }
42
+
43
+
44
+ def build_wenyao_fixture(ctx: dict, rec: dict) -> dict:
45
+ boxes = max(1, int(rec['箱数'] or 1))
46
+ return {
47
+ '产品名称': rec['品名'], '货件号': rec['货件号'], 'SKU': str(ctx.get('sku') or ''),
48
+ '店铺': str(ctx.get('store') or ''), '数量': int(rec['数量'] or 0), '箱数': boxes,
49
+ '装箱数': max(1, int(rec['数量'] or 0) // boxes),
50
+ '重量': float(ctx.get('weight') or 0), '长': float(ctx.get('length') or 0),
51
+ '宽': float(ctx.get('width') or 0), '高': float(ctx.get('height') or 0),
52
+ '材质': str(ctx.get('material') or ''), 'HS编码': str(ctx.get('hsCode') or ''),
53
+ '产品图': '',
54
+ }
55
+
56
+
57
+ def run_wenyao(ctx: dict, rec: dict, generate_only: bool) -> dict:
58
+ """文鳐:SkuFlow fixture → p3/p4 → 门户 p6-p14;门户回写由本适配器接管,不写 lip。"""
59
+ import wenyao_run as wr
60
+ shipment = rec['货件号']
61
+ fixture = build_wenyao_fixture(ctx, rec)
62
+ wr.FIX_DIR.mkdir(parents=True, exist_ok=True)
63
+ fx = wr.FIX_DIR / f'skuflow-{ctx.get("skuFlowId","")}-{shipment}.json'
64
+ fx.write_text(json.dumps(fixture, ensure_ascii=False))
65
+ template = wr.DOWN_DIR / '跨境电商-下单模板.xlsx'
66
+ if not template.exists():
67
+ raise RuntimeError(f'文鳐模板不存在: {template}')
68
+ r3 = wr.p3_fill(str(fx), str(ctx.get('nameEn') or rec['品名']), '', None,
69
+ material_en=str(ctx.get('materialEn') or ''), write_dict=False)
70
+ wr.p4_verify(r3['xlsx'], str(template))
71
+ out = {'ok': True, 'invoicePath': r3['xlsx'], 'bulkLabelPath': '', 'orderNo': shipment}
72
+ if generate_only:
73
+ return out
74
+ import wenyao_portal as wp
75
+ orig = wr._writeback
76
+ wr._writeback = lambda *a, **k: None # 门户 P13/P14 的 lip 回写由 SkuFlow/ERP 接管
77
+ try:
78
+ class A: pass
79
+ a = A(); a.shipment = shipment; a.english_name = str(ctx.get('nameEn') or rec['品名'])
80
+ r1 = {'record_id': ''}
81
+ r2 = {'fixture': fixture}
82
+ with wp.portal_lock(site=f'portal.{shipment}', timeout=wp.portal_lock_timeout(),
83
+ reporter=lambda m: None) as waited:
84
+ final = wr.p6_p14_portal(a, r1, r2, r3, 1, wp, waited)
85
+ if not final:
86
+ raise RuntimeError('文鳐大货标签未生成')
87
+ out['bulkLabelPath'] = str(final)
88
+ finally:
89
+ wr._writeback = orig
90
+ return out
91
+
92
+
93
+ def main() -> int:
94
+ ap = argparse.ArgumentParser()
95
+ ap.add_argument('--record-json', required=True)
96
+ ap.add_argument('--generate-only', action='store_true')
97
+ ap.add_argument('--template', default='')
98
+ a = ap.parse_args()
99
+ out = {}
100
+ try:
101
+ ctx = json.loads(a.record_json)
102
+ rec = build_record(ctx)
103
+ missing = [k for k in ('货件号', '店铺名称', '数量', '箱数') if not rec.get(k)]
104
+ if missing:
105
+ raise RuntimeError(f"缺字段: {', '.join(missing)}")
106
+ sku = rec['sku_data']
107
+ miss2 = [k for k in ('海关编码', '材质中文', '重量(kg/箱)', '长(cm)', '宽(cm)', '高(cm)') if not sku.get(k)]
108
+ if miss2:
109
+ raise RuntimeError(f"SKU 发票主数据缺: {', '.join(miss2)}")
110
+ forwarder = str(ctx.get('forwarder') or '')
111
+ if '文鳐' in forwarder:
112
+ out = run_wenyao(ctx, rec, a.generate_only)
113
+ print(json.dumps(out, ensure_ascii=False))
114
+ return 0 if out.get('ok') else 1
115
+ if '鑫中航' not in forwarder:
116
+ raise RuntimeError(f"未知货代: {forwarder or '(空)'}")
117
+ mapping = load_mapping()
118
+ tpl = Path(a.template) if a.template else (DATA / 'invoice-templates' / 'xzh-template.xlsx')
119
+ if not tpl.exists():
120
+ tpl = Path(str(mapping.get('templates', {}).get('鑫中航') or ''))
121
+ if not tpl.exists():
122
+ raise RuntimeError(f"模板不存在: {tpl}")
123
+ import openpyxl
124
+ wb = openpyxl.load_workbook(tpl)
125
+ out_dir = DATA / 'invoice-output'
126
+ out_dir.mkdir(parents=True, exist_ok=True)
127
+ invoice = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{rec['货件号']}.xlsx"
128
+ generate_invoice(rec, mapping, wb, invoice)
129
+ out = {'ok': True, 'invoicePath': str(invoice), 'bulkLabelPath': '', 'orderNo': rec['货件号']}
130
+ if not a.generate_only:
131
+ from invoice_stageb import upload_invoice, download_label
132
+ if not upload_invoice(str(invoice), order_no=rec['货件号']):
133
+ raise RuntimeError('鑫中航上传失败')
134
+ label = download_label(rec['货件号'])
135
+ if not label:
136
+ raise RuntimeError('大货标签下载失败')
137
+ out['bulkLabelPath'] = str(label)
138
+ except Exception as e:
139
+ out = {'ok': False, 'error': str(e)[:500]}
140
+ print(json.dumps(out, ensure_ascii=False))
141
+ return 0 if out.get('ok') else 1
142
+
143
+
144
+ if __name__ == '__main__':
145
+ raise SystemExit(main())