@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.
Files changed (113) hide show
  1. package/MANIFEST.json +109 -43
  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 +3 -3
  7. package/engine/core/contracts/verbs.schema.json +64 -1
  8. package/engine/core/lib/account-token.mjs +37 -0
  9. package/engine/core/lib/contract.mjs +30 -0
  10. package/engine/core/lib/redact.mjs +34 -0
  11. package/engine/core/mcp/billing-upload.mjs +77 -0
  12. package/engine/core/mcp/erp-server.mjs +300 -0
  13. package/engine/core/mcp/gateway.mjs +333 -0
  14. package/engine/core/mcp/meter.mjs +101 -0
  15. package/engine/core/mcp/server.mjs +416 -2
  16. package/engine/core/mcp/vault.mjs +78 -0
  17. package/engine/scripts/appointment-worker.mjs +456 -35
  18. package/engine/scripts/appointment_grab.py +1389 -264
  19. package/engine/scripts/appointment_rules.py +118 -0
  20. package/engine/scripts/argent-timers.mjs +227 -0
  21. package/engine/scripts/argent-web-preflight.mjs +123 -0
  22. package/engine/scripts/argent-web-verify.mjs +105 -0
  23. package/engine/scripts/billing-upload.mjs +26 -0
  24. package/engine/scripts/build-doc-index.mjs +68 -0
  25. package/engine/scripts/build-engine-package.mjs +7 -1
  26. package/engine/scripts/capability-packs.lock.json +323 -300
  27. package/engine/scripts/check-docs-drift.mjs +51 -4
  28. package/engine/scripts/check-version-consistency.mjs +14 -1
  29. package/engine/scripts/ci-run.sh +2 -2
  30. package/engine/scripts/collect-intel.mjs +108 -0
  31. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  32. package/engine/scripts/daily-report-timers.sh +36 -3
  33. package/engine/scripts/daily-report.mjs +78 -2
  34. package/engine/scripts/doc-status.mjs +212 -0
  35. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  36. package/engine/scripts/engine-manifest.mjs +90 -0
  37. package/engine/scripts/engine-runtime-install.mjs +92 -0
  38. package/engine/scripts/erp-ui-install.mjs +127 -0
  39. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  40. package/engine/scripts/erp-ui-verify.mjs +135 -0
  41. package/engine/scripts/flow-requirements.json +122 -99
  42. package/engine/scripts/full-exec-worker.mjs +251 -0
  43. package/engine/scripts/gen-preset-rows.mjs +1 -1
  44. package/engine/scripts/invoice_lip_runner.py +1 -0
  45. package/engine/scripts/invoice_runner.py +17 -6
  46. package/engine/scripts/invoice_stageb.py +21 -4
  47. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  48. package/engine/scripts/lib/intel-card.mjs +43 -0
  49. package/engine/scripts/lib/invoice_names.py +23 -0
  50. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  51. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  52. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  53. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  54. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  55. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  56. package/engine/scripts/lib/ml-items.mjs +40 -0
  57. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  58. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  59. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  60. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  61. package/engine/scripts/line_pack.py +196 -0
  62. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  63. package/engine/scripts/migrate-providers.mjs +3 -3
  64. package/engine/scripts/ml-ads-advice.mjs +140 -0
  65. package/engine/scripts/ml-ads.mjs +221 -0
  66. package/engine/scripts/ml-category-baseline.mjs +174 -0
  67. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  68. package/engine/scripts/ml-insight-run.sh +183 -0
  69. package/engine/scripts/ml-insight-timers.sh +224 -0
  70. package/engine/scripts/ml-listing-audit.mjs +170 -0
  71. package/engine/scripts/ml-market-matrix.mjs +84 -0
  72. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  73. package/engine/scripts/ml-messages.mjs +145 -0
  74. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  75. package/engine/scripts/npm-publish-argent.mjs +14 -0
  76. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  77. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  78. package/engine/scripts/ops-digest.mjs +98 -0
  79. package/engine/scripts/ops-verify.mjs +67 -0
  80. package/engine/scripts/orchestrator.py +410 -20
  81. package/engine/scripts/orchestrator_br.py +146 -4
  82. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  83. package/engine/scripts/publish-engine.mjs +111 -0
  84. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  85. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  86. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  87. package/engine/scripts/vertical-lint.mjs +12 -1
  88. package/engine/scripts/web-switch.mjs +121 -0
  89. package/engine/scripts/wenyao_fill_template.py +52 -15
  90. package/engine/scripts/wenyao_run.py +2 -1
  91. package/engine/skills/README.md +3 -3
  92. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  93. package/engine/skills/douyin-upload/SKILL.md +74 -0
  94. package/engine/skills/internal.json +28 -0
  95. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  96. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  97. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  98. package/engine/skills/ml-invoice/SKILL.md +2 -2
  99. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  100. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  101. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  102. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  103. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  104. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  105. package/engine/skills/tencent-upload/SKILL.md +60 -0
  106. package/engine/skills/weibo-upload/SKILL.md +106 -0
  107. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  108. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/README.md +7 -0
  111. package/engine/verticals/_engine-words.baseline.txt +27 -59
  112. package/engine/verticals/mercadolibre/manifest.json +132 -6
  113. package/package.json +5 -1
