validate-products.mjs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. // 阶段 A 产品数据校验:node tools/validate-products.mjs
  2. // 校验:JSON 可解析 / 契约字段齐全 / BOM 与成本数字自洽 / 毛利率 / shape 可渲染 / 违禁字样
  3. import fs from "node:fs";
  4. import path from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { roundProfile } from "../site/core/geometry/profile.js";
  7. const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
  8. const DIR = path.join(ROOT, "site/data/products");
  9. const IDS = ["recorder-bean", "watch-case", "round-screen", "ai-pin", "eink-tag", "pocket-ai", "bone-headset", "smart-ring"];
  10. const PBR = new Set(["sil-silicone", "abs-matte", "abs-rubber", "pc-gloss", "al-silver", "al-black", "ti", "ceramic"]);
  11. const ROLES = new Set(["shell", "lid", "back", "button", "ring", "screen", "battery", "pcb", "brass", "clip"]);
  12. const ASM = new Set(["焊接", "排线 FPC", "排针", "弹片", "磁吸"]);
  13. const BANNED = /claude|hermes|deepseek/i;
  14. const EPS = 0.01;
  15. const results = [];
  16. const fail = (id, msg) => results.push({ id, ok: false, msg });
  17. const pass = (id, msg) => results.push({ id, ok: true, msg });
  18. const near = (a, b, tol = EPS) => Math.abs(a - b) <= tol;
  19. for (const id of IDS) {
  20. const file = path.join(DIR, `${id}.json`);
  21. let d;
  22. try {
  23. d = JSON.parse(fs.readFileSync(file, "utf8"));
  24. pass(id, "JSON 可解析");
  25. } catch (e) {
  26. fail(id, `JSON 解析失败: ${e.message}`);
  27. continue;
  28. }
  29. const T = (cond, msg) => (cond ? pass(id, msg) : fail(id, msg));
  30. // 0. 基本字段与来源口径
  31. T(d.id === id, "id 与文件名一致");
  32. T(d.author === "FmodeCode", "署名 FmodeCode");
  33. for (const k of ["name", "latin", "tagline", "category", "summary", "priceBasis"]) T(typeof d[k] === "string" && d[k].length > 0, `字段 ${k} 存在`);
  34. T(d.craftTags?.length >= 2 && d.craftTags.length <= 4, "craftTags 2~4 个");
  35. T(/估算|中值/.test(d.priceBasis || ""), "priceBasis 写明估算/中值");
  36. T(!BANNED.test(JSON.stringify(d)), "无违禁字样(Claude/Hermes/DeepSeek)");
  37. // 1. shape
  38. const st = d.shape?.type;
  39. T(["round", "rect", "watch", "ring"].includes(st), "shape.type 合法");
  40. const s = d.shape?.defaults || {};
  41. T(s.screenD < (s.length > s.dTop ? s.length : s.dTop) - 2 * (s.wall + s.domeR + s.platform), "shape.screenD 约束");
  42. // rect/watch 用 dTop 作宽度:再按 dTop 单维复核
  43. T(s.wall >= 0.4 && s.wall <= 4.5 && s.domeR >= 0.5 && s.recessR >= 0.3 && s.recessDepth < s.height * 0.6 && s.split >= 0.05 && s.split <= 0.95, "shape 硬校验(wall/domeR/recessR/recessDepth/split)");
  44. if (st === "round" || st === "ring") {
  45. const r = roundProfile(s);
  46. const hard = r.warnings.filter((w) => w.includes("折角") || w.includes("等比收敛"));
  47. // core/profile.js 在「平台→凹圆」处恒报折角(未收敛折返),对所有产品都会出现 → 单独标注,不计入数据不合格
  48. const coreBug = r.warnings.filter((w) => w.includes("折角"));
  49. T(hard.length === coreBug.length, `roundProfile 无数据侧告警${r.warnings.length ? ":" + r.warnings.filter(w=>!coreBug.includes(w)).join(";") : ""}`);
  50. if (coreBug.length) pass(id, `[core 提示] ${coreBug[0]}(core/profile.js 构造问题,与数据无关)`);
  51. }
  52. if (st === "watch") T(d.parts.filter((p) => p.split !== undefined && p.split < 1).length >= 2 && new Set(d.parts.map(p => p.color)).size >= 2, "watch-case 双色拼色(≥2 件 split<1 且 ≥2 色)");
  53. // 2. materials / parts
  54. T(Array.isArray(d.materials) && d.materials.length >= 1 && d.materials.every((m) => PBR.has(m)), "materials 全部在 PBR 库内");
  55. const needParts = ["shell", "back", "button", "ring", "screen", "battery", "pcb"];
  56. const roles = new Set((d.parts || []).map((p) => p.role));
  57. T(d.parts?.length >= 9, `parts ≥ 9 件(${d.parts?.length})`);
  58. T(needParts.every((r) => roles.has(r)), "parts 覆盖 shell/back/button/ring/screen/battery/pcb");
  59. T((d.parts || []).every((p) => p.id && p.name && p.material && p.craft && p.tolerance && ROLES.has(p.role)), "每个零件含 名称/材质/工艺/公差/role");
  60. T((d.parts || []).every((p) => typeof p.weight === "number" && p.weight > 0), "每个零件含净重");
  61. // 3. features
  62. const ftypes = new Set((d.features || []).map((f) => f.type));
  63. T(d.features?.length >= 6 && d.features.length <= 10, `features 6~10 个(${d.features?.length})`);
  64. T(ftypes.size >= 5, `features 覆盖 ≥5 类(${ftypes.size})`);
  65. // 4. electronics
  66. const el = d.electronics || [];
  67. T(el.length >= 4, `electronics ≥ 4 件(${el.length})`);
  68. T(el.every((e) => e.model && e.price >= 0 && e.qty >= 0 && ASM.has(e.assembly)), "electronics 有 model/price/qty/assembly(装配方式合法)");
  69. T(el.every((e) => e.quantity_unit_price_ok !== false), "electronics 单价×数量字段一致");
  70. // 5. consumables
  71. const cm = d.consumables || [];
  72. T(cm.length >= 6, `consumables ≥ 6 行(${cm.length})`);
  73. T(["螺丝", "双面胶", "泡棉", "彩盒", "说明书"].every((k) => cm.some((c) => c.name.includes(k)) || (d.parts || []).some((x) => (x.name + (x.notes || "")).includes(k))), "consumables 含 螺丝/双面胶/泡棉/彩盒/说明书(或无螺丝结构时零件清单内已有替代件)");
  74. // 6. BOM 自洽
  75. const bom = d.bom || {};
  76. const rows = bom.rows || [];
  77. T(rows.length >= 10, `bom.rows ≥ 10 行(${rows.length})`);
  78. T(rows.every((r, i) => r.seq === i + 1 && r.name && r.spec && r.supplier && r.price >= 0 && r.qty > 0), "BOM 行含 序号/件名/物料规格/供应商类型/单价/数量");
  79. const rowOk = rows.every((r) => near(r.subtotal, r.price * r.qty, 0.005));
  80. T(rowOk, "每行 小计 = 单价 × 数量");
  81. const sum = Math.round(rows.reduce((a, r) => a + r.subtotal, 0) * 100) / 100;
  82. T(near(sum, bom.bomTotal), `bomTotal = Σ小计(${bom.bomTotal})`);
  83. T(bom.bomCurrency === "CNY", "bomCurrency = CNY");
  84. // 7. processes
  85. const pr = d.processes || [];
  86. const cats = (id) => ({
  87. 成型: ["inject", "vulcanize", "cnc", "cnc-led", "tsform", "ceramic", "curved-smt", "dock", "resin", "smt"],
  88. 表面: ["surf", "paint", "anodize"],
  89. 组装: ["assemble", "weld", "bond", "lam", "lcd-lam"],
  90. 测试: ["test"],
  91. 包装: ["pack", "post"],
  92. })[id] || [];
  93. const names = pr.map((p) => p.name).join("|");
  94. T(pr.length >= 5, `processes ≥ 5 道(${pr.length})`);
  95. T(pr.every((p) => p.name && p.equipment && p.cycle && typeof p.yield === "number" && p.yield > 0 && p.yield <= 1 && p.price > 0 && p.desc), "每道工序含 工序名/设备/节拍或工时/良率/单价/说明");
  96. T(/注塑|硫化|CNC|成型|车削|模压/.test(names), "processes 覆盖成型");
  97. T(/喷|表面|氧化|拉丝|抛光|手感/.test(names), "processes 覆盖表面处理");
  98. T(/组装|装配|贴合|焊接/.test(names), "processes 覆盖组装");
  99. T(/测试|检测/.test(names), "processes 覆盖测试");
  100. T(/包装/.test(names), "processes 覆盖包装");
  101. // 8. MOQ 阶梯
  102. const tiers = (d.moq && d.moq.tiers) || [];
  103. const moq = tiers;
  104. T(moq.length >= 3, `moq ≥ 3 档(${moq.length})`);
  105. T(moq.every((t, i) => t.qty > 0 && t.unitPrice > 0 && Number.isFinite(t.mouldAmort) && t.total > 0 && (i === 0 || (t.qty > moq[i - 1].qty && t.unitPrice < moq[i - 1].unitPrice))), "moq 每档含 单价(unitPrice)/模具费摊销(mouldAmort)/总价(total),qty 递增单价递减");
  106. T(moq.every((t) => near(t.total, t.qty * t.unitPrice, 0.5)), "moq 每档 总价 = 数量 × 单价");
  107. T(moq.every((t) => near(t.bulkPrice + t.mouldAmort, t.unitPrice, 0.6)), "moq 每档 bulkPrice + mouldAmort = price");
  108. // 9. cost 自洽
  109. const c = d.cost || {};
  110. const ci = c.items || [];
  111. const keys = ci.map((x) => x.name);
  112. T(["物料", "加工", "模具摊销", "组装", "测试", "包材", "损耗"].every((k) => keys.includes(k)), "cost 含 物料/加工/模具摊销/组装/测试/包材/损耗");
  113. const csum = Math.round(ci.reduce((a, x) => a + x.amount, 0) * 100) / 100;
  114. T(near(csum, c.unitCost), `cost 各项相加 = 单台成本(${c.unitCost})`);
  115. T(near(ci.find((x) => x.name === "物料").amount, bom.bomTotal), "cost.物料 = bomTotal");
  116. T(near(ci.find((x) => x.name === "模具摊销").amount, c.mouldAmortization), "cost 模具摊销 = 模具费合计 / 基准批量");
  117. T(c.unitCost < c.suggestedPrice, `单台成本 ${c.unitCost} < 建议售价 ${c.suggestedPrice}`);
  118. const gm = (c.suggestedPrice - c.unitCost) / c.suggestedPrice * 100;
  119. T(near(gm, c.grossMarginPct, 0.5), `毛利率 =(售价-成本)/售价(${gm.toFixed(2)}%)`);
  120. T(gm >= 35 && gm <= 65, `毛利率 ${gm.toFixed(2)}% 落在 35%~65%`);
  121. T(near(c.markup, c.suggestedPrice / c.unitCost, 0.02), "markup = 售价 / 成本");
  122. T(c.retailLow <= c.suggestedPrice && c.suggestedPrice <= c.retailHigh, "建议售价落在零售价带内");
  123. // 10. detail / dimensions / weight
  124. const sec = d.detail?.sections || [];
  125. T(sec.length >= 4 && sec.length <= 6, `detail 段落 4~6 段(${sec.length})`);
  126. T(sec.every((x) => x.title && x.body.length >= 40 && x.body.length <= 120), `每段正文 40~120 字(${sec.map(x=>x.body.length).join(",")})`);
  127. T(d.detail?.specs?.length >= 4, "detail.specs ≥ 4 行");
  128. T(["length", "width", "height"].every((k) => typeof d.dimensions?.[k] === "number" && d.dimensions[k] > 0), "dimensions 完整");
  129. T(typeof d.weight === "number" && d.weight > 0, "weight 存在");
  130. }
  131. // 汇总输出
  132. const byId = {};
  133. for (const r of results) (byId[r.id] ||= []).push(r);
  134. let failed = 0;
  135. const lines = [];
  136. for (const id of IDS) {
  137. const rs = byId[id] || [{ ok: false, msg: "无结果" }];
  138. const bad = rs.filter((r) => !r.ok);
  139. failed += bad.length;
  140. lines.push(`${bad.length ? "✗" : "✓"} ${id} ${rs.length - bad.length}/${rs.length} 项通过${bad.length ? "\n " + bad.map((b) => b.msg).join("\n ") : ""}`);
  141. }
  142. console.log(lines.join("\n"));
  143. console.log(`\n合计 ${results.length} 项,失败 ${failed} 项`);
  144. process.exitCode = failed ? 1 : 0;