@whyshu/argent-engine 0.8.0-rc.9 → 0.13.28

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.
Files changed (106) hide show
  1. package/MANIFEST.json +102 -40
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * FULL 多标签执行 worker(Argent PR4,实验性)。
4
+ *
5
+ * 从 ERP FullExecutionTask 队列按店铺领取 N 个任务,使用引擎
6
+ * `orchestrator.py --record-jsons-file` 的父锁 + N 子进程并行执行;
7
+ * 完成后上传产物并回写队列结果。
8
+ *
9
+ * ⛔ 默认不启用;需要 env 配置。不是插件自动启动项。
10
+ *
11
+ * 必填 env:
12
+ * ARGENT_ERP_BASE=https://whyshu.com
13
+ * ARGENT_TENANT_APP_ID=ly-0001
14
+ * ARGENT_MACHINE_TOKEN=<machine token>
15
+ * ARGENT_ENGINE_DIR=/path/to/engine
16
+ * FULL_EXEC_STORES=墨西哥-2店-子账号[,店铺2...]
17
+ * 可选:
18
+ * FULL_EXEC_TABS=2
19
+ * FULL_EXEC_POLL_MS=5000
20
+ * ZINIAO_DOWNLOAD_ROOT=...
21
+ */
22
+ import { spawn } from 'node:child_process'
23
+ import { mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises'
24
+ import { existsSync } from 'node:fs'
25
+ import { tmpdir } from 'node:os'
26
+ import { basename, join } from 'node:path'
27
+ import { uploadFulfillmentFiles } from '../plugins/argent/src/fulfillment-result.mjs'
28
+
29
+ const BASE = String(process.env.ARGENT_ERP_BASE || 'https://whyshu.com').replace(/\/+$/, '')
30
+ const APP = String(process.env.ARGENT_TENANT_APP_ID || '').trim()
31
+ const TOKEN = String(process.env.ARGENT_MACHINE_TOKEN || '').trim()
32
+ const MACHINE = String(process.env.ARGENT_MACHINE_ID || '').trim()
33
+ const ENGINE = String(process.env.ARGENT_ENGINE_DIR || '').trim()
34
+ const STORES = String(process.env.FULL_EXEC_STORES || '').split(',').map((x) => x.trim()).filter(Boolean)
35
+ const TABS = Math.max(1, Math.min(5, Number(process.env.FULL_EXEC_TABS || 2) || 2))
36
+ const POLL_MS = Math.max(1000, Number(process.env.FULL_EXEC_POLL_MS || 5000) || 5000)
37
+ const DOWNLOAD_ROOT = String(process.env.ZINIAO_DOWNLOAD_ROOT || '')
38
+ || join(process.env.HOME || '', 'Library', 'Application Support', 'ziniaobrowserdatas', 'ziniao browser')
39
+
40
+ if (!APP || !TOKEN || !ENGINE || !STORES.length) {
41
+ console.error('缺少 ARGENT_TENANT_APP_ID / ARGENT_MACHINE_TOKEN / ARGENT_ENGINE_DIR / FULL_EXEC_STORES')
42
+ process.exit(2)
43
+ }
44
+ if (!MACHINE) console.warn('[worker] ARGENT_MACHINE_ID 未设置,将用 worker 作为 leaseOwner,可能导致 heartbeat 失败')
45
+
46
+ const api = async (method, path, body, timeoutMs = 30_000) => {
47
+ const res = await fetch(`${BASE}${path}`, {
48
+ method,
49
+ headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' },
50
+ body: body === undefined ? undefined : JSON.stringify(body),
51
+ signal: AbortSignal.timeout(timeoutMs),
52
+ })
53
+ const json = await res.json().catch(() => ({}))
54
+ if (!res.ok) throw new Error(json?.error?.message || `HTTP ${res.status}`)
55
+ return json?.data ?? json
56
+ }
57
+ const workerId = MACHINE || `full-exec-worker-${process.pid}`
58
+
59
+ async function preflightCheck() {
60
+ const problems = []
61
+ if (!existsSync(join(ENGINE, 'scripts', 'orchestrator.py'))) problems.push(`找不到引擎: ${join(ENGINE, 'scripts', 'orchestrator.py')}`)
62
+ if (!existsSync(DOWNLOAD_ROOT)) problems.push(`找不到紫鸟下载目录: ${DOWNLOAD_ROOT}`)
63
+ try {
64
+ const q = await api('GET', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/worker-snapshot`)
65
+ console.log(`[check] api=ok mode=${q.mode || '?'} capacity=${q.capacity || '?'}`)
66
+ if (String(q.mode || '') !== 'on') problems.push(`队列未开启: FULL_EXEC_QUEUE=${q.mode || '?'}`)
67
+ } catch (e) { problems.push(`ERP API 不可用: ${e.message}`) }
68
+ console.log(`[check] stores=${STORES.join(',')} tabs=${TABS} worker=${workerId}`)
69
+ if (problems.length) {
70
+ console.error('[check] 未通过:')
71
+ for (const p of problems) console.error(' - ' + p)
72
+ process.exit(1)
73
+ }
74
+ console.log('[check] 通过(只读检查,未 claim、未执行)')
75
+ process.exit(0)
76
+ }
77
+
78
+ async function walkFiles(dir, out = [], depth = 0) {
79
+ if (depth > 5) return out
80
+ let entries = []
81
+ try { entries = await readdir(dir, { withFileTypes: true }) } catch { return out }
82
+ for (const ent of entries) {
83
+ const p = join(dir, ent.name)
84
+ if (ent.isDirectory()) await walkFiles(p, out, depth + 1)
85
+ else if (ent.isFile()) out.push(p)
86
+ }
87
+ return out
88
+ }
89
+
90
+ function kindOf(key) {
91
+ const s = String(key || '')
92
+ if (/箱唛|carton/i.test(s)) return 'carton'
93
+ if (/大货|bulk/i.test(s)) return 'bulk_label'
94
+ return 'product_label'
95
+ }
96
+
97
+ async function findArtifacts(filesUploaded, sinceMs) {
98
+ const wanted = Object.entries(filesUploaded || {}).map(([key, name]) => ({ kind: kindOf(key), name: basename(String(name || '')) })).filter((x) => x.name)
99
+ if (!wanted.length) return []
100
+ const all = await walkFiles(DOWNLOAD_ROOT)
101
+ const recent = []
102
+ for (const p of all) {
103
+ try {
104
+ const st = await stat(p)
105
+ if (!st.isFile()) continue
106
+ if (sinceMs && st.mtimeMs + 5_000 < sinceMs) continue // 只认本次任务开始后落盘的文件
107
+ recent.push(p)
108
+ } catch { /* skip */ }
109
+ }
110
+ const found = []
111
+ for (const w of wanted) {
112
+ const candidates = recent.filter((p) => basename(p) === w.name)
113
+ // 同名文件按 mtime 最新;不按 path 字符串(避免目录名影响)
114
+ let best = ''
115
+ let bestMs = -1
116
+ for (const p of candidates) {
117
+ try { const st = await stat(p); if (st.mtimeMs > bestMs) { best = p; bestMs = st.mtimeMs } } catch { /* skip */ }
118
+ }
119
+ if (best) found.push({ path: best, kind: w.kind, filename: w.name })
120
+ }
121
+ return found
122
+ }
123
+
124
+ let activeChild = null
125
+ const activeTasks = new Map()
126
+ let shuttingDown = false
127
+
128
+ async function shutdown(signal = 'SIGTERM') {
129
+ if (shuttingDown) return
130
+ shuttingDown = true
131
+ console.log(`[worker] 收到 ${signal},停止并释放任务…`)
132
+ try { activeChild?.kill('SIGTERM') } catch { /* noop */ }
133
+ for (const t of activeTasks.values()) {
134
+ await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/release`, {
135
+ workerId, reason: `worker_shutdown:${signal}`,
136
+ }).catch(() => {})
137
+ }
138
+ setTimeout(() => process.exit(0), 3000).unref?.()
139
+ setTimeout(() => process.exit(0), 8000)
140
+ }
141
+ process.on('SIGTERM', () => { void shutdown('SIGTERM') })
142
+ process.on('SIGINT', () => { void shutdown('SIGINT') })
143
+
144
+ async function executeBatch(tasks) {
145
+ const records = []
146
+ const contexts = []
147
+ for (const t of tasks) {
148
+ activeTasks.set(String(t.id), t)
149
+ const c = await api('GET', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/context`)
150
+ records.push(c.record)
151
+ contexts.push({ task: t, record: c.record })
152
+ }
153
+ const dir = await mkdtemp(join(tmpdir(), 'argent-full-exec-'))
154
+ const file = join(dir, 'records.json')
155
+ await writeFile(file, JSON.stringify(records), 'utf8')
156
+ const hb = setInterval(() => {
157
+ for (const t of tasks) api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/heartbeat`, { workerId }).catch(() => {})
158
+ }, 30_000)
159
+ let out = ''
160
+ try {
161
+ out = await new Promise((resolve) => {
162
+ const child = spawn(process.env.ARGENT_PY || 'python3', [
163
+ join(ENGINE, 'scripts', 'orchestrator.py'), '--mode', 'full',
164
+ '--record-jsons-file', file, '--parallel-records', String(Math.min(tasks.length, TABS)),
165
+ '--allow-write', '--no-lip',
166
+ ], { cwd: ENGINE, env: { ...process.env, PYTHONPATH: 'scripts' } })
167
+ activeChild = child
168
+ let stdout = ''; let stderr = ''
169
+ child.stdout.on('data', (b) => { stdout += String(b) })
170
+ child.stderr.on('data', (b) => { stderr += String(b) })
171
+ child.on('close', () => { activeChild = null; resolve(stdout || stderr) })
172
+ child.on('error', (e) => { activeChild = null; resolve(`WORKER_ERROR: ${e.message}`) })
173
+ })
174
+ } finally {
175
+ clearInterval(hb)
176
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
177
+ }
178
+ let batch = null
179
+ for (const line of String(out).split('\n').reverse()) {
180
+ try { const j = JSON.parse(line); if (j && j.status) { batch = j; break } } catch { /* next */ }
181
+ }
182
+ if (!batch) {
183
+ for (const t of tasks) await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/result`, { workerId, status: 'failed', error: 'worker 未解析到引擎结果' }).catch(() => {})
184
+ return
185
+ }
186
+ const results = Array.isArray(batch.results) ? batch.results : []
187
+ for (const ctx of contexts) {
188
+ const rid = String(ctx.record.record_id || '')
189
+ const result = results.find((x) => String(x.record_id || '') === rid)
190
+ || (results.length === contexts.length ? results[contexts.indexOf(ctx)] : null)
191
+ || { status: 'failed', error: { message: batch.error || '引擎未返回该记录结果' } }
192
+ if (String(result.status || '') !== 'success') {
193
+ await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(ctx.task.id)}/result`, {
194
+ workerId, status: 'failed', error: String(result?.error?.message || result?.message || result?.status || 'FULL 失败'),
195
+ }).catch(() => {})
196
+ continue
197
+ }
198
+ const taskStarted = ctx.task.createdAt ? new Date(ctx.task.createdAt).getTime() : Date.now() - 2 * 3600_000
199
+ const files = await findArtifacts(result.files_uploaded || {}, taskStarted)
200
+ if (!files.length) {
201
+ await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(ctx.task.id)}/result`, {
202
+ workerId, status: 'failed', error: 'FULL 成功但未找到可上传的产物文件',
203
+ }).catch(() => {})
204
+ continue
205
+ }
206
+ const uploaded = await uploadFulfillmentFiles({
207
+ files,
208
+ cmdBase: `/api/argent/v1/tenants/${encodeURIComponent(APP)}/machines/${encodeURIComponent(MACHINE || workerId)}`,
209
+ apiCall: (method, path, body, timeoutMs) => api(method, path, body, timeoutMs),
210
+ }).catch((e) => ({ files: [], errors: [String(e?.message || e)] }))
211
+ if (!uploaded.files.length) {
212
+ await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(ctx.task.id)}/result`, {
213
+ workerId, status: 'failed', error: `产物上传失败: ${uploaded.errors.join('; ').slice(0, 300)}`,
214
+ }).catch(() => {})
215
+ continue
216
+ }
217
+ await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(ctx.task.id)}/result`, {
218
+ workerId, status: 'succeeded',
219
+ files: uploaded.files,
220
+ resultSummary: { summary: result.summary || `FULL 完成:${result.shipment_id || ctx.task.shipmentNo || ''}`, shipmentNo: result.shipment_id || ctx.task.shipmentNo || '' },
221
+ ticketComplete: Boolean(result.ticket_complete),
222
+ completedSteps: Array.isArray(result.completed_steps) ? result.completed_steps : [],
223
+ }).catch((e) => console.warn('[worker] 回写失败', ctx.task.id, e.message))
224
+ }
225
+ for (const t of tasks) activeTasks.delete(String(t.id))
226
+ }
227
+
228
+ async function tick() {
229
+ for (const store of STORES) {
230
+ try {
231
+ const claimed = await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/claim-batch`, {
232
+ store, workerId, capacity: TABS, max: TABS,
233
+ })
234
+ const tasks = Array.isArray(claimed.tasks) ? claimed.tasks : []
235
+ if (!tasks.length) continue
236
+ console.log(`[worker] ${store}: 领取 ${tasks.length} 个任务`)
237
+ await executeBatch(tasks)
238
+ } catch (e) {
239
+ console.warn(`[worker] ${store} 轮询失败:${e.message}`)
240
+ }
241
+ }
242
+ }
243
+
244
+ if (process.argv.includes('--check')) await preflightCheck()
245
+ console.log(`[worker] 启动 stores=${STORES.join(',')} tabs=${TABS} base=${BASE}`)
246
+ await tick()
247
+ if (process.env.FULL_EXEC_ONCE === '1') {
248
+ console.log('[worker] FULL_EXEC_ONCE=1,单轮结束')
249
+ process.exit(0)
250
+ }
251
+ setInterval(tick, POLL_MS)
@@ -165,7 +165,7 @@ export function renderPatch({ id, meta, composition, order }) {
165
165
  export function renderPackageJson(ids) {
166
166
  return JSON.stringify({
167
167
  name: '@whyshu/argent-presets',
168
- version: '0.1.1',
168
+ version: '0.1.3',
169
169
  description: 'Argent on DSH — 角色 preset 行式声明(dsh 0.1.7+;bundle patch 形态)',
170
170
  type: 'module',
171
171
  main: 'src/index.js',
@@ -1158,6 +1158,7 @@ def generate_for_row(row):
1158
1158
  record = {
1159
1159
  "货件号": _first(row.get(F_SHIP)),
1160
1160
  "品名": _first(row.get(F_NAME)),
1161
+ "SKU": sku,
1161
1162
  "数量": _first(row.get(F_QTY)),
1162
1163
  "箱数": _first(row.get(F_BOX)),
1163
1164
  "店铺名称": store,
@@ -84,6 +84,7 @@ if _EXTRA_PATH:
84
84
  HOME = Path.home()
85
85
  # 数据目录:**唯一判据**在 `scripts/lib/argent_datadir.py`(三级链,与 JS 内核同语义)
86
86
  sys.path.insert(0, str(Path(__file__).resolve().parent / 'lib'))
87
+ from invoice_names import strip_sku_prefix # noqa: E402
87
88
  from argent_datadir import resolve_data_dir # noqa: E402 —— 勿在此复制判据
88
89
  DATA = Path(resolve_data_dir()['dir'])
89
90
  MAPPING_FILE = DATA / "invoice-mapping.json"
@@ -242,12 +243,19 @@ def fix_drawing_xfrm(xlsx_path, ws, img_w, img_h, off_x, off_y, row_idx):
242
243
  tpl_dr = tpl_dr.replace("".join(anchors[1:]), "")
243
244
  tmp = xlsx_path.with_name(xlsx_path.name + ".tmp")
244
245
  with zipfile.ZipFile(xlsx_path) as zin, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
246
+ # 2026-11-03:模板 rels 写死 ../media/image1.png,但 openpyxl 按实际图片格式存成
247
+ # image1.jpeg(JPEG 源)⇒ 引用断裂,门户判「图片为空」。这里按实际媒体名改写 rels。
248
+ media = [n for n in zin.namelist() if n.startswith("xl/media/")]
249
+ actual_media = media[0].split("/")[-1] if media else "image1.png"
250
+ rels_bytes = tpl_rels
251
+ if rels_bytes:
252
+ rels_bytes = re.sub(rb"image1\.[A-Za-z0-9]+", actual_media.encode(), rels_bytes)
245
253
  for item in zin.namelist():
246
254
  data = zin.read(item)
247
255
  if item == "xl/drawings/drawing1.xml" and tpl_dr:
248
256
  data = tpl_dr.encode()
249
- elif item == "xl/drawings/_rels/drawing1.xml.rels" and tpl_rels:
250
- data = tpl_rels
257
+ elif item == "xl/drawings/_rels/drawing1.xml.rels" and rels_bytes:
258
+ data = rels_bytes
251
259
  elif item.endswith("worksheets/_rels/sheet1.xml.rels"):
252
260
  xml = data.decode()
253
261
  xml = xml.replace('Target="/xl/drawings/drawing1.xml"', 'Target="../drawings/drawing1.xml"')
@@ -317,7 +325,8 @@ def generate_invoice(record, mapping, wb, out_path):
317
325
  ws.cell(row=row, column=2).value = int(store_id) if str(store_id).isdigit() else store_id # PO Number(数字)
318
326
  ws.cell(row=row, column=3).value = boxes # 总箱数
319
327
  ws.cell(row=row, column=4).value = strip_name_parens(sku.get("品名英文"))
320
- ws.cell(row=row, column=5).value = norm(record.get("品名")) or ""
328
+ # 2026-11-20:模板 B 列只写产品名;如果 ERP 产品名称带 SKU 前缀,去掉(SKU 另有独立列)
329
+ ws.cell(row=row, column=5).value = strip_sku_prefix(norm(record.get("品名")), norm(record.get("SKU"))) or ""
321
330
  hs = clean_hs(sku.get("海关编码"))
322
331
  ws.cell(row=row, column=6).value = int(hs) if str(hs).isdigit() else hs # 目的国海关编码(数字)
323
332
  ws.cell(row=row, column=7).value = sku.get("材质英文") or ""
@@ -343,11 +352,13 @@ def generate_invoice(record, mapping, wb, out_path):
343
352
  ws.cell(row=row, column=17).value = d.get("model", "无")
344
353
  # 列 18 产品图片:SKU 主数据附件 → 下载 → OneCellAnchor 精确锚定 R 列该行
345
354
  # (固定 from 单元格 + ext 像素,不依赖 TwoCellAnchor 的 to 扩散计算)
355
+ # 2026-11-03:优先用「已下载到本地的产品图」(SkuFlow 路径由签名 URL 拉取)
356
+ local_img = sku.get("产品图本地") or ""
346
357
  imgs = sku.get("产品图") or []
347
- if imgs and sku.get("产品图记录"):
358
+ if not local_img and imgs and sku.get("产品图记录"):
348
359
  ft = imgs[0].get("file_token") if isinstance(imgs[0], dict) else str(imgs[0])
349
360
  local_img = download_attachment(ft, sku.get("产品图记录"), mapping)
350
- if local_img:
361
+ if local_img:
351
362
  from openpyxl.drawing.image import Image as XLImage
352
363
  from openpyxl.drawing.spreadsheet_drawing import TwoCellAnchor, AnchorMarker
353
364
  # 用原始附件图片(不做 PIL 处理——鑫中航后端对处理过的图片识别异常)
@@ -371,7 +382,7 @@ def generate_invoice(record, mapping, wb, out_path):
371
382
  wb.save(str(out_path))
372
383
  # 补图片 xfrm(鑫中航后端要求;无图时跳过)。坐标固定用官方示例图1(R22)
373
384
  try:
374
- if imgs:
385
+ if local_img:
375
386
  fix_drawing_xfrm(out_path, ws, 0, 0, 0, 0, 0)
376
387
  except Exception:
377
388
  pass
@@ -436,6 +436,13 @@ def download_label(order_no, save_name=None, wait_keep=15):
436
436
  print("订单页就绪", flush=True)
437
437
  page.wait_for_timeout(4000)
438
438
  n_rows, n_hit = _search_order(page, frame, order_no)
439
+ # 2026-11-03:刚导入的订单门户要几秒才可查 —— 未命中先等一轮再重试(最多 3 次)
440
+ for attempt in range(2):
441
+ if n_rows == 1 and n_hit == 1:
442
+ break
443
+ print(f"⚠ 第 {attempt + 1} 次未命中(rows={n_rows} hit={n_hit}),8s 后重试", flush=True)
444
+ page.wait_for_timeout(8000)
445
+ n_rows, n_hit = _search_order(page, frame, order_no)
439
446
  if not (n_rows == 1 and n_hit == 1):
440
447
  print("⚠ 未确认单行命中,不勾选不下载(安全保护)", flush=True)
441
448
  return None
@@ -572,12 +579,16 @@ def upload_invoice(invoice_path, order_no=None, wait_keep=20):
572
579
  return "notfound";
573
580
  }''')
574
581
  print(" 点击单票导入:", r, flush=True)
582
+ if r != "clicked":
583
+ raise RuntimeError("鑫中航上传失败: 找不到「单票导入」入口")
575
584
  page.wait_for_timeout(6000)
576
- close_overlays(page)
585
+ # ⚠️ 2026-11-03:这里**不能** close_overlays —— 它会把刚打开的「单票导入」弹窗一起关掉,
586
+ # 导致文件没选、上传没点,函数却返回成功(实测:弹窗开了又关)。
577
587
  fi = frame.locator("input[type=file]")
578
- if fi.count():
579
- fi.first.set_input_files(invoice_path)
580
- print(" 已选择文件:", invoice_path, flush=True)
588
+ if not fi.count():
589
+ raise RuntimeError("鑫中航上传失败: 单票导入弹窗里找不到文件输入框")
590
+ fi.first.set_input_files(invoice_path)
591
+ print(" 已选择文件:", invoice_path, flush=True)
581
592
  page.wait_for_timeout(6000)
582
593
  up = frame.evaluate('''() => {
583
594
  const els = [...document.querySelectorAll("a,button")];
@@ -585,6 +596,8 @@ def upload_invoice(invoice_path, order_no=None, wait_keep=20):
585
596
  if (el) { el.click(); return "clicked"; }
586
597
  return "notfound";
587
598
  }''')
599
+ if up != "clicked":
600
+ raise RuntimeError("鑫中航上传失败: 找不到「开始上传」按钮")
588
601
  print(" 点击开始上传:", up, flush=True)
589
602
  page.wait_for_timeout(15000)
590
603
  st = frame.evaluate('''() => {
@@ -596,6 +609,10 @@ def upload_invoice(invoice_path, order_no=None, wait_keep=20):
596
609
  }''')
597
610
  print(" === 上传结果 ===", flush=True)
598
611
  print(json.dumps(st, ensure_ascii=False, indent=1)[:1500], flush=True)
612
+ text = " ".join(st.get("dialogs") or [])
613
+ bad = [w for w in ("失败", "错误", "不能为空", "校验", "不合法", "重复", "异常") if w in text]
614
+ if bad:
615
+ raise RuntimeError(f"鑫中航上传失败: {text[:300]}")
599
616
  return True
600
617
  except Exception:
601
618
  traceback.print_exc()
@@ -347,12 +347,14 @@ export const STARTUP_FAILED_RE = /^\s*dsh: startup failed:/
347
347
  */
348
348
  export const PROVIDER_LINES = [
349
349
  {
350
- id: 'argent-core',
350
+ // 2026-11-24(0.13):客户侧已是单 bundle `@whyshu/argent`(旧 argent-core/flow/gateway/drive
351
+ // 多插件形态退场);必需提供行改为单 bundle 的 ERP 连接器启动行。
352
+ id: 'argent-bundle',
351
353
  required: true,
352
- re: /\[argent-core\]\s*已启动/,
353
- sample: '[argent-core] 已启动,数据目录: …',
354
- sourceFile: 'plugins/argent-core/src/index.js',
355
- literals: ["[argent-core] 已启动"],
354
+ re: /\[argent\]\s*ERP 连接器已启动/,
355
+ sample: '[argent] ERP 连接器已启动,数据目录: …',
356
+ sourceFile: 'plugins/argent/src/index.js',
357
+ literals: ['[argent] ERP 连接器已启动'],
356
358
  },
357
359
  {
358
360
  id: 'argent-flow',
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 日报「平台情报」卡片块(0.10.0 P4)
3
+ *
4
+ * 只负责把 `intel[]` 变成飞书卡片的 blocks(`{head, risk, groups}`),**纯函数**:
5
+ * ⛔ 不发请求、不读配置、不碰文件 —— 采集在 `scripts/collect-intel.mjs`,
6
+ * 拼卡在 `scripts/daily-report.mjs`,这里只管"长什么样",所以能单测。
7
+ *
8
+ * 为什么单独成文件:daily-report.mjs 有 1700 行且模块顶层会跑 main(),
9
+ * 测试直接 import 它不安全;把可测的部分抽出来,是把判据从"人看"变成"机器看"的最低成本做法。
10
+ */
11
+
12
+ /** 单条最多留多少摘要字符(超过会占满一屏) */
13
+ export const SNIPPET_MAX = 120
14
+ /** 最多显示几条情报 */
15
+ export const MAX_ITEMS = 6
16
+
17
+ /**
18
+ * @param {Array<{title:string,url?:string,snippet?:string,site_name?:string,date?:string}>} intel
19
+ * @returns {string[]} markdown 行(空数组 = 没有情报,调用方据此不拼卡)
20
+ */
21
+ export function intelHeadLines(intel) {
22
+ const items = (Array.isArray(intel) ? intel : []).filter((x) => x && x.title)
23
+ if (items.length === 0) return []
24
+ const lines = ['**🔎 平台情报**(自动搜索,仅供参考)', '']
25
+ for (const it of items.slice(0, MAX_ITEMS)) {
26
+ const title = it.url ? `[${it.title}](${it.url})` : it.title
27
+ const meta = [it.site_name, it.date ? `(${String(it.date).slice(0, 10)})` : ''].filter(Boolean).join(' ')
28
+ lines.push(`· ${title}${meta ? ` — ${meta}` : ''}`)
29
+ const snip = String(it.snippet || '').trim()
30
+ if (snip) lines.push(` ${snip.slice(0, SNIPPET_MAX)}${snip.length > SNIPPET_MAX ? '…' : ''}`)
31
+ }
32
+ if (items.length > MAX_ITEMS) lines.push(`· …另有 ${items.length - MAX_ITEMS} 条未显示`)
33
+ lines.push('', '_情报来自公开搜索;引用链接请自行核实后再决策。_')
34
+ return lines
35
+ }
36
+
37
+ /**
38
+ * 卡片 blocks(与 `cardMessageV2(title, blocks)` 对接)。
39
+ * @param {Array} intel
40
+ */
41
+ export function intelCardBlocks(intel) {
42
+ return { head: intelHeadLines(intel), risk: [], groups: [] }
43
+ }
@@ -0,0 +1,23 @@
1
+ """发票品名清洗:中文品名里如果前缀是 SKU,模板只写产品名,不重复写 SKU。
2
+
3
+ 背景(2026-11-20,发票现场):ERP/飞书的「产品名称」常写成
4
+ `HW-MX-116 60cm三色LED室内壁灯`;货代发票模板的「产品中文品名」列直接取该字段,
5
+ 于是模板 B 列把 SKU 也带进了品名,和旁边独立 SKU 列重复。
6
+
7
+ 规则很窄:只去掉**开头的、与 SKU 完全相同的** token(大小写不敏感),且后面必须是
8
+ 空白/分隔符或字符串结束;其它位置、其它编码一律不动。清空则回退原值(宁可不改,不产生空品名)。
9
+ """
10
+ import re
11
+
12
+
13
+ def strip_sku_prefix(name, sku):
14
+ """返回去掉开头 SKU token 后的中文品名;不匹配/空结果返回原值。"""
15
+ text = re.sub(r"\s+", " ", str(name or "")).strip()
16
+ token = str(sku or "").strip()
17
+ if not text or not token:
18
+ return text
19
+ m = re.match(r"^" + re.escape(token) + r"(?=$|[\s\-_:/:||])", text, re.IGNORECASE)
20
+ if not m:
21
+ return text
22
+ rest = text[m.end():].lstrip(" -_:/:||\t").strip()
23
+ return rest or text
@@ -22,12 +22,72 @@
22
22
  * · 指标可回溯 90 天;数据每天 10:00 (GMT-3) 更新。
23
23
  */
24
24
 
25
- /** 请求的活动指标(逗号串直接拼进 query)。 */
26
- export const ADS_METRICS = [
25
+ /**
26
+ * 请求的活动指标(逗号串直接拼进 query)。
27
+ *
28
+ * ## 2026-11-20 口径校准(T1)
29
+ * 官方 Product Ads 现行 metrics 列表里**没有** `units_quantity` / `total_amount` /
30
+ * `direct_amount` / `indirect_amount`(旧名),现行是:
31
+ * `clicks, prints, ctr, cost, cpc, acos, roas, cvr, sov, direct,
32
+ * organic_units_quantity, organic_units_amount, organic_items_quantity,
33
+ * direct_items_quantity, indirect_items_quantity, advertising_items_quantity`
34
+ * ⇒ 默认只请求**官方现行名**;旧名保留在 `ADS_METRICS_LEGACY` 里用于「客户机探针」与回退解析
35
+ * (⛔ 旧名是否仍被接受必须用真实请求验,代码不猜)。
36
+ * 「广告销售额」官方不直接给 ⇒ 用 `roas × cost` 反推,并在 totals 里标 `amountDerived=true`,
37
+ * 让卡片/日报能注明口径(⛔ 不许把它当平台原值)。
38
+ */
39
+ export const ADS_METRICS_OFFICIAL = [
40
+ 'clicks', 'prints', 'ctr', 'cost', 'cpc', 'acos', 'roas', 'cvr',
41
+ 'advertising_items_quantity', 'direct_items_quantity', 'indirect_items_quantity',
42
+ 'organic_units_quantity', 'organic_units_amount',
43
+ ]
44
+
45
+ /** 旧口径(2026-10 之前我们请求的名字):仅用于探针与解析回退,不作为默认请求。 */
46
+ export const ADS_METRICS_LEGACY = [
27
47
  'clicks', 'prints', 'ctr', 'cost', 'cpc', 'acos', 'roas',
28
48
  'units_quantity', 'total_amount', 'direct_amount', 'indirect_amount',
29
49
  'advertising_items_quantity',
30
- ].join(',')
50
+ ]
51
+
52
+ export const ADS_METRICS = ADS_METRICS_OFFICIAL.join(',')
53
+
54
+ /** 从 metrics 对象里取第一个存在的数值(按候选名顺序),都没有 ⇒ null。 */
55
+ export function pickNum(m, ...names) {
56
+ for (const n of names) {
57
+ const v = m && m[n]
58
+ if (v !== undefined && v !== null && v !== '') {
59
+ const x = Number(v)
60
+ if (Number.isFinite(x)) return x
61
+ }
62
+ }
63
+ return null
64
+ }
65
+
66
+ /** 广告带来的件数:现行优先 `advertising_items_quantity`,其次 direct+indirect,最后旧名。 */
67
+ export function adsUnitsOf(m) {
68
+ const adv = pickNum(m, 'advertising_items_quantity')
69
+ if (adv != null) return adv
70
+ const d = pickNum(m, 'direct_items_quantity')
71
+ const i = pickNum(m, 'indirect_items_quantity')
72
+ if (d != null || i != null) return (d || 0) + (i || 0)
73
+ return pickNum(m, 'units_quantity') || 0
74
+ }
75
+
76
+ /**
77
+ * 广告销售额:官方现行不直接给,按「旧名 → direct+indirect → roas×cost」回退。
78
+ * @returns {{amount:number, derived:boolean}}
79
+ */
80
+ export function adsAmountOf(m) {
81
+ const legacy = pickNum(m, 'total_amount')
82
+ if (legacy != null) return { amount: legacy, derived: false }
83
+ const d = pickNum(m, 'direct_amount')
84
+ const i = pickNum(m, 'indirect_amount')
85
+ if (d != null || i != null) return { amount: (d || 0) + (i || 0), derived: false }
86
+ const cost = pickNum(m, 'cost') || 0
87
+ const roas = pickNum(m, 'roas')
88
+ if (roas != null && cost > 0) return { amount: round2(cost * roas), derived: true }
89
+ return { amount: 0, derived: false }
90
+ }
31
91
 
32
92
  /** 默认告警阈值(可按店铺/全局覆盖)。 */
33
93
  export const ADS_ALERT_DEFAULTS = {
@@ -44,16 +104,18 @@ const num = (x) => Number(x || 0)
44
104
  * @param {Array<{id?:any,name?:string,status?:string,metrics?:object}>} campaigns
45
105
  */
46
106
  export function deriveAdsTotals(campaigns = []) {
47
- const t = { clicks: 0, prints: 0, cost: 0, units: 0, amount: 0, directAmount: 0, indirectAmount: 0, campaigns: campaigns.length, activeCampaigns: 0 }
107
+ const t = { clicks: 0, prints: 0, cost: 0, units: 0, amount: 0, directAmount: 0, indirectAmount: 0, amountDerived: false, campaigns: campaigns.length, activeCampaigns: 0 }
48
108
  for (const c of campaigns) {
49
109
  const m = (c && c.metrics) || {}
50
110
  t.clicks += num(m.clicks)
51
111
  t.prints += num(m.prints)
52
112
  t.cost += num(m.cost)
53
- t.units += num(m.units_quantity)
54
- t.amount += num(m.total_amount)
55
- t.directAmount += num(m.direct_amount)
56
- t.indirectAmount += num(m.indirect_amount)
113
+ t.units += adsUnitsOf(m)
114
+ const a = adsAmountOf(m)
115
+ t.amount += a.amount
116
+ if (a.derived) t.amountDerived = true
117
+ t.directAmount += num(pickNum(m, 'direct_amount') || 0)
118
+ t.indirectAmount += num(pickNum(m, 'indirect_amount') || 0)
57
119
  if (String(c && c.status || '').toLowerCase() === 'active') t.activeCampaigns++
58
120
  }
59
121
  t.cost = round2(t.cost)
@@ -126,6 +188,20 @@ export async function fetchAdsReport({ apiGet, token, site, dateFrom, dateTo, pa
126
188
  advertiserId: a.advertiser_id, site: advSite, name: a.advertiser_name || '', account: a.account_name || '',
127
189
  campaignTotal: total ?? campaigns.length, totals,
128
190
  topCampaigns: pickCampaigns(campaigns),
191
+ // 2026-11-25(P2a):广告诊断规则需要**活动级全量**(零转化/ACoS/花费集中度),
192
+ // topCampaigns 只有 top3 不够;这里给归一化后的全部活动(字段小,量级几十)。
193
+ campaigns: campaigns.map((c) => {
194
+ const m = (c && c.metrics) || {}
195
+ const amt = adsAmountOf(m)
196
+ return {
197
+ id: String(c && c.id != null ? c.id : ''), name: String((c && c.name) || ''),
198
+ status: String((c && c.status) || ''),
199
+ cost: round2(num(m.cost)), amount: round2(amt.amount), amountDerived: amt.derived,
200
+ clicks: num(m.clicks), prints: num(m.prints), units: adsUnitsOf(m),
201
+ ctr: round2(pickNum(m, 'ctr') || 0), roas: round2(pickNum(m, 'roas') || 0),
202
+ acos: round2(pickNum(m, 'acos') || 0), cvr: round2(pickNum(m, 'cvr') || 0),
203
+ }
204
+ }),
129
205
  })
130
206
  }
131
207
  const combined = combineTotals(perAdvertiser.map((x) => x.totals))
@@ -137,8 +213,9 @@ export function combineTotals(list = []) {
137
213
  const sum = list.reduce((a, t) => {
138
214
  a.clicks += num(t.clicks); a.prints += num(t.prints); a.cost += num(t.cost)
139
215
  a.units += num(t.units); a.amount += num(t.amount); a.campaigns += num(t.campaigns)
216
+ if (t && t.amountDerived) a.amountDerived = true
140
217
  return a
141
- }, { clicks: 0, prints: 0, cost: 0, units: 0, amount: 0, campaigns: 0 })
218
+ }, { clicks: 0, prints: 0, cost: 0, units: 0, amount: 0, campaigns: 0, amountDerived: false })
142
219
  sum.cost = round2(sum.cost); sum.amount = round2(sum.amount)
143
220
  sum.roas = sum.cost > 0 ? round2(sum.amount / sum.cost) : 0
144
221
  sum.acos = sum.amount > 0 ? round2((sum.cost / sum.amount) * 100) : 0
@@ -150,15 +227,19 @@ export function combineTotals(list = []) {
150
227
 
151
228
  /** 纯函数:挑出「花钱最多 / ACoS 超标」的活动(用于下钻展示)。 */
152
229
  export function pickCampaigns(campaigns = [], { topSpend = 3, badAcos = ADS_ALERT_DEFAULTS.acosBad, minSpend = 50 } = {}) {
153
- const rows = campaigns.map((c) => ({
154
- id: c.id, name: c.name || String(c.id || ''), status: String(c.status || ''),
155
- cost: round2(num(c.metrics && c.metrics.cost)),
156
- amount: round2(num(c.metrics && c.metrics.total_amount)),
157
- clicks: num(c.metrics && c.metrics.clicks),
158
- units: num(c.metrics && c.metrics.units_quantity),
159
- roas: round2(num(c.metrics && c.metrics.roas)),
160
- acos: round2(num(c.metrics && c.metrics.acos)),
161
- })).filter((x) => x.cost > 0)
230
+ const rows = campaigns.map((c) => {
231
+ const m = (c && c.metrics) || {}
232
+ const amt = adsAmountOf(m)
233
+ return {
234
+ id: c.id, name: c.name || String(c.id || ''), status: String(c.status || ''),
235
+ cost: round2(num(m.cost)),
236
+ amount: round2(amt.amount), amountDerived: amt.derived,
237
+ clicks: num(m.clicks),
238
+ units: adsUnitsOf(m),
239
+ roas: round2(pickNum(m, 'roas') || 0),
240
+ acos: round2(pickNum(m, 'acos') || 0),
241
+ }
242
+ }).filter((x) => x.cost > 0)
162
243
  const top = [...rows].sort((a, b) => b.cost - a.cost).slice(0, topSpend)
163
244
  const bad = rows.filter((x) => x.cost >= minSpend && (x.acos > badAcos || x.amount <= 0))
164
245
  .sort((a, b) => b.cost - a.cost).slice(0, 3)
@@ -187,6 +268,7 @@ export function adsCardLines(report, opts = {}) {
187
268
  const t = report.totals || {}
188
269
  out.push(`**📣 广告**(${report.dateFrom} ~ ${report.dateTo},Product Ads)`)
189
270
  out.push(`花费 ${m(t.cost)} · 广告销售额 ${m(t.amount)} · **ROAS ${t.roas}** · ACoS ${t.acos}% · 点击 ${t.clicks} · 广告单量 ${t.units} · ${t.campaigns} 个活动`)
271
+ if (t.amountDerived) out.push(' └ 口径:广告销售额由 **ROAS × 花费** 推算(官方现行 metrics 不直接返回销售额)')
190
272
  for (const a of report.advertisers) {
191
273
  const at = a.totals || {}
192
274
  const alerts = classifyAdsAlerts(at, opts.alertOpts)