1696 lines
59 KiB
TypeScript
1696 lines
59 KiB
TypeScript
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import type { CorpConfig } from "../../../core/config/types.js";
|
||
import { defaultSealUrl } from "../../../core/auth/hose.js";
|
||
import * as api from "../api.js";
|
||
import type {
|
||
ApprovalRule,
|
||
ApprovalRun,
|
||
RuleSetVersion,
|
||
SimulationBatch,
|
||
WebhookIntegration
|
||
} from "../types.js";
|
||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||
import type { LocalRuleItem } from "../rules-local.js";
|
||
import { loadRuleMappingSnapshot } from "../rule-mapping.js";
|
||
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||
|
||
export type CapabilityContext = {
|
||
corp: CorpConfig;
|
||
};
|
||
|
||
export type SealCapabilityDefinition = {
|
||
name: string;
|
||
description: string;
|
||
parameters: z.ZodType;
|
||
handler: (client: KyInstance, params: never, context: CapabilityContext) => Promise<unknown>;
|
||
};
|
||
|
||
export function presentWebhookIntegration(
|
||
integration: WebhookIntegration,
|
||
includeSecret: boolean
|
||
) {
|
||
return includeSecret
|
||
? integration
|
||
: { ...integration, secret: "<redacted>" };
|
||
}
|
||
|
||
export function getConfiguredSealBaseUrl(corp: CorpConfig): string {
|
||
if (corp.seal.url) return corp.seal.url;
|
||
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source);
|
||
return corp.source.sealUrl;
|
||
}
|
||
|
||
export type ApprovalRunSummary = {
|
||
id: string;
|
||
tenantId?: string;
|
||
agentId?: string;
|
||
status?: string;
|
||
taskMode?: string;
|
||
finalExecutionMode?: string;
|
||
sourceSystem?: string;
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
documentId?: string;
|
||
simulationBatchId?: string;
|
||
langfuseTraceId?: string;
|
||
langfuseSessionFallback?: string;
|
||
ruleSetVersionNumber?: number;
|
||
ruleSetPublishedAt?: number;
|
||
ruleSetPublishedByName?: string;
|
||
humanResult?: string;
|
||
humanResultPath?: string;
|
||
aiDecision?: unknown;
|
||
aiSummary?: unknown;
|
||
createdAt?: string | number;
|
||
updatedAt?: string | number;
|
||
};
|
||
|
||
export type ApprovalRunsSummaryOptions = {
|
||
date: string;
|
||
timezone: string;
|
||
fetched: number;
|
||
total?: number;
|
||
};
|
||
|
||
export type RuleField = keyof ApprovalRule;
|
||
|
||
/** Render a rule timestamp in the standard Beijing ISO second precision instead of raw epoch millis. */
|
||
function standardRuleTimestamp(value: unknown): string | undefined {
|
||
if (typeof value === "number" && Number.isFinite(value) && value > 0) return formatBeijingIso(value);
|
||
if (typeof value === "string" && value.trim()) return normalizeBeijingIso(value);
|
||
return undefined;
|
||
}
|
||
|
||
export function projectApprovalRules(
|
||
data: { rules: ApprovalRule[]; hasPendingDeletes: boolean },
|
||
params: {
|
||
countOnly?: boolean;
|
||
fields?: RuleField[];
|
||
limit?: number;
|
||
offset?: number;
|
||
}
|
||
) {
|
||
const count = data.rules.length;
|
||
if (params.countOnly || params.limit === 0) {
|
||
return { count };
|
||
}
|
||
|
||
const offset = params.offset ?? 0;
|
||
const rules = data.rules.slice(offset, params.limit === undefined ? undefined : offset + params.limit);
|
||
const fields = params.fields;
|
||
|
||
return {
|
||
count,
|
||
hasPendingDeletes: data.hasPendingDeletes,
|
||
rules: fields
|
||
? rules.map((rule) => pickRuleFields(rule, fields))
|
||
: rules.map((rule) => {
|
||
const codeNum = parseRuleCodeNumber(rule.code);
|
||
const withCode = codeNum !== undefined ? { ...rule, code: formatRuleCode(codeNum) } : rule;
|
||
return {
|
||
...withCode,
|
||
createdAt: standardRuleTimestamp(rule.createdAt),
|
||
updatedAt: standardRuleTimestamp(rule.updatedAt)
|
||
};
|
||
})
|
||
};
|
||
}
|
||
|
||
export function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
|
||
const output: Partial<ApprovalRule> = {};
|
||
for (const field of fields) {
|
||
if (rule[field] !== undefined) {
|
||
if (field === "code") {
|
||
const codeNum = parseRuleCodeNumber(rule.code);
|
||
output.code = (codeNum !== undefined ? formatRuleCode(codeNum) : rule.code) as never;
|
||
} else if (field === "createdAt" || field === "updatedAt") {
|
||
output[field] = standardRuleTimestamp(rule[field]) as never;
|
||
} else {
|
||
output[field] = rule[field] as never;
|
||
}
|
||
}
|
||
}
|
||
return output;
|
||
}
|
||
|
||
export type RulePushPlan = {
|
||
created: LocalRuleItem[];
|
||
updated: Array<{ id: string; rule: LocalRuleItem; changedFields: string[] }>;
|
||
deleted: ApprovalRule[];
|
||
unchanged: Array<Pick<ApprovalRule, "id">>;
|
||
};
|
||
|
||
export function buildRulePushPlan(
|
||
remoteRules: ApprovalRule[],
|
||
localRules: LocalRuleItem[]
|
||
): RulePushPlan {
|
||
const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule]));
|
||
const usedRemoteIds = new Set<string>();
|
||
const created: LocalRuleItem[] = [];
|
||
const updated: RulePushPlan["updated"] = [];
|
||
const unchanged: RulePushPlan["unchanged"] = [];
|
||
|
||
for (const localRule of localRules) {
|
||
let remoteRule: ApprovalRule | undefined;
|
||
if (localRule.id) {
|
||
remoteRule = remoteById.get(localRule.id);
|
||
if (!remoteRule) {
|
||
throw new Error(
|
||
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
|
||
);
|
||
}
|
||
if (usedRemoteIds.has(localRule.id)) {
|
||
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
|
||
}
|
||
} else {
|
||
const matches = remoteRules.filter(
|
||
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
|
||
);
|
||
if (matches.length > 1) {
|
||
throw new Error(
|
||
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
|
||
);
|
||
}
|
||
remoteRule = matches[0];
|
||
}
|
||
|
||
if (!remoteRule) {
|
||
created.push(localRule);
|
||
continue;
|
||
}
|
||
|
||
usedRemoteIds.add(remoteRule.id);
|
||
const changedFields = ruleChangedFields(remoteRule, localRule);
|
||
if (changedFields.length) {
|
||
updated.push({ id: remoteRule.id, rule: localRule, changedFields });
|
||
} else {
|
||
unchanged.push({ id: remoteRule.id });
|
||
}
|
||
}
|
||
|
||
return {
|
||
created,
|
||
updated,
|
||
deleted: remoteRules.filter((rule) => !usedRemoteIds.has(rule.id)),
|
||
unchanged
|
||
};
|
||
}
|
||
|
||
export function rulesHaveSameContent(remoteRule: ApprovalRule, localRule: LocalRuleItem): boolean {
|
||
return remoteRule.description === localRule.description.trim() &&
|
||
remoteRule.scope === (localRule.scope ?? "ALL") &&
|
||
remoteRule.strictness === normalizeRuleStrictness(localRule.strictness);
|
||
}
|
||
|
||
export function ruleChangedFields(remoteRule: ApprovalRule, localRule: LocalRuleItem): string[] {
|
||
const changed: string[] = [];
|
||
if (remoteRule.description !== localRule.description.trim()) changed.push("description");
|
||
if (remoteRule.scope !== (localRule.scope ?? "ALL")) changed.push("scope");
|
||
if (remoteRule.strictness !== normalizeRuleStrictness(localRule.strictness)) changed.push("strictness");
|
||
return changed;
|
||
}
|
||
|
||
export function normalizeRuleStrictness(value?: string): string {
|
||
const normalized = value?.toUpperCase() ?? "MUST_FOLLOW";
|
||
if (normalized.includes("SHOULD")) return "SHOULD_FOLLOW";
|
||
if (normalized.includes("SUGGEST")) return "SUGGESTION";
|
||
return "MUST_FOLLOW";
|
||
}
|
||
|
||
export type SimulationBatchCreateInput = {
|
||
mode?: string;
|
||
sourceSystem?: string;
|
||
flowIds?: string[];
|
||
documentSn?: string | string[];
|
||
rejectNodeName?: string | null;
|
||
thinkingDepthOverride?: "default" | "medium" | "high";
|
||
skipInvoiceGeneration?: boolean;
|
||
skipExpenseExtraction?: boolean;
|
||
disableAttachmentCache?: boolean;
|
||
signKey?: string;
|
||
packageIds?: string[];
|
||
packageId?: string;
|
||
templateId?: string;
|
||
schemaConfig?: Record<string, unknown>;
|
||
approvalCode?: string;
|
||
nodeId?: string;
|
||
runMode?: string;
|
||
requestIds?: string[];
|
||
workflowTypeId?: string;
|
||
flowStatusList?: number[];
|
||
businessCodes?: string[];
|
||
documentType?: string;
|
||
formCodes?: string[];
|
||
formSubTypeBizCode?: string;
|
||
formStatus?: string;
|
||
pageNo?: number;
|
||
pageSize?: number;
|
||
startTime?: number;
|
||
endTime?: number;
|
||
status?: string[];
|
||
limit?: number;
|
||
// 预留:其他取数模式(如合思时间范围)透传参数,覆盖构建结果
|
||
rawParams?: Record<string, unknown>;
|
||
};
|
||
|
||
export function parseDurationMs(duration: string): number {
|
||
const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);
|
||
if (!match || !match[1]) return 600000;
|
||
const val = parseFloat(match[1]);
|
||
const unit = (match[2] ?? "s").toLowerCase();
|
||
switch (unit) {
|
||
case "ms": return val;
|
||
case "s": return val * 1000;
|
||
case "m": return val * 60 * 1000;
|
||
case "h": return val * 3600 * 1000;
|
||
case "d": return val * 86400 * 1000;
|
||
default: return val * 1000;
|
||
}
|
||
}
|
||
|
||
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
|
||
return Object.fromEntries(
|
||
Object.entries(integration).map(([key, value]) => [
|
||
key,
|
||
// signKey participates in the outbound callback URL as config_id, so it
|
||
// behaves like a credential: the diagnostic views mask it the same way as
|
||
// apiKey/apiSecret. The operator still receives it through the stderr
|
||
// guidance lines (`👉 Next action: ... sync <signKey>`) when they need it.
|
||
["apiKey", "apiSecret", "secret", "signKey"].includes(key) && typeof value === "string"
|
||
? "***"
|
||
: value
|
||
])
|
||
);
|
||
}
|
||
|
||
export function mutationPreview(
|
||
context: CapabilityContext,
|
||
endpoint: string,
|
||
before: unknown,
|
||
after: unknown,
|
||
impactCount: number
|
||
) {
|
||
const baseUrl = getConfiguredSealBaseUrl(context.corp).replace(/\/+$/, "");
|
||
return {
|
||
preview: true,
|
||
targetUrl: `${baseUrl}/${endpoint.replace(/^\/+/, "")}`,
|
||
changesDiff: {
|
||
before: redactPreviewValue(before),
|
||
after: redactPreviewValue(after)
|
||
},
|
||
impactCount
|
||
};
|
||
}
|
||
|
||
export function redactPreviewValue(value: unknown): unknown {
|
||
if (Array.isArray(value)) return value.map(redactPreviewValue);
|
||
if (!value || typeof value !== "object") return value;
|
||
return Object.fromEntries(
|
||
Object.entries(value).map(([key, item]) => [
|
||
key,
|
||
["apiKey", "apiSecret", "secret", "token", "password"].includes(key) && typeof item === "string"
|
||
? "***"
|
||
: redactPreviewValue(item)
|
||
])
|
||
);
|
||
}
|
||
|
||
export function buildSimulationBatchParams(input: SimulationBatchCreateInput): Record<string, unknown> {
|
||
const sourceSystem = input.sourceSystem ?? input.mode ?? "hosecloud";
|
||
const params: Record<string, unknown> = {
|
||
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
|
||
skipExpenseExtraction: input.skipExpenseExtraction ?? true,
|
||
thinkingDepthOverride: input.thinkingDepthOverride ?? "default",
|
||
disableAttachmentCache: input.disableAttachmentCache ?? false
|
||
};
|
||
|
||
const docSns = input.flowIds ?? (typeof input.documentSn === "string" ? input.documentSn.split(",").map((s) => s.trim()).filter(Boolean) : input.documentSn);
|
||
|
||
if (sourceSystem === "hosecloud") {
|
||
if (!docSns?.length && input.startTime === undefined) {
|
||
throw new Error("hosecloud 模式需要提供 flowIds(单号列表)");
|
||
}
|
||
Object.assign(params, {
|
||
dataCollectionMode: "2",
|
||
rejectNodeName: input.rejectNodeName ?? null,
|
||
sourceSystem: "hosecloud"
|
||
});
|
||
if (docSns?.length) params.flowIds = docSns;
|
||
if (input.signKey) params.signKey = input.signKey;
|
||
if (input.startTime !== undefined) params.startTime = input.startTime;
|
||
if (input.endTime !== undefined) params.endTime = input.endTime;
|
||
if (input.status) params.status = input.status;
|
||
if (input.limit) params.limit = input.limit;
|
||
} else if (sourceSystem === "material_pack" || sourceSystem === "material-pack") {
|
||
const packageIds = input.packageIds ?? (input.packageId ? [input.packageId] : undefined);
|
||
if (!packageIds?.length) {
|
||
throw new Error("material_pack 模式需要提供 packageIds(材料包 id)");
|
||
}
|
||
const templateId = input.templateId ?? (input.schemaConfig as { id?: string } | undefined)?.id;
|
||
if (!templateId) {
|
||
throw new Error("material_pack 模式需要提供 templateId(或 schemaConfig.id)");
|
||
}
|
||
Object.assign(params, {
|
||
templateId,
|
||
packageIds,
|
||
approvalCode: input.approvalCode ?? "material_pack",
|
||
nodeId: input.nodeId ?? "material_pack",
|
||
runMode: input.runMode ?? "import_and_simulate"
|
||
});
|
||
if (input.schemaConfig !== undefined) params.schemaConfig = input.schemaConfig;
|
||
} else if (sourceSystem === "weaver") {
|
||
Object.assign(params, {
|
||
sourceSystem: "weaver",
|
||
workflowTypeId: input.workflowTypeId,
|
||
requestIds: input.requestIds,
|
||
flowStatusList: input.flowStatusList,
|
||
nodeId: input.nodeId,
|
||
startTime: input.startTime,
|
||
endTime: input.endTime,
|
||
status: input.status,
|
||
limit: input.limit ?? 100,
|
||
rejectNodeName: input.rejectNodeName ?? null
|
||
});
|
||
} else if (sourceSystem === "helios") {
|
||
Object.assign(params, {
|
||
sourceSystem: "helios",
|
||
documentType: input.documentType,
|
||
businessCodes: input.businessCodes,
|
||
rejectNodeName: input.rejectNodeName ?? null
|
||
});
|
||
} else if (sourceSystem === "maycur" || sourceSystem === "maycur-standard") {
|
||
Object.assign(params, {
|
||
sourceSystem,
|
||
formCodes: input.formCodes ?? docSns,
|
||
createdAtStart: input.startTime,
|
||
createdAtEnd: input.endTime,
|
||
formSubTypeBizCode: input.formSubTypeBizCode,
|
||
formStatus: input.formStatus,
|
||
pageNo: input.pageNo ?? 1,
|
||
pageSize: input.pageSize ?? 100,
|
||
signKey: input.signKey
|
||
});
|
||
} else if (sourceSystem === "feishu") {
|
||
Object.assign(params, {
|
||
sourceSystem: "feishu",
|
||
approvalCode: input.approvalCode,
|
||
nodeId: input.nodeId,
|
||
startTime: input.startTime,
|
||
endTime: input.endTime,
|
||
status: input.status,
|
||
limit: input.limit ?? 100,
|
||
signKey: input.signKey
|
||
});
|
||
} else {
|
||
Object.assign(params, { sourceSystem });
|
||
}
|
||
|
||
if (input.rawParams) Object.assign(params, input.rawParams);
|
||
return params;
|
||
}
|
||
|
||
export function summarizeSimulationBatch(batch: SimulationBatch) {
|
||
return {
|
||
id: batch.id,
|
||
status: batch.status,
|
||
approvalCode: batch.approvalCode,
|
||
sourceSystem: batch.sourceSystem,
|
||
totalCount: batch.totalCount,
|
||
processedCount: batch.processedCount,
|
||
successCount: batch.successCount,
|
||
failedCount: batch.failedCount,
|
||
createdCount: batch.createdCount,
|
||
createFailedCount: batch.createFailedCount,
|
||
requestSummary: batch.requestSummary,
|
||
resultSummary: batch.resultSummary,
|
||
createdAt: batch.createdAt
|
||
};
|
||
}
|
||
|
||
const REUSE_BLOCKED_BATCH_STATUSES = new Set(["failed", "cancelled", "canceled"]);
|
||
|
||
export type SimulationBatchReuseKey = {
|
||
flowIds?: string[];
|
||
packageIds?: string[];
|
||
signKey?: string;
|
||
};
|
||
|
||
function normalizedIdSet(ids?: string[]): string[] | undefined {
|
||
const cleaned = (ids ?? []).map((id) => id.trim()).filter(Boolean);
|
||
return cleaned.length ? [...new Set(cleaned)].sort() : undefined;
|
||
}
|
||
|
||
function sameIdSet(left?: string[], right?: string[]): boolean {
|
||
const leftSet = normalizedIdSet(left);
|
||
const rightSet = normalizedIdSet(right);
|
||
if (!leftSet || !rightSet) return false;
|
||
return leftSet.length === rightSet.length && leftSet.every((id, index) => id === rightSet[index]);
|
||
}
|
||
|
||
export function simulationBatchCreatedAtMs(batch: SimulationBatch): number | null {
|
||
const raw = batch.createdAt;
|
||
if (raw === undefined) return null;
|
||
const ms = typeof raw === "number" ? raw : Date.parse(raw);
|
||
return Number.isFinite(ms) && ms > 0 ? ms : null;
|
||
}
|
||
|
||
// 幂等复用: 同一组单号/材料包在时间窗内已有非失败终态的批次则复用, 防止 agent 打断后重发导致同一笔单重复扣费
|
||
export function findReusableSimulationBatch(
|
||
batches: SimulationBatch[],
|
||
key: SimulationBatchReuseKey,
|
||
windowMs: number,
|
||
nowMs: number = Date.now()
|
||
): SimulationBatch | null {
|
||
const flowIds = normalizedIdSet(key.flowIds);
|
||
const packageIds = normalizedIdSet(key.packageIds);
|
||
if (!flowIds && !packageIds) return null;
|
||
|
||
return batches.find((batch) => {
|
||
if (REUSE_BLOCKED_BATCH_STATUSES.has((batch.status ?? "").toLowerCase())) return false;
|
||
const createdAtMs = simulationBatchCreatedAtMs(batch);
|
||
if (createdAtMs === null) return false;
|
||
const ageMs = nowMs - createdAtMs;
|
||
if (ageMs < 0 || ageMs > windowMs) return false;
|
||
if (flowIds && !sameIdSet(batch.params?.flowIds, flowIds)) return false;
|
||
if (packageIds && !sameIdSet(batch.params?.packageIds, packageIds)) return false;
|
||
if (key.signKey && batch.params?.signKey && batch.params.signKey !== key.signKey) return false;
|
||
return true;
|
||
}) ?? null;
|
||
}
|
||
|
||
export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
|
||
const sourceDocumentSN = record.sourceDocumentSN;
|
||
const humanResult = extractHumanResult(record);
|
||
const ai = summarizeApprovalRunResult(record);
|
||
|
||
return {
|
||
id: record.id,
|
||
tenantId: record.tenantId,
|
||
agentId: record.agentId,
|
||
status: record.status,
|
||
taskMode: record.taskMode,
|
||
finalExecutionMode: record.finalExecutionMode,
|
||
sourceSystem: record.sourceSystem,
|
||
sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
documentId: record.documentId,
|
||
simulationBatchId: record.sourceExtendData?.simulation_batch_id,
|
||
langfuseTraceId: record.sourceExtendData?._langfuseTraceId,
|
||
langfuseSessionFallback: sourceDocumentSN ? `hosecloud-${sourceDocumentSN}` : undefined,
|
||
ruleSetVersionNumber: record.ruleSetVersionNumber,
|
||
ruleSetPublishedAt: record.ruleSetPublishedAt,
|
||
ruleSetPublishedByName: record.ruleSetPublishedByName,
|
||
humanResult: humanResult?.value,
|
||
humanResultPath: humanResult?.path,
|
||
aiDecision: ai.decision,
|
||
aiSummary: ai.summary,
|
||
createdAt: record.createdAt,
|
||
updatedAt: record.updatedAt
|
||
};
|
||
}
|
||
|
||
export function summarizeApprovalRuns(records: ApprovalRun[], options: ApprovalRunsSummaryOptions) {
|
||
return {
|
||
date: options.date,
|
||
timezone: options.timezone,
|
||
fetched: options.fetched,
|
||
matched: records.length,
|
||
total: options.total,
|
||
statusCounts: countBy(records, (record) => record.status ?? "unknown"),
|
||
taskModeCounts: countBy(records, (record) => record.taskMode ?? "unknown"),
|
||
records: records.map((record) => {
|
||
const summary = summarizeApprovalRun(record);
|
||
return {
|
||
createdAt: formatLocalDateTime(summary.createdAt, options.timezone),
|
||
sourceDocumentSN: summary.sourceDocumentSN,
|
||
sourceDocumentId: summary.sourceDocumentId,
|
||
status: summary.status,
|
||
taskMode: summary.taskMode,
|
||
finalExecutionMode: summary.finalExecutionMode,
|
||
simulationBatchId: summary.simulationBatchId,
|
||
langfuseTraceId: summary.langfuseTraceId,
|
||
langfuseSessionFallback: summary.langfuseSessionFallback,
|
||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||
ruleSetPublishedAt: formatLocalDateTime(summary.ruleSetPublishedAt, options.timezone),
|
||
ruleSetPublishedByName: summary.ruleSetPublishedByName,
|
||
humanResult: summary.humanResult,
|
||
humanResultPath: summary.humanResultPath,
|
||
recordId: summary.id
|
||
};
|
||
})
|
||
};
|
||
}
|
||
|
||
export function parseFieldPaths(fields: string | string[] | undefined): string[] {
|
||
if (!fields) return [];
|
||
const raw = Array.isArray(fields) ? fields : fields.split(",");
|
||
return raw.map((field) => field.trim()).filter(Boolean);
|
||
}
|
||
|
||
export function pickRunFields(record: Record<string, unknown>, fields: readonly string[]) {
|
||
const output: Record<string, unknown> = {};
|
||
for (const field of fields) {
|
||
if (field === "metadata") {
|
||
output.metadata = approvalRunMetadata(record as ApprovalRun);
|
||
continue;
|
||
}
|
||
const value = getPath(record, field);
|
||
if (value !== undefined) setPath(output, field, value);
|
||
}
|
||
return output;
|
||
}
|
||
|
||
export function approvalRunMetadata(record: ApprovalRun) {
|
||
const summary = summarizeApprovalRun(record);
|
||
return {
|
||
recordId: summary.id,
|
||
tenantId: summary.tenantId,
|
||
agentId: summary.agentId,
|
||
sourceSystem: summary.sourceSystem,
|
||
sourceDocumentSN: summary.sourceDocumentSN,
|
||
sourceDocumentId: summary.sourceDocumentId,
|
||
documentId: summary.documentId,
|
||
status: summary.status,
|
||
taskMode: summary.taskMode,
|
||
finalExecutionMode: summary.finalExecutionMode,
|
||
simulationBatchId: summary.simulationBatchId,
|
||
langfuseTraceId: summary.langfuseTraceId,
|
||
langfuseSessionFallback: summary.langfuseSessionFallback,
|
||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||
ruleSetPublishedAt: summary.ruleSetPublishedAt,
|
||
ruleSetPublishedByName: summary.ruleSetPublishedByName,
|
||
createdAt: summary.createdAt,
|
||
updatedAt: summary.updatedAt
|
||
};
|
||
}
|
||
|
||
export function summarizeApprovalRunDetail(record: ApprovalRun) {
|
||
return {
|
||
metadata: approvalRunMetadata(record),
|
||
document: summarizeApprovalRunDocument(record).document,
|
||
aiResult: summarizeApprovalRunResult(record),
|
||
manualResult: extractHumanResult(record)?.value,
|
||
manualResultPath: extractHumanResult(record)?.path,
|
||
ruleSetVersionNumber: record.ruleSetVersionNumber,
|
||
ruleSetPublishedAt: record.ruleSetPublishedAt,
|
||
ruleSetPublishedByName: record.ruleSetPublishedByName
|
||
};
|
||
}
|
||
|
||
export function summarizeApprovalRunResult(record: ApprovalRun) {
|
||
const result = asRecord(record.result);
|
||
return {
|
||
recordId: record.id,
|
||
sourceDocumentSN: record.sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
traceId: record.sourceExtendData?._langfuseTraceId,
|
||
langfuseTraceId: record.sourceExtendData?._langfuseTraceId,
|
||
decision: firstPath(result, [
|
||
"decision",
|
||
"manualApproval.decision",
|
||
"manualApproval.result",
|
||
"review.decision",
|
||
"finalDecision"
|
||
]),
|
||
summary: firstPath(result, [
|
||
"summary",
|
||
"result.summary",
|
||
"review.summary",
|
||
"conclusion"
|
||
]),
|
||
riskPointCount: countPathCandidates(result, [
|
||
"riskPoints",
|
||
"risks",
|
||
"risk_points",
|
||
"review.riskPoints"
|
||
]),
|
||
matchedRuleCount: countPathCandidates(result, [
|
||
"matchedRules",
|
||
"hitRules",
|
||
"ruleResults",
|
||
"rules",
|
||
"review.matchedRules"
|
||
])
|
||
};
|
||
}
|
||
|
||
export function prioritizeKeyFields(fields: Array<Record<string, unknown>>, maxCount = 60) {
|
||
const priorityKeywords = ["金额", "费用", "报销", "申请", "借款", "付款", "部门", "事由", "收款", "公司", "抬头", "税", "类别", "项目", "说明", "币种"];
|
||
const prioritized: Array<Record<string, unknown>> = [];
|
||
const others: Array<Record<string, unknown>> = [];
|
||
|
||
for (const field of fields) {
|
||
const label = stringFromUnknown(field.label) ?? "";
|
||
const path = stringFromUnknown(field.path) ?? "";
|
||
const isPriority = priorityKeywords.some((k) => label.includes(k) || path.toLowerCase().includes(k.toLowerCase()));
|
||
if (isPriority) {
|
||
prioritized.push(field);
|
||
} else {
|
||
others.push(field);
|
||
}
|
||
}
|
||
|
||
return [...prioritized, ...others].slice(0, maxCount);
|
||
}
|
||
|
||
export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||
const document = asRecord(record.document);
|
||
const fields = flattenDocumentFields(record.document);
|
||
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
|
||
const prioritizedFields = prioritizeKeyFields(fields, 60);
|
||
return {
|
||
recordId: record.id,
|
||
sourceDocumentSN: record.sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
document: compactObject({
|
||
id: document?.id,
|
||
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
||
title: document?.title ?? document?.name,
|
||
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
|
||
amount:
|
||
firstByLabel(fields, [
|
||
"金额",
|
||
"报销金额",
|
||
"付款金额",
|
||
"申请金额",
|
||
"借款金额",
|
||
"实报金额",
|
||
"总金额",
|
||
"费用金额",
|
||
"单据金额",
|
||
"合计",
|
||
"价税合计",
|
||
"明细合计",
|
||
"总计"
|
||
]) ??
|
||
firstPath(document, ["amount", "totalAmount", "expenseAmount", "applyAmount", "paymentAmount"]) ??
|
||
fields.find((f) => {
|
||
const path = stringFromUnknown(f.path)?.toLowerCase() ?? "";
|
||
return path.endsWith(".amount") || path.endsWith(".totalamount");
|
||
})?.value,
|
||
expenseType:
|
||
firstByLabel(fields, [
|
||
"费用类型",
|
||
"费用类别",
|
||
"报销类型",
|
||
"报销类别",
|
||
"支出类别",
|
||
"费用科目",
|
||
"单据类型",
|
||
"业务类型"
|
||
]) ??
|
||
firstPath(document, ["expenseType", "expenseCategory", "categoryName", "businessType"]),
|
||
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
|
||
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
|
||
keyFields: prioritizedFields,
|
||
totalFieldsCount: fields.length,
|
||
fieldsTruncated: fields.length > prioritizedFields.length
|
||
}),
|
||
invoices: collectInvoiceSummary(record),
|
||
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
|
||
aiResult: summarizeApprovalRunResult(record),
|
||
manualResult: extractHumanResult(record)?.value,
|
||
hints: compactObject({
|
||
amountMentions: findKeywordLines(fieldText, ["金额", "合计", "税率"], 8),
|
||
partyMentions: findKeywordLines(fieldText, ["买方", "卖方", "甲方", "乙方", "收款"], 8)
|
||
})
|
||
};
|
||
}
|
||
|
||
export function extractCitedRules(record: ApprovalRun, corp?: CorpConfig | string) {
|
||
const candidates: Array<[string, unknown]> = [
|
||
["result.rulesResult", getPath(record, "result.rulesResult")],
|
||
["result.hitRules", getPath(record, "result.hitRules")],
|
||
["result.citedRules", getPath(record, "result.citedRules")],
|
||
["result.matchedRules", getPath(record, "result.matchedRules")],
|
||
["result.ruleResults", getPath(record, "result.ruleResults")],
|
||
["result.rules", getPath(record, "result.rules")],
|
||
["pipelineData.citedRules", getPath(record, "pipelineData.citedRules")],
|
||
["pipelineData.matchedRules", getPath(record, "pipelineData.matchedRules")]
|
||
];
|
||
const rules: Array<Record<string, unknown>> = [];
|
||
const byIdentity = new Map<string, Record<string, unknown>>();
|
||
const seen = new Set<string>();
|
||
|
||
for (const [path, value] of candidates) {
|
||
const items = Array.isArray(value)
|
||
? value
|
||
: value && typeof value === "object"
|
||
? Object.values(value as Record<string, unknown>)
|
||
: [];
|
||
items.forEach((item, index) => {
|
||
const object = asRecord(item);
|
||
if (!object) return;
|
||
const rawRuntimeId =
|
||
stringFromUnknown(object.runtimeRuleId) ??
|
||
stringFromUnknown(object.runtimeId) ??
|
||
stringFromUnknown(object.id) ??
|
||
stringFromUnknown(object.ruleId);
|
||
const rawCode = object.ruleCode ?? object.code;
|
||
const codeNum = parseRuleCodeNumber(rawCode ?? rawRuntimeId);
|
||
const runtimeRuleId =
|
||
rawRuntimeId ?? (codeNum !== undefined ? `rule-${codeNum}` : undefined);
|
||
const ruleCode =
|
||
(codeNum !== undefined ? formatRuleCode(codeNum) : undefined) ??
|
||
stringFromUnknown(object.ruleCode) ??
|
||
stringFromUnknown(object.code) ??
|
||
(runtimeRuleId ? runtimeRuleIdToCode(runtimeRuleId) : undefined);
|
||
const output = compactObject({
|
||
code: ruleCode,
|
||
runtimeRuleId,
|
||
ruleCode,
|
||
versionNumber: numberFromUnknown(object.versionNumber) ?? record.ruleSetVersionNumber,
|
||
description: stringFromUnknown(object.description),
|
||
scope: stringFromUnknown(object.scope),
|
||
strictness: stringFromUnknown(object.strictness),
|
||
ruleIntent: stringFromUnknown(object.ruleIntent),
|
||
appliedAnalysis: object.appliedAnalysis ?? object.analysis ?? object.reasoning,
|
||
checkResult: object.checkResult ?? object.result ?? object.decision,
|
||
findings: object.findings ?? object.riskPoints ?? object.evidence,
|
||
sourcePath: `${path}.${index}`
|
||
});
|
||
const identityKey = runtimeRuleId ?? ruleCode;
|
||
if (identityKey) {
|
||
const existing = byIdentity.get(identityKey);
|
||
if (existing) {
|
||
for (const [k, v] of Object.entries(output)) {
|
||
if (existing[k] === undefined && v !== undefined) {
|
||
existing[k] = v;
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
byIdentity.set(identityKey, output);
|
||
rules.push(output);
|
||
return;
|
||
}
|
||
const key = JSON.stringify(output);
|
||
if (!seen.has(key)) {
|
||
seen.add(key);
|
||
rules.push(output);
|
||
}
|
||
});
|
||
}
|
||
|
||
const corpId = typeof corp === "string" ? corp : corp?.id;
|
||
if (corpId) {
|
||
try {
|
||
const snapshot = loadRuleMappingSnapshot(corpId, record.ruleSetVersionNumber ?? "latest");
|
||
if (snapshot && snapshot.ruleMapping) {
|
||
for (const rule of rules) {
|
||
const ruleCode = stringFromUnknown(rule.code);
|
||
const runtimeRuleId = stringFromUnknown(rule.runtimeRuleId);
|
||
const codeNum = parseRuleCodeNumber(ruleCode ?? runtimeRuleId);
|
||
const matchedItem = snapshot.ruleMapping.find((m) => {
|
||
if (ruleCode && (String(m.targetRuleCode) === ruleCode || m.targetRuleCode === ruleCode)) return true;
|
||
if (runtimeRuleId && (m.targetRuleId === runtimeRuleId || `rule-${m.targetRuleCode}` === runtimeRuleId)) return true;
|
||
if (codeNum !== undefined) {
|
||
const targetNum = parseRuleCodeNumber(m.targetRuleCode);
|
||
if (targetNum !== undefined && targetNum === codeNum) return true;
|
||
}
|
||
return false;
|
||
});
|
||
if (matchedItem) {
|
||
const mappedCodeNum = parseRuleCodeNumber(matchedItem.sourceRuleCode);
|
||
rule.mappedProdCode = mappedCodeNum !== undefined ? formatRuleCode(mappedCodeNum) : String(matchedItem.sourceRuleCode);
|
||
rule.mappedProdRuleId = matchedItem.sourceRuleId;
|
||
rule.mappingNote = `测试规则 ${ruleCode ?? runtimeRuleId} 对应生产规则 ${rule.mappedProdCode}`;
|
||
}
|
||
}
|
||
}
|
||
} catch {}
|
||
}
|
||
|
||
return {
|
||
recordId: record.id,
|
||
sourceDocumentSN: record.sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
ruleSetVersionNumber: record.ruleSetVersionNumber,
|
||
count: rules.length,
|
||
rules
|
||
};
|
||
}
|
||
|
||
export function firstPath(object: Record<string, unknown> | undefined, paths: readonly string[]) {
|
||
if (!object) return undefined;
|
||
for (const path of paths) {
|
||
const value = getPath(object, path);
|
||
if (value !== undefined) return value;
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
export function countPathCandidates(object: Record<string, unknown> | undefined, paths: readonly string[]) {
|
||
if (!object) return 0;
|
||
for (const path of paths) {
|
||
const value = getPath(object, path);
|
||
if (Array.isArray(value)) return value.length;
|
||
if (value && typeof value === "object") return Object.keys(value).length;
|
||
if (typeof value === "number") return value;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
export function getPath(value: unknown, path: string): unknown {
|
||
return path.split(".").reduce<unknown>((current, segment) => {
|
||
if (current === undefined || current === null) return undefined;
|
||
if (Array.isArray(current)) {
|
||
const index = Number(segment);
|
||
return Number.isInteger(index) ? current[index] : undefined;
|
||
}
|
||
if (typeof current === "object") {
|
||
return (current as Record<string, unknown>)[segment];
|
||
}
|
||
return undefined;
|
||
}, value);
|
||
}
|
||
|
||
export function setPath(target: Record<string, unknown>, path: string, value: unknown) {
|
||
const segments = path.split(".");
|
||
let current = target;
|
||
for (const segment of segments.slice(0, -1)) {
|
||
const existing = current[segment];
|
||
if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
|
||
current[segment] = {};
|
||
}
|
||
current = current[segment] as Record<string, unknown>;
|
||
}
|
||
current[segments[segments.length - 1] ?? path] = value;
|
||
}
|
||
|
||
export function compactObject(object: Record<string, unknown>) {
|
||
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
|
||
}
|
||
|
||
export function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||
return value && typeof value === "object" && !Array.isArray(value)
|
||
? value as Record<string, unknown>
|
||
: undefined;
|
||
}
|
||
|
||
export function numberFromUnknown(value: unknown): number | undefined {
|
||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||
}
|
||
|
||
export function flattenDocumentFields(value: unknown) {
|
||
const fields: Array<Record<string, unknown>> = [];
|
||
collectDocumentFields(value, "document", fields);
|
||
return fields;
|
||
}
|
||
|
||
export function collectDocumentFields(value: unknown, path: string, output: Array<Record<string, unknown>>) {
|
||
if (Array.isArray(value)) {
|
||
value.forEach((item, index) => collectDocumentFields(item, `${path}.${index}`, output));
|
||
return;
|
||
}
|
||
|
||
const object = asRecord(value);
|
||
if (!object) return;
|
||
|
||
const label = stringFromUnknown(object.label) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.title) ?? stringFromUnknown(object.fieldName);
|
||
const rawValue = object.value ?? object.displayValue ?? object.text ?? object.content;
|
||
if (label && rawValue !== undefined && typeof rawValue !== "object") {
|
||
output.push(compactObject({
|
||
path,
|
||
label,
|
||
value: rawValue,
|
||
type: stringFromUnknown(object.type) ?? stringFromUnknown(object.fieldType)
|
||
}));
|
||
}
|
||
|
||
for (const [key, child] of Object.entries(object)) {
|
||
if (key === "attachments") continue;
|
||
collectDocumentFields(child, `${path}.${key}`, output);
|
||
}
|
||
}
|
||
|
||
export function firstByLabel(fields: Array<Record<string, unknown>>, labels: string[]) {
|
||
const hit = fields.find((field) => {
|
||
const label = stringFromUnknown(field.label) ?? "";
|
||
return labels.some((item) => label.includes(item));
|
||
});
|
||
return hit?.value;
|
||
}
|
||
|
||
export function collectInvoiceSummary(record: ApprovalRun) {
|
||
const invoices: Array<Record<string, unknown>> = [];
|
||
collectInvoiceObjects(record.result, "result", invoices);
|
||
collectInvoiceObjects(record.document, "document", invoices);
|
||
return invoices.slice(0, 20);
|
||
}
|
||
|
||
export function collectInvoiceObjects(value: unknown, path: string, output: Array<Record<string, unknown>>) {
|
||
if (Array.isArray(value)) {
|
||
value.forEach((item, index) => collectInvoiceObjects(item, `${path}.${index}`, output));
|
||
return;
|
||
}
|
||
const object = asRecord(value);
|
||
if (!object) return;
|
||
if (/invoice|发票/i.test(path)) {
|
||
output.push(compactObject({
|
||
path,
|
||
fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name),
|
||
buyer: object.buyer ?? object.buyerName ?? object.purchaserName,
|
||
seller: object.seller ?? object.sellerName,
|
||
amount: object.amount ?? object.totalAmount ?? object.total,
|
||
taxRate: object.taxRate,
|
||
category: object.category ?? object.type
|
||
}));
|
||
}
|
||
for (const [key, child] of Object.entries(object)) {
|
||
collectInvoiceObjects(child, `${path}.${key}`, output);
|
||
}
|
||
}
|
||
|
||
export function findKeywordLines(text: string, keywords: string[], limit: number) {
|
||
return text
|
||
.split(/\r?\n/)
|
||
.filter((line) => keywords.some((keyword) => line.includes(keyword)))
|
||
.slice(0, limit);
|
||
}
|
||
|
||
export function summarizeRunBridge(records: ApprovalRun[]) {
|
||
return records.map((record) => {
|
||
const summary = summarizeApprovalRun(record);
|
||
const resolution = summary.langfuseTraceId
|
||
? "trace"
|
||
: summary.langfuseSessionFallback
|
||
? "session-fallback"
|
||
: "unresolved";
|
||
return {
|
||
recordId: summary.id,
|
||
tenantId: summary.tenantId,
|
||
agentId: summary.agentId,
|
||
sourceDocumentSN: summary.sourceDocumentSN,
|
||
sourceDocumentId: summary.sourceDocumentId,
|
||
simulationBatchId: summary.simulationBatchId,
|
||
langfuseTraceId: summary.langfuseTraceId,
|
||
langfuseSessionFallback: summary.langfuseSessionFallback,
|
||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||
ruleSetPublishedAt: summary.ruleSetPublishedAt,
|
||
ruleSetPublishedByName: summary.ruleSetPublishedByName,
|
||
resolution,
|
||
// Ready-to-run handoff into the built-in read-only Langfuse domain.
|
||
...(summary.langfuseTraceId
|
||
? { next: `seal-use langfuse outline ${summary.langfuseTraceId} --include-io-preview` }
|
||
: summary.langfuseSessionFallback
|
||
? { next: `seal-use langfuse session ${summary.langfuseSessionFallback}` }
|
||
: {})
|
||
};
|
||
});
|
||
}
|
||
|
||
export function summarizeRuleVersion(version: RuleSetVersion) {
|
||
return {
|
||
id: version.id,
|
||
tenantId: version.tenantId,
|
||
versionNumber: version.versionNumber,
|
||
versionName: version.versionName,
|
||
publishedBy: version.publishedBy,
|
||
publishedByName: version.publishedByName,
|
||
rulesCount: version.rules.length,
|
||
publishedAt: standardRuleTimestamp(version.publishedAt),
|
||
createdAt: standardRuleTimestamp(version.createdAt)
|
||
};
|
||
}
|
||
|
||
export async function resolveRuleVersionForLookup(
|
||
client: KyInstance,
|
||
params: { versionId?: string; versionNumber?: number; latest?: boolean; recordId?: string }
|
||
) {
|
||
if (params.recordId && !params.versionId && !params.versionNumber && !params.latest) {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
if (!record.ruleSetVersionNumber) {
|
||
throw new Error(`Approval run ${params.recordId} has no ruleSetVersionNumber`);
|
||
}
|
||
return resolveRuleVersion(client, { versionNumber: record.ruleSetVersionNumber });
|
||
}
|
||
return resolveRuleVersion(client, params);
|
||
}
|
||
|
||
export function findRuleInDraft(
|
||
rules: ApprovalRule[],
|
||
selector: { code?: string; runtimeId?: string; ruleId?: string }
|
||
) {
|
||
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
|
||
if (!rawTarget || !rawTarget.trim()) {
|
||
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
|
||
}
|
||
const trimmed = rawTarget.trim();
|
||
const targetCodeNum = parseRuleCodeNumber(trimmed);
|
||
|
||
const rule = rules.find((item) => {
|
||
if (item.id === trimmed) return true;
|
||
if (targetCodeNum !== undefined) {
|
||
const itemCodeNum = parseRuleCodeNumber(item.code);
|
||
if (itemCodeNum !== undefined && itemCodeNum === targetCodeNum) return true;
|
||
}
|
||
return false;
|
||
});
|
||
if (!rule) return undefined;
|
||
|
||
const codeNum = parseRuleCodeNumber(rule.code);
|
||
const formattedCode = codeNum !== undefined ? formatRuleCode(codeNum) : normalizeRuleCode(rule.code);
|
||
return compactObject({
|
||
id: rule.id,
|
||
code: formattedCode ?? rule.code,
|
||
ruleCode: formattedCode,
|
||
runtimeRuleId: codeNum !== undefined ? `rule-${codeNum}` : undefined,
|
||
description: rule.description,
|
||
scope: rule.scope,
|
||
strictness: rule.strictness,
|
||
status: rule.status,
|
||
createdAt: standardRuleTimestamp(rule.createdAt),
|
||
updatedAt: standardRuleTimestamp(rule.updatedAt)
|
||
});
|
||
}
|
||
|
||
export function findRuleInVersion(
|
||
version: RuleSetVersion,
|
||
selector: { code?: string; runtimeId?: string; ruleId?: string },
|
||
draftRules?: ApprovalRule[]
|
||
) {
|
||
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
|
||
if (!rawTarget || !rawTarget.trim()) {
|
||
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
|
||
}
|
||
const trimmed = rawTarget.trim();
|
||
const targetCodeNum = parseRuleCodeNumber(trimmed);
|
||
const normalizedTarget = normalizeRuleCode(trimmed);
|
||
|
||
const rule = version.rules.find((item) => {
|
||
const object = item as Record<string, unknown>;
|
||
const itemId = stringFromUnknown(object.id) ?? stringFromUnknown(object.ruleId) ?? stringFromUnknown(object.stableId);
|
||
if (itemId && itemId === trimmed) return true;
|
||
const rawItemCode = object.code ?? object.ruleCode ?? object.runtimeRuleId ?? object.runtimeId;
|
||
const itemCodeNum = parseRuleCodeNumber(rawItemCode);
|
||
if (targetCodeNum !== undefined && itemCodeNum !== undefined) {
|
||
return itemCodeNum === targetCodeNum;
|
||
}
|
||
const itemCode = normalizeRuleCode(rawItemCode);
|
||
return Boolean(itemCode && normalizedTarget && itemCode === normalizedTarget);
|
||
});
|
||
if (!rule) return undefined;
|
||
|
||
const object = rule as Record<string, unknown>;
|
||
const rawItemCode = object.code ?? object.ruleCode ?? object.runtimeRuleId ?? object.runtimeId;
|
||
const codeNum = parseRuleCodeNumber(rawItemCode);
|
||
const matchedDraft = draftRules?.find((d) => {
|
||
if (codeNum !== undefined && parseRuleCodeNumber(d.code) === codeNum) return true;
|
||
return d.description === rule.description && d.scope === rule.scope && d.strictness === rule.strictness;
|
||
});
|
||
const resolvedId =
|
||
stringFromUnknown(object.id) ??
|
||
stringFromUnknown(object.ruleId) ??
|
||
stringFromUnknown(object.stableId) ??
|
||
matchedDraft?.id;
|
||
|
||
const formattedCode =
|
||
codeNum !== undefined
|
||
? formatRuleCode(codeNum)
|
||
: normalizeRuleCode(rawItemCode);
|
||
|
||
return compactObject({
|
||
id: resolvedId,
|
||
code: formattedCode ?? rawItemCode,
|
||
runtimeRuleId:
|
||
stringFromUnknown(object.runtimeRuleId) ??
|
||
(codeNum !== undefined ? `rule-${codeNum}` : stringFromUnknown(object.code)),
|
||
ruleCode: formattedCode,
|
||
versionId: version.id,
|
||
versionNumber: version.versionNumber,
|
||
versionName: version.versionName,
|
||
publishedAt: standardRuleTimestamp(version.publishedAt),
|
||
publishedByName: version.publishedByName,
|
||
description: rule.description,
|
||
scope: rule.scope,
|
||
strictness: rule.strictness,
|
||
status: stringFromUnknown(object.status) ?? matchedDraft?.status
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Resolve the cross-environment rule code from the latest sync-test mapping snapshot, when one
|
||
* exists. Mapping snapshots are saved under the test (target) corp id, so a test corp reads its own
|
||
* snapshot directly while a production corp reads the snapshot of its bound test tenant.
|
||
*/
|
||
export function resolveCrossEnvRuleMapping(
|
||
corp: CorpConfig,
|
||
rule: { code?: unknown; id?: unknown }
|
||
): {
|
||
environment: "production" | "test";
|
||
code: string;
|
||
direction: "prodToTest" | "testToProd";
|
||
syncedAt: string;
|
||
} | undefined {
|
||
const codeNum = parseRuleCodeNumber(rule.code);
|
||
const ruleId = stringFromUnknown(rule.id);
|
||
if (codeNum === undefined && !ruleId) return undefined;
|
||
const direction = corp.environment === "test" ? "testToProd" : "prodToTest";
|
||
const snapshot = corp.environment === "test"
|
||
? loadRuleMappingSnapshot(corp.id)
|
||
: corp.testCorpId
|
||
? loadRuleMappingSnapshot(corp.testCorpId)
|
||
: null;
|
||
if (!snapshot) return undefined;
|
||
const item = snapshot.ruleMapping.find((mapping) => {
|
||
if (direction === "prodToTest") {
|
||
return (codeNum !== undefined && parseRuleCodeNumber(mapping.sourceRuleCode) === codeNum)
|
||
|| (ruleId !== undefined && mapping.sourceRuleId === ruleId);
|
||
}
|
||
return (codeNum !== undefined && parseRuleCodeNumber(mapping.targetRuleCode) === codeNum)
|
||
|| (ruleId !== undefined && mapping.targetRuleId === ruleId);
|
||
});
|
||
if (!item) return undefined;
|
||
const crossCode = direction === "prodToTest" ? item.targetRuleCode : item.sourceRuleCode;
|
||
const crossCodeNum = parseRuleCodeNumber(crossCode);
|
||
return {
|
||
environment: direction === "prodToTest" ? "test" : "production",
|
||
code: crossCodeNum !== undefined ? formatRuleCode(crossCodeNum) : String(crossCode),
|
||
direction,
|
||
syncedAt: snapshot.syncedAt
|
||
};
|
||
}
|
||
|
||
export function parseRuleCodeNumber(value: unknown): number | undefined {
|
||
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
|
||
return value;
|
||
}
|
||
if (typeof value !== "string") return undefined;
|
||
const trimmed = value.trim();
|
||
const match = trimmed.match(/^(?:#|rule[-_:]?)?(\d+)$/i);
|
||
if (!match?.[1]) return undefined;
|
||
const num = Number(match[1]);
|
||
return Number.isInteger(num) && num >= 0 ? num : undefined;
|
||
}
|
||
|
||
export function normalizeRuleCode(value?: unknown) {
|
||
const codeNum = parseRuleCodeNumber(value);
|
||
if (codeNum !== undefined) return formatRuleCode(codeNum);
|
||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||
}
|
||
|
||
export function runtimeRuleIndex(value?: unknown) {
|
||
return parseRuleCodeNumber(value);
|
||
}
|
||
|
||
export function runtimeRuleIdToCode(value: string) {
|
||
const index = parseRuleCodeNumber(value);
|
||
return index !== undefined ? formatRuleCode(index) : undefined;
|
||
}
|
||
|
||
export function formatRuleCode(value: number) {
|
||
return String(value).padStart(4, "0");
|
||
}
|
||
|
||
export function pickApprovalRunCandidate(record: ApprovalRun, fields: string[]) {
|
||
const summary = summarizeApprovalRun(record);
|
||
const candidate = {
|
||
recordId: summary.id,
|
||
sourceDocumentSN: summary.sourceDocumentSN,
|
||
sourceDocumentId: summary.sourceDocumentId,
|
||
simulationBatchId: summary.simulationBatchId,
|
||
status: summary.status,
|
||
taskMode: summary.taskMode,
|
||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||
langfuseTraceId: summary.langfuseTraceId,
|
||
manualResult: summary.humanResult,
|
||
aiDecision: summary.aiDecision,
|
||
aiSummary: summary.aiSummary,
|
||
createdAt: summary.createdAt
|
||
};
|
||
if (fields.length === 0) return candidate;
|
||
return pickRunFields(candidate, fields);
|
||
}
|
||
|
||
export async function resolveApprovalRunForUrl(
|
||
client: KyInstance,
|
||
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string }
|
||
): Promise<ApprovalRun> {
|
||
if (params.recordId) {
|
||
return api.getApprovalRun(client, params.recordId);
|
||
}
|
||
|
||
const data = await api.listApprovalRuns(client, {
|
||
limit: 1,
|
||
search: params.sourceDocumentSN ?? params.sourceDocumentId,
|
||
sourceDocumentSN: params.sourceDocumentSN,
|
||
sourceDocumentId: params.sourceDocumentId
|
||
});
|
||
const record = data.records[0];
|
||
if (!record) {
|
||
const lookup = params.sourceDocumentSN
|
||
? `sourceDocumentSN ${params.sourceDocumentSN}`
|
||
: `sourceDocumentId ${params.sourceDocumentId}`;
|
||
throw new Error(`Approval run not found for ${lookup}`);
|
||
}
|
||
|
||
return api.getApprovalRun(client, record.id);
|
||
}
|
||
|
||
export function resolveSealBaseUrl(corp: CorpConfig): string {
|
||
if (corp.seal?.url) return corp.seal.url.replace(/\/+$/, "");
|
||
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source).replace(/\/+$/, "");
|
||
if ("sealUrl" in corp.source && typeof corp.source.sealUrl === "string" && corp.source.sealUrl) {
|
||
return corp.source.sealUrl.replace(/\/+$/, "");
|
||
}
|
||
return `https://${corp.id.toLowerCase()}.sealai.cc`;
|
||
}
|
||
|
||
export function normalizeUrl(value: string): string {
|
||
return value.replace(/\/+$/, "");
|
||
}
|
||
|
||
export function stringFromUnknown(value: unknown): string | undefined {
|
||
return typeof value === "string" && value.trim() ? value : undefined;
|
||
}
|
||
|
||
export async function pickApprovalRuns(
|
||
client: KyInstance,
|
||
params: { query: string; sn?: string; batchId?: string; latest?: boolean; limit: number; maxScan: number }
|
||
) {
|
||
const pageSize = Math.min(100, Math.max(params.limit, 20));
|
||
const records: ApprovalRun[] = [];
|
||
let total: number | undefined;
|
||
let scanned = 0;
|
||
|
||
while (scanned < params.maxScan && records.length < params.limit) {
|
||
const data = await api.listApprovalRuns(client, {
|
||
offset: scanned,
|
||
limit: Math.min(pageSize, params.maxScan - scanned),
|
||
search: params.sn ?? params.query,
|
||
sourceDocumentSN: params.sn
|
||
});
|
||
|
||
total = data.total;
|
||
scanned += data.records.length;
|
||
const filtered = filterRuns(data.records, params.query)
|
||
.filter((record) => !params.sn || record.sourceDocumentSN === params.sn)
|
||
.filter((record) => !params.batchId || record.sourceExtendData?.simulation_batch_id === params.batchId);
|
||
records.push(...filtered);
|
||
|
||
if (data.records.length === 0 || (total !== undefined && scanned >= total)) break;
|
||
|
||
}
|
||
|
||
records.sort((left, right) => timestampOf(right.createdAt) - timestampOf(left.createdAt));
|
||
|
||
return {
|
||
total,
|
||
scanned,
|
||
records: records.slice(0, params.latest ? 1 : params.limit)
|
||
};
|
||
}
|
||
|
||
export function timestampOf(value: unknown): number {
|
||
if (typeof value === "number") return value;
|
||
if (typeof value === "string") {
|
||
const parsed = Date.parse(value);
|
||
return Number.isFinite(parsed) ? parsed : 0;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
export async function resolveRuleVersion(
|
||
client: KyInstance,
|
||
params: { versionId?: string; versionNumber?: number; latestRuleVersion?: boolean; latest?: boolean }
|
||
) {
|
||
if (params.versionId) return api.getApprovalRuleVersion(client, params.versionId);
|
||
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const version = params.versionNumber
|
||
? versions.find((item) => item.versionNumber === params.versionNumber)
|
||
: versions[0];
|
||
|
||
if (!version) {
|
||
throw new Error(params.versionNumber
|
||
? `Rule version not found: ${params.versionNumber}`
|
||
: "No rule versions found");
|
||
}
|
||
|
||
return version;
|
||
}
|
||
|
||
export async function resolveRuleVersionSelector(client: KyInstance, selector: string): Promise<RuleSetVersion> {
|
||
const normalized = selector.trim();
|
||
if (!normalized) throw new Error("Rule version selector cannot be empty");
|
||
if (normalized === "latest") {
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const latest = versions[0];
|
||
if (!latest) throw new Error("No rule versions found");
|
||
return api.getApprovalRuleVersion(client, latest.id);
|
||
}
|
||
|
||
const versionNumber = Number(normalized);
|
||
if (Number.isInteger(versionNumber) && versionNumber > 0) {
|
||
const versions = await api.listApprovalRuleVersions(client);
|
||
const version = versions.find((item) => item.versionNumber === versionNumber);
|
||
if (!version) throw new Error(`Rule version not found: ${versionNumber}`);
|
||
return api.getApprovalRuleVersion(client, version.id);
|
||
}
|
||
|
||
return api.getApprovalRuleVersion(client, normalized);
|
||
}
|
||
|
||
export function filterRuns(records: ApprovalRun[], query?: string): ApprovalRun[] {
|
||
const normalized = query?.trim().toLowerCase();
|
||
if (!normalized) return records;
|
||
|
||
return records.filter((record) => {
|
||
const directValues = [
|
||
record.id,
|
||
record.sourceDocumentSN,
|
||
record.sourceDocumentId,
|
||
record.documentId,
|
||
record.sourceExtendData?._langfuseTraceId,
|
||
record.sourceExtendData?.simulation_batch_id,
|
||
record.status,
|
||
record.taskMode,
|
||
record.finalExecutionMode,
|
||
record.sourceSystem,
|
||
record.ruleSetVersionNumber,
|
||
record.ruleSetPublishedByName
|
||
];
|
||
|
||
return directValues.some((value) => scalarIncludes(value, normalized)) ||
|
||
objectContainsScalar(record, normalized);
|
||
});
|
||
}
|
||
|
||
export function scalarIncludes(value: unknown, normalized: string): boolean {
|
||
if (value === null || value === undefined) return false;
|
||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
||
return String(value).toLowerCase().includes(normalized);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
export function objectContainsScalar(value: unknown, normalized: string, depth = 0): boolean {
|
||
if (depth > 6) return false;
|
||
if (scalarIncludes(value, normalized)) return true;
|
||
if (!value || typeof value !== "object") return false;
|
||
|
||
if (Array.isArray(value)) {
|
||
return value.some((item) => objectContainsScalar(item, normalized, depth + 1));
|
||
}
|
||
|
||
return Object.entries(value as Record<string, unknown>).some(([key, item]) =>
|
||
scalarIncludes(key, normalized) || objectContainsScalar(item, normalized, depth + 1)
|
||
);
|
||
}
|
||
|
||
export function filterRunsByHumanResult(records: ApprovalRun[], humanResult?: string): ApprovalRun[] {
|
||
const normalized = humanResult?.trim().toLowerCase();
|
||
if (!normalized) return records;
|
||
|
||
return records.filter((record) =>
|
||
extractHumanResult(record)?.value.toLowerCase().includes(normalized)
|
||
);
|
||
}
|
||
|
||
export function withApprovalRunFilters<T extends {
|
||
manualApprovalStatus?: string | string[];
|
||
humanResult?: string;
|
||
}>(params: T) {
|
||
return {
|
||
...params,
|
||
manualApprovalStatus: resolveManualApprovalStatus(
|
||
params.manualApprovalStatus,
|
||
params.humanResult
|
||
)
|
||
};
|
||
}
|
||
|
||
export function resolveManualApprovalStatus(
|
||
manualApprovalStatus?: string | string[],
|
||
humanResult?: string
|
||
): string | string[] | undefined {
|
||
if (manualApprovalStatus) return manualApprovalStatus;
|
||
|
||
const normalized = humanResult?.trim().toLowerCase();
|
||
if (!normalized) return undefined;
|
||
if (["驳回", "已驳回", "拒绝", "不通过", "terminated", "reject", "rejected", "denied"].includes(normalized)) {
|
||
return "TERMINATED";
|
||
}
|
||
|
||
return undefined;
|
||
}
|
||
|
||
export async function prepareApprovalRuns(
|
||
client: KyInstance,
|
||
records: ApprovalRun[],
|
||
filters: {
|
||
query?: string;
|
||
humanResult?: string;
|
||
}
|
||
): Promise<ApprovalRun[]> {
|
||
const queriedRecords = filterRuns(records, filters.query);
|
||
if (!filters.humanResult?.trim()) return queriedRecords;
|
||
|
||
const detailedRecords = await Promise.all(
|
||
queriedRecords.map(async (record) => {
|
||
if (extractHumanResult(record)) return record;
|
||
|
||
try {
|
||
return await api.getApprovalRun(client, record.id);
|
||
} catch {
|
||
return record;
|
||
}
|
||
})
|
||
);
|
||
|
||
return filterRunsByHumanResult(detailedRecords, filters.humanResult);
|
||
}
|
||
|
||
export type HumanResultMatch = {
|
||
value: string;
|
||
path: string;
|
||
};
|
||
|
||
export function approvalRunAliases(record: ApprovalRun) {
|
||
return {
|
||
originalDocumentData: {
|
||
path: "document",
|
||
frontendLabel: "单据原始数据",
|
||
description: "前端详情页展示的单据原始数据对象",
|
||
id: record.document?.id ?? record.documentId,
|
||
sourceDocumentSN: record.document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
||
sourceDocumentId: record.document?.sourceDocumentId ?? record.sourceDocumentId
|
||
},
|
||
aiDocumentFields: {
|
||
path: "document.fields",
|
||
frontendLabel: "AI 看的单据",
|
||
description: "AI 审核实际读取的字段数组,即单据原始数据中的 fields",
|
||
fieldCount: record.document?.fields?.length
|
||
},
|
||
aiDocument: {
|
||
path: "document.fields",
|
||
frontendLabel: "AI 看的单据",
|
||
description: "兼容别名,等同于 aiDocumentFields",
|
||
aliasOf: "aiDocumentFields",
|
||
fieldCount: record.document?.fields?.length
|
||
},
|
||
sourceDocument: {
|
||
path: "sourceExtendData.hosecloudViewUrl",
|
||
description: "合思原始单据入口;详情响应中只有入口和源单据 ID,不包含完整原始单据 JSON",
|
||
sourceSystem: record.sourceSystem,
|
||
sourceDocumentSN: record.sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
originalDocumentId: record.sourceExtendData?.original_document_id,
|
||
viewUrl: record.sourceExtendData?.hosecloudViewUrl
|
||
},
|
||
aiResult: {
|
||
path: "result",
|
||
description: "AI 最终审核结构化结果"
|
||
},
|
||
aiAuditLog: {
|
||
path: "pipelineData.logs",
|
||
description: "AI 审核过程日志"
|
||
},
|
||
manualApproval: {
|
||
path: "manualApprovalRecord",
|
||
description: "人工审核结果、节点和驳回原因"
|
||
}
|
||
};
|
||
}
|
||
|
||
export function extractHumanResult(record: ApprovalRun): HumanResultMatch | undefined {
|
||
const roots: Array<[string, unknown]> = [
|
||
["result", record.result],
|
||
["pipelineData", record.pipelineData]
|
||
];
|
||
|
||
for (const [path, value] of roots) {
|
||
const match = findHumanResultValue(value, path);
|
||
if (match) return match;
|
||
}
|
||
|
||
return undefined;
|
||
}
|
||
|
||
export function findHumanResultValue(
|
||
value: unknown,
|
||
path: string,
|
||
depth = 0
|
||
): HumanResultMatch | undefined {
|
||
if (depth > 8 || value === null || value === undefined) return undefined;
|
||
|
||
if (Array.isArray(value)) {
|
||
for (let index = 0; index < value.length; index += 1) {
|
||
const match = findHumanResultValue(value[index], `${path}[${index}]`, depth + 1);
|
||
if (match) return match;
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
if (typeof value !== "object") return undefined;
|
||
|
||
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||
const childPath = `${path}.${key}`;
|
||
const match = findHumanResultValue(child, childPath, depth + 1);
|
||
if (match) return match;
|
||
|
||
if (isHumanResultKey(key) || isHumanResultKey(childPath)) {
|
||
const text = stringifyHumanResultValue(child);
|
||
if (text) return { value: text, path: childPath };
|
||
}
|
||
}
|
||
|
||
return undefined;
|
||
}
|
||
|
||
export function isHumanResultKey(key: string): boolean {
|
||
const normalized = key.toLowerCase();
|
||
const isHuman =
|
||
normalized.includes("human") ||
|
||
normalized.includes("manual") ||
|
||
normalized.includes("reviewer") ||
|
||
normalized.includes("operator") ||
|
||
key.includes("人工") ||
|
||
key.includes("人工审批") ||
|
||
key.includes("人工审核");
|
||
const isResult =
|
||
normalized.includes("result") ||
|
||
normalized.includes("decision") ||
|
||
normalized.includes("outcome") ||
|
||
normalized.includes("conclusion") ||
|
||
normalized.includes("action") ||
|
||
key.includes("结果") ||
|
||
key.includes("结论") ||
|
||
key.includes("动作");
|
||
|
||
return isHuman && isResult;
|
||
}
|
||
|
||
export function stringifyHumanResultValue(value: unknown): string | undefined {
|
||
if (typeof value === "string") return value.trim() || undefined;
|
||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||
if (!value || typeof value !== "object") return undefined;
|
||
|
||
const object = value as Record<string, unknown>;
|
||
for (const key of ["label", "name", "text", "value", "result", "decision", "outcome", "status", "action"]) {
|
||
const text = stringifyHumanResultValue(object[key]);
|
||
if (text) return text;
|
||
}
|
||
|
||
return undefined;
|
||
}
|
||
|
||
export function matchesRunLookup(
|
||
record: ApprovalRun,
|
||
lookup: {
|
||
recordId?: string;
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
}
|
||
): boolean {
|
||
if (lookup.recordId && record.id !== lookup.recordId) return false;
|
||
if (lookup.sourceDocumentSN && record.sourceDocumentSN !== lookup.sourceDocumentSN) return false;
|
||
if (lookup.sourceDocumentId && record.sourceDocumentId !== lookup.sourceDocumentId) return false;
|
||
return true;
|
||
}
|
||
|
||
export function countBy<T>(items: T[], keyFor: (item: T) => string): Record<string, number> {
|
||
return items.reduce<Record<string, number>>((counts, item) => {
|
||
const key = keyFor(item);
|
||
counts[key] = (counts[key] ?? 0) + 1;
|
||
return counts;
|
||
}, {});
|
||
}
|
||
|
||
export function localDateKey(value: string | number | undefined, timezone: string): string | undefined {
|
||
const date = toDate(value);
|
||
if (!date) return undefined;
|
||
|
||
const parts = localParts(date, timezone);
|
||
const year = parts.year;
|
||
const month = (parts.month ?? "01").padStart(2, "0");
|
||
const day = (parts.day ?? "01").padStart(2, "0");
|
||
return `${year}-${month}-${day}`;
|
||
}
|
||
|
||
export function formatLocalDateTime(value: string | number | undefined, timezone: string): string | undefined {
|
||
const date = toDate(value);
|
||
if (!date) return undefined;
|
||
|
||
const parts = localParts(date, timezone);
|
||
const month = (parts.month ?? "01").padStart(2, "0");
|
||
const day = (parts.day ?? "01").padStart(2, "0");
|
||
const hour = (parts.hour ?? "00").padStart(2, "0");
|
||
const minute = (parts.minute ?? "00").padStart(2, "0");
|
||
const second = (parts.second ?? "00").padStart(2, "0");
|
||
const offset = timezoneOffsetString(date, timezone);
|
||
return `${parts.year ?? "0000"}-${month}-${day}T${hour}:${minute}:${second}${offset}`;
|
||
}
|
||
|
||
function timezoneOffsetString(date: Date, timezone: string): string {
|
||
if (
|
||
timezone === "Asia/Shanghai" ||
|
||
timezone === "Asia/Chongqing" ||
|
||
timezone === "Asia/Hong_Kong" ||
|
||
timezone === "Asia/Taipei"
|
||
) {
|
||
return "+08:00";
|
||
}
|
||
try {
|
||
const tzPart = new Intl.DateTimeFormat("en-US", {
|
||
timeZone: timezone,
|
||
timeZoneName: "longOffset"
|
||
})
|
||
.formatToParts(date)
|
||
.find((part) => part.type === "timeZoneName")?.value;
|
||
if (!tzPart || tzPart === "GMT" || tzPart === "UTC") return "+00:00";
|
||
return tzPart.replace(/^GMT/, "");
|
||
} catch {
|
||
return "+08:00";
|
||
}
|
||
}
|
||
|
||
export function toDate(value: string | number | undefined): Date | null {
|
||
if (value === undefined) return null;
|
||
|
||
const date = new Date(value);
|
||
return Number.isNaN(date.getTime()) ? null : date;
|
||
}
|
||
|
||
export function localParts(date: Date, timezone: string): Record<string, string> {
|
||
return Object.fromEntries(
|
||
new Intl.DateTimeFormat("en-CA", {
|
||
timeZone: timezone,
|
||
year: "numeric",
|
||
month: "2-digit",
|
||
day: "2-digit",
|
||
hour: "2-digit",
|
||
minute: "2-digit",
|
||
second: "2-digit",
|
||
hour12: false,
|
||
hourCycle: "h23"
|
||
})
|
||
.formatToParts(date)
|
||
.filter((part) => part.type !== "literal")
|
||
.map((part) => [part.type, part.value])
|
||
);
|
||
}
|
||
|