diff --git a/app/service/systemMethods/order/packing.js b/app/service/systemMethods/order/packing.js index ba567cb..5c47629 100644 --- a/app/service/systemMethods/order/packing.js +++ b/app/service/systemMethods/order/packing.js @@ -31,12 +31,15 @@ class OrderPackingMethodService extends MainService { * @param {Object} [data.pagination] 分页参数 { page, pageSize } * @param {Object} [data.where] 筛选条件。 * 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、 - * order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、 + * order_id(订单ID)、workbench_id(工作台ID)、operator_text(打包员/作业人员姓名)、 + * quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、 * start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围); * start_time_start / start_time_end 为开始时间范围的兼容旧写法。 * 运单号与波次号字段支持 {operator, value} 标准结构且 value 支持数组: * operator=contains/like 时按 LIKE '%值%' 模糊匹配(waybill_code 可命中 '主体-1-1-' 等分段单号),wave_no 另支持 eq/in 精确、ne 不等; * waybill_code 缺省/eq 时为「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀」精确匹配。 + * operator_text(打包员/作业人员姓名)支持 {operator,value} 标准结构且 value 支持数组: + * contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)。 * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } * @return {Promise} 统一成功包装响应 */ diff --git a/app/service/systems/order_packing.js b/app/service/systems/order_packing.js index 76b9da2..9d74fe9 100644 --- a/app/service/systems/order_packing.js +++ b/app/service/systems/order_packing.js @@ -76,9 +76,12 @@ class OrderPackingService extends Service { } /** - * 构建列表筛选条件(list 与 export 复用同一套语义)。 + * 构建列表筛选条件(list 与 exportPackTask 复用同一套语义,导出会自动获得同一筛选语义)。 * - * @param {Object} where 筛选条件对象(与 list 入参一致) + * @param {Object} where 筛选条件对象(与 list 入参一致)。其中 operator_text(打包员/作业人员姓名, + * 对应 wms_pack_task.operator_text 多人姓名逗号拼接快照列)支持 {operator,value} 标准结构, + * value 支持字符串或字符串数组(多值取并集):contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义)、 + * eq/in 精确(单值等值、多值 Op.in)、ne 不等于(取首值)、notlike 排除(多值逐个排除)。 * @param {Object} Op Sequelize Op 对象 * @param {number} warehouseId 仓库ID * @return {Promise} Sequelize where 条件对象 @@ -189,6 +192,57 @@ class OrderPackingService extends Service { } } + // 打包员(作业人员)筛选:wms_pack_task.operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。 + // 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集): + // - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义); + // - operator=eq / in:精确匹配(单值等值,多值 Op.in); + // - operator=ne:不等于(取首值); + // - operator=notlike:NOT LIKE '%值%'(多值时逐个排除)。 + // 本函数同时被 list 与 exportPackTask 复用,因此导出 Excel 会自动获得同一筛选语义。 + if (where.operator_text) { + // 空值识别:仅当条件是对象且 value 为 null/undefined 时视为空(忽略该条件、不过滤), + // 不得回退到条件对象本身,否则会被 String 化为 '[object Object]' 产生恒空过滤。 + const operatorTextCondition = where.operator_text; + const isConditionObject = operatorTextCondition + && typeof operatorTextCondition === 'object' + && !Array.isArray(operatorTextCondition); + const operatorTextRawValue = isConditionObject ? operatorTextCondition.value : operatorTextCondition; + const operatorTextOperator = isConditionObject + ? String(operatorTextCondition.operator || '').trim().toLowerCase() + : ''; + const operatorTextList = (Array.isArray(operatorTextRawValue) ? operatorTextRawValue : [ operatorTextRawValue ]) + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + + if (operatorTextList.length > 0) { + if (operatorTextOperator === 'eq' || operatorTextOperator === 'in') { + queryWhere.operator_text = operatorTextList.length === 1 + ? operatorTextList[0] + : { [Op.in]: operatorTextList }; + } else if (operatorTextOperator === 'ne') { + queryWhere.operator_text = { [Op.ne]: operatorTextList[0] }; + } else if (operatorTextOperator === 'notlike') { + if (operatorTextList.length === 1) { + queryWhere.operator_text = { [Op.notLike]: `%${escapeLikeWildcards(operatorTextList[0])}%` }; + } else { + const notLikeConditions = operatorTextList.map( + item => ({ operator_text: { [Op.notLike]: `%${escapeLikeWildcards(item)}%` } }) + ); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), ...notLikeConditions ]; + } + } else if (operatorTextList.length === 1) { + queryWhere.operator_text = { [Op.like]: `%${escapeLikeWildcards(operatorTextList[0])}%` }; + } else { + const likeConditions = operatorTextList.map( + item => ({ operator_text: { [Op.like]: `%${escapeLikeWildcards(item)}%` } }) + ); + queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), + { [Op.or]: likeConditions }, + ]; + } + } + } + // 订单ID精确匹配 if (where.order_id !== undefined && where.order_id !== null) { const orderIdValue = where.order_id?.value ?? where.order_id; @@ -442,6 +496,7 @@ class OrderPackingService extends Service { * @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤)。支持 {operator,value} 标准结构,value 支持字符串或数组: * operator=contains/like 时按 LIKE '%单号%' 模糊匹配(可命中分段单号);缺省/eq 时先剥离一单多件分段后缀、主体单号等值匹配 + 主体前缀匹配 * @param {Object} [where.wave_no] 波次号。支持 {operator,value} 标准结构,value 支持字符串或数组:eq/in 精确、ne 不等、contains/like 与缺省为模糊匹配 + * @param {Object} [where.operator_text] 打包员/作业人员姓名(wms_pack_task.operator_text 快照列,多人姓名逗号拼接)。支持 {operator,value} 标准结构,value 支持字符串或数组:contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除) * @param {Object} [where.order_id] 订单ID(精确匹配) * @param {Object} [where.workbench_id] 工作台ID(精确匹配) * @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中) diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 695cc4b..4523ff5 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -2804,6 +2804,9 @@ class ReturnUnpackService extends Service { * 根据标准化 where 条件构建主表 Sequelize 查询条件。 * * @param {Object} where 标准化 where 条件对象。 + * 文本字段(unpack_no / waybill_code / unpacker_name)支持 {operator,value} 标准结构: + * operator=like 时按 LIKE '%值%' 模糊匹配(value 为数组时多值取并集)、eq/in 精确、ne/notin 取反、between 范围等; + * 其中 unpacker_name 为拆包人员工号名称快照列(wms_return_unpack.unpacker_name)。 * @param {Object} Op Sequelize Op 对象。 * @return {Object} Sequelize where 条件。 */ @@ -2853,12 +2856,28 @@ class ReturnUnpackService extends Service { } } - // 文本字段(支持模糊) - const textFields = [ 'unpack_no', 'waybill_code' ]; + // 文本字段(支持模糊;unpacker_name 为拆包人员工号名称快照列) + const textFields = [ 'unpack_no', 'waybill_code', 'unpacker_name' ]; for (const field of textFields) { - if (where[field] !== undefined && where[field] !== null) { - queryWhere[field] = this._resolveConditionValue(where[field], Op); + const condition = where[field]; + if (condition === undefined || condition === null) { + continue; } + // 空值条件跳过:条件对象取 condition.value,为 null/undefined/纯空白字符串/空数组时不生成该字段条件, + // 避免生成 IS NULL / IN () 等恒空条件(如 unpacker_name 列 NOT NULL,IS NULL 会清空整个列表)。 + // 例外:operator=like 的空数组由 _resolveConditionValue 退化为 '%%'(全匹配、不过滤,既有测试锁定该口径)。 + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + const conditionValue = condition.value; + const conditionOperator = String(condition.operator || '').trim().toLowerCase(); + const isEmptyValue = conditionValue === null + || conditionValue === undefined + || (typeof conditionValue === 'string' && conditionValue.trim() === '') + || (Array.isArray(conditionValue) && conditionValue.length === 0 && conditionOperator !== 'like'); + if (isEmptyValue) { + continue; + } + } + queryWhere[field] = this._resolveConditionValue(condition, Op); } return queryWhere; @@ -2930,6 +2949,8 @@ class ReturnUnpackService extends Service { /** * 解析标准化条件值为 Sequelize 可用的条件对象。 + * like 分支:value 为标量时保持 LIKE '%值%' 行为不变;value 为数组时按元素做并集模糊 + * (多值 → { [Op.or]: [{ [Op.like]: '%值1%' }, ...] }),数组经 trim/去空归一后为空则退化为 '%%'(全匹配、不过滤)。 * * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。 * @param {Object} Op Sequelize Op 对象。 @@ -2953,8 +2974,21 @@ class ReturnUnpackService extends Service { return { [Op.in]: Array.isArray(value) ? value : [ value ] }; case 'notin': return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; - case 'like': + case 'like': { + if (Array.isArray(value)) { + const likeList = value + .map(item => (item === undefined || item === null ? '' : String(item).trim())) + .filter(Boolean); + if (likeList.length === 0) { + return { [Op.like]: '%%' }; + } + if (likeList.length === 1) { + return { [Op.like]: `%${likeList[0]}%` }; + } + return { [Op.or]: likeList.map(item => ({ [Op.like]: `%${item}%` })) }; + } return { [Op.like]: `%${value}%` }; + } case 'gt': return { [Op.gt]: value }; case 'gte': diff --git a/methods/changes/system.json b/methods/changes/system.json index d3d3ad1..101d1bd 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,26 @@ [ + { + "version": "2026.09.26-order-packing-returnUnpack-where-person-filter", + "date": "2026-09-26", + "type": "updated", + "summary": "接口入参新增:order.packing.list 新增 where.operator_text(打包员/作业人员筛选,wms_pack_task.operator_text 多人姓名逗号拼接快照,支持 {operator,value,type} 标准结构,value 支持字符串或数组多值取并集;contains/like 与缺省为 LIKE 模糊(通配符已转义)、eq/in 精确、ne 不等于、notlike 逐值排除、空值忽略);returnUnpack.list 新增 where.unpacker_name(拆包人筛选,wms_return_unpack.unpacker_name 工号名称快照,like 支持数组多值并集,兼支持 eq/ne/in/notin/between)。同一 _buildListWhere 被复用,order.packing.export 与 returnUnpack.export 的 where 同步获得同一筛选语义(其 where 字段清单已补 operator_text / unpacker_name)。", + "methods": [ + "order.packing.list", + "order.packing.export", + "returnUnpack.list", + "returnUnpack.export" + ], + "notes": [ + "变更类型:updated(接口入参新增 where 字段,不新增/删除 method、不改变响应结构与错误码)。", + "代码依据:app/service/systems/order_packing.js#_buildListWhere(operator_text 分支,同时被 list 与 exportPackTask 复用,L525/L653);app/service/systems/return_unpack.js#_buildListWhere(textFields 新增 unpacker_name,同时被 list 与 exportUnpack 复用,L937/L1149)与 #_resolveConditionValue(like 支持数组多值并集)。目标列:wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 小吴哥,阿猫;写入见 app/service/systems/workbench.js);wms_return_unpack.unpacker_name(STRING(50) NOT NULL,拆包人员工号名称快照 employees_name/real_name,app/model/return_unpack.js)。", + "operator_text 取值口径(以代码为准):支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集);operator=contains/like 与缺省(不传 operator)→ LIKE %值%(%/_ 通配符已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → NOT LIKE %值%(多值逐个 AND 排除);值为 空串/null/空数组(trim/去空归一后为空)时忽略该条件(不过滤)。", + "unpacker_name 取值口径(以代码为准):{operator:\"like\",value} 或直接值 → LIKE %值%;value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为 %% 全匹配、不过滤);同时兼容 _resolveConditionValue 既有操作符 eq/ne/in/notin/between/gt/gte/lt/lte。", + "文档变更范围:methods/system.json 更新 order.packing.list(where.children 新增 operator_text)、order.packing.export(where description 字段清单补 operator_text)、returnUnpack.list(params 新增 where.unpacker_name)、returnUnpack.export(where description 字段清单补 unpacker_name)共 4 条;分组条数与响应结构不变;根版本 0.3.190 → 0.3.191、updatedAt 2026-09-25 → 2026-09-26;methods/changes/system.json 新增本条(插入数组首位)。", + "前端传参示例:order.packing.list / export 传 {\"where\":{\"operator_text\":{\"value\":\"小吴哥\",\"operator\":\"like\",\"type\":\"text\"}}};returnUnpack.list / export 传 {\"where\":{\"unpacker_name\":{\"operator\":\"like\",\"value\":\"阿猫\"}}}。", + "维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta,导出脚本 script/method-doc-export.cjs)。本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库(遵循「只修改文档」红线)。后续需由维护者决定是否同步入库(method-doc-update 或全量 method-doc-import 后重新导出),否则下次执行 method-doc-export.cjs 会用库表重建 system.json 而丢失本次文件改动。", + "发布顺序:纯文档变更,无迁移、无代码改动(代码已实现并通过 ESLint),前端无需适配。" + ] + }, { "version": "2026.09.25-index-upload-client-error-log", "date": "2026-09-25", diff --git a/methods/system.json b/methods/system.json index 1f4d18b..1ea7d20 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.190", - "updatedAt": "2026-09-25", + "version": "0.3.191", + "updatedAt": "2026-09-26", "headers": [ { "name": "platform", @@ -7892,6 +7892,12 @@ "required": false, "description": "工作台ID(精确匹配)" }, + { + "name": "operator_text", + "type": "string", + "required": false, + "description": "打包员(作业人员)筛选:目标列 wms_pack_task.operator_text(TEXT,多人姓名逗号拼接快照,如 '小吴哥,阿猫')。支持 {operator,value,type} 标准结构,value 支持字符串或字符串数组(多值取并集):operator=contains/like 与缺省(不传 operator)→ 模糊匹配 LIKE '%值%'(通配符 %/_ 已转义);operator=eq/in → 精确匹配(单值等值、多值 IN);operator=ne → 不等于(多值取首值);operator=notlike → 不包含 NOT LIKE '%值%'(多值逐个 AND 排除);值为 ''/null/空数组时忽略该条件(不过滤)" + }, { "name": "quickWhere", "type": "string", @@ -7971,7 +7977,7 @@ "type": "object", "required": false, "source": "body", - "description": "查询条件,语义与 order.packing.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 status/pack_mode/waybill_code/wave_no/order_id/workbench_id/quickWhere/has_video/video_enable/start_time/end_time/create_time 等);禁止传入 warehouse_id/warehouseId(服务端注入)" + "description": "查询条件,语义与 order.packing.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 status/pack_mode/waybill_code/wave_no/order_id/workbench_id/operator_text/quickWhere/has_video/video_enable/start_time/end_time/create_time 等);禁止传入 warehouse_id/warehouseId(服务端注入)" }, { "name": "sort", @@ -45066,6 +45072,13 @@ "source": "body.where", "description": "拆包人员工号ID(等值)" }, + { + "name": "where.unpacker_name", + "type": "string", + "required": false, + "source": "body.where", + "description": "拆包人筛选:目标列 wms_return_unpack.unpacker_name(STRING(50),拆包人员工号名称快照)。传 {operator:'like',value} 或直接值 → 模糊 LIKE '%值%';value 为数组时多值 LIKE 取并集(trim/去空归一后为空退化为全匹配、不过滤);也支持 eq/ne/in/notin/between 等既有操作符" + }, { "name": "where.return_received_id", "type": "number", @@ -45358,7 +45371,7 @@ "type": "object", "required": false, "source": "body", - "description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态" + "description": "查询条件,语义与 returnUnpack.list 的 where 一致(支持 {operator,value,type} 标准结构或直接值;字段含 unpack_no/waybill_code/unpacker_name 模糊、unpack_date/start_time/end_time/created_at/updated_at 范围、status/detail_status/store_id/order_express_id/order_id/unpacker_id/return_received_id 等值、has_video/video_enable 等);禁止传入 warehouse_id/warehouseId(服务端注入);不传 status 时不过滤状态" }, { "name": "sort", diff --git a/test/app/service/systems/order_packing.list.operatorText.test.js b/test/app/service/systems/order_packing.list.operatorText.test.js new file mode 100644 index 0000000..2c2852a --- /dev/null +++ b/test/app/service/systems/order_packing.list.operatorText.test.js @@ -0,0 +1,445 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { Op } = Sequelize; +const OrderPackingService = require('../../../../app/service/systems/order_packing'); +const { matchesWhere } = require('../../../support/where_matcher'); + +const TEST_WAREHOUSE_ID = 100000; + +/** + * 打包员筛选 fixture:operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。 + * 额外包含 % / _ 字面量行,用于校验通配符转义。 + * @param {Array} rows 行定义({ order_id, operator_text, wave_no?, warehouse_id? })。 + * @return {Array} 打包任务行。 + */ +function buildOperatorTextRows(rows) { + return rows.map((item, index) => ({ + id: index + 1, + order_id: item.order_id, + warehouse_id: item.warehouse_id === undefined ? TEST_WAREHOUSE_ID : item.warehouse_id, + wave_id: item.wave_id || 0, + wave_no: item.wave_no || '', + pack_mode: item.pack_mode || 1, + status: 1, + operator_text: item.operator_text === undefined ? '' : item.operator_text, + start_time: null, + end_time: null, + create_time: null, + update_time: null, + deleted_at: null, + workbench: null, + videos: [], + expresses: [], + })); +} + +/** + * 创建 order.packing.list 服务测试环境(复用 waybill 测试文件的 harness 结构)。 + * mock 模型通过 matchesWhere 按真实 where 语义过滤 fixture 行。 + * @param {Object} [options={}] 测试配置。 + * @return {{service: OrderPackingService, calls: Object}} 测试上下文。 + */ +function createOperatorTextHarness(options = {}) { + const packTaskRows = buildOperatorTextRows(options.packTaskRows || []); + const expressRows = Array.isArray(options.expressRows) ? options.expressRows.map(item => ({ ...item })) : []; + const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) + ? options.orderDeliveryRows.map(item => ({ ...item })) + : []; + const waveBatchRows = Array.isArray(options.waveBatchRows) ? options.waveBatchRows.map(item => ({ ...item })) : []; + + const calls = { + expressFindAllWheres: [], + packTaskFindAndCountAllWhere: null, + }; + + const ctx = { + app: { + Sequelize, + config: {}, + formatDate(value) { + return value === null || value === undefined ? null : String(value); + }, + }, + user: { store_id: TEST_WAREHOUSE_ID }, + logger: { info() {}, warn() {}, error() {} }, + model: { + OrderExpress: { + async findAll(query = {}) { + calls.expressFindAllWheres.push(query.where || null); + return expressRows.filter(item => matchesWhere(item, query.where || {})); + }, + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findAll(query = {}) { + return orderDeliveryRows.filter(item => matchesWhere(item, query.where || {})); + }, + }; + }, + async getDispatchModel() { + return { + async findAll(query = {}) { + return orderDeliveryRows.filter(item => matchesWhere(item, query.where || {})); + }, + }; + }, + }, + WaveBatch: { + async findAll(query = {}) { + return waveBatchRows.filter(item => matchesWhere(item, query.where || {})); + }, + }, + PrintComputer: { + async findOne() { + return null; + }, + }, + Workbench: {}, + PackTaskVideo: {}, + Camera: {}, + PackTask: { + async count(query = {}) { + return packTaskRows.filter(item => matchesWhere(item, query.where || {})).length; + }, + async findAll(query = {}) { + calls.packTaskFindAndCountAllWhere = query.where || null; + const filtered = packTaskRows.filter(item => matchesWhere(item, query.where || {})); + const pageSize = Number(query.limit) || filtered.length; + const offset = Number(query.offset) || 0; + return filtered.slice(offset, offset + pageSize).map(row => ({ + get() { + return { ...row }; + }, + })); + }, + }, + }, + }; + + return { + service: new OrderPackingService(ctx), + calls, + }; +} + +/** + * 从结果中提取 order_id 列表(升序)。 + * @param {Object} result 服务返回结果。 + * @return {Array} order_id 列表。 + */ +function resultOrderIds(result) { + return (result && result.data && result.data.list ? result.data.list : []) + .map(item => Number(item.order_id)) + .sort((a, b) => a - b); +} + +const OPERATOR_TEXT_ROWS = [ + { order_id: 201, operator_text: '小吴哥,阿猫' }, + { order_id: 202, operator_text: '阿猫,小张' }, + { order_id: 203, operator_text: '李四' }, + { order_id: 204, operator_text: '100%合格' }, + { order_id: 205, operator_text: '1000合格' }, + { order_id: 206, operator_text: '王五_临时' }, + { order_id: 207, operator_text: '王五X临时' }, +]; + +describe('test/app/service/systems/order_packing.list.operatorText.test.js', () => { + describe('order.packing.list where.operator_text 打包员筛选', () => { + it('单值 like(type=text)应命中 operator_text 逗号拼接快照中的任一姓名', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'like', value: '小吴哥', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual( + calls.packTaskFindAndCountAllWhere.operator_text, + { [Op.like]: '%小吴哥%' }, + '应生成 operator_text LIKE %小吴哥%' + ); + assert.deepEqual(resultOrderIds(result), [ 201 ], '仅含小吴哥的行命中'); + assert.equal(result.data.pagination.total, 1); + }); + + it('多值数组 like 应取并集(Op.or 经 Op.and 承载,不占用顶层 Op.or)', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'like', value: [ '小吴哥', '李四' ], type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + const where = calls.packTaskFindAndCountAllWhere; + assert.equal(where.operator_text, undefined, '多值 like 不得生成顶层 operator_text 键'); + const andConditions = where[Op.and]; + assert.ok(Array.isArray(andConditions) && andConditions.length === 1, '应追加一条 Op.and 条件'); + assert.deepEqual( + andConditions[0][Op.or], + [ + { operator_text: { [Op.like]: '%小吴哥%' } }, + { operator_text: { [Op.like]: '%李四%' } }, + ], + 'Op.or 应包含两个 operator_text LIKE 条件' + ); + assert.deepEqual(resultOrderIds(result), [ 201, 203 ], '命中任一姓名的行都应返回(并集)'); + assert.equal(result.data.pagination.total, 2); + }); + + it('eq 单值应为等值匹配(快照列整体相等,而非子串)', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'eq', value: '小吴哥,阿猫', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.equal(calls.packTaskFindAndCountAllWhere.operator_text, '小吴哥,阿猫'); + assert.deepEqual(resultOrderIds(result), [ 201 ], '仅快照整体相等的行命中'); + }); + + it('eq 多值应生成 Op.in', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'eq', value: [ '小吴哥,阿猫', '李四' ], type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual( + calls.packTaskFindAndCountAllWhere.operator_text, + { [Op.in]: [ '小吴哥,阿猫', '李四' ] }, + '多值 eq 应生成 Op.in' + ); + assert.deepEqual(resultOrderIds(result), [ 201, 203 ]); + }); + + it('ne 应排除命中的行(取首值)', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'ne', value: '小吴哥,阿猫', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual(calls.packTaskFindAndCountAllWhere.operator_text, { [Op.ne]: '小吴哥,阿猫' }); + assert.deepEqual(resultOrderIds(result), [ 202, 203, 204, 205, 206, 207 ], '小吴哥,阿猫 行应被排除'); + }); + + it('notlike 多值应逐个排除(含任一关键词的行都不返回)', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { operator: 'notlike', value: [ '小吴哥', '李四' ], type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + const where = calls.packTaskFindAndCountAllWhere; + assert.equal(where.operator_text, undefined, '多值 notlike 不得生成顶层 operator_text 键'); + assert.deepEqual( + where[Op.and], + [ + { operator_text: { [Op.notLike]: '%小吴哥%' } }, + { operator_text: { [Op.notLike]: '%李四%' } }, + ], + '应生成两个 NOT LIKE 条件' + ); + assert.deepEqual(resultOrderIds(result), [ 202, 204, 205, 206, 207 ], '含任一关键词的行都应被排除'); + }); + + it('空串不得产生 operator_text 条件(不过滤任何数据)', async () => { + for (const emptyValue of [{ operator: 'eq', value: '' }, { operator: 'like', value: '' }]) { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: emptyValue }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.equal( + Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'), + false, + `空串形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件` + ); + assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回'); + } + }); + + it('空数组不得产生 operator_text 条件(不过滤任何数据)', async () => { + for (const emptyValue of [{ operator: 'in', value: [] }, { operator: 'like', value: [] }]) { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: emptyValue }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.equal( + Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'), + false, + `空数组形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件` + ); + assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回'); + } + }); + + it('value=null 不得产生 operator_text 条件(当前实现缺陷:会生成非法条件过滤全部数据)', async () => { + // 复现:normalizeWhereParams 会把 null 归一为 { operator: 'eq', value: null }, + // _buildListWhere 的 `value ?? where.operator_text` 将整个条件对象回退并 String 化为 '[object Object]', + // 导致生成 operator_text = '[object Object]'(eq)或 LIKE '%[object Object]%'(like),过滤掉全部数据。 + for (const emptyValue of [{ operator: 'eq', value: null }, { operator: 'like', value: null }]) { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: emptyValue }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.equal( + Object.prototype.hasOwnProperty.call(calls.packTaskFindAndCountAllWhere, 'operator_text'), + false, + `null 形态 ${JSON.stringify(emptyValue)} 不得生成 operator_text 条件(当前实现生成了 ${JSON.stringify(calls.packTaskFindAndCountAllWhere.operator_text)})` + ); + assert.deepEqual(resultOrderIds(result), [ 201, 202, 203, 204, 205, 206, 207 ], '所有行都应返回'); + } + }); + + it('通配符转义:% / _ 不得扩大匹配范围', async () => { + const percentHarness = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + const percentResult = await percentHarness.service.list( + { operator_text: { operator: 'like', value: '100%', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual( + percentHarness.calls.packTaskFindAndCountAllWhere.operator_text, + { [Op.like]: '%100\\%%' }, + '% 应被转义为字面量' + ); + assert.deepEqual( + resultOrderIds(percentResult), + [ 204 ], + '搜 100% 仅命中含字面量 100% 的行,不得命中 1000 合格' + ); + + const underscoreHarness = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + const underscoreResult = await underscoreHarness.service.list( + { operator_text: { operator: 'like', value: '王五_临时', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual( + underscoreHarness.calls.packTaskFindAndCountAllWhere.operator_text, + { [Op.like]: '%王五\\_临时%' }, + '_ 应被转义为字面量' + ); + assert.deepEqual( + resultOrderIds(underscoreResult), + [ 206 ], + '搜 王五_临时 仅命中含字面量下划线的行,不得命中 王五X临时' + ); + }); + + it('与 quickWhere 共存时顶层 Op.or 不被覆盖(多值打包员走 Op.and)', async () => { + const { service, calls } = createOperatorTextHarness({ + packTaskRows: [ + { order_id: 301, operator_text: '小吴哥,阿猫', wave_no: 'W7-A1' }, + { order_id: 302, operator_text: '李四', wave_no: 'W7-A2' }, + { order_id: 303, operator_text: '小吴哥,王五', wave_no: 'B9-X1' }, + ], + }); + + const result = await service.list( + { + operator_text: { operator: 'like', value: [ '小吴哥', '李四' ], type: 'text' }, + quickWhere: 'W7', + }, + { page: 1, pageSize: 20 }, + {} + ); + + const where = calls.packTaskFindAndCountAllWhere; + assert.ok(Array.isArray(where[Op.or]) && where[Op.or].length === 1, '顶层 Op.or 应仅承载 quickWhere 条件'); + assert.deepEqual(where[Op.or], [{ wave_no: { [Op.like]: '%W7%' } }], 'quickWhere 的 Op.or 不得被打包员条件覆盖'); + assert.ok(Array.isArray(where[Op.and]), '打包员多值条件应走 Op.and'); + assert.deepEqual( + where[Op.and][0][Op.or], + [ + { operator_text: { [Op.like]: '%小吴哥%' } }, + { operator_text: { [Op.like]: '%李四%' } }, + ], + '打包员并集条件嵌套在 Op.and 内' + ); + assert.deepEqual(resultOrderIds(result), [ 301, 302 ], '波次 W7 且打包员为 小吴哥/李四 的行命中'); + }); + + it('warehouse_id 隔离仍生效(其他仓库的行不可见)', async () => { + const { service, calls } = createOperatorTextHarness({ + packTaskRows: [ + { order_id: 401, operator_text: '小吴哥', warehouse_id: TEST_WAREHOUSE_ID }, + { order_id: 402, operator_text: '小吴哥', warehouse_id: 999999 }, + ], + }); + + const result = await service.list( + { operator_text: { operator: 'like', value: '小吴哥', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.equal(calls.packTaskFindAndCountAllWhere.warehouse_id, TEST_WAREHOUSE_ID); + assert.deepEqual(resultOrderIds(result), [ 401 ], '仅测试仓库内的行返回'); + }); + + it('打包员条件与 wave_no 条件可共存(不互相覆盖)', async () => { + const { service, calls } = createOperatorTextHarness({ + packTaskRows: [ + { order_id: 501, operator_text: '小吴哥', wave_no: 'W8-01' }, + { order_id: 502, operator_text: '李四', wave_no: 'W8-01' }, + { order_id: 503, operator_text: '小吴哥', wave_no: 'W8-02' }, + ], + }); + + const result = await service.list( + { + operator_text: { operator: 'like', value: '小吴哥', type: 'text' }, + wave_no: { operator: 'eq', value: 'W8-01' }, + }, + { page: 1, pageSize: 20 }, + {} + ); + + const where = calls.packTaskFindAndCountAllWhere; + assert.equal(where.wave_no, 'W8-01'); + assert.deepEqual(where.operator_text, { [Op.like]: '%小吴哥%' }); + assert.deepEqual(resultOrderIds(result), [ 501 ], '两个条件应同时生效'); + }); + + it('缺省 operator(未指定)应保持历史模糊行为', async () => { + const { service, calls } = createOperatorTextHarness({ packTaskRows: OPERATOR_TEXT_ROWS }); + + const result = await service.list( + { operator_text: { value: '小吴哥', type: 'text' } }, + { page: 1, pageSize: 20 }, + {} + ); + + assert.deepEqual(calls.packTaskFindAndCountAllWhere.operator_text, { [Op.like]: '%小吴哥%' }); + assert.deepEqual(resultOrderIds(result), [ 201 ]); + }); + }); +}); diff --git a/test/app/service/systems/return_unpack.list.unpackerName.test.js b/test/app/service/systems/return_unpack.list.unpackerName.test.js new file mode 100644 index 0000000..0a23ade --- /dev/null +++ b/test/app/service/systems/return_unpack.list.unpackerName.test.js @@ -0,0 +1,222 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { Op } = Sequelize; +const ReturnUnpackService = require('../../../../app/service/systems/return_unpack'); +const { matchesWhere } = require('../../../support/where_matcher'); + +/** + * returnUnpack.list where.unpacker_name(拆包人快照列)筛选单元测试。 + * + * 背景:_buildListWhere 将 unpacker_name 加入 textFields;_resolveConditionValue 的 like 分支 + * 新增数组支持(多值 → { [Op.or]: [ { [Op.like]: '%值%' }, ... ] }),标量行为不变。 + * 本文件 mock 的 count/findAll 通过 matchesWhere 按真实 where 语义过滤 fixture 行, + * 同时断言条件真实透传到 ReturnUnpack.count({ where }) 与 ReturnUnpack.findAll({ where })。 + */ + +const WAREHOUSE_ID = 100000; + +/** + * 拆包单 fixture:unpacker_name 覆盖等值/拼接快照两种形态,unpack_no/waybill_code 用于回归断言。 + * @return {Array} 拆包单行。 + */ +function createRows() { + const defs = [ + { id: 1, unpacker_name: '阿猫', unpack_no: 'RP20260900001', waybill_code: 'SF00001' }, + { id: 2, unpacker_name: '阿猫,小李', unpack_no: 'RP20260900002', waybill_code: 'SF00002' }, + { id: 3, unpacker_name: '张三', unpack_no: 'RP20260900003', waybill_code: 'SF00003' }, + { id: 4, unpacker_name: '李四', unpack_no: 'RP20260910001', waybill_code: 'YT00001' }, + ]; + return defs.map(item => ({ + ...item, + warehouse_id: WAREHOUSE_ID, + store_id: 1000000, + order_express_id: null, + unpacker_id: item.id, + camera_ids: '[1,2]', + total_items: 1, + total_quantity: 2, + unpack_date: '2026-09-10', + start_time: '2026-09-10 09:00:00', + end_time: '2026-09-10 09:05:00', + created_at: '2026-09-10 09:06:00', + updated_at: '2026-09-10 09:06:00', + videos: [], + })); +} + +/** + * 创建 returnUnpack.list 服务测试环境。 + * count 不带 include(对齐既有测试口径);count/findAll 均按真实 where 语义过滤。 + * @return {{service: ReturnUnpackService, captured: Object, allRows: Array}} 测试上下文。 + */ +function createHarness() { + const allRows = createRows(); + const captured = { + countCalls: [], + findAllCalls: [], + }; + + const ctx = { + app: { + Sequelize, + formatDate(value, fmt) { + if (value instanceof Date) { + const iso = value.toISOString(); + return fmt === 'YYYY-MM-DD' ? iso.slice(0, 10) : iso.slice(0, 19).replace('T', ' '); + } + return value === null || value === undefined ? '' : String(value); + }, + }, + logger: { + warn() {}, + info() {}, + error() {}, + }, + model: { + ReturnUnpack: { + async count(opts = {}) { + captured.countCalls.push(opts); + return allRows.filter(item => matchesWhere(item, opts.where || {})).length; + }, + async findAll(opts = {}) { + captured.findAllCalls.push(opts); + const offset = Number(opts.offset || 0); + const limit = Number(opts.limit || allRows.length); + return allRows + .filter(item => matchesWhere(item, opts.where || {})) + .slice(offset, offset + limit) + .map(row => ({ ...row })); + }, + }, + PrintComputer: { + async findOne() { + return { id: 9 }; + }, + }, + }, + }; + + const service = new ReturnUnpackService(ctx); + return { service, captured, allRows }; +} + +/** + * 从结果中提取 id 列表(升序)。 + * @param {Object} result 服务返回结果。 + * @return {Array} id 列表。 + */ +function resultIds(result) { + return (result && result.list ? result.list : []).map(item => Number(item.id)).sort((a, b) => a - b); +} + +describe('test/app/service/systems/return_unpack.list.unpackerName.test.js', () => { + describe('returnUnpack.list where.unpacker_name 拆包人筛选', () => { + it('标量 like 应生成 { [Op.like]: "%阿猫%" } 且实际过滤命中', async () => { + const { service, captured } = createHarness(); + + const result = await service.list( + { warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: '阿猫' } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual( + captured.countCalls[0].where.unpacker_name, + { [Op.like]: '%阿猫%' }, + 'unpacker_name 应生成 LIKE %阿猫%' + ); + // 条件真实透传到 count 与 findAll,且 count 不带 include(保持既有口径) + assert.deepEqual(captured.findAllCalls[0].where, captured.countCalls[0].where); + assert.equal( + Object.prototype.hasOwnProperty.call(captured.countCalls[0], 'include'), + false, + 'count 调用不得携带 include' + ); + assert.deepEqual(resultIds(result), [ 1, 2 ], '含阿猫的行(含拼接快照)命中'); + assert.equal(result.pagination.total, 2); + }); + + it('数组 like 应生成 Op.or 多个 LIKE 并集', async () => { + const { service, captured } = createHarness(); + + const result = await service.list( + { warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: [ '阿猫', '张三' ] } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual( + captured.countCalls[0].where.unpacker_name, + { + [Op.or]: [ + { [Op.like]: '%阿猫%' }, + { [Op.like]: '%张三%' }, + ], + }, + '数组 like 应生成 Op.or 多个 LIKE' + ); + assert.deepEqual(captured.findAllCalls[0].where, captured.countCalls[0].where); + assert.deepEqual(resultIds(result), [ 1, 2, 3 ], '命中任一姓名的行都应返回'); + assert.equal(result.pagination.total, 3); + }); + + it('eq 应为精确等值、ne 应排除命中行', async () => { + const eqHarness = createHarness(); + const eqResult = await eqHarness.service.list( + { warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'eq', value: '阿猫' } }, + { page: 1, pageSize: 20 } + ); + + assert.equal(eqHarness.captured.countCalls[0].where.unpacker_name, '阿猫', 'eq 应直接等值'); + assert.deepEqual(resultIds(eqResult), [ 1 ], '仅快照整体相等的行命中(阿猫,小李 不命中)'); + + const neHarness = createHarness(); + const neResult = await neHarness.service.list( + { warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'ne', value: '阿猫' } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual(neHarness.captured.countCalls[0].where.unpacker_name, { [Op.ne]: '阿猫' }); + assert.deepEqual(resultIds(neResult), [ 2, 3, 4 ], '阿猫 行应被排除'); + }); + + it('空数组 like 应退化为 %%(全匹配、不过滤)', async () => { + const { service, captured } = createHarness(); + + const result = await service.list( + { warehouse_id: WAREHOUSE_ID, unpacker_name: { operator: 'like', value: [] } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual(captured.countCalls[0].where.unpacker_name, { [Op.like]: '%%' }); + assert.deepEqual(resultIds(result), [ 1, 2, 3, 4 ], '空数组不得过滤任何数据'); + assert.equal(result.pagination.total, 4); + }); + }); + + describe('returnUnpack.list 既有文本筛选回归', () => { + it('unpack_no 标量 like 保持 %值% 行为', async () => { + const { service, captured } = createHarness(); + + const result = await service.list( + { warehouse_id: WAREHOUSE_ID, unpack_no: { operator: 'like', value: 'RP2026090' } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual(captured.countCalls[0].where.unpack_no, { [Op.like]: '%RP2026090%' }); + assert.deepEqual(resultIds(result), [ 1, 2, 3 ]); + }); + + it('waybill_code 标量 like 保持 %值% 行为', async () => { + const { service, captured } = createHarness(); + + const result = await service.list( + { warehouse_id: WAREHOUSE_ID, waybill_code: { operator: 'like', value: 'SF00' } }, + { page: 1, pageSize: 20 } + ); + + assert.deepEqual(captured.countCalls[0].where.waybill_code, { [Op.like]: '%SF00%' }); + assert.deepEqual(resultIds(result), [ 1, 2, 3 ]); + }); + }); +}); diff --git a/test/support/where_matcher.js b/test/support/where_matcher.js new file mode 100644 index 0000000..9c1159f --- /dev/null +++ b/test/support/where_matcher.js @@ -0,0 +1,153 @@ +'use strict'; + +/** + * Sequelize where 条件匹配器(测试专用)。 + * 供 service 层测试的 mock 模型复用:在内存中按真实 where 语义过滤 fixture 行, + * 重点支持 Op.like(含 % _ 与反斜杠转义语义),避免只断言到「假行为」。 + */ + +const Sequelize = require('sequelize'); + +const { Op } = Sequelize; + +/** + * 宽松等值比较:先严格比较,再对数字做数值化比较(兼容字符串/数字混用)。 + * @param {*} left 左值。 + * @param {*} right 右值。 + * @return {boolean} 是否等值。 + */ +function looseEqual(left, right) { + if (left === right) return true; + if (left === null || right === null || left === undefined || right === undefined) return false; + + const leftNum = Number(left); + const rightNum = Number(right); + if (String(left).trim() !== '' && String(right).trim() !== '' + && Number.isFinite(leftNum) && Number.isFinite(rightNum)) { + return leftNum === rightNum; + } + + return String(left) === String(right); +} + +/** + * 转义正则元字符。 + * @param {string} ch 单个字符。 + * @return {string} 转义后的字符。 + */ +function escapeRegExpChar(ch) { + return ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * 将 SQL LIKE 模式转换为等价正则(支持 \ 转义 % _ \)。 + * @param {string} pattern LIKE 模式。 + * @return {RegExp} 等价正则。 + */ +function likeToRegExp(pattern) { + let body = '^'; + for (let index = 0; index < pattern.length; index++) { + const ch = pattern[index]; + if (ch === '\\') { + const next = pattern[index + 1]; + if (next !== undefined) { + body += escapeRegExpChar(next); + index++; + } else { + body += '\\\\'; + } + } else if (ch === '%') { + body += '.*'; + } else if (ch === '_') { + body += '.'; + } else { + body += escapeRegExpChar(ch); + } + } + body += '$'; + return new RegExp(body); +} + +/** + * 判断字段值是否命中 LIKE 模式。 + * @param {*} value 字段值。 + * @param {string} pattern LIKE 模式。 + * @return {boolean} 是否命中。 + */ +function matchLike(value, pattern) { + return likeToRegExp(String(pattern)).test(String(value === null || value === undefined ? '' : value)); +} + +/** + * 判断单条条件对象是否命中。 + * @param {Object} row 待匹配行。 + * @param {string} field 字段名。 + * @param {Object} condition 条件对象。 + * @return {boolean} 是否命中。 + */ +function matchConditionObject(row, field, condition) { + const symbols = Object.getOwnPropertySymbols(condition); + if (symbols.length > 0) { + return symbols.every(symbol => { + const value = condition[symbol]; + if (symbol === Op.eq) return looseEqual(row[field], value); + if (symbol === Op.ne) return !looseEqual(row[field], value); + if (symbol === Op.in) return Array.isArray(value) && value.some(item => looseEqual(row[field], item)); + if (symbol === Op.notIn) return Array.isArray(value) && !value.some(item => looseEqual(row[field], item)); + if (symbol === Op.like || symbol === Op.iLike) return matchLike(row[field], value); + if (symbol === Op.notLike) return !matchLike(row[field], value); + if (symbol === Op.gt) return Number(row[field]) > Number(value); + if (symbol === Op.gte) return Number(row[field]) >= Number(value); + if (symbol === Op.lt) return Number(row[field]) < Number(value); + if (symbol === Op.lte) return Number(row[field]) <= Number(value); + if (symbol === Op.or) return Array.isArray(value) && value.some(item => matchConditionObject(row, field, item)); + if (symbol === Op.and) return Array.isArray(value) && value.every(item => matchConditionObject(row, field, item)); + if (symbol === Op.not) return !matchConditionObject(row, field, value); + return true; + }); + } + + if (Object.keys(condition).length > 0) { + return matchesWhere(row[field], condition); + } + + return true; +} + +/** + * 判断 mock 行数据是否匹配 where 条件(支持 Op.and / Op.or / Op.not / Op.like 等)。 + * @param {Object|*} row 待匹配行。 + * @param {Object|Array|*} where Sequelize where 条件。 + * @return {boolean} 是否匹配。 + */ +function matchesWhere(row, where) { + if (where === null || where === undefined) return true; + if (typeof where !== 'object') return looseEqual(row, where); + if (Array.isArray(where)) return where.some(item => matchesWhere(row, item)); + + if (Array.isArray(where[Op.and]) && !where[Op.and].every(item => matchesWhere(row, item))) { + return false; + } + if (Array.isArray(where[Op.or]) && !where[Op.or].some(item => matchesWhere(row, item))) { + return false; + } + if (where[Op.not] !== undefined && matchesWhere(row, where[Op.not])) { + return false; + } + + return Object.entries(where).every(([ field, condition ]) => { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + return matchConditionObject(row, field, condition); + } + if (Array.isArray(condition)) { + return condition.some(item => looseEqual(row[field], item)); + } + return looseEqual(row[field], condition); + }); +} + +module.exports = { + looseEqual, + matchLike, + matchesWhere, +};