feat: add bill attachment download command
This commit is contained in:
1 parent
a5bfaafa10
commit
17e5418005
8 files changed
+225
-6
No files matched your search
@@ -39,6 +39,7 @@ metadata:
|
||||
| 单据关联关系 / 冲借款与前置申请追溯 | `hose bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件下载 | `hose bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
|
||||
| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) |
|
||||
| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose permission get` | [references/role.md](references/role.md) |
|
||||
@@ -85,6 +86,7 @@ hose bill refs S26000001 # 解析提交人、归属
|
||||
hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose bill attachments S26000001 # 查看附件和发票原件列表
|
||||
hose bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
|
||||
hose dimension list # 查看系统与自定义档案维度
|
||||
hose dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose role list # 查看企业角色定义
|
||||
|
||||
@@ -94,14 +94,19 @@ hose bill budget S26000001 --json
|
||||
|
||||
### 单据附件列表 (`bill attachments`)
|
||||
|
||||
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段:
|
||||
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
|
||||
|
||||
```bash
|
||||
hose bill attachments S26000001
|
||||
hose bill attachments S26000001 --json
|
||||
```
|
||||
|
||||
当前命令只读取并标准化附件元数据;下载通道待在带真实附件的测试单据上确认前端文件服务请求后接入。
|
||||
需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件:
|
||||
|
||||
```bash
|
||||
hose bill download S26000001 --output-dir ./downloads
|
||||
hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
|
||||
```
|
||||
|
||||
## 4. 单据实体元数据字典 (`bill schema`)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
downloadBillAttachments,
|
||||
getFieldDictionary,
|
||||
} from "../../domains/bill/tools.js";
|
||||
|
||||
@@ -380,6 +381,36 @@ export async function handleBillCommand(
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "download":
|
||||
case "file-download": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "link":
|
||||
case "url": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
@@ -442,6 +473,6 @@ export async function handleBillCommand(
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, refs <单号>, relations <单号>, attachments <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,15 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain("corpId=corpxx");
|
||||
});
|
||||
|
||||
test("脱敏对象存储签名 URL 中的临时凭证", () => {
|
||||
const input = "https://files.example/a.png?Expires=1&OSSAccessKeyId=key&Signature=sig&security-token=secret";
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).toContain("OSSAccessKeyId=<redacted>");
|
||||
expect(redacted).toContain("Signature=<redacted>");
|
||||
expect(redacted).toContain("security-token=<redacted>");
|
||||
expect(redacted).not.toContain("secret");
|
||||
});
|
||||
|
||||
test("脱敏 Authorization Bearer token", () => {
|
||||
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||
const redacted = redactSensitiveText(input);
|
||||
|
||||
+3
-2
@@ -6,7 +6,7 @@ export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
@@ -119,7 +119,7 @@ export function printHelp(): string {
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, refs <单号|ID>, relations <单号|ID>, attachments <单号|ID>, flow <单号|ID>, risk <单号|ID>, budget <单号|ID>, schema, link <单号|ID>)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, refs <单号|ID>, relations <单号|ID>, attachments <单号|ID>, download <单号|ID>, flow <单号|ID>, risk <单号|ID>, budget <单号|ID>, schema, link <单号|ID>)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
@@ -169,6 +169,7 @@ export function printHelp(): string {
|
||||
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use role list # 查看企业角色定义
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
@@ -182,6 +183,33 @@ export async function getRawBillsByIds(
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 附件文件元数据与签名下载地址 API ──────────────────────────────────────────
|
||||
|
||||
const AttachmentFileSchema = z.object({
|
||||
id: z.string(),
|
||||
key: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
thumbUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
export type AttachmentFile = z.infer<typeof AttachmentFileSchema>;
|
||||
|
||||
export async function resolveAttachmentFiles(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[],
|
||||
): Promise<AttachmentFile[]> {
|
||||
if (ids.length === 0) return [];
|
||||
|
||||
const response = await client.post("api/v1/attachment/attachments/ids", {
|
||||
searchParams: { corpId },
|
||||
json: { ids },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(AttachmentFileSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
|
||||
|
||||
export async function listEntitySchemas(
|
||||
|
||||
@@ -145,4 +145,28 @@ describe("Bill Domain", () => {
|
||||
expect(result?.attachments[0]?.fileId).toBe("file-1");
|
||||
expect(result?.attachments[0]?.fileName).toBe("receipt.pdf");
|
||||
});
|
||||
|
||||
it("enriches attachment metadata with file-service download URLs", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("attachment/attachments/ids")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [{ id: "file-2", key: "receipt-key", name: "receipt.pdf", url: "https://files.example/receipt.pdf", thumbUrl: "https://files.example/thumb" }],
|
||||
}));
|
||||
}
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillAttachments(client, "corp-files", "E26000003");
|
||||
expect(result?.attachments[0]).toMatchObject({
|
||||
fileId: "file-2",
|
||||
fileName: "receipt.pdf",
|
||||
key: "receipt-key",
|
||||
url: "https://files.example/receipt.pdf",
|
||||
thumbUrl: "https://files.example/thumb",
|
||||
});
|
||||
});
|
||||
});
|
||||
+120
-1
@@ -1,5 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { basename, extname, join, resolve } from "node:path";
|
||||
import {
|
||||
searchRawBills,
|
||||
getRawBillsByIds,
|
||||
@@ -9,6 +12,7 @@ import {
|
||||
listActiveStaffCatalog,
|
||||
getDepartmentTree,
|
||||
getFeeTypeTree,
|
||||
resolveAttachmentFiles,
|
||||
} from "./api.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
@@ -424,16 +428,131 @@ export async function getBillAttachments(
|
||||
const attachments: BillAttachment[] = [];
|
||||
collectAttachments("form", form, attachments);
|
||||
const deduped = [...new Map(attachments.map((item) => [`${item.fileId || ""}|${item.key || ""}|${item.fileName || ""}`, item])).values()];
|
||||
const fileIds = deduped
|
||||
.map((item) => item.fileId)
|
||||
.filter((fileId): fileId is string => Boolean(fileId));
|
||||
let resolved: Awaited<ReturnType<typeof resolveAttachmentFiles>> = [];
|
||||
try {
|
||||
resolved = await resolveAttachmentFiles(client, corpId, fileIds);
|
||||
} catch {
|
||||
// 附件元数据接口不可用时,仍返回审批详情中已经拿到的原始字段。
|
||||
}
|
||||
const resolvedById = new Map(resolved.map((item) => [item.id, item]));
|
||||
const enriched = deduped.map((item) => {
|
||||
const metadata = item.fileId ? resolvedById.get(item.fileId) : undefined;
|
||||
if (!metadata) return item;
|
||||
return {
|
||||
...item,
|
||||
key: item.key ?? metadata.key,
|
||||
fileName: item.fileName ?? metadata.name,
|
||||
url: item.url ?? metadata.url,
|
||||
thumbUrl: item.thumbUrl ?? metadata.thumbUrl,
|
||||
raw: { ...item.raw, resolved: metadata },
|
||||
};
|
||||
});
|
||||
return {
|
||||
target,
|
||||
billId,
|
||||
billCode,
|
||||
title,
|
||||
attachments: deduped,
|
||||
attachments: enriched,
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
export interface DownloadedBillAttachment {
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
key?: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
function safeAttachmentName(value: string): string {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/?%*:|"<>]/g, "_")
|
||||
.replace(/^\.+/, "_")
|
||||
.trim();
|
||||
return cleaned || "attachment";
|
||||
}
|
||||
|
||||
function uniqueAttachmentPath(outputDir: string, fileName: string, fileId: string | undefined, used: Set<string>): string {
|
||||
const extension = extname(fileName);
|
||||
const stem = extension ? fileName.slice(0, -extension.length) : fileName;
|
||||
let index = 0;
|
||||
while (true) {
|
||||
const suffix = index === 0 ? "" : fileId ? `-${fileId}${index > 1 ? `-${index}` : ""}` : `-copy${index > 1 ? `-${index}` : ""}`;
|
||||
const candidate = join(outputDir, `${stem}${suffix}${extension}`);
|
||||
if (!used.has(candidate) && !existsSync(candidate)) {
|
||||
used.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadBillAttachments(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
outputDir: string,
|
||||
fileId?: string,
|
||||
): Promise<{
|
||||
target: string;
|
||||
outputDir: string;
|
||||
requestedFileId?: string;
|
||||
downloaded: DownloadedBillAttachment[];
|
||||
skipped: number;
|
||||
report: BillAttachmentReport;
|
||||
}> {
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) throw new Error(`未找到单据附件: ${target}`);
|
||||
|
||||
const selected = fileId
|
||||
? report.attachments.filter((item) => item.fileId === fileId)
|
||||
: report.attachments;
|
||||
if (fileId && selected.length === 0) {
|
||||
throw new Error(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
|
||||
}
|
||||
|
||||
const destination = resolve(outputDir);
|
||||
await mkdir(destination, { recursive: true });
|
||||
const usedPaths = new Set<string>();
|
||||
const downloaded: DownloadedBillAttachment[] = [];
|
||||
let skipped = 0;
|
||||
|
||||
for (const attachment of selected) {
|
||||
if (!attachment.url) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
const sourceName = attachment.fileName || attachment.key || attachment.fileId || "attachment";
|
||||
const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths);
|
||||
const response = await fetch(attachment.url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`附件下载失败 (${response.status}): ${sourceName}`);
|
||||
}
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
await writeFile(path, content);
|
||||
downloaded.push({
|
||||
fileId: attachment.fileId,
|
||||
fileName: attachment.fileName,
|
||||
key: attachment.key,
|
||||
path,
|
||||
bytes: content.byteLength,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
outputDir: destination,
|
||||
requestedFileId: fileId,
|
||||
downloaded,
|
||||
skipped,
|
||||
report,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function formatSingleBill(
|
||||
|
||||
Reference in new issue
Block a user