账面口径统一为 wms_storage SUM(available_quantity)(不再加 locked_quantity),避免静态盘点在仍有在途拣货时开盘产生假盘亏(PD20261027000001 商品 160240 -115)。 静态盘点(is_static=1)新增拣货完成判定 _fetchStockLockedQuantityMap:workData/workDataDetail 输出 picking_completed 与明盘 locked_quantity,report 对仍有锁定量(未完成拣货)的商品返回 400 拒绝上报。 同步更新 methods/system.json(0.3.319~0.3.321)与 changes 变更记录。ESLint 0 错误。
9419 lines
438 KiB
JavaScript
9419 lines
438 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 库存盘点模块(stock.check.*)集成测试。
|
||
*
|
||
* 测试层次:
|
||
* - systems.stockCheck(业务层):状态机、单号生成、明细快照、作业记录(wms_stock_check_record)、
|
||
* 汇总重算等核心逻辑,直连本地开发库(config.local.js,127.0.0.1:3307)验证真实写入/查询链路;
|
||
* - systemMethods.stock.check(方法包装层):仓库上下文注入、统一 success/fail 包装、
|
||
* 业务错误码 400 透传。
|
||
*
|
||
* 覆盖范围(本轮适配:detail 精简为只返回任务本身信息({ check })、明细范围行/盘点结果由
|
||
* result 返回、新增 result 返回盘点结果聚合、
|
||
* 主表移除 check_date 字段(start_time=首个明细写入时间、end_time=完成盘点时间)、
|
||
* patternCreate 移除 mode 入参):
|
||
* - create 单号全局递增(跨仓库接续)与 uk_check_no 撞号自动重取(并发兜底);
|
||
* - create 盘点方式规则:type=location 一律强制盲盘 blind(忽略前端传入的 mode),
|
||
* type=store/goods 按传入值(缺省默认明盘 open);type 缺省 location,all 已下线(400);
|
||
* - addDetail 类型分派:goods/store 按 stock_ids、location 按 locations,
|
||
* 维度互斥报 400;货主一致性校验(invalid_stock_ids);
|
||
* type=location 缺省 locations 自动生成全仓库启用库位明细(原全盘语义);库位行幂等跳过;
|
||
* - addDetail location_ids 库位ID直查(新增入参):location 类型按 wms_location_space.id
|
||
* + warehouse_id 直查校验(与 locations 同传时 location_ids 优先、locations 忽略),
|
||
* 无效 ID 计入 invalid_location_ids;幂等按 uk_check_location;商品型任务传 location_ids 报 400;
|
||
* addLocationDetail 兼容入口薄封装转调 addDetail(返回结构不变);
|
||
* - report 覆盖式上报(mode=created/updated,space_id 必传并按库位ID落库);商品行 stock_id 不一致 400,
|
||
* 库位行 stock_id 必填/本仓库校验/库位以明细为准;
|
||
* - uk_detail_stock_location(detail_id, stock_id, location_code) 唯一索引并发加固
|
||
* (历史无库位记录库中存空串 ''、recordList 接口返回 null;report 不再产生该分组);
|
||
* - recordList/recordDelete 作业记录查询与删除;
|
||
* - batchDelete 批量删除:仅作废任务删除(事务级联清空主表/明细/作业记录),
|
||
* 非作废与查不到的任务计入 skipped_ids(保持入参顺序);单值 ids 兼容、去重、
|
||
* 200 上限与 400 参数校验;方法层仓库上下文注入与 success/failure 包装;
|
||
* - detailDelete 批量删除明细(本轮升级:单值删除 → 批量删除):detailIds 单值自动转数组
|
||
* (单次上限 200)、仅 created/rejected 状态允许(否则 400)、未命中明细计入 skipped_ids
|
||
* 不报错(deleted_ids/skipped_ids 保持入参顺序)、删除后防御性清理 wms_stock_check_record
|
||
* 并重算 total_items;返回结构 { deleted_count, deleted_ids, skipped_ids, total_items };
|
||
* 400 边界(任务ID为空/任务不存在/状态不允许/请至少选择一个明细/单次最多删除 200 条明细);
|
||
* 方法层 detail_ids/detailIds/detail_id 三种入参写法兼容与 success/failure 包装;
|
||
* - list 筛选扩展:type/mode 单值或数组 in、store_id、created_at 单值 gte 与
|
||
* [from,to] between(直插 created_at 造数)、start_time/end_time 盘点时间范围
|
||
* (report/finish 后落库)、type+status 组合筛选、非法时间值静默忽略;
|
||
* where 标准结构(operator/value)经方法层 prepareWhereContext 提取(eq/in/between);
|
||
* - list 货主名称补齐:rows 每条补 store_name(合约表 wms_store_warehouse.store_remask 优先、
|
||
* wms_store.company_name 兜底、store_id 为空或查不到为空串),
|
||
* store_id 筛选 + store_name 组合返回口径校验;
|
||
* - detail 只返回任务本身信息({ check },_formatCheckRow 口径),不返回明细范围行
|
||
* 与盘点作业聚合(明细范围行/盘点结果由 result 返回、作业记录由 recordList 返回);
|
||
* 400 边界(任务ID为空/任务不存在);
|
||
* - result 返回盘点结果聚合:商品行 checked_quantity/diff_quantity/is_diff/status/location_codes/
|
||
* checkers/last_checked_at/records/locations,库位行 stocks 按商品聚合(账面来自 wms_storage)
|
||
* 与行级 checked_quantity/diff_quantity;
|
||
* - 汇总差异口径:商品行用快照、库位行用 wms_storage 实时账面;
|
||
* - workData 盘点作业数据(单接口三视图,is_goods 驱动;不返回 check,任务信息由 detail 返回):
|
||
* location 视图库位结构(任务库位范围行为列表,行内挂 goods 子列表与 has_unknown/checkers/status)、
|
||
* goods 视图商品结构(按商品汇总,同商品多库位明细合并为一行:行级账面为快照合计、
|
||
* 作业记录跨明细按库位合并、locations 带该库位明细ID 与账面快照;明盘返回
|
||
* system_quantity/checked_quantity/diff_quantity/is_diff 与 locations.quantity,盲盘不含任何数量字段)、space 视图聚合库位结构(wms_storage 所在库位
|
||
* 按拣货路径排序,明盘含库位账面/已盘数量,盲盘不含数量);无记录任务子列表为空、
|
||
* 响应为 { view, rows, total, page, pageSize }(view=解析后的视图 location/goods/space;不返回 check,任务信息由 detail 返回)、400 边界(任务ID/任务不存在/跨仓库隔离)
|
||
* 与状态限制(created/submitted/rejected/completed/cancelled 均 400,仅 approved/checking 可拉取)
|
||
* 及方法层 is_goods 透传/success 包装;
|
||
* - finish 允许部分未盘完成(未盘商品行按实盘 0 计盘亏,库位行按商品聚合计盈亏,返回 unchecked_items);
|
||
* - exportStockChecks 导出(盘点明细=作业记录口径):Sheet1「盘点单」一行一个任务、
|
||
* Sheet2「盘点明细」一行一条实际盘点记录(不导出未盘范围行),商品快照从
|
||
* wms_stock_warehouse 补齐、空库位编码输出为空、total_count=作业记录总数;
|
||
* mock COS 上传后回读 Excel 校验列名/列序/单元格值;
|
||
* 未知商品(stock_id 为空)导出商品编码=扫描条码、商品名称=名称快照。
|
||
* - 未知商品记录(stock_id 可空 + barcode/item_name,迁移 20261001100000):
|
||
* report 库位行仅传 barcode(未命中系统条码)→ stock_id=NULL + barcode + item_name 落库
|
||
* (item_name 缺省=barcode,显式传名称按快照);barcode 命中 wms_stock_barcodes 系统条码
|
||
* → 回填 stock_id 按已知商品处理(商品行命中其他商品报 400);未知商品覆盖式查重
|
||
* (同 detail+同 barcode+同库位二次上报 → mode=updated 数量更新不新增);
|
||
* result 商品行/库位行均输出行级 unknown_items [{ barcode, item_name, checked_quantity }]
|
||
* (未知商品无账面:实盘=盘盈计入行级差异,stocks 保持只含已知商品);
|
||
* finish 未知商品计入 profit_total/diff_items;
|
||
* report 未传 stock_id 且未传 barcode 沿用原报错口径;
|
||
* 已知商品原链路回归(stock_id 匹配、库位行必填、barcode/item_name 保持 NULL)。
|
||
* - 图片独立维护:FileReference(business_type=stock_check_record、business_id=记录ID)
|
||
* 挂载到 recordList 与 result.records 的 images [{ id: file_id, url }](无图片为空数组);
|
||
* recordDelete 删除记录时清理其 FileReference 图片引用;
|
||
* recordList 未知商品 item_code=条码、item_name=名称快照(已知商品维持明细快照)。
|
||
* - 操作日志(wms_operation_log,business_type=stock_check):10 个写操作成功路径
|
||
* 写入日志(直查表断言 operation_code/business_id/warehouse_id/message/operator 快照),
|
||
* batchDelete 仅 deletedIds 非空写 1 条(business_id=首个删除 id),失败路径不写日志。
|
||
* - patternList/patternCreate 盘点定式快速创建:5 个定式清单(id/name/description/type)、
|
||
* 按定式收集对象(空库位/错发/临期/静态/预警)后任务直接 submitted 落库
|
||
* (明细快照、total_items 重算、STOCK_CHECK_CREATE 日志含 pattern_id、static 定式
|
||
* 写 wms_stock_static_check_task 并排除已盘商品)、盘点方式由定式范围类型固定
|
||
* (库位类盲盘 blind、商品类明盘 open)、主表不含 check_date(start_time/end_time 承载盘点时间语义)、
|
||
* 400 边界(定式不存在/无对象/未开启预警/缺仓库)、方法层 success/failure 包装与仓库注入。
|
||
*
|
||
* 运行前提(显式开启真实库,普通测试运行自动跳过,与 interceptRealDb.chain.test.js 口径一致):
|
||
* cmd /c "set DISPATCH_FACTORY_TEST_MYSQL=1&& npx egg-bin test test/app/service/systems/stock_check.test.js"
|
||
*
|
||
* 固定测试参数(与 wms-test-agent 约定一致):
|
||
* - 测试仓库 ID:100000
|
||
* - 测试货主 ID:1000000
|
||
*
|
||
* 数据策略:按用户偏好,本测试不清理写入数据(保留以供核对写入格式),
|
||
* 用例通过唯一标题/关键字与"断言包含关系"的方式保证可重复执行。
|
||
*/
|
||
|
||
const assert = require('node:assert/strict');
|
||
const crypto = require('node:crypto');
|
||
const mm = require('egg-mock');
|
||
const ExcelJS = require('exceljs');
|
||
|
||
const REAL_DB_ENABLED = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1';
|
||
const runner = REAL_DB_ENABLED ? describe : describe.skip;
|
||
|
||
const TEST_WAREHOUSE_ID = 100000;
|
||
// 另一测试仓库(跨仓库隔离/全局递增验证口径,与 detailDelete 仓库隔离用例一致)
|
||
const OTHER_TEST_WAREHOUSE_ID = 100001;
|
||
const TEST_STORE_ID = 1000000;
|
||
// 真实测试账号(开发库 wms_account_store_employee:id=4,account_id=1 liufumingren,store_id=100000,status=1)
|
||
const TEST_CREATOR_ID = 4;
|
||
const TEST_CREATOR_NAME = '阿猫';
|
||
// 固定测试库位编码与对应 wms_location_space.id(warehouse_id=100000)
|
||
const TEST_LOCATION_CODE = 'A1715-01-01-01';
|
||
const TEST_LOCATION_ID = 26885;
|
||
// 无库存的启用库位(用于库位行账面 0 口径验证,warehouse_id=100000)
|
||
const TEST_EMPTY_LOCATION_CODE = 'E07-01-02-01';
|
||
// 有效库位过滤 SQL(与业务排除无头库位口径一致:库位未删除且所属 zone 存在未删除)
|
||
const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls '
|
||
+ 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL '
|
||
+ 'WHERE ls.deleted_at IS NULL)';
|
||
|
||
// 第二/第三有效库位(report 已改为 space_id 必传,多库位用例必须用真实库位),在 before 中初始化
|
||
let TEST_LOCATION_CODE_2 = null;
|
||
let TEST_LOCATION_ID_2 = 0;
|
||
let TEST_LOCATION_CODE_3 = null;
|
||
|
||
let titleSeq = 0;
|
||
|
||
/**
|
||
* 生成唯一标题,避免多次执行测试时互相干扰。
|
||
*
|
||
* @param {string} prefix 标题前缀。
|
||
* @return {string} 唯一标题。
|
||
*/
|
||
function uniqueTitle(prefix) {
|
||
titleSeq += 1;
|
||
return `${prefix}_${Date.now()}_${titleSeq}`;
|
||
}
|
||
|
||
/**
|
||
* 获取当前日期片段(YYYYMMDD),用于校验单号前缀。
|
||
*
|
||
* @return {string} 日期片段。
|
||
*/
|
||
function currentDatePart() {
|
||
const now = new Date();
|
||
return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
|
||
}
|
||
|
||
runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集成测试)', function() {
|
||
this.timeout(300000);
|
||
|
||
let app;
|
||
let ctx;
|
||
|
||
before(async () => {
|
||
app = mm.app({
|
||
baseDir: process.cwd(),
|
||
env: 'local',
|
||
clean: false,
|
||
cache: false,
|
||
});
|
||
await app.ready();
|
||
ctx = app.createAnonymousContext();
|
||
|
||
// 校验固定测试库位编码在当前开发库真实存在,且 location_id 与常量一致(不一致快速失败)
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_LOCATION_CODE },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
assert.ok(space, `固定测试库位编码不存在(warehouse_id=${TEST_WAREHOUSE_ID}, code=${TEST_LOCATION_CODE})`);
|
||
assert.equal(Number(space.id), TEST_LOCATION_ID, '固定测试库位 ID 与本地库实际值不一致');
|
||
|
||
// 多库位用例所需的有效库位(report 的 space_id 必传,不能再用虚构编码)
|
||
const extraLocations = (await fetchValidLocations(3))
|
||
.filter(item => item.space_code !== TEST_LOCATION_CODE && item.space_code !== TEST_EMPTY_LOCATION_CODE);
|
||
assert.ok(extraLocations.length >= 2, '测试仓库应至少存在 2 个额外有效库位(多库位用例依赖)');
|
||
TEST_LOCATION_CODE_2 = extraLocations[0].space_code;
|
||
TEST_LOCATION_ID_2 = extraLocations[0].id;
|
||
TEST_LOCATION_CODE_3 = extraLocations[1].space_code;
|
||
});
|
||
|
||
after(async () => {
|
||
await app.close();
|
||
});
|
||
|
||
afterEach(() => {
|
||
mm.restore();
|
||
});
|
||
|
||
// ------------------- 辅助函数(业务层直调) -------------------
|
||
|
||
/**
|
||
* 创建盘点任务(业务层直调,固定测试仓库)。
|
||
* 默认 type=goods(商品维度用例口径);库位维度用例显式传 type=location。
|
||
*
|
||
* @param {Object} [options] 创建参数覆盖项。
|
||
* @return {Promise<Object>} 格式化后的盘点任务行。
|
||
*/
|
||
async function createCheck(options = {}) {
|
||
return ctx.service.systems.stockCheck.create({
|
||
warehouseId: options.warehouseId !== undefined ? options.warehouseId : TEST_WAREHOUSE_ID,
|
||
title: options.title || uniqueTitle('盘点单元测试'),
|
||
type: options.type || 'goods',
|
||
mode: options.mode || 'open',
|
||
storeId: options.storeId !== undefined ? options.storeId : null,
|
||
isStatic: options.isStatic,
|
||
remark: options.remark,
|
||
creatorId: options.creatorId || TEST_CREATOR_ID,
|
||
creatorName: options.creatorName || TEST_CREATOR_NAME,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 拉取固定测试仓库下的真实库存行(用于生成盘点明细快照)。
|
||
*
|
||
* @param {number} count 行数。
|
||
* @param {Object} [options] 过滤选项。
|
||
* @param {boolean} [options.requireUnlocked=false] 仅取无锁定量商品
|
||
* (wms_storage SUM(locked_quantity)=0,静态盘点上报要求商品已完成拣货)。
|
||
* @return {Promise<Array<Object>>} 库存行。
|
||
*/
|
||
async function fetchStockRows(count = 2, options = {}) {
|
||
// 取「仅在单个启用库位有库存」的商品:商品明细按「商品 + 库位」拆行后每商品 1 行,
|
||
// 保证 total_items 与商品数一致(多库位商品拆多行、无库存库位商品不可加入盘点)
|
||
const { Op, fn, col, literal } = ctx.app.Sequelize;
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [
|
||
'stock_id',
|
||
[ fn('COUNT', fn('DISTINCT', col('space_id'))), 'spaceCount' ],
|
||
[ literal('SUM(locked_quantity)'), 'lockedQuantity' ],
|
||
],
|
||
group: [ 'stock_id' ],
|
||
raw: true,
|
||
});
|
||
const singleSpaceStockIds = storageRows
|
||
.filter(row => Number(row.spaceCount) === 1)
|
||
.filter(row => options.requireUnlocked !== true || (Number(row.lockedQuantity) || 0) === 0)
|
||
.map(row => Number(row.stock_id));
|
||
|
||
return ctx.model.StockWarehouse.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
store_id: TEST_STORE_ID,
|
||
id: { [Op.in]: singleSpaceStockIds },
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
limit: count,
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 拉取固定测试仓库下其他货主的库存行(货主隔离校验用)。
|
||
*
|
||
* @return {Promise<Object|null>} 库存行。
|
||
*/
|
||
async function fetchOtherStoreStockRow() {
|
||
const { Op } = ctx.app.Sequelize;
|
||
return ctx.model.StockWarehouse.findOne({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
store_id: { [Op.ne]: TEST_STORE_ID },
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 拉取其他仓库的库存行(跨仓库隔离校验用)。
|
||
*
|
||
* @return {Promise<Object|null>} 库存行。
|
||
*/
|
||
async function fetchOtherWarehouseStockRow() {
|
||
const { Op } = ctx.app.Sequelize;
|
||
return ctx.model.StockWarehouse.findOne({
|
||
where: { warehouse_id: { [Op.ne]: TEST_WAREHOUSE_ID } },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询库位商品账面数量(wms_storage 按 stock_id SUM(可用数量),与实现口径一致)。
|
||
*
|
||
* @param {number} spaceId 库位ID。
|
||
* @param {Array<number>} stockIds 商品库存ID列表。
|
||
* @return {Promise<Map<number, number>>} stock_id -> 账面数量。
|
||
*/
|
||
async function fetchStorageQuantity(spaceId, stockIds) {
|
||
const { Op, literal } = ctx.app.Sequelize;
|
||
const rows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
space_id: Number(spaceId),
|
||
stock_id: { [Op.in]: stockIds.map(id => Number(id)) },
|
||
},
|
||
attributes: [ 'stock_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
|
||
group: [ 'stock_id' ],
|
||
raw: true,
|
||
});
|
||
return new Map(rows.map(row => [ Number(row.stock_id), Number(row.totalQuantity) || 0 ]));
|
||
}
|
||
|
||
/**
|
||
* 查询库位下真实库存商品ID列表(用于库位行多商品上报,按 stock_id 升序)。
|
||
*
|
||
* @param {number} spaceId 库位ID。
|
||
* @param {number} [count] 行数。
|
||
* @return {Promise<Array<number>>} 商品库存ID列表。
|
||
*/
|
||
async function fetchStorageStockIds(spaceId, count = 2) {
|
||
const rows = await ctx.model.Storage.findAll({
|
||
where: { space_id: Number(spaceId) },
|
||
attributes: [ 'stock_id' ],
|
||
group: [ 'stock_id' ],
|
||
order: [[ 'stock_id', 'ASC' ]],
|
||
limit: count,
|
||
raw: true,
|
||
});
|
||
return rows.map(row => Number(row.stock_id));
|
||
}
|
||
|
||
/**
|
||
* 取固定测试仓库下「只存放在单一库位」的有效商品与库位对(保证库位-商品一一对应,
|
||
* 供 space 视图聚合/排序用例使用),并附库位编码/名称与账面数量(账面口径与实现一致:
|
||
* wms_storage 按 warehouse+space+stock+is_enabled=1 SUM(available_quantity))
|
||
* 及锁定数量(SUM(locked_quantity))。
|
||
*
|
||
* @param {number} count 对数。
|
||
* @return {Promise<Array<Object>>} [{ spaceId, stockId, spaceCode, customName, book, bookLocked }]。
|
||
*/
|
||
async function fetchSpaceStockPairs(count = 3) {
|
||
const { Op, fn, col, literal } = ctx.app.Sequelize;
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [ 'space_id', 'stock_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
// 商品 → 库位集合(筛选只存放在单一库位的商品,避免同商品多库位干扰聚合断言)
|
||
const spacesByStock = new Map();
|
||
for (const row of storageRows) {
|
||
const stockId = Number(row.stock_id);
|
||
if (!spacesByStock.has(stockId)) {
|
||
spacesByStock.set(stockId, new Set());
|
||
}
|
||
spacesByStock.get(stockId).add(Number(row.space_id));
|
||
}
|
||
const candidatesBySpace = new Map();
|
||
for (const [ stockId, spaceSet ] of spacesByStock) {
|
||
if (spaceSet.size !== 1) {
|
||
continue;
|
||
}
|
||
const spaceId = [ ...spaceSet ][0];
|
||
if (!candidatesBySpace.has(spaceId)) {
|
||
candidatesBySpace.set(spaceId, []);
|
||
}
|
||
candidatesBySpace.get(spaceId).push(stockId);
|
||
}
|
||
|
||
const pairs = [];
|
||
const sortedSpaces = [ ...candidatesBySpace.keys() ].sort((left, right) => left - right);
|
||
for (const spaceId of sortedSpaces) {
|
||
const stockId = candidatesBySpace.get(spaceId).sort((left, right) => left - right)[0];
|
||
const stock = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: stockId, warehouse_id: TEST_WAREHOUSE_ID, is_valid: 'Y' },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
if (!stock) {
|
||
continue;
|
||
}
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: { id: spaceId },
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
raw: true,
|
||
});
|
||
if (!space) {
|
||
continue;
|
||
}
|
||
const bookRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
is_enabled: 1,
|
||
},
|
||
attributes: [
|
||
[ ctx.app.Sequelize.literal('SUM(available_quantity)'), 'totalQuantity' ],
|
||
[ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ],
|
||
],
|
||
raw: true,
|
||
});
|
||
pairs.push({
|
||
spaceId,
|
||
stockId,
|
||
spaceCode: String(space.space_code || '').trim(),
|
||
customName: String(space.custom_name || '').trim(),
|
||
book: Number(bookRows[0] && bookRows[0].totalQuantity) || 0,
|
||
bookLocked: Number(bookRows[0] && bookRows[0].totalLockedQuantity) || 0,
|
||
});
|
||
if (pairs.length >= count) {
|
||
break;
|
||
}
|
||
}
|
||
assert.ok(
|
||
pairs.length >= Math.min(count, 2),
|
||
`固定测试仓库应存在至少 ${Math.min(count, 2)} 个单一库位库存商品(space 视图真实数据依赖)`
|
||
);
|
||
return pairs;
|
||
}
|
||
|
||
/**
|
||
* 按实现口径解析货主名(合约表 store_remask 优先、公司名兜底、查不到为 null),
|
||
* 供 workData 各视图 store_name 字段交叉验证。
|
||
*
|
||
* @param {number} storeId 货主ID。
|
||
* @return {Promise<string|null>} 货主名称。
|
||
*/
|
||
async function resolveStoreName(storeId) {
|
||
const normalizedId = Number(storeId);
|
||
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
|
||
return null;
|
||
}
|
||
const contract = await ctx.model.StoreWarehouse.findOne({
|
||
where: { store_id: normalizedId, warehouse_id: TEST_WAREHOUSE_ID },
|
||
attributes: [ 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
if (contract && contract.store_remask) {
|
||
return contract.store_remask;
|
||
}
|
||
const store = await ctx.model.Store.findOne({
|
||
where: { id: normalizedId },
|
||
attributes: [ 'company_name' ],
|
||
raw: true,
|
||
});
|
||
return (store && store.company_name) || null;
|
||
}
|
||
|
||
/**
|
||
* 创建一条已审核(approved)的库位维度盘点任务(固定测试库位),返回主表与库位明细行。
|
||
*
|
||
* @return {Promise<Object>} { check, detail }。
|
||
*/
|
||
async function createApprovedLocationCheck() {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
return { check, detail: details.rows[0] };
|
||
}
|
||
|
||
/**
|
||
* 业务层:添加盘点明细(商品维度)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Array<number>} stockIds 库存ID列表。
|
||
* @return {Promise<Object>} 添加结果。
|
||
*/
|
||
async function addDetail(checkId, stockIds) {
|
||
return ctx.service.systems.stockCheck.addDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
stockIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:添加盘点明细(库位维度)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Array<string>} [locations] 库位编码列表(缺省时按任务类型处理)。
|
||
* @return {Promise<Object>} 添加结果。
|
||
*/
|
||
async function addLocationDetail(checkId, locations) {
|
||
return ctx.service.systems.stockCheck.addDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
locations,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:添加盘点明细(原始参数透传,用于维度互斥等参数校验场景)。
|
||
*
|
||
* @param {Object} params 添加参数(自动注入固定测试仓库)。
|
||
* @return {Promise<Object>} 添加结果。
|
||
*/
|
||
async function addDetailRaw(params = {}) {
|
||
return ctx.service.systems.stockCheck.addDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:批量添加库位明细(兼容入口,按库位ID直查)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Array<number>} locationIds 库位ID列表。
|
||
* @return {Promise<Object>} 添加结果。
|
||
*/
|
||
async function addLocationDetailByIds(checkId, locationIds) {
|
||
return ctx.service.systems.stockCheck.addLocationDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
locationIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取一个本地库中不存在的库位ID(按当前最大 ID 递增,避免与真实数据冲突)。
|
||
*
|
||
* @return {Promise<number>} 不存在的库位ID。
|
||
*/
|
||
async function fetchMissingLocationId() {
|
||
const { fn, col } = ctx.app.Sequelize;
|
||
const maxRow = await ctx.model.LocationSpace.findOne({
|
||
attributes: [[ fn('MAX', col('id')), 'maxId' ]],
|
||
raw: true,
|
||
});
|
||
return Number(maxRow && maxRow.maxId) + 1000;
|
||
}
|
||
|
||
/**
|
||
* 业务层:提交审核。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} 提交结果。
|
||
*/
|
||
async function submitCheck(checkId) {
|
||
return ctx.service.systems.stockCheck.submit({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:取消任务。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} 取消结果。
|
||
*/
|
||
async function cancelCheck(checkId) {
|
||
return ctx.service.systems.stockCheck.cancel({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:审核任务。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {string} action approve/reject。
|
||
* @param {string} [reason] 驳回原因。
|
||
* @return {Promise<Object>} 审核结果。
|
||
*/
|
||
async function auditCheck(checkId, action, reason) {
|
||
return ctx.service.systems.stockCheck.audit({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
action,
|
||
reason,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取测试仓库内 N 个分区有效(zone 存在未删除)的库位,供多库位上报用例使用。
|
||
*
|
||
* @param {number} count 需要的库位数量。
|
||
* @return {Promise<Array<Object>>} [{ id, space_code }](按 id 升序,过滤空编码)。
|
||
*/
|
||
async function fetchValidLocations(count = 3) {
|
||
const rows = await ctx.model.LocationSpace.findAll({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID },
|
||
attributes: [ 'id', 'space_code' ],
|
||
include: [{
|
||
model: ctx.model.LocationZone,
|
||
as: 'zone',
|
||
attributes: [],
|
||
required: true,
|
||
}],
|
||
order: [[ 'id', 'ASC' ]],
|
||
limit: count + 20,
|
||
raw: true,
|
||
});
|
||
return rows
|
||
.filter(row => String(row.space_code || '').trim())
|
||
.slice(0, count)
|
||
.map(row => ({ id: Number(row.id), space_code: String(row.space_code).trim() }));
|
||
}
|
||
|
||
/**
|
||
* 解析上报应携带的 space_id(库位ID):就近取「本仓库 + 分区有效」的库位行。
|
||
* report 已改为 space_id 必传,测试通过本函数模拟调用方从取回数据中拿到的库位ID。
|
||
*
|
||
* @param {number} detailId 盘点明细ID。
|
||
* @param {string} [location] 上报库位编码。
|
||
* @return {Promise<number>} 库位ID(解析不到返回 0)。
|
||
*/
|
||
async function resolveReportSpaceId(detailId, location) {
|
||
const { Op } = ctx.app.Sequelize;
|
||
const code = location !== undefined && location !== null ? String(location).trim() : '';
|
||
const validZoneInclude = [{
|
||
model: ctx.model.LocationZone,
|
||
as: 'zone',
|
||
attributes: [],
|
||
required: true,
|
||
}];
|
||
if (code) {
|
||
const row = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: code },
|
||
attributes: [ 'id' ],
|
||
include: validZoneInclude,
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
return row ? Number(row.id) : 0;
|
||
}
|
||
const detail = await ctx.model.StockCheckDetail.findOne({
|
||
where: { id: Number(detailId), warehouse_id: { [Op.or]: [ TEST_WAREHOUSE_ID, OTHER_TEST_WAREHOUSE_ID ] } },
|
||
attributes: [ 'location_id', 'location_code', 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
if (!detail) {
|
||
return 0;
|
||
}
|
||
const candidateIds = [];
|
||
if (Number(detail.location_id) > 0) {
|
||
candidateIds.push(Number(detail.location_id));
|
||
}
|
||
const detailCode = String(detail.location_code || '').trim();
|
||
if (detailCode) {
|
||
const rows = await ctx.model.LocationSpace.findAll({
|
||
where: { warehouse_id: Number(detail.warehouse_id), space_code: detailCode },
|
||
attributes: [ 'id' ],
|
||
include: validZoneInclude,
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
for (const row of rows) {
|
||
if (!candidateIds.includes(Number(row.id))) {
|
||
candidateIds.push(Number(row.id));
|
||
}
|
||
}
|
||
}
|
||
if (candidateIds.length === 0) {
|
||
return 0;
|
||
}
|
||
const validRow = await ctx.model.LocationSpace.findOne({
|
||
where: { id: { [Op.in]: candidateIds } },
|
||
attributes: [ 'id' ],
|
||
include: validZoneInclude,
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
return validRow ? Number(validRow.id) : 0;
|
||
}
|
||
|
||
/**
|
||
* 业务层:盘点作业上报。
|
||
* space_id 必传(report 强制要求):未显式传 options.spaceId 时按上报库位编码/明细库位自动解析。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {number} detailId 明细ID。
|
||
* @param {number} quantity 实盘数量。
|
||
* @param {string} [location] 库位编码。
|
||
* @param {Object} [options] 覆盖项(spaceId/stockId/barcode/itemName/checkerId/checkerName/is_empty;
|
||
* spaceId 显式传 0/null 表示「不携带库位ID」用于 400 用例;
|
||
* 库位行必传 stockId 或 barcode(或 is_empty=true 空库位标记),itemName 为未知商品名称快照)。
|
||
* @return {Promise<Object>} 上报结果(含新增作业记录 record 与主表汇总)。
|
||
*/
|
||
async function reportCheck(checkId, detailId, quantity, location, options = {}) {
|
||
const spaceId = options.spaceId !== undefined
|
||
? options.spaceId
|
||
: await resolveReportSpaceId(detailId, location);
|
||
return ctx.service.systems.stockCheck.report({
|
||
warehouseId: options.warehouseId !== undefined ? options.warehouseId : TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
detailId,
|
||
quantity,
|
||
location,
|
||
spaceId,
|
||
stockId: options.stockId,
|
||
barcode: options.barcode,
|
||
itemName: options.itemName,
|
||
is_empty: options.is_empty,
|
||
checkerId: options.checkerId !== undefined ? options.checkerId : TEST_CREATOR_ID,
|
||
checkerName: options.checkerName !== undefined ? options.checkerName : TEST_CREATOR_NAME,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:完成盘点。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} 完成结果。
|
||
*/
|
||
async function finishCheck(checkId) {
|
||
return ctx.service.systems.stockCheck.finish({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:查询列表。
|
||
*
|
||
* @param {Object} [params] 查询参数。
|
||
* @return {Promise<Object>} 列表结果。
|
||
*/
|
||
async function listChecks(params = {}) {
|
||
return ctx.service.systems.stockCheck.list({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:查询任务详情(主表信息 + 全部明细范围行)。
|
||
* detail 接口只返回任务本身信息({ check });明细范围行改由直查明细表补齐
|
||
* (等价于原 detail.rows 的纯范围行口径),供用例获取明细 ID / 快照字段使用。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} { check, rows, total }。
|
||
*/
|
||
async function detailCheck(checkId) {
|
||
const { check } = await ctx.service.systems.stockCheck.detail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
});
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: checkId, warehouse_id: TEST_WAREHOUSE_ID },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
return { check, rows, total: rows.length };
|
||
}
|
||
|
||
/**
|
||
* 业务层:查询盘点结果聚合(范围行 + 作业记录聚合)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} { check, rows, total }。
|
||
*/
|
||
async function resultCheck(checkId) {
|
||
return ctx.service.systems.stockCheck.result({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Object} [options] 可选参数 { isGoods, keyword, onlyAbnormal, pagination }。
|
||
* @return {Promise<Object>} { view, rows, total, page, pageSize }。
|
||
*/
|
||
async function workDataCheck(checkId, options = {}) {
|
||
const extraParams = options && typeof options === 'object' ? options : {};
|
||
return ctx.service.systems.stockCheck.workData({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
...extraParams,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:拉取盘点作业数据明细(库位明细单行 / 商品钻取)。
|
||
*
|
||
* @param {number|Object} input 明细ID(数字)或 { id, stockId, detailId } 参数对象。
|
||
* @return {Promise<Object>} 库位单行或商品 { check_id, stock_id, summary, rows }。
|
||
*/
|
||
async function workDataDetailCheck(input) {
|
||
const params = input !== null && typeof input === 'object' ? input : { detailId: input };
|
||
return ctx.service.systems.stockCheck.workDataDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 读取主表最新状态。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Object>} 主表行(plain)。
|
||
*/
|
||
async function findCheckRow(checkId) {
|
||
const row = await ctx.model.StockCheck.findOne({
|
||
where: { id: Number(checkId) },
|
||
});
|
||
return row ? row.get({ plain: true }) : null;
|
||
}
|
||
|
||
/**
|
||
* 直插主表 created_at(造不同创建时间的历史任务,供 created_at 范围筛选用例使用)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Date} createdAt 目标创建时间。
|
||
* @return {Promise<Object>} 更新后的主表行(plain)。
|
||
*/
|
||
async function setCheckCreatedAt(checkId, createdAt) {
|
||
await ctx.model.StockCheck.update(
|
||
{ created_at: createdAt },
|
||
{ where: { id: Number(checkId) } }
|
||
);
|
||
return findCheckRow(checkId);
|
||
}
|
||
|
||
/**
|
||
* 查询盘点作业记录(wms_stock_check_record)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {number} [detailId] 明细ID(可选,用于限定某条明细)。
|
||
* @return {Promise<Array<Object>>} 作业记录行(plain,按 id 升序)。
|
||
*/
|
||
async function queryRecords(checkId, detailId) {
|
||
const where = { check_id: Number(checkId) };
|
||
if (detailId !== undefined) {
|
||
where.detail_id = Number(detailId);
|
||
}
|
||
return ctx.model.StockCheckRecord.findAll({
|
||
where,
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:删除作业记录(批量:单值自动转数组,未命中计入 skipped_ids 不报错)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Array<number>|number} recordIds 作业记录ID(单值或数组,单次上限 200)。
|
||
* @return {Promise<Object>} 删除结果(含重算后的汇总)。
|
||
*/
|
||
async function deleteRecord(checkId, recordIds) {
|
||
return ctx.service.systems.stockCheck.recordDelete({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
recordIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:删除盘点明细(批量:单值自动转数组,未命中计入 skipped_ids 不报错)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {Array<number>|number} detailIds 盘点明细ID(单值或数组,单次上限 200)。
|
||
* @return {Promise<Object>} { deleted_count, deleted_ids, skipped_ids, total_items }。
|
||
*/
|
||
async function deleteDetail(checkId, detailIds) {
|
||
return ctx.service.systems.stockCheck.detailDelete({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
detailIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:删除盘点明细(原始参数透传,用于参数校验场景)。
|
||
*
|
||
* @param {Object} params 删除参数(自动注入固定测试仓库)。
|
||
* @return {Promise<Object>} { deleted_count, deleted_ids, skipped_ids, total_items }。
|
||
*/
|
||
async function deleteDetailRaw(params = {}) {
|
||
return ctx.service.systems.stockCheck.detailDelete({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:查询作业记录列表。
|
||
*
|
||
* @param {Object} [params] 查询参数(id/detailId/pagination)。
|
||
* @return {Promise<Object>} { rows, total, page, pageSize }。
|
||
*/
|
||
async function listRecords(params = {}) {
|
||
return ctx.service.systems.stockCheck.recordList({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:批量删除盘点任务(固定测试仓库)。
|
||
*
|
||
* @param {Array<number>|number} ids 盘点任务ID(数组或单值)。
|
||
* @return {Promise<Object>} { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||
*/
|
||
async function batchDeleteCheck(ids) {
|
||
return ctx.service.systems.stockCheck.batchDelete({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
ids,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务层:批量删除盘点任务(原始参数透传,用于参数校验场景)。
|
||
*
|
||
* @param {Object} params 批量删除参数。
|
||
* @return {Promise<Object>} { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||
*/
|
||
async function batchDeleteRaw(params = {}) {
|
||
return ctx.service.systems.stockCheck.batchDelete(params);
|
||
}
|
||
|
||
/**
|
||
* 取一个当前库中不存在的盘点任务 ID(基于主表最大 ID 偏移,避免误删历史数据)。
|
||
*
|
||
* @return {Promise<number>} 不存在的主键 ID。
|
||
*/
|
||
async function findFreeCheckId() {
|
||
const row = await ctx.model.StockCheck.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
return (row ? Number(row.id) : 0) + 1000000;
|
||
}
|
||
|
||
/**
|
||
* 取一个当前库中不存在的盘点明细 ID(基于明细表最大 ID 偏移,避免误删历史数据)。
|
||
*
|
||
* @return {Promise<number>} 不存在的主键 ID。
|
||
*/
|
||
async function findFreeDetailId() {
|
||
const row = await ctx.model.StockCheckDetail.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
return (row ? Number(row.id) : 0) + 1000000;
|
||
}
|
||
|
||
/**
|
||
* 创建一条已作废的盘点任务(含 1 条商品明细,status=cancelled)。
|
||
*
|
||
* @return {Promise<Object>} { check, stock }。
|
||
*/
|
||
async function createCancelledCheck() {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await cancelCheck(check.id);
|
||
return { check, stock: stocks[0] };
|
||
}
|
||
|
||
/**
|
||
* 构造商品条码(wms_stock_barcodes,固定测试仓库,条码值唯一)。
|
||
*
|
||
* @param {number} stockId 商品库存ID(wms_stock_warehouse.id,需属于测试仓库)。
|
||
* @param {string} [barcode] 条码值(缺省自动生成唯一条码)。
|
||
* @return {Promise<Object>} { barcode, stockBarcode }。
|
||
*/
|
||
async function createStockBarcode(stockId, barcode) {
|
||
const barcodeValue = barcode || uniqueTitle('TEST-BARCODE');
|
||
const stockBarcode = await ctx.model.StockBarcode.create({
|
||
stock_id: Number(stockId),
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
barcode: barcodeValue,
|
||
description: '盘点未知商品测试条码',
|
||
create_time: new Date(),
|
||
});
|
||
return { barcode: barcodeValue, stockBarcode };
|
||
}
|
||
|
||
/**
|
||
* 为作业记录挂载图片(图片独立维护口径:wms_file + wms_file_reference,
|
||
* business_type=stock_check_record、business_id=记录ID)。
|
||
*
|
||
* @param {number} recordId 作业记录ID。
|
||
* @return {Promise<Object>} { file, reference }。
|
||
*/
|
||
async function createRecordImage(recordId) {
|
||
const token = uniqueTitle('img');
|
||
const file = await ctx.model.File.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
file_key: `test/stock_check/${token}.jpg`,
|
||
file_url: `https://img.test.local/${token}.jpg`,
|
||
file_name: `${token}.jpg`,
|
||
file_size: 1024,
|
||
file_type: 'stock_check_image',
|
||
mime_type: 'image/jpeg',
|
||
md5_hash: crypto.createHash('md5').update(token).digest('hex'),
|
||
sha1_hash: crypto.createHash('sha1').update(token).digest('hex'),
|
||
storage_mode: 'cos',
|
||
uploader_id: String(TEST_CREATOR_ID),
|
||
uploader_name: TEST_CREATOR_NAME,
|
||
created_at: new Date(),
|
||
});
|
||
const reference = await ctx.model.FileReference.create({
|
||
file_id: file.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
business_type: 'stock_check_record',
|
||
business_id: String(recordId),
|
||
display_order: 0,
|
||
created_by: String(TEST_CREATOR_ID),
|
||
created_at: new Date(),
|
||
});
|
||
return { file, reference };
|
||
}
|
||
|
||
// ------------------- create:创建盘点任务 -------------------
|
||
|
||
describe('create 创建盘点任务', () => {
|
||
it('生成 PD+YYYYMMDD+6位序号单号,初始状态 created', async () => {
|
||
const result = await createCheck();
|
||
|
||
assert.match(result.check_no, /^PD\d{14}$/, `单号格式应为 PD+YYYYMMDD+6位序号: ${result.check_no}`);
|
||
assert.ok(result.check_no.startsWith(`PD${currentDatePart()}`), '单号日期部分应为当前日期');
|
||
assert.equal(result.status, 'created');
|
||
assert.equal(result.detail_status, 'none_checked');
|
||
assert.equal(result.total_items, 0);
|
||
assert.equal(result.checked_items, 0);
|
||
|
||
const row = await findCheckRow(result.id);
|
||
assert.equal(row.warehouse_id, TEST_WAREHOUSE_ID, '主表应写入固定测试仓库 ID');
|
||
assert.equal(row.check_no, result.check_no);
|
||
});
|
||
|
||
it('同仓库连续创建序号递增', async () => {
|
||
const first = await createCheck();
|
||
const second = await createCheck();
|
||
|
||
const firstSeq = Number(first.check_no.slice(-6));
|
||
const secondSeq = Number(second.check_no.slice(-6));
|
||
assert.equal(secondSeq, firstSeq + 1, `序号应连续递增: ${first.check_no} -> ${second.check_no}`);
|
||
});
|
||
|
||
it('跨仓库创建序号全局递增:另一仓库单号接续本仓库序号', async () => {
|
||
const first = await createCheck();
|
||
const second = await createCheck({ warehouseId: OTHER_TEST_WAREHOUSE_ID });
|
||
|
||
const firstSeq = Number(first.check_no.slice(-6));
|
||
const secondSeq = Number(second.check_no.slice(-6));
|
||
assert.equal(
|
||
secondSeq,
|
||
firstSeq + 1,
|
||
`跨仓库序号应接续递增(不按仓库隔离): ${first.check_no} -> ${second.check_no}`
|
||
);
|
||
|
||
const secondRow = await ctx.model.StockCheck.findOne({
|
||
where: { id: second.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(Number(secondRow.warehouse_id), OTHER_TEST_WAREHOUSE_ID, '第二个任务应写入另一测试仓库');
|
||
});
|
||
|
||
it('单号撞 uk_check_no 唯一键自动重取:创建成功且取到下一号', async () => {
|
||
const service = ctx.service.systems.stockCheck;
|
||
const expectedNo = await service.generateCheckNo();
|
||
const expectedSeq = Number(expectedNo.slice(-6));
|
||
|
||
// 预插入同前缀同序号单号,模拟并发创建先占号
|
||
const occupied = await ctx.model.StockCheck.create({
|
||
warehouse_id: OTHER_TEST_WAREHOUSE_ID,
|
||
check_no: expectedNo,
|
||
title: uniqueTitle('盘点单元测试-撞号占位'),
|
||
type: 'location',
|
||
mode: 'blind',
|
||
status: 'created',
|
||
detail_status: 'none_checked',
|
||
creator_id: TEST_CREATOR_ID,
|
||
creator_name: TEST_CREATOR_NAME,
|
||
});
|
||
assert.equal(occupied.check_no, expectedNo, '占位单号应等于预取单号');
|
||
|
||
// 模拟并发撞号:首次取号强制返回已占用单号,随后恢复真实取号逻辑,
|
||
// 使 create 的第一次 INSERT 真实触发 uk_check_no 冲突并进入重试。
|
||
const originalGenerate = service.generateCheckNo.bind(service);
|
||
let generateCalls = 0;
|
||
mm(service, 'generateCheckNo', async () => {
|
||
generateCalls += 1;
|
||
if (generateCalls === 1) {
|
||
return expectedNo;
|
||
}
|
||
return originalGenerate();
|
||
});
|
||
|
||
const created = await createCheck();
|
||
mm.restore();
|
||
|
||
assert.equal(generateCalls, 2, '撞号后应重新取号一次(第一次撞号、第二次成功)');
|
||
const createdSeq = Number(created.check_no.slice(-6));
|
||
assert.equal(
|
||
createdSeq,
|
||
expectedSeq + 1,
|
||
`撞号后应自动重取下一号: ${expectedNo} -> ${created.check_no}`
|
||
);
|
||
const rowCount = await ctx.model.StockCheck.count({ where: { check_no: created.check_no } });
|
||
assert.equal(rowCount, 1, '重取后的单号应正常落库且全局唯一');
|
||
});
|
||
|
||
it('isCheckNoDuplicateError:仅 ER_DUP_ENTRY 且命中 check_no 唯一索引判为撞号', () => {
|
||
const service = ctx.service.systems.stockCheck;
|
||
|
||
const dupError = new Error('insert duplicate');
|
||
dupError.parent = {
|
||
code: 'ER_DUP_ENTRY',
|
||
sqlMessage: "Duplicate entry 'PD20260929000001' for key 'wms_stock_check.uk_check_no'",
|
||
};
|
||
assert.equal(service.isCheckNoDuplicateError(dupError), true, 'uk_check_no 唯一键冲突应判定为撞号');
|
||
|
||
const primaryError = new Error('insert duplicate');
|
||
primaryError.parent = { code: 'ER_DUP_ENTRY', sqlMessage: "Duplicate entry '1' for key 'PRIMARY'" };
|
||
assert.equal(service.isCheckNoDuplicateError(primaryError), false, '主键冲突不应判定为撞号');
|
||
|
||
const deadlockError = new Error('deadlock');
|
||
deadlockError.parent = { code: 'ER_LOCK_DEADLOCK', sqlMessage: 'Deadlock found' };
|
||
assert.equal(service.isCheckNoDuplicateError(deadlockError), false, '其他错误码不应判定为撞号');
|
||
|
||
const noParentError = new Error("Duplicate entry for key 'uk_check_no'");
|
||
assert.equal(service.isCheckNoDuplicateError(noParentError), false, '缺少 parent 元数据不应判定为撞号');
|
||
});
|
||
|
||
it('非法 type/mode 或按货主缺货主时报 400(check_date 已移除入参)', async () => {
|
||
await assert.rejects(async () => {
|
||
await createCheck({ type: 'bad_type' });
|
||
}, error => error.code === 400);
|
||
|
||
await assert.rejects(async () => {
|
||
await createCheck({ mode: 'bad_mode' });
|
||
}, error => error.code === 400);
|
||
|
||
await assert.rejects(async () => {
|
||
await createCheck({ type: 'store', storeId: null });
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('create 不写 check_date:返回与主表均不含该字段,start_time/end_time 初始为空', async () => {
|
||
const result = await createCheck();
|
||
|
||
assert.equal(result.status, 'created');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(result, 'check_date'),
|
||
false,
|
||
'create 返回结果不应含 check_date 字段'
|
||
);
|
||
const row = await findCheckRow(result.id);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, 'check_date'),
|
||
false,
|
||
'主表行不应含 check_date 字段'
|
||
);
|
||
assert.equal(row.start_time, null, '创建时 start_time 应为空(首次上报明细才写入)');
|
||
assert.equal(row.end_time, null, '创建时 end_time 应为空(完成盘点才写入)');
|
||
});
|
||
|
||
it('type=location 传 mode=open:按库位盘点一律盲盘,忽略前端传入', async () => {
|
||
const result = await createCheck({ type: 'location', mode: 'open' });
|
||
|
||
assert.equal(result.mode, 'blind', '按库位盘点应强制盲盘,忽略前端传入的 mode=open');
|
||
const row = await findCheckRow(result.id);
|
||
assert.equal(row.mode, 'blind', '主表应落库 blind');
|
||
});
|
||
|
||
it('type=all 已下线:创建报 400(全盘语义并入 location)', async () => {
|
||
await assert.rejects(async () => {
|
||
await createCheck({ type: 'all' });
|
||
}, error => error.code === 400 && /盘点范围类型不合法/.test(error.message));
|
||
});
|
||
|
||
it('type=goods 传 mode=blind:按商品盘点保留传入值', async () => {
|
||
const result = await createCheck({ type: 'goods', mode: 'blind' });
|
||
|
||
assert.equal(result.mode, 'blind', '按商品盘点应保留传入的 mode=blind');
|
||
const row = await findCheckRow(result.id);
|
||
assert.equal(row.mode, 'blind', '主表应落库 blind');
|
||
});
|
||
|
||
it('type=store 不传 mode:按商品盘点默认明盘 open', async () => {
|
||
// 业务层直调且不传 mode,验证默认明盘(绕过 createCheck 辅助函数的 mode 兜底)
|
||
const result = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('盘点单元测试-货主默认明盘'),
|
||
type: 'store',
|
||
storeId: TEST_STORE_ID,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
|
||
assert.equal(result.mode, 'open', '按货主盘点不传 mode 应默认明盘 open');
|
||
const row = await findCheckRow(result.id);
|
||
assert.equal(row.mode, 'open', '主表应落库 open');
|
||
});
|
||
|
||
it('is_static 静态标记:缺省 0、传 1/true 落库 1、兼容 isStatic 驼峰与 list/detail 返回、库位盘点强制 0', async () => {
|
||
// 缺省不传 → 普通盘点
|
||
const normal = await createCheck({ title: uniqueTitle('静态标记-缺省') });
|
||
assert.equal(Number(normal.is_static), 0, '缺省应为普通盘点(0)');
|
||
assert.equal(Number((await findCheckRow(normal.id)).is_static), 0, '主表应落库 0');
|
||
|
||
// 业务层传 isStatic=1 → 静态盘点
|
||
const staticCheck = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态标记-开启'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
assert.equal(Number(staticCheck.is_static), 1, '传 isStatic=1 应返回 is_static=1');
|
||
assert.equal(Number((await findCheckRow(staticCheck.id)).is_static), 1, '主表应落库 1');
|
||
|
||
// detail 返回该字段
|
||
const detail = await ctx.service.systems.stockCheck.detail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: staticCheck.id,
|
||
});
|
||
assert.equal(Number(detail.check.is_static), 1, 'detail 应返回 is_static');
|
||
|
||
// list 返回该字段
|
||
const listResult = await listChecks({ pagination: { page: 1, pageSize: 200 } });
|
||
const listed = listResult.rows.find(row => Number(row.id) === Number(staticCheck.id));
|
||
assert.ok(listed, '前置:list 应能查到该任务');
|
||
assert.equal(Number(listed.is_static), 1, 'list 行应返回 is_static');
|
||
|
||
// 方法层兼容 is_static 下划线与 isStatic 驼峰两种写法(需仓库上下文,临时设置 ctx.user)
|
||
const previousUser = ctx.user;
|
||
ctx.user = { id: TEST_CREATOR_ID, store_id: TEST_WAREHOUSE_ID, employees_name: TEST_CREATOR_NAME };
|
||
try {
|
||
const viaMethodSnake = await ctx.service.systemMethods.stock.check.create({
|
||
title: uniqueTitle('静态标记-方法层下划线'),
|
||
type: 'goods',
|
||
is_static: 1,
|
||
});
|
||
assert.equal(viaMethodSnake.flag, 'success');
|
||
assert.equal(Number(viaMethodSnake.data.is_static), 1, '方法层 is_static 应透传');
|
||
|
||
const viaMethodCamel = await ctx.service.systemMethods.stock.check.create({
|
||
title: uniqueTitle('静态标记-方法层驼峰'),
|
||
type: 'goods',
|
||
isStatic: 'true',
|
||
});
|
||
assert.equal(viaMethodCamel.flag, 'success');
|
||
assert.equal(Number(viaMethodCamel.data.is_static), 1, "方法层 isStatic='true' 应透传");
|
||
} finally {
|
||
ctx.user = previousUser;
|
||
}
|
||
|
||
// 其他值(0/'false'/空串)视为普通盘点
|
||
for (const value of [ 0, 'false', '', false ]) {
|
||
const created = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle(`静态标记-非开启-${String(value)}`),
|
||
type: 'goods',
|
||
isStatic: value,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
assert.equal(Number(created.is_static), 0, `isStatic=${JSON.stringify(value)} 应为普通盘点`);
|
||
}
|
||
|
||
// 仅对商品盘点有效:按库位盘点(location)即使传 isStatic=1 也一律 0
|
||
for (const value of [ 1, true, 'true' ]) {
|
||
const locationCheck = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle(`静态标记-库位盘点-${String(value)}`),
|
||
type: 'location',
|
||
isStatic: value,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
assert.equal(Number(locationCheck.is_static), 0, `按库位盘点传 isStatic=${JSON.stringify(value)} 应强制为 0`);
|
||
assert.equal(Number((await findCheckRow(locationCheck.id)).is_static), 0, '库位盘点主表应落库 0');
|
||
}
|
||
});
|
||
});
|
||
|
||
// ------------------- addDetail:添加盘点明细 -------------------
|
||
|
||
describe('addDetail 添加盘点明细', () => {
|
||
it('按 stock_ids 生成明细快照(item_code/item_name/spec/system_quantity)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
const stockIds = stocks.map(stock => stock.id);
|
||
|
||
const result = await addDetail(check.id, stockIds);
|
||
|
||
assert.equal(result.added, 2);
|
||
assert.equal(result.skipped, 0);
|
||
assert.equal(result.total_items, 2);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 2);
|
||
|
||
for (const row of rows) {
|
||
const stock = stocks.find(item => item.id === Number(row.stock_id));
|
||
assert.ok(stock, `明细应命中库存快照 stock_id=${row.stock_id}`);
|
||
assert.equal(row.item_code, stock.item_code, 'item_code 快照不一致');
|
||
assert.equal(row.item_name, stock.item_name, 'item_name 快照不一致');
|
||
assert.equal(row.spec, stock.sku_property, 'spec 应快照 sku_property');
|
||
// 拆行口径:system_quantity = 该商品在其库存库位的账面(wms_storage SUM(可用数量))
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
stock_id: Number(row.stock_id),
|
||
space_id: Number(row.location_id),
|
||
is_enabled: 1,
|
||
},
|
||
raw: true,
|
||
});
|
||
const expectedSystemQuantity = storageRows.reduce(
|
||
(sum, item) => sum + (Number(item.available_quantity) || 0),
|
||
0
|
||
);
|
||
assert.equal(Number(row.system_quantity), expectedSystemQuantity, 'system_quantity 应为该库位账面');
|
||
assert.equal(row.batch_no, null, '批次快照默认应为空');
|
||
}
|
||
|
||
// 明细范围行由直查明细表校验(detail 接口只返回任务本身信息):商品行 scope_type=goods 且绑定库存库位
|
||
const detailResult = await detailCheck(check.id);
|
||
assert.equal(detailResult.total, 2);
|
||
for (const row of detailResult.rows) {
|
||
assert.equal(row.scope_type, 'goods', '商品明细 scope_type 应为 goods');
|
||
assert.ok(row.stock_id, '商品明细应含 stock_id');
|
||
assert.ok(row.location_id, '商品明细应绑定库存库位');
|
||
assert.ok(row.location_code, '商品明细应绑定库位编码');
|
||
}
|
||
|
||
// 盘点前(无作业记录):result 直接返回明细范围行(wms_stock_check_detail)
|
||
const checkResult = await resultCheck(check.id);
|
||
assert.equal(checkResult.total, 2);
|
||
for (const row of checkResult.rows) {
|
||
assert.equal(row.scope_type, 'goods');
|
||
assert.ok(row.stock_id, '明细行应含 stock_id');
|
||
assert.ok(row.location_code, '明细行应含库位编码');
|
||
assert.ok(Number(row.system_quantity) >= 0, '明细行应含账面快照');
|
||
}
|
||
const recordCount = await ctx.model.StockCheckRecord.count({
|
||
where: { check_id: check.id },
|
||
});
|
||
assert.equal(recordCount, 0, '添加明细阶段不应写作业记录');
|
||
});
|
||
|
||
it('重复添加同一 stock_id 幂等跳过,不重复生成明细', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
const stockIds = stocks.map(stock => stock.id);
|
||
|
||
const first = await addDetail(check.id, stockIds);
|
||
const second = await addDetail(check.id, stockIds);
|
||
|
||
assert.equal(first.added, 2);
|
||
assert.equal(second.added, 0);
|
||
assert.equal(second.skipped, 2);
|
||
|
||
const count = await ctx.model.StockCheckDetail.count({
|
||
where: { check_id: check.id },
|
||
});
|
||
assert.equal(count, 2, '重复添加不应生成多余明细');
|
||
});
|
||
|
||
it('多库位商品按「商品 + 库位」拆多行,各行账面为该库位库存', async () => {
|
||
const { Op, literal } = ctx.app.Sequelize;
|
||
// 找一个在两个启用库位都有库存的商品
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
|
||
group: [ 'stock_id', 'space_id' ],
|
||
raw: true,
|
||
});
|
||
const spacesByStock = new Map();
|
||
for (const row of storageRows) {
|
||
const stockId = Number(row.stock_id);
|
||
if (!spacesByStock.has(stockId)) {
|
||
spacesByStock.set(stockId, []);
|
||
}
|
||
spacesByStock.get(stockId).push(row);
|
||
}
|
||
const multiStockEntry = [ ...spacesByStock.entries() ].find(([ , rows ]) => rows.length >= 2);
|
||
assert.ok(multiStockEntry, '前置:测试库应存在多库位库存商品');
|
||
const multiStockId = Number(multiStockEntry[0]);
|
||
const multiStock = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: multiStockId, warehouse_id: TEST_WAREHOUSE_ID },
|
||
raw: true,
|
||
});
|
||
assert.ok(multiStock, '前置:多库位商品应存在于 wms_stock_warehouse');
|
||
|
||
const check = await createCheck({ type: 'goods', storeId: multiStock.store_id || null });
|
||
const result = await addDetail(check.id, [ multiStockId ]);
|
||
|
||
assert.equal(result.added, multiStockEntry[1].length, 'added 应为拆分明细行数(商品按库位拆多行)');
|
||
assert.equal(result.total_items, 1, '按商品盘点 total_items 按商品计数(多库位拆多行仍计 1 项)');
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, multiStockEntry[1].length);
|
||
const spaceIds = rows.map(row => Number(row.location_id)).sort((a, b) => a - b);
|
||
assert.deepEqual(
|
||
spaceIds,
|
||
multiStockEntry[1].map(row => Number(row.space_id)).sort((a, b) => a - b),
|
||
'明细行应覆盖商品全部库存库位'
|
||
);
|
||
const quantityBySpace = new Map(multiStockEntry[1].map(row => [ Number(row.space_id), Number(row.totalQuantity) || 0 ]));
|
||
for (const row of rows) {
|
||
assert.equal(Number(row.system_quantity), quantityBySpace.get(Number(row.location_id)), '各行账面应为该库位库存');
|
||
assert.ok(row.location_code, '各行应绑定库位编码');
|
||
}
|
||
|
||
// 拆行任务可正常提交
|
||
const submitResult = await submitCheck(check.id);
|
||
assert.equal(submitResult.status, 'submitted');
|
||
});
|
||
|
||
it('商品在仓库中没有启用库存库位 → 计入 invalid_stock_ids 不入明细', async () => {
|
||
const check = await createCheck();
|
||
// 构造无库存库位的商品(只写 wms_stock_warehouse,不写 wms_storage)
|
||
const [ fabricatedResult ] = await ctx.model.query(
|
||
`INSERT INTO wms_stock_warehouse
|
||
(item_code, item_name, store_id, stock_unit, item_type, create_at,
|
||
warehouse_id, is_valid, quantity, is_shelf_life_mgmt, remaining_threshold_days)
|
||
VALUES (:itemCode, '盘点拆行测试商品', :storeId, '个', 'normal', NOW(),
|
||
:warehouseId, 'Y', 3, 'N', 0)`,
|
||
{
|
||
replacements: {
|
||
itemCode: `PATT-NOLOC-${Date.now()}`,
|
||
storeId: TEST_STORE_ID,
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
},
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
const fabricatedId = Number(fabricatedResult);
|
||
const validStocks = await fetchStockRows(1);
|
||
|
||
const result = await addDetail(check.id, [ validStocks[0].id, fabricatedId ]);
|
||
|
||
assert.equal(result.added, 1, '仅有效商品入明细');
|
||
assert.deepEqual(result.invalid_stock_ids, [ fabricatedId ], '无库存库位商品应计入 invalid_stock_ids');
|
||
assert.equal(result.total_items, 1);
|
||
});
|
||
|
||
it('不存在的 stock_id 计入 invalid_stock_ids,不影响有效明细', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const result = await addDetail(check.id, [ stocks[0].id, 999999999 ]);
|
||
|
||
assert.equal(result.added, 1);
|
||
assert.deepEqual(result.invalid_stock_ids, [ 999999999 ]);
|
||
assert.equal(result.total_items, 1);
|
||
});
|
||
|
||
it('空 stock_ids 报 400', async () => {
|
||
const check = await createCheck();
|
||
|
||
await assert.rejects(async () => {
|
||
await addDetail(check.id, []);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('submitted 状态不允许添加明细,报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
}, error => error.code === 400);
|
||
});
|
||
});
|
||
|
||
// ------------------- addDetail:盘点范围类型分派(商品/库位维度互斥) -------------------
|
||
|
||
describe('addDetail 盘点范围类型分派', () => {
|
||
it('goods/store 类型传 locations 报 400(商品与库位维度互斥)', async () => {
|
||
const goodsCheck = await createCheck({ type: 'goods' });
|
||
await assert.rejects(async () => {
|
||
await addDetailRaw({ id: goodsCheck.id, locations: [ TEST_LOCATION_CODE ] });
|
||
}, error => error.code === 400 && /按商品盘点/.test(error.message));
|
||
|
||
const storeCheck = await createCheck({ type: 'store', storeId: TEST_STORE_ID });
|
||
await assert.rejects(async () => {
|
||
await addDetailRaw({ id: storeCheck.id, locations: [ TEST_LOCATION_CODE ] });
|
||
}, error => error.code === 400 && /按商品盘点/.test(error.message));
|
||
});
|
||
|
||
it('location 类型传 stock_ids 报 400(库位与商品维度互斥)', async () => {
|
||
const stocks = await fetchStockRows(1);
|
||
|
||
const locationCheck = await createCheck({ type: 'location' });
|
||
await assert.rejects(async () => {
|
||
await addDetailRaw({ id: locationCheck.id, stockIds: [ stocks[0].id ] });
|
||
}, error => error.code === 400 && /按库位盘点/.test(error.message));
|
||
});
|
||
|
||
it('type=location 缺省 locations 自动生成全仓库启用库位明细(排除无头库位),重复添加全部幂等跳过', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
// 有效库位口径:启用且所属 zone 存在未删除(与业务排除无头库位口径一致)
|
||
const enabledSpaces = await ctx.model.LocationSpace.findAll({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, is_enabled: true },
|
||
attributes: [ 'space_code' ],
|
||
include: [{
|
||
model: ctx.model.LocationZone,
|
||
as: 'zone',
|
||
attributes: [],
|
||
required: true,
|
||
}],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
const enabledCount = new Set(enabledSpaces
|
||
.map(row => String(row.space_code || '').trim())
|
||
.filter(Boolean)).size;
|
||
assert.ok(enabledCount > 0, '固定测试仓库应存在启用库位');
|
||
|
||
const result = await addLocationDetail(check.id, undefined);
|
||
|
||
assert.equal(result.added, enabledCount, '自动生成的明细数应等于全仓库启用库位数');
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(result.invalid_locations, []);
|
||
assert.deepEqual(result.invalid_stock_ids, []);
|
||
assert.equal(result.total_items, enabledCount);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, enabledCount);
|
||
for (const row of rows) {
|
||
assert.equal(row.scope_type, 'location', '全盘自动生成的明细应为库位行');
|
||
assert.equal(row.stock_id, null, '库位行不应写商品 ID');
|
||
assert.equal(row.item_code, null, '库位行不应写商品编码快照');
|
||
assert.equal(Number(row.system_quantity), 0, '库位行账面快照固定为 0');
|
||
assert.ok(row.location_code, '库位行应写库位编码');
|
||
assert.ok(row.location_id, '库位行应写库位 ID');
|
||
}
|
||
const testLocationRow = rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
assert.ok(testLocationRow, '固定测试库位应包含在自动生成明细中');
|
||
assert.equal(Number(testLocationRow.location_id), TEST_LOCATION_ID);
|
||
|
||
// 幂等:再次缺省添加 → 全部跳过,不重复生成明细
|
||
const again = await addLocationDetail(check.id, undefined);
|
||
assert.equal(again.added, 0);
|
||
assert.equal(again.skipped, enabledCount);
|
||
assert.equal(again.total_items, enabledCount);
|
||
});
|
||
|
||
it('历史遗留 type=all 任务拒绝添加明细:报 400(all 已下线,防御脏数据)', async () => {
|
||
const legacyCheck = await ctx.model.StockCheck.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
check_no: `DIA${Date.now()}`,
|
||
title: uniqueTitle('盘点单元测试-历史all任务'),
|
||
type: 'all',
|
||
mode: 'blind',
|
||
status: 'created',
|
||
detail_status: 'none_checked',
|
||
creator_id: TEST_CREATOR_ID,
|
||
creator_name: TEST_CREATOR_NAME,
|
||
});
|
||
|
||
await assert.rejects(async () => {
|
||
await addLocationDetail(legacyCheck.id, [ TEST_LOCATION_CODE ]);
|
||
}, error => error.code === 400 && /盘点范围类型不合法/.test(error.message));
|
||
});
|
||
|
||
it('库位添加:有效编码落库 scope_type/location 字段、无效编码计入 invalid_locations、重复添加幂等跳过', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
const first = await addLocationDetail(check.id, [ TEST_LOCATION_CODE, 'NOT_EXIST_SPACE_999' ]);
|
||
assert.equal(first.added, 1);
|
||
assert.equal(first.skipped, 0);
|
||
assert.deepEqual(first.invalid_locations, [ 'NOT_EXIST_SPACE_999' ], '未匹配编码应计入非法库位');
|
||
assert.deepEqual(first.invalid_stock_ids, []);
|
||
assert.equal(first.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1, '非法库位不应落库');
|
||
assert.equal(rows[0].scope_type, 'location');
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID, '库位行应落库 location_id');
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE, '库位行应落库 location_code');
|
||
assert.equal(rows[0].stock_id, null);
|
||
assert.equal(rows[0].item_code, null);
|
||
assert.equal(Number(rows[0].system_quantity), 0);
|
||
|
||
const second = await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
assert.equal(second.added, 0);
|
||
assert.equal(second.skipped, 1, '同库位重复添加应幂等跳过');
|
||
assert.equal(second.total_items, 1);
|
||
|
||
const count = await ctx.model.StockCheckDetail.count({
|
||
where: { check_id: check.id },
|
||
});
|
||
assert.equal(count, 1, '重复添加不应生成多余明细');
|
||
});
|
||
|
||
it('无头库位(所属 zone 不存在)计入 invalid_locations 且不入库', async () => {
|
||
// fixture:造一个 zone 不存在的库位(zone_id 无外键约束,模拟无头库位)
|
||
const headless = await ctx.model.LocationSpace.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
zone_id: 999999999,
|
||
location_type_id: 1,
|
||
space_code: 'HDLS-TEST-001',
|
||
});
|
||
try {
|
||
const check = await createCheck({ type: 'location' });
|
||
const result = await addLocationDetail(check.id, [ TEST_LOCATION_CODE, 'HDLS-TEST-001' ]);
|
||
assert.equal(result.added, 1, '仅有效库位应入库');
|
||
assert.deepEqual(result.invalid_locations, [ 'HDLS-TEST-001' ], '无头库位应计入 invalid_locations');
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: check.id }, raw: true });
|
||
assert.equal(rows.length, 1, '无头库位不应落库');
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE);
|
||
} finally {
|
||
await ctx.model.LocationSpace.destroy({ where: { id: headless.id }, force: true });
|
||
}
|
||
});
|
||
|
||
it('按货主盘点:任务货主与商品货主不一致计入 invalid_stock_ids 且不入库', async () => {
|
||
const check = await createCheck({ type: 'store', storeId: TEST_STORE_ID });
|
||
const stocks = await fetchStockRows(1);
|
||
const foreignStock = await fetchOtherStoreStockRow();
|
||
assert.ok(foreignStock, '固定测试仓库应存在其他货主的商品(货主隔离校验依赖)');
|
||
|
||
const result = await addDetail(check.id, [ stocks[0].id, foreignStock.id ]);
|
||
|
||
assert.equal(result.added, 1, '仅任务货主商品应入库');
|
||
assert.deepEqual(result.invalid_stock_ids, [ Number(foreignStock.id) ], '其他货主商品应计入非法列表');
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1, '其他货主商品不应生成明细');
|
||
assert.equal(Number(rows[0].stock_id), stocks[0].id);
|
||
});
|
||
});
|
||
|
||
// ------------------- addDetail:location_ids 库位ID直查(新增入参) -------------------
|
||
|
||
describe('addDetail location_ids 库位ID直查', () => {
|
||
it('type=location 传 location_ids:按 ID 直查落库 scope_type=location 行,invalid_location_ids=[]', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
const result = await addDetailRaw({ id: check.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
|
||
assert.equal(result.added, 1);
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(result.invalid_location_ids, [], '有效库位ID不应计入非法列表');
|
||
assert.deepEqual(result.invalid_locations, []);
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1);
|
||
assert.equal(rows[0].scope_type, 'location', '库位ID直查生成的明细应为库位行');
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID, '库位行应落库 location_id');
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE, '库位行应落库 location_code');
|
||
assert.equal(rows[0].stock_id, null);
|
||
assert.equal(rows[0].item_code, null);
|
||
assert.equal(Number(rows[0].system_quantity), 0);
|
||
});
|
||
|
||
it('type=location 传 location_ids:只添加指定库位,不触发全盘自动生成', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
const result = await addDetailRaw({ id: check.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
|
||
assert.equal(result.added, 1);
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(result.invalid_location_ids, []);
|
||
assert.equal(result.total_items, 1, '显式传库位ID时不应按全盘自动生成全部启用库位');
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1);
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID);
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE);
|
||
});
|
||
|
||
it('location_ids 与 locations 同传:location_ids 优先,locations 忽略(无效编码不进 invalid_locations)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
const result = await addDetailRaw({
|
||
id: check.id,
|
||
locations: [ 'NOT_EXIST_SPACE_999' ],
|
||
locationIds: [ TEST_LOCATION_ID ],
|
||
});
|
||
|
||
assert.equal(result.added, 1);
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(result.invalid_location_ids, []);
|
||
assert.deepEqual(result.invalid_locations, [], 'locations 被忽略时不应解析编码,也不应计入非法库位');
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1);
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID, '应按 location_ids 的库位 ID 落库');
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE);
|
||
});
|
||
|
||
it('无效 location_id(不存在/其他仓库)计入 invalid_location_ids 且不入库', async () => {
|
||
const { Op } = ctx.app.Sequelize;
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
// 其他仓库的真实库位 ID:ID 存在但 warehouse_id 不属于当前仓库,应视为无效
|
||
const foreignSpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: { [Op.ne]: TEST_WAREHOUSE_ID } },
|
||
attributes: [ 'id', 'space_code' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
assert.ok(foreignSpace, '本地库应存在其他仓库的库位(跨仓库隔离校验依赖)');
|
||
const missingLocationId = await fetchMissingLocationId();
|
||
|
||
const result = await addDetailRaw({
|
||
id: check.id,
|
||
locationIds: [ TEST_LOCATION_ID, missingLocationId, foreignSpace.id ],
|
||
});
|
||
|
||
assert.equal(result.added, 1);
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(
|
||
result.invalid_location_ids,
|
||
[ missingLocationId, Number(foreignSpace.id) ],
|
||
'不存在与其他仓库的库位ID应按入参顺序计入非法列表'
|
||
);
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1, '无效库位ID不应落库');
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID);
|
||
});
|
||
|
||
it('无头库位 ID(zone 不存在)计入 invalid_location_ids 且不入库', async () => {
|
||
// fixture:造一个 zone 不存在的库位(zone_id 无外键约束,模拟无头库位)
|
||
const headless = await ctx.model.LocationSpace.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
zone_id: 999999999,
|
||
location_type_id: 1,
|
||
space_code: 'HDLS-TEST-002',
|
||
});
|
||
try {
|
||
const check = await createCheck({ type: 'location' });
|
||
const result = await addDetailRaw({ id: check.id, locationIds: [ TEST_LOCATION_ID, headless.id ] });
|
||
assert.equal(result.added, 1, '仅有效库位应入库');
|
||
assert.deepEqual(result.invalid_location_ids, [ Number(headless.id) ], '无头库位ID应计入非法列表');
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: check.id }, raw: true });
|
||
assert.equal(rows.length, 1, '无头库位不应落库');
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID);
|
||
} finally {
|
||
await ctx.model.LocationSpace.destroy({ where: { id: headless.id }, force: true });
|
||
}
|
||
});
|
||
|
||
it('幂等:同次重复 ID 去重、重复传同一 location_id 跳过、编码路径已入库后 ID 路径也跳过', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
const first = await addDetailRaw({
|
||
id: check.id,
|
||
locationIds: [ TEST_LOCATION_ID, TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(first.added, 1, '同次调用重复 ID 应去重只新增一次');
|
||
assert.equal(first.skipped, 0);
|
||
assert.equal(first.total_items, 1);
|
||
|
||
const second = await addDetailRaw({ id: check.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
assert.equal(second.added, 0);
|
||
assert.equal(second.skipped, 1, '重复传同一 location_id 应幂等跳过');
|
||
assert.equal(second.total_items, 1);
|
||
|
||
// 跨路径幂等(uk_check_location 口径):编码路径已入库,再按 ID 添加应跳过
|
||
const anotherCheck = await createCheck({ type: 'location' });
|
||
await addLocationDetail(anotherCheck.id, [ TEST_LOCATION_CODE ]);
|
||
const cross = await addDetailRaw({ id: anotherCheck.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
assert.equal(cross.added, 0, '编码路径已入库的库位,ID 路径应跳过');
|
||
assert.equal(cross.skipped, 1);
|
||
assert.equal(cross.total_items, 1);
|
||
|
||
const count = await ctx.model.StockCheckDetail.count({ where: { check_id: check.id } });
|
||
assert.equal(count, 1, '重复添加不应生成多余明细');
|
||
});
|
||
|
||
it('goods/store 类型传 location_ids 报 400(按商品盘点,不能添加库位明细)', async () => {
|
||
const goodsCheck = await createCheck({ type: 'goods' });
|
||
await assert.rejects(async () => {
|
||
await addDetailRaw({ id: goodsCheck.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
}, error => error.code === 400 && /按商品盘点,不能添加库位明细/.test(error.message));
|
||
|
||
const storeCheck = await createCheck({ type: 'store', storeId: TEST_STORE_ID });
|
||
await assert.rejects(async () => {
|
||
await addDetailRaw({ id: storeCheck.id, locationIds: [ TEST_LOCATION_ID ] });
|
||
}, error => error.code === 400 && /按商品盘点,不能添加库位明细/.test(error.message));
|
||
});
|
||
|
||
it('addLocationDetail 兼容入口:转调 addDetail 落库,返回结构不变(过滤 invalid_locations/invalid_stock_ids)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
const missingLocationId = await fetchMissingLocationId();
|
||
|
||
const result = await addLocationDetailByIds(check.id, [ TEST_LOCATION_ID, missingLocationId ]);
|
||
|
||
assert.deepEqual(
|
||
Object.keys(result).sort(),
|
||
[ 'added', 'invalid_location_ids', 'skipped', 'total_items' ].sort(),
|
||
'兼容入口返回结构应保持不变'
|
||
);
|
||
assert.equal(result.added, 1);
|
||
assert.equal(result.skipped, 0);
|
||
assert.deepEqual(result.invalid_location_ids, [ missingLocationId ]);
|
||
assert.equal(result.total_items, 1);
|
||
|
||
const rows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
raw: true,
|
||
});
|
||
assert.equal(rows.length, 1, '无效库位ID不应落库');
|
||
assert.equal(Number(rows[0].location_id), TEST_LOCATION_ID);
|
||
assert.equal(rows[0].location_code, TEST_LOCATION_CODE);
|
||
});
|
||
|
||
it('addLocationDetail 参数校验保持旧口径:空库位ID与超 200 上限报 400', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
|
||
await assert.rejects(async () => {
|
||
await addLocationDetailByIds(check.id, []);
|
||
}, error => error.code === 400 && /至少选择一个库位/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await addLocationDetailByIds(check.id, undefined);
|
||
}, error => error.code === 400 && /至少选择一个库位/.test(error.message));
|
||
|
||
const overLimitIds = Array.from({ length: 201 }, (_, index) => index + 1);
|
||
await assert.rejects(async () => {
|
||
await addLocationDetailByIds(check.id, overLimitIds);
|
||
}, error => error.code === 400 && /200/.test(error.message));
|
||
});
|
||
});
|
||
|
||
// ------------------- detailDelete:删除盘点明细 -------------------
|
||
|
||
describe('detailDelete 删除盘点明细', () => {
|
||
it('created 状态删除 1 条明细(detailIds 单值自动转数组):deleted_count=1、total_items 重算、detail 中该 stock_id 消失', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
|
||
const before = await detailCheck(check.id);
|
||
assert.equal(before.total, 2);
|
||
|
||
const deletedDetail = before.rows[0];
|
||
const keptDetail = before.rows[1];
|
||
const result = await deleteDetail(check.id, deletedDetail.id);
|
||
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.deepEqual(result.deleted_ids.map(Number), [ Number(deletedDetail.id) ], '返回的明细 ID 应一致');
|
||
assert.deepEqual(result.skipped_ids, [], '全部命中不应有跳过明细');
|
||
assert.equal(result.total_items, 1, '删除后主表明细数应重算为 1');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.total_items, 1, '主表 total_items 应同步重算');
|
||
|
||
const after = await detailCheck(check.id);
|
||
assert.equal(after.total, 1);
|
||
assert.ok(
|
||
!after.rows.some(item => Number(item.stock_id) === Number(deletedDetail.stock_id)),
|
||
'被删除明细的 stock_id 应从 detail 中消失'
|
||
);
|
||
assert.ok(
|
||
after.rows.some(item => Number(item.stock_id) === Number(keptDetail.stock_id)),
|
||
'未删除明细应保留'
|
||
);
|
||
});
|
||
|
||
it('批量删除 2 条明细:deleted_count=2、deleted_ids 保持入参顺序、total_items 减 2、DB 明细清空', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(3);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 3, '前置:任务应有 3 条明细');
|
||
|
||
const targetIds = [ details.rows[0].id, details.rows[1].id ];
|
||
const result = await deleteDetail(check.id, targetIds);
|
||
|
||
assert.equal(result.deleted_count, 2);
|
||
assert.deepEqual(result.deleted_ids.map(Number), targetIds.map(Number), 'deleted_ids 应保持入参顺序');
|
||
assert.deepEqual(result.skipped_ids, [], '全部命中不应有跳过明细');
|
||
assert.equal(result.total_items, 1, '删除 2 条后主表明细数应重算为 1');
|
||
assert.equal((await findCheckRow(check.id)).total_items, 1, '主表 total_items 应同步重算');
|
||
|
||
// DB 明细清空校验:被删 ID 消失、仅剩未删除的 1 条
|
||
const remaining = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: check.id },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
const remainingIds = remaining.map(row => Number(row.id));
|
||
for (const targetId of targetIds) {
|
||
assert.ok(!remainingIds.includes(Number(targetId)), `被删明细 ${targetId} 应从 DB 消失`);
|
||
}
|
||
assert.deepEqual(remainingIds, [ Number(details.rows[2].id) ], '仅剩未删除的 1 条明细');
|
||
});
|
||
|
||
it('混合删除:存在 + 不存在 ID 分流(deleted_ids/skipped_ids 均保持入参顺序)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 2);
|
||
|
||
const missingIdA = await findFreeDetailId();
|
||
const missingIdB = missingIdA + 1;
|
||
const mixed = [ missingIdA, details.rows[0].id, missingIdB, details.rows[1].id ];
|
||
const result = await deleteDetail(check.id, mixed);
|
||
|
||
assert.equal(result.deleted_count, 2);
|
||
assert.deepEqual(
|
||
result.deleted_ids.map(Number),
|
||
[ Number(details.rows[0].id), Number(details.rows[1].id) ],
|
||
'deleted_ids 应保持命中明细的入参顺序'
|
||
);
|
||
assert.deepEqual(
|
||
result.skipped_ids.map(Number),
|
||
[ missingIdA, missingIdB ],
|
||
'skipped_ids 应保持未命中明细的入参顺序'
|
||
);
|
||
assert.equal(result.total_items, 0, '命中明细全部删除后主表明细数重算为 0');
|
||
assert.equal(
|
||
await ctx.model.StockCheckDetail.count({ where: { check_id: check.id } }),
|
||
0,
|
||
'DB 明细应清空'
|
||
);
|
||
});
|
||
|
||
it('detailIds 超过 200 条报 400(单次最多删除 200 条明细)', async () => {
|
||
const check = await createCheck();
|
||
const tooManyIds = Array.from({ length: 201 }, (_, index) => index + 1);
|
||
await assert.rejects(
|
||
() => deleteDetailRaw({ id: check.id, detailIds: tooManyIds }),
|
||
error => error.code === 400 && /单次最多删除 200 条明细/.test(error.message)
|
||
);
|
||
});
|
||
|
||
it('重复删除同一明细不报错:未命中计入 skipped_ids(deleted_count=0,不改变剩余明细)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
|
||
const details = await detailCheck(check.id);
|
||
await deleteDetail(check.id, details.rows[0].id);
|
||
|
||
const result = await deleteDetail(check.id, details.rows[0].id);
|
||
assert.equal(result.deleted_count, 0, '重复删除不应命中');
|
||
assert.deepEqual(result.deleted_ids, [], '重复删除不应有命中明细');
|
||
assert.deepEqual(
|
||
result.skipped_ids.map(Number),
|
||
[ Number(details.rows[0].id) ],
|
||
'未命中明细应计入 skipped_ids'
|
||
);
|
||
assert.equal(result.total_items, 1, '未命中删除不应改变剩余明细数');
|
||
assert.equal((await findCheckRow(check.id)).total_items, 1, '主表 total_items 不应变化');
|
||
});
|
||
|
||
it('submitted/approved/checking 状态删除明细报 400', async () => {
|
||
// submitted 状态
|
||
const submittedCheck = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(submittedCheck.id, stocks.map(stock => stock.id));
|
||
await submitCheck(submittedCheck.id);
|
||
const submittedDetails = await detailCheck(submittedCheck.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await deleteDetail(submittedCheck.id, submittedDetails.rows[0].id);
|
||
}, error => error.code === 400 && /不允许删除明细/.test(error.message));
|
||
|
||
// approved 状态
|
||
const approvedCheck = await createCheck();
|
||
const moreStocks = await fetchStockRows(2);
|
||
await addDetail(approvedCheck.id, moreStocks.map(stock => stock.id));
|
||
await submitCheck(approvedCheck.id);
|
||
await auditCheck(approvedCheck.id, 'approve');
|
||
const approvedDetails = await detailCheck(approvedCheck.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await deleteDetail(approvedCheck.id, approvedDetails.rows[0].id);
|
||
}, error => error.code === 400 && /不允许删除明细/.test(error.message));
|
||
|
||
// checking 状态(approved → 首次上报 → checking)
|
||
await reportCheck(approvedCheck.id, approvedDetails.rows[0].id, 0);
|
||
assert.equal((await findCheckRow(approvedCheck.id)).status, 'checking');
|
||
await assert.rejects(async () => {
|
||
await deleteDetail(approvedCheck.id, approvedDetails.rows[0].id);
|
||
}, error => error.code === 400 && /不允许删除明细/.test(error.message));
|
||
});
|
||
|
||
it('rejected 状态可删除明细(submit→audit reject 后删除成功)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'reject', '明细商品有误,请重新盘点');
|
||
assert.equal((await findCheckRow(check.id)).status, 'rejected');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await deleteDetail(check.id, details.rows[0].id);
|
||
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.deepEqual(result.deleted_ids.map(Number), [ Number(details.rows[0].id) ]);
|
||
assert.deepEqual(result.skipped_ids, []);
|
||
assert.equal(result.total_items, 1);
|
||
assert.equal((await findCheckRow(check.id)).total_items, 1, '主表 total_items 应同步重算');
|
||
});
|
||
|
||
it('detailIds 缺失/全非法值或任务 id 非法报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
|
||
// detailIds 缺失
|
||
await assert.rejects(
|
||
() => deleteDetailRaw({ id: check.id }),
|
||
error => error.code === 400 && /请至少选择一个明细/.test(error.message)
|
||
);
|
||
|
||
// detailIds 全非法值(归一化后为空):单值与数组形态均报 400
|
||
for (const badDetailIds of [ null, '', 0, -1, 1.5, 'abc', [], [ 0, -1, 1.5, 'abc' ]]) {
|
||
await assert.rejects(
|
||
() => deleteDetailRaw({ id: check.id, detailIds: badDetailIds }),
|
||
error => error.code === 400 && /请至少选择一个明细/.test(error.message)
|
||
);
|
||
}
|
||
|
||
// 任务 id 非法
|
||
await assert.rejects(
|
||
() => deleteDetailRaw({ id: 'abc', detailIds: [ 1 ] }),
|
||
error => error.code === 400 && /任务ID/.test(error.message)
|
||
);
|
||
});
|
||
|
||
it('仓库隔离:其他仓库任务不可删除;跨仓库明细未命中计入 skipped_ids', async () => {
|
||
const otherWarehouseId = OTHER_TEST_WAREHOUSE_ID;
|
||
|
||
// 其他仓库任务(直接造数,避免与单号生成器按仓库隔离序号、全局唯一索引的耦合):
|
||
// 本仓库视角任务不存在
|
||
const otherCheck = await ctx.model.StockCheck.create({
|
||
warehouse_id: otherWarehouseId,
|
||
check_no: `DIA${Date.now()}`,
|
||
title: uniqueTitle('盘点单元测试-仓库隔离'),
|
||
type: 'location',
|
||
mode: 'blind',
|
||
status: 'created',
|
||
detail_status: 'none_checked',
|
||
creator_id: TEST_CREATOR_ID,
|
||
creator_name: TEST_CREATOR_NAME,
|
||
});
|
||
await assert.rejects(async () => {
|
||
await deleteDetail(otherCheck.id, 1);
|
||
}, error => error.code === 400 && /任务不存在/.test(error.message));
|
||
|
||
// 同任务下跨仓库明细:仓库隔离查询查不到 → 计入 skipped_ids(不报错)
|
||
// (uk_check_stock(check_id, stock_id) 唯一索引下跨仓库明细须使用不同商品,避免直接撞索引)
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
const foreignDetail = await ctx.model.StockCheckDetail.create({
|
||
check_id: check.id,
|
||
warehouse_id: otherWarehouseId,
|
||
stock_id: stocks[1].id,
|
||
item_code: 'FOREIGN-ISOLATION-ITEM',
|
||
item_name: '仓库隔离测试商品',
|
||
system_quantity: 1,
|
||
});
|
||
const skippedResult = await deleteDetail(check.id, foreignDetail.id);
|
||
assert.equal(skippedResult.deleted_count, 0, '跨仓库明细不应命中删除');
|
||
assert.deepEqual(skippedResult.deleted_ids, []);
|
||
assert.deepEqual(
|
||
skippedResult.skipped_ids.map(Number),
|
||
[ Number(foreignDetail.id) ],
|
||
'跨仓库明细应计入 skipped_ids'
|
||
);
|
||
|
||
// 未命中删除不改变本仓库明细
|
||
const afterSkip = await detailCheck(check.id);
|
||
assert.equal(afterSkip.total, 1, '本仓库明细应保持未删除');
|
||
|
||
// 清理跨仓库明细,恢复任务数据形态后本仓库明细删除不受影响
|
||
await ctx.model.StockCheckDetail.destroy({ where: { id: foreignDetail.id } });
|
||
const details = await detailCheck(check.id);
|
||
const result = await deleteDetail(check.id, details.rows[0].id);
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.deepEqual(result.deleted_ids.map(Number), [ Number(details.rows[0].id) ]);
|
||
assert.equal(result.total_items, 0, '本仓库明细删除后任务内无剩余明细');
|
||
});
|
||
|
||
it('防御清理:明细存在作业记录时删除明细一并清除记录', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows[0];
|
||
|
||
// created 状态正常流程不会有作业记录,直接造数模拟防御清理场景
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: targetDetail.id,
|
||
stock_id: targetDetail.stock_id,
|
||
location_code: 'DEFENSE-CLEAN-001',
|
||
quantity: 5,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
assert.equal(
|
||
(await queryRecords(check.id, targetDetail.id)).length,
|
||
1,
|
||
'造数应写入一条作业记录'
|
||
);
|
||
|
||
const result = await deleteDetail(check.id, targetDetail.id);
|
||
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.deepEqual(result.deleted_ids.map(Number), [ Number(targetDetail.id) ]);
|
||
assert.deepEqual(result.skipped_ids, []);
|
||
assert.equal(result.total_items, 1, '删除明细后主表明细数重算为 1');
|
||
assert.equal(
|
||
(await queryRecords(check.id, targetDetail.id)).length,
|
||
0,
|
||
'该明细的作业记录应一并清除'
|
||
);
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({ where: { check_id: check.id } }),
|
||
0,
|
||
'任务内不应残留作业记录'
|
||
);
|
||
const after = await detailCheck(check.id);
|
||
assert.equal(after.total, 1, '仅剩 1 条未删除明细');
|
||
});
|
||
|
||
it('防御清理(批量):带作业记录的 2 条明细批量删除后作业记录全部清空', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 2);
|
||
|
||
// created 状态正常流程不会有作业记录,批量造数模拟防御清理场景
|
||
for (const detail of details.rows) {
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: detail.stock_id,
|
||
location_code: `DEFENSE-BATCH-${detail.id}`,
|
||
quantity: 5,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
}
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({ where: { check_id: check.id } }),
|
||
2,
|
||
'前置:应有 2 条作业记录'
|
||
);
|
||
|
||
const targetIds = details.rows.map(detail => detail.id);
|
||
const result = await deleteDetail(check.id, targetIds);
|
||
|
||
assert.equal(result.deleted_count, 2);
|
||
assert.deepEqual(result.deleted_ids.map(Number), targetIds.map(Number));
|
||
assert.deepEqual(result.skipped_ids, []);
|
||
assert.equal(result.total_items, 0, '批量删除后主表明细数重算为 0');
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({ where: { check_id: check.id } }),
|
||
0,
|
||
'批量删除后任务内不应残留作业记录'
|
||
);
|
||
assert.equal(
|
||
await ctx.model.StockCheckDetail.count({ where: { check_id: check.id } }),
|
||
0,
|
||
'批量删除后 DB 明细应清空'
|
||
);
|
||
});
|
||
});
|
||
|
||
// ------------------- submit/cancel/audit:状态流转 -------------------
|
||
|
||
describe('submit/cancel/audit 状态流转', () => {
|
||
it('无明细不允许提交(400);有明细提交后置 submitted', async () => {
|
||
const check = await createCheck();
|
||
|
||
await assert.rejects(async () => {
|
||
await submitCheck(check.id);
|
||
}, error => error.code === 400);
|
||
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
const result = await submitCheck(check.id);
|
||
|
||
assert.equal(result.status, 'submitted');
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'submitted');
|
||
});
|
||
|
||
it('submitted 状态重复提交报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await submitCheck(check.id);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('库位范围明细缺少库位(location_id/location_code 为空)不可提交', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
|
||
// 直写一条缺库位的脏数据明细(location_id/location_code 均为空)
|
||
await ctx.model.StockCheckDetail.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
scope_type: 'location',
|
||
stock_id: null,
|
||
item_code: null,
|
||
item_name: null,
|
||
spec: null,
|
||
batch_no: null,
|
||
system_quantity: 0,
|
||
location_id: null,
|
||
location_code: '',
|
||
});
|
||
|
||
await assert.rejects(async () => {
|
||
await submitCheck(check.id);
|
||
}, error => error.code === 400 && /缺少库位的盘点明细/.test(error.message));
|
||
|
||
// 清除脏数据后正常提交
|
||
await ctx.model.StockCheckDetail.destroy({
|
||
where: { check_id: check.id, location_code: '' },
|
||
});
|
||
const result = await submitCheck(check.id);
|
||
assert.equal(result.status, 'submitted');
|
||
});
|
||
|
||
it('created/submitted 状态可取消 → cancelled;cancelled 终态不可再取消', async () => {
|
||
const createdCheck = await createCheck();
|
||
const cancelledFromCreated = await cancelCheck(createdCheck.id);
|
||
assert.equal(cancelledFromCreated.status, 'cancelled');
|
||
|
||
const submittedCheck = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(submittedCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(submittedCheck.id);
|
||
const cancelledFromSubmitted = await cancelCheck(submittedCheck.id);
|
||
assert.equal(cancelledFromSubmitted.status, 'cancelled');
|
||
|
||
await assert.rejects(async () => {
|
||
await cancelCheck(submittedCheck.id);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('audit approve → approved;approved 状态再次审核报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
const result = await auditCheck(check.id, 'approve');
|
||
assert.equal(result.status, 'approved');
|
||
assert.equal((await findCheckRow(check.id)).status, 'approved');
|
||
|
||
await assert.rejects(async () => {
|
||
await auditCheck(check.id, 'approve');
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('audit reject → rejected 并写入驳回原因;驳回后可重新提交', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
const rejected = await auditCheck(check.id, 'reject', '明细商品有误,请重新盘点');
|
||
assert.equal(rejected.status, 'rejected');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'rejected');
|
||
assert.equal(row.remark, '明细商品有误,请重新盘点');
|
||
|
||
const resubmitted = await submitCheck(check.id);
|
||
assert.equal(resubmitted.status, 'submitted');
|
||
});
|
||
|
||
it('非法审核动作或非 submitted 状态审核报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await auditCheck(check.id, 'bad_action');
|
||
}, error => error.code === 400);
|
||
|
||
const createdCheck = await createCheck();
|
||
await assert.rejects(async () => {
|
||
await auditCheck(createdCheck.id, 'approve');
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('商品任务提交审核刷新明细行账面快照(提交时点账面),主表不写额外快照', async () => {
|
||
const { literal } = ctx.app.Sequelize;
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.rows.length, 1, '单库位商品应只有一条明细行');
|
||
const detail = details.rows[0];
|
||
const stockId = Number(detail.stock_id);
|
||
const spaceId = Number(detail.location_id);
|
||
|
||
// 提交前账面(口径与实现一致:SUM 可用数量)
|
||
const bookRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
stock_id: stockId,
|
||
space_id: spaceId,
|
||
is_enabled: 1,
|
||
},
|
||
attributes: [
|
||
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
|
||
],
|
||
raw: true,
|
||
});
|
||
const bookTotal = Number((bookRows[0] || {}).totalQuantity) || 0;
|
||
|
||
// 模拟提交前库存变动:一条库存行可用数量 +100(finally 恢复)
|
||
const storageRow = await ctx.model.Storage.findOne({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
stock_id: stockId,
|
||
space_id: spaceId,
|
||
is_enabled: 1,
|
||
},
|
||
raw: true,
|
||
});
|
||
assert.ok(storageRow, '前置:应存在库存行');
|
||
await ctx.model.Storage.update(
|
||
{ available_quantity: Number(storageRow.available_quantity) + 100 },
|
||
{ where: { id: storageRow.id } }
|
||
);
|
||
try {
|
||
await submitCheck(check.id);
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'submitted');
|
||
assert.equal(row.scope_snapshot, null, '主表不写额外快照(明细表已完整记录)');
|
||
|
||
const afterDetails = await detailCheck(check.id);
|
||
assert.equal(
|
||
Number(afterDetails.rows[0].system_quantity),
|
||
bookTotal + 100,
|
||
'明细行库位级账面快照应刷新为提交时账面'
|
||
);
|
||
} finally {
|
||
await ctx.model.Storage.update(
|
||
{ available_quantity: Number(storageRow.available_quantity) },
|
||
{ where: { id: storageRow.id } }
|
||
);
|
||
}
|
||
});
|
||
|
||
it('库位范围任务提交不刷新商品账面快照(明细行 system_quantity 保持 0、主表 scope_snapshot 保持 null)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
|
||
await submitCheck(check.id);
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'submitted');
|
||
assert.equal(row.scope_snapshot, null, '库位范围任务不写商品账面快照');
|
||
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(Number(details.rows[0].system_quantity), 0, '库位明细行账面快照保持 0');
|
||
});
|
||
});
|
||
|
||
// ------------------- report:盘点作业上报 -------------------
|
||
|
||
describe('report 盘点作业上报', () => {
|
||
it('实盘数量为负数或非整数报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, -1);
|
||
}, error => error.code === 400);
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 1.5);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('report 写记录表:record 字段完整(check_id/warehouse_id/detail_id/stock_id/quantity/checker/checked_at)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
|
||
const result = await reportCheck(check.id, detail.id, 7, TEST_LOCATION_CODE);
|
||
|
||
assert.equal(Number(result.detail_id), Number(detail.id), '返回的明细 ID 应一致');
|
||
assert.equal(result.total_items, 1);
|
||
assert.equal(result.checked_items, 1, '该明细存在记录应计入已盘');
|
||
assert.equal(result.detail_status, 'all_checked');
|
||
assert.ok(result.record, '应返回新增的作业记录');
|
||
|
||
assert.equal(Number(result.record.check_id), check.id, '记录应关联盘点任务');
|
||
assert.equal(Number(result.record.warehouse_id), TEST_WAREHOUSE_ID, '记录应写入固定测试仓库');
|
||
assert.equal(Number(result.record.detail_id), Number(detail.id), '记录应关联明细');
|
||
assert.equal(Number(result.record.stock_id), Number(detail.stock_id), '记录应冗余商品库存 ID');
|
||
assert.equal(Number(result.record.quantity), 7, '记录应写入实盘数量');
|
||
assert.equal(Number(result.record.checker_id), TEST_CREATOR_ID, '记录应写入盘点人 ID');
|
||
assert.equal(result.record.checker_name, TEST_CREATOR_NAME, '记录应写入盘点人名称');
|
||
assert.ok(result.record.checked_at, '记录应写入上报时间');
|
||
assert.equal(result.mode, 'created', '首次上报 mode 应为 created');
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 1, '上报一次应写入一条作业记录');
|
||
});
|
||
|
||
it('同一明细多库位多次上报:写入多条记录,明细已盘数量=合计,checked_items 只计一次', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
|
||
const firstReport = await reportCheck(check.id, firstDetail.id, 10, TEST_LOCATION_CODE);
|
||
const secondReport = await reportCheck(check.id, firstDetail.id, 5, TEST_EMPTY_LOCATION_CODE);
|
||
await reportCheck(check.id, secondDetail.id, 0);
|
||
assert.equal(firstReport.mode, 'created', '首次上报 mode 应为 created');
|
||
assert.equal(secondReport.mode, 'created', '不同库位上报应新增记录');
|
||
|
||
const firstRecords = await queryRecords(check.id, firstDetail.id);
|
||
assert.equal(firstRecords.length, 2, '同一明细不同库位两次上报应写入两条作业记录');
|
||
assert.equal(Number(firstRecords[0].quantity), 10);
|
||
assert.equal(Number(firstRecords[1].quantity), 5);
|
||
|
||
const after = await resultCheck(check.id);
|
||
const firstRow = after.rows.find(row => Number(row.id) === Number(firstDetail.id));
|
||
assert.equal(firstRow.checked_quantity, 15, '明细已盘数量应为多条记录合计');
|
||
assert.equal(firstRow.status, 'checked');
|
||
assert.deepEqual(
|
||
firstRow.location_codes,
|
||
[ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ],
|
||
'多库位编码应合并'
|
||
);
|
||
assert.equal(firstRow.records.length, 2, 'records 应包含该明细全部作业记录');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.checked_items, 2, 'checked_items 按明细去重计数,不因多记录重复累计');
|
||
assert.equal(row.detail_status, 'all_checked');
|
||
});
|
||
|
||
it('盘盈/无差异场景:按明细聚合校验 diff_quantity/is_diff,汇总 diff_items 正确', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
|
||
const firstResult = await reportCheck(
|
||
check.id,
|
||
firstDetail.id,
|
||
Number(firstDetail.system_quantity) + 5
|
||
);
|
||
assert.equal(firstResult.checked_items, 1);
|
||
assert.equal(firstResult.detail_status, 'partial_checked', '部分已盘');
|
||
|
||
const afterFirst = await resultCheck(check.id);
|
||
const firstRow = afterFirst.rows.find(row => Number(row.id) === Number(firstDetail.id));
|
||
assert.equal(firstRow.checked_quantity, Number(firstDetail.system_quantity) + 5);
|
||
assert.equal(firstRow.diff_quantity, 5, '盘盈 5');
|
||
assert.equal(firstRow.is_diff, 1, '有差异应标记 is_diff=1');
|
||
assert.equal(firstRow.status, 'checked');
|
||
|
||
const secondResult = await reportCheck(
|
||
check.id,
|
||
secondDetail.id,
|
||
Number(secondDetail.system_quantity)
|
||
);
|
||
assert.equal(secondResult.checked_items, 2);
|
||
assert.equal(secondResult.diff_items, 1);
|
||
assert.equal(secondResult.detail_status, 'all_checked', '全部已盘');
|
||
|
||
const afterSecond = await resultCheck(check.id);
|
||
const secondRow = afterSecond.rows.find(row => Number(row.id) === Number(secondDetail.id));
|
||
assert.equal(secondRow.diff_quantity, 0, '数量一致差异为 0');
|
||
assert.equal(secondRow.is_diff, 0, '无差异应标记 is_diff=0');
|
||
});
|
||
|
||
it('明细差异=已盘合计-账面快照(非单次上报数量)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
const snapshot = Number(detail.system_quantity);
|
||
|
||
// 第一次上报数量=账面快照 → 单次差异 0
|
||
await reportCheck(check.id, detail.id, snapshot, TEST_LOCATION_CODE);
|
||
const afterFirst = await resultCheck(check.id);
|
||
assert.equal(afterFirst.rows[0].checked_quantity, snapshot);
|
||
assert.equal(afterFirst.rows[0].diff_quantity, 0, '单次上报无差异');
|
||
assert.equal(afterFirst.rows[0].is_diff, 0);
|
||
|
||
// 第二次上报 5(另一库位)→ 已盘合计=账面+5,差异应按合计而非单次上报数量计算
|
||
const secondResult = await reportCheck(check.id, detail.id, 5, TEST_EMPTY_LOCATION_CODE);
|
||
assert.equal(secondResult.diff_items, 1, '按合计计算应产生 1 条差异明细');
|
||
|
||
const afterSecond = await resultCheck(check.id);
|
||
assert.equal(afterSecond.rows[0].checked_quantity, snapshot + 5, '已盘数量应为账面+5');
|
||
assert.equal(afterSecond.rows[0].diff_quantity, 5, '差异=已盘合计-账面快照');
|
||
assert.equal(afterSecond.rows[0].is_diff, 1);
|
||
});
|
||
|
||
it('首次上报将主表 approved 自动转 checking 并写 start_time(≈首个明细写入时间)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const beforeRow = await findCheckRow(check.id);
|
||
assert.equal(beforeRow.status, 'approved');
|
||
assert.equal(beforeRow.start_time, null);
|
||
|
||
const details = await detailCheck(check.id);
|
||
const beforeReport = Date.now();
|
||
await reportCheck(check.id, details.rows[0].id, 0);
|
||
const afterReport = Date.now();
|
||
|
||
const afterRow = await findCheckRow(check.id);
|
||
assert.equal(afterRow.status, 'checking', '首次上报应自动转盘点作业中');
|
||
assert.ok(afterRow.start_time, '应写入实际开始时间');
|
||
const startTs = new Date(afterRow.start_time).getTime();
|
||
assert.ok(
|
||
startTs >= beforeReport - 5000 && startTs <= afterReport + 5000,
|
||
'start_time 应≈第一个盘点明细写入时间'
|
||
);
|
||
});
|
||
|
||
it('space_id 必传:库位以 space_id 对应库位为准,编码不一致报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE);
|
||
|
||
assert.equal(result.record.location_code, TEST_LOCATION_CODE);
|
||
assert.equal(Number(result.record.location_id), TEST_LOCATION_ID, '库位编码命中应回填 location_id');
|
||
|
||
const records = await queryRecords(check.id, details.rows[0].id);
|
||
assert.equal(records.length, 1);
|
||
assert.equal(Number(records[0].location_id), TEST_LOCATION_ID, '记录表应持久化回填的 location_id');
|
||
assert.equal(records[0].location_code, TEST_LOCATION_CODE);
|
||
|
||
// 上报编码与 space_id 对应库位编码不一致 → 400(库位以 space_id 为准,不再按编码猜)
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, details.rows[0].id, 3, 'NOT_EXIST_SPACE_999', { spaceId: TEST_LOCATION_ID });
|
||
}, error => error.code === 400 && error.message.includes('库位ID不一致'));
|
||
});
|
||
|
||
it('同仓库同编码存在多条库位时:上报沿用明细固化 location_id,space 视图不产生幽灵行', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
const detailLocationId = Number(detail.location_id);
|
||
assert.ok(detailLocationId > 0, '前置:商品明细应带库位ID');
|
||
const originSpace = await ctx.model.LocationSpace.findByPk(detailLocationId, { raw: true });
|
||
assert.ok(originSpace, '前置:明细库位应存在');
|
||
|
||
// 构造同仓库同编码的历史重复库位(所属分区不存在,即无头库位)
|
||
let duplicateSpace = null;
|
||
try {
|
||
duplicateSpace = await ctx.model.LocationSpace.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
zone_id: 99999999,
|
||
location_type_id: Number(originSpace.location_type_id) || 1,
|
||
space_code: detail.location_code,
|
||
});
|
||
assert.ok(Number(duplicateSpace.id) > 0, '前置:重复库位应创建成功');
|
||
|
||
// 上报库位与明细一致 → 沿用明细固化库位,不被同编码重复库位抢走
|
||
const result = await reportCheck(check.id, detail.id, 5, detail.location_code);
|
||
assert.equal(
|
||
Number(result.record.location_id),
|
||
detailLocationId,
|
||
'同编码多条库位时应沿用明细固化 location_id'
|
||
);
|
||
|
||
// 模拟历史脏数据(记录被写成重复库位)→ space 视图应归并回有效库位,只出一行且带库位自定义字段
|
||
await ctx.model.StockCheckRecord.update(
|
||
{ location_id: Number(duplicateSpace.id) },
|
||
{ where: { check_id: check.id, detail_id: detail.id } }
|
||
);
|
||
const data = await workDataCheck(check.id);
|
||
assert.equal(data.view, 'space');
|
||
const rows = data.rows.filter(row => row.space_code === detail.location_code);
|
||
assert.equal(rows.length, 1, '同编码重复库位不应产生幽灵行');
|
||
assert.equal(Number(rows[0].id), detailLocationId, '应归并到明细固化库位');
|
||
assert.equal(rows[0].custom_name, originSpace.custom_name || null, '库位自定义名称应取有效库位行');
|
||
const item = rows[0].goods.find(goods => Number(goods.stock_id) === Number(detail.stock_id));
|
||
assert.ok(item, '归并后的库位行应包含该商品');
|
||
assert.equal(Number(item.checked_quantity), 5, '实盘数量应继续落在有效库位行上');
|
||
assert.equal(item.status, 'checked');
|
||
} finally {
|
||
if (duplicateSpace) {
|
||
await ctx.model.LocationSpace.destroy({ where: { id: duplicateSpace.id }, force: true });
|
||
}
|
||
}
|
||
});
|
||
|
||
it('space_id 必传且优先:直传库位ID按ID落库;缺失/编码不一致/跨仓库/分区已删除报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
// 1) 只传 space_id(不传 location):编码由库位行反推,记录直接用该 ID
|
||
const first = await reportCheck(check.id, detailId, 4, undefined, { spaceId: TEST_LOCATION_ID });
|
||
assert.equal(Number(first.record.location_id), TEST_LOCATION_ID, '直传 space_id 应原样落库');
|
||
assert.equal(first.record.location_code, TEST_LOCATION_CODE, '库位编码应由库位行反推');
|
||
|
||
// 2) location 与 space_id 同时传且编码一致:通过
|
||
const second = await reportCheck(check.id, detailId, 6, TEST_LOCATION_CODE, { spaceId: TEST_LOCATION_ID });
|
||
assert.equal(Number(second.record.location_id), TEST_LOCATION_ID);
|
||
assert.equal(Number(second.record.quantity), 6);
|
||
|
||
// 3) 编码与 ID 不一致:400
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 6, TEST_EMPTY_LOCATION_CODE, { spaceId: TEST_LOCATION_ID });
|
||
}, error => error.code === 400 && error.message.includes('库位ID不一致'));
|
||
|
||
// 4) 其他仓库的库位ID:400
|
||
const otherWarehouseSpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: OTHER_TEST_WAREHOUSE_ID },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
if (otherWarehouseSpace) {
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 6, undefined, { spaceId: Number(otherWarehouseSpace.id) });
|
||
}, error => error.code === 400 && error.message.includes('上报库位不存在'));
|
||
}
|
||
|
||
// 5) 无头库位(分区已删除)的ID:400
|
||
let headlessSpace = null;
|
||
try {
|
||
headlessSpace = await ctx.model.LocationSpace.create({
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
zone_id: 99999998,
|
||
location_type_id: 1,
|
||
space_code: `HD-${Date.now()}`,
|
||
});
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 6, undefined, { spaceId: Number(headlessSpace.id) });
|
||
}, error => error.code === 400 && error.message.includes('上报库位不存在'));
|
||
} finally {
|
||
if (headlessSpace) {
|
||
await ctx.model.LocationSpace.destroy({ where: { id: headlessSpace.id }, force: true });
|
||
}
|
||
}
|
||
|
||
// 6) 缺失/非法值:400(不允许退回按编码猜库位)
|
||
for (const spaceId of [ null, '', 0, -5, 'abc' ]) {
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 6, TEST_LOCATION_CODE, { spaceId });
|
||
}, error => error.code === 400 && error.message.includes('缺少库位ID'));
|
||
}
|
||
// 完全不传 space_id(直接调业务层,绕过测试辅助的自动解析)同样 400
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.report({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
detailId,
|
||
quantity: 6,
|
||
location: TEST_LOCATION_CODE,
|
||
checkerId: TEST_CREATOR_ID,
|
||
checkerName: TEST_CREATOR_NAME,
|
||
});
|
||
}, error => error.code === 400 && error.message.includes('缺少库位ID'));
|
||
});
|
||
|
||
it('实盘数量超上限报 400(不落库、不返回 500)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 6955416422066, TEST_LOCATION_CODE);
|
||
}, error => error.code === 400 && error.message.includes('实盘数量不能超过'));
|
||
|
||
const records = await queryRecords(check.id, detailId);
|
||
assert.equal(records.length, 0, '超限上报不应落库');
|
||
|
||
// 边界值本身允许
|
||
const boundary = await reportCheck(check.id, detailId, 2147483647, TEST_LOCATION_CODE);
|
||
assert.equal(Number(boundary.record.quantity), 2147483647);
|
||
});
|
||
|
||
it('上报写入操作日志:message 含库位编码/ID,before_changes 记录库位与明细库位快照', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
await reportCheck(check.id, detailId, 3, TEST_LOCATION_CODE);
|
||
|
||
const log = await ctx.model.OperationLog.findOne({
|
||
where: {
|
||
business_type: 'stock_check',
|
||
business_id: String(check.id),
|
||
operation_code: 'STOCK_CHECK_REPORT',
|
||
},
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
assert.ok(log, '应写入 STOCK_CHECK_REPORT 操作日志');
|
||
assert.ok(log.message.includes(TEST_LOCATION_CODE), 'message 应包含库位编码');
|
||
assert.ok(log.message.includes(`#${TEST_LOCATION_ID}`), 'message 应包含库位ID');
|
||
assert.ok(log.before_changes, 'before_changes 应落库');
|
||
const changes = typeof log.before_changes === 'string'
|
||
? JSON.parse(log.before_changes)
|
||
: log.before_changes;
|
||
assert.equal(changes.detail_id, Number(detailId));
|
||
assert.equal(changes.location_code, TEST_LOCATION_CODE);
|
||
assert.equal(changes.location_id, TEST_LOCATION_ID);
|
||
assert.equal(changes.quantity, 3);
|
||
assert.equal(changes.mode, 'created');
|
||
});
|
||
|
||
it('非 approved/checking 状态上报报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
|
||
const details = await detailCheck(check.id);
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, details.rows[0].id, 1);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('同明细同库位重复上报:记录仍 1 条、数量为最新值、mode=updated', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
const first = await reportCheck(check.id, detailId, 7, TEST_LOCATION_CODE);
|
||
assert.equal(first.mode, 'created', '首次上报 mode 应为 created');
|
||
|
||
const second = await reportCheck(check.id, detailId, 9, TEST_LOCATION_CODE);
|
||
assert.equal(second.mode, 'updated', '同库位重复上报 mode 应为 updated');
|
||
assert.equal(Number(second.record.id), Number(first.record.id), '应更新同一条记录');
|
||
assert.equal(Number(second.record.quantity), 9, '记录数量应为最新值');
|
||
assert.equal(Number(second.record.checker_id), TEST_CREATOR_ID, '盘点人应更新为最新上报人');
|
||
|
||
const records = await queryRecords(check.id, detailId);
|
||
assert.equal(records.length, 1, '同明细同库位只保留一条记录');
|
||
assert.equal(Number(records[0].quantity), 9, '库内记录数量应为最新值');
|
||
assert.equal(records[0].location_code, TEST_LOCATION_CODE);
|
||
|
||
const after = await resultCheck(check.id);
|
||
assert.equal(after.rows[0].checked_quantity, 9, '已盘数量应为最新值而非两次之和');
|
||
assert.equal(after.rows[0].records.length, 1);
|
||
});
|
||
|
||
it('同明细跨库位:不同库位新增、同库位覆盖更新,已盘=各库位最新值合计', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
const created = await reportCheck(check.id, detailId, 10, TEST_LOCATION_CODE);
|
||
assert.equal(created.mode, 'created');
|
||
const updated = await reportCheck(check.id, detailId, 12, TEST_LOCATION_CODE);
|
||
assert.equal(updated.mode, 'updated', '同库位重复上报应覆盖更新');
|
||
const otherLocation = await reportCheck(check.id, detailId, 5, TEST_EMPTY_LOCATION_CODE);
|
||
assert.equal(otherLocation.mode, 'created', '不同库位应新增记录');
|
||
|
||
const records = await queryRecords(check.id, detailId);
|
||
assert.equal(records.length, 2, '两个库位各保留一条记录');
|
||
const quantityByCode = new Map(records.map(record => [ record.location_code, Number(record.quantity) ]));
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE), 12, '同库位保留最新值');
|
||
assert.equal(quantityByCode.get(TEST_EMPTY_LOCATION_CODE), 5);
|
||
|
||
const after = await resultCheck(check.id);
|
||
assert.equal(after.rows[0].checked_quantity, 17, '已盘数量=各库位最新值合计');
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.checked_items, 1, 'checked_items 按明细去重不重复累计');
|
||
});
|
||
|
||
it('space_id 必传:未携带库位ID上报报 400;历史无库位记录(location_code=空串)仍可查询归一为 null', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
const detailId = detail.id;
|
||
|
||
// 1) 不传 space_id → 400(不再有"无库位上报"通道)
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detailId, 8, undefined, { spaceId: 0 });
|
||
}, error => error.code === 400 && error.message.includes('缺少库位ID'));
|
||
|
||
// 2) 历史脏数据(location_code 空串)仍可查询:recordList 空串归一为 null
|
||
const legacy = await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detailId,
|
||
stock_id: Number(detail.stock_id),
|
||
location_id: null,
|
||
location_code: '',
|
||
quantity: 8,
|
||
is_empty: false,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
assert.ok(Number(legacy.id) > 0, '前置:历史无库位记录应写入成功');
|
||
|
||
const listed = await listRecords({ id: check.id, detailId });
|
||
assert.equal(listed.total, 1);
|
||
assert.equal(listed.rows[0].location_code, null, '接口返回无库位记录 location_code 应为 null');
|
||
});
|
||
|
||
it('唯一索引加固:同明细同库位连续上报 DB 记录总数恒为 1', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
// 同库位连续三次上报:覆盖式语义下 DB 只保留 1 条记录
|
||
await reportCheck(check.id, detailId, 10, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, detailId, 11, TEST_LOCATION_CODE);
|
||
const last = await reportCheck(check.id, detailId, 12, TEST_LOCATION_CODE);
|
||
assert.equal(last.mode, 'updated', '第三次同库位上报应为覆盖更新');
|
||
|
||
// 另一库位再报一次:新增 1 条(共 2 条)
|
||
await reportCheck(check.id, detailId, 4, TEST_EMPTY_LOCATION_CODE);
|
||
|
||
const records = await queryRecords(check.id, detailId);
|
||
assert.equal(records.length, 2, '两个库位各 1 条记录');
|
||
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({
|
||
where: { detail_id: detailId, location_code: TEST_LOCATION_CODE },
|
||
}),
|
||
1,
|
||
'同库位分组记录数恒为 1(唯一索引生效)'
|
||
);
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({
|
||
where: { detail_id: detailId, location_code: null },
|
||
}),
|
||
0,
|
||
'库中不应存在 location_code 为 NULL 的记录'
|
||
);
|
||
});
|
||
|
||
it('唯一索引 DB 层验证:重复 (detail_id, stock_id, location_code) 直接插入被拒绝', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
|
||
// 业务链路先写入一条有库位记录,再直接插入同组记录 → 触发唯一约束错误
|
||
await reportCheck(check.id, detail.id, 7, TEST_LOCATION_CODE);
|
||
await assert.rejects(async () => {
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: detail.stock_id,
|
||
location_id: TEST_LOCATION_ID,
|
||
location_code: TEST_LOCATION_CODE,
|
||
quantity: 99,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
}, error => error.name === 'SequelizeUniqueConstraintError');
|
||
|
||
// 历史无库位(空串)分组同样受唯一索引约束
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: detail.stock_id,
|
||
location_id: null,
|
||
location_code: '',
|
||
quantity: 3,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
await assert.rejects(async () => {
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: detail.stock_id,
|
||
location_id: null,
|
||
location_code: '',
|
||
quantity: 88,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
}, error => error.name === 'SequelizeUniqueConstraintError');
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 2, '被唯一索引拒绝的插入不应落库');
|
||
});
|
||
});
|
||
|
||
// ------------------- report:库位行与商品行 stock_id 维度校验 -------------------
|
||
|
||
describe('report 库位行与商品行 stock_id 维度校验', () => {
|
||
it('库位行缺 stock_id 报 400', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 1);
|
||
}, error => error.code === 400 && /必须指定商品/.test(error.message));
|
||
});
|
||
|
||
it('库位行商品非本仓库报 400', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const foreignStock = await fetchOtherWarehouseStockRow();
|
||
assert.ok(foreignStock, '应存在其他仓库商品用于跨仓库隔离校验');
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 1, undefined, { stockId: foreignStock.id });
|
||
}, error => error.code === 400 && /不属于本仓库/.test(error.message));
|
||
});
|
||
|
||
it('库位行上报库位与明细库位不一致报 400', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const otherSpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_EMPTY_LOCATION_CODE },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
assert.ok(otherSpace, '前置:另一有效库位应存在');
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 1, TEST_EMPTY_LOCATION_CODE, {
|
||
stockId: stocks[0].id,
|
||
spaceId: Number(otherSpace.id),
|
||
});
|
||
}, error => error.code === 400 && /库位与盘点明细库位不一致/.test(error.message));
|
||
});
|
||
|
||
it('库位行正常上报:record 含 stock_id、库位以明细为准,覆盖式按 (detail,stock,location) 更新', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const stockId = stocks[0].id;
|
||
|
||
const first = await reportCheck(check.id, detail.id, 5, TEST_LOCATION_CODE, { stockId });
|
||
assert.equal(first.mode, 'created');
|
||
assert.equal(Number(first.record.stock_id), stockId, '记录应写入上报商品 ID');
|
||
assert.equal(first.record.location_code, TEST_LOCATION_CODE, '库位应以明细库位为准');
|
||
assert.equal(Number(first.record.location_id), TEST_LOCATION_ID, '库位 ID 应取明细库位');
|
||
assert.equal(first.checked_items, 1);
|
||
assert.equal(first.detail_status, 'all_checked');
|
||
|
||
// 同明细 + 同商品 + 同库位(未传库位同样以明细库位为准)→ 覆盖更新
|
||
const second = await reportCheck(check.id, detail.id, 9, undefined, { stockId });
|
||
assert.equal(second.mode, 'updated', '同 (detail,stock,location) 应覆盖更新');
|
||
assert.equal(Number(second.record.id), Number(first.record.id), '应更新同一条记录');
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 1);
|
||
assert.equal(Number(records[0].quantity), 9);
|
||
assert.equal(Number(records[0].stock_id), stockId);
|
||
});
|
||
|
||
it('商品行上报 stock_id 与明细商品不一致报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, details.rows[0].id, 1, undefined, { stockId: stocks[1].id });
|
||
}, error => error.code === 400 && /上报商品与盘点明细商品不一致/.test(error.message));
|
||
});
|
||
|
||
it('同库位行多商品上报:记录按 (detail,stock,location) 各自落库,不撞唯一索引', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 2);
|
||
assert.ok(stockIds.length >= 2, '固定测试库位应存在至少两个商品库存(真实数据依赖)');
|
||
|
||
const first = await reportCheck(check.id, detail.id, 3, undefined, { stockId: stockIds[0] });
|
||
assert.equal(first.mode, 'created');
|
||
const second = await reportCheck(check.id, detail.id, 4, undefined, { stockId: stockIds[1] });
|
||
assert.equal(second.mode, 'created', '不同商品应新增记录而非覆盖');
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 2, '同库位行多商品应各保留一条记录(uk_detail_stock_location 生效)');
|
||
for (const record of records) {
|
||
assert.equal(record.location_code, TEST_LOCATION_CODE);
|
||
}
|
||
|
||
// 覆盖式:同商品再报更新原记录,记录数不变
|
||
const updated = await reportCheck(check.id, detail.id, 7, undefined, { stockId: stockIds[0] });
|
||
assert.equal(updated.mode, 'updated');
|
||
const after = await queryRecords(check.id, detail.id);
|
||
assert.equal(after.length, 2, '覆盖更新后记录数不变');
|
||
const updatedRecord = after.find(record => Number(record.stock_id) === stockIds[0]);
|
||
assert.equal(Number(updatedRecord.quantity), 7);
|
||
});
|
||
});
|
||
|
||
// ------------------- recordDelete:删除作业记录 -------------------
|
||
|
||
describe('recordDelete 删除作业记录', () => {
|
||
it('删除后汇总回退:明细回到未盘、detail_status=未盘,主表状态不回退', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 5, TEST_LOCATION_CODE);
|
||
const beforeRow = await findCheckRow(check.id);
|
||
assert.equal(beforeRow.status, 'checking');
|
||
assert.equal(beforeRow.checked_items, 1);
|
||
|
||
const records = await queryRecords(check.id, details.rows[0].id);
|
||
assert.equal(records.length, 1);
|
||
|
||
const result = await deleteRecord(check.id, records[0].id);
|
||
|
||
assert.equal(result.deleted_count, 1, '应标记删除 1 条');
|
||
assert.deepEqual(result.deleted_ids.map(Number), [ Number(records[0].id) ]);
|
||
assert.deepEqual(result.skipped_ids, []);
|
||
assert.equal(result.total_items, 2);
|
||
assert.equal(result.checked_items, 0, '删除后已盘明细回退为 0');
|
||
assert.equal(result.diff_items, 0);
|
||
assert.equal(result.detail_status, 'none_checked', '明细记录删光回到未盘');
|
||
|
||
const remaining = await queryRecords(check.id, details.rows[0].id);
|
||
assert.equal(remaining.length, 0, '记录应被删除');
|
||
|
||
const afterRow = await findCheckRow(check.id);
|
||
assert.equal(afterRow.status, 'checking', '主表状态不回退');
|
||
assert.equal(afterRow.checked_items, 0);
|
||
assert.equal(afterRow.detail_status, 'none_checked');
|
||
|
||
const after = await resultCheck(check.id);
|
||
const targetRow = after.rows.find(row => Number(row.id) === Number(details.rows[0].id));
|
||
assert.ok(targetRow, '记录删光后应返回明细范围行');
|
||
assert.equal(targetRow.scope_type, 'goods');
|
||
assert.ok(Number(targetRow.system_quantity) >= 0, '明细行应含账面快照');
|
||
});
|
||
|
||
it('非 approved/checking 状态删除报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
|
||
await assert.rejects(async () => {
|
||
await deleteRecord(check.id, 999999999);
|
||
}, error => error.code === 400);
|
||
});
|
||
|
||
it('作业记录不属于该盘点任务计入 skipped_ids 不报错(批量口径)', async () => {
|
||
const checkA = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(checkA.id, [ stocks[0].id ]);
|
||
await submitCheck(checkA.id);
|
||
await auditCheck(checkA.id, 'approve');
|
||
const detailsA = await detailCheck(checkA.id);
|
||
const reportResult = await reportCheck(checkA.id, detailsA.rows[0].id, 3, TEST_LOCATION_CODE);
|
||
|
||
const checkB = await createCheck();
|
||
await addDetail(checkB.id, [ stocks[0].id ]);
|
||
await submitCheck(checkB.id);
|
||
await auditCheck(checkB.id, 'approve');
|
||
|
||
const result = await ctx.service.systems.stockCheck.recordDelete({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkB.id,
|
||
recordIds: [ reportResult.record.id ],
|
||
});
|
||
assert.equal(result.deleted_count, 0);
|
||
assert.deepEqual(result.deleted_ids, []);
|
||
assert.deepEqual(result.skipped_ids.map(Number), [ Number(reportResult.record.id) ], '不属于该任务的记录应计入 skipped_ids');
|
||
});
|
||
});
|
||
|
||
// ------------------- recheckClearLocation:重盘清除库位 -------------------
|
||
|
||
describe('recheckClearLocation 重盘清除库位(按库位清除盘点信息)', () => {
|
||
it('清除库位记录:记录清空、汇总回退、库位回到未盘(含空库位标记一并清除)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
const stocks = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
await reportCheck(check.id, detailId, 5, undefined, { stockId: stocks[0] });
|
||
// 覆盖为空标记
|
||
await reportCheck(check.id, detailId, 0, undefined, { is_empty: true });
|
||
assert.equal((await queryRecords(check.id, detailId)).length, 1, '前置:空标记记录存在');
|
||
|
||
const result = await ctx.service.systems.stockCheck.recheckClearLocation({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
|
||
assert.equal(Number(result.detail_id), Number(detailId));
|
||
assert.equal(result.location_id, TEST_LOCATION_ID);
|
||
assert.equal(result.deleted_count, 1, '应清除该库位全部记录(含空标记)');
|
||
assert.equal(result.checked_items, 0, '清除后已盘回退为 0');
|
||
assert.equal(result.detail_status, 'none_checked');
|
||
|
||
assert.equal((await queryRecords(check.id, detailId)).length, 0, '记录应被清空');
|
||
const data = await workDataCheck(check.id);
|
||
const row = data.rows[0];
|
||
assert.equal(row.status, 'unchecked', '库位回到未盘');
|
||
assert.equal(row.is_empty, false, '空标记一并清除');
|
||
assert.deepEqual(row.goods, []);
|
||
});
|
||
|
||
it('非库位任务(商品任务)→ 400 仅库位盘点任务支持重盘清除库位', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.recheckClearLocation({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
}, error => error.code === 400 && /仅库位盘点任务支持重盘清除库位/.test(error.message));
|
||
});
|
||
|
||
it('库位不在任务范围 → 400 该库位不在盘点任务范围内', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.recheckClearLocation({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
}, error => error.code === 400 && /该库位不在盘点任务范围内/.test(error.message));
|
||
});
|
||
|
||
it('状态不允许(created)→ 400 当前状态不允许清除库位盘点信息', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.recheckClearLocation({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
}, error => error.code === 400 && /不允许清除库位盘点信息/.test(error.message));
|
||
});
|
||
|
||
it('方法层:location_id/locationId 兼容 + success 包装 + 非库位任务 failure 400', async () => {
|
||
ctx.user = { id: TEST_CREATOR_ID, store_id: TEST_WAREHOUSE_ID, employees_name: TEST_CREATOR_NAME };
|
||
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const emptySpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_EMPTY_LOCATION_CODE },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
const emptyLocationId = Number(emptySpace.id);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.recheckClearLocation({
|
||
id: check.id,
|
||
location_id: emptyLocationId,
|
||
});
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.deleted_count, 0, '未盘库位清除记录数应为 0');
|
||
assert.equal(result.data.location_id, emptyLocationId);
|
||
|
||
const goodsCheck = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(goodsCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(goodsCheck.id);
|
||
await auditCheck(goodsCheck.id, 'approve');
|
||
const failure = await ctx.service.systemMethods.stock.check.recheckClearLocation({
|
||
id: goodsCheck.id,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
assert.equal(failure.flag, 'failure');
|
||
assert.equal(failure.code, 400);
|
||
assert.match(failure.message, /仅库位盘点任务支持重盘清除库位/);
|
||
});
|
||
});
|
||
|
||
// ------------------- recordList:查询作业记录 -------------------
|
||
|
||
describe('recordList 查询作业记录', () => {
|
||
it('按任务查询:返回全字段+item_code/item_name,按 id 倒序', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, details.rows[1].id, 4);
|
||
|
||
const result = await listRecords({ id: check.id });
|
||
|
||
assert.equal(result.total, 2);
|
||
assert.equal(result.rows.length, 2);
|
||
assert.equal(result.page, 1);
|
||
assert.equal(result.pageSize, 20);
|
||
assert.ok(Number(result.rows[0].id) > Number(result.rows[1].id), '应按记录 id 倒序');
|
||
for (const row of result.rows) {
|
||
assert.equal(Number(row.check_id), check.id, '记录应关联盘点任务');
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, '记录应限定固定测试仓库');
|
||
assert.ok(row.detail_id, '记录应含明细 ID');
|
||
assert.ok(row.stock_id, '记录应含库存商品 ID');
|
||
assert.ok(row.checked_at, '记录应含上报时间');
|
||
assert.ok(row.item_code, '记录应回填商品编码');
|
||
assert.ok(row.item_name, '记录应回填商品名称');
|
||
}
|
||
});
|
||
|
||
it('按明细查询:仅返回该明细的记录,仅传 detail_id 也可查', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
await reportCheck(check.id, firstDetail.id, 3, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, details.rows[1].id, 4);
|
||
|
||
const byTaskAndDetail = await listRecords({ id: check.id, detailId: firstDetail.id });
|
||
assert.equal(byTaskAndDetail.total, 1, '只返回该明细的记录');
|
||
assert.equal(Number(byTaskAndDetail.rows[0].detail_id), Number(firstDetail.id));
|
||
assert.equal(Number(byTaskAndDetail.rows[0].quantity), 3);
|
||
assert.equal(byTaskAndDetail.rows[0].item_code, firstDetail.item_code);
|
||
|
||
const byDetailOnly = await listRecords({ detailId: firstDetail.id });
|
||
assert.equal(byDetailOnly.total, 1, '仅传 detail_id 应可查询');
|
||
assert.equal(Number(byDetailOnly.rows[0].detail_id), Number(firstDetail.id));
|
||
});
|
||
|
||
it('分页:total 为全量,按页返回且两页无交集', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
const reportLocations = await fetchValidLocations(3);
|
||
assert.equal(reportLocations.length, 3, '前置:测试仓库应有 3 个有效库位');
|
||
await reportCheck(check.id, detailId, 1, reportLocations[0].space_code, { spaceId: reportLocations[0].id });
|
||
await reportCheck(check.id, detailId, 2, reportLocations[1].space_code, { spaceId: reportLocations[1].id });
|
||
await reportCheck(check.id, detailId, 3, reportLocations[2].space_code, { spaceId: reportLocations[2].id });
|
||
|
||
const firstPage = await listRecords({
|
||
id: check.id,
|
||
pagination: { page: 1, pageSize: 2 },
|
||
});
|
||
assert.equal(firstPage.total, 3);
|
||
assert.equal(firstPage.rows.length, 2);
|
||
assert.equal(firstPage.page, 1);
|
||
assert.equal(firstPage.pageSize, 2);
|
||
|
||
const secondPage = await listRecords({
|
||
id: check.id,
|
||
pagination: { page: 2, pageSize: 2 },
|
||
});
|
||
assert.equal(secondPage.total, 3);
|
||
assert.equal(secondPage.rows.length, 1);
|
||
|
||
const firstPageIds = firstPage.rows.map(row => Number(row.id));
|
||
const secondPageIds = secondPage.rows.map(row => Number(row.id));
|
||
for (const firstId of firstPageIds) {
|
||
assert.ok(!secondPageIds.includes(firstId), '两页记录不应重复');
|
||
for (const secondId of secondPageIds) {
|
||
assert.ok(firstId > secondId, '倒序分页:第一页记录 id 应大于第二页');
|
||
}
|
||
}
|
||
});
|
||
|
||
it('id 与 detail_id 均未传报 400', async () => {
|
||
await assert.rejects(async () => {
|
||
await listRecords({});
|
||
}, error => error.code === 400);
|
||
});
|
||
});
|
||
|
||
// ------------------- finish:完成盘点 -------------------
|
||
|
||
describe('finish 完成盘点', () => {
|
||
it('存在未盘明细不再拦截:未盘按实盘 0 计盘亏,返回 unchecked_items', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const checkedDetail = details.rows[0];
|
||
const uncheckedDetail = details.rows[1];
|
||
await reportCheck(check.id, checkedDetail.id, Number(checkedDetail.system_quantity) + 2);
|
||
|
||
const result = await finishCheck(check.id);
|
||
|
||
assert.equal(result.status, 'completed');
|
||
assert.equal(result.total_items, 2);
|
||
assert.equal(result.checked_items, 1);
|
||
assert.equal(result.unchecked_items, 1, '未盘明细数应为 1');
|
||
assert.equal(result.profit_total, 2, '已盘明细盘盈 2');
|
||
assert.equal(
|
||
result.loss_total,
|
||
Number(uncheckedDetail.system_quantity),
|
||
'未盘明细按实盘 0 处理,盘亏=账面快照'
|
||
);
|
||
assert.equal(result.diff_items, 2, '盘盈 1 条 + 未盘盘亏 1 条');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'completed');
|
||
assert.equal(row.detail_status, 'all_checked');
|
||
assert.equal(row.checked_items, 1);
|
||
assert.equal(row.diff_items, 2);
|
||
assert.ok(row.end_time, '完成盘点应写入 end_time');
|
||
});
|
||
|
||
it('全部已盘 → completed + end_time,盘盈盘亏汇总正确', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
await reportCheck(check.id, firstDetail.id, Number(firstDetail.system_quantity) + 5);
|
||
await reportCheck(check.id, secondDetail.id, Number(secondDetail.system_quantity) - 3);
|
||
|
||
const beforeFinish = Date.now();
|
||
const result = await finishCheck(check.id);
|
||
const afterFinish = Date.now();
|
||
|
||
assert.equal(result.status, 'completed');
|
||
assert.equal(result.total_items, 2);
|
||
assert.equal(result.checked_items, 2);
|
||
assert.equal(result.diff_items, 2);
|
||
assert.equal(result.unchecked_items, 0, '全部已盘时未盘明细数应为 0');
|
||
assert.equal(result.profit_total, 5, '盘盈合计应为 5');
|
||
assert.equal(result.loss_total, 3, '盘亏合计应为 3');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'completed');
|
||
assert.equal(row.detail_status, 'all_checked');
|
||
assert.ok(row.end_time, '完成盘点应写入 end_time');
|
||
const endTs = new Date(row.end_time).getTime();
|
||
assert.ok(
|
||
endTs >= beforeFinish - 5000 && endTs <= afterFinish + 5000,
|
||
'end_time 应≈完成盘点时间'
|
||
);
|
||
});
|
||
});
|
||
|
||
// ------------------- 汇总/差异:库位行口径 -------------------
|
||
|
||
describe('汇总/差异 库位行口径', () => {
|
||
it('库位行差异口径:任一商品实盘≠账面即该行有差异,diff_items 按明细去重', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 2);
|
||
assert.ok(stockIds.length >= 2, '固定测试库位应存在至少两个商品库存(真实数据依赖)');
|
||
const bookMap = await fetchStorageQuantity(TEST_LOCATION_ID, stockIds);
|
||
const bookA = Number(bookMap.get(stockIds[0]) || 0);
|
||
|
||
// 实盘=账面 → 无差异
|
||
const first = await reportCheck(check.id, detail.id, bookA, undefined, { stockId: stockIds[0] });
|
||
assert.equal(first.diff_items, 0, '实盘=账面应无差异');
|
||
assert.equal(first.detail_status, 'all_checked');
|
||
|
||
// 实盘=账面+3 → 该行有差异(行内任一商品差异即整行差异)
|
||
const second = await reportCheck(check.id, detail.id, bookA + 3, undefined, { stockId: stockIds[0] });
|
||
assert.equal(second.diff_items, 1);
|
||
assert.equal(second.checked_items, 1, 'checked_items 按明细去重不重复累计');
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
assert.equal(row.is_diff, 1);
|
||
assert.equal(row.stocks[0].diff_quantity, 3);
|
||
});
|
||
|
||
it('finish 库位行按商品聚合 vs wms_storage 计算盘盈盘亏,未盘库位行不计差异', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
const emptySpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_EMPTY_LOCATION_CODE },
|
||
raw: true,
|
||
});
|
||
assert.ok(emptySpace, `空库位编码不存在(${TEST_EMPTY_LOCATION_CODE})`);
|
||
assert.equal(
|
||
await ctx.model.Storage.count({ where: { space_id: Number(emptySpace.id) } }),
|
||
0,
|
||
'测试用空库位应无库存记录'
|
||
);
|
||
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 2);
|
||
assert.ok(stockIds.length >= 2, '固定测试库位应存在至少两个商品库存(真实数据依赖)');
|
||
const bookMap = await fetchStorageQuantity(TEST_LOCATION_ID, stockIds);
|
||
const bookA = Number(bookMap.get(stockIds[0]) || 0);
|
||
const bookB = Number(bookMap.get(stockIds[1]) || 0);
|
||
assert.ok(bookB >= 2, '库位行盘亏用例要求第二商品账面≥2(真实数据不满足时需调整固定库位)');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const checkedDetail = details.rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, checkedDetail.id, bookA + 5, undefined, { stockId: stockIds[0] });
|
||
await reportCheck(check.id, checkedDetail.id, bookB - 2, undefined, { stockId: stockIds[1] });
|
||
|
||
const result = await finishCheck(check.id);
|
||
|
||
assert.equal(result.status, 'completed');
|
||
assert.equal(result.total_items, 2);
|
||
assert.equal(result.checked_items, 1, '仅固定测试库位行已盘');
|
||
assert.equal(result.unchecked_items, 1, '未盘空库位行计入未盘');
|
||
assert.equal(result.diff_items, 1, '库位行差异按明细去重计数');
|
||
assert.equal(result.profit_total, 5, '盘盈合计=商品A +5');
|
||
assert.equal(result.loss_total, 2, '盘亏合计=商品B -2');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'completed');
|
||
assert.equal(row.diff_items, 1);
|
||
assert.ok(row.end_time, '完成盘点应写入 end_time');
|
||
});
|
||
});
|
||
|
||
// ------------------- list:列表查询 -------------------
|
||
|
||
describe('list 列表查询', () => {
|
||
it('status 单值筛选:仅返回指定状态的任务', async () => {
|
||
const createdCheck = await createCheck();
|
||
const submittedCheck = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(submittedCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(submittedCheck.id);
|
||
|
||
const result = await listChecks({ status: 'submitted' });
|
||
|
||
assert.ok(Array.isArray(result.rows));
|
||
assert.ok(result.rows.length > 0);
|
||
for (const row of result.rows) {
|
||
assert.equal(row.status, 'submitted', '筛选结果只能包含 submitted 状态');
|
||
}
|
||
const ids = result.rows.map(row => row.id);
|
||
assert.ok(ids.includes(submittedCheck.id), '应包含本次提交的任务');
|
||
assert.ok(!ids.includes(createdCheck.id), 'created 任务不应出现在 submitted 筛选结果中');
|
||
});
|
||
|
||
it('status 数组筛选:created/submitted 均可命中', async () => {
|
||
const createdCheck = await createCheck();
|
||
const submittedCheck = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(submittedCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(submittedCheck.id);
|
||
|
||
const result = await listChecks({ status: [ 'created', 'submitted' ] });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(createdCheck.id), 'created 任务应命中数组筛选');
|
||
assert.ok(ids.includes(submittedCheck.id), 'submitted 任务应命中数组筛选');
|
||
for (const row of result.rows) {
|
||
assert.ok([ 'created', 'submitted' ].includes(row.status), `非法状态出现在筛选结果: ${row.status}`);
|
||
}
|
||
});
|
||
|
||
it('store_id 货主筛选:只返回固定测试货主的任务', async () => {
|
||
const storeCheck = await createCheck({
|
||
type: 'store',
|
||
storeId: TEST_STORE_ID,
|
||
title: uniqueTitle('货主筛选'),
|
||
});
|
||
|
||
const result = await listChecks({ storeId: TEST_STORE_ID });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(storeCheck.id), '固定测试货主的任务应命中筛选');
|
||
for (const row of result.rows) {
|
||
assert.equal(Number(row.store_id), TEST_STORE_ID, '筛选结果只能包含固定测试货主');
|
||
}
|
||
});
|
||
|
||
it('list 返回 store_name:store 类型任务(store_id=1000000)取合约备注,无合约回退公司全称', async () => {
|
||
const storeCheck = await createCheck({
|
||
type: 'store',
|
||
storeId: TEST_STORE_ID,
|
||
title: uniqueTitle('store_name合约备注'),
|
||
});
|
||
|
||
const result = await listChecks({ keyword: storeCheck.title });
|
||
const row = result.rows.find(item => item.id === storeCheck.id);
|
||
|
||
assert.ok(row, '本次创建的任务应出现在 keyword 查询结果中');
|
||
assert.ok(Object.prototype.hasOwnProperty.call(row, 'store_name'), 'rows 每条应包含 store_name 字段');
|
||
assert.equal(typeof row.store_name, 'string', 'store_name 应为字符串');
|
||
assert.ok(row.store_name.length > 0, 'store_id=1000000 的任务 store_name 不应为空');
|
||
|
||
// 与实现口径对齐:优先合约表 store_remask,无合约/备注为空时回退公司全称
|
||
const contractRow = await ctx.model.StoreWarehouse.findOne({
|
||
where: { store_id: TEST_STORE_ID, warehouse_id: TEST_WAREHOUSE_ID },
|
||
attributes: [ 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
if (contractRow && contractRow.store_remask) {
|
||
assert.equal(row.store_name, contractRow.store_remask, '有合约备注时应与 wms_store_warehouse.store_remask 一致');
|
||
} else {
|
||
const storeRow = await ctx.model.Store.findOne({
|
||
where: { id: TEST_STORE_ID },
|
||
attributes: [ 'company_name' ],
|
||
raw: true,
|
||
});
|
||
assert.ok(storeRow && storeRow.company_name, '无合约备注时 wms_store.company_name 应存在且非空(否则无法兜底)');
|
||
assert.equal(row.store_name, storeRow.company_name, '无合约备注时应回退 wms_store.company_name');
|
||
}
|
||
});
|
||
|
||
it('list 返回 store_name 空串:type=location 任务 store_id 为空', async () => {
|
||
const allCheck = await createCheck({ type: 'location', title: uniqueTitle('store_name空串全盘') });
|
||
const mainRow = await findCheckRow(allCheck.id);
|
||
assert.ok(mainRow.store_id === null || mainRow.store_id === undefined || mainRow.store_id === 0 || mainRow.store_id === '',
|
||
'库位任务 store_id 应为空');
|
||
|
||
const result = await listChecks({ keyword: allCheck.title });
|
||
const row = result.rows.find(item => item.id === allCheck.id);
|
||
|
||
assert.ok(row, '本次创建的任务应出现在 keyword 查询结果中');
|
||
assert.ok(Object.prototype.hasOwnProperty.call(row, 'store_name'), 'rows 每条应包含 store_name 字段');
|
||
assert.equal(row.store_name, '', 'store_id 为空的任务 store_name 应为空字符串');
|
||
});
|
||
|
||
it('store_id 筛选 + store_name 组合正确:仅返回该货主任务且名称一致', async () => {
|
||
const prefix = uniqueTitle('store_name组合筛选');
|
||
const storeCheck = await createCheck({ type: 'store', storeId: TEST_STORE_ID, title: `${prefix}-store` });
|
||
const goodsCheck = await createCheck({ title: `${prefix}-goods` });
|
||
|
||
const result = await listChecks({ storeId: TEST_STORE_ID, keyword: prefix });
|
||
const ids = result.rows.map(item => item.id);
|
||
|
||
assert.ok(ids.includes(storeCheck.id), 'store 类型任务应命中 store_id 筛选');
|
||
assert.ok(!ids.includes(goodsCheck.id), 'store_id 为空的商品任务不应命中 store_id 筛选');
|
||
|
||
const contractRow = await ctx.model.StoreWarehouse.findOne({
|
||
where: { store_id: TEST_STORE_ID, warehouse_id: TEST_WAREHOUSE_ID },
|
||
attributes: [ 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
const fallbackRow = contractRow && contractRow.store_remask
|
||
? null
|
||
: await ctx.model.Store.findOne({
|
||
where: { id: TEST_STORE_ID },
|
||
attributes: [ 'company_name' ],
|
||
raw: true,
|
||
});
|
||
const expectedName = (contractRow && contractRow.store_remask) || (fallbackRow && fallbackRow.company_name) || '';
|
||
|
||
for (const row of result.rows) {
|
||
assert.equal(Number(row.store_id), TEST_STORE_ID, 'store_id 筛选结果只能包含固定测试货主');
|
||
assert.equal(row.store_name, expectedName, '筛选行 store_name 应与合约备注(或公司全称兜底)一致');
|
||
}
|
||
const target = result.rows.find(item => item.id === storeCheck.id);
|
||
assert.ok(target, '本次创建的任务应出现在 store_id 筛选结果中');
|
||
assert.ok(target.store_name.length > 0, '固定测试货主的 store_name 不应为空');
|
||
});
|
||
|
||
it('分页 total 正确:keyword 限定范围后按页返回', async () => {
|
||
const prefix = uniqueTitle('分页测试');
|
||
await createCheck({ title: `${prefix}-1` });
|
||
await createCheck({ title: `${prefix}-2` });
|
||
await createCheck({ title: `${prefix}-3` });
|
||
|
||
const firstPage = await listChecks({
|
||
keyword: prefix,
|
||
pagination: { page: 1, pageSize: 2 },
|
||
});
|
||
assert.equal(firstPage.total, 3, 'total 应为关键词命中的全部 3 条');
|
||
assert.equal(firstPage.rows.length, 2, '第一页应返回 2 条');
|
||
|
||
const secondPage = await listChecks({
|
||
keyword: prefix,
|
||
pagination: { page: 2, pageSize: 2 },
|
||
});
|
||
assert.equal(secondPage.total, 3);
|
||
assert.equal(secondPage.rows.length, 1, '第二页应返回 1 条');
|
||
});
|
||
|
||
it('type 单值筛选:location 与 goods 任务并存时只返回 location', async () => {
|
||
const locationCheck = await createCheck({ type: 'location' });
|
||
const goodsCheck = await createCheck();
|
||
|
||
const result = await listChecks({ type: 'location' });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(locationCheck.id), 'location 任务应命中 type=location');
|
||
assert.ok(!ids.includes(goodsCheck.id), 'goods 任务不应命中 type=location');
|
||
for (const row of result.rows) {
|
||
assert.equal(row.type, 'location', '筛选结果只能包含 location 任务');
|
||
}
|
||
});
|
||
|
||
it('type 数组筛选 in:命中仅限传入类型(store 不混入 location/goods)', async () => {
|
||
const locationCheck = await createCheck({ type: 'location' });
|
||
const goodsCheck = await createCheck();
|
||
const storeCheck = await createCheck({ type: 'store', storeId: TEST_STORE_ID });
|
||
|
||
const result = await listChecks({ type: [ 'location', 'goods' ] });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(locationCheck.id), 'location 任务应命中数组筛选');
|
||
assert.ok(ids.includes(goodsCheck.id), 'goods 任务应命中数组筛选');
|
||
assert.ok(!ids.includes(storeCheck.id), 'store 任务不应命中 location/goods 数组筛选');
|
||
for (const row of result.rows) {
|
||
assert.ok([ 'location', 'goods' ].includes(row.type), `非法类型出现在筛选结果: ${row.type}`);
|
||
}
|
||
});
|
||
|
||
it('mode 筛选:open/blind 各命中对应任务(location 强制盲盘口径)', async () => {
|
||
const openCheck = await createCheck({ type: 'goods', mode: 'open' });
|
||
const blindCheck = await createCheck({ type: 'location' });
|
||
const blindRow = await findCheckRow(blindCheck.id);
|
||
assert.equal(blindRow.mode, 'blind', 'location 任务应被强制为盲盘,作为 mode 筛选的盲盘样本');
|
||
|
||
const openResult = await listChecks({ mode: 'open' });
|
||
const openIds = openResult.rows.map(row => row.id);
|
||
assert.ok(openIds.includes(openCheck.id), 'open 任务应命中 mode=open');
|
||
assert.ok(!openIds.includes(blindCheck.id), 'blind 任务不应命中 mode=open');
|
||
for (const row of openResult.rows) {
|
||
assert.equal(row.mode, 'open', 'mode=open 筛选结果只能包含明盘任务');
|
||
}
|
||
|
||
const bothResult = await listChecks({ mode: [ 'open', 'blind' ] });
|
||
const bothIds = bothResult.rows.map(row => row.id);
|
||
assert.ok(bothIds.includes(openCheck.id), 'mode 数组筛选应命中 open 任务');
|
||
assert.ok(bothIds.includes(blindCheck.id), 'mode 数组筛选应命中 blind 任务');
|
||
});
|
||
|
||
it('created_at 单值 gte:只返回创建时间不早于阈值的任务(直插 created_at 造数)', async () => {
|
||
const oldCheck = await createCheck({ title: uniqueTitle('created_at单值gte') });
|
||
const newCheck = await createCheck({ title: uniqueTitle('created_at单值gte') });
|
||
const oldRow = await setCheckCreatedAt(oldCheck.id, new Date('2019-06-15T00:00:00Z'));
|
||
const newRow = await setCheckCreatedAt(newCheck.id, new Date('2021-05-10T00:00:00Z'));
|
||
assert.equal(new Date(oldRow.created_at).getFullYear(), 2019, 'created_at 应直插为 2019 年');
|
||
assert.equal(new Date(newRow.created_at).getFullYear(), 2021, 'created_at 应直插为 2021 年');
|
||
|
||
const result = await listChecks({ createdAt: '2021-01-01' });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(newCheck.id), '2021 年创建的任务应命中 gte=2021-01-01');
|
||
assert.ok(!ids.includes(oldCheck.id), '2019 年创建的任务不应命中 gte=2021-01-01');
|
||
});
|
||
|
||
it('created_at 区间 between:只返回区间内创建的任务(直插 created_at 造数)', async () => {
|
||
const inRangeCheck = await createCheck({ title: uniqueTitle('created_at区间between') });
|
||
const outRangeCheck = await createCheck({ title: uniqueTitle('created_at区间between') });
|
||
await setCheckCreatedAt(inRangeCheck.id, new Date('2019-06-15T00:00:00Z'));
|
||
await setCheckCreatedAt(outRangeCheck.id, new Date('2021-05-10T00:00:00Z'));
|
||
|
||
const result = await listChecks({ createdAt: [ '2019-01-01', '2019-12-31' ] });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(inRangeCheck.id), '2019-06 创建的任务应命中 2019 年区间');
|
||
assert.ok(!ids.includes(outRangeCheck.id), '2021 年创建的任务不应命中 2019 年区间');
|
||
});
|
||
|
||
it('start_time/end_time 范围:report/finish 后按盘点时间范围筛选', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE);
|
||
await finishCheck(check.id);
|
||
|
||
const finishedRow = await findCheckRow(check.id);
|
||
assert.ok(finishedRow.start_time, 'report 后 start_time 应落库');
|
||
assert.ok(finishedRow.end_time, 'finish 后 end_time 应落库');
|
||
|
||
const wideRange = [ '2000-01-01', '2099-12-31' ];
|
||
const startHit = await listChecks({ startTime: wideRange });
|
||
assert.ok(startHit.rows.map(row => row.id).includes(check.id), 'start_time 应命中宽区间');
|
||
const endHit = await listChecks({ endTime: wideRange });
|
||
assert.ok(endHit.rows.map(row => row.id).includes(check.id), 'end_time 应命中宽区间');
|
||
|
||
const pastRange = [ '1990-01-01', '1999-12-31' ];
|
||
const startMiss = await listChecks({ startTime: pastRange });
|
||
assert.ok(!startMiss.rows.map(row => row.id).includes(check.id), 'start_time 不应命中 1999 年前的区间');
|
||
const endMiss = await listChecks({ endTime: pastRange });
|
||
assert.ok(!endMiss.rows.map(row => row.id).includes(check.id), 'end_time 不应命中 1999 年前的区间');
|
||
});
|
||
|
||
it('组合筛选 type+status:两个条件同时生效', async () => {
|
||
const goodsSubmitted = await createCheck({ title: uniqueTitle('组合筛选type-status') });
|
||
const goodsCreated = await createCheck({ title: uniqueTitle('组合筛选type-status') });
|
||
const locationSubmitted = await createCheck({ type: 'location', title: uniqueTitle('组合筛选type-status') });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(goodsSubmitted.id, [ stocks[0].id ]);
|
||
await submitCheck(goodsSubmitted.id);
|
||
await addLocationDetail(locationSubmitted.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(locationSubmitted.id);
|
||
|
||
const result = await listChecks({ type: 'goods', status: 'submitted' });
|
||
const ids = result.rows.map(row => row.id);
|
||
|
||
assert.ok(ids.includes(goodsSubmitted.id), 'goods+submitted 任务应命中组合筛选');
|
||
assert.ok(!ids.includes(goodsCreated.id), 'goods+created 任务不应命中 status=submitted');
|
||
assert.ok(!ids.includes(locationSubmitted.id), 'location+submitted 任务不应命中 type=goods');
|
||
for (const row of result.rows) {
|
||
assert.equal(row.type, 'goods', '组合筛选结果只能包含 goods 任务');
|
||
assert.equal(row.status, 'submitted', '组合筛选结果只能包含 submitted 任务');
|
||
}
|
||
});
|
||
|
||
it('非法时间值静默忽略:单值/数组/空值均不报错', async () => {
|
||
const check = await createCheck({ title: uniqueTitle('非法时间值') });
|
||
|
||
const singleResult = await listChecks({ createdAt: 'not-a-date' });
|
||
assert.ok(Array.isArray(singleResult.rows), '非法单值时间不应报错');
|
||
assert.equal(typeof singleResult.total, 'number', '非法单值时间应返回正常分页结构');
|
||
assert.ok(singleResult.rows.map(row => row.id).includes(check.id), '非法单值时间应按无条件返回全部任务');
|
||
|
||
const rangeResult = await listChecks({ createdAt: [ 'bad-from', 'bad-to' ] });
|
||
assert.ok(Array.isArray(rangeResult.rows), '两端均非法的区间不应报错');
|
||
assert.ok(rangeResult.rows.map(row => row.id).includes(check.id), '两端均非法的区间应按无条件返回全部任务');
|
||
|
||
const partialRangeResult = await listChecks({ startTime: [ 'bad-from', '2099-12-31' ] });
|
||
assert.ok(Array.isArray(partialRangeResult.rows), '一端非法的区间不应报错(降级为 lte)');
|
||
|
||
const emptyResult = await listChecks({ createdAt: '' });
|
||
assert.ok(Array.isArray(emptyResult.rows), '空字符串时间不应报错');
|
||
});
|
||
});
|
||
|
||
// ------------------- detail:查询任务详情(只返回任务本身信息) -------------------
|
||
|
||
describe('detail 查询任务详情(只返回任务本身信息)', () => {
|
||
it('只返回任务本身信息({ check }),不返回明细 rows/total', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
|
||
const result = await ctx.service.systems.stockCheck.detail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
});
|
||
|
||
assert.deepEqual(Object.keys(result).sort(), [ 'check' ], 'detail 只返回 check,不返回 rows/total');
|
||
assert.equal(result.rows, undefined, 'detail 不应返回明细 rows');
|
||
assert.equal(result.total, undefined, 'detail 不应返回明细 total');
|
||
assert.equal(Number(result.check.id), Number(check.id));
|
||
assert.equal(result.check.check_no, check.check_no);
|
||
assert.equal(result.check.status, 'created');
|
||
assert.equal(result.check.detail_status, 'none_checked');
|
||
assert.equal(result.check.total_items, 2, 'check.total_items 应为明细行数');
|
||
assert.equal(result.check.checked_items, 0);
|
||
assert.equal(result.check.diff_items, 0);
|
||
assert.ok(result.check.created_at, 'check 应含创建时间');
|
||
|
||
// 数量差异汇总:未盘商品行按实盘 0 计盘亏(loss_total = 账面快照合计,正数口径)
|
||
const snapshotRows = await ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: Number(check.id) },
|
||
attributes: [ 'system_quantity' ],
|
||
raw: true,
|
||
});
|
||
const expectedLoss = snapshotRows.reduce((sum, row) => sum + (Number(row.system_quantity) || 0), 0);
|
||
assert.equal(result.check.profit_total, 0, '未盘任务盘盈应为 0');
|
||
assert.equal(result.check.loss_total, expectedLoss, '未盘任务盘亏应为账面快照合计(与 finish 未盘口径一致)');
|
||
});
|
||
|
||
it('已盘后数量差异汇总:profit_total/loss_total 与 finish 口径一致', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
const firstSnapshot = Number(firstDetail.system_quantity);
|
||
const secondSnapshot = Number(secondDetail.system_quantity);
|
||
|
||
// 第一行盘盈 2、第二行盘亏 1
|
||
await reportCheck(check.id, firstDetail.id, firstSnapshot + 2, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, secondDetail.id, secondSnapshot - 1, TEST_EMPTY_LOCATION_CODE);
|
||
|
||
const detailResult = await ctx.service.systems.stockCheck.detail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
});
|
||
assert.equal(detailResult.check.profit_total, 2, '盘盈合计应为 2');
|
||
assert.equal(detailResult.check.loss_total, 1, '盘亏合计应为 1(正数口径)');
|
||
|
||
// 与 finish 返回口径交叉验证
|
||
const finishResult = await finishCheck(check.id);
|
||
assert.equal(detailResult.check.profit_total, finishResult.profit_total, 'detail 盘盈应与 finish 一致');
|
||
assert.equal(detailResult.check.loss_total, finishResult.loss_total, 'detail 盘亏应与 finish 一致');
|
||
assert.equal(detailResult.check.diff_items, finishResult.diff_items, 'detail 差异明细数应与 finish 一致');
|
||
});
|
||
|
||
it('盘点任务ID 非法 / 任务不存在报 400', async () => {
|
||
const missingId = await findFreeCheckId();
|
||
await assert.rejects(
|
||
() => ctx.service.systems.stockCheck.detail({ warehouseId: TEST_WAREHOUSE_ID, id: 0 }),
|
||
error => error.code === 400 && /盘点任务ID不能为空/.test(error.message)
|
||
);
|
||
await assert.rejects(
|
||
() => ctx.service.systems.stockCheck.detail({ warehouseId: TEST_WAREHOUSE_ID, id: missingId }),
|
||
error => error.code === 400 && /盘点任务不存在/.test(error.message)
|
||
);
|
||
});
|
||
});
|
||
|
||
// ------------------- result:盘点结果聚合 -------------------
|
||
|
||
describe('result 盘点结果聚合', () => {
|
||
it('盘点前(无作业记录):rows 直接返回 wms_stock_check_detail 明细范围行', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
|
||
const result = await resultCheck(check.id);
|
||
const details = await detailCheck(check.id);
|
||
|
||
assert.equal(result.total, 2);
|
||
assert.equal(result.rows.length, details.rows.length);
|
||
for (const row of result.rows) {
|
||
assert.equal(row.scope_type, 'goods', '明细行应含 scope_type');
|
||
assert.ok(row.stock_id, '明细行应含 stock_id');
|
||
assert.ok(row.location_id, '明细行应含 location_id');
|
||
assert.ok(row.location_code, '明细行应含库位编码');
|
||
assert.ok(row.item_code, '明细行应含商品编码快照');
|
||
assert.ok(Number(row.system_quantity) >= 0, '明细行应含账面快照');
|
||
}
|
||
assert.deepEqual(
|
||
result.rows.map(row => Number(row.id)),
|
||
details.rows.map(row => Number(row.id)),
|
||
'rows 应为明细表原始行'
|
||
);
|
||
});
|
||
|
||
it('待提交(submitted)状态:rows 同样返回明细范围行(后台盘点前查看明细)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
|
||
const result = await resultCheck(check.id);
|
||
|
||
assert.equal(result.check.status, 'submitted');
|
||
assert.equal(result.rows.length, 2, '待提交任务应返回明细范围行');
|
||
assert.ok(
|
||
result.rows.every(row => row.scope_type === 'goods' && row.stock_id && row.location_code),
|
||
'待提交任务 rows 应为明细表原始行(含商品/库位/快照)'
|
||
);
|
||
});
|
||
|
||
it('已盘明细:location_codes/checkers 合并去重、records 完整、last_checked_at 取最近', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
await reportCheck(check.id, detailId, 3, TEST_LOCATION_CODE, { checkerName: '盘点人A' });
|
||
await reportCheck(check.id, detailId, 4, TEST_LOCATION_CODE_2, { checkerName: '盘点人A' });
|
||
await reportCheck(check.id, detailId, 2, TEST_LOCATION_CODE_3, { checkerName: '盘点人B' });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
|
||
assert.equal(row.checked_quantity, 9, '已盘数量应为三条记录合计');
|
||
assert.equal(row.status, 'checked');
|
||
assert.deepEqual(row.location_codes, [ TEST_LOCATION_CODE, TEST_LOCATION_CODE_2, TEST_LOCATION_CODE_3 ], '库位编码应合并去重');
|
||
assert.deepEqual(row.checkers, [ '盘点人A', '盘点人B' ], '盘点人应合并去重');
|
||
assert.equal(row.records.length, 3, 'records 应包含全部作业记录');
|
||
for (const record of row.records) {
|
||
assert.ok(record.location_code, '记录应含库位编码');
|
||
assert.ok(record.quantity !== undefined, '记录应含实盘数量');
|
||
assert.ok(record.checker_name, '记录应含盘点人');
|
||
assert.ok(record.checked_at, '记录应含上报时间');
|
||
}
|
||
assert.ok(row.last_checked_at, '最近盘点时间应非空');
|
||
const lastRecord = row.records[row.records.length - 1];
|
||
assert.equal(
|
||
new Date(row.last_checked_at).getTime(),
|
||
new Date(lastRecord.checked_at).getTime(),
|
||
'last_checked_at 应为最近一条记录的上报时间'
|
||
);
|
||
});
|
||
|
||
it('result 与 detail 行一一对应:范围行数与行 id 完全一致', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 1, TEST_LOCATION_CODE);
|
||
|
||
const result = await resultCheck(check.id);
|
||
|
||
assert.equal(result.total, details.total, 'result 与 detail 范围行数应一致');
|
||
assert.equal(result.rows.length, details.rows.length);
|
||
const detailIds = details.rows.map(row => Number(row.id));
|
||
const resultIds = result.rows.map(row => Number(row.id));
|
||
assert.deepEqual(resultIds, detailIds, 'result 行 id 集合应与 detail 一致');
|
||
for (const row of result.rows) {
|
||
assert.ok(row.stock_id, '商品范围行应含 stock_id');
|
||
}
|
||
});
|
||
|
||
it('result 商品行聚合与 recordList 交叉验证:checked_quantity/diff/locations 与记录表口径一致', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
const snapshot = Number(details.rows[0].system_quantity);
|
||
await reportCheck(check.id, detailId, snapshot + 2, TEST_LOCATION_CODE, { checkerName: '盘点人A' });
|
||
await reportCheck(check.id, detailId, 4, TEST_LOCATION_CODE_2, { checkerName: '盘点人B' });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
|
||
const listed = await listRecords({ id: check.id, detailId });
|
||
assert.equal(listed.total, 2, 'recordList 应返回该明细全部作业记录');
|
||
const expectedChecked = listed.rows.reduce((sum, record) => sum + Number(record.quantity), 0);
|
||
assert.equal(row.checked_quantity, expectedChecked, 'checked_quantity 应与 recordList 数量合计一致');
|
||
assert.equal(row.diff_quantity, expectedChecked - snapshot, 'diff_quantity=已盘合计-账面快照');
|
||
assert.equal(row.is_diff, 1);
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.records.length, listed.total, 'records 条数应与 recordList 一致');
|
||
assert.deepEqual(
|
||
row.records.map(record => Number(record.id)).sort((left, right) => left - right),
|
||
listed.rows.map(record => Number(record.id)).sort((left, right) => left - right),
|
||
'records 记录 id 应与 recordList 完全一致'
|
||
);
|
||
assert.deepEqual(
|
||
row.location_codes.sort(),
|
||
[ TEST_LOCATION_CODE, TEST_LOCATION_CODE_2 ].sort(),
|
||
'location_codes 应与记录库位编码一致'
|
||
);
|
||
const locationQuantityMap = new Map(row.locations.map(item => [ item.location_code, item.quantity ]));
|
||
assert.equal(locationQuantityMap.get(TEST_LOCATION_CODE), snapshot + 2, '有库位组数量应为该库位上报值');
|
||
assert.equal(locationQuantityMap.get(TEST_LOCATION_CODE_2), 4, '无库位组数量应为该库位上报值');
|
||
});
|
||
|
||
it('多库位商品合并为一行:locations 输出各库位账面快照与实盘,差异=实盘合计-账面快照合计', async () => {
|
||
const { Op, literal } = ctx.app.Sequelize;
|
||
// 找一个在两个启用库位都有库存的商品(与 addDetail 拆行用例同口径)
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
|
||
group: [ 'stock_id', 'space_id' ],
|
||
raw: true,
|
||
});
|
||
const spacesByStock = new Map();
|
||
for (const row of storageRows) {
|
||
const stockId = Number(row.stock_id);
|
||
if (!spacesByStock.has(stockId)) {
|
||
spacesByStock.set(stockId, []);
|
||
}
|
||
spacesByStock.get(stockId).push(row);
|
||
}
|
||
const multiStockEntry = [ ...spacesByStock.entries() ].find(([ , rows ]) => rows.length >= 2);
|
||
assert.ok(multiStockEntry, '前置:测试库应存在多库位库存商品');
|
||
const multiStockId = Number(multiStockEntry[0]);
|
||
const multiStock = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: multiStockId, warehouse_id: TEST_WAREHOUSE_ID },
|
||
raw: true,
|
||
});
|
||
assert.ok(multiStock, '前置:多库位商品应存在于 wms_stock_warehouse');
|
||
|
||
const check = await createCheck({ type: 'goods', storeId: multiStock.store_id || null });
|
||
const addResult = await addDetail(check.id, [ multiStockId ]);
|
||
assert.equal(addResult.total_items, 1, '按商品盘点 total_items 按商品计数');
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
assert.ok(details.rows.length >= 2, '前置:商品应按库位拆成多行');
|
||
|
||
// 全部库位上报:第一个库位盘盈 5、第二个库位盘盈 1、其余库位实盘=账面(差异合计恒为 6)
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
for (const detail of details.rows) {
|
||
let quantity = Number(detail.system_quantity);
|
||
if (Number(detail.id) === Number(firstDetail.id)) {
|
||
quantity += 5;
|
||
}
|
||
if (Number(detail.id) === Number(secondDetail.id)) {
|
||
quantity += 1;
|
||
}
|
||
await reportCheck(check.id, detail.id, quantity, detail.location_code || undefined);
|
||
}
|
||
|
||
const result = await resultCheck(check.id);
|
||
assert.equal(result.total, 1, '多库位商品应合并为一行');
|
||
assert.equal(result.rows.length, 1);
|
||
const row = result.rows[0];
|
||
assert.equal(Number(row.stock_id), multiStockId);
|
||
assert.equal(row.scope_type, 'goods');
|
||
assert.equal(row.location_id, null, '合并行不绑定单一库位');
|
||
assert.equal(row.location_code, null, '合并行不绑定单一库位编码');
|
||
const totalSnapshot = details.rows.reduce((sum, detail) => sum + Number(detail.system_quantity), 0);
|
||
assert.equal(Number(row.system_quantity), totalSnapshot, '行级账面=各库位账面快照合计');
|
||
assert.equal(row.checked_quantity, totalSnapshot + 6, '已盘数量=各库位实盘合计');
|
||
assert.equal(row.diff_quantity, 6, '差异=实盘合计-账面快照合计');
|
||
assert.equal(row.is_diff, 1);
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.records.length, details.rows.length, 'records 应包含全部库位作业记录');
|
||
|
||
const firstLocation = row.locations.find(item => item.location_code === firstDetail.location_code);
|
||
assert.ok(firstLocation, 'locations 应含第一个库位');
|
||
assert.equal(Number(firstLocation.system_quantity), Number(firstDetail.system_quantity), '库位账面=创建明细时的快照');
|
||
assert.equal(Number(firstLocation.quantity), Number(firstDetail.system_quantity) + 5, '库位实盘=该库位上报值');
|
||
const secondLocation = row.locations.find(item => item.location_code === secondDetail.location_code);
|
||
assert.ok(secondLocation, 'locations 应含第二个库位');
|
||
assert.equal(Number(secondLocation.system_quantity), Number(secondDetail.system_quantity), '库位账面=创建明细时的快照');
|
||
assert.equal(Number(secondLocation.quantity), Number(secondDetail.system_quantity) + 1, '库位实盘=该库位上报值');
|
||
});
|
||
});
|
||
|
||
// ------------------- result.locations:库位分组聚合 -------------------
|
||
|
||
describe('result.locations 库位分组聚合', () => {
|
||
it('多库位分组:按库位聚合数量、空库位归 null 组、按组内首条记录 id 升序', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
await reportCheck(check.id, detailId, 10, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, detailId, 5, TEST_LOCATION_CODE_2);
|
||
await reportCheck(check.id, detailId, 7, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, detailId, 3, TEST_LOCATION_CODE_3);
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
|
||
// 商品按商品合并后:快照库位(含账面快照)+ 已盘库位(按首条记录 id 升序追加)
|
||
const quantityByCode = new Map(row.locations.map(location => [ location.location_code, location.quantity ]));
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE), 7, '命中库位数量应为该库位最新值');
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE_2), 5);
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE_3), 3);
|
||
const snapshotEntry = row.locations.find(location => Number(location.system_quantity) > 0);
|
||
assert.ok(snapshotEntry, '应含账面快照库位(system_quantity=创建明细时账面快照)');
|
||
assert.equal(
|
||
Number(snapshotEntry.system_quantity),
|
||
Number(details.rows[0].system_quantity),
|
||
'账面快照应为明细快照值'
|
||
);
|
||
const checkedEntry = row.locations.find(location => location.location_code === TEST_LOCATION_CODE);
|
||
assert.equal(Number(checkedEntry.location_id), TEST_LOCATION_ID, '命中库位应回填 location_id');
|
||
const otherEntry = row.locations.find(location => location.location_code === TEST_LOCATION_CODE_2);
|
||
assert.equal(Number(otherEntry.location_id), TEST_LOCATION_ID_2, '有效库位应回填 location_id');
|
||
assert.equal(row.checked_quantity, 15, '已盘数量=各库位最新值合计');
|
||
assert.equal(row.records.length, 3, 'records 流水保持三条');
|
||
assert.equal(row.location_codes.length, 3, '既有聚合字段 location_codes 不变');
|
||
});
|
||
|
||
it('历史无库位记录(location_code=空串)归入 location_code=null 组(report 不再产生该分组)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
|
||
// report 已强制 space_id,无库位上报直接被拒
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 4, undefined, { spaceId: 0 });
|
||
}, error => error.code === 400 && error.message.includes('缺少库位ID'));
|
||
|
||
// 历史脏数据(空串库位)仍按既有口径归入 null 组
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: Number(detail.stock_id),
|
||
location_id: null,
|
||
location_code: '',
|
||
quantity: 6,
|
||
is_empty: false,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
|
||
const nullGroup = row.locations.find(location => location.location_code === null);
|
||
assert.ok(nullGroup, '空库位归 location_code=null 组');
|
||
assert.equal(nullGroup.location_id, null);
|
||
assert.equal(Number(nullGroup.quantity), 6, '无库位组数量为该记录实盘值');
|
||
assert.equal(Number(nullGroup.system_quantity), 0, '无库位组无账面快照');
|
||
assert.equal(Number(row.checked_quantity), 6);
|
||
});
|
||
});
|
||
|
||
// ------------------- result:库位行 stocks 聚合(账面来自 wms_storage) -------------------
|
||
|
||
describe('result 库位行 stocks 聚合', () => {
|
||
it('库位行 stocks 按商品聚合:多商品账面来自 wms_storage、行级差异为各商品差异代数和', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 2);
|
||
assert.ok(stockIds.length >= 2, '固定测试库位应存在至少两个商品库存(真实数据依赖)');
|
||
|
||
const bookMap = await fetchStorageQuantity(TEST_LOCATION_ID, stockIds);
|
||
const bookA = Number(bookMap.get(stockIds[0]) || 0);
|
||
const bookB = Number(bookMap.get(stockIds[1]) || 0);
|
||
const qtyA = bookA + 5;
|
||
const qtyB = Math.max(0, bookB - 2);
|
||
await reportCheck(check.id, detail.id, qtyA, undefined, { stockId: stockIds[0] });
|
||
await reportCheck(check.id, detail.id, qtyB, undefined, { stockId: stockIds[1] });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
|
||
assert.equal(row.scope_type, 'location', '库位行应输出 scope_type=location');
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.checked_quantity, qtyA + qtyB, '行级已盘数量=行内商品已盘合计');
|
||
const expectedDiff = 5 + (qtyB - bookB);
|
||
assert.equal(row.diff_quantity, expectedDiff, '行级差异=各商品差异代数和');
|
||
assert.equal(row.is_diff, expectedDiff !== 0 ? 1 : 0);
|
||
|
||
assert.equal(row.stocks.length, 2);
|
||
assert.deepEqual(
|
||
row.stocks.map(stock => Number(stock.stock_id)),
|
||
stockIds,
|
||
'stocks 应按 stock_id 升序'
|
||
);
|
||
const stockA = row.stocks[0];
|
||
assert.equal(Number(stockA.system_quantity), bookA, '账面应来自 wms_storage 实时汇总');
|
||
assert.equal(stockA.checked_quantity, qtyA);
|
||
assert.equal(stockA.diff_quantity, 5);
|
||
assert.ok(stockA.item_code, 'stocks 应回填商品编码');
|
||
const stockB = row.stocks[1];
|
||
assert.equal(Number(stockB.system_quantity), bookB);
|
||
assert.equal(stockB.checked_quantity, qtyB);
|
||
assert.equal(stockB.diff_quantity, qtyB - bookB);
|
||
|
||
// 与作业记录表交叉验证:records 商品 ID 应与上报商品一致
|
||
assert.equal(row.records.length, 2, 'records 应包含行内全部作业记录');
|
||
assert.deepEqual(
|
||
row.records.map(record => Number(record.stock_id)).sort((left, right) => left - right),
|
||
[ ...stockIds ].sort((left, right) => left - right),
|
||
'records 商品 ID 应与上报商品一致'
|
||
);
|
||
});
|
||
|
||
it('库位无库存时账面按 0:diff=已盘-0', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
const emptySpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_EMPTY_LOCATION_CODE },
|
||
raw: true,
|
||
});
|
||
assert.ok(emptySpace, `空库位编码不存在(${TEST_EMPTY_LOCATION_CODE})`);
|
||
const storageCount = await ctx.model.Storage.count({
|
||
where: { space_id: Number(emptySpace.id) },
|
||
});
|
||
assert.equal(storageCount, 0, '测试用空库位应无库存记录(账面 0 口径依赖)');
|
||
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const stocks = await fetchStockRows(1);
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows.find(row => row.location_code === TEST_EMPTY_LOCATION_CODE);
|
||
await reportCheck(check.id, detail.id, 7, undefined, { stockId: stocks[0].id });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows.find(item => item.location_code === TEST_EMPTY_LOCATION_CODE);
|
||
|
||
assert.equal(row.stocks.length, 1);
|
||
assert.equal(Number(row.stocks[0].system_quantity), 0, '无库存库位账面应为 0');
|
||
assert.equal(row.stocks[0].checked_quantity, 7);
|
||
assert.equal(row.stocks[0].diff_quantity, 7, 'diff=已盘-0');
|
||
assert.equal(row.diff_quantity, 7);
|
||
assert.equal(row.is_diff, 1);
|
||
});
|
||
});
|
||
|
||
// ------------------- workData:盘点作业数据(单接口三视图) -------------------
|
||
|
||
describe('workData 盘点作业数据(location/goods/space 单接口三视图)', () => {
|
||
it('location 视图:库位范围行与明细一致、未盘行 status=unchecked、子列表为空、不返回 check 且 view=location', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 2, '前置:任务应有两条库位范围行');
|
||
|
||
const data = await workDataCheck(check.id, 'location');
|
||
|
||
assert.deepEqual(
|
||
Object.keys(data).sort(),
|
||
[ 'page', 'pageSize', 'rows', 'total', 'view' ],
|
||
'workData 只返回作业数据行 + view(不返回 check,任务信息请调 detail)'
|
||
);
|
||
assert.equal(data.view, 'location', '库位任务应返回 view=location');
|
||
assert.equal(data.total, 2);
|
||
assert.equal(data.rows.length, 2);
|
||
assert.equal((await findCheckRow(check.id)).mode, 'blind', '库位维度任务应为盲盘');
|
||
assert.deepEqual(
|
||
data.rows.map(row => Number(row.detail_id)),
|
||
details.rows.map(row => Number(row.id)),
|
||
'location 行应与任务库位范围行一一对应(按明细 id 升序)'
|
||
);
|
||
for (const row of data.rows) {
|
||
const detail = details.rows.find(item => Number(item.id) === Number(row.detail_id));
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: { id: Number(detail.location_id) },
|
||
attributes: [ 'space_code', 'custom_name' ],
|
||
raw: true,
|
||
});
|
||
assert.equal(Number(row.location_id), Number(detail.location_id), 'location_id 应来自明细快照');
|
||
assert.equal(row.location_code, detail.location_code, 'location_code 应来自明细快照');
|
||
assert.equal(
|
||
row.location_name,
|
||
(space.custom_name || space.space_code) || detail.location_code,
|
||
'location_name 应为 custom_name 兜底 space_code'
|
||
);
|
||
assert.equal(row.status, 'unchecked', '无作业记录应输出未盘');
|
||
assert.equal(row.has_unknown, false);
|
||
assert.equal(row.checked_at, null);
|
||
assert.deepEqual(row.checkers, []);
|
||
assert.deepEqual(row.goods, []);
|
||
}
|
||
});
|
||
|
||
it('keyword 过滤:仅库位任务生效,按 location_code/location_name 模糊匹配(不区分大小写)后再分页', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||
where: { space_code: { [ctx.app.Sequelize.Op.in]: [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ] } },
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
raw: true,
|
||
});
|
||
const spaceA = spaceRows.find(row => row.space_code === TEST_LOCATION_CODE);
|
||
const spaceE = spaceRows.find(row => row.space_code === TEST_EMPTY_LOCATION_CODE);
|
||
|
||
// 1) 按 location_code 前缀匹配(小写验证不区分大小写)
|
||
const byCode = await workDataCheck(check.id, { keyword: 'a1715' });
|
||
assert.equal(byCode.total, 1, '按库位编码前缀应命中 1 行');
|
||
assert.equal(byCode.rows.length, 1);
|
||
assert.equal(byCode.rows[0].location_code, TEST_LOCATION_CODE);
|
||
|
||
// 2) 按 location_name 匹配(取名称中不被另一库位编码/名称包含的唯一字符做关键字)
|
||
const nameA = (spaceA && (spaceA.custom_name || spaceA.space_code)) || TEST_LOCATION_CODE;
|
||
const otherTexts = [ TEST_EMPTY_LOCATION_CODE, spaceE && spaceE.custom_name ]
|
||
.filter(Boolean)
|
||
.map(text => String(text).toLowerCase());
|
||
const uniqueChar = Array.from(String(nameA))
|
||
.find(char => !otherTexts.some(text => text.includes(String(char).toLowerCase())));
|
||
if (uniqueChar) {
|
||
const byName = await workDataCheck(check.id, { keyword: uniqueChar });
|
||
assert.equal(byName.total, 1, '按库位名称唯一字符应命中 1 行');
|
||
assert.equal(byName.rows[0].location_code, TEST_LOCATION_CODE);
|
||
}
|
||
|
||
// 3) 无命中关键字 → total=0、rows=[]
|
||
const miss = await workDataCheck(check.id, { keyword: 'ZZZ-NO-MATCH-998' });
|
||
assert.equal(miss.total, 0);
|
||
assert.deepEqual(miss.rows, []);
|
||
|
||
// 4) 空白关键字 → 视为未传,不过滤
|
||
const blank = await workDataCheck(check.id, { keyword: ' ' });
|
||
assert.equal(blank.total, 2, '空白关键字应不过滤');
|
||
|
||
// 5) 非库位任务忽略 keyword(goods 任务 space 视图)
|
||
const goodsCheck = await createCheck({ type: 'goods' });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(goodsCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(goodsCheck.id);
|
||
await auditCheck(goodsCheck.id, 'approve');
|
||
const goodsAll = await workDataCheck(goodsCheck.id);
|
||
const goodsFiltered = await workDataCheck(goodsCheck.id, { keyword: 'ZZZ-NO-MATCH-998' });
|
||
assert.equal(goodsFiltered.total, goodsAll.total, '商品任务应忽略 keyword');
|
||
});
|
||
|
||
it('space 视图行 location_id 与 id 同义(供调用方直接回传 report 的 location_id)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const data = await workDataCheck(check.id);
|
||
assert.equal(data.view, 'space');
|
||
assert.ok(data.rows.length > 0, '前置:space 视图应有库位行');
|
||
for (const row of data.rows) {
|
||
assert.ok(Number(row.id) > 0, 'id 应为库位ID');
|
||
assert.equal(Number(row.location_id), Number(row.id), 'location_id 应与 id 一致');
|
||
}
|
||
});
|
||
|
||
it('space 视图:库位仅按拣货顺序排序(pick_sequence 升序,pick_priority 与库位 id 不参与)', async () => {
|
||
// 1) 找两个不同库位、各只有一个库存库位的商品(确保 space 视图恰好聚合这两个库位)
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
assert.ok(pairs.length >= 2, '测试仓库应至少有 2 个单库位启用库存库位(真实数据依赖)');
|
||
const spaceA = Number(pairs[0].spaceId);
|
||
const spaceB = Number(pairs[1].spaceId);
|
||
const stockA = Number(pairs[0].stockId);
|
||
const stockB = Number(pairs[1].stockId);
|
||
const stockRows = await ctx.model.StockWarehouse.findAll({
|
||
where: {
|
||
id: { [ctx.app.Sequelize.Op.in]: [ stockA, stockB ] },
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
assert.equal(stockRows.length, 2, '两个商品均应属于测试仓库');
|
||
|
||
const check = await createCheck({ type: 'goods' });
|
||
await addDetail(check.id, [ stockA, stockB ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
// 2) 记录库位原始排序值,验证后恢复(不污染开发库拣货路径数据)
|
||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||
where: { id: { [ctx.app.Sequelize.Op.in]: [ spaceA, spaceB ] } },
|
||
attributes: [ 'id', 'pick_sequence', 'pick_priority' ],
|
||
raw: true,
|
||
});
|
||
const originalValues = new Map(spaceRows.map(row => [
|
||
Number(row.id),
|
||
{ pick_sequence: row.pick_sequence, pick_priority: row.pick_priority },
|
||
]));
|
||
const restoreSpaces = async () => {
|
||
for (const [ spaceId, values ] of originalValues.entries()) {
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: values.pick_sequence, pick_priority: values.pick_priority },
|
||
{ where: { id: spaceId } }
|
||
);
|
||
}
|
||
};
|
||
|
||
try {
|
||
// 阶段1:pick_priority 相同(50)时按 pick_sequence 升序 → B(100) 在 A(200) 前
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 200, pick_priority: 50 },
|
||
{ where: { id: spaceA } }
|
||
);
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 100, pick_priority: 50 },
|
||
{ where: { id: spaceB } }
|
||
);
|
||
let data = await workDataCheck(check.id);
|
||
assert.equal(data.view, 'space', '商品任务默认应为 space 视图');
|
||
assert.deepEqual(
|
||
data.rows.map(row => Number(row.id)),
|
||
[ spaceB, spaceA ],
|
||
'pick_sequence 应升序(小值在前)'
|
||
);
|
||
|
||
// 阶段2:pick_sequence 相同(300)时 pick_priority 不参与排序,
|
||
// 同值保持库位查询顺序(实际按 id 升序);两方向设置 priority 断言顺序不变,
|
||
// 若实现误把 priority 纳入排序键,总有一组断言会失败
|
||
const [ smallerId, largerId ] = [ spaceA, spaceB ].sort((left, right) => left - right);
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 300, pick_priority: 10 },
|
||
{ where: { id: smallerId } }
|
||
);
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 300, pick_priority: 90 },
|
||
{ where: { id: largerId } }
|
||
);
|
||
data = await workDataCheck(check.id);
|
||
assert.deepEqual(
|
||
data.rows.map(row => Number(row.id)),
|
||
[ smallerId, largerId ],
|
||
'pick_priority 不参与排序(同 pick_sequence 保持原顺序,升序误入会交换)'
|
||
);
|
||
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 300, pick_priority: 90 },
|
||
{ where: { id: smallerId } }
|
||
);
|
||
await ctx.model.LocationSpace.update(
|
||
{ pick_sequence: 300, pick_priority: 10 },
|
||
{ where: { id: largerId } }
|
||
);
|
||
data = await workDataCheck(check.id);
|
||
assert.deepEqual(
|
||
data.rows.map(row => Number(row.id)),
|
||
[ smallerId, largerId ],
|
||
'pick_priority 不参与排序(同 pick_sequence 保持原顺序,降序误入会交换)'
|
||
);
|
||
} finally {
|
||
await restoreSpaces();
|
||
}
|
||
});
|
||
|
||
it('only_abnormal 过滤 location 视图:仅保留未盘行与含未知商品行,兼容 onlyAbnormal 驼峰写法', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const checkedDetail = details.rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
const uncheckedDetail = details.rows.find(row => row.location_code === TEST_EMPTY_LOCATION_CODE);
|
||
assert.ok(checkedDetail && uncheckedDetail, '前置:两条库位范围行均应存在');
|
||
|
||
// 已盘行(无未知商品):上报后应被过滤,仅剩未盘行
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
await reportCheck(check.id, checkedDetail.id, 3, undefined, { stockId: stockIds[0] });
|
||
|
||
const abnormal = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(abnormal.total, 1, '已盘无未知商品行应被过滤,仅剩未盘行');
|
||
assert.equal(Number(abnormal.rows[0].detail_id), Number(uncheckedDetail.id));
|
||
assert.equal(abnormal.rows[0].status, 'unchecked');
|
||
|
||
// 未传 only_abnormal → 不过滤;onlyAbnormal 驼峰写法等价
|
||
const all = await workDataCheck(check.id, {});
|
||
assert.equal(all.total, 2, '未传 only_abnormal 应不过滤');
|
||
const camel = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(camel.total, 1, 'onlyAbnormal 驼峰写法应等价生效');
|
||
|
||
// 已盘行补充未知商品记录 → has_unknown=true 视为差异,应保留
|
||
await reportCheck(check.id, checkedDetail.id, 7, undefined, { barcode: uniqueTitle('ONLY-ABN-UNKNOWN') });
|
||
const abnormal2 = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(abnormal2.total, 2, '未知商品行(has_unknown)应视为差异保留');
|
||
const checkedRow = abnormal2.rows.find(row => Number(row.detail_id) === Number(checkedDetail.id));
|
||
assert.equal(checkedRow.has_unknown, true);
|
||
});
|
||
|
||
it('only_abnormal 过滤 goods 视图明盘:未盘行与差异行保留、已盘平账行移除、total 为过滤后行数', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const diffDetail = details.rows[0];
|
||
const flatDetail = details.rows[1];
|
||
const diffSnapshot = Number(diffDetail.system_quantity);
|
||
const flatSnapshot = Number(flatDetail.system_quantity);
|
||
|
||
// 仅第一行盘盈(差异)→ only_abnormal 应保留差异行与未盘行
|
||
await reportCheck(check.id, diffDetail.id, diffSnapshot + 2, TEST_LOCATION_CODE);
|
||
|
||
const first = await workDataCheck(check.id, { isGoods: true, onlyAbnormal: true });
|
||
assert.equal(first.view, 'goods');
|
||
assert.equal(first.total, 2, '差异行 + 未盘行应均保留');
|
||
assert.deepEqual(
|
||
first.rows.map(row => Number(row.stock_id)).sort((left, right) => left - right),
|
||
[ Number(diffDetail.stock_id), Number(flatDetail.stock_id) ].sort((left, right) => left - right),
|
||
'保留行应为差异行与未盘行(goods 视图按商品汇总,行键为 stock_id)'
|
||
);
|
||
const flatRow = first.rows.find(row => Number(row.stock_id) === Number(flatDetail.stock_id));
|
||
assert.ok(
|
||
!flatRow.locations.some(location => Array.isArray(location.record_ids) && location.record_ids.length > 0),
|
||
'未盘行应无任何作业记录'
|
||
);
|
||
|
||
// 第二行平账(已盘无差异)→ 仅剩差异行
|
||
await reportCheck(check.id, flatDetail.id, flatSnapshot, TEST_LOCATION_CODE);
|
||
const second = await workDataCheck(check.id, { isGoods: true, onlyAbnormal: true });
|
||
assert.equal(second.total, 1, '已盘平账行应被过滤,仅剩差异行');
|
||
assert.equal(Number(second.rows[0].stock_id), Number(diffDetail.stock_id));
|
||
assert.equal(second.rows[0].is_diff, 1);
|
||
|
||
// 过滤在分页切片之前:pageSize=1 时 rows 为当前页、total 仍为过滤后行数
|
||
const paged = await workDataCheck(check.id, { isGoods: true, onlyAbnormal: true, pagination: { page: 1, pageSize: 1 } });
|
||
assert.equal(paged.total, 1);
|
||
assert.equal(paged.rows.length, 1);
|
||
|
||
// false/0/空串视为未传不过滤
|
||
for (const value of [ false, 0, 'false', '' ]) {
|
||
const noFilter = await workDataCheck(check.id, { isGoods: true, onlyAbnormal: value });
|
||
assert.equal(noFilter.total, 2, `only_abnormal=${JSON.stringify(value)} 应不过滤`);
|
||
}
|
||
});
|
||
|
||
it('only_abnormal 过滤 space 视图明盘:行内 goods 按未盘/数量差异过滤、空行移除', async () => {
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const diffPair = pairs[0];
|
||
const flatPair = pairs[1];
|
||
const diffDetail = details.rows.find(row => Number(row.stock_id) === diffPair.stockId);
|
||
const flatDetail = details.rows.find(row => Number(row.stock_id) === flatPair.stockId);
|
||
|
||
// 库位1盘盈(差异)、库位2未盘 → 两个库位行均应保留(差异子项 + 未盘子项)
|
||
await reportCheck(check.id, diffDetail.id, diffPair.book + 2, diffPair.spaceCode);
|
||
|
||
const first = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(first.view, 'space');
|
||
assert.equal(first.total, 2, '差异库位与未盘库位均应保留');
|
||
const diffRow = first.rows.find(row => Number(row.id) === diffPair.spaceId);
|
||
const uncheckedRow = first.rows.find(row => Number(row.id) === flatPair.spaceId);
|
||
assert.ok(diffRow && uncheckedRow, '差异库位与未盘库位行均应存在');
|
||
assert.equal(diffRow.goods.length, 1, '差异库位行应保留差异商品子项');
|
||
assert.equal(Number(diffRow.goods[0].checked_quantity), diffPair.book + 2);
|
||
assert.equal(uncheckedRow.goods.length, 1);
|
||
assert.equal(uncheckedRow.goods[0].status, 'unchecked');
|
||
|
||
// 库位2平账(已盘无差异)→ 该库位行整体移除,仅剩差异库位行
|
||
await reportCheck(check.id, flatDetail.id, flatPair.book, flatPair.spaceCode);
|
||
const second = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(second.total, 1, '已盘平账库位行应被整体移除');
|
||
assert.equal(Number(second.rows[0].id), diffPair.spaceId);
|
||
assert.equal(second.rows[0].goods.length, 1, '保留行内 goods 应仅剩差异商品');
|
||
});
|
||
|
||
it('only_abnormal 过滤 space 视图盲盘:无数量字段仅按未盘过滤(已盘行移除)', async () => {
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck({ mode: 'blind' });
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const reportedDetail = details.rows.find(row => Number(row.stock_id) === pairs[0].stockId);
|
||
await reportCheck(check.id, reportedDetail.id, 6, pairs[0].spaceCode);
|
||
|
||
const data = await workDataCheck(check.id, { onlyAbnormal: true });
|
||
assert.equal(data.total, 1, '盲盘已盘行无法判断差异应移除,仅剩未盘库位行');
|
||
assert.equal(Number(data.rows[0].id), pairs[1].spaceId, '保留行应为未盘库位');
|
||
assert.equal(data.rows[0].goods[0].status, 'unchecked');
|
||
});
|
||
|
||
it('only_abnormal 与 keyword 叠加:location 视图先 keyword 过滤再按未盘/差异过滤', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const checkedDetail = details.rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
await reportCheck(check.id, checkedDetail.id, 3, undefined, { stockId: stockIds[0] });
|
||
|
||
// keyword 命中已盘行 + only_abnormal → 已盘行被过滤 → 0 行
|
||
const hitChecked = await workDataCheck(check.id, { keyword: 'a1715', onlyAbnormal: true });
|
||
assert.equal(hitChecked.total, 0, 'keyword 命中的已盘行被 only_abnormal 过滤后应为空');
|
||
|
||
// keyword 命中未盘行 + only_abnormal → 1 行
|
||
const hitUnchecked = await workDataCheck(check.id, { keyword: TEST_EMPTY_LOCATION_CODE, onlyAbnormal: true });
|
||
assert.equal(hitUnchecked.total, 1, 'keyword 命中的未盘行应保留');
|
||
assert.equal(hitUnchecked.rows[0].status, 'unchecked');
|
||
});
|
||
|
||
it('workDataDetail:按明细ID返回单行(结构同 location 视图行),已盘/未盘口径与列表一致', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
const emptyDetail = details.rows.find(row => row.location_code === TEST_EMPTY_LOCATION_CODE);
|
||
assert.ok(targetDetail && emptyDetail, '前置:两条库位范围行均应存在');
|
||
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
const reported = await reportCheck(check.id, targetDetail.id, 6, undefined, { stockId: stockIds[0] });
|
||
|
||
const row = await workDataDetailCheck(targetDetail.id);
|
||
assert.deepEqual(
|
||
Object.keys(row).sort(),
|
||
[ 'checked_at', 'checkers', 'detail_id', 'goods', 'has_unknown', 'is_empty', 'location_code', 'location_id', 'location_name', 'space_id', 'status' ].sort(),
|
||
'单行字段应与 location 视图行结构一致'
|
||
);
|
||
assert.equal(Number(row.detail_id), Number(targetDetail.id));
|
||
assert.equal(Number(row.location_id), Number(targetDetail.location_id));
|
||
assert.equal(row.location_code, targetDetail.location_code);
|
||
assert.ok(row.location_name, '应输出库位名称');
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.has_unknown, false);
|
||
assert.equal(row.is_empty, false);
|
||
assert.equal(row.goods.length, 1, 'goods 应含已盘商品');
|
||
assert.equal(Number(row.goods[0].record_id), Number(reported.record.id));
|
||
assert.ok(row.checkers.includes(TEST_CREATOR_NAME));
|
||
assert.ok(row.checked_at);
|
||
|
||
// 与 workData 列表对应行逐字段一致
|
||
const listData = await workDataCheck(check.id, 'location');
|
||
const listRow = listData.rows.find(item => Number(item.detail_id) === Number(targetDetail.id));
|
||
assert.deepEqual(row, listRow, 'workDataDetail 单行应与 workData 列表对应行一致');
|
||
|
||
// 未盘明细 → unchecked 空行
|
||
const emptyRow = await workDataDetailCheck(emptyDetail.id);
|
||
assert.equal(emptyRow.status, 'unchecked');
|
||
assert.deepEqual(emptyRow.goods, []);
|
||
assert.deepEqual(emptyRow.checkers, []);
|
||
assert.equal(emptyRow.checked_at, null);
|
||
assert.equal(emptyRow.is_empty, false);
|
||
assert.equal(emptyRow.has_unknown, false);
|
||
});
|
||
|
||
it('workDataDetail 校验:明细ID非法/不存在/任务未审核均拒绝', async () => {
|
||
await assert.rejects(async () => workDataDetailCheck(null), /请提供盘点明细ID/);
|
||
await assert.rejects(async () => workDataDetailCheck(999999999), /盘点明细不存在/);
|
||
|
||
// 任务未审核 → 状态校验拒绝
|
||
const check2 = await createCheck({ type: 'location' });
|
||
const locDetails = await addLocationDetail(check2.id, [ TEST_LOCATION_CODE ]);
|
||
assert.ok(locDetails, '前置:应成功添加库位明细');
|
||
const pendingDetails = await detailCheck(check2.id);
|
||
await assert.rejects(
|
||
async () => workDataDetailCheck(pendingDetails.rows[0].id),
|
||
/仅审核完成(approved)或盘点作业中(checking)/
|
||
);
|
||
});
|
||
|
||
it('workDataDetail 商品钻取:传 id + stock_id 返回 summary 汇总与按库位分行(账面快照/实盘/库位ID/明细ID)', async () => {
|
||
const check = await createCheck({ type: 'goods' });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows[0];
|
||
const snapshot = Number(targetDetail.system_quantity);
|
||
|
||
// 上报库位取一个与该商品明细库位不同的测试库位(验证「已盘库位 vs 明细库位」两类分行)
|
||
const reportCode = [ TEST_LOCATION_CODE, TEST_LOCATION_CODE_2, TEST_EMPTY_LOCATION_CODE ]
|
||
.find(code => code && String(code) !== String(targetDetail.location_code));
|
||
assert.ok(reportCode, '前置:应存在与商品明细库位不同的测试库位');
|
||
|
||
// 上报:盘盈 2
|
||
await reportCheck(check.id, targetDetail.id, snapshot + 2, reportCode);
|
||
|
||
const detail = await workDataDetailCheck({ id: check.id, stockId: targetDetail.stock_id });
|
||
assert.equal(Number(detail.check_id), Number(check.id), '应返回任务ID');
|
||
assert.equal(Number(detail.stock_id), Number(targetDetail.stock_id), '应返回商品ID');
|
||
assert.equal(detail.view, undefined, '不做 view/rows 视图包装');
|
||
assert.ok(detail.item_code !== undefined, '应含商品编码');
|
||
assert.ok(detail.item_name !== undefined, '应含商品名称');
|
||
assert.ok(Array.isArray(detail.images), '应含商品图片数组');
|
||
assert.ok(detail.summary, '应返回汇总数据 summary');
|
||
assert.equal(Number(detail.summary.system_quantity), snapshot, '汇总账面应为明细快照合计');
|
||
assert.equal(Number(detail.summary.checked_quantity), snapshot + 2, '汇总实盘应为实盘合计');
|
||
assert.equal(Number(detail.summary.diff_quantity), 2, '汇总差异应为实盘-账面');
|
||
assert.equal(Number(detail.summary.is_diff), 1);
|
||
|
||
assert.ok(Array.isArray(detail.rows) && detail.rows.length >= 1, '应返回按库位的分行数据 rows');
|
||
const checkedRow = detail.rows.find(row => String(row.location_code) === String(reportCode));
|
||
assert.ok(checkedRow, '已盘库位应出现在 rows');
|
||
// 上报库位不是该商品的明细库位(商品实际库位在别处)→ 该分行无明细ID、快照为 0
|
||
assert.equal(checkedRow.detail_id, null, '非明细库位分行不应带明细ID');
|
||
assert.equal(Number(checkedRow.checked_quantity), snapshot + 2, '分行实盘应与上报一致');
|
||
assert.equal(Number(checkedRow.snapshot_quantity), 0, '无明细快照的库位账面快照为 0');
|
||
assert.equal(Number(checkedRow.diff_quantity), snapshot + 2, '分行差异=实盘-快照');
|
||
assert.equal(typeof checkedRow.system_quantity, 'number', '明盘分行应含当前账面数量');
|
||
assert.equal(typeof checkedRow.locked_quantity, 'number', '明盘分行应含锁定数量');
|
||
assert.ok(checkedRow.checked_at, '已盘库位应有上报时间');
|
||
// 库位ID:location_id 与同义 space_id 均为 wms_location_space.id,可直接回传 report
|
||
assert.equal(Number(checkedRow.location_id), Number(checkedRow.space_id));
|
||
const spaceRow = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: reportCode },
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(Number(checkedRow.location_id), Number(spaceRow.id), '分行库位ID应与库位编码对应');
|
||
|
||
// 明细库位分行:带明细ID与账面快照,未盘(实盘 0,差异=-快照)
|
||
const ownRow = detail.rows.find(row => String(row.location_code) === String(targetDetail.location_code));
|
||
assert.ok(ownRow, '商品明细库位应出现在 rows');
|
||
assert.equal(Number(ownRow.detail_id), Number(targetDetail.id), '明细库位分行应带该库位明细ID');
|
||
assert.equal(Number(ownRow.snapshot_quantity), snapshot, '明细库位分行应带该库位账面快照');
|
||
assert.equal(Number(ownRow.checked_quantity), 0, '未盘库位实盘为 0');
|
||
assert.equal(ownRow.checked_at, null, '未盘库位 checked_at 应为 null');
|
||
|
||
// 与 workData goods 视图行交叉验证
|
||
const goodsAll = await workDataCheck(check.id, { isGoods: true });
|
||
const goodsRow = goodsAll.rows.find(item => Number(item.stock_id) === Number(targetDetail.stock_id));
|
||
assert.ok(goodsRow, 'goods 视图应含该商品行');
|
||
assert.equal(Number(detail.summary.checked_quantity), Number(goodsRow.checked_quantity), '汇总实盘应与 goods 视图一致');
|
||
assert.equal(Number(detail.summary.diff_quantity), Number(goodsRow.diff_quantity), '汇总差异应与 goods 视图一致');
|
||
assert.equal(detail.rows.length, goodsRow.locations.length, '分行数应与 goods 视图 locations 一致');
|
||
|
||
// 兼容:传商品范围明细ID 也返回同一钻取结构
|
||
const byDetailId = await workDataDetailCheck({ detailId: targetDetail.id });
|
||
assert.equal(Number(byDetailId.stock_id), Number(targetDetail.stock_id));
|
||
assert.equal(Number(byDetailId.summary.checked_quantity), snapshot + 2);
|
||
});
|
||
|
||
it('workDataDetail 商品钻取盲盘:不返回数量字段,行信息仍输出', async () => {
|
||
const check = await createCheck({ type: 'goods', mode: 'blind' });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows[0];
|
||
await reportCheck(check.id, targetDetail.id, 6, TEST_LOCATION_CODE);
|
||
|
||
const detail = await workDataDetailCheck({ id: check.id, stockId: targetDetail.stock_id });
|
||
assert.equal(Number(detail.stock_id), Number(targetDetail.stock_id));
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(detail, 'summary'),
|
||
false,
|
||
'盲盘不应返回汇总数量'
|
||
);
|
||
assert.ok(detail.rows.length >= 1, 'rows 应包含商品所在库位');
|
||
for (const row of detail.rows) {
|
||
for (const key of [ 'system_quantity', 'locked_quantity', 'snapshot_quantity', 'checked_quantity', 'diff_quantity' ]) {
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, key),
|
||
false,
|
||
`盲盘分行不应含数量字段 ${key}`
|
||
);
|
||
}
|
||
assert.ok(row.location_code, '盲盘分行仍应输出库位编码');
|
||
assert.ok(Array.isArray(row.record_ids), '盲盘分行仍应输出作业记录ID');
|
||
}
|
||
});
|
||
|
||
it('location 视图:已盘/未盘 status、checkers 合并去重、checked_at 取最近、goods.quantity 为最新覆盖值', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE, TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const checkedDetail = details.rows.find(row => row.location_code === TEST_LOCATION_CODE);
|
||
const uncheckedDetail = details.rows.find(row => row.location_code === TEST_EMPTY_LOCATION_CODE);
|
||
assert.ok(checkedDetail && uncheckedDetail, '前置:两条库位范围行均应存在');
|
||
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 2);
|
||
assert.ok(stockIds.length >= 2, '固定测试库位应存在至少两个商品库存(真实数据依赖)');
|
||
await reportCheck(check.id, checkedDetail.id, 3, undefined, { stockId: stockIds[0], checkerName: '盘点人A' });
|
||
await reportCheck(check.id, checkedDetail.id, 5, undefined, { stockId: stockIds[1], checkerName: '盘点人B' });
|
||
// 覆盖式上报:同商品再报,goods.quantity 应为最新值
|
||
await reportCheck(check.id, checkedDetail.id, 9, undefined, { stockId: stockIds[0], checkerName: '盘点人A' });
|
||
|
||
const data = await workDataCheck(check.id, 'location');
|
||
|
||
const checkedRow = data.rows.find(row => Number(row.detail_id) === Number(checkedDetail.id));
|
||
const uncheckedRow = data.rows.find(row => Number(row.detail_id) === Number(uncheckedDetail.id));
|
||
assert.equal(checkedRow.status, 'checked', '有作业记录的库位行应输出已盘');
|
||
assert.deepEqual(checkedRow.checkers, [ '盘点人A', '盘点人B' ], '盘点人应按记录顺序合并去重');
|
||
assert.ok(checkedRow.checked_at, '已盘行应输出最近盘点时间');
|
||
assert.equal(checkedRow.has_unknown, false);
|
||
|
||
const goodsByStock = new Map(checkedRow.goods.map(item => [ Number(item.stock_id), item ]));
|
||
assert.equal(checkedRow.goods.length, 2, 'goods 应含两个已盘商品');
|
||
assert.equal(goodsByStock.get(stockIds[0]).quantity, 9, '覆盖更新后 quantity 应为最新值');
|
||
assert.equal(goodsByStock.get(stockIds[1]).quantity, 5);
|
||
assert.equal(goodsByStock.get(stockIds[0]).checker_name, '盘点人A');
|
||
|
||
const records = await queryRecords(check.id, checkedDetail.id);
|
||
const latestCheckedAt = records.reduce((latest, record) => {
|
||
const timestamp = new Date(record.checked_at).getTime();
|
||
return latest === null || timestamp > latest ? timestamp : latest;
|
||
}, null);
|
||
assert.equal(
|
||
new Date(checkedRow.checked_at).getTime(),
|
||
latestCheckedAt,
|
||
'checked_at 应为该库位最近一条记录的上报时间'
|
||
);
|
||
|
||
assert.equal(uncheckedRow.status, 'unchecked', '无作业记录的库位行应输出未盘');
|
||
assert.equal(uncheckedRow.checked_at, null);
|
||
assert.deepEqual(uncheckedRow.checkers, []);
|
||
assert.deepEqual(uncheckedRow.goods, []);
|
||
assert.equal(uncheckedRow.has_unknown, false);
|
||
});
|
||
|
||
it('location 视图 goods 子项:商品信息/货主名/条码/商品图片与 getStockDetails 交叉验证', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
// 取一个有效的库存商品(跳过已从库存表删除的商品)
|
||
const storageStockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 5);
|
||
let stockId = null;
|
||
for (const candidate of storageStockIds) {
|
||
const valid = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: candidate, warehouse_id: TEST_WAREHOUSE_ID, is_valid: 'Y' },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
if (valid) {
|
||
stockId = candidate;
|
||
break;
|
||
}
|
||
}
|
||
assert.ok(stockId, '前置:固定测试库位应存在有效库存商品');
|
||
|
||
const reported = await reportCheck(check.id, detail.id, 7, undefined, { stockId });
|
||
const stockDetail = (await ctx.service.systems.stockWarehouse.getStockDetails([ stockId ], {
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
}))[0];
|
||
assert.ok(stockDetail, '前置:商品详情应可查询');
|
||
|
||
const data = await workDataCheck(check.id, 'location');
|
||
const goods = data.rows[0].goods;
|
||
assert.equal(goods.length, 1, 'goods 应只含已盘商品');
|
||
const item = goods[0];
|
||
assert.equal(Number(item.record_id), Number(reported.record.id), 'goods 子项应关联作业记录');
|
||
assert.equal(Number(item.stock_id), stockId);
|
||
assert.equal(item.item_code, stockDetail.item_code || null);
|
||
assert.equal(item.item_name, stockDetail.item_name || null);
|
||
assert.equal(item.barcode, (stockDetail.barcodes[0] && stockDetail.barcodes[0].barcode) || null);
|
||
assert.deepEqual(item.images, stockDetail.image_url || [], 'goods 图片应挂载商品图片列表');
|
||
assert.equal(Number(item.store_id), Number(stockDetail.store_id) || 0);
|
||
assert.equal(item.store_name, await resolveStoreName(Number(stockDetail.store_id)), '货主名应为合约备注优先、公司名兜底');
|
||
assert.equal(item.quantity, 7, '实盘数量应与上报一致');
|
||
assert.equal(item.checker_name, TEST_CREATOR_NAME);
|
||
assert.ok(item.checked_at, '应输出上报时间');
|
||
});
|
||
|
||
it('location 视图 goods 子项:未知商品也并入 goods(stock_id=null 输出记录快照)+ 记录图片挂载 + has_unknown 标记', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
const knownReport = await reportCheck(check.id, detail.id, 4, undefined, { stockId: stockIds[0] });
|
||
const unknownBarcode = uniqueTitle('WORKDATA-UNKNOWN');
|
||
const unknownReport = await reportCheck(check.id, detail.id, 7, undefined, {
|
||
barcode: unknownBarcode,
|
||
itemName: '未知商品快照名称',
|
||
});
|
||
const { file } = await createRecordImage(Number(unknownReport.record.id));
|
||
|
||
const data = await workDataCheck(check.id, 'location');
|
||
const row = data.rows[0];
|
||
|
||
assert.equal(row.has_unknown, true, '存在未知商品记录应标记 has_unknown');
|
||
assert.equal(row.goods.length, 2, '已知商品与未知商品均应进入 goods 子列表');
|
||
const knownGoods = row.goods.find(item => Number(item.record_id) === Number(knownReport.record.id));
|
||
assert.ok(knownGoods, '已知商品应在 goods 子列表');
|
||
assert.ok(Number(knownGoods.stock_id) > 0, '已知商品 stock_id 应为正整数');
|
||
|
||
const unknownGoods = row.goods.find(item => Number(item.record_id) === Number(unknownReport.record.id));
|
||
assert.ok(unknownGoods, '未知商品应在 goods 子列表');
|
||
assert.equal(unknownGoods.stock_id, null, '未知商品 stock_id 应为 null');
|
||
assert.equal(unknownGoods.item_code, unknownBarcode, '未知商品编码列应兑底扫描条码');
|
||
assert.equal(unknownGoods.barcode, unknownBarcode);
|
||
assert.equal(unknownGoods.item_name, '未知商品快照名称', '未知商品名称应为上报快照');
|
||
assert.equal(unknownGoods.quantity, 7);
|
||
assert.equal(unknownGoods.checker_name, TEST_CREATOR_NAME);
|
||
assert.ok(unknownGoods.checked_at, '应输出上报时间');
|
||
assert.deepEqual(unknownGoods.images, [{ id: file.id, url: file.file_url }], '未知商品图片应挂载记录图片');
|
||
});
|
||
|
||
it('库位模式空库位标记:is_empty 上报 → 记录落库 is_empty=1、location 视图行 is_empty=true/goods=[]、计入已盘', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await reportCheck(check.id, details.rows[0].id, 0, undefined, { is_empty: true });
|
||
|
||
assert.equal(result.record.is_empty, true, '空标记记录 is_empty 应为 true');
|
||
assert.equal(result.record.stock_id, null);
|
||
assert.equal(result.record.barcode, null);
|
||
assert.equal(result.record.quantity, 0);
|
||
assert.equal(result.checked_items, 1, '空标记应计入已盘');
|
||
assert.equal(result.diff_items, 0, '账面无库存库位标记空应无差异');
|
||
assert.equal(result.detail_status, 'all_checked');
|
||
|
||
const data = await workDataCheck(check.id);
|
||
const row = data.rows[0];
|
||
assert.equal(row.is_empty, true, 'location 行应输出 is_empty 标记');
|
||
assert.equal(row.status, 'checked', '空库位标记后应视为已盘点');
|
||
assert.deepEqual(row.goods, [], '空库位 goods 应为空');
|
||
assert.equal(row.has_unknown, false);
|
||
assert.ok(row.checkers.includes(TEST_CREATOR_NAME), '空库位盘点人应计入 checkers');
|
||
});
|
||
|
||
it('空库位标记与商品记录互斥:标记空清商品记录,再上报商品清空标记', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
await reportCheck(check.id, details.rows[0].id, 3, undefined, { stockId: stockIds[0] });
|
||
|
||
// 标记空 → 商品记录被清除,仅剩空标记记录
|
||
await reportCheck(check.id, details.rows[0].id, 0, undefined, { is_empty: true });
|
||
const afterEmpty = await queryRecords(check.id, details.rows[0].id);
|
||
assert.equal(afterEmpty.length, 1, '标记空后应仅剩一条空标记记录');
|
||
assert.equal(Number(afterEmpty[0].is_empty), 1, '空标记记录 is_empty 应为 1');
|
||
|
||
// 再上报商品 → 空标记被清除,仅剩商品记录
|
||
const result = await reportCheck(check.id, details.rows[0].id, 5, undefined, { stockId: stockIds[0] });
|
||
const afterGoods = await queryRecords(check.id, details.rows[0].id);
|
||
assert.equal(afterGoods.length, 1, '上报商品后应仅剩一条商品记录');
|
||
assert.equal(Number(afterGoods[0].is_empty), 0);
|
||
assert.equal(Number(afterGoods[0].stock_id), stockIds[0]);
|
||
const data = await workDataCheck(check.id);
|
||
assert.equal(data.rows[0].is_empty, false, '再上报商品后行级 is_empty 应为 false');
|
||
assert.equal(result.detail_status, 'all_checked');
|
||
});
|
||
|
||
it('有账面库存的库位标记空 → 盘亏差异(主表 diff_items=1、result 库位行差异为负)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await reportCheck(check.id, details.rows[0].id, 0, undefined, { is_empty: true });
|
||
assert.equal(result.diff_items, 1, '账面有库存的库位标记空应计盘亏差异');
|
||
|
||
const agg = await resultCheck(check.id);
|
||
const row = agg.rows[0];
|
||
assert.equal(row.is_empty, true);
|
||
assert.equal(row.is_diff, 1);
|
||
assert.ok(Number(row.diff_quantity) < 0, '盘亏差异应为负数');
|
||
assert.equal(row.status, 'checked');
|
||
assert.deepEqual(row.stocks, [], '空库位行 stocks 应为空');
|
||
assert.deepEqual(row.unknown_items, [], '空库位行 unknown_items 应为空');
|
||
});
|
||
|
||
it('商品明细行传 is_empty → 400(仅库位盘点明细支持空库位标记)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, details.rows[0].id, 0, undefined, { is_empty: true });
|
||
}, error => error.code === 400 && /仅库位盘点明细支持空库位标记/.test(error.message));
|
||
});
|
||
|
||
it('markEmpty:库位任务标记空成功(记录/汇总/视图一致)', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await ctx.service.systems.stockCheck.markEmpty({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
detailId: details.rows[0].id,
|
||
});
|
||
|
||
assert.equal(result.record.is_empty, true, '应写入空标记记录');
|
||
assert.equal(result.checked_items, 1);
|
||
assert.equal(result.detail_status, 'all_checked');
|
||
|
||
const data = await workDataCheck(check.id);
|
||
assert.equal(data.rows[0].is_empty, true);
|
||
assert.equal(data.rows[0].status, 'checked');
|
||
});
|
||
|
||
it('markEmpty:非库位任务(商品任务)→ 400 仅库位盘点任务支持空库位标记', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.markEmpty({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
detailId: details.rows[0].id,
|
||
});
|
||
}, error => error.code === 400 && /仅库位盘点任务支持空库位标记/.test(error.message));
|
||
});
|
||
|
||
it('markEmpty:状态不允许(created)→ 400 当前状态不允许盘点作业', async () => {
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
const details = await detailCheck(check.id);
|
||
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.markEmpty({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
detailId: details.rows[0].id,
|
||
});
|
||
}, error => error.code === 400 && /不允许盘点作业/.test(error.message));
|
||
});
|
||
|
||
it('workData 挂载作业照片与 record_ids:location goods 子项 / goods locations 项 / space goods 项', async () => {
|
||
// location 视图:已知商品 goods 子项挂记录图片(FileReference)
|
||
const { check: locationCheck, detail: locationDetail } = await createApprovedLocationCheck();
|
||
const locationStocks = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
const locationReport = await reportCheck(locationCheck.id, locationDetail.id, 3, undefined, { stockId: locationStocks[0] });
|
||
const { file: locationImage } = await createRecordImage(Number(locationReport.record.id));
|
||
|
||
const locationData = await workDataCheck(locationCheck.id);
|
||
const locationGoods = locationData.rows[0].goods[0];
|
||
assert.equal(Number(locationGoods.record_id), Number(locationReport.record.id), 'location goods 子项应含 record_id');
|
||
assert.deepEqual(
|
||
locationGoods.images,
|
||
[{ id: Number(locationImage.id), url: locationImage.file_url }],
|
||
'location goods 子项应挂作业照片(记录图片)'
|
||
);
|
||
|
||
// goods/space 视图:locations/goods 子项输出 record_ids 与作业照片(供编辑移除)
|
||
const pairs = await fetchSpaceStockPairs(1);
|
||
const goodsCheck = await createCheck();
|
||
await addDetail(goodsCheck.id, [ pairs[0].stockId ]);
|
||
await submitCheck(goodsCheck.id);
|
||
await auditCheck(goodsCheck.id, 'approve');
|
||
const details = await detailCheck(goodsCheck.id);
|
||
const goodsReport = await reportCheck(goodsCheck.id, details.rows[0].id, 5, pairs[0].spaceCode);
|
||
const { file: goodsImage } = await createRecordImage(Number(goodsReport.record.id));
|
||
|
||
const goodsData = await workDataCheck(goodsCheck.id, { isGoods: true });
|
||
const locationItem = goodsData.rows[0].locations[0];
|
||
assert.deepEqual(locationItem.record_ids.map(Number), [ Number(goodsReport.record.id) ], 'goods 视图 locations 项应含 record_ids');
|
||
assert.deepEqual(locationItem.images, [{ id: Number(goodsImage.id), url: goodsImage.file_url }], 'goods 视图 locations 项应挂作业照片');
|
||
|
||
const spaceData = await workDataCheck(goodsCheck.id);
|
||
const spaceGoods = spaceData.rows[0].goods[0];
|
||
assert.deepEqual(spaceGoods.record_ids.map(Number), [ Number(goodsReport.record.id) ], 'space 视图 goods 子项应含 record_ids');
|
||
assert.deepEqual(spaceGoods.images, [{ id: Number(goodsImage.id), url: goodsImage.file_url }], 'space 视图 goods 子项应挂作业照片');
|
||
});
|
||
|
||
it('goods 视图明盘:system_quantity/checked_quantity/diff_quantity/is_diff/locations.quantity 与 result 交叉验证', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
const snapshot = Number(firstDetail.system_quantity);
|
||
|
||
await reportCheck(check.id, firstDetail.id, snapshot + 2, TEST_LOCATION_CODE, { checkerName: '盘点人A' });
|
||
await reportCheck(check.id, firstDetail.id, 4, TEST_LOCATION_CODE_2, { checkerName: '盘点人B' });
|
||
|
||
const data = await workDataCheck(check.id, { isGoods: true });
|
||
|
||
assert.equal(data.total, 2);
|
||
|
||
const firstRow = data.rows.find(row => Number(row.stock_id) === Number(firstDetail.stock_id));
|
||
assert.equal(Number(firstRow.system_quantity), snapshot, '账面应来自明细快照');
|
||
assert.equal(firstRow.checked_quantity, snapshot + 6, '已盘合计应为多库位实盘之和');
|
||
assert.equal(firstRow.diff_quantity, 6, '差异=已盘合计-账面快照');
|
||
assert.equal(firstRow.is_diff, 1);
|
||
const quantityByCode = new Map(firstRow.locations.map(item => [ item.location_code, Number(item.quantity) ]));
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE), snapshot + 2, '已盘库位实盘应与上报一致');
|
||
assert.equal(quantityByCode.get(TEST_LOCATION_CODE_2), 4, '已盘库位实盘应与上报一致');
|
||
const checkedLocationA = firstRow.locations.find(item => item.location_code === TEST_LOCATION_CODE);
|
||
const checkedLocationB = firstRow.locations.find(item => item.location_code === TEST_LOCATION_CODE_2);
|
||
assert.equal(checkedLocationA.checker_name, '盘点人A');
|
||
assert.equal(checkedLocationB.checker_name, '盘点人B');
|
||
assert.ok(checkedLocationA.checked_at && checkedLocationB.checked_at);
|
||
assert.equal(typeof checkedLocationA.system_quantity, 'number', '明盘已盘库位应含账面数量');
|
||
assert.equal(typeof checkedLocationB.system_quantity, 'number', '明盘已盘库位应含账面数量');
|
||
assert.equal(typeof checkedLocationA.locked_quantity, 'number', '明盘已盘库位应含锁定数量');
|
||
assert.equal(typeof checkedLocationB.locked_quantity, 'number', '明盘已盘库位应含锁定数量');
|
||
|
||
// 与 result 聚合交叉验证:checked_quantity/diff_quantity/is_diff 口径一致
|
||
const result = await resultCheck(check.id);
|
||
const resultFirst = result.rows.find(row => Number(row.id) === Number(firstDetail.id));
|
||
assert.equal(firstRow.checked_quantity, resultFirst.checked_quantity);
|
||
assert.equal(firstRow.diff_quantity, resultFirst.diff_quantity);
|
||
assert.equal(firstRow.is_diff, resultFirst.is_diff);
|
||
|
||
// 未盘行:明盘按 0 处理、locations 为商品所在库位列表(无作业信息)
|
||
const secondRow = data.rows.find(row => Number(row.stock_id) === Number(secondDetail.stock_id));
|
||
assert.equal(Number(secondRow.system_quantity), Number(secondDetail.system_quantity));
|
||
assert.equal(secondRow.checked_quantity, 0);
|
||
assert.equal(secondRow.diff_quantity, 0);
|
||
assert.equal(secondRow.is_diff, 0);
|
||
assert.ok(Array.isArray(secondRow.locations), '未盘行 locations 应为数组(商品所在库位列表)');
|
||
for (const location of secondRow.locations) {
|
||
assert.equal(location.checked_at, null, '未盘库位 checked_at 应为 null');
|
||
assert.equal(Number(location.quantity), 0, '未盘库位实盘应为 0');
|
||
assert.equal(typeof location.system_quantity, 'number', '明盘未盘库位应含账面数量');
|
||
assert.equal(typeof location.locked_quantity, 'number', '明盘未盘库位应含锁定数量');
|
||
}
|
||
});
|
||
|
||
it('goods 视图:商品信息/store_name/barcode/images 挂载(未盘行 locations=商品所在库位列表、明盘零差异)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
stocks.map(stock => stock.id),
|
||
{ warehouseId: TEST_WAREHOUSE_ID }
|
||
);
|
||
|
||
const data = await workDataCheck(check.id, { isGoods: true });
|
||
assert.equal(data.total, 2);
|
||
|
||
for (const row of data.rows) {
|
||
const detail = details.rows.find(item => Number(item.stock_id) === Number(row.stock_id));
|
||
const stockDetail = stockDetails.find(item => Number(item.id) === Number(row.stock_id));
|
||
assert.ok(stockDetail, '前置:商品详情应可查询');
|
||
assert.equal(row.item_code, stockDetail.item_code || detail.item_code || null);
|
||
assert.equal(row.item_name, stockDetail.item_name || detail.item_name || null);
|
||
assert.equal(row.spec, (stockDetail.sku_property || detail.spec) || null);
|
||
assert.equal(Number(row.store_id), Number(stockDetail.store_id) || 0);
|
||
assert.equal(row.store_name, await resolveStoreName(Number(row.store_id)));
|
||
assert.equal(row.barcode, (stockDetail.barcodes[0] && stockDetail.barcodes[0].barcode) || null);
|
||
assert.deepEqual(row.images, stockDetail.image_url || [], 'images 应挂载商品图片列表');
|
||
|
||
// 未盘行 locations = 商品所在全部库位(wms_storage,与业务口径一致排除无头库位),每库位无作业信息、实盘 0
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
stock_id: Number(row.stock_id),
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [ctx.app.Sequelize.Op.in]: ctx.app.Sequelize.literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [ 'space_id' ],
|
||
raw: true,
|
||
});
|
||
// 有效库位数:storage 行中能在库位表查到(有 space_code)的库位
|
||
const storageSpaceIds = [ ...new Set(storageRows.map(item => Number(item.space_id)).filter(id => id > 0)) ];
|
||
let validSpaceCount = 0;
|
||
if (storageSpaceIds.length > 0) {
|
||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||
where: { id: { [ctx.app.Sequelize.Op.in]: storageSpaceIds } },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
validSpaceCount = spaceRows.length;
|
||
}
|
||
assert.ok(
|
||
row.locations.length >= validSpaceCount,
|
||
'未盘行 locations 应包含商品所在全部库位'
|
||
);
|
||
for (const location of row.locations) {
|
||
assert.equal(location.checked_at, null, '未盘库位 checked_at 应为 null');
|
||
assert.deepEqual(location.record_ids, [], '未盘库位 record_ids 应为空数组');
|
||
assert.equal(Number(location.quantity), 0, '未盘库位实盘应为 0');
|
||
assert.equal(typeof location.system_quantity, 'number', '明盘未盘库位应含账面数量');
|
||
assert.equal(typeof location.locked_quantity, 'number', '明盘未盘库位应含锁定数量');
|
||
// locations 应回传库位ID(供调用方直接回传 stock.check.report 的 location_id)
|
||
assert.ok(
|
||
Number(location.location_id) > 0,
|
||
'locations 应含有效库位ID(location_id)'
|
||
);
|
||
if (location.location_code) {
|
||
const spaceRow = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: location.location_code },
|
||
order: [[ 'id', 'ASC' ]],
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
assert.equal(Number(location.location_id), Number(spaceRow.id), 'location_id 应与库位编码对应');
|
||
}
|
||
}
|
||
assert.equal(Number(row.system_quantity), Number(detail.system_quantity), '账面应为明细快照');
|
||
assert.equal(row.checked_quantity, 0);
|
||
assert.equal(row.diff_quantity, 0);
|
||
assert.equal(row.is_diff, 0);
|
||
}
|
||
});
|
||
|
||
it('goods 视图多库位商品按商品汇总为一行:账面快照合计、跨明细按库位合并、workDataDetail 返回汇总+分行', async () => {
|
||
const { Op, literal } = ctx.app.Sequelize;
|
||
// 前置:找一个在两个及以上启用库位都有库存的商品(addDetail 按「商品 + 库位」拆多行明细)
|
||
const storageRows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
is_enabled: 1,
|
||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||
},
|
||
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
|
||
group: [ 'stock_id', 'space_id' ],
|
||
raw: true,
|
||
});
|
||
const spacesByStock = new Map();
|
||
for (const row of storageRows) {
|
||
const stockId = Number(row.stock_id);
|
||
if (!spacesByStock.has(stockId)) {
|
||
spacesByStock.set(stockId, []);
|
||
}
|
||
spacesByStock.get(stockId).push(row);
|
||
}
|
||
const multiStockEntry = [ ...spacesByStock.entries() ].find(([ , rows ]) => rows.length >= 2);
|
||
assert.ok(multiStockEntry, '前置:测试库应存在多库位库存商品');
|
||
const multiStockId = Number(multiStockEntry[0]);
|
||
const multiStock = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: multiStockId, warehouse_id: TEST_WAREHOUSE_ID },
|
||
raw: true,
|
||
});
|
||
assert.ok(multiStock, '前置:多库位商品应存在于 wms_stock_warehouse');
|
||
|
||
const check = await createCheck({ type: 'goods', storeId: multiStock.store_id || null });
|
||
await addDetail(check.id, [ multiStockId ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.rows.length, multiStockEntry[1].length, '前置:多库位商品按库位拆多行明细');
|
||
const detailIds = details.rows.map(row => Number(row.id));
|
||
const snapshotTotal = details.rows.reduce((sum, row) => sum + (Number(row.system_quantity) || 0), 0);
|
||
|
||
// 两个库位分别上报(记录落在各自明细行),汇总行应合并
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
const firstCode = String(firstDetail.location_code || '').trim();
|
||
const secondCode = String(secondDetail.location_code || '').trim();
|
||
const firstReport = await reportCheck(check.id, firstDetail.id, 7, firstCode);
|
||
const secondReport = await reportCheck(check.id, secondDetail.id, 3, secondCode);
|
||
|
||
const data = await workDataCheck(check.id, { isGoods: true });
|
||
assert.equal(data.total, 1, '同商品多库位明细应汇总为一行');
|
||
const row = data.rows[0];
|
||
assert.equal(Number(row.stock_id), multiStockId);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, 'detail_id'),
|
||
false,
|
||
'goods 汇总视图行不再输出明细ID(逐库位明细走 workDataDetail)'
|
||
);
|
||
assert.equal(Number(row.system_quantity), snapshotTotal, '行级账面应为各库位明细快照之和');
|
||
assert.equal(row.checked_quantity, 10, '行级已盘合计应跨明细合并');
|
||
assert.equal(row.diff_quantity, 10 - snapshotTotal);
|
||
assert.equal(row.is_diff, row.diff_quantity !== 0 ? 1 : 0);
|
||
|
||
const quantityByCode = new Map(row.locations.map(item => [ item.location_code, Number(item.quantity) ]));
|
||
assert.equal(quantityByCode.get(firstCode), 7, '首个库位实盘应来自其明细下记录');
|
||
assert.equal(quantityByCode.get(secondCode), 3, '第二个库位实盘应来自另一条明细下记录');
|
||
const firstLocation = row.locations.find(item => item.location_code === firstCode);
|
||
const secondLocation = row.locations.find(item => item.location_code === secondCode);
|
||
assert.deepEqual(firstLocation.record_ids, [ Number(firstReport.record.id) ]);
|
||
assert.deepEqual(secondLocation.record_ids, [ Number(secondReport.record.id) ]);
|
||
// locations 每项带该库位明细ID 与账面快照(供逐库位上报/钻取)
|
||
assert.equal(Number(firstLocation.detail_id), Number(firstDetail.id));
|
||
assert.equal(Number(secondLocation.detail_id), Number(secondDetail.id));
|
||
assert.equal(Number(firstLocation.snapshot_quantity), Number(firstDetail.system_quantity));
|
||
assert.equal(Number(secondLocation.snapshot_quantity), Number(secondDetail.system_quantity));
|
||
|
||
// workDataDetail:id + stock_id 返回该商品的汇总 + 按库位分行
|
||
const detail = await workDataDetailCheck({ id: check.id, stockId: multiStockId });
|
||
assert.equal(detail.rows.length, detailIds.length, '分行数应等于该商品的库位明细行数');
|
||
assert.equal(Number(detail.summary.system_quantity), snapshotTotal, '汇总账面=各行快照之和');
|
||
assert.equal(Number(detail.summary.checked_quantity), 10, '汇总实盘=各行实盘之和');
|
||
assert.equal(Number(detail.summary.diff_quantity), 10 - snapshotTotal);
|
||
const firstDetailRow = detail.rows.find(item => item.location_code === firstCode);
|
||
const secondDetailRow = detail.rows.find(item => item.location_code === secondCode);
|
||
assert.equal(Number(firstDetailRow.detail_id), Number(firstDetail.id), '分行应带该库位明细ID');
|
||
assert.equal(Number(secondDetailRow.detail_id), Number(secondDetail.id));
|
||
assert.equal(Number(firstDetailRow.checked_quantity), 7);
|
||
assert.equal(Number(secondDetailRow.checked_quantity), 3);
|
||
assert.equal(Number(firstDetailRow.diff_quantity), 7 - Number(firstDetail.system_quantity));
|
||
assert.equal(Number(secondDetailRow.diff_quantity), 3 - Number(secondDetail.system_quantity));
|
||
// 分行实盘之和 = 汇总实盘(与 goods 视图行级 checked_quantity 一致)
|
||
assert.equal(
|
||
detail.rows.reduce((sum, item) => sum + (Number(item.checked_quantity) || 0), 0),
|
||
Number(row.checked_quantity)
|
||
);
|
||
});
|
||
|
||
it('report 兼容:不传 detail_id 时按 id + stock_id + space_id 反查该商品明细上报', async () => {
|
||
const check = await createCheck({ type: 'goods' });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows[0];
|
||
const spaceId = Number(targetDetail.location_id);
|
||
const reported = await ctx.service.systems.stockCheck.report({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
stockId: targetDetail.stock_id,
|
||
spaceId,
|
||
quantity: 12,
|
||
checkerId: TEST_CREATOR_ID,
|
||
checkerName: TEST_CREATOR_NAME,
|
||
});
|
||
assert.equal(Number(reported.detail_id), Number(targetDetail.id), '应反查命中该商品的库位明细');
|
||
assert.equal(Number(reported.record.stock_id), Number(targetDetail.stock_id));
|
||
assert.equal(Number(reported.record.quantity), 12);
|
||
|
||
// 既无 detail_id 也无 stock_id → 400
|
||
await assert.rejects(
|
||
async () => ctx.service.systems.stockCheck.report({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
spaceId,
|
||
quantity: 1,
|
||
checkerId: TEST_CREATOR_ID,
|
||
checkerName: TEST_CREATOR_NAME,
|
||
}),
|
||
/盘点明细ID不能为空/
|
||
);
|
||
|
||
// 商品不在本任务盘点范围 → 400
|
||
await assert.rejects(
|
||
async () => ctx.service.systems.stockCheck.report({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
stockId: 999999999,
|
||
spaceId,
|
||
quantity: 1,
|
||
checkerId: TEST_CREATOR_ID,
|
||
checkerName: TEST_CREATOR_NAME,
|
||
}),
|
||
/盘点明细不存在/
|
||
);
|
||
});
|
||
|
||
it('账面取值按任务静态标记:静态任务取明细快照、非静态任务取当前 storage(goods/space/workDataDetail 一致)', async () => {
|
||
// 静态任务上报要求商品已完成拣货(无锁定量),故只取无锁定商品
|
||
const stocks = await fetchStockRows(1, { requireUnlocked: true });
|
||
const targetStock = stocks[0];
|
||
const DELTA = 7;
|
||
|
||
/**
|
||
* 构造一个已审核通过的商品任务,并在审核后人为改动该库位账面(模拟盘点期间库存变动)。
|
||
*
|
||
* @param {boolean} isStatic 是否静态盘点。
|
||
* @return {Promise<Object>} { check, detailRow, snapshot, liveBook, spaceId }。
|
||
*/
|
||
async function prepareCheck(isStatic) {
|
||
const check = await createCheck({
|
||
title: uniqueTitle(`账面口径-${isStatic ? '静态' : '非静态'}`),
|
||
type: 'goods',
|
||
isStatic,
|
||
});
|
||
await addDetail(check.id, [ targetStock.id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailRow = details.rows[0];
|
||
const spaceId = Number(detailRow.location_id);
|
||
const snapshot = Number(detailRow.system_quantity);
|
||
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity + :delta
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{ replacements: { delta: DELTA, warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
const liveRows = await ctx.model.query(
|
||
`SELECT COALESCE(SUM(available_quantity), 0) AS total
|
||
FROM wms_storage
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{
|
||
replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
return { check, detailRow, spaceId, snapshot, liveBook: Number(liveRows[0] && liveRows[0].total) || 0 };
|
||
}
|
||
|
||
/**
|
||
* 回滚人为库存变动。
|
||
*
|
||
* @param {number} spaceId 库位ID。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async function restoreBook(spaceId) {
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity - :delta
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{ replacements: { delta: DELTA, warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
}
|
||
|
||
const spaceIdList = [];
|
||
const checkIdList = [];
|
||
try {
|
||
// ── 静态任务:账面=快照(冻结),当前 storage 仅作为参考字段输出 ──
|
||
const staticPrepared = await prepareCheck(true);
|
||
spaceIdList.push(staticPrepared.spaceId);
|
||
checkIdList.push(staticPrepared.check.id);
|
||
assert.ok(staticPrepared.liveBook > staticPrepared.snapshot, '前置:人为变动后当前账面应大于快照');
|
||
|
||
const staticGoods = await workDataCheck(staticPrepared.check.id, { isGoods: true });
|
||
const staticRow = staticGoods.rows[0];
|
||
const staticLocation = staticRow.locations.find(item => item.detail_id !== null);
|
||
assert.equal(Number(staticRow.is_static), 1);
|
||
assert.equal(staticRow.book_source, 'snapshot', '静态任务账面来源应为快照');
|
||
assert.equal(
|
||
Number(staticRow.system_quantity),
|
||
staticPrepared.snapshot,
|
||
'静态任务行级账面应取明细快照(不受盘点期间库存变动影响)'
|
||
);
|
||
assert.equal(Number(staticLocation.system_quantity), staticPrepared.snapshot, '静态任务库位账面应取快照');
|
||
assert.equal(Number(staticLocation.snapshot_quantity), staticPrepared.snapshot);
|
||
assert.equal(Number(staticLocation.storage_quantity), staticPrepared.liveBook, '当前 storage 账面作为参考字段输出');
|
||
|
||
// 上报后差异按快照计算
|
||
await reportCheck(staticPrepared.check.id, staticPrepared.detailRow.id, staticPrepared.snapshot - 2, staticPrepared.detailRow.location_code);
|
||
const staticAfterReport = await workDataCheck(staticPrepared.check.id, { isGoods: true });
|
||
assert.equal(
|
||
Number(staticAfterReport.rows[0].diff_quantity),
|
||
-2,
|
||
'静态任务差异=实盘-快照(而非实盘-当前账面)'
|
||
);
|
||
|
||
// space 视图同口径
|
||
const staticSpace = await workDataCheck(staticPrepared.check.id);
|
||
const staticSpaceItem = staticSpace.rows
|
||
.flatMap(row => row.goods || [])
|
||
.find(item => Number(item.stock_id) === Number(targetStock.id));
|
||
assert.ok(staticSpaceItem, 'space 视图应含该商品');
|
||
assert.equal(Number(staticSpaceItem.system_quantity), staticPrepared.snapshot, 'space 视图静态任务账面应取快照');
|
||
assert.equal(Number(staticSpaceItem.storage_quantity), staticPrepared.liveBook);
|
||
|
||
// workDataDetail 同口径
|
||
const staticDrill = await workDataDetailCheck({ id: staticPrepared.check.id, stockId: targetStock.id });
|
||
assert.equal(Number(staticDrill.is_static), 1);
|
||
assert.equal(staticDrill.book_source, 'snapshot');
|
||
assert.equal(Number(staticDrill.summary.system_quantity), staticPrepared.snapshot, '钻取汇总账面应取快照');
|
||
const staticDrillRow = staticDrill.rows.find(item => item.detail_id !== null);
|
||
assert.equal(Number(staticDrillRow.system_quantity), staticPrepared.snapshot);
|
||
assert.equal(Number(staticDrillRow.snapshot_quantity), staticPrepared.snapshot);
|
||
assert.equal(Number(staticDrillRow.storage_quantity), staticPrepared.liveBook);
|
||
|
||
// ── 非静态任务:账面=当前 storage,快照仅作参考字段 ──
|
||
const normalPrepared = await prepareCheck(false);
|
||
spaceIdList.push(normalPrepared.spaceId);
|
||
checkIdList.push(normalPrepared.check.id);
|
||
|
||
const normalGoods = await workDataCheck(normalPrepared.check.id, { isGoods: true });
|
||
const normalRow = normalGoods.rows[0];
|
||
const normalLocation = normalRow.locations.find(item => item.detail_id !== null);
|
||
assert.equal(Number(normalRow.is_static), 0);
|
||
assert.equal(normalRow.book_source, 'storage', '非静态任务账面来源应为当前 storage');
|
||
assert.equal(Number(normalRow.system_quantity), normalPrepared.liveBook, '非静态任务行级账面应取当前 storage');
|
||
assert.equal(Number(normalLocation.system_quantity), normalPrepared.liveBook);
|
||
assert.equal(Number(normalLocation.snapshot_quantity), normalPrepared.snapshot, '快照仍作为参考字段输出');
|
||
|
||
await reportCheck(normalPrepared.check.id, normalPrepared.detailRow.id, normalPrepared.liveBook - 3, normalPrepared.detailRow.location_code);
|
||
const normalAfterReport = await workDataCheck(normalPrepared.check.id, { isGoods: true });
|
||
assert.equal(
|
||
Number(normalAfterReport.rows[0].diff_quantity),
|
||
-3,
|
||
'非静态任务差异=实盘-当前账面'
|
||
);
|
||
|
||
const normalSpace = await workDataCheck(normalPrepared.check.id);
|
||
const normalSpaceItem = normalSpace.rows
|
||
.flatMap(row => row.goods || [])
|
||
.find(item => Number(item.stock_id) === Number(targetStock.id));
|
||
assert.equal(Number(normalSpaceItem.system_quantity), normalPrepared.liveBook, 'space 视图非静态任务账面应取当前 storage');
|
||
|
||
const normalDrill = await workDataDetailCheck({ id: normalPrepared.check.id, stockId: targetStock.id });
|
||
assert.equal(Number(normalDrill.is_static), 0);
|
||
assert.equal(normalDrill.book_source, 'storage');
|
||
assert.equal(Number(normalDrill.summary.system_quantity), normalPrepared.liveBook);
|
||
} finally {
|
||
for (const spaceId of spaceIdList) {
|
||
await restoreBook(spaceId);
|
||
}
|
||
// 收尾:完成盘点释放静态锁定,避免留存的 checking 静态任务影响后续锁定相关用例
|
||
for (const checkId of checkIdList) {
|
||
const latestRow = await findCheckRow(checkId);
|
||
if (latestRow && [ 'approved', 'checking' ].includes(String(latestRow.status))) {
|
||
await ctx.service.systems.stockCheck.finish({ warehouseId: TEST_WAREHOUSE_ID, id: checkId });
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
it('静态盘点拣货完成标记:商品仍有锁定量时 picking_completed=0 且 report 拒绝上报', async () => {
|
||
const stocks = await fetchStockRows(1, { requireUnlocked: true });
|
||
const targetStock = stocks[0];
|
||
const LOCK_DELTA = 2;
|
||
|
||
// 前置:测试商品在测试仓库不应有锁定量(否则 picking_completed 初值即为 0,用例无法区分)
|
||
const lockedBefore = await ctx.model.query(
|
||
`SELECT COALESCE(SUM(locked_quantity), 0) AS total
|
||
FROM wms_storage
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId`,
|
||
{
|
||
replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
assert.equal(
|
||
Number(lockedBefore[0] && lockedBefore[0].total) || 0,
|
||
0,
|
||
'前置:测试商品在测试仓库不应有锁定量'
|
||
);
|
||
|
||
const check = await createCheck({
|
||
title: uniqueTitle('静态拣货完成'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
});
|
||
await addDetail(check.id, [ targetStock.id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailRow = details.rows[0];
|
||
const spaceId = Number(detailRow.location_id);
|
||
|
||
// 模拟分配储位:available → locked(quantity 不变),即该商品仍有在途待拣出库
|
||
const shiftLock = async delta => {
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity - :delta,
|
||
locked_quantity = locked_quantity + :delta
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{ replacements: { delta, warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
};
|
||
|
||
try {
|
||
await shiftLock(LOCK_DELTA);
|
||
|
||
// goods 视图:picking_completed=0,并输出该商品仓库内锁定量合计
|
||
const lockedGoods = await workDataCheck(check.id, { isGoods: true });
|
||
const lockedRow = lockedGoods.rows[0];
|
||
assert.equal(Number(lockedRow.is_static), 1);
|
||
assert.equal(Number(lockedRow.picking_completed), 0, '商品仍有锁定量时 picking_completed 应为 0');
|
||
assert.equal(Number(lockedRow.locked_quantity), LOCK_DELTA, '行级应输出该商品锁定量合计');
|
||
|
||
// workDataDetail 同口径
|
||
const lockedDrill = await workDataDetailCheck({ id: check.id, stockId: targetStock.id });
|
||
assert.equal(Number(lockedDrill.picking_completed), 0, '钻取 picking_completed 应为 0');
|
||
assert.equal(Number(lockedDrill.locked_quantity), LOCK_DELTA, '钻取应输出该商品锁定量合计');
|
||
|
||
// space 视图(workData 默认视图)goods 子项同口径
|
||
const lockedSpace = await workDataCheck(check.id);
|
||
const lockedSpaceItem = lockedSpace.rows
|
||
.flatMap(row => row.goods || [])
|
||
.find(item => Number(item.stock_id) === Number(targetStock.id));
|
||
assert.ok(lockedSpaceItem, 'space 视图应含该商品');
|
||
assert.equal(Number(lockedSpaceItem.picking_completed), 0, 'space 视图 picking_completed 应为 0');
|
||
|
||
// workDataSpaceDetails(space 视图分页版)同口径
|
||
const lockedSpaceDetails = await ctx.service.systems.stockCheck.workDataSpaceDetails({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: spaceId,
|
||
});
|
||
const lockedSpaceDetailItem = (lockedSpaceDetails.rows[0] && lockedSpaceDetails.rows[0].goods || [])
|
||
.find(item => Number(item.stock_id) === Number(targetStock.id));
|
||
assert.ok(lockedSpaceDetailItem, 'workDataSpaceDetails 库位行应含该商品');
|
||
assert.equal(
|
||
Number(lockedSpaceDetailItem.picking_completed),
|
||
0,
|
||
'workDataSpaceDetails picking_completed 应为 0'
|
||
);
|
||
|
||
// 未完成拣货:report 拒绝上报
|
||
await assert.rejects(
|
||
async () => reportCheck(check.id, detailRow.id, 1, detailRow.location_code),
|
||
/商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货/
|
||
);
|
||
|
||
// 拣货完成(锁定量清零)后 picking_completed=1,可正常上报
|
||
await shiftLock(-LOCK_DELTA);
|
||
const doneGoods = await workDataCheck(check.id, { isGoods: true });
|
||
assert.equal(Number(doneGoods.rows[0].picking_completed), 1, '无锁定量时 picking_completed 应为 1');
|
||
assert.equal(Number(doneGoods.rows[0].locked_quantity), 0, '无锁定量时行级锁定量应为 0');
|
||
const doneSpaceDetails = await ctx.service.systems.stockCheck.workDataSpaceDetails({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: spaceId,
|
||
});
|
||
const doneSpaceDetailItem = (doneSpaceDetails.rows[0] && doneSpaceDetails.rows[0].goods || [])
|
||
.find(item => Number(item.stock_id) === Number(targetStock.id));
|
||
assert.equal(
|
||
Number(doneSpaceDetailItem && doneSpaceDetailItem.picking_completed),
|
||
1,
|
||
'拣货完成后 workDataSpaceDetails 的 picking_completed 应为 1'
|
||
);
|
||
const reported = await reportCheck(check.id, detailRow.id, 1, detailRow.location_code);
|
||
assert.equal(Number(reported.record.quantity), 1, '拣货完成后应允许上报');
|
||
} finally {
|
||
// 收尾:完成盘点释放静态锁定,避免留存的 checking 静态任务影响后续锁定相关用例
|
||
const latestRow = await findCheckRow(check.id);
|
||
if (latestRow && [ 'approved', 'checking' ].includes(String(latestRow.status))) {
|
||
await ctx.service.systems.stockCheck.finish({ warehouseId: TEST_WAREHOUSE_ID, id: check.id });
|
||
}
|
||
// 兜底回滚:无论用例是否中途失败,都把锁定量搬回可用数量
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity + locked_quantity,
|
||
locked_quantity = 0
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId
|
||
AND locked_quantity > 0`,
|
||
{ replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
}
|
||
});
|
||
|
||
it('goods 视图盲盘:不含任何数量字段(system_quantity/checked_quantity/diff_quantity/is_diff 与 locations.quantity)', async () => {
|
||
const check = await createCheck({ mode: 'blind' });
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 5, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE_2);
|
||
|
||
const data = await workDataCheck(check.id, { isGoods: true });
|
||
const row = data.rows[0];
|
||
assert.ok(row.locations.length >= 2, 'locations 应包含商品所在库位与已盘库位');
|
||
const checkedCodes = [ TEST_LOCATION_CODE, TEST_LOCATION_CODE_2 ];
|
||
for (const code of checkedCodes) {
|
||
const location = row.locations.find(item => String(item.location_code) === code);
|
||
assert.ok(location, `已盘库位 ${code} 应出现在 locations`);
|
||
assert.ok(location.checked_at, `已盘库位 ${code} 应有上报时间`);
|
||
}
|
||
assert.ok(
|
||
row.locations.some(location => !location.checked_at),
|
||
'未盘库位 checked_at 应为 null'
|
||
);
|
||
for (const key of [ 'system_quantity', 'checked_quantity', 'diff_quantity', 'is_diff' ]) {
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, key),
|
||
false,
|
||
`盲盘行不应包含数量字段 ${key}`
|
||
);
|
||
}
|
||
for (const location of row.locations) {
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(location, 'quantity'),
|
||
false,
|
||
'盲盘 locations 不应包含 quantity'
|
||
);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(location, 'system_quantity'),
|
||
false,
|
||
'盲盘 locations 不应包含账面数量'
|
||
);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(location, 'locked_quantity'),
|
||
false,
|
||
'盲盘 locations 不应包含锁定数量'
|
||
);
|
||
assert.ok(location.location_code, '盲盘仍应输出库位编码');
|
||
}
|
||
});
|
||
|
||
it('space 视图:库位聚合与 wms_storage 一致、按拣货路径排序(pick_sequence/pick_priority/id 兜底)', async () => {
|
||
const pairs = await fetchSpaceStockPairs(3);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const data = await workDataCheck(check.id, 'space');
|
||
const returnedIds = data.rows.map(row => Number(row.id));
|
||
|
||
assert.deepEqual(
|
||
[ ...returnedIds ].sort((left, right) => left - right),
|
||
pairs.map(pair => pair.spaceId).sort((left, right) => left - right),
|
||
'聚合库位集合应与任务商品所在库位(wms_storage)一致'
|
||
);
|
||
for (const pair of pairs) {
|
||
const row = data.rows.find(item => Number(item.id) === pair.spaceId);
|
||
assert.ok(row, `任务商品所在库位 ${pair.spaceId} 应出现在聚合列表`);
|
||
assert.equal(row.space_code, pair.spaceCode || null, '库位编码应来自库位表');
|
||
assert.equal(row.custom_name, pair.customName || null, '库位名称应为库位表 custom_name 原值');
|
||
assert.equal(row.goods.length, 1, '该库位仅一个任务商品,goods 应恰好一条');
|
||
assert.equal(Number(row.goods[0].stock_id), pair.stockId, '库位行应挂载该库位的任务商品');
|
||
}
|
||
|
||
// 排序口径:pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底(与实现一致)
|
||
const { Op } = ctx.app.Sequelize;
|
||
const locationRows = await ctx.model.LocationSpace.findAll({
|
||
where: { id: { [Op.in]: returnedIds } },
|
||
attributes: [ 'id', 'pick_sequence', 'pick_priority' ],
|
||
raw: true,
|
||
});
|
||
const locationById = new Map(locationRows.map(row => [ Number(row.id), row ]));
|
||
const expectedIds = [ ...returnedIds ].sort((left, right) => {
|
||
const leftRow = locationById.get(left) || {};
|
||
const rightRow = locationById.get(right) || {};
|
||
const sequenceDiff = Number(leftRow.pick_sequence || 0) - Number(rightRow.pick_sequence || 0);
|
||
if (sequenceDiff !== 0) {
|
||
return sequenceDiff;
|
||
}
|
||
const priorityDiff = Number(rightRow.pick_priority || 0) - Number(leftRow.pick_priority || 0);
|
||
if (priorityDiff !== 0) {
|
||
return priorityDiff;
|
||
}
|
||
return left - right;
|
||
});
|
||
assert.deepEqual(returnedIds, expectedIds, 'space 视图应按拣货路径排序');
|
||
});
|
||
|
||
it('space 视图明盘:库位账面=wms_storage SUM、已盘=该库位实盘合计、status 已盘/未盘', async () => {
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const reported = pairs[0];
|
||
const reportedDetail = details.rows.find(row => Number(row.stock_id) === reported.stockId);
|
||
const reportedQuantity = reported.book + 2;
|
||
await reportCheck(check.id, reportedDetail.id, reportedQuantity, reported.spaceCode);
|
||
|
||
const data = await workDataCheck(check.id, 'space');
|
||
|
||
const reportedRow = data.rows.find(row => Number(row.id) === reported.spaceId);
|
||
assert.ok(reportedRow, '已盘库位应出现在聚合列表');
|
||
assert.equal(reportedRow.goods.length, 1);
|
||
const reportedGoods = reportedRow.goods[0];
|
||
assert.equal(Number(reportedGoods.detail_id), Number(reportedDetail.id));
|
||
assert.equal(Number(reportedGoods.stock_id), reported.stockId);
|
||
assert.equal(Number(reportedGoods.system_quantity), reported.book, '库位账面应为 wms_storage SUM(可用数量)');
|
||
assert.equal(Number(reportedGoods.locked_quantity), reported.bookLocked, '库位锁定数量应为 wms_storage SUM(locked_quantity)');
|
||
assert.equal(Number(reportedGoods.checked_quantity), reportedQuantity, '已盘应为该库位实盘合计');
|
||
assert.equal(reportedGoods.status, 'checked');
|
||
|
||
const unreported = pairs[1];
|
||
const unreportedRow = data.rows.find(row => Number(row.id) === unreported.spaceId);
|
||
assert.ok(unreportedRow, '未盘库位应出现在聚合列表');
|
||
assert.equal(unreportedRow.goods.length, 1);
|
||
const unreportedGoods = unreportedRow.goods[0];
|
||
assert.equal(Number(unreportedGoods.system_quantity), unreported.book);
|
||
assert.equal(Number(unreportedGoods.locked_quantity), unreported.bookLocked, '未盘库位锁定数量也应输出');
|
||
assert.equal(Number(unreportedGoods.checked_quantity), 0, '未盘库位已盘数量应为 0');
|
||
assert.equal(unreportedGoods.status, 'unchecked');
|
||
});
|
||
|
||
it('space 视图盲盘:不返回数量字段、status 与库位信息仍输出', async () => {
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck({ mode: 'blind' });
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const reportedDetail = details.rows.find(row => Number(row.stock_id) === pairs[0].stockId);
|
||
await reportCheck(check.id, reportedDetail.id, 6, pairs[0].spaceCode);
|
||
|
||
const data = await workDataCheck(check.id, 'space');
|
||
|
||
const reportedRow = data.rows.find(row => Number(row.id) === pairs[0].spaceId);
|
||
const unreportedRow = data.rows.find(row => Number(row.id) === pairs[1].spaceId);
|
||
assert.ok(reportedRow && unreportedRow, '两个库位均应出现在聚合列表');
|
||
for (const [ row, pair ] of [[ reportedRow, pairs[0] ], [ unreportedRow, pairs[1] ]]) {
|
||
assert.equal(row.space_code, pair.spaceCode || null);
|
||
assert.equal(row.custom_name, pair.customName || null);
|
||
assert.equal(row.goods.length, 1);
|
||
const goods = row.goods[0];
|
||
assert.equal(Number(goods.stock_id), pair.stockId);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(goods, 'system_quantity'),
|
||
false,
|
||
'盲盘不应包含库位账面'
|
||
);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(goods, 'locked_quantity'),
|
||
false,
|
||
'盲盘不应包含库位锁定数量'
|
||
);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(goods, 'checked_quantity'),
|
||
false,
|
||
'盲盘不应包含已盘数量'
|
||
);
|
||
assert.ok(goods.status, '盲盘仍应输出已盘/未盘状态');
|
||
}
|
||
assert.equal(reportedRow.goods[0].status, 'checked');
|
||
assert.equal(unreportedRow.goods[0].status, 'unchecked');
|
||
});
|
||
|
||
it('视图驱动规则:库位任务一律 location(无视 is_goods/view)、商品任务默认 space、is_goods=true 才 goods', async () => {
|
||
// 库位任务:传 is_goods=true 仍返回 location 视图行(库位范围行)
|
||
const { check: locationCheck } = await createApprovedLocationCheck();
|
||
const locRows = await workDataCheck(locationCheck.id, { isGoods: true });
|
||
assert.equal(locRows.view, 'location', '库位任务无视 is_goods,view 应为 location');
|
||
assert.equal(locRows.total, 1, '库位任务应返回库位范围行');
|
||
assert.ok(locRows.rows.every(row => row.location_id !== undefined), 'location 视图行应含 location_id');
|
||
|
||
// 商品任务:默认(不传 is_goods)→ space 聚合库位视图
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const goodsCheck = await createCheck();
|
||
await addDetail(goodsCheck.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(goodsCheck.id);
|
||
await auditCheck(goodsCheck.id, 'approve');
|
||
|
||
const defaultView = await workDataCheck(goodsCheck.id);
|
||
assert.equal(defaultView.view, 'space', '商品任务默认 view 应为 space');
|
||
assert.equal(defaultView.total, 2, '商品任务默认应返回聚合库位视图');
|
||
assert.ok(defaultView.rows.every(row => row.space_code !== undefined), 'space 视图行应含 space_code');
|
||
|
||
// 商品任务:is_goods=true → goods 商品视图(明细行)
|
||
const goodsView = await workDataCheck(goodsCheck.id, { isGoods: true });
|
||
assert.equal(goodsView.view, 'goods', 'is_goods=true 时 view 应为 goods');
|
||
assert.equal(goodsView.total, 2);
|
||
assert.ok(goodsView.rows.every(row => row.stock_id !== undefined), 'goods 视图行应含 stock_id');
|
||
|
||
// view 入参已废弃:库位任务传 view='space' 仍返回 location 行
|
||
const viewIgnored = await workDataCheck(locationCheck.id, 'space');
|
||
assert.equal(viewIgnored.view, 'location');
|
||
assert.equal(viewIgnored.total, 1);
|
||
assert.ok(viewIgnored.rows.every(row => row.location_id !== undefined), 'view 入参被忽略,库位任务仍返回 location 行');
|
||
});
|
||
|
||
it('is_goods 非 true(false/0/字符串/缺省)一律按默认聚合库位视图', async () => {
|
||
const pairs = await fetchSpaceStockPairs(1);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, [ pairs[0].stockId ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
for (const value of [ undefined, false, 0, 'false', '' ]) {
|
||
const data = await workDataCheck(check.id, { isGoods: value });
|
||
assert.equal(data.view, 'space', `is_goods=${JSON.stringify(value)} 应按默认 space 返回`);
|
||
assert.equal(data.total, 1, `is_goods=${JSON.stringify(value)} 应按默认 space 返回`);
|
||
assert.ok(data.rows[0].space_code !== undefined, '非 true 值应按默认 space 视图返回');
|
||
}
|
||
});
|
||
|
||
it('分页:rows 按页切片、total 为全量行数、page/pageSize 归一化(默认 20、上限 200、非法回退)', async () => {
|
||
const pairs = await fetchSpaceStockPairs(3);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const callWithPagination = pagination => ctx.service.systems.stockCheck.workData({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
view: 'space',
|
||
pagination,
|
||
});
|
||
|
||
// page=1 pageSize=2 → 2 行,total 仍为全量 3
|
||
const firstPage = await callWithPagination({ page: 1, pageSize: 2 });
|
||
assert.equal(firstPage.total, 3, 'total 应为全量行数(未分页口径)');
|
||
assert.equal(firstPage.rows.length, 2, 'pageSize=2 应只返回 2 行');
|
||
assert.equal(firstPage.page, 1);
|
||
assert.equal(firstPage.pageSize, 2);
|
||
|
||
// page=2 pageSize=2 → 剩余 1 行,两页并集覆盖全量且不重叠
|
||
const secondPage = await callWithPagination({ page: 2, pageSize: 2 });
|
||
assert.equal(secondPage.rows.length, 1);
|
||
const pagedIds = [
|
||
...firstPage.rows.map(row => Number(row.id)),
|
||
...secondPage.rows.map(row => Number(row.id)),
|
||
].sort((left, right) => left - right);
|
||
assert.deepEqual(
|
||
pagedIds,
|
||
pairs.map(pair => pair.spaceId).sort((left, right) => left - right),
|
||
'两页并集应覆盖全量库位且不重叠'
|
||
);
|
||
|
||
// 不传分页 → 默认 page=1/pageSize=20,返回全量
|
||
const defaultPage = await workDataCheck(check.id, 'space');
|
||
assert.equal(defaultPage.total, 3);
|
||
assert.equal(defaultPage.rows.length, 3, '默认 pageSize=20 应返回全部 3 行');
|
||
assert.equal(defaultPage.page, 1);
|
||
assert.equal(defaultPage.pageSize, 20);
|
||
|
||
// 非法分页值(page=-1/pageSize=0)→ 回退默认
|
||
const invalidPage = await callWithPagination({ page: -1, pageSize: 0 });
|
||
assert.equal(invalidPage.page, 1);
|
||
assert.equal(invalidPage.pageSize, 20);
|
||
assert.equal(invalidPage.rows.length, 3);
|
||
|
||
// pageSize 超上限 500 → 收敛到 200(本任务全量 3 行全部返回)
|
||
const hugePage = await callWithPagination({ page: 1, pageSize: 500 });
|
||
assert.equal(hugePage.pageSize, 200);
|
||
assert.equal(hugePage.rows.length, 3);
|
||
|
||
// 超出范围页 → rows 空、total 仍为全量
|
||
const beyondPage = await callWithPagination({ page: 3, pageSize: 2 });
|
||
assert.equal(beyondPage.total, 3);
|
||
assert.deepEqual(beyondPage.rows, [], '超出范围页应返回空行');
|
||
});
|
||
|
||
it('400 边界:任务 ID 为空/非法(undefined/0/负数/非数字)', async () => {
|
||
const assertInvalidId = async badId => {
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.workData({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: badId,
|
||
});
|
||
}, error => error.code === 400 && /任务ID不能为空/.test(error.message));
|
||
};
|
||
for (const badId of [ undefined, 0, -1, 'abc' ]) {
|
||
await assertInvalidId(badId);
|
||
}
|
||
});
|
||
|
||
it('400 边界:任务不存在', async () => {
|
||
const missingId = await findFreeCheckId();
|
||
await assert.rejects(async () => {
|
||
await workDataCheck(missingId, 'goods');
|
||
}, error => error.code === 400 && /任务不存在/.test(error.message));
|
||
});
|
||
|
||
it('400 边界:其他仓库任务不可见(仓库隔离)', async () => {
|
||
const other = await createCheck({ warehouseId: OTHER_TEST_WAREHOUSE_ID });
|
||
await assert.rejects(async () => {
|
||
await workDataCheck(other.id, 'goods');
|
||
}, error => error.code === 400 && /任务不存在/.test(error.message));
|
||
});
|
||
|
||
it('400 状态限制:created/submitted/cancelled 状态拉取作业数据均拒绝且 message 含状态说明', async () => {
|
||
const assertStatusRejected = async (checkId, label) => {
|
||
await assert.rejects(async () => {
|
||
await workDataCheck(checkId, 'goods');
|
||
}, error => error.code === 400
|
||
&& /不允许拉取盘点作业数据/.test(error.message)
|
||
&& /仅审核完成(approved)或盘点作业中(checking)的任务可拉取/.test(error.message)
|
||
&& error.message.includes(`当前状态(${label})`));
|
||
};
|
||
|
||
// created:任务创建(含明细)后未提交审核即拉取
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await assertStatusRejected(check.id, '已创建');
|
||
|
||
// submitted:提交审核后(未审核)拉取
|
||
await submitCheck(check.id);
|
||
await assertStatusRejected(check.id, '待审核');
|
||
|
||
// cancelled:取消任务后拉取
|
||
await cancelCheck(check.id);
|
||
await assertStatusRejected(check.id, '已取消');
|
||
});
|
||
|
||
it('400 状态限制:rejected 状态拉取作业数据 → 400 且 message 含状态说明', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'reject', '任务信息有误');
|
||
await assert.rejects(async () => {
|
||
await workDataCheck(check.id, 'goods');
|
||
}, error => error.code === 400
|
||
&& /不允许拉取盘点作业数据/.test(error.message)
|
||
&& error.message.includes('当前状态(已驳回)'));
|
||
});
|
||
|
||
it('400 状态限制:completed 状态拉取作业数据 → 400 且 message 含状态说明', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
await finishCheck(check.id);
|
||
await assert.rejects(async () => {
|
||
await workDataCheck(check.id, 'goods');
|
||
}, error => error.code === 400
|
||
&& /不允许拉取盘点作业数据/.test(error.message)
|
||
&& error.message.includes('当前状态(已完成)'));
|
||
});
|
||
|
||
it('workDataSpaceDetails:传入 location_id 只返回该库位行(total=1,结构与 space 视图一致)', async () => {
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const target = pairs[0];
|
||
const data = await ctx.service.systems.stockCheck.workDataSpaceDetails({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
locationId: target.spaceId,
|
||
});
|
||
|
||
assert.equal(data.view, 'space', 'view 应恒为 space');
|
||
assert.equal(data.total, 1, '传入库位ID时应只返回该库位');
|
||
assert.equal(data.rows.length, 1);
|
||
const row = data.rows[0];
|
||
assert.equal(Number(row.id), target.spaceId, '行 id 应为库位ID');
|
||
assert.equal(row.space_code, target.spaceCode || null);
|
||
assert.equal(row.custom_name, target.customName || null);
|
||
assert.equal(row.goods.length, 1, '该库位仅一个任务商品');
|
||
assert.equal(Number(row.goods[0].stock_id), target.stockId, 'goods 应挂载该库位的任务商品');
|
||
assert.equal(Number(row.goods[0].system_quantity), target.book, '明盘库位账面应为 wms_storage SUM(可用数量)');
|
||
assert.equal(Number(row.goods[0].locked_quantity), target.bookLocked, '明盘库位锁定数量应为 wms_storage SUM(locked_quantity)');
|
||
assert.equal(Number(row.goods[0].checked_quantity), 0, '未盘库位已盘应为 0');
|
||
assert.equal(row.goods[0].status, 'unchecked');
|
||
});
|
||
|
||
it('workDataSpaceDetails:不传 location_id 按分页返回全部 space 行(total/rows/page/pageSize 口径)', async () => {
|
||
const pairs = await fetchSpaceStockPairs(3);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const data = await ctx.service.systems.stockCheck.workDataSpaceDetails({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
pagination: { page: 1, pageSize: 2 },
|
||
});
|
||
|
||
assert.equal(data.view, 'space');
|
||
assert.equal(data.total, 3, '应返回全部 3 个库位行数');
|
||
assert.equal(data.rows.length, 2, 'pageSize=2 应只返回 2 行');
|
||
assert.equal(data.page, 1);
|
||
assert.equal(data.pageSize, 2);
|
||
const page1Ids = data.rows.map(row => Number(row.id));
|
||
assert.ok(
|
||
page1Ids.every(id => pairs.some(pair => pair.spaceId === id)),
|
||
'第一页返回库位应属于任务商品所在库位集合'
|
||
);
|
||
|
||
// 第二页
|
||
const page2 = await ctx.service.systems.stockCheck.workDataSpaceDetails({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: check.id,
|
||
pagination: { page: 2, pageSize: 2 },
|
||
});
|
||
assert.equal(page2.total, 3);
|
||
assert.equal(page2.rows.length, 1, '第二页应返回剩余 1 行');
|
||
assert.equal(page2.page, 2);
|
||
|
||
// 两页合并应与任务商品所在库位全集一致
|
||
const mergedIds = [ ...page1Ids, ...page2.rows.map(row => Number(row.id)) ].sort((left, right) => left - right);
|
||
assert.deepEqual(
|
||
mergedIds,
|
||
pairs.map(pair => pair.spaceId).sort((left, right) => left - right),
|
||
'两页合并的库位集合应与任务商品所在库位一致'
|
||
);
|
||
});
|
||
|
||
it('workDataSpaceDetails 方法层:仓库注入 + location_id 驼峰兼容 + success 包装', async () => {
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
const pairs = await fetchSpaceStockPairs(2);
|
||
const check = await createCheck();
|
||
await addDetail(check.id, pairs.map(pair => pair.stockId));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.workDataSpaceDetails({
|
||
id: check.id,
|
||
locationId: pairs[0].spaceId,
|
||
});
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.data.view, 'space');
|
||
assert.equal(result.data.total, 1);
|
||
assert.equal(Number(result.data.rows[0].id), pairs[0].spaceId, '库位ID驼峰写法应生效');
|
||
|
||
// 库位任务(type=location)不适用 space 视图聚合,但接口仍按任务类型构建(无 goods 明细返回空)
|
||
const locationCheck = await createCheck({ type: 'location' });
|
||
await addLocationDetail(locationCheck.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(locationCheck.id);
|
||
await auditCheck(locationCheck.id, 'approve');
|
||
const locationResult = await ctx.service.systemMethods.stock.check.workDataSpaceDetails({
|
||
id: locationCheck.id,
|
||
});
|
||
assert.equal(locationResult.flag, 'success');
|
||
assert.equal(locationResult.data.view, 'space');
|
||
assert.equal(locationResult.data.total, 0, '库位任务无商品范围明细,space 聚合应为空');
|
||
});
|
||
});
|
||
|
||
// ------------------- systemMethods.stock.check.workData:方法包装层 -------------------
|
||
|
||
describe('systemMethods.stock.check.workData 方法包装层', () => {
|
||
/** 设置当前上下文的用户信息(模拟登录用户,仓库固定 100000)。 */
|
||
function mockCurrentUser() {
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
}
|
||
|
||
it('is_goods 透传 + 仓库上下文注入 + success 包装', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.workData({ id: check.id, is_goods: true });
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(result.data, 'check'),
|
||
false,
|
||
'方法层 workData 不返回 check(任务信息请调 detail)'
|
||
);
|
||
assert.equal(result.data.view, 'goods', '方法层 workData 应返回解析后的 view');
|
||
assert.equal(result.data.total, 1);
|
||
assert.equal(result.data.rows.length, 1);
|
||
assert.equal(Number(result.data.rows[0].stock_id), Number(stocks[0].id), 'is_goods=true 应返回商品视图行');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(result.data.rows[0], 'system_quantity'),
|
||
true,
|
||
'明盘商品视图应含账面快照'
|
||
);
|
||
});
|
||
|
||
it('view 入参已废弃:传非法 view 不报错,商品任务默认 space、is_goods=true 时 goods', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
// view 传非法值不报错(入参已废弃忽略)
|
||
const invalidView = await ctx.service.systemMethods.stock.check.workData({ id: check.id, view: 'invalid' });
|
||
assert.equal(invalidView.flag, 'success');
|
||
assert.equal(invalidView.code, 1);
|
||
|
||
// is_goods=true 返回商品视图(商品行含 stock_id 与明盘账面快照)
|
||
const goodsResult = await ctx.service.systemMethods.stock.check.workData({ id: check.id, view: 'invalid', is_goods: true });
|
||
assert.equal(goodsResult.flag, 'success');
|
||
assert.equal(goodsResult.data.total, 1);
|
||
assert.equal(Number(goodsResult.data.rows[0].stock_id), Number(stocks[0].id), 'is_goods=true 应返回商品视图行');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(goodsResult.data.rows[0], 'system_quantity'),
|
||
true,
|
||
'明盘商品视图应含账面快照'
|
||
);
|
||
});
|
||
|
||
it('workDataDetail 方法层:id + stock_id 返回 summary + rows,兼容 stockId 驼峰与 detail_id', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const targetDetail = details.rows[0];
|
||
const snapshot = Number(targetDetail.system_quantity);
|
||
await reportCheck(check.id, targetDetail.id, snapshot + 1, TEST_LOCATION_CODE);
|
||
|
||
const bySnake = await ctx.service.systemMethods.stock.check.workDataDetail({
|
||
id: check.id,
|
||
stock_id: stocks[0].id,
|
||
});
|
||
assert.equal(bySnake.flag, 'success');
|
||
assert.equal(bySnake.code, 1);
|
||
assert.equal(Number(bySnake.data.stock_id), Number(stocks[0].id));
|
||
assert.equal(Number(bySnake.data.summary.checked_quantity), snapshot + 1, '方法层应返回汇总数据');
|
||
assert.ok(Array.isArray(bySnake.data.rows) && bySnake.data.rows.length >= 1, '方法层应返回分行数据');
|
||
|
||
const byCamel = await ctx.service.systemMethods.stock.check.workDataDetail({
|
||
id: check.id,
|
||
stockId: stocks[0].id,
|
||
});
|
||
assert.equal(byCamel.flag, 'success');
|
||
assert.equal(Number(byCamel.data.summary.checked_quantity), snapshot + 1);
|
||
|
||
// 兼容旧写法:只传 detail_id(商品范围明细)
|
||
const byDetailId = await ctx.service.systemMethods.stock.check.workDataDetail({ detail_id: targetDetail.id });
|
||
assert.equal(byDetailId.flag, 'success');
|
||
assert.equal(Number(byDetailId.data.stock_id), Number(stocks[0].id));
|
||
|
||
// 缺少必要参数 → failure 400 包装
|
||
const missing = await ctx.service.systemMethods.stock.check.workDataDetail({ id: check.id });
|
||
assert.equal(missing.flag, 'failure');
|
||
assert.equal(missing.code, 400);
|
||
});
|
||
});
|
||
|
||
// ------------------- exportStockChecks:盘点导出(盘点明细=作业记录口径) -------------------
|
||
|
||
describe('exportStockChecks 盘点导出(盘点明细=作业记录口径)', () => {
|
||
/** Sheet1「盘点单」表头(列名与列序,与实现完全一致) */
|
||
const SHEET1_HEADERS = [
|
||
'盘点单号', '盘点名称', '盘点范围', '盘点方式', '盘点状态', '盘点进度',
|
||
'货主ID', '创建人', '明细行数', '已盘行数', '差异行数', '开始时间', '结束时间', '备注',
|
||
];
|
||
/** Sheet2「盘点明细」表头(作业记录口径:一行一条实际盘点记录) */
|
||
const SHEET2_HEADERS = [
|
||
'盘点单号', '商品编码', '商品名称', '库位编码', '实盘数量', '盘点人', '盘点时间',
|
||
];
|
||
|
||
/**
|
||
* mock 上传服务:拦截 uploadFile 收集文件流 Buffer(不发起真实 COS 上传),
|
||
* uploadSuccessNotify 返回落库记录。
|
||
*
|
||
* @return {Object} captured 捕获的上传调用与文件 Buffer。
|
||
*/
|
||
function mockUploadService() {
|
||
const captured = { buffers: [], uploadCalls: [], notifyCalls: [] };
|
||
app.mockService('systems.upload', 'uploadFile', async function(fileStream, uploadOptions = {}) {
|
||
captured.uploadCalls.push({
|
||
filename: fileStream.filename,
|
||
key: uploadOptions.key,
|
||
fileSize: fileStream.fileSize,
|
||
});
|
||
const chunks = [];
|
||
for await (const chunk of fileStream) {
|
||
chunks.push(chunk);
|
||
}
|
||
captured.buffers.push(Buffer.concat(chunks));
|
||
const key = uploadOptions.key;
|
||
return {
|
||
fileName: key,
|
||
url: `https://cdn.test.local/${key}`,
|
||
cdnUrl: `https://cdn.test.local/${key}`,
|
||
cosUrl: `https://cos.test.local/${key}`,
|
||
};
|
||
});
|
||
app.mockService('systems.upload', 'uploadSuccessNotify', async function(data) {
|
||
captured.notifyCalls.push(data);
|
||
return {
|
||
fileId: 90001,
|
||
fileUrl: `https://cdn.test.local/${data.fileKey}`,
|
||
fileKey: data.fileKey,
|
||
fileName: data.fileName,
|
||
};
|
||
});
|
||
return captured;
|
||
}
|
||
|
||
/**
|
||
* 将最近一次上传的 Excel Buffer 回读为工作簿。
|
||
*
|
||
* @param {Object} captured mockUploadService 返回的捕获对象。
|
||
* @return {Promise<Object>} ExcelJS 工作簿。
|
||
*/
|
||
async function readBackWorkbook(captured) {
|
||
assert.ok(captured.buffers.length > 0, '上传文件流未捕获到内容');
|
||
const workbook = new ExcelJS.Workbook();
|
||
await workbook.xlsx.load(captured.buffers[captured.buffers.length - 1]);
|
||
return workbook;
|
||
}
|
||
|
||
/**
|
||
* 读取单元格值(空值统一归一为空字符串)。
|
||
*
|
||
* @param {Object} worksheet ExcelJS 工作表。
|
||
* @param {number} rowNo 行号(1 起)。
|
||
* @param {number} colNo 列号(1 起)。
|
||
* @return {*} 单元格值。
|
||
*/
|
||
function getCell(worksheet, rowNo, colNo) {
|
||
const value = worksheet.getRow(rowNo).getCell(colNo).value;
|
||
return value === null || value === undefined ? '' : value;
|
||
}
|
||
|
||
/**
|
||
* 收集工作表表头列名(按列序)。
|
||
*
|
||
* @param {Object} worksheet ExcelJS 工作表。
|
||
* @return {Array<string>} 表头列名。
|
||
*/
|
||
function collectHeaders(worksheet) {
|
||
const headers = [];
|
||
for (let col = 1; col <= worksheet.actualColumnCount; col += 1) {
|
||
const value = worksheet.getRow(1).getCell(col).value;
|
||
headers.push(value === null || value === undefined ? '' : String(value));
|
||
}
|
||
return headers;
|
||
}
|
||
|
||
/**
|
||
* 导出指定盘点任务(直调业务层,上传服务已 mock),返回导出结果与回读工作簿。
|
||
*
|
||
* @param {Array<number>} ids 盘点任务ID列表。
|
||
* @param {Object} captured mockUploadService 返回的捕获对象。
|
||
* @param {Array<Object>} [progressCalls] 进度回调收集数组。
|
||
* @return {Promise<Object>} { result, workbook }。
|
||
*/
|
||
async function exportChecks(ids, captured, progressCalls = []) {
|
||
const result = await ctx.service.systems.stockCheck.exportStockChecks({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
ids,
|
||
onProgress: async progress => {
|
||
progressCalls.push(progress);
|
||
},
|
||
});
|
||
const workbook = await readBackWorkbook(captured);
|
||
return { result, workbook };
|
||
}
|
||
|
||
it('Sheet2 明细行数=作业记录数:未盘范围行不导出,total_count=记录总数', async () => {
|
||
const captured = mockUploadService();
|
||
|
||
// 商品维度任务:2 条范围行,仅第一条上报作业记录(第二条保持未盘)
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.rows.length, 2, '前置:2 条盘点范围行');
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
await reportCheck(check.id, details.rows[0].id, 5);
|
||
|
||
const records = await queryRecords(check.id);
|
||
assert.equal(records.length, 1, '前置:仅 1 条作业记录');
|
||
|
||
const progressCalls = [];
|
||
const { result, workbook } = await exportChecks([ check.id ], captured, progressCalls);
|
||
|
||
// 返回统计:total_count=作业记录总数(而非范围行数)
|
||
assert.equal(result.total_count, 1);
|
||
assert.equal(result.current_count, 1);
|
||
assert.match(result.filename, /^库存盘点导出_\d{14}\.xlsx$/, '文件名格式应为 库存盘点导出_时间戳.xlsx');
|
||
|
||
// 双 Sheet 名称 + 表头列名列序
|
||
assert.equal(workbook.worksheets.length, 2);
|
||
assert.equal(workbook.worksheets[0].name, '盘点单');
|
||
assert.equal(workbook.worksheets[1].name, '盘点明细');
|
||
assert.deepEqual(collectHeaders(workbook.worksheets[0]), SHEET1_HEADERS);
|
||
assert.deepEqual(collectHeaders(workbook.worksheets[1]), SHEET2_HEADERS);
|
||
|
||
// Sheet1 无「盘点日期」列;开始时间=首次上报时间(非空)、结束时间未完成(空)
|
||
const sheet1 = workbook.worksheets[0];
|
||
assert.ok(
|
||
!collectHeaders(sheet1).includes('盘点日期'),
|
||
'Sheet1 不应含「盘点日期」列'
|
||
);
|
||
assert.notEqual(getCell(sheet1, 2, 12), '', 'Sheet1 开始时间应非空(首次上报已写 start_time)');
|
||
assert.equal(getCell(sheet1, 2, 13), '', 'Sheet1 结束时间应为空(未完成盘点)');
|
||
|
||
// Sheet1:表头 + 1 个任务;Sheet2:表头 + 1 条作业记录(未盘的第 2 条范围行不导出)
|
||
assert.equal(workbook.worksheets[0].actualRowCount, 2);
|
||
assert.equal(workbook.worksheets[1].actualRowCount, 2);
|
||
|
||
// Sheet2 数据行:盘点单号/实盘数量正确
|
||
const sheet2 = workbook.worksheets[1];
|
||
assert.equal(getCell(sheet2, 2, 1), check.check_no);
|
||
assert.equal(getCell(sheet2, 2, 5), 5);
|
||
|
||
// 进度推送 totalCount 为作业记录总数
|
||
const progressWithTotal = progressCalls.find(item => item && item.totalCount !== undefined);
|
||
assert.ok(progressWithTotal, '应推送包含 totalCount 的进度');
|
||
assert.equal(progressWithTotal.totalCount, 1);
|
||
});
|
||
|
||
it('库位行记录导出含商品快照:item_code/item_name 从 wms_stock_warehouse 补齐', async () => {
|
||
const captured = mockUploadService();
|
||
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
assert.ok(stockIds.length > 0, '前置:固定库位下存在库存商品');
|
||
await reportCheck(check.id, details.rows[0].id, 7, TEST_LOCATION_CODE, { stockId: stockIds[0] });
|
||
|
||
const stockRow = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: stockIds[0] },
|
||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||
raw: true,
|
||
});
|
||
|
||
const { result, workbook } = await exportChecks([ check.id ], captured);
|
||
assert.equal(result.total_count, 1);
|
||
|
||
const sheet2 = workbook.worksheets[1];
|
||
assert.equal(sheet2.actualRowCount, 2);
|
||
assert.equal(getCell(sheet2, 2, 1), check.check_no);
|
||
assert.equal(getCell(sheet2, 2, 2), stockRow.item_code, '商品编码应来自 wms_stock_warehouse');
|
||
assert.equal(getCell(sheet2, 2, 3), stockRow.item_name, '商品名称应来自 wms_stock_warehouse');
|
||
assert.equal(getCell(sheet2, 2, 4), TEST_LOCATION_CODE);
|
||
assert.equal(getCell(sheet2, 2, 5), 7);
|
||
assert.equal(getCell(sheet2, 2, 6), TEST_CREATOR_NAME);
|
||
assert.notEqual(getCell(sheet2, 2, 7), '', '盘点时间应非空');
|
||
});
|
||
|
||
it('历史空库位记录(location_code="")导出库位编码为空', async () => {
|
||
const captured = mockUploadService();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
// report 已强制 space_id,这里直接构造历史脏数据(空串库位)验证导出兼容
|
||
await ctx.model.StockCheckRecord.create({
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: detail.id,
|
||
stock_id: Number(detail.stock_id),
|
||
location_id: null,
|
||
location_code: '',
|
||
quantity: 3,
|
||
is_empty: false,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
});
|
||
|
||
const records = await queryRecords(check.id);
|
||
assert.equal(records.length, 1);
|
||
assert.equal(records[0].location_code, '', '前置:库中 location_code 应为空串');
|
||
|
||
const { workbook } = await exportChecks([ check.id ], captured);
|
||
const sheet2 = workbook.worksheets[1];
|
||
assert.equal(sheet2.actualRowCount, 2);
|
||
assert.equal(getCell(sheet2, 2, 1), check.check_no);
|
||
assert.equal(getCell(sheet2, 2, 4), '', '空库位记录的库位编码应导出为空');
|
||
assert.equal(getCell(sheet2, 2, 5), 3);
|
||
});
|
||
|
||
it('多任务导出:按盘点单号分组正确,Sheet1 一行一个任务', async () => {
|
||
const captured = mockUploadService();
|
||
|
||
const checkA = await createCheck();
|
||
const checkB = await createCheck();
|
||
const quantityMap = new Map([
|
||
[ checkA.id, 4 ],
|
||
[ checkB.id, 6 ],
|
||
]);
|
||
for (const check of [ checkA, checkB ]) {
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, quantityMap.get(check.id));
|
||
}
|
||
|
||
const { result, workbook } = await exportChecks([ checkA.id, checkB.id ], captured);
|
||
assert.equal(result.total_count, 2);
|
||
|
||
// Sheet1:表头 + 2 个任务(按 id 升序)
|
||
const sheet1 = workbook.worksheets[0];
|
||
assert.equal(sheet1.actualRowCount, 3);
|
||
assert.equal(getCell(sheet1, 2, 1), checkA.check_no);
|
||
assert.equal(getCell(sheet1, 3, 1), checkB.check_no);
|
||
|
||
// Sheet2:两条作业记录按盘点单号各归各任务
|
||
const sheet2 = workbook.worksheets[1];
|
||
assert.equal(sheet2.actualRowCount, 3);
|
||
assert.equal(getCell(sheet2, 2, 1), checkA.check_no, '第一条记录应属于任务A');
|
||
assert.equal(getCell(sheet2, 2, 5), 4);
|
||
assert.equal(getCell(sheet2, 3, 1), checkB.check_no, '第二条记录应属于任务B');
|
||
assert.equal(getCell(sheet2, 3, 5), 6);
|
||
});
|
||
|
||
it('未知商品导出口径:Sheet2 商品编码=扫描条码、商品名称=名称快照', async () => {
|
||
const captured = mockUploadService();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 2, TEST_LOCATION_CODE);
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-EXPORT');
|
||
await reportCheck(check.id, details.rows[0].id, 4, TEST_LOCATION_CODE_2, {
|
||
barcode: unknownBarcode,
|
||
itemName: '导出未知商品快照',
|
||
});
|
||
|
||
const { result, workbook } = await exportChecks([ check.id ], captured);
|
||
assert.equal(result.total_count, 2);
|
||
|
||
const sheet2 = workbook.worksheets[1];
|
||
assert.equal(sheet2.actualRowCount, 3, '表头 + 2 条作业记录');
|
||
assert.equal(getCell(sheet2, 2, 2), details.rows[0].item_code, '已知商品编码来自 wms_stock_warehouse');
|
||
assert.equal(getCell(sheet2, 3, 2), unknownBarcode, '未知商品编码列显示扫描条码');
|
||
assert.equal(getCell(sheet2, 3, 3), '导出未知商品快照', '未知商品名称列显示名称快照');
|
||
assert.equal(getCell(sheet2, 3, 4), TEST_LOCATION_CODE_2);
|
||
assert.equal(getCell(sheet2, 3, 5), 4);
|
||
});
|
||
});
|
||
|
||
// ------------------- exportCheckDetail:盘点明细导出(按盘点范围分流) -------------------
|
||
|
||
describe('exportCheckDetail 盘点明细导出(商品盘点分库位明细/汇总+差异,库位盘点简化)', () => {
|
||
/** 商品盘点 Sheet1「汇总和差异」表头 */
|
||
const SUMMARY_SHEET_HEADERS = [
|
||
'盘点单号', '商品编码', '条码', '商品名称', '规格', '账面数量', '盘点数量', '差异数量', '差异类型',
|
||
];
|
||
/** 商品盘点 Sheet2「库位明细」表头 */
|
||
const LOCATION_SHEET_HEADERS = [ '库位编码', '数量', '条码', '商品名称' ];
|
||
/** 库位盘点 Sheet「盘点明细」表头 */
|
||
const SIMPLE_SHEET_HEADERS = [ '库位编码', '商品编码', '商品名称', '盘点数量' ];
|
||
|
||
function mockUploadService() {
|
||
const captured = { buffers: [], uploadCalls: [], notifyCalls: [] };
|
||
app.mockService('systems.upload', 'uploadFile', async function(fileStream, uploadOptions = {}) {
|
||
captured.uploadCalls.push({
|
||
filename: fileStream.filename,
|
||
key: uploadOptions.key,
|
||
fileSize: fileStream.fileSize,
|
||
});
|
||
const chunks = [];
|
||
for await (const chunk of fileStream) {
|
||
chunks.push(chunk);
|
||
}
|
||
captured.buffers.push(Buffer.concat(chunks));
|
||
const key = uploadOptions.key;
|
||
return {
|
||
fileName: key,
|
||
url: `https://cdn.test.local/${key}`,
|
||
cdnUrl: `https://cdn.test.local/${key}`,
|
||
cosUrl: `https://cos.test.local/${key}`,
|
||
};
|
||
});
|
||
app.mockService('systems.upload', 'uploadSuccessNotify', async function(data) {
|
||
captured.notifyCalls.push(data);
|
||
return {
|
||
fileId: 90002,
|
||
fileUrl: `https://cdn.test.local/${data.fileKey}`,
|
||
fileKey: data.fileKey,
|
||
fileName: data.fileName,
|
||
};
|
||
});
|
||
return captured;
|
||
}
|
||
|
||
async function readBackWorkbook(captured) {
|
||
assert.ok(captured.buffers.length > 0, '上传文件流未捕获到内容');
|
||
const workbook = new ExcelJS.Workbook();
|
||
await workbook.xlsx.load(captured.buffers[captured.buffers.length - 1]);
|
||
return workbook;
|
||
}
|
||
|
||
function getCell(worksheet, rowNo, colNo) {
|
||
const value = worksheet.getRow(rowNo).getCell(colNo).value;
|
||
return value === null || value === undefined ? '' : value;
|
||
}
|
||
|
||
function collectHeaders(worksheet) {
|
||
const headers = [];
|
||
for (let col = 1; col <= worksheet.actualColumnCount; col += 1) {
|
||
const value = worksheet.getRow(1).getCell(col).value;
|
||
headers.push(value === null || value === undefined ? '' : String(value));
|
||
}
|
||
return headers;
|
||
}
|
||
|
||
async function exportDetail(checkId) {
|
||
return ctx.service.systems.stockCheck.exportCheckDetail({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
id: checkId,
|
||
onProgress: () => {},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 按实现口径解析库位显示文本:自定义名称 → 自定义编码 → 库位编码。
|
||
*
|
||
* @param {string} code 库位编码。
|
||
* @return {Promise<string>} 期望显示的库位文本。
|
||
*/
|
||
async function resolveLocationDisplay(code) {
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: String(code || '').trim() },
|
||
attributes: [ 'space_code', 'custom_name', 'custom_barcode' ],
|
||
raw: true,
|
||
});
|
||
if (!space) {
|
||
return String(code || '').trim();
|
||
}
|
||
return String(space.custom_name || '').trim()
|
||
|| String(space.custom_barcode || '').trim()
|
||
|| String(space.space_code || '').trim();
|
||
}
|
||
|
||
it('商品任务:两个 sheet——「汇总和差异」每商品一行 + 「库位明细」库位/数量/条码/商品名称', async () => {
|
||
const captured = mockUploadService();
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const firstDetail = details.rows[0];
|
||
const secondDetail = details.rows[1];
|
||
const firstSnapshot = Number(firstDetail.system_quantity);
|
||
const secondSnapshot = Number(secondDetail.system_quantity);
|
||
// 在商品自身快照库位上报:第一商品盘盈 7、第二商品持平
|
||
await reportCheck(check.id, firstDetail.id, firstSnapshot + 7, firstDetail.location_code);
|
||
await reportCheck(check.id, secondDetail.id, secondSnapshot, secondDetail.location_code);
|
||
|
||
// 商品条码(wms_stock_barcodes 按 stock_id 取第一条,口径与实现一致)
|
||
const barcodeRows = await ctx.model.StockBarcode.findAll({
|
||
where: {
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
stock_id: { [Op.in]: [ Number(firstDetail.stock_id), Number(secondDetail.stock_id) ] },
|
||
},
|
||
attributes: [ 'stock_id', 'barcode' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
const barcodeByStock = new Map();
|
||
for (const row of barcodeRows) {
|
||
const rowStockId = Number(row.stock_id);
|
||
if (!barcodeByStock.has(rowStockId)) {
|
||
barcodeByStock.set(rowStockId, String(row.barcode || '').trim());
|
||
}
|
||
}
|
||
|
||
const result = await exportDetail(check.id);
|
||
assert.equal(result.total_count, 4, '汇总 2 行 + 作业记录 2 行');
|
||
|
||
const workbook = await readBackWorkbook(captured);
|
||
assert.equal(workbook.worksheets.length, 2, '商品盘点固定两个 sheet');
|
||
|
||
const summarySheet = workbook.worksheets[0];
|
||
assert.equal(summarySheet.name, '汇总和差异');
|
||
assert.deepEqual(collectHeaders(summarySheet), SUMMARY_SHEET_HEADERS);
|
||
assert.equal(summarySheet.actualRowCount, 3, '表头 + 2 商品');
|
||
assert.equal(getCell(summarySheet, 2, 2), firstDetail.item_code);
|
||
assert.equal(
|
||
getCell(summarySheet, 2, 3),
|
||
barcodeByStock.get(Number(firstDetail.stock_id)) || '',
|
||
'条码=商品条码'
|
||
);
|
||
assert.equal(getCell(summarySheet, 2, 6), firstSnapshot, '账面=快照合计');
|
||
assert.equal(getCell(summarySheet, 2, 7), firstSnapshot + 7);
|
||
assert.equal(getCell(summarySheet, 2, 8), 7);
|
||
assert.equal(getCell(summarySheet, 2, 9), '盘盈');
|
||
assert.equal(getCell(summarySheet, 3, 8), 0, '持平商品差异 0');
|
||
assert.equal(getCell(summarySheet, 3, 9), '', '持平商品差异类型为空');
|
||
|
||
const locationSheet = workbook.worksheets[1];
|
||
assert.equal(locationSheet.name, '库位明细');
|
||
assert.deepEqual(collectHeaders(locationSheet), LOCATION_SHEET_HEADERS);
|
||
assert.equal(locationSheet.actualRowCount, 3, '表头 + 2 条作业记录');
|
||
assert.equal(
|
||
getCell(locationSheet, 2, 1),
|
||
await resolveLocationDisplay(firstDetail.location_code),
|
||
'库位显示=自定义名称→自定义编码→库位编码'
|
||
);
|
||
assert.equal(getCell(locationSheet, 2, 2), firstSnapshot + 7, '数量=实盘');
|
||
assert.equal(getCell(locationSheet, 2, 3), barcodeByStock.get(Number(firstDetail.stock_id)) || '', '条码=商品条码');
|
||
assert.equal(getCell(locationSheet, 2, 4), firstDetail.item_name);
|
||
assert.equal(
|
||
getCell(locationSheet, 3, 1),
|
||
await resolveLocationDisplay(secondDetail.location_code),
|
||
'库位显示=自定义名称→自定义编码→库位编码'
|
||
);
|
||
assert.equal(getCell(locationSheet, 3, 2), secondSnapshot);
|
||
assert.equal(getCell(locationSheet, 3, 4), secondDetail.item_name);
|
||
});
|
||
|
||
it('库位任务:单 sheet 库位/商品编码/商品名称/盘点数量(未知商品编码=条码)', async () => {
|
||
const captured = mockUploadService();
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
assert.ok(stockIds.length > 0, '前置:固定测试库位应存在库存商品');
|
||
await reportCheck(check.id, detail.id, 3, undefined, { stockId: stockIds[0] });
|
||
const unknownBarcode = uniqueTitle('LOCATION-EXPORT-UNKNOWN');
|
||
await reportCheck(check.id, detail.id, 4, undefined, { barcode: unknownBarcode });
|
||
|
||
const result = await exportDetail(check.id);
|
||
assert.equal(result.total_count, 2, '两条作业记录');
|
||
|
||
const workbook = await readBackWorkbook(captured);
|
||
assert.equal(workbook.worksheets.length, 1, '库位任务单 sheet');
|
||
const sheet = workbook.worksheets[0];
|
||
assert.equal(sheet.name, '盘点明细');
|
||
assert.deepEqual(collectHeaders(sheet), SIMPLE_SHEET_HEADERS);
|
||
assert.equal(sheet.actualRowCount, 3, '表头 + 2 行');
|
||
assert.equal(
|
||
getCell(sheet, 2, 1),
|
||
await resolveLocationDisplay(TEST_LOCATION_CODE),
|
||
'库位列显示=自定义名称→自定义编码→库位编码'
|
||
);
|
||
assert.equal(getCell(sheet, 2, 4), 3, '盘点数量');
|
||
assert.equal(getCell(sheet, 3, 2), unknownBarcode, '未知商品编码=扫描条码');
|
||
assert.equal(getCell(sheet, 3, 4), 4);
|
||
});
|
||
|
||
it('方法层 exportDetail:返回任务ID并异步完成(进度复用 exportTaskProgress)', async () => {
|
||
mockUploadService();
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.exportDetail({ id: check.id });
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.ok(result.task_id, '应返回导出任务ID');
|
||
assert.equal(result.status, 'submitted');
|
||
|
||
// 轮询导出进度至终态(上传服务已 mock,egg-mock 环境内可正常执行)
|
||
const taskId = result.task_id;
|
||
let progress = null;
|
||
for (let attempt = 0; attempt < 50; attempt++) {
|
||
progress = await ctx.service.systemMethods.stock.check.exportTaskProgress({ task_id: taskId });
|
||
if (progress.status === 'success' || progress.status === 'failed') {
|
||
break;
|
||
}
|
||
await new Promise(resolve => setTimeout(resolve, 100));
|
||
}
|
||
assert.equal(progress.status, 'success', `导出任务应完成: ${progress.error}`);
|
||
assert.ok(progress.download_url, '完成后应返回下载链接');
|
||
|
||
// 未传 id 报 400
|
||
const invalid = await ctx.service.systemMethods.stock.check.exportDetail({});
|
||
assert.equal(invalid.flag, 'failure');
|
||
assert.equal(invalid.code, 400);
|
||
});
|
||
});
|
||
|
||
// ------------------- 未知商品记录 + 图片独立维护(迁移 20261001100000) -------------------
|
||
|
||
describe('未知商品记录 + 图片独立维护', () => {
|
||
it('未知商品:库位行仅传 barcode(不存在)→ stock_id=NULL、barcode/item_name 落库(item_name 缺省=barcode)', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-BARCODE');
|
||
|
||
// 前置:条码未命中本仓库系统商品
|
||
assert.equal(
|
||
await ctx.model.StockBarcode.count({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, barcode: unknownBarcode },
|
||
}),
|
||
0,
|
||
'前置:测试条码不应命中系统商品'
|
||
);
|
||
|
||
const result = await reportCheck(check.id, detail.id, 5, undefined, { barcode: unknownBarcode });
|
||
|
||
assert.equal(result.mode, 'created');
|
||
assert.equal(result.record.stock_id, null, '未知商品 stock_id 应为 NULL');
|
||
assert.equal(result.record.barcode, unknownBarcode, '记录应写入扫描条码');
|
||
assert.equal(result.record.item_name, unknownBarcode, 'item_name 缺省应为条码');
|
||
assert.equal(result.record.location_code, TEST_LOCATION_CODE, '库位以明细库位为准');
|
||
assert.equal(result.checked_items, 1);
|
||
assert.equal(result.detail_status, 'all_checked');
|
||
|
||
const record = await ctx.model.StockCheckRecord.findOne({
|
||
where: { id: Number(result.record.id) },
|
||
raw: true,
|
||
});
|
||
assert.equal(record.stock_id, null, '库中 stock_id 应为 NULL');
|
||
assert.equal(record.barcode, unknownBarcode);
|
||
assert.equal(record.item_name, unknownBarcode);
|
||
});
|
||
|
||
it('未知商品:显式传 item_name 按快照落库(非缺省条码)', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-BARCODE-NAME');
|
||
|
||
const result = await reportCheck(check.id, detail.id, 2, undefined, {
|
||
barcode: unknownBarcode,
|
||
itemName: '未知商品快照名称',
|
||
});
|
||
|
||
assert.equal(result.record.stock_id, null);
|
||
assert.equal(result.record.barcode, unknownBarcode);
|
||
assert.equal(result.record.item_name, '未知商品快照名称', 'item_name 应为显式快照');
|
||
});
|
||
|
||
it('barcode 命中系统条码:库位行回填 stock_id 按已知商品处理,重复上报覆盖更新', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const stockId = Number(stocks[0].id);
|
||
const knownBarcode = uniqueTitle('KNOWN-BARCODE');
|
||
await createStockBarcode(stockId, knownBarcode);
|
||
|
||
const first = await reportCheck(check.id, detail.id, 3, undefined, { barcode: knownBarcode });
|
||
assert.equal(first.mode, 'created');
|
||
assert.equal(Number(first.record.stock_id), stockId, '命中系统条码应回填 stock_id');
|
||
assert.equal(first.record.barcode, knownBarcode, '已知商品记录冗余条码');
|
||
assert.equal(first.record.item_name, null, '已知商品不落 item_name');
|
||
|
||
const second = await reportCheck(check.id, detail.id, 6, undefined, { barcode: knownBarcode });
|
||
assert.equal(second.mode, 'updated', '回填后按 (detail,stock,location) 覆盖更新');
|
||
assert.equal(Number(second.record.id), Number(first.record.id));
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 1, '同 (detail,stock,location) 只保留一条记录');
|
||
assert.equal(Number(records[0].stock_id), stockId);
|
||
assert.equal(Number(records[0].quantity), 6);
|
||
});
|
||
|
||
it('商品行 barcode 命中系统条码:与明细商品一致回填 stock_id;命中其他商品报 400', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
|
||
const barcodeForA = uniqueTitle('GOODS-BARCODE-A');
|
||
const barcodeForB = uniqueTitle('GOODS-BARCODE-B');
|
||
await createStockBarcode(stocks[0].id, barcodeForA);
|
||
await createStockBarcode(stocks[1].id, barcodeForB);
|
||
|
||
const hit = await reportCheck(check.id, detail.id, 4, undefined, { barcode: barcodeForA });
|
||
assert.equal(hit.mode, 'created');
|
||
assert.equal(Number(hit.record.stock_id), Number(detail.stock_id), '命中且一致应回填明细商品');
|
||
assert.equal(hit.record.barcode, barcodeForA);
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 4, undefined, { barcode: barcodeForB });
|
||
}, error => error.code === 400 && /上报商品与盘点明细商品不一致/.test(error.message));
|
||
});
|
||
|
||
it('未知商品覆盖式:同 detail+同 barcode+同库位二次上报 → updated、数量更新、不新增记录', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-UPDATE');
|
||
|
||
const first = await reportCheck(check.id, detail.id, 5, undefined, { barcode: unknownBarcode });
|
||
assert.equal(first.mode, 'created');
|
||
|
||
const second = await reportCheck(check.id, detail.id, 9, undefined, { barcode: unknownBarcode });
|
||
assert.equal(second.mode, 'updated', '同 barcode 同库位应覆盖更新');
|
||
assert.equal(Number(second.record.id), Number(first.record.id), '应更新同一条记录');
|
||
|
||
const records = await queryRecords(check.id, detail.id);
|
||
assert.equal(records.length, 1, '未知商品同 barcode 同库位只保留一条记录');
|
||
assert.equal(Number(records[0].quantity), 9);
|
||
});
|
||
|
||
it('result 库位行 unknown_items:未知实盘=盘盈差异、stocks 保持只含已知商品', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stockIds = await fetchStorageStockIds(TEST_LOCATION_ID, 1);
|
||
assert.ok(stockIds.length > 0, '前置:固定测试库位应存在库存商品');
|
||
const bookMap = await fetchStorageQuantity(TEST_LOCATION_ID, stockIds);
|
||
const bookA = Number(bookMap.get(stockIds[0]) || 0);
|
||
|
||
await reportCheck(check.id, detail.id, bookA, undefined, { stockId: stockIds[0] });
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-RESULT');
|
||
await reportCheck(check.id, detail.id, 7, undefined, { barcode: unknownBarcode });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
assert.equal(row.checked_quantity, bookA + 7, '行级已盘=已知+未知合计');
|
||
assert.equal(row.diff_quantity, 7, '未知商品无账面:差异=实盘=盘盈');
|
||
assert.equal(row.is_diff, 1);
|
||
assert.deepEqual(row.unknown_items, [
|
||
{ barcode: unknownBarcode, item_name: unknownBarcode, checked_quantity: 7 },
|
||
], 'unknown_items 应为未知商品聚合');
|
||
assert.equal(row.stocks.length, 1, 'stocks 保持只含已知商品');
|
||
assert.equal(Number(row.stocks[0].stock_id), Number(stockIds[0]));
|
||
assert.equal(row.stocks[0].diff_quantity, 0, '已知商品账面持平无差异');
|
||
});
|
||
|
||
it('result 商品行 unknown_items:已知+未知混合,行级差异=已知差异+未知实盘', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
const snapshot = Number(detail.system_quantity);
|
||
|
||
await reportCheck(check.id, detail.id, snapshot, TEST_LOCATION_CODE);
|
||
const unknownBarcode = uniqueTitle('GOODS-UNKNOWN');
|
||
await reportCheck(check.id, detail.id, 4, TEST_LOCATION_CODE_2, { barcode: unknownBarcode });
|
||
|
||
const result = await resultCheck(check.id);
|
||
const row = result.rows[0];
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.checked_quantity, snapshot + 4);
|
||
assert.equal(row.diff_quantity, 4, '未知实盘计入商品行差异');
|
||
assert.equal(row.is_diff, 1);
|
||
assert.deepEqual(row.unknown_items, [
|
||
{ barcode: unknownBarcode, item_name: unknownBarcode, checked_quantity: 4 },
|
||
], '商品行同样输出 unknown_items');
|
||
});
|
||
|
||
it('finish 未知商品计入 profit_total/diff_items(无账面=盘盈)', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-FINISH');
|
||
await reportCheck(check.id, detail.id, 11, undefined, { barcode: unknownBarcode });
|
||
|
||
const result = await finishCheck(check.id);
|
||
|
||
assert.equal(result.status, 'completed');
|
||
assert.equal(result.total_items, 1);
|
||
assert.equal(result.checked_items, 1);
|
||
assert.equal(result.unchecked_items, 0);
|
||
assert.equal(result.diff_items, 1, '未知商品必然差异计入 diff_items');
|
||
assert.equal(result.profit_total, 11, '未知商品实盘=盘盈');
|
||
assert.equal(result.loss_total, 0);
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.status, 'completed');
|
||
assert.equal(row.diff_items, 1);
|
||
});
|
||
|
||
it('图片独立维护:FileReference(business_type=stock_check_record) 挂载 recordList 与 result.records', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const knownReport = await reportCheck(check.id, detail.id, 3, undefined, { stockId: stocks[0].id });
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-IMAGE-EMPTY');
|
||
const unknownReport = await reportCheck(check.id, detail.id, 2, undefined, { barcode: unknownBarcode });
|
||
const { file } = await createRecordImage(Number(knownReport.record.id));
|
||
|
||
const listed = await listRecords({ id: check.id, detailId: detail.id });
|
||
assert.equal(listed.total, 2);
|
||
const listedKnown = listed.rows.find(row => Number(row.id) === Number(knownReport.record.id));
|
||
const listedUnknown = listed.rows.find(row => Number(row.id) === Number(unknownReport.record.id));
|
||
assert.deepEqual(
|
||
listedKnown.images,
|
||
[{ id: Number(file.id), url: file.file_url }],
|
||
'recordList 应挂载 FileReference 图片'
|
||
);
|
||
assert.deepEqual(listedUnknown.images, [], '无图片记录 images 应为空数组');
|
||
|
||
const result = await resultCheck(check.id);
|
||
const records = result.rows[0].records;
|
||
assert.equal(records.length, 2);
|
||
const resultKnown = records.find(record => Number(record.id) === Number(knownReport.record.id));
|
||
const resultUnknown = records.find(record => Number(record.id) === Number(unknownReport.record.id));
|
||
assert.deepEqual(
|
||
resultKnown.images,
|
||
[{ id: Number(file.id), url: file.file_url }],
|
||
'result.records 应挂载 FileReference 图片'
|
||
);
|
||
assert.deepEqual(resultUnknown.images, [], 'result 无图片记录 images 应为空数组');
|
||
});
|
||
|
||
it('recordDelete 删除记录时清理其 FileReference 图片引用', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const reportResult = await reportCheck(check.id, detail.id, 3, undefined, { stockId: stocks[0].id });
|
||
const recordId = Number(reportResult.record.id);
|
||
await createRecordImage(recordId);
|
||
|
||
assert.equal(
|
||
await ctx.model.FileReference.count({
|
||
where: { business_type: 'stock_check_record', business_id: String(recordId) },
|
||
}),
|
||
1,
|
||
'前置:图片引用已创建'
|
||
);
|
||
|
||
await deleteRecord(check.id, recordId);
|
||
|
||
assert.equal(
|
||
await ctx.model.FileReference.count({
|
||
where: { business_type: 'stock_check_record', business_id: String(recordId) },
|
||
}),
|
||
0,
|
||
'删除记录后其图片引用应被清理'
|
||
);
|
||
assert.equal((await queryRecords(check.id, detail.id)).length, 0, '作业记录应被删除');
|
||
});
|
||
|
||
it('recordList 未知商品展示口径:item_code=条码、item_name=名称快照;已知商品维持明细快照', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const detail = details.rows[0];
|
||
|
||
await reportCheck(check.id, detail.id, 2, TEST_LOCATION_CODE);
|
||
const unknownBarcode = uniqueTitle('UNKNOWN-LIST');
|
||
await reportCheck(check.id, detail.id, 3, TEST_LOCATION_CODE_2, {
|
||
barcode: unknownBarcode,
|
||
itemName: '盘点神秘商品',
|
||
});
|
||
|
||
const listed = await listRecords({ id: check.id, detailId: detail.id });
|
||
assert.equal(listed.total, 2);
|
||
|
||
const unknownRow = listed.rows.find(row => row.stock_id === null);
|
||
const knownRow = listed.rows.find(row => row.stock_id !== null);
|
||
assert.ok(unknownRow, '应存在未知商品记录');
|
||
assert.ok(knownRow, '应存在已知商品记录');
|
||
assert.equal(unknownRow.item_code, unknownBarcode, '未知商品编码列显示扫描条码');
|
||
assert.equal(unknownRow.item_name, '盘点神秘商品', '未知商品名称列显示名称快照');
|
||
assert.equal(unknownRow.barcode, unknownBarcode, '记录含原始条码字段');
|
||
assert.equal(knownRow.item_code, detail.item_code, '已知商品编码列维持明细快照');
|
||
assert.equal(knownRow.item_name, detail.item_name, '已知商品名称列维持明细快照');
|
||
assert.deepEqual(unknownRow.images, [], '无图片记录 images 应为空数组');
|
||
assert.equal(unknownRow.store_id, null, '未知商品 store_id 应为 null');
|
||
assert.equal(unknownRow.store_name, null, '未知商品 store_name 应为 null');
|
||
assert.equal(unknownRow.spec, null, '未知商品 spec 应为 null');
|
||
});
|
||
|
||
it('recordList 对齐 workData:已知商品挂 store_id/store_name/spec/商品条码,保留记录全字段', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const reportResult = await reportCheck(check.id, details.rows[0].id, 3, undefined, { stockId: stocks[0].id });
|
||
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
[ stocks[0].id ],
|
||
{ warehouseId: TEST_WAREHOUSE_ID }
|
||
);
|
||
const stockDetail = stockDetails.find(item => Number(item.id) === Number(stocks[0].id)) || {};
|
||
|
||
const listed = await listRecords({ id: check.id });
|
||
assert.equal(listed.total, 1);
|
||
const row = listed.rows[0];
|
||
assert.equal(Number(row.id), Number(reportResult.record.id));
|
||
// 保留记录全字段
|
||
for (const key of [ 'check_id', 'warehouse_id', 'detail_id', 'stock_id', 'location_id', 'quantity', 'checker_id', 'checker_name', 'checked_at', 'is_empty', 'remark' ]) {
|
||
assert.ok(Object.prototype.hasOwnProperty.call(row, key), `应保留全字段 ${key}`);
|
||
}
|
||
// 对齐 workData 商品口径
|
||
assert.equal(Number(row.store_id), Number(stockDetail.store_id) || 0, '应挂商品货主ID');
|
||
assert.ok(row.store_name, '应解析货主名');
|
||
assert.equal(row.spec, stockDetail.sku_property || null, '应挂商品规格');
|
||
assert.ok(row.item_code);
|
||
assert.ok(row.barcode, '应挂商品条码(workData 口径)');
|
||
assert.deepEqual(row.images, [], '保留 images 作业照片字段');
|
||
});
|
||
|
||
it('report 未传 stock_id 且未传 barcode:库位行报 400,barcode 空串同口径', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 1);
|
||
}, error => error.code === 400 && /必须指定商品/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, detail.id, 1, undefined, { barcode: ' ' });
|
||
}, error => error.code === 400 && /必须指定商品/.test(error.message));
|
||
});
|
||
|
||
it('已知商品原链路回归:库位行传 stock_id 正常上报,barcode/item_name 保持 NULL', async () => {
|
||
const { check, detail } = await createApprovedLocationCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
const result = await reportCheck(check.id, detail.id, 6, undefined, { stockId: stocks[0].id });
|
||
|
||
assert.equal(result.mode, 'created');
|
||
assert.equal(Number(result.record.stock_id), Number(stocks[0].id));
|
||
assert.equal(result.record.barcode, null, '已知商品未传条码 barcode 应为 NULL');
|
||
assert.equal(result.record.item_name, null, '已知商品 item_name 应为 NULL');
|
||
assert.equal(result.checked_items, 1);
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(row.checked_items, 1);
|
||
});
|
||
});
|
||
|
||
// ------------------- 操作日志(wms_operation_log):10 个写操作落库验证 -------------------
|
||
|
||
describe('操作日志落库(wms_operation_log,business_type=stock_check)', () => {
|
||
/**
|
||
* 查询某个盘点任务的全部操作日志(按 id 升序)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Array<Object>>} 日志行(plain)。
|
||
*/
|
||
async function queryOperationLogs(checkId) {
|
||
return ctx.model.OperationLog.findAll({
|
||
where: { business_type: 'stock_check', business_id: String(checkId) },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询某个盘点任务指定 operation_code 的日志行。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @param {string} operationCode 操作编码。
|
||
* @return {Promise<Array<Object>>} 日志行(plain)。
|
||
*/
|
||
async function queryOperationLogsByCode(checkId, operationCode) {
|
||
const logs = await queryOperationLogs(checkId);
|
||
return logs.filter(item => item.operation_code === operationCode);
|
||
}
|
||
|
||
it('create 写入 STOCK_CHECK_CREATE:business_id=任务 id、warehouse_id=100000、message 含单号', async () => {
|
||
const result = await createCheck();
|
||
|
||
const logs = await queryOperationLogsByCode(result.id, 'STOCK_CHECK_CREATE');
|
||
|
||
assert.equal(logs.length, 1, '创建成功后应写入 1 条 STOCK_CHECK_CREATE 日志');
|
||
const log = logs[0];
|
||
assert.equal(log.business_type, 'stock_check');
|
||
assert.equal(log.business_id, String(result.id), 'business_id 应为任务 id');
|
||
assert.equal(Number(log.warehouse_id), TEST_WAREHOUSE_ID, 'warehouse_id 应为固定测试仓库');
|
||
assert.ok(log.message && log.message.includes(result.check_no), `message 应包含单号: ${log.message}`);
|
||
});
|
||
|
||
it('addDetail/detailDelete 分别写入 STOCK_CHECK_ADD_DETAIL 与 STOCK_CHECK_DELETE_DETAIL', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
await deleteDetail(check.id, detailId);
|
||
|
||
const addLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_ADD_DETAIL');
|
||
assert.equal(addLogs.length, 1, '添加明细成功后应写入 1 条 STOCK_CHECK_ADD_DETAIL 日志');
|
||
assert.ok(addLogs[0].message && addLogs[0].message.includes('添加盘点明细'), `message 应含操作描述: ${addLogs[0].message}`);
|
||
assert.equal(Number(addLogs[0].warehouse_id), TEST_WAREHOUSE_ID);
|
||
|
||
const deleteLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_DELETE_DETAIL');
|
||
assert.equal(deleteLogs.length, 1, '删除明细成功后应写入 1 条 STOCK_CHECK_DELETE_DETAIL 日志');
|
||
assert.ok(
|
||
deleteLogs[0].message && deleteLogs[0].message.includes('删除盘点明细'),
|
||
`message 应含操作描述: ${deleteLogs[0].message}`
|
||
);
|
||
assert.ok(
|
||
deleteLogs[0].message && deleteLogs[0].message.includes('删除 1 个,跳过 0 个'),
|
||
`message 应含批量删除统计: ${deleteLogs[0].message}`
|
||
);
|
||
assert.equal(Number(deleteLogs[0].warehouse_id), TEST_WAREHOUSE_ID);
|
||
});
|
||
|
||
it('submit/cancel 分别写入 STOCK_CHECK_SUBMIT 与 STOCK_CHECK_CANCEL', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await cancelCheck(check.id);
|
||
|
||
const submitLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_SUBMIT');
|
||
assert.equal(submitLogs.length, 1, '提交审核成功后应写入 1 条 STOCK_CHECK_SUBMIT 日志');
|
||
assert.equal(submitLogs[0].business_id, String(check.id));
|
||
assert.ok(submitLogs[0].message && submitLogs[0].message.includes('提交审核'), `message 应含操作描述: ${submitLogs[0].message}`);
|
||
|
||
const cancelLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_CANCEL');
|
||
assert.equal(cancelLogs.length, 1, '取消成功后应写入 1 条 STOCK_CHECK_CANCEL 日志');
|
||
assert.equal(cancelLogs[0].business_id, String(check.id));
|
||
assert.ok(cancelLogs[0].message && cancelLogs[0].message.includes('取消盘点任务'), `message 应含操作描述: ${cancelLogs[0].message}`);
|
||
});
|
||
|
||
it('report/recordDelete 分别写入 STOCK_CHECK_REPORT 与 STOCK_CHECK_DELETE_RECORD', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
|
||
const reportResult = await reportCheck(check.id, detailId, 7);
|
||
assert.equal(reportResult.mode, 'created');
|
||
|
||
const reportLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_REPORT');
|
||
assert.equal(reportLogs.length, 1, '上报成功后应写入 1 条 STOCK_CHECK_REPORT 日志');
|
||
assert.equal(reportLogs[0].business_id, String(check.id));
|
||
assert.equal(Number(reportLogs[0].warehouse_id), TEST_WAREHOUSE_ID);
|
||
assert.ok(reportLogs[0].message && reportLogs[0].message.includes(`明细 ${detailId}`), `message 应含 detail_id: ${reportLogs[0].message}`);
|
||
assert.ok(reportLogs[0].message && reportLogs[0].message.includes('实盘 7'), `message 应含实盘数量: ${reportLogs[0].message}`);
|
||
|
||
const records = await queryRecords(check.id, detailId);
|
||
assert.equal(records.length, 1, '前置:应有 1 条作业记录');
|
||
await deleteRecord(check.id, records[0].id);
|
||
|
||
const deleteLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_DELETE_RECORD');
|
||
assert.equal(deleteLogs.length, 1, '删除作业记录后应写入 1 条 STOCK_CHECK_DELETE_RECORD 日志');
|
||
assert.ok(deleteLogs[0].message && deleteLogs[0].message.includes('批量删除盘点作业记录 1 条'), `message 应含批量删除描述: ${deleteLogs[0].message}`);
|
||
});
|
||
|
||
it('finish 写入 STOCK_CHECK_FINISH:message 含差异汇总(盘盈/盘亏)', async () => {
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 0);
|
||
|
||
const finishResult = await finishCheck(check.id);
|
||
assert.equal(finishResult.status, 'completed');
|
||
|
||
const logs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_FINISH');
|
||
assert.equal(logs.length, 1, '完成后应写入 1 条 STOCK_CHECK_FINISH 日志');
|
||
assert.equal(logs[0].business_id, String(check.id));
|
||
assert.ok(logs[0].message && logs[0].message.includes('完成盘点'), `message 应含操作描述: ${logs[0].message}`);
|
||
assert.ok(logs[0].message && logs[0].message.includes('盘盈'), `message 应含盘盈汇总: ${logs[0].message}`);
|
||
assert.ok(logs[0].message && logs[0].message.includes('盘亏'), `message 应含盘亏汇总: ${logs[0].message}`);
|
||
});
|
||
|
||
it('audit approve/reject 写入 STOCK_CHECK_AUDIT:reject message 含驳回原因', async () => {
|
||
const approveCheck = await createCheck();
|
||
const approveStocks = await fetchStockRows(1);
|
||
await addDetail(approveCheck.id, [ approveStocks[0].id ]);
|
||
await submitCheck(approveCheck.id);
|
||
await auditCheck(approveCheck.id, 'approve');
|
||
|
||
const rejectCheck = await createCheck();
|
||
const rejectStocks = await fetchStockRows(1);
|
||
await addDetail(rejectCheck.id, [ rejectStocks[0].id ]);
|
||
await submitCheck(rejectCheck.id);
|
||
const rejectReason = '实盘与账面差异过大-测试驳回';
|
||
await auditCheck(rejectCheck.id, 'reject', rejectReason);
|
||
|
||
const approveLogs = await queryOperationLogsByCode(approveCheck.id, 'STOCK_CHECK_AUDIT');
|
||
assert.equal(approveLogs.length, 1, '审核通过应写入 1 条 STOCK_CHECK_AUDIT 日志');
|
||
assert.ok(approveLogs[0].message && approveLogs[0].message.includes('审核通过'), `approve message 应含动作: ${approveLogs[0].message}`);
|
||
|
||
const rejectLogs = await queryOperationLogsByCode(rejectCheck.id, 'STOCK_CHECK_AUDIT');
|
||
assert.equal(rejectLogs.length, 1, '审核驳回应写入 1 条 STOCK_CHECK_AUDIT 日志');
|
||
assert.ok(rejectLogs[0].message && rejectLogs[0].message.includes('审核驳回'), `reject message 应含动作: ${rejectLogs[0].message}`);
|
||
assert.ok(rejectLogs[0].message && rejectLogs[0].message.includes(rejectReason), 'reject 日志 message 应包含驳回原因');
|
||
});
|
||
|
||
it('batchDelete 删除 2 个作废任务仅写 1 条日志:business_id=首个删除 id、message 含删除/跳过数量', async () => {
|
||
const cancelledA = await createCancelledCheck();
|
||
const cancelledB = await createCancelledCheck();
|
||
|
||
const result = await batchDeleteCheck([ cancelledA.check.id, cancelledB.check.id ]);
|
||
assert.equal(result.deleted_count, 2);
|
||
assert.equal(result.skipped_count, 0);
|
||
|
||
const logsA = await queryOperationLogsByCode(cancelledA.check.id, 'STOCK_CHECK_BATCH_DELETE');
|
||
assert.equal(logsA.length, 1, '删除 2 个任务应只写 1 条日志,business_id 取首个删除 id');
|
||
assert.equal(logsA[0].business_id, String(cancelledA.check.id), 'business_id 应为首个删除任务 id');
|
||
assert.equal(Number(logsA[0].warehouse_id), TEST_WAREHOUSE_ID);
|
||
assert.ok(logsA[0].message && logsA[0].message.includes('删除 2 个'), `message 应含删除数量: ${logsA[0].message}`);
|
||
assert.ok(logsA[0].message && logsA[0].message.includes('跳过 0 个'), `message 应含跳过数量: ${logsA[0].message}`);
|
||
|
||
const logsB = await queryOperationLogsByCode(cancelledB.check.id, 'STOCK_CHECK_BATCH_DELETE');
|
||
assert.equal(logsB.length, 0, '第二个删除 id 不应单独写日志');
|
||
|
||
// deletedIds 为空(全跳过)时不写日志
|
||
const missingId = await findFreeCheckId();
|
||
const skipResult = await batchDeleteCheck([ missingId ]);
|
||
assert.equal(skipResult.deleted_count, 0);
|
||
assert.equal(skipResult.skipped_count, 1);
|
||
const skipLogs = await queryOperationLogsByCode(missingId, 'STOCK_CHECK_BATCH_DELETE');
|
||
assert.equal(skipLogs.length, 0, 'deletedIds 为空时不应写 STOCK_CHECK_BATCH_DELETE 日志');
|
||
});
|
||
|
||
it('失败路径不写日志:submit 空任务/report 非法状态 400 后无新日志', async () => {
|
||
const check = await createCheck();
|
||
|
||
await assert.rejects(async () => {
|
||
await submitCheck(check.id);
|
||
}, error => error.code === 400 && /明细/.test(error.message));
|
||
|
||
const submitLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_SUBMIT');
|
||
assert.equal(submitLogs.length, 0, 'submit 失败后不应写入 STOCK_CHECK_SUBMIT 日志');
|
||
|
||
// created 状态不允许盘点作业:report 状态校验失败后不应写 STOCK_CHECK_REPORT
|
||
await assert.rejects(async () => {
|
||
await reportCheck(check.id, 1, 1);
|
||
}, error => error.code === 400 && /状态/.test(error.message));
|
||
|
||
const reportLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_REPORT');
|
||
assert.equal(reportLogs.length, 0, 'report 失败后不应写入 STOCK_CHECK_REPORT 日志');
|
||
|
||
// 对照:create 成功日志仍在
|
||
const createLogs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_CREATE');
|
||
assert.equal(createLogs.length, 1, '对照:STOCK_CHECK_CREATE 成功日志应存在');
|
||
});
|
||
|
||
it('operator 快照:operator_id/operator_name 与上下文一致', async () => {
|
||
// 真实测试工号(开发库 wms_account_store_employee:id=38,account autotest_acc_mgmt_keep,store_id=100000,status=1)
|
||
const operatorId = 38;
|
||
const operatorName = '测试工号保留';
|
||
ctx.user = { employees_id: operatorId, employees_name: operatorName };
|
||
|
||
const check = await createCheck();
|
||
delete ctx.user;
|
||
|
||
const logs = await queryOperationLogsByCode(check.id, 'STOCK_CHECK_CREATE');
|
||
assert.equal(logs.length, 1);
|
||
assert.equal(String(logs[0].operator_id), String(operatorId), 'operator_id 应快照 employees_id');
|
||
assert.equal(logs[0].operator_name, operatorName, 'operator_name 应快照 employees_name');
|
||
});
|
||
});
|
||
|
||
// ------------------- patternList/patternCreate:盘点定式快速创建 -------------------
|
||
|
||
describe('盘点定式 patternList/patternCreate(业务层 + 方法层)', () => {
|
||
/** 静态定式测试阈值:小时数(300 天,隔离开发库真实商品最后流水集中在 250~300 天的口径) */
|
||
const STATIC_TEST_HOURS = 7200;
|
||
/** 构造静态商品的主表创建时间(距今 330 天,超过阈值) */
|
||
const STATIC_STOCK_AGE_DAYS = 330;
|
||
/** 构造数据序号(保证 item_code/批次号等唯一) */
|
||
let fabricatedSeq = 0;
|
||
/** 上一个 static 用例构造的商品 ID(供再次调用排除断言) */
|
||
let staticStockAId = null;
|
||
|
||
/** 生成构造数据唯一后缀。 */
|
||
function nextFabricatedSuffix() {
|
||
fabricatedSeq += 1;
|
||
return `${Date.now()}-${fabricatedSeq}`;
|
||
}
|
||
|
||
/** 读取测试仓库 wms_store 实例(subject_config 归一化后返回)。 */
|
||
async function fetchSubjectConfigInstance() {
|
||
return ctx.model.Store.findOne({ where: { id: TEST_WAREHOUSE_ID } });
|
||
}
|
||
|
||
/**
|
||
* 临时修改测试仓库 subject_config,fn 执行后恢复原值。
|
||
*
|
||
* @param {Object} patch 待合并的配置覆盖项。
|
||
* @param {Function} fn 配置生效期间执行的异步函数。
|
||
* @return {Promise<*>} fn 的返回值。
|
||
*/
|
||
async function withSubjectConfig(patch, fn) {
|
||
const store = await fetchSubjectConfigInstance();
|
||
const previous = store.subject_config;
|
||
await store.update({ subject_config: { ...previous, ...patch } });
|
||
try {
|
||
return await fn();
|
||
} finally {
|
||
await ctx.model.Store.update(
|
||
{ subject_config: previous },
|
||
{ where: { id: TEST_WAREHOUSE_ID } }
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 业务层:按定式创建盘点任务(自动注入固定测试仓库与创建人)。
|
||
*
|
||
* @param {Object} [params={}] 创建参数覆盖项。
|
||
* @return {Promise<Object>} patternCreate 返回结果。
|
||
*/
|
||
async function patternCreateRaw(params = {}) {
|
||
return ctx.service.systems.stockCheck.patternCreate({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
...params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 按定式收集盘点对象(业务层直调 stockCheckPatterns.collectById)。
|
||
*
|
||
* @param {string} patternId 定式ID。
|
||
* @return {Promise<Object>} 收集结果。
|
||
*/
|
||
async function collectPattern(patternId) {
|
||
return ctx.service.systems.stockCheckPatterns.collectById(patternId, {
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 直查任务全部明细行(按 id 升序)。
|
||
*
|
||
* @param {number} checkId 盘点任务ID。
|
||
* @return {Promise<Array<Object>>} 明细行(plain)。
|
||
*/
|
||
async function queryCheckDetails(checkId) {
|
||
return ctx.model.StockCheckDetail.findAll({
|
||
where: { check_id: Number(checkId) },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 构造一个全新商品主表行(raw SQL,固定测试仓库/货主)。
|
||
*
|
||
* @param {Object} [options={}] 构造参数(itemCode/createAt/quantity/shelfLife/thresholdDays)。
|
||
* @return {Promise<Object>} { id, itemCode }。
|
||
*/
|
||
async function createFabricatedStock(options = {}) {
|
||
const itemCode = options.itemCode || `PATT-STOCK-${nextFabricatedSuffix()}`;
|
||
const [ result ] = await ctx.model.query(
|
||
`INSERT INTO wms_stock_warehouse
|
||
(item_code, item_name, store_id, stock_unit, item_type, create_at,
|
||
warehouse_id, is_valid, quantity, is_shelf_life_mgmt, remaining_threshold_days)
|
||
VALUES (:itemCode, '盘点定式测试商品', :storeId, '个', 'normal', :createAt,
|
||
:warehouseId, 'Y', :quantity, :shelfLife, :thresholdDays)`,
|
||
{
|
||
replacements: {
|
||
itemCode,
|
||
storeId: TEST_STORE_ID,
|
||
createAt: options.createAt || new Date(),
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
quantity: options.quantity !== undefined ? options.quantity : 0,
|
||
shelfLife: options.shelfLife || 'N',
|
||
thresholdDays: options.thresholdDays !== undefined ? options.thresholdDays : 0,
|
||
},
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
return { id: Number(result), itemCode };
|
||
}
|
||
|
||
/**
|
||
* 构造一条库存行(raw SQL,固定测试仓库/货主/库位)。
|
||
*
|
||
* @param {Object} [options={}] 构造参数(stockId/spaceId/batchNo/quantity/expiryDate/orderNo)。
|
||
* @return {Promise<string>} 批次号。
|
||
*/
|
||
async function createFabricatedStorage(options = {}) {
|
||
const batchNo = options.batchNo || `PATT-BATCH-${nextFabricatedSuffix()}`;
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_storage
|
||
(warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type,
|
||
quantity, expiry_date, inbound_time, inbound_order_no)
|
||
VALUES (:warehouseId, :storeId, :spaceId, :stockId, :batchNo, 'ZP',
|
||
:quantity, :expiryDate, NOW(), :orderNo)`,
|
||
{
|
||
replacements: {
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
storeId: TEST_STORE_ID,
|
||
spaceId: options.spaceId,
|
||
stockId: options.stockId,
|
||
batchNo,
|
||
quantity: options.quantity !== undefined ? options.quantity : 5,
|
||
expiryDate: options.expiryDate || null,
|
||
orderNo: options.orderNo || `PATT-IN-${nextFabricatedSuffix()}`,
|
||
},
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
return batchNo;
|
||
}
|
||
|
||
/**
|
||
* 构造错发售后工单与订单明细分表行(raw SQL,固定测试仓库)。
|
||
*
|
||
* @param {number} stockId 关联商品库存ID。
|
||
* @return {Promise<Object>} { orderId, afterSaleNo }。
|
||
*/
|
||
async function createFabricatedMisShipment(stockId) {
|
||
const suffix = nextFabricatedSuffix();
|
||
const [ maxRows ] = await ctx.model.query(
|
||
'SELECT COALESCE(MAX(order_id), 0) AS maxOrderId FROM wms_order_items_100000',
|
||
{ type: ctx.model.QueryTypes.SELECT }
|
||
);
|
||
const orderId = Number(maxRows.maxOrderId) + 1;
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_order_items_100000
|
||
(order_id, item_code, item_name, stock_id, actual_price, created_at, updated_at)
|
||
VALUES (:orderId, 'PATT-ITEM', '错发盘点测试商品', :stockId, 0, NOW(), NOW())`,
|
||
{
|
||
replacements: { orderId, stockId },
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
const afterSaleNo = `AS${currentDatePart()}T${suffix}`;
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_after_sale
|
||
(warehouse_id, after_sale_no, type, sub_type, status, title, creator_id, order_id)
|
||
VALUES (:warehouseId, :afterSaleNo, 'order', 'mis_shipment', 'pending',
|
||
'错发盘点测试工单', :creatorId, :orderId)`,
|
||
{
|
||
replacements: {
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
afterSaleNo,
|
||
creatorId: TEST_CREATOR_ID,
|
||
orderId,
|
||
},
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
return { orderId, afterSaleNo };
|
||
}
|
||
|
||
it('patternList:返回 5 个定式,id/name/description/type 字段完整且 type 取值合法', async () => {
|
||
const result = await ctx.service.systems.stockCheck.patternList();
|
||
|
||
assert.equal(result.total, 5);
|
||
assert.equal(result.patterns.length, 5);
|
||
assert.deepEqual(
|
||
result.patterns.map(item => item.id),
|
||
[ 'empty_location', 'mis_shipment', 'expiring', 'static', 'warning' ],
|
||
'定式顺序应与注册顺序一致'
|
||
);
|
||
for (const pattern of result.patterns) {
|
||
assert.deepEqual(
|
||
Object.keys(pattern).sort(),
|
||
[ 'description', 'id', 'name', 'type' ],
|
||
'每条定式应仅包含 id/name/description/type 字段'
|
||
);
|
||
assert.ok(pattern.id, 'id 不应为空');
|
||
assert.ok(pattern.name, 'name 不应为空');
|
||
assert.ok(pattern.description, 'description 不应为空');
|
||
assert.ok([ 'location', 'goods' ].includes(pattern.type), `type 取值非法: ${pattern.type}`);
|
||
}
|
||
const locationPatterns = result.patterns.filter(item => item.type === 'location');
|
||
assert.deepEqual(locationPatterns.map(item => item.id), [ 'empty_location' ]);
|
||
for (const goodsPattern of [ 'mis_shipment', 'expiring', 'static', 'warning' ]) {
|
||
assert.equal(
|
||
result.patterns.find(item => item.id === goodsPattern).type,
|
||
'goods',
|
||
`${goodsPattern} 应为 goods 型定式`
|
||
);
|
||
}
|
||
});
|
||
|
||
it('method 层 patternList:success 包装返回 patterns/total', async () => {
|
||
ctx.user = { id: TEST_CREATOR_ID, store_id: TEST_WAREHOUSE_ID, employees_name: TEST_CREATOR_NAME };
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.patternList();
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.total, 5);
|
||
assert.equal(result.data.patterns.length, 5);
|
||
});
|
||
|
||
it('patternCreate(warning):submitted/none_checked、type=goods、mode=open、不含 check_date、明细快照、total_items、check_no 与日志 STOCK_CHECK_CREATE(含 pattern_id)', async () => {
|
||
const title = uniqueTitle('预警定式创建');
|
||
const result = await withSubjectConfig(
|
||
{ stock_warning_enabled: true, stock_warning_quantity: 999999999 },
|
||
async () => {
|
||
const collected = await collectPattern('warning');
|
||
assert.ok(collected.stock_ids.length > 0, '前置:开启预警后应存在符合条件的商品');
|
||
return patternCreateRaw({
|
||
patternId: 'warning',
|
||
title,
|
||
remark: '定式创建测试',
|
||
});
|
||
}
|
||
);
|
||
|
||
assert.equal(result.pattern_id, 'warning');
|
||
const check = result.check;
|
||
assert.match(check.check_no, /^PD\d{14}$/, `应生成盘点单号: ${check.check_no}`);
|
||
assert.equal(check.status, 'submitted', '定式创建的任务应直接进入待审核');
|
||
assert.equal(check.detail_status, 'none_checked');
|
||
assert.equal(check.type, 'goods', 'warning 定式应为按商品盘点');
|
||
assert.equal(check.mode, 'open', '商品类定式应固定明盘(open)');
|
||
assert.equal(Number(check.is_static), 0, '非静态定式创建的任务应为普通盘点(is_static=0)');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(check, 'check_date'),
|
||
false,
|
||
'patternCreate 返回不应含 check_date 字段'
|
||
);
|
||
assert.equal(check.start_time, null, '定式创建任务 start_time 应为空');
|
||
assert.equal(check.end_time, null, '定式创建任务 end_time 应为空');
|
||
assert.equal(check.title, title);
|
||
assert.equal(check.creator_id, TEST_CREATOR_ID);
|
||
assert.ok(result.total_items > 0, '应有明细行');
|
||
|
||
const row = await findCheckRow(check.id);
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID);
|
||
assert.equal(row.status, 'submitted');
|
||
assert.equal(row.total_items, result.total_items);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, 'check_date'),
|
||
false,
|
||
'主表行不应含 check_date 字段'
|
||
);
|
||
|
||
const details = await queryCheckDetails(check.id);
|
||
const detailStockIds = new Set(details.map(detail => Number(detail.stock_id)));
|
||
assert.equal(detailStockIds.size, result.total_items, 'total_items 应按商品计数(多库位商品拆多行仍计 1 项)');
|
||
assert.ok(details.length >= result.total_items, '明细行数应不少于商品数(按「商品+库位」拆行)');
|
||
for (const detail of details) {
|
||
assert.equal(detail.scope_type, 'goods');
|
||
assert.ok(detail.stock_id, '商品明细应含 stock_id');
|
||
assert.ok(detail.item_code, '商品明细应含商品编码快照');
|
||
}
|
||
|
||
const logs = await ctx.model.OperationLog.findAll({
|
||
where: {
|
||
business_type: 'stock_check',
|
||
business_id: String(check.id),
|
||
operation_code: 'STOCK_CHECK_CREATE',
|
||
},
|
||
raw: true,
|
||
});
|
||
assert.equal(logs.length, 1, '应写入 1 条 STOCK_CHECK_CREATE 日志');
|
||
assert.ok(logs[0].message && logs[0].message.includes('warning'), `日志应含 pattern_id: ${logs[0].message}`);
|
||
assert.ok(logs[0].message && logs[0].message.includes(check.check_no), '日志应含盘点单号');
|
||
assert.equal(Number(logs[0].warehouse_id), TEST_WAREHOUSE_ID);
|
||
});
|
||
|
||
it('patternCreate 参数校验:定式不存在/缺仓库 → 400 且未创建任务(mode/check_date 已移除入参)', async () => {
|
||
const beforeRow = await ctx.model.StockCheck.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
const beforeMax = beforeRow ? Number(beforeRow.id) : 0;
|
||
|
||
await assert.rejects(async () => {
|
||
await patternCreateRaw({ patternId: 'not_exists' });
|
||
}, error => error.code === 400 && /盘点定式不存在/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await ctx.service.systems.stockCheck.patternCreate({
|
||
warehouseId: 0,
|
||
patternId: 'warning',
|
||
});
|
||
}, error => error.code === 400 && /仓库/.test(error.message));
|
||
|
||
const afterRow = await ctx.model.StockCheck.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(afterRow ? Number(afterRow.id) : 0, beforeMax, '参数非法时不应创建任务');
|
||
});
|
||
|
||
it('empty_location 收集口径:直查 wms_storage 对比,账面为空库位入库、有库存库位不入', async () => {
|
||
const { Op } = ctx.app.Sequelize;
|
||
const emptySpace = await ctx.model.LocationSpace.findOne({
|
||
where: { warehouse_id: TEST_WAREHOUSE_ID, space_code: TEST_EMPTY_LOCATION_CODE },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
const emptyStorageCnt = await ctx.model.Storage.count({
|
||
where: { space_id: Number(emptySpace.id), quantity: { [Op.gt]: 0 } },
|
||
});
|
||
const stockStorageCnt = await ctx.model.Storage.count({
|
||
where: { space_id: TEST_LOCATION_ID, quantity: { [Op.gt]: 0 } },
|
||
});
|
||
assert.equal(emptyStorageCnt, 0, `前置:${TEST_EMPTY_LOCATION_CODE} 应无 quantity>0 库存`);
|
||
assert.ok(stockStorageCnt > 0, `前置:${TEST_LOCATION_CODE} 应有 quantity>0 库存`);
|
||
|
||
const collected = await collectPattern('empty_location');
|
||
const codes = collected.locations.map(item => item.location_code);
|
||
assert.ok(codes.includes(TEST_EMPTY_LOCATION_CODE), '账面为空库位应被收集');
|
||
assert.ok(!codes.includes(TEST_LOCATION_CODE), '有库存库位不应被收集');
|
||
for (const location of collected.locations) {
|
||
assert.ok(Number(location.location_id) > 0, 'location_id 应为正整数');
|
||
assert.ok(location.location_code, 'location_code 不应为空');
|
||
}
|
||
});
|
||
|
||
it('empty_location patternCreate:明细只含空库位(location 行)、total_items=收集数、mode=blind、不含 check_date', async () => {
|
||
const collected = await collectPattern('empty_location');
|
||
assert.ok(collected.locations.length > 0, '前置:应存在账面为空库位');
|
||
|
||
const result = await patternCreateRaw({
|
||
patternId: 'empty_location',
|
||
title: uniqueTitle('空库位定式创建'),
|
||
});
|
||
|
||
assert.equal(result.pattern_id, 'empty_location');
|
||
assert.equal(result.check.type, 'location');
|
||
assert.equal(result.check.status, 'submitted');
|
||
assert.equal(result.check.mode, 'blind', '库位类定式应固定盲盘(blind)');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(result.check, 'check_date'),
|
||
false,
|
||
'patternCreate 返回不应含 check_date 字段'
|
||
);
|
||
assert.equal(result.check.start_time, null, '定式创建任务 start_time 应为空');
|
||
assert.equal(result.check.end_time, null, '定式创建任务 end_time 应为空');
|
||
assert.equal(result.total_items, collected.locations.length);
|
||
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.equal(details.length, result.total_items);
|
||
const collectedCodes = new Set(collected.locations.map(item => item.location_code));
|
||
for (const detail of details) {
|
||
assert.equal(detail.scope_type, 'location', '库位明细行 scope_type 应为 location');
|
||
assert.equal(detail.stock_id, null, '库位明细行不应含 stock_id');
|
||
assert.ok(Number(detail.location_id) > 0, '库位明细行应含 location_id');
|
||
assert.ok(collectedCodes.has(detail.location_code), `明细库位应属于收集结果: ${detail.location_code}`);
|
||
}
|
||
assert.ok(
|
||
details.some(item => item.location_code === TEST_EMPTY_LOCATION_CODE),
|
||
'明细应含账面为空库位'
|
||
);
|
||
assert.ok(
|
||
!details.some(item => item.location_code === TEST_LOCATION_CODE),
|
||
'明细不应含有库存库位'
|
||
);
|
||
});
|
||
|
||
it('warning 定式:开启配置后低于阈值商品入明细;关闭配置 → 400 未开启库存预警', async () => {
|
||
let lowStockId = 0;
|
||
await withSubjectConfig(
|
||
{ stock_warning_enabled: true, stock_warning_quantity: 2 },
|
||
async () => {
|
||
const lowStock = await createFabricatedStock({ quantity: 1 });
|
||
lowStockId = lowStock.id;
|
||
// 商品必须有库存库位才能入明细(商品任务按库位盘点拆行)
|
||
await createFabricatedStorage({ stockId: lowStock.id, spaceId: TEST_LOCATION_ID, quantity: 1 });
|
||
const collected = await collectPattern('warning');
|
||
assert.ok(collected.stock_ids.includes(lowStock.id), '低于阈值商品应被收集');
|
||
|
||
const result = await patternCreateRaw({
|
||
patternId: 'warning',
|
||
title: uniqueTitle('预警阈值创建'),
|
||
});
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.ok(
|
||
details.some(item => Number(item.stock_id) === lowStock.id),
|
||
'低于阈值商品应写入明细'
|
||
);
|
||
}
|
||
);
|
||
assert.ok(lowStockId > 0, '前置:应已构造低于阈值商品');
|
||
|
||
await assert.rejects(async () => {
|
||
await patternCreateRaw({ patternId: 'warning' });
|
||
}, error => error.code === 400 && /未开启库存预警/.test(error.message));
|
||
});
|
||
|
||
it('static 定式:超时商品入明细,创建后写入 wms_stock_static_check_task', async () => {
|
||
const stockA = await createFabricatedStock({
|
||
itemCode: `PATT-STATIC-A-${nextFabricatedSuffix()}`,
|
||
createAt: new Date(Date.now() - STATIC_STOCK_AGE_DAYS * 24 * 3600 * 1000),
|
||
});
|
||
staticStockAId = stockA.id;
|
||
await createFabricatedStorage({ stockId: stockA.id, spaceId: TEST_LOCATION_ID, quantity: 1 });
|
||
|
||
const result = await withSubjectConfig(
|
||
{ stock_static_hours: STATIC_TEST_HOURS },
|
||
async () => {
|
||
const collected = await collectPattern('static');
|
||
assert.ok(collected.stock_ids.includes(stockA.id), '构造的超时商品应被收集');
|
||
return patternCreateRaw({
|
||
patternId: 'static',
|
||
title: uniqueTitle('静态定式创建'),
|
||
});
|
||
}
|
||
);
|
||
|
||
assert.equal(result.pattern_id, 'static');
|
||
assert.equal(result.check.type, 'goods');
|
||
assert.equal(result.check.mode, 'open', '商品类定式应固定明盘(open)');
|
||
assert.equal(Number(result.check.is_static), 1, '静态定式创建的任务应标记为静态盘点');
|
||
const staticTaskRow = await findCheckRow(result.check.id);
|
||
assert.equal(Number(staticTaskRow.is_static), 1, '主表应落库 is_static=1');
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.ok(details.some(item => Number(item.stock_id) === stockA.id), '超时商品应写入明细');
|
||
|
||
const taskRows = await ctx.model.StockStaticCheckTask.findAll({
|
||
where: { stock_id: stockA.id },
|
||
raw: true,
|
||
});
|
||
assert.ok(taskRows.length >= 1, '创建成功后应写入静态盘点任务关联记录');
|
||
});
|
||
|
||
it('static 再次调用:已盘商品被排除,明细不再包含', async () => {
|
||
assert.ok(staticStockAId > 0, '前置:上一个用例应已构造静态商品 A');
|
||
const stockB = await createFabricatedStock({
|
||
itemCode: `PATT-STATIC-B-${nextFabricatedSuffix()}`,
|
||
createAt: new Date(Date.now() - STATIC_STOCK_AGE_DAYS * 24 * 3600 * 1000),
|
||
});
|
||
await createFabricatedStorage({ stockId: stockB.id, spaceId: TEST_LOCATION_ID, quantity: 1 });
|
||
|
||
const result = await withSubjectConfig(
|
||
{ stock_static_hours: STATIC_TEST_HOURS },
|
||
async () => {
|
||
const collected = await collectPattern('static');
|
||
assert.ok(collected.stock_ids.includes(stockB.id), '新构造超时商品应被收集');
|
||
assert.ok(
|
||
!collected.stock_ids.includes(staticStockAId),
|
||
'已写入静态任务记录的商品应被排除'
|
||
);
|
||
return patternCreateRaw({
|
||
patternId: 'static',
|
||
title: uniqueTitle('静态定式再次创建'),
|
||
});
|
||
}
|
||
);
|
||
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.ok(details.some(item => Number(item.stock_id) === stockB.id), '再次调用应只含新超时商品');
|
||
assert.ok(
|
||
!details.some(item => Number(item.stock_id) === staticStockAId),
|
||
'已盘商品不应再出现在明细中'
|
||
);
|
||
});
|
||
|
||
it('expiring 定式:构造保质期管理商品与已过期库存 → 入明细', async () => {
|
||
const expiryStock = await createFabricatedStock({
|
||
itemCode: `PATT-EXP-${nextFabricatedSuffix()}`,
|
||
shelfLife: 'Y',
|
||
thresholdDays: null,
|
||
});
|
||
await createFabricatedStorage({
|
||
stockId: expiryStock.id,
|
||
spaceId: TEST_LOCATION_ID,
|
||
quantity: 3,
|
||
expiryDate: new Date(Date.now() - 24 * 3600 * 1000),
|
||
});
|
||
|
||
const collected = await collectPattern('expiring');
|
||
assert.ok(collected.stock_ids.includes(expiryStock.id), '临期商品应被收集');
|
||
|
||
const result = await patternCreateRaw({
|
||
patternId: 'expiring',
|
||
title: uniqueTitle('临期定式创建'),
|
||
});
|
||
assert.equal(result.check.type, 'goods');
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.ok(
|
||
details.some(item => Number(item.stock_id) === expiryStock.id),
|
||
'临期商品应写入明细'
|
||
);
|
||
});
|
||
|
||
it('mis_shipment 定式:构造错发工单与订单明细商品 → 入明细', async () => {
|
||
const stocks = await fetchStockRows(1);
|
||
assert.equal(stocks.length, 1);
|
||
const stockId = Number(stocks[0].id);
|
||
await createFabricatedMisShipment(stockId);
|
||
|
||
const collected = await collectPattern('mis_shipment');
|
||
assert.ok(collected.stock_ids.includes(stockId), '错发工单关联商品应被收集');
|
||
|
||
const result = await patternCreateRaw({
|
||
patternId: 'mis_shipment',
|
||
title: uniqueTitle('错发定式创建'),
|
||
});
|
||
assert.equal(result.check.type, 'goods');
|
||
const details = await queryCheckDetails(result.check.id);
|
||
assert.ok(
|
||
details.some(item => Number(item.stock_id) === stockId),
|
||
'错发商品应写入明细'
|
||
);
|
||
});
|
||
|
||
it('无符合条件的商品 → 400「没有符合条件的商品」且未创建任务', async () => {
|
||
const beforeRow = await ctx.model.StockCheck.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
const beforeMax = beforeRow ? Number(beforeRow.id) : 0;
|
||
|
||
await withSubjectConfig(
|
||
{ stock_warning_enabled: true, stock_warning_quantity: 0 },
|
||
async () => {
|
||
await assert.rejects(async () => {
|
||
await patternCreateRaw({ patternId: 'warning' });
|
||
}, error => error.code === 400 && /没有符合条件的商品/.test(error.message));
|
||
}
|
||
);
|
||
|
||
const afterRow = await ctx.model.StockCheck.findOne({
|
||
attributes: [ 'id' ],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
assert.equal(afterRow ? Number(afterRow.id) : 0, beforeMax, '无对象时不应创建任务');
|
||
});
|
||
|
||
it('method 层 patternCreate:驼峰 patternId 兼容、仓库注入、定式不存在/缺仓库 400 包装', async () => {
|
||
ctx.user = { id: TEST_CREATOR_ID, store_id: TEST_WAREHOUSE_ID, employees_name: TEST_CREATOR_NAME };
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.patternCreate({
|
||
patternId: 'mis_shipment',
|
||
title: uniqueTitle('方法层驼峰创建'),
|
||
});
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.pattern_id, 'mis_shipment');
|
||
assert.equal(result.data.check.status, 'submitted');
|
||
assert.ok(result.data.total_items >= 1, '错发定式应收集到商品');
|
||
const row = await findCheckRow(result.data.check.id);
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, '仓库应由 ctx.user.store_id 注入');
|
||
|
||
const notFound = await ctx.service.systemMethods.stock.check.patternCreate({
|
||
pattern_id: 'not_exists',
|
||
});
|
||
assert.equal(notFound.flag, 'failure');
|
||
assert.equal(notFound.code, 400);
|
||
assert.match(notFound.message, /盘点定式不存在/);
|
||
|
||
ctx.user = null;
|
||
const noWarehouse = await ctx.service.systemMethods.stock.check.patternCreate({
|
||
pattern_id: 'mis_shipment',
|
||
});
|
||
assert.equal(noWarehouse.flag, 'failure');
|
||
assert.equal(noWarehouse.code, 400);
|
||
assert.match(noWarehouse.message, /仓库/);
|
||
});
|
||
});
|
||
|
||
// ------------------- systemMethods.stock.check:方法包装层 -------------------
|
||
|
||
describe('systemMethods.stock.check 方法包装层', () => {
|
||
/**
|
||
* 设置当前上下文的用户信息(模拟登录用户,仓库固定 100000)。
|
||
*/
|
||
function mockCurrentUser() {
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
}
|
||
|
||
it('create:注入仓库上下文并统一 success 包装', async () => {
|
||
mockCurrentUser();
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.create({
|
||
title: uniqueTitle('方法层创建'),
|
||
type: 'location',
|
||
mode: 'open',
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.match(result.data.check_no, /^PD\d{14}$/);
|
||
assert.equal(result.data.status, 'created');
|
||
assert.equal(result.data.creator_id, TEST_CREATOR_ID, '创建人应由上下文注入');
|
||
assert.equal(result.data.creator_name, TEST_CREATOR_NAME);
|
||
|
||
const row = await findCheckRow(result.data.id);
|
||
assert.equal(row.warehouse_id, TEST_WAREHOUSE_ID, '仓库 ID 应由 ctx.user.store_id 注入');
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(result.data, 'check_date'),
|
||
false,
|
||
'方法层 create 返回不应含 check_date 字段'
|
||
);
|
||
assert.equal(
|
||
Object.prototype.hasOwnProperty.call(row, 'check_date'),
|
||
false,
|
||
'主表行不应含 check_date 字段'
|
||
);
|
||
assert.equal(row.start_time, null, '创建时 start_time 应为空');
|
||
assert.equal(row.end_time, null, '创建时 end_time 应为空');
|
||
});
|
||
|
||
it('list:where.status 数组筛选与统一 success 包装', async () => {
|
||
mockCurrentUser();
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 10 },
|
||
where: { status: [ 'created', 'submitted' ] },
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.ok(Array.isArray(result.data.rows));
|
||
assert.ok(Number(result.data.total) >= result.data.rows.length, 'total 应不小于当前页行数');
|
||
for (const row of result.data.rows) {
|
||
assert.ok([ 'created', 'submitted' ].includes(row.status));
|
||
}
|
||
});
|
||
|
||
it('list:where.type 标准结构(operator/eq/value)只返回 location 任务', async () => {
|
||
mockCurrentUser();
|
||
|
||
const locationCheck = await createCheck({ type: 'location', title: uniqueTitle('方法层type标准结构') });
|
||
const goodsCheck = await createCheck({ title: uniqueTitle('方法层type标准结构') });
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 200 },
|
||
where: { type: { operator: 'eq', value: 'location' } },
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
const ids = result.data.rows.map(row => row.id);
|
||
assert.ok(ids.includes(locationCheck.id), '标准结构 eq=location 应命中 location 任务');
|
||
assert.ok(!ids.includes(goodsCheck.id), '标准结构 eq=location 不应命中 goods 任务');
|
||
for (const row of result.data.rows) {
|
||
assert.equal(row.type, 'location', '标准结构筛选结果只能包含 location 任务');
|
||
}
|
||
});
|
||
|
||
it('list:where.type 数组 in 与 where.mode 组合筛选', async () => {
|
||
mockCurrentUser();
|
||
|
||
const goodsOpen = await createCheck({ type: 'goods', mode: 'open', title: uniqueTitle('方法层in-mode组合') });
|
||
const locationBlind = await createCheck({ type: 'location', title: uniqueTitle('方法层in-mode组合') });
|
||
|
||
const typeInResult = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 200 },
|
||
where: { type: [ 'location', 'goods' ] },
|
||
});
|
||
assert.equal(typeInResult.flag, 'success');
|
||
const typeInIds = typeInResult.data.rows.map(row => row.id);
|
||
assert.ok(typeInIds.includes(goodsOpen.id), 'goods 任务应命中 type in 数组');
|
||
assert.ok(typeInIds.includes(locationBlind.id), 'location 任务应命中 type in 数组');
|
||
for (const row of typeInResult.data.rows) {
|
||
assert.ok([ 'location', 'goods' ].includes(row.type), `非法类型出现在 in 筛选结果: ${row.type}`);
|
||
}
|
||
|
||
const modeResult = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 200 },
|
||
where: { mode: 'blind' },
|
||
});
|
||
assert.equal(modeResult.flag, 'success');
|
||
const modeIds = modeResult.data.rows.map(row => row.id);
|
||
assert.ok(modeIds.includes(locationBlind.id), '盲盘任务应命中 mode=blind');
|
||
assert.ok(!modeIds.includes(goodsOpen.id), '明盘任务不应命中 mode=blind');
|
||
});
|
||
|
||
it('list:where.store_id 货主筛选与 where.created_at between(标准结构)', async () => {
|
||
mockCurrentUser();
|
||
|
||
const storeCheck = await createCheck({ type: 'store', storeId: TEST_STORE_ID, title: uniqueTitle('方法层store_id') });
|
||
const storeResult = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 200 },
|
||
where: { store_id: TEST_STORE_ID },
|
||
});
|
||
assert.equal(storeResult.flag, 'success');
|
||
const storeIds = storeResult.data.rows.map(row => row.id);
|
||
assert.ok(storeIds.includes(storeCheck.id), '固定测试货主的任务应命中 where.store_id');
|
||
for (const row of storeResult.data.rows) {
|
||
assert.equal(Number(row.store_id), TEST_STORE_ID, 'where.store_id 筛选结果只能包含固定测试货主');
|
||
}
|
||
|
||
const inRangeCheck = await createCheck({ title: uniqueTitle('方法层created_at区间') });
|
||
const outRangeCheck = await createCheck({ title: uniqueTitle('方法层created_at区间') });
|
||
await setCheckCreatedAt(inRangeCheck.id, new Date('2019-06-15T00:00:00Z'));
|
||
const betweenResult = await ctx.service.systemMethods.stock.check.list({
|
||
pagination: { page: 1, pageSize: 200 },
|
||
where: {
|
||
created_at: {
|
||
operator: 'between',
|
||
value: { from: '2019-01-01', to: '2019-12-31' },
|
||
},
|
||
},
|
||
});
|
||
assert.equal(betweenResult.flag, 'success');
|
||
const betweenIds = betweenResult.data.rows.map(row => row.id);
|
||
assert.ok(betweenIds.includes(inRangeCheck.id), '标准结构 between 应命中 2019 年创建的任务');
|
||
assert.ok(!betweenIds.includes(outRangeCheck.id), '标准结构 between 不应命中 2019 年外创建的任务');
|
||
});
|
||
|
||
it('addDetail:业务错误码 400 经方法层包装为 failure', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.addDetail({
|
||
id: check.id,
|
||
stock_ids: [ stocks[0].id ],
|
||
});
|
||
|
||
assert.equal(result.flag, 'failure');
|
||
assert.equal(result.code, 400, 'submitted 状态添加明细应包装为 400');
|
||
assert.ok(result.message, '应返回错误文案');
|
||
});
|
||
|
||
it('addDetail:location_ids(snake)与 locationIds(驼峰)均可用并成功包装', async () => {
|
||
mockCurrentUser();
|
||
|
||
const snakeCheck = await createCheck({ type: 'location' });
|
||
const snakeResult = await ctx.service.systemMethods.stock.check.addDetail({
|
||
id: snakeCheck.id,
|
||
location_ids: [ TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(snakeResult.flag, 'success');
|
||
assert.equal(snakeResult.code, 1);
|
||
assert.equal(snakeResult.data.added, 1);
|
||
assert.equal(snakeResult.data.skipped, 0);
|
||
assert.deepEqual(snakeResult.data.invalid_location_ids, []);
|
||
assert.equal(snakeResult.data.total_items, 1);
|
||
|
||
const camelCheck = await createCheck({ type: 'location' });
|
||
const camelResult = await ctx.service.systemMethods.stock.check.addDetail({
|
||
id: camelCheck.id,
|
||
locationIds: [ TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(camelResult.flag, 'success');
|
||
assert.equal(camelResult.code, 1);
|
||
assert.equal(camelResult.data.added, 1);
|
||
assert.deepEqual(camelResult.data.invalid_location_ids, []);
|
||
|
||
for (const checkId of [ snakeCheck.id, camelCheck.id ]) {
|
||
const row = await ctx.model.StockCheckDetail.findOne({
|
||
where: { check_id: checkId },
|
||
raw: true,
|
||
});
|
||
assert.equal(Number(row.location_id), TEST_LOCATION_ID, '方法层库位行应落库 location_id');
|
||
assert.equal(row.location_code, TEST_LOCATION_CODE, '方法层库位行应落库 location_code');
|
||
}
|
||
});
|
||
|
||
it('addLocationDetail:方法层成功包装(snake/驼峰均可用),商品型任务转调报 400 包装为 failure', async () => {
|
||
mockCurrentUser();
|
||
|
||
const snakeCheck = await createCheck({ type: 'location' });
|
||
const snakeResult = await ctx.service.systemMethods.stock.check.addLocationDetail({
|
||
id: snakeCheck.id,
|
||
location_ids: [ TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(snakeResult.flag, 'success');
|
||
assert.equal(snakeResult.code, 1);
|
||
assert.equal(snakeResult.data.added, 1);
|
||
assert.equal(snakeResult.data.skipped, 0);
|
||
assert.deepEqual(snakeResult.data.invalid_location_ids, []);
|
||
assert.equal(snakeResult.data.total_items, 1);
|
||
|
||
const camelCheck = await createCheck({ type: 'location' });
|
||
const camelResult = await ctx.service.systemMethods.stock.check.addLocationDetail({
|
||
id: camelCheck.id,
|
||
locationIds: [ TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(camelResult.flag, 'success');
|
||
assert.equal(camelResult.code, 1);
|
||
assert.equal(camelResult.data.added, 1);
|
||
assert.deepEqual(camelResult.data.invalid_location_ids, []);
|
||
|
||
// 商品型任务转调 addDetail 报 400,经方法层包装为 failure
|
||
const goodsCheck = await createCheck();
|
||
const failure = await ctx.service.systemMethods.stock.check.addLocationDetail({
|
||
id: goodsCheck.id,
|
||
location_ids: [ TEST_LOCATION_ID ],
|
||
});
|
||
assert.equal(failure.flag, 'failure');
|
||
assert.equal(failure.code, 400);
|
||
assert.match(failure.message, /按商品盘点,不能添加库位明细/);
|
||
});
|
||
|
||
it('detail:success 包装只返回任务本身信息({ check }),不含明细 rows/total', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.detail({
|
||
id: check.id,
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.deepEqual(Object.keys(result.data).sort(), [ 'check' ], '方法层 detail 只返回 check');
|
||
assert.equal(result.data.rows, undefined, '方法层 detail 不应返回明细 rows');
|
||
assert.equal(result.data.total, undefined, '方法层 detail 不应返回明细 total');
|
||
assert.equal(Number(result.data.check.id), Number(check.id));
|
||
assert.equal(result.data.check.check_no, check.check_no);
|
||
assert.equal(result.data.check.total_items, 1, 'check.total_items 应为明细行数');
|
||
});
|
||
|
||
it('detail:任务ID 非法 / 任务不存在经方法层包装为 failure 400', async () => {
|
||
mockCurrentUser();
|
||
|
||
const invalid = await ctx.service.systemMethods.stock.check.detail({ id: 0 });
|
||
assert.equal(invalid.flag, 'failure');
|
||
assert.equal(invalid.code, 400);
|
||
assert.match(invalid.message, /盘点任务ID不能为空/);
|
||
|
||
const missing = await ctx.service.systemMethods.stock.check.detail({ id: await findFreeCheckId() });
|
||
assert.equal(missing.flag, 'failure');
|
||
assert.equal(missing.code, 400);
|
||
assert.match(missing.message, /盘点任务不存在/);
|
||
});
|
||
|
||
it('result:仓库上下文注入、success 包装返回盘点结果聚合', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
const snapshot = Number(details.rows[0].system_quantity);
|
||
await reportCheck(check.id, detailId, snapshot + 3, TEST_LOCATION_CODE);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.result({
|
||
id: check.id,
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.total, 1);
|
||
assert.equal(result.data.rows.length, 1);
|
||
const row = result.data.rows[0];
|
||
assert.equal(Number(row.check_id), check.id, '范围行应关联盘点任务');
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, '仓库应由 ctx.user.store_id 注入');
|
||
assert.equal(row.checked_quantity, snapshot + 3, '已盘数量=各库位记录合计');
|
||
assert.equal(row.diff_quantity, 3);
|
||
assert.equal(row.is_diff, 1);
|
||
assert.equal(row.status, 'checked');
|
||
assert.equal(row.records.length, 1);
|
||
assert.deepEqual(row.location_codes, [ TEST_LOCATION_CODE ]);
|
||
const checkedLocation = row.locations.find(item => item.location_code === TEST_LOCATION_CODE);
|
||
assert.ok(checkedLocation, '应含已盘库位');
|
||
assert.equal(Number(checkedLocation.location_id), TEST_LOCATION_ID, '命中库位应回填 location_id');
|
||
assert.equal(Number(checkedLocation.quantity), snapshot + 3, '已盘库位实盘应为上报值');
|
||
});
|
||
|
||
it('result:任务不存在包装为 failure 400', async () => {
|
||
mockCurrentUser();
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.result({
|
||
id: 999999999,
|
||
});
|
||
|
||
assert.equal(result.flag, 'failure');
|
||
assert.equal(result.code, 400);
|
||
assert.ok(result.message, '应返回错误文案');
|
||
});
|
||
|
||
it('report:注入仓库/盘点人上下文,success 包装返回作业记录', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await ctx.service.systemMethods.stock.check.report({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
quantity: 6,
|
||
location: TEST_LOCATION_CODE,
|
||
space_id: TEST_LOCATION_ID,
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(Number(result.data.record.warehouse_id), TEST_WAREHOUSE_ID, '仓库 ID 应由 ctx.user.store_id 注入');
|
||
assert.equal(Number(result.data.record.checker_id), TEST_CREATOR_ID, '盘点人 ID 应由上下文注入');
|
||
assert.equal(result.data.record.checker_name, TEST_CREATOR_NAME);
|
||
assert.equal(Number(result.data.record.quantity), 6);
|
||
assert.equal(Number(result.data.record.location_id), TEST_LOCATION_ID, '库位以 space_id 为准');
|
||
assert.equal(result.data.detail_status, 'all_checked');
|
||
});
|
||
|
||
it('report:方法层未携带 space_id 包装为 failure 400', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await ctx.service.systemMethods.stock.check.report({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
quantity: 6,
|
||
location: TEST_LOCATION_CODE,
|
||
});
|
||
assert.equal(result.flag, 'failure');
|
||
assert.equal(result.code, 400);
|
||
assert.ok(result.message.includes('缺少库位ID'), '缺少库位ID应返回明确文案');
|
||
});
|
||
|
||
it('report:方法层透传 space_id/locationId 别名,按库位ID落库', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const snake = await ctx.service.systemMethods.stock.check.report({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
quantity: 2,
|
||
location: TEST_LOCATION_CODE,
|
||
space_id: TEST_LOCATION_ID,
|
||
});
|
||
assert.equal(snake.flag, 'success');
|
||
assert.equal(Number(snake.data.record.location_id), TEST_LOCATION_ID, 'space_id 别名应透传为 locationId');
|
||
|
||
const camel = await ctx.service.systemMethods.stock.check.report({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
quantity: 3,
|
||
location: TEST_LOCATION_CODE,
|
||
locationId: TEST_LOCATION_ID,
|
||
});
|
||
assert.equal(camel.flag, 'success');
|
||
assert.equal(Number(camel.data.record.location_id), TEST_LOCATION_ID, 'locationId 驼峰应透传');
|
||
|
||
const tooLarge = await ctx.service.systemMethods.stock.check.report({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
quantity: 6955416422066,
|
||
location: TEST_LOCATION_CODE,
|
||
});
|
||
assert.equal(tooLarge.flag, 'failure');
|
||
assert.equal(tooLarge.code, 400, '超限数量应返回业务 400 而非 500');
|
||
});
|
||
|
||
it('markEmpty:方法层 success 包装(库位任务)+ 非库位任务 failure 400', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck({ type: 'location' });
|
||
await addLocationDetail(check.id, [ TEST_EMPTY_LOCATION_CODE ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const result = await ctx.service.systemMethods.stock.check.markEmpty({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
});
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.record.is_empty, true);
|
||
assert.equal(result.data.detail_status, 'all_checked');
|
||
|
||
const goodsCheck = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(goodsCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(goodsCheck.id);
|
||
await auditCheck(goodsCheck.id, 'approve');
|
||
const goodsDetails = await detailCheck(goodsCheck.id);
|
||
const failure = await ctx.service.systemMethods.stock.check.markEmpty({
|
||
id: goodsCheck.id,
|
||
detail_id: goodsDetails.rows[0].id,
|
||
});
|
||
assert.equal(failure.flag, 'failure');
|
||
assert.equal(failure.code, 400);
|
||
assert.match(failure.message, /仅库位盘点任务支持空库位标记/);
|
||
});
|
||
|
||
it('recordList:方法层 success 包装,按任务查询记录并回填商品信息', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(2);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE);
|
||
await reportCheck(check.id, details.rows[1].id, 4);
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.recordList({
|
||
id: check.id,
|
||
pagination: { page: 1, pageSize: 10 },
|
||
});
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.total, 2);
|
||
assert.equal(result.data.rows.length, 2);
|
||
for (const row of result.data.rows) {
|
||
assert.equal(Number(row.check_id), check.id, '记录应限定在指定任务');
|
||
assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, '仓库应由 ctx.user.store_id 注入');
|
||
assert.ok(row.item_code, '记录应回填商品编码');
|
||
}
|
||
});
|
||
|
||
it('recordDelete:方法层批量兼容 record_ids/recordIds/record_id 三种写法,未命中计入 skipped、删除后汇总回退', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(1);
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const details = await detailCheck(check.id);
|
||
const detailId = details.rows[0].id;
|
||
const first = await reportCheck(check.id, detailId, 3, TEST_LOCATION_CODE);
|
||
const second = await reportCheck(check.id, detailId, 4, TEST_LOCATION_CODE_2);
|
||
|
||
// record_ids 下划线数组写法(批量入口),混入不存在的 ID 计入 skipped
|
||
const snakeResult = await ctx.service.systemMethods.stock.check.recordDelete({
|
||
id: check.id,
|
||
record_ids: [ first.record.id, 999999999 ],
|
||
});
|
||
assert.equal(snakeResult.flag, 'success', `record_ids 批量删除应成功: ${snakeResult.message}`);
|
||
assert.equal(snakeResult.code, 1);
|
||
assert.equal(snakeResult.data.deleted_count, 1);
|
||
assert.deepEqual(snakeResult.data.deleted_ids.map(Number), [ Number(first.record.id) ]);
|
||
assert.deepEqual(snakeResult.data.skipped_ids, [ 999999999 ], '未命中记录应计入 skipped_ids');
|
||
assert.equal(snakeResult.data.checked_items, 1, '删除一条后仍有一条记录');
|
||
|
||
// recordId 驼峰单值写法(单值自动转数组)
|
||
const camelResult = await ctx.service.systemMethods.stock.check.recordDelete({
|
||
id: check.id,
|
||
recordId: second.record.id,
|
||
});
|
||
assert.equal(camelResult.flag, 'success', `recordId 单值删除应成功: ${camelResult.message}`);
|
||
assert.equal(camelResult.data.deleted_count, 1);
|
||
assert.deepEqual(camelResult.data.deleted_ids.map(Number), [ Number(second.record.id) ]);
|
||
assert.equal(camelResult.data.checked_items, 0, '全部删除后已盘回退为 0');
|
||
assert.equal(camelResult.data.detail_status, 'none_checked');
|
||
});
|
||
|
||
it('detailDelete:detail_ids/detailIds/detail_id 三种写法兼容、success 包装、未命中计入 skipped、状态限制包装为 failure', async () => {
|
||
mockCurrentUser();
|
||
|
||
const check = await createCheck();
|
||
const stocks = await fetchStockRows(3);
|
||
await addDetail(check.id, stocks.map(stock => stock.id));
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 3, '前置:任务应有 3 条明细');
|
||
|
||
// detail_ids 下划线数组写法(批量入口)
|
||
const snakeResult = await ctx.service.systemMethods.stock.check.detailDelete({
|
||
id: check.id,
|
||
detail_ids: [ details.rows[0].id ],
|
||
});
|
||
assert.equal(snakeResult.flag, 'success');
|
||
assert.equal(snakeResult.code, 1);
|
||
assert.equal(snakeResult.data.deleted_count, 1);
|
||
assert.deepEqual(snakeResult.data.deleted_ids.map(Number), [ Number(details.rows[0].id) ]);
|
||
assert.deepEqual(snakeResult.data.skipped_ids, []);
|
||
assert.equal(snakeResult.data.total_items, 2);
|
||
|
||
// detailIds 驼峰写法(兼容别名,单值自动转数组)
|
||
const camelResult = await ctx.service.systemMethods.stock.check.detailDelete({
|
||
id: check.id,
|
||
detailIds: details.rows[1].id,
|
||
});
|
||
assert.equal(camelResult.flag, 'success');
|
||
assert.equal(camelResult.code, 1);
|
||
assert.equal(camelResult.data.deleted_count, 1);
|
||
assert.deepEqual(camelResult.data.deleted_ids.map(Number), [ Number(details.rows[1].id) ]);
|
||
assert.deepEqual(camelResult.data.skipped_ids, []);
|
||
assert.equal(camelResult.data.total_items, 1);
|
||
|
||
// detail_id 旧版单值写法(兼容入口,单值自动转数组)
|
||
const legacyResult = await ctx.service.systemMethods.stock.check.detailDelete({
|
||
id: check.id,
|
||
detail_id: details.rows[2].id,
|
||
});
|
||
assert.equal(legacyResult.flag, 'success');
|
||
assert.equal(legacyResult.code, 1);
|
||
assert.equal(legacyResult.data.deleted_count, 1);
|
||
assert.deepEqual(legacyResult.data.deleted_ids.map(Number), [ Number(details.rows[2].id) ]);
|
||
assert.deepEqual(legacyResult.data.skipped_ids, []);
|
||
assert.equal(legacyResult.data.total_items, 0);
|
||
|
||
// 已删除明细再次删除:未命中 → success + skipped_ids(不再报 400)
|
||
const repeatedResult = await ctx.service.systemMethods.stock.check.detailDelete({
|
||
id: check.id,
|
||
detail_id: details.rows[0].id,
|
||
});
|
||
assert.equal(repeatedResult.flag, 'success');
|
||
assert.equal(repeatedResult.code, 1);
|
||
assert.equal(repeatedResult.data.deleted_count, 0);
|
||
assert.deepEqual(repeatedResult.data.deleted_ids, []);
|
||
assert.deepEqual(repeatedResult.data.skipped_ids.map(Number), [ Number(details.rows[0].id) ]);
|
||
|
||
// 状态不允许 → failure 400 包装
|
||
const submittedCheck = await createCheck();
|
||
const submittedStocks = await fetchStockRows(1);
|
||
await addDetail(submittedCheck.id, [ submittedStocks[0].id ]);
|
||
await submitCheck(submittedCheck.id);
|
||
const submittedDetails = await detailCheck(submittedCheck.id);
|
||
const statusFailure = await ctx.service.systemMethods.stock.check.detailDelete({
|
||
id: submittedCheck.id,
|
||
detail_ids: [ submittedDetails.rows[0].id ],
|
||
});
|
||
assert.equal(statusFailure.flag, 'failure');
|
||
assert.equal(statusFailure.code, 400);
|
||
assert.match(statusFailure.message, /不允许删除明细/);
|
||
});
|
||
});
|
||
|
||
// ------------------- batchDelete:批量删除盘点任务(业务层) -------------------
|
||
|
||
describe('batchDelete 批量删除盘点任务(业务层)', () => {
|
||
it('作废任务删除:主表/明细/作业记录全部物理删除(事务级联)', async () => {
|
||
const { check, stock } = await createCancelledCheck();
|
||
const details = await detailCheck(check.id);
|
||
assert.equal(details.total, 1, '前置:作废任务应有 1 条明细');
|
||
|
||
// report 仅 approved/checking 状态开放,作废任务无法自然产生作业记录;
|
||
// 直写两条记录用于验证 batchDelete 级联删除 record 表。
|
||
await ctx.model.StockCheckRecord.bulkCreate([
|
||
{
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: details.rows[0].id,
|
||
stock_id: stock.id,
|
||
location_code: TEST_LOCATION_CODE,
|
||
quantity: 3,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
},
|
||
{
|
||
check_id: check.id,
|
||
warehouse_id: TEST_WAREHOUSE_ID,
|
||
detail_id: details.rows[0].id,
|
||
stock_id: stock.id,
|
||
location_code: '',
|
||
quantity: 5,
|
||
checker_id: TEST_CREATOR_ID,
|
||
checker_name: TEST_CREATOR_NAME,
|
||
checked_at: new Date(),
|
||
},
|
||
]);
|
||
assert.equal(
|
||
await ctx.model.StockCheckRecord.count({ where: { check_id: check.id } }),
|
||
2,
|
||
'前置:应有 2 条作业记录'
|
||
);
|
||
|
||
const result = await batchDeleteCheck([ check.id ]);
|
||
|
||
assert.equal(result.total, 1);
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.equal(result.skipped_count, 0);
|
||
assert.deepEqual(result.deleted_ids, [ check.id ]);
|
||
assert.deepEqual(result.skipped_ids, []);
|
||
|
||
// 级联物理删除:主表 / 明细 / 作业记录全部清空
|
||
assert.equal(await findCheckRow(check.id), null, '主表行应物理删除');
|
||
assert.equal(await ctx.model.StockCheckDetail.count({ where: { check_id: check.id } }), 0, '明细应物理删除');
|
||
assert.equal(await ctx.model.StockCheckRecord.count({ where: { check_id: check.id } }), 0, '作业记录应物理删除');
|
||
});
|
||
|
||
it('非作废状态任务全部跳过:created/submitted/approved/completed 数据保持', async () => {
|
||
const created = await createCheck();
|
||
|
||
const submitted = await createCheck();
|
||
const submittedStocks = await fetchStockRows(1);
|
||
await addDetail(submitted.id, [ submittedStocks[0].id ]);
|
||
await submitCheck(submitted.id);
|
||
|
||
const approved = await createCheck();
|
||
const approvedStocks = await fetchStockRows(1);
|
||
await addDetail(approved.id, [ approvedStocks[0].id ]);
|
||
await submitCheck(approved.id);
|
||
await auditCheck(approved.id, 'approve');
|
||
|
||
const completed = await createCheck();
|
||
const completedStocks = await fetchStockRows(1);
|
||
await addDetail(completed.id, [ completedStocks[0].id ]);
|
||
await submitCheck(completed.id);
|
||
await auditCheck(completed.id, 'approve');
|
||
const completedDetails = await detailCheck(completed.id);
|
||
await reportCheck(completed.id, completedDetails.rows[0].id, 1);
|
||
await finishCheck(completed.id);
|
||
|
||
const ids = [ created.id, submitted.id, approved.id, completed.id ];
|
||
const result = await batchDeleteCheck(ids);
|
||
|
||
assert.equal(result.total, 4);
|
||
assert.equal(result.deleted_count, 0);
|
||
assert.equal(result.skipped_count, 4);
|
||
assert.deepEqual(result.deleted_ids, []);
|
||
assert.deepEqual(result.skipped_ids, ids, 'skipped_ids 应保持入参顺序');
|
||
|
||
// 数据保持:主表仍在且状态不变,明细仍在
|
||
assert.equal((await findCheckRow(created.id)).status, 'created');
|
||
assert.equal((await findCheckRow(submitted.id)).status, 'submitted');
|
||
assert.equal((await findCheckRow(approved.id)).status, 'approved');
|
||
assert.equal((await findCheckRow(completed.id)).status, 'completed');
|
||
for (const checkId of [ submitted.id, approved.id, completed.id ]) {
|
||
assert.equal(
|
||
await ctx.model.StockCheckDetail.count({ where: { check_id: checkId } }),
|
||
1,
|
||
`任务 ${checkId} 明细应保持`
|
||
);
|
||
}
|
||
});
|
||
|
||
it('混合批量:仅删除作废任务,其余跳过,计数与顺序正确', async () => {
|
||
const cancelledA = await createCancelledCheck();
|
||
const kept = await createCheck();
|
||
const cancelledB = await createCancelledCheck();
|
||
const missingId = await findFreeCheckId();
|
||
|
||
const ids = [ cancelledA.check.id, kept.id, missingId, cancelledB.check.id ];
|
||
const result = await batchDeleteCheck(ids);
|
||
|
||
assert.equal(result.total, 4);
|
||
assert.equal(result.deleted_count, 2);
|
||
assert.equal(result.skipped_count, 2);
|
||
assert.deepEqual(result.deleted_ids, [ cancelledA.check.id, cancelledB.check.id ], 'deleted_ids 保持入参顺序');
|
||
assert.deepEqual(result.skipped_ids, [ kept.id, missingId ], 'skipped_ids 保持入参顺序');
|
||
|
||
assert.equal(await findCheckRow(cancelledA.check.id), null, '作废任务 A 应删除');
|
||
assert.equal(await findCheckRow(cancelledB.check.id), null, '作废任务 B 应删除');
|
||
assert.equal((await findCheckRow(kept.id)).status, 'created', '非作废任务应保持');
|
||
});
|
||
|
||
it('不存在的 ID 计入 skipped_ids', async () => {
|
||
const missingId = await findFreeCheckId();
|
||
|
||
const result = await batchDeleteCheck([ missingId ]);
|
||
|
||
assert.equal(result.total, 1);
|
||
assert.equal(result.deleted_count, 0);
|
||
assert.equal(result.skipped_count, 1);
|
||
assert.deepEqual(result.skipped_ids, [ missingId ]);
|
||
assert.deepEqual(result.deleted_ids, []);
|
||
});
|
||
|
||
it('ids 空/非法 → 400', async () => {
|
||
await assert.rejects(async () => {
|
||
await batchDeleteCheck([]);
|
||
}, error => error.code === 400 && /ids/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await batchDeleteRaw({ warehouseId: TEST_WAREHOUSE_ID, ids: undefined });
|
||
}, error => error.code === 400 && /ids/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await batchDeleteCheck([ 0, -1, 'abc' ]);
|
||
}, error => error.code === 400 && /ids/.test(error.message));
|
||
|
||
await assert.rejects(async () => {
|
||
await batchDeleteRaw({ warehouseId: 0, ids: [ 1 ] });
|
||
}, error => error.code === 400 && /仓库/.test(error.message));
|
||
});
|
||
|
||
it('超过 200 个上限 → 400;200 个边界正常返回', async () => {
|
||
const baseId = await findFreeCheckId();
|
||
const overLimitIds = Array.from({ length: 201 }, (_, index) => baseId + index);
|
||
|
||
await assert.rejects(async () => {
|
||
await batchDeleteCheck(overLimitIds);
|
||
}, error => error.code === 400 && /200/.test(error.message));
|
||
|
||
const boundaryIds = Array.from({ length: 200 }, (_, index) => baseId + index + 1000);
|
||
const result = await batchDeleteCheck(boundaryIds);
|
||
assert.equal(result.total, 200);
|
||
assert.equal(result.deleted_count, 0);
|
||
assert.equal(result.skipped_count, 200);
|
||
});
|
||
|
||
it('单值 ids 兼容(传数字而非数组)', async () => {
|
||
const { check } = await createCancelledCheck();
|
||
|
||
const result = await batchDeleteCheck(check.id);
|
||
|
||
assert.equal(result.total, 1);
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.deepEqual(result.deleted_ids, [ check.id ]);
|
||
assert.equal(await findCheckRow(check.id), null, '单值 ids 也应正常删除');
|
||
});
|
||
|
||
it('重复 id 去重后只删一次', async () => {
|
||
const { check } = await createCancelledCheck();
|
||
|
||
const result = await batchDeleteCheck([ check.id, check.id, check.id ]);
|
||
|
||
assert.equal(result.total, 1);
|
||
assert.equal(result.deleted_count, 1);
|
||
assert.equal(result.skipped_count, 0);
|
||
assert.deepEqual(result.deleted_ids, [ check.id ]);
|
||
});
|
||
});
|
||
|
||
// ------------------- systemMethods.stock.check.batchDelete:方法包装层 -------------------
|
||
|
||
describe('systemMethods.stock.check.batchDelete 方法包装层', () => {
|
||
/** 设置当前上下文的用户信息(模拟登录用户,仓库固定 100000)。 */
|
||
function mockCurrentUser() {
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
}
|
||
|
||
it('success 包装:作废任务删除成功,仓库由 ctx.user.store_id 注入', async () => {
|
||
mockCurrentUser();
|
||
|
||
const { check } = await createCancelledCheck();
|
||
const result = await ctx.service.systemMethods.stock.check.batchDelete({ ids: [ check.id ] });
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.total, 1);
|
||
assert.equal(result.data.deleted_count, 1);
|
||
assert.equal(result.data.skipped_count, 0);
|
||
assert.deepEqual(result.data.deleted_ids, [ check.id ]);
|
||
assert.equal(await findCheckRow(check.id), null, '主表行应物理删除(仓库注入正确才可删除)');
|
||
});
|
||
|
||
it('仓库隔离:其他仓库的作废任务计入 skipped_ids 不删除', async () => {
|
||
mockCurrentUser();
|
||
|
||
// 其他仓库(100001)作废任务:方法层当前上下文仓库为 100000,应跳过不删
|
||
const other = await createCheck({ warehouseId: OTHER_TEST_WAREHOUSE_ID });
|
||
await ctx.service.systems.stockCheck.cancel({
|
||
warehouseId: OTHER_TEST_WAREHOUSE_ID,
|
||
id: other.id,
|
||
});
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.batchDelete({ ids: [ other.id ] });
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.deleted_count, 0);
|
||
assert.equal(result.data.skipped_count, 1);
|
||
assert.deepEqual(result.data.skipped_ids, [ other.id ]);
|
||
assert.equal((await findCheckRow(other.id)).status, 'cancelled', '其他仓库任务应保持');
|
||
});
|
||
|
||
it('ids 空 → failure 400 包装', async () => {
|
||
mockCurrentUser();
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.batchDelete({ ids: [] });
|
||
|
||
assert.equal(result.flag, 'failure');
|
||
assert.equal(result.code, 400);
|
||
assert.ok(result.message, '应返回错误文案');
|
||
});
|
||
|
||
it('缺少仓库上下文 → failure 400 包装', async () => {
|
||
ctx.user = null;
|
||
|
||
const result = await ctx.service.systemMethods.stock.check.batchDelete({ ids: [ 1 ] });
|
||
|
||
assert.equal(result.flag, 'failure');
|
||
assert.equal(result.code, 400);
|
||
assert.match(result.message, /仓库/);
|
||
});
|
||
|
||
it('单值 ids 兼容(方法层传数字)', async () => {
|
||
mockCurrentUser();
|
||
|
||
const { check } = await createCancelledCheck();
|
||
const result = await ctx.service.systemMethods.stock.check.batchDelete({ ids: [ check.id ] });
|
||
|
||
assert.equal(result.flag, 'success');
|
||
assert.equal(result.code, 1);
|
||
assert.equal(result.data.deleted_count, 1);
|
||
assert.deepEqual(result.data.deleted_ids, [ check.id ]);
|
||
});
|
||
});
|
||
|
||
// ------------------- staticLockList:静态盘点锁定商品(公共查询 + 缓存) -------------------
|
||
|
||
describe('staticLockList 静态盘点锁定商品(公共查询 + 缓存 + 审核刷新快照)', () => {
|
||
/** 设置当前上下文用户(方法层需仓库上下文)。 */
|
||
function mockCurrentUser() {
|
||
ctx.user = {
|
||
id: TEST_CREATOR_ID,
|
||
store_id: TEST_WAREHOUSE_ID,
|
||
employees_name: TEST_CREATOR_NAME,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 读取锁定缓存原始值(用于断言缓存命中/失效)。
|
||
*
|
||
* @return {Promise<Object|null>} 缓存载荷。
|
||
*/
|
||
async function readLockCache() {
|
||
return ctx.app.getCacheAsync(`stock_check:static_lock:${TEST_WAREHOUSE_ID}`);
|
||
}
|
||
|
||
/**
|
||
* 清理锁定缓存,保证用例互不影响。
|
||
*
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async function clearLockCache() {
|
||
await ctx.app.delCacheAsync(`stock_check:static_lock:${TEST_WAREHOUSE_ID}`);
|
||
}
|
||
|
||
/**
|
||
* 业务层:查询静态锁定列表。
|
||
*
|
||
* @return {Promise<Object>} { warehouse_id, stock_ids, rows, total, cached, updated_at }。
|
||
*/
|
||
async function staticLockList() {
|
||
return ctx.service.systems.stockCheck.staticLockList({ warehouseId: TEST_WAREHOUSE_ID });
|
||
}
|
||
|
||
it('仅统计 is_static=1 且 approved/checking 任务的商品;submitted 与普通任务不计入', async () => {
|
||
await clearLockCache();
|
||
const stocks = await fetchStockRows(2);
|
||
|
||
// 静态任务 A:审核通过(锁定中)
|
||
const staticCheck = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-审核通过'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(staticCheck.id, [ stocks[0].id ]);
|
||
await submitCheck(staticCheck.id);
|
||
await auditCheck(staticCheck.id, 'approve');
|
||
|
||
// 静态任务 B:待审核(未锁定)
|
||
const pendingCheck = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-待审核'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(pendingCheck.id, [ stocks[1].id ]);
|
||
await submitCheck(pendingCheck.id);
|
||
|
||
const lockList = await staticLockList();
|
||
const lockedIds = lockList.stock_ids.map(Number);
|
||
assert.ok(lockedIds.includes(Number(stocks[0].id)), '审核通过的静态任务商品应锁定');
|
||
assert.equal(
|
||
lockedIds.includes(Number(stocks[1].id)),
|
||
false,
|
||
'待审核的静态任务商品不应锁定'
|
||
);
|
||
for (const stockId of lockedIds) {
|
||
assert.ok(Number.isInteger(stockId) && stockId > 0, '锁定集合应为正整数商品ID');
|
||
}
|
||
const targetRow = lockList.rows.find(row => Number(row.stock_id) === Number(stocks[0].id));
|
||
assert.ok(targetRow, 'rows 应含锁定商品');
|
||
assert.ok(targetRow.check_ids.includes(Number(staticCheck.id)), 'rows 应含来源任务ID');
|
||
assert.ok(targetRow.check_nos.length >= 1, 'rows 应含来源单号');
|
||
assert.ok(Array.isArray(targetRow.location_codes) && targetRow.location_codes.length >= 1, 'rows 应含盘点库位编码');
|
||
|
||
// 普通(非静态)任务即使审核通过也不锁定
|
||
const normalCheck = await createCheck({ title: uniqueTitle('静态锁定-普通任务') });
|
||
const normalStock = (await fetchStockRows(3)).find(stock => Number(stock.id) !== Number(stocks[0].id)
|
||
&& Number(stock.id) !== Number(stocks[1].id));
|
||
if (normalStock) {
|
||
await addDetail(normalCheck.id, [ normalStock.id ]);
|
||
await submitCheck(normalCheck.id);
|
||
await auditCheck(normalCheck.id, 'approve');
|
||
const afterNormal = await staticLockList();
|
||
assert.equal(
|
||
afterNormal.stock_ids.map(Number).includes(Number(normalStock.id)),
|
||
false,
|
||
'非静态任务不应进入锁定集合'
|
||
);
|
||
}
|
||
});
|
||
|
||
it('缓存命中与失效:二次查询命中缓存,审核/完成/取消后缓存清除', async () => {
|
||
await clearLockCache();
|
||
const stocks = await fetchStockRows(1);
|
||
const check = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-缓存'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
|
||
// 提交审核不锁定:首次查询未命中缓存,且不包含本任务
|
||
const beforeApprove = await staticLockList();
|
||
assert.equal(beforeApprove.cached, false, '首次查询应回源');
|
||
assert.equal(
|
||
beforeApprove.rows.some(row => row.check_ids.map(Number).includes(Number(check.id))),
|
||
false,
|
||
'待审核阶段不锁定(rows 不应含该任务)'
|
||
);
|
||
|
||
// 审核通过后缓存被立即重建(不是删除等下次回源)→ 含本任务;查询命中缓存
|
||
await auditCheck(check.id, 'approve');
|
||
const cacheAfterAudit = await readLockCache();
|
||
assert.ok(cacheAfterAudit, '审核通过应重建锁定缓存(不留空窗)');
|
||
assert.ok(
|
||
cacheAfterAudit.rows.some(row => row.check_ids.map(Number).includes(Number(check.id))),
|
||
'重建后的缓存应包含刚审核通过的任务'
|
||
);
|
||
const afterApprove = await staticLockList();
|
||
assert.equal(afterApprove.cached, true, '审核后查询应直接命中已重建的缓存');
|
||
const lockedRow = afterApprove.rows.find(row => Number(row.stock_id) === Number(stocks[0].id));
|
||
assert.ok(lockedRow, '审核通过后该商品应出现在锁定集合');
|
||
assert.ok(lockedRow.check_ids.map(Number).includes(Number(check.id)), '锁定行应含该任务ID');
|
||
assert.ok(afterApprove.updated_at, '缓存载荷应含 updated_at');
|
||
|
||
// 完成盘点 → 缓存重建且本任务已被移除
|
||
await finishCheck(check.id);
|
||
const cacheAfterFinish = await readLockCache();
|
||
assert.ok(cacheAfterFinish, '完成盘点应重建锁定缓存');
|
||
assert.equal(
|
||
cacheAfterFinish.rows.some(row => row.check_ids.map(Number).includes(Number(check.id))),
|
||
false,
|
||
'重建后的缓存不应再包含已完成任务'
|
||
);
|
||
const afterFinish = await staticLockList();
|
||
assert.equal(afterFinish.cached, true, '完成后查询命中已重建的缓存');
|
||
assert.equal(
|
||
afterFinish.rows.some(row => row.check_ids.map(Number).includes(Number(check.id))),
|
||
false,
|
||
'已完成任务不应出现在锁定集合'
|
||
);
|
||
|
||
// 取消任务 → 同样失效
|
||
const cancelledCheck = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-取消'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await staticLockList();
|
||
await cancelCheck(cancelledCheck.id);
|
||
const cacheAfterCancel = await readLockCache();
|
||
assert.ok(cacheAfterCancel, '取消任务应重建锁定缓存');
|
||
assert.equal(
|
||
cacheAfterCancel.rows.some(row => row.check_ids.map(Number).includes(Number(cancelledCheck.id))),
|
||
false,
|
||
'重建后的缓存不应包含已取消任务'
|
||
);
|
||
});
|
||
|
||
it('isStockStaticLocked:按商品判断是否锁定(读缓存),未锁定返回 false', async () => {
|
||
await clearLockCache();
|
||
const stocks = await fetchStockRows(2);
|
||
const check = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-单商品判断'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const lockedHit = await ctx.service.systems.stockCheck.isStockStaticLocked({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockId: stocks[0].id,
|
||
});
|
||
assert.equal(lockedHit.locked, true, '锁定中的商品应返回 locked=true');
|
||
assert.deepEqual(lockedHit.locked_stock_ids, [ Number(stocks[0].id) ]);
|
||
assert.equal(Number(lockedHit.rows[0].stock_id), Number(stocks[0].id));
|
||
|
||
const lockedMiss = await ctx.service.systems.stockCheck.isStockStaticLocked({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockId: [ stocks[1].id, 999999999 ],
|
||
});
|
||
assert.equal(lockedMiss.locked, false, '未锁定商品应返回 locked=false');
|
||
assert.deepEqual(lockedMiss.locked_stock_ids, []);
|
||
|
||
await assert.rejects(
|
||
async () => ctx.service.systems.stockCheck.isStockStaticLocked({ warehouseId: TEST_WAREHOUSE_ID }),
|
||
/商品ID不能为空/
|
||
);
|
||
await assert.rejects(
|
||
async () => ctx.service.systems.stockCheck.staticLockList({ warehouseId: 0 }),
|
||
/无法获取当前仓库上下文/
|
||
);
|
||
});
|
||
|
||
it('审核通过刷新商品明细账面快照:提交后库存变化,审核时快照刷新为审核时点账面', async () => {
|
||
const stocks = await fetchStockRows(1);
|
||
const targetStock = stocks[0];
|
||
const check = await createCheck({ title: uniqueTitle('审核刷新快照'), type: 'goods' });
|
||
const added = await addDetail(check.id, [ targetStock.id ]);
|
||
assert.ok(added.added >= 1, '前置:应生成商品明细(按库位拆行)');
|
||
|
||
const detailsBefore = await detailCheck(check.id);
|
||
const targetDetail = detailsBefore.rows[0];
|
||
const spaceId = Number(targetDetail.location_id);
|
||
|
||
/**
|
||
* 读取指定商品在指定库位的当前账面(可用数量)。
|
||
*
|
||
* @return {Promise<number>} 账面数量。
|
||
*/
|
||
async function readSpaceBook() {
|
||
const rows = await ctx.model.query(
|
||
`SELECT COALESCE(SUM(available_quantity), 0) AS total
|
||
FROM wms_storage
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{
|
||
replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId },
|
||
type: ctx.model.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
return Number(rows[0] && rows[0].total) || 0;
|
||
}
|
||
|
||
const bookOnSubmit = await readSpaceBook();
|
||
// 提交审核:快照=提交时点账面
|
||
await submitCheck(check.id);
|
||
const afterSubmit = await ctx.model.StockCheckDetail.findByPk(targetDetail.id, { raw: true });
|
||
assert.equal(Number(afterSubmit.system_quantity), bookOnSubmit, '提交时快照应等于提交时点账面');
|
||
|
||
// 模拟提交后、审核前的库存变动(该库位每行可用数量 +5)
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity + 5
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{ replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
const bookAfterChange = await readSpaceBook();
|
||
assert.ok(bookAfterChange > bookOnSubmit, '前置:库存变动后账面应增加');
|
||
|
||
try {
|
||
const auditResult = await auditCheck(check.id, 'approve');
|
||
assert.equal(
|
||
Number(auditResult.snapshot_refreshed) >= 1,
|
||
true,
|
||
'审核通过应刷新快照并返回刷新行数'
|
||
);
|
||
const afterAudit = await ctx.model.StockCheckDetail.findByPk(targetDetail.id, { raw: true });
|
||
assert.equal(
|
||
Number(afterAudit.system_quantity),
|
||
bookAfterChange,
|
||
'审核通过后快照应刷新为审核时点账面(快照随库存变动更新为最新账面)'
|
||
);
|
||
} finally {
|
||
// 回滚本次人为库存变更,避免污染开发库
|
||
await ctx.model.query(
|
||
`UPDATE wms_storage
|
||
SET available_quantity = available_quantity - 5
|
||
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
|
||
{ replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
|
||
);
|
||
}
|
||
});
|
||
|
||
it('完成盘点立即释放锁定:finish 清除缓存并返回 released_stock_ids,之后该商品不再锁定', async () => {
|
||
await clearLockCache();
|
||
// 构造一个只属于本用例的商品(避免被历史静态任务同时锁定,便于验证释放)
|
||
const uniqueSuffix = `${Date.now()}-${Math.floor(Math.random() * 1000)}`;
|
||
const itemCode = `VERIFY-LOCK-${uniqueSuffix}`;
|
||
const [ fabricatedId ] = await ctx.model.query(
|
||
`INSERT INTO wms_stock_warehouse
|
||
(item_code, item_name, store_id, stock_unit, item_type, create_at,
|
||
warehouse_id, is_valid, quantity, is_shelf_life_mgmt, remaining_threshold_days)
|
||
VALUES (:itemCode, '静态锁定释放测试商品', :storeId, '个', 'normal', NOW(),
|
||
:warehouseId, 'Y', 3, 'N', 0)`,
|
||
{ replacements: { itemCode, storeId: TEST_STORE_ID, warehouseId: TEST_WAREHOUSE_ID } }
|
||
);
|
||
const stockId = Number(fabricatedId);
|
||
const [ validLocation ] = await fetchValidLocations(1);
|
||
assert.ok(validLocation, '前置:应存在有效库位');
|
||
await ctx.model.query(
|
||
`INSERT INTO wms_storage
|
||
(warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type,
|
||
quantity, expiry_date, inbound_time, inbound_order_no)
|
||
VALUES (:warehouseId, :storeId, :spaceId, :stockId, :batchNo, 'ZP', 3, NULL, NOW(), :orderNo)`,
|
||
{
|
||
replacements: {
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
storeId: TEST_STORE_ID,
|
||
spaceId: validLocation.id,
|
||
stockId,
|
||
batchNo: `VERIFY-LOCK-BATCH-${uniqueSuffix}`,
|
||
orderNo: `VERIFY-LOCK-IN-${uniqueSuffix}`,
|
||
},
|
||
type: ctx.model.QueryTypes.INSERT,
|
||
}
|
||
);
|
||
|
||
const check = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-完成释放'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(check.id, [ stockId ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
// 审核后锁定
|
||
const lockedBefore = await ctx.service.systems.stockCheck.isStockStaticLocked({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockId,
|
||
});
|
||
assert.equal(lockedBefore.locked, true, '审核通过后该商品应在锁定集合中');
|
||
|
||
// 完成盘点 → 清缓存 + 返回释放商品 + 不再锁定
|
||
const finishResult = await finishCheck(check.id);
|
||
assert.equal(finishResult.status, 'completed');
|
||
assert.deepEqual(finishResult.released_stock_ids, [ stockId ], 'finish 应返回本任务覆盖的商品ID');
|
||
const cacheAfterFinish = await readLockCache();
|
||
assert.ok(cacheAfterFinish, '完成盘点应重建锁定缓存(不留空窗)');
|
||
assert.equal(
|
||
cacheAfterFinish.stock_ids.includes(stockId),
|
||
false,
|
||
'重建后的缓存不应再包含该商品(已释放)'
|
||
);
|
||
|
||
// 完成盘点后该商品解除锁定,且缓存已重建(回源口径)
|
||
const lockedAfter = await ctx.service.systems.stockCheck.isStockStaticLocked({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockId,
|
||
});
|
||
assert.equal(lockedAfter.locked, false, '完成盘点后该商品应解除锁定');
|
||
assert.deepEqual(lockedAfter.locked_stock_ids, []);
|
||
assert.equal(lockedAfter.cached, true, '完成时已重建缓存,判断应命中缓存');
|
||
|
||
// 清理本用例构造的商品数据
|
||
await ctx.model.query('DELETE FROM wms_storage WHERE stock_id = :stockId', { replacements: { stockId } });
|
||
await ctx.model.query('DELETE FROM wms_stock_warehouse WHERE id = :stockId', { replacements: { stockId } });
|
||
});
|
||
|
||
it('空集合也缓存(不穿透):无锁定任务的仓库首次回源、二次命中;并发未命中只回源一次且结果一致', async () => {
|
||
// 用另一个测试仓库(无静态任务)验证「空结果缓存」与并发 singleflight
|
||
const emptyWarehouseId = OTHER_TEST_WAREHOUSE_ID;
|
||
const emptyKey = `stock_check:static_lock:${emptyWarehouseId}`;
|
||
await ctx.app.delCacheAsync(emptyKey);
|
||
|
||
const firstEmpty = await ctx.service.systems.stockCheck.staticLockList({ warehouseId: emptyWarehouseId });
|
||
assert.equal(firstEmpty.cached, false, '首次查询应回源');
|
||
assert.deepEqual(firstEmpty.stock_ids, [], '无锁定任务时为空集合');
|
||
assert.equal(firstEmpty.total, 0);
|
||
|
||
const secondEmpty = await ctx.service.systems.stockCheck.staticLockList({ warehouseId: emptyWarehouseId });
|
||
assert.equal(secondEmpty.cached, true, '空集合也会被缓存,二次查询命中(不穿透数据库)');
|
||
assert.deepEqual(secondEmpty.stock_ids, []);
|
||
|
||
// 并发未命中:singleflight 共用同一次回源,结果一致
|
||
await ctx.app.delCacheAsync(emptyKey);
|
||
const concurrent = await Promise.all(Array.from({ length: 5 }, () =>
|
||
ctx.service.systems.stockCheck.staticLockList({ warehouseId: emptyWarehouseId })));
|
||
assert.equal(concurrent.length, 5);
|
||
for (const item of concurrent) {
|
||
assert.deepEqual(item.stock_ids, [], '并发查询结果应一致');
|
||
}
|
||
assert.ok(
|
||
concurrent.every(item => item.cached === false),
|
||
'并发未命中时均由同一次回源答复(cached=false),不会各自打出多轮 SQL'
|
||
);
|
||
|
||
// forceRefresh 强制回源
|
||
const forced = await ctx.service.systems.stockCheck.staticLockList({
|
||
warehouseId: emptyWarehouseId,
|
||
forceRefresh: true,
|
||
});
|
||
assert.equal(forced.cached, false, 'forceRefresh 应跳过缓存回源');
|
||
|
||
await ctx.app.delCacheAsync(emptyKey);
|
||
});
|
||
|
||
it('防脏读:回源期间发生状态流转(代次变化)时不写入旧快照,缓存保持为空由下次回源', async () => {
|
||
const guardWarehouseId = OTHER_TEST_WAREHOUSE_ID;
|
||
const guardKey = `stock_check:static_lock:${guardWarehouseId}`;
|
||
await ctx.app.delCacheAsync(guardKey);
|
||
|
||
const service = ctx.service.systems.stockCheck;
|
||
const originalQuery = service._queryStaticLockRows;
|
||
try {
|
||
// 模拟「查询过程中另一个审核/完成流转正在重建缓存」:查询内部递增锁定代次
|
||
service._queryStaticLockRows = async warehouseId => {
|
||
await service._bumpStaticLockGeneration(warehouseId);
|
||
return originalQuery.call(service, warehouseId);
|
||
};
|
||
const guarded = await service.staticLockList({ warehouseId: guardWarehouseId, forceRefresh: true });
|
||
assert.equal(guarded.cache_skipped, true, '代次变化时不写缓存');
|
||
assert.equal(await ctx.app.getCacheAsync(guardKey), null, '旧快照不应写入缓存(避免脏读)');
|
||
assert.deepEqual(guarded.stock_ids, [], '仍返回本次查询结果,供调用方使用');
|
||
|
||
// 恢复后正常写缓存
|
||
service._queryStaticLockRows = originalQuery;
|
||
const normal = await service.staticLockList({ warehouseId: guardWarehouseId, forceRefresh: true });
|
||
assert.equal(normal.cache_skipped, undefined, '无并发流转时正常写缓存');
|
||
assert.ok(await ctx.app.getCacheAsync(guardKey), '缓存已写入');
|
||
|
||
// 状态流转会递增代次(审核通过时由 refreshStaticLockCache 递增)
|
||
const generationBefore = await service._readStaticLockGeneration(guardWarehouseId);
|
||
await service.refreshStaticLockCache(guardWarehouseId);
|
||
const generationAfter = await service._readStaticLockGeneration(guardWarehouseId);
|
||
assert.ok(generationAfter > generationBefore, 'refreshStaticLockCache 应递增锁定代次');
|
||
} finally {
|
||
service._queryStaticLockRows = originalQuery;
|
||
await ctx.app.delCacheAsync(guardKey);
|
||
}
|
||
});
|
||
|
||
it('getStaticLockConflict:锁定商品返回可读冲突文案,未锁定返回空', async () => {
|
||
await clearLockCache();
|
||
const stocks = await fetchStockRows(1);
|
||
const check = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-冲突文案'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
const conflict = await ctx.service.systems.stockCheck.getStaticLockConflict({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockIds: [ stocks[0].id ],
|
||
actionLabel: '分配储位',
|
||
});
|
||
assert.equal(conflict.locked, true);
|
||
assert.match(conflict.message, /禁止分配储位/);
|
||
assert.match(conflict.message, new RegExp(check.check_no), '冲突文案应含盘点单号');
|
||
assert.equal(Number(conflict.rows[0].stock_id), Number(stocks[0].id));
|
||
|
||
const noConflict = await ctx.service.systems.stockCheck.getStaticLockConflict({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockIds: [ 999999999 ],
|
||
actionLabel: '移库',
|
||
});
|
||
assert.equal(noConflict.locked, false);
|
||
assert.equal(noConflict.message, '');
|
||
assert.deepEqual(noConflict.rows, []);
|
||
|
||
// 空入参不查库、不报错
|
||
const emptyInput = await ctx.service.systems.stockCheck.getStaticLockConflict({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
stockIds: [],
|
||
});
|
||
assert.equal(emptyInput.locked, false);
|
||
});
|
||
|
||
it('方法层 staticLockList:仓库上下文注入、success 包装、缓存标识透出', async () => {
|
||
await clearLockCache();
|
||
mockCurrentUser();
|
||
const stocks = await fetchStockRows(1);
|
||
const check = await ctx.service.systems.stockCheck.create({
|
||
warehouseId: TEST_WAREHOUSE_ID,
|
||
title: uniqueTitle('静态锁定-方法层'),
|
||
type: 'goods',
|
||
isStatic: 1,
|
||
creatorId: TEST_CREATOR_ID,
|
||
creatorName: TEST_CREATOR_NAME,
|
||
});
|
||
await addDetail(check.id, [ stocks[0].id ]);
|
||
await submitCheck(check.id);
|
||
await auditCheck(check.id, 'approve');
|
||
|
||
// 审核通过时已重建缓存 → 首次调用即命中缓存
|
||
const warmed = await ctx.service.systemMethods.stock.check.staticLockList();
|
||
assert.equal(warmed.data.cached, true, '审核通过已重建缓存,首次调用应命中');
|
||
|
||
// 手动清除缓存后首次调用回源(cached=false),再次调用命中
|
||
await clearLockCache();
|
||
const first = await ctx.service.systemMethods.stock.check.staticLockList();
|
||
assert.equal(first.flag, 'success');
|
||
assert.equal(first.code, 1);
|
||
assert.equal(Number(first.data.warehouse_id), TEST_WAREHOUSE_ID, '仓库应由 ctx.user.store_id 注入');
|
||
assert.ok(first.data.stock_ids.map(Number).includes(Number(stocks[0].id)));
|
||
assert.equal(first.data.cached, false);
|
||
assert.equal(first.data.total, first.data.rows.length);
|
||
|
||
const second = await ctx.service.systemMethods.stock.check.staticLockList();
|
||
assert.equal(second.flag, 'success');
|
||
assert.equal(second.data.cached, true, '二次调用应命中缓存');
|
||
|
||
// 缺仓库上下文 → failure 400
|
||
ctx.user = null;
|
||
const noWarehouse = await ctx.service.systemMethods.stock.check.staticLockList();
|
||
assert.equal(noWarehouse.flag, 'failure');
|
||
assert.equal(noWarehouse.code, 400);
|
||
});
|
||
});
|
||
});
|