@@ -0,0 +1,424 @@
1
+ /**
2
+ * ml-insight-facts.mjs —— 店铺诊断的**取数层**(L1):把日报分区 / listing / market / ads 的事实
3
+ * 组装成 `assessStore()` 需要的 `storeFacts`。
4
+ *
5
+ * 分工:
6
+ * · 本文件只做"取数 + 归一",**不做判断**(阈值/评分全在 ml-insight-core);
7
+ * · HTTP 入口注入 `apiGet`(离线测试可替换);订单可注入 `orders`(避免测试联网);
8
+ * · 某个数据源失败/缺失 ⇒ 写进 `coverage.missing`,对应维度在评分卡里 N/A(⛔ 不猜 0)。
9
+ *
10
+ * 数据源(与日报/现有 CLI 同一口径,不新造):
11
+ * · 订单:`/users/{uid}/orders/search`(`fetchOrdersWithMeta`,或注入)
12
+ * · 商品:`/users/{uid}/items/search` + 批量 `/items`
13
+ * · 访客:`/items/{id}/visits/time_window?last=7|14&unit=day`(按抽样,1~2 请求/商品)
14
+ * · 价格竞争力:`/items/{id}/price_to_win?version=v2`
15
+ * · 风险:`/users/me`(seller_reputation)+ claims/questions 搜索
16
+ * · 广告:`fetchAdsReport`(与 ml-ads/日报同一实现)
17
+ * · Listing:`runListingAudit`(官方 `/item/{id}/performance`)
18
+ * · 竞品:ml-market 快照 JSONL(调用方读文件后传入)
19
+ */
20
+ import {
21
+ aggregateOrders, fetchOrdersWithMeta, SITE_TZ, fallbackSite,
22
+ localDateStr, startOfLocalDayUTC, isoWithOffset,
23
+ } from './daily-report-core.mjs'
24
+ import { fetchAdsReport } from './ml-ads-core.mjs'
25
+ import { runListingAudit } from './ml-listing-core.mjs'
26
+ import { parseSnapshotJsonl } from './ml-market-core.mjs'
27
+ import { fetchItemsBatched } from './ml-items.mjs'
28
+
29
+ const DAY = 86400000
30
+ const num = (x) => (x === null || x === undefined || x === '' ? null : (Number.isFinite(Number(x)) ? Number(x) : null))
31
+ const round2 = (x) => Math.round(Number(x || 0) * 100) / 100
32
+ const round4 = (x) => Math.round(Number(x || 0) * 10000) / 10000
33
+
34
+ /** 自描述:本文件组装了哪些块、缺哪些(进 facts.coverage,评分卡据此 N/A)。 */
35
+ function newMissing() { return [] }
36
+
37
+ /**
38
+ * 主入口:组装 storeFacts(只读取数;失败降级为 missing)。
39
+ * @param {object} p
40
+ * @param {(path:string, token:string, opts?:object)=>Promise<any>} p.apiGet
41
+ * @param {string} p.token
42
+ * @param {{name:string,user_id:string,site?:string}} p.store
43
+ * @param {Date} [p.now]
44
+ * @param {object[]} [p.orders] 可注入订单(离线测试);缺省则真拉(14 天)
45
+ * @param {string[]} [p.marketLines] ml-market 快照 JSONL 行
46
+ * @param {object} [p.opts] { visitsLimit, priceLimit, listingLimit, ads, listing, traffic, priceToWin, risk, days }
47
+ */
48
+ export async function collectFacts({ apiGet, token, store, now = new Date(), orders = null, marketLines = [], opts = {} } = {}) {
49
+ if (typeof apiGet !== 'function') throw new Error('collectFacts 需要注入 apiGet')
50
+ const site = fallbackSite(store && store.site)
51
+ const tz = SITE_TZ[site]
52
+ const uid = String((store && store.user_id) || '')
53
+ if (!uid) throw new Error('collectFacts 需要 store.user_id')
54
+ const missing = newMissing()
55
+ const o = { visitsLimit: 20, priceLimit: 10, listingLimit: 20, ads: true, listing: true, traffic: true, priceToWin: true, risk: true, days: 7, ...opts }
56
+
57
+ const todayStart = startOfLocalDayUTC(tz, now)
58
+ const weekStart = todayStart - o.days * DAY
59
+ const prevStart = weekStart - o.days * DAY
60
+ const facts = {
61
+ store: String(store.name || ''), site, date: localDateStr(tz, new Date(weekStart)),
62
+ capturedAt: isoWithOffset(tz, now), coverage: { missing },
63
+ sales: null, traffic: null, catalog: null, priceToWin: null, ads: null,
64
+ risk: null, stock: null, listing: null, market: null, trends: null,
65
+ }
66
+
67
+ // ── 1. 商品(自有在售;批量取价格/状态/库存)────────────────
68
+ let itemIds = []
69
+ let itemById = {}
70
+ try {
71
+ const r = await apiGet(`/users/${uid}/items/search?status=active&limit=50&offset=0`, token)
72
+ itemIds = (r && (r.results || r.item_ids)) || []
73
+ const total = num(r && r.paging && r.paging.total)
74
+ facts.catalog = { active: total != null ? total : itemIds.length }
75
+ if (itemIds.length) {
76
+ // ⚠️ 平台硬限制:`/items?ids=` 最多 20 个(实测 50 个 ⇒ HTTP 400)⇒ 必须分片
77
+ const want = itemIds.slice(0, 50)
78
+ for (let i = 0; i < want.length; i += 20) {
79
+ // ⚠️ `ids` 里的逗号**必须是裸逗号**(实测 `%2C` ⇒ 403 ResourceDeprecated);attributes 同理
80
+ const attrs = 'id,title,price,status,available_quantity,permalink,sold_quantity'
81
+ // 2026-12-01:批量接口可能被弃用 ⇒ 批量优先 + 单条兜底
82
+ const rows = await fetchItemsBatched({ apiGet, token, ids: want.slice(i, i + 20), attrs, batchSize: 20 })
83
+ for (const row of rows) if (row && row.body && row.body.id) itemById[String(row.body.id)] = row.body
84
+ }
85
+ }
86
+ } catch (e) {
87
+ missing.push(`items: ${String((e && e.message) || e).slice(0, 120)}`)
88
+ }
89
+
90
+ // ── 2. 订单 → 销售/利润线索/库存件数 ───────────────────────
91
+ try {
92
+ let allOrders = orders
93
+ if (!allOrders) {
94
+ const r = await fetchOrdersWithMeta(token, uid, new Date(prevStart).toISOString(), new Date(todayStart).toISOString(), {})
95
+ if (!r.complete && r.reason) missing.push(`orders: ${r.reason}`)
96
+ allOrders = r.orders || []
97
+ }
98
+ const winCur = { weekStartMs: weekStart, reportStartMs: weekStart, todayStartMs: todayStart }
99
+ const winPrev = { weekStartMs: prevStart, reportStartMs: prevStart, todayStartMs: weekStart }
100
+ const cur = aggregateOrders(allOrders, itemById, winCur, site)
101
+ const prev = aggregateOrders(allOrders, itemById, winPrev, site)
102
+ const cs = cur.summary || {}
103
+ const ps = prev.summary || {}
104
+ const cancels = cs.cancelled || 0
105
+ facts.sales = {
106
+ orders: cs.orders, ordersPrev: ps.orders,
107
+ gmv: round2(cs.gmv), gmvPrev: round2(ps.gmv),
108
+ units: cs.units, aov: cs.avg != null ? round2(cs.avg) : null,
109
+ cancelRate: cs.orders + cancels > 0 ? round4(cancels / (cs.orders + cancels)) : null,
110
+ }
111
+ facts.stock = (cur.skus || []).map((s) => ({ sku: s.sku || s.id, stock: s.avail, sold7: s.units7 })).filter((s) => s.stock != null)
112
+ if (!facts.stock.length) facts.stock = null
113
+ } catch (e) {
114
+ missing.push(`orders: ${String((e && e.message) || e).slice(0, 120)}`)
115
+ }
116
+
117
+ // ── 3. 访客(抽样:last=7 与 last=14,差值作上期)─────────────
118
+ if (o.traffic && itemIds.length) {
119
+ const sample = itemIds.slice(0, o.visitsLimit)
120
+ let cur = 0, prevSum = 0, ok = 0, zeros = 0
121
+ for (const id of sample) {
122
+ try {
123
+ const a = await apiGet(`/items/${id}/visits/time_window?last=${o.days}&unit=day`, token)
124
+ const b = await apiGet(`/items/${id}/visits/time_window?last=${o.days * 2}&unit=day`, token)
125
+ const c7 = num(a && a.total_visits), c14 = num(b && b.total_visits)
126
+ if (c7 == null) continue
127
+ cur += c7
128
+ if (c14 != null) prevSum += Math.max(0, c14 - c7)
129
+ if (c7 === 0) zeros++
130
+ ok++
131
+ } catch { /* 单商品失败跳过(缺失会体现在抽样覆盖率上) */ }
132
+ }
133
+ if (ok > 0) {
134
+ const activeTotal = (facts.catalog && facts.catalog.active) || itemIds.length
135
+ const share = ok ? zeros / ok : null
136
+ const extrapolated = share != null ? Math.round(share * activeTotal) : null
137
+ facts.traffic = {
138
+ visits: cur,
139
+ visitsPrev: ok > 0 && prevSum > 0 ? prevSum : null,
140
+ zeroVisitActive: extrapolated,
141
+ sampled: ok,
142
+ }
143
+ if (facts.traffic.visitsPrev == null) missing.push('traffic.visitsPrev(只取到 last=7,无法算环比)')
144
+ if (ok < Math.min(itemIds.length, o.visitsLimit)) missing.push(`traffic.sampled=${ok}(抽样未覆盖全部在售)`)
145
+ } else missing.push('traffic: 访客接口全部失败')
146
+ } else if (o.traffic) missing.push('traffic: 无在售商品可抽样')
147
+
148
+ // ── 4. 价格竞争力(抽样:price_to_win v2)───────────────────
149
+ if (o.priceToWin && itemIds.length) {
150
+ // 真实状态:winning / losing / shared / **not_listed(未参与目录/价格竞争,reason=item_not_opted_in)**。
151
+ // ⛔ not_listed 不能当 losing:实测整个店都可能 not_listed(商品未 opt-in),否则会出现"价格落后 0%"的假红。
152
+ let worst = null, anyLosing = false, notListed = 0, eligible = 0
153
+ for (const id of itemIds.slice(0, o.priceLimit)) {
154
+ try {
155
+ const p = await apiGet(`/items/${id}/price_to_win?version=v2`, token)
156
+ const status = String((p && p.status) || '')
157
+ if (status === 'not_listed') { notListed++; continue }
158
+ if (!status || status === 'unknown') continue
159
+ eligible++
160
+ const cur = num(p && p.current_price), target = num(p && p.price_to_win)
161
+ const gap = cur != null && target != null && target > 0 ? round4((cur - target) / target) : null
162
+ if (status !== 'winning') anyLosing = true
163
+ if (gap != null && (worst == null || gap > worst.gapPct)) worst = { status, gapPct: gap }
164
+ } catch { /* 单商品失败跳过 */ }
165
+ }
166
+ if (!eligible) {
167
+ missing.push(`traffic.priceToWin: 抽样 ${notListed} 个商品均未参与目录竞争(not_listed/item_not_opted_in)`)
168
+ } else if (anyLosing) {
169
+ facts.priceToWin = { status: 'losing', gapPct: worst ? worst.gapPct : null }
170
+ } else {
171
+ facts.priceToWin = { status: 'winning', gapPct: 0 }
172
+ }
173
+ } else if (o.priceToWin) missing.push('traffic.priceToWin: 无在售商品可抽样')
174
+
175
+ // ── 5. 风险(信誉/纠纷/未回复提问)──────────────────────────
176
+ if (o.risk) {
177
+ try {
178
+ const me = await apiGet('/users/me', token)
179
+ const rep = (me && me.seller_reputation) || {}
180
+ const metrics = rep.metrics || {}
181
+ const claimRate = num(metrics.claims && metrics.claims.rate)
182
+ // 官方 reputation 指标优先(60 天窗口):cancel/claim 用官方率,缺才退回订单口径
183
+ const cancelRate = num(metrics.cancellations && metrics.cancellations.rate) ?? (facts.sales ? facts.sales.cancelRate : null)
184
+ const delayedShipments = num(metrics.delayed_handling_time && metrics.delayed_handling_time.value)
185
+ let unanswered = null, oldestDays = null
186
+ try {
187
+ const q = await apiGet(`/questions/search?seller_id=${encodeURIComponent(uid)}&status=UNANSWERED&limit=50`, token)
188
+ const rows = (q && (q.questions || q.results)) || []
189
+ unanswered = num(q && q.total) ?? rows.length
190
+ const oldest = rows.map((x) => Date.parse(x.date_created || '')).filter((t) => Number.isFinite(t)).sort((a, b) => a - b)[0]
191
+ if (oldest) oldestDays = Math.floor((now.getTime() - oldest) / DAY)
192
+ } catch { missing.push('risk.questions') }
193
+ try {
194
+ const c = await apiGet('/post-purchase/v1/claims/search?role=seller&status=opened&limit=50', token)
195
+ const rows = (c && (c.data || c.results)) || []
196
+ if (claimRate == null && facts.sales && facts.sales.orders) claimRate = round4(rows.length / facts.sales.orders)
197
+ } catch { /* claims 失败不致命 */ }
198
+ facts.risk = {
199
+ claimRate, cancelRate, unansweredQuestions: unanswered, oldestQuestionDays: oldestDays,
200
+ // 官方 delayed_handling_time.value = 窗口内延迟单数(period 通常是 60 天,报文里标注)
201
+ delayedShipments,
202
+ }
203
+ if (delayedShipments == null) missing.push('risk.delayedShipments(官方指标未返回,S8 不判该子项)')
204
+ else missing.push('risk.delayedShipments 口径=官方 delayed_handling_time.value(窗口 60 天)')
205
+ } catch (e) {
206
+ missing.push(`risk: ${String((e && e.message) || e).slice(0, 120)}`)
207
+ }
208
+ }
209
+
210
+ // ── 6. 广告(与 ml-ads/日报同一实现)───────────────────────
211
+ if (o.ads) {
212
+ try {
213
+ const dateTo = localDateStr(tz, new Date(todayStart - DAY))
214
+ const dateFrom = localDateStr(tz, new Date(todayStart - o.days * DAY))
215
+ const rep = await fetchAdsReport({ apiGet, token, site, dateFrom, dateTo })
216
+ const t = rep.totals || {}
217
+ let active = 0, paused = 0, zeroConv = 0
218
+ for (const a of rep.advertisers || []) {
219
+ active += num(a.activeCampaigns) || 0
220
+ paused += num(a.pausedCampaigns) || 0
221
+ zeroConv += (a.zeroConvCampaigns || 0)
222
+ }
223
+ facts.ads = {
224
+ cost: t.cost || 0, amount: t.amount || 0, roas: t.roas ?? null, acos: t.acos ?? null,
225
+ targetRoas: null, activeCampaigns: active, pausedCampaigns: paused, zeroConvCampaigns: zeroConv,
226
+ minSpend: 100,
227
+ }
228
+ if (!facts.ads.cost) missing.push('ads: 无广告花费(可能未开权限或本期无投放)')
229
+ } catch (e) {
230
+ missing.push(`ads: ${String((e && e.message) || e).slice(0, 120)}`)
231
+ }
232
+ }
233
+
234
+ // ── 7. Listing 质量(官方 /performance)─────────────────────
235
+ if (o.listing) {
236
+ try {
237
+ const r = await runListingAudit({ apiGet, token, site, uid, limit: o.listingLimit })
238
+ if (r.summary && r.summary.scored > 0) {
239
+ facts.listing = { avgScore: r.summary.avg, pendingTotal: r.summary.pendingTotal, count: r.summary.count, scored: r.summary.scored }
240
+ } else missing.push('listing: 未取到质量分(接口失败或无权限)')
241
+ } catch (e) {
242
+ missing.push(`listing: ${String((e && e.message) || e).slice(0, 120)}`)
243
+ }
244
+ }
245
+
246
+ // ── 8. 竞品(ml-market 快照;调用方读 JSONL 传入)───────────
247
+ if (marketLines && marketLines.length) {
248
+ try {
249
+ const recs = parseSnapshotJsonl(marketLines.join('\n')).records
250
+ const byCap = new Map()
251
+ for (const r of recs) {
252
+ const cap = String(r.capturedAt || '')
253
+ if (!cap) continue
254
+ if (!byCap.has(cap)) byCap.set(cap, [])
255
+ byCap.get(cap).push(r)
256
+ }
257
+ const caps = [...byCap.keys()].sort()
258
+ const latest = caps.length ? byCap.get(caps[caps.length - 1]) : []
259
+ const prev = caps.length > 1 ? byCap.get(caps[caps.length - 2]) : []
260
+ const prevBy = new Map(prev.map((r) => [r.itemId, r]))
261
+ const own = latest.filter((r) => r.source === 'own')
262
+ const comps = latest.filter((r) => r.source !== 'own')
263
+ const ourPrices = own.map((r) => num(r.price)).filter((x) => x != null)
264
+ const ourRatings = own.map((r) => num(r.rating)).filter((x) => x != null)
265
+ if (comps.length) {
266
+ facts.market = {
267
+ ourPrice: ourPrices.length ? round2(ourPrices.reduce((a, b) => a + b, 0) / ourPrices.length) : null,
268
+ ourRating: ourRatings.length ? round2(ourRatings.reduce((a, b) => a + b, 0) / ourRatings.length) : null,
269
+ competitors: comps.slice(0, 20).map((r) => ({
270
+ id: r.itemId, price: num(r.price), rating: num(r.rating),
271
+ prevPrice: prevBy.has(r.itemId) ? num(prevBy.get(r.itemId).price) : null,
272
+ })),
273
+ }
274
+ } else missing.push('market: 快照里没有竞品记录(先跑 ml-market-snapshot --items-file)')
275
+ } catch (e) {
276
+ missing.push(`market: ${String((e && e.message) || e).slice(0, 120)}`)
277
+ }
278
+ }
279
+
280
+ facts.coverage = { missing: [...new Set(missing)] }
281
+ return facts
282
+ }
283
+
284
+ /**
285
+ * **零请求**事实组装:直接复用日报快照(`daily-report-cache/<date>-<storeKey>.json`)。
286
+ *
287
+ * 为什么:日报每天已经把订单/风险/库存取过一遍;诊断再拉一次 = 重复请求(1 店 14 天 ≈ 190 页),
288
+ * 客户机上叠加定时器容易触发平台限流。诊断默认走快照,只有快照没有的块才按需补取。
289
+ *
290
+ * 快照里有什么(2026-11 实测结构):
291
+ * summary(orders/gmv/units/avg/cancelled)| comparisons.prevWeek(订单环比)|
292
+ * top/skus7(SKU 库存与 7 日件数)| data.reputation / claims / questions / sla / paused | itemById
293
+ * 快照里**没有**:visits(访客)|ads(广告)|price_to_win |listing 质量分 ⇒ 如实进 missing。
294
+ *
295
+ * @param {object} p
296
+ * @param {object} p.snapshot 日报快照对象(含 date/site/name/summary/comparisons/top/data…)
297
+ * @param {object} [p.facts] 现有 facts(用于覆盖/补充,如 listing 缓存、market)
298
+ * @param {{store?:string, site?:string, now?:Date}} [p.opts]
299
+ */
300
+ export function factsFromDailySnapshot({ snapshot, facts = {}, opts = {} } = {}) {
301
+ if (!snapshot || typeof snapshot !== 'object') throw new Error('factsFromDailySnapshot 需要日报快照对象')
302
+ const s = snapshot
303
+ const site = fallbackSite((s.site || (opts.site) || 'MLM'))
304
+ const store = String(s.name || (opts.store) || '')
305
+ const out = { ...facts }
306
+ const missing = new Set((out.coverage && out.coverage.missing) || [])
307
+ const summary = s.summary || {}
308
+ const comparisons = s.comparisons || {}
309
+ const prevWeek = comparisons.prevWeek || {}
310
+
311
+ // ── 销售(0 请求)────────────────────────────────────────
312
+ const orders = num(summary.orders)
313
+ const ordersPrev = num(prevWeek.orders)
314
+ const cancelled = num(summary.cancelled) || 0
315
+ if (orders != null) {
316
+ out.sales = {
317
+ orders, ordersPrev,
318
+ gmv: round2(summary.gmv), gmvPrev: round2(prevWeek.gmv),
319
+ units: num(summary.units), aov: summary.avg != null ? round2(summary.avg) : null,
320
+ cancelRate: orders + cancelled > 0 ? round4(cancelled / (orders + cancelled)) : null,
321
+ }
322
+ if (ordersPrev == null) missing.add('sales.ordersPrev(快照无上期对比 ⇒ S1 不判环比)')
323
+ } else missing.add('sales.summary(快照缺销售汇总)')
324
+
325
+ // ── 利润(0 请求,S7 用):平台净收入 = GMV − 佣金 − 优惠券(未含采购/头程/物流成本)──
326
+ const profitFees = num(summary.fees)
327
+ const profitCoupons = num(summary.coupons) || 0
328
+ const profitPrev = {
329
+ gmv: num(prevWeek.gmv) ?? num(s.prev && s.prev.gmv),
330
+ fees: num(prevWeek.fees) ?? num(s.prev && s.prev.fees),
331
+ }
332
+ if (orders != null && out.sales && num(out.sales.gmv) > 0 && profitFees != null) {
333
+ const gmv7 = num(out.sales.gmv)
334
+ const net = gmv7 - profitFees - profitCoupons
335
+ const netRate = round4(net / gmv7)
336
+ const feeRate = round4(profitFees / gmv7)
337
+ const prevGmv = profitPrev.gmv
338
+ const prevFees = profitPrev.fees
339
+ out.profit = {
340
+ gmv: gmv7, fees: round2(profitFees), coupons: round2(profitCoupons), net: round2(net),
341
+ feeRate, netRate,
342
+ feeRatePrev: prevGmv > 0 && prevFees != null ? round4(prevFees / prevGmv) : null,
343
+ netRateFloor: num(opts.netRateFloor) ?? num(process.env.ML_PROFIT_NET_FLOOR) ?? 0.12,
344
+ currency: String(s.currency || s.site || ''),
345
+ }
346
+ if (out.profit.feeRatePrev == null) missing.add('profit.feeRatePrev(快照无上期费用 ⇒ S7 仅按净收入底线判红)')
347
+ missing.add('profit.cost(快照无采购/头程/物流成本 ⇒ 净收入为平台侧口径,未含成本)')
348
+ } else missing.add('profit.fees/net(快照缺平台费用或 GMV ⇒ S7 不判)')
349
+
350
+ // ── 库存(0 请求)────────────────────────────────────────
351
+ const skuRows = (Array.isArray(s.skus7) && s.skus7.length) ? s.skus7 : (Array.isArray(s.top) ? s.top : [])
352
+ const stock = skuRows
353
+ .map((x) => ({ sku: String(x.sku || x.id || ''), stock: num(x.avail), sold7: num(x.units7 ?? x.sold) }))
354
+ .filter((x) => x.sku && x.stock != null)
355
+ if (stock.length) out.stock = stock.slice(0, 60)
356
+ else missing.add('ops.restock(快照无 SKU 库存)')
357
+
358
+ // ── 风险(0 请求:快照 data 段=官方指标)─────────────────
359
+ const data = s.data || {}
360
+ const rep = (data.reputation && data.reputation.metrics) || {}
361
+ const questions = data.questions || {}
362
+ const claims = data.claims || {}
363
+ const claimRate = num(rep.claims && rep.claims.rate)
364
+ const cancelRate = num(rep.cancellations && rep.cancellations.rate) ?? (out.sales ? out.sales.cancelRate : null)
365
+ const delayed = num(rep.delayed_handling_time && rep.delayed_handling_time.value)
366
+ const unanswered = num(questions.total) ?? num(claims.total)
367
+ const oldestHours = num(questions.oldestHours)
368
+ if (rep && Object.keys(rep).length) {
369
+ out.risk = {
370
+ claimRate, cancelRate, unansweredQuestions: unanswered,
371
+ oldestQuestionDays: oldestHours != null ? Math.floor(oldestHours / 24) : null,
372
+ delayedShipments: delayed,
373
+ }
374
+ if (delayed == null) missing.add('risk.delayedShipments(快照未含官方延迟单数)')
375
+ else missing.add('risk.delayedShipments 口径=官方 delayed_handling_time.value(窗口 60 天)')
376
+ } else missing.add('risk.*(快照无信誉/纠纷/提问)')
377
+
378
+ // ── 快照没有的块:如实标注(不猜、不额外请求)───────────
379
+ if (!out.traffic) missing.add('traffic.visits(快照未存访客 ⇒ S1 降级为订单口径、S2/S6 不判)')
380
+ if (!out.ads) missing.add('ads.summary(快照未存广告 ⇒ 加 --with-live 才取)')
381
+ if (!out.priceToWin) missing.add('traffic.priceToWin(快照未存 ⇒ 加 --with-live 才取)')
382
+ if (!out.listing) missing.add('ml-listing(日检结果未缓存 ⇒ 加 --with-live 或等定时器跑过后读取缓存)')
383
+
384
+ out.store = store
385
+ out.site = site
386
+ out.date = String(s.date || (out.date || ''))
387
+ out.capturedAt = String(s.capturedAt || (out.capturedAt || ''))
388
+ out.coverage = { missing: [...missing], source: 'daily-report-snapshot', snapshotDate: String(s.date || '') }
389
+ return out
390
+ }
391
+
392
+ /**
393
+ * 竞品事实(**零请求**):从 ml-market 快照 JSONL 的最近两份取价格/评分(不联网)。
394
+ * @param {{marketLines?:string[], ourPrice?:number, ourRating?:number}} p
395
+ */
396
+ export function factsFromMarketLines({ marketLines = [], ourPrice = null, ourRating = null } = {}) {
397
+ if (!Array.isArray(marketLines) || !marketLines.length) return null
398
+ const recs = parseSnapshotJsonl(marketLines.join('\n')).records || []
399
+ const byCap = new Map()
400
+ for (const r of recs) {
401
+ const cap = String(r.capturedAt || '')
402
+ if (!cap) continue
403
+ if (!byCap.has(cap)) byCap.set(cap, [])
404
+ byCap.get(cap).push(r)
405
+ }
406
+ const caps = [...byCap.keys()].sort()
407
+ const latest = caps.length ? byCap.get(caps[caps.length - 1]) : []
408
+ const prev = caps.length > 1 ? byCap.get(caps[caps.length - 2]) : []
409
+ const prevBy = new Map(prev.map((r) => [r.itemId, r]))
410
+ const own = latest.filter((r) => r.source === 'own')
411
+ const comps = latest.filter((r) => r.source !== 'own')
412
+ const ourPrices = own.map((r) => num(r.price)).filter((x) => x != null)
413
+ const ourRatings = own.map((r) => num(r.rating)).filter((x) => x != null)
414
+ const price = num(ourPrice) ?? (ourPrices.length ? round2(ourPrices.reduce((a, b) => a + b, 0) / ourPrices.length) : null)
415
+ const rating = num(ourRating) ?? (ourRatings.length ? round2(ourRatings.reduce((a, b) => a + b, 0) / ourRatings.length) : null)
416
+ if (!comps.length) return null
417
+ return {
418
+ ourPrice: price, ourRating: rating,
419
+ competitors: comps.slice(0, 20).map((r) => ({
420
+ id: r.itemId, price: num(r.price), rating: num(r.rating),
421
+ prevPrice: prevBy.has(r.itemId) ? num(prevBy.get(r.itemId).price) : null,
422
+ })),
423
+ }
424
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 商品详情取数(L1,注入 apiGet)——批量优先,单条兜底。
3
+ *
4
+ * 背景(2026-12-01 实测):`/items?ids=` 对部分 app 已返回
5
+ * `403 ResourceDeprecated - client no longer allowed to consume this resource`;
6
+ * 而单条 `/items/{id}` 仍可用。为避免"平台一改批量接口,所有功能全挂",
7
+ * 这里统一做:**先批量(裸逗号,≤20/批);批量被拒(403/弃用)⇒ 自动逐条取**。
8
+ *
9
+ * 返回:`Array<{body: object}>`(与批量接口形状一致,调用方无需改逻辑;失败的 id 不返回)。
10
+ */
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
12
+
13
+ export async function fetchItemsBatched({ apiGet, token, ids = [], attrs = '', batchSize = 20, gapMs = 120, maxSingle = 200 } = {}) {
14
+ if (typeof apiGet !== 'function') throw new Error('fetchItemsBatched 需要注入 apiGet')
15
+ const all = (Array.isArray(ids) ? ids : []).map((x) => String(x).trim()).filter((x) => /^[A-Za-z0-9]{1,40}$/.test(x))
16
+ const step = Math.max(1, Math.min(20, Math.trunc(Number(batchSize) || 20)))
17
+ const out = []
18
+ let singleMode = false
19
+ for (let i = 0; i < all.length; i += step) {
20
+ const chunk = all.slice(i, i + step)
21
+ if (!singleMode) {
22
+ try {
23
+ const res = await apiGet(`/items?ids=${chunk.join(',')}${attrs ? `&attributes=${attrs}` : ''}`, token)
24
+ const rows = Array.isArray(res) ? res : (res && res.body) || []
25
+ if (Array.isArray(rows) && rows.length) { out.push(...rows.filter((r) => r && r.body)); continue }
26
+ } catch (e) {
27
+ const msg = String((e && e.message) || e)
28
+ // 只有"接口被弃用/无权限"才降级;限流/网络错误照常抛给调用方(避免放大请求)
29
+ if (!/ResourceDeprecated|HTTP 403|not allowed/i.test(msg)) throw e
30
+ singleMode = true
31
+ }
32
+ }
33
+ for (const id of chunk.slice(0, maxSingle)) {
34
+ try { const b = await apiGet(`/items/${encodeURIComponent(id)}`, token); if (b && b.id) out.push({ body: b }) }
35
+ catch { /* 单条失败:跳过该 id,不影响整体 */ }
36
+ if (gapMs) await sleep(gapMs)
37
+ }
38
+ }
39
+ return out
40
+ }