- storeWarehouse.store.saveApiConfig:新增 resolveContractApiInterfaceType, interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)自动映射为 2(OPEN_API 货主开放接口)落库, 不再要求当前主体为仓库(货主可维护自身签约关系下的接口配置) - callback_url 不再取入参(含 callbackUrl 别名),统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空) - storeWarehouse.store.listApiConfig:interface_type_id 过滤同步映射(传 3 按 2 查询) - 文档:methods/system.json 升级 0.3.350、methods/changes/system.json 变更记录、docs/openapi-callback-events.md 回调地址来源说明 - 测试:saveApiConfig 新增 4 条用例(3→2 落库、忽略入参回调地址、默认值未配置、货主主体可保存、缺失类型 404),listApiConfig 新增 1 条过滤映射用例 同时提交工作区其余在制品改动: - waybill:移除 wms_order_express_trace 模型并新增 drop 迁移,轨迹查询/取号/打印链路调整 - order:订单 SN 编码(order_item_sn / order_item_sn_log / sn_code_rule、has_sn_item 回填迁移),pendingOrder/recheckOrder/wave/base 调整 - express_platform、order_async、order_export、order_storage_allocation、storage.report、stock_store 配套修复 - lib:新增 jd_client,调整 qimen_client、callback_functions 及配套测试 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
714 lines
24 KiB
JavaScript
714 lines
24 KiB
JavaScript
'use strict';
|
||
|
||
const OrderBaseService = require('../systemMethods/order/base');
|
||
|
||
/** SN 主表状态:复核提交即视为已核验并已随订单发出 */
|
||
const SN_STATUS_VERIFIED = 'VERIFIED';
|
||
/** SN 主表状态:已绑定待核验(可被复核提交升级为 VERIFIED) */
|
||
const SN_STATUS_BOUND = 'BOUND';
|
||
/** 核验通过 */
|
||
const VERIFY_STATUS_PASS = 'PASS';
|
||
/** 流水表中代表「已随订单发出」的变更后状态,用于判断 SN 是否已经发过 */
|
||
const SHIPPED_SN_STATUS_LIST = [ 'VERIFIED', 'REISSUED' ];
|
||
/** 复核提交写入的流水动作类型 */
|
||
const RECHECK_LOG_ACTION = 'VERIFY';
|
||
/** SN 码最大长度(与 wms_order_item_sn.sn_code VARCHAR(512) 保持一致,支持链接/二维码内容) */
|
||
const MAX_SN_CODE_LENGTH = 512;
|
||
|
||
/**
|
||
* 订单明细 SN 服务。
|
||
* 负责复核提交环节的 SN 入参归一化、数量与占用校验,以及 SN 主表/流水表落库。
|
||
*/
|
||
class OrderItemSnService extends OrderBaseService {
|
||
/**
|
||
* 归一化复核入参中的 SN 提交内容。
|
||
*
|
||
* 统一只有一种格式:sn_map = { stock_id: [ sn_code, ... ] }(值也兼容逗号/换行分隔的字符串),
|
||
* 即「商品(仓库商品ID)→ SN 码列表」一一对应,不再按订单明细ID提交。
|
||
* 单个 SN 码最长 512 字符(支持链接/二维码内容)。
|
||
*
|
||
* @param {Object} payload 复核请求体。
|
||
* @return {Map<string, string[]>} 仓库商品ID键 -> SN 码列表。
|
||
*/
|
||
normalizeRecheckSnPayload(payload = {}) {
|
||
const requestData = this.isPlainObject(payload) ? payload : {};
|
||
const codesByStock = new Map();
|
||
const snMap = requestData.sn_map ?? requestData.snMap;
|
||
if (!this.isPlainObject(snMap)) {
|
||
return codesByStock;
|
||
}
|
||
|
||
for (const [ rawStockKey, rawCodes ] of Object.entries(snMap)) {
|
||
const stockKey = this.normalizeSnStockKey(rawStockKey);
|
||
if (!stockKey) {
|
||
continue;
|
||
}
|
||
const codeList = Array.isArray(rawCodes) ? rawCodes : this.splitSnCodeText(rawCodes);
|
||
const codes = codeList
|
||
.map(code => this.normalizeSnCode(code))
|
||
.filter(code => !!code);
|
||
for (const code of codes) {
|
||
if (code.length > MAX_SN_CODE_LENGTH) {
|
||
throw new Error(
|
||
`SN码长度不能超过${MAX_SN_CODE_LENGTH}个字符:${code.slice(0, 32)}…(共${code.length}字符)`
|
||
);
|
||
}
|
||
}
|
||
if (codes.length === 0) {
|
||
continue;
|
||
}
|
||
if (!codesByStock.has(stockKey)) {
|
||
codesByStock.set(stockKey, []);
|
||
}
|
||
codesByStock.get(stockKey).push(...codes);
|
||
}
|
||
|
||
return codesByStock;
|
||
}
|
||
|
||
/**
|
||
* 判断请求体是否提交了 SN 码内容(非空才算提交)。
|
||
* @param {Object} payload 复核请求体。
|
||
* @return {boolean} 是否提交了 SN 码。
|
||
*/
|
||
hasRecheckSnPayload(payload = {}) {
|
||
const codesByStock = this.normalizeRecheckSnPayload(payload);
|
||
for (const codes of codesByStock.values()) {
|
||
if (codes.length > 0) {
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 复核提交时校验并写入 SN 码。
|
||
* 校验规则:
|
||
* 1. SN 订单必须提交 SN 码,且每个序列号管理商品(stock_id)的 SN 数量必须等于该商品在订单内的 plan_qty 合计;
|
||
* 2. 非序列号管理商品不允许提交 SN 码;提交的 stock_id 必须属于当前订单;
|
||
* 3. 同一批提交内 SN 不可重复;
|
||
* 4. SN 若已绑定其它订单/明细,或流水显示已随其它订单发出,则判定为已发过,直接失败;
|
||
* 5. 同一订单同一明细重复提交视为幂等,不重复写入。
|
||
* @param {Object} params 参数。
|
||
* @param {Object} params.order 订单主表行(需包含 id 与 has_sn_item)。
|
||
* @param {number|string} params.warehouseId 仓库ID。
|
||
* @param {Object} params.payload 复核请求体,含 sn_map(stock_id -> SN 列表)。
|
||
* @param {Object} [params.operator] 操作人。
|
||
* @param {Date} [params.now] 复核时间。
|
||
* @param {Object} [params.transaction] Sequelize 事务,与复核状态更新共用。
|
||
* @return {Promise<{ sn_count: number, sn_item_count: number, sn_created_count: number, sn_reused_count: number }>}
|
||
* SN 提交汇总:SN 总数、涉及明细数、新增写入数、幂等复用数。
|
||
*/
|
||
async verifyRecheckSnList({ order = {}, warehouseId, payload = {}, operator = {}, now = new Date(), transaction }) {
|
||
const orderId = Number(order && order.id);
|
||
const normalizedWarehouseId = Number(warehouseId);
|
||
const storeId = Number(order && order.store_id) || 0;
|
||
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error('订单ID不合法,无法校验SN码');
|
||
}
|
||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
throw new Error('仓库ID不合法,无法校验SN码');
|
||
}
|
||
|
||
const codesByStock = this.normalizeRecheckSnPayload(payload);
|
||
const isSnOrder = this.isSnOrderRow(order);
|
||
const submittedCodeCount = this.countSnCodes(codesByStock);
|
||
|
||
if (submittedCodeCount === 0) {
|
||
if (isSnOrder) {
|
||
throw new Error('订单包含序列号管理商品,提交复核时必须上传全部SN码');
|
||
}
|
||
return { sn_count: 0, sn_item_count: 0, sn_created_count: 0, sn_reused_count: 0 };
|
||
}
|
||
|
||
const items = await this.loadOrderItemsForSn(orderId, normalizedWarehouseId, transaction);
|
||
const snStockIdSet = await this.loadSnStockIdSet(items, normalizedWarehouseId);
|
||
const stockItemMap = this.buildSnStockItemMap(items, snStockIdSet);
|
||
|
||
if (isSnOrder && stockItemMap.size === 0) {
|
||
throw new Error('订单序列号商品信息缺失,无法校验SN码,请检查商品是否启用序列号管理');
|
||
}
|
||
|
||
this.assertSnStockCodesMatched({ stockItemMap, codesByStock });
|
||
const codesByItem = this.mapStockCodesToOrderItems({ stockItemMap, codesByStock });
|
||
|
||
const allCodes = [];
|
||
for (const codes of codesByItem.values()) {
|
||
allCodes.push(...codes);
|
||
}
|
||
this.assertSnCodesUnique(allCodes);
|
||
|
||
const writeResult = await this.persistRecheckSn({
|
||
orderId,
|
||
warehouseId: normalizedWarehouseId,
|
||
storeId,
|
||
codesByItem,
|
||
allCodes,
|
||
operator,
|
||
now,
|
||
transaction,
|
||
});
|
||
|
||
return {
|
||
sn_count: allCodes.length,
|
||
sn_item_count: codesByItem.size,
|
||
sn_created_count: writeResult.createdCount,
|
||
sn_reused_count: writeResult.reusedCount,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 判断订单是否含序列号管理商品。
|
||
* @param {Object} order 订单主表行。
|
||
* @return {boolean} 是否 SN 订单。
|
||
*/
|
||
isSnOrderRow(order = {}) {
|
||
return String(order && order.has_sn_item || '').trim().toUpperCase() === 'Y';
|
||
}
|
||
|
||
/**
|
||
* 清洗单个 SN 码。
|
||
* @param {*} rawCode 原始 SN 码。
|
||
* @return {string} 清洗后的 SN 码,空值返回空串。
|
||
*/
|
||
normalizeSnCode(rawCode) {
|
||
if (rawCode === undefined || rawCode === null) {
|
||
return '';
|
||
}
|
||
return String(rawCode).trim();
|
||
}
|
||
|
||
/**
|
||
* 把 SN 文本按换行/逗号/分号/空格拆分为 SN 数组。
|
||
* @param {*} rawText 原始文本。
|
||
* @return {string[]} SN 数组。
|
||
*/
|
||
splitSnCodeText(rawText) {
|
||
if (rawText === undefined || rawText === null) {
|
||
return [];
|
||
}
|
||
if (Array.isArray(rawText)) {
|
||
return rawText.map(code => this.normalizeSnCode(code)).filter(Boolean);
|
||
}
|
||
return String(rawText)
|
||
.split(/[\s,;]+/)
|
||
.map(code => this.normalizeSnCode(code))
|
||
.filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* 归一化订单明细主键,统一为字符串键,避免数字/字符串混用导致分组错乱。
|
||
* @param {*} rawItemKey 明细ID原始值。
|
||
* @return {string} 明细ID键,非法返回空串。
|
||
*/
|
||
normalizeSnItemKey(rawItemKey) {
|
||
return this.normalizeSnStockKey(rawItemKey);
|
||
}
|
||
|
||
/**
|
||
* 归一化仓库商品ID(stock_id)键,统一为字符串键。
|
||
* @param {*} rawStockKey 仓库商品ID原始值。
|
||
* @return {string} 仓库商品ID键,非法返回空串。
|
||
*/
|
||
normalizeSnStockKey(rawStockKey) {
|
||
if (rawStockKey === undefined || rawStockKey === null) {
|
||
return '';
|
||
}
|
||
const stockKey = String(rawStockKey).trim();
|
||
if (!stockKey) {
|
||
return '';
|
||
}
|
||
return /^\d+$/.test(stockKey) ? String(Number(stockKey)) : stockKey;
|
||
}
|
||
|
||
/**
|
||
* 统计按明细分组的 SN 总数。
|
||
* @param {Map<string, string[]>} codesByItem 按明细分组的 SN。
|
||
* @return {number} SN 总数。
|
||
*/
|
||
countSnCodes(codesByItem) {
|
||
let total = 0;
|
||
for (const codes of codesByItem.values()) {
|
||
total += codes.length;
|
||
}
|
||
return total;
|
||
}
|
||
|
||
/**
|
||
* 读取订单明细。
|
||
* @param {number} orderId 订单ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} [transaction] Sequelize 事务。
|
||
* @return {Promise<Object[]>} 订单明细列表。
|
||
*/
|
||
async loadOrderItemsForSn(orderId, warehouseId, transaction) {
|
||
const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId);
|
||
const rows = await orderItemsModel.findAll({
|
||
where: { order_id: orderId },
|
||
attributes: [ 'id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
return Array.isArray(rows) ? rows : [];
|
||
}
|
||
|
||
/**
|
||
* 读取明细对应商品的序列号管理标记,返回序列号管理商品ID集合。
|
||
* @param {Object[]} items 订单明细。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Set<number>>} 启用了序列号管理的仓库商品ID集合。
|
||
*/
|
||
async loadSnStockIdSet(items, warehouseId) {
|
||
const { ctx } = this;
|
||
const snStockIdSet = new Set();
|
||
const stockIds = [ ...new Set(
|
||
(items || []).map(item => Number(item.stock_id)).filter(id => Number.isInteger(id) && id > 0)
|
||
) ];
|
||
|
||
if (stockIds.length === 0) {
|
||
return snStockIdSet;
|
||
}
|
||
|
||
const stockModel = ctx.model && ctx.model.StockWarehouse;
|
||
if (!stockModel) {
|
||
throw new Error('商品仓库模型不存在,无法校验SN码');
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
// paranoid:false 保证商品被软删后仍能读到 is_sn_mgmt,避免历史订单无法校验 SN
|
||
const stockRows = await stockModel.findAll({
|
||
where: {
|
||
id: { [Op.in]: stockIds },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'is_sn_mgmt' ],
|
||
raw: true,
|
||
paranoid: false,
|
||
});
|
||
|
||
for (const row of (stockRows || [])) {
|
||
if (String(row.is_sn_mgmt || '').trim().toUpperCase() !== 'Y') {
|
||
continue;
|
||
}
|
||
const stockId = Number(row.id);
|
||
if (Number.isInteger(stockId) && stockId > 0) {
|
||
snStockIdSet.add(stockId);
|
||
}
|
||
}
|
||
|
||
return snStockIdSet;
|
||
}
|
||
|
||
/**
|
||
* 按序列号管理商品(stock_id)聚合订单明细。
|
||
* @param {Object[]} items 订单明细。
|
||
* @param {Set<number>} snStockIdSet 序列号管理商品ID集合。
|
||
* @return {Map<string, Object[]>} 仓库商品ID键 -> 该商品的订单明细(按明细ID升序)。
|
||
*/
|
||
buildSnStockItemMap(items, snStockIdSet) {
|
||
const stockItemMap = new Map();
|
||
const sortedItems = (Array.isArray(items) ? items : [])
|
||
.slice()
|
||
.sort((a, b) => Number(a && a.id || 0) - Number(b && b.id || 0));
|
||
|
||
for (const item of sortedItems) {
|
||
if (!snStockIdSet || !snStockIdSet.has(Number(item && item.stock_id))) {
|
||
continue;
|
||
}
|
||
const stockKey = this.normalizeSnStockKey(item.stock_id);
|
||
if (!stockKey) {
|
||
continue;
|
||
}
|
||
if (!stockItemMap.has(stockKey)) {
|
||
stockItemMap.set(stockKey, []);
|
||
}
|
||
stockItemMap.get(stockKey).push(item);
|
||
}
|
||
|
||
return stockItemMap;
|
||
}
|
||
|
||
/**
|
||
* 校验提交的 SN 是否按商品齐套。
|
||
* @param {Object} params 参数。
|
||
* @param {Map<string, Object[]>} params.stockItemMap 序列号管理商品 -> 明细。
|
||
* @param {Map<string, string[]>} params.codesByStock 提交的 SN(商品ID -> SN 列表)。
|
||
*/
|
||
assertSnStockCodesMatched({ stockItemMap, codesByStock }) {
|
||
for (const [ stockKey, codes ] of codesByStock.entries()) {
|
||
const items = stockItemMap.get(stockKey);
|
||
if (!items || items.length === 0) {
|
||
throw new Error(`提交的SN码对应商品不在订单中或未启用序列号管理:stock_id=${stockKey}`);
|
||
}
|
||
const label = this.buildSnItemLabel(items[0]);
|
||
const requiredQty = this.sumSnItemPlanQty(items);
|
||
if (requiredQty <= 0) {
|
||
throw new Error(`商品[${label}]数量异常,无法校验SN码`);
|
||
}
|
||
if (codes.length !== requiredQty) {
|
||
throw new Error(`商品[${label}]需提交${requiredQty}个SN码,实际提交${codes.length}个`);
|
||
}
|
||
}
|
||
|
||
for (const [ stockKey, items ] of stockItemMap.entries()) {
|
||
if (codesByStock.has(stockKey)) {
|
||
continue;
|
||
}
|
||
const requiredQty = this.sumSnItemPlanQty(items);
|
||
// 数量为 0 的序列号商品不需要提交 SN,避免历史脏数据阻塞复核
|
||
if (requiredQty <= 0) {
|
||
continue;
|
||
}
|
||
throw new Error(
|
||
`商品[${this.buildSnItemLabel(items[0])}]需提交${requiredQty}个SN码,实际提交0个`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 汇总同一商品下所有明细的 plan_qty(仅统计合法正整数)。
|
||
* @param {Object[]} items 同一商品的订单明细。
|
||
* @return {number} 需要的 SN 总数。
|
||
*/
|
||
sumSnItemPlanQty(items) {
|
||
let total = 0;
|
||
for (const item of (Array.isArray(items) ? items : [])) {
|
||
const planQty = Number(item && item.plan_qty);
|
||
if (Number.isInteger(planQty) && planQty > 0) {
|
||
total += planQty;
|
||
}
|
||
}
|
||
return total;
|
||
}
|
||
|
||
/**
|
||
* 把「商品 -> SN 列表」按明细 plan_qty 顺序拆分到具体订单明细,供落库使用。
|
||
* @param {Object} params 参数。
|
||
* @param {Map<string, Object[]>} params.stockItemMap 序列号管理商品 -> 明细。
|
||
* @param {Map<string, string[]>} params.codesByStock 提交的 SN(商品ID -> SN 列表)。
|
||
* @return {Map<string, string[]>} 订单明细ID键 -> SN 列表。
|
||
*/
|
||
mapStockCodesToOrderItems({ stockItemMap, codesByStock }) {
|
||
const codesByItem = new Map();
|
||
|
||
for (const [ stockKey, codes ] of codesByStock.entries()) {
|
||
const items = stockItemMap.get(stockKey) || [];
|
||
let cursor = 0;
|
||
|
||
for (const item of items) {
|
||
const planQty = Number(item && item.plan_qty);
|
||
if (!Number.isInteger(planQty) || planQty <= 0) {
|
||
continue;
|
||
}
|
||
const itemCodes = codes.slice(cursor, cursor + planQty);
|
||
cursor += planQty;
|
||
if (itemCodes.length === 0) {
|
||
continue;
|
||
}
|
||
const itemKey = this.normalizeSnItemKey(item.id);
|
||
if (!itemKey) {
|
||
continue;
|
||
}
|
||
codesByItem.set(itemKey, itemCodes);
|
||
}
|
||
|
||
if (cursor < codes.length) {
|
||
const tailItem = items[items.length - 1];
|
||
const tailKey = tailItem ? this.normalizeSnItemKey(tailItem.id) : '';
|
||
if (tailKey) {
|
||
const merged = (codesByItem.get(tailKey) || []).concat(codes.slice(cursor));
|
||
codesByItem.set(tailKey, merged);
|
||
}
|
||
}
|
||
}
|
||
|
||
return codesByItem;
|
||
}
|
||
|
||
/**
|
||
* 校验同一批提交内 SN 不重复。
|
||
* @param {string[]} allCodes 全部 SN。
|
||
*/
|
||
assertSnCodesUnique(allCodes) {
|
||
const seen = new Set();
|
||
const duplicated = new Set();
|
||
for (const code of allCodes) {
|
||
if (seen.has(code)) {
|
||
duplicated.add(code);
|
||
}
|
||
seen.add(code);
|
||
}
|
||
if (duplicated.size > 0) {
|
||
const sample = Array.from(duplicated).slice(0, 5).join('、');
|
||
throw new Error(`SN码重复提交:${sample}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成明细展示文案,优先商品编码 + 名称。
|
||
* @param {Object} item 订单明细。
|
||
* @return {string} 展示文案。
|
||
*/
|
||
buildSnItemLabel(item = {}) {
|
||
const code = String(item.item_code || '').trim();
|
||
const name = String(item.item_name || '').trim();
|
||
if (code && name) {
|
||
return `${code} ${name}`;
|
||
}
|
||
return code || name || String(item.id || '');
|
||
}
|
||
|
||
/**
|
||
* 校验 SN 是否已发过并写入 SN 主表与流水表。
|
||
* @param {Object} params 参数。
|
||
* @param {number} params.orderId 订单ID。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {number} [params.storeId] 货主ID(从订单冗余写入,便于按货主隔离查询)。
|
||
* @param {Map<string, string[]>} params.codesByItem 按明细分组的 SN。
|
||
* @param {string[]} params.allCodes 全部 SN。
|
||
* @param {Object} [params.operator] 操作人。
|
||
* @param {Date} params.now 复核时间。
|
||
* @param {Object} [params.transaction] Sequelize 事务。
|
||
* @return {Promise<{ createdCount: number, reusedCount: number }>} 新增写入数与此前已绑定同明细的幂等复用数。
|
||
*/
|
||
async persistRecheckSn({ orderId, warehouseId, storeId = 0, codesByItem, allCodes, operator = {}, now = new Date(), transaction }) {
|
||
const { ctx } = this;
|
||
const { Op } = this.app.Sequelize;
|
||
const orderItemSnModel = ctx.model && ctx.model.OrderItemSn;
|
||
const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog;
|
||
|
||
if (!orderItemSnModel || !orderItemSnLogModel) {
|
||
throw new Error('订单SN模型不存在,无法写入SN码');
|
||
}
|
||
|
||
const itemIdByCode = new Map();
|
||
for (const [ itemKey, codes ] of codesByItem.entries()) {
|
||
for (const code of codes) {
|
||
itemIdByCode.set(code, Number(itemKey));
|
||
}
|
||
}
|
||
|
||
const lockOption = transaction && transaction.LOCK ? { lock: transaction.LOCK.UPDATE } : {};
|
||
const existingRows = await orderItemSnModel.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
sn_code: { [Op.in]: allCodes },
|
||
},
|
||
attributes: [ 'id', 'order_id', 'order_item_id', 'sn_code', 'sn_status' ],
|
||
raw: true,
|
||
...lockOption,
|
||
transaction,
|
||
});
|
||
|
||
const existingByCode = new Map();
|
||
for (const row of existingRows || []) {
|
||
existingByCode.set(String(row.sn_code), row);
|
||
}
|
||
|
||
const createRows = [];
|
||
const upgradeRows = [];
|
||
let reusedCount = 0;
|
||
|
||
for (const code of allCodes) {
|
||
const existing = existingByCode.get(code);
|
||
if (!existing) {
|
||
createRows.push(code);
|
||
continue;
|
||
}
|
||
|
||
const sameOrder = Number(existing.order_id) === orderId;
|
||
const sameItem = Number(existing.order_item_id) === Number(itemIdByCode.get(code));
|
||
const existingStatus = String(existing.sn_status || '').trim().toUpperCase();
|
||
|
||
if (!sameOrder || !sameItem) {
|
||
throw new Error(`SN码[${code}]已被其他订单占用,不可重复使用`);
|
||
}
|
||
if (existingStatus === SN_STATUS_VERIFIED) {
|
||
reusedCount += 1;
|
||
continue;
|
||
}
|
||
if (existingStatus === SN_STATUS_BOUND) {
|
||
upgradeRows.push(existing);
|
||
continue;
|
||
}
|
||
throw new Error(`SN码[${code}]状态为${existingStatus || 'UNKNOWN'},不可用于当前订单复核`);
|
||
}
|
||
|
||
const createCodeSet = new Set(createRows);
|
||
await this.assertSnCodesNotShipped({
|
||
warehouseId,
|
||
allCodes: allCodes.filter(code => createCodeSet.has(code)),
|
||
orderId,
|
||
transaction,
|
||
});
|
||
|
||
const normalizedStoreId = Number(storeId) > 0 ? Number(storeId) : null;
|
||
const createdRows = [];
|
||
if (createRows.length > 0) {
|
||
const payload = createRows.map(code => ({
|
||
warehouse_id: warehouseId,
|
||
store_id: normalizedStoreId,
|
||
order_id: orderId,
|
||
order_item_id: itemIdByCode.get(code),
|
||
sn_code: code,
|
||
sn_status: SN_STATUS_VERIFIED,
|
||
verify_status: VERIFY_STATUS_PASS,
|
||
bound_at: now,
|
||
verified_at: now,
|
||
version: 1,
|
||
created_at: now,
|
||
updated_at: now,
|
||
}));
|
||
|
||
let instances;
|
||
try {
|
||
instances = await orderItemSnModel.bulkCreate(payload, { transaction });
|
||
} catch (error) {
|
||
if (this.isDuplicateKeyError(error)) {
|
||
throw new Error('SN码已被占用,请核对后重新提交');
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
for (const instance of instances || []) {
|
||
createdRows.push({
|
||
sn_id: instance.id,
|
||
order_item_id: Number(instance.order_item_id),
|
||
sn_code: String(instance.sn_code),
|
||
});
|
||
}
|
||
}
|
||
|
||
if (upgradeRows.length > 0) {
|
||
await orderItemSnModel.update({
|
||
sn_status: SN_STATUS_VERIFIED,
|
||
verify_status: VERIFY_STATUS_PASS,
|
||
verified_at: now,
|
||
updated_at: now,
|
||
version: this.app.Sequelize.literal('version + 1'),
|
||
...(normalizedStoreId !== null && { store_id: normalizedStoreId }),
|
||
}, {
|
||
where: { id: { [Op.in]: upgradeRows.map(row => row.id) } },
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
const operatorId = this.normalizeSnOperatorId(operator);
|
||
const logRows = [
|
||
...createdRows.map(row => ({
|
||
warehouse_id: warehouseId,
|
||
sn_id: row.sn_id,
|
||
order_id: orderId,
|
||
order_item_id: row.order_item_id,
|
||
sn_code: row.sn_code,
|
||
from_sn_status: null,
|
||
to_sn_status: SN_STATUS_VERIFIED,
|
||
verify_status: VERIFY_STATUS_PASS,
|
||
action_type: RECHECK_LOG_ACTION,
|
||
remark: '复核提交SN核验',
|
||
operator_id: operatorId,
|
||
operated_at: now,
|
||
created_at: now,
|
||
updated_at: now,
|
||
})),
|
||
...upgradeRows.map(row => ({
|
||
warehouse_id: warehouseId,
|
||
sn_id: row.id,
|
||
order_id: orderId,
|
||
order_item_id: Number(row.order_item_id),
|
||
sn_code: String(row.sn_code),
|
||
from_sn_status: SN_STATUS_BOUND,
|
||
to_sn_status: SN_STATUS_VERIFIED,
|
||
verify_status: VERIFY_STATUS_PASS,
|
||
action_type: RECHECK_LOG_ACTION,
|
||
remark: '复核提交SN核验',
|
||
operator_id: operatorId,
|
||
operated_at: now,
|
||
created_at: now,
|
||
updated_at: now,
|
||
})),
|
||
];
|
||
|
||
if (logRows.length > 0) {
|
||
await orderItemSnLogModel.bulkCreate(logRows, { transaction });
|
||
}
|
||
|
||
return { createdCount: createdRows.length, reusedCount };
|
||
}
|
||
|
||
/**
|
||
* 校验 SN 是否已经随其它订单发出(流水存在 VERIFIED/REISSUED 记录)。
|
||
* @param {Object} params 参数。
|
||
* @param {number} params.warehouseId 仓库ID。
|
||
* @param {string[]} params.allCodes 待校验 SN。
|
||
* @param {number} params.orderId 当前订单ID。
|
||
* @param {Object} [params.transaction] Sequelize 事务。
|
||
* @return {Promise<void>} 无返回值,命中已发货 SN 时抛错。
|
||
*/
|
||
async assertSnCodesNotShipped({ warehouseId, allCodes, orderId, transaction }) {
|
||
if (!Array.isArray(allCodes) || allCodes.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const { ctx } = this;
|
||
const { Op } = this.app.Sequelize;
|
||
const orderItemSnLogModel = ctx.model && ctx.model.OrderItemSnLog;
|
||
if (!orderItemSnLogModel) {
|
||
throw new Error('订单SN流水模型不存在,无法校验SN码');
|
||
}
|
||
|
||
const shippedLogs = await orderItemSnLogModel.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
sn_code: { [Op.in]: allCodes },
|
||
to_sn_status: { [Op.in]: SHIPPED_SN_STATUS_LIST },
|
||
order_id: { [Op.ne]: orderId },
|
||
},
|
||
attributes: [ 'sn_code', 'order_id', 'to_sn_status' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (Array.isArray(shippedLogs) && shippedLogs.length > 0) {
|
||
const first = shippedLogs[0];
|
||
throw new Error(
|
||
`SN码[${first.sn_code}]已随订单[${first.order_id}]发货,不可重复使用`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 归一化操作人ID,非数字操作人(如 system)落空,避免 BIGINT 写入失败。
|
||
* @param {Object} operator 操作人。
|
||
* @return {number|null} 操作人ID。
|
||
*/
|
||
normalizeSnOperatorId(operator = {}) {
|
||
const rawId = String(operator && operator.id || '').trim();
|
||
if (!/^\d+$/.test(rawId)) {
|
||
return null;
|
||
}
|
||
const parsed = Number(rawId);
|
||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
|
||
}
|
||
|
||
/**
|
||
* 判断是否唯一键冲突错误。
|
||
* @param {Object} error 错误对象。
|
||
* @return {boolean} 是否唯一键冲突。
|
||
*/
|
||
isDuplicateKeyError(error) {
|
||
if (!error) {
|
||
return false;
|
||
}
|
||
if (error.name === 'SequelizeUniqueConstraintError') {
|
||
return true;
|
||
}
|
||
return Boolean(error.parent && error.parent.code === 'ER_DUP_ENTRY');
|
||
}
|
||
}
|
||
|
||
module.exports = OrderItemSnService;
|