将工作流查询、配置、执行、差异、调试、目录和 DataLink 记录、表达式、审计分别归位。 门面保留显式导出,消除 tracker 及分支类型经聚合出口形成的循环,补充文件级循环检查。 同步总纲、层级文档与接口源码索引,交付完整整改报告。 验证:943 项测试通过,类型、版本和 README 审计通过;二进制和插件构建、验证与打包通过。 81 个迁移函数体保持一致,公共 SDK 导出名和三份生成规范与原始基线一致。
296 lines
11 KiB
TypeScript
296 lines
11 KiB
TypeScript
import { ValidationError } from "../../../core/errors.js";
|
|
import type { DatalinkEntity, DatalinkField, DatalinkRecord } from "./types.js";
|
|
import { resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js";
|
|
|
|
|
|
export interface BuildKeywordFilterOptions {
|
|
entity?: DatalinkEntity;
|
|
searchFields?: string[];
|
|
}
|
|
|
|
|
|
/**
|
|
* 格式化服务端 filterBy 字段表达式。
|
|
* 针对 DataLink 特性:
|
|
* - 动态业务字段(E_ 前缀)自动附加 form. 命名空间
|
|
* - money 货币复合对象自动下钻到 .standard 标准字符串
|
|
* - number 数值字段支持比较运算符
|
|
*/
|
|
export function formatServerFieldExpr(
|
|
fieldKey: string,
|
|
op: string,
|
|
rawVal: string,
|
|
entity?: DatalinkEntity
|
|
): string {
|
|
const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined;
|
|
const targetKey = resolved?.name || fieldKey;
|
|
const isCustom = targetKey.startsWith("E_");
|
|
const serverPath = isCustom ? `form.${targetKey}` : targetKey;
|
|
const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== "";
|
|
|
|
// Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... })
|
|
if (resolved?.type === "money") {
|
|
const moneyPath = `${serverPath}.standard`;
|
|
const num = Number(rawVal);
|
|
const withDec = !Number.isNaN(num) && !rawVal.includes("../../datalink") ? `${rawVal}.00` : rawVal;
|
|
if (op === "=" || op === "==") {
|
|
if (withDec !== rawVal) {
|
|
return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`;
|
|
}
|
|
return `${moneyPath}=="${escaped}"`;
|
|
}
|
|
if (op === "!=") {
|
|
return `${moneyPath}!="${escaped}"`;
|
|
}
|
|
return `${moneyPath}.containsIgnoreCase("${escaped}")`;
|
|
}
|
|
|
|
// Number 字段
|
|
if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) {
|
|
if (op === "~" || op === "=~" || op === ":") {
|
|
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
|
}
|
|
const cmp = op === "=" ? "==" : op;
|
|
return `${serverPath}${cmp}${rawVal}`;
|
|
}
|
|
|
|
// Text / Ref / Other 字段
|
|
if (op === "~" || op === "=~" || op === ":") {
|
|
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
|
}
|
|
if (op === "!=") {
|
|
return `${serverPath}!="${escaped}"`;
|
|
}
|
|
return `${serverPath}=="${escaped}"`;
|
|
}
|
|
|
|
|
|
export function buildKeywordFilter(
|
|
keyword: string,
|
|
options?: BuildKeywordFilterOptions
|
|
): string {
|
|
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
const conds: string[] = [
|
|
`name.containsIgnoreCase("${escaped}")`,
|
|
`code.containsIgnoreCase("${escaped}")`,
|
|
];
|
|
|
|
if (options?.entity && options.searchFields && options.searchFields.length > 0) {
|
|
for (const searchField of options.searchFields) {
|
|
const resolved = resolveEntityField(options.entity, searchField);
|
|
const targetName = resolved?.name || searchField;
|
|
if (targetName && targetName !== "name" && targetName !== "code") {
|
|
const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity);
|
|
conds.push(expr);
|
|
}
|
|
}
|
|
}
|
|
|
|
return `(${conds.join("||")})&&(active.in(true,false))`;
|
|
}
|
|
|
|
|
|
/**
|
|
* 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。
|
|
* 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。
|
|
*/
|
|
export function buildServerFieldFilter(
|
|
filterInput: string,
|
|
entity?: DatalinkEntity
|
|
): string {
|
|
const trimmed = filterInput.trim();
|
|
if (
|
|
trimmed.startsWith("(") ||
|
|
trimmed.includes(".containsIgnoreCase(") ||
|
|
trimmed.includes(".in(") ||
|
|
trimmed.includes("==")
|
|
) {
|
|
return trimmed;
|
|
}
|
|
|
|
// 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用"
|
|
const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/);
|
|
if (!match) return trimmed;
|
|
|
|
const rawKey = match[1].trim();
|
|
const op = match[2];
|
|
const rawVal = match[3].trim().replace(/^["']|["']$/g, "");
|
|
|
|
const expr = formatServerFieldExpr(rawKey, op, rawVal, entity);
|
|
return expr ? `(${expr})&&(active.in(true,false))` : trimmed;
|
|
}
|
|
|
|
|
|
/**
|
|
* 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合)
|
|
*/
|
|
function splitPredicateParts(source: string, separator: string): string[] {
|
|
const parts: string[] = [];
|
|
let quote = "", depth = 0, start = 0;
|
|
for (let i = 0; i < source.length; i++) {
|
|
const char = source[i];
|
|
if (quote) {
|
|
if (char === "\\") i++;
|
|
else if (char === quote) quote = "";
|
|
continue;
|
|
}
|
|
if (char === "'" || char === '"') quote = char;
|
|
else if (char === "(") depth++;
|
|
else if (char === ")") {
|
|
if (--depth < 0) throw new ValidationError("筛选条件括号不匹配");
|
|
} else if (depth === 0 && source.startsWith(separator, i)) {
|
|
parts.push(source.slice(start, i).trim());
|
|
start = i + separator.length;
|
|
i += separator.length - 1;
|
|
}
|
|
}
|
|
if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配");
|
|
parts.push(source.slice(start).trim());
|
|
if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空");
|
|
return parts;
|
|
}
|
|
|
|
|
|
function predicateLiteral(raw: string): string | number | boolean | null {
|
|
if (/^(["']).*\1$/s.test(raw)) {
|
|
const value = raw.slice(1, -1);
|
|
if (raw[0] === '"') {
|
|
try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); }
|
|
}
|
|
if (/(?<!\\)'/.test(value)) throw new ValidationError(`筛选值引号不匹配: ${raw}`);
|
|
return value.replace(/\\(['\\])/g, "$1");
|
|
}
|
|
if (raw === "null") return null;
|
|
if (raw === "true" || raw === "false") return raw === "true";
|
|
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw) && Number.isFinite(Number(raw))) return Number(raw);
|
|
if (/^[\p{L}\p{N}_:.$/-]+$/u.test(raw)) return raw;
|
|
throw new ValidationError(`不支持的筛选值: ${raw};文本中的空格或符号请使用引号`);
|
|
}
|
|
|
|
|
|
function predicateField(entity: DatalinkEntity, query: string): DatalinkField | string {
|
|
const field = resolveEntityField(entity, query);
|
|
if (field) return field;
|
|
if (["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
|
|
throw new ValidationError(`未知筛选字段: ${query}`);
|
|
}
|
|
|
|
|
|
/** 先完整校验语法和字段,再生成可复用的筛选器,空结果集也不能掩盖错误。 */
|
|
export function compileRecordPredicate(whereClause: string, entity: DatalinkEntity): (record: DatalinkRecord) => boolean {
|
|
const conditions = splitPredicateParts(whereClause, "&&").map(cond => {
|
|
// 1. in 操作符: field in (v1, v2, v3)
|
|
const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i);
|
|
// 2. 比较操作符: ==, !=, >=, <=, >, <, =
|
|
const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s);
|
|
if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`);
|
|
const field = predicateField(entity, (inMatch ?? compMatch)![1].trim());
|
|
const op = inMatch ? "in" : compMatch![2];
|
|
const targets = inMatch
|
|
? splitPredicateParts(inMatch[2], ",").map(predicateLiteral)
|
|
: [predicateLiteral(compMatch![3].trim())];
|
|
return (record: DatalinkRecord) => {
|
|
const actual = extractRecordFieldValue(record, field);
|
|
const equal = (target: string | number | boolean | null): boolean => {
|
|
if (target === null) return actual === null || actual === undefined;
|
|
if (typeof target === "number") return extractNumericFieldValue(record, field) === target;
|
|
return actual !== null && actual !== undefined && String(actual) === String(target);
|
|
};
|
|
if (op === "in") return targets.some(equal);
|
|
// 字符串/布尔比较
|
|
if (op === "=" || op === "==") return equal(targets[0]);
|
|
if (op === "!=") return !equal(targets[0]);
|
|
// 数值比较
|
|
const value = extractNumericFieldValue(record, field);
|
|
const target = targets[0];
|
|
if (value === null || typeof target !== "number") return false;
|
|
return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target;
|
|
};
|
|
});
|
|
return record => conditions.every(condition => condition(record));
|
|
}
|
|
|
|
|
|
export function filterRecordsByPredicate(
|
|
records: DatalinkRecord[],
|
|
whereClause: string,
|
|
entity: DatalinkEntity
|
|
): DatalinkRecord[] {
|
|
if (!whereClause || !whereClause.trim()) return records;
|
|
return records.filter(compileRecordPredicate(whereClause, entity));
|
|
}
|
|
|
|
|
|
/**
|
|
* 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销"
|
|
*/
|
|
export function parseSetClause(
|
|
setClause: string,
|
|
entity: DatalinkEntity
|
|
): Record<string, unknown> {
|
|
const result: Record<string, unknown> = {};
|
|
let assignments: string[];
|
|
try { assignments = splitPredicateParts(setClause, ","); }
|
|
catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); }
|
|
|
|
for (const assign of assignments) {
|
|
const eqIdx = assign.indexOf("=");
|
|
if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`);
|
|
const rawKey = assign.slice(0, eqIdx).trim();
|
|
if (!rawKey) throw new ValidationError("赋值字段不能为空");
|
|
let rawVal = assign.slice(eqIdx + 1).trim();
|
|
|
|
// 去除外层引号,同时保留显式字符串的类型与转义语义。
|
|
const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'"));
|
|
const literal = quoted ? predicateLiteral(rawVal) : undefined;
|
|
|
|
const field = resolveEntityField(entity, rawKey);
|
|
const targetKey = field ? field.name : rawKey;
|
|
|
|
// 类型智能转换
|
|
if (quoted) {
|
|
result[targetKey] = literal;
|
|
} else if (rawVal === "true") {
|
|
result[targetKey] = true;
|
|
} else if (rawVal === "false") {
|
|
result[targetKey] = false;
|
|
} else if (rawVal === "null") {
|
|
result[targetKey] = null;
|
|
} else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") {
|
|
result[targetKey] = Number(rawVal);
|
|
} else {
|
|
result[targetKey] = rawVal;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
|
|
/**
|
|
* 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05"
|
|
*/
|
|
export function parseExpectClause(
|
|
expectClause: string
|
|
): Array<{ field: string; targetValue: number; tolerance?: number }> {
|
|
if (!expectClause || !expectClause.trim()) return [];
|
|
const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean);
|
|
const results: Array<{ field: string; targetValue: number; tolerance?: number }> = [];
|
|
|
|
for (const part of parts) {
|
|
const match = part.match(
|
|
/^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/
|
|
);
|
|
if (match) {
|
|
const field = match[1].trim();
|
|
const targetValue = parseFloat(match[2]);
|
|
const tolerance = match[3] ? parseFloat(match[3]) : undefined;
|
|
if (!Number.isNaN(targetValue)) {
|
|
results.push({ field, targetValue, tolerance });
|
|
}
|
|
}
|
|
}
|
|
return results;
|
|
}
|