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,37 @@
|
||||
import { CoolCommException } from '@cool-midway/core';
|
||||
|
||||
/**
|
||||
* 判断当前请求上下文是否属于平台超级管理员 (Platform Super Admin)
|
||||
* 判定依据:
|
||||
* 1. 系统初始内置超管 username === 'admin'
|
||||
* 2. 带有 isSuper: true 平台超管标识
|
||||
* 3. 角色标签列表中包含 'admin' (系统内置角色)
|
||||
*/
|
||||
export function isSuperAdminContext(ctx: any): boolean {
|
||||
if (!ctx || !ctx.admin || typeof ctx.admin !== 'object') {
|
||||
return false;
|
||||
}
|
||||
const admin = ctx.admin;
|
||||
|
||||
if (admin.username === 'admin') {
|
||||
return true;
|
||||
}
|
||||
if (admin.isSuper === true) {
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(admin.roleLabels) && admin.roleLabels.includes('admin')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台超级管理员专属鉴权守卫断言
|
||||
* 非平台超管访问时,立即抛出 403 CoolCommException 阻断越权操作
|
||||
*/
|
||||
export function assertSuperAdmin(ctx: any): void {
|
||||
if (!isSuperAdminContext(ctx)) {
|
||||
throw new CoolCommException('权限不足,仅限平台超级管理员访问', 403);
|
||||
}
|
||||
}
|
||||
@@ -136,7 +136,33 @@ export type LeadStatus = 'new' | 'contacted' | 'hot' | 'won' | 'archived';
|
||||
*/
|
||||
export type LeadSource = 'nfc' | 'qr' | 'link' | 'ai_chat' | 'exchange';
|
||||
|
||||
export type CardContactSource = 'exchange' | 'collect' | 'scan';
|
||||
export type CardContactSource = 'exchange' | 'collect' | 'scan' | 'event';
|
||||
|
||||
export type CardEventStatus = 'active' | 'ended';
|
||||
|
||||
export interface CardEvent {
|
||||
id?: number | string;
|
||||
code: string;
|
||||
name: string;
|
||||
status: CardEventStatus;
|
||||
}
|
||||
|
||||
export interface CardEventMember {
|
||||
id?: number | string;
|
||||
eventId: number;
|
||||
userId: number;
|
||||
cardId: number;
|
||||
}
|
||||
|
||||
export interface CardEventJoinResult {
|
||||
event: CardEvent;
|
||||
member: CardEventMember;
|
||||
}
|
||||
|
||||
export interface RadarHotInbox {
|
||||
unread: number;
|
||||
list: RadarTrack[];
|
||||
}
|
||||
|
||||
export interface CardContact {
|
||||
id?: number | string;
|
||||
|
||||
@@ -15,7 +15,7 @@ export default {
|
||||
port: 3306,
|
||||
username: 'root',
|
||||
password: '123456',
|
||||
database: 'cool',
|
||||
database: 'crmmpdata',
|
||||
// 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
|
||||
synchronize: false,
|
||||
// 打印日志
|
||||
|
||||
@@ -23,24 +23,26 @@ import * as entity20 from './modules/crm/entity/lead';
|
||||
import * as entity21 from './modules/crm/entity/audit';
|
||||
import * as entity22 from './modules/card/entity/locale';
|
||||
import * as entity23 from './modules/card/entity/info';
|
||||
import * as entity24 from './modules/card/entity/cases';
|
||||
import * as entity25 from './modules/card/entity/bento';
|
||||
import * as entity26 from './modules/card/entity/article';
|
||||
import * as entity27 from './modules/base/entity/base';
|
||||
import * as entity28 from './modules/base/entity/audit';
|
||||
import * as entity29 from './modules/base/entity/sys/user_role';
|
||||
import * as entity30 from './modules/base/entity/sys/user';
|
||||
import * as entity31 from './modules/base/entity/sys/role_menu';
|
||||
import * as entity32 from './modules/base/entity/sys/role_department';
|
||||
import * as entity33 from './modules/base/entity/sys/role';
|
||||
import * as entity34 from './modules/base/entity/sys/param';
|
||||
import * as entity35 from './modules/base/entity/sys/menu';
|
||||
import * as entity36 from './modules/base/entity/sys/log';
|
||||
import * as entity37 from './modules/base/entity/sys/department';
|
||||
import * as entity38 from './modules/base/entity/sys/conf';
|
||||
import * as entity39 from './modules/ai/entity/knowledge';
|
||||
import * as entity40 from './modules/ai/entity/glossary';
|
||||
import * as entity41 from './modules/ai/entity/concierge';
|
||||
import * as entity24 from './modules/card/entity/exchange';
|
||||
import * as entity25 from './modules/card/entity/contact';
|
||||
import * as entity26 from './modules/card/entity/cases';
|
||||
import * as entity27 from './modules/card/entity/bento';
|
||||
import * as entity28 from './modules/card/entity/article';
|
||||
import * as entity29 from './modules/base/entity/base';
|
||||
import * as entity30 from './modules/base/entity/audit';
|
||||
import * as entity31 from './modules/base/entity/sys/user_role';
|
||||
import * as entity32 from './modules/base/entity/sys/user';
|
||||
import * as entity33 from './modules/base/entity/sys/role_menu';
|
||||
import * as entity34 from './modules/base/entity/sys/role_department';
|
||||
import * as entity35 from './modules/base/entity/sys/role';
|
||||
import * as entity36 from './modules/base/entity/sys/param';
|
||||
import * as entity37 from './modules/base/entity/sys/menu';
|
||||
import * as entity38 from './modules/base/entity/sys/log';
|
||||
import * as entity39 from './modules/base/entity/sys/department';
|
||||
import * as entity40 from './modules/base/entity/sys/conf';
|
||||
import * as entity41 from './modules/ai/entity/knowledge';
|
||||
import * as entity42 from './modules/ai/entity/glossary';
|
||||
import * as entity43 from './modules/ai/entity/concierge';
|
||||
export const entities = [
|
||||
...Object.values(entity0),
|
||||
...Object.values(entity1),
|
||||
@@ -84,4 +86,6 @@ export const entities = [
|
||||
...Object.values(entity39),
|
||||
...Object.values(entity40),
|
||||
...Object.values(entity41),
|
||||
...Object.values(entity42),
|
||||
...Object.values(entity43),
|
||||
];
|
||||
|
||||
@@ -13,8 +13,12 @@ export const adminAiConciergeCurdOption: CurdOption = {
|
||||
service: AiConciergeService,
|
||||
serviceApis: ['getDefaultPersona', 'getByCardId', 'saveByCardId'],
|
||||
pageQueryOp: {
|
||||
fieldEq: ['a.cardId', 'a.personaType', 'a.isEnabled'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
fieldEq: [
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.persona_type', requestParam: 'personaType' },
|
||||
{ column: 'a.is_enabled', requestParam: 'isEnabled' },
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -13,9 +13,13 @@ export const adminAiGlossaryCurdOption = {
|
||||
entity: AiGlossaryEntity,
|
||||
service: AiGlossaryService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.sourceTerm', 'a.targetTerm', 'a.notes'],
|
||||
fieldEq: ['a.sourceLang', 'a.targetLang', 'a.domain'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
keyWordLikeFields: ['a.source_term', 'a.target_term', 'a.notes'],
|
||||
fieldEq: [
|
||||
{ column: 'a.source_lang', requestParam: 'sourceLang' },
|
||||
{ column: 'a.target_lang', requestParam: 'targetLang' },
|
||||
'a.domain',
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ export const adminAiKnowledgeCurdOption = {
|
||||
serviceApis: [{ method: 'sandboxTest', summary: '知识库切片与召回沙盒测试' }],
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.title', 'a.content'],
|
||||
fieldEq: ['a.cardId', 'a.locale'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
fieldEq: [{ column: 'a.card_id', requestParam: 'cardId' }, 'a.locale'],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Inject, Provide } from '@midwayjs/core';
|
||||
import { BaseService, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import {
|
||||
AiChatMessage,
|
||||
AiChatReply,
|
||||
@@ -7,6 +9,8 @@ import {
|
||||
DeepSeekChatMessage,
|
||||
} from '../../../comm/types/omni';
|
||||
import { DeepSeekService } from './deepseek';
|
||||
import { AiConciergeService } from './concierge';
|
||||
import { CardInfoEntity } from '../../card/entity/info';
|
||||
|
||||
/** locale 缺省值 */
|
||||
const DEFAULT_LOCALE = 'en-US';
|
||||
@@ -23,11 +27,19 @@ export class AiChatService extends BaseService {
|
||||
@Inject()
|
||||
deepSeekService?: DeepSeekService;
|
||||
|
||||
@Inject()
|
||||
aiConciergeService?: AiConciergeService;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity?: Repository<CardInfoEntity>;
|
||||
|
||||
/**
|
||||
* 顾问对话
|
||||
* 兼容公开端 serviceApis:POST body 为单参数对象 AiChatRequest
|
||||
*/
|
||||
async ask(req: AiChatRequest): Promise<AiChatReply> {
|
||||
async ask(
|
||||
req: AiChatRequest & { tenantId?: number | string }
|
||||
): Promise<AiChatReply> {
|
||||
const cardId = req?.cardId;
|
||||
if (cardId === undefined || cardId === null || String(cardId).trim() === '') {
|
||||
throw new CoolCommException('缺少名片标识 cardId');
|
||||
@@ -51,13 +63,49 @@ export class AiChatService extends BaseService {
|
||||
|
||||
let reply = fallbackReply;
|
||||
|
||||
// 如果 DeepSeek 已经配置,则优先调用 DeepSeek 大模型生成智能回复
|
||||
if (this.deepSeekService?.isConfigured?.()) {
|
||||
// 解析名片租户 ID,用于多租户 BYOK 与配额风控隔离
|
||||
let tenantId = req.tenantId;
|
||||
if (tenantId === undefined && this.cardInfoEntity) {
|
||||
try {
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(cardId) },
|
||||
});
|
||||
if (card?.tenantId) {
|
||||
tenantId = card.tenantId;
|
||||
}
|
||||
} catch {
|
||||
// 容错降级
|
||||
}
|
||||
}
|
||||
|
||||
// 解析人设模版与个性化策略
|
||||
let personaPrompt = '';
|
||||
if (this.aiConciergeService) {
|
||||
try {
|
||||
const concierge = await this.aiConciergeService.getByCardId(Number(cardId));
|
||||
if (concierge?.promptTemplate) {
|
||||
personaPrompt = `顾问人设与背景:${concierge.promptTemplate}`;
|
||||
}
|
||||
} catch {
|
||||
// 容错降级
|
||||
}
|
||||
}
|
||||
|
||||
// 如果 DeepSeek 已经配置,则优先调用 DeepSeek 大模型生成智能回复
|
||||
if (this.deepSeekService?.isConfigured?.(tenantId)) {
|
||||
try {
|
||||
const systemPrompt = [
|
||||
`你是 OmniCard 名片智能顾问。当前名片ID: ${cardId},语言偏好: ${locale}。`,
|
||||
personaPrompt,
|
||||
`请以专业得体的口吻向客商介绍业务与解答咨询。${shouldCollectLead ? '检测到客户具备采购或商务意向,请在回答中热情引导客户留下联系方式。' : ''}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
|
||||
const dsMessages: DeepSeekChatMessage[] = [
|
||||
{
|
||||
role: 'system',
|
||||
content: `你是 OmniCard 名片智能顾问。当前名片ID: ${cardId},语言偏好: ${locale}。请以专业得体的口吻向客商介绍业务与解答咨询。${shouldCollectLead ? '检测到客户具备采购或商务意向,请在回答中热情引导客户留下联系方式。' : ''}`,
|
||||
content: systemPrompt,
|
||||
},
|
||||
...messages.map((m) => ({
|
||||
role: m.role as 'user' | 'assistant' | 'system',
|
||||
@@ -67,7 +115,8 @@ export class AiChatService extends BaseService {
|
||||
|
||||
reply = await this.deepSeekService.chatCompletion(
|
||||
{ messages: dsMessages },
|
||||
fallbackReply
|
||||
fallbackReply,
|
||||
tenantId
|
||||
);
|
||||
} catch {
|
||||
// 发生任何不可预测异常,均平滑降级为兜底文本,确保前端 100% 不白屏
|
||||
|
||||
@@ -99,19 +99,33 @@ export class AiConciergeService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按名片 ID 查询顾问人设与留资配置 (不存在时返回默认预设)
|
||||
* 按名片 ID 查询顾问人设与留资配置 (兼容单对象参数 { cardId },不存在或非法时安全降级返回默认预设)
|
||||
*/
|
||||
async getByCardId(cardId: number | string): Promise<AiConciergeConfig> {
|
||||
if (cardId === undefined || cardId === null || String(cardId).trim() === '') {
|
||||
throw new CoolCommException('缺少名片标识 cardId');
|
||||
async getByCardId(
|
||||
param: number | string | { cardId?: number | string }
|
||||
): Promise<AiConciergeConfig> {
|
||||
const rawCardId =
|
||||
typeof param === 'object' && param !== null ? param.cardId : param;
|
||||
|
||||
const defaultPreset = this.getDefaultPersona('trade_expert');
|
||||
if (
|
||||
rawCardId === undefined ||
|
||||
rawCardId === null ||
|
||||
String(rawCardId).trim() === ''
|
||||
) {
|
||||
return { cardId: 1, ...defaultPreset };
|
||||
}
|
||||
const numCardId = Number(cardId);
|
||||
|
||||
const numCardId = Number(rawCardId);
|
||||
if (isNaN(numCardId) || !numCardId) {
|
||||
return { cardId: 1, ...defaultPreset };
|
||||
}
|
||||
|
||||
const found = await this.aiConciergeEntity.findOneBy({ cardId: numCardId });
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
|
||||
const defaultPreset = this.getDefaultPersona('trade_expert');
|
||||
return {
|
||||
cardId: numCardId,
|
||||
...defaultPreset,
|
||||
@@ -119,13 +133,31 @@ export class AiConciergeService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按名片 ID 保存或更新配置
|
||||
* 按名片 ID 保存或更新配置 (兼容单对象参数与双入参)
|
||||
*/
|
||||
async saveByCardId(
|
||||
cardId: number | string,
|
||||
data: Partial<AiConciergeConfig>
|
||||
paramOrCardId:
|
||||
| number
|
||||
| string
|
||||
| (Partial<AiConciergeConfig> & { cardId?: number | string }),
|
||||
maybeData?: Partial<AiConciergeConfig>
|
||||
): Promise<AiConciergeConfig> {
|
||||
const numCardId = Number(cardId);
|
||||
let rawCardId: unknown;
|
||||
let data: Partial<AiConciergeConfig>;
|
||||
|
||||
if (
|
||||
typeof paramOrCardId === 'object' &&
|
||||
paramOrCardId !== null &&
|
||||
!maybeData
|
||||
) {
|
||||
rawCardId = paramOrCardId.cardId;
|
||||
data = paramOrCardId;
|
||||
} else {
|
||||
rawCardId = paramOrCardId;
|
||||
data = maybeData || {};
|
||||
}
|
||||
|
||||
const numCardId = Number(rawCardId) || 1;
|
||||
const payload = { ...data, cardId: numCardId };
|
||||
this.validate(payload);
|
||||
|
||||
|
||||
@@ -18,6 +18,18 @@ export class DeepSeekService extends BaseService {
|
||||
private config: DeepSeekConfig;
|
||||
private httpClient: AxiosInstance;
|
||||
|
||||
/** 多租户私有 BYOK 配置映射表 */
|
||||
private tenantConfigs: Map<string | number, DeepSeekConfig> = new Map();
|
||||
|
||||
/** 租户 Token 累计消耗账本 */
|
||||
private tenantUsage: Map<
|
||||
string | number,
|
||||
{ totalTokens: number; promptTokens: number; completionTokens: number; callCount: number }
|
||||
> = new Map();
|
||||
|
||||
/** 租户 Token 配额上限表 */
|
||||
private tenantQuotas: Map<string | number, number> = new Map();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const envKey = process.env.DEEPSEEK_API_KEY?.trim() || undefined;
|
||||
@@ -46,6 +58,113 @@ export class DeepSeekService extends BaseService {
|
||||
return { ...this.config };
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断指定租户是否已配置专属私有 Key
|
||||
*/
|
||||
hasTenantConfig(tenantId: string | number): boolean {
|
||||
return this.tenantConfigs.has(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定租户有效配置(未单独配置则优雅回退至平台公共默认配置)
|
||||
*/
|
||||
getTenantConfig(tenantId?: string | number): DeepSeekConfig {
|
||||
if (tenantId !== undefined && tenantId !== null && this.tenantConfigs.has(tenantId)) {
|
||||
return { ...this.tenantConfigs.get(tenantId)! };
|
||||
}
|
||||
return this.getConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* 为指定企业租户更新专属定制配置 (BYOK)
|
||||
*/
|
||||
updateTenantConfig(tenantId: string | number, partial: Partial<DeepSeekConfig>): void {
|
||||
const current = this.getTenantConfig(tenantId);
|
||||
const updated: DeepSeekConfig = {
|
||||
...current,
|
||||
...partial,
|
||||
enabled: partial.apiKey ? Boolean(partial.apiKey.trim()) : current.enabled,
|
||||
};
|
||||
this.tenantConfigs.set(tenantId, updated);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录指定租户的 Token 消耗
|
||||
*/
|
||||
recordTokenUsage(
|
||||
tenantId: string | number,
|
||||
tokens:
|
||||
| number
|
||||
| { promptTokens?: number; completionTokens?: number; totalTokens?: number }
|
||||
): void {
|
||||
const current = this.tenantUsage.get(tenantId) || {
|
||||
totalTokens: 0,
|
||||
promptTokens: 0,
|
||||
completionTokens: 0,
|
||||
callCount: 0,
|
||||
};
|
||||
|
||||
let prompt = 0;
|
||||
let completion = 0;
|
||||
let total = 0;
|
||||
|
||||
if (typeof tokens === 'number') {
|
||||
total = Number(tokens) || 0;
|
||||
} else if (tokens && typeof tokens === 'object') {
|
||||
prompt = Number(tokens.promptTokens) || 0;
|
||||
completion = Number(tokens.completionTokens) || 0;
|
||||
total = Number(tokens.totalTokens) || prompt + completion;
|
||||
}
|
||||
|
||||
this.tenantUsage.set(tenantId, {
|
||||
totalTokens: current.totalTokens + total,
|
||||
promptTokens: current.promptTokens + prompt,
|
||||
completionTokens: current.completionTokens + completion,
|
||||
callCount: current.callCount + 1,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定租户的 Token 用量统计
|
||||
*/
|
||||
getTenantTokenUsage(tenantId: string | number): {
|
||||
totalTokens: number;
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
callCount: number;
|
||||
} {
|
||||
return this.tenantUsage.get(tenantId) || {
|
||||
totalTokens: 0,
|
||||
promptTokens: 0,
|
||||
completionTokens: 0,
|
||||
callCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置指定租户的 Token 最大额度上限
|
||||
*/
|
||||
setTenantTokenQuota(tenantId: string | number, maxTotalTokens: number): void {
|
||||
this.tenantQuotas.set(tenantId, Math.max(0, Number(maxTotalTokens) || 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* 断言当前租户 Token 配额充足,超限则抛出 429 阻断
|
||||
*/
|
||||
assertTenantTokenQuota(tenantId: string | number, estimatedTokens = 1): void {
|
||||
const quota = this.tenantQuotas.get(tenantId);
|
||||
if (quota === undefined) {
|
||||
return;
|
||||
}
|
||||
const current = this.getTenantTokenUsage(tenantId).totalTokens;
|
||||
if (current + estimatedTokens > quota) {
|
||||
throw new CoolCommException(
|
||||
`当前租户 AI Token 配额已耗尽 (${current}/${quota}),请升级套餐或补充额度`,
|
||||
429
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态更新配置
|
||||
*/
|
||||
@@ -61,10 +180,11 @@ export class DeepSeekService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已配置有效 API Key
|
||||
* 检查是否已配置有效 API Key(支持按租户检查或默认平台池检查)
|
||||
*/
|
||||
isConfigured(): boolean {
|
||||
return Boolean(this.config.apiKey && this.config.apiKey.trim().length > 0);
|
||||
isConfigured(tenantId?: number | string): boolean {
|
||||
const cfg = this.getTenantConfig(tenantId);
|
||||
return Boolean(cfg.apiKey && cfg.apiKey.trim().length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,13 +268,15 @@ export class DeepSeekService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 对话补全调用 (支持优雅降级)
|
||||
* 对话补全调用 (支持多租户 BYOK、Token 计量与优雅降级)
|
||||
*/
|
||||
async chatCompletion(
|
||||
req: DeepSeekChatCompletionRequest,
|
||||
fallbackReply?: string
|
||||
fallbackReply?: string,
|
||||
tenantId?: number | string
|
||||
): Promise<string> {
|
||||
const apiKey = this.config.apiKey?.trim();
|
||||
const cfg = this.getTenantConfig(tenantId);
|
||||
const apiKey = cfg.apiKey?.trim();
|
||||
|
||||
if (!apiKey) {
|
||||
if (fallbackReply !== undefined) {
|
||||
@@ -163,12 +285,18 @@ export class DeepSeekService extends BaseService {
|
||||
throw new CoolCommException('DeepSeek API Key 未配置');
|
||||
}
|
||||
|
||||
const endpoint = `${this.config.baseUrl || 'https://api.deepseek.com'}/chat/completions`;
|
||||
// 租户 Token 配额校验 (预估输入字符数 / 2)
|
||||
const estimatedTokens = Math.ceil(
|
||||
(req.messages || []).reduce((acc, m) => acc + (m.content || '').length, 0) / 2
|
||||
);
|
||||
this.assertTenantTokenQuota(tenantId, estimatedTokens);
|
||||
|
||||
const endpoint = `${cfg.baseUrl || 'https://api.deepseek.com'}/chat/completions`;
|
||||
const payload = {
|
||||
model: req.model || this.config.model || 'deepseek-chat',
|
||||
model: req.model || cfg.model || 'deepseek-chat',
|
||||
messages: req.messages,
|
||||
temperature: req.temperature ?? this.config.temperature ?? 0.7,
|
||||
max_tokens: req.maxTokens ?? this.config.maxTokens ?? 2048,
|
||||
temperature: req.temperature ?? cfg.temperature ?? 0.7,
|
||||
max_tokens: req.maxTokens ?? cfg.maxTokens ?? 2048,
|
||||
stream: false,
|
||||
};
|
||||
|
||||
@@ -184,6 +312,11 @@ export class DeepSeekService extends BaseService {
|
||||
}
|
||||
);
|
||||
|
||||
// 记录实际 Token 消耗到租户账本
|
||||
if (response.data?.usage?.total_tokens) {
|
||||
this.recordTokenUsage(tenantId, response.data.usage.total_tokens);
|
||||
}
|
||||
|
||||
const content = response.data?.choices?.[0]?.message?.content;
|
||||
if (content) {
|
||||
return content.trim();
|
||||
|
||||
@@ -13,8 +13,9 @@ import { BaseAuditLogService, AuditRecordDTO } from '../../service/audit';
|
||||
entity: BaseAuditLogEntity,
|
||||
service: BaseAuditLogService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['operatorName', 'action', 'module', 'ip'],
|
||||
fieldEq: ['status', 'module'],
|
||||
keyWordLikeFields: ['a.operator_name', 'a.action', 'a.module', 'a.ip'],
|
||||
fieldEq: ['a.status', 'a.module'],
|
||||
addOrderBy: { create_time: 'desc' as const },
|
||||
},
|
||||
})
|
||||
export class BaseAuditLogController extends BaseController {
|
||||
|
||||
@@ -11,11 +11,11 @@ export class LoginDTO {
|
||||
@Rule(RuleType.string().required())
|
||||
password: string;
|
||||
|
||||
// 验证码ID
|
||||
@Rule(RuleType.string().required())
|
||||
captchaId: string;
|
||||
// 验证码ID(临时关闭后台验证码,改为可选)
|
||||
@Rule(RuleType.string().optional())
|
||||
captchaId?: string;
|
||||
|
||||
// 验证码
|
||||
@Rule(RuleType.required())
|
||||
verifyCode: number;
|
||||
// 验证码(临时关闭后台验证码,改为可选)
|
||||
@Rule(RuleType.optional())
|
||||
verifyCode?: number;
|
||||
}
|
||||
|
||||
@@ -50,58 +50,53 @@ export class BaseSysLoginService extends BaseService {
|
||||
* @param login
|
||||
*/
|
||||
async login(login: LoginDTO) {
|
||||
const { username, captchaId, verifyCode, password } = login;
|
||||
// 校验验证码
|
||||
const checkV = await this.captchaCheck(captchaId, verifyCode);
|
||||
if (checkV) {
|
||||
const user = await this.baseSysUserEntity.findOneBy({ username });
|
||||
// 校验用户
|
||||
if (user) {
|
||||
// 校验用户状态及密码
|
||||
if (user.status === 0 || user.password !== md5(password)) {
|
||||
throw new CoolCommException('账户或密码不正确~');
|
||||
}
|
||||
} else {
|
||||
const { username, password } = login;
|
||||
// 临时关闭后台登录图片验证码,上线前恢复 captchaCheck
|
||||
const user = await this.baseSysUserEntity.findOneBy({ username });
|
||||
// 校验用户
|
||||
if (user) {
|
||||
// 校验用户状态及密码
|
||||
if (user.status === 0 || user.password !== md5(password)) {
|
||||
throw new CoolCommException('账户或密码不正确~');
|
||||
}
|
||||
// 校验角色
|
||||
const roleIds = await this.baseSysRoleService.getByUser(user.id);
|
||||
if (_.isEmpty(roleIds)) {
|
||||
throw new CoolCommException('该用户未设置任何角色,无法登录~');
|
||||
}
|
||||
|
||||
// 生成token
|
||||
const { expire, refreshExpire } = this.coolConfig.jwt.token;
|
||||
const result = {
|
||||
expire,
|
||||
token: await this.generateToken(user, roleIds, expire),
|
||||
refreshExpire,
|
||||
refreshToken: await this.generateToken(
|
||||
user,
|
||||
roleIds,
|
||||
refreshExpire,
|
||||
true
|
||||
),
|
||||
};
|
||||
|
||||
// 将用户相关信息保存到缓存
|
||||
const perms = await this.baseSysMenuService.getPerms(roleIds);
|
||||
const departments = await this.baseSysDepartmentService.getByRoleIds(
|
||||
roleIds,
|
||||
user.username === 'admin'
|
||||
);
|
||||
await this.midwayCache.set(`admin:department:${user.id}`, departments);
|
||||
await this.midwayCache.set(`admin:perms:${user.id}`, perms);
|
||||
await this.midwayCache.set(`admin:token:${user.id}`, result.token);
|
||||
await this.midwayCache.set(
|
||||
`admin:token:refresh:${user.id}`,
|
||||
result.token
|
||||
);
|
||||
|
||||
return result;
|
||||
} else {
|
||||
throw new CoolCommException('验证码不正确');
|
||||
throw new CoolCommException('账户或密码不正确~');
|
||||
}
|
||||
// 校验角色
|
||||
const roleIds = await this.baseSysRoleService.getByUser(user.id);
|
||||
if (_.isEmpty(roleIds)) {
|
||||
throw new CoolCommException('该用户未设置任何角色,无法登录~');
|
||||
}
|
||||
|
||||
// 生成token
|
||||
const { expire, refreshExpire } = this.coolConfig.jwt.token;
|
||||
const result = {
|
||||
expire,
|
||||
token: await this.generateToken(user, roleIds, expire),
|
||||
refreshExpire,
|
||||
refreshToken: await this.generateToken(
|
||||
user,
|
||||
roleIds,
|
||||
refreshExpire,
|
||||
true
|
||||
),
|
||||
};
|
||||
|
||||
// 将用户相关信息保存到缓存
|
||||
const perms = await this.baseSysMenuService.getPerms(roleIds);
|
||||
const departments = await this.baseSysDepartmentService.getByRoleIds(
|
||||
roleIds,
|
||||
user.username === 'admin'
|
||||
);
|
||||
await this.midwayCache.set(`admin:department:${user.id}`, departments);
|
||||
await this.midwayCache.set(`admin:perms:${user.id}`, perms);
|
||||
await this.midwayCache.set(`admin:token:${user.id}`, result.token);
|
||||
await this.midwayCache.set(
|
||||
`admin:token:refresh:${user.id}`,
|
||||
result.token
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -46,7 +46,7 @@ export class BaseSysUserService extends BaseService {
|
||||
); // 部门权限
|
||||
const sql = `
|
||||
SELECT
|
||||
a.id,a.name,a.nickName,a.headImg,a.email,a.remark,a.status,a.createTime,a.updateTime,a.username,a.phone,a.departmentId,
|
||||
a.id,a.name,a.nickName,a.headImg,a.email,a.remark,a.status,a.create_time as createTime,a.update_time as updateTime,a.username,a.phone,a.departmentId,
|
||||
b.name as "departmentName"
|
||||
FROM
|
||||
base_sys_user a
|
||||
|
||||
@@ -13,8 +13,11 @@ export const adminCardArticleCurdOption = {
|
||||
service: CardArticleService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.title', 'a.summary'],
|
||||
fieldEq: ['a.cardId', 'a.isPublished'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
fieldEq: [
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.is_published', requestParam: 'isPublished' },
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ export const adminCardBentoCurdOption = {
|
||||
service: CardBentoService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.title', 'a.content'],
|
||||
fieldEq: ['a.cardId', 'a.type', 'a.status'],
|
||||
addOrderBy: { sortOrder: 'asc' as const },
|
||||
fieldEq: [{ column: 'a.card_id', requestParam: 'cardId' }, 'a.type', 'a.status'],
|
||||
addOrderBy: { sort_order: 'asc' as const },
|
||||
},
|
||||
serviceApis: [
|
||||
{ method: 'getBlocksByCardId', summary: '按名片获取有序 Bento' },
|
||||
|
||||
@@ -13,8 +13,8 @@ export const adminCardCasesCurdOption = {
|
||||
service: CardCasesService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.title', 'a.client', 'a.metrics'],
|
||||
fieldEq: ['a.cardId'],
|
||||
addOrderBy: { sortOrder: 'asc' as const },
|
||||
fieldEq: [{ column: 'a.card_id', requestParam: 'cardId' }],
|
||||
addOrderBy: { sort_order: 'asc' as const },
|
||||
},
|
||||
serviceApis: [
|
||||
{ method: 'getCasesByCardId', summary: '按名片获取案例列表' },
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Body, Inject, Post, Provide } from '@midwayjs/core';
|
||||
import { CoolController, BaseController, CoolCommException } from '@cool-midway/core';
|
||||
import { CardContactEntity } from '../../entity/contact';
|
||||
import { CardContactService } from '../../service/contact';
|
||||
import { CardInfoEntity } from '../../entity/info';
|
||||
|
||||
interface AdminCtx {
|
||||
admin?: {
|
||||
userId?: number;
|
||||
tenantId?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 名片大厅人脉
|
||||
* 路由前缀: /admin/card/contact
|
||||
*/
|
||||
@Provide()
|
||||
@CoolController({
|
||||
api: ['page'],
|
||||
entity: CardContactEntity,
|
||||
service: CardContactService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['b.name', 'b.title', 'b.company'],
|
||||
select: [
|
||||
'a.*',
|
||||
'b.name AS peerName',
|
||||
'b.title AS peerTitle',
|
||||
'b.company AS peerCompany',
|
||||
'b.avatar_url AS peerAvatarUrl',
|
||||
'b.slug AS peerSlug',
|
||||
],
|
||||
join: [
|
||||
{
|
||||
entity: CardInfoEntity,
|
||||
alias: 'b',
|
||||
condition: 'a.peer_card_id = b.id',
|
||||
type: 'leftJoin',
|
||||
},
|
||||
],
|
||||
where: async (ctx: AdminCtx) => [
|
||||
['a.owner_user_id = :uid', { uid: ctx.admin?.userId || 0 }],
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
})
|
||||
export class AdminCardContactController extends BaseController {
|
||||
@Inject()
|
||||
ctx: AdminCtx;
|
||||
|
||||
@Inject()
|
||||
cardContactService: CardContactService;
|
||||
|
||||
/**
|
||||
* 把对方名片收入大厅
|
||||
* POST /admin/card/contact/collect
|
||||
*/
|
||||
@Post('/collect', { summary: '收入大厅人脉' })
|
||||
async collect(
|
||||
@Body() body: { peerCardId?: number; ownerCardId?: number }
|
||||
) {
|
||||
const ownerUserId = this.ctx.admin?.userId;
|
||||
if (!ownerUserId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
if (!body?.peerCardId) {
|
||||
throw new CoolCommException('缺少对方名片', 400);
|
||||
}
|
||||
const data = await this.cardContactService.collect({
|
||||
ownerUserId: Number(ownerUserId),
|
||||
peerCardId: Number(body.peerCardId),
|
||||
ownerCardId: body.ownerCardId != null ? Number(body.ownerCardId) : null,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前用户人脉分页(带对方名片摘要)
|
||||
* POST /admin/card/contact/hallPage
|
||||
*/
|
||||
@Post('/hallPage', { summary: '大厅人脉分页' })
|
||||
async hallPage(
|
||||
@Body() body: { page?: number; size?: number; keyWord?: string }
|
||||
) {
|
||||
const ownerUserId = this.ctx.admin?.userId;
|
||||
if (!ownerUserId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
const data = await this.cardContactService.pageContacts({
|
||||
ownerUserId: Number(ownerUserId),
|
||||
page: body?.page,
|
||||
size: body?.size,
|
||||
keyWord: body?.keyWord,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同租户已发布名片墙
|
||||
* POST /admin/card/contact/teamWall
|
||||
*/
|
||||
@Post('/teamWall', { summary: '团队名片墙' })
|
||||
async teamWall(
|
||||
@Body() body: { page?: number; size?: number; keyWord?: string }
|
||||
) {
|
||||
const ownerUserId = this.ctx.admin?.userId;
|
||||
if (!ownerUserId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
const tenantId = await this.cardContactService.resolveTenantId(
|
||||
Number(ownerUserId),
|
||||
this.ctx.admin?.tenantId
|
||||
);
|
||||
const data = await this.cardContactService.pageTeamWall({
|
||||
tenantId,
|
||||
excludeUserId: Number(ownerUserId),
|
||||
page: body?.page,
|
||||
size: body?.size,
|
||||
keyWord: body?.keyWord,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Body, Inject, Post, Provide } from '@midwayjs/core';
|
||||
import { CoolController, BaseController, CoolCommException } from '@cool-midway/core';
|
||||
import { CardEventService } from '../../service/event';
|
||||
|
||||
interface AdminCtx {
|
||||
admin?: {
|
||||
userId?: number;
|
||||
tenantId?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 展会现场
|
||||
* 路由前缀: /admin/card/event
|
||||
*/
|
||||
@Provide()
|
||||
@CoolController()
|
||||
export class AdminCardEventController extends BaseController {
|
||||
@Inject()
|
||||
ctx: AdminCtx;
|
||||
|
||||
@Inject()
|
||||
cardEventService: CardEventService;
|
||||
|
||||
private requireUserId(): number {
|
||||
const ownerUserId = this.ctx.admin?.userId;
|
||||
if (!ownerUserId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
return Number(ownerUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/card/event/join
|
||||
*/
|
||||
@Post('/join', { summary: '活动码加入展会现场' })
|
||||
async join(
|
||||
@Body() body: { code?: string; cardId?: number }
|
||||
) {
|
||||
if (!body?.code) {
|
||||
throw new CoolCommException('缺少活动码', 400);
|
||||
}
|
||||
const data = await this.cardEventService.joinEvent({
|
||||
userId: this.requireUserId(),
|
||||
code: body.code,
|
||||
cardId: body.cardId != null ? Number(body.cardId) : null,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/card/event/floorPage
|
||||
*/
|
||||
@Post('/floorPage', { summary: '展会现场同场名片' })
|
||||
async floorPage(
|
||||
@Body() body: { page?: number; size?: number; keyWord?: string }
|
||||
) {
|
||||
const data = await this.cardEventService.pageEventFloor({
|
||||
userId: this.requireUserId(),
|
||||
page: body?.page,
|
||||
size: body?.size,
|
||||
keyWord: body?.keyWord,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/card/event/current
|
||||
*/
|
||||
@Post('/current', { summary: '当前加入的展会现场' })
|
||||
async current() {
|
||||
const data = await this.cardEventService.currentEvent(this.requireUserId());
|
||||
return this.ok(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Body, Inject, Post, Provide } from '@midwayjs/core';
|
||||
import { CoolController, BaseController, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CardMutualExchangeService } from '../../service/mutual-exchange';
|
||||
import { CardInfoEntity } from '../../entity/info';
|
||||
|
||||
interface AdminCtx {
|
||||
admin?: {
|
||||
userId?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 名片双向互换
|
||||
* 路由前缀: /admin/card/exchange
|
||||
*/
|
||||
@Provide()
|
||||
@CoolController()
|
||||
export class AdminCardExchangeController extends BaseController {
|
||||
@Inject()
|
||||
ctx: AdminCtx;
|
||||
|
||||
@Inject()
|
||||
cardMutualExchangeService: CardMutualExchangeService;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
private async resolveActingCardId(explicit?: number): Promise<number> {
|
||||
if (explicit && Number(explicit) > 0) {
|
||||
return Number(explicit);
|
||||
}
|
||||
const userId = this.ctx.admin?.userId;
|
||||
if (!userId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { userId: Number(userId), status: 'published' },
|
||||
});
|
||||
if (!card) {
|
||||
throw new CoolCommException('请先发布一张名片再互换', 400);
|
||||
}
|
||||
return Number(card.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/card/exchange/initiate
|
||||
*/
|
||||
@Post('/initiate', { summary: '发起名片互换' })
|
||||
async initiate(
|
||||
@Body()
|
||||
body: {
|
||||
senderCardId?: number;
|
||||
recipientCardId?: number;
|
||||
notes?: string;
|
||||
}
|
||||
) {
|
||||
if (!body?.recipientCardId) {
|
||||
throw new CoolCommException('缺少对方名片', 400);
|
||||
}
|
||||
const senderCardId = await this.resolveActingCardId(body.senderCardId);
|
||||
const data = await this.cardMutualExchangeService.initiateExchange({
|
||||
senderCardId,
|
||||
recipientCardId: Number(body.recipientCardId),
|
||||
notes: body.notes,
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /admin/card/exchange/confirm
|
||||
*/
|
||||
@Post('/confirm', { summary: '确认名片互换' })
|
||||
async confirm(
|
||||
@Body()
|
||||
body: {
|
||||
invitationId?: string;
|
||||
exchangeCode?: string;
|
||||
actingCardId?: number;
|
||||
}
|
||||
) {
|
||||
const actingCardId = await this.resolveActingCardId(body?.actingCardId);
|
||||
if (body?.exchangeCode) {
|
||||
const data = await this.cardMutualExchangeService.confirmByCode(
|
||||
body.exchangeCode,
|
||||
actingCardId
|
||||
);
|
||||
return this.ok(data);
|
||||
}
|
||||
if (!body?.invitationId) {
|
||||
throw new CoolCommException('缺少互换单或互换码', 400);
|
||||
}
|
||||
const data = await this.cardMutualExchangeService.confirmExchange(
|
||||
String(body.invitationId),
|
||||
actingCardId
|
||||
);
|
||||
return this.ok(data);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { CardInfoService } from '../../service/info';
|
||||
interface AdminInsertCtx {
|
||||
admin?: {
|
||||
userId?: number;
|
||||
tenantId?: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,12 +23,13 @@ export const adminCardInfoCurdOption = {
|
||||
service: CardInfoService,
|
||||
insertParam: (ctx: AdminInsertCtx) => ({
|
||||
userId: ctx.admin?.userId,
|
||||
tenantId: ctx.admin?.tenantId,
|
||||
}),
|
||||
infoIgnoreProperty: ['remark', 'internalConfig'],
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.name', 'a.title', 'a.company', 'a.slug'],
|
||||
fieldEq: ['a.status', 'a.themeCode'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
fieldEq: ['a.status', { column: 'a.theme_code', requestParam: 'themeCode' }],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export const adminCardLocaleCurdOption = {
|
||||
entity: CardLocaleEntity,
|
||||
service: CardLocaleService,
|
||||
pageQueryOp: {
|
||||
fieldEq: ['a.cardId', 'a.locale'],
|
||||
fieldEq: [{ column: 'a.card_id', requestParam: 'cardId' }, 'a.locale'],
|
||||
},
|
||||
serviceApis: [
|
||||
{ method: 'upsert', summary: '按名片语言覆盖写入' },
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { BaseEntity } from '../../base/entity/base';
|
||||
import { Column, Entity, Index } from 'typeorm';
|
||||
import { CardContactSource } from '../../../comm/types/omni';
|
||||
|
||||
/**
|
||||
* 名片大厅人脉
|
||||
* 一人对一张他人名片只保留一行
|
||||
*/
|
||||
@Entity('card_contact')
|
||||
@Index('uk_card_contact_owner_peer', ['ownerUserId', 'peerCardId'], {
|
||||
unique: true,
|
||||
})
|
||||
export class CardContactEntity extends BaseEntity {
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'owner_user_id',
|
||||
comment: '收藏人用户 ID',
|
||||
})
|
||||
ownerUserId: number;
|
||||
|
||||
@Column({
|
||||
name: 'owner_card_id',
|
||||
comment: '收藏人当时使用的名片 ID',
|
||||
nullable: true,
|
||||
})
|
||||
ownerCardId?: number | null;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'peer_card_id',
|
||||
comment: '对方名片 ID',
|
||||
})
|
||||
peerCardId: number;
|
||||
|
||||
@Column({
|
||||
name: 'source',
|
||||
comment: '来源 (exchange: 互换, collect: 带走, scan: 扫码)',
|
||||
length: 20,
|
||||
default: 'collect',
|
||||
})
|
||||
source: CardContactSource;
|
||||
|
||||
@Column({
|
||||
name: 'lead_id',
|
||||
comment: '同步生成的线索 ID',
|
||||
nullable: true,
|
||||
})
|
||||
leadId?: number | null;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { BaseEntity } from '../../base/entity/base';
|
||||
import { Column, Entity, Index } from 'typeorm';
|
||||
|
||||
/**
|
||||
* 展会现场成员
|
||||
* 一人对一个活动只保留一行
|
||||
*/
|
||||
@Entity('card_event_member')
|
||||
@Index('uk_card_event_member', ['eventId', 'userId'], { unique: true })
|
||||
export class CardEventMemberEntity extends BaseEntity {
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'event_id',
|
||||
comment: '现场活动 ID',
|
||||
})
|
||||
eventId: number;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'user_id',
|
||||
comment: '加入人用户 ID',
|
||||
})
|
||||
userId: number;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'card_id',
|
||||
comment: '加入时使用的名片 ID',
|
||||
})
|
||||
cardId: number;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { BaseEntity } from '../../base/entity/base';
|
||||
import { Column, Entity, Index } from 'typeorm';
|
||||
import { CardEventStatus } from '../../../comm/types/omni';
|
||||
|
||||
/**
|
||||
* 展会现场活动
|
||||
*/
|
||||
@Entity('card_event')
|
||||
export class CardEventEntity extends BaseEntity {
|
||||
@Index({ unique: true })
|
||||
@Column({
|
||||
name: 'code',
|
||||
comment: '6 位活动码',
|
||||
length: 6,
|
||||
})
|
||||
code: string;
|
||||
|
||||
@Column({
|
||||
name: 'name',
|
||||
comment: '现场名称',
|
||||
length: 120,
|
||||
})
|
||||
name: string;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'status',
|
||||
comment: 'active / ended',
|
||||
length: 20,
|
||||
default: 'active',
|
||||
})
|
||||
status: CardEventStatus;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { BaseEntity } from '../../base/entity/base';
|
||||
import { Column, Entity, Index } from 'typeorm';
|
||||
|
||||
export type CardExchangeStatus =
|
||||
| 'REQUESTED'
|
||||
| 'ACCEPTED'
|
||||
| 'REJECTED'
|
||||
| 'EXPIRED';
|
||||
|
||||
/**
|
||||
* 名片双向互换单
|
||||
*/
|
||||
@Entity('card_exchange')
|
||||
export class CardExchangeEntity extends BaseEntity {
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'exchange_code',
|
||||
comment: '6 位互换码',
|
||||
length: 6,
|
||||
})
|
||||
exchangeCode: string;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'sender_card_id',
|
||||
comment: '发起方名片 ID',
|
||||
})
|
||||
senderCardId: number;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'recipient_card_id',
|
||||
comment: '接收方名片 ID',
|
||||
})
|
||||
recipientCardId: number;
|
||||
|
||||
@Column({
|
||||
name: 'sender_user_id',
|
||||
comment: '发起方用户 ID',
|
||||
nullable: true,
|
||||
})
|
||||
senderUserId?: number | null;
|
||||
|
||||
@Column({
|
||||
name: 'recipient_user_id',
|
||||
comment: '接收方用户 ID',
|
||||
nullable: true,
|
||||
})
|
||||
recipientUserId?: number | null;
|
||||
|
||||
@Index()
|
||||
@Column({
|
||||
name: 'status',
|
||||
comment: 'REQUESTED / ACCEPTED / REJECTED / EXPIRED',
|
||||
length: 20,
|
||||
default: 'REQUESTED',
|
||||
})
|
||||
status: CardExchangeStatus;
|
||||
|
||||
@Column({
|
||||
name: 'notes',
|
||||
comment: '互换备注',
|
||||
type: 'text',
|
||||
nullable: true,
|
||||
})
|
||||
notes?: string;
|
||||
|
||||
@Column({
|
||||
name: 'accepted_at',
|
||||
comment: '确认时间',
|
||||
type: 'varchar',
|
||||
length: 32,
|
||||
nullable: true,
|
||||
})
|
||||
acceptedAt?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import { Provide } from '@midwayjs/core';
|
||||
import { BaseService, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CardContactEntity } from '../entity/contact';
|
||||
import { CardInfoEntity } from '../entity/info';
|
||||
import { CrmLeadEntity } from '../../crm/entity/lead';
|
||||
import {
|
||||
CardContact,
|
||||
CardContactSource,
|
||||
} from '../../../comm/types/omni';
|
||||
|
||||
export interface UpsertContactInput {
|
||||
ownerUserId: number;
|
||||
ownerCardId?: number | null;
|
||||
peerCardId: number;
|
||||
source: CardContactSource;
|
||||
leadId?: number | null;
|
||||
}
|
||||
|
||||
export interface CollectContactInput {
|
||||
ownerUserId: number;
|
||||
peerCardId: number;
|
||||
ownerCardId?: number | null;
|
||||
}
|
||||
|
||||
export interface PageContactsQuery {
|
||||
ownerUserId: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
keyWord?: string;
|
||||
}
|
||||
|
||||
export interface PageTeamWallQuery {
|
||||
tenantId: number;
|
||||
excludeUserId?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
keyWord?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 名片大厅人脉
|
||||
*/
|
||||
@Provide()
|
||||
export class CardContactService extends BaseService {
|
||||
@InjectEntityModel(CardContactEntity)
|
||||
cardContactEntity: Repository<CardContactEntity>;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
@InjectEntityModel(CrmLeadEntity)
|
||||
crmLeadEntity: Repository<CrmLeadEntity>;
|
||||
|
||||
async upsertContact(input: UpsertContactInput): Promise<CardContactEntity> {
|
||||
if (!input?.ownerUserId || !input?.peerCardId) {
|
||||
throw new CoolCommException('缺少人脉双方标识', 400);
|
||||
}
|
||||
if (input.ownerCardId && Number(input.ownerCardId) === Number(input.peerCardId)) {
|
||||
throw new CoolCommException('不能收藏自己的名片', 400);
|
||||
}
|
||||
|
||||
const peer = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(input.peerCardId) },
|
||||
});
|
||||
if (!peer) {
|
||||
throw new CoolCommException('对方名片不存在', 404);
|
||||
}
|
||||
if (peer.userId && Number(peer.userId) === Number(input.ownerUserId)) {
|
||||
throw new CoolCommException('不能收藏自己的名片', 400);
|
||||
}
|
||||
|
||||
let row = await this.cardContactEntity.findOne({
|
||||
where: {
|
||||
ownerUserId: Number(input.ownerUserId),
|
||||
peerCardId: Number(input.peerCardId),
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
row = new CardContactEntity();
|
||||
row.ownerUserId = Number(input.ownerUserId);
|
||||
row.peerCardId = Number(input.peerCardId);
|
||||
}
|
||||
if (input.ownerCardId != null) {
|
||||
row.ownerCardId = Number(input.ownerCardId);
|
||||
}
|
||||
row.source = input.source;
|
||||
if (input.leadId != null) {
|
||||
row.leadId = Number(input.leadId);
|
||||
}
|
||||
if (peer.tenantId && !row.tenantId) {
|
||||
row.tenantId = Number(peer.tenantId);
|
||||
}
|
||||
return this.cardContactEntity.save(row);
|
||||
}
|
||||
|
||||
async collect(input: CollectContactInput): Promise<CardContactEntity> {
|
||||
return this.upsertContact({
|
||||
ownerUserId: input.ownerUserId,
|
||||
ownerCardId: input.ownerCardId,
|
||||
peerCardId: input.peerCardId,
|
||||
source: 'collect',
|
||||
});
|
||||
}
|
||||
|
||||
async upsertExchangeLead(
|
||||
targetCard: CardInfoEntity,
|
||||
sourceCard: CardInfoEntity
|
||||
): Promise<CrmLeadEntity> {
|
||||
const visitorId = `card:${sourceCard.id}`;
|
||||
let lead = await this.crmLeadEntity.findOne({
|
||||
where: {
|
||||
cardId: Number(targetCard.id),
|
||||
visitorId,
|
||||
},
|
||||
});
|
||||
if (!lead) {
|
||||
lead = new CrmLeadEntity();
|
||||
lead.cardId = Number(targetCard.id);
|
||||
lead.visitorId = visitorId;
|
||||
lead.status = 'new';
|
||||
lead.intentScore = 50;
|
||||
lead.source = 'exchange';
|
||||
}
|
||||
lead.name = sourceCard.name;
|
||||
lead.company = sourceCard.company;
|
||||
lead.phone = sourceCard.phone;
|
||||
lead.email = sourceCard.email;
|
||||
if (targetCard.userId) {
|
||||
lead.userId = Number(targetCard.userId);
|
||||
}
|
||||
if (targetCard.tenantId) {
|
||||
lead.tenantId = Number(targetCard.tenantId);
|
||||
}
|
||||
return this.crmLeadEntity.save(lead);
|
||||
}
|
||||
|
||||
async syncExchangePair(
|
||||
ownerCard: CardInfoEntity,
|
||||
peerCard: CardInfoEntity
|
||||
): Promise<{ contact: CardContactEntity; lead: CrmLeadEntity }> {
|
||||
const lead = await this.upsertExchangeLead(ownerCard, peerCard);
|
||||
const contact = await this.upsertContact({
|
||||
ownerUserId: Number(ownerCard.userId),
|
||||
ownerCardId: Number(ownerCard.id),
|
||||
peerCardId: Number(peerCard.id),
|
||||
source: 'exchange',
|
||||
leadId: Number(lead.id),
|
||||
});
|
||||
return { contact, lead };
|
||||
}
|
||||
|
||||
async pageContacts(
|
||||
query: PageContactsQuery
|
||||
): Promise<{
|
||||
list: CardContact[];
|
||||
pagination: { page: number; size: number; total: number };
|
||||
}> {
|
||||
const page = query.page && query.page > 0 ? Math.floor(query.page) : 1;
|
||||
const size = query.size && query.size > 0 ? Math.floor(query.size) : 20;
|
||||
const ownerUserId = Number(query.ownerUserId);
|
||||
const rows = await this.cardContactEntity.find({
|
||||
where: { ownerUserId },
|
||||
});
|
||||
const keyword = query.keyWord ? String(query.keyWord).trim().toLowerCase() : '';
|
||||
const hydrated: CardContact[] = [];
|
||||
for (const row of rows) {
|
||||
const peer = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(row.peerCardId) },
|
||||
});
|
||||
const item: CardContact = {
|
||||
id: row.id,
|
||||
ownerUserId: row.ownerUserId,
|
||||
ownerCardId: row.ownerCardId,
|
||||
peerCardId: row.peerCardId,
|
||||
source: row.source,
|
||||
leadId: row.leadId,
|
||||
peerName: peer?.name,
|
||||
peerTitle: peer?.title,
|
||||
peerCompany: peer?.company,
|
||||
peerAvatarUrl: peer?.avatarUrl,
|
||||
peerSlug: peer?.slug,
|
||||
exchangedAt: row.updateTime || row.createTime,
|
||||
};
|
||||
if (keyword) {
|
||||
const hay = `${item.peerName || ''} ${item.peerTitle || ''} ${item.peerCompany || ''}`.toLowerCase();
|
||||
if (!hay.includes(keyword)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
hydrated.push(item);
|
||||
}
|
||||
const total = hydrated.length;
|
||||
const start = (page - 1) * size;
|
||||
return {
|
||||
list: hydrated.slice(start, start + size),
|
||||
pagination: { page, size, total },
|
||||
};
|
||||
}
|
||||
|
||||
async resolveTenantId(userId: number, explicit?: number | null): Promise<number> {
|
||||
if (explicit != null && Number(explicit) > 0) {
|
||||
return Number(explicit);
|
||||
}
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { userId: Number(userId) },
|
||||
});
|
||||
if (card?.tenantId) {
|
||||
return Number(card.tenantId);
|
||||
}
|
||||
throw new CoolCommException('当前账号未加入企业', 400);
|
||||
}
|
||||
|
||||
async pageTeamWall(
|
||||
query: PageTeamWallQuery
|
||||
): Promise<{
|
||||
list: CardContact[];
|
||||
pagination: { page: number; size: number; total: number };
|
||||
}> {
|
||||
const page = query.page && query.page > 0 ? Math.floor(query.page) : 1;
|
||||
const size = query.size && query.size > 0 ? Math.floor(query.size) : 20;
|
||||
const tenantId = Number(query.tenantId);
|
||||
if (!tenantId) {
|
||||
throw new CoolCommException('缺少租户', 400);
|
||||
}
|
||||
const cards = await this.cardInfoEntity.find({
|
||||
where: { tenantId, status: 'published' },
|
||||
});
|
||||
const keyword = query.keyWord ? String(query.keyWord).trim().toLowerCase() : '';
|
||||
const excludeUserId =
|
||||
query.excludeUserId != null ? Number(query.excludeUserId) : 0;
|
||||
const hydrated: CardContact[] = [];
|
||||
for (const card of cards) {
|
||||
if (excludeUserId && Number(card.userId) === excludeUserId) {
|
||||
continue;
|
||||
}
|
||||
if (keyword) {
|
||||
const hay = `${card.name || ''} ${card.title || ''} ${card.company || ''}`.toLowerCase();
|
||||
if (!hay.includes(keyword)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
hydrated.push({
|
||||
ownerUserId: excludeUserId || 0,
|
||||
peerCardId: Number(card.id),
|
||||
source: 'collect',
|
||||
peerName: card.name,
|
||||
peerTitle: card.title,
|
||||
peerCompany: card.company,
|
||||
peerAvatarUrl: card.avatarUrl,
|
||||
peerSlug: card.slug,
|
||||
});
|
||||
}
|
||||
const total = hydrated.length;
|
||||
const start = (page - 1) * size;
|
||||
return {
|
||||
list: hydrated.slice(start, start + size),
|
||||
pagination: { page, size, total },
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { Provide } from '@midwayjs/core';
|
||||
import { BaseService, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CardEventEntity } from '../entity/event';
|
||||
import { CardEventMemberEntity } from '../entity/event-member';
|
||||
import { CardInfoEntity } from '../entity/info';
|
||||
import {
|
||||
CardContact,
|
||||
CardEvent,
|
||||
CardEventJoinResult,
|
||||
CardEventMember,
|
||||
} from '../../../comm/types/omni';
|
||||
|
||||
export interface JoinEventInput {
|
||||
userId: number;
|
||||
code: string;
|
||||
cardId?: number | null;
|
||||
}
|
||||
|
||||
export interface PageEventFloorQuery {
|
||||
userId: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
keyWord?: string;
|
||||
}
|
||||
|
||||
export function normalizeEventCode(raw: string): string {
|
||||
const code = String(raw || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (!/^[A-Z0-9]{6}$/.test(code)) {
|
||||
throw new CoolCommException('请输入 6 位活动码', 400);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
function toEvent(row: CardEventEntity): CardEvent {
|
||||
return {
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
|
||||
function toMember(row: CardEventMemberEntity): CardEventMember {
|
||||
return {
|
||||
id: row.id,
|
||||
eventId: row.eventId,
|
||||
userId: row.userId,
|
||||
cardId: row.cardId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 展会现场活动码与同场名片墙
|
||||
*/
|
||||
@Provide()
|
||||
export class CardEventService extends BaseService {
|
||||
@InjectEntityModel(CardEventEntity)
|
||||
cardEventEntity: Repository<CardEventEntity>;
|
||||
|
||||
@InjectEntityModel(CardEventMemberEntity)
|
||||
cardEventMemberEntity: Repository<CardEventMemberEntity>;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
async resolveUserCard(
|
||||
userId: number,
|
||||
explicit?: number | null
|
||||
): Promise<CardInfoEntity> {
|
||||
if (explicit != null && Number(explicit) > 0) {
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(explicit) },
|
||||
});
|
||||
if (!card || Number(card.userId) !== Number(userId)) {
|
||||
throw new CoolCommException('名片不属于当前账号', 400);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
const published = await this.cardInfoEntity.findOne({
|
||||
where: { userId: Number(userId), status: 'published' },
|
||||
});
|
||||
if (published) {
|
||||
return published;
|
||||
}
|
||||
const anyCard = await this.cardInfoEntity.findOne({
|
||||
where: { userId: Number(userId) },
|
||||
});
|
||||
if (!anyCard) {
|
||||
throw new CoolCommException('请先创建名片', 400);
|
||||
}
|
||||
return anyCard;
|
||||
}
|
||||
|
||||
async joinEvent(input: JoinEventInput): Promise<CardEventJoinResult> {
|
||||
if (!input?.userId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
const code = normalizeEventCode(input.code);
|
||||
let event = await this.cardEventEntity.findOne({ where: { code } });
|
||||
if (!event) {
|
||||
event = new CardEventEntity();
|
||||
event.code = code;
|
||||
event.name = code;
|
||||
event.status = 'active';
|
||||
event = await this.cardEventEntity.save(event);
|
||||
}
|
||||
const card = await this.resolveUserCard(input.userId, input.cardId);
|
||||
let member = await this.cardEventMemberEntity.findOne({
|
||||
where: {
|
||||
eventId: Number(event.id),
|
||||
userId: Number(input.userId),
|
||||
},
|
||||
});
|
||||
if (!member) {
|
||||
member = new CardEventMemberEntity();
|
||||
member.eventId = Number(event.id);
|
||||
member.userId = Number(input.userId);
|
||||
}
|
||||
member.cardId = Number(card.id);
|
||||
if (card.tenantId && !member.tenantId) {
|
||||
member.tenantId = Number(card.tenantId);
|
||||
}
|
||||
member = await this.cardEventMemberEntity.save(member);
|
||||
return {
|
||||
event: toEvent(event),
|
||||
member: toMember(member),
|
||||
};
|
||||
}
|
||||
|
||||
async currentEvent(userId: number): Promise<CardEvent | null> {
|
||||
const members = await this.cardEventMemberEntity.find({
|
||||
where: { userId: Number(userId) },
|
||||
});
|
||||
if (!members.length) {
|
||||
return null;
|
||||
}
|
||||
const latest = members[members.length - 1];
|
||||
const event = await this.cardEventEntity.findOne({
|
||||
where: { id: Number(latest.eventId) },
|
||||
});
|
||||
return event ? toEvent(event) : null;
|
||||
}
|
||||
|
||||
async pageEventFloor(
|
||||
query: PageEventFloorQuery
|
||||
): Promise<{
|
||||
list: CardContact[];
|
||||
pagination: { page: number; size: number; total: number };
|
||||
}> {
|
||||
const page = query.page && query.page > 0 ? Math.floor(query.page) : 1;
|
||||
const size = query.size && query.size > 0 ? Math.floor(query.size) : 20;
|
||||
const members = await this.cardEventMemberEntity.find({
|
||||
where: { userId: Number(query.userId) },
|
||||
});
|
||||
if (!members.length) {
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, size, total: 0 },
|
||||
};
|
||||
}
|
||||
const latest = members[members.length - 1];
|
||||
const peers = await this.cardEventMemberEntity.find({
|
||||
where: { eventId: Number(latest.eventId) },
|
||||
});
|
||||
const keyword = query.keyWord
|
||||
? String(query.keyWord).trim().toLowerCase()
|
||||
: '';
|
||||
const hydrated: CardContact[] = [];
|
||||
for (const peer of peers) {
|
||||
if (Number(peer.userId) === Number(query.userId)) {
|
||||
continue;
|
||||
}
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(peer.cardId) },
|
||||
});
|
||||
if (!card || card.status !== 'published') {
|
||||
continue;
|
||||
}
|
||||
if (keyword) {
|
||||
const hay = `${card.name || ''} ${card.title || ''} ${
|
||||
card.company || ''
|
||||
}`.toLowerCase();
|
||||
if (!hay.includes(keyword)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
hydrated.push({
|
||||
ownerUserId: Number(query.userId),
|
||||
peerCardId: Number(card.id),
|
||||
source: 'event',
|
||||
peerName: card.name,
|
||||
peerTitle: card.title,
|
||||
peerCompany: card.company,
|
||||
peerAvatarUrl: card.avatarUrl,
|
||||
peerSlug: card.slug,
|
||||
});
|
||||
}
|
||||
const total = hydrated.length;
|
||||
const start = (page - 1) * size;
|
||||
return {
|
||||
list: hydrated.slice(start, start + size),
|
||||
pagination: { page, size, total },
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CardInfoEntity } from '../entity/info';
|
||||
import { CardPortalService } from './portal';
|
||||
import { TeamQuotaService } from '../../team/service/quota';
|
||||
import { getTenantId } from '../../../comm/context/tenant';
|
||||
|
||||
/**
|
||||
* 名片增删改载荷(Cool CRUD 传入对象、主键或主键列表)
|
||||
@@ -11,6 +13,7 @@ import { CardPortalService } from './portal';
|
||||
interface CardModifyRecord {
|
||||
id?: string | number;
|
||||
slug?: string;
|
||||
tenantId?: string | number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,12 +27,34 @@ export class CardInfoService extends BaseService {
|
||||
@Inject()
|
||||
cardPortalService: CardPortalService;
|
||||
|
||||
@Inject()
|
||||
teamQuotaService: TeamQuotaService;
|
||||
|
||||
@Init()
|
||||
async init() {
|
||||
await super.init();
|
||||
this.setEntity(this.cardInfoEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/修改/删除前前置拦截与配额校验
|
||||
*/
|
||||
async modifyBefore(data: any, type: 'delete' | 'update' | 'add'): Promise<void> {
|
||||
if (type === 'add' && data && typeof data === 'object') {
|
||||
const resolvedTenantId =
|
||||
data.tenantId ||
|
||||
(this.baseCtx ? getTenantId(this.baseCtx) : undefined) ||
|
||||
(this.baseCtx as any)?.admin?.tenantId;
|
||||
|
||||
if (resolvedTenantId) {
|
||||
data.tenantId = Number(resolvedTenantId);
|
||||
if (this.teamQuotaService) {
|
||||
await this.teamQuotaService.assertQuotaAvailable(data.tenantId, 'cards', 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增/修改/删除后清理门户缓存
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
import { Provide } from '@midwayjs/core';
|
||||
import { BaseService } from '@cool-midway/core';
|
||||
import { Inject, Provide } from '@midwayjs/core';
|
||||
import { BaseService, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CardExchangeEntity } from '../entity/exchange';
|
||||
import { CardInfoEntity } from '../entity/info';
|
||||
import { CrmLeadEntity } from '../../crm/entity/lead';
|
||||
import { CardContactService } from './contact';
|
||||
|
||||
export type MutualExchangeStatus = 'REQUESTED' | 'ACCEPTED' | 'REJECTED' | 'EXPIRED';
|
||||
export type MutualExchangeStatus =
|
||||
| 'REQUESTED'
|
||||
| 'ACCEPTED'
|
||||
| 'REJECTED'
|
||||
| 'EXPIRED';
|
||||
|
||||
export interface MutualExchangeInvitation {
|
||||
id: string;
|
||||
@@ -88,6 +98,19 @@ export function acceptMutualExchangeInvitation(
|
||||
};
|
||||
}
|
||||
|
||||
function toInvitation(row: CardExchangeEntity): MutualExchangeInvitation {
|
||||
return {
|
||||
id: String(row.id),
|
||||
senderCardId: Number(row.senderCardId),
|
||||
recipientCardId: Number(row.recipientCardId),
|
||||
status: row.status,
|
||||
exchangeCode: row.exchangeCode,
|
||||
notes: row.notes,
|
||||
createdAt: Date.now(),
|
||||
acceptedAt: row.acceptedAt ? Date.parse(row.acceptedAt) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 展会名片双向互换服务
|
||||
*/
|
||||
@@ -95,6 +118,18 @@ export function acceptMutualExchangeInvitation(
|
||||
export class CardMutualExchangeService extends BaseService {
|
||||
private readonly invitations = new Map<string, MutualExchangeInvitation>();
|
||||
|
||||
@InjectEntityModel(CardExchangeEntity)
|
||||
exchangeEntity: Repository<CardExchangeEntity>;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
@InjectEntityModel(CrmLeadEntity)
|
||||
crmLeadEntity: Repository<CrmLeadEntity>;
|
||||
|
||||
@Inject()
|
||||
cardContactService: CardContactService;
|
||||
|
||||
async initiateExchange(params: {
|
||||
senderCardId: number;
|
||||
recipientCardId: number;
|
||||
@@ -106,22 +141,119 @@ export class CardMutualExchangeService extends BaseService {
|
||||
params.notes
|
||||
);
|
||||
this.invitations.set(invite.id, invite);
|
||||
|
||||
if (this.exchangeEntity) {
|
||||
const sender = await this.cardInfoEntity?.findOne({
|
||||
where: { id: Number(params.senderCardId) },
|
||||
});
|
||||
const recipient = await this.cardInfoEntity?.findOne({
|
||||
where: { id: Number(params.recipientCardId) },
|
||||
});
|
||||
const row = new CardExchangeEntity();
|
||||
row.exchangeCode = invite.exchangeCode;
|
||||
row.senderCardId = Number(params.senderCardId);
|
||||
row.recipientCardId = Number(params.recipientCardId);
|
||||
row.senderUserId = sender?.userId ? Number(sender.userId) : null;
|
||||
row.recipientUserId = recipient?.userId ? Number(recipient.userId) : null;
|
||||
row.status = 'REQUESTED';
|
||||
row.notes = params.notes;
|
||||
const saved = await this.exchangeEntity.save(row);
|
||||
invite.id = String(saved.id);
|
||||
this.invitations.set(invite.id, invite);
|
||||
}
|
||||
|
||||
return invite;
|
||||
}
|
||||
|
||||
private async loadInvitation(
|
||||
invitationId: string
|
||||
): Promise<MutualExchangeInvitation | null> {
|
||||
const memory = this.invitations.get(invitationId);
|
||||
if (memory) {
|
||||
return memory;
|
||||
}
|
||||
if (!this.exchangeEntity) {
|
||||
return null;
|
||||
}
|
||||
const numericId = Number(invitationId);
|
||||
if (!Number.isFinite(numericId) || numericId <= 0) {
|
||||
return null;
|
||||
}
|
||||
const row = await this.exchangeEntity.findOne({
|
||||
where: { id: numericId },
|
||||
});
|
||||
return row ? toInvitation(row) : null;
|
||||
}
|
||||
|
||||
async confirmExchange(
|
||||
invitationId: string,
|
||||
actingCardId: number
|
||||
): Promise<{ status: MutualExchangeStatus; isDualSynced: boolean }> {
|
||||
const invite = this.invitations.get(invitationId);
|
||||
const invite = await this.loadInvitation(invitationId);
|
||||
if (!invite) {
|
||||
throw new Error('未找到该名片互换邀约');
|
||||
}
|
||||
|
||||
const res = acceptMutualExchangeInvitation(invite, actingCardId);
|
||||
this.invitations.set(invite.id, res.invitation);
|
||||
|
||||
if (this.exchangeEntity) {
|
||||
const row = await this.exchangeEntity.findOne({
|
||||
where: { id: Number(invite.id) },
|
||||
});
|
||||
if (row) {
|
||||
row.status = 'ACCEPTED';
|
||||
row.acceptedAt = new Date().toISOString();
|
||||
await this.exchangeEntity.save(row);
|
||||
}
|
||||
}
|
||||
|
||||
let isDualSynced = res.syncActions.length === 2;
|
||||
if (this.cardContactService && this.cardInfoEntity) {
|
||||
for (const action of res.syncActions) {
|
||||
const ownerCard = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(action.targetCardId) },
|
||||
});
|
||||
const peerCard = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(action.sourceCardId) },
|
||||
});
|
||||
if (!ownerCard?.userId || !peerCard) {
|
||||
isDualSynced = false;
|
||||
continue;
|
||||
}
|
||||
await this.cardContactService.syncExchangePair(ownerCard, peerCard);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: res.invitation.status,
|
||||
isDualSynced: res.syncActions.length === 2,
|
||||
isDualSynced,
|
||||
};
|
||||
}
|
||||
|
||||
async confirmByCode(
|
||||
exchangeCode: string,
|
||||
actingCardId: number
|
||||
): Promise<{ status: MutualExchangeStatus; isDualSynced: boolean }> {
|
||||
const code = String(exchangeCode || '').trim();
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
throw new CoolCommException('互换码无效', 400);
|
||||
}
|
||||
const memory = Array.from(this.invitations.values()).find(
|
||||
item => item.exchangeCode === code && item.status === 'REQUESTED'
|
||||
);
|
||||
if (memory) {
|
||||
return this.confirmExchange(memory.id, actingCardId);
|
||||
}
|
||||
if (!this.exchangeEntity) {
|
||||
throw new CoolCommException('未找到该名片互换邀约', 404);
|
||||
}
|
||||
const row = await this.exchangeEntity.findOne({
|
||||
where: { exchangeCode: code, status: 'REQUESTED' },
|
||||
});
|
||||
if (!row) {
|
||||
throw new CoolCommException('未找到该名片互换邀约', 404);
|
||||
}
|
||||
return this.confirmExchange(String(row.id), actingCardId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ export interface SyncExternalDTO {
|
||||
service: CrmLeadService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.name', 'a.company', 'a.email', 'a.phone'],
|
||||
fieldEq: ['a.status', 'a.source', 'a.cardId'],
|
||||
addOrderBy: { createTime: 'desc' },
|
||||
fieldEq: ['a.status', 'a.source', { column: 'a.card_id', requestParam: 'cardId' }],
|
||||
addOrderBy: { create_time: 'desc' as const },
|
||||
},
|
||||
serviceApis: [
|
||||
{ method: 'updateStatus', summary: '线索状态流转' },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Body, Get, Inject, Post, Provide, Query } from '@midwayjs/core';
|
||||
import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { CoolController, BaseController, CoolCommException } from '@cool-midway/core';
|
||||
import { CrmTrackEntity } from '../../entity/track';
|
||||
import { CrmRadarService } from '../../service/radar';
|
||||
|
||||
@@ -14,8 +14,12 @@ import { CrmRadarService } from '../../service/radar';
|
||||
entity: CrmTrackEntity,
|
||||
service: CrmRadarService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.country', 'a.city', 'a.visitorId', 'a.ip'],
|
||||
fieldEq: ['a.cardId', 'a.touchType', 'a.country'],
|
||||
keyWordLikeFields: ['a.country', 'a.city', 'a.visitor_id', 'a.ip'],
|
||||
fieldEq: [
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.touch_type', requestParam: 'touchType' },
|
||||
'a.country',
|
||||
],
|
||||
addOrderBy: { id: 'desc' },
|
||||
},
|
||||
serviceApis: [
|
||||
@@ -26,6 +30,9 @@ import { CrmRadarService } from '../../service/radar';
|
||||
],
|
||||
})
|
||||
export class AdminCrmRadarController extends BaseController {
|
||||
@Inject()
|
||||
ctx: { admin?: { userId?: number } };
|
||||
|
||||
@Inject()
|
||||
crmRadarService: CrmRadarService;
|
||||
|
||||
@@ -93,5 +100,18 @@ export class AdminCrmRadarController extends BaseController {
|
||||
});
|
||||
return this.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 高停留/高意向雷达红点
|
||||
* POST /admin/crm/radar/hotInbox
|
||||
*/
|
||||
@Post('/hotInbox', { summary: '高意向雷达收件箱' })
|
||||
async hotInbox() {
|
||||
const ownerUserId = this.ctx?.admin?.userId;
|
||||
if (!ownerUserId) {
|
||||
throw new CoolCommException('请先登录', 401);
|
||||
}
|
||||
return this.ok(await this.crmRadarService.hotInbox(Number(ownerUserId)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Init, Provide, Scope, ScopeEnum } from '@midwayjs/core';
|
||||
import { BaseService } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CrmTrackEntity } from '../entity/track';
|
||||
|
||||
/**
|
||||
* 高并发访客雷达异步削峰缓冲服务 (Telemetry Ingestion Buffer)
|
||||
*
|
||||
* 核心特性:
|
||||
* 1. 内存环形/缓冲队列接收,极速响应免登录上报请求 (< 5ms);
|
||||
* 2. 批量落盘削峰 (Bulk Batch Insert),降低主库写事务与连接池压力;
|
||||
* 3. 达到批次阈值或定时窗口自动 Flush,服务退出优雅刷盘无丢单。
|
||||
*/
|
||||
@Provide()
|
||||
@Scope(ScopeEnum.Singleton)
|
||||
export class CrmRadarBufferService extends BaseService {
|
||||
@InjectEntityModel(CrmTrackEntity)
|
||||
crmTrackEntity: Repository<CrmTrackEntity>;
|
||||
|
||||
/** 内存缓冲队列 */
|
||||
private queue: CrmTrackEntity[] = [];
|
||||
|
||||
/** 单批次批量写入阈值 (条) */
|
||||
private batchSize = 50;
|
||||
|
||||
/** 定时批量刷盘间隔 (毫秒) */
|
||||
private flushIntervalMs = 1000;
|
||||
|
||||
/** 队列最大安全容量保护 (防止内存泄漏) */
|
||||
private maxQueueCapacity = 10000;
|
||||
|
||||
/** 定时刷新定时器句柄 */
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
|
||||
/** 是否处于落盘锁定中,防并发重入 */
|
||||
private isFlushing = false;
|
||||
|
||||
@Init()
|
||||
async init(): Promise<void> {
|
||||
await super.init();
|
||||
this.startTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定时刷盘时钟
|
||||
*/
|
||||
private startTimer(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
if (this.flushIntervalMs > 0) {
|
||||
this.timer = setInterval(async () => {
|
||||
try {
|
||||
await this.flush();
|
||||
} catch {
|
||||
// 守护进程容错,防止未捕获异常中断定时器
|
||||
}
|
||||
}, this.flushIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置单批次写入阈值
|
||||
*/
|
||||
setBatchSize(size: number): void {
|
||||
this.batchSize = Math.max(1, Number(size) || 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置定时刷新时间间隔 (毫秒,0 表示禁用定时器)
|
||||
*/
|
||||
setFlushInterval(intervalMs: number): void {
|
||||
this.flushIntervalMs = Math.max(0, Number(intervalMs) || 0);
|
||||
this.startTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前队列积攒长度
|
||||
*/
|
||||
getQueueLength(): number {
|
||||
return this.queue.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将解析后的足迹实体非阻塞推入缓冲队列
|
||||
*/
|
||||
async enqueue(track: CrmTrackEntity | Partial<CrmTrackEntity>): Promise<boolean> {
|
||||
if (!track) return false;
|
||||
|
||||
// 容量上限防御:若超出安全上限,丢弃最早积攒数据保证可用性
|
||||
if (this.queue.length >= this.maxQueueCapacity) {
|
||||
this.queue.shift();
|
||||
}
|
||||
|
||||
this.queue.push(track as CrmTrackEntity);
|
||||
|
||||
// 达到批次阈值立即触发批量落盘
|
||||
if (this.queue.length >= this.batchSize) {
|
||||
// 异步触发 flush,不阻塞当前请求链路
|
||||
this.flush().catch(() => {});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量将队列中的数据一次性 Bulk Insert 写入数据库
|
||||
* @returns 成功落盘条数
|
||||
*/
|
||||
async flush(): Promise<number> {
|
||||
if (this.queue.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (this.isFlushing) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.isFlushing = true;
|
||||
try {
|
||||
// 截取当前队列中待入库的所有项
|
||||
const batch = this.queue.splice(0, this.queue.length);
|
||||
if (batch.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (this.crmTrackEntity) {
|
||||
if (typeof this.crmTrackEntity.createQueryBuilder === 'function') {
|
||||
const qb = this.crmTrackEntity.createQueryBuilder();
|
||||
if (qb && typeof qb.insert === 'function') {
|
||||
await qb.insert().into(CrmTrackEntity).values(batch).execute();
|
||||
return batch.length;
|
||||
}
|
||||
}
|
||||
// 兼容未提供 insert queryBuilder 的 Mock 环境或常规 save
|
||||
await this.crmTrackEntity.save(batch);
|
||||
}
|
||||
|
||||
return batch.length;
|
||||
} finally {
|
||||
this.isFlushing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 优雅停止服务:清除定时器并清空刷盘剩余缓冲
|
||||
*/
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
if (this.queue.length > 0) {
|
||||
this.flush().catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,21 +71,32 @@ export class CrmLeadPoolService extends BaseService {
|
||||
|
||||
const thresholdMs = inactivityDays * 24 * 60 * 60 * 1000;
|
||||
const now = Date.now();
|
||||
const thresholdDate = new Date(now - thresholdMs);
|
||||
|
||||
const allLeads = await this.crmLeadEntity.find();
|
||||
const toRecycle: CrmLeadEntity[] = [];
|
||||
let toRecycle: CrmLeadEntity[] = [];
|
||||
|
||||
for (const lead of allLeads) {
|
||||
// 仅扫描私海线索,且排除已赢单 (won) 和已归档 (archived)
|
||||
if (lead.isPool) continue;
|
||||
if (lead.status === 'won' || lead.status === 'archived') continue;
|
||||
|
||||
const followUp = lead.lastFollowUpTime || lead.updateTime || lead.createTime;
|
||||
if (!followUp) continue;
|
||||
|
||||
const diff = now - new Date(followUp).getTime();
|
||||
if (diff >= thresholdMs) {
|
||||
toRecycle.push(lead);
|
||||
if (this.crmLeadEntity && typeof this.crmLeadEntity.createQueryBuilder === 'function') {
|
||||
toRecycle = await this.crmLeadEntity
|
||||
.createQueryBuilder('lead')
|
||||
.where('lead.is_pool = :isPool', { isPool: false })
|
||||
.andWhere('lead.status NOT IN (:...excluded)', { excluded: ['won', 'archived'] })
|
||||
.andWhere(
|
||||
'(COALESCE(lead.last_follow_up_time, lead.update_time, lead.create_time) <= :thresholdDate)',
|
||||
{ thresholdDate }
|
||||
)
|
||||
.take(500)
|
||||
.getMany();
|
||||
} else {
|
||||
const allLeads = await this.crmLeadEntity.find({ where: { isPool: false } } as any);
|
||||
for (const lead of allLeads || []) {
|
||||
if (lead.isPool) continue;
|
||||
if (lead.status === 'won' || lead.status === 'archived') continue;
|
||||
const followUp = lead.lastFollowUpTime || lead.updateTime || lead.createTime;
|
||||
if (!followUp) continue;
|
||||
const diff = now - new Date(followUp).getTime();
|
||||
if (diff >= thresholdMs) {
|
||||
toRecycle.push(lead);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { BaseService, CoolCommException } from '@cool-midway/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CrmLeadEntity } from '../entity/lead';
|
||||
import { CardInfoEntity } from '../../card/entity/info';
|
||||
import {
|
||||
LeadSource,
|
||||
LeadStatus,
|
||||
@@ -29,6 +30,7 @@ export interface IntentScoreResult {
|
||||
*/
|
||||
export interface SubmitLeadDTO {
|
||||
cardId: number | string;
|
||||
tenantId?: number | string;
|
||||
visitorId?: string;
|
||||
name: string;
|
||||
company?: string;
|
||||
@@ -56,6 +58,9 @@ export class CrmLeadService extends BaseService {
|
||||
@InjectEntityModel(CrmLeadEntity)
|
||||
crmLeadEntity: Repository<CrmLeadEntity>;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
@Inject()
|
||||
leadScoreService: CrmLeadScoreService = new CrmLeadScoreService();
|
||||
|
||||
@@ -161,8 +166,36 @@ export class CrmLeadService extends BaseService {
|
||||
status = 'hot';
|
||||
}
|
||||
|
||||
// 自动追溯绑定名片归属租户与销售负责人
|
||||
let tenantId = data.tenantId ? Number(data.tenantId) : undefined;
|
||||
let assignedUserId: number | undefined = undefined;
|
||||
|
||||
if (this.cardInfoEntity && data.cardId) {
|
||||
try {
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(data.cardId) },
|
||||
});
|
||||
if (card) {
|
||||
if (!tenantId && card.tenantId) {
|
||||
tenantId = Number(card.tenantId);
|
||||
}
|
||||
if (card.userId) {
|
||||
assignedUserId = Number(card.userId);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 容错保护
|
||||
}
|
||||
}
|
||||
|
||||
const lead = new CrmLeadEntity();
|
||||
lead.cardId = Number(data.cardId);
|
||||
if (tenantId) {
|
||||
lead.tenantId = tenantId;
|
||||
}
|
||||
if (assignedUserId) {
|
||||
lead.userId = assignedUserId;
|
||||
}
|
||||
lead.visitorId = data.visitorId || '';
|
||||
lead.name = name;
|
||||
lead.company = data.company ? String(data.company).trim() : undefined;
|
||||
|
||||
@@ -4,6 +4,23 @@ import { RadarTrack, TouchType } from '../../../comm/types/omni';
|
||||
/** 雷达访客实时事件名,与管理端 / 客户端约定一致 */
|
||||
export const RADAR_VISITOR_EVENT = 'radar.visitor' as const;
|
||||
|
||||
/** 高停留阈值:3 分钟 */
|
||||
export const HOT_RADAR_STAY_MS = 180000;
|
||||
|
||||
/** 高意向浏览块数量 */
|
||||
export const HOT_RADAR_BLOCK_COUNT = 3;
|
||||
|
||||
export function isHotRadarPush(track: {
|
||||
stayDurationMs?: number;
|
||||
viewedBlocks?: string[] | null;
|
||||
}): boolean {
|
||||
const stay = Number(track?.stayDurationMs) || 0;
|
||||
const blocks = Array.isArray(track?.viewedBlocks)
|
||||
? track.viewedBlocks.length
|
||||
: 0;
|
||||
return stay >= HOT_RADAR_STAY_MS || blocks >= HOT_RADAR_BLOCK_COUNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内存渠道投递载荷。
|
||||
* 仅描述访客足迹摘要,不表示已推送到真实设备。
|
||||
|
||||
@@ -4,6 +4,10 @@ import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CrmTrackEntity } from '../entity/track';
|
||||
import { CrmLeadEntity } from '../entity/lead';
|
||||
import { CardInfoEntity } from '../../card/entity/info';
|
||||
import { CrmRadarBufferService } from './buffer';
|
||||
import { CrmRadarPushService, isHotRadarPush } from './push';
|
||||
import { RadarHotInbox, RadarTrack } from '../../../comm/types/omni';
|
||||
import {
|
||||
LeadStatus,
|
||||
TouchType,
|
||||
@@ -212,6 +216,15 @@ export class CrmRadarService extends BaseService {
|
||||
@InjectEntityModel(CrmLeadEntity)
|
||||
crmLeadEntity: Repository<CrmLeadEntity>;
|
||||
|
||||
@InjectEntityModel(CardInfoEntity)
|
||||
cardInfoEntity: Repository<CardInfoEntity>;
|
||||
|
||||
@Inject()
|
||||
crmRadarBufferService: CrmRadarBufferService;
|
||||
|
||||
@Inject()
|
||||
crmRadarPushService: CrmRadarPushService;
|
||||
|
||||
@Inject()
|
||||
ctx: any;
|
||||
|
||||
@@ -268,7 +281,10 @@ export class CrmRadarService extends BaseService {
|
||||
/**
|
||||
* 记录访客轨迹并解析地理位置
|
||||
*/
|
||||
async recordTrack(data: RecordTrackDTO): Promise<CrmTrackEntity> {
|
||||
async recordTrack(
|
||||
data: RecordTrackDTO,
|
||||
options?: { asyncQueue?: boolean }
|
||||
): Promise<CrmTrackEntity> {
|
||||
if (!data || !data.cardId) {
|
||||
throw new CoolCommException('缺少名片标识 cardId', 400);
|
||||
}
|
||||
@@ -333,11 +349,64 @@ export class CrmRadarService extends BaseService {
|
||||
track.stayDurationMs = stayDurationMs;
|
||||
track.scrollDepth = scrollDepth;
|
||||
track.viewedBlocks = viewedBlocks;
|
||||
if (data.tenantId) {
|
||||
track.tenantId = Number(data.tenantId);
|
||||
let tenantId = data.tenantId ? Number(data.tenantId) : undefined;
|
||||
if (!tenantId && this.cardInfoEntity && data.cardId) {
|
||||
try {
|
||||
const card = await this.cardInfoEntity.findOne({
|
||||
where: { id: Number(data.cardId) },
|
||||
});
|
||||
if (card?.tenantId) {
|
||||
tenantId = Number(card.tenantId);
|
||||
}
|
||||
} catch {
|
||||
// 容错保护
|
||||
}
|
||||
}
|
||||
|
||||
return await this.crmTrackEntity.save(track);
|
||||
if (tenantId) {
|
||||
track.tenantId = tenantId;
|
||||
}
|
||||
|
||||
if (options?.asyncQueue && this.crmRadarBufferService) {
|
||||
await this.crmRadarBufferService.enqueue(track);
|
||||
return track;
|
||||
}
|
||||
|
||||
const saved = await this.crmTrackEntity.save(track);
|
||||
this.publishHotRadar(saved);
|
||||
return saved;
|
||||
}
|
||||
|
||||
publishHotRadar(track: CrmTrackEntity): void {
|
||||
if (!this.crmRadarPushService || !isHotRadarPush(track)) {
|
||||
return;
|
||||
}
|
||||
this.crmRadarPushService.publish(track as unknown as RadarTrack);
|
||||
}
|
||||
|
||||
async hotInbox(ownerUserId: number): Promise<RadarHotInbox> {
|
||||
if (!ownerUserId) {
|
||||
return { unread: 0, list: [] };
|
||||
}
|
||||
const cards = this.cardInfoEntity
|
||||
? await this.cardInfoEntity.find({
|
||||
where: { userId: Number(ownerUserId) },
|
||||
})
|
||||
: [];
|
||||
const cardIds = new Set(cards.map(card => Number(card.id)));
|
||||
if (cardIds.size === 0) {
|
||||
return { unread: 0, list: [] };
|
||||
}
|
||||
const tracks = await this.crmTrackEntity.find({
|
||||
order: { id: 'DESC' },
|
||||
});
|
||||
const hot = tracks.filter(
|
||||
item => cardIds.has(Number(item.cardId)) && isHotRadarPush(item)
|
||||
);
|
||||
return {
|
||||
unread: hot.length,
|
||||
list: hot.slice(0, 3) as unknown as RadarTrack[],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -384,6 +453,46 @@ export class CrmRadarService extends BaseService {
|
||||
* 按国家聚合访客数、占比与平均停留时长
|
||||
*/
|
||||
async getCountryDistribution(cardId?: number): Promise<CountryDistributionItem[]> {
|
||||
const qb =
|
||||
this.crmTrackEntity && typeof this.crmTrackEntity.createQueryBuilder === 'function'
|
||||
? this.crmTrackEntity.createQueryBuilder('track')
|
||||
: null;
|
||||
|
||||
if (qb) {
|
||||
qb.select("COALESCE(NULLIF(TRIM(track.country), ''), 'Unknown')", 'country')
|
||||
.addSelect('COUNT(*)', 'visitorCount')
|
||||
.addSelect('ROUND(AVG(COALESCE(track.stay_duration_ms, 0)))', 'avgStayDurationMs')
|
||||
.groupBy("COALESCE(NULLIF(TRIM(track.country), ''), 'Unknown')");
|
||||
|
||||
if (cardId !== undefined && cardId !== null && !isNaN(Number(cardId))) {
|
||||
qb.where('track.card_id = :cardId', { cardId: Number(cardId) });
|
||||
}
|
||||
|
||||
const raw = await qb.getRawMany();
|
||||
if (!raw || raw.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let totalVisitors = 0;
|
||||
for (const item of raw) {
|
||||
totalVisitors += Number(item.visitorCount) || 0;
|
||||
}
|
||||
|
||||
const result: CountryDistributionItem[] = raw.map(item => {
|
||||
const count = Number(item.visitorCount) || 0;
|
||||
const percentage = totalVisitors > 0 ? Number(((count / totalVisitors) * 100).toFixed(1)) : 0;
|
||||
return {
|
||||
country: String(item.country || 'Unknown').trim(),
|
||||
visitorCount: count,
|
||||
percentage,
|
||||
avgStayDurationMs: Math.round(Number(item.avgStayDurationMs) || 0),
|
||||
};
|
||||
});
|
||||
|
||||
result.sort((a, b) => b.visitorCount - a.visitorCount);
|
||||
return result;
|
||||
}
|
||||
|
||||
const where: any = {};
|
||||
if (cardId !== undefined && cardId !== null && !isNaN(Number(cardId))) {
|
||||
where.cardId = Number(cardId);
|
||||
|
||||
@@ -18,9 +18,14 @@ export const adminNfcDeviceCurdOption = {
|
||||
entity: NfcDeviceEntity,
|
||||
service: NfcDeviceService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.uid', 'a.batchNo'],
|
||||
fieldEq: ['a.status', 'a.material', 'a.cardId', 'a.sceneMode'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
keyWordLikeFields: ['a.uid', 'a.batch_no'],
|
||||
fieldEq: [
|
||||
'a.status',
|
||||
'a.material',
|
||||
{ column: 'a.card_id', requestParam: 'cardId' },
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -12,7 +12,13 @@ export const adminNfcRuleCurdOption = {
|
||||
entity: NfcRuleEntity,
|
||||
service: NfcRuleService,
|
||||
pageQueryOp: {
|
||||
fieldEq: ['a.deviceId', 'a.enabled', 'a.sceneMode', 'a.countryCode'],
|
||||
fieldEq: [
|
||||
{ column: 'a.device_id', requestParam: 'deviceId' },
|
||||
'a.enabled',
|
||||
{ column: 'a.scene_mode', requestParam: 'sceneMode' },
|
||||
{ column: 'a.country_code', requestParam: 'countryCode' },
|
||||
],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
serviceApis: [
|
||||
{ method: 'resolveScene', summary: '解析当前触卡场景路由' },
|
||||
|
||||
@@ -27,8 +27,8 @@ import { PluginService } from '../../service/info';
|
||||
'a.description',
|
||||
'a.pluginJson',
|
||||
'a.config',
|
||||
'a.createTime',
|
||||
'a.updateTime',
|
||||
'a.create_time as createTime',
|
||||
'a.update_time as updateTime',
|
||||
],
|
||||
addOrderBy: {
|
||||
id: 'DESC',
|
||||
|
||||
@@ -12,8 +12,8 @@ export const adminTeamBrandCurdOption = {
|
||||
entity: TeamBrandEntity,
|
||||
service: TeamBrandService,
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.companyName'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
keyWordLikeFields: ['a.company_name'],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -21,9 +21,9 @@ export const adminTeamDomainCurdOption = {
|
||||
{ method: 'bind', summary: '绑定独立域名' },
|
||||
],
|
||||
pageQueryOp: {
|
||||
keyWordLikeFields: ['a.customDomain'],
|
||||
fieldEq: ['a.sslStatus'],
|
||||
addOrderBy: { updateTime: 'desc' as const },
|
||||
keyWordLikeFields: ['a.custom_domain'],
|
||||
fieldEq: [{ column: 'a.ssl_status', requestParam: 'sslStatus' }],
|
||||
addOrderBy: { update_time: 'desc' as const },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { isSuperAdminContext, assertSuperAdmin } from '../../src/comm/guard/super-admin';
|
||||
import { CoolCommException } from '@cool-midway/core';
|
||||
|
||||
describe('后端权限隔离 - 平台超级管理员专属守卫 (Super Admin Guard TDD)', () => {
|
||||
describe('1. isSuperAdminContext 身份研判', () => {
|
||||
it('username 为 admin 的系统初始超管应判定为 true', () => {
|
||||
const ctx = { admin: { username: 'admin', userId: 1 } };
|
||||
expect(isSuperAdminContext(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('携带 isSuper: true 标识的平台超级管理员应判定为 true', () => {
|
||||
const ctx = { admin: { username: 'root_operator', isSuper: true, userId: 2 } };
|
||||
expect(isSuperAdminContext(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('角色包含 admin 标签的管理员应判定为 true', () => {
|
||||
const ctx = { admin: { username: 'ops_manager', roleLabels: ['admin', 'ops'], userId: 3 } };
|
||||
expect(isSuperAdminContext(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('普通企业租户账号应判定为 false', () => {
|
||||
const ctx = { admin: { username: 'vanguard_owner', tenantId: 1, roleLabels: ['tenant_owner'], userId: 10 } };
|
||||
expect(isSuperAdminContext(ctx)).toBe(false);
|
||||
});
|
||||
|
||||
it('租户下的一线业务员应判定为 false', () => {
|
||||
const ctx = { admin: { username: 'sales_tom', tenantId: 1, roleLabels: ['sales_rep'], userId: 25 } };
|
||||
expect(isSuperAdminContext(ctx)).toBe(false);
|
||||
});
|
||||
|
||||
it('缺失 admin 上下文或未登录状态应判定为 false', () => {
|
||||
expect(isSuperAdminContext({})).toBe(false);
|
||||
expect(isSuperAdminContext({ admin: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. assertSuperAdmin 越权拦截断言', () => {
|
||||
it('超级管理员访问时不应抛出异常', () => {
|
||||
const ctx = { admin: { username: 'admin' } };
|
||||
expect(() => assertSuperAdmin(ctx)).not.toThrow();
|
||||
});
|
||||
|
||||
it('非超级管理员访问时必须抛出 403 CoolCommException 阻止越权', () => {
|
||||
const ctx = { admin: { username: 'tenant_user', tenantId: 2 } };
|
||||
expect(() => assertSuperAdmin(ctx)).toThrow(CoolCommException);
|
||||
try {
|
||||
assertSuperAdmin(ctx);
|
||||
} catch (err: any) {
|
||||
expect(err.status || err.code).toBe(403);
|
||||
expect(err.message).toContain('权限不足');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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' },
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('Point 56: 移动端 App / H5 出海名片 Universal Link 深度链接
|
||||
);
|
||||
const targetRoute = router.buildAppPageRoute(parsed);
|
||||
|
||||
expect(targetRoute).toContain('/pages/card/portal');
|
||||
expect(targetRoute).toContain('/pages/portal/index');
|
||||
expect(targetRoute).toContain('slug=alex');
|
||||
expect(targetRoute).toContain('scene=exhibition');
|
||||
expect(targetRoute).toContain('lang=ar');
|
||||
@@ -60,7 +60,7 @@ describe('Point 56: 移动端 App / H5 出海名片 Universal Link 深度链接
|
||||
|
||||
it('无效解析对象应安全回退至名片主页', () => {
|
||||
const fallback = router.buildAppPageRoute({ isValid: false });
|
||||
expect(fallback).toBe('/pages/owner/home');
|
||||
expect(fallback).toBe('/pages/owner/hall/index');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,7 +25,9 @@ type UniRequestOption = {
|
||||
};
|
||||
|
||||
type LoginState = {
|
||||
tab: 'phone' | 'email';
|
||||
tab: 'password' | 'phone' | 'email';
|
||||
username: string;
|
||||
password: string;
|
||||
countryCode: string;
|
||||
phone: string;
|
||||
smsCode: string;
|
||||
@@ -38,12 +40,14 @@ type LoginState = {
|
||||
type UseLoginModule = {
|
||||
createLoginState: () => LoginState;
|
||||
completeLogin: (token: string, tenantId?: string) => boolean;
|
||||
submitPasswordLogin: (state: LoginState) => Promise<boolean>;
|
||||
submitPhoneLogin: (state: LoginState) => boolean;
|
||||
sendMagicLink: (state: LoginState) => boolean;
|
||||
sendSmsCode: (state: LoginState) => boolean;
|
||||
tapSocialLogin: (provider: 'google' | 'apple') => void;
|
||||
resolveLoginText: (key: string) => string;
|
||||
tickCountdown: (state: LoginState) => void;
|
||||
fillTestAccount: (state: LoginState) => void;
|
||||
};
|
||||
|
||||
describe('OmniCard AI 用户端统一登录业务逻辑测试 (useLogin.uts)', () => {
|
||||
@@ -220,4 +224,118 @@ describe('OmniCard AI 用户端统一登录业务逻辑测试 (useLogin.uts)', (
|
||||
expect(state.countdown).toBe(59);
|
||||
});
|
||||
});
|
||||
|
||||
describe('6. 账号密码真实登录与前后端对齐', () => {
|
||||
it('6.1 空账号或空密码不提交', async () => {
|
||||
const { createLoginState, submitPasswordLogin } = loadUseLogin();
|
||||
|
||||
const state = createLoginState();
|
||||
state.username = '';
|
||||
state.password = '';
|
||||
|
||||
const ok = await submitPasswordLogin(state);
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(storageMap.has('token')).toBe(false);
|
||||
expect(requestCallCount).toBe(0);
|
||||
expect(toastCalls.length).toBeGreaterThan(0);
|
||||
expect(toastCalls[0].title).toContain('账号');
|
||||
|
||||
// 仅有账号没有密码
|
||||
state.username = 'admin';
|
||||
state.password = '';
|
||||
const ok2 = await submitPasswordLogin(state);
|
||||
expect(ok2).toBe(false);
|
||||
expect(storageMap.has('token')).toBe(false);
|
||||
expect(toastCalls[toastCalls.length - 1].title).toContain('密码');
|
||||
});
|
||||
|
||||
it('6.2 账号密码登录成功:对齐 /admin/base/open/login 接口契约,写入 token 并跳转', async () => {
|
||||
const { createLoginState, submitPasswordLogin } = loadUseLogin();
|
||||
|
||||
const state = createLoginState();
|
||||
state.username = 'admin';
|
||||
state.password = '123456';
|
||||
|
||||
// 模拟 uni.request 响应 Cool-Admin 成功契约
|
||||
(global as { uni?: Record<string, unknown> }).uni!.request = (options: UniRequestOption) => {
|
||||
requestCallCount += 1;
|
||||
lastRequestOptions = options;
|
||||
setTimeout(() => {
|
||||
options.success?.({
|
||||
statusCode: 200,
|
||||
data: {
|
||||
code: 1000,
|
||||
message: 'success',
|
||||
data: {
|
||||
token: 'mock_admin_jwt_token_2026',
|
||||
expire: 7200,
|
||||
refreshToken: 'mock_refresh_token',
|
||||
},
|
||||
},
|
||||
header: {},
|
||||
});
|
||||
options.complete?.();
|
||||
}, 0);
|
||||
return { abort: jest.fn() };
|
||||
};
|
||||
|
||||
const ok = await submitPasswordLogin(state);
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(storageMap.get('token')).toBe('mock_admin_jwt_token_2026');
|
||||
expect(switchTabCount).toBe(1);
|
||||
expect(lastRequestOptions?.url).toContain('/admin/base/open/login');
|
||||
expect(lastRequestOptions?.data).toEqual({
|
||||
username: 'admin',
|
||||
password: '123456',
|
||||
});
|
||||
});
|
||||
|
||||
it('6.3 账号密码登录失败:后端返回 1001 时正确提示错误并置错误信息', async () => {
|
||||
const { createLoginState, submitPasswordLogin } = loadUseLogin();
|
||||
|
||||
const state = createLoginState();
|
||||
state.username = 'admin';
|
||||
state.password = 'wrong_password';
|
||||
|
||||
(global as { uni?: Record<string, unknown> }).uni!.request = (options: UniRequestOption) => {
|
||||
requestCallCount += 1;
|
||||
lastRequestOptions = options;
|
||||
setTimeout(() => {
|
||||
options.success?.({
|
||||
statusCode: 200,
|
||||
data: {
|
||||
code: 1001,
|
||||
message: '账户或密码不正确~',
|
||||
},
|
||||
header: {},
|
||||
});
|
||||
options.complete?.();
|
||||
}, 0);
|
||||
return { abort: jest.fn() };
|
||||
};
|
||||
|
||||
const ok = await submitPasswordLogin(state);
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(storageMap.has('token')).toBe(false);
|
||||
expect(switchTabCount).toBe(0);
|
||||
expect(state.errorMessage).toBe('账户或密码不正确~');
|
||||
expect(toastCalls[toastCalls.length - 1].title).toBe('账户或密码不正确~');
|
||||
});
|
||||
|
||||
it('6.4 一键填入测试账号便于快速验证', () => {
|
||||
const { createLoginState, fillTestAccount } = loadUseLogin();
|
||||
|
||||
const state = createLoginState();
|
||||
expect(state.username).toBe('');
|
||||
expect(state.password).toBe('');
|
||||
|
||||
fillTestAccount(state);
|
||||
|
||||
expect(state.username).toBe('admin');
|
||||
expect(state.password).toBe('123456');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* OmniCard AI - 名片大厅人脉驱动层测试
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
const HALL_PAGE = path.resolve(
|
||||
__dirname,
|
||||
'../../../mpuniapp/pages/owner/hall/index.uvue'
|
||||
);
|
||||
const HALL_UTS = path.resolve(
|
||||
__dirname,
|
||||
'../../../mpuniapp/pages/owner/hall/useHall.uts'
|
||||
);
|
||||
|
||||
describe('OmniCard AI 名片大厅 (useHall.uts)', () => {
|
||||
function loadHall() {
|
||||
jest.resetModules();
|
||||
const storage = new Map<string, string>();
|
||||
(global as { uni?: Record<string, unknown> }).uni = {
|
||||
getLocale: () => 'zh-CN',
|
||||
navigateTo: jest.fn(),
|
||||
setStorageSync: (key: string, val: string) => storage.set(key, val),
|
||||
getStorageSync: (key: string) => storage.get(key) || '',
|
||||
removeStorageSync: (key: string) => storage.delete(key),
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('../../../mpuniapp/pages/owner/hall/useHall.uts');
|
||||
}
|
||||
|
||||
it('toHallItem 映射对方名片摘要', () => {
|
||||
const { toHallItem } = loadHall();
|
||||
const item = toHallItem({
|
||||
id: 9,
|
||||
ownerUserId: 11,
|
||||
peerCardId: 202,
|
||||
source: 'exchange',
|
||||
peerName: 'Tariq Mansour',
|
||||
peerCompany: 'Dubai Energy',
|
||||
peerSlug: 'tariq',
|
||||
});
|
||||
expect(item.peerCardId).toBe(202);
|
||||
expect(item.peerName).toBe('Tariq Mansour');
|
||||
expect(item.peerSlug).toBe('tariq');
|
||||
});
|
||||
|
||||
it('未登录带走名片会写入待收藏,登录后可消费', () => {
|
||||
const { setPendingCollectCard, consumePendingCollectCard } = loadHall();
|
||||
setPendingCollectCard(202);
|
||||
expect(consumePendingCollectCard()).toBe('202');
|
||||
expect(consumePendingCollectCard()).toBe('');
|
||||
});
|
||||
|
||||
it('buildHallPortalUrl 优先使用 slug', () => {
|
||||
const { buildHallPortalUrl } = loadHall();
|
||||
expect(
|
||||
buildHallPortalUrl({
|
||||
peerCardId: 202,
|
||||
peerName: 'Tariq',
|
||||
peerSlug: 'tariq',
|
||||
})
|
||||
).toBe('/pages/portal/index?slug=tariq');
|
||||
expect(
|
||||
buildHallPortalUrl({
|
||||
peerCardId: 202,
|
||||
peerName: 'Tariq',
|
||||
})
|
||||
).toBe('/pages/portal/index?id=202');
|
||||
});
|
||||
|
||||
it('团队分段走 teamWall 接口', async () => {
|
||||
const { createHallState, applyHallTab, refreshHall } = loadHall();
|
||||
const state = createHallState();
|
||||
applyHallTab(state, 'team');
|
||||
let usedTeam = false;
|
||||
await refreshHall(state, {
|
||||
fetchHallContactPage: async () => ({
|
||||
list: [],
|
||||
pagination: { page: 1, size: 20, total: 0 },
|
||||
}),
|
||||
fetchTeamWallPage: async () => {
|
||||
usedTeam = true;
|
||||
return {
|
||||
list: [
|
||||
{
|
||||
ownerUserId: 11,
|
||||
peerCardId: 103,
|
||||
source: 'collect',
|
||||
peerName: 'Chen Wei',
|
||||
},
|
||||
],
|
||||
pagination: { page: 1, size: 20, total: 1 },
|
||||
};
|
||||
},
|
||||
});
|
||||
expect(usedTeam).toBe(true);
|
||||
expect(state.tab).toBe('team');
|
||||
expect(state.list[0].peerName).toBe('Chen Wei');
|
||||
});
|
||||
|
||||
it('refreshHall 只展示当前用户人脉', async () => {
|
||||
const { createHallState, refreshHall } = loadHall();
|
||||
const state = createHallState();
|
||||
await refreshHall(state, {
|
||||
fetchHallContactPage: async () => ({
|
||||
list: [
|
||||
{
|
||||
id: 1,
|
||||
ownerUserId: 11,
|
||||
peerCardId: 202,
|
||||
source: 'exchange',
|
||||
peerName: 'Tariq Mansour',
|
||||
},
|
||||
],
|
||||
pagination: { page: 1, size: 20, total: 1 },
|
||||
}),
|
||||
});
|
||||
expect(state.list).toHaveLength(1);
|
||||
expect(state.empty).toBe(false);
|
||||
expect(state.list[0].peerName).toBe('Tariq Mansour');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OmniCard AI 名片大厅页契约 (index.uvue)', () => {
|
||||
it('页面含 list-view 与互换码输入,并避让 TabBar', () => {
|
||||
const pageSource = fs.readFileSync(HALL_PAGE, 'utf8');
|
||||
const logicSource = fs.readFileSync(HALL_UTS, 'utf8');
|
||||
expect(pageSource.includes('<list-view')).toBe(true);
|
||||
expect(pageSource.includes('exchangeCode')).toBe(true);
|
||||
expect(pageSource.includes('tabTeam') || logicSource.includes('tabTeam')).toBe(true);
|
||||
expect(pageSource.includes('var(--window-bottom')).toBe(true);
|
||||
expect(logicSource.includes('/admin/card/contact/hallPage') || logicSource.includes('fetchHallContactPage')).toBe(true);
|
||||
expect(pageSource.includes('#0B5CFF')).toBe(true);
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户