Add automatic hosecloud integration sync for test environments

- Sync hosecloud integrations from prod to test during corps sync-test
- Format outboundName as {corpNamePrefix}(Seal测) capped at 13 chars
- Force assisted mode and reuse existing credentials and apiOrigin
- Skip outbound sync to Hosecloud to preserve production approval flows
- Add unit and integration tests covering naming, mode, and idempotency
This commit is contained in:
gitea committed 2026-09-11 14:52:17 +08:00
1 parent 72b61819a1
commit c2d3c119f2
2 files changed
+410

No files matched your search

+286
View File
@@ -402,6 +402,292 @@ describe("corps sync-test", () => {
});
});
describe("buildTestHosecloudOutboundName", () => {
test("appends (Seal测) suffix, using up to 6 chars of corp name", async () => {
const { buildTestHosecloudOutboundName } = await import("./corps.js");
// Short name — all chars fit
expect(buildTestHosecloudOutboundName("钰泰半导体")).toBe("钰泰半导体(Seal测)");
// Exactly 6-char prefix
expect(buildTestHosecloudOutboundName("美年大健康产业控股")).toBe("美年大健康产(Seal测)");
// Long name — truncated to 6 chars prefix
expect(buildTestHosecloudOutboundName("钰泰半导体股份有限公司")).toBe("钰泰半导体股(Seal测)");
// Total is always ≤ 13 chars
const name = buildTestHosecloudOutboundName("一二三四五六七八九十");
expect([...name].length).toBeLessThanOrEqual(13);
expect(name.endsWith("(Seal测)")).toBe(true);
});
});
describe("sync-test hosecloud integration auto-sync", () => {
function setupHoseTestEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-hose-sync-"));
const enterprises = join(root, "enterprises");
const mappings = join(root, "mappings");
mkdirSync(enterprises, { recursive: true });
mkdirSync(mappings, { recursive: true });
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
// Prod corp is hose-sourced (has appKey/appSecurity)
const prodCorp: CorpConfig = {
id: "hose-prod",
name: "钰泰半导体股份有限公司",
environment: "production",
testCorpId: "hose-test",
seal: {
url: "https://hose-prod.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "hose",
domain: "https://wx2.ekuaibao.com",
appKey: "test-app-key-123",
appSecurity: "test-app-secret-456",
staffId: "hose-prod:staffid",
corpId: "hose-prod"
},
auth: { refreshTtl: 300 }
};
const testCorp: CorpConfig = {
id: "hose-test",
name: "谢子豪测试环境",
environment: "test",
prodCorpId: "hose-prod",
seal: {
url: "https://hose-test.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "test-token",
sealUrl: "https://hose-test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorp, null, 2));
writeFileSync(join(enterprises, "hose-test.json"), JSON.stringify(testCorp, null, 2));
return { root, enterprises };
}
function mockHoseSyncRequests(options: {
prodHosecloudIntegrations?: any[];
testHosecloudIntegrations?: any[];
onConfigWrite?: (isProd: boolean, body: unknown) => void;
} = {}) {
const prodIntegrations = options.prodHosecloudIntegrations ?? [
{
type: "hosecloud",
signKey: "prod-sign-key",
outboundName: "钰泰正式审批",
mode: "fully_automatic",
apiKey: "test-app-key-123",
apiSecret: "test-app-secret-456",
apiOrigin: "custom",
customApiUrl: "https://wx2.ekuaibao.com",
corporationId: "hose-prod"
}
];
const testIntegrations = options.testHosecloudIntegrations ?? [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string" ? input
: input instanceof URL ? input.toString() : input.url;
const method = (
init?.method ??
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
).toUpperCase();
const url = new URL(requestUrl);
const isProd = url.host.includes("prod");
let rawBody = typeof init?.body === "string" ? init.body : undefined;
if (!rawBody && typeof input === "object" && "text" in input) {
rawBody = await (input as Request).clone().text().catch(() => "{}");
}
if (url.pathname === "/api/v1/auth/me") {
return jsonResponse({
data: {
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "hose-prod" : "hose-test" }
}
});
}
// Hose → Seal SSO token exchange (used when prod corp is hose-sourced)
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
return jsonResponse({ token: "mock-hose-seal-token", expiresIn: 3600 });
}
// Hose openapi token exchange
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
return jsonResponse({ value: { accessToken: "mock-hose-openapi-token" } });
}
// Hose provisional auth URL (getProvisionalAuth) — must return a URL with accessToken param
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
return jsonResponse({ value: { message: "https://mock.ekuaibao.com/provisional?accessToken=mock-closeapi-token" } });
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
return jsonResponse({
data: {
tone: "formal",
language: "zh-CN",
decisionPreferences: { explicitApprove: "", explicitReject: "", exemptApprove: "", review: "" },
thinkingDepthPreference: { defaultLevel: "medium", routingPolicies: [] },
integrations: isProd ? prodIntegrations : testIntegrations
}
});
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
const body = JSON.parse(rawBody || "{}");
options.onConfigWrite?.(isProd, body);
return jsonResponse({ data: { success: true } });
}
// Minimal stubs for rules/docs/versions
if (url.pathname === "/api/v1/knowledge/articles") {
return jsonResponse({ data: { articles: [], total: 0 } });
}
if (url.pathname === "/api/v1/rules") {
return jsonResponse({ data: { rules: [], hasPendingDeletes: false } });
}
if (url.pathname === "/api/v1/rule-set-versions") {
return jsonResponse({ data: [] });
}
if (url.pathname === "/api/v1/rule-set-versions/publish") {
return jsonResponse({ data: { version: { id: "v1", versionNumber: 1, versionName: "v1", rules: [] }, rulesCount: 0 } });
}
if (url.pathname === "/api/v1/rules/batch-recode") {
return jsonResponse({ data: { success: true } });
}
return jsonResponse({ error: `Unexpected: ${method} ${url.pathname}` }, 404);
}) as typeof fetch;
}
test("hose-sourced prod corp auto-syncs hosecloud integration with assisted mode and naming convention", async () => {
setupHoseTestEnv();
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
let capturedTestConfigBody: any;
mockHoseSyncRequests({
onConfigWrite: (isProd, body) => {
if (!isProd) capturedTestConfigBody = body;
}
});
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
expect(result.isError).toBe(false);
const parsed = JSON.parse(result.stdout);
expect(parsed.hosecloudSync).toBeDefined();
expect(parsed.hosecloudSync.skipped).toBe(false);
expect(parsed.hosecloudSync.synced).toHaveLength(1);
const synced = parsed.hosecloudSync.synced[0];
expect(synced.outboundName).toBe("钰泰半导体股(Seal测)");
expect(synced.corporationId).toBe("hose-prod");
expect(synced.action).toBe("created");
// Verify the written integration has assisted mode regardless of prod mode
expect(capturedTestConfigBody).toBeDefined();
const writtenIntegration = capturedTestConfigBody.integrations?.find((i: any) => i.type === "hosecloud");
expect(writtenIntegration?.mode).toBe("assisted");
expect(writtenIntegration?.apiOrigin).toBe("custom");
expect(writtenIntegration?.customApiUrl).toBe("https://wx2.ekuaibao.com");
expect(writtenIntegration?.outboundName).toBe("钰泰半导体股(Seal测)");
});
test("preserves existing test signKey when re-syncing (idempotent)", async () => {
setupHoseTestEnv();
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
const existingSignKey = "existing-test-sign-key";
let capturedBody: any;
mockHoseSyncRequests({
testHosecloudIntegrations: [
{
type: "hosecloud",
signKey: existingSignKey,
outboundName: "钰泰半导体股(Seal测)",
mode: "assisted",
apiKey: "test-app-key-123",
apiSecret: "test-app-secret-456",
apiOrigin: "custom",
customApiUrl: "https://wx2.ekuaibao.com",
corporationId: "hose-prod"
}
],
onConfigWrite: (isProd, body) => {
if (!isProd) capturedBody = body;
}
});
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
expect(result.isError).toBe(false);
const parsed = JSON.parse(result.stdout);
expect(parsed.hosecloudSync.synced[0].action).toBe("updated");
expect(parsed.hosecloudSync.synced[0].signKey).toBe(existingSignKey);
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
expect(writtenIntegration?.signKey).toBe(existingSignKey);
});
test("skips hosecloud sync for non-hose-sourced prod corps", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-skip-hose-"));
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_MAPPINGS_DIR = join(root, "mappings");
mkdirSync(join(root, "mappings"), { recursive: true });
const sealProd: CorpConfig = {
id: "seal-prod",
name: "Acme Seal Native",
environment: "production",
testCorpId: "seal-test",
seal: { url: "https://seal-prod.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal", token: "tok", sealUrl: "https://seal-prod.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
const sealTest: CorpConfig = {
id: "seal-test",
name: "Acme Test",
environment: "test",
prodCorpId: "seal-prod",
seal: { url: "https://seal-test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal", token: "tok2", sealUrl: "https://seal-test.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "seal-prod.json"), JSON.stringify(sealProd, null, 2));
writeFileSync(join(enterprises, "seal-test.json"), JSON.stringify(sealTest, null, 2));
mockHoseSyncRequests({});
const result = await runCli(["corps", "sync-test", "seal-prod", "--yes"]);
expect(result.isError).toBe(false);
const parsed = JSON.parse(result.stdout);
expect(parsed.hosecloudSync.skipped).toBe(true);
expect(parsed.hosecloudSync.reason).toContain("not hose");
});
});
describe("corps list & current", () => {
test("outputs environment, testCorpId, and prodCorpId", async () => {
setupTestEnv();