feat(plugin): 发放 SN 带 source;插件 id 收敛到 src/meta.ts

- 新增 src/meta.ts 作为 PLUGIN_ID 的唯一字面量来源(index.ts 与页面共用)。
  这个 id 同时出现在 config、自注册 manifest、菜单/路由/命令 id 前缀、
  发放请求的 source 四处,任何一处抄错都是难查的静默故障。
- 发放请求加 source: funjia.print-tag(页面与 print-tag:issue-sn 命令都加)。
  后端 callerMeta 明确建议插件填自己的 ID,否则 SN 台账里一律记成 pc,
  分不清是插件发的还是别的入口发的。已在预览里验证落到台账。
- preview/mock-api.ts 的 SN 部分改为逐位镜像真后端(库存管理系统
  backend/src/api/sn-code/):校验位算法与字符表照抄,SN 形状/正则/补位口径一致。
  实测 mock 产出的 SN 全部能通过真后端校验位算法 —— 本地调通的码切到真后端不会失效。

最终验收:typecheck 通过;插件自检 0 error;仓库 verify-repository 32 passed / 0 failed;
repo-doctor 0 error 0 warning;源码模式与产物模式预览均跑通且无控制台报错。
This commit is contained in:
2026-10-04 00:01:26 +08:00
parent 7c986fd5c5
commit 0cbff3ccd5
4 changed files with 82 additions and 36 deletions
+43 -18
View File
@@ -174,12 +174,17 @@ function readBody(req: IncomingMessage): Promise<any> {
* ## 与真后端的关系
*
* 参数口径(`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<string, string> = {
DEVICE: "ZP",
PART: "PJ",
@@ -189,23 +194,37 @@ const SN_PREFIX: Record<string, string> = {
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 });
+4 -3
View File
@@ -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 } : {}),
+16
View File
@@ -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";
+19 -15
View File
@@ -227,6 +227,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
import { useCtx } from "../runtime";
import { PLUGIN_ID } from "../meta";
import { code128Bits, LABEL_BARCODE_STRIP_MM } from "../codes";
import { DEFAULT_QR_IMAGE } from "../assets/default-qr";
import Input from "../components/Input.vue";
@@ -469,28 +470,31 @@ const labelContext = (slot: Slot) => ({
defaultImage: DEFAULT_QR_IMAGE,
});
/** 领取 SN:数量 1 走 generate,多条走 batch —— 与 SN 码工具插件同一套接口 */
/**
* 领取 SN:数量 1 走 generate,多条走 batch —— 与 SN 码工具插件同一套接口。
*
* `source` 是后端认的字段(「调用来源,插件建议填插件 ID,便于追责」)。
* 填上之后,SN 台账里能看出这条码是谁发的 —— 否则一律记成 `pc`,
* 出了问题分不清是插件发的还是别的入口发的。
*/
const issueSn = async (n: number): Promise<Array<{ sn: string }>> => {
const base = {
targetType: snForm.targetType,
source: PLUGIN_ID,
...(snForm.refId ? { refId: snForm.refId } : {}),
...(snForm.refLabel ? { refLabel: snForm.refLabel } : {}),
...(snForm.remark ? { remark: snForm.remark } : {}),
};
if (n > 1) {
const res = await ctx.http.post<any>("/api/sn-codes/batch", {
targetType: snForm.targetType,
count: n,
...(snForm.refId ? { refId: snForm.refId } : {}),
...(snForm.refLabel ? { refLabel: snForm.refLabel } : {}),
...(snForm.remark ? { remark: snForm.remark } : {}),
});
const res = await ctx.http.post<any>("/api/sn-codes/batch", { ...base, count: n });
if (res.code === 401) return [];
if (res.code !== 0) throw new Error(res.msg || "批量领码失败");
const list = res.data?.items || res.data || [];
return Array.isArray(list) ? list : [];
}
const res = await ctx.http.post<any>("/api/sn-codes/generate", {
targetType: snForm.targetType,
...(snForm.refId ? { refId: snForm.refId } : {}),
...(snForm.refLabel ? { refLabel: snForm.refLabel } : {}),
...(snForm.remark ? { remark: snForm.remark } : {}),
});
const res = await ctx.http.post<any>("/api/sn-codes/generate", base);
if (res.code === 401) return [];
if (res.code !== 0) throw new Error(res.msg || "领码失败");
return res.data?.sn ? [res.data] : [];
@@ -734,7 +738,7 @@ onMounted(async () => {
if (snEnabled.value) await loadSnMeta();
ctx.logger.info(`[funjia.print-tag] 页面已挂载(宿主 ${ctx.hostVersion},插件 ${ctx.plugin.version})`);
ctx.logger.info(`[${PLUGIN_ID}] 页面已挂载(宿主 ${ctx.hostVersion},插件 ${ctx.plugin.version})`);
});
onBeforeUnmount(() => {