refactor: 将应用数据与工作流统一归入应用平台子模块
建立 applications 的应用模型和查询出口,保留基础及详情投影差异。 下沉 DataLink,将工作流模型、API、编排及执行上下文归回 workflow。 同步 CLI、SDK、生成脚本、测试和活跃文档引用,公开命令与 SDK 名称保持兼容。 验证:943 项测试、类型和版本检查通过;三份生成规范字节一致,README 审计通过。
This commit is contained in:
1 parent
edf300b808
commit
4e03c9bcd7
107 files changed
+423
-496
No files matched your search
@@ -1,39 +1,17 @@
|
||||
# Platform 域说明
|
||||
# 自建应用平台(platform)
|
||||
|
||||
Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能力。自建应用下的业务对象、字段、记录和权限查询统一放在 [DataLink 域](../datalink/README.datalink.md)。
|
||||
本域以自建应用为共同业务根,包含应用元数据、业务对象数据与工作流三个子模块。CLI 命令按使用场景组织,源码归属按业务职责组织。
|
||||
|
||||
## 代码结构
|
||||
| 子模块 | 所有权 | 入口 |
|
||||
|---|---|---|
|
||||
| applications | 应用基础/详情模型、列表、全量列表、名称解析及应用级权限元数据 | [README.applications.md](./applications/README.applications.md) |
|
||||
| datalink | 业务对象、字段、记录、导入、数据编辑与台账审计 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| workflow | 工作流模型、传输、配置保存、节点、执行、诊断与监听 | [README.workflow.md](./workflow/README.workflow.md) |
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志、枚举类型)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验、Piper Job 端点与 EKB_ENUM 字典拉取)
|
||||
├── services.ts # 门面聚合与对外服务导出(含 resolveWorkflowEnumOptions 混合架构)
|
||||
├── workflow/ # 工作流体系子域(高内聚分层架构)
|
||||
│ ├── index.ts # 工作流能力统合导出
|
||||
│ ├── enums.ts # 单据审批事件触发器标准系统枚举(18 项内置字典与翻译器)
|
||||
│ ├── watch/ # 实时任务监听、TaskExecutionTracker 状态机与日志流 (tracker, engine, formatter)
|
||||
│ ├── nodes/ # 声明式节点树编排、树形索引定位、插入追加与重排 (tree, locator, mutations)
|
||||
│ ├── script/ # 脚本 AST 语法校验、上游依赖扫描与隔离沙箱仿真引擎 (lint, scanner, sandbox)
|
||||
│ ├── branch/ # 条件分支与规则解释诊断引擎 (explain, types)
|
||||
│ ├── analysis/ # 工作流静态吞错、审批状态死锁过滤与联动覆盖巡检 (analyzer, types)
|
||||
│ ├── state/ # 草稿版本状态机与发布乐观锁保护
|
||||
│ └── alert/ # 错误指纹告警与 SQLite 本地持久化
|
||||
└── execution-context.ts # 执行树与节点输出上下文辅助
|
||||
```
|
||||
## 依赖与入口
|
||||
|
||||
## 工作流使用与诊断
|
||||
applications 不依赖另外两个模块;DataLink 可使用应用模型和服务,不能依赖工作流;工作流跨应用查询通过 applications 服务获取应用。跨子模块调用使用 services,不直接导入其他子模块的 api。共享认证和数据库仍使用 core。
|
||||
|
||||
CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实时监听以及诊断结果契约,统一见 [Workflow 说明](./workflow/README.workflow.md)。
|
||||
各子模块拥有自己的 api、services 与 types。platform 根目录只保留总览,不保留混合的 api/services/types 门面。内部私有源码路径已经调整,公共 `hose-use/sdk` 名称和 CLI 命令继续保持兼容。
|
||||
|
||||
## 模块边界
|
||||
|
||||
- `workflow/{analysis,branch,nodes,script,state,watch,alert}/index.ts` 是各能力的目录出口;内部引用直接指向所属目录,不再保留根目录的一行转发文件。
|
||||
- 单元测试与对应实现放在同一目录;分层测试检查已移除路径,保留正常的模块出口文件。
|
||||
- MVEL 校验先识别字符串、转义及行/块注释,再检查有效代码中的括号、return 和节点引用;这属于轻量静态检查,不是完整的 MVEL 编译器。JavaScript 校验仍检查函数体语法,不执行脚本。
|
||||
|
||||
## 详细文档
|
||||
|
||||
接口职责、认证链路与 CLI 能力导航见(MCP 统一使用 `hose_cli`):
|
||||
|
||||
[docs/modules/platform.md](../../../docs/modules/platform.md)
|
||||
具体 CLI 与认证链路见 [模块说明](../../../docs/modules/platform.md),强制导入规则见 [架构边界测试](../../cli/architecture-boundaries.test.ts)。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 自建应用元数据(applications)
|
||||
|
||||
本模块拥有应用基础模型、详情模型、应用级权限元数据及目标解析。业务对象与工作流分别由 [DataLink](../datalink/README.datalink.md) 和 [Workflow](../workflow/README.workflow.md) 管理。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| [api.ts](./api.ts) | 应用 HTTP 请求和响应投影,共用启用应用列表请求 |
|
||||
| [types.ts](./types.ts) | PlatformSchema、应用详情与公开兼容类型 DatalinkPlatformDetail |
|
||||
| [services.ts](./services.ts) | 基础/详情列表、全量列表、详情与唯一目标解析出口 |
|
||||
| [application-contract.test.ts](./application-contract.test.ts) | 迁移前后两种投影、缺省与包装兼容回归 |
|
||||
|
||||
`listBasicPlatforms` 保留原工作流基础投影:剥离未建模字段,缺少 items 时拒绝。`listPlatforms` 保留详情投影:保留扩展字段、清洗 admin 信息、兼容空列表。两者共用请求实现,不强行混同既有错误及空值行为。
|
||||
|
||||
`listAllPlatforms` 与 `getPlatform` 保留原有全量及详情契约;当前全量列表原始数组仍被归为空列表,这属于已锁定的既有兼容行为,本轮不借迁移改变。`resolvePlatform` 按 ID、名称或编码做不区分大小写的精确匹配,再读取详情。
|
||||
|
||||
CLI 的 platform/app 详情及公共 SDK 的原函数名继续可用。不得从本模块反向依赖 DataLink 或工作流,不在应用模型中复制节点或记录结构。
|
||||
@@ -0,0 +1,74 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { PlatformSchema, DatalinkPlatformDetailSchema, type DatalinkPlatformDetail } from "./types.js";
|
||||
|
||||
function asRecord(value: unknown): Record<string, any> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
|
||||
}
|
||||
|
||||
async function fetchEnabledPlatforms(client: KyInstance, corpId: string): Promise<unknown> {
|
||||
const response = await client.get("api/v2/datalink/platform/search", { searchParams: { scope: "enable", corpId } });
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/** 工作流使用的基础投影:保留缺少 items 时拒绝的既有契约。 */
|
||||
export async function listBasicPlatforms(client: KyInstance, corpId: string) {
|
||||
const json = await fetchEnabledPlatforms(client, corpId) as { items: unknown[] };
|
||||
return z.array(PlatformSchema).parse(json.items);
|
||||
}
|
||||
|
||||
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
|
||||
const platform = asRecord(value);
|
||||
const admin = Array.isArray(platform.admin)
|
||||
? platform.admin.map((item) => {
|
||||
const staff = asRecord(item);
|
||||
return {
|
||||
id: staff.id,
|
||||
name: staff.name,
|
||||
code: staff.code,
|
||||
active: staff.active,
|
||||
};
|
||||
})
|
||||
: platform.admin;
|
||||
return { ...platform, admin };
|
||||
}
|
||||
|
||||
/** 列出当前企业可见的启用自建应用。 */
|
||||
export async function listPlatforms(client: KyInstance, corpId: string) {
|
||||
const json = asRecord(await fetchEnabledPlatforms(client, corpId));
|
||||
const items = Array.isArray(json.items) ? json.items.map(sanitizePlatformDetail) : [];
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 列出当前企业全量自建应用与模板平台(包含 HAB 模板与全部自建应用)。 */
|
||||
export async function listAllPlatforms(client: KyInstance, corpId: string) {
|
||||
const response = await client.get("api/v2/datalink/platform", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawList = Array.isArray(json) ? json : Array.isArray(json.items) ? json.items : [];
|
||||
const items = rawList.map(sanitizePlatformDetail);
|
||||
return z.array(DatalinkPlatformDetailSchema).parse(items);
|
||||
}
|
||||
|
||||
/** 获取单个应用详情以及应用级人员/角色/部门权限。 */
|
||||
export async function getPlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkPlatformDetail> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const bareId = platformId.startsWith("$") ? platformId.slice(1) : platformId;
|
||||
const response = await client.get(`api/v2/datalink/platform/${normalizedId}`, {
|
||||
// 前端实际使用两个 join,并且详情接口要求同时传 id。
|
||||
searchParams: new URLSearchParams([
|
||||
["id", bareId],
|
||||
["join", "icon.fileId,fileId,/v1/attachment/attachments"],
|
||||
["corpId", corpId],
|
||||
["join", "adminIds,admin,/v1/organization/staffs"],
|
||||
]),
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json));
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listPlatforms as listBasic } from "./api.js";
|
||||
import { listPlatforms as listDetailed, listAllPlatforms, getPlatform } from "../datalink/api.js";
|
||||
import { listBasicPlatforms as listBasic } from "./api.js";
|
||||
import { listPlatforms as listDetailed, listAllPlatforms, getPlatform } from "./api.js";
|
||||
|
||||
function client(body: unknown) {
|
||||
const calls: Array<{ path: string; options: any }> = [];
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkPlatformDetail } from "./types.js";
|
||||
|
||||
export function listBasicPlatforms(...args: Parameters<typeof api.listBasicPlatforms>) { return api.listBasicPlatforms(...args); }
|
||||
export function listPlatforms(...args: Parameters<typeof api.listPlatforms>) { return api.listPlatforms(...args); }
|
||||
export function listAllPlatforms(...args: Parameters<typeof api.listAllPlatforms>) { return api.listAllPlatforms(...args); }
|
||||
export function getPlatform(...args: Parameters<typeof api.getPlatform>) { return api.getPlatform(...args); }
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
}
|
||||
|
||||
export async function resolvePlatform(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<DatalinkPlatformDetail | undefined> {
|
||||
const platforms = await api.listPlatforms(client, corpId);
|
||||
const found = platforms.find((platform) =>
|
||||
[platform.id, platform.name, platform.code].some((value) => matches(value, target))
|
||||
);
|
||||
return found ? api.getPlatform(client, corpId, found.id) : undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 自建应用(DataLink Platform)─────────────────────────────
|
||||
|
||||
export const PlatformSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
nameSpell: z.string().default(""),
|
||||
enName: z.string().nullable().optional(),
|
||||
code: z.string().default(""),
|
||||
corporationId: z.string(),
|
||||
active: z.boolean().default(true),
|
||||
type: z.string().default(""),
|
||||
groupType: z.string().default(""),
|
||||
platformType: z.string().default(""),
|
||||
source: z.string().default(""),
|
||||
adminIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
desc: z.string().nullable().optional(),
|
||||
importMethod: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
});
|
||||
|
||||
export const DatalinkPlatformDetailSchema = PlatformSchema.passthrough().extend({
|
||||
staffIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
roleIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
departmentsIncludeChildren: z.boolean().nullish().transform((value) => value ?? false),
|
||||
});
|
||||
|
||||
export type Platform = z.infer<typeof PlatformSchema>;
|
||||
export type DatalinkPlatformDetail = z.infer<typeof DatalinkPlatformDetailSchema>;
|
||||
@@ -0,0 +1,104 @@
|
||||
# DataLink 域说明
|
||||
|
||||
DataLink 是应用平台的数据子模块,负责业务对象、字段定义、业务记录、对象级权限快照和导入状态。应用列表、详情与名称解析由 [applications](../applications/README.applications.md) 拥有;公共 SDK 保留原调用名称。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/domains/platform/datalink/
|
||||
├── types.ts # 应用详情、对象字段、记录分页与权限模型
|
||||
├── api.ts # DataLink HTTP 传输层
|
||||
├── services.ts # 应用/对象名称解析与查询表达式辅助、SDK 门面
|
||||
└── fields.ts # 读取与写入共用的唯一字段解析
|
||||
```
|
||||
|
||||
## 查询链路
|
||||
|
||||
```text
|
||||
platform/search
|
||||
└─ platform/{platformId} 应用详情与管理权限
|
||||
└─ entity/platformId/{platformId} 业务对象与字段定义
|
||||
└─ searchPlatformDataLinkWithChild/{entityId} 业务记录
|
||||
```
|
||||
|
||||
应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
hose-use platform record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--where="条件"|--ids=id1,id2|--filter=...] [--set="字段=值"|--data='{"field": "val"}'] [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only] [--check-continuous=序号字段] [--expect="字段 ~= 期望值 [+- 容差]"]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||
- `records --page=<页码> --count=<每页>`:分页查询,默认 `count=20`;用于替代无边界全量拉取。
|
||||
- `records --all`:不再直接返回全量 JSON/表格。普通查询请用 `--page/--count`;确实需要全量时只允许 `--ndjson --output-file <path>` 流式导出,避免几十万条记录进入 stdout 或一次性载入内存。大范围检索建议由 Agent 编写脚本处理。
|
||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||
- `records --keyword="关键词" [--search-fields="字段1,字段2"]`:服务端原生索引检索。缺省检索 `name` 与 `code`;指定 `--search-fields` 时,自动解析业务字段(无论标签更名还是底层代码),自动附加 `form.E_...` 命名空间及货币复合对象(`standard`)过滤,服务端秒级精准返回,杜绝客户端无边界全表扫描。
|
||||
- `records --filter="表达式"`:服务端原生 `filterBy` 过滤。支持原生 DSL 语法,同时支持简写形式(如 `--filter="客户名称~猫子"`、`--filter="不含税金额=191700"`、`--filter="状态!=停用"`),自动结合业务对象元数据映射底层物理字段与数据类型。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- **客户端谓词早退机制(Early-Exit)**:未显式指定 `--all` 时,检索采用流式迭代,匹配满 `count`(默认 20 条)即刻终止拉取,杜绝无脑拉取全量台账导致的大流量开销与终端假死。
|
||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
|
||||
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- 筛选、`--set` 与 JSON 安全合并共用字段解析:明确物理键优先,标签或模糊匹配必须唯一;歧义在写入前拒绝,须改用完整物理字段名。未知原始字段继续保持兼容透传,`--raw` 仍直接透传原始补丁。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
|
||||
## 公共 SDK (`hose-use/sdk`)
|
||||
|
||||
对于需要针对十万级业务记录编写个性化业务循环、分析或报表导出的脚本,直接通过 `hose-use/sdk` 引入标准公共 API,彻底告别依赖 CLI 内部文件路径:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
initCorpRuntime,
|
||||
requireSelectedCorp,
|
||||
createClientsForCorp,
|
||||
resolvePlatform,
|
||||
resolveEntity,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
} from "hose-use/sdk";
|
||||
|
||||
const runtime = initCorpRuntime({ corpId: "企业配置ID", stateless: true });
|
||||
const corp = requireSelectedCorp(runtime);
|
||||
const clients = await createClientsForCorp(corp);
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, "应用名称");
|
||||
if (!platform) throw new Error("未找到自建应用");
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, "合同");
|
||||
if (!entity) throw new Error("未找到业务对象");
|
||||
|
||||
// 1. 万级海量数据 $O(1)$ 内存流式遍历
|
||||
for await (const rawRecord of iterateAllEntityRecords(clients.ekbClient, corpId, entity.id, { pageSize: 200 })) {
|
||||
const record = normalizeDatalinkRecord(rawRecord, entity);
|
||||
// 执行业务逻辑...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
`--set` 按引号、转义和括号边界拆分赋值项,支持 `名称="ACME, Inc.", 编码=ACME`。缺少等号、空字段或未闭合引号会在发起更新前明确报错,不再静默截断或忽略。
|
||||
|
||||
`--set` 中带单引号或双引号的值明确表示字符串,并解码字符串转义;例如 `编码="001"` 保留前导零,`名称="true"` 保留文本。未加引号的数值、`true/false/null` 继续按对应类型转换。
|
||||
@@ -0,0 +1,460 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { resolveDatalinkField } from "./fields.js";
|
||||
import {
|
||||
DatalinkEntitySchema,
|
||||
enrichDatalinkField,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkRecord,
|
||||
type DatalinkRecordDetail,
|
||||
type DatalinkRecordEditPayload,
|
||||
type DatalinkRecordPage,
|
||||
type DatalinkRecordQuery,
|
||||
} from "./types.js";
|
||||
|
||||
function asRecord(value: unknown): Record<string, any> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, any>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function parseEntity(value: unknown): DatalinkEntity {
|
||||
const entity = DatalinkEntitySchema.parse(asRecord(value));
|
||||
return {
|
||||
...entity,
|
||||
fields: entity.fields.map(enrichDatalinkField),
|
||||
};
|
||||
}
|
||||
|
||||
/** 获取应用下的业务对象目录及完整字段定义。 */
|
||||
export async function listPlatformEntities(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<DatalinkEntity[]> {
|
||||
const normalizedId = platformId.startsWith("$") ? platformId : `$${platformId}`;
|
||||
const response = await client.post(`api/v2/datalink/entity/platformId/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
// 该 POST 即使没有筛选条件也要求发送空 JSON body;前端会发送 {}。
|
||||
json: {},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const rawItems = Array.isArray(json.items)
|
||||
? json.items
|
||||
: Array.isArray(asRecord(json.value).items)
|
||||
? asRecord(json.value).items
|
||||
: [];
|
||||
return rawItems.map(parseEntity);
|
||||
}
|
||||
|
||||
/** 分页检索指定业务对象的记录。filterBy 使用 DataLink 原生表达式。 */
|
||||
export async function searchEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
query: DatalinkRecordQuery = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const limit = {
|
||||
start: query.start ?? 0,
|
||||
count: query.count ?? 20,
|
||||
};
|
||||
const nativeQuery: Record<string, unknown> = {
|
||||
filterBy: query.filterBy?.trim() || "(active.in(true,false))",
|
||||
limit,
|
||||
};
|
||||
if (query.orderBy !== undefined) nativeQuery.orderBy = query.orderBy;
|
||||
|
||||
const response = await client.post(
|
||||
`api/v2/datalink/searchPlatformDataLinkWithChild/${normalizedId}`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
json: { query: nativeQuery, entityId },
|
||||
}
|
||||
);
|
||||
const json = asRecord(await response.json());
|
||||
const payload = asRecord(json.items && !Array.isArray(json.items) ? json.items : json.value ?? json);
|
||||
const rawData = Array.isArray(payload.data)
|
||||
? payload.data
|
||||
: Array.isArray(payload.items)
|
||||
? payload.items
|
||||
: Array.isArray(json.items)
|
||||
? json.items
|
||||
: [];
|
||||
|
||||
return {
|
||||
total: numberOr(payload.total ?? json.total, rawData.length),
|
||||
data: rawData.filter((item): item is DatalinkRecord => item !== null && typeof item === "object"),
|
||||
actions: Array.isArray(payload.actions) ? payload.actions : [],
|
||||
components: Array.isArray(payload.components) ? payload.components : [],
|
||||
path: payload.path,
|
||||
template: payload.template,
|
||||
};
|
||||
}
|
||||
|
||||
/** 查询对象导入任务状态。 */
|
||||
export async function listImportJobs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<DatalinkImportJob[]> {
|
||||
const response = await client.get("api/engine/easo/batchJobs", {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
const items = json.items ?? asRecord(json.value).items ?? json.value ?? [];
|
||||
return Array.isArray(items) ? items.filter((item): item is DatalinkImportJob => item !== null && typeof item === "object") : [];
|
||||
}
|
||||
|
||||
/** 查询对象最近一次 Excel 导入结果。 */
|
||||
export async function getImportResult(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const response = await client.get(`api/v1/datalink/excel/import/result/${normalizedId}`, {
|
||||
searchParams: { entityId, corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 切换业务对象记录的停启用状态 (active: true <-> false)。若未指定 state 则自动反转当前状态。 */
|
||||
export async function toggleRecordState(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string,
|
||||
state?: boolean
|
||||
): Promise<{ recordId: string; active: boolean }> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
let targetState = state;
|
||||
if (targetState === undefined) {
|
||||
const detail = await getRecordDetail(client, corpId, recordId);
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
targetState = !(record.active ?? true);
|
||||
}
|
||||
|
||||
await client.put(`api/supplier/v3/contract/${normalizedId}/state`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: bareId, state: targetState },
|
||||
});
|
||||
|
||||
return { recordId: bareId, active: targetState };
|
||||
}
|
||||
|
||||
/** 获取单条业务对象记录的完整详情(包含展示模板、字段值、可见性及审批历史等)。 */
|
||||
export async function getRecordDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<DatalinkRecordDetail> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const bareId = recordId.startsWith("$") ? recordId.slice(1) : recordId;
|
||||
const response = await client.get(`api/v2/datalink/detail/${normalizedId}/$DETAIL`, {
|
||||
searchParams: {
|
||||
dataLinkId: bareId,
|
||||
type: "DETAIL",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as DatalinkRecordDetail;
|
||||
}
|
||||
|
||||
/** 获取业务对象编辑表单的字段结构定义。 */
|
||||
export async function getRecordFormSchema(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = entityId.startsWith("$") ? entityId : `$${entityId}`;
|
||||
const bareId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const response = await client.get(`api/v2/datalink/entityEdit/entityForm/${normalizedId}/$true`, {
|
||||
searchParams: {
|
||||
entityId: bareId,
|
||||
isInsert: "true",
|
||||
needFormula: "true",
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
/** 编辑更新业务对象记录字段。 */
|
||||
export async function editRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
payload: DatalinkRecordEditPayload
|
||||
): Promise<Record<string, unknown>> {
|
||||
const bareEntityId = payload.dataLinkEntityId.startsWith("$")
|
||||
? payload.dataLinkEntityId.slice(1)
|
||||
: payload.dataLinkEntityId;
|
||||
const bareRecordId = payload.dataLinkId.startsWith("$")
|
||||
? payload.dataLinkId.slice(1)
|
||||
: payload.dataLinkId;
|
||||
|
||||
const response = await client.post("api/v2/datalink/entityEdit/edit", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
...payload,
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
},
|
||||
});
|
||||
const json = asRecord(await response.json());
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const REFERENCE_FIELD_TYPES = new Set([
|
||||
"dimension",
|
||||
"dataLink",
|
||||
"staff",
|
||||
"department",
|
||||
"role",
|
||||
"reference",
|
||||
]);
|
||||
|
||||
const SYSTEM_RECORD_KEYS = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"active",
|
||||
"visibility",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"corporationId",
|
||||
"platformId",
|
||||
"ownerId",
|
||||
"creatorId",
|
||||
"form",
|
||||
"fieldAuth",
|
||||
"actions",
|
||||
"source",
|
||||
"sourceId",
|
||||
]);
|
||||
|
||||
function extractReferenceId(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("standard" in obj) return undefined;
|
||||
if (typeof obj.id === "string" && obj.id) return obj.id;
|
||||
if (obj.dataLink && typeof obj.dataLink === "object" && !Array.isArray(obj.dataLink)) {
|
||||
const dl = obj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
|
||||
const dataObj = obj.data as Record<string, unknown>;
|
||||
if (typeof dataObj.id === "string" && dataObj.id) return dataObj.id;
|
||||
if (dataObj.dataLink && typeof dataObj.dataLink === "object" && !Array.isArray(dataObj.dataLink)) {
|
||||
const dl = dataObj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeRecordFieldValue(
|
||||
value: unknown,
|
||||
fieldDef?: DatalinkField
|
||||
): unknown {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return "";
|
||||
const isRefType = fieldDef ? REFERENCE_FIELD_TYPES.has(fieldDef.type) : false;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => {
|
||||
const refId = extractReferenceId(item);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && "standard" in (value as Record<string, unknown>)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const refId = extractReferenceId(value);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resolveEntityFieldKey(
|
||||
inputKey: string,
|
||||
entityId: string,
|
||||
fields: DatalinkField[] = [],
|
||||
existingForm: Record<string, unknown> = {}
|
||||
): { key: string; fieldDef?: DatalinkField } {
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const field = resolveDatalinkField(fields, bareEntityId, inputKey);
|
||||
if (field) return { key: field.name, fieldDef: field };
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
|
||||
return { key: inputKey };
|
||||
}
|
||||
if (prefixedKey in existingForm) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
if (fields.some((f) => f.name.startsWith(`E_${bareEntityId}_`)) && !(inputKey in existingForm)) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
return { key: inputKey };
|
||||
}
|
||||
|
||||
export interface SafeRecordEditOptions {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
fields?: DatalinkField[];
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建安全的业务对象记录 Read-Modify-Write 编辑 Payload:
|
||||
* 1. 自动提取并保留原记录全部 E_<entityId>_* 及已有业务字段;
|
||||
* 2. 自动将 dimension / dataLink / staff / department 等引用对象 { id: "ID01..." } 归一化为字符串 ID;
|
||||
* 3. 自动保留 active 与 visibility(将 staff/role/department 映射为 staffs/roles/departments);
|
||||
* 4. 支持按完整字段名(E_<entityId>_xxx)或简写字段显示名/后缀(我方签约主体、name、code)合并变更。
|
||||
*/
|
||||
export function buildSafeRecordEditPayload(
|
||||
options: SafeRecordEditOptions
|
||||
): DatalinkRecordEditPayload {
|
||||
const bareEntityId = options.entityId.startsWith("$")
|
||||
? options.entityId.slice(1)
|
||||
: options.entityId;
|
||||
const bareRecordId = options.recordId.startsWith("$")
|
||||
? options.recordId.slice(1)
|
||||
: options.recordId;
|
||||
const fields = options.fields ?? [];
|
||||
const detailObj = asRecord(options.detail);
|
||||
const nestedData = asRecord(detailObj.data);
|
||||
const record = asRecord(
|
||||
detailObj.dataLink ?? nestedData.dataLink ?? detailObj
|
||||
);
|
||||
|
||||
const mergedForm: Record<string, unknown> = {};
|
||||
const fieldByName = new Map<string, DatalinkField>();
|
||||
for (const f of fields) {
|
||||
if (f.name) fieldByName.set(f.name, f);
|
||||
}
|
||||
|
||||
// 1. 提取 record.form 中的字段(兼容测试与部分特殊实体结构)
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
const fDef = fieldByName.get(k);
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 提取原记录中的 E_<entityId>_* 字段与 schema 中定义的业务字段
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (SYSTEM_RECORD_KEYS.has(k)) continue;
|
||||
const fDef = fieldByName.get(k);
|
||||
if (k.startsWith(entityPrefix) || k.startsWith("E_") || fDef) {
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 合并用户传入的 patchForm(支持字段名、中文显示名或后缀简写)
|
||||
for (const [rawKey, rawVal] of Object.entries(options.patchForm)) {
|
||||
const { key, fieldDef } = resolveEntityFieldKey(
|
||||
rawKey,
|
||||
bareEntityId,
|
||||
fields,
|
||||
mergedForm
|
||||
);
|
||||
mergedForm[key] = normalizeRecordFieldValue(rawVal, fieldDef);
|
||||
}
|
||||
|
||||
// 4. 保留 active 与 visibility
|
||||
const resolvedActive =
|
||||
options.active !== undefined
|
||||
? options.active
|
||||
: typeof record.active === "boolean"
|
||||
? record.active
|
||||
: true;
|
||||
|
||||
const rawVis = asRecord(record.visibility);
|
||||
const normalizeRefIdList = (list: unknown): string[] => {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) =>
|
||||
typeof item === "string"
|
||||
? item
|
||||
: item && typeof item === "object" && typeof (item as Record<string, unknown>).id === "string"
|
||||
? String((item as Record<string, unknown>).id)
|
||||
: undefined
|
||||
)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
};
|
||||
|
||||
const visibility = {
|
||||
fullVisible:
|
||||
typeof rawVis.fullVisible === "boolean" ? rawVis.fullVisible : true,
|
||||
staffs: normalizeRefIdList(rawVis.staffs ?? rawVis.staff),
|
||||
roles: normalizeRefIdList(rawVis.roles ?? rawVis.role),
|
||||
departments: normalizeRefIdList(rawVis.departments ?? rawVis.department),
|
||||
departmentsIncludeChildren:
|
||||
typeof rawVis.departmentsIncludeChildren === "boolean"
|
||||
? rawVis.departmentsIncludeChildren
|
||||
: false,
|
||||
};
|
||||
|
||||
return {
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
active: resolvedActive,
|
||||
form: mergedForm,
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全编辑单条业务对象记录(Read-Modify-Write 模式)。
|
||||
*/
|
||||
export async function safeEditRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: Omit<SafeRecordEditOptions, "detail"> & {
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
}
|
||||
): Promise<{
|
||||
payload: DatalinkRecordEditPayload;
|
||||
result: Record<string, unknown>;
|
||||
}> {
|
||||
const detail =
|
||||
options.detail ?? (await getRecordDetail(client, corpId, options.recordId));
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
...options,
|
||||
detail,
|
||||
});
|
||||
const result = await editRecord(client, corpId, payload);
|
||||
return { payload, result };
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
recordId: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const normalizedId = recordId.startsWith("$") ? recordId : `$${recordId}`;
|
||||
const response = await client.post(`api/v2/ledger/recompute/${normalizedId}`, {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,721 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { buildSafeRecordEditPayload, editRecord, getRecordDetail, listPlatformEntities, recomputeRecordLedger, searchEntityRecords, toggleRecordState } from "./api.js";
|
||||
import { getPlatform, listPlatforms } from "../applications/api.js";
|
||||
import {
|
||||
aggregateRecordFields,
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
compileRecordPredicate,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
formatServerFieldExpr,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
parseSetClause,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
describe("record predicate and normalized projection regressions", () => {
|
||||
const entity = { id: "ent", name: "台账", fields: [
|
||||
{ name: "E_ent_seq", label: "序号", type: "number" },
|
||||
{ name: "E_ent_rent", label: "租金", type: "number" },
|
||||
{ name: "E_ent_note", label: "备注", type: "text" },
|
||||
{ name: "E_ent_name", label: "名称", type: "text" },
|
||||
] } as any;
|
||||
const records = [
|
||||
{ dataLink: { id: "r1", E_ent_seq: 1, E_ent_rent: 100, E_ent_note: "A,B && C", E_ent_name: "Name" } },
|
||||
{ dataLink: { id: "r2", E_ent_seq: 2, E_ent_rent: 200, E_ent_note: null } },
|
||||
];
|
||||
|
||||
for (const clause of ["序号 in [1]", "序号 == 1 &&", "不存在 != 1", "序号 === 1", "序号 in ()", "序号 > 1 || 序号 < 3", "备注 == 'broken", "序号 == 1&&garbage"]) {
|
||||
test(`rejects invalid predicate even with no records: ${clause}`, () => {
|
||||
expect(() => filterRecordsByPredicate([], clause, entity)).toThrow();
|
||||
});
|
||||
}
|
||||
test("validates unknown and ambiguous fields before evaluating records", () => {
|
||||
expect(() => compileRecordPredicate("租 == 1", { ...entity, fields: [...entity.fields, { name: "other", label: "租期", type: "number" }] })).toThrow("歧义");
|
||||
});
|
||||
test("honors quotes, commas and conjunctions inside values", () => {
|
||||
expect(filterRecordsByPredicate(records, "备注 in ('A,B && C','other')&&序号>=1", entity)).toEqual([records[0]]);
|
||||
expect(filterRecordsByPredicate(records, "备注 == null", entity)).toEqual([records[1]]);
|
||||
expect(filterRecordsByPredicate(records, "序号 in (1,2) && 租金 < 150", entity)).toEqual([records[0]]);
|
||||
});
|
||||
test("selects normalized business fields and system name by label or original field name", () => {
|
||||
const normalized = normalizeDatalinkRecord(records[0], entity);
|
||||
expect(selectRecordFields(normalized as any, ["租金", "E_ent_seq", "名称", "id"], entity.fields)).toEqual({ 租金: 100, 序号: 1, 名称: "Name", id: "r1" });
|
||||
});
|
||||
});
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
name: "业务应用",
|
||||
corporationId: "corp-1",
|
||||
active: true,
|
||||
adminIds: ["staff-1"],
|
||||
};
|
||||
|
||||
describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
test("列出应用并为权限数组提供稳定默认值", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/search");
|
||||
expect(options.searchParams).toEqual({ scope: "enable", corpId: "corp-1" });
|
||||
return { json: async () => ({ items: [platform] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatforms(client, "corp-1");
|
||||
expect(result[0]?.name).toBe("业务应用");
|
||||
expect(result[0]?.staffIds).toEqual([]);
|
||||
expect(result[0]?.departmentIds).toEqual([]);
|
||||
});
|
||||
|
||||
test("获取应用详情时请求管理员关联", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/platform/$platform-1");
|
||||
expect(options.searchParams).toBeInstanceOf(URLSearchParams);
|
||||
expect(options.searchParams.get("id")).toBe("platform-1");
|
||||
expect(options.searchParams.getAll("join")).toEqual([
|
||||
"icon.fileId,fileId,/v1/attachment/attachments",
|
||||
"adminIds,admin,/v1/organization/staffs",
|
||||
]);
|
||||
expect(options.searchParams.get("corpId")).toBe("corp-1");
|
||||
return { json: async () => ({ value: { ...platform, staffIds: ["staff-1"], roleIds: ["role-1"], departmentIds: [], admin: [{ id: "staff-1", name: "管理员", code: "A-1", cellphone: "13800000000" }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getPlatform(client, "corp-1", "platform-1");
|
||||
expect(result.adminIds).toEqual(["staff-1"]);
|
||||
expect(result.roleIds).toEqual(["role-1"]);
|
||||
expect(result.admin).toEqual([{ id: "staff-1", name: "管理员", code: "A-1", active: undefined }]);
|
||||
expect(JSON.stringify(result)).not.toContain("13800000000");
|
||||
});
|
||||
|
||||
test("获取对象字段元数据并保留扩展属性", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entity/platformId/$platform-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({});
|
||||
return { json: async () => ({ items: [{ id: "entity-1", name: "供应商", fields: [{ name: "code", label: "编码", type: "text", optional: false, customFlag: true }] }] }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await listPlatformEntities(client, "corp-1", "platform-1");
|
||||
expect(result[0]?.fields[0]?.label).toBe("编码");
|
||||
expect(result[0]?.fields[0]?.customFlag).toBe(true);
|
||||
});
|
||||
|
||||
test("分页查询记录并生成标准化分页结果", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/searchPlatformDataLinkWithChild/$entity-1");
|
||||
expect(options.searchParams.corpId).toBe("corp-1");
|
||||
expect(options.json).toEqual({
|
||||
entityId: "entity-1",
|
||||
query: { filterBy: 'code == "A-1"', limit: { start: 10, count: 5 } },
|
||||
});
|
||||
return { json: async () => ({ items: { total: 1, data: [{ id: "record-1", dataLink: { code: "A-1" } }] } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await searchEntityRecords(client, "corp-1", "entity-1", { start: 10, count: 5, filterBy: 'code == "A-1"' });
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.data[0]?.dataLink?.code).toBe("A-1");
|
||||
});
|
||||
|
||||
test("关键词过滤和字段投影可用于通用 CLI 查询", () => {
|
||||
expect(buildKeywordFilter('A"1')).toContain('A\\"1');
|
||||
expect(selectRecordFields({ id: "r-1", dataLink: { code: "A-1" } }, ["编码"], [{ name: "code", label: "编码", type: "text" }])).toEqual({ id: "r-1", dataLink: { 编码: "A-1" } });
|
||||
});
|
||||
|
||||
test("切换记录停启用状态调用 PUT contract state 接口", async () => {
|
||||
let calledUrl = "";
|
||||
let calledParams: any = null;
|
||||
let calledJson: any = null;
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({ value: { id: "record-1", active: true } }),
|
||||
}),
|
||||
put: async (url: string, options: any) => {
|
||||
calledUrl = url;
|
||||
calledParams = options.searchParams;
|
||||
calledJson = options.json;
|
||||
return { status: 204 };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const res = await toggleRecordState(client, "corp-1", "record-1");
|
||||
expect(calledUrl).toBe("api/supplier/v3/contract/$record-1/state");
|
||||
expect(calledParams).toEqual({ corpId: "corp-1" });
|
||||
expect(calledJson).toEqual({ id: "record-1", state: false });
|
||||
expect(res).toEqual({ recordId: "record-1", active: false });
|
||||
});
|
||||
|
||||
test("获取记录详情调用 GET datalink detail 接口", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/detail/$record-1/$DETAIL");
|
||||
expect(options.searchParams).toEqual({
|
||||
dataLinkId: "record-1",
|
||||
type: "DETAIL",
|
||||
corpId: "corp-1",
|
||||
});
|
||||
return { json: async () => ({ value: { id: "record-1", name: "记录1" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getRecordDetail(client, "corp-1", "record-1");
|
||||
expect((result as any).name).toBe("记录1");
|
||||
});
|
||||
|
||||
test("编辑业务对象记录调用 POST entityEdit edit 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
expect(options.json.dataLinkEntityId).toBe("entity-1");
|
||||
expect(options.json.dataLinkId).toBe("record-1");
|
||||
expect(options.json.form).toEqual({ name: "新名称" });
|
||||
return { json: async () => ({ value: { id: "record-1", name: "新名称" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await editRecord(client, "corp-1", {
|
||||
dataLinkEntityId: "$entity-1",
|
||||
dataLinkId: "$record-1",
|
||||
form: { name: "新名称" },
|
||||
});
|
||||
expect((result as any).name).toBe("新名称");
|
||||
});
|
||||
|
||||
test("重算台账调用 POST ledger recompute 接口", async () => {
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
expect(url).toBe("api/v2/ledger/recompute/$record-1");
|
||||
expect(options.searchParams).toEqual({ corpId: "corp-1" });
|
||||
return { json: async () => ({ id: "ok" }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
|
||||
test("buildSafeRecordEditPayload 执行 Read-Modify-Write 安全合并并归一化嵌套引用 ID 与 visibility", async () => {
|
||||
const fields = [
|
||||
{ name: "E_e1_name", label: "合同名称", type: "text" },
|
||||
{ name: "E_e1_company", label: "我方签约主体", type: "dimension" },
|
||||
{ name: "E_e1_supplier", label: "供应商", type: "supplier" },
|
||||
{ name: "E_e1_amount", label: "合同金额", type: "money" },
|
||||
];
|
||||
const detail = {
|
||||
dataLink: {
|
||||
id: "ID01VSau4VJWSH",
|
||||
active: true,
|
||||
E_e1_name: "年度采购合同",
|
||||
E_e1_company: null,
|
||||
E_e1_supplier: { id: "ID01SUP123", name: "测试供应商" },
|
||||
E_e1_amount: { standard: "1000.00", standardUnit: "元", standardScale: 2 },
|
||||
visibility: {
|
||||
fullVisible: false,
|
||||
staff: [{ id: "staff-1" }],
|
||||
role: ["role-1"],
|
||||
department: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
entityId: "e1",
|
||||
recordId: "ID01VSau4VJWSH",
|
||||
detail,
|
||||
fields: fields as any,
|
||||
patchForm: {
|
||||
我方签约主体: "ID01RnG3b79daL",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payload.dataLinkEntityId).toBe("e1");
|
||||
expect(payload.dataLinkId).toBe("ID01VSau4VJWSH");
|
||||
expect(payload.active).toBe(true);
|
||||
expect(payload.form.E_e1_name).toBe("年度采购合同");
|
||||
expect(payload.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(payload.form.E_e1_supplier).toBe("ID01SUP123");
|
||||
expect(payload.form.E_e1_amount).toBe(
|
||||
JSON.stringify({
|
||||
standard: "1000.00",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
})
|
||||
);
|
||||
expect(payload.visibility).toEqual({
|
||||
fullVisible: false,
|
||||
staffs: ["staff-1"],
|
||||
roles: ["role-1"],
|
||||
departments: [],
|
||||
departmentsIncludeChildren: false,
|
||||
});
|
||||
|
||||
let postUrl = "";
|
||||
let postBody: any = null;
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
postUrl = url;
|
||||
postBody = options.json;
|
||||
return { json: async () => ({ value: { id: "ID01VSau4VJWSH" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
await editRecord(client, "corp-1", payload);
|
||||
expect(postUrl).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(postBody.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(postBody.visibility.staffs).toEqual(["staff-1"]);
|
||||
});
|
||||
|
||||
test("fetchAllEntityRecords 自动分页拉取全量记录", async () => {
|
||||
const calls: Array<{ start: number; count: number }> = [];
|
||||
const client = {
|
||||
post: async (_url: string, options: any) => {
|
||||
const limit = options.json.query.limit;
|
||||
calls.push(limit);
|
||||
if (limit.start === 0) {
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1" } },
|
||||
{ id: "r-2", dataLink: { id: "r-2" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "r-3", dataLink: { id: "r-3" } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await fetchAllEntityRecords(client, "corp-1", "entity-1", { pageSize: 2 });
|
||||
expect(calls).toEqual([
|
||||
{ start: 0, count: 2 },
|
||||
{ start: 2, count: 2 },
|
||||
]);
|
||||
expect(result.data).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("auditEntityRecords 巡检必填缺失、停用引用与跨台账同名字段同步差异", () => {
|
||||
const childEntity = {
|
||||
id: "e_plan",
|
||||
name: "支付计划表",
|
||||
fields: [
|
||||
{ name: "E_e_plan_code", label: "编码", type: "text", optional: true },
|
||||
{ name: "E_e_plan_company", label: "我方签约主体", type: "dimension", optional: false },
|
||||
{
|
||||
name: "E_e_plan_contract",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: true,
|
||||
entityId: "e_contract",
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{
|
||||
id: "plan-1",
|
||||
dataLink: {
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
active: true,
|
||||
E_e_plan_company: null,
|
||||
E_e_plan_contract: {
|
||||
id: "contract-1",
|
||||
name: "测试合同",
|
||||
active: false,
|
||||
data: {
|
||||
dataLink: {
|
||||
id: "contract-1",
|
||||
code: "HT-001",
|
||||
active: false,
|
||||
E_e_contract_company: {
|
||||
id: "ID01RnG3b79daL",
|
||||
name: "北京转转精神科技有限责任公司",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const report = auditEntityRecords(records as any, childEntity as any, {
|
||||
checkFields: ["我方签约主体"],
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(1);
|
||||
expect(report.summary.missingFieldCount).toBe(1);
|
||||
expect(report.summary.disabledReferenceCount).toBe(1);
|
||||
expect(report.summary.crossLedgerMissingSyncCount).toBe(1);
|
||||
expect(report.suggestedPatches).toEqual([
|
||||
{
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
form: {
|
||||
E_e_plan_company: "ID01RnG3b79daL",
|
||||
},
|
||||
reason: "我方签约主体 <- 北京转转精神科技有限责任公司 (ID01RnG3b79daL)",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("batchSafeEditRecords 支持 dryRun 预览与并发安全合并", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
name: "合同流程",
|
||||
fields: [{ name: "E_e1_company", label: "我方签约主体", type: "dimension" }],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
value: {
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
E_e1_company: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const results = await batchSafeEditRecords(
|
||||
client,
|
||||
"corp-1",
|
||||
entity as any,
|
||||
[{ recordId: "r-1", patchForm: { 我方签约主体: "ID01RnG3b79daL" } }],
|
||||
{ dryRun: true }
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
|
||||
test("aggregateRecordFields 准确统计数值、金额对象、货币字符串并支持分组", () => {
|
||||
const entity = {
|
||||
id: "e_lease",
|
||||
name: "租金台账",
|
||||
fields: [
|
||||
{ name: "E_e_lease_period", label: "期数", type: "number" },
|
||||
{ name: "E_e_lease_rent", label: "租赁费用", type: "money" },
|
||||
{ name: "E_e_lease_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", E_e_lease_period: 1, E_e_lease_rent: { standard: 10000 }, E_e_lease_status: "已摊销" },
|
||||
{ id: "2", E_e_lease_period: 2, E_e_lease_rent: 15000, E_e_lease_status: "已摊销" },
|
||||
{ id: "3", E_e_lease_period: 3, E_e_lease_rent: "¥20,000.00", E_e_lease_status: "待摊销" },
|
||||
];
|
||||
|
||||
const report = aggregateRecordFields(records as any, entity as any, {
|
||||
fields: ["租赁费用"],
|
||||
groupBy: "状态",
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(3);
|
||||
const rentStats = report.overall["租赁费用"];
|
||||
expect(rentStats).toBeDefined();
|
||||
expect(rentStats?.count).toBe(3);
|
||||
expect(rentStats?.sum).toBe(45000);
|
||||
expect(rentStats?.avg).toBe(15000);
|
||||
expect(rentStats?.min).toBe(10000);
|
||||
expect(rentStats?.max).toBe(20000);
|
||||
|
||||
expect(report.groups).toHaveLength(2);
|
||||
const amortizedGroup = report.groups?.find((g) => g.groupValue === "已摊销");
|
||||
expect(amortizedGroup?.count).toBe(2);
|
||||
expect(amortizedGroup?.aggregates["租赁费用"]?.sum).toBe(25000);
|
||||
});
|
||||
|
||||
test("auditLedgerContinuityAndBaseline 精准诊断台账序号断层、重号以及离群异常", () => {
|
||||
const entity = {
|
||||
id: "e_lease",
|
||||
name: "租金台账",
|
||||
fields: [
|
||||
{ name: "E_e_lease_seq", label: "摊销序号", type: "number" },
|
||||
{ name: "E_e_lease_fee", label: "租金金额", type: "money" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "r-1", E_e_lease_seq: 1, E_e_lease_fee: 78787.55 },
|
||||
{ id: "r-2a", E_e_lease_seq: 2, E_e_lease_fee: 78787.55 },
|
||||
{ id: "r-2b", E_e_lease_seq: 2, E_e_lease_fee: 0 }, // 离群 + 重号
|
||||
// 缺少序号 3
|
||||
{ id: "r-4", E_e_lease_seq: 4, E_e_lease_fee: 78787.55 },
|
||||
];
|
||||
|
||||
const report = auditLedgerContinuityAndBaseline(records as any, entity as any, {
|
||||
sequenceField: "摊销序号",
|
||||
expectedValues: [{ field: "租金金额", targetValue: 78787.55, tolerance: 0.1 }],
|
||||
});
|
||||
|
||||
expect(report.sequenceSummary).toBeDefined();
|
||||
expect(report.sequenceSummary?.min).toBe(1);
|
||||
expect(report.sequenceSummary?.max).toBe(4);
|
||||
expect(report.sequenceSummary?.missing).toEqual([3]);
|
||||
expect(report.sequenceSummary?.duplicates).toEqual([2]);
|
||||
|
||||
expect(report.outliers).toHaveLength(1);
|
||||
expect(report.outliers[0]?.recordId).toBe("r-2b");
|
||||
expect(report.outliers[0]?.value).toBe(0);
|
||||
expect(report.outliers[0]?.expectedValue).toBe(78787.55);
|
||||
|
||||
const missingIssue = report.issues.find((i) => i.type === "MISSING_SEQUENCE");
|
||||
expect(missingIssue?.message).toContain("缺少第 [3] 期记录");
|
||||
const dupIssue = report.issues.find((i) => i.type === "DUPLICATE_SEQUENCE");
|
||||
expect(dupIssue?.message).toContain("第 [2] 期存在 2 条重复记录");
|
||||
});
|
||||
|
||||
test("parseExpectClause 解析各种容差与期望表达式", () => {
|
||||
const res1 = parseExpectClause("租赁费用 ~= 78787.55");
|
||||
expect(res1).toEqual([{ field: "租赁费用", targetValue: 78787.55, tolerance: undefined }]);
|
||||
|
||||
const res2 = parseExpectClause("租赁费用 = 78787.55 +- 0.05, 日折旧费 ~= 2626.25");
|
||||
expect(res2).toEqual([
|
||||
{ field: "租赁费用", targetValue: 78787.55, tolerance: 0.05 },
|
||||
{ field: "日折旧费", targetValue: 2626.25, tolerance: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
test("filterRecordsByPredicate 支持比较操作符与 in 语法", () => {
|
||||
const entity = {
|
||||
id: "e_item",
|
||||
name: "资产",
|
||||
fields: [
|
||||
{ name: "E_e_item_amount", label: "金额", type: "number" },
|
||||
{ name: "E_e_item_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", E_e_item_amount: 100, E_e_item_status: "ACTIVE" },
|
||||
{ id: "2", E_e_item_amount: 0, E_e_item_status: "INACTIVE" },
|
||||
{ id: "3", E_e_item_amount: 250, E_e_item_status: "ACTIVE" },
|
||||
];
|
||||
|
||||
const matchZero = filterRecordsByPredicate(records as any, "金额 == 0", entity as any);
|
||||
expect(matchZero.map((r) => r.id)).toEqual(["2"]);
|
||||
|
||||
const matchActiveGt100 = filterRecordsByPredicate(records as any, "状态 == 'ACTIVE' && 金额 > 100", entity as any);
|
||||
expect(matchActiveGt100.map((r) => r.id)).toEqual(["3"]);
|
||||
|
||||
const matchIn = filterRecordsByPredicate(records as any, "状态 in (ACTIVE, PENDING)", entity as any);
|
||||
expect(matchIn.map((r) => r.id)).toEqual(["1", "3"]);
|
||||
});
|
||||
|
||||
test("parseSetClause 解析声明式更新赋值并映射到实体字段名", () => {
|
||||
const entity = {
|
||||
id: "e_item",
|
||||
name: "资产",
|
||||
fields: [
|
||||
{ name: "E_e_item_amount", label: "租赁费用", type: "number" },
|
||||
{ name: "E_e_item_status", label: "状态", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const patch = parseSetClause("租赁费用 = 78787.55, 状态 = '待摊销', active = true", entity as any);
|
||||
expect(patch).toEqual({
|
||||
E_e_item_amount: 78787.55,
|
||||
E_e_item_status: "待摊销",
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizeDatalinkRecord 自动提取主键 ID、名称、编码并剥离动态前缀", () => {
|
||||
const entity = {
|
||||
id: "e816139ba5e1cd4ae3c0",
|
||||
name: "摊销明细",
|
||||
fields: [
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_code", label: "编码", type: "text" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_name", label: "名称", type: "text" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_rent", label: "当期租金", type: "money" },
|
||||
{ name: "E_e816139ba5e1cd4ae3c0_vendor", label: "供应商", type: "ref" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const rawRecord = {
|
||||
dataLink: {
|
||||
id: "ID01UsDobfXRRZ",
|
||||
active: false,
|
||||
createTime: 1780000000000,
|
||||
updateTime: 1789000000000,
|
||||
E_e816139ba5e1cd4ae3c0_code: "0-DT-2026-month-1",
|
||||
E_e816139ba5e1cd4ae3c0_name: "使用权资产摊销-北京仓",
|
||||
E_e816139ba5e1cd4ae3c0_rent: { standard: "42680.54", standardUnit: "元" },
|
||||
E_e816139ba5e1cd4ae3c0_vendor: { name: "博展科技" },
|
||||
},
|
||||
};
|
||||
|
||||
const norm = normalizeDatalinkRecord(rawRecord as any, entity as any);
|
||||
expect(norm.id).toBe("ID01UsDobfXRRZ");
|
||||
expect(norm.active).toBe(false);
|
||||
expect(norm.code).toBe("0-DT-2026-month-1");
|
||||
expect(norm.name).toBe("使用权资产摊销-北京仓");
|
||||
expect(norm.fields["当期租金"]).toBe("42680.54");
|
||||
expect(norm.fields["供应商"]).toBe("博展科技");
|
||||
});
|
||||
|
||||
test("calculateEntityRecordStats 准确统计启用率、重名交叉与编码结构聚类", () => {
|
||||
const entity = {
|
||||
id: "e_test",
|
||||
name: "测试对象",
|
||||
fields: [
|
||||
{ name: "code", label: "编码", type: "text" },
|
||||
{ name: "name", label: "名称", type: "text" },
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{ id: "1", code: "0-DT-20260831-0001-month-1", name: "北京仓", active: true, createTime: 1000, updateTime: 2000 },
|
||||
{ id: "2", code: "0-DT-20260831-0001-month-2", name: "北京仓", active: true, createTime: 1000, updateTime: 3000 },
|
||||
{ id: "3", code: "0-DT-20260831-0001-period-1", name: "北京仓", active: false, createTime: 1000, updateTime: 2500 },
|
||||
{ id: "4", code: "0-DT-20260831-0002-month-1", name: "上海仓", active: false, createTime: 1200, updateTime: 2200 },
|
||||
];
|
||||
|
||||
const stats = calculateEntityRecordStats(records as any, entity as any, 4);
|
||||
expect(stats.total).toBe(4);
|
||||
expect(stats.activeCount).toBe(2);
|
||||
expect(stats.inactiveCount).toBe(2);
|
||||
expect(stats.activeRate).toBe("50.0%");
|
||||
expect(stats.uniqueNames).toBe(2);
|
||||
expect(stats.duplicateNamesCount).toBe(1); // "北京仓" 出现 3 次
|
||||
expect(stats.mixedStatusNamesCount).toBe(1); // "北京仓" 同时含启用与停用
|
||||
expect(stats.codePatterns).toHaveLength(2);
|
||||
expect(stats.codePatterns[0].count).toBe(3); // 3 条 month
|
||||
expect(stats.codePatterns[1].count).toBe(1); // 1 条 period
|
||||
});
|
||||
|
||||
test("iterateAllEntityRecords 支持跨页逐条流式下发", async () => {
|
||||
let callCount = 0;
|
||||
const mockClient = {
|
||||
post: () => ({
|
||||
json: async () => {
|
||||
callCount++;
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "rec-1" }, { id: "rec-2" }],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "rec-3" }],
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const stream = iterateAllEntityRecords(mockClient as any, "corp-1", "entity-1", { pageSize: 2 });
|
||||
const collected: string[] = [];
|
||||
for await (const record of stream) {
|
||||
collected.push(record.id!);
|
||||
}
|
||||
|
||||
expect(collected).toEqual(["rec-1", "rec-2", "rec-3"]);
|
||||
expect(callCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DataLink native server filter and keyword expression builder", () => {
|
||||
const entity = {
|
||||
id: "c214f3d2d4bc7e8adfc0",
|
||||
name: "待摊台账",
|
||||
fields: [
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_客户名称", label: "客户名称", type: "text" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_不含税金额", label: "不含税金额", type: "money" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_合同月数", label: "月数", type: "number" },
|
||||
{ name: "E_c214f3d2d4bc7e8adfc0_单号", label: "单号", type: "text" },
|
||||
],
|
||||
} as any;
|
||||
|
||||
test("buildKeywordFilter 缺省模式保持向后兼容并仅查询 name 与 code", () => {
|
||||
const filter = buildKeywordFilter("测试");
|
||||
expect(filter).toBe('(name.containsIgnoreCase("测试")||code.containsIgnoreCase("测试"))&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildKeywordFilter 支持指定业务字段并自动附加 form. 命名空间", () => {
|
||||
const filter = buildKeywordFilter("猫子", {
|
||||
entity,
|
||||
searchFields: ["客户名称"],
|
||||
});
|
||||
expect(filter).toBe(
|
||||
'(name.containsIgnoreCase("猫子")||code.containsIgnoreCase("猫子")||form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))'
|
||||
);
|
||||
});
|
||||
|
||||
test("formatServerFieldExpr 针对 money 字段生成标准 .standard 精确表达式", () => {
|
||||
const expr = formatServerFieldExpr("不含税金额", "=", "191700", entity);
|
||||
expect(expr).toBe(
|
||||
'(form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700"||form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700.00")'
|
||||
);
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 支持 key~val 模糊检索并附加 active 白名单", () => {
|
||||
const filter = buildServerFieldFilter("客户名称~猫子", entity);
|
||||
expect(filter).toBe('(form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 支持已更名标签或底层物理 Code 映射", () => {
|
||||
// 字段名为 "合同月数",标签修改为 "月数"
|
||||
const filterByLabel = buildServerFieldFilter("月数=1", entity);
|
||||
expect(filterByLabel).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||
|
||||
const filterByCode = buildServerFieldFilter("E_c214f3d2d4bc7e8adfc0_合同月数=1", entity);
|
||||
expect(filterByCode).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||
});
|
||||
|
||||
test("buildServerFieldFilter 透传原生复杂的 DataLink DSL 表达式", () => {
|
||||
const rawDsl = '(active == true && INSTR(form.code, "ABC") > 0)';
|
||||
expect(buildServerFieldFilter(rawDsl, entity)).toBe(rawDsl);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import ky from "ky";
|
||||
import { DatalinkEntitySchema } from "./types.js";
|
||||
import { buildSafeRecordEditPayload, compileRecordPredicate, parseSetClause, safeEditRecord } from "./services.js";
|
||||
|
||||
const entity = DatalinkEntitySchema.parse({ id: "entity", fields: [
|
||||
{ name: "E_entity_a", label: "金额", type: "number" },
|
||||
{ name: "E_entity_b", label: "金额", type: "number" },
|
||||
] });
|
||||
|
||||
test("筛选、赋值和 JSON 安全合并均拒绝歧义标签", () => {
|
||||
expect(() => compileRecordPredicate("金额 == 10", entity)).toThrow("歧义");
|
||||
expect(() => parseSetClause("金额=10", entity)).toThrow("歧义");
|
||||
expect(() => buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: entity.fields, patchForm: { 金额: 10 } })).toThrow("歧义");
|
||||
});
|
||||
|
||||
test("明确物理键即使与另一个字段的标签冲突,也保持唯一目标", () => {
|
||||
const collision = DatalinkEntitySchema.parse({ id: "entity", fields: [
|
||||
{ name: "E_entity_a", label: "E_entity_b", type: "number" },
|
||||
{ name: "E_entity_b", label: "金额", type: "number" },
|
||||
] });
|
||||
expect(parseSetClause("E_entity_b=10", collision)).toEqual({ E_entity_b: 10 });
|
||||
expect(compileRecordPredicate("E_entity_b == 10", collision)({ E_entity_a: 1, E_entity_b: 10 })).toBe(true);
|
||||
const payload = buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: collision.fields, patchForm: { E_entity_b: 10 } });
|
||||
expect(payload.form.E_entity_b).toBe(10);
|
||||
expect(payload.form.E_entity_a).toBeUndefined();
|
||||
});
|
||||
|
||||
test("模糊匹配不唯一时拒绝;物理短名、唯一标签和未知字段兼容保留", () => {
|
||||
const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [
|
||||
{ name: "E_entity_a", label: "原始金额", type: "number" },
|
||||
{ name: "E_entity_b", label: "折算金额", type: "number" },
|
||||
] });
|
||||
expect(() => parseSetClause("金额=10", fields)).toThrow("歧义");
|
||||
expect(parseSetClause("a=10,折算金额=20,active=true", fields)).toEqual({ E_entity_a: 10, E_entity_b: 20, active: true });
|
||||
});
|
||||
|
||||
test("安全编辑遇到歧义字段在发出写请求前终止", async () => {
|
||||
const requests: string[] = [];
|
||||
const client = ky.create({ prefix: "https://tenant.invalid", fetch: async input => {
|
||||
requests.push(String(input));
|
||||
return Response.json({});
|
||||
} });
|
||||
await expect(safeEditRecord(client, "corp", { entityId: entity.id, recordId: "r", detail: { id: "r" }, fields: entity.fields, patchForm: { 金额: 10 } })).rejects.toThrow("歧义");
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
test("未声明的系统字段保留原语义,不会模糊匹配 inactive 等业务标签", () => {
|
||||
const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [{ name: "E_entity_old", label: "inactive", type: "text" }] });
|
||||
expect(compileRecordPredicate("active == true", fields)({ active: true, E_entity_old: false })).toBe(true);
|
||||
expect(parseSetClause("active=true", fields)).toEqual({ active: true });
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ValidationError } from "../../../core/errors.js";
|
||||
import type { DatalinkField } from "./types.js";
|
||||
|
||||
/** 物理键优先;标签和模糊匹配必须指向唯一物理字段。未知字段由调用方决定是否透传。 */
|
||||
export function resolveDatalinkField(
|
||||
fields: DatalinkField[],
|
||||
entityId: string,
|
||||
query: string
|
||||
): DatalinkField | undefined {
|
||||
const key = query.trim().toLowerCase();
|
||||
if (!key) return undefined;
|
||||
const prefix = `e_${entityId.replace(/^\$/, "").toLowerCase()}_`;
|
||||
const unique = (matches: DatalinkField[]): DatalinkField | undefined => {
|
||||
const byName = new Map(matches.map((field) => [field.name, field]));
|
||||
if (byName.size > 1) {
|
||||
throw new ValidationError(`字段存在歧义: ${query},请使用完整字段名`);
|
||||
}
|
||||
return byName.values().next().value;
|
||||
};
|
||||
const exact = unique(fields.filter((field) => field.name.toLowerCase() === key))
|
||||
?? unique(fields.filter((field) => field.name.toLowerCase() === prefix + key))
|
||||
?? unique(fields.filter((field) => field.label?.toLowerCase() === key));
|
||||
if (exact) return exact;
|
||||
// 未在元数据声明的系统键由调用方读取/透传,不能误匹配到 inactive 等业务标签。
|
||||
if (["id", "recordid", "active", "name", "code", "createtime", "updatetime", "entityid"].includes(key)) return undefined;
|
||||
return unique(fields.filter((field) => field.label?.toLowerCase().includes(key)));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseSetClause } from "./services.js";
|
||||
const entity = { id: "entity", fields: [{ name: "code", label: "编码", type: "text" }, { name: "name", label: "名称", type: "text" }] } as any;
|
||||
test("quoted numbers, booleans and null remain text while bare literals retain conversion", () => {
|
||||
expect(parseSetClause('编码="001", 名称="true"', entity)).toEqual({ code: "001", name: "true" });
|
||||
expect(parseSetClause("编码='false', 名称='null'", entity)).toEqual({ code: "false", name: "null" });
|
||||
expect(parseSetClause("code=42, name=false", entity)).toEqual({ code: 42, name: false });
|
||||
expect(parseSetClause("code=null", entity)).toEqual({ code: null });
|
||||
expect(parseSetClause(String.raw`code="A\"B"`, entity)).toEqual({ code: 'A"B' });
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseSetClause } from "./services.js";
|
||||
const entity = { id: "entity", fields: [{ name: "name", label: "名称", type: "text" }, { name: "code", label: "编码", type: "text" }] } as any;
|
||||
test("commas inside single and double quoted strings do not split assignments", () => {
|
||||
expect(parseSetClause('名称="ACME, Inc.", 编码=ACME', entity)).toEqual({ name: "ACME, Inc.", code: "ACME" });
|
||||
expect(parseSetClause("名称='A,B', 编码=C", entity)).toEqual({ name: "A,B", code: "C" });
|
||||
});
|
||||
test("escaped quotes preserve the quoted comma boundary", () => {
|
||||
const parsed = parseSetClause(String.raw`name="ACME\", Inc.", code=C`, entity);
|
||||
expect(parsed.code).toBe("C");
|
||||
expect(parsed.name).toEndWith(", Inc.");
|
||||
expect(Object.keys(parsed)).toHaveLength(2);
|
||||
});
|
||||
for (const clause of ['名称="unfinished', "名称=A,broken", "名称=A,", "=A"]) {
|
||||
test(`rejects incomplete assignments: ${clause}`, () => { expect(() => parseSetClause(clause, entity)).toThrow(); });
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { z } from "zod";
|
||||
import type { DatalinkPlatformDetail } from "../applications/types.js";
|
||||
|
||||
const NullableBoolean = z.boolean().nullable().optional();
|
||||
|
||||
/** DataLink 字段元数据。保留服务端未建模的扩展字段,避免丢失配置。 */
|
||||
export const DatalinkFieldSchema = z
|
||||
.object({
|
||||
name: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: NullableBoolean,
|
||||
regex: z.string().nullable().optional(),
|
||||
source: z.string().nullable().optional(),
|
||||
formula: z.boolean().nullable().optional(),
|
||||
calculation: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
entity: z.string().nullable().optional(),
|
||||
withTime: z.boolean().nullable().optional(),
|
||||
scale: z.number().nullable().optional(),
|
||||
unit: z.string().nullable().optional(),
|
||||
index: z.boolean().nullable().optional(),
|
||||
systemField: z.boolean().nullable().optional(),
|
||||
fieldKey: z.string().optional(),
|
||||
displayName: z.string().optional(),
|
||||
role: z.enum(["title", "code", "system", "custom"]).optional(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export function enrichDatalinkField<T extends DatalinkField>(field: T): T {
|
||||
const name = field.name;
|
||||
const label = field.label;
|
||||
let role: "title" | "code" | "system" | "custom" = "custom";
|
||||
let description = `业务自定义字段 (界面显示为「${label}」),API与工作流配置时使用此物理键`;
|
||||
if (name.endsWith("_name")) {
|
||||
role = "title";
|
||||
description = `实体主名称/标题 (界面显示为「${label}」),系统基础字段`;
|
||||
} else if (name.endsWith("_code")) {
|
||||
role = "code";
|
||||
description = `业务单号/流水号 (界面显示为「${label}」),通常由自动编号规则生成`;
|
||||
} else if (field.systemField) {
|
||||
role = "system";
|
||||
description = `系统预置字段 (界面显示为「${label}」)`;
|
||||
}
|
||||
return {
|
||||
...field,
|
||||
fieldKey: field.fieldKey ?? name,
|
||||
displayName: field.displayName ?? label,
|
||||
role: field.role ?? role,
|
||||
description: field.description ?? description,
|
||||
};
|
||||
}
|
||||
|
||||
export const DatalinkEntitySchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
code: z.string().default(""),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
active: z.boolean().default(true),
|
||||
fields: z.array(DatalinkFieldSchema).default([]),
|
||||
actions: z.array(z.unknown()).default([]),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
visibility: z.unknown().optional(),
|
||||
homeVisibility: z.unknown().optional(),
|
||||
exportVisibility: z.unknown().optional(),
|
||||
dataFilter: z.unknown().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export interface DatalinkRecordQuery {
|
||||
start?: number;
|
||||
count?: number;
|
||||
filterBy?: string;
|
||||
/** 服务端支持的排序表达式,原样透传。 */
|
||||
orderBy?: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecord {
|
||||
id?: string;
|
||||
entityId?: string;
|
||||
dataLink?: Record<string, unknown>;
|
||||
fieldAuth?: Record<string, unknown>;
|
||||
visibility?: unknown;
|
||||
active?: boolean;
|
||||
ownerId?: string;
|
||||
createTime?: number | string;
|
||||
updateTime?: number | string;
|
||||
actions?: unknown[];
|
||||
source?: unknown;
|
||||
sourceId?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordPage {
|
||||
total: number;
|
||||
data: DatalinkRecord[];
|
||||
actions: unknown[];
|
||||
components: unknown[];
|
||||
path: unknown;
|
||||
template: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkImportJob {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type DatalinkField = z.infer<typeof DatalinkFieldSchema>;
|
||||
export type DatalinkEntity = z.infer<typeof DatalinkEntitySchema>;
|
||||
export type { DatalinkPlatformDetail } from "../applications/types.js";
|
||||
|
||||
export interface DatalinkPermissionSnapshot {
|
||||
platform: DatalinkPlatformDetail;
|
||||
entity?: DatalinkEntity;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordDetail {
|
||||
dataLink?: DatalinkRecord;
|
||||
template?: unknown;
|
||||
entity?: unknown;
|
||||
actions?: unknown[];
|
||||
flowCounts?: Record<string, unknown>;
|
||||
ledger?: Record<string, unknown>;
|
||||
ledgers?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordEditPayload {
|
||||
dataLinkEntityId: string;
|
||||
dataLinkId: string;
|
||||
active?: boolean;
|
||||
form: Record<string, unknown>;
|
||||
visibility?: {
|
||||
fullVisible?: boolean;
|
||||
staffs?: string[];
|
||||
roles?: string[];
|
||||
departments?: string[];
|
||||
departmentsIncludeChildren?: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// ── 台账聚合统计与数学核对模型 ─────────────────────────────────────────────
|
||||
|
||||
export interface AggregateFieldStats {
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
count: number;
|
||||
sum: number;
|
||||
avg: number;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface GroupAggregateResult {
|
||||
groupValue: string;
|
||||
count: number;
|
||||
aggregates: Record<string, AggregateFieldStats>;
|
||||
}
|
||||
|
||||
export interface LedgerAggregateReport {
|
||||
totalRecords: number;
|
||||
overall: Record<string, AggregateFieldStats>;
|
||||
groups?: GroupAggregateResult[];
|
||||
}
|
||||
|
||||
// ── 台账连续性与基线断层核对模型 ──────────────────────────────────────────
|
||||
|
||||
export interface ContinuityIssue {
|
||||
type: "MISSING_SEQUENCE" | "DUPLICATE_SEQUENCE" | "VALUE_OUTLIER";
|
||||
recordId?: string;
|
||||
field: string;
|
||||
message: string;
|
||||
expected?: unknown;
|
||||
actual?: unknown;
|
||||
}
|
||||
|
||||
export interface LedgerContinuityReport {
|
||||
totalRecords: number;
|
||||
sequenceSummary?: {
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
min: number;
|
||||
max: number;
|
||||
expectedCount: number;
|
||||
actualCount: number;
|
||||
missing: number[];
|
||||
duplicates: number[];
|
||||
};
|
||||
issues: ContinuityIssue[];
|
||||
outliers: Array<{
|
||||
recordId: string;
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
value: number;
|
||||
expectedValue: number;
|
||||
diff: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
// ── 归一化记录与统计画像模型 ───────────────────────────────────────────────
|
||||
|
||||
export interface NormalizedDatalinkRecord {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
active: boolean;
|
||||
createTime?: number | null;
|
||||
updateTime?: number | null;
|
||||
fields: Record<string, unknown>;
|
||||
raw?: DatalinkRecord;
|
||||
}
|
||||
|
||||
export interface DatalinkRecordStats {
|
||||
total: number;
|
||||
activeCount: number;
|
||||
inactiveCount: number;
|
||||
activeRate: string;
|
||||
uniqueNames: number;
|
||||
duplicateNamesCount: number;
|
||||
mixedStatusNamesCount: number;
|
||||
codePatterns: Array<{
|
||||
pattern: string;
|
||||
sample: string;
|
||||
count: number;
|
||||
activeCount: number;
|
||||
inactiveCount: number;
|
||||
}>;
|
||||
earliestCreateTime?: string | null;
|
||||
latestUpdateTime?: string | null;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
> 本模块归属自建应用平台;工作流模型、传输与编排现位于同级 `types.ts`、`api.ts`、`services.ts`,跨应用查询使用 applications 服务。上级入口见 [Platform 总览](../README.platform.md)。
|
||||
|
||||
# Workflow 工作流模块
|
||||
|
||||
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||||
import type {
|
||||
WorkflowAnalysis,
|
||||
WorkflowAstNode,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||||
import { analyzeWorkflow } from "./analyzer.js";
|
||||
|
||||
const selector = (key: unknown, label?: unknown) => `@{value('${JSON.stringify({ key, label })}')}`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./index.js";
|
||||
import { PlatformSchema } from "../../types.js";
|
||||
import { PlatformSchema } from "../../applications/types.js";
|
||||
|
||||
describe("Workflow static analysis", () => {
|
||||
it("accepts nullable app center metadata", () => {
|
||||
|
||||
File renamed without changes.
@@ -1,8 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import ky, { KyInstance } from "ky";
|
||||
import { AuthenticationError, BusinessError, EkbApiError } from "../../core/errors.js";
|
||||
import { AuthenticationError, BusinessError, EkbApiError } from "../../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
WorkflowStatsSchema,
|
||||
WorkflowChargeSchema,
|
||||
@@ -87,19 +86,6 @@ async function ok(response: Response): Promise<{ success: boolean }> {
|
||||
return { success: response.status === 200 };
|
||||
}
|
||||
|
||||
// ── 自建应用 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listPlatforms(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<import("./types.js").Platform[]> {
|
||||
const response = await client.get("api/v2/datalink/platform/search", {
|
||||
searchParams: { scope: "enable", corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items: unknown[] };
|
||||
return z.array(PlatformSchema).parse(json.items);
|
||||
}
|
||||
|
||||
// ── 工作流(EASO)─────────────────────────────────────────────────────────────
|
||||
// 注意:EASO 客户端已自动注入 corpId,无需再传
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import { indexExecutionContexts } from "../../execution-context.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
import { indexExecutionContexts } from "../execution-context.js";
|
||||
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
|
||||
|
||||
export const OP_MAP: Record<string, string> = {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { explainConditionBranches } from "./index.js";
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
|
||||
describe("Workflow Condition Branch Diagnosis", () => {
|
||||
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
isWorkflowActionCode,
|
||||
matchWorkflowAction,
|
||||
resolveWorkflowEnumOptions,
|
||||
} from "../services.js";
|
||||
} from "./services.js";
|
||||
import { analyzeWorkflow } from "./analysis/index.js";
|
||||
|
||||
describe("Workflow Action Enums & Diagnostics", () => {
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -12,7 +12,7 @@ import {
|
||||
displayNameLength,
|
||||
isDisplayNameTooLong,
|
||||
} from "./index.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||||
|
||||
const mockWorkflow: WorkflowDetail = {
|
||||
id: "wf_test_100",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
import type { LocatedWorkflowTask } from "./types.js";
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||||
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
|
||||
import { findWorkflowTask } from "./locator.js";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
import type { FlattenedWorkflowTask } from "./types.js";
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
|
||||
export interface FlattenedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { classifyCliError } from "../../cli/errors.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../../core/errors.js";
|
||||
import { classifyCliError } from "../../../cli/errors.js";
|
||||
import { listRunningJobs, unwrap } from "./api.js";
|
||||
import { watchWorkflowPipeline } from "./workflow/watch/pipeline-watcher.js";
|
||||
import { watchWorkflowPipeline } from "./watch/pipeline-watcher.js";
|
||||
|
||||
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { EkbError } from "../../../core/errors.js";
|
||||
import type { WorkflowDetail } from "../types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
|
||||
/** 主保存已经提交,后续元数据刷新失败。调用方必须保留已保存版本。 */
|
||||
export class WorkflowSavePartialError extends EkbError {
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
executeJavaScriptSandbox,
|
||||
executeMvelSandbox,
|
||||
} from "./index.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
import type { WorkflowDetail } from "../types.js";
|
||||
|
||||
describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => {
|
||||
describe("hasReturnStatement", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasMvelFinalExpression } from "./mvel-subset.js";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "../types.js";
|
||||
import type { NodeScriptLintReport, WorkflowScriptLintReport, ScriptIssue } from "./types.js";
|
||||
import { lintJavaScriptCode } from "./lint-js.js";
|
||||
import { lintMvelCode, collectAllWorkflowNodeNames } from "./lint-mvel.js";
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { listBasicPlatforms } from "../applications/services.js";
|
||||
import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { WorkflowSavePartialError } from "./workflow/save-error.js";
|
||||
import { CorpConfig } from "../../../core/config/types.js";
|
||||
import { WorkflowSavePartialError } from "./save-error.js";
|
||||
import * as api from "./api.js";
|
||||
import { PermissionError, ValidationError } from "../../core/errors.js";
|
||||
import { explainConditionBranches } from "./workflow/branch/index.js";
|
||||
import { PermissionError, ValidationError } from "../../../core/errors.js";
|
||||
import { explainConditionBranches } from "./branch/index.js";
|
||||
import { indexExecutionContexts } from "./execution-context.js";
|
||||
import {
|
||||
Platform,
|
||||
WorkflowSummary,
|
||||
WorkflowListAllError,
|
||||
WorkflowTask,
|
||||
@@ -21,16 +21,12 @@ import {
|
||||
NodeExecutionDiff,
|
||||
} from "./types.js";
|
||||
|
||||
export interface PlatformClients {
|
||||
export interface WorkflowClients {
|
||||
corp: CorpConfig;
|
||||
ekbClient: KyInstance;
|
||||
easoClient: KyInstance;
|
||||
}
|
||||
|
||||
export function listPlatforms(...args: Parameters<typeof api.listPlatforms>) {
|
||||
return api.listPlatforms(...args);
|
||||
}
|
||||
|
||||
export function listWorkflows(...args: Parameters<typeof api.listWorkflows>) {
|
||||
return api.listWorkflows(...args);
|
||||
}
|
||||
@@ -309,14 +305,14 @@ export interface ListAllWorkflowsResult {
|
||||
}
|
||||
|
||||
export async function listAllWorkflows(
|
||||
clients: PlatformClients,
|
||||
clients: WorkflowClients,
|
||||
options: ListAllWorkflowsOptions = {}
|
||||
): Promise<ListAllWorkflowsResult> {
|
||||
const { ekbClient, easoClient, corp } = clients;
|
||||
const page = options.page ?? 1;
|
||||
const pageSize = options.pageSize ?? 20;
|
||||
|
||||
const platforms = await api.listPlatforms(ekbClient, corp.credentials.corpId);
|
||||
const platforms = await listBasicPlatforms(ekbClient, corp.credentials.corpId);
|
||||
const enabledPlatforms = platforms.filter((p) => p.active !== false);
|
||||
|
||||
const workflows: WorkflowSummary[] = [];
|
||||
@@ -381,7 +377,7 @@ export interface FindWorkflowsByTaskTypeResult {
|
||||
}
|
||||
|
||||
export async function findWorkflowsByTaskType(
|
||||
clients: PlatformClients,
|
||||
clients: WorkflowClients,
|
||||
taskType: string,
|
||||
options: FindWorkflowsByTaskTypeOptions = {}
|
||||
): Promise<FindWorkflowsByTaskTypeResult> {
|
||||
@@ -967,7 +963,7 @@ export {
|
||||
explainConditionBranches,
|
||||
type ConditionBranchExplanation,
|
||||
type ConditionRuleExplanation,
|
||||
} from "./workflow/branch/index.js";
|
||||
} from "./branch/index.js";
|
||||
|
||||
export {
|
||||
classifyWorkflowTrigger,
|
||||
@@ -1009,7 +1005,7 @@ export async function resolveWorkflowEnumOptions(
|
||||
}
|
||||
|
||||
if (thirdId.toLowerCase() === "action") {
|
||||
const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./workflow/enums.js");
|
||||
const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./enums.js");
|
||||
return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({
|
||||
code: item.code,
|
||||
label: item.label,
|
||||
@@ -1066,7 +1062,7 @@ export async function grantWorkflowNodes(
|
||||
}
|
||||
|
||||
// 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type)
|
||||
const { findGrayNode } = await import("./workflow/nodes/gray-nodes-catalog.js");
|
||||
const { findGrayNode } = await import("./nodes/gray-nodes-catalog.js");
|
||||
const normalizedNodes = options.nodes.map((node) => {
|
||||
const matched = findGrayNode(node);
|
||||
return matched ? matched.type : node.trim();
|
||||
@@ -1091,4 +1087,4 @@ export async function grantWorkflowNodes(
|
||||
return result;
|
||||
}
|
||||
|
||||
export * from "./workflow/index.js";
|
||||
export * from "./index.js";
|
||||
File renamed without changes.
@@ -8,8 +8,8 @@ import {
|
||||
hasWorkflowVersionConflict,
|
||||
patchWorkflowDraft,
|
||||
} from "./index.js";
|
||||
import { WorkflowDetailSchema } from "../../types.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
import { WorkflowDetailSchema } from "../types.js";
|
||||
import type { WorkflowDetail } from "../types.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
} from "../../api.js";
|
||||
} from "../api.js";
|
||||
import {
|
||||
extractFailureExecutions,
|
||||
findExecutionNode,
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
isTaskExecutionFailed,
|
||||
updateWorkflow,
|
||||
sanitizeWorkflowSnapshot,
|
||||
} from "../../services.js";
|
||||
} from "../services.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "../alert/index.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NotFoundError, ValidationError } from "../../../../core/errors.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
import type { WorkflowDetail } from "../types.js";
|
||||
|
||||
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "partial" | "failed";
|
||||
|
||||
|
||||
File renamed without changes.
@@ -1,26 +1,5 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 自建应用(DataLink Platform)─────────────────────────────
|
||||
|
||||
export const PlatformSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
nameSpell: z.string().default(""),
|
||||
enName: z.string().nullable().optional(),
|
||||
code: z.string().default(""),
|
||||
corporationId: z.string(),
|
||||
active: z.boolean().default(true),
|
||||
type: z.string().default(""),
|
||||
groupType: z.string().default(""),
|
||||
platformType: z.string().default(""),
|
||||
source: z.string().default(""),
|
||||
adminIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
desc: z.string().nullable().optional(),
|
||||
importMethod: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 工作流任务节点(递归、按类型区分)─────────────────────────────────────────
|
||||
|
||||
export const BaseTaskSchema = z.object({
|
||||
@@ -561,7 +540,6 @@ export const WorkflowWithMatchesSchema = WorkflowSummarySchema.extend({
|
||||
|
||||
// ── 类型导出 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type Platform = z.infer<typeof PlatformSchema>;
|
||||
export type FilterGroup = z.infer<typeof FilterGroupSchema>;
|
||||
export type WorkflowState = z.infer<typeof WorkflowStateSchema>;
|
||||
export type Workflow = z.infer<typeof WorkflowSchema>;
|
||||
@@ -727,7 +705,7 @@ export interface WorkflowTestReport {
|
||||
triggerLabel?: string;
|
||||
executionTree: WorkflowTaskExecution[];
|
||||
failedExecutions: WorkflowTaskExecution[];
|
||||
conditionDiagnoses: import("./workflow/branch/index.js").ConditionBranchExplanation[];
|
||||
conditionDiagnoses: import("./branch/index.js").ConditionBranchExplanation[];
|
||||
}
|
||||
|
||||
// ── 触发器元类型分类与智能路径路由 ───────────────────────────────────────────────
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
|
||||
export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
watchWorkflowPipeline,
|
||||
type WorkflowWatchEvent,
|
||||
} from "./index.js";
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
|
||||
describe("workflow-watch - 实时监控与日志流跟踪引擎", () => {
|
||||
describe("TaskExecutionTracker", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import * as api from "../../api.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { watchSingleJob } from "./single-job.js";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../../types.js";
|
||||
import * as api from "../../api.js";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { TaskExecutionTracker } from "./tracker.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { WorkflowTaskExecution } from "../../types.js";
|
||||
import { flattenExecutionTree, isTaskExecutionFailed } from "../../services.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
import { flattenExecutionTree, isTaskExecutionFailed } from "../services.js";
|
||||
import type { WorkflowWatchEvent } from "./types.js";
|
||||
import { extractTaskErrorMessage } from "./helpers.js";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkflowJobDetail } from "../../types.js";
|
||||
import type { WorkflowJobDetail } from "../types.js";
|
||||
|
||||
export type WorkflowWatchEventType =
|
||||
| "pipeline_watch_start"
|
||||
|
||||
File renamed without changes.
+2
-2
@@ -3,8 +3,8 @@ import ky from "ky";
|
||||
import { deleteWorkflow, updateWorkflowChooses } from "./api.js";
|
||||
import { refreshWorkflowChooses, updateWorkflow } from "./services.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import { WorkflowSavePartialError } from "./workflow/save-error.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
import { WorkflowSavePartialError } from "./save-error.js";
|
||||
import { AuthenticationError } from "../../../core/errors.js";
|
||||
|
||||
test("Piper 无返回值写操作兼容空成功,拒绝业务失败与无效 JSON", async () => {
|
||||
for (const action of [deleteWorkflow, updateWorkflowChooses]) {
|
||||
Reference in new issue
Block a user