@whyshu/argent-engine 0.8.0-rc.13 → 0.8.0-rc.15
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 +71 -36
- package/engine/VERSION +1 -1
- package/engine/configs/mcp-tools.snapshot.json +8 -1
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/core/mcp/erp-server.mjs +10 -6
- package/engine/core/mcp/gateway.mjs +3 -3
- package/engine/core/mcp/server.mjs +245 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1329 -284
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-version-consistency.mjs +14 -1
- 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 +1 -1
- package/engine/scripts/daily-report.mjs +22 -0
- package/engine/scripts/engine-manifest.mjs +90 -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 +3 -1
- 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/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +40 -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/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 +24 -3
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- 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/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -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 +1 -1
|
@@ -229,8 +229,68 @@ def running_windows(port: int, timeout: float = 30.0) -> list[dict[str, Any]]:
|
|
|
229
229
|
return resp.get("browsers") or []
|
|
230
230
|
|
|
231
231
|
|
|
232
|
+
_STORES_CACHE: dict[str, Any] = {"at": 0.0, "map": {}}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _stores_json_paths() -> list[str]:
|
|
236
|
+
"""stores.json 候选路径:env 指定 → ARGENT_DATA_DIR → 常见数据目录。"""
|
|
237
|
+
import os
|
|
238
|
+
out: list[str] = []
|
|
239
|
+
raw = str(os.environ.get("STORES_JSON") or "").strip()
|
|
240
|
+
if raw:
|
|
241
|
+
out.append(os.path.expanduser(raw))
|
|
242
|
+
for base in (os.environ.get("ARGENT_DATA_DIR") or "", os.path.expanduser("~/.dsh/argent"),
|
|
243
|
+
os.path.expanduser("~/.dsh-argent/argent")):
|
|
244
|
+
if base:
|
|
245
|
+
out.append(os.path.join(base, "stores.json"))
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _store_id_of_window(b: dict[str, Any]) -> str:
|
|
250
|
+
"""窗口条目 → 紫鸟 storeId:userData 里的 `chrome_<storeId>` 优先(实测可靠)。"""
|
|
251
|
+
ud = str(b.get("userData") or "").replace("\\", "/")
|
|
252
|
+
for token in ud.split("/"):
|
|
253
|
+
if token.startswith("chrome_"):
|
|
254
|
+
return token[len("chrome_"):].strip()
|
|
255
|
+
bid = str(b.get("browserId") or "").strip()
|
|
256
|
+
return bid
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _store_name_by_id(store_id: str) -> str:
|
|
260
|
+
"""storeId → stores.json 里的店铺名(10 分钟缓存;读不到就空串)。"""
|
|
261
|
+
sid = str(store_id or "").strip()
|
|
262
|
+
if not sid:
|
|
263
|
+
return ""
|
|
264
|
+
import json, os, time
|
|
265
|
+
now = time.time()
|
|
266
|
+
if now - float(_STORES_CACHE.get("at") or 0) > 600:
|
|
267
|
+
mapping: dict[str, str] = {}
|
|
268
|
+
for path in _stores_json_paths():
|
|
269
|
+
try:
|
|
270
|
+
data = json.load(open(path, "r", encoding="utf-8")) or {}
|
|
271
|
+
for name, info in data.items():
|
|
272
|
+
if isinstance(info, dict) and info.get("store_id"):
|
|
273
|
+
mapping[str(info["store_id"])] = str(name)
|
|
274
|
+
if mapping:
|
|
275
|
+
break
|
|
276
|
+
except Exception:
|
|
277
|
+
continue
|
|
278
|
+
_STORES_CACHE["map"] = mapping
|
|
279
|
+
_STORES_CACHE["at"] = now
|
|
280
|
+
return str((_STORES_CACHE.get("map") or {}).get(sid) or "")
|
|
281
|
+
|
|
282
|
+
|
|
232
283
|
def window_item_name(b: dict[str, Any]) -> str:
|
|
233
|
-
"""窗口条目 →
|
|
284
|
+
"""窗口条目 → 店名。
|
|
285
|
+
|
|
286
|
+
2026-11-18:优先用 userData 里的 storeId 去 stores.json 反查店铺名,
|
|
287
|
+
**不再优先用 downloadPath 末段**——实测紫鸟环境的下载目录会配错
|
|
288
|
+
(墨西哥-1店 的下载目录写成「巴西-2店」),日志窗口名一度被误读成"开错店"。
|
|
289
|
+
兜底顺序:storeId 反查 → downloadPath 末段 → userData 末段 → `?`。
|
|
290
|
+
"""
|
|
291
|
+
by_id = _store_name_by_id(_store_id_of_window(b))
|
|
292
|
+
if by_id:
|
|
293
|
+
return by_id
|
|
234
294
|
return (str(b.get("downloadPath") or "").rstrip("/").split("/")[-1]
|
|
235
295
|
or str(b.get("userData") or "").split("/")[-1] or "?")
|
|
236
296
|
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""产品线打包(单插件时代)
|
|
3
|
+
|
|
4
|
+
把一个产品线(`lines/<id>/`)打成**单个 .mjs 发布物** + 一份 manifest。
|
|
5
|
+
|
|
6
|
+
为什么是单文件:壳的安装流程是「下载 → sha256 校验 → 落盘 → import」,
|
|
7
|
+
多文件就要解包(tar/zip 依赖)与"半装"状态。单文件没有中间态,失败即整体回退。
|
|
8
|
+
|
|
9
|
+
用法:
|
|
10
|
+
python3 scripts/line_pack.py --line hr [--out-dir dist/lines] [--base-url https://whyshu.com/dl/lines]
|
|
11
|
+
python3 scripts/line_pack.py --line hr --json # 机器可读
|
|
12
|
+
python3 scripts/line_pack.py --line hr --check # 只校验:产物是否与源一致(CI/发布前)
|
|
13
|
+
python3 scripts/line_pack.py --list # 列出可打包的线
|
|
14
|
+
|
|
15
|
+
判据(红即退出非零):
|
|
16
|
+
L1 清单字段齐全、id 为 kebab-case、version 为语义化版本
|
|
17
|
+
L2 技能目录名 = frontmatter `name`(kebab),且有 `description`
|
|
18
|
+
L3 渲染后的 entry **不得** import 宿主包,且必须 export default mount
|
|
19
|
+
L4 产物的 sha256 必须写进 manifest(客户端据此三方校验)
|
|
20
|
+
|
|
21
|
+
退出码:0 正常;1 校验失败/产物漂移;2 用法或读取错误。
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import re
|
|
29
|
+
import sys
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
33
|
+
LINES = ROOT / "lines"
|
|
34
|
+
KEBAB = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
|
35
|
+
SEMVER = re.compile(r"^\d+\.\d+\.\d+(?:[-+][\w.]+)?$")
|
|
36
|
+
MARKER = "// __ARGENT_LINE_SKILLS__"
|
|
37
|
+
FORBIDDEN = ("@deepseek-ai/", "cordis")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def die(msg: str, code: int = 1):
|
|
41
|
+
print(f"✗ {msg}", file=sys.stderr)
|
|
42
|
+
sys.exit(code)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def parse_frontmatter(text: str) -> dict:
|
|
46
|
+
if not text.startswith("---"):
|
|
47
|
+
return {}
|
|
48
|
+
end = text.find("\n---", 3)
|
|
49
|
+
if end < 0:
|
|
50
|
+
return {}
|
|
51
|
+
out = {}
|
|
52
|
+
for line in text[3:end].splitlines():
|
|
53
|
+
if ":" in line:
|
|
54
|
+
k, v = line.split(":", 1)
|
|
55
|
+
out[k.strip()] = v.strip().strip('"').strip("'")
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_skill(path: Path) -> dict:
|
|
60
|
+
raw = path.read_text(encoding="utf-8")
|
|
61
|
+
fm = parse_frontmatter(raw)
|
|
62
|
+
name = fm.get("name", "")
|
|
63
|
+
desc = fm.get("description", "")
|
|
64
|
+
dirname = path.parent.name
|
|
65
|
+
if not KEBAB.match(name or ""):
|
|
66
|
+
die(f"[L2] {path}: name 必须是 kebab-case(当前 {name!r})")
|
|
67
|
+
if name != dirname:
|
|
68
|
+
die(f"[L2] {path}: name({name}) 必须等于目录名({dirname})")
|
|
69
|
+
if not desc:
|
|
70
|
+
die(f"[L2] {path}: 缺 description")
|
|
71
|
+
body = raw[raw.find("\n---", 3) + 4:].lstrip("\n") if fm else raw
|
|
72
|
+
# `source` 是 dsh 技能契约的**必填**字段(SkillSummary.source,字符串);
|
|
73
|
+
# 缺了会报 `loaded skill source must be a string`(2026-11-15 实测)。
|
|
74
|
+
# 运行时注册的技能统一记为 runtime,与 registry 的默认 provider 一致。
|
|
75
|
+
return {"name": name, "description": desc, "source": "runtime", "content": body}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build(line_id: str, out_dir: Path, base_url: str) -> dict:
|
|
79
|
+
ldir = LINES / line_id
|
|
80
|
+
man_path = ldir / "line.json"
|
|
81
|
+
if not man_path.is_file():
|
|
82
|
+
die(f"[L1] 找不到 {man_path}", 2)
|
|
83
|
+
man = json.loads(man_path.read_text(encoding="utf-8"))
|
|
84
|
+
|
|
85
|
+
for key in ("id", "title", "version", "requires", "entry"):
|
|
86
|
+
if not man.get(key):
|
|
87
|
+
die(f"[L1] 清单缺字段:{key}")
|
|
88
|
+
if man["id"] != line_id:
|
|
89
|
+
die(f"[L1] 清单 id({man['id']}) 与目录名({line_id}) 不一致")
|
|
90
|
+
if not KEBAB.match(man["id"]):
|
|
91
|
+
die(f"[L1] id 必须是 kebab-case:{man['id']}")
|
|
92
|
+
if not SEMVER.match(man["version"]):
|
|
93
|
+
die(f"[L1] version 不是语义化版本:{man['version']}")
|
|
94
|
+
|
|
95
|
+
skills = [read_skill(ldir / "skills" / s / "SKILL.md") for s in man.get("skills", [])]
|
|
96
|
+
entry_src = (ldir / man["entry"]).read_text(encoding="utf-8")
|
|
97
|
+
if MARKER not in entry_src:
|
|
98
|
+
die(f"[L3] {man['entry']} 缺少标记行 {MARKER}")
|
|
99
|
+
|
|
100
|
+
payload = json.dumps(skills, ensure_ascii=False, indent=2)
|
|
101
|
+
rendered = entry_src.replace(MARKER, f"SKILLS = {payload}")
|
|
102
|
+
|
|
103
|
+
for needle in FORBIDDEN:
|
|
104
|
+
if re.search(r"(from\s*|import\s*\(|require\s*\()\s*['\"]" + re.escape(needle), rendered):
|
|
105
|
+
die(f"[L3] 产物 import 了宿主包:{needle}")
|
|
106
|
+
if not re.search(r"export\s+default\s+(async\s+)?function", rendered):
|
|
107
|
+
die("[L3] 产物缺少 export default mount")
|
|
108
|
+
|
|
109
|
+
data = rendered.encode("utf-8")
|
|
110
|
+
sha = hashlib.sha256(data).hexdigest()
|
|
111
|
+
name = f"{man['id']}-{man['version']}.mjs"
|
|
112
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
(out_dir / name).write_bytes(data)
|
|
114
|
+
|
|
115
|
+
manifest = {
|
|
116
|
+
"id": man["id"],
|
|
117
|
+
"title": man["title"],
|
|
118
|
+
"version": man["version"],
|
|
119
|
+
"sha256": sha,
|
|
120
|
+
"sizeBytes": len(data),
|
|
121
|
+
"entryUrl": f"{base_url.rstrip('/')}/{name}",
|
|
122
|
+
"requires": man.get("requires", {}),
|
|
123
|
+
"requiresEngine": bool(man.get("requiresEngine", False)),
|
|
124
|
+
"minPlan": man.get("minPlan", ""),
|
|
125
|
+
"contributes": {"skills": [s["name"] for s in skills]},
|
|
126
|
+
}
|
|
127
|
+
(out_dir / f"{man['id']}-{man['version']}.json").write_text(
|
|
128
|
+
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
129
|
+
return manifest
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def main() -> None:
|
|
133
|
+
ap = argparse.ArgumentParser(add_help=True)
|
|
134
|
+
ap.add_argument("--line")
|
|
135
|
+
ap.add_argument("--out-dir", default=str(ROOT / "dist" / "lines"))
|
|
136
|
+
ap.add_argument("--base-url", default="https://whyshu.com/dl/lines")
|
|
137
|
+
ap.add_argument("--json", action="store_true")
|
|
138
|
+
ap.add_argument("--check", action="store_true")
|
|
139
|
+
ap.add_argument("--emit-server-manifest", dest="emit", default="")
|
|
140
|
+
ap.add_argument("--list", action="store_true")
|
|
141
|
+
a = ap.parse_args()
|
|
142
|
+
|
|
143
|
+
if a.list:
|
|
144
|
+
ids = sorted(p.parent.name for p in LINES.glob("*/line.json"))
|
|
145
|
+
print(json.dumps(ids, ensure_ascii=False) if a.json else "\n".join(ids))
|
|
146
|
+
return
|
|
147
|
+
if not a.line:
|
|
148
|
+
ap.print_help()
|
|
149
|
+
sys.exit(2)
|
|
150
|
+
|
|
151
|
+
out_dir = Path(a.out_dir)
|
|
152
|
+
before = {}
|
|
153
|
+
for f in out_dir.glob(f"{a.line}-*.mjs"):
|
|
154
|
+
before[f.name] = hashlib.sha256(f.read_bytes()).hexdigest()
|
|
155
|
+
|
|
156
|
+
man = build(a.line, out_dir, a.base_url)
|
|
157
|
+
|
|
158
|
+
if a.check:
|
|
159
|
+
name = f"{a.line}-{man['version']}.mjs"
|
|
160
|
+
drift = before.get(name) != man["sha256"]
|
|
161
|
+
status = "drift" if drift else "ok"
|
|
162
|
+
print(json.dumps({"line": a.line, "version": man["version"], "sha256": man["sha256"],
|
|
163
|
+
"status": status}, ensure_ascii=False) if a.json
|
|
164
|
+
else (f"✗ 产物与源不一致({name}):需要重新打包" if drift
|
|
165
|
+
else f"✓ {a.line}@{man['version']} 产物与源一致"))
|
|
166
|
+
sys.exit(1 if drift else 0)
|
|
167
|
+
|
|
168
|
+
if a.emit:
|
|
169
|
+
target = Path(a.emit)
|
|
170
|
+
doc = {"lines": []}
|
|
171
|
+
if target.is_file():
|
|
172
|
+
try:
|
|
173
|
+
doc = json.loads(target.read_text(encoding="utf-8"))
|
|
174
|
+
except Exception:
|
|
175
|
+
die(f"现有清单读不出来:{target}", 2)
|
|
176
|
+
lines = [l for l in doc.get("lines", []) if l.get("id") != man["id"]]
|
|
177
|
+
lines.append(man)
|
|
178
|
+
lines.sort(key=lambda l: str(l.get("id")))
|
|
179
|
+
doc["lines"] = lines
|
|
180
|
+
doc.setdefault("_note", "产品线清单(0.10.0 P3):由 argent-dsh `scripts/line_pack.py --emit-server-manifest` 生成,勿手改。")
|
|
181
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
target.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
183
|
+
print(f"✓ 已写入服务端清单:{target}({len(lines)} 条)")
|
|
184
|
+
|
|
185
|
+
if a.json:
|
|
186
|
+
print(json.dumps(man, ensure_ascii=False, indent=2))
|
|
187
|
+
else:
|
|
188
|
+
print(f"✓ 打包 {man['id']}@{man['version']}")
|
|
189
|
+
print(f" sha256 : {man['sha256']}")
|
|
190
|
+
print(f" 体积 : {man['sizeBytes']} 字节")
|
|
191
|
+
print(f" 技能 : {', '.join(man['contributes']['skills'])}")
|
|
192
|
+
print(f" 产物 : {out_dir / (a.line + '-' + man['version'] + '.mjs')}")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
if __name__ == "__main__":
|
|
196
|
+
main()
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ml-ads-advice.mjs —— Mercado Ads **只读诊断建议单**(P2a,2026-11-25)
|
|
4
|
+
*
|
|
5
|
+
* 与 `ml-ads.mjs` 的区别:那个只报"数字+告警";这里给**可执行建议**(哪条规则、改什么、先改哪个、
|
|
6
|
+
* 估算能省多少),阈值按毛利结构算(缺少毛利数据时用平台默认并标注)。
|
|
7
|
+
*
|
|
8
|
+
* 用法:
|
|
9
|
+
* node scripts/ml-ads-advice.mjs # 全部已授权店铺 · 近 7 天
|
|
10
|
+
* node scripts/ml-ads-advice.mjs --store 1店 # 店铺过滤
|
|
11
|
+
* node scripts/ml-ads-advice.mjs --days 30 --margin 0.35 --commission 0.15 --shipping 0.10
|
|
12
|
+
* node scripts/ml-ads-advice.mjs --json / --lines
|
|
13
|
+
*
|
|
14
|
+
* ⛔ 只读:只发 GET;只出建议,不改预算/暂停/调价(人工执行)。
|
|
15
|
+
*/
|
|
16
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, chmodSync } from 'node:fs'
|
|
17
|
+
import { join, dirname } from 'node:path'
|
|
18
|
+
import { resolveDataDir } from './lib/argent-datadir.mjs'
|
|
19
|
+
import {
|
|
20
|
+
loadEnvFile, refreshStoreToken, apiGet as coreApiGet,
|
|
21
|
+
SITE_CURRENCY, fallbackSite, startOfLocalDayUTC, localDateStr, matchStores,
|
|
22
|
+
} from './lib/daily-report-core.mjs'
|
|
23
|
+
import { fetchAdsReport } from './lib/ml-ads-core.mjs'
|
|
24
|
+
import { diagnoseAds, adsAdviceLines, buildAdsBridgePayload, ADS_RULE_DEFAULTS } from './lib/ml-ads-rules.mjs'
|
|
25
|
+
import { resolveBridgeAuth, readAgentReport, assertBridgeAuth } from './lib/ml-bridge-auth.mjs'
|
|
26
|
+
|
|
27
|
+
const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
|
|
28
|
+
// 引擎侧 `apiGet` 不硬编码域名(vertical 门禁)⇒ CLI 必须把基址注入进程环境,
|
|
29
|
+
// 否则 `refreshStoreToken` 这条内部路径会报「缺少 API 基址」(2026-11-25 实测)。
|
|
30
|
+
if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
|
|
31
|
+
const args = process.argv.slice(2)
|
|
32
|
+
const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
|
|
33
|
+
const has = (n) => args.includes(n)
|
|
34
|
+
if (has('-h') || has('--help')) {
|
|
35
|
+
console.log(`Mercado Ads 诊断建议(只读)
|
|
36
|
+
|
|
37
|
+
用法: node scripts/ml-ads-advice.mjs [选项]
|
|
38
|
+
--store <名或uid> 店铺过滤(名称子串 / uid 全等)
|
|
39
|
+
--days <n> 回溯天数,默认 7(MELI 上限 90)
|
|
40
|
+
--target-acos <n> 目标 ACoS%(未给毛利数据时用),默认 ${ADS_RULE_DEFAULTS.targetAcos}
|
|
41
|
+
--margin <0-1> 毛利率(给了就按 毛利−佣金−物流 算可承受 ACoS)
|
|
42
|
+
--commission <0-1> 平台佣金率,默认 ${ADS_RULE_DEFAULTS.commissionRate}
|
|
43
|
+
--shipping <0-1> 物流成本率,默认 ${ADS_RULE_DEFAULTS.shippingRate}
|
|
44
|
+
--min-spend <n> 账户级显著花费门槛,默认 ${ADS_RULE_DEFAULTS.minSpend}
|
|
45
|
+
--json 结构化 JSON(stdout)
|
|
46
|
+
--push 建议单推到 ERP「智能分析 → 广告诊断」(机器令牌;先 --dry-run 核对)
|
|
47
|
+
--dry-run 配 --push 时只打印 payload
|
|
48
|
+
--lines 中文建议单(给角色/日报复用)
|
|
49
|
+
--env <path> daily-report.env 路径
|
|
50
|
+
退出码: 0 正常 | 1 用法/取数失败 | 2 全部店铺失败`)
|
|
51
|
+
process.exit(0)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const DATA_DIR = resolveDataDir({ env: process.env }).dir
|
|
55
|
+
const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
|
|
56
|
+
const STORES_PATH = process.env.ML_API_STORES_JSON || join(DATA_DIR, 'ml-api-stores.json')
|
|
57
|
+
const env = loadEnvFile(ENV_PATH)
|
|
58
|
+
const doc = existsSync(STORES_PATH) ? JSON.parse(readFileSync(STORES_PATH, 'utf8')) : { stores: [] }
|
|
59
|
+
const stores = doc.stores || []
|
|
60
|
+
const envGet = (k) => (env && env[k]) || ''
|
|
61
|
+
const persistStores = () => {
|
|
62
|
+
try {
|
|
63
|
+
mkdirSync(dirname(STORES_PATH), { recursive: true })
|
|
64
|
+
const tmp = `${STORES_PATH}.tmp`
|
|
65
|
+
writeFileSync(tmp, JSON.stringify({ stores }, null, 2) + '\n', { mode: 0o600 })
|
|
66
|
+
renameSync(tmp, STORES_PATH); chmodSync(STORES_PATH, 0o600)
|
|
67
|
+
} catch (e) { console.error(`✗ token 写回失败:${e.message}`) }
|
|
68
|
+
}
|
|
69
|
+
const apiGet = (path, token) => coreApiGet(path, token, { base: API_BASE() })
|
|
70
|
+
|
|
71
|
+
const numArg = (v) => { if (v === undefined || v === null || String(v).trim() === '') return null; const n = Number(v); return Number.isFinite(n) ? n : null }
|
|
72
|
+
const cfg = {
|
|
73
|
+
targetAcos: numArg(argVal('--target-acos') ?? envGet('ML_ADS_TARGET_ACOS')) ?? ADS_RULE_DEFAULTS.targetAcos,
|
|
74
|
+
marginRate: numArg(argVal('--margin') ?? envGet('ML_ADS_MARGIN_RATE')),
|
|
75
|
+
commissionRate: numArg(argVal('--commission') ?? envGet('ML_ADS_COMMISSION_RATE')) ?? ADS_RULE_DEFAULTS.commissionRate,
|
|
76
|
+
shippingRate: numArg(argVal('--shipping') ?? envGet('ML_ADS_SHIPPING_RATE')) ?? ADS_RULE_DEFAULTS.shippingRate,
|
|
77
|
+
minSpend: numArg(argVal('--min-spend')) ?? ADS_RULE_DEFAULTS.minSpend,
|
|
78
|
+
}
|
|
79
|
+
const days = Math.max(1, Math.min(90, Number(argVal('--days') || 7)))
|
|
80
|
+
const queries = (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean)
|
|
81
|
+
const picked = matchStores(stores, queries)
|
|
82
|
+
if (!picked.length) { console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`); process.exit(1) }
|
|
83
|
+
|
|
84
|
+
const results = []
|
|
85
|
+
for (const store of picked) {
|
|
86
|
+
const site = fallbackSite(store.site)
|
|
87
|
+
const row = { store: store.name, site, currency: SITE_CURRENCY[site] || '' }
|
|
88
|
+
try {
|
|
89
|
+
const token = await refreshStoreToken(env, store, { onRotate: persistStores })
|
|
90
|
+
const todayStart = startOfLocalDayUTC('America/Mexico_City', new Date()) // 站点窗口在 fetch 内按站点算;这里仅取"昨天"日期字符串
|
|
91
|
+
void todayStart
|
|
92
|
+
const dateTo = localDateStr(site === 'MLB' ? 'America/Sao_Paulo' : site === 'MLA' ? 'America/Argentina/Buenos_Aires' : 'America/Mexico_City', new Date(Date.now() - 86400000))
|
|
93
|
+
const dateFrom = localDateStr(site === 'MLB' ? 'America/Sao_Paulo' : site === 'MLA' ? 'America/Argentina/Buenos_Aires' : 'America/Mexico_City', new Date(Date.now() - days * 86400000))
|
|
94
|
+
const report = await fetchAdsReport({ apiGet, token, site, dateFrom, dateTo })
|
|
95
|
+
row.diagnosis = diagnoseAds(report, cfg)
|
|
96
|
+
row.window = { from: dateFrom, to: dateTo }
|
|
97
|
+
results.push(row)
|
|
98
|
+
} catch (e) {
|
|
99
|
+
row.error = String((e && e.message) || e)
|
|
100
|
+
results.push(row)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── A(2026-12-01):建议单推 ERP「智能分析 → 广告诊断」(只读建议;⛔ 不改任何广告设置)──
|
|
105
|
+
if (has('--push')) {
|
|
106
|
+
const auth = resolveBridgeAuth({ env: process.env, agentReport: readAgentReport({ file: join(DATA_DIR, 'agent-report.json') }) })
|
|
107
|
+
assertBridgeAuth(auth)
|
|
108
|
+
let fail = 0
|
|
109
|
+
for (const r of results.filter((x) => !x.error)) {
|
|
110
|
+
const payload = buildAdsBridgePayload(r.diagnosis, { store: r.store, site: r.site, currency: r.currency, days })
|
|
111
|
+
if (has('--dry-run')) { console.log(JSON.stringify({ dryRun: true, authMode: auth.mode, payload }, null, 2)); continue }
|
|
112
|
+
const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/reports/ads/bridge`
|
|
113
|
+
const headers = { 'content-type': 'application/json', ...(auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : {}), ...(auth.secret ? { 'x-appointment-secret': auth.secret } : {}) }
|
|
114
|
+
const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(20000) }).catch((e) => ({ ok: false, status: 0, json: async () => ({ message: String(e.message) }) }))
|
|
115
|
+
const body = await res.json().catch(() => ({}))
|
|
116
|
+
if (res.ok) console.error(`✓ ${r.store} 建议单已推 ERP(${payload.items.length} 条)`)
|
|
117
|
+
else { fail++; console.error(`✗ ${r.store} 推送失败:HTTP ${res.status} ${JSON.stringify(body).slice(0, 160)}`) }
|
|
118
|
+
}
|
|
119
|
+
if (fail) process.exit(2)
|
|
120
|
+
}
|
|
121
|
+
const okRows = results.filter((r) => !r.error)
|
|
122
|
+
if (!okRows.length) {
|
|
123
|
+
if (has('--json')) console.log(JSON.stringify({ results }, null, 2))
|
|
124
|
+
else for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
|
|
125
|
+
process.exit(2)
|
|
126
|
+
}
|
|
127
|
+
if (has('--json')) {
|
|
128
|
+
console.log(JSON.stringify({ generatedAt: new Date().toISOString(), config: cfg, results }, null, 2))
|
|
129
|
+
process.exit(0)
|
|
130
|
+
}
|
|
131
|
+
if (has('--lines')) {
|
|
132
|
+
for (const r of okRows) { console.log(`### ${r.store}(${r.window.from}~${r.window.to})`); console.log(adsAdviceLines(r.diagnosis, { currency: r.currency }).join('\n')) }
|
|
133
|
+
process.exit(0)
|
|
134
|
+
}
|
|
135
|
+
let text = `## 📣 广告诊断建议(近 ${days} 天)\n\n`
|
|
136
|
+
for (const r of results) {
|
|
137
|
+
if (r.error) { text += `### ${r.store}\n✗ ${r.error}\n\n`; continue }
|
|
138
|
+
text += `### ${r.store}(${r.window.from}~${r.window.to})\n` + adsAdviceLines(r.diagnosis, { currency: r.currency }).join('\n') + '\n\n'
|
|
139
|
+
}
|
|
140
|
+
console.log(text)
|
|
@@ -34,9 +34,13 @@ import {
|
|
|
34
34
|
} from './lib/daily-report-core.mjs'
|
|
35
35
|
import {
|
|
36
36
|
fetchAdsReport, classifyAdsAlerts, adsCardLines, fmtMoney, ADS_ALERT_DEFAULTS,
|
|
37
|
+
ADS_METRICS_OFFICIAL, ADS_METRICS_LEGACY,
|
|
37
38
|
} from './lib/ml-ads-core.mjs'
|
|
38
39
|
|
|
39
40
|
const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
|
|
41
|
+
// 引擎侧 `apiGet` 不硬编码域名(vertical 门禁)⇒ CLI 必须把基址注入进程环境,
|
|
42
|
+
// 否则 `refreshStoreToken` 这条内部路径会报「缺少 API 基址」(2026-11-25 实测)。
|
|
43
|
+
if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
|
|
40
44
|
|
|
41
45
|
const args = process.argv.slice(2)
|
|
42
46
|
const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
|
|
@@ -51,6 +55,7 @@ if (has('-h') || has('--help')) {
|
|
|
51
55
|
--to <YYYY-MM-DD> 结束日(站点本地),默认「昨天」
|
|
52
56
|
--detail 附活动级下钻(花钱最多 + ACoS 超标)
|
|
53
57
|
--list 只列出每店广告主(1 请求/店)
|
|
58
|
+
--probe-metrics 实测指标名:分别用「官方现行名」和「旧名」各拉 1 条,报告谁被接受(只读)
|
|
54
59
|
--json 结构化 JSON(stdout)
|
|
55
60
|
--lines 中文卡片行(给日报分区/角色回复复用)
|
|
56
61
|
--acos-warn <n> ACoS 黄色阈值,默认 ${ADS_ALERT_DEFAULTS.acosWarn}
|
|
@@ -90,6 +95,7 @@ const FLAG_JSON = has('--json')
|
|
|
90
95
|
const FLAG_LINES = has('--lines')
|
|
91
96
|
const FLAG_DETAIL = has('--detail')
|
|
92
97
|
const FLAG_LIST = has('--list')
|
|
98
|
+
const FLAG_PROBE = has('--probe-metrics') // 客户机实测:官方现行 metrics 名 vs 旧名,谁被接受
|
|
93
99
|
const days = Math.max(1, Math.min(90, Number(argVal('--days') || 7)))
|
|
94
100
|
const toArg = argVal('--to')
|
|
95
101
|
|
|
@@ -112,6 +118,27 @@ for (const store of picked) {
|
|
|
112
118
|
const row = { store: store.name, site, uid: store.user_id, currency: SITE_CURRENCY[site] || '', dateFrom, dateTo }
|
|
113
119
|
try {
|
|
114
120
|
const token = await refreshStoreToken(env, store, { onRotate: persistStores })
|
|
121
|
+
if (FLAG_PROBE) {
|
|
122
|
+
const adv = await apiGet('/advertising/advertisers?product_id=PADS', token)
|
|
123
|
+
const a0 = (adv.advertisers || [])[0]
|
|
124
|
+
if (!a0) { row.probe = { error: 'no_advertiser' }; results.push(row); continue }
|
|
125
|
+
const advSite = a0.site_id || site
|
|
126
|
+
const probe = {}
|
|
127
|
+
for (const [name, list] of [['official', ADS_METRICS_OFFICIAL], ['legacy', ADS_METRICS_LEGACY]]) {
|
|
128
|
+
const metrics = list.join(',')
|
|
129
|
+
try {
|
|
130
|
+
const q = new URLSearchParams({ limit: '1', offset: '0', date_from: dateFrom, date_to: dateTo, metrics })
|
|
131
|
+
const r = await apiGet(`/advertising/${advSite}/advertisers/${a0.advertiser_id}/product_ads/campaigns/search?${q}`, token)
|
|
132
|
+
const first = ((r && r.results) || [])[0] || {}
|
|
133
|
+
probe[name] = { ok: true, metrics, sampleKeys: Object.keys(first.metrics || {}).slice(0, 24) }
|
|
134
|
+
} catch (e) {
|
|
135
|
+
probe[name] = { ok: false, metrics, error: String(e.message || e).slice(0, 200) }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
row.probe = probe
|
|
139
|
+
results.push(row)
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
115
142
|
if (FLAG_LIST) {
|
|
116
143
|
const adv = await apiGet('/advertising/advertisers?product_id=PADS', token)
|
|
117
144
|
row.advertisers = (adv.advertisers || []).map((a) => ({ advertiser_id: a.advertiser_id, site: a.site_id, name: a.advertiser_name }))
|
|
@@ -135,6 +162,19 @@ if (!ok.length) {
|
|
|
135
162
|
else for (const r of results) console.error(`✗ ${r.store}:${r.error}`)
|
|
136
163
|
process.exit(2)
|
|
137
164
|
}
|
|
165
|
+
if (FLAG_PROBE) {
|
|
166
|
+
if (FLAG_JSON) { console.log(JSON.stringify({ generatedAt: now.toISOString(), results }, null, 2)); process.exit(0) }
|
|
167
|
+
for (const r of results) {
|
|
168
|
+
if (r.error) { console.log(`${r.store}: ✗ ${r.error}`); continue }
|
|
169
|
+
console.log(`### ${r.store}(${r.site})`)
|
|
170
|
+
for (const [k, p] of Object.entries(r.probe || {})) {
|
|
171
|
+
console.log(`- ${k}:${p.ok ? '✅ 被接受' : '❌ ' + p.error}`)
|
|
172
|
+
if (p.ok && p.sampleKeys && p.sampleKeys.length) console.log(` metrics 返回字段:${p.sampleKeys.join(', ')}`)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
process.exit(0)
|
|
176
|
+
}
|
|
177
|
+
|
|
138
178
|
if (FLAG_JSON) { console.log(JSON.stringify({ generatedAt: now.toISOString(), days, results }, null, 2)); process.exit(0) }
|
|
139
179
|
|
|
140
180
|
if (FLAG_LINES) {
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ml-category-baseline.mjs —— 类目基线 / 行业简版 / 选品候选 / 热词雷达(C,只读)。
|
|
4
|
+
*
|
|
5
|
+
* 数据来源(**官方允许的只读端点**;2026-12-01 实测 `/sites/{site}/search` 对第三方不可用、`/items?ids=` 对部分 app 已弃用):
|
|
6
|
+
* · 自有商品:/users/{uid}/items/search(列 id)→ /items/{id}(单条详情,含 category_id/price/sold)
|
|
7
|
+
* · 竞品样本:ERP 竞品清单(机器令牌读 /market/competitor-items)→ /items/{id} 单条
|
|
8
|
+
* · 热词:/trends/{site}(L1:只有词,无搜索量)
|
|
9
|
+
* 口径:**基于客户指定竞品样本**(L2 窄版),不是全类目;已售=平台分桶参考值(估算,不是真实销量)。
|
|
10
|
+
* ⛔ 不抓页面、不推断真实销量、不写客户平台。
|
|
11
|
+
*/
|
|
12
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { resolveDataDir } from './lib/argent-datadir.mjs'
|
|
15
|
+
import { loadEnvFile, refreshStoreToken, apiGet as coreApiGet, SITE_CURRENCY, fallbackSite, matchStores } from './lib/daily-report-core.mjs'
|
|
16
|
+
import { bucketOfQuantity } from './lib/ml-market-core.mjs'
|
|
17
|
+
import { categoryBaseline, categoryBaselineLines, industryFromResults, selectionCandidates, industryLines } from './lib/ml-category-core.mjs'
|
|
18
|
+
import { resolveBridgeAuth, readAgentReport, assertBridgeAuth } from './lib/ml-bridge-auth.mjs'
|
|
19
|
+
|
|
20
|
+
const API_BASE = () => process.env.ML_API_BASE || 'https://api.mercadolibre.com'
|
|
21
|
+
if (!process.env.ML_API_BASE) process.env.ML_API_BASE = API_BASE()
|
|
22
|
+
const args = process.argv.slice(2)
|
|
23
|
+
const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
|
|
24
|
+
const has = (n) => args.includes(n)
|
|
25
|
+
if (has('-h') || has('--help')) {
|
|
26
|
+
console.log(`类目基线 / 行业简版 / 选品候选 / 热词雷达(只读;L2 窄版口径)
|
|
27
|
+
|
|
28
|
+
用法: node scripts/ml-category-baseline.mjs [选项]
|
|
29
|
+
--store <名或uid> 店铺(默认全部授权店)
|
|
30
|
+
--comps <n> 每店竞品样本上限(默认 30,上限 60;来源=ERP 竞品清单)
|
|
31
|
+
--json / --lines 输出格式
|
|
32
|
+
--push / --dry-run 推 ERP「智能分析 → 类目基线」(机器令牌)
|
|
33
|
+
退出码: 0 正常 | 1 用法/无数据 | 2 推送失败`)
|
|
34
|
+
process.exit(0)
|
|
35
|
+
}
|
|
36
|
+
const DATA_DIR = resolveDataDir({ env: process.env }).dir
|
|
37
|
+
const ENV_PATH = argVal('--env') || join(DATA_DIR, 'daily-report.env')
|
|
38
|
+
if (!existsSync(ENV_PATH)) { console.error(`✗ 未找到 env:${ENV_PATH}`); process.exit(1) }
|
|
39
|
+
const env = loadEnvFile(ENV_PATH)
|
|
40
|
+
const STORES_PATH = join(DATA_DIR, 'ml-api-stores.json')
|
|
41
|
+
const stores = existsSync(STORES_PATH) ? (JSON.parse(readFileSync(STORES_PATH, 'utf8')).stores || []) : []
|
|
42
|
+
const compLimit = Math.max(1, Math.min(60, Number(argVal('--comps') || 30)))
|
|
43
|
+
const queries = (argVal('--store') || '').split(',').map((x) => x.trim()).filter(Boolean)
|
|
44
|
+
const picked = matchStores(stores, queries)
|
|
45
|
+
if (!picked.length) { console.error(`✗ 没有匹配到店铺(已授权 ${stores.length} 家)`); process.exit(1) }
|
|
46
|
+
|
|
47
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
48
|
+
const safeGet = async (path, token, tries = 2) => {
|
|
49
|
+
for (let i = 0; i < tries; i++) {
|
|
50
|
+
try { return await coreApiGet(path, token) } catch (e) {
|
|
51
|
+
const msg = String((e && e.message) || e)
|
|
52
|
+
if (/HTTP 40[34]/.test(msg)) throw e
|
|
53
|
+
if (i === tries - 1) throw e
|
|
54
|
+
await sleep(1200)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const itemInfo = async (id, token) => {
|
|
59
|
+
const r = await safeGet(`/items/${encodeURIComponent(id)}`, token)
|
|
60
|
+
return {
|
|
61
|
+
itemId: String(r.id || id), title: String(r.title || ''), price: r.price,
|
|
62
|
+
categoryId: String(r.category_id || ''),
|
|
63
|
+
sellerId: r.seller_id ? String(r.seller_id) : '',
|
|
64
|
+
sold: r.sold_quantity ?? null,
|
|
65
|
+
rating: null,
|
|
66
|
+
permalink: String(r.permalink || ''),
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 读 ERP 竞品清单(机器令牌;失败 ⇒ 空数组,不影响自有类目基线)。 */
|
|
71
|
+
async function fetchErpCompetitors(auth) {
|
|
72
|
+
try {
|
|
73
|
+
const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/market/competitor-items`
|
|
74
|
+
const headers = auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : { 'x-appointment-secret': auth.secret }
|
|
75
|
+
const res = await fetch(url, { headers, signal: AbortSignal.timeout(15000) })
|
|
76
|
+
const body = await res.json().catch(() => ({}))
|
|
77
|
+
const items = body && body.data && Array.isArray(body.data.items) ? body.data.items : []
|
|
78
|
+
return items.map((x) => String(x)).filter((x) => /^[A-Za-z0-9]{4,40}$/.test(x))
|
|
79
|
+
} catch { return [] }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const auth = has('--push') ? resolveBridgeAuth({ env: process.env, agentReport: readAgentReport({ file: join(DATA_DIR, 'agent-report.json') }) }) : null
|
|
83
|
+
if (has('--push')) assertBridgeAuth(auth)
|
|
84
|
+
const erpComps = auth ? await fetchErpCompetitors(auth) : []
|
|
85
|
+
if (auth && !erpComps.length) console.error('⚠ ERP 竞品清单为空 ⇒ 行业/选品仅基于自有商品(去 ERP「智能分析 → 竞品设置」维护)')
|
|
86
|
+
|
|
87
|
+
const results = []
|
|
88
|
+
for (const store of picked) {
|
|
89
|
+
const site = fallbackSite(store.site)
|
|
90
|
+
const row = { store: store.name, site, currency: SITE_CURRENCY[site] || '', categories: [], trends: [] }
|
|
91
|
+
try {
|
|
92
|
+
const token = await refreshStoreToken(env, store, { onRotate: () => {} })
|
|
93
|
+
// 热词雷达(L1:只有词,无搜索量)
|
|
94
|
+
try {
|
|
95
|
+
const tr = await safeGet(`/trends/${site}`, token)
|
|
96
|
+
row.trends = (Array.isArray(tr) ? tr : []).slice(0, 12).map((x) => String(x && (x.keyword || x) || '')).filter(Boolean)
|
|
97
|
+
} catch (e) { row.warn = '热词不可用:' + String((e && e.message) || e).slice(0, 80) }
|
|
98
|
+
// 自有商品:列 id(最多 20)→ 单条详情
|
|
99
|
+
const own = []
|
|
100
|
+
const list = await safeGet(`/users/${encodeURIComponent(store.user_id)}/items/search?status=active&limit=20`, token).catch(() => null)
|
|
101
|
+
for (const id of ((list && list.results) || []).slice(0, 20)) {
|
|
102
|
+
try { own.push({ ...(await itemInfo(id, token)), role: 'own' }); await sleep(120) } catch {}
|
|
103
|
+
}
|
|
104
|
+
// 竞品样本:ERP 清单(≤60)→ 单条详情
|
|
105
|
+
const comps = []
|
|
106
|
+
for (const id of erpComps.slice(0, compLimit)) {
|
|
107
|
+
try { comps.push({ ...(await itemInfo(id, token)), role: 'competitor' }); await sleep(120) } catch {}
|
|
108
|
+
}
|
|
109
|
+
const all = [...own, ...comps]
|
|
110
|
+
const byCat = new Map()
|
|
111
|
+
for (const it of all) {
|
|
112
|
+
const cat = it.categoryId || 'unknown'
|
|
113
|
+
if (!byCat.has(cat)) byCat.set(cat, [])
|
|
114
|
+
byCat.get(cat).push(it)
|
|
115
|
+
}
|
|
116
|
+
for (const [catId, items] of [...byCat.entries()].slice(0, 8)) {
|
|
117
|
+
const prices = items.map((x) => x.price).filter((p) => Number(p) > 0)
|
|
118
|
+
const ownItem = items.find((x) => x.role === 'own' && Number(x.price) > 0)
|
|
119
|
+
const rowsSample = items.map((x) => ({ itemId: x.itemId, title: x.title, price: x.price, rating: null, sold: x.sold, sellerId: x.sellerId, brand: '' }))
|
|
120
|
+
const base = categoryBaseline({ categoryId: catId, total: null, results: rowsSample }, { ourPrice: ownItem ? ownItem.price : null })
|
|
121
|
+
base.industry = industryFromResults(rowsSample)
|
|
122
|
+
base.candidates = selectionCandidates(rowsSample, { limit: 10 })
|
|
123
|
+
base.source = '客户指定竞品样本(ERP 竞品设置)'
|
|
124
|
+
base.note = '口径:客户指定竞品样本,不是全类目;在售总数不可得(官方搜索对本 app 不可用);已售=平台分桶参考值(估算)'
|
|
125
|
+
base.sample = true
|
|
126
|
+
results.length // noop
|
|
127
|
+
if (!prices.length) continue
|
|
128
|
+
row.categories.push(base)
|
|
129
|
+
}
|
|
130
|
+
if (!row.categories.length) row.error = '没有可统计的类目(自有/竞品商品都没有 category_id)'
|
|
131
|
+
results.push(row)
|
|
132
|
+
} catch (e) { row.error = String((e && e.message) || e); results.push(row) }
|
|
133
|
+
}
|
|
134
|
+
const okRows = results.filter((r) => !r.error && r.categories.length)
|
|
135
|
+
if (!okRows.length) { for (const r of results) console.error(`✗ ${r.store}:${r.error || '无类目数据'}`); process.exit(1) }
|
|
136
|
+
|
|
137
|
+
if (has('--push')) {
|
|
138
|
+
let fail = 0
|
|
139
|
+
for (const r of okRows) {
|
|
140
|
+
const payload = {
|
|
141
|
+
store: r.store, site: r.site, capturedAt: new Date().toISOString(), currency: r.currency,
|
|
142
|
+
categories: r.categories, trends: r.trends,
|
|
143
|
+
}
|
|
144
|
+
if (has('--dry-run')) { console.log(JSON.stringify({ dryRun: true, authMode: auth.mode, payload }, null, 2)); continue }
|
|
145
|
+
const url = `${auth.base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(auth.tenant)}/reports/category/bridge`
|
|
146
|
+
const headers = { 'content-type': 'application/json', ...(auth.machineToken ? { authorization: `Bearer ${auth.machineToken}` } : {}), ...(auth.secret ? { 'x-appointment-secret': auth.secret } : {}) }
|
|
147
|
+
const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(20000) }).catch((e) => ({ ok: false, status: 0, json: async () => ({ message: String(e.message) }) }))
|
|
148
|
+
const body = await res.json().catch(() => ({}))
|
|
149
|
+
if (res.ok) console.error(`✓ ${r.store} 类目基线已推 ERP(${payload.categories.length} 类目)`)
|
|
150
|
+
else { fail++; console.error(`✗ ${r.store} 推送失败:HTTP ${res.status} ${JSON.stringify(body).slice(0, 160)}`) }
|
|
151
|
+
}
|
|
152
|
+
if (fail) process.exit(2)
|
|
153
|
+
}
|
|
154
|
+
const CACHE = join(DATA_DIR, 'ml-category-cache', 'latest.json')
|
|
155
|
+
mkdirSync(join(DATA_DIR, 'ml-category-cache'), { recursive: true, mode: 0o700 })
|
|
156
|
+
const doc = { generatedAt: new Date().toISOString(), rows: okRows }
|
|
157
|
+
writeFileSync(CACHE + '.tmp', JSON.stringify(doc, null, 2), { mode: 0o600 })
|
|
158
|
+
renameSync(CACHE + '.tmp', CACHE)
|
|
159
|
+
if (has('--json')) { console.log(JSON.stringify(doc, null, 2)); process.exit(0) }
|
|
160
|
+
const lines = []
|
|
161
|
+
for (const r of okRows) {
|
|
162
|
+
lines.push(`### ${r.store}(${r.site})`)
|
|
163
|
+
if (r.trends.length) lines.push(`热词雷达(L1,无搜索量):${r.trends.slice(0, 10).join(' / ')}`)
|
|
164
|
+
for (const c of r.categories) {
|
|
165
|
+
lines.push(...categoryBaselineLines(c, { currency: r.currency }))
|
|
166
|
+
if (c.industry) lines.push(...industryLines(c.industry))
|
|
167
|
+
if (Array.isArray(c.candidates) && c.candidates.length) {
|
|
168
|
+
lines.push('选品候选(已售≈档位,估算):')
|
|
169
|
+
for (const x of c.candidates.slice(0, 5)) lines.push(` ${x.rank}. ${x.title || x.itemId} · ${r.currency} ${x.price} · 已售≈${x.soldRef ?? '—'}`)
|
|
170
|
+
}
|
|
171
|
+
lines.push(` ⚠ ${c.source};${c.note}`, '')
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
console.log(lines.join('\n'))
|