import { createSealClient } from "../../../core/http/factory.js"; import type { CorpConfig } from "../../../core/config/types.js"; import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js"; import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js"; import { selectCorp } from "../../helpers.js"; import { CliError, confirmationRequired, usageError } from "../../errors.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { outputOptions, printJson } from "../../printer.js"; import type { ParsedArgs } from "../../types.js"; export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js"; export async function handleCorpSync( action: string | undefined, maybeName: string | undefined, args: ParsedArgs ): Promise { 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} --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 versionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName); const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true; const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true; if (dryRun) { printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, dryRun: true })); return true; } if (!confirmed) { const preview = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: false }) as { rulesPlan: { sourceDraftRuleCount: number; targetExistingDraftRuleCount: number }; documentsPlan: { sourceDocumentCount: number; toDeleteCount: number }; }; throw confirmationRequired( `Refusing to sync into test enterprise '${testCorp.name}' (${testCorp.id}) without --yes. ` + `This is DESTRUCTIVE for the test tenant: it will DELETE its ${preview.rulesPlan.targetExistingDraftRuleCount} existing draft rules and rebuild them from ${preview.rulesPlan.sourceDraftRuleCount} production draft rules, ` + `DELETE ${preview.documentsPlan.toDeleteCount} existing knowledge documents and re-import ${preview.documentsPlan.sourceDocumentCount} documents from production, overwrite test preferences, and publish a new rules version. ` + `Run with --dry-run first to review the exact documents that will be deleted.`, `seal-use corps sync-test ${prodCorp.id} --yes` ); } const result = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }); const targetVersion = (result as { target?: { publishedVersion?: { versionNumber?: number; versionName?: string; rulesCount?: number } } })?.target?.publishedVersion; const rulesList = (result as { ruleMapping?: unknown[] })?.ruleMapping ?? []; console.error( `✅ 测试企业同步完成: 生产「${prodCorp.name}」(${prodCorp.id}) -> 测试「${testCorp.name}」(${testCorp.id})\n` + `📦 已发布测试版本: v${targetVersion?.versionNumber ?? "?"} (${targetVersion?.versionName ?? "最新"}) | 规则总数: ${targetVersion?.rulesCount ?? rulesList.length} 条\n` + `🔄 规则映射已归档: 共 ${rulesList.length} 条规则已与测试环境对齐\n` + `👉 下一步模拟测试建议: seal-use simulation create --document-sn <单号> --corp ${testCorp.id} --extract-expenses` ); printJson(result, outputOptions(args.options)); 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} --confirm' first to establish a verified 1-to-1 association,\n` + `or add '--force' (or use 'seal-use webhook replay --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 ?? ""} --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((value) => value.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((value) => value.trim()).filter(Boolean) : undefined; const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined); const query: ReplayRecordsQuery = { recordId, recordIds, sn, sns, limit, status: stringOption(args.options.status), startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]), 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); 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: stringOption(args.options.webhook) ?? stringOption(args.options.selector), snPrefix: stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]), snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]), docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]), docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]), dryRun, confirm: confirmed }); if (dryRun) { console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`); printJson(result); return true; } if (result.success) { 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}`); printJson(result); if (!result.success) throw new CliError(`Approval record replay failed: ${result.failureCount} record(s) failed.`, 1); return true; } return false; }