feat(aipro): introduce init session with 6-char short runId and 6h TTL, support --run audit logging in scopes, translate, rules and logs
This commit is contained in:
1 parent
a16d429d44
commit
b0149ed32d
5 files changed
+392
-73
No files matched your search
+221
-38
@@ -8,6 +8,7 @@ import {
|
||||
ApprovalRepository,
|
||||
ApprovalGatewayBlockedError,
|
||||
FindingCheckStatus,
|
||||
ApprovalRunRecord,
|
||||
} from "./domains/approval/index.js";
|
||||
import { getRawBillFlow } from "./domains/bill/api.js";
|
||||
import { translateBillFlowToMarkdown } from "./domains/bill/translator.js";
|
||||
@@ -36,7 +37,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const eqIdx = arg.indexOf("=");
|
||||
if (eqIdx === -1) {
|
||||
const flagName = arg.replace(/^--?/, "").toLowerCase();
|
||||
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName);
|
||||
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute"].includes(flagName);
|
||||
if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
|
||||
i++; // skip option value
|
||||
}
|
||||
@@ -68,10 +69,83 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
// ── 1. 规约场景索引列表查看 ─────────────────────────────────────────
|
||||
// ── 1. 初始化审批实例会话(签发 6 位短 ID,有效期 6 小时)──────────────
|
||||
case "init":
|
||||
case "start": {
|
||||
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
if (!billSn) {
|
||||
throw new Error("请提供单号: hose-aipro init <单号>");
|
||||
}
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, billSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号为 [${billSn}] 的单据`);
|
||||
}
|
||||
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<string, any>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const snapshot = translateBillFlowToMarkdown(raw);
|
||||
|
||||
// 创建全新独立运行实例 (永久长 ID + 6 位短 ID, 6 小时有效期)
|
||||
const run = repo.createApprovalRun({
|
||||
documentSn: form.code || billSn,
|
||||
corpId: context.corpId,
|
||||
flowId: flowIdObj.id || raw.id,
|
||||
documentSnapshot: snapshot,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "init",
|
||||
runId: run.shortId || run.id,
|
||||
documentSn: run.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `初始化审批会话成功,签发 6 位短 ID: ${run.shortId} (有效期 6 小时)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(
|
||||
{
|
||||
runId: run.shortId,
|
||||
documentSn: run.documentSn,
|
||||
title,
|
||||
corpId: run.corpId,
|
||||
status: run.decision,
|
||||
expiresIn: "6h",
|
||||
createdAt: run.createdAt,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 规约场景索引列表查看(支持 --run <runId> 锚定会话)─────────────
|
||||
case "scopes":
|
||||
case "index":
|
||||
case "indexes": {
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "scopes",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord ? `在会话 [${runRecord.shortId}] 查阅规约场景索引` : "查阅规约场景索引",
|
||||
});
|
||||
|
||||
const scopes = repo.listScopes().map((s) => ({
|
||||
index: s.index,
|
||||
scope: s.scope,
|
||||
@@ -79,15 +153,111 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 2. 查询命中索引关联的所有规则(按 code 升序平铺输出纯规则)──────────
|
||||
case "rules":
|
||||
case "rule":
|
||||
case "scope": {
|
||||
const rawInputs = [
|
||||
...positional.slice(1),
|
||||
stringOption(parsed.options, ["scope", "s", "index", "i", "indexes"]),
|
||||
].filter(Boolean) as string[];
|
||||
// ── 3. 单据字段转译器(支持 --run <runId>,支持查主单据或跨单据)────────
|
||||
case "translate":
|
||||
case "doc":
|
||||
case "markdown":
|
||||
case "render": {
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const specifiedSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
} else if (specifiedSn) {
|
||||
// 如果未显式传 --run,但参数本身是 6 位 shortId
|
||||
const maybeRun = repo.getRunByHandle(specifiedSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === specifiedSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
// 确定要查的目标单号:若用户显式指定了单号(且不是 shortId)则查该单号;否则查会话主单据
|
||||
let targetSn: string | undefined;
|
||||
let isSessionPrimary = false;
|
||||
|
||||
if (runRecord) {
|
||||
if (specifiedSn && specifiedSn !== runRecord.shortId) {
|
||||
targetSn = specifiedSn;
|
||||
} else {
|
||||
targetSn = runRecord.documentSn;
|
||||
isSessionPrimary = true;
|
||||
}
|
||||
} else {
|
||||
targetSn = specifiedSn;
|
||||
}
|
||||
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供会话 ID 或单号: hose-aipro translate [单号] --run <runId>");
|
||||
}
|
||||
|
||||
// 若查询的是当前会话的主单据且已缓存有快照,直接毫秒级返回
|
||||
if (isSessionPrimary && runRecord?.documentSnapshot) {
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId}] 读取主单据快照 [${runRecord.documentSn}]`,
|
||||
});
|
||||
return {
|
||||
stdout: runRecord.documentSnapshot.endsWith("\n") ? runRecord.documentSnapshot : runRecord.documentSnapshot + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 查询其它关联单据或重新拉取
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, targetSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
|
||||
}
|
||||
const markdown = translateBillFlowToMarkdown(raw);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查阅关联单据 [${targetSn}] 转译文本`
|
||||
: `查阅单据 [${targetSn}] 转译文本`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: markdown.endsWith("\n") ? markdown : markdown + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 4. 查询命中索引关联的所有规则(方案二:全显式具名参数)────────────
|
||||
case "rules":
|
||||
case "rule": {
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const rawIndexes =
|
||||
stringOption(parsed.options, ["indexes", "index", "i", "scope", "s"]) ||
|
||||
positional[1] ||
|
||||
positional[2];
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
// 若传入了 --run,进行会话校验
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
const rawInputs = [rawIndexes].filter(Boolean) as string[];
|
||||
const targetIndexes: number[] = [];
|
||||
for (const raw of rawInputs) {
|
||||
const trimmed = raw.trim();
|
||||
@@ -102,7 +272,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
continue;
|
||||
}
|
||||
} catch {
|
||||
// 兼容非严格 JSON 数组,如 [1, 2]
|
||||
const inner = trimmed.slice(1, -1);
|
||||
const parts = inner.split(/[,,\s]+/).filter(Boolean);
|
||||
for (const p of parts) {
|
||||
@@ -123,7 +292,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
if (uniqueIndexes.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `请提供包裹好的索引数组,例如:\n hose-aipro rules "[2]"\n hose-aipro rules "[1, 2]"\n`,
|
||||
stderr: `请提供具名参数,例如:\n hose-aipro rules --run <runId> --indexes "[1]"\n hose-aipro rules --run <runId> --indexes "[1, 2]"\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -155,9 +324,21 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
};
|
||||
}
|
||||
|
||||
// 按照 code 顺序平铺规则
|
||||
// 按照 code 顺序平铺规则 (形态 1)
|
||||
const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.code - b.code);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "rules",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`
|
||||
: `查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(flattenedRules, null, 2) + "\n",
|
||||
stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "",
|
||||
@@ -165,28 +346,6 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 单据字段转译器(转译为标准 LLM / 审核视图 Markdown)─────────────
|
||||
case "translate":
|
||||
case "doc":
|
||||
case "markdown":
|
||||
case "render": {
|
||||
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
if (!billSn) {
|
||||
throw new Error("请提供要转译的单号: hose-aipro translate <单号>");
|
||||
}
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, billSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${billSn}] 的单据`);
|
||||
}
|
||||
const markdown = translateBillFlowToMarkdown(raw);
|
||||
return {
|
||||
stdout: markdown.endsWith("\n") ? markdown : markdown + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 4. 查看审核要点清单(纯规则元数据,与具体单据无关)────────────────
|
||||
case "points":
|
||||
case "clauses": {
|
||||
@@ -583,8 +742,30 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
case "log":
|
||||
case "history":
|
||||
case "trail": {
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
|
||||
const logs = repo.listAiProLogs(targetSn || undefined, limit);
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
} else if (targetSn) {
|
||||
const maybeRun = repo.getRunByHandle(targetSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
const filter: { runId?: string; documentSn?: string } = {};
|
||||
if (runRecord) {
|
||||
filter.runId = runRecord.shortId || runRecord.id;
|
||||
} else if (runHandle) {
|
||||
filter.runId = runHandle;
|
||||
}
|
||||
if (targetSn && targetSn !== runRecord?.shortId) {
|
||||
filter.documentSn = targetSn;
|
||||
}
|
||||
|
||||
const logs = repo.listAiProLogs(filter, limit);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -595,17 +776,19 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
const targetDesc = filter.runId ? ` (会话: ${filter.runId})` : filter.documentSn ? ` (单号: ${filter.documentSn})` : "";
|
||||
return {
|
||||
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`,
|
||||
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetDesc}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
|
||||
const headers = ["#", "发生时间", "会话 ID", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
|
||||
const rows = logs.map((l, i) => [
|
||||
i + 1,
|
||||
new Date(l.createdAt).toLocaleString("zh-CN"),
|
||||
l.runId || "-",
|
||||
l.action,
|
||||
l.documentSn || "-",
|
||||
l.operator || "-",
|
||||
|
||||
@@ -296,4 +296,64 @@ describe("Approval Domain - SQLite 持久化与规约仓储", () => {
|
||||
|
||||
expect(repo.getAuditChecklist("EXEC-FAIL", "corp-a").run?.decision).toBe("ERROR");
|
||||
});
|
||||
|
||||
test("审批会话 6 位 shortId 生成、6 小时 TTL 与会话级日志挂载", () => {
|
||||
// 1. 同一单号多次审批,生成完全独立的运行实例
|
||||
const run1 = repo.createApprovalRun({
|
||||
documentSn: "MULTI-RUN-001",
|
||||
corpId: "corp-test",
|
||||
documentSnapshot: "# 单据初审快照",
|
||||
});
|
||||
const run2 = repo.createApprovalRun({
|
||||
documentSn: "MULTI-RUN-001",
|
||||
corpId: "corp-test",
|
||||
documentSnapshot: "# 单据复审快照",
|
||||
});
|
||||
|
||||
expect(run1.id).not.toBe(run2.id);
|
||||
expect(run1.shortId).toHaveLength(6);
|
||||
expect(run2.shortId).toHaveLength(6);
|
||||
expect(run1.shortId).not.toBe(run2.shortId);
|
||||
expect(run1.expiresAt).toBeGreaterThan(Date.now());
|
||||
|
||||
// 2. 通过 6 位短 ID 检索会话
|
||||
const found1 = repo.getRunByHandle(run1.shortId!);
|
||||
expect(found1?.id).toBe(run1.id);
|
||||
expect(found1?.documentSnapshot).toBe("# 单据初审快照");
|
||||
|
||||
// 3. 过期检测拦截
|
||||
const expiredRun = repo.createApprovalRun({
|
||||
documentSn: "EXPIRED-001",
|
||||
expiresAt: Date.now() - 1000, // 过去的时间
|
||||
});
|
||||
expect(() => repo.getRunByHandle(expiredRun.shortId!)).toThrow("已过期");
|
||||
|
||||
// 4. 会话级日志挂载与检索
|
||||
repo.logAiProAction({
|
||||
action: "init",
|
||||
runId: run1.shortId,
|
||||
documentSn: "MULTI-RUN-001",
|
||||
summary: "初始化审批会话",
|
||||
});
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: run1.shortId,
|
||||
documentSn: "MULTI-RUN-001",
|
||||
summary: "读取快照",
|
||||
});
|
||||
repo.logAiProAction({
|
||||
action: "init",
|
||||
runId: run2.shortId,
|
||||
documentSn: "MULTI-RUN-001",
|
||||
summary: "第二次初始化审批会话",
|
||||
});
|
||||
|
||||
const run1Logs = repo.listAiProLogs({ runId: run1.shortId! });
|
||||
expect(run1Logs.length).toBe(2);
|
||||
expect(run1Logs.map((l) => l.action).sort()).toEqual(["init", "translate"].sort());
|
||||
|
||||
const run2Logs = repo.listAiProLogs({ runId: run2.shortId! });
|
||||
expect(run2Logs.length).toBe(1);
|
||||
expect(run2Logs[0]!.summary).toBe("第二次初始化审批会话");
|
||||
});
|
||||
});
|
||||
@@ -105,6 +105,8 @@ export function initDatabaseSchema(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS approval_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
short_id TEXT,
|
||||
expires_at INTEGER,
|
||||
flow_id TEXT,
|
||||
document_sn TEXT NOT NULL,
|
||||
corp_id TEXT,
|
||||
@@ -120,10 +122,15 @@ export function initDatabaseSchema(db: Database): void {
|
||||
`);
|
||||
try {
|
||||
db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;");
|
||||
} catch {
|
||||
// column already exists
|
||||
}
|
||||
} catch {}
|
||||
try {
|
||||
db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;");
|
||||
} catch {}
|
||||
try {
|
||||
db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;");
|
||||
} catch {}
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
|
||||
|
||||
// 4. 审批要点事实记录表
|
||||
@@ -146,6 +153,7 @@ export function initDatabaseSchema(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS aipro_logs (
|
||||
id TEXT PRIMARY KEY,
|
||||
run_id TEXT,
|
||||
action TEXT NOT NULL,
|
||||
document_sn TEXT,
|
||||
operator TEXT,
|
||||
@@ -156,7 +164,11 @@ export function initDatabaseSchema(db: Database): void {
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
try {
|
||||
db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;");
|
||||
} catch {}
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
|
||||
|
||||
// 种子数据:初始化默认偏好
|
||||
|
||||
@@ -14,6 +14,15 @@ import {
|
||||
StrictnessTier
|
||||
} from "./types.js";
|
||||
|
||||
export function generateShortRunId(): string {
|
||||
const chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
let result = "";
|
||||
for (let i = 0; i < 6; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export interface CreateRuleInput {
|
||||
scope: string;
|
||||
body: string;
|
||||
@@ -287,6 +296,39 @@ export class ApprovalRepository {
|
||||
|
||||
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
|
||||
|
||||
public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const shortId = input.shortId ?? generateShortRunId();
|
||||
const now = Date.now();
|
||||
const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO approval_runs (
|
||||
id, short_id, expires_at, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
id,
|
||||
shortId,
|
||||
expiresAt,
|
||||
input.flowId ?? null,
|
||||
input.documentSn.trim(),
|
||||
input.corpId ?? null,
|
||||
input.scope ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
input.decisionSummary ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
input.documentSnapshot ?? null,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
);
|
||||
|
||||
return this.getRunById(id)!;
|
||||
}
|
||||
|
||||
public createOrResetApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
|
||||
const now = Date.now();
|
||||
@@ -315,30 +357,28 @@ export class ApprovalRepository {
|
||||
return this.getRunById(existing.id)!;
|
||||
}
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO approval_runs (
|
||||
id, flow_id, document_sn, corp_id, scope, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.flowId ?? null,
|
||||
input.documentSn.trim(),
|
||||
input.corpId ?? null,
|
||||
input.scope ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
input.decisionSummary ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
input.documentSnapshot ?? null,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
);
|
||||
return this.createApprovalRun(input);
|
||||
}
|
||||
|
||||
return this.getRunById(id)!;
|
||||
public getRunByHandle(handle: string, corpId?: string): ApprovalRunRecord | null {
|
||||
const trimmed = handle.trim();
|
||||
const now = Date.now();
|
||||
// 1. 如果符合 6 位大写短 ID 特征
|
||||
if (/^[A-Za-z0-9]{6}$/.test(trimmed)) {
|
||||
const row = this.db
|
||||
.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?) AND (expires_at IS NULL OR expires_at > ?)")
|
||||
.get(trimmed, now) as any;
|
||||
if (row) return this.mapRunRow(row);
|
||||
const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any;
|
||||
if (expiredRow) {
|
||||
throw new Error(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
|
||||
}
|
||||
}
|
||||
// 2. 尝试按长 UUID 查找
|
||||
const byId = this.getRunById(trimmed);
|
||||
if (byId) return byId;
|
||||
// 3. 尝试按单号查找最新未过期的运行记录
|
||||
return this.getLatestRunBySn(trimmed, corpId);
|
||||
}
|
||||
|
||||
public getLatestRunBySn(documentSn: string, corpId?: string): ApprovalRunRecord | null {
|
||||
@@ -514,6 +554,8 @@ export class ApprovalRepository {
|
||||
private mapRunRow(row: any): ApprovalRunRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
shortId: row.short_id ?? null,
|
||||
expiresAt: row.expires_at ? Number(row.expires_at) : null,
|
||||
flowId: row.flow_id,
|
||||
documentSn: row.document_sn,
|
||||
corpId: row.corp_id,
|
||||
@@ -553,19 +595,20 @@ export class ApprovalRepository {
|
||||
public logAiProAction(input: CreateAiProLogInput): AiProLogRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const now = Date.now();
|
||||
|
||||
const status = input.status ?? "SUCCESS";
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO aipro_logs (id, action, document_sn, operator, args, status, decision, summary, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO aipro_logs (id, run_id, action, document_sn, operator, args, status, decision, summary, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.runId ?? null,
|
||||
input.action,
|
||||
input.documentSn ?? null,
|
||||
input.operator ?? null,
|
||||
input.args ?? null,
|
||||
input.status,
|
||||
status,
|
||||
input.decision ?? null,
|
||||
input.summary ?? null,
|
||||
now,
|
||||
@@ -574,30 +617,45 @@ export class ApprovalRepository {
|
||||
|
||||
return {
|
||||
id,
|
||||
runId: input.runId,
|
||||
action: input.action,
|
||||
documentSn: input.documentSn,
|
||||
operator: input.operator,
|
||||
args: input.args,
|
||||
status: input.status,
|
||||
status,
|
||||
decision: input.decision,
|
||||
summary: input.summary,
|
||||
createdAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
public listAiProLogs(documentSn?: string, limit = 50): AiProLogRecord[] {
|
||||
public listAiProLogs(filter?: string | { documentSn?: string; runId?: string }, limit = 50): AiProLogRecord[] {
|
||||
let sql = "SELECT * FROM aipro_logs";
|
||||
const conditions: string[] = [];
|
||||
const params: any[] = [];
|
||||
if (documentSn) {
|
||||
sql += " WHERE document_sn = ?";
|
||||
params.push(documentSn.trim());
|
||||
|
||||
const f = typeof filter === "string" ? { documentSn: filter } : filter;
|
||||
|
||||
if (f?.runId) {
|
||||
conditions.push("run_id = ?");
|
||||
params.push(f.runId.trim());
|
||||
}
|
||||
if (f?.documentSn) {
|
||||
conditions.push("document_sn = ?");
|
||||
params.push(f.documentSn.trim());
|
||||
}
|
||||
|
||||
if (conditions.length > 0) {
|
||||
sql += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
sql += " ORDER BY created_at DESC LIMIT ?";
|
||||
params.push(limit);
|
||||
|
||||
const rows = this.db.query(sql).all(...params) as any[];
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
runId: r.run_id ?? null,
|
||||
action: r.action,
|
||||
documentSn: r.document_sn,
|
||||
operator: r.operator,
|
||||
@@ -612,6 +670,8 @@ export class ApprovalRepository {
|
||||
|
||||
export interface CreateApprovalRunInput {
|
||||
documentSn: string;
|
||||
shortId?: string | null;
|
||||
expiresAt?: number | null;
|
||||
flowId?: string | null;
|
||||
corpId?: string | null;
|
||||
scope?: string | null;
|
||||
@@ -633,6 +693,7 @@ export interface CreateFindingInput {
|
||||
|
||||
export interface CreateAiProLogInput {
|
||||
action: string;
|
||||
runId?: string | null;
|
||||
documentSn?: string | null;
|
||||
operator?: string | null;
|
||||
args?: string | null;
|
||||
|
||||
@@ -77,6 +77,8 @@ export type ApprovalDecision = "PENDING" | "APPROVE" | "REJECT" | "PASS_WITH_NOT
|
||||
|
||||
export interface ApprovalRunRecord {
|
||||
id: string;
|
||||
shortId?: string | null;
|
||||
expiresAt?: number | null;
|
||||
flowId?: string | null;
|
||||
documentSn: string;
|
||||
corpId?: string | null;
|
||||
@@ -123,6 +125,7 @@ export class ApprovalGatewayBlockedError extends Error {
|
||||
|
||||
export interface AiProLogRecord {
|
||||
id: string;
|
||||
runId?: string | null;
|
||||
action: string;
|
||||
documentSn?: string | null;
|
||||
operator?: string | null;
|
||||
|
||||
Reference in new issue
Block a user