Split corps command by domain
This commit is contained in:
1 parent
1987b45336
commit
f5be38d112
7 files changed
+2034
-2333
No files matched your search
@@ -0,0 +1,637 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { KyInstance } from "ky";
|
||||
import { createSealClient } from "../../../core/http/factory.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import * as api from "../../../domains/seal/api.js";
|
||||
import {
|
||||
computeNextSyncIteration,
|
||||
formatSyncVersionName,
|
||||
saveRuleMappingSnapshot
|
||||
} from "../../../domains/seal/rule-mapping.js";
|
||||
import { savePublishedRuleVersionSnapshot } from "../../../domains/seal/rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export async function handleCorpSync(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
): Promise<boolean> {
|
||||
if (action === "sync-test") {
|
||||
const targetCorpId = maybeName ?? stringOption(args.options.corp);
|
||||
const prodCorp = selectCorp(targetCorpId);
|
||||
|
||||
if (!prodCorp.testCorpId) {
|
||||
throw usageError(
|
||||
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
|
||||
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
|
||||
);
|
||||
}
|
||||
|
||||
const testCorp = selectCorp(prodCorp.testCorpId);
|
||||
if (testCorp.environment !== "test") {
|
||||
throw new Error(
|
||||
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.`
|
||||
);
|
||||
}
|
||||
|
||||
const prodClient = await createSealClient(prodCorp);
|
||||
const testClient = await createSealClient(testCorp);
|
||||
const [
|
||||
prodPref,
|
||||
testPref,
|
||||
prodRules,
|
||||
testRules,
|
||||
prodVersions,
|
||||
testVersions,
|
||||
prodDocsRes,
|
||||
testDocsRes
|
||||
] = await Promise.all([
|
||||
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
|
||||
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences),
|
||||
api.listApprovalRules(prodClient),
|
||||
api.listApprovalRules(testClient),
|
||||
api.listApprovalRuleVersions(prodClient),
|
||||
api.listApprovalRuleVersions(testClient),
|
||||
listAllApprovalDocuments(prodClient),
|
||||
listAllApprovalDocuments(testClient)
|
||||
]);
|
||||
|
||||
const prodDocs = (prodDocsRes.articles || []).filter((d) => !d.isDeleted);
|
||||
const testDocs = (testDocsRes.articles || []).filter((d) => !d.isDeleted);
|
||||
const testDocsByTitle = new Map(testDocs.map((d) => [d.title.trim(), d]));
|
||||
const docsToCreate = [];
|
||||
const docsToUpdate = [];
|
||||
const prodTitles = new Set(prodDocs.map((d) => d.title.trim()));
|
||||
|
||||
for (const prodDoc of prodDocs) {
|
||||
const title = prodDoc.title.trim();
|
||||
const existing = testDocsByTitle.get(title);
|
||||
if (!existing) {
|
||||
docsToCreate.push(prodDoc);
|
||||
continue;
|
||||
}
|
||||
|
||||
const contentChanged = existing.content !== prodDoc.content;
|
||||
const purposeChanged = (existing.purpose ?? "") !== (prodDoc.purpose ?? "");
|
||||
const enabledChanged = existing.enabled !== prodDoc.enabled;
|
||||
const contentTypeChanged = existing.contentType !== prodDoc.contentType;
|
||||
const statusChanged = (existing.status ?? "") !== (prodDoc.status ?? "");
|
||||
const scenariosChanged = JSON.stringify([...(existing.scenarios ?? [])].sort()) !==
|
||||
JSON.stringify([...(prodDoc.scenarios ?? [])].sort());
|
||||
const tagsChanged = JSON.stringify([...(existing.tags ?? [])].sort()) !==
|
||||
JSON.stringify([...(prodDoc.tags ?? [])].sort());
|
||||
|
||||
if (contentChanged || purposeChanged || enabledChanged || contentTypeChanged || statusChanged || scenariosChanged || tagsChanged) {
|
||||
docsToUpdate.push({
|
||||
testId: existing.id,
|
||||
prodDoc,
|
||||
reasons: [
|
||||
...(contentChanged ? ["content"] : []),
|
||||
...(purposeChanged ? ["purpose"] : []),
|
||||
...(enabledChanged ? ["enabled"] : []),
|
||||
...(contentTypeChanged ? ["contentType"] : []),
|
||||
...(statusChanged ? ["status"] : []),
|
||||
...(scenariosChanged ? ["scenarios"] : []),
|
||||
...(tagsChanged ? ["tags"] : [])
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const docsToDelete = testDocs.filter((td) => !prodTitles.has(td.title.trim()));
|
||||
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
|
||||
const latestProd = sortedProdVersions[0];
|
||||
const prodVersionNumber = latestProd?.versionNumber;
|
||||
const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber);
|
||||
const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1;
|
||||
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
|
||||
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
|
||||
const versionName = customVersionName ?? formatSyncVersionName(
|
||||
prodCorp.name,
|
||||
prodVersionNumber,
|
||||
nextIteration,
|
||||
targetTestExpectedVersionNumber
|
||||
);
|
||||
const updatedTestPref = {
|
||||
...testPref,
|
||||
tone: prodPref.tone,
|
||||
language: prodPref.language,
|
||||
detailLevel: prodPref.detailLevel,
|
||||
outputFormat: prodPref.outputFormat,
|
||||
examples: prodPref.examples ?? [],
|
||||
prohibitedPhrases: prodPref.prohibitedPhrases ?? [],
|
||||
customInstructions: prodPref.customInstructions,
|
||||
decisionPreferences: prodPref.decisionPreferences,
|
||||
thinkingDepthPreference: prodPref.thinkingDepthPreference
|
||||
};
|
||||
|
||||
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
|
||||
if (dryRun) {
|
||||
printJson({
|
||||
dryRun: true,
|
||||
source: {
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
environment: prodCorp.environment,
|
||||
latestPublishedVersion: latestProd ? {
|
||||
versionNumber: latestProd.versionNumber,
|
||||
versionName: latestProd.versionName
|
||||
} : null,
|
||||
documentsCount: prodDocs.length
|
||||
},
|
||||
target: {
|
||||
id: testCorp.id,
|
||||
name: testCorp.name,
|
||||
environment: testCorp.environment
|
||||
},
|
||||
versionMappingPlan: {
|
||||
sourceProdVersionNumber: prodVersionNumber ?? null,
|
||||
sourceProdVersionName: latestProd?.versionName ?? null,
|
||||
targetTestExpectedVersionNumber,
|
||||
targetTestPublishVersionName: versionName,
|
||||
iteration: nextIteration
|
||||
},
|
||||
preferencesDiff: {
|
||||
decisionPreferences: {
|
||||
before: testPref.decisionPreferences,
|
||||
after: prodPref.decisionPreferences
|
||||
},
|
||||
thinkingDepthPreference: {
|
||||
before: testPref.thinkingDepthPreference,
|
||||
after: prodPref.thinkingDepthPreference
|
||||
}
|
||||
},
|
||||
rulesPlan: {
|
||||
sourceDraftRuleCount: prodRules.rules.length,
|
||||
targetExistingDraftRuleCount: testRules.rules.length,
|
||||
toDeleteCount: testRules.rules.length,
|
||||
toCreateCount: prodRules.rules.length,
|
||||
rulesToSync: prodRules.rules.map((r, idx) => ({
|
||||
index: idx + 1,
|
||||
sourceRuleId: r.id,
|
||||
sourceRuleCode: r.code ?? idx + 1,
|
||||
expectedTargetCode: `rule-${idx + 1}`,
|
||||
description: r.description,
|
||||
scope: r.scope,
|
||||
strictness: r.strictness
|
||||
}))
|
||||
},
|
||||
documentsPlan: {
|
||||
sourceDocumentCount: prodDocs.length,
|
||||
targetExistingDocumentCount: testDocs.length,
|
||||
toCreateCount: docsToCreate.length,
|
||||
toCreate: docsToCreate.map((d) => ({
|
||||
title: d.title,
|
||||
purpose: d.purpose,
|
||||
contentType: d.contentType,
|
||||
scenarios: d.scenarios
|
||||
})),
|
||||
toUpdateCount: docsToUpdate.length,
|
||||
toUpdate: docsToUpdate.map((d) => ({
|
||||
targetDocumentId: d.testId,
|
||||
title: d.prodDoc.title,
|
||||
reasons: d.reasons
|
||||
})),
|
||||
toDeleteCount: docsToDelete.length,
|
||||
toDelete: docsToDelete.map((d) => ({
|
||||
targetDocumentId: d.id,
|
||||
title: d.title
|
||||
}))
|
||||
},
|
||||
publishingPlan: {
|
||||
targetCorpId: testCorp.id,
|
||||
publishVersionName: versionName,
|
||||
publishTarget: "test"
|
||||
},
|
||||
hosecloudSyncPlan: buildHosecloudSyncPlan(prodCorp, prodPref),
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||
if (!confirmed) {
|
||||
throw confirmationRequired(
|
||||
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
|
||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||
);
|
||||
}
|
||||
|
||||
// 1. Update style & decision preferences in test enterprise
|
||||
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
|
||||
|
||||
// 2. Synchronize knowledge documents in test enterprise (full coverage, delete redundant test documents)
|
||||
const deletedDocs: Array<{ id: string; title: string }> = [];
|
||||
for (const doc of docsToDelete) {
|
||||
await api.deleteApprovalDocument(testClient, doc.id);
|
||||
deletedDocs.push({ id: doc.id, title: doc.title });
|
||||
}
|
||||
|
||||
const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = [];
|
||||
for (const item of docsToUpdate) {
|
||||
await api.updateApprovalDocument(testClient, item.testId, {
|
||||
title: item.prodDoc.title,
|
||||
purpose: item.prodDoc.purpose,
|
||||
content: item.prodDoc.content,
|
||||
contentType: item.prodDoc.contentType,
|
||||
status: item.prodDoc.status,
|
||||
enabled: item.prodDoc.enabled,
|
||||
scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"],
|
||||
tags: item.prodDoc.tags
|
||||
});
|
||||
updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons });
|
||||
}
|
||||
|
||||
const createdDocs: Array<{ id: string; title: string }> = [];
|
||||
for (const doc of docsToCreate) {
|
||||
const created = await api.createApprovalDocument(testClient, {
|
||||
title: doc.title,
|
||||
purpose: doc.purpose,
|
||||
content: doc.content,
|
||||
contentType: doc.contentType,
|
||||
status: doc.status,
|
||||
enabled: doc.enabled,
|
||||
scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"],
|
||||
tags: doc.tags
|
||||
});
|
||||
createdDocs.push({ id: created.id, title: created.title });
|
||||
}
|
||||
|
||||
// 3. Clear old draft rules in test enterprise
|
||||
for (const rule of testRules.rules) {
|
||||
await api.deleteApprovalRule(testClient, rule.id);
|
||||
}
|
||||
|
||||
// 4. Create new draft rules in test enterprise
|
||||
const createdRules: any[] = [];
|
||||
for (const rule of prodRules.rules) {
|
||||
const created = await api.createApprovalRule(testClient, {
|
||||
description: rule.description,
|
||||
scope: rule.scope,
|
||||
strictness: rule.strictness
|
||||
});
|
||||
createdRules.push(created);
|
||||
}
|
||||
|
||||
// 5. Batch recode rules in test enterprise
|
||||
const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number };
|
||||
if (!recodeResult.ok) {
|
||||
throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`);
|
||||
}
|
||||
|
||||
// 6. Sync HoseCloud integrations before publishing the test version. This
|
||||
// keeps a Hose configuration failure from leaving a newly published
|
||||
// version behind, although the overall multi-request operation remains
|
||||
// non-transactional.
|
||||
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient);
|
||||
// 7. Publish new version in test enterprise
|
||||
const published = await api.publishApprovalRuleVersion(testClient, versionName);
|
||||
try {
|
||||
savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules);
|
||||
} catch {}
|
||||
|
||||
const publishedRules = published.version.rules ?? [];
|
||||
const ruleMapping = prodRules.rules.map((prodRule, idx) => {
|
||||
const testDraft = createdRules[idx];
|
||||
const publishedRule = publishedRules[idx];
|
||||
return {
|
||||
index: idx + 1,
|
||||
sourceRuleId: prodRule.id,
|
||||
sourceRuleCode: prodRule.code ?? idx + 1,
|
||||
targetRuleId: testDraft?.id ?? "",
|
||||
targetRuleCode: publishedRule?.code ?? `rule-${idx + 1}`,
|
||||
description: prodRule.description,
|
||||
scope: prodRule.scope,
|
||||
strictness: prodRule.strictness
|
||||
};
|
||||
});
|
||||
|
||||
const versionMapping = {
|
||||
sourceProdVersionNumber: prodVersionNumber ?? null,
|
||||
sourceProdVersionName: latestProd?.versionName ?? null,
|
||||
targetTestVersionNumber: published.version.versionNumber,
|
||||
targetTestVersionName: published.version.versionName ?? null
|
||||
};
|
||||
|
||||
let mappingSavedTo: string | undefined;
|
||||
try {
|
||||
mappingSavedTo = saveRuleMappingSnapshot({
|
||||
syncedAt: new Date().toISOString(),
|
||||
source: {
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
latestPublishedVersionNumber: prodVersionNumber ?? null,
|
||||
latestPublishedVersionName: latestProd?.versionName ?? null
|
||||
},
|
||||
target: {
|
||||
id: testCorp.id,
|
||||
name: testCorp.name,
|
||||
publishedVersionNumber: published.version.versionNumber,
|
||||
publishedVersionName: published.version.versionName,
|
||||
rulesCount: published.rulesCount
|
||||
},
|
||||
versionMapping,
|
||||
ruleMapping
|
||||
});
|
||||
} catch {}
|
||||
|
||||
printJson({
|
||||
success: true,
|
||||
syncedAt: new Date().toISOString(),
|
||||
source: {
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
environment: prodCorp.environment,
|
||||
latestPublishedVersion: latestProd ? {
|
||||
versionNumber: latestProd.versionNumber,
|
||||
versionName: latestProd.versionName
|
||||
} : null,
|
||||
draftRulesCount: prodRules.rules.length,
|
||||
documentsCount: prodDocs.length
|
||||
},
|
||||
target: {
|
||||
id: testCorp.id,
|
||||
name: testCorp.name,
|
||||
environment: testCorp.environment,
|
||||
deletedDraftRulesCount: testRules.rules.length,
|
||||
createdDraftRulesCount: createdRules.length,
|
||||
publishedVersion: {
|
||||
id: published.version.id,
|
||||
versionNumber: published.version.versionNumber,
|
||||
versionName: published.version.versionName,
|
||||
rulesCount: published.rulesCount
|
||||
}
|
||||
},
|
||||
documents: {
|
||||
sourceCount: prodDocs.length,
|
||||
targetExistingCount: testDocs.length,
|
||||
createdCount: createdDocs.length,
|
||||
created: createdDocs,
|
||||
updatedCount: updatedDocs.length,
|
||||
updated: updatedDocs,
|
||||
deletedCount: deletedDocs.length,
|
||||
deleted: deletedDocs
|
||||
},
|
||||
versionMapping,
|
||||
ruleMapping,
|
||||
...(mappingSavedTo ? { mappingSavedTo } : {}),
|
||||
hosecloudSync,
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (action === "replay-test") {
|
||||
const targetCorpId = maybeName ?? stringOption(args.options.corp) ?? stringOption(args.options.prodCorp) ?? stringOption(args.options["prod-corp"]);
|
||||
const prodCorp = selectCorp(targetCorpId);
|
||||
const force = booleanOption(args.options.force) === true;
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||
let testCorp: CorpConfig;
|
||||
|
||||
if (!prodCorp.testCorpId) {
|
||||
if (!force) {
|
||||
throw usageError(
|
||||
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
|
||||
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,\n` +
|
||||
`or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`
|
||||
);
|
||||
}
|
||||
testCorp = prodCorp;
|
||||
} else {
|
||||
testCorp = selectCorp(prodCorp.testCorpId);
|
||||
if (testCorp.environment !== "test" && !force) {
|
||||
throw new Error(
|
||||
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!dryRun && !confirmed) {
|
||||
throw confirmationRequired(
|
||||
"Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",
|
||||
`seal-use corps replay-test ${targetCorpId ?? "<prodCorpId>"} --confirm`
|
||||
);
|
||||
}
|
||||
|
||||
const recordId = stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
|
||||
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
|
||||
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options.documentSn) ?? stringOption(args.options["document-sn"]);
|
||||
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
|
||||
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined);
|
||||
const status = stringOption(args.options.status);
|
||||
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
|
||||
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
|
||||
const prodClient = await createSealClient(prodCorp);
|
||||
const testClient = prodCorp.id === testCorp.id ? prodClient : await createSealClient(testCorp);
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
|
||||
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
|
||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||
const query: ReplayRecordsQuery = { recordId, recordIds, sn, sns, limit, status, startDate, endDate };
|
||||
|
||||
console.error(`[corps-replay-test] 正式企业「${prodCorp.name}」(${prodCorp.id}) -> 测试企业「${testCorp.name}」(${testCorp.id})`);
|
||||
const result = await executeApprovalRunsReplay({
|
||||
query,
|
||||
sourceClient: prodClient,
|
||||
targetClient: testClient,
|
||||
sourceCorp: prodCorp,
|
||||
targetCorp: testCorp,
|
||||
webhookSelector: selector,
|
||||
snPrefix,
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
dryRun
|
||||
});
|
||||
|
||||
if (dryRun) {
|
||||
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
if (result.totalCount === 1 && result.replayedDocument) {
|
||||
console.error(`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${testCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`);
|
||||
} else {
|
||||
console.error(`🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`);
|
||||
}
|
||||
} else {
|
||||
console.error(`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${testCorp.name}」`);
|
||||
}
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${testCorp.id} --limit ${result.totalCount}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (!result.success) {
|
||||
throw new CliError(`Approval record replay failed: ${result.failureCount} record(s) failed.`, 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async function listAllApprovalDocuments(client: KyInstance) {
|
||||
const pageSize = 100;
|
||||
const documents: Awaited<ReturnType<typeof api.listApprovalDocuments>>["articles"] = [];
|
||||
let offset = 0;
|
||||
|
||||
while (true) {
|
||||
const page = await api.listApprovalDocuments(client, { offset, limit: pageSize });
|
||||
documents.push(...page.articles);
|
||||
offset += page.articles.length;
|
||||
if (page.articles.length === 0 || page.articles.length < pageSize) break;
|
||||
if (page.total !== undefined && offset >= page.total) break;
|
||||
}
|
||||
|
||||
return { articles: documents, total: documents.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the outboundName for a test-env hosecloud integration.
|
||||
* Format: {企业名前7字}(Seal测) — capped at 13 chars total.
|
||||
*/
|
||||
export function buildTestHosecloudOutboundName(corpName: string): string {
|
||||
const suffix = "(Seal测)";
|
||||
// "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix.
|
||||
const maxPrefix = 13 - suffix.length;
|
||||
const prefix = [...corpName].slice(0, maxPrefix).join("");
|
||||
return prefix + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hosecloud integrations from the production Seal enterprise into the
|
||||
* test Seal enterprise. Rules:
|
||||
* - Only runs when prodCorp.source.type === "hose" (credentials available locally)
|
||||
* - outboundName: buildTestHosecloudOutboundName(prodCorp.name)
|
||||
* - mode: always "assisted"
|
||||
* - apiKey/apiSecret: from prodCorp.source.appKey / appSecurity
|
||||
* - apiOrigin/customApiUrl: copied verbatim from the production integration config
|
||||
* - signKey: existing test integration keeps its key; new ones get a fresh random key
|
||||
* - Does NOT call syncHosecloudOutbound (no sync to 合思)
|
||||
*/
|
||||
interface HosecloudSyncResult {
|
||||
skipped: boolean;
|
||||
reason?: string;
|
||||
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>;
|
||||
}
|
||||
|
||||
function buildHosecloudSyncPlan(prodCorp: CorpConfig, prodPref: any) {
|
||||
if (prodCorp.source.type !== "hose") {
|
||||
return {
|
||||
sourceType: prodCorp.source.type,
|
||||
skipped: true,
|
||||
reason: "prod source is not hose; no hosecloud credentials available"
|
||||
};
|
||||
}
|
||||
const rawHose = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
const seen = new Set<string>();
|
||||
const distinct = rawHose.filter((i: any) => {
|
||||
const cid = i.corporationId ?? prodCorp.id;
|
||||
if (seen.has(cid)) return false;
|
||||
seen.add(cid);
|
||||
return true;
|
||||
});
|
||||
return {
|
||||
sourceType: "hose",
|
||||
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
|
||||
targetMode: "assisted",
|
||||
integrationsCount: distinct.length,
|
||||
integrations: distinct.map((i: any) => ({
|
||||
corporationId: i.corporationId,
|
||||
apiOrigin: i.apiOrigin,
|
||||
customApiUrl: i.customApiUrl
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
async function syncHosecloudIntegrationsToTest(
|
||||
prodCorp: CorpConfig,
|
||||
testCorp: CorpConfig,
|
||||
prodClient: KyInstance,
|
||||
testClient: KyInstance
|
||||
): Promise<HosecloudSyncResult> {
|
||||
if (prodCorp.source.type !== "hose") {
|
||||
return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" };
|
||||
}
|
||||
|
||||
const appKey = (prodCorp.source.appKey ?? prodCorp.source.key)?.trim();
|
||||
const appSecurity = (prodCorp.source.appSecurity ?? prodCorp.source.password)?.trim();
|
||||
if (!appKey || !appSecurity) {
|
||||
return { skipped: true, reason: "prod hose source missing appKey/appSecurity (or key/password)" };
|
||||
}
|
||||
|
||||
const [prodPref, testPref] = await Promise.all([
|
||||
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
|
||||
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences)
|
||||
]);
|
||||
const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
if (prodIntegrations.length === 0) {
|
||||
return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" };
|
||||
}
|
||||
|
||||
// Deduplicate prod integrations by corporationId:
|
||||
// Production enterprises may have multiple integrations (e.g. "assisted" + "fully_automatic")
|
||||
// with the same corporationId. For the test environment, exactly one assisted integration per
|
||||
// corporationId is needed.
|
||||
const seenCorpIds = new Set<string>();
|
||||
const distinctProdIntegrations: any[] = [];
|
||||
for (const item of prodIntegrations) {
|
||||
const cid = item.corporationId ?? prodCorp.id;
|
||||
if (!seenCorpIds.has(cid)) {
|
||||
seenCorpIds.add(cid);
|
||||
distinctProdIntegrations.push({ ...item, corporationId: cid });
|
||||
}
|
||||
}
|
||||
|
||||
const testIntegrations: any[] = testPref.integrations ?? [];
|
||||
const testByCorpId = new Map<string, any>(
|
||||
testIntegrations.filter((i: any) => i.type === "hosecloud").map((i: any) => [i.corporationId, i])
|
||||
);
|
||||
const outboundName = buildTestHosecloudOutboundName(prodCorp.name);
|
||||
const synced: HosecloudSyncResult["synced"] = [];
|
||||
const nextHosecloudIntegrations: any[] = distinctProdIntegrations.map((prodInt: any) => {
|
||||
const existing = testByCorpId.get(prodInt.corporationId);
|
||||
const signKey = existing?.signKey ?? randomBytes(6).toString("hex");
|
||||
synced!.push({
|
||||
signKey,
|
||||
outboundName,
|
||||
corporationId: prodInt.corporationId,
|
||||
action: existing ? "updated" : "created"
|
||||
});
|
||||
return {
|
||||
type: "hosecloud",
|
||||
signKey,
|
||||
outboundName,
|
||||
mode: "assisted",
|
||||
apiKey: appKey,
|
||||
apiSecret: appSecurity,
|
||||
apiOrigin: prodInt.apiOrigin,
|
||||
...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}),
|
||||
corporationId: prodInt.corporationId
|
||||
};
|
||||
});
|
||||
|
||||
// Merge: keep non-hosecloud entries + newly built hosecloud entries
|
||||
const otherIntegrations = testIntegrations.filter((i: any) => i.type !== "hosecloud");
|
||||
await api.updateApprovalStylePreferences(
|
||||
testClient,
|
||||
{ ...testPref, integrations: [...otherIntegrations, ...nextHosecloudIntegrations] },
|
||||
testCorp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
return { skipped: false, synced };
|
||||
}
|
||||
Reference in new issue
Block a user