feat: 完成全系统30个功能点开发与E2E全链路验收 (8轮调度32个子代理闭环)
- 模块一: 出海案例作品集、博客动态发布、人名发音语音条、RTL阿语多语言切换 - 模块二: AI顾问人设配置、行业术语库润色、RAG切片沙盒调试、流式会话与意向留资卡片 - 模块三: 全球访客雷达大屏、多维加权意向算分、外部CRM对接推送、团队公海池流转 - 模块四: 移动端NFC安全挂失、NFC动态路由规则配置、动态防伪验签、展会制卡Zip批量导出 - 模块五: 组织架构与名片分配、移动端个人中心设置、离职交接与历史线索迁移、安全审计日志 - 模块六: Stripe国际信用卡订阅Webhook、独立二级域名与SSL检测、坐席配额预警、多币种发票 - 模块七: 纸质名片OCR解析入库、国际商务日程RFC 5545 ICS日历、微官网离线SWR预加载、展会实时排行榜大屏 - 模块八: 全球出海SEO OpenGraph元标签注入与社交爬虫探测、30点端到端全链路业务流集成测试套件
这个提交包含在:
202
backend/test/modules/ai/chat.test.ts
普通文件
202
backend/test/modules/ai/chat.test.ts
普通文件
@@ -0,0 +1,202 @@
|
||||
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 { AiChatService } from '../../../src/modules/ai/service/chat';
|
||||
import {
|
||||
OpenAiChatController,
|
||||
openAiChatCurdOption,
|
||||
} from '../../../src/modules/ai/controller/open/chat';
|
||||
import { AiChatRequest } from '../../../src/comm/types/omni';
|
||||
|
||||
/**
|
||||
* CoolController 元数据(脚本路径解析为异步)
|
||||
*/
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待 CoolController 将 CRUD 配置写入类元数据
|
||||
*/
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(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));
|
||||
}
|
||||
|
||||
function userAsk(
|
||||
content: string,
|
||||
extra?: Partial<AiChatRequest>
|
||||
): AiChatRequest {
|
||||
return {
|
||||
cardId: extra?.cardId ?? 101,
|
||||
locale: extra?.locale,
|
||||
messages: extra?.messages ?? [{ role: 'user', content }],
|
||||
};
|
||||
}
|
||||
|
||||
describe('T36: 名片 AI 顾问对话 (modules/ai chat)', () => {
|
||||
describe('1. AiChatService.ask 入参校验', () => {
|
||||
let service: AiChatService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiChatService();
|
||||
});
|
||||
|
||||
it('缺 cardId 应抛 CoolCommException', async () => {
|
||||
await expect(
|
||||
service.ask({
|
||||
cardId: '' as unknown as number,
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.ask({
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
} as AiChatRequest)
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('空 messages 应抛 CoolCommException', async () => {
|
||||
await expect(
|
||||
service.ask({ cardId: 101, messages: [] })
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.ask({ cardId: 101, messages: undefined as unknown as [] })
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('最后一条非 user 或内容为空应抛 CoolCommException', async () => {
|
||||
await expect(
|
||||
service.ask({
|
||||
cardId: 101,
|
||||
messages: [{ role: 'assistant', content: 'hi' }],
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.ask({
|
||||
cardId: 101,
|
||||
messages: [{ role: 'user', content: ' ' }],
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. RuleBased 回复与留资意图', () => {
|
||||
let service: AiChatService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiChatService();
|
||||
});
|
||||
|
||||
it('价格问题 shouldCollectLead=true,并引导留资', async () => {
|
||||
const result = await service.ask(userAsk('What is the price for a partnership?'));
|
||||
expect(result.shouldCollectLead).toBe(true);
|
||||
expect(result.reply).toBeTruthy();
|
||||
expect(result.locale).toBe('en-US');
|
||||
});
|
||||
|
||||
it('合作 / 联系问题 shouldCollectLead=true', async () => {
|
||||
const coop = await service.ask(userAsk('想谈合作'));
|
||||
expect(coop.shouldCollectLead).toBe(true);
|
||||
|
||||
const contact = await service.ask(
|
||||
userAsk('How can I contact you?', { locale: 'en-GB' })
|
||||
);
|
||||
expect(contact.shouldCollectLead).toBe(true);
|
||||
expect(contact.locale).toBe('en-GB');
|
||||
});
|
||||
|
||||
it('普通问候 shouldCollectLead=false 且 reply 非空', async () => {
|
||||
const result = await service.ask(userAsk('hello'));
|
||||
expect(result.shouldCollectLead).toBe(false);
|
||||
expect(result.reply).toBeTruthy();
|
||||
expect(result.reply.trim().length).toBeGreaterThan(0);
|
||||
expect(result.locale).toBe('en-US');
|
||||
});
|
||||
|
||||
it('locale 缺省为 en-US,英文回复不含中文', async () => {
|
||||
const result = await service.ask(userAsk('hi there'));
|
||||
expect(result.locale).toBe('en-US');
|
||||
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(false);
|
||||
});
|
||||
|
||||
it('zh-CN 回复含中文', async () => {
|
||||
const result = await service.ask(userAsk('你好', { locale: 'zh-CN' }));
|
||||
expect(result.locale).toBe('zh-CN');
|
||||
expect(result.shouldCollectLead).toBe(false);
|
||||
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(true);
|
||||
});
|
||||
|
||||
it('兼容 serviceApis 单对象入参', async () => {
|
||||
const body: AiChatRequest = {
|
||||
cardId: 88,
|
||||
locale: 'zh-CN',
|
||||
messages: [
|
||||
{ role: 'system', content: 'concierge' },
|
||||
{ role: 'user', content: '价格多少' },
|
||||
],
|
||||
};
|
||||
const result = await service.ask(body);
|
||||
expect(result.shouldCollectLead).toBe(true);
|
||||
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. OpenAiChatController /open/ai/chat', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/open/chat.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(OpenAiChatController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('文件路径应符合 /open/ai/chat 自动路由约定', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(controllerFile.replace(/\\/g, '/')).toMatch(
|
||||
/modules\/ai\/controller\/open\/chat\.ts$/
|
||||
);
|
||||
});
|
||||
|
||||
it('路由前缀应为 /open/ai/chat', () => {
|
||||
expect(meta.prefix).toBe('/open/ai/chat');
|
||||
});
|
||||
|
||||
it('控制器应继承 BaseController,绑定 AiChatService,不开 CRUD', () => {
|
||||
expect(OpenAiChatController.prototype).toBeInstanceOf(BaseController);
|
||||
expect(option.service).toBe(AiChatService);
|
||||
expect(openAiChatCurdOption.service).toBe(AiChatService);
|
||||
expect(option.api || []).toEqual([]);
|
||||
});
|
||||
|
||||
it('serviceApis 应包含 ask', () => {
|
||||
const methods = serviceApiMethods(option.serviceApis);
|
||||
expect(methods).toContain('ask');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,279 @@
|
||||
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 { getMetadataArgsStorage, Repository } from 'typeorm';
|
||||
import { BaseEntity } from '../../../src/comm/entity/base';
|
||||
import { AiConciergeEntity } from '../../../src/modules/ai/entity/concierge';
|
||||
import { AiConciergeService } from '../../../src/modules/ai/service/concierge';
|
||||
import {
|
||||
AdminAiConciergeController,
|
||||
adminAiConciergeCurdOption,
|
||||
} from '../../../src/modules/ai/controller/admin/concierge';
|
||||
import { AiConciergeConfig, ConciergePersonaType } from '../../../src/comm/types/omni';
|
||||
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(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));
|
||||
}
|
||||
|
||||
describe('Point 05: 后台名片 AI 顾问人设与意向留资策略配置', () => {
|
||||
describe('1. 实体定义与表结构 (AiConciergeEntity)', () => {
|
||||
const metadata = getMetadataArgsStorage();
|
||||
|
||||
it('实体表名必须为 ai_concierge 并继承 BaseEntity', () => {
|
||||
const table = metadata.tables.find(t => t.target === AiConciergeEntity);
|
||||
expect(table).toBeDefined();
|
||||
expect(table?.name).toBe('ai_concierge');
|
||||
expect(AiConciergeEntity.prototype).toBeInstanceOf(BaseEntity);
|
||||
});
|
||||
|
||||
it('数据库列名必须严格采用下划线命名', () => {
|
||||
const columns = metadata.columns.filter(c => c.target === AiConciergeEntity);
|
||||
const expectedColumnMappings: Record<string, string> = {
|
||||
cardId: 'card_id',
|
||||
personaType: 'persona_type',
|
||||
welcomeMsg: 'welcome_msg',
|
||||
triggerLeadThreshold: 'trigger_lead_threshold',
|
||||
promptTemplate: 'prompt_template',
|
||||
toneStyle: 'tone_style',
|
||||
isEnabled: 'is_enabled',
|
||||
};
|
||||
|
||||
for (const [prop, dbCol] of Object.entries(expectedColumnMappings)) {
|
||||
const col = columns.find(c => c.propertyName === prop);
|
||||
expect(col).toBeDefined();
|
||||
expect(col?.options.name || col?.propertyName).toBe(dbCol);
|
||||
}
|
||||
});
|
||||
|
||||
it('cardId 字段必须声明索引', () => {
|
||||
const indexes = metadata.indices.filter(i => i.target === AiConciergeEntity);
|
||||
const cardIndex = indexes.find(i => {
|
||||
if (Array.isArray(i.columns)) {
|
||||
return i.columns.includes('cardId') || i.columns.includes('card_id');
|
||||
}
|
||||
return false;
|
||||
});
|
||||
expect(cardIndex).toBeDefined();
|
||||
});
|
||||
|
||||
it('实体实例能赋值并满足 AiConciergeConfig 契约', () => {
|
||||
const entity = new AiConciergeEntity();
|
||||
entity.id = 1;
|
||||
entity.cardId = 101;
|
||||
entity.personaType = 'trade_expert';
|
||||
entity.welcomeMsg = 'Hello! How can I assist your business?';
|
||||
entity.triggerLeadThreshold = 75;
|
||||
entity.promptTemplate = 'You are an export trade consultant.';
|
||||
entity.toneStyle = 'professional';
|
||||
entity.isEnabled = true;
|
||||
|
||||
const config: AiConciergeConfig = entity;
|
||||
expect(config.cardId).toBe(101);
|
||||
expect(config.personaType).toBe('trade_expert');
|
||||
expect(config.triggerLeadThreshold).toBe(75);
|
||||
expect(config.isEnabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. 服务逻辑与校验 (AiConciergeService)', () => {
|
||||
let service: AiConciergeService;
|
||||
let mockRepo: Partial<Repository<AiConciergeEntity>>;
|
||||
let savedStore: Map<number, AiConciergeEntity>;
|
||||
|
||||
beforeEach(() => {
|
||||
savedStore = new Map();
|
||||
mockRepo = {
|
||||
findOneBy: jest.fn(async (where: { cardId?: number }) => {
|
||||
if (!where.cardId) return null;
|
||||
return savedStore.get(where.cardId) || null;
|
||||
}),
|
||||
save: jest.fn(async (entity: any) => {
|
||||
const toSave = { ...entity, id: entity.id || Date.now() };
|
||||
savedStore.set(Number(toSave.cardId), toSave);
|
||||
return toSave;
|
||||
}),
|
||||
};
|
||||
|
||||
service = new AiConciergeService();
|
||||
(service as any).aiConciergeEntity = mockRepo;
|
||||
});
|
||||
|
||||
it('getDefaultPersona 应支持 trade_expert / business_rep / tech_advisor 并返回预设配置', () => {
|
||||
const expert = service.getDefaultPersona('trade_expert');
|
||||
expect(expert.personaType).toBe('trade_expert');
|
||||
expect(expert.welcomeMsg.length).toBeGreaterThan(0);
|
||||
expect(expert.promptTemplate.length).toBeGreaterThan(0);
|
||||
expect(expert.toneStyle).toBe('professional');
|
||||
expect(expert.triggerLeadThreshold).toBeGreaterThanOrEqual(50);
|
||||
expect(expert.triggerLeadThreshold).toBeLessThanOrEqual(90);
|
||||
|
||||
const rep = service.getDefaultPersona('business_rep');
|
||||
expect(rep.personaType).toBe('business_rep');
|
||||
expect(rep.welcomeMsg.length).toBeGreaterThan(0);
|
||||
|
||||
const tech = service.getDefaultPersona('tech_advisor');
|
||||
expect(tech.personaType).toBe('tech_advisor');
|
||||
expect(tech.welcomeMsg.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('validate 校验非法入参应抛出 CoolCommException', () => {
|
||||
// 缺少 cardId
|
||||
expect(() =>
|
||||
service.validate({
|
||||
welcomeMsg: 'hi',
|
||||
triggerLeadThreshold: 60,
|
||||
})
|
||||
).toThrow(CoolCommException);
|
||||
|
||||
// welcomeMsg 为空
|
||||
expect(() =>
|
||||
service.validate({
|
||||
cardId: 101,
|
||||
welcomeMsg: ' ',
|
||||
triggerLeadThreshold: 60,
|
||||
})
|
||||
).toThrow(CoolCommException);
|
||||
|
||||
// triggerLeadThreshold 超出 0~100 范围
|
||||
expect(() =>
|
||||
service.validate({
|
||||
cardId: 101,
|
||||
welcomeMsg: 'hi',
|
||||
triggerLeadThreshold: -5,
|
||||
})
|
||||
).toThrow(CoolCommException);
|
||||
|
||||
expect(() =>
|
||||
service.validate({
|
||||
cardId: 101,
|
||||
welcomeMsg: 'hi',
|
||||
triggerLeadThreshold: 105,
|
||||
})
|
||||
).toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('validate 校验合法入参应正常通过', () => {
|
||||
expect(() =>
|
||||
service.validate({
|
||||
cardId: 101,
|
||||
personaType: 'trade_expert',
|
||||
welcomeMsg: 'Hello',
|
||||
triggerLeadThreshold: 70,
|
||||
promptTemplate: 'Be polite.',
|
||||
toneStyle: 'professional',
|
||||
isEnabled: true,
|
||||
})
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('getByCardId 在无记录时返回默认人设配置,有记录时返回持久化数据', async () => {
|
||||
// 无记录
|
||||
const defaultConfig = await service.getByCardId(888);
|
||||
expect(defaultConfig.cardId).toBe(888);
|
||||
expect(defaultConfig.personaType).toBe('trade_expert');
|
||||
expect(defaultConfig.isEnabled).toBe(true);
|
||||
expect(defaultConfig.welcomeMsg).toBeTruthy();
|
||||
|
||||
// 保存记录
|
||||
await service.saveByCardId(888, {
|
||||
welcomeMsg: 'Welcome to our international showroom.',
|
||||
triggerLeadThreshold: 80,
|
||||
});
|
||||
|
||||
// 再次读取
|
||||
const fetched = await service.getByCardId(888);
|
||||
expect(fetched.welcomeMsg).toBe('Welcome to our international showroom.');
|
||||
expect(fetched.triggerLeadThreshold).toBe(80);
|
||||
});
|
||||
|
||||
it('saveByCardId 更新现有记录与新增记录', async () => {
|
||||
const saved = await service.saveByCardId(999, {
|
||||
personaType: 'tech_advisor',
|
||||
welcomeMsg: 'Tech support online',
|
||||
triggerLeadThreshold: 65,
|
||||
promptTemplate: 'Assist developer integration',
|
||||
toneStyle: 'direct',
|
||||
isEnabled: false,
|
||||
});
|
||||
|
||||
expect(saved.cardId).toBe(999);
|
||||
expect(saved.personaType).toBe('tech_advisor');
|
||||
expect(saved.isEnabled).toBe(false);
|
||||
|
||||
// 更新
|
||||
const updated = await service.saveByCardId(999, {
|
||||
welcomeMsg: 'Updated support message',
|
||||
triggerLeadThreshold: 60,
|
||||
});
|
||||
expect(updated.welcomeMsg).toBe('Updated support message');
|
||||
expect(updated.triggerLeadThreshold).toBe(60);
|
||||
expect(updated.personaType).toBe('tech_advisor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. 控制器路由与契约 (AdminAiConciergeController)', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/admin/concierge.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(AdminAiConciergeController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('控制器文件路径与路由前缀必须为 /admin/ai/concierge', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(meta.prefix).toBe('/admin/ai/concierge');
|
||||
});
|
||||
|
||||
it('控制器必须继承 BaseController,绑定 AiConciergeService 与 AiConciergeEntity', () => {
|
||||
expect(AdminAiConciergeController.prototype).toBeInstanceOf(BaseController);
|
||||
expect(option.service).toBe(AiConciergeService);
|
||||
expect(option.entity).toBe(AiConciergeEntity);
|
||||
expect(adminAiConciergeCurdOption.service).toBe(AiConciergeService);
|
||||
});
|
||||
|
||||
it('CRUD API 应包含 add, delete, update, info, list, page', () => {
|
||||
const apis = option.api || [];
|
||||
expect(apis).toContain('add');
|
||||
expect(apis).toContain('delete');
|
||||
expect(apis).toContain('update');
|
||||
expect(apis).toContain('info');
|
||||
expect(apis).toContain('list');
|
||||
expect(apis).toContain('page');
|
||||
});
|
||||
|
||||
it('serviceApis 应注册 getDefaultPersona, getByCardId, saveByCardId', () => {
|
||||
const methods = serviceApiMethods(option.serviceApis);
|
||||
expect(methods).toContain('getDefaultPersona');
|
||||
expect(methods).toContain('getByCardId');
|
||||
expect(methods).toContain('saveByCardId');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
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 { AiCopilotService } from '../../../src/modules/ai/service/copilot';
|
||||
import {
|
||||
AdminAiCopilotController,
|
||||
adminAiCopilotCurdOption,
|
||||
} from '../../../src/modules/ai/controller/admin/copilot';
|
||||
import { CopilotRequest } from '../../../src/comm/types/omni';
|
||||
|
||||
/**
|
||||
* CoolController 元数据(脚本路径解析为异步)
|
||||
*/
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
/**
|
||||
* generate 入参:契约 + 可选意向分
|
||||
*/
|
||||
type CopilotGenerateInput = CopilotRequest & {
|
||||
intentScore?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 等待 CoolController 将 CRUD 配置写入类元数据
|
||||
*/
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(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));
|
||||
}
|
||||
|
||||
describe('T40: 销售跟进话术生成 (modules/ai copilot)', () => {
|
||||
describe('1. AiCopilotService.generate 入参校验', () => {
|
||||
let service: AiCopilotService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiCopilotService();
|
||||
});
|
||||
|
||||
it('无名且无 leadId 应抛 CoolCommException', async () => {
|
||||
await expect(service.generate({} as CopilotRequest)).rejects.toThrow(
|
||||
CoolCommException
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.generate({ name: ' ', locale: 'en-US' })
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.generate({ leadId: '', name: '' })
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('仅有 leadId 无库时可生成,脚本非空', async () => {
|
||||
const result = await service.generate({ leadId: 12 });
|
||||
expect(result.script.trim().length).toBeGreaterThan(0);
|
||||
expect(result.channel).toBe('email');
|
||||
expect(result.locale).toBe('en-US');
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. 渠道模板与意向诊断', () => {
|
||||
let service: AiCopilotService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiCopilotService();
|
||||
});
|
||||
|
||||
it('email / whatsapp 脚本不同', async () => {
|
||||
const req: CopilotGenerateInput = { name: 'Ada Chen' };
|
||||
const email = await service.generate({ ...req, channel: 'email' });
|
||||
const whatsapp = await service.generate({ ...req, channel: 'whatsapp' });
|
||||
|
||||
expect(email.channel).toBe('email');
|
||||
expect(whatsapp.channel).toBe('whatsapp');
|
||||
expect(email.script).toBeTruthy();
|
||||
expect(whatsapp.script).toBeTruthy();
|
||||
expect(email.script).not.toBe(whatsapp.script);
|
||||
expect(email.script).toContain('Ada Chen');
|
||||
expect(whatsapp.script).toContain('Ada Chen');
|
||||
});
|
||||
|
||||
it('高意向 diagnosis 不同', async () => {
|
||||
const low = await service.generate({
|
||||
name: 'Ada Chen',
|
||||
intentScore: 10,
|
||||
} as CopilotGenerateInput);
|
||||
const high = await service.generate({
|
||||
name: 'Ada Chen',
|
||||
intentScore: 90,
|
||||
} as CopilotGenerateInput);
|
||||
|
||||
expect(low.diagnosis).toBeTruthy();
|
||||
expect(high.diagnosis).toBeTruthy();
|
||||
expect(high.diagnosis).not.toBe(low.diagnosis);
|
||||
});
|
||||
|
||||
it('缺省 channel=email、locale=en-US,英文不含中文', async () => {
|
||||
const result = await service.generate({ name: 'Ada Chen' });
|
||||
expect(result.channel).toBe('email');
|
||||
expect(result.locale).toBe('en-US');
|
||||
expect(/[\u4e00-\u9fff]/.test(result.script)).toBe(false);
|
||||
expect(/[\u4e00-\u9fff]/.test(result.diagnosis)).toBe(false);
|
||||
});
|
||||
|
||||
it('zh-CN 含中文', async () => {
|
||||
const result = await service.generate({
|
||||
name: '陈安',
|
||||
locale: 'zh-CN',
|
||||
channel: 'email',
|
||||
});
|
||||
expect(result.locale).toBe('zh-CN');
|
||||
expect(/[\u4e00-\u9fff]/.test(result.script)).toBe(true);
|
||||
expect(/[\u4e00-\u9fff]/.test(result.diagnosis)).toBe(true);
|
||||
expect(result.script).toContain('陈安');
|
||||
});
|
||||
|
||||
it('兼容 serviceApis 单对象入参且脚本非空', async () => {
|
||||
const body: CopilotGenerateInput = {
|
||||
name: 'Ada Chen',
|
||||
locale: 'zh-CN',
|
||||
channel: 'whatsapp',
|
||||
intentScore: 80,
|
||||
};
|
||||
const result = await service.generate(body);
|
||||
expect(result.channel).toBe('whatsapp');
|
||||
expect(result.locale).toBe('zh-CN');
|
||||
expect(result.script.trim().length).toBeGreaterThan(0);
|
||||
expect(/[\u4e00-\u9fff]/.test(result.script)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. AdminAiCopilotController /admin/ai/copilot', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/admin/copilot.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(AdminAiCopilotController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('文件路径应符合 /admin/ai/copilot 自动路由约定', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(controllerFile.replace(/\\/g, '/')).toMatch(
|
||||
/modules\/ai\/controller\/admin\/copilot\.ts$/
|
||||
);
|
||||
});
|
||||
|
||||
it('路由前缀应为 /admin/ai/copilot', () => {
|
||||
expect(meta.prefix).toBe('/admin/ai/copilot');
|
||||
});
|
||||
|
||||
it('控制器应继承 BaseController,绑定 AiCopilotService,不开 CRUD', () => {
|
||||
expect(AdminAiCopilotController.prototype).toBeInstanceOf(BaseController);
|
||||
expect(option.service).toBe(AiCopilotService);
|
||||
expect(adminAiCopilotCurdOption.service).toBe(AiCopilotService);
|
||||
expect(option.api || []).toEqual([]);
|
||||
});
|
||||
|
||||
it('serviceApis 应包含 generate', () => {
|
||||
const methods = serviceApiMethods(option.serviceApis);
|
||||
expect(methods).toContain('generate');
|
||||
expect(serviceApiMethods(adminAiCopilotCurdOption.serviceApis)).toContain(
|
||||
'generate'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
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 { Repository } from 'typeorm';
|
||||
import { AiGlossaryEntity } from '../../../src/modules/ai/entity/glossary';
|
||||
import { AiGlossaryService } from '../../../src/modules/ai/service/glossary';
|
||||
import { AiLocalizeService } from '../../../src/modules/ai/service/localize';
|
||||
import {
|
||||
AdminAiGlossaryController,
|
||||
adminAiGlossaryCurdOption,
|
||||
} from '../../../src/modules/ai/controller/admin/glossary';
|
||||
import { AiGlossaryItem } from '../../../src/comm/types/omni';
|
||||
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(resolve => setImmediate(resolve));
|
||||
}
|
||||
throw new Error(`${target.name} 的 CoolController 元数据未就绪`);
|
||||
}
|
||||
|
||||
function createMockRepo(seedItems: AiGlossaryEntity[] = []): Repository<AiGlossaryEntity> {
|
||||
let list = [...seedItems];
|
||||
let autoId = 100;
|
||||
|
||||
return {
|
||||
find: jest.fn(async (options?: { where?: Record<string, unknown> }) => {
|
||||
if (!options?.where) {
|
||||
return list;
|
||||
}
|
||||
return list.filter(item => {
|
||||
for (const [k, v] of Object.entries(options.where ?? {})) {
|
||||
if (v !== undefined && (item as unknown as Record<string, unknown>)[k] !== v) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}),
|
||||
save: jest.fn(async (entityOrEntities: AiGlossaryEntity | AiGlossaryEntity[]) => {
|
||||
if (Array.isArray(entityOrEntities)) {
|
||||
for (const item of entityOrEntities) {
|
||||
if (!item.id) {
|
||||
item.id = ++autoId;
|
||||
}
|
||||
list.push(item);
|
||||
}
|
||||
return entityOrEntities;
|
||||
}
|
||||
if (!entityOrEntities.id) {
|
||||
entityOrEntities.id = ++autoId;
|
||||
}
|
||||
list.push(entityOrEntities);
|
||||
return entityOrEntities;
|
||||
}),
|
||||
insert: jest.fn(async (item: AiGlossaryEntity) => {
|
||||
if (!item.id) {
|
||||
item.id = ++autoId;
|
||||
}
|
||||
list.push(item);
|
||||
return { identifiers: [{ id: item.id }] };
|
||||
}),
|
||||
} as unknown as Repository<AiGlossaryEntity>;
|
||||
}
|
||||
|
||||
describe('Point 06: 后台多语言 AI 润色中心与行业术语库 (Glossary)', () => {
|
||||
describe('1. 实体 AiGlossaryEntity 定义与字段校验', () => {
|
||||
it('实体属性与映射表名 ai_glossary 校验', () => {
|
||||
const entity = new AiGlossaryEntity();
|
||||
entity.sourceTerm = 'digital business card';
|
||||
entity.targetTerm = '智能数字名片';
|
||||
entity.sourceLang = 'en';
|
||||
entity.targetLang = 'zh-CN';
|
||||
entity.domain = 'tech';
|
||||
entity.notes = '核心品牌术语';
|
||||
|
||||
expect(entity.sourceTerm).toBe('digital business card');
|
||||
expect(entity.targetTerm).toBe('智能数字名片');
|
||||
expect(entity.sourceLang).toBe('en');
|
||||
expect(entity.targetLang).toBe('zh-CN');
|
||||
expect(entity.domain).toBe('tech');
|
||||
expect(entity.notes).toBe('核心品牌术语');
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. AiGlossaryService 批量导入与增删改查', () => {
|
||||
let service: AiGlossaryService;
|
||||
let mockRepo: Repository<AiGlossaryEntity>;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiGlossaryService();
|
||||
mockRepo = createMockRepo();
|
||||
service.aiGlossaryEntity = mockRepo;
|
||||
});
|
||||
|
||||
it('batchImport 空列表应抛异常或返回0', async () => {
|
||||
await expect(service.batchImport([])).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('batchImport 忽略缺少 sourceTerm 或 targetTerm 的无效项', async () => {
|
||||
const result = await service.batchImport([
|
||||
{ sourceTerm: '', targetTerm: '无效' },
|
||||
{ sourceTerm: 'CRM', targetTerm: '' },
|
||||
{ sourceTerm: 'NFC Card', targetTerm: 'NFC 实体卡', targetLang: 'zh-CN' },
|
||||
]);
|
||||
expect(result.total).toBe(3);
|
||||
expect(result.inserted).toBe(1);
|
||||
});
|
||||
|
||||
it('batchImport 批量导入多项成功', async () => {
|
||||
const items: Array<Partial<AiGlossaryItem>> = [
|
||||
{ sourceTerm: 'OmniCard', targetTerm: '奥秘名片', targetLang: 'zh-CN' },
|
||||
{ sourceTerm: 'Radar', targetTerm: '访客雷达', targetLang: 'zh-CN', domain: 'crm' },
|
||||
];
|
||||
const result = await service.batchImport(items);
|
||||
expect(result.inserted).toBe(2);
|
||||
expect(result.total).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. AiGlossaryService 术语匹配替换 (贪心长词优先 & 领域匹配)', () => {
|
||||
let service: AiGlossaryService;
|
||||
|
||||
beforeEach(() => {
|
||||
const seed: AiGlossaryEntity[] = [
|
||||
{
|
||||
id: 1,
|
||||
sourceTerm: 'digital card',
|
||||
targetTerm: '电子名片',
|
||||
targetLang: 'zh-CN',
|
||||
domain: 'general',
|
||||
} as AiGlossaryEntity,
|
||||
{
|
||||
id: 2,
|
||||
sourceTerm: 'smart digital card',
|
||||
targetTerm: '全球智能数字名片',
|
||||
targetLang: 'zh-CN',
|
||||
domain: 'tech',
|
||||
} as AiGlossaryEntity,
|
||||
{
|
||||
id: 3,
|
||||
sourceTerm: 'lead',
|
||||
targetTerm: '高意向商机',
|
||||
targetLang: 'zh-CN',
|
||||
domain: 'crm',
|
||||
} as AiGlossaryEntity,
|
||||
{
|
||||
id: 4,
|
||||
sourceTerm: 'lead',
|
||||
targetTerm: '线索',
|
||||
targetLang: 'zh-CN',
|
||||
domain: 'general',
|
||||
} as AiGlossaryEntity,
|
||||
{
|
||||
id: 5,
|
||||
sourceTerm: 'بطاقة',
|
||||
targetTerm: 'بطاقة ذكية',
|
||||
targetLang: 'ar-SA',
|
||||
} as AiGlossaryEntity,
|
||||
];
|
||||
service = new AiGlossaryService();
|
||||
const mockRepo = createMockRepo(seed);
|
||||
service.aiGlossaryEntity = mockRepo;
|
||||
});
|
||||
|
||||
it('长词优先贪心匹配:smart digital card 应被替换为 全球智能数字名片 而非 电子名片', async () => {
|
||||
const input = 'This is our smart digital card platform.';
|
||||
const output = await service.replaceTerms(input, 'zh-CN', 'tech');
|
||||
expect(output).toContain('全球智能数字名片');
|
||||
expect(output).not.toContain('电子名片');
|
||||
});
|
||||
|
||||
it('领域匹配优先:domain 为 crm 时 lead 替换为 高意向商机,否则为 线索', async () => {
|
||||
const input = 'We captured a new lead yesterday.';
|
||||
const crmOutput = await service.replaceTerms(input, 'zh-CN', 'crm');
|
||||
expect(crmOutput).toContain('高意向商机');
|
||||
|
||||
const generalOutput = await service.replaceTerms(input, 'zh-CN', 'general');
|
||||
expect(generalOutput).toContain('线索');
|
||||
});
|
||||
|
||||
it('跨目标语言隔离:目标语言 ar-SA 不应应用 zh-CN 术语', async () => {
|
||||
const input = 'smart digital card and بطاقة';
|
||||
const output = await service.replaceTerms(input, 'ar-SA');
|
||||
expect(output).toContain('بطاقة ذكية');
|
||||
expect(output).not.toContain('全球智能数字名片');
|
||||
});
|
||||
});
|
||||
|
||||
describe('4. AiLocalizeService 引用术语库并强行替换', () => {
|
||||
let localizeService: AiLocalizeService;
|
||||
let glossaryService: AiGlossaryService;
|
||||
|
||||
beforeEach(() => {
|
||||
glossaryService = new AiGlossaryService();
|
||||
const seed: AiGlossaryEntity[] = [
|
||||
{
|
||||
id: 1,
|
||||
sourceTerm: 'digital cards',
|
||||
targetTerm: '智能数字名片',
|
||||
targetLang: 'zh-CN',
|
||||
} as AiGlossaryEntity,
|
||||
];
|
||||
const mockRepo = createMockRepo(seed);
|
||||
glossaryService.aiGlossaryEntity = mockRepo;
|
||||
|
||||
localizeService = new AiLocalizeService();
|
||||
localizeService.aiGlossaryService = glossaryService;
|
||||
});
|
||||
|
||||
it('润色时应将术语强制替换为术语库配置的目标词', async () => {
|
||||
const result = await localizeService.localize({
|
||||
text: 'We help global teams share digital cards.',
|
||||
targetLocale: 'zh-CN',
|
||||
tone: 'professional',
|
||||
});
|
||||
expect(result.locale).toBe('zh-CN');
|
||||
expect(result.text).toContain('智能数字名片');
|
||||
});
|
||||
});
|
||||
|
||||
describe('5. AdminAiGlossaryController 路由与元数据校验', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/admin/glossary.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(AdminAiGlossaryController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('文件路径必须符合 /admin/ai/glossary 规范', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(controllerFile.replace(/\\/g, '/')).toMatch(
|
||||
/modules\/ai\/controller\/admin\/glossary\.ts$/
|
||||
);
|
||||
});
|
||||
|
||||
it('路由前缀必须为 /admin/ai/glossary', () => {
|
||||
expect(meta.prefix).toBe('/admin/ai/glossary');
|
||||
});
|
||||
|
||||
it('控制器应继承 BaseController 并开启 CRUD 与 serviceApis', () => {
|
||||
expect(AdminAiGlossaryController.prototype).toBeInstanceOf(BaseController);
|
||||
expect(option.service).toBe(AiGlossaryService);
|
||||
expect(adminAiGlossaryCurdOption.service).toBe(AiGlossaryService);
|
||||
expect(option.entity).toBe(AiGlossaryEntity);
|
||||
expect(option.api).toEqual(
|
||||
expect.arrayContaining(['add', 'delete', 'update', 'info', 'list', 'page'])
|
||||
);
|
||||
expect(option.serviceApis).toEqual(expect.arrayContaining(['batchImport']));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
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 { AiLocalizeService } from '../../../src/modules/ai/service/localize';
|
||||
import {
|
||||
AdminAiLocalizeController,
|
||||
adminAiLocalizeCurdOption,
|
||||
} from '../../../src/modules/ai/controller/admin/localize';
|
||||
import { LocalizeRequest, LocalizeTone } from '../../../src/comm/types/omni';
|
||||
|
||||
/**
|
||||
* CoolController 元数据(脚本路径解析为异步)
|
||||
*/
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待 CoolController 将 CRUD 配置写入类元数据
|
||||
*/
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(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));
|
||||
}
|
||||
|
||||
const SAMPLE_TEXT = 'We help global teams share digital cards.';
|
||||
|
||||
function localizeReq(
|
||||
extra?: Partial<LocalizeRequest>
|
||||
): LocalizeRequest {
|
||||
return {
|
||||
text: extra?.text ?? SAMPLE_TEXT,
|
||||
targetLocale: extra?.targetLocale ?? 'en-US',
|
||||
tone: extra?.tone,
|
||||
};
|
||||
}
|
||||
|
||||
describe('T39: AI 出海润色 (modules/ai localize)', () => {
|
||||
describe('1. AiLocalizeService.localize 入参校验', () => {
|
||||
let service: AiLocalizeService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiLocalizeService();
|
||||
});
|
||||
|
||||
it('缺 text 应抛 CoolCommException', async () => {
|
||||
await expect(
|
||||
service.localize({
|
||||
text: '',
|
||||
targetLocale: 'en-US',
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.localize({
|
||||
text: ' ',
|
||||
targetLocale: 'en-US',
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.localize({
|
||||
targetLocale: 'en-US',
|
||||
} as LocalizeRequest)
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
|
||||
it('缺 targetLocale 应抛 CoolCommException', async () => {
|
||||
await expect(
|
||||
service.localize({
|
||||
text: SAMPLE_TEXT,
|
||||
targetLocale: '',
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.localize({
|
||||
text: SAMPLE_TEXT,
|
||||
targetLocale: ' ',
|
||||
})
|
||||
).rejects.toThrow(CoolCommException);
|
||||
|
||||
await expect(
|
||||
service.localize({
|
||||
text: SAMPLE_TEXT,
|
||||
} as LocalizeRequest)
|
||||
).rejects.toThrow(CoolCommException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. 语气骨架与 locale 包裹', () => {
|
||||
let service: AiLocalizeService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiLocalizeService();
|
||||
});
|
||||
|
||||
it('三种 tone 返回不同文本', async () => {
|
||||
const tones: LocalizeTone[] = ['professional', 'direct', 'storytelling'];
|
||||
const texts = await Promise.all(
|
||||
tones.map(tone =>
|
||||
service.localize(localizeReq({ tone })).then(r => r.text)
|
||||
)
|
||||
);
|
||||
expect(new Set(texts).size).toBe(3);
|
||||
expect(texts.every(t => t.trim().length > 0)).toBe(true);
|
||||
});
|
||||
|
||||
it('tone 缺省为 professional', async () => {
|
||||
const implicit = await service.localize(localizeReq());
|
||||
const explicit = await service.localize(
|
||||
localizeReq({ tone: 'professional' })
|
||||
);
|
||||
expect(implicit.tone).toBe('professional');
|
||||
expect(implicit.text).toBe(explicit.text);
|
||||
});
|
||||
|
||||
it('zh-CN 回复含中文', async () => {
|
||||
const result = await service.localize(
|
||||
localizeReq({ targetLocale: 'zh-CN' })
|
||||
);
|
||||
expect(result.locale).toBe('zh-CN');
|
||||
expect(result.tone).toBe('professional');
|
||||
expect(/[\u4e00-\u9fff]/.test(result.text)).toBe(true);
|
||||
expect(result.text).toContain(SAMPLE_TEXT);
|
||||
});
|
||||
|
||||
it('兼容 serviceApis 单对象入参并回传 locale / tone', async () => {
|
||||
const body: LocalizeRequest = {
|
||||
text: SAMPLE_TEXT,
|
||||
targetLocale: 'ar-SA',
|
||||
tone: 'direct',
|
||||
};
|
||||
const result = await service.localize(body);
|
||||
expect(result.locale).toBe('ar-SA');
|
||||
expect(result.tone).toBe('direct');
|
||||
expect(result.text.trim().length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. AdminAiLocalizeController /admin/ai/localize', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/admin/localize.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(AdminAiLocalizeController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('文件路径应符合 /admin/ai/localize 自动路由约定', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(controllerFile.replace(/\\/g, '/')).toMatch(
|
||||
/modules\/ai\/controller\/admin\/localize\.ts$/
|
||||
);
|
||||
});
|
||||
|
||||
it('路由前缀应为 /admin/ai/localize', () => {
|
||||
expect(meta.prefix).toBe('/admin/ai/localize');
|
||||
});
|
||||
|
||||
it('控制器应继承 BaseController,绑定 AiLocalizeService,不开 CRUD', () => {
|
||||
expect(AdminAiLocalizeController.prototype).toBeInstanceOf(BaseController);
|
||||
expect(option.service).toBe(AiLocalizeService);
|
||||
expect(adminAiLocalizeCurdOption.service).toBe(AiLocalizeService);
|
||||
expect(option.api || []).toEqual([]);
|
||||
});
|
||||
|
||||
it('serviceApis 应包含 localize', () => {
|
||||
const methods = serviceApiMethods(option.serviceApis);
|
||||
expect(methods).toContain('localize');
|
||||
expect(serviceApiMethods(adminAiLocalizeCurdOption.serviceApis)).toContain(
|
||||
'localize'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core';
|
||||
import { BaseController, CurdOption } from '@cool-midway/core';
|
||||
import { AiKnowledgeService } from '../../../src/modules/ai/service/knowledge';
|
||||
import {
|
||||
AdminAiKnowledgeController,
|
||||
adminAiKnowledgeCurdOption,
|
||||
} from '../../../src/modules/ai/controller/admin/knowledge';
|
||||
import { KnowledgeChunk } from '../../../src/comm/types/omni';
|
||||
|
||||
interface CoolControllerMeta {
|
||||
prefix?: string;
|
||||
curdOption?: CurdOption;
|
||||
}
|
||||
|
||||
async function waitCoolMeta(
|
||||
target: new (...args: never[]) => unknown
|
||||
): Promise<CoolControllerMeta> {
|
||||
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<void>(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));
|
||||
}
|
||||
|
||||
describe('Point 07: AI 知识库分块切片与召回沙盒 (modules/ai knowledge sandbox)', () => {
|
||||
let service: AiKnowledgeService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new AiKnowledgeService();
|
||||
});
|
||||
|
||||
describe('1. splitTextToChunks 切片算法边界', () => {
|
||||
it('空文本或空白文本应返回空数组', () => {
|
||||
expect(service.splitTextToChunks('')).toEqual([]);
|
||||
expect(service.splitTextToChunks(' \n\t ')).toEqual([]);
|
||||
});
|
||||
|
||||
it('小文本边界:文本长度 <= chunkSize 应返回单一切片', () => {
|
||||
const text = 'OmniCard 全球数字名片';
|
||||
const chunks = service.splitTextToChunks(text, 50, 10);
|
||||
expect(chunks).toHaveLength(1);
|
||||
expect(chunks[0].content).toBe(text);
|
||||
expect(chunks[0].index).toBe(0);
|
||||
expect(chunks[0].length).toBe(text.length);
|
||||
});
|
||||
|
||||
it('长文本滑动切片:验证切片数、重叠字符与末尾覆盖', () => {
|
||||
// 构造长度为 45 的文本
|
||||
const text = '1234567890abcdefghij1234567890abcdefghij12345';
|
||||
const chunkSize = 20;
|
||||
const overlap = 5;
|
||||
const chunks = service.splitTextToChunks(text, chunkSize, overlap);
|
||||
|
||||
// step = 20 - 5 = 15:
|
||||
// chunk 0: [0, 20]
|
||||
// chunk 1: [15, 35]
|
||||
// chunk 2: [30, 45] (末尾到达 45)
|
||||
expect(chunks).toHaveLength(3);
|
||||
expect(chunks[0].content).toBe(text.slice(0, 20));
|
||||
expect(chunks[1].content).toBe(text.slice(15, 35));
|
||||
expect(chunks[2].content).toBe(text.slice(30, 45));
|
||||
|
||||
// 验证重叠:chunk 0 的末尾 5 字符应等于 chunk 1 的开头 5 字符
|
||||
expect(chunks[0].content.slice(-5)).toBe(chunks[1].content.slice(0, 5));
|
||||
// 验证末尾完整覆盖
|
||||
expect(chunks[chunks.length - 1].content.endsWith('12345')).toBe(true);
|
||||
});
|
||||
|
||||
it('重叠截断边界:overlap >= chunkSize 时应自动纠正步长,防止死循环', () => {
|
||||
const text = '这是一段用来测试重叠过大保护机制的测试长文本';
|
||||
// overlap 设为 30,大于 chunkSize 20
|
||||
const chunks = service.splitTextToChunks(text, 20, 30);
|
||||
expect(chunks.length).toBeGreaterThan(1);
|
||||
expect(chunks[0].length).toBeLessThanOrEqual(20);
|
||||
});
|
||||
|
||||
it('未指定 chunkSize 与 overlap 时应具有合理默认值', () => {
|
||||
const longText = 'A'.repeat(500);
|
||||
const chunks = service.splitTextToChunks(longText);
|
||||
expect(chunks.length).toBeGreaterThan(1);
|
||||
expect(chunks[0].content.length).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. simulateRetrieval 召回算法与排序计算', () => {
|
||||
const mockChunks: KnowledgeChunk[] = [
|
||||
{
|
||||
index: 0,
|
||||
content: 'OmniCard 提供 NFC 智能实体卡,碰一碰即可传输联系方式与微官网。',
|
||||
length: 37,
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
content: '雷达系统支持出海 CRM 访客轨迹追踪、停留时长与意向度自动评分。',
|
||||
length: 33,
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
content: 'AI 知识库提供文档分块切片预览与 RAG 检索增强沙盒调试能力。',
|
||||
length: 34,
|
||||
},
|
||||
{
|
||||
index: 3,
|
||||
content: 'Bento Grid 便当盒美学布局,响应式适配全球多语言及 RTL 界面。',
|
||||
length: 34,
|
||||
},
|
||||
];
|
||||
|
||||
it('空 query 或空 chunks 应返回空数组', () => {
|
||||
expect(service.simulateRetrieval('', mockChunks)).toEqual([]);
|
||||
expect(service.simulateRetrieval('NFC', [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('应按匹配置信度降序排序,完全匹配/高频命中排第一', () => {
|
||||
const query = 'NFC 实体卡 碰一碰';
|
||||
const results = service.simulateRetrieval(query, mockChunks, 3);
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
// 第一条应该是 index 为 0 的 NFC 相关切片
|
||||
expect(results[0].index).toBe(0);
|
||||
expect(results[0].score).toBeGreaterThan(0.5);
|
||||
expect(results[0].score).toBeLessThanOrEqual(1.0);
|
||||
});
|
||||
|
||||
it('应支持 topK 截断返回数量', () => {
|
||||
const query = '系统 智能 适配';
|
||||
const results = service.simulateRetrieval(query, mockChunks, 2);
|
||||
expect(results.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('应支持 threshold 阈值过滤低相关度切片', () => {
|
||||
const query = 'RAG 沙盒调试';
|
||||
// 只有切片 2 高度匹配,设置高阈值过滤其他低分或无关切片
|
||||
const results = service.simulateRetrieval(query, mockChunks, 4, 0.4);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].index).toBe(2);
|
||||
expect(results[0].content).toContain('RAG 检索增强沙盒调试');
|
||||
});
|
||||
|
||||
it('应兼容接收纯字符串数组 chunks', () => {
|
||||
const stringChunks = [
|
||||
'出海多语言支持英文、中文、阿拉伯语',
|
||||
'国内网络环境配置说明',
|
||||
];
|
||||
const results = service.simulateRetrieval('阿拉伯语 出海', stringChunks, 2);
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].content).toContain('阿拉伯语');
|
||||
expect(results[0].score).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. AdminAiKnowledgeController 与 /admin/ai/knowledge/sandbox-test 接口', () => {
|
||||
const controllerFile = path.join(
|
||||
__dirname,
|
||||
'../../../src/modules/ai/controller/admin/knowledge.ts'
|
||||
);
|
||||
|
||||
let meta: CoolControllerMeta;
|
||||
let option: CurdOption;
|
||||
|
||||
beforeAll(async () => {
|
||||
meta = await waitCoolMeta(AdminAiKnowledgeController);
|
||||
option = meta.curdOption as CurdOption;
|
||||
});
|
||||
|
||||
it('控制器文件与路由前缀符合规范', () => {
|
||||
expect(fs.existsSync(controllerFile)).toBe(true);
|
||||
expect(meta.prefix).toBe('/admin/ai/knowledge');
|
||||
expect(AdminAiKnowledgeController.prototype).toBeInstanceOf(BaseController);
|
||||
});
|
||||
|
||||
it('serviceApis 应注册 sandboxTest,且控制器包含 sandboxTest 方法', () => {
|
||||
const methods = serviceApiMethods(option.serviceApis);
|
||||
expect(methods).toContain('sandboxTest');
|
||||
expect(typeof (AdminAiKnowledgeController.prototype as unknown as Record<string, unknown>).sandboxTest).toBe('function');
|
||||
});
|
||||
|
||||
it('AiKnowledgeService.sandboxTest 应能执行切片并召回', async () => {
|
||||
const result = await service.sandboxTest({
|
||||
query: 'NFC 实体卡',
|
||||
content: 'OmniCard NFC 智能实体名片碰一碰极速交换。另有 AI 智能数字人与访客雷达。',
|
||||
chunkSize: 30,
|
||||
overlap: 5,
|
||||
topK: 2,
|
||||
});
|
||||
expect(result.totalChunks).toBeGreaterThan(0);
|
||||
expect(result.chunks.length).toBe(result.totalChunks);
|
||||
expect(result.recallList.length).toBeGreaterThan(0);
|
||||
expect(result.recallList[0].score).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户