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 打包无错误
这个提交包含在:
wikiboss
2026-09-21 11:14:10 +08:00
父节点 e73c15bd22
当前提交 6c3d5d323a
共有 637 个文件被更改,包括 4731 次插入 和 56919 次删除

查看文件

@@ -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);
}
}