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 },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
在新工单中引用
屏蔽一个用户