refactor(arch): 落地平台架构演进第一二阶段整改,消除OOM与越权风险并支持高并发缓冲与AI多租户BYOK
- [P0安全底座] 多租户数据闭环:公开留资与雷达足迹自动逆向追溯绑定名片 tenantId 与归属销售 userId - [P0性能稳定] 消除内存全量加载:公海池分批带条件扫描回收,雷达国家分布改用 SQL 原生 GROUP BY 聚合查询彻底消除 OOM 隐患 - [P0商业变现] 商业化配额门禁切面:在 Cool-Admin modifyBefore 生命周期织入 assertQuotaAvailable 校验,阻断超额名片创建 - [P0环境解耦] 客户端解耦本地硬编码:request.uts 支持 api_base_url 本地覆盖,生产数据库名修正为 crmmpdata - [P1高并发削峰] 雷达足迹批量缓冲引擎:引入 CrmRadarBufferService 环形缓冲队列与阈值/定时批量 Bulk Insert 落盘 - [P2中枢租户化] AI 智能中枢多租户 BYOK 与 Token 成本风控:支持企业自带 Key 隔离、Token 消耗账本、用量配额门禁与名片人设个性化联动 - [跨端规范] 对齐 Uni-app x 移动微官网原生首屏与底部原生 tabBar 规范 - [测试驱动] 全工程 116 个测试套件,1,175 个单元与集成测试用例全部 100% 绿色通过,管理后台 Vite 打包无错误
这个提交包含在:
@@ -0,0 +1,197 @@
|
||||
import { adminCardInfoCurdOption } from '../../../src/modules/card/controller/admin/info';
|
||||
import { adminCardCasesCurdOption } from '../../../src/modules/card/controller/admin/cases';
|
||||
import { adminCardArticleCurdOption } from '../../../src/modules/card/controller/admin/article';
|
||||
import { adminCardBentoCurdOption } from '../../../src/modules/card/controller/admin/bento';
|
||||
import { adminCardLocaleCurdOption } from '../../../src/modules/card/controller/admin/locale';
|
||||
import { AdminCrmLeadController } from '../../../src/modules/crm/controller/admin/lead';
|
||||
import { AdminCrmRadarController } from '../../../src/modules/crm/controller/admin/radar';
|
||||
import { adminNfcDeviceCurdOption } from '../../../src/modules/nfc/controller/admin/device';
|
||||
import { adminNfcRuleCurdOption } from '../../../src/modules/nfc/controller/admin/rule';
|
||||
import { adminAiKnowledgeCurdOption } from '../../../src/modules/ai/controller/admin/knowledge';
|
||||
import { adminAiGlossaryCurdOption } from '../../../src/modules/ai/controller/admin/glossary';
|
||||
import { adminAiConciergeCurdOption } from '../../../src/modules/ai/controller/admin/concierge';
|
||||
import { adminTeamBrandCurdOption } from '../../../src/modules/team/controller/admin/brand';
|
||||
import { adminTeamDomainCurdOption } from '../../../src/modules/team/controller/admin/domain';
|
||||
import { BaseAuditLogController } from '../../../src/modules/base/controller/admin/audit';
|
||||
import { AiConciergeService } from '../../../src/modules/ai/service/concierge';
|
||||
import { getClassMetadata, CONTROLLER_KEY } from '@midwayjs/core';
|
||||
|
||||
describe('Admin Controllers & Services SQL Column Matching', () => {
|
||||
describe('1. Controller pageQueryOp SQL 列名必须与 MySQL 物理表字段一致', () => {
|
||||
it('Card Info pageQueryOp 应使用 update_time 与 theme_code', () => {
|
||||
expect(adminCardInfoCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminCardInfoCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining(['a.status', { column: 'a.theme_code', requestParam: 'themeCode' }])
|
||||
);
|
||||
});
|
||||
|
||||
it('Card Cases pageQueryOp 应使用 sort_order 与 card_id', () => {
|
||||
expect(adminCardCasesCurdOption.pageQueryOp.addOrderBy).toEqual({ sort_order: 'asc' });
|
||||
expect(adminCardCasesCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }])
|
||||
);
|
||||
});
|
||||
|
||||
it('Card Article pageQueryOp 应使用 update_time, card_id 与 is_published', () => {
|
||||
expect(adminCardArticleCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminCardArticleCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.is_published', requestParam: 'isPublished' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('Card Bento pageQueryOp 应使用 sort_order 与 card_id', () => {
|
||||
expect(adminCardBentoCurdOption.pageQueryOp.addOrderBy).toEqual({ sort_order: 'asc' });
|
||||
expect(adminCardBentoCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }, 'a.type', 'a.status'])
|
||||
);
|
||||
});
|
||||
|
||||
it('Card Locale pageQueryOp 应使用 card_id', () => {
|
||||
expect(adminCardLocaleCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }, 'a.locale'])
|
||||
);
|
||||
});
|
||||
|
||||
it('CRM Lead pageQueryOp 应使用 create_time 与 card_id', () => {
|
||||
const option = getClassMetadata(CONTROLLER_KEY, AdminCrmLeadController).curdOption;
|
||||
expect(option.pageQueryOp.addOrderBy).toEqual({ create_time: 'desc' });
|
||||
expect(option.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining(['a.status', 'a.source', { column: 'a.card_id', requestParam: 'cardId' }])
|
||||
);
|
||||
});
|
||||
|
||||
it('CRM Radar pageQueryOp 应使用 visitor_id 与 card_id, touch_type', () => {
|
||||
const option = getClassMetadata(CONTROLLER_KEY, AdminCrmRadarController).curdOption;
|
||||
expect(option.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.country', 'a.city', 'a.visitor_id', 'a.ip'])
|
||||
);
|
||||
expect(option.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.touch_type', requestParam: 'touchType' },
|
||||
'a.country',
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('NFC Device pageQueryOp 应使用 update_time, batch_no, card_id, scene_mode', () => {
|
||||
expect(adminNfcDeviceCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminNfcDeviceCurdOption.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.uid', 'a.batch_no'])
|
||||
);
|
||||
expect(adminNfcDeviceCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
'a.status',
|
||||
'a.material',
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('NFC Rule pageQueryOp 应使用 update_time, device_id, scene_mode, country_code', () => {
|
||||
expect((adminNfcRuleCurdOption.pageQueryOp as any).addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect((adminNfcRuleCurdOption.pageQueryOp as any).fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.device_id', requestParam: 'deviceId' },
|
||||
'a.enabled',
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
{ column: 'a.country_code', requestParam: 'countryCode' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('AI Knowledge pageQueryOp 应使用 update_time 与 card_id', () => {
|
||||
expect(adminAiKnowledgeCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminAiKnowledgeCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }, 'a.locale'])
|
||||
);
|
||||
});
|
||||
|
||||
it('AI Glossary pageQueryOp 应使用 update_time, source_term, target_term, source_lang, target_lang', () => {
|
||||
expect(adminAiGlossaryCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminAiGlossaryCurdOption.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.source_term', 'a.target_term', 'a.notes'])
|
||||
);
|
||||
expect(adminAiGlossaryCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.source_lang', requestParam: 'sourceLang' },
|
||||
{ column: 'a.target_lang', requestParam: 'targetLang' },
|
||||
'a.domain',
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('AI Concierge pageQueryOp 应使用 update_time, card_id, persona_type, is_enabled', () => {
|
||||
expect((adminAiConciergeCurdOption.pageQueryOp as any).addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect((adminAiConciergeCurdOption.pageQueryOp as any).fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.persona_type', requestParam: 'personaType' },
|
||||
{ column: 'a.is_enabled', requestParam: 'isEnabled' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('Team Brand pageQueryOp 应使用 update_time 与 company_name', () => {
|
||||
expect(adminTeamBrandCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminTeamBrandCurdOption.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.company_name'])
|
||||
);
|
||||
});
|
||||
|
||||
it('Team Domain pageQueryOp 应使用 update_time, custom_domain 与 ssl_status', () => {
|
||||
expect(adminTeamDomainCurdOption.pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
expect(adminTeamDomainCurdOption.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.custom_domain'])
|
||||
);
|
||||
expect(adminTeamDomainCurdOption.pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.ssl_status', requestParam: 'sslStatus' }])
|
||||
);
|
||||
});
|
||||
|
||||
it('Base Audit Log pageQueryOp 应使用 create_time 与 operator_name', () => {
|
||||
const option = getClassMetadata(CONTROLLER_KEY, BaseAuditLogController).curdOption;
|
||||
expect(option.pageQueryOp.addOrderBy).toEqual({ create_time: 'desc' });
|
||||
expect(option.pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.operator_name', 'a.action', 'a.module', 'a.ip'])
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. AiConciergeService 健壮入参处理 (防止 NaN 导致的 SQL 语法异常)', () => {
|
||||
let service: AiConciergeService;
|
||||
let mockFindOneBy: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiConciergeService();
|
||||
mockFindOneBy = jest.fn();
|
||||
service.aiConciergeEntity = {
|
||||
findOneBy: mockFindOneBy,
|
||||
} as any;
|
||||
});
|
||||
|
||||
it('getByCardId 支持对象入参 { cardId: 1 } 并正确提取数值', async () => {
|
||||
mockFindOneBy.mockResolvedValueOnce({
|
||||
id: 10,
|
||||
cardId: 1,
|
||||
personaType: 'trade_expert',
|
||||
welcomeMsg: 'Hello',
|
||||
});
|
||||
|
||||
const result = await service.getByCardId({ cardId: 1 } as any);
|
||||
expect(mockFindOneBy).toHaveBeenCalledWith({ cardId: 1 });
|
||||
expect(result.cardId).toBe(1);
|
||||
});
|
||||
|
||||
it('getByCardId 遇非法 cardId 应降级返回默认预设,禁止传递 NaN 给数据库', async () => {
|
||||
const result = await service.getByCardId({ cardId: NaN } as any);
|
||||
expect(mockFindOneBy).not.toHaveBeenCalled();
|
||||
expect(result.personaType).toBe('trade_expert');
|
||||
expect(result.cardId).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -217,4 +217,75 @@ describe('T36: 名片 AI 顾问对话 (modules/ai chat)', () => {
|
||||
expect(methods).toContain('ask');
|
||||
});
|
||||
});
|
||||
|
||||
describe('4. 多租户 BYOK 与 AI 人设顾问联动', () => {
|
||||
let service: AiChatService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiChatService();
|
||||
});
|
||||
|
||||
it('根据 cardId 自动回溯租户 tenantId 并透传至 chatCompletion', async () => {
|
||||
const mockDeepSeek = {
|
||||
isConfigured: jest.fn().mockReturnValue(true),
|
||||
chatCompletion: jest.fn().mockResolvedValue('租户专用模型回复'),
|
||||
};
|
||||
const mockCardRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 88, tenantId: 999 }),
|
||||
};
|
||||
|
||||
service.deepSeekService = mockDeepSeek as any;
|
||||
service.cardInfoEntity = mockCardRepo as any;
|
||||
|
||||
const res = await service.ask({
|
||||
cardId: 88,
|
||||
messages: [{ role: 'user', content: '您好' }],
|
||||
});
|
||||
|
||||
expect(res.reply).toBe('租户专用模型回复');
|
||||
expect(mockDeepSeek.chatCompletion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
messages: expect.any(Array),
|
||||
}),
|
||||
expect.any(String),
|
||||
999
|
||||
);
|
||||
});
|
||||
|
||||
it('注入 AiConciergeService 时将个性化人设编排进 system prompt', async () => {
|
||||
const mockDeepSeek = {
|
||||
isConfigured: jest.fn().mockReturnValue(true),
|
||||
chatCompletion: jest.fn().mockResolvedValue('人设定制回复'),
|
||||
};
|
||||
const mockConcierge = {
|
||||
getByCardId: jest.fn().mockResolvedValue({
|
||||
cardId: 66,
|
||||
personaType: 'tech_advisor',
|
||||
promptTemplate: '你是一名资深技术顾问',
|
||||
welcomeMsg: '欢迎咨询',
|
||||
}),
|
||||
};
|
||||
|
||||
service.deepSeekService = mockDeepSeek as any;
|
||||
service.aiConciergeService = mockConcierge as any;
|
||||
|
||||
await service.ask({
|
||||
cardId: 66,
|
||||
messages: [{ role: 'user', content: '系统架构是怎样的?' }],
|
||||
});
|
||||
|
||||
expect(mockDeepSeek.chatCompletion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
messages: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
role: 'system',
|
||||
content: expect.stringContaining('你是一名资深技术顾问'),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
expect.any(String),
|
||||
undefined
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { DeepSeekService } from '../../../src/modules/ai/service/deepseek';
|
||||
import { CoolCommException } from '@cool-midway/core';
|
||||
|
||||
describe('AI 智能中枢: 多租户 BYOK 配置隔离与 Token 成本风控', () => {
|
||||
let service: DeepSeekService;
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.DEEPSEEK_API_KEY;
|
||||
delete process.env.DEEPSEEK_BASE_URL;
|
||||
service = new DeepSeekService();
|
||||
});
|
||||
|
||||
describe('1. 租户专属配置隔离 (Tenant BYOK)', () => {
|
||||
it('未单独配置的租户,获取配置时应优雅回退至平台公共默认配置', () => {
|
||||
const tenantConfig = service.getTenantConfig(88);
|
||||
expect(tenantConfig.baseUrl).toBe('https://api.deepseek.com');
|
||||
expect(tenantConfig.model).toBe('deepseek-chat');
|
||||
expect(service.hasTenantConfig(88)).toBe(false);
|
||||
});
|
||||
|
||||
it('特定租户配置专属 API Key 与定制模型后,应严格与公共配置及其他租户隔离', () => {
|
||||
// 租户 101 配置独立 Key (BYOK)
|
||||
service.updateTenantConfig(101, {
|
||||
apiKey: 'sk-tenant-101-custom-key',
|
||||
model: 'deepseek-reasoner',
|
||||
baseUrl: 'https://gateway.company101.com',
|
||||
});
|
||||
|
||||
expect(service.hasTenantConfig(101)).toBe(true);
|
||||
const config101 = service.getTenantConfig(101);
|
||||
expect(config101.apiKey).toBe('sk-tenant-101-custom-key');
|
||||
expect(config101.model).toBe('deepseek-reasoner');
|
||||
expect(config101.baseUrl).toBe('https://gateway.company101.com');
|
||||
|
||||
// 租户 202 保持未受影响
|
||||
expect(service.hasTenantConfig(202)).toBe(false);
|
||||
const config202 = service.getTenantConfig(202);
|
||||
expect(config202.apiKey).toBeUndefined();
|
||||
expect(config202.baseUrl).toBe('https://api.deepseek.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. 租户 Token 消耗度量与限流风控 (Token Metering & Quota)', () => {
|
||||
it('调用 recordTokenUsage 应准确累计指定租户的 Token 消耗流水', () => {
|
||||
service.recordTokenUsage(101, {
|
||||
promptTokens: 120,
|
||||
completionTokens: 80,
|
||||
totalTokens: 200,
|
||||
});
|
||||
|
||||
service.recordTokenUsage(101, {
|
||||
promptTokens: 50,
|
||||
completionTokens: 50,
|
||||
totalTokens: 100,
|
||||
});
|
||||
|
||||
const usage = service.getTenantTokenUsage(101);
|
||||
expect(usage.totalTokens).toBe(300);
|
||||
expect(usage.promptTokens).toBe(170);
|
||||
expect(usage.completionTokens).toBe(130);
|
||||
expect(usage.callCount).toBe(2);
|
||||
});
|
||||
|
||||
it('当租户 Token 用量超出配额上限时,assertTenantTokenQuota 必须阻断抛错', () => {
|
||||
// 设置租户 101 最大配额 500 Token
|
||||
service.setTenantTokenQuota(101, 500);
|
||||
|
||||
service.recordTokenUsage(101, { totalTokens: 480 });
|
||||
|
||||
// 预估 10 Token,尚未超限 (490 <= 500)
|
||||
expect(() => service.assertTenantTokenQuota(101, 10)).not.toThrow();
|
||||
|
||||
// 预估 30 Token,超出配额 (480 + 30 = 510 > 500)
|
||||
expect(() => service.assertTenantTokenQuota(101, 30)).toThrow(CoolCommException);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -289,8 +289,12 @@ describe('后台 Bento 画布 CRUD (Admin Card Bento CoolController)', () => {
|
||||
fieldEq?: string[];
|
||||
addOrderBy?: Record<string, string>;
|
||||
};
|
||||
expect(pageQueryOp.fieldEq).toEqual(['a.cardId', 'a.type', 'a.status']);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ sortOrder: 'asc' });
|
||||
expect(pageQueryOp.fieldEq).toEqual([
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
'a.type',
|
||||
'a.status',
|
||||
]);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ sort_order: 'asc' });
|
||||
});
|
||||
|
||||
it('应将 getBlocksByCardId / batchSaveLayout / toggleStatus 注册为 serviceApis', () => {
|
||||
|
||||
@@ -52,7 +52,7 @@ describe('后台名片 CRUD (Admin Card Info CoolController)', () => {
|
||||
expect.arrayContaining(['a.name'])
|
||||
);
|
||||
expect(pageQueryOp.fieldEq).toEqual(expect.arrayContaining(['a.status']));
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ updateTime: 'desc' });
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
});
|
||||
|
||||
it('insertParam 应从后台登录态写入 userId', () => {
|
||||
|
||||
@@ -55,9 +55,12 @@ describe('后台博客文章与动态发布中心 (Card Article CoolController &
|
||||
expect.arrayContaining(['a.title', 'a.summary'])
|
||||
);
|
||||
expect(pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining(['a.cardId', 'a.isPublished'])
|
||||
expect.arrayContaining([
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.is_published', requestParam: 'isPublished' },
|
||||
])
|
||||
);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ updateTime: 'desc' });
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -48,11 +48,13 @@ describe('后台出海案例作品集 (Admin Card Cases CRUD)', () => {
|
||||
|
||||
it('pageQueryOp 应支持 a.cardId 精确筛选与 title/client/metrics 模糊搜索', () => {
|
||||
const pageQueryOp = adminCardCasesCurdOption.pageQueryOp;
|
||||
expect(pageQueryOp.fieldEq).toEqual(expect.arrayContaining(['a.cardId']));
|
||||
expect(pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }])
|
||||
);
|
||||
expect(pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.title', 'a.client', 'a.metrics'])
|
||||
);
|
||||
expect(pageQueryOp.addOrderBy).toMatchObject({ sortOrder: 'asc' });
|
||||
expect(pageQueryOp.addOrderBy).toMatchObject({ sort_order: 'asc' });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { CardContactService } from '../../../src/modules/card/service/contact';
|
||||
import {
|
||||
CardMutualExchangeService,
|
||||
createMutualExchangeInvitation,
|
||||
} from '../../../src/modules/card/service/mutual-exchange';
|
||||
|
||||
describe('P0 名片大厅人脉与双向互换落库', () => {
|
||||
let contactService: CardContactService;
|
||||
let exchangeService: CardMutualExchangeService;
|
||||
let contactStore: any[];
|
||||
let leadStore: any[];
|
||||
let cardStore: any[];
|
||||
let exchangeStore: any[];
|
||||
|
||||
function createRepo(store: any[], idStart = 1) {
|
||||
let seq = idStart;
|
||||
return {
|
||||
findOne: jest.fn(async (opts: { where?: Record<string, unknown> }) => {
|
||||
const where = opts?.where || {};
|
||||
return (
|
||||
store.find(row =>
|
||||
Object.keys(where).every(key => row[key] === (where as any)[key])
|
||||
) || null
|
||||
);
|
||||
}),
|
||||
find: jest.fn(async (opts?: { where?: Record<string, unknown> }) => {
|
||||
const where = opts?.where || {};
|
||||
return store.filter(row =>
|
||||
Object.keys(where).every(key => row[key] === (where as any)[key])
|
||||
);
|
||||
}),
|
||||
save: jest.fn(async (item: any) => {
|
||||
if (item.id) {
|
||||
const idx = store.findIndex(row => row.id === item.id);
|
||||
if (idx >= 0) {
|
||||
store[idx] = { ...store[idx], ...item };
|
||||
return store[idx];
|
||||
}
|
||||
}
|
||||
const saved = { ...item, id: item.id || seq++ };
|
||||
store.push(saved);
|
||||
return saved;
|
||||
}),
|
||||
createQueryBuilder: jest.fn(() => {
|
||||
const qb: any = {
|
||||
alias: 'a',
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
skip: jest.fn().mockReturnThis(),
|
||||
take: jest.fn().mockReturnThis(),
|
||||
getCount: jest.fn(async () =>
|
||||
store.filter(row => row.ownerUserId === 11).length
|
||||
),
|
||||
getRawAndEntities: jest.fn(async () => ({
|
||||
entities: store.filter(row => row.ownerUserId === 11),
|
||||
raw: [],
|
||||
})),
|
||||
};
|
||||
return qb;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
contactStore = [];
|
||||
leadStore = [];
|
||||
exchangeStore = [];
|
||||
cardStore = [
|
||||
{
|
||||
id: 101,
|
||||
userId: 11,
|
||||
tenantId: 1,
|
||||
name: 'Alex Rivera',
|
||||
title: 'VP',
|
||||
company: 'OmniCard',
|
||||
phone: '+8613800000001',
|
||||
email: 'alex@omni.test',
|
||||
slug: 'alex',
|
||||
status: 'published',
|
||||
},
|
||||
{
|
||||
id: 202,
|
||||
userId: 22,
|
||||
tenantId: 2,
|
||||
name: 'Tariq Mansour',
|
||||
title: 'Director',
|
||||
company: 'Dubai Energy',
|
||||
phone: '+971501234567',
|
||||
email: 'tariq@dubai.test',
|
||||
slug: 'tariq',
|
||||
status: 'published',
|
||||
},
|
||||
{
|
||||
id: 103,
|
||||
userId: 33,
|
||||
tenantId: 1,
|
||||
name: 'Chen Wei',
|
||||
title: 'Sales',
|
||||
company: 'OmniCard',
|
||||
phone: '+8613800000003',
|
||||
email: 'chen@omni.test',
|
||||
slug: 'chen-wei',
|
||||
status: 'published',
|
||||
},
|
||||
];
|
||||
|
||||
contactService = new CardContactService();
|
||||
contactService.cardContactEntity = createRepo(contactStore) as any;
|
||||
contactService.cardInfoEntity = createRepo(cardStore, 300) as any;
|
||||
contactService.crmLeadEntity = createRepo(leadStore, 500) as any;
|
||||
|
||||
exchangeService = new CardMutualExchangeService();
|
||||
exchangeService.exchangeEntity = createRepo(exchangeStore, 800) as any;
|
||||
exchangeService.cardContactService = contactService;
|
||||
exchangeService.cardInfoEntity = contactService.cardInfoEntity;
|
||||
exchangeService.crmLeadEntity = contactService.crmLeadEntity;
|
||||
});
|
||||
|
||||
it('不能把自己的名片收入自己的大厅', async () => {
|
||||
await expect(
|
||||
contactService.upsertContact({
|
||||
ownerUserId: 11,
|
||||
ownerCardId: 101,
|
||||
peerCardId: 101,
|
||||
source: 'collect',
|
||||
})
|
||||
).rejects.toThrow(/不能收藏自己/);
|
||||
});
|
||||
|
||||
it('收藏他人名片只写一行人脉,重复收藏复用同一行', async () => {
|
||||
const first = await contactService.collect({
|
||||
ownerUserId: 11,
|
||||
peerCardId: 202,
|
||||
});
|
||||
const second = await contactService.collect({
|
||||
ownerUserId: 11,
|
||||
peerCardId: 202,
|
||||
});
|
||||
|
||||
expect(contactStore).toHaveLength(1);
|
||||
expect(first.id).toBe(second.id);
|
||||
expect(first.peerCardId).toBe(202);
|
||||
expect(first.source).toBe('collect');
|
||||
expect(first.ownerUserId).toBe(11);
|
||||
});
|
||||
|
||||
it('确认互换后双方各有一条人脉和一条线索', async () => {
|
||||
const invite = await exchangeService.initiateExchange({
|
||||
senderCardId: 101,
|
||||
recipientCardId: 202,
|
||||
});
|
||||
expect(invite.status).toBe('REQUESTED');
|
||||
expect(exchangeStore).toHaveLength(1);
|
||||
|
||||
const outcome = await exchangeService.confirmExchange(invite.id, 202);
|
||||
|
||||
expect(outcome.status).toBe('ACCEPTED');
|
||||
expect(outcome.isDualSynced).toBe(true);
|
||||
expect(contactStore).toHaveLength(2);
|
||||
expect(leadStore).toHaveLength(2);
|
||||
|
||||
const alexContact = contactStore.find(row => row.ownerUserId === 11);
|
||||
const tariqContact = contactStore.find(row => row.ownerUserId === 22);
|
||||
expect(alexContact.peerCardId).toBe(202);
|
||||
expect(tariqContact.peerCardId).toBe(101);
|
||||
expect(alexContact.source).toBe('exchange');
|
||||
|
||||
expect(leadStore.every(row => row.source === 'exchange')).toBe(true);
|
||||
expect(leadStore.find(row => row.cardId === 101)?.name).toBe('Tariq Mansour');
|
||||
expect(leadStore.find(row => row.cardId === 202)?.name).toBe('Alex Rivera');
|
||||
});
|
||||
|
||||
it('大厅分页只返回当前用户的人脉', async () => {
|
||||
await contactService.collect({ ownerUserId: 11, peerCardId: 202 });
|
||||
await contactService.upsertContact({
|
||||
ownerUserId: 22,
|
||||
peerCardId: 101,
|
||||
source: 'collect',
|
||||
});
|
||||
|
||||
const page = await contactService.pageContacts({
|
||||
ownerUserId: 11,
|
||||
page: 1,
|
||||
size: 20,
|
||||
});
|
||||
|
||||
expect(page.list).toHaveLength(1);
|
||||
expect(page.list[0].peerCardId).toBe(202);
|
||||
expect(page.pagination.total).toBe(1);
|
||||
});
|
||||
|
||||
it('团队墙只返回同租户已发布名片,并排除自己', async () => {
|
||||
const page = await contactService.pageTeamWall({
|
||||
tenantId: 1,
|
||||
excludeUserId: 11,
|
||||
page: 1,
|
||||
size: 20,
|
||||
});
|
||||
|
||||
expect(page.list).toHaveLength(1);
|
||||
expect(page.list[0].peerCardId).toBe(103);
|
||||
expect(page.list[0].peerName).toBe('Chen Wei');
|
||||
expect(page.list.find(row => row.peerCardId === 101)).toBeUndefined();
|
||||
expect(page.list.find(row => row.peerCardId === 202)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('纯函数互换邀约仍拒绝自己与自己互换', () => {
|
||||
expect(() => createMutualExchangeInvitation(101, 101)).toThrow(
|
||||
/不能与自己互换/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { CardEventService, normalizeEventCode } from '../../../src/modules/card/service/event';
|
||||
|
||||
describe('P2 展会现场活动码与同场名片墙', () => {
|
||||
let eventService: CardEventService;
|
||||
let eventStore: any[];
|
||||
let memberStore: any[];
|
||||
let cardStore: any[];
|
||||
|
||||
function createRepo(store: any[], idStart = 1) {
|
||||
let seq = idStart;
|
||||
return {
|
||||
findOne: jest.fn(async (opts: { where?: Record<string, unknown> }) => {
|
||||
const where = opts?.where || {};
|
||||
return (
|
||||
store.find(row =>
|
||||
Object.keys(where).every(key => row[key] === (where as any)[key])
|
||||
) || null
|
||||
);
|
||||
}),
|
||||
find: jest.fn(async (opts?: { where?: Record<string, unknown> }) => {
|
||||
const where = opts?.where || {};
|
||||
return store.filter(row =>
|
||||
Object.keys(where).every(key => row[key] === (where as any)[key])
|
||||
);
|
||||
}),
|
||||
save: jest.fn(async (item: any) => {
|
||||
if (item.id) {
|
||||
const idx = store.findIndex(row => row.id === item.id);
|
||||
if (idx >= 0) {
|
||||
store[idx] = { ...store[idx], ...item };
|
||||
return store[idx];
|
||||
}
|
||||
}
|
||||
const saved = { ...item, id: item.id || seq++ };
|
||||
store.push(saved);
|
||||
return saved;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
eventStore = [];
|
||||
memberStore = [];
|
||||
cardStore = [
|
||||
{
|
||||
id: 101,
|
||||
userId: 11,
|
||||
tenantId: 1,
|
||||
name: 'Alex Rivera',
|
||||
title: 'VP',
|
||||
company: 'OmniCard',
|
||||
slug: 'alex',
|
||||
status: 'published',
|
||||
},
|
||||
{
|
||||
id: 103,
|
||||
userId: 33,
|
||||
tenantId: 1,
|
||||
name: 'Chen Wei',
|
||||
title: 'Sales',
|
||||
company: 'OmniCard',
|
||||
slug: 'chen-wei',
|
||||
status: 'published',
|
||||
},
|
||||
{
|
||||
id: 202,
|
||||
userId: 22,
|
||||
tenantId: 2,
|
||||
name: 'Tariq Mansour',
|
||||
title: 'Director',
|
||||
company: 'Dubai Energy',
|
||||
slug: 'tariq',
|
||||
status: 'published',
|
||||
},
|
||||
];
|
||||
eventService = new CardEventService();
|
||||
eventService.cardEventEntity = createRepo(eventStore) as any;
|
||||
eventService.cardEventMemberEntity = createRepo(memberStore, 50) as any;
|
||||
eventService.cardInfoEntity = createRepo(cardStore, 300) as any;
|
||||
});
|
||||
|
||||
it('normalizeEventCode 只接受 6 位字母数字', () => {
|
||||
expect(normalizeEventCode('ces26a')).toBe('CES26A');
|
||||
expect(() => normalizeEventCode('12')).toThrow(/活动码/);
|
||||
expect(() => normalizeEventCode('CES-26')).toThrow(/活动码/);
|
||||
});
|
||||
|
||||
it('首次加入活动码会创建现场并写入成员', async () => {
|
||||
const result = await eventService.joinEvent({
|
||||
userId: 11,
|
||||
code: 'ces26a',
|
||||
});
|
||||
|
||||
expect(result.event.code).toBe('CES26A');
|
||||
expect(result.event.status).toBe('active');
|
||||
expect(result.member.userId).toBe(11);
|
||||
expect(result.member.cardId).toBe(101);
|
||||
expect(eventStore).toHaveLength(1);
|
||||
expect(memberStore).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('同一用户重复加入同一现场只保留一行成员', async () => {
|
||||
await eventService.joinEvent({ userId: 11, code: 'CES26A' });
|
||||
await eventService.joinEvent({ userId: 11, code: 'ces26a' });
|
||||
|
||||
expect(eventStore).toHaveLength(1);
|
||||
expect(memberStore).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('现场墙只返回同场他人已发布名片', async () => {
|
||||
await eventService.joinEvent({ userId: 11, code: 'CES26A' });
|
||||
await eventService.joinEvent({ userId: 33, code: 'CES26A' });
|
||||
await eventService.joinEvent({ userId: 22, code: 'GITEX1' });
|
||||
|
||||
const page = await eventService.pageEventFloor({
|
||||
userId: 11,
|
||||
page: 1,
|
||||
size: 20,
|
||||
});
|
||||
|
||||
expect(page.list).toHaveLength(1);
|
||||
expect(page.list[0].peerCardId).toBe(103);
|
||||
expect(page.list[0].peerName).toBe('Chen Wei');
|
||||
expect(page.list[0].source).toBe('event');
|
||||
expect(page.list.find(row => row.peerCardId === 101)).toBeUndefined();
|
||||
expect(page.list.find(row => row.peerCardId === 202)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('未加入现场时墙为空', async () => {
|
||||
const page = await eventService.pageEventFloor({
|
||||
userId: 11,
|
||||
page: 1,
|
||||
size: 20,
|
||||
});
|
||||
expect(page.list).toHaveLength(0);
|
||||
expect(page.pagination.total).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -361,7 +361,7 @@ describe('T17 名片内容级多语言分支 (card_locale)', () => {
|
||||
fieldEq?: string[];
|
||||
};
|
||||
expect(pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining(['a.cardId', 'a.locale'])
|
||||
expect.arrayContaining([{ column: 'a.card_id', requestParam: 'cardId' }, 'a.locale'])
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { CardInfoService } from '../../../src/modules/card/service/info';
|
||||
import { TeamQuotaService } from '../../../src/modules/team/service/quota';
|
||||
import { CoolCommException } from '@cool-midway/core';
|
||||
|
||||
describe('商业化配额门禁: 新增名片配额校验与租户自动绑定', () => {
|
||||
let cardInfoService: CardInfoService;
|
||||
let mockQuotaService: any;
|
||||
let mockPortalService: any;
|
||||
let mockRepo: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepo = {
|
||||
save: jest.fn().mockImplementation(async (item: any) => ({ id: 1, ...item })),
|
||||
};
|
||||
|
||||
mockPortalService = {
|
||||
clearPortalCache: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
mockQuotaService = {
|
||||
assertQuotaAvailable: jest.fn().mockImplementation(async (tenantId: number, type: string) => {
|
||||
if (tenantId === 999) {
|
||||
throw new CoolCommException('当前套餐名片配额已达上限,请升级套餐', 400);
|
||||
}
|
||||
return { used: 1, limit: 5, exceeded: false };
|
||||
}),
|
||||
};
|
||||
|
||||
cardInfoService = new CardInfoService();
|
||||
cardInfoService.cardInfoEntity = mockRepo;
|
||||
cardInfoService.cardPortalService = mockPortalService;
|
||||
cardInfoService.teamQuotaService = mockQuotaService;
|
||||
});
|
||||
|
||||
it('当租户配额超限时,modifyBefore 新增拦截必须阻断并抛出 CoolCommException', async () => {
|
||||
const cardData = {
|
||||
name: '超限测试名片',
|
||||
tenantId: 999,
|
||||
};
|
||||
|
||||
await expect(
|
||||
cardInfoService.modifyBefore(cardData, 'add')
|
||||
).rejects.toThrow(/配额/);
|
||||
|
||||
expect(mockQuotaService.assertQuotaAvailable).toHaveBeenCalledWith(999, 'cards', 1);
|
||||
});
|
||||
|
||||
it('当租户配额充足时,modifyBefore 新增允许通过并自动锁定 tenantId', async () => {
|
||||
const cardData = {
|
||||
name: '合规名片',
|
||||
tenantId: 88,
|
||||
};
|
||||
|
||||
await expect(
|
||||
cardInfoService.modifyBefore(cardData, 'add')
|
||||
).resolves.not.toThrow();
|
||||
|
||||
expect(mockQuotaService.assertQuotaAvailable).toHaveBeenCalledWith(88, 'cards', 1);
|
||||
});
|
||||
});
|
||||
@@ -89,8 +89,12 @@ describe('CRM 管理后台 CRUD 控制器 (admin/crm)', () => {
|
||||
fieldEq?: string[];
|
||||
addOrderBy?: Record<string, string>;
|
||||
};
|
||||
expect(pageQueryOp.fieldEq).toEqual(['a.status', 'a.source', 'a.cardId']);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ createTime: 'desc' });
|
||||
expect(pageQueryOp.fieldEq).toEqual([
|
||||
'a.status',
|
||||
'a.source',
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
]);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ create_time: 'desc' });
|
||||
});
|
||||
|
||||
it('应将 updateStatus 注册为 serviceApi(线索状态流转)', () => {
|
||||
@@ -129,13 +133,13 @@ describe('CRM 管理后台 CRUD 控制器 (admin/crm)', () => {
|
||||
it('分页查询应支持国家/城市/访客/IP 模糊检索', () => {
|
||||
const pageQueryOp = option.pageQueryOp as {
|
||||
keyWordLikeFields?: string[];
|
||||
fieldEq?: string[];
|
||||
fieldEq?: unknown[];
|
||||
addOrderBy?: Record<string, string>;
|
||||
};
|
||||
expect(pageQueryOp.keyWordLikeFields).toEqual([
|
||||
'a.country',
|
||||
'a.city',
|
||||
'a.visitorId',
|
||||
'a.visitor_id',
|
||||
'a.ip',
|
||||
]);
|
||||
});
|
||||
@@ -143,12 +147,12 @@ describe('CRM 管理后台 CRUD 控制器 (admin/crm)', () => {
|
||||
it('分页查询应支持名片/触达方式/国家精确筛选,并按 id 倒序', () => {
|
||||
const pageQueryOp = option.pageQueryOp as {
|
||||
keyWordLikeFields?: string[];
|
||||
fieldEq?: string[];
|
||||
fieldEq?: unknown[];
|
||||
addOrderBy?: Record<string, string>;
|
||||
};
|
||||
expect(pageQueryOp.fieldEq).toEqual([
|
||||
'a.cardId',
|
||||
'a.touchType',
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.touch_type', requestParam: 'touchType' },
|
||||
'a.country',
|
||||
]);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ id: 'desc' });
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { CrmRadarService } from '../../../src/modules/crm/service/radar';
|
||||
|
||||
describe('性能与防 OOM: 雷达国家分布与时段统计原生 SQL 聚合机制', () => {
|
||||
let radarService: CrmRadarService;
|
||||
let mockQb: any;
|
||||
let mockTrackRepo: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockQb = {
|
||||
select: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
groupBy: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
getRawMany: jest.fn().mockResolvedValue([
|
||||
{ country: 'United Arab Emirates', visitorCount: '30', avgStayDurationMs: '45000' },
|
||||
{ country: 'Germany', visitorCount: '20', avgStayDurationMs: '30000' },
|
||||
{ country: 'United States', visitorCount: '10', avgStayDurationMs: '20000' },
|
||||
]),
|
||||
};
|
||||
|
||||
mockTrackRepo = {
|
||||
createQueryBuilder: jest.fn().mockReturnValue(mockQb),
|
||||
find: jest.fn(),
|
||||
};
|
||||
|
||||
radarService = new CrmRadarService();
|
||||
radarService.crmTrackEntity = mockTrackRepo;
|
||||
});
|
||||
|
||||
it('getCountryDistribution 必须使用 createQueryBuilder 原生 GROUP BY 聚合,严禁全表 find 加载至内存', async () => {
|
||||
const result = await radarService.getCountryDistribution(101);
|
||||
|
||||
expect(mockTrackRepo.createQueryBuilder).toHaveBeenCalledWith('track');
|
||||
expect(mockQb.select).toHaveBeenCalled();
|
||||
expect(mockQb.groupBy).toHaveBeenCalled();
|
||||
expect(mockQb.where).toHaveBeenCalledWith('track.card_id = :cardId', { cardId: 101 });
|
||||
expect(mockTrackRepo.find).not.toHaveBeenCalled();
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0].country).toBe('United Arab Emirates');
|
||||
expect(result[0].visitorCount).toBe(30);
|
||||
expect(result[0].percentage).toBe(50); // 30 / 60 * 100
|
||||
expect(result[0].avgStayDurationMs).toBe(45000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { CrmRadarBufferService } from '../../../src/modules/crm/service/buffer';
|
||||
import { CrmTrackEntity } from '../../../src/modules/crm/entity/track';
|
||||
|
||||
describe('高并发雷达削峰缓冲服务 (CrmRadarBufferService)', () => {
|
||||
let bufferService: CrmRadarBufferService;
|
||||
let insertedBatches: Array<any[]>;
|
||||
let mockTrackRepo: any;
|
||||
let mockInsertQb: any;
|
||||
|
||||
beforeEach(() => {
|
||||
insertedBatches = [];
|
||||
|
||||
mockInsertQb = {
|
||||
insert: jest.fn().mockReturnThis(),
|
||||
into: jest.fn().mockReturnThis(),
|
||||
values: jest.fn().mockImplementation((batch: any[]) => {
|
||||
insertedBatches.push([...batch]);
|
||||
return mockInsertQb;
|
||||
}),
|
||||
execute: jest.fn().mockResolvedValue({ identifiers: [] }),
|
||||
};
|
||||
|
||||
mockTrackRepo = {
|
||||
createQueryBuilder: jest.fn().mockReturnValue(mockInsertQb),
|
||||
save: jest.fn().mockImplementation(async (items: any[]) => {
|
||||
insertedBatches.push(Array.isArray(items) ? [...items] : [items]);
|
||||
return items;
|
||||
}),
|
||||
};
|
||||
|
||||
bufferService = new CrmRadarBufferService();
|
||||
bufferService.crmTrackEntity = mockTrackRepo;
|
||||
// 单元测试中设置较小的批次阈值,禁用自动定时器
|
||||
bufferService.setBatchSize(5);
|
||||
bufferService.setFlushInterval(0); // 禁用定时器以便手动可控测试
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
bufferService.stop();
|
||||
});
|
||||
|
||||
describe('1. 缓冲入队与队列状态 (Enqueue & Queue Length)', () => {
|
||||
it('调用 enqueue 能够将足迹实体推入内存环形队列,且非阻塞瞬间返回', async () => {
|
||||
const track: Partial<CrmTrackEntity> = {
|
||||
cardId: 101,
|
||||
tenantId: 88,
|
||||
visitorId: 'vis_test_001',
|
||||
touchType: 'nfc',
|
||||
country: 'United Arab Emirates',
|
||||
};
|
||||
|
||||
const queued = await bufferService.enqueue(track as CrmTrackEntity);
|
||||
expect(queued).toBe(true);
|
||||
expect(bufferService.getQueueLength()).toBe(1);
|
||||
// 队列未达批量阈值,尚未触发物理落盘
|
||||
expect(insertedBatches).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('队列到达批次阈值 (BatchSize) 时应自动触发批量 Bulk Insert 落盘', async () => {
|
||||
bufferService.setBatchSize(3);
|
||||
|
||||
await bufferService.enqueue({ cardId: 1, visitorId: 'v1' } as any);
|
||||
await bufferService.enqueue({ cardId: 2, visitorId: 'v2' } as any);
|
||||
expect(insertedBatches).toHaveLength(0);
|
||||
|
||||
// 放入第 3 条达到阈值,触发自动 flush
|
||||
await bufferService.enqueue({ cardId: 3, visitorId: 'v3' } as any);
|
||||
|
||||
expect(insertedBatches).toHaveLength(1);
|
||||
expect(insertedBatches[0]).toHaveLength(3);
|
||||
expect(bufferService.getQueueLength()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. 手动批量落盘与关闭刷新 (Flush & Stop)', () => {
|
||||
it('显式调用 flush 应将队列中剩余所有足迹一次性批量入库', async () => {
|
||||
bufferService.setBatchSize(100);
|
||||
|
||||
await bufferService.enqueue({ cardId: 1, visitorId: 'v1' } as any);
|
||||
await bufferService.enqueue({ cardId: 2, visitorId: 'v2' } as any);
|
||||
expect(bufferService.getQueueLength()).toBe(2);
|
||||
|
||||
const flushedCount = await bufferService.flush();
|
||||
expect(flushedCount).toBe(2);
|
||||
expect(bufferService.getQueueLength()).toBe(0);
|
||||
expect(insertedBatches).toHaveLength(1);
|
||||
expect(insertedBatches[0][0].visitorId).toBe('v1');
|
||||
expect(insertedBatches[0][1].visitorId).toBe('v2');
|
||||
});
|
||||
|
||||
it('空队列调用 flush 应安全返回 0 且不执行数据库写入', async () => {
|
||||
const flushedCount = await bufferService.flush();
|
||||
expect(flushedCount).toBe(0);
|
||||
expect(insertedBatches).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('调用 stop 应清除内部定时器并把剩余积攒数据完全 flush', async () => {
|
||||
await bufferService.enqueue({ cardId: 99, visitorId: 'v_exit' } as any);
|
||||
bufferService.stop();
|
||||
|
||||
expect(insertedBatches).toHaveLength(1);
|
||||
expect(bufferService.getQueueLength()).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { CrmLeadService } from '../../../src/modules/crm/service/lead';
|
||||
import { CrmRadarService } from '../../../src/modules/crm/service/radar';
|
||||
import { CardInfoEntity } from '../../../src/modules/card/entity/info';
|
||||
import { CrmLeadEntity } from '../../../src/modules/crm/entity/lead';
|
||||
import { CrmTrackEntity } from '../../../src/modules/crm/entity/track';
|
||||
|
||||
describe('多租户安全闭环: 公开留资与雷达足迹自动绑定名片所属租户', () => {
|
||||
let leadService: CrmLeadService;
|
||||
let radarService: CrmRadarService;
|
||||
|
||||
const mockCard: Partial<CardInfoEntity> = {
|
||||
id: 101,
|
||||
tenantId: 88,
|
||||
userId: 12,
|
||||
name: '测试名片',
|
||||
};
|
||||
|
||||
let mockCardRepo: any;
|
||||
let mockLeadRepo: any;
|
||||
let mockTrackRepo: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockCardRepo = {
|
||||
findOne: jest.fn().mockImplementation(async ({ where }: any) => {
|
||||
if (where?.id === 101) {
|
||||
return { ...mockCard };
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
};
|
||||
|
||||
mockLeadRepo = {
|
||||
save: jest.fn().mockImplementation(async (item: any) => {
|
||||
return { id: 1, ...item };
|
||||
}),
|
||||
};
|
||||
|
||||
mockTrackRepo = {
|
||||
save: jest.fn().mockImplementation(async (item: any) => {
|
||||
return { id: 1, ...item };
|
||||
}),
|
||||
};
|
||||
|
||||
leadService = new CrmLeadService();
|
||||
leadService.crmLeadEntity = mockLeadRepo;
|
||||
leadService.cardInfoEntity = mockCardRepo;
|
||||
|
||||
radarService = new CrmRadarService();
|
||||
radarService.crmTrackEntity = mockTrackRepo;
|
||||
radarService.cardInfoEntity = mockCardRepo;
|
||||
});
|
||||
|
||||
describe('1. CrmLeadService.submitLead 租户自动继承', () => {
|
||||
it('公开留资未显式传入 tenantId 时,必须根据 cardId 自动追溯绑定归属名片的 tenantId 和 userId', async () => {
|
||||
const lead = await leadService.submitLead({
|
||||
cardId: 101,
|
||||
name: '海外采购商',
|
||||
phone: '+971-50-9876543',
|
||||
company: 'Dubai Trading LLC',
|
||||
});
|
||||
|
||||
expect(mockCardRepo.findOne).toHaveBeenCalledWith({ where: { id: 101 } });
|
||||
expect(lead.tenantId).toBe(88);
|
||||
expect(lead.userId).toBe(12);
|
||||
});
|
||||
|
||||
it('若显式指定了有效 tenantId,则应保持显式值', async () => {
|
||||
const lead = await leadService.submitLead({
|
||||
cardId: 101,
|
||||
tenantId: 999,
|
||||
name: '海外采购商',
|
||||
phone: '+971-50-9876543',
|
||||
} as any);
|
||||
|
||||
expect(lead.tenantId).toBe(999);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. CrmRadarService.recordTrack 租户自动继承', () => {
|
||||
it('公开雷达足迹未传入 tenantId 时,必须根据 cardId 自动补齐名片所属 tenantId', async () => {
|
||||
const track = await radarService.recordTrack({
|
||||
cardId: 101,
|
||||
ip: '8.8.8.8',
|
||||
touchType: 'nfc',
|
||||
});
|
||||
|
||||
expect(mockCardRepo.findOne).toHaveBeenCalledWith({ where: { id: 101 } });
|
||||
expect(track.tenantId).toBe(88);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -395,17 +395,17 @@ describe('T21 NFC 设备台账 (nfc_device)', () => {
|
||||
addOrderBy?: Record<string, string>;
|
||||
};
|
||||
expect(pageQueryOp.keyWordLikeFields).toEqual(
|
||||
expect.arrayContaining(['a.uid', 'a.batchNo'])
|
||||
expect.arrayContaining(['a.uid', 'a.batch_no'])
|
||||
);
|
||||
expect(pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
'a.status',
|
||||
'a.material',
|
||||
'a.cardId',
|
||||
'a.sceneMode',
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
])
|
||||
);
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ updateTime: 'desc' });
|
||||
expect(pageQueryOp.addOrderBy).toEqual({ update_time: 'desc' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -425,14 +425,14 @@ describe('T23 NFC 场景路由规则 (nfc_rule)', () => {
|
||||
|
||||
it('pageQueryOp.fieldEq 应支持 deviceId/enabled/sceneMode/countryCode', () => {
|
||||
const pageQueryOp = option.pageQueryOp as {
|
||||
fieldEq?: string[];
|
||||
fieldEq?: any[];
|
||||
};
|
||||
expect(pageQueryOp.fieldEq).toEqual(
|
||||
expect.arrayContaining([
|
||||
'a.deviceId',
|
||||
{ column: 'a.device_id', requestParam: 'deviceId' },
|
||||
'a.enabled',
|
||||
'a.sceneMode',
|
||||
'a.countryCode',
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
{ column: 'a.country_code', requestParam: 'countryCode' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
在新工单中引用
屏蔽一个用户