'use strict'; const { app, mock, assert } = require('egg-mock/bootstrap'); const jwt = require('jsonwebtoken'); const { Op } = require('sequelize'); /** 假实例:update 时把字段合并回自身 */ const instance = (data) => Object.assign( { toJSON: () => data, update: async (fields) => Object.assign(data, fields), }, data, ); /** 假实例:额外回调 update 的字段(多次 update 时累积) */ const inst = (data, onUpdate) => Object.assign( { toJSON: () => data, update: async fields => { if (onUpdate) onUpdate(fields); Object.assign(data, fields); return data; }, }, data, ); /** 与服务端一致的密钥/签发者,造一个中控(扫描器)JWT */ function signToken(payload = {}, options = {}) { return jwt.sign( Object.assign({ sub: '1', sn: 'SN-HUB-01', typ: 'scanner', jti: 'jti-1' }, payload), app.config.jwt.secret, Object.assign({ algorithm: 'HS256', expiresIn: '365d', issuer: app.config.jwt.issuer, audience: app.config.jwt.audience, }, options), ); } function authScanner(overrides = {}) { return Object.assign({ id: 1, sn: 'SN-HUB-01', status: 1, tokenJti: 'jti-1' }, overrides); } describe('test/app/controller/scan.test.js', () => { const token = () => `Bearer ${signToken()}`; it('四个扫码接口都必须带 JWT:无令牌一律 401', async () => { await app.httpRequest().post('/api/scan/channels').send({ channels: [] }).expect(401); await app.httpRequest().get('/api/scan/channels').expect(401); await app.httpRequest().post('/api/scan/records').send({ records: [] }).expect(401); await app.httpRequest().get('/api/scan/records').expect(401); }); it('POST /api/scan/channels 首次上报:按 (中控, 通道 id) 建通道', async () => { let created = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return []; }, async create(data) { created = data; return instance(Object.assign({ id: 9 }, data)); }, async update() { return [ 1 ]; }, }, }); const res = await app.httpRequest() .post('/api/scan/channels') .set('Authorization', token()) .send({ channels: [{ channelId: '1', channelName: '1 号打包口' }] }) .expect(200); assert(res.body.data.created === 1 && res.body.data.updated === 0 && res.body.data.invalid === 0); assert(created.scannerId === 1, '通道归属当前中控'); assert(created.channelId === '1'); assert(created.channelName === '1 号打包口'); assert(created.lastReportAt instanceof Date, '应记录最近上报时间'); assert(res.body.data.channels[0].channelId === '1'); }); it('POST /api/scan/channels 再次上报同通道:更新通道名(不新建)', async () => { let args = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ instance({ id: 7, scannerId: 1, channelId: '1', channelName: '旧名字', deletedAt: null }) ]; }, async update(fields, options) { args = { fields, options }; return [ 1 ]; }, async create() { throw new Error('不该新建通道'); }, }, }); const res = await app.httpRequest() .post('/api/scan/channels') .set('Authorization', token()) .send({ channelId: '1', channelName: '新名字' }) // 也支持单条上报 .expect(200); assert(res.body.data.updated === 1 && res.body.data.created === 0); assert(args.fields.channelName === '新名字'); assert(args.fields.lastReportAt instanceof Date); assert(args.options.where.id === 7); assert(args.options.paranoid === false, '软删除的通道也要能更新'); }); it('POST /api/scan/channels 曾软删除的通道会被复活(restore)', async () => { let restored = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ instance({ id: 3, scannerId: 1, channelId: 'CH-2', channelName: '停用过的口', deletedAt: new Date() }) ]; }, async restore(options) { restored = options; return 1; }, async update() { return [ 1 ]; }, }, }); const res = await app.httpRequest() .post('/api/scan/channels') .set('Authorization', token()) .send({ channels: [{ channelId: 'CH-2', channelName: '重新启用' }] }) .expect(200); assert(res.body.data.updated === 1); assert(restored && restored.where.id === 3, '应先 restore 复活通道'); }); it('POST /api/scan/channels 同一批里重复通道只留最后一条;非法通道计入 invalid', async () => { let created = null; let createCount = 0; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return []; }, async create(data) { created = data; createCount++; return instance(Object.assign({ id: 10 }, data)); }, async update() { return [ 1 ]; }, }, }); const res = await app.httpRequest() .post('/api/scan/channels') .set('Authorization', token()) .send({ channels: [ { channelId: '1', channelName: '第一次' }, { channelId: '1', channelName: '最后一次' }, { channelName: '没有通道 id' }, ], }) .expect(200); assert(createCount === 1, '同一批里同 channelId 只处理一次'); assert(created.channelName === '最后一次', '应保留最后一次上报的名字'); assert(res.body.data.received === 3 && res.body.data.created === 1 && res.body.data.invalid === 1); assert(res.body.data.errors[0].message.includes('channelId')); }); it('POST /api/scan/channels 空数组 / 缺参 → 422', async () => { mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: {}, }); await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({ channels: [] }).expect(422); await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({}).expect(422); }); it('POST /api/scan/records 首次上报:入库并刷新通道/心跳', async () => { let rows = null; let scannerUpdated = null; const scanner = inst(authScanner(), fields => { scannerUpdated = Object.assign(scannerUpdated || {}, fields); }); let channelBulk = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return scanner; } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; // 通道已登记 }, async bulkCreate(items) { channelBulk = items; return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate(items) { rows = items; return items; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [{ barcode: '6901234567890', scanTime: '2026-10-16 10:20:30', channelId: '1' }] }) .expect(200); assert(res.body.data.received === 1 && res.body.data.inserted === 1 && res.body.data.duplicated === 0); assert(rows[0].scannerId === 1, '记录要归属当前中控'); assert(rows[0].channelId === '1'); assert(rows[0].barcode === '6901234567890'); assert(rows[0].scanTime instanceof Date && rows[0].scanTime.getMilliseconds() === 0, '扫描时间截断到秒'); assert(rows[0].reportedAt instanceof Date, '应记录服务端接收时间'); assert(!channelBulk, '已登记的通道不该补建'); assert(scannerUpdated && scannerUpdated.lastSeenAt instanceof Date, '上报即视为心跳'); }); it('POST /api/scan/records 时间格式:支持 13 位 / 10 位时间戳,非法时间计入 invalid', async () => { let rows = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; }, async bulkCreate(items) { return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate(items) { rows = items; return items; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [ { barcode: 'A', scanTime: 1792137600000, channelId: '1' }, // 13 位毫秒 { barcode: 'B', scanTime: 1792137600, channelId: '1' }, // 10 位秒 { barcode: 'C', scanTime: '不是时间', channelId: '1' }, { barcode: 'D', scanTime: '2026-10-16T10:20:30', channelId: '1' }, ], }) .expect(200); assert(rows.length === 3, '合法时间入库 3 条'); assert(res.body.data.invalid === 1 && res.body.data.errors[0].message.includes('scanTime')); assert(rows[0].scanTime.getTime() === 1792137600000); assert(rows[1].scanTime.getTime() === 1792137600000); }); it('POST /api/scan/records 库里已存在 → 不入库、duplicated +1', async () => { let inserted = false; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; }, async bulkCreate(items) { return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return [ { scannerId: 1, channelId: '1', barcode: 'X1', scanTime: new Date('2026-10-16T10:00:00') } ]; }, async bulkCreate() { inserted = true; return []; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [{ barcode: 'X1', scanTime: '2026-10-16 10:00:00', channelId: '1' }] }) .expect(200); assert(res.body.data.inserted === 0 && res.body.data.duplicated === 1); assert(!inserted, '完全相同的记录不应再次入库'); }); it('POST /api/scan/records 同一批内重复只入库一次', async () => { let rows = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; }, async bulkCreate(items) { return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate(items) { rows = items; return items; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [ { barcode: 'A1', scanTime: '2026-10-16 10:00:00', channelId: '1' }, { barcode: 'A1', scanTime: '2026-10-16 10:00:00', channelId: '1' }, ], }) .expect(200); assert(rows.length === 1, '同批重复只留一条'); assert(res.body.data.received === 2 && res.body.data.inserted === 1 && res.body.data.duplicated === 1); }); it('POST /api/scan/records 未知通道自动补建(通道名留空)', async () => { let channelRows = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return []; }, // 通道从未登记 async bulkCreate(items) { channelRows = items; return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate(items) { return items; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [{ barcode: 'B1', scanTime: '2026-10-16 11:00:00', channelId: '9' }] }) .expect(200); assert(res.body.data.unknownChannels.length === 1 && res.body.data.unknownChannels[0] === '9'); assert(channelRows[0].channelId === '9' && channelRows[0].channelName === ''); assert(channelRows[0].scannerId === 1); }); it('POST /api/scan/records 唯一键冲突(并发重复)→ 退化成逐条插入,重复计数', async () => { let createCount = 0; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; }, async bulkCreate(items) { return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate() { const err = new Error('Duplicate entry'); err.name = 'SequelizeUniqueConstraintError'; throw err; }, async create() { createCount++; if (createCount === 1) { const err = new Error('Duplicate entry'); err.parent = { code: 'ER_DUP_ENTRY' }; throw err; } return {}; }, }, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [ { barcode: 'C1', scanTime: '2026-10-16 12:00:00', channelId: '1' }, { barcode: 'C2', scanTime: '2026-10-16 12:00:01', channelId: '1' }, ], }) .expect(200); assert(res.body.data.inserted === 1 && res.body.data.duplicated === 1); }); it('POST /api/scan/records 全部非法 / 空数组 → 分别返回 invalid 与 422', async () => { mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: {}, ScanRecord: {}, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [{ channelId: '1' }] }) // 缺条码与时间 .expect(200); assert(res.body.data.inserted === 0 && res.body.data.invalid === 1); await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send({ records: [] }).expect(422); }); it('POST /api/scan/records 支持 JSON 字符串形式的上报体', async () => { let rows = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); } }, ScanChannel: { async findAll() { return [ { channelId: '1' } ]; }, async bulkCreate(items) { return items; }, async update() { return [ 1 ]; }, }, ScanRecord: { async findAll() { return []; }, async bulkCreate(items) { rows = items; return items; }, }, }); await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: JSON.stringify([{ barcode: 'S1', scanTime: '2026-10-16 13:00:00', channelId: '1' }]) }) .expect(200); assert(rows.length === 1 && rows[0].barcode === 'S1'); }); it('GET /api/scan/channels 只返回当前中控的通道', async () => { let options = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); }, async findAll() { return []; }, }, ScanChannel: { async findAndCountAll(opts) { options = opts; return { rows: [ instance({ id: 1, scannerId: 1, channelId: '1', channelName: '1 号口', scanner: { sn: 'SN-HUB-01' } }) ], count: 1, }; }, }, }); const res = await app.httpRequest().get('/api/scan/channels?pageSize=5').set('Authorization', token()).expect(200); assert(options.where.scannerId === 1, '必须按当前中控过滤'); assert(options.limit === 5); assert(res.body.data.total === 1 && res.body.data.list[0].channelName === '1 号口'); }); it('GET /api/scan/records 支持通道/条码/时间过滤且只查当前中控', async () => { let options = null; mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner()); }, async findAll() { return []; }, }, ScanRecord: { async findAndCountAll(opts) { options = opts; return { rows: [ instance({ id: 3, scannerId: 1, channelId: '1', barcode: 'B1', scanTime: new Date() }) ], count: 1, }; }, }, }); const res = await app.httpRequest() .get('/api/scan/records?channelId=1&barcode=B1&startTime=2026-10-16&endTime=2026-10-17') .set('Authorization', token()) .expect(200); assert(options.where.scannerId === 1); assert(options.where.channelId === '1'); assert(String(options.where.barcode[Op.like]) === '%B1%'); assert(options.where.scanTime[Op.gte] instanceof Date && options.where.scanTime[Op.lte] instanceof Date); assert(options.order[0][0] === 'scanTime' && options.order[0][1] === 'DESC'); assert(res.body.data.total === 1 && res.body.data.list[0].barcode === 'B1'); }); it('被禁用的中控调用上报接口 → 403', async () => { mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner({ status: 0 })); } }, ScanChannel: {}, ScanRecord: {}, }); await app.httpRequest() .post('/api/scan/channels') .set('Authorization', token()) .send({ channels: [{ channelId: '1' }] }) .expect(403); }); it('已被轮换的旧 JWT 调上报接口 → 401(与 scanner 接口一致)', async () => { mock(app, 'model', { User: {}, Scanner: { async findByPk() { return instance(authScanner({ tokenJti: 'new-jti' })); } }, ScanChannel: {}, ScanRecord: {}, }); const res = await app.httpRequest() .post('/api/scan/records') .set('Authorization', token()) .send({ records: [{ barcode: 'A', scanTime: '2026-10-16 10:00:00', channelId: '1' }] }) .expect(401); assert(res.body.message.includes('已失效')); }); it('老的 sn + secret 登录入口已下线(设备统一走扫码登录)', async () => { const res = await app.httpRequest().post('/api/scanner/login').send({ sn: 'SN-HUB-01', secret: 'x' }).expect(404); assert(res.body.ok === false && res.body.message === '接口不存在', JSON.stringify(res.body)); }); });