liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

435 lines
15 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');
const { Op } = require('sequelize');
/** 单次上报的条数上限(防止一次请求塞太多) */
const MAX_BATCH = 500;
/** 字段长度(与 DDL 保持一致) */
const MAX_CHANNEL_ID = 64;
const MAX_CHANNEL_NAME = 128;
const MAX_BARCODE = 255;
/** 去掉首尾空白并把非字符串转成字符串 */
function text(value) {
if (value === undefined || value === null) return '';
return String(value).trim();
}
/**
* 解析扫描时间,统一截断到秒(去重键的一部分)
*
* 支持:`2026-10-16 12:00:00` / `2026-10-16T12:00:00` / `2026/10/16 12:00:00`
* / 10 位秒级时间戳 / 13 位毫秒级时间戳 / Date
* 无时区的字符串按**服务器本地时区**解析(与 Sequelize 的 +08:00 一致)。
*
* @return {Date|null} 非法返回 null
*/
function parseScanTime(value) {
if (value === undefined || value === null || value === '') return null;
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : truncateToSecond(value);
const str = text(value);
if (!str) return null;
let date;
if (/^\d{10}$/.test(str)) {
date = new Date(Number(str) * 1000); // 秒级时间戳
} else if (/^\d{13}$/.test(str)) {
date = new Date(Number(str)); // 毫秒级时间戳
} else {
date = new Date(str.replace(/\//g, '-').replace(' ', 'T'));
}
if (!date || Number.isNaN(date.getTime())) return null;
return truncateToSecond(date);
}
function truncateToSecond(date) {
const copy = new Date(date.getTime());
copy.setMilliseconds(0);
return copy;
}
/** 唯一键冲突(重复上报)错误 */
function isDuplicateError(err) {
if (!err) return false;
if (err.name === 'SequelizeUniqueConstraintError') return true;
if (err.parent && err.parent.code === 'ER_DUP_ENTRY') return true;
return err.code === 'ER_DUP_ENTRY';
}
/** 记录去重用的内存键 */
function dedupKey(row) {
return [ row.scannerId, row.channelId, row.scanTime.getTime(), row.barcode ].join('\u0000');
}
function toInt(value) {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
class ScanService extends Service {
get ScanChannel() {
return this.app.model.ScanChannel;
}
get ScanRecord() {
return this.app.model.ScanRecord;
}
/**
* 中控上报通道(channel_id + channel_name)
*
* - 同一中控 + 同一 channel_id 视为同一个通道:存在则更新通道名与最近上报时间;
* - 曾被软删除的通道会被「复活」(deleted_at 置空),避免唯一键挡住重新启用;
* - 同一次上报里重复的 channel_id 只处理最后一次。
*
* @param {object} scanner 中控(扫描器实例,来自 scanner_auth)
* @param {Array} channels 形如 [{ channelId, channelName }]
* @return {Promise<{received:number, created:number, updated:number, invalid:number, errors:Array, channels:Array}>}
*/
async reportChannels(scanner, channels) {
const list = Array.isArray(channels) ? channels : [];
if (!list.length) this.ctx.throw(422, 'channels 不能为空');
if (list.length > MAX_BATCH) this.ctx.throw(422, `单次最多上报 ${MAX_BATCH} 个通道`);
const now = new Date();
const errors = [];
const normalized = new Map(); // channelId -> { channelId, channelName }
list.forEach((raw, index) => {
const item = raw && typeof raw === 'object' ? raw : {};
const channelId = text(item.channelId || item.channel_id);
const channelName = text(item.channelName || item.channel_name);
if (!channelId) {
errors.push({ index, message: 'channelId 不能为空' });
return;
}
if (channelId.length > MAX_CHANNEL_ID) {
errors.push({ index, message: `channelId 超长(>${MAX_CHANNEL_ID})` });
return;
}
if (channelName.length > MAX_CHANNEL_NAME) {
errors.push({ index, message: `channelName 超长(>${MAX_CHANNEL_NAME})` });
return;
}
// 同一次上报里同 channelId 只保留最后一次
normalized.set(channelId, { channelId, channelName });
});
const rows = [ ...normalized.values() ];
if (!rows.length) {
return { received: list.length, created: 0, updated: 0, invalid: errors.length, errors, channels: [] };
}
const ids = rows.map(row => row.channelId);
const existing = await this.ScanChannel.findAll({
where: { scannerId: scanner.id, channelId: { [Op.in]: ids } },
paranoid: false,
});
const existingMap = new Map(existing.map(row => [ row.channelId, row ]));
let created = 0;
let updated = 0;
const saved = [];
for (const row of rows) {
const hit = existingMap.get(row.channelId);
if (hit) {
if (hit.deletedAt) {
await this.ScanChannel.restore({ where: { id: hit.id } });
this.ctx.logger.info('[scan] 通道 %s 已重新启用 (scanner=%s)', row.channelId, scanner.sn);
}
await this.ScanChannel.update(
{ channelName: row.channelName, lastReportAt: now },
{ where: { id: hit.id }, paranoid: false },
);
updated++;
saved.push(Object.assign({ id: hit.id }, row, { lastReportAt: now }));
} else {
const instance = await this.ScanChannel.create({
scannerId: scanner.id,
channelId: row.channelId,
channelName: row.channelName,
lastReportAt: now,
status: 1,
});
created++;
saved.push(instance.toJSON());
}
}
this.ctx.logger.info('[scan] 通道上报 %s: 新增 %d / 更新 %d / 非法 %d', scanner.sn, created, updated, errors.length);
return {
received: list.length,
created,
updated,
invalid: errors.length,
errors,
channels: saved,
};
}
/**
* 中控上报扫码结果:条码 + 扫描时间 + 通道 id
*
* 去重:同一中控 + 同一通道 + 同一时间(秒) + 同一条码 只入库一次,
* 重复上报不报错,返回 { inserted, duplicated }。
* 顺带:刷新通道的最近上报时间(未知通道自动补一条,通道名留空)、刷新中控心跳。
*
* @param {object} scanner 中控(扫描器实例)
* @param {Array} records 形如 [{ barcode, scanTime, channelId }]
* @return {Promise<object>} { received, inserted, duplicated, invalid, errors, unknownChannels }
*/
async ingest(scanner, records) {
const list = Array.isArray(records) ? records : [];
if (!list.length) this.ctx.throw(422, 'records 不能为空');
if (list.length > MAX_BATCH) this.ctx.throw(422, `单次最多上报 ${MAX_BATCH} 条`);
const now = new Date();
const errors = [];
const rows = [];
const seen = new Set();
list.forEach((raw, index) => {
const item = raw && typeof raw === 'object' ? raw : {};
const barcode = text(item.barcode || item.code);
const channelId = text(item.channelId || item.channel_id);
const scanTime = parseScanTime(item.scanTime || item.scan_time || item.time);
if (!channelId) {
errors.push({ index, message: 'channelId 不能为空' });
return;
}
if (channelId.length > MAX_CHANNEL_ID) {
errors.push({ index, message: `channelId 超长(>${MAX_CHANNEL_ID})` });
return;
}
if (!barcode) {
errors.push({ index, message: 'barcode 不能为空' });
return;
}
if (barcode.length > MAX_BARCODE) {
errors.push({ index, message: `barcode 超长(>${MAX_BARCODE})` });
return;
}
if (!scanTime) {
errors.push({ index, message: 'scanTime 不能为空或格式非法' });
return;
}
const row = { scannerId: scanner.id, channelId, barcode, scanTime, reportedAt: now };
// 同一批里完全相同的上报只留一条
const key = dedupKey(row);
if (seen.has(key)) return;
seen.add(key);
rows.push(row);
});
const result = {
received: list.length,
inserted: 0,
duplicated: list.length - errors.length - rows.length, // 同一批内的重复条数
invalid: errors.length,
errors,
unknownChannels: [],
};
if (!rows.length) return result;
const fresh = await this.filterExisting(rows);
result.duplicated += rows.length - fresh.length;
if (fresh.length) {
try {
await this.ScanRecord.bulkCreate(fresh);
result.inserted = fresh.length;
} catch (err) {
if (!isDuplicateError(err)) throw err;
// 并发下正好撞上唯一键:退化成逐条插入,撞上的算重复
for (const row of fresh) {
try {
await this.ScanRecord.create(row);
result.inserted++;
} catch (inner) {
if (!isDuplicateError(inner)) throw inner;
}
}
result.duplicated += fresh.length - result.inserted;
}
}
const channelIds = [ ...new Set(rows.map(row => row.channelId)) ];
result.unknownChannels = await this.touchChannels(scanner, channelIds, now);
// 有数据上报即视为中控在线,刷新心跳
await this.ctx.service.scanner.heartbeat(scanner, this.ctx.ip);
this.ctx.logger.info(
'[scan] 扫码上报 %s: 收到 %d / 入库 %d / 去重 %d / 非法 %d',
scanner.sn, result.received, result.inserted, result.duplicated, result.invalid,
);
if (result.unknownChannels.length) {
this.ctx.logger.warn('[scan] %s 上报了未登记的通道: %s', scanner.sn, result.unknownChannels.join(', '));
}
return result;
}
/**
* 过滤掉库里已存在的记录(一次查询,按中控 + 时间范围 + 通道)
* @return {Promise<Array>} 需要新入库的行
*/
async filterExisting(rows) {
const channelIds = [ ...new Set(rows.map(row => row.channelId)) ];
const times = rows.map(row => row.scanTime.getTime());
const from = new Date(Math.min(...times));
const to = new Date(Math.max(...times));
const existing = await this.ScanRecord.findAll({
attributes: [ 'scannerId', 'channelId', 'barcode', 'scanTime' ],
where: {
scannerId: rows[0].scannerId,
channelId: { [Op.in]: channelIds },
scanTime: { [Op.between]: [ from, to ] },
},
raw: true,
});
const existingKeys = new Set(existing.map(row => dedupKey(Object.assign({}, row, {
scanTime: new Date(row.scanTime),
}))));
return rows.filter(row => !existingKeys.has(dedupKey(row)));
}
/**
* 刷新通道的最近上报时间;未登记的通道自动补一条(通道名留空)
* @return {Promise<Array<string>>} 自动补建的通道 id
*/
async touchChannels(scanner, channelIds, at = new Date()) {
if (!channelIds.length) return [];
const known = await this.ScanChannel.findAll({
attributes: [ 'channelId' ],
where: { scannerId: scanner.id, channelId: { [Op.in]: channelIds } },
paranoid: false,
raw: true,
});
const knownIds = new Set(known.map(row => row.channelId));
const missing = channelIds.filter(id => !knownIds.has(id));
if (missing.length) {
await this.ScanChannel.bulkCreate(missing.map(channelId => ({
scannerId: scanner.id,
channelId,
channelName: '',
lastReportAt: at,
status: 1,
})));
}
await this.ScanChannel.update(
{ lastReportAt: at },
{ where: { scannerId: scanner.id, channelId: { [Op.in]: channelIds } }, paranoid: false },
);
return missing;
}
/** 通道列表(分页;可按中控 / 关键字过滤),带所属中控 */
async listChannels({ page = 1, pageSize = 20, scannerId, keyword, status } = {}) {
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (scannerId) where.scannerId = Number(scannerId);
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ channelId: { [Op.like]: `%${keyword}%` } },
{ channelName: { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await this.ScanChannel.findAndCountAll({
where,
include: [{ model: this.app.model.Scanner, as: 'scanner', required: false, attributes: [ 'id', 'sn', 'name' ] }],
order: [[ 'scannerId', 'ASC' ], [ 'channelId', 'ASC' ]],
limit: size,
offset: (current - 1) * size,
});
return {
list: rows.map(row => row.toJSON()),
total: count,
page: current,
pageSize: size,
};
}
/**
* 扫码记录列表(分页 + 通道 / 条码 / 时间范围过滤),带所属中控
* @param {object} params { page, pageSize, scannerId 单个中控, scannerIds 多个中控(用户端按「我的设备」过滤用),
* channelId, barcode, startTime, endTime }
*/
async listRecords({ page = 1, pageSize = 20, scannerId, scannerIds, channelId, barcode, startTime, endTime } = {}) {
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (scannerId) where.scannerId = Number(scannerId);
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
if (channelId) where.channelId = channelId;
if (barcode) where.barcode = { [Op.like]: `%${barcode}%` };
const from = parseScanTime(startTime);
const to = parseScanTime(endTime);
if (from || to) {
where.scanTime = {};
if (from) where.scanTime[Op.gte] = from;
if (to) where.scanTime[Op.lte] = to;
}
const { rows, count } = await this.ScanRecord.findAndCountAll({
where,
include: [{ model: this.app.model.Scanner, as: 'scanner', required: false, attributes: [ 'id', 'sn', 'name' ] }],
order: [[ 'scanTime', 'DESC' ], [ 'id', 'DESC' ]],
limit: size,
offset: (current - 1) * size,
});
return {
list: rows.map(row => row.toJSON()),
total: count,
page: current,
pageSize: size,
};
}
/**
* 通道数(首页统计用)
* @param {object} where 普通条件;或 `{ scannerIds: [1,2] }` 限定这几个中控(用户端统计用)
*/
async countChannels({ scannerIds, ...where } = {}) {
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
return this.ScanChannel.count({ where });
}
/** 扫码记录数(首页统计用;`{ scannerIds }` 限定中控,同 countChannels) */
async countRecords({ scannerIds, ...where } = {}) {
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
return this.ScanRecord.count({ where });
}
/** 某中控的通道(上报后回显用) */
async findChannelsByScanner(scannerId) {
const rows = await this.ScanChannel.findAll({
where: { scannerId },
order: [[ 'channelId', 'ASC' ]],
});
return rows.map(row => row.toJSON());
}
}
module.exports = ScanService;
module.exports.parseScanTime = parseScanTime;