Compare commits
No commits in common. "c02f2f0d56166fd6135d1374f01867f09ddabf0a" and "0e7545bd9a0740628dfd3ed7b249e0ca6d267935" have entirely different histories.
c02f2f0d56
...
0e7545bd9a
@ -562,8 +562,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, export, exportTaskProgress, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
|
||||
- app/service/systemMethods/storeWarehouse/warehouse.js (3)
|
||||
- list, sign, confirmSign
|
||||
- app/service/systemMethods/user.js (12)
|
||||
- login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, updateUsername, changePassword, changeRole, register
|
||||
- app/service/systemMethods/user.js (10)
|
||||
- login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, changeRole, register
|
||||
- app/service/systemMethods/warehouse.js (25)
|
||||
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces
|
||||
- app/service/systemMethods/waybill/warehouse.js (9)
|
||||
@ -582,8 +582,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- generateAppKey, generateAppSecret, getDefaultInterfaceTypeId, list, create, update, delete, regenerateSecret
|
||||
- app/service/systems/auth/role_permission.js (7)
|
||||
- normalizeTypeFilter, normalizePermissionSet, toApiPermissionIds, serializePermissionSet, getPermissionIdsForRoles, assignPermissions, removePermissionsFromAllRoles
|
||||
- app/service/systems/auth/user.js (70)
|
||||
- getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, publishWechatLoginEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getAccountInfo, updateUsername, changePassword, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
|
||||
- app/service/systems/auth/user.js (68)
|
||||
- getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, publishWechatLoginEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getAccountInfo, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
|
||||
- app/service/systems/camera.js (12)
|
||||
- list, detail, create, update, setOsd, _findCameraForControl, _assertPtzSuccess, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete
|
||||
- app/service/systems/cameraServer.js (5)
|
||||
|
||||
@ -74,18 +74,6 @@ module.exports = app => {
|
||||
},
|
||||
comment: '状态:0-封号,1-启用',
|
||||
},
|
||||
is_custom_password: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1 ]],
|
||||
msg: '自定义密码标记值不合法,0-否,1-是',
|
||||
},
|
||||
},
|
||||
comment: '是否自定义密码:0-否,1-是',
|
||||
},
|
||||
last_login_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
|
||||
@ -33,8 +33,8 @@ module.exports = app => {
|
||||
type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'location',
|
||||
comment: '盘点范围类型:location=按库位(未传库位时自动全盘),store=按货主,goods=按商品',
|
||||
defaultValue: 'all',
|
||||
comment: '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位',
|
||||
},
|
||||
mode: {
|
||||
type: STRING(20),
|
||||
|
||||
@ -425,39 +425,6 @@ function resolveExpressMapping(expressNameMap, candidateKeys = []) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按系统快递编码分组构建快递产品类型映射。
|
||||
*
|
||||
* @param {Array} productTypeList 快递产品类型列表
|
||||
* @return {Object} 系统快递编码(大写)到产品类型列表([{ name, code }])的映射
|
||||
*/
|
||||
function buildExpressProductTypeMap(productTypeList) {
|
||||
return normalizeArray(productTypeList).reduce((result, productTypeItem) => {
|
||||
const currentItem = productTypeItem && typeof productTypeItem === 'object' ? productTypeItem : {};
|
||||
const expressCode = normalizeText(currentItem.express_code).trim().toUpperCase();
|
||||
const code = normalizeText(currentItem.code).trim();
|
||||
|
||||
if (!expressCode || !code) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!Array.isArray(result[expressCode])) {
|
||||
result[expressCode] = [];
|
||||
}
|
||||
|
||||
if (result[expressCode].some(item => item.code === code)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
result[expressCode].push({
|
||||
name: normalizeText(currentItem.name).trim() || code,
|
||||
code,
|
||||
});
|
||||
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。
|
||||
*
|
||||
@ -2259,9 +2226,6 @@ class indexService extends MainService {
|
||||
/**
|
||||
* 获取指定店铺的快递签约列表。
|
||||
*
|
||||
* 每个列表项会按 sys_express_code 匹配 wms_express_product_type,
|
||||
* 补充 product_types: [{ name, code }],未匹配到时返回空数组;PDD 平台不补充该字段。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {string|number} [data.shop_id] 店铺 ID
|
||||
* @param {string|number} [data.shopId] 店铺 ID,兼容驼峰字段
|
||||
@ -2589,57 +2553,16 @@ class indexService extends MainService {
|
||||
break;
|
||||
}
|
||||
|
||||
const listWithProductTypes = await this.attachExpressProductTypes(list, platformCode);
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
shop_id: shopPlain.id,
|
||||
platform_code: platformCode,
|
||||
list: listWithProductTypes,
|
||||
list,
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按系统快递编码为店铺快递列表补充快递产品类型。
|
||||
*
|
||||
* 产品类型来源于 wms_express_product_type,读取走系统快递服务缓存。
|
||||
* PDD 分支不补充该字段。
|
||||
*
|
||||
* @param {Array} list 店铺快递列表
|
||||
* @param {string} [platformCode=''] 店铺所属平台编码
|
||||
* @return {Promise<Array>} 补充 product_types 后的列表
|
||||
*/
|
||||
async attachExpressProductTypes(list, platformCode = '') {
|
||||
const { ctx, service } = this;
|
||||
const normalizedList = normalizeArray(list);
|
||||
const normalizedPlatformCode = normalizeText(platformCode).trim().toUpperCase();
|
||||
|
||||
if (normalizedList.length === 0 || normalizedPlatformCode === 'PDD') {
|
||||
return normalizedList;
|
||||
}
|
||||
|
||||
let productTypeMap = {};
|
||||
|
||||
try {
|
||||
const productTypeList = await service.systems.express.getExpressProductTypeList();
|
||||
productTypeMap = buildExpressProductTypeMap(productTypeList);
|
||||
} catch (error) {
|
||||
ctx.logger.warn('[SystemMethods.attachExpressProductTypes] 获取快递产品类型失败: %s', error.message);
|
||||
}
|
||||
|
||||
return normalizedList.map(item => {
|
||||
const currentItem = item && typeof item === 'object' ? item : {};
|
||||
const expressCode = normalizeText(currentItem.sys_express_code).trim().toUpperCase();
|
||||
|
||||
return {
|
||||
...currentItem,
|
||||
product_types: normalizeArray(productTypeMap[expressCode]),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取淘宝菜鸟 STF 模板列表。
|
||||
*
|
||||
|
||||
@ -59,9 +59,9 @@ class StockCheckMethodService extends MainService {
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.title] 盘点名称/主题。
|
||||
* @param {string} [data.type] 盘点范围类型:location/store/goods,缺省 location。
|
||||
* @param {string} [data.type] 盘点范围类型:all/store/goods/location。
|
||||
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘;
|
||||
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
|
||||
* @param {string} [data.remark] 备注。
|
||||
* 盘点日期固定为今天,前端不传。
|
||||
@ -151,7 +151,7 @@ class StockCheckMethodService extends MainService {
|
||||
* @param {Object} [data.pagination] 分页参数。
|
||||
* @param {Object} [data.where] 查询条件。
|
||||
* @param {string|Array<string>} [data.where.status] 状态筛选(单值或数组)。
|
||||
* @param {string|Array<string>} [data.where.type] 范围类型筛选(location/store/goods)。
|
||||
* @param {string|Array<string>} [data.where.type] 范围类型筛选(all/store/goods/location)。
|
||||
* @param {string|Array<string>} [data.where.mode] 盘点方式筛选(open/blind)。
|
||||
* @param {number} [data.where.store_id] 货主筛选。
|
||||
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
|
||||
@ -334,7 +334,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 视图规则:任务范围为库位(type=location)时一律按库位视图返回(无视 view/is_goods);
|
||||
* 视图规则:任务范围为库位(type=location/all)时一律按库位视图返回(无视 view/is_goods);
|
||||
* 任务范围为商品(type=goods/store)时默认聚合库位视图(space),
|
||||
* 仅传入 is_goods=true 时按商品视图(goods)返回。
|
||||
* 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致,
|
||||
@ -386,7 +386,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 拉取盘点作业数据(space 视图分页版)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods,
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods,
|
||||
* goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/
|
||||
* record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked);
|
||||
* 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。
|
||||
@ -450,10 +450,8 @@ class StockCheckMethodService extends MainService {
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} data.detail_id 明细ID。
|
||||
* @param {number} data.space_id 库位ID(wms_location_space.id,**必传**;兼容 spaceId / location_id / locationId 写法)。
|
||||
* 必须属于本仓库且所属分区有效;服务端以该 ID 为准落库,不再按库位编码猜库位。
|
||||
* @param {string} [data.location] 库位编码(可选,仅做一致性校验:与 space_id 对应库位编码不一致报 400)。
|
||||
* @param {number} data.quantity 实盘数量(>=0 且 <= 2147483647)。
|
||||
* @param {string} [data.location] 库位编码(可空;库位明细行以明细库位为准)。
|
||||
* @param {number} data.quantity 实盘数量(>=0)。
|
||||
* @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
|
||||
* @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。
|
||||
* @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。
|
||||
@ -474,13 +472,7 @@ class StockCheckMethodService extends MainService {
|
||||
barcode,
|
||||
item_name: itemName,
|
||||
is_empty: isEmpty,
|
||||
space_id: spaceIdSnake,
|
||||
spaceId: spaceIdCamel,
|
||||
location_id: locationIdSnake,
|
||||
locationId: locationIdCamel,
|
||||
} = data || {};
|
||||
const spaceId = [ spaceIdSnake, spaceIdCamel, locationIdSnake, locationIdCamel ]
|
||||
.find(value => value !== undefined && value !== null && value !== '');
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.report({
|
||||
@ -488,7 +480,6 @@ class StockCheckMethodService extends MainService {
|
||||
id,
|
||||
detailId,
|
||||
location,
|
||||
spaceId,
|
||||
quantity,
|
||||
stockId,
|
||||
barcode,
|
||||
@ -503,7 +494,7 @@ class StockCheckMethodService extends MainService {
|
||||
|
||||
/**
|
||||
* 标记库位为空(库位盘点模式专属)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location)时允许,
|
||||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location/all)时允许,
|
||||
* 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。
|
||||
* 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。
|
||||
*
|
||||
@ -603,7 +594,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
|
||||
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘;
|
||||
* 仅任务范围为库位(type=location)且状态 approved/checking 时允许,非库位任务报 400。
|
||||
* 仅任务范围为库位(type=location/all)且状态 approved/checking 时允许,非库位任务报 400。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
|
||||
@ -7,7 +7,7 @@ class userService extends MainService {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
|
||||
const _noNeedRight = '*';
|
||||
const _noNeedLog = 'info,getAccountInfo,changePassword,getBindWechatCode,getLoginWechatCode';
|
||||
const _noNeedLog = 'info,getAccountInfo,getBindWechatCode,getLoginWechatCode';
|
||||
const _noNeedAuth = '*';
|
||||
// info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
|
||||
const _noNeedBind = 'info';
|
||||
@ -81,24 +81,6 @@ class userService extends MainService {
|
||||
}
|
||||
return this.fail(result.message || '获取账号信息失败', result);
|
||||
}
|
||||
// 修改当前账号用户名(服务端校验重名,排除自己)
|
||||
async updateUsername(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.auth.user.updateUsername(data);
|
||||
if (result.code === 200) {
|
||||
return this.success(result.message || '用户名修改成功', result);
|
||||
}
|
||||
return this.fail(result.message || '用户名修改失败', result);
|
||||
}
|
||||
// 修改当前账号密码(首次自定义密码可不传旧密码)
|
||||
async changePassword(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.auth.user.changePassword(data);
|
||||
if (result.code === 200) {
|
||||
return this.success(result.message || '密码修改成功', result);
|
||||
}
|
||||
return this.fail(result.message || '密码修改失败', result);
|
||||
}
|
||||
async changeRole(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.auth.user.changeRole(data);
|
||||
|
||||
@ -1742,8 +1742,8 @@ class UserService extends Service {
|
||||
*/
|
||||
async getAccountInfo() {
|
||||
const { ctx } = this;
|
||||
const userId = this.getCurrentAccountId();
|
||||
if (!userId) {
|
||||
const userId = Number(ctx.userId || (ctx.user && ctx.user.id));
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
@ -1758,7 +1758,7 @@ class UserService extends Service {
|
||||
// 白名单字段,避免返回 password_hash / salt / last_login_ip 等敏感信息
|
||||
attributes: [
|
||||
'id', 'username', 'real_name', 'phone', 'email',
|
||||
'status', 'is_custom_password', 'last_login_at', 'created_at', 'updated_at',
|
||||
'status', 'last_login_at', 'created_at', 'updated_at',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
@ -1789,240 +1789,6 @@ class UserService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改当前登录账号的用户名(服务端做重名校验,排除自己)
|
||||
* @param {Object} [data={}] 入参
|
||||
* @param {string} [data.username] 新用户名
|
||||
* @return {Promise<Object>} 修改结果
|
||||
*/
|
||||
async updateUsername(data = {}) {
|
||||
const { ctx } = this;
|
||||
const userId = this.getCurrentAccountId();
|
||||
if (!userId) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 401,
|
||||
message: '未登录或登录已过期',
|
||||
};
|
||||
}
|
||||
|
||||
const username = typeof data.username === 'string' ? data.username.trim() : '';
|
||||
if (!username) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: 'username 不能为空',
|
||||
};
|
||||
}
|
||||
if (username.length < 3 || username.length > 50) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '用户名长度应在3-50个字符之间',
|
||||
};
|
||||
}
|
||||
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '用户名只能包含字母、数字和下划线',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const account = await ctx.model.Account.findOne({
|
||||
where: { id: userId },
|
||||
attributes: [ 'id', 'username' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!account) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 404,
|
||||
message: '账号不存在',
|
||||
};
|
||||
}
|
||||
if (account.username === username) {
|
||||
return {
|
||||
success: true,
|
||||
data: { id: userId, username },
|
||||
code: 200,
|
||||
message: '用户名未变更',
|
||||
};
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const duplicate = await ctx.model.Account.findOne({
|
||||
where: {
|
||||
username,
|
||||
id: { [Op.ne]: userId },
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (duplicate) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 409,
|
||||
message: '用户名已存在',
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.model.Account.update({ username }, {
|
||||
where: { id: userId },
|
||||
});
|
||||
// clearUserCache 默认平台清单不含 miniprogram/wx 等取值,先按当前平台补清一次
|
||||
const platformCode = ctx.header && ctx.header.platform;
|
||||
if (platformCode) {
|
||||
await this.clearUserCache(userId, platformCode);
|
||||
}
|
||||
await this.clearUserCache(userId);
|
||||
|
||||
ctx.username = username;
|
||||
if (ctx.user) {
|
||||
ctx.user.username = username;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { id: userId, username },
|
||||
code: 200,
|
||||
message: '用户名修改成功',
|
||||
};
|
||||
} catch (error) {
|
||||
const isDuplicate = error && (
|
||||
error.name === 'SequelizeUniqueConstraintError'
|
||||
|| (error.parent && error.parent.code === 'ER_DUP_ENTRY')
|
||||
);
|
||||
if (isDuplicate) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 409,
|
||||
message: '用户名已存在',
|
||||
};
|
||||
}
|
||||
ctx.logger.error(`修改用户名失败: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 0,
|
||||
message: '修改用户名失败',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改当前登录账号的密码;首次自定义密码(is_custom_password=0)无需旧密码。
|
||||
* @param {Object} [data={}] 入参
|
||||
* @param {string} [data.old_password] 旧密码(is_custom_password=1 时必填)
|
||||
* @param {string} [data.new_password] 新密码
|
||||
* @return {Promise<Object>} 修改结果
|
||||
*/
|
||||
async changePassword(data = {}) {
|
||||
const { ctx } = this;
|
||||
const userId = this.getCurrentAccountId();
|
||||
if (!userId) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 401,
|
||||
message: '未登录或登录已过期',
|
||||
};
|
||||
}
|
||||
|
||||
const rawOldPassword = data.old_password !== undefined ? data.old_password : data.oldPassword;
|
||||
const rawNewPassword = data.new_password !== undefined ? data.new_password : data.newPassword;
|
||||
const oldPassword = typeof rawOldPassword === 'string' ? rawOldPassword : '';
|
||||
const newPassword = typeof rawNewPassword === 'string' ? rawNewPassword.trim() : '';
|
||||
|
||||
if (!newPassword) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '新密码不能为空',
|
||||
};
|
||||
}
|
||||
if (newPassword.length > 64) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '新密码长度不能超过64个字符',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const account = await ctx.model.Account.findOne({
|
||||
where: { id: userId },
|
||||
attributes: [ 'id', 'password_hash', 'salt', 'is_custom_password' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!account) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 404,
|
||||
message: '账号不存在',
|
||||
};
|
||||
}
|
||||
|
||||
if (Number(account.is_custom_password) === 1) {
|
||||
if (!oldPassword) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '请输入旧密码',
|
||||
};
|
||||
}
|
||||
try {
|
||||
await this.verifyPassword(oldPassword, account.password_hash, account.salt);
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '旧密码错误',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const salt = this.generateSalt();
|
||||
const passwordHash = await this.encryptPassword(newPassword, salt);
|
||||
await ctx.model.Account.update({
|
||||
password_hash: passwordHash,
|
||||
salt,
|
||||
is_custom_password: 1,
|
||||
}, {
|
||||
where: { id: userId },
|
||||
});
|
||||
await this.clearUserCache(userId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { is_custom_password: 1 },
|
||||
code: 200,
|
||||
message: '密码修改成功',
|
||||
};
|
||||
} catch (error) {
|
||||
ctx.logger.error(`修改密码失败: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 0,
|
||||
message: '修改密码失败',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找用户所有的角色以及对应的主体(重构版)
|
||||
* @param {number} userId 用户ID
|
||||
|
||||
@ -376,44 +376,9 @@ class LocationZoneService extends Service {
|
||||
return count === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验分区编码在同仓库未占用(已归档分区不占用编码:paranoid 查询自动带 deleted_at IS NULL)。
|
||||
* 同仓库同 zone_code 并存会生成同 space_code 的库位行,导致盘点/库存按编码定位到多条库位。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} zoneCode 分区编码。
|
||||
* @param {number} [excludeZoneId] 排除的分区ID(更新场景排除自身)。
|
||||
* @return {Promise<void>} 校验不通过时抛出错误。
|
||||
*/
|
||||
async assertZoneCodeAvailable(warehouseId, zoneCode, excludeZoneId = 0) {
|
||||
const { ctx } = this;
|
||||
const code = String(zoneCode || '').trim();
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Z0-9]{1,5}$/.test(code)) {
|
||||
throw new Error('编码必须是1-5位大写字母或数字');
|
||||
}
|
||||
const where = {
|
||||
warehouse_id: Number(warehouseId),
|
||||
zone_code: code,
|
||||
};
|
||||
if (Number(excludeZoneId) > 0) {
|
||||
where.id = { [ctx.app.Sequelize.Op.ne]: Number(excludeZoneId) };
|
||||
}
|
||||
const exists = await ctx.model.LocationZone.findOne({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (exists) {
|
||||
throw new Error(`分区编码已存在:${code}(同仓库编码需唯一,归档分区不占用编码)`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建元素
|
||||
* @param {Object} data 元素数据
|
||||
* @param {Object} data 元素数据
|
||||
* @return {Promise<Object>} 创建的元素
|
||||
*/
|
||||
async createZone(data) {
|
||||
@ -433,9 +398,6 @@ class LocationZoneService extends Service {
|
||||
// 5. 处理编码(根据类型)
|
||||
const zoneCode = this.generateZoneCodeByType(data);
|
||||
|
||||
// 5.1 编码唯一性:同仓库未归档分区不得重复(否则会生成同编码库位,盘点按编码定位错乱)
|
||||
await this.assertZoneCodeAvailable(warehouse_id, zoneCode);
|
||||
|
||||
// 6. 创建分区
|
||||
const zone = await ctx.model.LocationZone.create({
|
||||
warehouse_id,
|
||||
@ -775,17 +737,6 @@ class LocationZoneService extends Service {
|
||||
|
||||
const updateData = { ...data };
|
||||
|
||||
// 编码变更需保证同仓库未归档分区内唯一(未变更则跳过)
|
||||
if (updateData.zone_code !== undefined && updateData.zone_code !== null) {
|
||||
const nextCode = String(updateData.zone_code).trim();
|
||||
if (nextCode && nextCode !== String(zone.zone_code || '').trim()) {
|
||||
await this.assertZoneCodeAvailable(zone.warehouse_id, nextCode, id);
|
||||
updateData.zone_code = nextCode;
|
||||
} else if (!nextCode) {
|
||||
delete updateData.zone_code;
|
||||
}
|
||||
}
|
||||
|
||||
if (data.is_active !== undefined) {
|
||||
const isActive = [ true, 1, '1', 'true' ].includes(data.is_active);
|
||||
const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active);
|
||||
|
||||
@ -9,7 +9,7 @@ const ExcelJS = require('exceljs');
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 盘点范围类型枚举(wms_stock_check.type) */
|
||||
const STOCK_CHECK_TYPES = Object.freeze([ 'store', 'goods', 'location' ]);
|
||||
const STOCK_CHECK_TYPES = Object.freeze([ 'all', 'store', 'goods', 'location' ]);
|
||||
/** 盘点方式枚举(wms_stock_check.mode) */
|
||||
const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]);
|
||||
/** 允许添加明细的主表状态 */
|
||||
@ -18,11 +18,6 @@ const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
|
||||
const STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS = 200;
|
||||
/** 允许盘点作业上报/完成的主表状态 */
|
||||
const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]);
|
||||
/**
|
||||
* 单次上报实盘数量上限(wms_stock_check_record.quantity 为 int(12) 有符号列,
|
||||
* 实际可存上限 2147483647;超限直接落库会抛 Out of range 变成 500)。
|
||||
*/
|
||||
const REPORT_MAX_QUANTITY = 2147483647;
|
||||
/** 允许提交审核的主表状态 */
|
||||
const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
|
||||
/** 允许取消的主表状态 */
|
||||
@ -38,6 +33,7 @@ const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls '
|
||||
|
||||
/** 盘点范围类型中文标签 */
|
||||
const STOCK_CHECK_TYPE_LABELS = Object.freeze({
|
||||
all: '全盘',
|
||||
store: '按货主',
|
||||
goods: '按商品',
|
||||
location: '按库位',
|
||||
@ -162,7 +158,7 @@ class StockCheckService extends Service {
|
||||
id: row.id,
|
||||
check_no: row.check_no,
|
||||
title: row.title || '',
|
||||
type: row.type || 'location',
|
||||
type: row.type || 'all',
|
||||
mode: row.mode || 'open',
|
||||
store_id: row.store_id || null,
|
||||
status: row.status || 'created',
|
||||
@ -550,9 +546,9 @@ class StockCheckService extends Service {
|
||||
* @param {Object} params 创建参数。
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.title] 盘点名称/主题。
|
||||
* @param {string} [params.type='location'] 盘点范围类型:location/store/goods。
|
||||
* @param {string} [params.type='all'] 盘点范围类型:all/store/goods/location。
|
||||
* @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘;
|
||||
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* @param {number} [params.storeId] 货主ID(按货主盘点时必填)。
|
||||
* @param {string} [params.remark] 备注。
|
||||
* 盘点日期固定为今天,前端不传。
|
||||
@ -579,7 +575,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const normalizedType = type ? String(type).trim() : 'location';
|
||||
const normalizedType = type ? String(type).trim() : 'all';
|
||||
if (!STOCK_CHECK_TYPES.includes(normalizedType)) {
|
||||
throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`);
|
||||
}
|
||||
@ -588,9 +584,9 @@ class StockCheckService extends Service {
|
||||
if (!STOCK_CHECK_MODES.includes(normalizedMode)) {
|
||||
throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`);
|
||||
}
|
||||
// 按库位盘点一律盲盘,不管前端传入什么;
|
||||
// 按库位盘点(all/location)一律盲盘,不管前端传入什么;
|
||||
// 按商品盘点(store/goods)按传入值(默认明盘)
|
||||
if (normalizedType === 'location') {
|
||||
if (normalizedType === 'all' || normalizedType === 'location') {
|
||||
normalizedMode = 'blind';
|
||||
}
|
||||
|
||||
@ -1050,9 +1046,10 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 添加盘点明细(商品或库位,按任务盘点类型决定)。
|
||||
* 仅 created/rejected 状态允许;store/goods 类型按 stock_ids 添加商品行(商品必须属于
|
||||
* 任务货主);location 类型按 locations(库位编码,兼容旧调用)或 location_ids
|
||||
* 任务货主);all/location 类型按 locations(库位编码,兼容旧调用)或 location_ids
|
||||
* (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、
|
||||
* locations 忽略;location 未传库位且未传库位ID时自动拉取全仓库启用库位(原全盘语义);
|
||||
* locations 忽略;all 未传库位且未传库位ID时自动拉取全仓库启用库位;
|
||||
* 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids;
|
||||
* 已存在的同盘点项跳过(幂等),重算主表 total_items。
|
||||
*
|
||||
* @param {Object} params 添加明细参数。
|
||||
@ -1083,16 +1080,26 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`);
|
||||
}
|
||||
|
||||
const checkType = String(check.type || 'location').trim();
|
||||
const isGoodsScope = checkType === 'store' || checkType === 'goods';
|
||||
const isLocationScope = checkType === 'location';
|
||||
if (!isGoodsScope && !isLocationScope) {
|
||||
throw this.createBusinessError(`盘点范围类型不合法(${checkType})`);
|
||||
}
|
||||
const checkType = String(check.type || 'all').trim();
|
||||
let isGoodsScope = checkType === 'store' || checkType === 'goods';
|
||||
let isLocationScope = checkType === 'all' || checkType === 'location';
|
||||
const numericStockIds = this._normalizeIdList(stockIds);
|
||||
const locationCodes = this._normalizeCodeList(locations);
|
||||
const numericLocationIds = this._normalizeIdList(locationIds);
|
||||
|
||||
// 兼容历史任务:改造前 type=all 的任务按商品添加明细(明细行 scope_type='goods')。
|
||||
// 这类任务已存在商品明细行时,继续按商品模式接受 stock_ids,避免旧调用被 400 拒绝;
|
||||
// 全新 type=all 任务(无任何商品明细行)维持新语义:按库位盘点,只能传 locations。
|
||||
if (checkType === 'all' && isLocationScope) {
|
||||
const goodsScopeCount = await ctx.model.StockCheckDetail.count({
|
||||
where: { check_id: checkId, scope_type: 'goods' },
|
||||
});
|
||||
if (goodsScopeCount > 0) {
|
||||
isGoodsScope = true;
|
||||
isLocationScope = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 按盘点类型校验入参维度(商品与库位互斥)
|
||||
if (isGoodsScope && locationCodes.length > 0) {
|
||||
throw this.createBusinessError('当前盘点类型按商品盘点,请传 stock_ids');
|
||||
@ -1136,9 +1143,8 @@ class StockCheckService extends Service {
|
||||
});
|
||||
} else {
|
||||
let codes = locationCodes;
|
||||
// 未显式传库位时自动拉取全仓库启用库位(原全盘语义);
|
||||
// 排除无头库位:zone 必须存在且未删除
|
||||
if (codes.length === 0) {
|
||||
// 全盘:未显式传库位时自动拉取全仓库启用库位(排除无头库位:zone 必须存在且未删除)
|
||||
if (checkType === 'all' && codes.length === 0) {
|
||||
const enabledSpaces = await ctx.model.LocationSpace.findAll({
|
||||
where: { warehouse_id: Number(warehouseId), is_enabled: true },
|
||||
attributes: [ 'space_code' ],
|
||||
@ -1158,6 +1164,9 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('当前仓库没有启用库位,无法按全盘自动生成盘点范围');
|
||||
}
|
||||
}
|
||||
if (codes.length === 0) {
|
||||
throw this.createBusinessError('请至少选择一个库位');
|
||||
}
|
||||
await this._addLocationDetailRows({
|
||||
checkId,
|
||||
warehouseId,
|
||||
@ -1399,7 +1408,7 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成按库位盘点明细的待创建行(location 类型)。
|
||||
* 生成按库位盘点明细的待创建行(all/location 类型)。
|
||||
* 按 space_code 匹配 wms_location_space(warehouse_id + space_code),
|
||||
* 不存在的编码记入 invalidLocations;已存在同 check_id+location_code 的明细跳过(幂等)。
|
||||
*
|
||||
@ -1474,7 +1483,7 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成按库位盘点明细的待创建行(库位ID直查路径,location 类型)。
|
||||
* 生成按库位盘点明细的待创建行(库位ID直查路径,all/location 类型)。
|
||||
* 直接按 wms_location_space.id 查库校验(warehouse_id 仓库隔离),不经过 space_code 二次解析;
|
||||
* 查不到的 ID 记入 invalidLocationIds(不报错);库位编码为空(脏数据)或已存在
|
||||
* 同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径,幂等),
|
||||
@ -2345,72 +2354,14 @@ class StockCheckService extends Service {
|
||||
return stockRow ? matchedStockId : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按库位编码解析库位ID(仅命中分区存在且未删除的有效库位行)。
|
||||
* 同仓库同编码可能同时存在多条库位(历史重复库位、分区已删除的无头库位,
|
||||
* 唯一索引含 deleted_at 且 NULL 不去重),此处取稳定口径:
|
||||
* 优先该商品有启用库存的库位行,其次 ID 最小的有效行。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} locationCode 库位编码。
|
||||
* @param {number} [stockId] 商品库存ID(wms_stock_warehouse.id,用于优先命中库存所在库位)。
|
||||
* @return {Promise<number>} 库位ID,未命中返回 0。
|
||||
*/
|
||||
async _resolveLocationIdByCode(warehouseId, locationCode, stockId) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const normalizedCode = String(locationCode || '').trim();
|
||||
if (!normalizedCode) {
|
||||
return 0;
|
||||
}
|
||||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: normalizedCode,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
// 库位有效性:zone 必须存在且未删除(无头库位不参与匹配)
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const candidateIds = (Array.isArray(spaceRows) ? spaceRows : [])
|
||||
.map(row => Number(row && row.id))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
if (candidateIds.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (candidateIds.length === 1 || !(Number(stockId) > 0)) {
|
||||
return candidateIds[0];
|
||||
}
|
||||
const storageRow = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
stock_id: Number(stockId),
|
||||
space_id: { [Op.in]: candidateIds },
|
||||
is_enabled: 1,
|
||||
},
|
||||
attributes: [ 'space_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const storageSpaceId = storageRow ? Number(storageRow.space_id) : 0;
|
||||
return storageSpaceId > 0 ? storageSpaceId : candidateIds[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 盘点作业上报(覆盖式)。
|
||||
* 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错),
|
||||
* 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错);
|
||||
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的
|
||||
* quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填),
|
||||
* 不再新增;未传库位编码时以 space_id 对应库位的编码落库;
|
||||
* **space_id 必传**(wms_location_space.id,须属于本仓库且分区有效),库位以该 ID 为准,
|
||||
* location 编码入参仅做一致性校验(不一致报 400),服务端不再按编码猜库位;
|
||||
* 不再新增;未传库位归入"无库位"分组(location_code 存空串);
|
||||
* 库位编码匹配 wms_location_space.space_code 时回填 location_id;
|
||||
* 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。
|
||||
* 数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全。
|
||||
*
|
||||
@ -2428,10 +2379,8 @@ class StockCheckService extends Service {
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {number} params.id 盘点任务ID。
|
||||
* @param {number} params.detailId 明细ID。
|
||||
* @param {string} [params.location] 库位编码(可选,仅做一致性校验;库位以 spaceId 为准)。
|
||||
* @param {number} params.spaceId 库位ID(wms_location_space.id,必传):必须属于本仓库且分区有效,
|
||||
* 缺失报 400「缺少库位ID(space_id)」;与 location 编码不一致或(库位明细行)与明细库位不一致同样 400。
|
||||
* @param {number} params.quantity 实盘数量(>=0 且 <= 2147483647)。
|
||||
* @param {string} [params.location] 库位编码(可空;库位明细行以明细库位为准)。
|
||||
* @param {number} params.quantity 实盘数量(>=0)。
|
||||
* @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
|
||||
* @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,
|
||||
* 未命中记为未知商品)。
|
||||
@ -2446,7 +2395,7 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径)。
|
||||
* 仅任务范围为库位(type=location)时允许:非库位任务报 400;
|
||||
* 仅任务范围为库位(type=location/all)时允许:非库位任务报 400;
|
||||
* 状态仅 approved/checking;明细必须属于本任务且为库位范围行(scope_type=location)。
|
||||
* 行为与 report(is_empty=true) 完全一致:写/更新空标记记录(stock_id/barcode/item_name 为空、
|
||||
* quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、
|
||||
@ -2481,7 +2430,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`);
|
||||
}
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
if (normalizedType !== 'location') {
|
||||
if (normalizedType !== 'location' && normalizedType !== 'all') {
|
||||
throw this.createBusinessError('仅库位盘点任务支持空库位标记');
|
||||
}
|
||||
|
||||
@ -2496,20 +2445,11 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('仅库位盘点明细支持空库位标记');
|
||||
}
|
||||
|
||||
// 转调 report 空库位标记口径(查重/互斥/汇总/日志统一);
|
||||
// report 要求必传 space_id,这里按明细库位编码解析有效库位(明细库位可能指向无头库位)
|
||||
const resolvedSpaceId = await this._resolveLocationIdByCode(
|
||||
Number(warehouseId),
|
||||
String(detail.location_code || '').trim()
|
||||
);
|
||||
if (resolvedSpaceId <= 0) {
|
||||
throw this.createBusinessError('盘点明细库位无效(库位不存在或所属分区已删除)');
|
||||
}
|
||||
// 转调 report 空库位标记口径(查重/互斥/汇总/日志统一)
|
||||
return this.report({
|
||||
warehouseId,
|
||||
id: checkId,
|
||||
detailId: detailRowId,
|
||||
spaceId: resolvedSpaceId,
|
||||
is_empty: true,
|
||||
checkerId,
|
||||
checkerName,
|
||||
@ -2522,7 +2462,6 @@ class StockCheckService extends Service {
|
||||
id,
|
||||
detailId,
|
||||
location,
|
||||
spaceId: spaceIdInput,
|
||||
quantity,
|
||||
stockId,
|
||||
barcode,
|
||||
@ -2557,9 +2496,6 @@ class StockCheckService extends Service {
|
||||
if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) {
|
||||
throw this.createBusinessError('实盘数量必须为不小于0的整数');
|
||||
}
|
||||
if (!normalizedIsEmpty && quantityValue > REPORT_MAX_QUANTITY) {
|
||||
throw this.createBusinessError(`实盘数量不能超过 ${REPORT_MAX_QUANTITY}`);
|
||||
}
|
||||
|
||||
const detail = await ctx.model.StockCheckDetail.findOne({
|
||||
where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) },
|
||||
@ -2582,36 +2518,6 @@ class StockCheckService extends Service {
|
||||
const inputItemName = itemName !== undefined && itemName !== null && String(itemName).trim() !== ''
|
||||
? String(itemName).trim()
|
||||
: '';
|
||||
// 必填库位ID(wms_location_space.id):必须属于本仓库且所属分区有效。
|
||||
// 不允许按编码猜库位(同仓库同编码可能有多条历史重复/无头库位),缺失即 400 由调用方补传
|
||||
const inputSpaceId = spaceIdInput !== undefined && spaceIdInput !== null && spaceIdInput !== ''
|
||||
? Number(spaceIdInput)
|
||||
: 0;
|
||||
if (!Number.isInteger(inputSpaceId) || inputSpaceId <= 0) {
|
||||
throw this.createBusinessError('缺少库位ID(space_id),请传取回数据中的 space_id');
|
||||
}
|
||||
const inputLocationRow = await ctx.model.LocationSpace.findOne({
|
||||
where: { id: inputSpaceId, warehouse_id: Number(warehouseId) },
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
if (!inputLocationRow) {
|
||||
throw this.createBusinessError('上报库位不存在、不属于当前仓库或所属分区已删除');
|
||||
}
|
||||
const inputLocationCode = String(inputLocationRow.space_code || '').trim();
|
||||
if (!inputLocationCode) {
|
||||
throw this.createBusinessError('上报库位的库位编码为空,无法上报');
|
||||
}
|
||||
// 入参库位编码(可选):仅做一致性校验,库位以 space_id 对应的库位行为准
|
||||
const inputLocationCodeParam = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
|
||||
let normalizedStockId = 0;
|
||||
let normalizedBarcode = null;
|
||||
@ -2646,25 +2552,39 @@ class StockCheckService extends Service {
|
||||
} else if (inputBarcode) {
|
||||
normalizedBarcode = inputBarcode;
|
||||
}
|
||||
// 库位以 space_id 对应的库位行为准(必填);location 编码仅做一致性校验
|
||||
if (inputLocationCodeParam && inputLocationCodeParam !== inputLocationCode) {
|
||||
throw this.createBusinessError('上报库位编码与库位ID不一致');
|
||||
// 库位编码匹配 wms_location_space.space_code 时回填 location_id;
|
||||
// 未传库位归一为空串("无库位"分组,配合 uk_detail_stock_location 唯一索引)
|
||||
locationCode = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
if (locationCode) {
|
||||
const space = await ctx.model.LocationSpace.findOne({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: locationCode,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (space) {
|
||||
locationId = space.id;
|
||||
}
|
||||
}
|
||||
locationCode = inputLocationCode;
|
||||
locationId = Number(inputLocationRow.id);
|
||||
} else {
|
||||
// 库位行:以明细库位为准
|
||||
locationCode = String(detail.location_code || '').trim();
|
||||
if (!locationCode) {
|
||||
throw this.createBusinessError('盘点明细缺少库位信息');
|
||||
}
|
||||
if (inputLocationCodeParam && inputLocationCodeParam !== locationCode) {
|
||||
const inputLocation = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
if (inputLocation && inputLocation !== locationCode) {
|
||||
throw this.createBusinessError('上报库位与盘点明细库位不一致');
|
||||
}
|
||||
if (inputLocationCode !== locationCode) {
|
||||
throw this.createBusinessError('上报库位与盘点明细库位不一致');
|
||||
}
|
||||
locationId = Number(inputLocationRow.id);
|
||||
locationId = detail.location_id !== null && detail.location_id !== undefined
|
||||
? Number(detail.location_id)
|
||||
: null;
|
||||
|
||||
if (normalizedIsEmpty) {
|
||||
// 空库位标记:不要求商品,stock_id/barcode/item_name 均为空、quantity=0
|
||||
@ -2708,7 +2628,7 @@ class StockCheckService extends Service {
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(库位编码来自 space_id 对应库位)更新已有记录,
|
||||
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录,
|
||||
// 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全;
|
||||
// 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重;
|
||||
// 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新
|
||||
@ -2841,8 +2761,6 @@ class StockCheckService extends Service {
|
||||
const summary = await this._recalcCheckSummary(checkId);
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
// message 补充库位编码/库位ID(原 message 只有明细与数量,事后无法定位是哪个库位被上报),
|
||||
// before_changes 落明细快照与本次上报字段,供追溯
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'stock_check',
|
||||
businessId: checkId,
|
||||
@ -2851,24 +2769,6 @@ class StockCheckService extends Service {
|
||||
changeSummary: normalizedIsEmpty
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'} 为空`
|
||||
: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`,
|
||||
beforeChanges: {
|
||||
check_no: check.check_no,
|
||||
detail_id: detailRowId,
|
||||
scope_type: scopeType,
|
||||
stock_id: normalizedStockId > 0 ? normalizedStockId : null,
|
||||
location_code: locationCode || '',
|
||||
location_id: locationId !== null && locationId !== undefined ? Number(locationId) : null,
|
||||
detail_location_code: String(detail.location_code || '').trim() || null,
|
||||
detail_location_id: detail.location_id !== null && detail.location_id !== undefined
|
||||
? Number(detail.location_id)
|
||||
: null,
|
||||
quantity: quantityValue,
|
||||
barcode: normalizedBarcode,
|
||||
is_unknown_goods: isUnknownGoods,
|
||||
is_empty: normalizedIsEmpty,
|
||||
mode,
|
||||
record_id: Number(record && record.id) || null,
|
||||
},
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||
name: ctx.user?.employees_name || '',
|
||||
@ -2878,15 +2778,14 @@ class StockCheckService extends Service {
|
||||
checkNo: check.check_no,
|
||||
detailId: detailRowId,
|
||||
locationCode,
|
||||
locationId: locationId !== null && locationId !== undefined ? Number(locationId) : null,
|
||||
quantity: quantityValue,
|
||||
barcode: normalizedBarcode,
|
||||
isUnknownGoods,
|
||||
is_empty: normalizedIsEmpty,
|
||||
mode,
|
||||
message: normalizedIsEmpty
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''} 为空`
|
||||
: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''},实盘 ${quantityValue}`,
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位为空`
|
||||
: `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`,
|
||||
},
|
||||
});
|
||||
|
||||
@ -3015,7 +2914,7 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动,view 入参已废弃忽略)。
|
||||
* 视图解析规则:
|
||||
* - 任务范围为库位(type=location):一律按库位视图(location)返回,无视 view/is_goods 入参;
|
||||
* - 任务范围为库位(type=location/all):一律按库位视图(location)返回,无视 view/is_goods 入参;
|
||||
* - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。
|
||||
* 三视图行结构:
|
||||
* location=库位结构,以任务库位范围行(scope_type=location)为列表,
|
||||
@ -3075,7 +2974,7 @@ class StockCheckService extends Service {
|
||||
// 商品范围任务默认 space(聚合库位),仅 is_goods=true 时 goods 视图
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
const goodsViewRequested = isGoods === true || isGoods === 'true' || isGoods === 1;
|
||||
const resolvedView = normalizedType === 'location'
|
||||
const resolvedView = normalizedType === 'location' || normalizedType === 'all'
|
||||
? 'location'
|
||||
: (goodsViewRequested ? 'goods' : 'space');
|
||||
|
||||
@ -3165,7 +3064,7 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 拉取盘点作业数据(space 视图分页版)。
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods),
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods),
|
||||
* 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1),
|
||||
* 不传时按分页返回全部库位行。
|
||||
*
|
||||
@ -3416,14 +3315,11 @@ class StockCheckService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
const rowLocationId = detailRow.location_id !== null && detailRow.location_id !== undefined
|
||||
? Number(detailRow.location_id)
|
||||
: null;
|
||||
return {
|
||||
detail_id: detailId,
|
||||
location_id: rowLocationId,
|
||||
// space_id 为 location_id 的同义字段,供调用方直接回传 stock.check.report
|
||||
space_id: rowLocationId,
|
||||
location_id: detailRow.location_id !== null && detailRow.location_id !== undefined
|
||||
? detailRow.location_id
|
||||
: null,
|
||||
location_code: locationCode,
|
||||
location_name: locationName,
|
||||
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
|
||||
@ -3553,42 +3449,6 @@ class StockCheckService extends Service {
|
||||
}
|
||||
const spaceCodeByStockMap = new Map();
|
||||
const spaceQuantityByStockMap = new Map();
|
||||
// 库位编码 → 有效库位ID(同编码多条时取拣货顺序第一条):供 goods 视图 locations[] 回传 location_id,
|
||||
// 让调用方能直接把库位ID回传 stock.check.report(否则只有编码,服务端只能按编码猜库位)
|
||||
const spaceIdByCodeMap = new Map();
|
||||
for (const row of sortedSpaceRows) {
|
||||
const spaceCode = String(row.space_code || '').trim();
|
||||
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
|
||||
spaceIdByCodeMap.set(spaceCode, Number(row.id));
|
||||
}
|
||||
}
|
||||
// 已盘库位(当前库存已无该商品)补查有效库位ID,口径与 workData space 视图一致(zone 存在未删除)
|
||||
const uncoveredRecordCodes = [ ...new Set(records
|
||||
.map(record => String(record.location_code || '').trim())
|
||||
.filter(code => code && !spaceIdByCodeMap.has(code))) ];
|
||||
if (uncoveredRecordCodes.length > 0) {
|
||||
const uncoveredRows = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: { [Op.in]: uncoveredRecordCodes },
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of uncoveredRows) {
|
||||
const spaceCode = String(row.space_code || '').trim();
|
||||
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
|
||||
spaceIdByCodeMap.set(spaceCode, Number(row.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [ stockId, spaceIds ] of stockSpaceIdsMap.entries()) {
|
||||
const spaceRowMap = new Map(sortedSpaceRows.map(row => [ Number(row.id), row ]));
|
||||
const orderedRows = spaceIds
|
||||
@ -3691,12 +3551,7 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
const buildLocationItem = (code, group) => {
|
||||
const locationIdValue = (code && spaceIdByCodeMap.get(code)) || (group && group.location_id) || null;
|
||||
const locationItem = {
|
||||
// 库位ID(wms_location_space.id):优先有效库位行,其次作业记录回填值;
|
||||
// space_id 供调用方直接回传 stock.check.report(location_id 为兼容别名)
|
||||
location_id: locationIdValue,
|
||||
space_id: locationIdValue,
|
||||
location_code: code || null,
|
||||
checked_at: group ? group.checked_at : null,
|
||||
checker_name: group ? group.checker_name : null,
|
||||
@ -3741,15 +3596,13 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 构建 space 视图行:以任务商品(scope_type=goods 的 stock_id 集合)所在的库位为列表。
|
||||
* 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id)
|
||||
* ∪ 作业记录库位(上报库位与明细库位编码一致时归并到明细固化 location_id,
|
||||
* 无头库位归并到同编码有效库位,避免同编码出现重复行),
|
||||
* 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id),
|
||||
* 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序,
|
||||
* 同值保持库位查询顺序);
|
||||
* 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock
|
||||
* SUM(available_quantity+locked_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity))
|
||||
* 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段;
|
||||
* status 已盘口径:该 (库位, 商品) 存在作业记录(兼容按明细 + 库位编码命中);
|
||||
* status 已盘口径:该 (detail_id, location_code) 存在作业记录;
|
||||
* 未在 wms_storage 有库位的商品不入列表(无库位可聚)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
@ -3794,11 +3647,6 @@ class StockCheckService extends Service {
|
||||
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
|
||||
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
|
||||
const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ]));
|
||||
const detailById = new Map(detailRows.map(row => [ Number(row.id), row ]));
|
||||
// 明细按「库位 + 商品」索引:同一商品分布在多个库位时,库位行应取本库位对应的明细
|
||||
const detailByStockSpace = new Map(
|
||||
detailRows.map(row => [ `${Number(row.location_id)}_${Number(row.stock_id)}`, row ])
|
||||
);
|
||||
|
||||
// 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id,
|
||||
// 同时按 (space_id, stock_id) 汇总账面数量(口径=可用+锁定)与锁定数量
|
||||
@ -3819,101 +3667,12 @@ class StockCheckService extends Service {
|
||||
group: [ 'space_id', 'stock_id' ],
|
||||
raw: true,
|
||||
});
|
||||
// 记录库位归一:上报库位与明细库位编码一致时以明细固化库位为准,
|
||||
// 避免同仓库同编码存在多条库位(历史重复库位/无头库位)时同一编码在视图里出现两行
|
||||
const recordSpaceIdMap = new Map();
|
||||
for (const record of records) {
|
||||
const recordCode = String(record.location_code || '').trim();
|
||||
const recordDetail = detailById.get(Number(record.detail_id));
|
||||
const detailLocationCode = recordDetail ? String(recordDetail.location_code || '').trim() : '';
|
||||
const detailLocationId = recordDetail ? Number(recordDetail.location_id) || 0 : 0;
|
||||
const recordSpaceId = recordCode && detailLocationCode === recordCode && detailLocationId > 0
|
||||
? detailLocationId
|
||||
: Number(record.location_id) || 0;
|
||||
recordSpaceIdMap.set(Number(record.id), recordSpaceId);
|
||||
}
|
||||
|
||||
// 无头库位(分区不存在/已删除)不直接入视图:同仓库同编码多条库位时会出现自定义字段为空的幽灵行,
|
||||
// 统一归并到同编码的有效库位(优先该商品有启用库存的库位,其次 ID 最小)
|
||||
const recordSpaceIdList = [ ...new Set([ ...recordSpaceIdMap.values() ].filter(spaceId => spaceId > 0)) ];
|
||||
if (recordSpaceIdList.length > 0) {
|
||||
const validRecordSpaceRows = await ctx.model.LocationSpace.findAll({
|
||||
where: { id: { [Op.in]: recordSpaceIdList } },
|
||||
attributes: [ 'id' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
const validRecordSpaceIdSet = new Set(validRecordSpaceRows.map(row => Number(row.id)));
|
||||
const invalidRecordSpaceIds = recordSpaceIdList.filter(spaceId => !validRecordSpaceIdSet.has(spaceId));
|
||||
if (invalidRecordSpaceIds.length > 0) {
|
||||
const invalidRows = await ctx.model.LocationSpace.findAll({
|
||||
where: { id: { [Op.in]: invalidRecordSpaceIds } },
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
raw: true,
|
||||
});
|
||||
const invalidSpaceCodeMap = new Map(
|
||||
invalidRows.map(row => [ Number(row.id), String(row.space_code || '').trim() ])
|
||||
);
|
||||
const fallbackCodes = [ ...new Set([ ...invalidSpaceCodeMap.values() ].filter(Boolean)) ];
|
||||
const fallbackRows = fallbackCodes.length === 0 ? [] : await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: { [Op.in]: fallbackCodes },
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const fallbackIdsByCode = new Map();
|
||||
for (const row of fallbackRows) {
|
||||
const code = String(row.space_code || '').trim();
|
||||
if (!fallbackIdsByCode.has(code)) {
|
||||
fallbackIdsByCode.set(code, []);
|
||||
}
|
||||
fallbackIdsByCode.get(code).push(Number(row.id));
|
||||
}
|
||||
const storageKeySet = new Set(
|
||||
storageRows.map(row => `${Number(row.space_id)}_${Number(row.stock_id)}`)
|
||||
);
|
||||
for (const record of records) {
|
||||
const recordId = Number(record.id);
|
||||
const currentSpaceId = recordSpaceIdMap.get(recordId) || 0;
|
||||
if (!invalidRecordSpaceIds.includes(currentSpaceId)) {
|
||||
continue;
|
||||
}
|
||||
const code = invalidSpaceCodeMap.get(currentSpaceId)
|
||||
|| String(record.location_code || '').trim();
|
||||
const candidates = fallbackIdsByCode.get(code) || [];
|
||||
if (candidates.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const recordStockId = Number(record.stock_id) || 0;
|
||||
const stockHit = recordStockId > 0
|
||||
? candidates.find(spaceId => storageKeySet.has(`${spaceId}_${recordStockId}`))
|
||||
: 0;
|
||||
recordSpaceIdMap.set(recordId, stockHit || candidates[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查,
|
||||
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行
|
||||
// (编码一致时已在上面归并到明细固化库位)。
|
||||
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行。
|
||||
const recordSpaceIds = [];
|
||||
const recordLocationCodes = [];
|
||||
for (const record of records) {
|
||||
const recordSpaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
|
||||
const recordSpaceId = Number(record.location_id) || 0;
|
||||
if (recordSpaceId > 0) {
|
||||
if (!recordSpaceIds.includes(recordSpaceId)) {
|
||||
recordSpaceIds.push(recordSpaceId);
|
||||
@ -4000,12 +3759,10 @@ class StockCheckService extends Service {
|
||||
codeMatchedLocationRows.map(row => [ String(row.space_code || '').trim(), Number(row.id) ])
|
||||
);
|
||||
const recordsByDetailSpace = new Map();
|
||||
// 记录按「库位 + 商品」归集:跨明细上报(记录明细与库位不一致)时仍能命中对应库位行
|
||||
const recordsBySpaceStock = new Map();
|
||||
// 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行
|
||||
const recordsBySpace = new Map();
|
||||
for (const record of records) {
|
||||
let spaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
|
||||
let spaceId = Number(record.location_id) || 0;
|
||||
if (!spaceId) {
|
||||
spaceId = codeToSpaceIdMap.get(String(record.location_code || '').trim()) || 0;
|
||||
}
|
||||
@ -4019,15 +3776,6 @@ class StockCheckService extends Service {
|
||||
}
|
||||
recordsByDetailSpace.get(detailSpaceKey).push(record);
|
||||
|
||||
const recordStockId = Number(record.stock_id) || 0;
|
||||
if (recordStockId > 0) {
|
||||
const spaceStockKey = `${spaceId}_${recordStockId}`;
|
||||
if (!recordsBySpaceStock.has(spaceStockKey)) {
|
||||
recordsBySpaceStock.set(spaceStockKey, []);
|
||||
}
|
||||
recordsBySpaceStock.get(spaceStockKey).push(record);
|
||||
}
|
||||
|
||||
if (!recordsBySpace.has(spaceId)) {
|
||||
recordsBySpace.set(spaceId, []);
|
||||
}
|
||||
@ -4052,7 +3800,7 @@ class StockCheckService extends Service {
|
||||
.sort((left, right) => Number(left.stock_id) - Number(right.stock_id))
|
||||
.map(storageRow => {
|
||||
const stockId = Number(storageRow.stock_id);
|
||||
const detailRow = detailByStockSpace.get(`${spaceId}_${stockId}`) || detailByStockId.get(stockId);
|
||||
const detailRow = detailByStockId.get(stockId);
|
||||
if (!detailRow) {
|
||||
return null;
|
||||
}
|
||||
@ -4060,8 +3808,7 @@ class StockCheckService extends Service {
|
||||
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
|
||||
const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
|
||||
const detailId = Number(detailRow.id);
|
||||
const locationRecords = recordsBySpaceStock.get(`${spaceId}_${stockId}`)
|
||||
|| recordsByDetailSpace.get(`${detailId}_${spaceId}`)
|
||||
const locationRecords = recordsByDetailSpace.get(`${detailId}_${spaceId}`)
|
||||
|| recordsByDetailLocation.get(`${detailId}_${spaceCode}`)
|
||||
|| [];
|
||||
// 作业照片与记录ID(供前端展示与编辑/移除记录)
|
||||
@ -4102,11 +3849,8 @@ class StockCheckService extends Service {
|
||||
.filter(item => item !== null);
|
||||
|
||||
return {
|
||||
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name);
|
||||
// location_id / space_id 均为 id 的同义字段,上报 stock.check.report 时以 space_id 必传
|
||||
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name)
|
||||
id: spaceId,
|
||||
location_id: spaceId,
|
||||
space_id: spaceId,
|
||||
space_code: spaceCode || null,
|
||||
custom_barcode: locationRow.custom_barcode != null && String(locationRow.custom_barcode).trim() !== ''
|
||||
? String(locationRow.custom_barcode).trim()
|
||||
@ -4238,7 +3982,7 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
|
||||
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),
|
||||
* 该库位回到未盘状态;仅任务范围为库位(type=location)且状态 approved/checking 时允许;
|
||||
* 该库位回到未盘状态;仅任务范围为库位(type=location/all)且状态 approved/checking 时允许;
|
||||
* 删除后重算 checked_items/diff_items/detail_status,主表状态不回退;
|
||||
* 同时清理被删记录的图片引用(失败仅告警不影响主流程)。
|
||||
*
|
||||
@ -4271,7 +4015,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许清除库位盘点信息`);
|
||||
}
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
if (normalizedType !== 'location') {
|
||||
if (normalizedType !== 'location' && normalizedType !== 'all') {
|
||||
throw this.createBusinessError('仅库位盘点任务支持重盘清除库位');
|
||||
}
|
||||
|
||||
@ -5347,23 +5091,10 @@ class StockCheckService extends Service {
|
||||
raw: true,
|
||||
});
|
||||
for (const spaceRow of spaceRows) {
|
||||
const code = String(spaceRow.space_code || '').trim();
|
||||
if (!code) {
|
||||
continue;
|
||||
}
|
||||
const candidate = {
|
||||
locationDisplayMap.set(String(spaceRow.space_code || '').trim(), {
|
||||
custom_name: String(spaceRow.custom_name || '').trim(),
|
||||
custom_barcode: String(spaceRow.custom_barcode || '').trim(),
|
||||
};
|
||||
// 同仓库同编码可能有多条库位(历史重复/无头库位):优先保留有自定义名称的行,
|
||||
// 避免空值行后写覆盖,导致导出回退成库位编码
|
||||
const existing = locationDisplayMap.get(code);
|
||||
const shouldReplace = !existing
|
||||
|| (!existing.custom_name && candidate.custom_name)
|
||||
|| (!existing.custom_name && !candidate.custom_name && candidate.custom_barcode);
|
||||
if (shouldReplace) {
|
||||
locationDisplayMap.set(code, candidate);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,44 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为账号表新增“是否自定义密码”标记。
|
||||
*/
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:新增 is_custom_password 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tableName = 'wms_account';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (columns.is_custom_password) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, 'is_custom_password', {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否自定义密码:0-否,1-是',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 is_custom_password 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tableName = 'wms_account';
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
|
||||
if (!columns.is_custom_password) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, 'is_custom_password');
|
||||
},
|
||||
};
|
||||
@ -1,53 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 移除盘点范围类型 all(与 location 语义重复:两者都按库位盘点、都强制盲盘、
|
||||
* 明细都是 scope_type='location';all 唯一的额外能力「未传库位时自动拉全仓库启用库位」
|
||||
* 已合并进 location):
|
||||
*
|
||||
* wms_stock_check:
|
||||
* 1. 存量数据:
|
||||
* - 存在商品明细行(scope_type='goods')的 type='all' 任务 = 2026-09-30 改造前的
|
||||
* 「全仓按商品」口径,改为 type='goods'(mode 保持原值,改造前商品口径允许明盘);
|
||||
* - 其余 type='all' 任务统一改为 'location',mode 归一到 'blind'(按库位盘点一律盲盘)。
|
||||
* 2. 列定义:默认值 all → location,comment 去掉 all。
|
||||
*
|
||||
* 发布前核查 SQL(确认两类任务各有多少):
|
||||
* SELECT c.type, d.scope_type, COUNT(DISTINCT c.id)
|
||||
* FROM wms_stock_check c LEFT JOIN wms_stock_check_detail d ON d.check_id = c.id
|
||||
* WHERE c.type = 'all' GROUP BY c.type, d.scope_type;
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_stock_check';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
// 改造前的「全仓按商品」任务(明细为商品行)按真实语义归入 goods,保留原 mode
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE \`${TABLE_NAME}\` c
|
||||
JOIN (
|
||||
SELECT DISTINCT check_id FROM wms_stock_check_detail WHERE scope_type = 'goods'
|
||||
) d ON d.check_id = c.id
|
||||
SET c.\`type\` = 'goods'
|
||||
WHERE c.\`type\` = 'all'
|
||||
`);
|
||||
// 其余(库位口径,含无明细的空任务)统一并入 location,并按库位口径归一为盲盘
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${TABLE_NAME}\` SET \`type\` = 'location', \`mode\` = 'blind' WHERE \`type\` = 'all'`
|
||||
);
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE \`${TABLE_NAME}\`
|
||||
MODIFY COLUMN \`type\` VARCHAR(20) NOT NULL DEFAULT 'location'
|
||||
COMMENT '盘点范围类型:location=按库位(未传库位时自动全盘),store=按货主,goods=按商品'
|
||||
`);
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
// 数据不可回滚(all 已并入 location/goods,无法区分原值),仅恢复列定义
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE \`${TABLE_NAME}\`
|
||||
MODIFY COLUMN \`type\` VARCHAR(20) NOT NULL DEFAULT 'all'
|
||||
COMMENT '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位'
|
||||
`);
|
||||
},
|
||||
};
|
||||
@ -1,73 +1,4 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.308",
|
||||
"date": "2026-10-27",
|
||||
"type": "updated",
|
||||
"summary": "库存盘点移除范围类型 all(与 location 语义重复):全盘能力(未传库位时自动拉取全仓库启用库位)并入 location,type 缺省值改为 location,create 传 all 返回 400;存量 type=all 任务由迁移收敛(商品行任务改 goods、库位行/空任务改 location 并归一盲盘)。",
|
||||
"methods": [
|
||||
"stock.check.create",
|
||||
"stock.check.list",
|
||||
"stock.check.addDetail",
|
||||
"stock.check.workData",
|
||||
"stock.check.markEmpty",
|
||||
"stock.check.recheckClearLocation"
|
||||
],
|
||||
"notes": [
|
||||
"动机:type=all 与 type=location 语义完全重复——两者都按库位盘点、明细都是 scope_type=location、mode 都被强制 blind;all 唯一的额外能力「添加明细时未传库位自动拉取全仓库启用库位」已合并进 location,all 因此下线。",
|
||||
"create:type 仅允许 store/goods/location,缺省由 all 改为 location;传 all 返回 400「盘点范围类型不合法,仅支持 store/goods/location」。mode 规则不变——location 一律盲盘(忽略传入),store/goods 按传入值(缺省明盘)。",
|
||||
"addDetail:type=location 未传 locations 且未传 location_ids 时自动拉取当前仓库全部启用且有效库位(排除无头库位)生成库位行(原 all 全盘语义);type=all 的历史任务不再走「已有商品明细行则按商品模式」兼容分支,直接返回 400「盘点范围类型不合法(all)」。",
|
||||
"存量数据:database/migrations/20261027010000-merge-stock-check-type-all-into-location.js 将明细含商品行(scope_type=goods,2026-09-30 改造前的全仓按商品口径)的 type=all 任务改为 type=goods(mode 保持原值),其余(明细为库位行或无明细的空任务)改为 type=location 并归一 mode=blind;wms_stock_check.type 列默认值改为 location、注释去掉 all。",
|
||||
"影响面:前端传 type=all 的创建调用将收到 400,需改为 location(需要全盘时创建 location 任务后调用 addDetail 不传库位即可)。workData/markEmpty/recheckClearLocation 等按库位判定的接口仍只认 type=location(历史 all 任务经迁移后即为 location)。",
|
||||
"测试:test/app/service/systems/stock_check.test.js 改为 location 口径——新增「type=all 创建报 400」「历史 type=all 任务添加明细报 400」用例;原「type=all 缺省库位自动全仓」用例改由 type=location 承接;移除 type=all 历史商品明细兼容用例。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/list/addDetail/workData/markEmpty/recheckClearLocation(type 语义、mode 规则、全盘自动范围、错误文案);根版本 0.3.307 → 0.3.308、updatedAt 2026-10-27;methods/changes/system.json 新增本条(插入数组首位);未改动其它分组。",
|
||||
"破坏性提示:type=all 不再是合法入参(400);依赖「all 缺省自动全仓」的调用改为 location 即可,行为一致。",
|
||||
"代码依据:app/service/systems/stock_check.js#create/#addDetail/#workData/#markEmpty/#recheckClearLocation、app/service/systemMethods/stock/check.js、app/model/stock_check.js、database/migrations/20261027010000-merge-stock-check-type-all-into-location.js。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.307",
|
||||
"date": "2026-10-25",
|
||||
"type": "updated",
|
||||
"summary": "库存盘点上报(stock.check.report)改为 space_id 必传:库位一律按库位ID落库、不再按编码猜库位(修复同仓库同编码重复库位导致作业记录挂到无头脏库位);实盘数量上限 2147483647 返回 400;取回接口补充 space_id/location_id 字段供回传;操作日志 message/before_changes 补充库位编码与库位ID。",
|
||||
"methods": [
|
||||
"stock.check.report",
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"问题现象:生产盘点单 PD20261025000001 的 stock.check.workData space 视图出现 custom_name/custom_barcode 为 null 的库位行(如 E02-06-01-01)。根因:wms_location_space 存在大量同仓库同编码重复库位(uk_warehouse_space_code 含 deleted_at,NULL 不去重导致重复插入不受约束),其中大量库位所属 zone 已删除(无头库位);report 旧逻辑只按 warehouse_id + space_code 做 findOne,命中最小的历史行,导致作业记录挂到脏库位,space 视图再按记录库位补行时又未做分区有效性过滤。",
|
||||
"取回侧字段(本次补齐):workData/workDataSpaceDetails 的 space 视图行新增 space_id 与 location_id(与既有 id 同值);goods 视图 locations[] 新增 space_id 与 location_id(取分区有效库位行,同编码多条取拣货顺序第一条,已盘但无库存的库位按编码补查有效库位)。location 视图/recordList/result 的 location_id 保持不变。",
|
||||
"report 写库(本次修正为强制):space_id 必传(兼容 spaceId/location_id/locationId 写法,取回接口 rows[].space_id、rows[].id、locations[].space_id 可直接回传);服务端校验属于本仓库且 zone 存在未删除,缺失/非法返回 400「缺少库位ID(space_id)」,不存在/跨仓库/分区已删除返回 400;库位编码以 space_id 对应库位行为准,location 入参降级为可选一致性校验(不一致 400),服务端不再按编码匹配/猜库位;库位明细行还要求 space_id 对应编码等于明细库位编码。",
|
||||
"report 校验:实盘数量新增上限 2147483647(wms_stock_check_record.quantity 为 int(12)),超限返回 400「实盘数量不能超过 2147483647」;此前超限直接落库抛 Out of range 变 500(生产今日 10 次)。",
|
||||
"workData space 视图:记录库位归一(上报编码与明细编码一致归并到明细固化 location_id;记录指向无头库位时归并到同编码有效库位),库位商品明细改按「库位+商品」索引、作业记录改按「库位+商品」聚合,避免跨库位上报时同一编码出现两行或实盘数落到别的行。",
|
||||
"操作日志:STOCK_CHECK_REPORT 的 message 追加库位编码与库位ID;before_changes 落 check_no/detail_id/scope_type/stock_id/location_code/location_id/detail_location_code/detail_location_id/quantity/barcode/is_unknown_goods/is_empty/mode/record_id 快照(原 changeSummary 参数在 operationLog.buildOperationLogData 中未落库,日志里查不到库位信息)。",
|
||||
"问题定位依据(只读核查):生产 wms-api.log 中 244 条 stock.check.report 请求 body 键仅 id/detail_id/quantity/location/stock_id,无 space_id;detail 6151 于 2026-10-25 22:55:36 上报 location=E02-06-01-01(明细库位为 E02-06-02-01),落库 location_id=13768(zone 59 已删除);有效行为 22093(E1区02-06-01/00224214)。",
|
||||
"测试:test/app/service/systems/stock_check.test.js 升级为 space_id 必传口径——新增/改写用例覆盖「同编码重复库位不产生幽灵行」「space_id 必传与缺失/非法/跨仓库/无头/编码不一致 400」「数量超限 400 且不落库」「操作日志含库位信息」「space 视图行 space_id=id」「goods 视图 locations[] 含 space_id」,全量 244 通过。",
|
||||
"文档变更范围:methods/system.json 的 stock.check.report(space_id 必填参数、location 降级为一致性校验、quantity 上限)、stock.check.workData / stock.check.workDataSpaceDetails(space 视图行含 id/space_id/location_id、goods locations[] 含 space_id)+根版本 0.3.306 → 0.3.307、updatedAt 2026-10-25;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"破坏性提示:旧调用方(未传 space_id)将收到 400「缺少库位ID(space_id)」,前端需改为回传取回接口返回的 space_id;「无库位上报」通道随之取消(历史 location_code='' 记录仍按既有口径展示/导出为空)。",
|
||||
"代码依据:app/service/systems/stock_check.js#_resolveLocationIdByCode/#report/#_buildSpaceWorkRows、app/service/systemMethods/stock/check.js#report。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.306",
|
||||
"date": "2026-10-25",
|
||||
"type": "added",
|
||||
"summary": "用户账号能力增强:user.getAccountInfo 返回新增 is_custom_password;新增 user.updateUsername(服务端重名校验并排除自己)与 user.changePassword(首次自定义密码可免旧密码,修改后置 is_custom_password=1,再次修改必须校验旧密码)。",
|
||||
"methods": [
|
||||
"user.getAccountInfo",
|
||||
"user.updateUsername",
|
||||
"user.changePassword"
|
||||
],
|
||||
"notes": [
|
||||
"user.getAccountInfo:返回字段白名单新增 is_custom_password(是否自定义密码:0-否,1-是),仍不返回 password_hash、salt、last_login_ip。",
|
||||
"user.updateUsername:新增方法,仅修改当前登录账号;username 必填,长度3-50且仅允许字母/数字/下划线;服务端查询 username 重名时排除自己(id != 当前账号),重名返回 409;用户名未变化直接返回成功;更新后清理用户缓存,并同步当前请求上下文 username。",
|
||||
"user.changePassword:新增方法,入参 new_password 必填(兼容 newPassword),old_password 兼容 oldPassword;is_custom_password=0 时旧密码可不传,is_custom_password=1 时必须传且校验通过;修改时重新生成 salt 与 password_hash,并将 is_custom_password 置为1;方法已加入 _noNeedLog,避免请求体中的明文密码写入操作日志。",
|
||||
"错误码:updateUsername 400(参数/格式)/401(未登录)/404(账号不存在)/409(用户名已存在);changePassword 400(新密码为空、请输入旧密码、旧密码错误)/401/404;数据库异常返回 code=0。",
|
||||
"数据库:依赖迁移 20261025135000-add-is-custom-password-to-wms-account.js(wms_account.is_custom_password TINYINT(1) NOT NULL DEFAULT 0),开发库与生产库均已执行。",
|
||||
"测试:test/app/service/systemMethods/user.getAccountInfo.test.js(5)、user.updateUsername.test.js(7)、user.changePassword.test.js(8),合计 20 通过。",
|
||||
"文档变更范围:methods/system.json 的 user.getAccountInfo(response 新增 is_custom_password)、user.updateUsername(新增)、user.changePassword(新增)+根版本 0.3.305 → 0.3.306、updatedAt 2026-10-25;方法文档已写入开发库 wms_api_method_doc 并重新导出;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"代码依据:app/service/systemMethods/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#getAccountInfo。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.305",
|
||||
"date": "2026-10-25",
|
||||
@ -12555,23 +12486,5 @@
|
||||
"测试:test/app/service/systemMethods/order/wave.wavePickTaskList.test.js 补充 cart_code 操作符/默认模糊/顶层优先/keyword 覆盖用例,并修复原 mock 缺失 QueryTypes.SELECT 导致的既有用例失败。"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.10.26-index.getShopExpressList-productTypes",
|
||||
"date": "2026-10-26",
|
||||
"type": "updated",
|
||||
"summary": "index.getShopExpressList 返回的 list 每项新增 product_types 字段:[{ name, code }],按 sys_express_code 匹配 wms_express_product_type 得到,未匹配时为空数组;PDD 平台不补充该字段。",
|
||||
"methods": [
|
||||
"index.getShopExpressList"
|
||||
],
|
||||
"notes": [
|
||||
"适用范围:仅 PDD 以外的平台(CAINIAO/DY/KS/SPH/XHS/JD 等)补充 product_types,PDD 平台保持原有返回结构不变。",
|
||||
"匹配规则:list 项 sys_express_code 与 wms_express_product_type.express_code 比较(trim + 大写,不区分大小写),同一 express_code 下按 code 去重;name 为空时回退为 code。",
|
||||
"数据来源与缓存:复用系统快递服务 getExpressProductTypeList 的全量缓存(缓存键 express:product-type:list,TTL 1 小时),缓存失效由 upsertExpressProductTypeList 在新增/更新产品类型后清理,接口不再额外直连数据库。",
|
||||
"容错:产品类型读取异常时仅记录 warn 日志,list 各项目 product_types 返回空数组,不影响电子面单签约列表主流程。",
|
||||
"JD 平台在 sys_express_code 补偿映射完成后再补充 product_types,与最终返回的 sys_express_code 一致。",
|
||||
"代码变更:app/service/systemMethods/index.js 新增 buildExpressProductTypeMap 与 attachExpressProductTypes,getShopExpressList 在返回前按平台补充字段(PDD 跳过、不读取产品类型缓存);methods/system.json 同步 data.list 说明与 product_types 子字段文档。"
|
||||
],
|
||||
"module": "index"
|
||||
}
|
||||
]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1,329 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 盘点库位一致性体检 / 订正脚本(wms_location_space 同编码重复 + 作业记录库位错挂)。
|
||||
*
|
||||
* 背景:uk_warehouse_space_code 为 (warehouse_id, space_code, deleted_at),MySQL 唯一索引不对
|
||||
* NULL 去重,同编码可重复插入;分区删除后库位行未被软删 → 出现「无头库位」(zone 不存在/已删除)
|
||||
* 与同编码多条并存。历史 stock.check.report 只按编码 findOne 猜库位,作业记录会挂到这些旧行上,
|
||||
* 导致 stock.check.workData space 视图出现 custom_name 为 null 的幽灵行。
|
||||
*
|
||||
* 用法:
|
||||
* node script/stock-check-location-consistency.cjs # 开发库体检(只读)
|
||||
* node script/stock-check-location-consistency.cjs --prod # 生产库体检(只读)
|
||||
* node script/stock-check-location-consistency.cjs --prod --apply-record # 订正作业记录 location_id
|
||||
* node script/stock-check-location-consistency.cjs --prod --sql-out=temp/fix-location.sql # 输出清理 SQL(不执行)
|
||||
*
|
||||
* 说明:
|
||||
* 1. 默认只读;只有显式 --apply-record 才写库,且仅处理「记录库位编码 == 明细库位编码」且
|
||||
* 明细库位分区有效的安全场景(跨库位上报需人工确认,只统计不修改)。
|
||||
* 2. 无头库位清理不直接执行:--sql-out 生成 SQL 文件(含引用计数过滤),人工审核后再跑。
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const PROJECT_ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
/**
|
||||
* 解析命令行参数。
|
||||
* @return {Object} 选项。
|
||||
*/
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const options = {
|
||||
prod: false,
|
||||
applyRecord: false,
|
||||
sqlOut: '',
|
||||
config: '',
|
||||
};
|
||||
for (const arg of args) {
|
||||
if (arg === '--prod') {
|
||||
options.prod = true;
|
||||
} else if (arg === '--apply-record') {
|
||||
options.applyRecord = true;
|
||||
} else if (arg.startsWith('--sql-out=')) {
|
||||
options.sqlOut = arg.slice('--sql-out='.length);
|
||||
} else if (arg.startsWith('--config=')) {
|
||||
options.config = arg.slice('--config='.length);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取数据库连接配置。
|
||||
* @param {Object} options 命令行选项。
|
||||
* @return {Object} mysql2 连接参数。
|
||||
*/
|
||||
function resolveClient(options) {
|
||||
const configPath = options.config
|
||||
? path.resolve(PROJECT_ROOT, options.config)
|
||||
: path.resolve(PROJECT_ROOT, options.prod ? 'script/db-query-prod-config.js' : 'config/config.local.js');
|
||||
// eslint-disable-next-line global-require
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-script' }) : configFactory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (!client) {
|
||||
throw new Error(`未在 ${configPath} 找到 mysql.clients.wms 配置`);
|
||||
}
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
connectTimeout: 20000,
|
||||
enableKeepAlive: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 引用库位ID的业务表(列名 → 表名),用于判断无头库位是否仍被引用 */
|
||||
const SPACE_REFERENCE_COLUMNS = [
|
||||
[ 'wms_storage', 'space_id' ],
|
||||
[ 'wms_picking', 'space_id' ],
|
||||
[ 'wms_receiving_detail', 'space_id' ],
|
||||
[ 'wms_storage_transaction', 'space_id' ],
|
||||
[ 'wms_inbound_direct_log', 'space_id' ],
|
||||
[ 'wms_stock_check_detail', 'location_id' ],
|
||||
[ 'wms_stock_check_record', 'location_id' ],
|
||||
];
|
||||
|
||||
/** 分批查询的批大小(避免 IN 列表过长 / 单条大查询超时) */
|
||||
const IN_CHUNK_SIZE = 500;
|
||||
|
||||
/**
|
||||
* 数组分块。
|
||||
* @param {Array} list 源数组。
|
||||
* @param {number} size 每块大小。
|
||||
* @return {Array<Array>} 分块结果。
|
||||
*/
|
||||
function chunk(list, size) {
|
||||
const result = [];
|
||||
for (let i = 0; i < list.length; i += size) {
|
||||
result.push(list.slice(i, i + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 有效库位判定 SQL(分区存在且未删除) */
|
||||
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)';
|
||||
|
||||
/**
|
||||
* 记录当前库位不可用判定(为空 / 行不存在 / 已归档 / 所属分区不存在或已删除)。
|
||||
* 订正只允许改动这类「坏记录」,已经是有效库位的记录一律不动。
|
||||
*/
|
||||
const BROKEN_RECORD_LOCATION_SQL = '(r.location_id IS NULL OR NOT EXISTS ('
|
||||
+ 'SELECT 1 FROM wms_location_space cur '
|
||||
+ 'JOIN wms_location_zone cz ON cz.id = cur.zone_id AND cz.deleted_at IS NULL '
|
||||
+ 'WHERE cur.id = r.location_id AND cur.deleted_at IS NULL))';
|
||||
|
||||
/** 同编码订正目标表达式(明细固化库位,且分区有效) */
|
||||
const SAME_CODE_TARGET_JOIN = 'JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id '
|
||||
+ 'JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL '
|
||||
+ 'JOIN wms_location_zone gz ON gz.id = good.zone_id AND gz.deleted_at IS NULL';
|
||||
|
||||
/** 跨编码订正目标(同仓库同编码、分区有效,取 id 最小);同时 JOIN 明细用于排除「编码本就等于明细编码」的记录 */
|
||||
const CROSS_CODE_TARGET_JOIN = 'JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id '
|
||||
+ 'JOIN ('
|
||||
+ 'SELECT ls.warehouse_id, ls.space_code, MIN(ls.id) target_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 GROUP BY ls.warehouse_id, ls.space_code'
|
||||
+ ') t ON t.warehouse_id = r.warehouse_id AND t.space_code = r.location_code';
|
||||
|
||||
/**
|
||||
* 主流程。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function main() {
|
||||
const options = parseArgs();
|
||||
// eslint-disable-next-line global-require
|
||||
const mysql = require(path.join(PROJECT_ROOT, 'node_modules/mysql2/promise'));
|
||||
const client = resolveClient(options);
|
||||
const connection = await mysql.createConnection(client);
|
||||
const summary = { target: `${client.host}:${client.port}/${client.database}`, applyRecord: options.applyRecord };
|
||||
|
||||
try {
|
||||
const [ warehouses ] = await connection.query(
|
||||
'SELECT warehouse_id, COUNT(*) space_cnt FROM wms_location_space WHERE deleted_at IS NULL GROUP BY warehouse_id'
|
||||
);
|
||||
summary.warehouseCount = warehouses.length;
|
||||
|
||||
// 1) 无头库位(分区不存在/已删除)ID 列表与总数
|
||||
const [ headlessIdRows ] = await connection.query(
|
||||
`SELECT ls.id FROM wms_location_space ls
|
||||
WHERE ls.deleted_at IS NULL AND ls.id NOT IN ${VALID_SPACE_SQL}`
|
||||
);
|
||||
const headlessIds = headlessIdRows.map(row => Number(row.id)).filter(id => id > 0);
|
||||
const headlessIdSet = new Set(headlessIds);
|
||||
summary.headlessSpaceCount = headlessIds.length;
|
||||
|
||||
// 2) 同编码重复分组
|
||||
const [ dupRows ] = await connection.query(
|
||||
`SELECT COUNT(*) group_cnt, COALESCE(SUM(c), 0) rows_in_dup FROM (
|
||||
SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space
|
||||
WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1
|
||||
) t`
|
||||
);
|
||||
summary.duplicateCodeGroups = Number(dupRows[0].group_cnt) || 0;
|
||||
summary.rowsInDuplicateGroups = Number(dupRows[0].rows_in_dup) || 0;
|
||||
|
||||
// 3) 作业记录库位错挂统计(记录库位编码 == 明细库位编码,但 location_id 不同)
|
||||
const [ sameCodeRows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt,
|
||||
SUM(CASE WHEN good.id IS NOT NULL THEN 1 ELSE 0 END) fixable
|
||||
FROM wms_stock_check_record r
|
||||
JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
LEFT JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL
|
||||
WHERE r.location_code = d.location_code
|
||||
AND (r.location_id IS NULL OR r.location_id <> d.location_id)`
|
||||
);
|
||||
summary.sameCodeMismatchRecords = Number(sameCodeRows[0].cnt) || 0;
|
||||
summary.sameCodeFixable = Number(sameCodeRows[0].fixable) || 0;
|
||||
|
||||
// 4) 跨库位上报(记录编码 != 明细编码)——需人工确认,不自动改
|
||||
const [ crossCodeRows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r
|
||||
JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
WHERE r.location_code <> d.location_code`
|
||||
);
|
||||
summary.crossCodeRecords = Number(crossCodeRows[0].cnt) || 0;
|
||||
|
||||
// 5) 无头库位中「无任何引用」的候选清理数:先取无头库位 id(小集合),再按表分批 IN 查引用,
|
||||
// 避免在 wms_storage_transaction / wms_inbound_direct_log 等大表上做相关 NOT EXISTS 导致超时
|
||||
const referencedHeadlessIds = new Set();
|
||||
for (const [ table, column ] of SPACE_REFERENCE_COLUMNS) {
|
||||
for (const ids of chunk(headlessIds, IN_CHUNK_SIZE)) {
|
||||
const [ refRows ] = await connection.query(
|
||||
`SELECT DISTINCT ${column} AS id FROM ${table} WHERE ${column} IN (?)`,
|
||||
[ ids ]
|
||||
);
|
||||
for (const refRow of refRows) {
|
||||
const refId = Number(refRow.id);
|
||||
if (headlessIdSet.has(refId)) {
|
||||
referencedHeadlessIds.add(refId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
summary.headlessReferencedCount = referencedHeadlessIds.size;
|
||||
summary.headlessOrphanCount = headlessIds.length - referencedHeadlessIds.size;
|
||||
|
||||
// 6) 需人工处理的重复编码 Top 10(按行数)
|
||||
const [ topDup ] = await connection.query(
|
||||
`SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space
|
||||
WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1
|
||||
ORDER BY c DESC, space_code ASC LIMIT 10`
|
||||
);
|
||||
summary.topDuplicates = topDup.map(row => ({
|
||||
warehouse_id: Number(row.warehouse_id),
|
||||
space_code: row.space_code,
|
||||
rows: Number(row.c),
|
||||
}));
|
||||
|
||||
// 7) 订正作业记录 location_id(仅安全场景,默认只读):
|
||||
// a. 记录编码 == 明细编码 → 改挂明细固化库位(分区有效)
|
||||
// b. 记录编码 != 明细编码(跨库位上报)→ 改挂「同仓库同编码、分区有效」的库位行(取 id 最小)
|
||||
// 两条都只处理当前 location_id 不可用的坏记录(为空/不存在/已归档/分区已删),已经有效的记录不动
|
||||
const [ drySameCode ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r ${SAME_CODE_TARGET_JOIN}
|
||||
WHERE r.location_code = d.location_code AND r.location_id <> d.location_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
const [ dryCrossCode ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r ${CROSS_CODE_TARGET_JOIN}
|
||||
WHERE r.location_code <> d.location_code
|
||||
AND r.location_id <> t.target_id AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
summary.wouldUpdateSameCode = Number(drySameCode[0].cnt) || 0;
|
||||
summary.wouldUpdateCrossCode = Number(dryCrossCode[0].cnt) || 0;
|
||||
|
||||
if (options.applyRecord) {
|
||||
const [ sameCodeResult ] = await connection.query(
|
||||
`UPDATE wms_stock_check_record r ${SAME_CODE_TARGET_JOIN}
|
||||
SET r.location_id = d.location_id
|
||||
WHERE r.location_code = d.location_code
|
||||
AND r.location_id <> d.location_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
const [ crossCodeResult ] = await connection.query(
|
||||
`UPDATE wms_stock_check_record r ${CROSS_CODE_TARGET_JOIN}
|
||||
SET r.location_id = t.target_id
|
||||
WHERE r.location_code <> d.location_code
|
||||
AND r.location_id <> t.target_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
summary.updatedRecords = (Number(sameCodeResult.affectedRows) || 0)
|
||||
+ (Number(crossCodeResult.affectedRows) || 0);
|
||||
summary.updatedRecordsSameCode = Number(sameCodeResult.affectedRows) || 0;
|
||||
summary.updatedRecordsCrossCode = Number(crossCodeResult.affectedRows) || 0;
|
||||
}
|
||||
|
||||
// 8) 生成无头库位清理 SQL(不执行)
|
||||
if (options.sqlOut) {
|
||||
const outPath = path.resolve(PROJECT_ROOT, options.sqlOut);
|
||||
const sql = [
|
||||
'-- 由 script/stock-check-location-consistency.cjs 生成,请人工审核后执行',
|
||||
`-- target: ${summary.target}`,
|
||||
'-- 1) 盘点作业记录 location_id 订正(只改当前库位不可用的坏记录:为空/不存在/已归档/分区已删)',
|
||||
'-- 1.1 记录编码 == 明细编码 → 改挂明细固化库位(要求明细库位分区有效)',
|
||||
'UPDATE wms_stock_check_record r',
|
||||
' JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id',
|
||||
' JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL',
|
||||
' JOIN wms_location_zone gz ON gz.id = good.zone_id AND gz.deleted_at IS NULL',
|
||||
' SET r.location_id = d.location_id',
|
||||
' WHERE r.location_code = d.location_code',
|
||||
' AND r.location_id <> d.location_id',
|
||||
` AND ${BROKEN_RECORD_LOCATION_SQL.replace(/\n/g, ' ')};`,
|
||||
'',
|
||||
'-- 1.2 跨库位上报(记录编码 != 明细编码)→ 改挂同仓库同编码、分区有效的库位行(取 id 最小)',
|
||||
'UPDATE wms_stock_check_record r',
|
||||
' JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id',
|
||||
' JOIN (',
|
||||
' SELECT ls.warehouse_id, ls.space_code, MIN(ls.id) target_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',
|
||||
' GROUP BY ls.warehouse_id, ls.space_code',
|
||||
' ) t ON t.warehouse_id = r.warehouse_id AND t.space_code = r.location_code',
|
||||
' SET r.location_id = t.target_id',
|
||||
' WHERE r.location_code <> d.location_code',
|
||||
' AND r.location_id <> t.target_id',
|
||||
` AND ${BROKEN_RECORD_LOCATION_SQL.replace(/\n/g, ' ')};`,
|
||||
'',
|
||||
'-- 2) 无头库位软删除(仅无任何业务引用的孤行;有引用的需人工合并到有效库位)',
|
||||
'UPDATE wms_location_space ls',
|
||||
' SET ls.deleted_at = NOW()',
|
||||
' WHERE ls.deleted_at IS NULL',
|
||||
` AND ls.id NOT IN ${VALID_SPACE_SQL}`,
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_storage s WHERE s.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_picking p WHERE p.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_receiving_detail rd WHERE rd.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_storage_transaction st WHERE st.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log il WHERE il.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_stock_check_detail d WHERE d.location_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_stock_check_record r WHERE r.location_id = ls.id);',
|
||||
'',
|
||||
'-- 3) 清理后复查:仍重复的编码(需人工决定保留哪一行)',
|
||||
'SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space',
|
||||
' WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1;',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, sql, 'utf8');
|
||||
summary.sqlOut = outPath;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[stock-check-location-consistency] 执行失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,223 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 盘点作业记录「库位指向异常」体检(只读)。
|
||||
*
|
||||
* 输出三类异常,均以 wms_stock_check_record.location_id 为准:
|
||||
* A 已归档库位:location_id 命中 wms_location_space 且 deleted_at IS NOT NULL(软删除/归档行)
|
||||
* B 无头库位:库位未归档,但所属 zone 不存在或已删除(分区被删后库位行漏归档)
|
||||
* C 悬空库位:location_id 在 wms_location_space 中查不到(行已被物理删除)
|
||||
*
|
||||
* 用法:
|
||||
* node script/stock-check-record-deleted-location.cjs # 开发库(只读)
|
||||
* node script/stock-check-record-deleted-location.cjs --prod # 生产库(只读)
|
||||
* node script/stock-check-record-deleted-location.cjs --prod --limit=30 --top=30
|
||||
* node script/stock-check-record-deleted-location.cjs --prod --csv-out=temp/records.csv
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const PROJECT_ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
/**
|
||||
* 解析命令行参数。
|
||||
* @return {Object} 选项。
|
||||
*/
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const options = { prod: false, limit: 20, top: 20, csvOut: '', config: '' };
|
||||
for (const arg of args) {
|
||||
if (arg === '--prod') {
|
||||
options.prod = true;
|
||||
} else if (arg.startsWith('--limit=')) {
|
||||
options.limit = Math.max(1, Number(arg.slice('--limit='.length)) || 20);
|
||||
} else if (arg.startsWith('--top=')) {
|
||||
options.top = Math.max(1, Number(arg.slice('--top='.length)) || 20);
|
||||
} else if (arg.startsWith('--csv-out=')) {
|
||||
options.csvOut = arg.slice('--csv-out='.length);
|
||||
} else if (arg.startsWith('--config=')) {
|
||||
options.config = arg.slice('--config='.length);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取数据库连接配置。
|
||||
* @param {Object} options 命令行选项。
|
||||
* @return {Object} mysql2 连接参数。
|
||||
*/
|
||||
function resolveClient(options) {
|
||||
const configPath = options.config
|
||||
? path.resolve(PROJECT_ROOT, options.config)
|
||||
: path.resolve(PROJECT_ROOT, options.prod ? 'script/db-query-prod-config.js' : 'config/config.local.js');
|
||||
// eslint-disable-next-line global-require
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-script' }) : configFactory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (!client) {
|
||||
throw new Error(`未在 ${configPath} 找到 mysql.clients.wms 配置`);
|
||||
}
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
};
|
||||
}
|
||||
|
||||
/** 分类条件(A 已归档 / B 无头 / C 悬空 / D 无库位ID),均以记录 location_id 为基准 */
|
||||
const CATEGORY_SQL = {
|
||||
A: 'ls.id IS NOT NULL AND ls.deleted_at IS NOT NULL',
|
||||
B: 'ls.id IS NOT NULL AND ls.deleted_at IS NULL AND (z.id IS NULL OR z.deleted_at IS NOT NULL)',
|
||||
C: 'r.location_id IS NOT NULL AND ls.id IS NULL',
|
||||
D: 'r.location_id IS NULL',
|
||||
};
|
||||
|
||||
const BASE_FROM = `FROM wms_stock_check_record r
|
||||
LEFT JOIN wms_stock_check c ON c.id = r.check_id
|
||||
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
|
||||
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id`;
|
||||
|
||||
/**
|
||||
* 主流程。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function main() {
|
||||
const options = parseArgs();
|
||||
// eslint-disable-next-line global-require
|
||||
const mysql = require(path.join(PROJECT_ROOT, 'node_modules/mysql2/promise'));
|
||||
const client = resolveClient(options);
|
||||
const connection = await mysql.createConnection(client);
|
||||
|
||||
try {
|
||||
const summary = { target: `${client.host}:${client.port}/${client.database}`, categories: {} };
|
||||
const [ totalRows ] = await connection.query('SELECT COUNT(*) cnt FROM wms_stock_check_record');
|
||||
summary.totalRecords = Number(totalRows[0].cnt) || 0;
|
||||
|
||||
for (const [ key, condition ] of Object.entries(CATEGORY_SQL)) {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt, COUNT(DISTINCT r.check_id) checks FROM wms_stock_check_record r
|
||||
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
|
||||
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id
|
||||
WHERE ${condition}`
|
||||
);
|
||||
summary.categories[key] = {
|
||||
records: Number(rows[0].cnt) || 0,
|
||||
checks: Number(rows[0].checks) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 明细明细:A(已归档库位)与 B(无头库位)分别出「按盘点单 / 按库位 / 样本」三段
|
||||
summary.details = {};
|
||||
for (const key of [ 'A', 'B' ]) {
|
||||
const condition = CATEGORY_SQL[key];
|
||||
const [ topChecks ] = await connection.query(
|
||||
`SELECT r.check_id, MAX(c.check_no) check_no, MAX(r.warehouse_id) warehouse_id,
|
||||
COUNT(*) records, COUNT(DISTINCT r.detail_id) details
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
GROUP BY r.check_id
|
||||
ORDER BY records DESC
|
||||
LIMIT ${options.top}`
|
||||
);
|
||||
const [ topLocations ] = await connection.query(
|
||||
`SELECT r.location_id, MAX(ls.space_code) space_code, MAX(ls.zone_id) zone_id,
|
||||
COUNT(*) records, COUNT(DISTINCT r.check_id) checks
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
GROUP BY r.location_id
|
||||
ORDER BY records DESC
|
||||
LIMIT ${options.top}`
|
||||
);
|
||||
const [ samples ] = await connection.query(
|
||||
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
|
||||
r.location_id, r.location_code, ls.space_code space_code, ls.zone_id zone_id,
|
||||
z.id zone_exists, z.deleted_at zone_deleted_at,
|
||||
r.quantity, r.checker_name, r.checked_at
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
ORDER BY r.id DESC
|
||||
LIMIT ${options.limit}`
|
||||
);
|
||||
summary.details[key] = {
|
||||
topChecks: topChecks.map(row => ({
|
||||
check_id: Number(row.check_id),
|
||||
check_no: row.check_no,
|
||||
warehouse_id: Number(row.warehouse_id),
|
||||
records: Number(row.records),
|
||||
details: Number(row.details),
|
||||
})),
|
||||
topLocations: topLocations.map(row => ({
|
||||
location_id: Number(row.location_id),
|
||||
space_code: row.space_code,
|
||||
zone_id: row.zone_id === null ? null : Number(row.zone_id),
|
||||
records: Number(row.records),
|
||||
checks: Number(row.checks),
|
||||
})),
|
||||
samples: samples.map(row => ({
|
||||
record_id: Number(row.record_id),
|
||||
check_id: Number(row.check_id),
|
||||
check_no: row.check_no,
|
||||
detail_id: Number(row.detail_id),
|
||||
stock_id: row.stock_id === null ? null : Number(row.stock_id),
|
||||
location_id: Number(row.location_id),
|
||||
record_location_code: row.location_code,
|
||||
space_code: row.space_code,
|
||||
zone_id: row.zone_id === null ? null : Number(row.zone_id),
|
||||
zone_exists: row.zone_exists !== null && row.zone_exists !== undefined,
|
||||
zone_deleted_at: row.zone_deleted_at,
|
||||
quantity: Number(row.quantity),
|
||||
checker_name: row.checker_name,
|
||||
checked_at: row.checked_at,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (options.csvOut) {
|
||||
const header = 'category,record_id,check_id,check_no,detail_id,stock_id,location_id,record_location_code,detail_location_code,detail_location_id,space_code,zone_id,zone_exists,zone_deleted_at,quantity,checker_name,checked_at';
|
||||
const lines = [];
|
||||
for (const key of [ 'A', 'B' ]) {
|
||||
if ((summary.categories[key].records || 0) === 0) {
|
||||
continue;
|
||||
}
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
|
||||
r.location_id, r.location_code, d.location_code detail_location_code,
|
||||
d.location_id detail_location_id, ls.space_code space_code, ls.zone_id zone_id,
|
||||
z.id zone_exists, z.deleted_at zone_deleted_at,
|
||||
r.quantity, r.checker_name, r.checked_at
|
||||
${BASE_FROM}
|
||||
LEFT JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
WHERE ${CATEGORY_SQL[key]}
|
||||
ORDER BY r.check_id ASC, r.id ASC`
|
||||
);
|
||||
for (const item of rows) {
|
||||
lines.push([
|
||||
key, item.record_id, item.check_id, item.check_no, item.detail_id, item.stock_id,
|
||||
item.location_id, item.location_code, item.detail_location_code, item.detail_location_id,
|
||||
item.space_code, item.zone_id, item.zone_exists ? 1 : 0, item.zone_deleted_at,
|
||||
item.quantity, item.checker_name,
|
||||
item.checked_at instanceof Date ? item.checked_at.toISOString() : item.checked_at,
|
||||
].map(value => (value === null || value === undefined ? '' : String(value).replace(/,/g, ' '))).join(','));
|
||||
}
|
||||
}
|
||||
const outPath = path.resolve(PROJECT_ROOT, options.csvOut);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, [ header, ...lines ].join('\n'), 'utf8');
|
||||
summary.csvOut = outPath;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[stock-check-record-deleted-location] 执行失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -338,8 +338,6 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
assert.equal(result.data.list[1].sys_express_code, '');
|
||||
assert.equal(calls.syncPddSfTimedDeliveryExpressProductTypes, 0);
|
||||
assert.equal(calls.getExpressProductTypeList, 0);
|
||||
assert.equal(result.data.list[0].product_types, undefined);
|
||||
assert.equal(result.data.list[1].product_types, undefined);
|
||||
});
|
||||
|
||||
it('getShopExpressList 在 TB 下 SF 且无 TIMED-DELIVERY 时也应补齐时效服务', async () => {
|
||||
@ -373,7 +371,7 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
calls.getExpressProductTypeList += 1;
|
||||
calls.getExpressProductTypeListPayload = expressCode;
|
||||
return [
|
||||
{ express_code: 'SF', code: 'T6', name: '特快' },
|
||||
{ code: 'T6', name: '特快' },
|
||||
];
|
||||
};
|
||||
service.requestTbWaybillSearch = async payload => {
|
||||
@ -448,77 +446,10 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
],
|
||||
},
|
||||
]);
|
||||
assert.equal(calls.getExpressProductTypeList, 1);
|
||||
assert.deepEqual(result.data.list[0].product_types, [
|
||||
{ name: '特快', code: 'T6' },
|
||||
]);
|
||||
assert.equal(calls.getExpressProductTypeList, 0);
|
||||
assert.equal(calls.syncPddSfTimedDeliveryExpressProductTypes, 0);
|
||||
});
|
||||
|
||||
it('getShopExpressList 在产品类型读取异常时应降级为空数组', async () => {
|
||||
const { service, ctx, calls } = createHarness();
|
||||
|
||||
ctx.model.Shop.findOne = async () => ({
|
||||
get() {
|
||||
return {
|
||||
id: 26,
|
||||
warehouse_id: 100000,
|
||||
platform_code: 'CAINIAO',
|
||||
access_token: 'TB_ACCESS_TOKEN',
|
||||
printPlatform: {
|
||||
platform_code: 'CAINIAO',
|
||||
platform_name: '菜鸟电子面单',
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
service.service.systems.express.getExpressList = async () => ([
|
||||
{
|
||||
code: 'YTO_SYS',
|
||||
name: '圆通速递',
|
||||
CAINIAO: 'YTO',
|
||||
},
|
||||
]);
|
||||
service.service.systems.express.getExpressProductTypeList = async () => {
|
||||
calls.getExpressProductTypeList += 1;
|
||||
throw new Error('产品类型缓存不可用');
|
||||
};
|
||||
service.requestTbWaybillSearch = async () => ({
|
||||
cainiao_waybill_ii_search_response: {
|
||||
request_id: 'TB-REQ-026',
|
||||
modules: {
|
||||
waybill_apply_subscription_cols: {
|
||||
waybill_apply_subscription_info: {
|
||||
cp_code: 'YTO',
|
||||
cp_name: '圆通速递',
|
||||
waybill_type: 'STANDARD',
|
||||
branch_account_cols: {
|
||||
waybill_branch_account: {
|
||||
branch_name: '圆通转运中心',
|
||||
customer_code_list: {
|
||||
string: 'TB-CUST-026',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.getShopExpressList({
|
||||
shop_id: 26,
|
||||
cp_code: 'YTO',
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.data.platform_code, 'CAINIAO');
|
||||
assert.equal(result.data.list[0].sys_express_code, 'YTO_SYS');
|
||||
assert.equal(calls.getExpressProductTypeList, 1);
|
||||
assert.deepEqual(result.data.list[0].product_types, []);
|
||||
});
|
||||
|
||||
it('getShopExpressList 在 SF 且已有 TIMED-DELIVERY 时不应重复追加', async () => {
|
||||
const { service, ctx, calls } = createHarness();
|
||||
|
||||
@ -581,7 +512,6 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
assert.equal(result.data.list[0].accounts[0].services.length, 1);
|
||||
assert.equal(result.data.list[0].accounts[0].services[0].service_code, 'TIMED-DELIVERY');
|
||||
assert.equal(calls.getExpressProductTypeList, 0);
|
||||
assert.equal(result.data.list[0].product_types, undefined);
|
||||
});
|
||||
|
||||
it('getShopExpressList 在 DY 下应编排为与 PDD 一致的统一结构', async () => {
|
||||
@ -682,7 +612,6 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
wp_name: '圆通速递',
|
||||
sys_express_code: 'YTO_SYS',
|
||||
wp_type: 'STANDARD',
|
||||
product_types: [],
|
||||
accounts: [
|
||||
{
|
||||
branch_code: 'DY-BRANCH-001',
|
||||
@ -1111,7 +1040,6 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.deepEqual(result.data.list[0].accounts[0].services, []);
|
||||
assert.equal(calls.getExpressProductTypeList, 0);
|
||||
assert.equal(result.data.list[0].product_types, undefined);
|
||||
});
|
||||
|
||||
it('getShopExpressList 应仅在拼多多顺丰定时派送场景触发产品类型同步', async () => {
|
||||
@ -1272,7 +1200,6 @@ describe('test/app/service/systemMethods/index.test.js', () => {
|
||||
wp_name: '圆通速递',
|
||||
sys_express_code: 'YTO_SYS',
|
||||
wp_type: 'STANDARD',
|
||||
product_types: [],
|
||||
accounts: [
|
||||
{
|
||||
branch_code: 'CUST-001',
|
||||
|
||||
@ -1,208 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('node:crypto');
|
||||
const UserMethodService = require('../../../../app/service/systemMethods/user');
|
||||
const UserSystemService = require('../../../../app/service/systems/auth/user');
|
||||
|
||||
const SALT = '0123456789abcdef0123';
|
||||
const OLD_PASSWORD = 'old-pass';
|
||||
const OLD_HASH = crypto.createHash('sha256').update(OLD_PASSWORD + SALT).digest('hex');
|
||||
|
||||
function createSystemHarness(options = {}) {
|
||||
const calls = {
|
||||
findOne: [],
|
||||
update: [],
|
||||
cleared: [],
|
||||
};
|
||||
const findOneResults = [ ...(options.findOneResults || []) ];
|
||||
const ctx = {
|
||||
app: { config: {}, Sequelize: {} },
|
||||
userId: options.userId,
|
||||
user: options.user,
|
||||
logger: { error() {} },
|
||||
model: {
|
||||
Account: {
|
||||
async findOne(args) {
|
||||
calls.findOne.push(args);
|
||||
return findOneResults.shift();
|
||||
},
|
||||
async update(values, updateOptions) {
|
||||
calls.update.push({ values, updateOptions });
|
||||
return [ 1 ];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new UserSystemService(ctx);
|
||||
service.clearUserCache = async userId => {
|
||||
calls.cleared.push(userId);
|
||||
return true;
|
||||
};
|
||||
|
||||
return { service, calls };
|
||||
}
|
||||
|
||||
function createMethodHarness(changePassword) {
|
||||
const calls = [];
|
||||
const ctx = {
|
||||
app: { config: {}, Sequelize: {} },
|
||||
logger: { error() {} },
|
||||
service: {
|
||||
systems: {
|
||||
auth: {
|
||||
user: {
|
||||
async changePassword(data) {
|
||||
calls.push(data);
|
||||
return changePassword(data);
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new UserMethodService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
function assertNewPasswordHash(values, newPassword) {
|
||||
assert.equal(values.is_custom_password, 1);
|
||||
assert.match(values.salt, /^[0-9a-f]{20}$/);
|
||||
const expected = crypto.createHash('sha256').update(newPassword + values.salt).digest('hex');
|
||||
assert.equal(values.password_hash, expected);
|
||||
}
|
||||
|
||||
describe('test/app/service/systemMethods/user.changePassword.test.js', () => {
|
||||
it('首次自定义密码无需旧密码,并更新 is_custom_password', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 0 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.changePassword({ new_password: 'new-pass' });
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(result.code, 200);
|
||||
assert.deepEqual(result.data, { is_custom_password: 1 });
|
||||
assert.equal(calls.update.length, 1);
|
||||
assert.deepEqual(calls.update[0].updateOptions, { where: { id: 7 } });
|
||||
assertNewPasswordHash(calls.update[0].values, 'new-pass');
|
||||
assert.deepEqual(calls.cleared, [ 7 ]);
|
||||
});
|
||||
|
||||
it('已自定义密码后必须校验旧密码', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.changePassword({
|
||||
old_password: OLD_PASSWORD,
|
||||
new_password: 'new-pass',
|
||||
});
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(calls.update.length, 1);
|
||||
assertNewPasswordHash(calls.update[0].values, 'new-pass');
|
||||
});
|
||||
|
||||
it('已自定义密码但未传旧密码返回 400', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.changePassword({ new_password: 'new-pass' });
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 400);
|
||||
assert.equal(result.message, '请输入旧密码');
|
||||
assert.equal(calls.update.length, 0);
|
||||
});
|
||||
|
||||
it('旧密码错误返回 400', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.changePassword({
|
||||
old_password: 'wrong-pass',
|
||||
new_password: 'new-pass',
|
||||
});
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 400);
|
||||
assert.equal(result.message, '旧密码错误');
|
||||
assert.equal(calls.update.length, 0);
|
||||
});
|
||||
|
||||
it('支持旧密码/新密码驼峰别名', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.changePassword({
|
||||
oldPassword: OLD_PASSWORD,
|
||||
newPassword: 'new-pass',
|
||||
});
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(calls.update.length, 1);
|
||||
});
|
||||
|
||||
it('新密码为空返回 400', async () => {
|
||||
const { service, calls } = createSystemHarness({ userId: 7 });
|
||||
|
||||
const result = await service.changePassword({ new_password: ' ' });
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 400);
|
||||
assert.equal(result.message, '新密码不能为空');
|
||||
assert.equal(calls.findOne.length, 0);
|
||||
});
|
||||
|
||||
it('未登录返回 401,账号不存在返回 404', async () => {
|
||||
const anonymous = createSystemHarness({});
|
||||
const missing = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [ null ],
|
||||
});
|
||||
|
||||
const anonymousResult = await anonymous.service.changePassword({ new_password: 'new-pass' });
|
||||
const missingResult = await missing.service.changePassword({ new_password: 'new-pass' });
|
||||
|
||||
assert.equal(anonymousResult.code, 401);
|
||||
assert.equal(missingResult.code, 404);
|
||||
});
|
||||
|
||||
it('方法层应保留业务失败码', async () => {
|
||||
const { service, calls } = createMethodHarness(async () => ({
|
||||
success: false,
|
||||
data: null,
|
||||
code: 400,
|
||||
message: '旧密码错误',
|
||||
}));
|
||||
|
||||
const result = await service.changePassword({ old_password: 'bad', new_password: 'new-pass' });
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 400);
|
||||
assert.deepEqual(calls, [{ old_password: 'bad', new_password: 'new-pass' }]);
|
||||
});
|
||||
});
|
||||
@ -93,7 +93,6 @@ describe('test/app/service/systemMethods/user.getAccountInfo.test.js', () => {
|
||||
phone: '13800000000',
|
||||
email: 'demo@example.com',
|
||||
status: 1,
|
||||
is_custom_password: 0,
|
||||
last_login_at: new Date('2026-10-25T05:00:00.000Z'),
|
||||
created_at: new Date('2026-01-01T00:00:00.000Z'),
|
||||
updated_at: new Date('2026-10-25T05:00:00.000Z'),
|
||||
@ -110,7 +109,7 @@ describe('test/app/service/systemMethods/user.getAccountInfo.test.js', () => {
|
||||
assert.equal(calls[0].raw, true);
|
||||
assert.deepEqual(calls[0].attributes, [
|
||||
'id', 'username', 'real_name', 'phone', 'email',
|
||||
'status', 'is_custom_password', 'last_login_at', 'created_at', 'updated_at',
|
||||
'status', 'last_login_at', 'created_at', 'updated_at',
|
||||
]);
|
||||
for (const field of [ 'password_hash', 'salt', 'last_login_ip' ]) {
|
||||
assert.ok(!calls[0].attributes.includes(field));
|
||||
|
||||
@ -1,188 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { Op } = require('sequelize');
|
||||
const UserMethodService = require('../../../../app/service/systemMethods/user');
|
||||
const UserSystemService = require('../../../../app/service/systems/auth/user');
|
||||
|
||||
function createSystemHarness(options = {}) {
|
||||
const calls = {
|
||||
findOne: [],
|
||||
update: [],
|
||||
cleared: [],
|
||||
};
|
||||
const findOneResults = [ ...(options.findOneResults || []) ];
|
||||
const ctx = {
|
||||
app: { config: {}, Sequelize: { Op } },
|
||||
userId: options.userId,
|
||||
user: options.user,
|
||||
logger: { error() {} },
|
||||
model: {
|
||||
Account: {
|
||||
async findOne(args) {
|
||||
calls.findOne.push(args);
|
||||
return findOneResults.shift();
|
||||
},
|
||||
async update(values, updateOptions) {
|
||||
calls.update.push({ values, updateOptions });
|
||||
if (options.updateError) {
|
||||
throw options.updateError;
|
||||
}
|
||||
return [ 1 ];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new UserSystemService(ctx);
|
||||
service.clearUserCache = async userId => {
|
||||
calls.cleared.push(userId);
|
||||
return true;
|
||||
};
|
||||
|
||||
return { service, calls, ctx };
|
||||
}
|
||||
|
||||
function createMethodHarness(updateUsername) {
|
||||
const calls = [];
|
||||
const ctx = {
|
||||
app: { config: {}, Sequelize: {} },
|
||||
logger: { error() {} },
|
||||
service: {
|
||||
systems: {
|
||||
auth: {
|
||||
user: {
|
||||
async updateUsername(data) {
|
||||
calls.push(data);
|
||||
return updateUsername(data);
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
service: new UserMethodService(ctx),
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systemMethods/user.updateUsername.test.js', () => {
|
||||
it('应修改用户名并清理用户缓存', async () => {
|
||||
const { service, calls, ctx } = createSystemHarness({
|
||||
userId: 7,
|
||||
user: { username: 'old_name' },
|
||||
findOneResults: [
|
||||
{ id: 7, username: 'old_name' },
|
||||
null,
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.updateUsername({ username: ' new_name ' });
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(result.code, 200);
|
||||
assert.deepEqual(result.data, { id: 7, username: 'new_name' });
|
||||
assert.deepEqual(calls.update, [{
|
||||
values: { username: 'new_name' },
|
||||
updateOptions: { where: { id: 7 } },
|
||||
}]);
|
||||
assert.deepEqual(calls.cleared, [ 7 ]);
|
||||
assert.equal(calls.findOne[1].where.username, 'new_name');
|
||||
assert.equal(calls.findOne[1].where.id[Op.ne], 7);
|
||||
assert.equal(ctx.user.username, 'new_name');
|
||||
});
|
||||
|
||||
it('用户名未变化时直接返回成功且不更新', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, username: 'same_name' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.updateUsername({ username: 'same_name' });
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(result.code, 200);
|
||||
assert.equal(result.message, '用户名未变更');
|
||||
assert.equal(calls.update.length, 0);
|
||||
});
|
||||
|
||||
it('重名(排除自己)应返回 409', async () => {
|
||||
const { service, calls } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, username: 'old_name' },
|
||||
{ id: 9, username: 'taken_name' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.updateUsername({ username: 'taken_name' });
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 409);
|
||||
assert.equal(result.message, '用户名已存在');
|
||||
assert.equal(calls.update.length, 0);
|
||||
});
|
||||
|
||||
it('唯一索引冲突应兜底返回 409', async () => {
|
||||
const duplicateError = new Error('Duplicate entry');
|
||||
duplicateError.parent = { code: 'ER_DUP_ENTRY' };
|
||||
const { service } = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [
|
||||
{ id: 7, username: 'old_name' },
|
||||
null,
|
||||
],
|
||||
updateError: duplicateError,
|
||||
});
|
||||
|
||||
const result = await service.updateUsername({ username: 'new_name' });
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 409);
|
||||
assert.equal(result.message, '用户名已存在');
|
||||
});
|
||||
|
||||
it('用户名格式非法应返回 400', async () => {
|
||||
const { service, calls } = createSystemHarness({ userId: 7 });
|
||||
|
||||
const shortResult = await service.updateUsername({ username: 'ab' });
|
||||
const invalidResult = await service.updateUsername({ username: 'bad-name' });
|
||||
|
||||
assert.equal(shortResult.code, 400);
|
||||
assert.equal(invalidResult.code, 400);
|
||||
assert.equal(calls.findOne.length, 0);
|
||||
});
|
||||
|
||||
it('未登录返回 401,账号不存在返回 404', async () => {
|
||||
const anonymous = createSystemHarness({});
|
||||
const missing = createSystemHarness({
|
||||
userId: 7,
|
||||
findOneResults: [ null ],
|
||||
});
|
||||
|
||||
const anonymousResult = await anonymous.service.updateUsername({ username: 'new_name' });
|
||||
const missingResult = await missing.service.updateUsername({ username: 'new_name' });
|
||||
|
||||
assert.equal(anonymousResult.code, 401);
|
||||
assert.equal(missingResult.code, 404);
|
||||
});
|
||||
|
||||
it('方法层应保留业务失败码', async () => {
|
||||
const { service, calls } = createMethodHarness(async () => ({
|
||||
success: false,
|
||||
data: null,
|
||||
code: 409,
|
||||
message: '用户名已存在',
|
||||
}));
|
||||
|
||||
const result = await service.updateUsername({ username: 'taken_name' });
|
||||
|
||||
assert.equal(result.flag, 'failure');
|
||||
assert.equal(result.code, 409);
|
||||
assert.deepEqual(calls, [{ username: 'taken_name' }]);
|
||||
});
|
||||
});
|
||||
@ -1,130 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 分区编码唯一性(真实库集成测试)。
|
||||
*
|
||||
* 覆盖:同仓库同 zone_code 只允许一条未归档分区(归档分区不占用编码)。
|
||||
* 背景:uk_warehouse_zone_code 含 deleted_at,未删除行 deleted_at 为 NULL 不参与去重,
|
||||
* 同 zone_code 并存会导致其下库位 space_code 重复(如 E02-06-01-01 多条),
|
||||
* 盘点/库存按编码定位会命中历史行。
|
||||
*
|
||||
* 注意:本文件会启动 egg-mock app,需单独运行(与其它同样启动 app 的用例在同一 mocha 进程内
|
||||
* 会触发 egg loader "can't overwrite property" 冲突,为仓库既有约束,如 return_received 系列)。
|
||||
*/
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const mm = require('egg-mock');
|
||||
|
||||
const REAL_DB_ENABLED = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1';
|
||||
const runner = REAL_DB_ENABLED ? describe : describe.skip;
|
||||
|
||||
const TEST_WAREHOUSE_ID = 100000;
|
||||
|
||||
runner('test/app/service/systems/location_zone.zoneCodeUnique.test.js(分区编码唯一性)', function() {
|
||||
this.timeout(120000);
|
||||
|
||||
let app;
|
||||
let ctx;
|
||||
const createdZoneIds = [];
|
||||
|
||||
before(async () => {
|
||||
app = mm.app({
|
||||
baseDir: process.cwd(),
|
||||
env: 'local',
|
||||
clean: false,
|
||||
cache: false,
|
||||
});
|
||||
await app.ready();
|
||||
ctx = app.createAnonymousContext();
|
||||
ctx.user = { id: 4, store_id: TEST_WAREHOUSE_ID, employees_name: '阿猫' };
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
for (const zoneId of createdZoneIds) {
|
||||
await ctx.model.LocationZone.destroy({ where: { id: zoneId }, force: true });
|
||||
}
|
||||
await app.close();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mm.restore();
|
||||
});
|
||||
|
||||
/**
|
||||
* 构造创建仓库类型分区的入参(warehouse 类型无需父元素,编码必填)。
|
||||
*
|
||||
* @param {string} zoneCode 分区编码(1-5 位大写字母/数字)。
|
||||
* @return {Object} createZone 入参。
|
||||
*/
|
||||
function buildWarehouseZonePayload(zoneCode) {
|
||||
return {
|
||||
zone_type: 'warehouse',
|
||||
zone_name: `测试仓_${zoneCode}`,
|
||||
zone_code: zoneCode,
|
||||
parent_id: 0,
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0,
|
||||
length: 100,
|
||||
width: 100,
|
||||
height: 100,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成当前仓库未占用的随机编码(1-5 位大写字母/数字)。
|
||||
*
|
||||
* @return {string} 分区编码。
|
||||
*/
|
||||
function uniqueZoneCode() {
|
||||
const suffix = String(Date.now()).slice(-4);
|
||||
return `Z${suffix}`.slice(0, 5).toUpperCase();
|
||||
}
|
||||
|
||||
it('同仓库同 zone_code 重复创建报错;归档后编码可复用', async () => {
|
||||
const zoneCode = uniqueZoneCode();
|
||||
|
||||
const created = await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload(zoneCode));
|
||||
assert.equal(created.success, true);
|
||||
const firstZoneId = Number(created.data.id);
|
||||
assert.ok(firstZoneId > 0, '前置:分区应创建成功');
|
||||
createdZoneIds.push(firstZoneId);
|
||||
|
||||
// 同编码再次创建 → 拒绝
|
||||
await assert.rejects(async () => {
|
||||
await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload(zoneCode));
|
||||
}, error => /分区编码已存在/.test(error.message));
|
||||
|
||||
// 编码格式校验(沿用规则:1-5 位大写字母/数字)
|
||||
await assert.rejects(async () => {
|
||||
await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload('bad-code'));
|
||||
}, error => /编码必须是1-5位大写字母或数字/.test(error.message));
|
||||
|
||||
// 归档(软删除)后同编码可再次创建:归档行不占用编码
|
||||
await ctx.model.LocationZone.destroy({ where: { id: firstZoneId } });
|
||||
const recreated = await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload(zoneCode));
|
||||
assert.equal(recreated.success, true);
|
||||
assert.notEqual(Number(recreated.data.id), firstZoneId, '归档后新建应为新关系');
|
||||
createdZoneIds.push(Number(recreated.data.id));
|
||||
});
|
||||
|
||||
it('更新分区编码:改为已占用编码报错,改回自身编码不报错', async () => {
|
||||
const codeA = uniqueZoneCode();
|
||||
const zoneA = await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload(codeA));
|
||||
createdZoneIds.push(Number(zoneA.data.id));
|
||||
|
||||
// 另建一个分区占位
|
||||
const codeB = `Y${String(Date.now()).slice(-4)}`.slice(0, 5).toUpperCase();
|
||||
const zoneB = await ctx.service.systems.locationZone.createZone(buildWarehouseZonePayload(codeB));
|
||||
createdZoneIds.push(Number(zoneB.data.id));
|
||||
|
||||
// 把 A 改成 B 的编码 → 报错
|
||||
await assert.rejects(async () => {
|
||||
await ctx.service.systems.locationZone.updateZone(Number(zoneA.data.id), { zone_code: codeB });
|
||||
}, error => /分区编码已存在/.test(error.message));
|
||||
|
||||
// 改回自身编码 → 正常
|
||||
const updated = await ctx.service.systems.locationZone.updateZone(Number(zoneA.data.id), { zone_code: codeA });
|
||||
assert.ok(updated, '自身编码不应被判为冲突');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
x
Reference in New Issue
Block a user