WEB/src/utils/stockQueryBuilder.ts
2026-06-16 18:24:32 +08:00

96 lines
3.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* stock.stockWarehouse 前端查询规则封装
* 对应文档:stock-stockWarehouse-query-rules.md
*/
/**
* 构建符合后端规范的 where 查询对象
* @param params 前端原始查询参数(通常来自 ScanBox)
* @returns 后端需要的 where 对象
*/
export function buildStockQuery(params: Record<string, any>) {
const where: Record<string, any> = {};
if (!params) return where;
for (const [key, val] of Object.entries(params)) {
// 1. 基础空值检查
if (val === null || val === undefined || val === '') continue;
if (Array.isArray(val) && val.length === 0) continue;
let condition = val;
// 2. 如果值不是对象结构(简单键值对),或数组(in 查询简写),则转换
if (typeof val !== 'object' || Array.isArray(val)) {
condition = { value: val };
} else {
// 如果是对象,检查内部 value 是否有效
if (
condition.value === null ||
condition.value === undefined ||
condition.value === '' ||
(Array.isArray(condition.value) && condition.value.length === 0)
) {
continue;
}
// 浅拷贝避免修改源数据
condition = { ...val };
}
// 3. 默认操作符处理
if (!condition.operator) {
if (key === 'barcode') {
condition.operator = 'like'; // 推荐 operator=eq|like
} else if (key === 'item_code') {
condition.operator = 'like';
} else {
condition.operator = 'eq';
}
}
// 4. 类型转换与值处理
// has_bound_item 为特殊字段,保留 boolean 原值(后端亦支持 Y/N)
if (key === 'has_bound_item' && condition.type === 'boolean') {
if (condition.value === true || condition.value === 'true' || condition.value === 1 || condition.value === '1') {
condition.value = true;
} else if (condition.value === false || condition.value === 'false' || condition.value === 0 || condition.value === '0') {
condition.value = false;
}
} else if (condition.type === 'boolean') {
// 处理 boolean -> Y/N
if (condition.value === true || condition.value === 'true') {
condition.value = 'Y';
} else if (condition.value === false || condition.value === 'false') {
condition.value = 'N';
}
}
// 处理 text (逗号分隔字符串拆分数组) - ScanBox 可能已经处理,这里做防守
if (condition.type === 'text' && typeof condition.value === 'string' && condition.value.includes(',')) {
// 如果 ScanBox 传来了 string 且 type=text,后端规则提到 "逗号分隔字符串拆分数组"
// 取決于 ScanBox 是否处理了。如果 ScanBox 里的 operator 是 in 或者 contains 可能会有逗号
// 文档说: type=text: 逗号分隔字符串拆分数组。
// 如果我们传数组给后端,JSON序列化后是数组。
if (!Array.isArray(condition.value)) {
condition.value = condition.value.split(',').filter((s: string) => s.trim() !== '');
}
}
// 5. 构造最终对象 (过滤掉多余字段如 isMultiple, placeholders 等)
const finalObj: Record<string, any> = {
operator: condition.operator,
value: condition.value
};
if (condition.type) finalObj.type = condition.type;
// 允许显式传递 field 映射
if (condition.field) finalObj.field = condition.field;
where[key] = finalObj;
}
return where;
}