@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.
Files changed (74) hide show
  1. package/MANIFEST.json +71 -36
  2. package/engine/VERSION +1 -1
  3. package/engine/configs/mcp-tools.snapshot.json +8 -1
  4. package/engine/core/contracts/argent.contracts.json +2 -2
  5. package/engine/core/mcp/erp-server.mjs +10 -6
  6. package/engine/core/mcp/gateway.mjs +3 -3
  7. package/engine/core/mcp/server.mjs +245 -0
  8. package/engine/scripts/appointment-worker.mjs +456 -35
  9. package/engine/scripts/appointment_grab.py +1329 -284
  10. package/engine/scripts/appointment_rules.py +118 -0
  11. package/engine/scripts/argent-timers.mjs +227 -0
  12. package/engine/scripts/capability-packs.lock.json +323 -300
  13. package/engine/scripts/check-version-consistency.mjs +14 -1
  14. package/engine/scripts/collect-intel.mjs +108 -0
  15. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  16. package/engine/scripts/daily-report-timers.sh +1 -1
  17. package/engine/scripts/daily-report.mjs +22 -0
  18. package/engine/scripts/engine-manifest.mjs +90 -0
  19. package/engine/scripts/flow-requirements.json +122 -99
  20. package/engine/scripts/full-exec-worker.mjs +251 -0
  21. package/engine/scripts/gen-preset-rows.mjs +1 -1
  22. package/engine/scripts/invoice_lip_runner.py +1 -0
  23. package/engine/scripts/invoice_runner.py +3 -1
  24. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  25. package/engine/scripts/lib/intel-card.mjs +43 -0
  26. package/engine/scripts/lib/invoice_names.py +23 -0
  27. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  28. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  29. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  30. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  31. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  32. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  33. package/engine/scripts/lib/ml-items.mjs +40 -0
  34. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  35. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  36. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  37. package/engine/scripts/line_pack.py +196 -0
  38. package/engine/scripts/ml-ads-advice.mjs +140 -0
  39. package/engine/scripts/ml-ads.mjs +40 -0
  40. package/engine/scripts/ml-category-baseline.mjs +174 -0
  41. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  42. package/engine/scripts/ml-insight-run.sh +183 -0
  43. package/engine/scripts/ml-insight-timers.sh +224 -0
  44. package/engine/scripts/ml-listing-audit.mjs +170 -0
  45. package/engine/scripts/ml-market-matrix.mjs +84 -0
  46. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  47. package/engine/scripts/ml-messages.mjs +145 -0
  48. package/engine/scripts/npm-publish-argent.mjs +14 -0
  49. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  50. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  51. package/engine/scripts/ops-digest.mjs +98 -0
  52. package/engine/scripts/ops-verify.mjs +67 -0
  53. package/engine/scripts/orchestrator.py +410 -20
  54. package/engine/scripts/orchestrator_br.py +146 -4
  55. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  56. package/engine/scripts/publish-engine.mjs +111 -0
  57. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  58. package/engine/scripts/skuflow_invoice_runner.py +24 -3
  59. package/engine/scripts/vertical-lint.mjs +12 -1
  60. package/engine/scripts/wenyao_fill_template.py +52 -15
  61. package/engine/scripts/wenyao_run.py +2 -1
  62. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  63. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  64. package/engine/skills/ml-invoice/SKILL.md +2 -2
  65. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  66. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  67. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  68. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  69. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  70. package/engine/version.mjs +1 -1
  71. package/engine/verticals/README.md +7 -0
  72. package/engine/verticals/_engine-words.baseline.txt +27 -59
  73. package/engine/verticals/mercadolibre/manifest.json +132 -6
  74. package/package.json +1 -1
