import * as fs from 'fs'; import * as path from 'path'; import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core'; import { BaseController, CoolCommException, CurdOption } from '@cool-midway/core'; import { NfcDeviceEntity } from '../../../src/modules/nfc/entity/device'; import { NfcBindService } from '../../../src/modules/nfc/service/bind'; import { AdminNfcBindController, adminNfcBindCurdOption, } from '../../../src/modules/nfc/controller/admin/bind'; /** * CoolController 元数据(脚本路径解析为异步) */ interface CoolControllerMeta { prefix?: string; curdOption?: CurdOption; } /** * 等待 CoolController 将 CRUD 配置写入类元数据 */ async function waitCoolMeta( target: new (...args: never[]) => unknown ): Promise { const started = Date.now(); while (Date.now() - started < 2000) { const meta = getClassMetadata(CONTROLLER_KEY, target) as | CoolControllerMeta | undefined; if (meta?.curdOption) { return meta; } await new Promise(resolve => setImmediate(resolve)); } throw new Error(`${target.name} 的 CoolController 元数据未就绪`); } function serviceApiMethods(apis: CurdOption['serviceApis'] = []): string[] { return apis.map(api => (typeof api === 'string' ? api : api.method)); } /** * 内存 Repository,覆盖 findOneBy / save */ class MemoryNfcDeviceRepo { private data: NfcDeviceEntity[] = []; private currentId = 1; constructor(initialData: Array> = []) { this.data = initialData.map(item => this.createEntity(item)); if (this.data.length > 0) { this.currentId = Math.max(...this.data.map(d => Number(d.id) || 0)) + 1; } } private createEntity(item: Partial): NfcDeviceEntity { const entity = new NfcDeviceEntity(); Object.assign(entity, { id: item.id || this.currentId++, createTime: item.createTime || new Date(), updateTime: new Date(), ...item, }); return entity; } async findOneBy( where: Partial> ): Promise { const found = this.data.find(item => { const keys = Object.keys(where) as Array; return keys.every(key => { const expected = where[key]; return expected === undefined || item[key] === expected; }); }); return found ? ({ ...found } as NfcDeviceEntity) : null; } async save( entityOrEntities: | Partial | Array> ): Promise { if (Array.isArray(entityOrEntities)) { const savedList: NfcDeviceEntity[] = []; for (const item of entityOrEntities) { savedList.push((await this.save(item)) as NfcDeviceEntity); } return savedList; } const item = entityOrEntities; if (item.id) { const index = this.data.findIndex(d => d.id === item.id); if (index !== -1) { this.data[index] = { ...this.data[index], ...item, updateTime: new Date(), } as NfcDeviceEntity; return { ...this.data[index] } as NfcDeviceEntity; } } const newEntity = this.createEntity(item); this.data.push(newEntity); return { ...newEntity } as NfcDeviceEntity; } } function createService( seed: Array> = [] ): NfcBindService { const service = new NfcBindService(); service.nfcDeviceEntity = new MemoryNfcDeviceRepo( seed ) as unknown as NfcBindService['nfcDeviceEntity']; return service; } function seedDevices(): Array> { return [ { id: 1, uid: '04:7A:B2:8F:1C:6D:80', cardId: null, batchNo: 'B2026-001', material: 'pvc', status: 'unbound', sceneMode: 'business', }, { id: 2, uid: '04:AA:BB:CC:DD:EE:01', cardId: 100, batchNo: 'B2026-001', material: 'metal', status: 'suspended', sceneMode: 'business', }, { id: 3, uid: '04:11:22:33:44:55:66', cardId: 200, batchNo: 'B2026-002', material: 'wood', status: 'active', sceneMode: 'business', }, { id: 4, uid: '04:UN:BD:CD:EF:01:02', cardId: 300, batchNo: 'B2026-003', material: 'pvc', status: 'unbound', sceneMode: 'social', }, ]; } describe('T22 NFC 绑定激活 (动态云端短链)', () => { describe('1. Service bind / activate / switchCard / unbind', () => { it('未挂失设备可 bind 成 active', async () => { const service = createService(seedDevices()); const bound = await service.bind({ uid: '04:7A:B2:8F:1C:6D:80', cardId: 88, }); expect(bound.uid).toBe('04:7A:B2:8F:1C:6D:80'); expect(bound.cardId).toBe(88); expect(bound.status).toBe('active'); }); it('suspended 设备不能 bind', async () => { const service = createService(seedDevices()); await expect( service.bind({ uid: '04:AA:BB:CC:DD:EE:01', cardId: 88, }) ).rejects.toThrow(CoolCommException); }); it('已有 cardId 的 unbound 设备可 activate 成 active', async () => { const service = createService(seedDevices()); const activated = await service.activate({ uid: '04:UN:BD:CD:EF:01:02', }); expect(activated.cardId).toBe(300); expect(activated.status).toBe('active'); expect(activated.uid).toBe('04:UN:BD:CD:EF:01:02'); }); it('无 cardId 或已挂失时不能 activate', async () => { const service = createService(seedDevices()); await expect( service.activate({ uid: '04:7A:B2:8F:1C:6D:80' }) ).rejects.toThrow(CoolCommException); await expect( service.activate({ uid: '04:AA:BB:CC:DD:EE:01' }) ).rejects.toThrow(CoolCommException); }); it('switchCard 只改 cardId,不改 uid', async () => { const service = createService(seedDevices()); const switched = await service.switchCard({ uid: '04:11:22:33:44:55:66', cardId: 501, }); expect(switched.uid).toBe('04:11:22:33:44:55:66'); expect(switched.cardId).toBe(501); expect(switched.status).toBe('active'); expect(switched.batchNo).toBe('B2026-002'); }); it('unbind 后 status 为 unbound 且 cardId 为空', async () => { const service = createService(seedDevices()); const unbound = await service.unbind({ uid: '04:11:22:33:44:55:66', }); expect(unbound.status).toBe('unbound'); expect(unbound.cardId == null).toBe(true); expect(unbound.uid).toBe('04:11:22:33:44:55:66'); }); it('uid 缺失或设备未入台账时应拒绝', async () => { const service = createService(seedDevices()); await expect(service.bind({ uid: '', cardId: 1 })).rejects.toThrow( CoolCommException ); await expect( service.bind({ uid: '04:NOT:IN:LEDGER', cardId: 1 }) ).rejects.toThrow(CoolCommException); }); }); describe('2. 后台控制器 /admin/nfc/bind', () => { const controllerFile = path.join( __dirname, '../../../src/modules/nfc/controller/admin/bind.ts' ); let meta: CoolControllerMeta; let option: CurdOption; beforeAll(async () => { meta = await waitCoolMeta(AdminNfcBindController); option = meta.curdOption as CurdOption; }); it('文件路径应符合 /admin/nfc/bind 自动路由约定', () => { expect(fs.existsSync(controllerFile)).toBe(true); expect(controllerFile.replace(/\\/g, '/')).toMatch( /modules\/nfc\/controller\/admin\/bind\.ts$/ ); }); it('路由前缀应为 /admin/nfc/bind', () => { expect(meta.prefix).toBe('/admin/nfc/bind'); }); it('控制器应继承 BaseController 并绑定 NfcBindService,不开 CRUD', () => { expect(AdminNfcBindController.prototype).toBeInstanceOf(BaseController); expect(option.service).toBe(NfcBindService); expect(adminNfcBindCurdOption.service).toBe(NfcBindService); expect(option.api || []).toEqual([]); }); it('serviceApis 应包含 bind / activate / switchCard / unbind', () => { const methods = serviceApiMethods(option.serviceApis); expect(methods).toEqual(['bind', 'activate', 'switchCard', 'unbind']); }); }); });