Merge pull request #56 from yunyingk/codex/issue-55-auth-bill
fix(auth): guard temporary token refresh and translate bill flow
This commit is contained in:
12 files changed
+238
-20
No files matched your search
@@ -49,11 +49,17 @@ hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToke
|
|||||||
|
|
||||||
# 可选附加别名与覆盖参数
|
# 可选附加别名与覆盖参数
|
||||||
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
||||||
|
|
||||||
|
# 未提供服务端 expTime 时,可显式指定本地有效期
|
||||||
|
hose-use corps add-link "<url>" --ttl 3d
|
||||||
|
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
|
||||||
```
|
```
|
||||||
- **全自动识别与身份探测**:
|
- **全自动识别与身份探测**:
|
||||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||||
|
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
|
||||||
|
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
|
||||||
|
|
||||||
### 代客协助凭证导入
|
### 代客协助凭证导入
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -240,6 +240,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
|
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
|
||||||
let name = stringOption(parsed.options, ["name"]);
|
let name = stringOption(parsed.options, ["name"]);
|
||||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||||
|
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||||
|
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||||
|
|
||||||
if (!raw && !accessToken && process.stdin.isTTY) {
|
if (!raw && !accessToken && process.stdin.isTTY) {
|
||||||
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
|
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
|
||||||
@@ -270,6 +272,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
name,
|
name,
|
||||||
baseUrl,
|
baseUrl,
|
||||||
overwrite,
|
overwrite,
|
||||||
|
ttl,
|
||||||
|
expires,
|
||||||
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
searchAndFormatBills,
|
searchAndFormatBills,
|
||||||
getBillByCodeOrId,
|
getBillByCodeOrId,
|
||||||
getBillFlow,
|
getBillFlow,
|
||||||
|
formatBillFlowOperator,
|
||||||
getBillRisk,
|
getBillRisk,
|
||||||
getBillReferences,
|
getBillReferences,
|
||||||
getBillRelations,
|
getBillRelations,
|
||||||
@@ -339,7 +340,7 @@ export async function handleBillCommand(
|
|||||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||||
entry.nodeName || "-",
|
entry.nodeName || "-",
|
||||||
entry.action || "-",
|
entry.action || "-",
|
||||||
entry.operator?.name || (entry.automatic ? "系统" : "-"),
|
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||||
entry.comment || "-",
|
entry.comment || "-",
|
||||||
|
|||||||
@@ -160,6 +160,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
|||||||
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||||
const name = stringOption(parsed.options, ["name"]);
|
const name = stringOption(parsed.options, ["name"]);
|
||||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||||
|
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||||
|
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||||
|
|
||||||
if (!linkUrl && process.stdin.isTTY) {
|
if (!linkUrl && process.stdin.isTTY) {
|
||||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||||
@@ -168,7 +170,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
|||||||
if (!linkUrl) {
|
if (!linkUrl) {
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--overwrite]\n",
|
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -177,6 +179,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
|||||||
const corp = await importFromLink(linkUrl, {
|
const corp = await importFromLink(linkUrl, {
|
||||||
name,
|
name,
|
||||||
overwrite,
|
overwrite,
|
||||||
|
ttl,
|
||||||
|
expires,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
|
||||||
|
import { createEkbClient } from "./ekb.js";
|
||||||
|
import type { CorpConfig } from "../config/types.js";
|
||||||
|
|
||||||
|
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||||
|
return {
|
||||||
|
id: "corp-1",
|
||||||
|
name: "测试企业",
|
||||||
|
source: "link",
|
||||||
|
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
|
||||||
|
...overrides,
|
||||||
|
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("core/auth/ekb refresh policy", () => {
|
||||||
|
it("only allows account credentials with an explicit account binding to refresh", () => {
|
||||||
|
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||||
|
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||||
|
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
|
||||||
|
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
|
||||||
|
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let calls = 0;
|
||||||
|
globalThis.fetch = (async () => {
|
||||||
|
calls += 1;
|
||||||
|
return new Response("expired", { status: 401 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = await createEkbClient(corp());
|
||||||
|
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("core/auth/login link expiry", () => {
|
||||||
|
it("parses explicit ttl and expires durations", () => {
|
||||||
|
const base = 1_700_000_000_000;
|
||||||
|
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
|
||||||
|
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||||
|
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||||
|
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
+16
-6
@@ -1,6 +1,7 @@
|
|||||||
import { CorpConfig } from "../config/types.js";
|
import { CorpConfig } from "../config/types.js";
|
||||||
|
import { AuthenticationError } from "../errors.js";
|
||||||
import { createAuthClient } from "../http/factory.js";
|
import { createAuthClient } from "../http/factory.js";
|
||||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
|
||||||
|
|
||||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||||
return {
|
return {
|
||||||
@@ -11,20 +12,29 @@ export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function createEkbClient(corp: CorpConfig) {
|
export async function createEkbClient(corp: CorpConfig) {
|
||||||
|
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||||
|
|
||||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||||
if (corp.auth?.expiresAt) {
|
if (canRefresh && corp.auth?.expiresAt) {
|
||||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||||
await refreshSingleCorpAccessToken(corp);
|
await refreshSingleCorpAccessToken(corp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 使用带 401 自动重试与换票的 AuthClient
|
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||||
return createAuthClient({
|
return createAuthClient({
|
||||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||||
getHeaders: () => getEkbHeaders(corp),
|
getHeaders: () => getEkbHeaders(corp),
|
||||||
onUnauthorized: async () => {
|
retryUnauthorized: canRefresh,
|
||||||
await refreshSingleCorpAccessToken(corp);
|
...(canRefresh
|
||||||
},
|
? {
|
||||||
|
onUnauthorized: async () => {
|
||||||
|
await refreshSingleCorpAccessToken(corp);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+38
-4
@@ -231,6 +231,8 @@ export interface F12ImportParams {
|
|||||||
source?: import("../config/types.js").CredentialSource;
|
source?: import("../config/types.js").CredentialSource;
|
||||||
enterprisesDir?: string;
|
enterprisesDir?: string;
|
||||||
overwrite?: boolean;
|
overwrite?: boolean;
|
||||||
|
ttl?: string | number;
|
||||||
|
expires?: string | number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ImportFromLinkOptions {
|
export interface ImportFromLinkOptions {
|
||||||
@@ -238,6 +240,34 @@ export interface ImportFromLinkOptions {
|
|||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
enterprisesDir?: string;
|
enterprisesDir?: string;
|
||||||
overwrite?: boolean;
|
overwrite?: boolean;
|
||||||
|
ttl?: string | number;
|
||||||
|
expires?: string | number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canRefreshCorpAccessToken(corp: CorpConfig): boolean {
|
||||||
|
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
|
||||||
|
const raw = String(value).trim().toLowerCase();
|
||||||
|
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
|
||||||
|
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
|
||||||
|
const amount = Number(match[1]);
|
||||||
|
if (!Number.isFinite(amount) || amount <= 0) {
|
||||||
|
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||||
|
}
|
||||||
|
const unit = match[2];
|
||||||
|
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
|
||||||
|
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveLinkExpiresAt(
|
||||||
|
options: { ttl?: string | number; expires?: string | number },
|
||||||
|
baseTime = Date.now()
|
||||||
|
): number | undefined {
|
||||||
|
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
|
||||||
|
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -361,6 +391,7 @@ export async function importCredentials(
|
|||||||
let isAdmin: boolean | undefined;
|
let isAdmin: boolean | undefined;
|
||||||
let sourceChannel: string | undefined;
|
let sourceChannel: string | undefined;
|
||||||
let jwtExpMs: number | undefined;
|
let jwtExpMs: number | undefined;
|
||||||
|
const requestedExpiresAt = resolveLinkExpiresAt(params);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const jwtHeaders: Record<string, string> = {
|
const jwtHeaders: Record<string, string> = {
|
||||||
@@ -495,9 +526,8 @@ export async function importCredentials(
|
|||||||
expiresAt = sessionData.expTime;
|
expiresAt = sessionData.expTime;
|
||||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||||
expiresAt = jwtExpMs;
|
expiresAt = jwtExpMs;
|
||||||
} else if ((sessionData?.isAssistPlatform || source === "link") && sessionData?.loginTime) {
|
} else if (requestedExpiresAt) {
|
||||||
// 协助/免密平台短期调试 Token 通常 2 小时有效
|
expiresAt = requestedExpiresAt;
|
||||||
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const corpConfig: CorpConfig = {
|
const corpConfig: CorpConfig = {
|
||||||
@@ -566,6 +596,8 @@ export async function importFromLink(
|
|||||||
enterprisesDir: options.enterprisesDir,
|
enterprisesDir: options.enterprisesDir,
|
||||||
overwrite: options.overwrite,
|
overwrite: options.overwrite,
|
||||||
source: "link",
|
source: "link",
|
||||||
|
ttl: options.ttl,
|
||||||
|
expires: options.expires,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -679,7 +711,9 @@ export async function refreshSingleCorpAccessToken(
|
|||||||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
|
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
|
||||||
idpUrl: string = DEFAULT_IDP_URL
|
idpUrl: string = DEFAULT_IDP_URL
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount();
|
if (!canRefreshCorpAccessToken(corp)) return false;
|
||||||
|
|
||||||
|
const account = getAccount(corp.accountId!);
|
||||||
if (!account?.cloudAuthToken) return false;
|
if (!account?.cloudAuthToken) return false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export interface CreateAuthClientOptions {
|
|||||||
prefixUrl: string;
|
prefixUrl: string;
|
||||||
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
|
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
|
||||||
onUnauthorized?: () => Promise<void> | void;
|
onUnauthorized?: () => Promise<void> | void;
|
||||||
|
onAuthFailure?: (response: Response) => Error;
|
||||||
|
retryUnauthorized?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createClient(options: CreateClientOptions): KyInstance {
|
export function createClient(options: CreateClientOptions): KyInstance {
|
||||||
@@ -22,7 +24,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
|||||||
return ky.create({
|
return ky.create({
|
||||||
prefix: options.prefixUrl,
|
prefix: options.prefixUrl,
|
||||||
retry: {
|
retry: {
|
||||||
limit: 1,
|
limit: options.retryUnauthorized === false ? 0 : 1,
|
||||||
methods: ["get", "post", "put", "delete", "patch"],
|
methods: ["get", "post", "put", "delete", "patch"],
|
||||||
statusCodes: [401],
|
statusCodes: [401],
|
||||||
},
|
},
|
||||||
@@ -59,6 +61,9 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
|||||||
}
|
}
|
||||||
return ky(request);
|
return ky(request);
|
||||||
}
|
}
|
||||||
|
if (isAuthError && options.onAuthFailure) {
|
||||||
|
throw options.onAuthFailure(response);
|
||||||
|
}
|
||||||
return response;
|
return response;
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -210,6 +210,39 @@ describe("Bill Domain", () => {
|
|||||||
expect(result?.history[1]?.skipped).toBe(true);
|
expect(result?.history[1]?.skipped).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("translates flow actions, states, Ebot operators and print reminders", async () => {
|
||||||
|
const client = {
|
||||||
|
post: async (path: string) => {
|
||||||
|
if (path.includes("backlogs/search")) {
|
||||||
|
return new Response(JSON.stringify({ items: [{ id: "backlog-i18n", flowId: { id: "flow-i18n", form: { code: "B26000001" } } }] }));
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ value: {
|
||||||
|
id: "backlog-i18n",
|
||||||
|
state: "APPROVING",
|
||||||
|
flowId: {
|
||||||
|
id: "flow-i18n",
|
||||||
|
state: "APPROVING",
|
||||||
|
form: { code: "B26000001" },
|
||||||
|
logs: [
|
||||||
|
{ action: "freeflow.submit", state: "SUBMITTED", operatorId: "staff-1", attributes: { nodeName: "提交" } },
|
||||||
|
{ action: "freeflow.autoAgree", state: "APPROVED", operatorId: "ebot", attributes: { isEbotNode: true } },
|
||||||
|
{ action: "freeflow.print", state: "COMPLETED", attributes: { isAuto: true } },
|
||||||
|
],
|
||||||
|
plan: { nodes: [{ id: "node-next", name: "财务审批", type: "APPROVAL" }] },
|
||||||
|
},
|
||||||
|
} }));
|
||||||
|
},
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
const result = await getBillFlow(client, "corp-i18n", "B26000001");
|
||||||
|
expect(result?.state).toBe("审批中");
|
||||||
|
expect(result?.history.map((entry) => entry.action)).toEqual(["提交送审", "自动同意", "打印单据"]);
|
||||||
|
expect(result?.history[1]?.operator?.name).toBe("Ebot (智能审批)");
|
||||||
|
expect(result?.history[2]?.nodeName).toBe("打印提醒");
|
||||||
|
expect(result?.history[0]?.rawAction).toBe("freeflow.submit");
|
||||||
|
expect(result?.history[0]?.rawState).toBe("SUBMITTED");
|
||||||
|
});
|
||||||
|
|
||||||
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
|
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
|
||||||
const calls: Array<{ path: string; options: any }> = [];
|
const calls: Array<{ path: string; options: any }> = [];
|
||||||
const client = {
|
const client = {
|
||||||
|
|||||||
@@ -23,7 +23,12 @@ import {
|
|||||||
type BillActionOptions,
|
type BillActionOptions,
|
||||||
type BillActionTarget,
|
type BillActionTarget,
|
||||||
} from "./api.js";
|
} from "./api.js";
|
||||||
import type { TranslatorOptions } from "./translator.js";
|
import {
|
||||||
|
formatBillFlowOperator,
|
||||||
|
translateBillFlowAction,
|
||||||
|
translateBillFlowState,
|
||||||
|
type TranslatorOptions,
|
||||||
|
} from "./translator.js";
|
||||||
import {
|
import {
|
||||||
type RawBillItem,
|
type RawBillItem,
|
||||||
type FormattedBill,
|
type FormattedBill,
|
||||||
@@ -875,17 +880,30 @@ export async function getBillFlow(
|
|||||||
const nextOperators = Array.isArray(log.nextOperatorIds)
|
const nextOperators = Array.isArray(log.nextOperatorIds)
|
||||||
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||||
: [];
|
: [];
|
||||||
|
const operator = flowPerson(log.operatorId);
|
||||||
|
const isEbot = attributes.isEbotNode === true || `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase().includes("ebot");
|
||||||
|
const labeledOperator = isEbot
|
||||||
|
? { ...(operator || { id: "ebot" }), name: "Ebot (智能审批)" }
|
||||||
|
: operator;
|
||||||
|
const rawAction = typeof log.action === "string" ? log.action : undefined;
|
||||||
|
const rawState = typeof log.state === "string" ? log.state : undefined;
|
||||||
return {
|
return {
|
||||||
id: typeof log.id === "string" ? log.id : undefined,
|
id: typeof log.id === "string" ? log.id : undefined,
|
||||||
time: currentTime,
|
time: currentTime,
|
||||||
durationMs,
|
durationMs,
|
||||||
state: typeof log.state === "string" ? log.state : undefined,
|
state: translateBillFlowState(rawState),
|
||||||
action: typeof log.action === "string" ? log.action : undefined,
|
rawState,
|
||||||
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
|
action: translateBillFlowAction(rawAction),
|
||||||
|
rawAction,
|
||||||
|
nodeName: typeof attributes.nodeName === "string" && attributes.nodeName
|
||||||
|
? attributes.nodeName
|
||||||
|
: typeof attributes.nextName === "string" && attributes.nextName
|
||||||
|
? attributes.nextName
|
||||||
|
: translateBillFlowAction(rawAction) === "打印单据" ? "打印提醒" : undefined,
|
||||||
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
|
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
|
||||||
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
|
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
|
||||||
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
|
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
|
||||||
operator: flowPerson(log.operatorId),
|
operator: labeledOperator,
|
||||||
nextOperators,
|
nextOperators,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -903,7 +921,7 @@ export async function getBillFlow(
|
|||||||
id: typeof node.id === "string" ? node.id : undefined,
|
id: typeof node.id === "string" ? node.id : undefined,
|
||||||
name: typeof node.name === "string" ? node.name : undefined,
|
name: typeof node.name === "string" ? node.name : undefined,
|
||||||
type: typeof node.type === "string" ? node.type : undefined,
|
type: typeof node.type === "string" ? node.type : undefined,
|
||||||
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
|
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "当前" : "后续",
|
||||||
approver,
|
approver,
|
||||||
approvers,
|
approvers,
|
||||||
};
|
};
|
||||||
@@ -916,7 +934,7 @@ export async function getBillFlow(
|
|||||||
flowId: typeof flow.id === "string" ? flow.id : undefined,
|
flowId: typeof flow.id === "string" ? flow.id : undefined,
|
||||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||||
title: typeof form.title === "string" ? form.title : undefined,
|
title: typeof form.title === "string" ? form.title : undefined,
|
||||||
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
|
state: translateBillFlowState(typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined),
|
||||||
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
|
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
|
||||||
history,
|
history,
|
||||||
pending,
|
pending,
|
||||||
@@ -1425,6 +1443,9 @@ export async function getTranslatorContext(
|
|||||||
|
|
||||||
export {
|
export {
|
||||||
translateBillFlowToMarkdown,
|
translateBillFlowToMarkdown,
|
||||||
|
formatBillFlowOperator,
|
||||||
|
translateBillFlowAction,
|
||||||
|
translateBillFlowState,
|
||||||
formatAmountValue,
|
formatAmountValue,
|
||||||
formatDateValue,
|
formatDateValue,
|
||||||
formatPersonValue,
|
formatPersonValue,
|
||||||
|
|||||||
@@ -130,6 +130,52 @@ export interface TranslatorOptions {
|
|||||||
datalinkCardMap?: Map<string, string>;
|
datalinkCardMap?: Map<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BILL_FLOW_ACTION_LABELS: Record<string, string> = {
|
||||||
|
"freeflow.submit": "提交送审",
|
||||||
|
"freeflow.agree": "审批同意",
|
||||||
|
"freeflow.autoAgree": "自动同意",
|
||||||
|
"freeflow.reject": "审批驳回",
|
||||||
|
"freeflow.print": "打印单据",
|
||||||
|
"freeflow.retract": "单据撤回",
|
||||||
|
"freeflow.addnode": "加签/转交",
|
||||||
|
"freeflow.comment": "发表评论",
|
||||||
|
};
|
||||||
|
|
||||||
|
const BILL_FLOW_STATE_LABELS: Record<string, string> = {
|
||||||
|
APPROVING: "审批中",
|
||||||
|
APPROVED: "审批通过",
|
||||||
|
REJECTED: "审批驳回",
|
||||||
|
REVOKED: "已撤回",
|
||||||
|
CANCELED: "已取消",
|
||||||
|
CANCELLED: "已取消",
|
||||||
|
SKIPPED: "已跳过",
|
||||||
|
SUBMITTED: "已提交",
|
||||||
|
PENDING: "待审批",
|
||||||
|
WAITING: "待处理",
|
||||||
|
COMPLETED: "已完成",
|
||||||
|
DRAFT: "草稿",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function translateBillFlowAction(action?: string): string | undefined {
|
||||||
|
if (!action) return undefined;
|
||||||
|
return BILL_FLOW_ACTION_LABELS[action] || action;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function translateBillFlowState(state?: string): string | undefined {
|
||||||
|
if (!state) return undefined;
|
||||||
|
return BILL_FLOW_STATE_LABELS[state.toUpperCase()] || state;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatBillFlowOperator(
|
||||||
|
operator?: { id?: string; name?: string },
|
||||||
|
automatic = false,
|
||||||
|
isEbot = false
|
||||||
|
): string {
|
||||||
|
const raw = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase();
|
||||||
|
if (isEbot || raw.includes("ebot")) return "Ebot (智能审批)";
|
||||||
|
return operator?.name || (automatic ? "系统" : "-");
|
||||||
|
}
|
||||||
|
|
||||||
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
|
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function formatDepartmentValue(
|
export function formatDepartmentValue(
|
||||||
|
|||||||
@@ -109,7 +109,9 @@ export interface BillFlowEntry {
|
|||||||
time?: number;
|
time?: number;
|
||||||
durationMs?: number;
|
durationMs?: number;
|
||||||
state?: string;
|
state?: string;
|
||||||
|
rawState?: string;
|
||||||
action?: string;
|
action?: string;
|
||||||
|
rawAction?: string;
|
||||||
nodeName?: string;
|
nodeName?: string;
|
||||||
comment?: string;
|
comment?: string;
|
||||||
automatic?: boolean;
|
automatic?: boolean;
|
||||||
|
|||||||
Reference in new issue
Block a user