feat(feetype): add fee type domain CRUD CLI commands and specifications

This commit is contained in:
gitea committed 2026-09-09 16:25:03 +08:00
1 parent 0be629778f
commit fb700a4c86
16 files changed
+2168 -2

No files matched your search

+1
View File
@@ -10,6 +10,7 @@
| `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) |
| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
## 分层规则
+68
View File
@@ -0,0 +1,68 @@
# FeeType (费用类型) 域说明
费用类型域负责合思/易快报企业费用类型的全生命周期管理,涵盖:
- 费用类型树与平铺目录查询(活跃 / 包含停用)
- 费用类型增删查改(新建、属性修改、软停用、级联启用、移动层级)
- 费用类型表单字段规格解析(报账字段与申请字段元数据)
## 架构职责
```text
CLI (feetype.ts) / MCP (feetypeTools in server.ts)
│
▼
domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规格继承、增删查改封装)
│
▼
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
│
▼
core/auth/ekb.ts (企业身份认证与凭证管理)
```
## 接口路由映射
| 操作 | HTTP 方法与路径 | 说明 |
|---|---|---|
| 获取活跃树 | `GET /api/v1/form/feeTypes/tree/active` | 获取用户端可见的活跃费用类型树 |
| 获取全量树 | `GET /api/v1/form/feeTypes/tree` | 包含已停用的全量费用类型树 |
| 获取单项详情 | `GET /api/v1/form/feeTypes/$id` | 精准获取持久化配置 |
| 获取表单规格 | `GET /api/form/v2/specifications/feeType/[id]` | 获取报账与申请字段定义 |
| 获取默认模板 | `GET /api/form/v2/specifications/default/$type` | 获取 expense / requisition 预置字段 |
| 新建费用类型 | `POST /api/v1/form/feeTypes` | 批量/单个创建,支持字段规则继承 |
| 更新费用类型 | `PUT /api/v1/form/feeTypes/$id` | 更新名称、编码、英文名、图标、颜色 |
| 停用费用类型 | `PUT /api/v1/form/feeTypes/[ids]/disable` | 软删除停用 |
| 启用费用类型 | `PUT /api/v1/form/feeTypes/$id/restore` | 重新启用(可级联) |
| 移动父级节点 | `PUT /api/v1/form/feeTypes/[ids]/parent` | 调整层级关系 |
## CLI 命令速查
```bash
# 查看费用类型树
hose-use feetype list
hose-use feetype list --all
hose-use feetype list --keyword="差旅"
hose-use feetype list --flat
# 查看单个费用类型详情
hose-use feetype get 交通费
hose-use feetype get 交通费 --specs
# 创建费用类型
hose-use feetype create --name="办公杂费"
hose-use feetype create --name="市内打车" --parent="交通费"
# 修改费用类型
hose-use feetype update 市内打车 --desc="滴滴企业版"
# 停用与启用
hose-use feetype disable 市内打车
hose-use feetype enable 市内打车
# 移动层级
hose-use feetype move 市内打车 --parent="差旅费用"
hose-use feetype move 市内打车 --parent=root
# 查看表单字段配置
hose-use feetype fields 交通费
```
+294
View File
@@ -0,0 +1,294 @@
import type { KyInstance } from "ky";
import {
FeeTypeDetailResponseSchema,
FeeTypeSpecificationResponseSchema,
FeeTypeTreeResponseSchema,
FeeTypeCreateResultSchema,
DefaultSpecResponseSchema,
FeeTypeNode,
FeeTypeItem,
FeeTypeSpecificationItem,
FeeTypeCreateResult,
FeeTypeComponent,
} from "./types.js";
import { BusinessError } from "../../core/errors.js";
/**
* 获取活跃费用类型树 (GET api/v1/form/feeTypes/tree/active)
*/
export async function getActiveFeeTypeTree(
client: KyInstance,
corpId: string
): Promise<FeeTypeNode[]> {
try {
const raw = await client
.get("api/v1/form/feeTypes/tree/active", {
searchParams: { corpId },
})
.json();
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
if (parsed.success) return parsed.data.items;
if (Array.isArray(raw)) {
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
}
return [];
} catch (err: any) {
throw new BusinessError(
`获取活跃费用类型树失败: ${err.message || String(err)}`,
"GET_ACTIVE_FEETYPE_FAILED"
);
}
}
/**
* 获取全量费用类型树 (含已停用) (GET api/v1/form/feeTypes/tree)
*/
export async function getFullFeeTypeTree(
client: KyInstance,
corpId: string
): Promise<FeeTypeNode[]> {
try {
const raw = await client
.get("api/v1/form/feeTypes/tree", {
searchParams: {
corpId,
join: "id,feetypeTemplate,/form/v2/specifications/feeType",
join$2: "children.id,feetypeTemplate,/form/v2/specifications/feeType",
},
})
.json();
const parsed = FeeTypeTreeResponseSchema.safeParse(raw);
if (parsed.success) return parsed.data.items;
if (Array.isArray(raw)) {
return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object"));
}
return [];
} catch (err: any) {
throw new BusinessError(
`获取全量费用类型树失败: ${err.message || String(err)}`,
"GET_FULL_FEETYPE_FAILED"
);
}
}
/**
* 获取单条费用类型详情 (GET api/v1/form/feeTypes/$id)
*/
export async function getFeeTypeById(
client: KyInstance,
corpId: string,
id: string
): Promise<FeeTypeItem> {
try {
const raw = await client
.get(`api/v1/form/feeTypes/$${id}`, {
searchParams: { corpId },
})
.json();
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
if (parsed.success) return parsed.data.value;
if (raw && typeof raw === "object" && "value" in raw) {
return (raw as any).value as FeeTypeItem;
}
return raw as FeeTypeItem;
} catch (err: any) {
throw new BusinessError(
`获取费用类型 [${id}] 详情失败: ${err.message || String(err)}`,
"GET_FEETYPE_DETAIL_FAILED"
);
}
}
/**
* 获取费用类型的表单字段规格定义 (GET api/form/v2/specifications/feeType/[id])
*/
export async function getFeeTypeSpecification(
client: KyInstance,
corpId: string,
id: string
): Promise<FeeTypeSpecificationItem | undefined> {
try {
const raw = await client
.get(`api/form/v2/specifications/feeType/[${id}]`, {
searchParams: { id, corpId },
})
.json();
const parsed = FeeTypeSpecificationResponseSchema.safeParse(raw);
if (parsed.success && parsed.data.items.length > 0) {
return parsed.data.items[0];
}
if (raw && typeof raw === "object" && Array.isArray((raw as any).items)) {
return (raw as any).items[0];
}
return undefined;
} catch (err: any) {
throw new BusinessError(
`获取费用类型 [${id}] 字段规格失败: ${err.message || String(err)}`,
"GET_FEETYPE_SPEC_FAILED"
);
}
}
/**
* 获取默认报账字段模板 (GET api/form/v2/specifications/default/$feeType_expense)
*/
export async function getDefaultExpenseSpec(
client: KyInstance,
corpId: string
): Promise<FeeTypeComponent[]> {
try {
const raw = await client
.get("api/form/v2/specifications/default/$feeType_expense", {
searchParams: { type: "feeType_expense", corpId },
})
.json();
const parsed = DefaultSpecResponseSchema.safeParse(raw);
return parsed.success ? (parsed.data.components ?? []) : [];
} catch {
return [];
}
}
/**
* 获取默认申请字段模板 (GET api/form/v2/specifications/default/$feeType_requisition)
*/
export async function getDefaultRequisitionSpec(
client: KyInstance,
corpId: string
): Promise<FeeTypeComponent[]> {
try {
const raw = await client
.get("api/form/v2/specifications/default/$feeType_requisition", {
searchParams: { type: "feeType_requisition", corpId },
})
.json();
const parsed = DefaultSpecResponseSchema.safeParse(raw);
return parsed.success ? (parsed.data.components ?? []) : [];
} catch {
return [];
}
}
/**
* 批量创建费用类型 (POST api/v1/form/feeTypes)
*/
export async function createFeeTypes(
client: KyInstance,
corpId: string,
items: Record<string, unknown>[]
): Promise<FeeTypeCreateResult> {
try {
const raw = await client
.post("api/v1/form/feeTypes", {
searchParams: { corpId },
json: { data: items },
})
.json();
const parsed = FeeTypeCreateResultSchema.safeParse(raw);
if (parsed.success) return parsed.data;
return raw as FeeTypeCreateResult;
} catch (err: any) {
throw new BusinessError(
`创建费用类型失败: ${err.message || String(err)}`,
"CREATE_FEETYPE_FAILED"
);
}
}
/**
* 更新费用类型基本信息 (PUT api/v1/form/feeTypes/$id)
*/
export async function updateFeeType(
client: KyInstance,
corpId: string,
id: string,
body: Record<string, unknown>
): Promise<FeeTypeItem> {
try {
const raw = await client
.put(`api/v1/form/feeTypes/$${id}`, {
searchParams: { corpId },
json: body,
})
.json();
const parsed = FeeTypeDetailResponseSchema.safeParse(raw);
if (parsed.success) return parsed.data.value;
if (raw && typeof raw === "object" && "value" in raw) {
return (raw as any).value as FeeTypeItem;
}
return raw as FeeTypeItem;
} catch (err: any) {
throw new BusinessError(
`更新费用类型 [${id}] 失败: ${err.message || String(err)}`,
"UPDATE_FEETYPE_FAILED"
);
}
}
/**
* 批量停用费用类型 (PUT api/v1/form/feeTypes/[ids]/disable)
*/
export async function disableFeeTypes(
client: KyInstance,
corpId: string,
ids: string[]
): Promise<boolean> {
try {
const idsParam = `[${ids.join(",")}]`;
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/disable`, {
searchParams: { corpId },
});
return res.status === 200 || res.status === 204;
} catch (err: any) {
throw new BusinessError(
`停用费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
"DISABLE_FEETYPE_FAILED"
);
}
}
/**
* 启用已停用的费用类型 (PUT api/v1/form/feeTypes/$id/restore)
*/
export async function restoreFeeType(
client: KyInstance,
corpId: string,
id: string,
recursive = true
): Promise<boolean> {
try {
const res = await client.put(`api/v1/form/feeTypes/$${id}/restore`, {
searchParams: { corpId, recursive: String(recursive) },
});
return res.status === 200 || res.status === 204;
} catch (err: any) {
throw new BusinessError(
`启用费用类型 [${id}] 失败: ${err.message || String(err)}`,
"RESTORE_FEETYPE_FAILED"
);
}
}
/**
* 移动费用类型父级 (PUT api/v1/form/feeTypes/[ids]/parent)
*/
export async function moveFeeTypes(
client: KyInstance,
corpId: string,
ids: string[],
parentId: string
): Promise<boolean> {
try {
const idsParam = `[${ids.join(",")}]`;
const res = await client.put(`api/v1/form/feeTypes/${idsParam}/parent`, {
searchParams: { corpId },
json: { parentId: parentId || "" },
});
return res.status === 200 || res.status === 204;
} catch (err: any) {
throw new BusinessError(
`移动费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`,
"MOVE_FEETYPE_FAILED"
);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { describe, it, expect } from "bun:test";
import { flattenFeeTypeTree } from "./tools.js";
import { FeeTypeNode } from "./types.js";
describe("domains/feetype > tools & helpers", () => {
const sampleTree = [
{
feeType: {
id: "node_1",
name: "差旅费",
code: "COST01",
active: true,
parentId: "",
},
children: [
{
feeType: {
id: "node_1_1",
name: "机票",
code: "COST01_1",
active: true,
parentId: "node_1",
},
children: [
{
feeType: {
id: "node_1_1_1",
name: "退改签",
code: "COST01_1_1",
active: true,
parentId: "node_1_1",
},
children: [],
},
],
},
],
},
{
feeType: {
id: "node_2",
name: "办公费",
code: "COST02",
active: false,
parentId: "",
},
children: [],
},
] as unknown as FeeTypeNode[];
it("flattenFeeTypeTree 正确递归展开全路径与父级关系", () => {
const flat = flattenFeeTypeTree(sampleTree);
expect(flat.length).toBe(4);
expect(flat[0].name).toBe("差旅费");
expect(flat[0].path).toBe("差旅费");
expect(flat[0].childrenCount).toBe(1);
expect(flat[1].name).toBe("机票");
expect(flat[1].path).toBe("差旅费 / 机票");
expect(flat[1].parentName).toBe("差旅费");
expect(flat[1].childrenCount).toBe(1);
expect(flat[2].name).toBe("退改签");
expect(flat[2].path).toBe("差旅费 / 机票 / 退改签");
expect(flat[2].parentName).toBe("机票");
expect(flat[2].childrenCount).toBe(0);
expect(flat[3].name).toBe("办公费");
expect(flat[3].path).toBe("办公费");
expect(flat[3].parentName).toBe("");
expect(flat[3].active).toBe(false);
});
});
+548
View File
@@ -0,0 +1,548 @@
import type { KyInstance } from "ky";
import { z } from "zod";
import {
FeeTypeComponent,
FeeTypeCreateInput,
FeeTypeItem,
FeeTypeNode,
FeeTypeQueryOptions,
FeeTypeUpdateInput,
FeeTypeView,
} from "./types.js";
import {
createFeeTypes,
disableFeeTypes,
getActiveFeeTypeTree,
getDefaultExpenseSpec,
getDefaultRequisitionSpec,
getFeeTypeById,
getFeeTypeSpecification,
getFullFeeTypeTree,
moveFeeTypes,
restoreFeeType,
updateFeeType,
} from "./api.js";
import { BusinessError } from "../../core/errors.js";
// ── 树遍历与平铺辅助 ─────────────────────────────────────────────────────────
export interface FlatFeeTypeItem extends FeeTypeItem {
path: string;
parentName: string;
childrenCount: number;
}
export function flattenFeeTypeTree(
nodes: FeeTypeNode[],
parentPath = "",
parentName = ""
): FlatFeeTypeItem[] {
const result: FlatFeeTypeItem[] = [];
for (const node of nodes) {
const item = node.feeType;
if (!item || !item.id) continue;
const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name;
const children = Array.isArray(node.children) ? node.children : [];
result.push({
...item,
path: currentPath,
parentName,
childrenCount: children.length,
});
if (children.length > 0) {
result.push(...flattenFeeTypeTree(children, currentPath, item.name));
}
}
return result;
}
/**
* 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用)
*/
function cleanComponents(list: FeeTypeComponent[]): Record<string, unknown>[] {
return list.map((item) => {
const copy = { ...item } as Record<string, unknown>;
delete copy.id;
delete copy.dataType;
delete copy.showValue;
delete copy.status;
delete copy.entityInfo;
delete copy.isLinkageFilter;
return copy;
});
}
// ── 核心业务编排 ─────────────────────────────────────────────────────────────
/**
* 模糊或精准解析单个费用类型节点 (支持按 ID, Code, Name 查找)
*/
export async function findFeeType(
client: KyInstance,
corpId: string,
target: string,
options: { all?: boolean } = {}
): Promise<FlatFeeTypeItem | undefined> {
const clean = target.trim();
if (!clean) return undefined;
const tree = options.all
? await getFullFeeTypeTree(client, corpId)
: await getActiveFeeTypeTree(client, corpId);
const flat = flattenFeeTypeTree(tree);
// 1. 精确 ID 匹配
const byId = flat.find((item) => item.id === clean);
if (byId) return byId;
// 2. 精确 Code 匹配 (不区分大小写)
const byCode = flat.find((item) => item.code.toLowerCase() === clean.toLowerCase());
if (byCode) return byCode;
// 3. 精确 Name 匹配
const byName = flat.find((item) => item.name === clean);
if (byName) return byName;
// 4. 包含匹配 (Name / Spell / EnName)
const byPartial = flat.find(
(item) =>
item.name.includes(clean) ||
(item.enName && item.enName.toLowerCase().includes(clean.toLowerCase()))
);
return byPartial;
}
/**
* 查询费用类型列表 (树形或平铺)
*/
export async function listFeeTypes(
client: KyInstance,
corpId: string,
options: FeeTypeQueryOptions = {}
): Promise<{
total: number;
items: FlatFeeTypeItem[] | FeeTypeNode[];
rawTree: FeeTypeNode[];
}> {
const rawTree = options.all
? await getFullFeeTypeTree(client, corpId)
: await getActiveFeeTypeTree(client, corpId);
let flat = flattenFeeTypeTree(rawTree);
if (options.keyword?.trim()) {
const kw = options.keyword.trim().toLowerCase();
flat = flat.filter(
(item) =>
item.name.toLowerCase().includes(kw) ||
item.code.toLowerCase().includes(kw) ||
(item.enName && item.enName.toLowerCase().includes(kw)) ||
item.path.toLowerCase().includes(kw)
);
}
return {
total: flat.length,
items: options.flat ? flat : (options.keyword ? flat : rawTree),
rawTree,
};
}
/**
* 获取费用类型详细信息 (含字段规格)
*/
export async function getFeeTypeDetail(
client: KyInstance,
corpId: string,
target: string,
options: { includeSpecs?: boolean } = {}
): Promise<{
feeType: FlatFeeTypeItem;
specifications?: {
expenseComponents: FeeTypeComponent[];
requisitionComponents: FeeTypeComponent[];
};
}> {
const found = await findFeeType(client, corpId, target, { all: true });
if (!found) {
throw new BusinessError(
`未找到匹配的费用类型: "${target}" (可尝试按编码或全称检索)`,
"FEETYPE_NOT_FOUND"
);
}
// 获取最新的精确持久化属性
const fresh = await getFeeTypeById(client, corpId, found.id);
const resultItem: FlatFeeTypeItem = {
...fresh,
path: found.path,
parentName: found.parentName,
childrenCount: found.childrenCount,
};
if (!options.includeSpecs) {
return { feeType: resultItem };
}
const spec = await getFeeTypeSpecification(client, corpId, found.id);
return {
feeType: resultItem,
specifications: {
expenseComponents: spec?.expenseComponents ?? [],
requisitionComponents: spec?.requisitionComponents ?? [],
},
};
}
/**
* 创建费用类型 (支持自动/指定编码、父级继承与字段规格适配)
*/
export async function createFeeType(
client: KyInstance,
corpId: string,
input: FeeTypeCreateInput
): Promise<FlatFeeTypeItem> {
const name = input.name.trim();
if (!name) {
throw new BusinessError("费用类型名称不能为空", "INVALID_FEETYPE_NAME");
}
let resolvedParentId = "";
let inheritedExpenseComponents: Record<string, unknown>[] = [];
let inheritedRequisitionComponents: Record<string, unknown>[] = [];
if (input.parentId?.trim()) {
const parent = await findFeeType(client, corpId, input.parentId.trim(), { all: true });
if (!parent) {
throw new BusinessError(
`指定的父级费用类型 "${input.parentId}" 不存在`,
"PARENT_FEETYPE_NOT_FOUND"
);
}
resolvedParentId = parent.id;
// 继承父级费用类型的字段设置
const parentSpec = await getFeeTypeSpecification(client, corpId, parent.id);
if (parentSpec) {
inheritedExpenseComponents = cleanComponents(parentSpec.expenseComponents ?? []);
inheritedRequisitionComponents = cleanComponents(parentSpec.requisitionComponents ?? []);
}
}
// 若无父级或父级无规格,加载系统预置默认字段规格
if (!inheritedExpenseComponents.length) {
const defaultExp = await getDefaultExpenseSpec(client, corpId);
inheritedExpenseComponents = cleanComponents(defaultExp);
}
if (!inheritedRequisitionComponents.length) {
const defaultReq = await getDefaultRequisitionSpec(client, corpId);
inheritedRequisitionComponents = cleanComponents(defaultReq);
}
// 确定唯一编码
let code = input.code?.trim();
if (!code) {
const allTree = await getFullFeeTypeTree(client, corpId);
const flat = flattenFeeTypeTree(allTree);
const existingCodes = new Set(flat.map((item) => item.code.toUpperCase()));
let seq = flat.length + 1;
code = `COST${seq}`;
while (existingCodes.has(code)) {
seq++;
code = `COST${seq}`;
}
}
const payloadItem = {
type: "ALL",
name,
enName: input.enName?.trim() || "",
code,
parentId: resolvedParentId,
description: input.description?.trim() || "",
color: input.color || "#90caf9",
icon: input.icon || "https://images.ekuaibao.com/feetype/sf_100.png",
expenseComponents: input.expenseComponents?.length
? input.expenseComponents
: inheritedExpenseComponents,
requisitionComponents: input.requisitionComponents?.length
? input.requisitionComponents
: inheritedRequisitionComponents,
};
const createRes = await createFeeTypes(client, corpId, [payloadItem]);
if (createRes.value?.errorMsgs?.length) {
throw new BusinessError(
`创建费用类型失败: ${createRes.value.errorMsgs.join("; ")}`,
"CREATE_FEETYPE_REJECTED"
);
}
const newId = createRes.value?.ids?.[0];
if (!newId) {
throw new BusinessError("创建接口未返回新增的费用类型 ID", "CREATE_FEETYPE_NO_ID");
}
const created = await getFeeTypeDetail(client, corpId, newId);
return created.feeType;
}
/**
* 修改费用类型属性 (名称、编码、英文名、图标、颜色、描述)
*/
export async function updateFeeTypeInfo(
client: KyInstance,
corpId: string,
target: string,
patch: FeeTypeUpdateInput
): Promise<FlatFeeTypeItem> {
const found = await findFeeType(client, corpId, target, { all: true });
if (!found) {
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
}
const current = await getFeeTypeById(client, corpId, found.id);
const updatedBody: Record<string, unknown> = {
id: found.id,
type: "FEETYPE",
name: patch.name !== undefined ? patch.name.trim() : current.name,
code: patch.code !== undefined ? patch.code.trim() : current.code,
enName: patch.enName !== undefined ? patch.enName.trim() : (current.enName || ""),
description: patch.description !== undefined ? patch.description.trim() : (current.description || ""),
color: patch.color !== undefined ? patch.color.trim() : (current.color || "#90caf9"),
icon: patch.icon !== undefined ? patch.icon.trim() : (current.icon || "https://images.ekuaibao.com/feetype/sf_100.png"),
};
await updateFeeType(client, corpId, found.id, updatedBody);
const fresh = await getFeeTypeDetail(client, corpId, found.id);
return fresh.feeType;
}
/**
* 停用费用类型 (软删除)
*/
export async function disableFeeTypeItem(
client: KyInstance,
corpId: string,
target: string
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
const found = await findFeeType(client, corpId, target, { all: true });
if (!found) {
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
}
if (!found.active) {
return { success: true, item: found };
}
const ok = await disableFeeTypes(client, corpId, [found.id]);
const fresh = await getFeeTypeDetail(client, corpId, found.id);
return { success: ok, item: fresh.feeType };
}
/**
* 启用费用类型 (可级联恢复)
*/
export async function enableFeeTypeItem(
client: KyInstance,
corpId: string,
target: string,
options: { recursive?: boolean } = { recursive: true }
): Promise<{ success: boolean; item: FlatFeeTypeItem }> {
const found = await findFeeType(client, corpId, target, { all: true });
if (!found) {
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
}
if (found.active) {
return { success: true, item: found };
}
const ok = await restoreFeeType(client, corpId, found.id, options.recursive ?? true);
const fresh = await getFeeTypeDetail(client, corpId, found.id);
return { success: ok, item: fresh.feeType };
}
/**
* 移动费用类型父级节点
*/
export async function moveFeeTypeItem(
client: KyInstance,
corpId: string,
target: string,
parentTarget?: string
): Promise<{ success: boolean; item: FlatFeeTypeItem; parentName: string }> {
const found = await findFeeType(client, corpId, target, { all: true });
if (!found) {
throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND");
}
let newParentId = "";
let newParentName = "根节点 (顶级)";
if (parentTarget && parentTarget !== "root" && parentTarget !== "0") {
const parent = await findFeeType(client, corpId, parentTarget, { all: true });
if (!parent) {
throw new BusinessError(
`目标父级费用类型 "${parentTarget}" 不存在`,
"PARENT_FEETYPE_NOT_FOUND"
);
}
if (parent.id === found.id) {
throw new BusinessError("不能将费用类型移动到其自身之下", "INVALID_MOVE_TARGET");
}
newParentId = parent.id;
newParentName = parent.name;
}
const ok = await moveFeeTypes(client, corpId, [found.id], newParentId);
const fresh = await getFeeTypeDetail(client, corpId, found.id);
return { success: ok, item: fresh.feeType, parentName: newParentName };
}
/**
* 获取费用类型的表单字段明细清单 (报账与申请字段)
*/
export async function getFeeTypeFieldsList(
client: KyInstance,
corpId: string,
target: string
): Promise<{
feeType: FlatFeeTypeItem;
expenseFields: {
field: string;
label: string;
type: string;
required: boolean;
editable: boolean;
hidden: boolean;
}[];
requisitionFields: {
field: string;
label: string;
type: string;
required: boolean;
editable: boolean;
hidden: boolean;
}[];
}> {
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs: true });
const mapComponent = (c: FeeTypeComponent) => ({
field: c.field || "-",
label: c.cnLabel || c.label || "-",
type: c.type || "text",
required: !c.optional,
editable: c.editable !== false,
hidden: Boolean(c.hide),
});
return {
feeType: detail.feeType,
expenseFields: (detail.specifications?.expenseComponents ?? []).map(mapComponent),
requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent),
};
}
// ── MCP Tool Definitions ─────────────────────────────────────────────────────
export const feetypeTools = [
{
name: "feetype_list",
description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"),
all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"),
flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"),
}),
handler: async (client: KyInstance, args: any) => {
return listFeeTypes(client, args.corpId, {
keyword: args.keyword,
all: args.all,
flat: args.flat,
});
},
},
{
name: "feetype_get",
description: "获取单个费用类型的详细配置与字段规格",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"),
}),
handler: async (client: KyInstance, args: any) => {
return getFeeTypeDetail(client, args.corpId, args.target, {
includeSpecs: args.includeSpecs,
});
},
},
{
name: "feetype_create",
description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
name: z.string().describe("费用类型名称"),
code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"),
parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"),
enName: z.string().optional().describe("英文名称"),
description: z.string().optional().describe("描述信息"),
color: z.string().optional().describe("标识颜色 (如 #90caf9)"),
}),
handler: async (client: KyInstance, args: any) => {
return createFeeType(client, args.corpId, args);
},
},
{
name: "feetype_update",
description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
name: z.string().optional().describe("新名称"),
code: z.string().optional().describe("新编码"),
enName: z.string().optional().describe("新英文名"),
description: z.string().optional().describe("新描述"),
color: z.string().optional().describe("新颜色"),
}),
handler: async (client: KyInstance, args: any) => {
return updateFeeTypeInfo(client, args.corpId, args.target, args);
},
},
{
name: "feetype_toggle",
description: "停用或启用费用类型",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("费用类型 ID、编码或名称"),
action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"),
recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"),
}),
handler: async (client: KyInstance, args: any) => {
if (args.action === "disable") {
return disableFeeTypeItem(client, args.corpId, args.target);
} else {
return enableFeeTypeItem(client, args.corpId, args.target, {
recursive: args.recursive,
});
}
},
},
{
name: "feetype_move",
description: "移动费用类型至新的父级节点 (传入 root 移至根目录)",
parameters: z.object({
corpId: z.string().describe("企业 ID"),
target: z.string().describe("待移动的费用类型 ID、编码或名称"),
parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"),
}),
handler: async (client: KyInstance, args: any) => {
return moveFeeTypeItem(client, args.corpId, args.target, args.parent);
},
},
];
+169
View File
@@ -0,0 +1,169 @@
import { z } from "zod";
// ── 费用类型基础实体 ─────────────────────────────────────────────────────────
export const FeeTypeItemSchema = z
.object({
id: z.string(),
name: z.string(),
code: z.string(),
enName: z.string().nullish().default(""),
parentId: z.string().nullish().default(""),
active: z.boolean().default(true),
order: z.number().nullish().default(1000000),
color: z.string().nullish().default("#90caf9"),
icon: z.string().nullish().default(""),
description: z.string().nullish().default(""),
corporationId: z.string().optional(),
expenseSpecificationId: z.string().nullish(),
requisitionSpecificationId: z.string().nullish(),
receiptSpecificationId: z.string().nullish(),
showPoint: z.boolean().nullish().default(false),
createTime: z.number().nullish(),
updateTime: z.number().nullish(),
permissions: z
.array(
z.object({
name: z.string(),
auth: z.boolean(),
})
)
.nullish()
.default([]),
})
.passthrough();
export type FeeTypeItem = z.infer<typeof FeeTypeItemSchema>;
// ── 树节点模型 ─────────────────────────────────────────────────────────────
export interface FeeTypeNode {
feeType: FeeTypeItem;
children: FeeTypeNode[];
}
export const FeeTypeNodeSchema: z.ZodType<FeeTypeNode> = z.lazy(() =>
z.object({
feeType: FeeTypeItemSchema,
children: z.array(FeeTypeNodeSchema).default([]),
})
);
export const FeeTypeTreeResponseSchema = z.object({
items: z.array(FeeTypeNodeSchema).default([]),
});
export type FeeTypeTreeResponse = z.infer<typeof FeeTypeTreeResponseSchema>;
export const FeeTypeDetailResponseSchema = z.object({
value: FeeTypeItemSchema,
});
export type FeeTypeDetailResponse = z.infer<typeof FeeTypeDetailResponseSchema>;
export const FeeTypeCreateResultSchema = z.object({
value: z
.object({
ids: z.array(z.string()).default([]),
names: z.record(z.string(), z.string()).optional(),
errorMsgs: z.array(z.string()).nullish().default([]),
})
.default({ ids: [], errorMsgs: [] }),
});
export type FeeTypeCreateResult = z.infer<typeof FeeTypeCreateResultSchema>;
// ── 字段配置与规格模型 ───────────────────────────────────────────────────────
export const FeeTypeComponentSchema = z
.object({
field: z.string().optional(),
label: z.string().optional(),
cnLabel: z.string().nullish(),
enLabel: z.string().nullish(),
type: z.string().optional(),
placeholder: z.string().nullish(),
readonly: z.boolean().nullish().default(false),
editable: z.boolean().nullish().default(true),
optional: z.boolean().nullish().default(true),
hide: z.boolean().nullish().default(false),
showInDetails: z.boolean().nullish().default(false),
defaultField: z.boolean().nullish().default(false),
defaultValue: z.record(z.string(), z.any()).nullish(),
})
.passthrough();
export type FeeTypeComponent = z.infer<typeof FeeTypeComponentSchema>;
export const FeeTypeSpecificationItemSchema = z
.object({
id: z.string(),
expenseComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
requisitionComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
receiptComponents: z.array(FeeTypeComponentSchema).nullish().default([]),
expenseRules: z.array(z.any()).nullish().default([]),
requisitionRules: z.array(z.any()).nullish().default([]),
receiptRules: z.array(z.any()).nullish().default([]),
})
.passthrough();
export type FeeTypeSpecificationItem = z.infer<typeof FeeTypeSpecificationItemSchema>;
export const FeeTypeSpecificationResponseSchema = z.object({
items: z.array(FeeTypeSpecificationItemSchema).default([]),
});
export type FeeTypeSpecificationResponse = z.infer<typeof FeeTypeSpecificationResponseSchema>;
export const DefaultSpecResponseSchema = z
.object({
components: z.array(FeeTypeComponentSchema).nullish().default([]),
})
.passthrough();
export type DefaultSpecResponse = z.infer<typeof DefaultSpecResponseSchema>;
// ── 业务输入参数 ────────────────────────────────────────────────────────────
export interface FeeTypeCreateInput {
name: string;
code?: string;
enName?: string;
parentId?: string;
description?: string;
color?: string;
icon?: string;
expenseComponents?: Record<string, unknown>[];
requisitionComponents?: Record<string, unknown>[];
}
export interface FeeTypeUpdateInput {
name?: string;
code?: string;
enName?: string;
description?: string;
color?: string;
icon?: string;
order?: number;
}
export interface FeeTypeQueryOptions {
all?: boolean;
keyword?: string;
flat?: boolean;
}
export interface FeeTypeView {
id: string;
name: string;
code: string;
enName: string;
active: boolean;
parentId: string;
parentName?: string;
path: string;
description: string;
color: string;
icon: string;
childrenCount: number;
}