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 (/(? 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 { const result: Record = {}; 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; }