补齐平台订阅、外部登录、CRM 同步与用户端页面;Nginx 转发用户端接口,登录页使用 Google 与 Apple 标志。 Co-authored-by: Cursor <cursoragent@cursor.com>
515 行
17 KiB
TypeScript
515 行
17 KiB
TypeScript
import * as crypto from 'crypto';
|
||
import axios from 'axios';
|
||
import { CrmSyncService } from '../../../src/modules/crm/service/sync';
|
||
import { AdminCrmLeadController } from '../../../src/modules/crm/controller/admin/lead';
|
||
import { CrmLeadEntity } from '../../../src/modules/crm/entity/lead';
|
||
import { CoolCommException } from '@cool-midway/core';
|
||
|
||
describe('Point 11: 国际主流 CRM (HubSpot / Salesforce / Webhook) 对接服务', () => {
|
||
let syncService: CrmSyncService;
|
||
let mockLead: CrmLeadEntity;
|
||
|
||
beforeEach(() => {
|
||
syncService = new CrmSyncService();
|
||
mockLead = new CrmLeadEntity();
|
||
mockLead.id = 101;
|
||
mockLead.name = 'John Doe';
|
||
mockLead.company = 'Acme Global Corp';
|
||
mockLead.email = 'john.doe@acme.com';
|
||
mockLead.phone = '+1-555-0199';
|
||
mockLead.status = 'new';
|
||
mockLead.intentScore = 88;
|
||
mockLead.source = 'nfc';
|
||
jest.clearAllMocks();
|
||
});
|
||
|
||
afterEach(() => {
|
||
jest.restoreAllMocks();
|
||
});
|
||
|
||
// ==========================================
|
||
// 1. HubSpot Contacts v3 转换测试
|
||
// ==========================================
|
||
describe('1. HubSpot Contacts v3 格式转换 (formatToHubSpot)', () => {
|
||
it('应正确转换完整线索字段,并固定 lifecyclestage 为 lead', () => {
|
||
const hubspotData = syncService.formatToHubSpot(mockLead);
|
||
|
||
expect(hubspotData).toEqual({
|
||
properties: {
|
||
email: 'john.doe@acme.com',
|
||
firstname: 'John',
|
||
lastname: 'Doe',
|
||
phone: '+1-555-0199',
|
||
company: 'Acme Global Corp',
|
||
lifecyclestage: 'lead',
|
||
},
|
||
});
|
||
});
|
||
|
||
it('单名应正确填入 firstname,lastname 为空字符串', () => {
|
||
mockLead.name = 'Madonna';
|
||
const hubspotData = syncService.formatToHubSpot(mockLead);
|
||
|
||
expect(hubspotData.properties.firstname).toBe('Madonna');
|
||
expect(hubspotData.properties.lastname).toBe('');
|
||
});
|
||
|
||
it('包含中间名/多个词的姓名应正确拆分首词为 firstname,其余为 lastname', () => {
|
||
mockLead.name = 'John Fitzgerald Kennedy';
|
||
const hubspotData = syncService.formatToHubSpot(mockLead);
|
||
|
||
expect(hubspotData.properties.firstname).toBe('John');
|
||
expect(hubspotData.properties.lastname).toBe('Fitzgerald Kennedy');
|
||
});
|
||
|
||
it('缺少可选字段时应优雅兜底为空字符串,不崩溃', () => {
|
||
const partialLead: Partial<CrmLeadEntity> = {
|
||
name: '',
|
||
};
|
||
const hubspotData = syncService.formatToHubSpot(partialLead);
|
||
|
||
expect(hubspotData.properties.email).toBe('');
|
||
expect(hubspotData.properties.firstname).toBe('');
|
||
expect(hubspotData.properties.lastname).toBe('');
|
||
expect(hubspotData.properties.phone).toBe('');
|
||
expect(hubspotData.properties.company).toBe('');
|
||
expect(hubspotData.properties.lifecyclestage).toBe('lead');
|
||
});
|
||
});
|
||
|
||
// ==========================================
|
||
// 2. Salesforce Lead sObject 格式转换测试
|
||
// ==========================================
|
||
describe('2. Salesforce Lead sObject 格式转换 (formatToSalesforce)', () => {
|
||
it('应正确转换标准字段,且状态固定为 Open - Not Contacted', () => {
|
||
const sfData = syncService.formatToSalesforce(mockLead);
|
||
|
||
expect(sfData).toEqual({
|
||
FirstName: 'John',
|
||
LastName: 'Doe',
|
||
Email: 'john.doe@acme.com',
|
||
Company: 'Acme Global Corp',
|
||
Phone: '+1-555-0199',
|
||
Status: 'Open - Not Contacted',
|
||
});
|
||
});
|
||
|
||
it('单名时应确保必填字段 LastName 有值,FirstName 为空', () => {
|
||
mockLead.name = 'Zendaya';
|
||
const sfData = syncService.formatToSalesforce(mockLead);
|
||
|
||
expect(sfData.FirstName).toBe('');
|
||
expect(sfData.LastName).toBe('Zendaya');
|
||
});
|
||
|
||
it('姓名为空时应兜底 LastName 为 Unknown,FirstName 为空', () => {
|
||
const emptyLead: Partial<CrmLeadEntity> = {
|
||
name: '',
|
||
company: '',
|
||
};
|
||
const sfData = syncService.formatToSalesforce(emptyLead);
|
||
|
||
expect(sfData.FirstName).toBe('');
|
||
expect(sfData.LastName).toBe('Unknown');
|
||
expect(sfData.Company).toBe('Unknown');
|
||
expect(sfData.Status).toBe('Open - Not Contacted');
|
||
});
|
||
});
|
||
|
||
// ==========================================
|
||
// 3. HMAC-SHA256 签名计算与验证
|
||
// ==========================================
|
||
describe('3. HMAC-SHA256 签名计算 (generateSignature)', () => {
|
||
it('应基于 secret 对 payload 计算出正确的 64 位十六进制 HMAC-SHA256 签名', () => {
|
||
const secret = 'omnicard_super_secret_key_2026';
|
||
const payload = {
|
||
event: 'crm.lead.sync',
|
||
data: { id: 101, name: 'John Doe' },
|
||
};
|
||
|
||
const signature = syncService.generateSignature(payload, secret);
|
||
const expected = crypto
|
||
.createHmac('sha256', secret)
|
||
.update(JSON.stringify(payload))
|
||
.digest('hex');
|
||
|
||
expect(signature).toHaveLength(64);
|
||
expect(signature).toBe(expected);
|
||
});
|
||
|
||
it('相同 payload 与 secret 计算出的签名必须严格幂等一致', () => {
|
||
const secret = 'test_secret';
|
||
const payload = { test: 123 };
|
||
|
||
const sig1 = syncService.generateSignature(payload, secret);
|
||
const sig2 = syncService.generateSignature(payload, secret);
|
||
|
||
expect(sig1).toBe(sig2);
|
||
});
|
||
});
|
||
|
||
// ==========================================
|
||
// 4. Webhook 发送与模拟退避重试 (sendWebhook)
|
||
// ==========================================
|
||
describe('4. Webhook 发送与模拟退避重试 (sendWebhook)', () => {
|
||
it('首次请求 200 成功时,应附加 X-OmniCard-Signature 请求头并返回 attempts: 1', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({
|
||
status: 200,
|
||
data: { received: true },
|
||
});
|
||
|
||
const url = 'https://api.partner.com/webhook';
|
||
const secret = 'wh_secret_888';
|
||
const result = await syncService.sendWebhook(url, secret, mockLead, {
|
||
delayMs: 1,
|
||
});
|
||
|
||
expect(result.success).toBe(true);
|
||
expect(result.attempts).toBe(1);
|
||
expect(postSpy).toHaveBeenCalledTimes(1);
|
||
|
||
const [calledUrl, calledPayload, config] = postSpy.mock.calls[0];
|
||
expect(calledUrl).toBe(url);
|
||
expect(calledPayload).toHaveProperty('event', 'crm.lead.sync');
|
||
expect(calledPayload).toHaveProperty('data');
|
||
expect(config?.headers?.['Content-Type']).toBe('application/json');
|
||
expect(config?.headers?.['X-OmniCard-Signature']).toBeDefined();
|
||
|
||
const verifiedSig = syncService.generateSignature(calledPayload, secret);
|
||
expect(config?.headers?.['X-OmniCard-Signature']).toBe(verifiedSig);
|
||
});
|
||
|
||
it('若前两次网络失败第三次成功,应自动重试并在第 3 次成功返回', async () => {
|
||
const postSpy = jest
|
||
.spyOn(axios, 'post')
|
||
.mockRejectedValueOnce(new Error('Network Timeout'))
|
||
.mockRejectedValueOnce(new Error('502 Bad Gateway'))
|
||
.mockResolvedValueOnce({ status: 200, data: { ok: true } });
|
||
|
||
const result = await syncService.sendWebhook(
|
||
'https://api.partner.com/webhook',
|
||
'wh_secret',
|
||
mockLead,
|
||
{ delayMs: 1 }
|
||
);
|
||
|
||
expect(result.success).toBe(true);
|
||
expect(result.attempts).toBe(3);
|
||
expect(postSpy).toHaveBeenCalledTimes(3);
|
||
});
|
||
|
||
it('连续失败超过 3 次时,应停止重试,捕获错误并返回 success: false, attempts: 3', async () => {
|
||
const postSpy = jest
|
||
.spyOn(axios, 'post')
|
||
.mockRejectedValue(new Error('Connection Refused'));
|
||
|
||
const result = await syncService.sendWebhook(
|
||
'https://api.partner.com/webhook',
|
||
'wh_secret',
|
||
mockLead,
|
||
{ delayMs: 1 }
|
||
);
|
||
|
||
expect(result.success).toBe(false);
|
||
expect(result.attempts).toBe(3);
|
||
expect(result.error).toBe('Connection Refused');
|
||
expect(postSpy).toHaveBeenCalledTimes(3);
|
||
});
|
||
|
||
it('缺少目标 Webhook URL 时应抛出 400 校验异常', async () => {
|
||
await expect(
|
||
syncService.sendWebhook('', 'secret', mockLead)
|
||
).rejects.toThrow(CoolCommException);
|
||
});
|
||
|
||
it.each([
|
||
'http://localhost/hook',
|
||
'http://127.0.0.1:9000/hook',
|
||
'http://10.1.2.3/hook',
|
||
'http://172.16.0.1/hook',
|
||
'http://172.31.255.1/hook',
|
||
'http://192.168.1.10/hook',
|
||
'ftp://hooks.example.com/crm',
|
||
'file:///etc/passwd',
|
||
])('拒绝内网或非 http(s) URL:%s,不发请求且不记成功', async url => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
|
||
await expect(
|
||
syncService.sendWebhook(url, 'wh_secret', mockLead, { delayMs: 1 })
|
||
).rejects.toThrow(CoolCommException);
|
||
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('公网 https URL 仍应发送并附带 X-OmniCard-Signature', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({
|
||
status: 200,
|
||
data: { ok: true },
|
||
});
|
||
const secret = 'wh_secret_public';
|
||
const url = 'https://hooks.example.com/crm/lead';
|
||
|
||
const result = await syncService.sendWebhook(url, secret, mockLead, {
|
||
delayMs: 1,
|
||
});
|
||
|
||
expect(result.success).toBe(true);
|
||
expect(postSpy).toHaveBeenCalledTimes(1);
|
||
const [, payload, config] = postSpy.mock.calls[0];
|
||
expect(config?.headers?.['X-OmniCard-Signature']).toBe(
|
||
syncService.generateSignature(payload, secret)
|
||
);
|
||
});
|
||
});
|
||
|
||
// ==========================================
|
||
// 5. Slack / 飞书:组包 ≠ 已送达 (delivered)
|
||
// ==========================================
|
||
describe('5. Slack / 飞书组包与送达标记', () => {
|
||
it('formatToSlack 仅组包,不发起 HTTP', () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
const payload = syncService.formatToSlack(mockLead);
|
||
|
||
expect(payload).toMatchObject({
|
||
text: expect.stringContaining('John Doe'),
|
||
});
|
||
expect(payload.text).toContain('Acme Global Corp');
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('formatToFeishu 仅组包,不发起 HTTP', () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
const payload = syncService.formatToFeishu(mockLead);
|
||
|
||
expect(payload.msg_type).toBe('text');
|
||
expect(payload.content?.text).toContain('John Doe');
|
||
expect(payload.content?.text).toContain('Acme Global Corp');
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('sendSlack 无 Webhook URL 时只组包,delivered 必须为 false', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
const result = await syncService.sendSlack(undefined, mockLead);
|
||
|
||
expect(result.delivered).toBe(false);
|
||
expect(result.channel).toBe('slack');
|
||
expect(result.payload).toBeDefined();
|
||
expect(result.reason).toBeTruthy();
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('sendFeishu 空 URL 时只组包,delivered 必须为 false', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
const result = await syncService.sendFeishu('', mockLead);
|
||
|
||
expect(result.delivered).toBe(false);
|
||
expect(result.channel).toBe('feishu');
|
||
expect(result.payload).toBeDefined();
|
||
expect(result.reason).toBeTruthy();
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('sendSlack 内网 URL 在发请求前抛 CoolCommException', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
|
||
await expect(
|
||
syncService.sendSlack('http://192.168.1.10/slack', mockLead)
|
||
).rejects.toThrow(CoolCommException);
|
||
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('sendFeishu 内网 URL 在发请求前抛 CoolCommException', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post');
|
||
|
||
await expect(
|
||
syncService.sendFeishu('http://10.0.0.8/feishu', mockLead)
|
||
).rejects.toThrow(CoolCommException);
|
||
|
||
expect(postSpy).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('sendSlack 公网 HTTP 2xx 才 delivered:true', async () => {
|
||
const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({
|
||
status: 200,
|
||
data: { ok: true },
|
||
});
|
||
|
||
const result = await syncService.sendSlack(
|
||
'https://hooks.slack.com/services/T00/B00/xxx',
|
||
mockLead,
|
||
{ delayMs: 1 }
|
||
);
|
||
|
||
expect(result.delivered).toBe(true);
|
||
expect(result.channel).toBe('slack');
|
||
expect(postSpy).toHaveBeenCalledTimes(1);
|
||
const [, body] = postSpy.mock.calls[0];
|
||
expect(body).toMatchObject({ text: expect.any(String) });
|
||
});
|
||
|
||
it('sendFeishu 公网 HTTP 非 2xx / 失败时 delivered:false,不伪造成功', async () => {
|
||
jest.spyOn(axios, 'post').mockRejectedValue(new Error('502 Bad Gateway'));
|
||
|
||
const result = await syncService.sendFeishu(
|
||
'https://open.feishu.cn/open-apis/bot/v2/hook/public-demo',
|
||
mockLead,
|
||
{ delayMs: 1, maxRetries: 1 }
|
||
);
|
||
|
||
expect(result.delivered).toBe(false);
|
||
expect(result.channel).toBe('feishu');
|
||
expect(result.error).toBeTruthy();
|
||
});
|
||
|
||
it('组包成功不得等同于 delivered:true(sendSlack / sendFeishu 无 URL)', async () => {
|
||
const slack = await syncService.sendSlack(undefined, mockLead);
|
||
const feishu = await syncService.sendFeishu(undefined, mockLead);
|
||
|
||
expect(slack.delivered).toBe(false);
|
||
expect(feishu.delivered).toBe(false);
|
||
expect(slack.payload).toBeDefined();
|
||
expect(feishu.payload).toBeDefined();
|
||
});
|
||
});
|
||
|
||
// ==========================================
|
||
// 6. 控制器接口集成 (/admin/crm/lead/sync-external)
|
||
// ==========================================
|
||
describe('6. 控制器接口 /admin/crm/lead/sync-external 集成测试', () => {
|
||
let controller: AdminCrmLeadController;
|
||
let mockLeadRepo: { findOne: jest.Mock };
|
||
|
||
beforeEach(() => {
|
||
controller = new AdminCrmLeadController();
|
||
mockLeadRepo = {
|
||
findOne: jest.fn(),
|
||
};
|
||
// 依赖注入模拟
|
||
(controller as unknown as { crmLeadEntity: unknown }).crmLeadEntity =
|
||
mockLeadRepo;
|
||
(controller as unknown as { crmSyncService: unknown }).crmSyncService =
|
||
syncService;
|
||
});
|
||
|
||
it('缺少线索 id 时应抛出 400 异常', async () => {
|
||
await expect(
|
||
controller.syncExternal({
|
||
id: 0,
|
||
target: 'hubspot',
|
||
})
|
||
).rejects.toThrow(CoolCommException);
|
||
});
|
||
|
||
it('不支持的 target 类型时应抛出 400 异常', async () => {
|
||
await expect(
|
||
controller.syncExternal({
|
||
id: 101,
|
||
target: 'unknown_crm' as unknown as 'hubspot',
|
||
})
|
||
).rejects.toThrow(CoolCommException);
|
||
});
|
||
|
||
it('线索记录不存在时应抛出 404 异常', async () => {
|
||
mockLeadRepo.findOne.mockResolvedValueOnce(null);
|
||
|
||
await expect(
|
||
controller.syncExternal({
|
||
id: 999,
|
||
target: 'hubspot',
|
||
})
|
||
).rejects.toThrow(CoolCommException);
|
||
});
|
||
|
||
it('正确同步至 hubspot 并返回格式化数据', async () => {
|
||
mockLeadRepo.findOne.mockResolvedValueOnce(mockLead);
|
||
|
||
const res = await controller.syncExternal({
|
||
id: 101,
|
||
target: 'hubspot',
|
||
});
|
||
|
||
expect(res).toEqual({
|
||
code: 1000,
|
||
message: 'success',
|
||
data: {
|
||
target: 'hubspot',
|
||
leadId: 101,
|
||
synced: false,
|
||
reason: '未配置 HubSpot',
|
||
payload: {
|
||
properties: {
|
||
email: 'john.doe@acme.com',
|
||
firstname: 'John',
|
||
lastname: 'Doe',
|
||
phone: '+1-555-0199',
|
||
company: 'Acme Global Corp',
|
||
lifecyclestage: 'lead',
|
||
},
|
||
},
|
||
},
|
||
});
|
||
});
|
||
|
||
it('正确同步至 salesforce 并返回格式化数据', async () => {
|
||
mockLeadRepo.findOne.mockResolvedValueOnce(mockLead);
|
||
|
||
const res = await controller.syncExternal({
|
||
id: 101,
|
||
target: 'salesforce',
|
||
});
|
||
|
||
expect(res).toEqual({
|
||
code: 1000,
|
||
message: 'success',
|
||
data: {
|
||
target: 'salesforce',
|
||
leadId: 101,
|
||
synced: false,
|
||
reason: '未配置 Salesforce',
|
||
payload: {
|
||
FirstName: 'John',
|
||
LastName: 'Doe',
|
||
Email: 'john.doe@acme.com',
|
||
Company: 'Acme Global Corp',
|
||
Phone: '+1-555-0199',
|
||
Status: 'Open - Not Contacted',
|
||
},
|
||
},
|
||
});
|
||
});
|
||
|
||
it('正确通过 webhook 发送签名数据并返回结果', async () => {
|
||
mockLeadRepo.findOne.mockResolvedValueOnce(mockLead);
|
||
jest.spyOn(axios, 'post').mockResolvedValueOnce({
|
||
status: 200,
|
||
data: { ok: true },
|
||
});
|
||
|
||
const res = await controller.syncExternal({
|
||
id: 101,
|
||
target: 'webhook',
|
||
webhookUrl: 'https://webhook.site/test',
|
||
webhookSecret: 'secret_123',
|
||
});
|
||
|
||
expect(res.code).toBe(1000);
|
||
expect(res.data.target).toBe('webhook');
|
||
expect(res.data.leadId).toBe(101);
|
||
expect(res.data.result.success).toBe(true);
|
||
expect(res.data.result.attempts).toBe(1);
|
||
});
|
||
|
||
it('webhook 缺少 webhookUrl 时应抛出 400 异常', async () => {
|
||
mockLeadRepo.findOne.mockResolvedValueOnce(mockLead);
|
||
|
||
await expect(
|
||
controller.syncExternal({
|
||
id: 101,
|
||
target: 'webhook',
|
||
})
|
||
).rejects.toThrow(CoolCommException);
|
||
});
|
||
});
|
||
});
|