@whyshu/argent-engine 0.8.0-rc.8 → 0.13.27
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.
- package/MANIFEST.json +109 -43
- package/bin/runtime-install.mjs +92 -0
- package/engine/VERSION +1 -1
- package/engine/configs/billing-actions.json +30 -0
- package/engine/configs/mcp-tools.snapshot.json +47 -0
- package/engine/core/contracts/argent.contracts.json +3 -3
- package/engine/core/contracts/verbs.schema.json +64 -1
- package/engine/core/lib/account-token.mjs +37 -0
- package/engine/core/lib/contract.mjs +30 -0
- package/engine/core/lib/redact.mjs +34 -0
- package/engine/core/mcp/billing-upload.mjs +77 -0
- package/engine/core/mcp/erp-server.mjs +300 -0
- package/engine/core/mcp/gateway.mjs +333 -0
- package/engine/core/mcp/meter.mjs +101 -0
- package/engine/core/mcp/server.mjs +416 -2
- package/engine/core/mcp/vault.mjs +78 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1389 -264
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/argent-web-preflight.mjs +123 -0
- package/engine/scripts/argent-web-verify.mjs +105 -0
- package/engine/scripts/billing-upload.mjs +26 -0
- package/engine/scripts/build-doc-index.mjs +68 -0
- package/engine/scripts/build-engine-package.mjs +7 -1
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-docs-drift.mjs +51 -4
- package/engine/scripts/check-version-consistency.mjs +14 -1
- package/engine/scripts/ci-run.sh +2 -2
- package/engine/scripts/collect-intel.mjs +108 -0
- package/engine/scripts/daily-report-timer-plist.sh +18 -4
- package/engine/scripts/daily-report-timers.sh +36 -3
- package/engine/scripts/daily-report.mjs +78 -2
- package/engine/scripts/doc-status.mjs +212 -0
- package/engine/scripts/dsh-web-doctor.mjs +84 -0
- package/engine/scripts/engine-manifest.mjs +90 -0
- package/engine/scripts/engine-runtime-install.mjs +92 -0
- package/engine/scripts/erp-ui-install.mjs +127 -0
- package/engine/scripts/erp-ui-preflight.mjs +104 -0
- package/engine/scripts/erp-ui-verify.mjs +135 -0
- package/engine/scripts/flow-requirements.json +122 -99
- package/engine/scripts/full-exec-worker.mjs +251 -0
- package/engine/scripts/gen-preset-rows.mjs +1 -1
- package/engine/scripts/invoice_lip_runner.py +1 -0
- package/engine/scripts/invoice_runner.py +17 -6
- package/engine/scripts/invoice_stageb.py +21 -4
- package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
- package/engine/scripts/lib/intel-card.mjs +43 -0
- package/engine/scripts/lib/invoice_names.py +23 -0
- package/engine/scripts/lib/ml-ads-core.mjs +100 -18
- package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
- package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
- package/engine/scripts/lib/ml-category-core.mjs +120 -0
- package/engine/scripts/lib/ml-insight-core.mjs +621 -0
- package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
- package/engine/scripts/lib/ml-items.mjs +40 -0
- package/engine/scripts/lib/ml-listing-core.mjs +342 -0
- package/engine/scripts/lib/ml-market-core.mjs +774 -0
- package/engine/scripts/lib/plugin-packages.mjs +13 -0
- package/engine/scripts/lib/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/mcp-gateway-switch.mjs +100 -0
- package/engine/scripts/migrate-providers.mjs +3 -3
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +221 -0
- package/engine/scripts/ml-category-baseline.mjs +174 -0
- package/engine/scripts/ml-insight-diagnose.mjs +247 -0
- package/engine/scripts/ml-insight-run.sh +183 -0
- package/engine/scripts/ml-insight-timers.sh +224 -0
- package/engine/scripts/ml-listing-audit.mjs +170 -0
- package/engine/scripts/ml-market-matrix.mjs +84 -0
- package/engine/scripts/ml-market-snapshot.mjs +261 -0
- package/engine/scripts/ml-messages.mjs +145 -0
- package/engine/scripts/ml-oauth-setup.mjs +1 -1
- package/engine/scripts/npm-publish-argent.mjs +14 -0
- package/engine/scripts/ops-codefix-pr.mjs +87 -0
- package/engine/scripts/ops-codefix-queue.mjs +30 -0
- package/engine/scripts/ops-digest.mjs +98 -0
- package/engine/scripts/ops-verify.mjs +67 -0
- package/engine/scripts/orchestrator.py +410 -20
- package/engine/scripts/orchestrator_br.py +146 -4
- package/engine/scripts/plugin-bootcheck.mjs +50 -1
- package/engine/scripts/publish-engine.mjs +111 -0
- package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
- package/engine/scripts/skuflow_invoice_runner.py +43 -3
- package/engine/scripts/v0.9-acceptance.mjs +107 -0
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/web-switch.mjs +121 -0
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- package/engine/skills/README.md +3 -3
- package/engine/skills/bilibili-upload/SKILL.md +109 -0
- package/engine/skills/douyin-upload/SKILL.md +74 -0
- package/engine/skills/internal.json +28 -0
- package/engine/skills/kuaishou-upload/SKILL.md +109 -0
- package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
- package/engine/skills/ml-full-appointment/SKILL.md +23 -0
- package/engine/skills/ml-invoice/SKILL.md +2 -2
- package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
- package/engine/skills/ml-label-recovery/SKILL.md +43 -0
- package/engine/skills/ml-listing-audit/SKILL.md +66 -0
- package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
- package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -0
- package/engine/skills/tencent-upload/SKILL.md +60 -0
- package/engine/skills/weibo-upload/SKILL.md +106 -0
- package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
- package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/README.md +7 -0
- package/engine/verticals/_engine-words.baseline.txt +27 -59
- package/engine/verticals/mercadolibre/manifest.json +132 -6
- package/package.json +5 -1
|
@@ -2226,7 +2226,8 @@ def _cdp_port_map_path() -> Path:
|
|
|
2226
2226
|
return Path(resolve_data_dir()["dir"]) / "cdp-port-map.json"
|
|
2227
2227
|
|
|
2228
2228
|
|
|
2229
|
-
def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int
|
|
2229
|
+
def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int,
|
|
2230
|
+
download_dir: str = "") -> None:
|
|
2230
2231
|
"""把 startBrowser 返回的 debuggingPort 写入 cdp-port-map.json(替代进程扫描)。
|
|
2231
2232
|
|
|
2232
2233
|
格式与 init-ml.sh 产物一致:storeId → {store_name, env_name, cdp_port}。
|
|
@@ -2238,7 +2239,9 @@ def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int)
|
|
|
2238
2239
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
2239
2240
|
except Exception:
|
|
2240
2241
|
data = {}
|
|
2241
|
-
data[store_id] = {"store_name": store_name, "env_name": env_name, "cdp_port": int(port)
|
|
2242
|
+
data[store_id] = {"store_name": store_name, "env_name": env_name, "cdp_port": int(port),
|
|
2243
|
+
"download_dir": str(download_dir or ""),
|
|
2244
|
+
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
2242
2245
|
try:
|
|
2243
2246
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
2244
2247
|
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
@@ -9485,6 +9488,29 @@ class Orchestrator:
|
|
|
9485
9488
|
return (f"⚠️ 表内货件号 {sid} 在 inbounds 查不到,+1/+2 也查不到 ⇒ "
|
|
9486
9489
|
f"可能已关闭(历史行正常现象)或确为坏号,需人工核对后再续跑")
|
|
9487
9490
|
|
|
9491
|
+
async def _existing_appointment_text(self) -> str:
|
|
9492
|
+
"""取「已有预约」卡片附近的文本(用于解析已预约日期/时段,改约判断用)。
|
|
9493
|
+
|
|
9494
|
+
做法:找到含 `Cancelar reserva` 的按钮,向上找 6 层祖先里第一个文本够长的容器;
|
|
9495
|
+
拿不到就退回整页文本(截断)。**只读**,不点任何按钮。
|
|
9496
|
+
"""
|
|
9497
|
+
try:
|
|
9498
|
+
return await self.browser.page.evaluate(
|
|
9499
|
+
"""() => {
|
|
9500
|
+
const btns = [...document.querySelectorAll('button')]
|
|
9501
|
+
.filter(b => /Cancelar reserva/i.test(b.innerText || ''));
|
|
9502
|
+
if (!btns.length) return '';
|
|
9503
|
+
let el = btns[0];
|
|
9504
|
+
for (let i = 0; i < 6 && el; i += 1) {
|
|
9505
|
+
el = el.parentElement;
|
|
9506
|
+
if (el && el.innerText && el.innerText.length > 40) return el.innerText.slice(0, 1200);
|
|
9507
|
+
}
|
|
9508
|
+
return (document.body.innerText || '').slice(0, 1200);
|
|
9509
|
+
}"""
|
|
9510
|
+
) or ''
|
|
9511
|
+
except Exception:
|
|
9512
|
+
return ''
|
|
9513
|
+
|
|
9488
9514
|
async def _has_existing_appointment(self) -> bool:
|
|
9489
9515
|
"""检测预约页是否已有预约:页面含「Cancelar reserva」按钮(已有预约的标识)。"""
|
|
9490
9516
|
try:
|
|
@@ -9767,7 +9793,15 @@ class Orchestrator:
|
|
|
9767
9793
|
# 实证:最早几个日期会被平台拒(红弹窗 `Algo salió mal / Inténtalo nuevamente`
|
|
9768
9794
|
# + `Código: IPL13-…`;运营口径"所选时间不可预约,得往后面的日期选择")。
|
|
9769
9795
|
_max_day = _appointment_max_day()
|
|
9770
|
-
|
|
9796
|
+
# 2026-11-18:巴西站点(MLB)预约日期至少为「今天+3」才可选(客户口径:18 号最早选 21 号);
|
|
9797
|
+
# 墨西哥(MLM)仍是今天+1 起。env `ARGENT_APPOINTMENT_MIN_DAY` 可覆盖。
|
|
9798
|
+
_min_day = 3 if str(getattr(_SITE, "site", "MLM")).upper() == "MLB" else 1
|
|
9799
|
+
_env_min = str(os.environ.get("ARGENT_APPOINTMENT_MIN_DAY") or "").strip()
|
|
9800
|
+
if _env_min.isdigit():
|
|
9801
|
+
_min_day = max(1, int(_env_min))
|
|
9802
|
+
if _min_day > 1:
|
|
9803
|
+
self._log(f" 📅 站点 {getattr(_SITE, 'site', 'MLM')} 规则:最早可约日 = 今天+{_min_day} 天")
|
|
9804
|
+
for date_offset in range(_min_day, _max_day + 1):
|
|
9771
9805
|
if date_offset > 1: # 换日期:重新进入预约页(上一日期可能残留选择状态)
|
|
9772
9806
|
self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
|
|
9773
9807
|
await self.browser.visit_plan_page("appointment-v2",
|
|
@@ -12473,6 +12507,108 @@ class Orchestrator:
|
|
|
12473
12507
|
return None
|
|
12474
12508
|
|
|
12475
12509
|
# ---- 店铺级**执行者**锁(同店同一时刻只允许一个执行者;§8.57 事故的机械约束)----
|
|
12510
|
+
# ── 每次预约任务:槽位锁 + 窗口复用(2026-11-17,为"每店 3 并行"铺路)────────────
|
|
12511
|
+
def acquire_appt_slot_lock(self, slot_no: int) -> bool:
|
|
12512
|
+
"""预约任务的「槽位锁」:同店 slotNo 1..N 各一把,非阻塞。
|
|
12513
|
+
|
|
12514
|
+
与店铺执行者锁的分工:
|
|
12515
|
+
· 店铺执行者锁 = **开店权**(取窗口会换端口、踢掉别人标签页)⇒ 同一时刻只该有一个进程开会话,
|
|
12516
|
+
拿到后开完店**立刻释放**,其他人读 cdp-port-map.json 复用端口;
|
|
12517
|
+
· 槽位锁 = **执行位**(本任务整个生命周期持有)⇒ 决定同店能同时跑几条。
|
|
12518
|
+
"""
|
|
12519
|
+
if getattr(self.args, "no_lock", False):
|
|
12520
|
+
return True
|
|
12521
|
+
key = self._store_lock_key()
|
|
12522
|
+
if not key:
|
|
12523
|
+
return True
|
|
12524
|
+
try:
|
|
12525
|
+
slot = int(slot_no or 0)
|
|
12526
|
+
except (TypeError, ValueError):
|
|
12527
|
+
slot = 0
|
|
12528
|
+
if slot <= 0:
|
|
12529
|
+
return True # 没有槽位号(老任务)⇒ 不额外限制
|
|
12530
|
+
lock_path = os.path.join(lock_dir(), f"appt-slot-{key}-{slot}.lock")
|
|
12531
|
+
lock = FileLock(lock_path, site="orchestrator.appt_slot_lock")
|
|
12532
|
+
try:
|
|
12533
|
+
got = lock.try_acquire()
|
|
12534
|
+
except LockError as exc:
|
|
12535
|
+
lock.release()
|
|
12536
|
+
self._log(f"⚠️ 槽位锁不可用,降级为不限制({exc})")
|
|
12537
|
+
return True
|
|
12538
|
+
if not got:
|
|
12539
|
+
lock.release()
|
|
12540
|
+
self._log(f"⛔ 同店槽位 {slot} 已被占用({lock_path})⇒ 本任务让位")
|
|
12541
|
+
return False
|
|
12542
|
+
self._appt_slot_lock = lock
|
|
12543
|
+
try:
|
|
12544
|
+
f = lock.fp
|
|
12545
|
+
f.seek(0); f.truncate()
|
|
12546
|
+
f.write(json.dumps({"pid": os.getpid(), "slot": slot, "store": self.state.store_name or "",
|
|
12547
|
+
"since": time.strftime("%Y-%m-%d %H:%M:%S")}, ensure_ascii=False))
|
|
12548
|
+
f.flush()
|
|
12549
|
+
except Exception: # noqa: BLE001
|
|
12550
|
+
pass
|
|
12551
|
+
self._log(f" 🔒 预约槽位锁已获取:slot={slot}")
|
|
12552
|
+
return True
|
|
12553
|
+
|
|
12554
|
+
def release_appt_slot_lock(self) -> None:
|
|
12555
|
+
lock = getattr(self, "_appt_slot_lock", None)
|
|
12556
|
+
if lock is None:
|
|
12557
|
+
return
|
|
12558
|
+
try:
|
|
12559
|
+
lock.release()
|
|
12560
|
+
except Exception: # noqa: BLE001
|
|
12561
|
+
pass
|
|
12562
|
+
self._appt_slot_lock = None
|
|
12563
|
+
|
|
12564
|
+
def release_store_executor_lock(self) -> None:
|
|
12565
|
+
"""释放开店权(同店窗口已就绪后立刻放行,让后续任务复用端口)。"""
|
|
12566
|
+
lock = getattr(self, "_store_exec_lock", None)
|
|
12567
|
+
if lock is None:
|
|
12568
|
+
return
|
|
12569
|
+
try:
|
|
12570
|
+
lock.release()
|
|
12571
|
+
except Exception: # noqa: BLE001
|
|
12572
|
+
pass
|
|
12573
|
+
self._store_exec_lock = None
|
|
12574
|
+
|
|
12575
|
+
def remember_store_window(self, port: int, download_dir: str = "") -> None:
|
|
12576
|
+
"""开店成功后把端口/下载目录写进 cdp-port-map.json,供同店其它任务复用(不再开店)。"""
|
|
12577
|
+
key = (self._cdp_store_id() or "").strip()
|
|
12578
|
+
if not key or not port:
|
|
12579
|
+
return
|
|
12580
|
+
try:
|
|
12581
|
+
write_cdp_port_map(key, self.state.store_name or "", "", int(port), str(download_dir or ""))
|
|
12582
|
+
except Exception as exc: # noqa: BLE001
|
|
12583
|
+
self._log(f" ⚠️ 写 cdp-port-map 失败(影响同店复用):{exc}")
|
|
12584
|
+
|
|
12585
|
+
def read_store_window(self, max_age_sec: int = 900):
|
|
12586
|
+
"""读 cdp-port-map.json 里本店窗口:返回 (download_dir, port) 或 (None, None)。
|
|
12587
|
+
|
|
12588
|
+
只认 `updated_at` 在 max_age_sec 内的记录,避免拿到早已失效的端口。
|
|
12589
|
+
"""
|
|
12590
|
+
key = (self._cdp_store_id() or "").strip()
|
|
12591
|
+
if not key:
|
|
12592
|
+
return None, None
|
|
12593
|
+
try:
|
|
12594
|
+
path = _cdp_port_map_path()
|
|
12595
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
12596
|
+
except Exception: # noqa: BLE001
|
|
12597
|
+
return None, None
|
|
12598
|
+
rec = data.get(key) or {}
|
|
12599
|
+
port = int(rec.get("cdp_port") or 0)
|
|
12600
|
+
if not port:
|
|
12601
|
+
return None, None
|
|
12602
|
+
ts = str(rec.get("updated_at") or "")
|
|
12603
|
+
if ts:
|
|
12604
|
+
try:
|
|
12605
|
+
age = (datetime.now() - datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S")).total_seconds()
|
|
12606
|
+
if age > max_age_sec:
|
|
12607
|
+
return None, None
|
|
12608
|
+
except ValueError:
|
|
12609
|
+
pass
|
|
12610
|
+
return (rec.get("download_dir") or None), port
|
|
12611
|
+
|
|
12476
12612
|
def acquire_store_executor_lock(self) -> bool:
|
|
12477
12613
|
"""获取店铺级执行者锁。拿不到 ⇒ False(调用方**不落表**、以 skipped 退出)。
|
|
12478
12614
|
|
|
@@ -12688,7 +12824,11 @@ class Orchestrator:
|
|
|
12688
12824
|
else:
|
|
12689
12825
|
await self.step3_select_product()
|
|
12690
12826
|
elif step == 4:
|
|
12691
|
-
|
|
12827
|
+
if getattr(self.args, "skip_appointment", False):
|
|
12828
|
+
self._log(" ⏭ 跳过步骤4 预约(预约交给 FULL 预约队列,由 worker 持续抢号)")
|
|
12829
|
+
self._mark_done(4)
|
|
12830
|
+
else:
|
|
12831
|
+
await self.step4_appointment()
|
|
12692
12832
|
elif step == 5:
|
|
12693
12833
|
await self.step5_package_confirm()
|
|
12694
12834
|
elif step == 6:
|
|
@@ -13942,6 +14082,8 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
13942
14082
|
help="step 模式下的步骤号")
|
|
13943
14083
|
p.add_argument("--allow-write", action="store_true",
|
|
13944
14084
|
help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
|
|
14085
|
+
p.add_argument("--skip-appointment", action="store_true",
|
|
14086
|
+
help="FULL 流程跳过步骤4 预约(预约交给 ERP 的 FULL 预约队列;2026-11-18)")
|
|
13945
14087
|
p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
|
|
13946
14088
|
p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
|
|
13947
14089
|
p.add_argument("--qty", help="数量(配合 --record-id 使用)")
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
* (实测 110 条 `disabling profile plugin row`),输出与"Argent 坏了"无法区分。此时**当场判红**。
|
|
56
56
|
*/
|
|
57
57
|
import { spawn, spawnSync } from 'node:child_process'
|
|
58
|
-
import { mkdtempSync, mkdirSync, rmSync, symlinkSync, existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs'
|
|
58
|
+
import { mkdtempSync, mkdirSync, rmSync, symlinkSync, existsSync, readFileSync, readdirSync, realpathSync, statSync, lstatSync, writeFileSync } from 'node:fs'
|
|
59
59
|
import { createRequire } from 'node:module'
|
|
60
60
|
import { homedir, tmpdir } from 'node:os'
|
|
61
61
|
import { join } from 'node:path'
|
|
@@ -273,6 +273,55 @@ if (!guard.ok) {
|
|
|
273
273
|
}
|
|
274
274
|
applyProfileWiring(plan)
|
|
275
275
|
|
|
276
|
+
// ── 预设 bundle 准备(2026-11-24)─────────────────────────────────────────
|
|
277
|
+
// 真实 profile 可能只装了 @whyshu/argent,没有 @whyshu/argent-presets(开发机常见);
|
|
278
|
+
// 这样 preset 探针永远拿不到注册表,报 15 个 Unknown agent preset。这里只在**临时 profile**
|
|
279
|
+
// 补仓库里的 preset bundle,供 bootcheck 真实挂载;⛔ 不写真实 profile。
|
|
280
|
+
function ensureRepoPresetBundle() {
|
|
281
|
+
if (mechanism !== MECHANISM.ROWS) return;
|
|
282
|
+
const src = join(process.cwd(), 'plugins', 'argent-presets');
|
|
283
|
+
if (!existsSync(join(src, 'presets.json'))) return;
|
|
284
|
+
const tmpWhyshu = join(tmpProfileDir, 'node_modules', '@whyshu');
|
|
285
|
+
try {
|
|
286
|
+
const realWhyshu = existsSync(tmpWhyshu) ? realpathSync(tmpWhyshu) : '';
|
|
287
|
+
if (existsSync(tmpWhyshu) && lstatSync(tmpWhyshu).isSymbolicLink()) {
|
|
288
|
+
rmSync(tmpWhyshu, { force: true });
|
|
289
|
+
mkdirSync(tmpWhyshu, { recursive: true });
|
|
290
|
+
for (const e of readdirSync(realWhyshu)) symlinkSync(join(realWhyshu, e), join(tmpWhyshu, e));
|
|
291
|
+
} else {
|
|
292
|
+
mkdirSync(tmpWhyshu, { recursive: true });
|
|
293
|
+
}
|
|
294
|
+
const dest = join(tmpWhyshu, 'argent-presets');
|
|
295
|
+
if (!existsSync(dest)) symlinkSync(src, dest, 'dir');
|
|
296
|
+
// 角色 preset 还引用仓库内的其他 @whyshu 插件(如 @whyshu/argent-ml);
|
|
297
|
+
// 临时 profile 也补上**仓库货架**的包,避免 bootcheck 因开发机 profile 未装齐而假红。
|
|
298
|
+
const repoPlugins = join(process.cwd(), 'plugins');
|
|
299
|
+
for (const dir of readdirSync(repoPlugins)) {
|
|
300
|
+
const pp = join(repoPlugins, dir, 'package.json');
|
|
301
|
+
if (!existsSync(pp)) continue;
|
|
302
|
+
let name = '';
|
|
303
|
+
try { name = JSON.parse(readFileSync(pp, 'utf8')).name || ''; } catch { continue; }
|
|
304
|
+
if (!name.startsWith('@whyshu/')) continue;
|
|
305
|
+
const sub = name.slice('@whyshu/'.length);
|
|
306
|
+
const link = join(tmpWhyshu, sub);
|
|
307
|
+
if (!existsSync(link)) symlinkSync(join(repoPlugins, dir), link, 'dir');
|
|
308
|
+
}
|
|
309
|
+
const pkgPath = join(tmpProfileDir, 'package.json');
|
|
310
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
311
|
+
pkg.dependencies = pkg.dependencies || {};
|
|
312
|
+
pkg.dependencies['@whyshu/argent-presets'] = `file:${src}`;
|
|
313
|
+
pkg.dsh = pkg.dsh || {};
|
|
314
|
+
pkg.dsh.profile = pkg.dsh.profile || {};
|
|
315
|
+
const bundles = Array.isArray(pkg.dsh.profile.bundles) ? pkg.dsh.profile.bundles : [];
|
|
316
|
+
if (!bundles.includes('@whyshu/argent-presets')) pkg.dsh.profile.bundles = [...bundles, '@whyshu/argent-presets'];
|
|
317
|
+
writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
|
318
|
+
console.log('[bootcheck] 已在临时 profile 补 @whyshu/argent-presets(只读挂载仓库货架,不写真实 profile)');
|
|
319
|
+
} catch (e) {
|
|
320
|
+
console.log('[bootcheck] ⚠️ 预设 bundle 准备失败:' + e.message);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
ensureRepoPresetBundle();
|
|
324
|
+
|
|
276
325
|
// 自证:从临时 profile 解析探针包,必须落到**目标 scope**内(解析不到 ⇒ 目标 scope 不可用)。
|
|
277
326
|
const req = createRequire(join(tmpProfileDir, 'package.json'))
|
|
278
327
|
const resolveFrom = (spec) => {
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 引擎包发布(P0 更新通道,2026-11-16)
|
|
4
|
+
*
|
|
5
|
+
* 产物:
|
|
6
|
+
* · `/dl/engine/argent-engine-<ver>.tgz`(含 `package/` 前缀,插件解压即用)
|
|
7
|
+
* · `engine-manifest.json`(latest + engines{版本:{url,sha256,size,minShell}})
|
|
8
|
+
*
|
|
9
|
+
* 用法:
|
|
10
|
+
* node scripts/publish-engine.mjs # dry-run:只打包 + 算摘要 + 打印计划
|
|
11
|
+
* node scripts/publish-engine.mjs --apply # 真发:rsync tgz 到 /dl/engine/ + 覆盖服务端清单
|
|
12
|
+
* 可选:--version <v>(默认取 plugins/argent/package.json 版本,引擎与插件同版本号发布)
|
|
13
|
+
*/
|
|
14
|
+
import { execFileSync } from 'node:child_process'
|
|
15
|
+
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
|
|
16
|
+
import { tmpdir } from 'node:os'
|
|
17
|
+
import { dirname, join, resolve } from 'node:path'
|
|
18
|
+
import { fileURLToPath } from 'node:url'
|
|
19
|
+
import { buildManifest, sha256File, emptyManifestDoc, upsertManifest, compareVersions } from './engine-manifest.mjs'
|
|
20
|
+
|
|
21
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
22
|
+
const REPO = resolve(HERE, '..')
|
|
23
|
+
const args = process.argv.slice(2)
|
|
24
|
+
const APPLY = args.includes('--apply')
|
|
25
|
+
const argOf = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : '' }
|
|
26
|
+
const MIRROR_REPO = argOf('--mirror-repo')
|
|
27
|
+
|
|
28
|
+
const SH = {
|
|
29
|
+
pkg: { host: 'ubuntu@81.69.222.211', dir: '/var/www/whyshu-web/dl/engine/', sshKey: '~/.ssh/whyshu.pem' },
|
|
30
|
+
manifest: { host: 'ubuntu@81.69.222.211', path: '/home/whyshu/server/config/engine-manifest.json' },
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function version() {
|
|
34
|
+
const v = argOf('--version')
|
|
35
|
+
if (v) return v.trim()
|
|
36
|
+
return JSON.parse(readFileSync(join(REPO, 'plugins/argent/package.json'), 'utf8')).version
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function main() {
|
|
40
|
+
const ver = version()
|
|
41
|
+
const work = mkdtempSync(join(tmpdir(), 'eng-publish-'))
|
|
42
|
+
const outDir = join(work, 'pkg')
|
|
43
|
+
mkdirSync(outDir, { recursive: true })
|
|
44
|
+
|
|
45
|
+
console.log(`── 打引擎包 v${ver}`)
|
|
46
|
+
execFileSync(process.execPath, [join(REPO, 'scripts/build-engine-package.mjs'), '--out', outDir], { stdio: 'inherit' })
|
|
47
|
+
|
|
48
|
+
// npm 风格:包根加 package/ 前缀(插件按 package/ 或扁平都能识别)
|
|
49
|
+
const stage = join(work, 'stage')
|
|
50
|
+
mkdirSync(join(stage, 'package'), { recursive: true })
|
|
51
|
+
execFileSync('cp', ['-R', `${outDir}/.`, join(stage, 'package')], { stdio: 'pipe' })
|
|
52
|
+
const tgzName = `argent-engine-${ver}.tgz`
|
|
53
|
+
const tgz = join(work, tgzName)
|
|
54
|
+
execFileSync('tar', ['-czf', tgz, '-C', stage, 'package'], { stdio: 'pipe' })
|
|
55
|
+
|
|
56
|
+
const sha256 = sha256File(tgz)
|
|
57
|
+
const size = Number(execFileSync('stat', ['-f%z', tgz], { encoding: 'utf8' }).trim())
|
|
58
|
+
const url = `https://whyshu.com/dl/engine/${tgzName}`
|
|
59
|
+
const manifest = buildManifest({ version: ver, url, sha256, size, minShell: '0.11.0' })
|
|
60
|
+
|
|
61
|
+
console.log(` ${tgzName} ${(size / 1024 / 1024).toFixed(2)} MB sha256=${sha256.slice(0, 16)}…`)
|
|
62
|
+
|
|
63
|
+
// 与服务端现有清单合并(保留历史版本,便于回滚)
|
|
64
|
+
let doc = emptyManifestDoc()
|
|
65
|
+
try {
|
|
66
|
+
const local = join(REPO, '.cache/engine-manifest.remote.json')
|
|
67
|
+
doc = JSON.parse(readFileSync(local, 'utf8'))
|
|
68
|
+
} catch { /* 首次发布没有本地缓存 */ }
|
|
69
|
+
const prevLatest = doc.latest || ''
|
|
70
|
+
const next = upsertManifest(doc, manifest)
|
|
71
|
+
const manifestPath = join(work, 'engine-manifest.json')
|
|
72
|
+
writeFileSync(manifestPath, `${JSON.stringify(next, null, 2)}\n`)
|
|
73
|
+
|
|
74
|
+
console.log(`\n── 计划`)
|
|
75
|
+
console.log(` 产物 → ${SH.pkg.host}:${SH.pkg.dir}${tgzName}`)
|
|
76
|
+
console.log(` 清单 → ${SH.manifest.host}:${SH.manifest.path}(latest=${next.latest})`)
|
|
77
|
+
if (!APPLY) {
|
|
78
|
+
console.log(`\n (dry-run)真发请加 --apply;清单临时文件:${manifestPath}`)
|
|
79
|
+
if (prevLatest === ver) console.log(` ⚠️ 服务端清单里已有 ${ver}:内容变了就必须提版本(内容变⇒版本必变)`)
|
|
80
|
+
return 0
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const ssh = ['-e', `ssh -i ${SH.pkg.sshKey} -o BatchMode=yes`]
|
|
84
|
+
execFileSync('ssh', ['-i', SH.pkg.sshKey, '-o', 'BatchMode=yes', SH.pkg.host, `mkdir -p ${SH.pkg.dir}`], { stdio: 'inherit' })
|
|
85
|
+
execFileSync('rsync', ['-az', ...ssh, tgz, `${SH.pkg.host}:${SH.pkg.dir}`], { stdio: 'inherit' })
|
|
86
|
+
execFileSync('rsync', ['-az', ...ssh, manifestPath, `${SH.manifest.host}:${SH.manifest.path}`], { stdio: 'inherit' })
|
|
87
|
+
|
|
88
|
+
// 取回验真(发布纪律:HTTP 取回算摘要)
|
|
89
|
+
const back = execFileSync('curl', ['-s', url], { maxBuffer: 64 * 1024 * 1024 })
|
|
90
|
+
const backSha = execFileSync(process.execPath, ['-e', `const c=require('crypto');const b=require('fs').readFileSync(0);process.stdout.write(c.createHash('sha256').update(b).digest('hex'))`], { input: back, encoding: 'utf8' })
|
|
91
|
+
if (backSha !== sha256) {
|
|
92
|
+
console.error(` ❌ HTTP 取回摘要不一致:期望 ${sha256.slice(0, 16)}… 实际 ${backSha.slice(0, 16)}…`)
|
|
93
|
+
return 1
|
|
94
|
+
}
|
|
95
|
+
console.log(` ✅ HTTP 取回验真一致`)
|
|
96
|
+
if (MIRROR_REPO) {
|
|
97
|
+
const target = join(MIRROR_REPO, 'src/config/engine-manifest.json')
|
|
98
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
99
|
+
writeFileSync(target, `${JSON.stringify(next, null, 2)}\n`)
|
|
100
|
+
console.log(` ↳ 已同步仓库副本:${target}`)
|
|
101
|
+
}
|
|
102
|
+
// 把合并后的清单落到本地缓存:下次发布据此合并;**也是误覆盖后的恢复源**
|
|
103
|
+
try {
|
|
104
|
+
mkdirSync(join(REPO, '.cache'), { recursive: true })
|
|
105
|
+
writeFileSync(join(REPO, '.cache/engine-manifest.remote.json'), `${JSON.stringify(next, null, 2)}\n`)
|
|
106
|
+
} catch { /* 缓存失败不影响发布 */ }
|
|
107
|
+
rmSync(work, { recursive: true, force: true })
|
|
108
|
+
return 0
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
main().then((c) => process.exit(c)).catch((e) => { console.error(e); process.exit(1) })
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# restart-dsh-with-tunnel.sh — 确保插件已装 → 停旧 dsh → 带隧道启动 → 自检;失败回退
|
|
3
|
+
# 用法: bash restart-dsh-with-tunnel.sh # 默认 3080(用户手动执行)
|
|
4
|
+
# PORT=3098 KILL_AFTER_TEST=1 bash ... # 自测:别的端口,成功后杀掉
|
|
5
|
+
set -o pipefail
|
|
6
|
+
|
|
7
|
+
SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
|
|
8
|
+
PORT="${PORT:-3080}"
|
|
9
|
+
EXEC="${DSH_EXEC:-/Users/Chester/.npm/_npx/1e7f6d9597241db0/node_modules/.bin/dsh}"
|
|
10
|
+
PROFILE_DIR="${ARGENT_PROFILE_DIR:-$HOME/.dsh/profiles/web}"
|
|
11
|
+
# 目标版本默认取仓库当前 package.json(不再硬编码):
|
|
12
|
+
# 硬编码会在别的会话 bump 版本后把插件"降级安装"(2026-11-08 并行会话风险)。
|
|
13
|
+
REPO_ROOT="$(cd "$(dirname "$SELF")/.." && pwd)"
|
|
14
|
+
DEFAULT_PLUGIN_VERSION="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['version'])" "$REPO_ROOT/plugins/argent/package.json" 2>/dev/null)"
|
|
15
|
+
PLUGIN_VERSION="${PLUGIN_VERSION:-${DEFAULT_PLUGIN_VERSION:-0.2.11}}"
|
|
16
|
+
BOOTLOG="${BOOTLOG:-/tmp/dsh-boot.log}"
|
|
17
|
+
RESTARTLOG="${RESTARTLOG:-/tmp/dsh-restart.log}"
|
|
18
|
+
|
|
19
|
+
if [ "${DSH_RESTART_DETACHED:-0}" != "1" ]; then
|
|
20
|
+
DSH_RESTART_DETACHED=1 nohup bash "$SELF" > "$RESTARTLOG" 2>&1 &
|
|
21
|
+
echo "已在后台执行(日志: ${RESTARTLOG});约 60 秒后看结果:"
|
|
22
|
+
echo " tail -f $RESTARTLOG"
|
|
23
|
+
exit 0
|
|
24
|
+
fi
|
|
25
|
+
|
|
26
|
+
log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }
|
|
27
|
+
port_pid() { lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -t 2>/dev/null | head -1; }
|
|
28
|
+
http_code() { curl -s -o /dev/null -w '%{http_code}' --max-time 2 "http://127.0.0.1:${PORT}/" 2>/dev/null || true; }
|
|
29
|
+
# 就绪判据:端口在监听 + HTTP 有任何响应(dsh 根路径无 token 返回 401,⛔ 不能要求 200)
|
|
30
|
+
ready() { [ -n "$(port_pid)" ] && [ "$(http_code)" != "000" ]; }
|
|
31
|
+
|
|
32
|
+
log "step1 ensure-plugin"
|
|
33
|
+
if [ "${SKIP_PLUGIN:-0}" = "1" ]; then
|
|
34
|
+
log "skip plugin install"
|
|
35
|
+
else
|
|
36
|
+
npm_config_registry=https://registry.npmjs.org "$EXEC" plugin --profile web add "@whyshu/argent@$PLUGIN_VERSION" >/tmp/dsh-plugin-add.log 2>&1
|
|
37
|
+
INSTALLED="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['version'])" "$PROFILE_DIR/node_modules/@whyshu/argent/package.json" 2>/dev/null)"
|
|
38
|
+
# 硬门禁:装上的版本必须等于目标版本,且带隧道模块。
|
|
39
|
+
# 不做这一步会「日志说失败、流程继续」,然后把 dsh 起成缺模块的旧版(2026-11-08 实际踩过:装成 0.2.4,无 tunnel.mjs)。
|
|
40
|
+
if [ "$INSTALLED" != "$PLUGIN_VERSION" ] || [ ! -f "$PROFILE_DIR/node_modules/@whyshu/argent/src/tunnel.mjs" ]; then
|
|
41
|
+
log "FATAL 插件版本不符:expected=$PLUGIN_VERSION installed=${INSTALLED:-none}(见 /tmp/dsh-plugin-add.log)"
|
|
42
|
+
log "⇒ 未重启任何 dsh,保持现状;请先修好插件安装再重试"
|
|
43
|
+
exit 1
|
|
44
|
+
fi
|
|
45
|
+
log "plugin ok $INSTALLED (tunnel.mjs present)"
|
|
46
|
+
fi
|
|
47
|
+
|
|
48
|
+
log "step2 stop old dsh on port $PORT"
|
|
49
|
+
OLD_PID="$(port_pid)"
|
|
50
|
+
if [ -n "${OLD_PID:-}" ]; then
|
|
51
|
+
kill -TERM "$OLD_PID" 2>/dev/null
|
|
52
|
+
for _ in $(seq 1 30); do
|
|
53
|
+
[ -z "$(port_pid)" ] && break
|
|
54
|
+
sleep 1
|
|
55
|
+
done
|
|
56
|
+
fi
|
|
57
|
+
if [ -n "$(port_pid)" ]; then
|
|
58
|
+
log "port $PORT still busy pid=$(port_pid); force kill"
|
|
59
|
+
kill -9 "$(port_pid)" 2>/dev/null
|
|
60
|
+
sleep 2
|
|
61
|
+
fi
|
|
62
|
+
if [ -n "$(port_pid)" ]; then
|
|
63
|
+
log "FATAL port $PORT still busy"
|
|
64
|
+
exit 1
|
|
65
|
+
fi
|
|
66
|
+
log "port $PORT free"
|
|
67
|
+
|
|
68
|
+
start_dsh() {
|
|
69
|
+
local mode="$1"
|
|
70
|
+
: > "$BOOTLOG"
|
|
71
|
+
# ⚠️ 用 env + 数组传环境变量:`${VAR:+...}` 为空时会被当成空词,导致后续赋值被当作命令名
|
|
72
|
+
# (2026-11-08 实测报错:ARGENT_PROFILE_DIR=...: No such file or directory)
|
|
73
|
+
# 隧道开关自 0.2.12 起走插件面板配置(app-config.json);env 只在显式设置时透传
|
|
74
|
+
local -a ENVARGS=("ARGENT_PROFILE_DIR=$PROFILE_DIR")
|
|
75
|
+
if [ -n "${ARGENT_TUNNEL:-}" ]; then ENVARGS+=("ARGENT_TUNNEL=$ARGENT_TUNNEL"); fi
|
|
76
|
+
if [ -n "${ARGENT_MCP_DISABLE:-}" ]; then ENVARGS+=("ARGENT_MCP_DISABLE=$ARGENT_MCP_DISABLE"); fi
|
|
77
|
+
nohup env "${ENVARGS[@]}" "$EXEC" --profile web --port "$PORT" --no-open >> "$BOOTLOG" 2>&1 &
|
|
78
|
+
echo $! > /tmp/dsh.pid
|
|
79
|
+
log "started mode=$mode pid=$(cat /tmp/dsh.pid) log=$BOOTLOG"
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
log "step3 start with tunnel"
|
|
83
|
+
start_dsh with-tunnel
|
|
84
|
+
OK=0
|
|
85
|
+
for _ in $(seq 1 45); do
|
|
86
|
+
ready && { OK=1; break; }
|
|
87
|
+
sleep 1
|
|
88
|
+
done
|
|
89
|
+
|
|
90
|
+
if [ "$OK" = "1" ]; then
|
|
91
|
+
log "SUCCESS ready on $PORT (http=$(http_code))"
|
|
92
|
+
grep -aE "隧道|MCP 网关|listen" "$BOOTLOG" | tail -6
|
|
93
|
+
cp -f "$BOOTLOG" "$HOME/.dsh/logs/boot-with-tunnel.log" 2>/dev/null
|
|
94
|
+
TOKEN=$(grep -aoE 'token=[A-Za-z0-9_-]{20,}' "$BOOTLOG" | head -1 | cut -d= -f2)
|
|
95
|
+
if [ -n "$TOKEN" ]; then
|
|
96
|
+
printf '%s\n' "$TOKEN" > "$HOME/.dsh/argent/dsh-web.token"
|
|
97
|
+
chmod 600 "$HOME/.dsh/argent/dsh-web.token"
|
|
98
|
+
log "wrote dsh-web.token (tunnel 可在 access 端点不可用时使用)"
|
|
99
|
+
else
|
|
100
|
+
log "WARN 未能从启动日志提取 dsh token(隧道可能 access-unavailable)"
|
|
101
|
+
fi
|
|
102
|
+
if [ "${KILL_AFTER_TEST:-0}" = "1" ]; then
|
|
103
|
+
log "KILL_AFTER_TEST=1 => stop test instance"
|
|
104
|
+
kill -TERM "$(port_pid)" 2>/dev/null
|
|
105
|
+
fi
|
|
106
|
+
exit 0
|
|
107
|
+
fi
|
|
108
|
+
|
|
109
|
+
log "FAIL http not 200; boot log tail:"
|
|
110
|
+
tail -40 "$BOOTLOG" | sed 's/^/ /'
|
|
111
|
+
log "step4 fallback: start WITHOUT plugin (默认不动 profile)"
|
|
112
|
+
# ⛔ 默认不覆盖 profile:`cp -a` 旧备份会把刚装好的新插件降级(2026-11-08 实测把 0.2.11 覆盖回 0.2.4)。
|
|
113
|
+
# 确实要回滚 profile 时显式 ALLOW_PROFILE_RESTORE=1。
|
|
114
|
+
BAK="$HOME/.dsh/profiles/web.bak-2051"
|
|
115
|
+
if [ "${ALLOW_PROFILE_RESTORE:-0}" = "1" ] && [ -d "$BAK" ]; then
|
|
116
|
+
cp -a "$BAK"/. "$PROFILE_DIR"/
|
|
117
|
+
log "restored $BAK (ALLOW_PROFILE_RESTORE=1)"
|
|
118
|
+
else
|
|
119
|
+
log "skip profile restore(需要回滚请 ALLOW_PROFILE_RESTORE=1 bash $0)"
|
|
120
|
+
fi
|
|
121
|
+
: > "$BOOTLOG"
|
|
122
|
+
nohup "$EXEC" --profile web --port "$PORT" --no-open >> "$BOOTLOG" 2>&1 &
|
|
123
|
+
echo $! > /tmp/dsh.pid
|
|
124
|
+
log "fallback started pid=$(cat /tmp/dsh.pid)"
|
|
125
|
+
for _ in $(seq 1 40); do
|
|
126
|
+
ready && { log "fallback SUCCESS ready (http=$(http_code))"; exit 0; }
|
|
127
|
+
sleep 1
|
|
128
|
+
done
|
|
129
|
+
log "fallback FAILED too; logs: $BOOTLOG"
|
|
@@ -16,13 +16,16 @@ sys.path.insert(0, str(HERE))
|
|
|
16
16
|
DATA = Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
17
17
|
|
|
18
18
|
from invoice_runner import load_mapping, generate_invoice # noqa: E402
|
|
19
|
+
sys.path.insert(0, str(HERE / 'lib'))
|
|
20
|
+
from invoice_names import strip_sku_prefix # noqa: E402
|
|
19
21
|
|
|
20
22
|
|
|
21
23
|
def build_record(ctx: dict) -> dict:
|
|
22
24
|
return {
|
|
23
25
|
'货件号': str(ctx.get('shipmentNo') or ''),
|
|
24
26
|
'店铺名称': str(ctx.get('store') or ''),
|
|
25
|
-
'品名': str(ctx.get('productName') or ctx.get('sku') or ''),
|
|
27
|
+
'品名': strip_sku_prefix(str(ctx.get('productName') or ''), str(ctx.get('sku') or '')) or str(ctx.get('sku') or ''),
|
|
28
|
+
'SKU': str(ctx.get('sku') or ''),
|
|
26
29
|
'数量': int(ctx.get('quantity') or 0),
|
|
27
30
|
'箱数': int(ctx.get('boxCount') or 0),
|
|
28
31
|
'国内收货仓库': '深圳仓',
|
|
@@ -41,10 +44,20 @@ def build_record(ctx: dict) -> dict:
|
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
|
|
47
|
+
def _download_product_image(url: str, dest) -> str:
|
|
48
|
+
"""下载 ERP 签名 URL 的产品图(模板 R 列必填)。"""
|
|
49
|
+
import urllib.request
|
|
50
|
+
req = urllib.request.Request(url, headers={'User-Agent': 'whyshu-skuflow/1.0'})
|
|
51
|
+
with urllib.request.urlopen(req, timeout=25) as r:
|
|
52
|
+
data = r.read()
|
|
53
|
+
dest.write_bytes(data)
|
|
54
|
+
return str(dest)
|
|
55
|
+
|
|
56
|
+
|
|
44
57
|
def build_wenyao_fixture(ctx: dict, rec: dict) -> dict:
|
|
45
58
|
boxes = max(1, int(rec['箱数'] or 1))
|
|
46
59
|
return {
|
|
47
|
-
'产品名称': rec['品名'], '货件号': rec['货件号'], 'SKU': str(ctx.get('sku') or ''),
|
|
60
|
+
'产品名称': strip_sku_prefix(rec['品名'], str(ctx.get('sku') or '')), '货件号': rec['货件号'], 'SKU': str(ctx.get('sku') or ''),
|
|
48
61
|
'店铺': str(ctx.get('store') or ''), '数量': int(rec['数量'] or 0), '箱数': boxes,
|
|
49
62
|
'装箱数': max(1, int(rec['数量'] or 0) // boxes),
|
|
50
63
|
'重量': float(ctx.get('weight') or 0), '长': float(ctx.get('length') or 0),
|
|
@@ -59,13 +72,31 @@ def run_wenyao(ctx: dict, rec: dict, generate_only: bool) -> dict:
|
|
|
59
72
|
import wenyao_run as wr
|
|
60
73
|
shipment = rec['货件号']
|
|
61
74
|
fixture = build_wenyao_fixture(ctx, rec)
|
|
75
|
+
# 2026-11-19 修复:ERP 节点已上传产品图(invoice.imageRefs / purchase.productImageRefs),
|
|
76
|
+
# 但 SkuFlow 文鳐路径之前把产品图写死为空 ⇒ 填报器误报「缺产品图(运营补)」。
|
|
77
|
+
# 这里下载 ERP 签名 URL 到本地,写进 fixture 并传给 p3_fill(模板 AA 列插图)。
|
|
78
|
+
image_path = ''
|
|
79
|
+
urls = [str(ctx.get('productImageUrl') or '')] + [str(x) for x in (ctx.get('productImageUrls') or []) if x]
|
|
80
|
+
out_dir = DATA / 'invoice-output'
|
|
81
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
dest = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{shipment}-product.png"
|
|
83
|
+
for u in urls:
|
|
84
|
+
if not u:
|
|
85
|
+
continue
|
|
86
|
+
try:
|
|
87
|
+
image_path = _download_product_image(u, dest)
|
|
88
|
+
fixture['产品图'] = image_path
|
|
89
|
+
print('产品图已下载:', image_path, flush=True)
|
|
90
|
+
break
|
|
91
|
+
except Exception as e:
|
|
92
|
+
print('产品图下载失败:', e, flush=True)
|
|
62
93
|
wr.FIX_DIR.mkdir(parents=True, exist_ok=True)
|
|
63
94
|
fx = wr.FIX_DIR / f'skuflow-{ctx.get("skuFlowId","")}-{shipment}.json'
|
|
64
95
|
fx.write_text(json.dumps(fixture, ensure_ascii=False))
|
|
65
96
|
template = wr.DOWN_DIR / '跨境电商-下单模板.xlsx'
|
|
66
97
|
if not template.exists():
|
|
67
98
|
raise RuntimeError(f'文鳐模板不存在: {template}')
|
|
68
|
-
r3 = wr.p3_fill(str(fx), str(ctx.get('nameEn') or rec['品名']), '', None,
|
|
99
|
+
r3 = wr.p3_fill(str(fx), str(ctx.get('nameEn') or rec['品名']), '', image_path or None,
|
|
69
100
|
material_en=str(ctx.get('materialEn') or ''), write_dict=False)
|
|
70
101
|
wr.p4_verify(r3['xlsx'], str(template))
|
|
71
102
|
out = {'ok': True, 'invoicePath': r3['xlsx'], 'bulkLabelPath': '', 'orderNo': shipment}
|
|
@@ -124,6 +155,15 @@ def main() -> int:
|
|
|
124
155
|
wb = openpyxl.load_workbook(tpl)
|
|
125
156
|
out_dir = DATA / 'invoice-output'
|
|
126
157
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
# 产品图(2026-11-03):模板 R 列必填;ERP 给短期签名 URL,下载后由 generate_invoice 嵌入
|
|
159
|
+
img_url = str(ctx.get('productImageUrl') or '')
|
|
160
|
+
if img_url:
|
|
161
|
+
try:
|
|
162
|
+
dest = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{rec['货件号']}.png"
|
|
163
|
+
sku['产品图本地'] = _download_product_image(img_url, dest)
|
|
164
|
+
print('产品图已下载:', sku['产品图本地'], flush=True)
|
|
165
|
+
except Exception as e:
|
|
166
|
+
print('产品图下载失败:', e, flush=True)
|
|
127
167
|
invoice = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{rec['货件号']}.xlsx"
|
|
128
168
|
generate_invoice(rec, mapping, wb, invoice)
|
|
129
169
|
out = {'ok': True, 'invoicePath': str(invoice), 'bulkLabelPath': '', 'orderNo': rec['货件号']}
|