diff --git a/plugin/preview/mock-api.ts b/plugin/preview/mock-api.ts index 73a3d82..110c1f4 100644 --- a/plugin/preview/mock-api.ts +++ b/plugin/preview/mock-api.ts @@ -174,12 +174,17 @@ function readBody(req: IncomingMessage): Promise { * ## 与真后端的关系 * * 参数口径(`targetType` / `count` / `refId` / `refLabel` / `remark`、返回 - * `{ items }`、校验返回 `{ valid, reason, exists, record }`)**照着真后端抄**, - * 但**数据是进程内的**、格式里的校验位算法也是这里自己定的 —— - * 所以:**别看号段,只验链路**。真要对接,关掉开关或设 `PREVIEW_API_TARGET`。 + * `{ batch, count, items }`、校验返回 `{ valid, reason, exists, record }`)、 + * 前缀表、SN 形状、**校验位算法与字符表**都是从真后端 + * `库存管理系统/backend/src/api/sn-code/` 逐项抄过来的 —— 所以这里生成的 SN + * 拿去真后端 `/verify` 也能过校验位。 + * + * 唯一不是真的地方是**数据**:台账在进程内存里,重启即清空。 + * 所以:**别看号段连不连号,只验链路**。真要对接,关掉开关或设 + * `PREVIEW_API_TARGET` 指向真后端。 */ -/** 业务类型 → 号段前缀。真后端同结构,前缀值以真后端 `/meta` 为准 */ +/** 业务类型 → 号段前缀。与真后端 `services/sn-code.js` 的 `DEFAULT_PREFIX` 逐项一致 */ const SN_PREFIX: Record = { DEVICE: "ZP", PART: "PJ", @@ -189,23 +194,37 @@ const SN_PREFIX: Record = { OTHER: "SN", }; -/** 校验位:body 各字符按 31 进制滚动求和后取模 36,映射到 0-9A-Z */ -function snChecksum(body: string): string { - let sum = 0; - for (let i = 0; i < body.length; i += 1) { - sum = (sum * 31 + body.charCodeAt(i)) % 36; +/** 校验位字符表:真后端刻意剔除了 0/O、1/I/L 这类肉眼与扫码都易混的字符 */ +const SN_CHECK_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; + +/** + * 校验位算法 —— **与真后端逐位相同**(`services/sn-code.js` 的 `checksumChar`)。 + * + * 这里刻意照抄而不是"自己定一个":抄一致之后,预览里生成的 SN + * 拿去真后端的 `/verify` 也能过校验位,本地调出来的码不会在切到真后端时集体失效。 + * 数据仍然是进程内的(不查库),但**形状与算法是真的**。 + */ +function snChecksum(payload: string): string { + let acc = 0; + for (let i = 0; i < payload.length; i += 1) { + // 位置加权:避免「字母调序」这类错误也算通过 + acc = (acc * 31 + payload.charCodeAt(i) * (i + 1)) % 1000003; } - return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[sum]; + return SN_CHECK_ALPHABET[acc % SN_CHECK_ALPHABET.length]; } +/** 与真后端一致的 SN 形状:`PREFIX-YYMMDD-NNNN-C` */ function makeSn(targetType: string, seq: number): string { - const pad = (n: number) => String(n).padStart(2, "0"); + const pad = (n: number, w = 2) => String(n).padStart(w, "0"); const now = new Date(); - const prefix = SN_PREFIX[targetType] || "SN"; - const body = `${prefix}-${String(now.getFullYear()).slice(2)}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${String(seq).padStart(4, "0")}`; - return `${body}-${snChecksum(body)}`; + const prefix = SN_PREFIX[targetType] || SN_PREFIX.OTHER; + const payload = `${prefix}-${String(now.getFullYear()).slice(2)}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(seq, 4)}`; + return `${payload}-${snChecksum(payload)}`; } +/** 与真后端同一套正则以判定格式 */ +const SN_PATTERN = /^([A-Z0-9]{2,3})-(\d{6})-(\d{1,6})-([A-Z0-9])$/; + function issueSn(ledger: Row[], body: any, count: number): Row[] { const targetType = String(body?.targetType || "DEVICE"); const batch = `B${Date.now().toString(36).toUpperCase()}`; @@ -218,6 +237,9 @@ function issueSn(ledger: Row[], body: any, count: number): Row[] { batch, status: "ISSUED", issuedAt: new Date().toISOString(), + // 真后端会记「调用来源」,插件建议填自己的 id(便于台账追溯是谁发的码)—— + // 这里原样透传,好让预览里也能验到「插件有没有带上 source」 + source: body?.source ? String(body.source) : null, ...(body?.refId ? { refId: body.refId } : {}), ...(body?.refLabel ? { refLabel: body.refLabel } : {}), ...(body?.remark ? { remark: body.remark } : {}), @@ -261,12 +283,15 @@ function handleSnCode( } if (method === "POST" && path === "/api/sn-codes/verify") { - const text = String(body?.sn || "").trim(); + const text = String(body?.sn || "").trim().toUpperCase(); if (!text) return ok({ valid: false, reason: "EMPTY" }); - const matched = text.match(/^([A-Z]{2})-(\d{6})-(\d{4})-([0-9A-Z])$/); + const matched = SN_PATTERN.exec(text); if (!matched) return ok({ valid: false, reason: "FORMAT" }); - if (snChecksum(`${matched[1]}-${matched[2]}-${matched[3]}`) !== matched[4]) { - return ok({ valid: false, reason: "CHECKSUM" }); + const [, prefix, date, seq, check] = matched; + // 与真后端一致:序号补齐到 4 位后再算校验位 + const payload = `${prefix}-${date}-${String(Number(seq)).padStart(4, "0")}`; + if (snChecksum(payload) !== check) { + return ok({ valid: false, reason: "CHECKSUM", expectedCheck: snChecksum(payload) }); } const record = ledger.find((row) => row.sn === text) || null; return ok({ valid: true, exists: !!record, record }); diff --git a/plugin/src/index.ts b/plugin/src/index.ts index 922a0ce..dc4cea0 100644 --- a/plugin/src/index.ts +++ b/plugin/src/index.ts @@ -24,12 +24,10 @@ import type { PluginCtx, PluginModule } from "./sdk"; import { setCtx } from "./runtime"; +import { PLUGIN_ID } from "./meta"; import PrintTagPage from "./pages/PrintTagPage.vue"; import { code128Svg, qrSvg } from "./codes"; -/** 必须与 plugin.config.json 的 id 完全一致 —— 宿主按它认领产物 */ -const PLUGIN_ID = "funjia.print-tag"; - /** 路由段;宿主会补成 `/plugin/funjia-print-tag/console` */ const ROUTE_SEGMENT = "console"; @@ -79,6 +77,9 @@ const plugin: PluginModule = { const count = Math.max(1, Number(input.count) || 1); const base = { targetType: input.targetType || "DEVICE", + // 后端认这个字段(「调用来源,插件建议填插件 ID,便于追责」)—— + // 不填的话台账里一律记成 `pc`,分不清是插件发的还是别的入口发的 + source: PLUGIN_ID, ...(input.refId ? { refId: input.refId } : {}), ...(input.refLabel ? { refLabel: input.refLabel } : {}), ...(input.remark ? { remark: input.remark } : {}), diff --git a/plugin/src/meta.ts b/plugin/src/meta.ts new file mode 100644 index 0000000..2e137f6 --- /dev/null +++ b/plugin/src/meta.ts @@ -0,0 +1,16 @@ +/** + * 插件身份常量 —— **全工程唯一一处字面量**。 + * + * 这个 id 出现在四个地方,任何一处写错都会造成很难查的现象: + * + * | 位置 | 写错的后果 | + * | ---- | ---- | + * | `plugin.config.json` 的 `id` | 宿主按 id 认领不到产物 —— 「脚本加载成功但插件不出现」 | + * | `src/index.ts` 自注册的 `manifest.id` | 同上 | + * | 菜单 / 路由 / 命令 id 前缀 | 停用时回收不干净,留下幽灵菜单 | + * | 发放 SN 时请求体里的 `source` | SN 台账里看不出这条码是谁发的(一律记成 `pc`) | + * + * 所以不要在别处再抄一遍 —— 统一从这里取。 + * (`plugin.config.json` 是 JSON,import 不到,那一处只能靠 `scripts/verify.mjs` 交叉校验。) + */ +export const PLUGIN_ID = "funjia.print-tag"; diff --git a/plugin/src/pages/PrintTagPage.vue b/plugin/src/pages/PrintTagPage.vue index 09a2265..8f18d46 100644 --- a/plugin/src/pages/PrintTagPage.vue +++ b/plugin/src/pages/PrintTagPage.vue @@ -227,6 +227,7 @@