@@ -0,0 +1,774 @@
1
+ /**
2
+ * ml-market-core.mjs —— 市场快照(自有店铺在售 + 客户指定竞品)的**纯逻辑**(L1 执行内核)。
3
+ *
4
+ * ## 干什么
5
+ * 把官方 item / reviews 数据归一化成**一行一个 item 的快照记录**(JSONL),并基于**连续快照**
6
+ * 计算差值、估算「近 N 天销量」。为后续竞品矩阵 / 销量趋势提供数据底座。
7
+ *
8
+ * ## 采集边界(降 ToS 风险,硬写在本文件之外由 CLI 执行)
9
+ * · 只采「自有店铺在售 item」+「客户显式给出的竞品 item ID 清单」;
10
+ * · ⛔ 不采搜索结果页、⛔ 不写客户任何系统(本 lib 零 IO、零网络,CLI 只发 GET)。
11
+ *
12
+ * ## 口径(必须写死,输出必须标注)
13
+ * 官方 `sold_quantity` / `available_quantity` 是**分桶参考值**,不是精确值:
14
+ * · 0–4 为精确值;
15
+ * · ≥5 返回的是某个**档位参考值** r(例:6–25→5、26–50→25、501–5000→500);
16
+ * raw=5 因「真实 5」与「6–25」都返回 5 ⇒ 真实区间 [5,25],无法再细分;
17
+ * · 参考值 r 的**真实值区间**由 {@link bucketOfQuantity} 给出(整数闭区间)⇒ 单次快照只能给区间,给不出精确数。
18
+ * 因此「近 N 天销量」**只能靠连续快照差值估算**,输出一律标「估算」,并且:
19
+ * · 两次快照落在同一桶内 ⇒ 只能给出很宽的区间(低置信),不冒充精确;
20
+ * · 缺参考值 / 参考值下降(下架/重置/平台调整)⇒ **不估算**(返回原因,不伪造 0)。
21
+ *
22
+ * ## 纪律
23
+ * · **纯 L1**:零 import(无 IO、无网络、无宿主模块);HTTP 入口 `apiGet` 由调用方注入;
24
+ * · 容错:官方字段随站点/版本缺失 ⇒ 一律软降级为 null + 记 `missing`,不猜数。
25
+ */
26
+
27
+ import { fetchItemsBatched } from './ml-items.mjs'
28
+
29
+
30
+ /** JSONL 行 schema 标识(读历史时可据此拒绝异形数据)。 */
31
+ export const SNAPSHOT_SCHEMA = 'argent-ml-market-snapshot/1'
32
+
33
+ /**
34
+ * 官方分桶档位(参考值,升序;0–4 精确值不在表内)。
35
+ * 依据:本任务口径的已知样例(6–25→5、26–50→25、501–5000→500)+公开观测到的更高档位
36
+ * (5000/10000/50000/100000/250000)。⚠️ 平台若调整档位,只需改这一处;
37
+ * 测试锁的是**口径含义**(参考值 ⇒ 整数闭区间 + 「只能估算」),不是某个具体数字的官方性。
38
+ */
39
+ export const QUANTITY_LADDER = Object.freeze([5, 25, 50, 100, 250, 500, 5000, 10000, 50000, 100000, 250000])
40
+
41
+ /** 精确值上限(含):0–4 的官方已售/库存可视为精确值(raw=5 开始进入分桶参考值)。 */
42
+ export const EXACT_MAX = 4
43
+
44
+ /** 口径常量(写死;CLI / 日报 / 角色回复都从这里取,⛔ 不要各处复制一套)。 */
45
+ export const CALIBER = Object.freeze({
46
+ binnedFields: Object.freeze(['sold_quantity', 'available_quantity']),
47
+ exactMax: EXACT_MAX,
48
+ ladder: QUANTITY_LADDER,
49
+ estimateWindowDays: 30,
50
+ /** 单条快照口径说明。 */
51
+ note:
52
+ '官方 sold_quantity / available_quantity 是**分桶参考值**(不是精确值;如 6–25→5、26–50→25、' +
53
+ '501–5000→500;0–4 为精确值,raw=5 因「真实 5」与「6–25」都返回 5 ⇒ 真实区间 5–25,无法再细分)。',
54
+ /** 估算口径说明。 */
55
+ estimateNote:
56
+ '「近 N 天销量」**只能由连续快照差值估算**,输出一律标「估算」,不可当作平台精确销量;' +
57
+ '同一分桶内无法给出可用估计。',
58
+ })
59
+
60
+ // ── 小工具(纯函数)────────────────────────────────────────────
61
+ const str = (x) => String(x == null ? '' : x).trim()
62
+
63
+ /** 数字或 null(空串/NaN/Infinity 一律 null,不落 0 —— 0 有业务含义)。 */
64
+ export function numOrNull(x) {
65
+ if (x == null || x === '') return null
66
+ const n = Number(x)
67
+ return Number.isFinite(n) ? n : null
68
+ }
69
+
70
+ const round1 = (x) => Math.round(Number(x) * 10) / 10
71
+ const DAY_MS = 86400000
72
+
73
+ /** ISO 时间 → 毫秒(不可解析 ⇒ null)。 */
74
+ export function toMs(x) {
75
+ if (x == null || x === '') return null
76
+ const n = typeof x === 'number' ? x : Date.parse(String(x))
77
+ return Number.isFinite(n) ? n : null
78
+ }
79
+
80
+ /** 两条记录的时间跨度(天,可小数;任一不可解析 ⇒ null)。 */
81
+ export function daysBetween(fromCapturedAt, toCapturedAt) {
82
+ const a = toMs(fromCapturedAt)
83
+ const b = toMs(toCapturedAt)
84
+ if (a == null || b == null) return null
85
+ return (b - a) / DAY_MS
86
+ }
87
+
88
+ /**
89
+ * 纯函数:把官方已售/库存**原始值**解释成真实值区间(闭区间整数,`maxInclusive=null` 表示最高档无上界)。
90
+ * 语义(口径写死):
91
+ * · raw 0–4 ⇒ 精确值 [v,v];
92
+ * · raw 5 ⇒ 参考值 5,真实值 ∈ [5,25](真实 5 与 6–25 都返回 5,无法区分);
93
+ * · raw r(r≥25 的档位)⇒ 真实值 ∈ [r+1, 下一档];
94
+ * · 非标准档位值(理论上不该出现,如 501/1000)⇒ 向下归入最近参考档,并标记 `known=false`。
95
+ * @returns {{raw:number|null, ref:number|null, exact:boolean, known:boolean,
96
+ * min:number|null, max:number|null, ladderIndex:number,
97
+ * range:{min:number|null,max:number|null}|null, label:string, note:string}}
98
+ */
99
+ export function bucketOfQuantity(value) {
100
+ const raw = numOrNull(value)
101
+ if (raw == null) {
102
+ return {
103
+ raw: null, ref: null, exact: false, known: false,
104
+ min: null, max: null, ladderIndex: -1,
105
+ range: null, label: '—', note: '未取到',
106
+ }
107
+ }
108
+ const v = Math.trunc(raw)
109
+ if (v < 5) {
110
+ return {
111
+ raw, ref: v, exact: true, known: true,
112
+ min: v, max: v, ladderIndex: -1,
113
+ range: { min: v, max: v },
114
+ label: `${v}(精确)`, note: '0–4 为精确值',
115
+ }
116
+ }
117
+ // 落到「最后一个 ≤ v 的档位」;raw=5..24 与 raw=5 同一个桶(参考值 5)
118
+ let idx = -1
119
+ for (let i = 0; i < QUANTITY_LADDER.length; i++) {
120
+ if (v >= QUANTITY_LADDER[i]) idx = i
121
+ else break
122
+ }
123
+ const ref = QUANTITY_LADDER[idx]
124
+ const max = idx + 1 < QUANTITY_LADDER.length ? QUANTITY_LADDER[idx + 1] : null
125
+ const min = ref === 5 ? 5 : ref + 1
126
+ const known = v === ref
127
+ return {
128
+ raw, ref, exact: false, known,
129
+ min, max, ladderIndex: idx,
130
+ range: { min, max },
131
+ label: max == null ? `>${ref}(参考值 ${ref})` : `${min}–${max}(参考值 ${ref})`,
132
+ note: known ? '官方分桶参考值' : '非标准档位 ⇒ 向下归入最近参考档',
133
+ }
134
+ }
135
+
136
+ /**
137
+ * 纯函数:归一化官方 reviews 响应(多种形状容错)。
138
+ * 形状兼容:`{rating_average, paging:{total}}` / `{rating_average, total}` /
139
+ * `{reviews:[{rating}], paging:{total}}` / 空对象。
140
+ * ⚠️ 官方平均分缺失时,用**本页 reviews 的算术平均**兜底,并标 `ratingSource='sample-average'`
141
+ * (样本近似,不是官方全量均分);`reviewsCount` 只认官方 total,缺了就 null(不拿页大小冒充总数)。
142
+ */
143
+ export function normalizeReviews(raw) {
144
+ const out = { rating: null, reviewsCount: null, ratingSample: 0, ratingSource: '' }
145
+ if (!raw || typeof raw !== 'object') return out
146
+ const reviews = Array.isArray(raw.reviews) ? raw.reviews : []
147
+ out.ratingSample = reviews.length
148
+ const avgRaw = [raw.rating_average, raw.ratingAverage, raw.average_rating, raw.rating]
149
+ .map(numOrNull)
150
+ .find((x) => x != null && x >= 0 && x <= 5)
151
+ if (avgRaw != null) {
152
+ out.rating = round1(avgRaw)
153
+ out.ratingSource = 'official-average'
154
+ } else if (reviews.length) {
155
+ const samples = reviews
156
+ .map((r) => numOrNull(r && (r.rating != null ? r.rating : r.rate)))
157
+ .filter((x) => x != null && x >= 0 && x <= 5)
158
+ if (samples.length) {
159
+ out.rating = round1(samples.reduce((s, x) => s + x, 0) / samples.length)
160
+ out.ratingSource = 'sample-average'
161
+ }
162
+ }
163
+ const total = [
164
+ raw.paging && raw.paging.total, raw.paging && raw.paging.total_count,
165
+ raw.total, raw.reviews_count, raw.reviewsCount,
166
+ ].map(numOrNull).find((x) => x != null && x >= 0)
167
+ out.reviewsCount = total == null ? null : Math.trunc(total)
168
+ return out
169
+ }
170
+
171
+ /**
172
+ * 纯函数:解析 `--items-file`(只收**竞品 item ID 清单**)。
173
+ * 兼容:`["MLM1"]` / `[{id}]` / `{items:[...]}` / `{itemIds:[...]}` / `{ids:[...]}` / `{competitors:[...]}`。
174
+ * @returns {{ids:string[], skipped:number}}
175
+ */
176
+ export function parseItemsDoc(doc) {
177
+ const list = Array.isArray(doc)
178
+ ? doc
179
+ : (doc && (doc.itemIds || doc.items || doc.competitors || doc.ids)) || []
180
+ const ids = []
181
+ let skipped = 0
182
+ for (const entry of Array.isArray(list) ? list : []) {
183
+ const id = typeof entry === 'string'
184
+ ? entry
185
+ : (entry && (entry.itemId || entry.item_id || entry.id))
186
+ const s = str(id)
187
+ if (!s) { skipped++; continue }
188
+ if (!ids.includes(s)) ids.push(s)
189
+ }
190
+ return { ids, skipped }
191
+ }
192
+
193
+ /** 纯函数:item ID 的站点前缀(如 `MLM123` → `MLM`;不合形状 ⇒ '')。 */
194
+ export function siteOfItemId(id) {
195
+ const m = /^([A-Za-z]{3})\d+$/.exec(str(id))
196
+ return m ? m[1].toUpperCase() : ''
197
+ }
198
+
199
+ /**
200
+ * 纯函数:一条官方 item(+ reviews)→ 一行快照记录(JSONL 可序列化)。
201
+ * 缺字段一律 null + 记入 `missing`,⛔ 不补 0、不猜值。
202
+ * @param {object} raw 官方 item body(也兼容 `{body:{...}}` 批响应行)
203
+ * @param {{capturedAt?:string, store?:string, site?:string, source?:string,
204
+ * currency?:string, itemId?:string, reviews?:object, errors?:string[]}} opts
205
+ */
206
+ export function normalizeItem(raw, opts = {}) {
207
+ const src = raw && raw.body && typeof raw.body === 'object' ? raw.body : (raw || {})
208
+ const reviews = normalizeReviews(opts.reviews)
209
+ const capturedAt = str(opts.capturedAt) || new Date().toISOString()
210
+ const itemId = str(src.id) || str(opts.itemId)
211
+ const price = numOrNull(src.price)
212
+ const currency = str(src.currency_id) || str(opts.currency)
213
+ const status = str(src.status)
214
+ const availableRaw = numOrNull(src.available_quantity)
215
+ const soldRaw = numOrNull(src.sold_quantity)
216
+ const logisticType = str(src.shipping && src.shipping.logistic_type) || str(src.logistic_type)
217
+ const missing = []
218
+ if (!itemId) missing.push('itemId')
219
+ if (price == null) missing.push('price')
220
+ if (!currency) missing.push('currency')
221
+ if (availableRaw == null) missing.push('available_quantity')
222
+ if (soldRaw == null) missing.push('sold_quantity')
223
+ if (reviews.rating == null) missing.push('rating')
224
+ if (reviews.reviewsCount == null) missing.push('reviews_count')
225
+ if (!status) missing.push('status')
226
+ return {
227
+ schema: SNAPSHOT_SCHEMA,
228
+ capturedAt,
229
+ store: str(opts.store),
230
+ site: str(opts.site),
231
+ source: str(opts.source) || 'own',
232
+ itemId,
233
+ title: str(src.title),
234
+ category_id: str(src.category_id) || str(src.categoryId) || '',
235
+ price,
236
+ currency,
237
+ status,
238
+ logistic_type: logisticType,
239
+ permalink: str(src.permalink),
240
+ available_quantity: availableRaw,
241
+ sold_quantity: soldRaw,
242
+ available_bucket: bucketOfQuantity(availableRaw),
243
+ sold_bucket: bucketOfQuantity(soldRaw),
244
+ rating: reviews.rating,
245
+ rating_sample: reviews.ratingSample,
246
+ rating_source: reviews.ratingSource,
247
+ reviews_count: reviews.reviewsCount,
248
+ missing,
249
+ errors: (Array.isArray(opts.errors) ? opts.errors : []).map((e) => str(e).slice(0, 200)).filter(Boolean),
250
+ }
251
+ }
252
+
253
+ /** 纯函数:JSONL 文本 → 快照记录(坏行记 errors,不抛、不静默)。 */
254
+ export function parseSnapshotJsonl(text) {
255
+ const records = []
256
+ const errors = []
257
+ const lines = String(text == null ? '' : text).split('\n')
258
+ lines.forEach((line, i) => {
259
+ const t = line.trim()
260
+ if (!t) return
261
+ try {
262
+ const rec = JSON.parse(t)
263
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec)) errors.push({ line: i + 1, error: '不是 JSON 对象' })
264
+ else if (!str(rec.itemId)) errors.push({ line: i + 1, error: '缺 itemId' })
265
+ else records.push(rec)
266
+ } catch (e) {
267
+ errors.push({ line: i + 1, error: str(e && e.message).slice(0, 120) || 'JSON 解析失败' })
268
+ }
269
+ })
270
+ return { records, errors }
271
+ }
272
+
273
+ /**
274
+ * 纯函数:两个分桶参考值 → 差值区间(用于「两次快照的增量」)。
275
+ * 数学:prev 真实值 ∈ [pMin,pMax],curr ∈ [cMin,cMax] ⇒ delta ∈ [cMin-pMax, cMax-pMin];
276
+ * 累计已售单调 ⇒ 下界再与 0 取大。
277
+ * @returns {{available:boolean, reason:string, exact:boolean, sameBucket:boolean,
278
+ * fromRef:number|null, toRef:number|null, fromRaw:number|null, toRaw:number|null,
279
+ * min:number|null, max:number|null, crossed:number, from:object, to:object}}
280
+ */
281
+ export function quantityDelta(prevValue, currValue) {
282
+ const prev = bucketOfQuantity(prevValue)
283
+ const curr = bucketOfQuantity(currValue)
284
+ const base = {
285
+ available: false, reason: '', exact: false, sameBucket: false,
286
+ fromRef: prev.ref, toRef: curr.ref, fromRaw: prev.raw, toRaw: curr.raw,
287
+ min: null, max: null, crossed: 0, from: prev, to: curr,
288
+ }
289
+ if (prev.raw == null || curr.raw == null) return { ...base, reason: 'missing' }
290
+ if (curr.raw < prev.raw) return { ...base, reason: 'decrease' }
291
+ if (prev.exact && curr.exact) {
292
+ const delta = curr.raw - prev.raw
293
+ return { ...base, available: true, exact: true, min: delta, max: delta }
294
+ }
295
+ const pLo = prev.min
296
+ const pHi = prev.max // null = 最高档(无上界)
297
+ const cLo = curr.min
298
+ const cHi = curr.max
299
+ const sameBucket = prev.ref === curr.ref && prev.ladderIndex === curr.ladderIndex
300
+ const min = pHi == null ? 0 : Math.max(0, cLo - pHi)
301
+ const max = cHi == null ? null : cHi - pLo
302
+ return {
303
+ ...base,
304
+ available: true,
305
+ exact: false,
306
+ sameBucket,
307
+ min,
308
+ max,
309
+ crossed: Math.max(0, curr.ladderIndex - prev.ladderIndex),
310
+ }
311
+ }
312
+
313
+ /**
314
+ * 纯函数:两次快照 → 逐字段 diff + 已售/库存增量 + 月销估算。
315
+ * @param {object} prev 前一快照记录
316
+ * @param {object} curr 后一快照记录
317
+ */
318
+ export function diffSnapshots(prev, curr) {
319
+ const p = prev || {}
320
+ const c = curr || {}
321
+ const scalar = (key, label) => {
322
+ const from = p[key] == null ? null : p[key]
323
+ const to = c[key] == null ? null : c[key]
324
+ return { key, label, from, to, changed: JSON.stringify(from) !== JSON.stringify(to) }
325
+ }
326
+ const numeric = (key, label) => {
327
+ const diff = scalar(key, label)
328
+ const from = numOrNull(diff.from)
329
+ const to = numOrNull(diff.to)
330
+ return { ...diff, from, to, delta: from != null && to != null ? round1(to - from) : null }
331
+ }
332
+ const sold = quantityDelta(p.sold_quantity, c.sold_quantity)
333
+ const available = quantityDelta(p.available_quantity, c.available_quantity)
334
+ return {
335
+ schema: SNAPSHOT_SCHEMA,
336
+ itemId: str(c.itemId) || str(p.itemId),
337
+ fromCapturedAt: str(p.capturedAt),
338
+ toCapturedAt: str(c.capturedAt),
339
+ days: daysBetween(p.capturedAt, c.capturedAt),
340
+ price: numeric('price', '价格'),
341
+ status: scalar('status', '状态'),
342
+ logistic_type: scalar('logistic_type', '履约类型'),
343
+ rating: numeric('rating', '评分'),
344
+ reviews_count: numeric('reviews_count', '评价数'),
345
+ available_quantity: available,
346
+ sold_quantity: sold,
347
+ estimate: estimateSalesBetween(p, c),
348
+ }
349
+ }
350
+
351
+ /**
352
+ * 纯函数:两次快照的已售差值 → 月销估算(**估算**,永远不是平台精确销量)。
353
+ * @param {object} prev 前一快照记录
354
+ * @param {object} curr 后一快照记录
355
+ * @param {{minSpanDays?:number}} opts
356
+ * @returns {{ok:boolean, reason:string, days:number|null, monthly:{min:number|null,max:number|null,mid:number|null,windowDays:number}|null,
357
+ * confidence:'high'|'medium'|'low'|'none', sold:object, note:string}}
358
+ */
359
+ export function estimateSalesBetween(prev, curr, opts = {}) {
360
+ const sold = quantityDelta(prev && prev.sold_quantity, curr && curr.sold_quantity)
361
+ const days = daysBetween(prev && prev.capturedAt, curr && curr.capturedAt)
362
+ const out = {
363
+ ok: false, reason: '', days, monthly: null,
364
+ confidence: 'none', sold, note: '',
365
+ }
366
+ if (!sold.available) {
367
+ out.reason = sold.reason || 'missing'
368
+ out.note = sold.reason === 'decrease'
369
+ ? '已售参考值下降(下架/换 listing/平台调整)⇒ 不做估算'
370
+ : '缺 sold_quantity 快照 ⇒ 无法估算(不伪造 0)'
371
+ return out
372
+ }
373
+ const minSpan = numOrNull(opts.minSpanDays)
374
+ if (days == null || days < (minSpan == null ? 1 : Math.max(0, minSpan))) {
375
+ out.reason = 'span_too_short'
376
+ out.note = '两次快照相隔不足 1 天 ⇒ 不外推月销'
377
+ return out
378
+ }
379
+ const scale = 30 / days
380
+ const toMonthly = (x) => (x == null ? null : round1(x * scale))
381
+ out.monthly = {
382
+ min: toMonthly(sold.min),
383
+ max: toMonthly(sold.max),
384
+ mid: sold.min != null && sold.max != null ? toMonthly((sold.min + sold.max) / 2) : null,
385
+ windowDays: 30,
386
+ }
387
+ out.ok = true
388
+ out.confidence = sold.exact
389
+ ? 'high'
390
+ : sold.sameBucket
391
+ ? 'low'
392
+ : (sold.max == null || days < 7 ? 'low' : 'medium')
393
+ out.note = sold.sameBucket
394
+ ? '两次快照同桶(未跨档)⇒ 只能给宽区间,低置信'
395
+ : (sold.max == null ? '已售参考值处于最高档(无上界)⇒ 低置信' : '按分桶差值区间中点估算')
396
+ return out
397
+ }
398
+
399
+ /** 纯函数:某个 item 的历史记录 → 选基线 + 估算近 N 天销量。 */
400
+ export function estimateItemMonthly(records, opts = {}) {
401
+ const windowDays = Math.max(1, Math.round(numOrNull(opts.days) || CALIBER.estimateWindowDays))
402
+ const rows = (Array.isArray(records) ? records : [])
403
+ .filter((r) => r && toMs(r.capturedAt) != null && numOrNull(r.sold_quantity) != null)
404
+ .slice()
405
+ .sort((a, b) => toMs(a.capturedAt) - toMs(b.capturedAt))
406
+ const out = {
407
+ ok: false, reason: '', windowDays, spanDays: null,
408
+ baseline: null, latest: null, estimate: null, needDays: 0,
409
+ }
410
+ if (!rows.length) {
411
+ out.reason = 'no_history'
412
+ return out
413
+ }
414
+ const latest = rows[rows.length - 1]
415
+ out.latest = { capturedAt: str(latest.capturedAt), sold_quantity: numOrNull(latest.sold_quantity) }
416
+ const latestMs = toMs(latest.capturedAt)
417
+ const target = latestMs - windowDays * DAY_MS
418
+ let baseline = null
419
+ for (const row of rows) {
420
+ if (toMs(row.capturedAt) <= target) baseline = row
421
+ else break
422
+ }
423
+ if (!baseline) {
424
+ const oldest = toMs(rows[0].capturedAt)
425
+ const haveDays = (latestMs - oldest) / DAY_MS
426
+ out.reason = 'history_insufficient'
427
+ out.needDays = round1(Math.max(0, windowDays - haveDays))
428
+ out.haveDays = round1(haveDays)
429
+ return out
430
+ }
431
+ out.baseline = { capturedAt: str(baseline.capturedAt), sold_quantity: numOrNull(baseline.sold_quantity) }
432
+ out.spanDays = round1(daysBetween(baseline.capturedAt, latest.capturedAt))
433
+ const est = estimateSalesBetween(baseline, latest, opts)
434
+ out.estimate = est
435
+ out.ok = est.ok
436
+ out.reason = est.ok ? '' : est.reason
437
+ return out
438
+ }
439
+
440
+ /** 纯函数:一次采集的记录集合 → 计数摘要(自有用/竞品/present 字段覆盖)。 */
441
+ export function summarizeRecords(records = []) {
442
+ const rows = Array.isArray(records) ? records : []
443
+ const status = {}
444
+ const missing = {}
445
+ let own = 0
446
+ let competitor = 0
447
+ for (const r of rows) {
448
+ if (!r) continue
449
+ if (r.source === 'competitor') competitor++
450
+ else own++
451
+ const st = str(r.status) || 'unknown'
452
+ status[st] = (status[st] || 0) + 1
453
+ for (const f of r.missing || []) missing[f] = (missing[f] || 0) + 1
454
+ }
455
+ const times = rows.map((r) => toMs(r && r.capturedAt)).filter((x) => x != null)
456
+ return {
457
+ total: rows.length,
458
+ own,
459
+ competitor,
460
+ status,
461
+ missing,
462
+ firstCapturedAt: times.length ? new Date(Math.min(...times)).toISOString() : '',
463
+ lastCapturedAt: times.length ? new Date(Math.max(...times)).toISOString() : '',
464
+ }
465
+ }
466
+
467
+ /** 纯函数:口径说明(CLI / 日报 / 角色回复共用的两行)。 */
468
+ export function caliberLines() {
469
+ return [
470
+ `口径:${CALIBER.note}`,
471
+ `口径:${CALIBER.estimateNote}`,
472
+ ]
473
+ }
474
+
475
+ const CONFIDENCE_LABEL = { high: '高', medium: '中', low: '低', none: '无' }
476
+
477
+ /** 纯函数:把一条月销估算渲染成人类可读文本(永不把估算写成精确值)。
478
+ * 兼容 `estimateSalesBetween` 与 `estimateItemMonthly`(后者包了一层 `.estimate`)。 */
479
+ export function formatEstimate(est) {
480
+ if (!est) return '—(无历史)'
481
+ const inner = est.estimate && typeof est.estimate === 'object' ? est.estimate : est
482
+ const reason = est.ok === false || !inner.ok ? (est.reason || inner.reason) : ''
483
+ if (!inner.ok) {
484
+ if (reason === 'history_insufficient') {
485
+ const have = est.haveDays == null ? '' : `,现有 ${est.haveDays} 天`
486
+ return `—(历史不足 ${est.windowDays || 30} 天${have})`
487
+ }
488
+ if (reason === 'no_history') return '—(无历史)'
489
+ if (reason === 'decrease') return '—(参考值下降,不估算)'
490
+ if (reason === 'missing') return '—(缺已售参考值,不估算)'
491
+ if (reason === 'span_too_short') return '—(快照间隔过短)'
492
+ return '—(不可估算)'
493
+ }
494
+ const m = inner.monthly || {}
495
+ const range = m.min == null ? '' : (m.max == null ? `≥${m.min}` : `${m.min}–${m.max}`)
496
+ const main = m.mid == null ? (m.min == null ? '—' : `≥${m.min}`) : m.mid
497
+ return `≈${main}/月(区间 ${range}|估算·${CONFIDENCE_LABEL[inner.confidence] || '低'}置信)`
498
+ }
499
+
500
+ /** 纯函数:单店快照报告(默认人类可读输出;`--json` 走结构化)。 */
501
+ export function renderStoreReport({
502
+ store = '', site = '', outFile = '', items = [], estimates = {}, history = null, estimateWindowDays = 30,
503
+ } = {}) {
504
+ const rows = Array.isArray(items) ? items : []
505
+ const sum = summarizeRecords(rows)
506
+ const lines = [`## 🛒 市场快照 · ${store || '(未命名店铺)'}${site ? `(${site})` : ''}`]
507
+ for (const l of caliberLines()) lines.push(`> ${l}`)
508
+ const hist = history
509
+ ? `历史 ${history.records || 0} 条${history.firstCapturedAt ? `(${String(history.firstCapturedAt).slice(0, 10)} → ${String(history.lastCapturedAt).slice(0, 10)})` : ''}`
510
+ : ''
511
+ lines.push(`商品 ${sum.total}(自有 ${sum.own} / 竞品 ${sum.competitor})${outFile ? `· 落盘 ${outFile}` : ''}${hist ? ` · ${hist}` : ''}`)
512
+ if (!rows.length) {
513
+ lines.push('未采到任何 item(自有在售为 0 且无竞品清单)')
514
+ } else {
515
+ lines.push('')
516
+ lines.push(`| item | 来源 | 价格 | 状态 | 累计已售(参考值/区间) | 库存(参考值/区间) | 评分 | 近 ${estimateWindowDays} 天销量(估算) |`)
517
+ lines.push('|---|---|---|---|---|---|---|---|')
518
+ for (const it of rows) {
519
+ const sold = it.sold_bucket || bucketOfQuantity(it.sold_quantity)
520
+ const avail = it.available_bucket || bucketOfQuantity(it.available_quantity)
521
+ const title = it.title ? ` ${String(it.title).slice(0, 24)}` : ''
522
+ const rating = it.rating == null ? '—' : `${it.rating}${it.reviews_count == null ? '' : `(${it.reviews_count} 评)`}`
523
+ lines.push(
524
+ `| ${it.itemId || '—'}${title} | ${it.source === 'competitor' ? '竞品' : '自有'} | ` +
525
+ `${it.price == null ? '—' : `${it.price} ${it.currency || ''}`.trim()} | ${it.status || '—'} | ` +
526
+ `${sold.label} | ${avail.label} | ${rating} | ${formatEstimate(estimates[it.itemId])} |`,
527
+ )
528
+ }
529
+ const miss = Object.entries(sum.missing)
530
+ if (miss.length) lines.push(`\n⚠️ 缺字段计数:${miss.map(([k, n]) => `${k}×${n}`).join('、')}(缺字段不补数,尾部快照缺口会在这里显形)`)
531
+ const errCount = rows.reduce((n, r) => n + ((r.errors || []).length ? 1 : 0), 0)
532
+ if (errCount) lines.push(`⚠️ ${errCount} 个 item 带取数错误(已落快照并标 missing,不伪造数据)`)
533
+ }
534
+ return lines
535
+ }
536
+
537
+ // ══════════════════════════════════════════════════════════════════════
538
+ // 只读取数(HTTP 入口 `apiGet` 注入;端点路径与现有 listing 体检同一套)
539
+ // ══════════════════════════════════════════════════════════════════════
540
+
541
+ /** 自有店铺在售 item id(分页直到凑够 limit)。 */
542
+ export async function listActiveItemIds({ apiGet, token, uid, limit = 50 } = {}) {
543
+ if (typeof apiGet !== 'function') throw new Error('listActiveItemIds 需要注入 apiGet')
544
+ if (!uid) throw new Error('listActiveItemIds 需要 uid(店铺 user_id)')
545
+ const cap = Math.max(1, Math.min(200, numOrNull(limit) || 50))
546
+ const ids = []
547
+ let offset = 0
548
+ for (let page = 0; page < 20 && ids.length < cap; page++) {
549
+ const r = await apiGet(`/users/${encodeURIComponent(uid)}/items/search?status=active&limit=50&offset=${offset}`, token)
550
+ const rows = (r && (r.results || r.item_ids)) || []
551
+ if (!rows.length) break
552
+ for (const id of rows) if (ids.length < cap) ids.push(String(id))
553
+ const total = numOrNull(r && r.paging && r.paging.total)
554
+ offset += rows.length
555
+ if (total != null && offset >= total) break
556
+ }
557
+ return ids
558
+ }
559
+
560
+ /** 批量取 item 详情(每批 ≤20)。返回 `{id: {body}|{error}}`,不抛。 */
561
+ export async function fetchItemDetails({ apiGet, token, ids = [], batchSize = 20 } = {}) {
562
+ if (typeof apiGet !== 'function') throw new Error('fetchItemDetails 需要注入 apiGet')
563
+ const out = {}
564
+ const all = (Array.isArray(ids) ? ids : []).map((x) => String(x)).filter(Boolean)
565
+ const step = Math.max(1, Math.min(20, Math.trunc(numOrNull(batchSize) || 20)))
566
+ for (let i = 0; i < all.length; i += step) {
567
+ const chunk = all.slice(i, i + step)
568
+ // ⚠️ `ids` 逗号必须裸写(`%2C` ⇒ 403 ResourceDeprecated;2026-11-24 实测)
569
+ const attrs = 'id,title,price,currency_id,status,available_quantity,sold_quantity,permalink,shipping'
570
+ let rows = []
571
+ try {
572
+ // 2026-12-01:平台对部分 app 弃用 `/items?ids=`(403 ResourceDeprecated)⇒ 统一走"批量优先+单条兜底"
573
+ rows = await fetchItemsBatched({ apiGet, token, ids: chunk, attrs, batchSize: step })
574
+ } catch (e) {
575
+ for (const id of chunk) out[id] = { error: `批量取商品失败:${str(e && e.message).slice(0, 140)}` }
576
+ continue
577
+ }
578
+ const seen = new Set()
579
+ for (const row of rows) {
580
+ const body = row && row.body
581
+ const id = body && str(body.id)
582
+ if (!id) continue
583
+ seen.add(id)
584
+ if (row.code && row.code !== 200) out[id] = { body: { id }, error: `HTTP ${row.code} ${str(row.message || (body && body.error)).slice(0, 120)}` }
585
+ else out[id] = { body }
586
+ }
587
+ for (const id of chunk) if (!seen.has(id)) out[id] = { body: { id }, error: '商品不在批量返回中(可能已下架/无权限)' }
588
+ }
589
+ return out
590
+ }
591
+
592
+ /**
593
+ * 只读取数:自有在售 + 客户指定竞品 → 归一化快照记录。
594
+ * @param {{apiGet:Function, token:string, site:string, uid:string, store?:string,
595
+ * ownLimit?:number, competitorIds?:string[], withReviews?:boolean, capturedAt?:string}} p
596
+ * @returns {Promise<{items:Array, warnings:string[]}>}
597
+ */
598
+ export async function collectStoreSnapshot({
599
+ apiGet, token, site, uid, store = '', ownLimit = 50,
600
+ competitorIds = [], withReviews = true, capturedAt, currency = '',
601
+ } = {}) {
602
+ if (typeof apiGet !== 'function') throw new Error('collectStoreSnapshot 需要注入 apiGet')
603
+ const warnings = []
604
+ const stamp = str(capturedAt) || new Date().toISOString()
605
+ let ownIds = []
606
+ try {
607
+ ownIds = await listActiveItemIds({ apiGet, token, uid, limit: ownLimit })
608
+ } catch (e) {
609
+ warnings.push(`自有在售列表取数失败:${str(e && e.message).slice(0, 140)}`)
610
+ }
611
+ // 竞品清单先按站点前缀过滤(跨站点 ID 用本店 token 取会 403,提前跳过并明说)
612
+ const ownSet = new Set(ownIds)
613
+ const competitor = []
614
+ for (const rawId of competitorIds) {
615
+ const id = str(rawId)
616
+ if (!id || ownSet.has(id)) continue
617
+ const idSite = siteOfItemId(id)
618
+ if (site && idSite && idSite !== site) {
619
+ warnings.push(`跳过竞品 ${id}(站点 ${idSite} ≠ 店铺站点 ${site})`)
620
+ continue
621
+ }
622
+ if (!competitor.includes(id)) competitor.push(id)
623
+ }
624
+ const targets = [
625
+ ...ownIds.map((id) => ({ id, source: 'own' })),
626
+ ...competitor.map((id) => ({ id, source: 'competitor' })),
627
+ ]
628
+ if (!targets.length) return { items: [], warnings }
629
+
630
+ const details = await fetchItemDetails({ apiGet, token, ids: targets.map((t) => t.id) })
631
+ const items = []
632
+ for (const t of targets) {
633
+ const got = details[t.id] || { body: { id: t.id }, error: '未取到商品详情' }
634
+ const errors = got.error ? [got.error] : []
635
+ let reviewsRaw = null
636
+ // 商品本身已失败(404/无权限)⇒ 不再多打一次评价接口(省配额;错误不重复记两遍)
637
+ if (withReviews && !got.error) {
638
+ try {
639
+ reviewsRaw = await apiGet(`/reviews/item/${encodeURIComponent(t.id)}`, token)
640
+ } catch (e) {
641
+ errors.push(`评价取数失败:${str(e && e.message).slice(0, 140)}`)
642
+ }
643
+ }
644
+ items.push(normalizeItem(got.body || { id: t.id }, {
645
+ capturedAt: stamp,
646
+ store,
647
+ site,
648
+ source: t.source,
649
+ currency,
650
+ reviews: reviewsRaw,
651
+ errors,
652
+ }))
653
+ }
654
+ return { items, warnings }
655
+ }
656
+
657
+ /**
658
+ * 竞品矩阵/趋势(P2b,2026-11-26,纯函数):快照记录 → 矩阵 + 序列。
659
+ *
660
+ * 口径纪律(与 T4 一致):
661
+ * · 销量/库存来自平台**分桶参考值**(`sold_bucket`/`available_bucket`),界面必须标"估算/档位";
662
+ * · 趋势**从接入日起**(没有历史快照就没有点),⛔ 不伪造 2 年历史;
663
+ * · 自有 vs 竞品按 `source`(`own` / 其他=竞品)。
664
+ *
665
+ * @param {Array<object>} records parseSnapshotJsonl(...).records
666
+ * @param {{maxSeries?:number, maxItems?:number}} [opts]
667
+ */
668
+ export function buildMarketMatrix(records = [], opts = {}) {
669
+ const maxSeries = Math.max(2, Math.min(120, Number(opts.maxSeries) || 60))
670
+ const maxItems = Math.max(1, Math.min(200, Number(opts.maxItems) || 200))
671
+ const recs = (Array.isArray(records) ? records : []).filter((r) => r && r.itemId)
672
+ const byCap = new Map()
673
+ for (const r of recs) {
674
+ const cap = String(r.capturedAt || '')
675
+ if (!cap) continue
676
+ if (!byCap.has(cap)) byCap.set(cap, [])
677
+ byCap.get(cap).push(r)
678
+ }
679
+ const caps = [...byCap.keys()].sort()
680
+ const lastCap = caps[caps.length - 1] || ''
681
+ const prevCap = caps.length > 1 ? caps[caps.length - 2] : ''
682
+
683
+ const byItem = new Map()
684
+ for (const r of recs) {
685
+ const id = String(r.itemId)
686
+ if (!byItem.has(id)) byItem.set(id, { id, title: '', role: String(r.source) === 'own' ? 'own' : 'competitor', site: r.site || '', series: [] })
687
+ const it = byItem.get(id)
688
+ if (r.title && !it.title) it.title = String(r.title)
689
+ it.series.push({ at: String(r.capturedAt || ''), price: Number.isFinite(Number(r.price)) ? Number(r.price) : null, rating: Number.isFinite(Number(r.rating)) ? Number(r.rating) : null, soldBucket: r.sold_bucket || '', availBucket: r.available_bucket || '', reviews: Number(r.reviews_count) || 0 })
690
+ }
691
+
692
+ const latestByItem = new Map()
693
+ for (const r of (byCap.get(lastCap) || [])) latestByItem.set(String(r.itemId), r)
694
+ const prevByItem = new Map()
695
+ for (const r of (byCap.get(prevCap) || [])) prevByItem.set(String(r.itemId), r)
696
+
697
+ const items = []
698
+ for (const it of byItem.values()) {
699
+ const series = it.series.sort((a, b) => (a.at < b.at ? -1 : 1)).slice(-maxSeries)
700
+ const cur = latestByItem.get(it.id) || {}
701
+ const prev = prevByItem.get(it.id) || {}
702
+ const price = Number.isFinite(Number(cur.price)) ? Number(cur.price) : null
703
+ const prevPrice = Number.isFinite(Number(prev.price)) ? Number(prev.price) : null
704
+ const rating = Number.isFinite(Number(cur.rating)) ? Number(cur.rating) : null
705
+ const prevRating = Number.isFinite(Number(prev.rating)) ? Number(prev.rating) : null
706
+ const priceDeltaPct = price != null && prevPrice ? Math.round(((price - prevPrice) / prevPrice) * 1000) / 1000 : null
707
+ const ratingDelta = rating != null && prevRating != null ? Math.round((rating - prevRating) * 100) / 100 : null
708
+ items.push({
709
+ id: it.id, title: it.title || (cur.title ? String(cur.title) : ''), role: it.role, site: it.site || String(cur.site || ''),
710
+ price, prevPrice, priceDeltaPct, rating, prevRating, ratingDelta,
711
+ soldBucket: String(cur.sold_bucket || ''), availBucket: String(cur.available_bucket || ''),
712
+ reviews: Number(cur.reviews_count) || 0,
713
+ firstSeen: series[0]?.at ? String(series[0].at).slice(0, 10) : '',
714
+ lastSeen: series[series.length - 1]?.at ? String(series[series.length - 1].at).slice(0, 10) : '',
715
+ series,
716
+ })
717
+ }
718
+ items.sort((a, b) => (a.role === b.role ? (Number(b.price) || 0) - (Number(a.price) || 0) : a.role === 'own' ? -1 : 1))
719
+ const own = items.filter((x) => x.role === 'own')
720
+ const comps = items.filter((x) => x.role !== 'own').slice(0, maxItems)
721
+ const avg = (arr, k) => { const v = arr.map((x) => Number(x[k])).filter((n) => Number.isFinite(n)); return v.length ? Math.round((v.reduce((a, b) => a + b, 0) / v.length) * 100) / 100 : null }
722
+ const ownAvg = avg(own, 'price')
723
+ const compAvg = avg(comps, 'price')
724
+ const cheaperCount = ownAvg == null ? null : comps.filter((c) => Number(c.price) > 0 && ownAvg > Number(c.price)).length
725
+
726
+ return {
727
+ store: String(records[0]?.store || ''), site: String(records[0]?.site || ''),
728
+ capturedAt: lastCap, prevCapturedAt: prevCap, snapshots: caps.length,
729
+ items: [...own, ...comps],
730
+ summary: {
731
+ competitors: comps.length, own: own.length, cheaperCount,
732
+ ownAvgPrice: ownAvg, competitorAvgPrice: compAvg,
733
+ updatedAt: lastCap, historyFrom: caps[0] ? String(caps[0]).slice(0, 10) : '',
734
+ },
735
+ }
736
+ }
737
+
738
+ /** Bridge 上报 payload(ERP「智能分析 → 竞品矩阵」tab 用;字段即契约)。 */
739
+ export function buildMarketBridgePayload(matrix, { days = 30 } = {}) {
740
+ const m = matrix || {}
741
+ return {
742
+ store: String(m.store || ''), site: String(m.site || ''),
743
+ capturedAt: String(m.capturedAt || ''), days: Number(days) || 30,
744
+ items: (m.items || []).map((x) => ({
745
+ id: String(x.id || ''), role: x.role === 'own' ? 'own' : 'competitor', title: String(x.title || '').slice(0, 120),
746
+ price: x.price ?? null, prevPrice: x.prevPrice ?? null, priceDeltaPct: x.priceDeltaPct ?? null,
747
+ rating: x.rating ?? null, prevRating: x.prevRating ?? null, ratingDelta: x.ratingDelta ?? null,
748
+ soldBucket: String(x.soldBucket || ''), availBucket: String(x.availBucket || ''), firstSeen: String(x.firstSeen || ''),
749
+ series: (x.series || []).slice(0, 60).map((p) => ({ at: String(p.at || ''), price: p.price ?? null, rating: p.rating ?? null })),
750
+ })),
751
+ summary: { ...(m.summary || {}) },
752
+ }
753
+ }
754
+
755
+ /** 纯函数:矩阵 → 中文卡片行(CLI/角色回复)。 */
756
+ export function marketMatrixLines(matrix, { currency = '' } = {}) {
757
+ const m = matrix || {}
758
+ const s = m.summary || {}
759
+ const cur = currency ? currency + ' ' : ''
760
+ const out = []
761
+ out.push(`🧭 竞品矩阵 · ${m.store || '-'} · 快照 ${m.snapshots || 0} 期 · 更新 ${String(m.capturedAt || '').slice(0, 16).replace('T', ' ')}`)
762
+ out.push(`自有 ${s.own || 0} 个 · 竞品 ${s.competitors || 0} 个 · 我方均价 ${cur}${s.ownAvgPrice ?? '—'} vs 竞品均价 ${cur}${s.competitorAvgPrice ?? '—'} · 比我便宜的竞品 ${s.cheaperCount == null ? '—' : s.cheaperCount} 个`)
763
+ const rows = (m.items || []).slice(0, 12)
764
+ for (const x of rows) {
765
+ const flag = x.role === 'own' ? '⭐' : '·'
766
+ const dep = x.priceDeltaPct == null ? '—' : `${x.priceDeltaPct > 0 ? '+' : ''}${Math.round(x.priceDeltaPct * 1000) / 10}%`
767
+ const rate = x.rating == null ? '—' : x.rating
768
+ const sold = x.soldBucket ? `已售≈${x.soldBucket}(估算档位)` : ''
769
+ out.push(`${flag} ${x.id} ${cur}${x.price ?? '—'}(较上次 ${dep})· 评分 ${rate}${x.ratingDelta ? `(${x.ratingDelta > 0 ? '+' : ''}${x.ratingDelta})` : ''} · ${sold} · 首次采集 ${x.firstSeen || '—'}`)
770
+ }
771
+ if ((m.items || []).length > 12) out.push(`… 其余 ${m.items.length - 12} 个见 ERP`)
772
+ out.push(`ℹ️ 销量/库存为平台**分桶参考值**(估算);趋势从接入日 ${s.historyFrom || '—'} 起算。`)
773
+ return out
774
+ }