packServer/backend/app/service/extension_config.js
liufumingren 7021e18e7c fix(extension): 插件单号跳转默认值改为线上站点
默认 urlTemplate 原来是 http://localhost:7301/local,插件装在员工浏览器里
点单号会打开他们自己的机器 —— 改成 https://pack.wms.gztbyc.com/local。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 03:29:57 +08:00

243 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
/**
* Chrome 插件的**集中配置**(平台管理员维护,插件只拉取执行)
*
* 存 `sys_config`(group=extension, key=config, valueType=json),不新建表:
* 配置是「一套全局值」,读写频率极低,且有 Redis 缓存(见 service/config.js)。
*
* 设计要点:
* - 后台**只维护前缀**(`YT` / `SF` / `32`…),单号正则由这里拼出来(`pattern`),
* 插件端不再自己拼正则、也不展示正则;
* - `hosts` 是插件允许工作的站点(glob:`*.abc.com`、`192.168.11.206`、`*`);
* - 每次保存 `version + 1`:插件靠它判断"配置变没变",没变就不重写 storage(避免整页重扫);
* - `pattern` 一并下发:服务端生成一次,所有客户端行为一致,不会各拼各的。
*/
/** sys_config 位置 */
const GROUP = 'extension';
const KEY = 'config';
/** 默认前缀(和老版插件内置的快递规则一致) */
const DEFAULT_PREFIXES = [ 'YT', 'SF', 'JD', 'ZTO', 'YTO', 'STO', 'EMS', 'DBL', '32', '77' ];
/**
* 单号点击后打开的页面(`{code}` 会被插件替换成单号)
*
* ⚠️ 默认值必须是线上站点:插件装在员工浏览器里,localhost 只会打开他们自己的机器。
* 内网镜像 / 联调要改就在「平台管理 → 插件配置」里改,别改这里。
*/
const DEFAULT_URL_TEMPLATE = 'https://pack.wms.gztbyc.com/local?code={code}';
const DEFAULT_APP_URL_TEMPLATE = 'yuncang://open?code={code}';
/** 前缀:字母/数字,1~8 位(`32` / `77` 这种数字前缀也要支持) */
const PREFIX_RE = /^[A-Z0-9]{1,8}$/;
/**
* 插件读取结果的服务端缓存
*
* 插件每 5 分钟拉一次,几百台机器就是每小时上万次请求 —— 但配置几乎不变,
* 所以服务端算一次缓存 **1 小时**;后台保存配置时立刻删掉(`save()` → `invalidate()`),
* 保证「提交新版本」马上生效。
*
* 安装包地址不参与这份缓存:插件自己读 nginx 的 `/download/version.json`(那边是 no-cache),
* 所以打包上传新安装包**天然即时**,不需要清这里的缓存。
*/
const PUBLIC_CACHE_KEY = 'extension:config:public';
const PUBLIC_CACHE_TTL_SECONDS = 3600;
/** 没配置过时的默认值 */
function defaults() {
return {
version: 0,
enabled: true,
hosts: [ '*' ],
prefixes: DEFAULT_PREFIXES.slice(),
minDigits: 10,
maxDigits: 16,
urlTemplate: DEFAULT_URL_TEMPLATE,
appUrlTemplate: DEFAULT_APP_URL_TEMPLATE,
downloadUrl: '',
updatedAt: null,
pattern: buildPattern(DEFAULT_PREFIXES, 10, 16),
flags: 'g',
};
}
/**
* 由前缀生成单号正则:`\b(?:YT|SF|…)\d{10,16}\b`
*
* 用 `g`(不带 `i`):前缀统一存成大写,避免把 `yt` 这类普通词误判成单号。
*/
function buildPattern(prefixes, minDigits, maxDigits) {
const list = prefixes.map(item => String(item).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
if (list.length === 0) return '';
return '\\b(?:' + list.join('|') + ')\\d{' + minDigits + ',' + maxDigits + '}\\b';
}
/** 数组去空去重(保持顺序) */
function uniq(list) {
const seen = new Set();
const out = [];
for (const item of list) {
if (seen.has(item)) continue;
seen.add(item);
out.push(item);
}
return out;
}
/** 生效站点:glob 字符串;留空 = 不限制(`*`) */
function normalizeHosts(value) {
const list = (Array.isArray(value) ? value : [])
.map(item => String(item == null ? '' : item).trim())
.filter(Boolean);
return list.length > 0 ? uniq(list) : [ '*' ];
}
/** 前缀:转大写、校验字符集、去重、限制数量 */
function normalizePrefixes(value) {
const list = (Array.isArray(value) ? value : [])
.map(item => String(item == null ? '' : item).trim().toUpperCase())
.filter(Boolean);
const bad = list.find(item => !PREFIX_RE.test(item));
if (bad) {
const error = new Error(`单号前缀「${bad}」不合法:只能是大写字母或数字,1~8 位`);
error.status = 422;
throw error;
}
const out = uniq(list);
if (out.length > 50) {
const error = new Error('单号前缀最多 50 个');
error.status = 422;
throw error;
}
return out;
}
/** 数字位数:4~24,且 min ≤ max */
function normalizeDigits(min, max) {
const toInt = (value, fallback) => {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) ? parsed : fallback;
};
let minDigits = Math.min(Math.max(toInt(min, 10), 4), 24);
let maxDigits = Math.min(Math.max(toInt(max, 16), 4), 24);
if (minDigits > maxDigits) [ minDigits, maxDigits ] = [ maxDigits, minDigits ];
return { minDigits, maxDigits };
}
/** 模板:必须含 `{code}`,否则回落到默认值(空串也算没填) */
function normalizeTemplate(value, fallback) {
const text = String(value == null ? '' : value).trim() || fallback;
return text.includes('{code}') ? text : fallback;
}
/** 把任意输入整理成合法配置(不含 version / updatedAt) */
function normalize(input) {
const source = input && typeof input === 'object' ? input : {};
const prefixes = normalizePrefixes(source.prefixes);
const { minDigits, maxDigits } = normalizeDigits(source.minDigits, source.maxDigits);
return {
enabled: source.enabled !== false,
hosts: normalizeHosts(source.hosts),
prefixes,
minDigits,
maxDigits,
urlTemplate: normalizeTemplate(source.urlTemplate, DEFAULT_URL_TEMPLATE),
appUrlTemplate: normalizeTemplate(source.appUrlTemplate, DEFAULT_APP_URL_TEMPLATE),
// 留空 = 插件同步时自己读 /download/version.json(永远用最新发布版本);
// 只有要指到内网镜像之类才需要填,后台页面已经不提供这个输入框。
downloadUrl: String(source.downloadUrl == null ? '' : source.downloadUrl).trim(),
pattern: buildPattern(prefixes, minDigits, maxDigits),
flags: 'g',
};
}
class ExtensionConfigService extends Service {
/**
* 读当前配置(给管理员看,含默认值)
*
* 存量数据可能是旧结构(例如手改过 sys_config),这里统一过一遍 normalize,
* 保证返回给前端 / 插件的字段永远齐全。
*/
async read() {
const stored = await this.ctx.service.config.get(GROUP, KEY, null);
if (!stored || typeof stored !== 'object') return defaults();
const config = normalize(stored);
return {
...config,
version: Number(stored.version) || 0,
updatedAt: stored.updatedAt || null,
};
}
/** 保存(管理端):校验 → version 自增 → 写 sys_config(带缓存失效) */
async save(input) {
const previous = await this.read();
const next = normalize(input);
next.version = (Number(previous.version) || 0) + 1;
next.updatedAt = new Date().toISOString();
await this.ctx.service.config.set({
groupName: GROUP,
configKey: KEY,
configValue: next,
valueType: 'json',
remark: 'Chrome 插件集中配置(识别前缀 / 生效站点 / 跳转模板)',
});
// 提交即生效:插件下次(最多 5 分钟)来拉的时候就能拿到新配置
await this.invalidate();
return next;
}
/**
* 插件读取用的公开视图(Redis 缓存 1 小时)
*
* 只给插件执行所需字段,**不含任何内部信息**(主体、账号、密钥一概没有)。
*/
async publicView() {
const cached = await this.ctx.service.cache.get(PUBLIC_CACHE_KEY);
if (cached) return cached;
const view = this.buildPublicView(await this.read());
await this.ctx.service.cache.set(PUBLIC_CACHE_KEY, view, PUBLIC_CACHE_TTL_SECONDS);
return view;
}
/** 主动失效(保存配置时调用;发布脚本/内部运维需要时也能用) */
async invalidate() {
await this.ctx.service.cache.del(PUBLIC_CACHE_KEY);
}
buildPublicView(config) {
return {
version: config.version,
enabled: config.enabled,
hosts: config.hosts,
prefixes: config.prefixes,
minDigits: config.minDigits,
maxDigits: config.maxDigits,
pattern: config.pattern,
flags: config.flags,
urlTemplate: config.urlTemplate,
appUrlTemplate: config.appUrlTemplate,
downloadUrl: config.downloadUrl,
updatedAt: config.updatedAt,
};
}
}
module.exports = ExtensionConfigService;