feat(backend): 入库单/出库单全流程与 WMS 对接

- 入库单、出库单控制器与模型(状态流转、审核、驳回换号、作废、删除约束)
- 明细共用 stock_items:应/已数量、行级库存类型 ZP/CC、明细锁定
- lib/wms:单据类型常量(orderTypes)、奇门/openapi 客户端(qimenClient)、签名(sign)
- 库存联动:utils/stock.js、utils/completeInbound.js(入库完成加库存,幂等)
- 驳回换号:utils/rejectBillNo.js;旧 orders 模块同步调整
- 相关迁移:入库单 WMS 字段/审核/推送结果、明细计划与实际数量、单据类型落 WMS 编码、出库库存扣减标记等
This commit is contained in:
liufumingren 2026-09-13 02:23:44 +08:00
parent cbd16752a5
commit ec81f8b3cd
24 changed files with 3179 additions and 15 deletions

View File

@ -0,0 +1,655 @@
'use strict';
const { Controller } = require('egg');
const recalcStock = require('../utils/recalcStock');
const completeInbound = require('../utils/completeInbound');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_INBOUND_ORDER_TYPE, INBOUND_ORDER_TYPE_LIST, normalizeInboundOrderType } = require('../lib/wms/orderTypes');
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
const API_TYPE_QIMEN = 'qimen';
/** 入库单单号前缀,未提供单据号时由系统按 {前缀}_{自增id} 自动生成(如 RK_123) */
const INBOUND_BILL_PREFIX = 'RK';
/** 把可能为 JSON 字符串的字段归一化为对象(已为对象则原样返回),便于写入 JSON 列 */
function toJson(val) {
if (val == null) return val;
if (typeof val === 'string') {
try { return JSON.parse(val); } catch { return val; }
}
return val;
}
/** 入库单上以 JSON 列承载的扩展字段 */
const INBOUND_JSON_FIELDS = [ 'sender_info', 'receiver_info', 'extend_props' ];
/**
* WMS 返回的「外部入库单已存在」判定(重复推送)
* 典型报文:`创建入库单失败,失败原因:\n入库单已存在,状态: CREATED`
* 场景:已推送(3) 的单据被驳回(本地回退到待入库)后重新审核再推送,
* 而 openapi 渠道没有入库单取消接口(entryorder.* 只有 create/query),
* 外部单据仍占用同一个 entryOrderCode,重复 create 必然被拒。
* @param {Object} resp WMS 响应报文
* @return {boolean} 是否为「外部单据已存在」
*/
function isDuplicateOrderResponse(resp) {
const message = resp && resp.message != null ? String(resp.message) : '';
return /已存在/.test(message);
}
/**
* WMS 明确反馈「该单据类型不支持取消」的判定
* 典型报文:openapi 渠道 `order.cancel` 对 RK 组返回「暂不支持该订单类型的取消操作」
* (openapiMethods/order.js 只实现 ORDER/CK 组);奇门渠道对未开发类型返回「…未开发完成」。
* 命中时按「渠道不支持取消」降级处理:仍允许驳回,但需人工在仓库侧处理外部单据。
* @param {Object} resp WMS 响应报文
* @return {boolean} 是否为渠道不支持取消
*/
function isUnsupportedCancelResponse(resp) {
const message = resp && resp.message != null ? String(resp.message) : '';
return /暂不支持该订单类型的取消操作|未开发完成/.test(message);
}
/**
* 单号与状态/生命周期字段由系统与业务事务(创建 / 审核 / 推送 / 完成 / 驳回 / 作废 / 取消 / 库存回调)推动,
* 禁止通过新增、更新等通用接口直接写入,避免破坏单据对外标识(WMS entryOrderCode=bill_no)或绕过状态机。
*/
const MANAGED_FIELDS = [
'bill_no', 'status', 'audit_by', 'audit_time', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'item_total', 'item_kind',
];
/**
* @controller InboundOrderController 入库单管理
* 单据头 inbound_orders;明细由 stock_items(bill_type=1)承载,随单据在同一事务内创建
*/
class InboundOrderController extends Controller {
/**
* @summary 入库单列表
* @router get /api/inbound-orders
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query string bill_no 入库单号,支持模糊匹配
* @request query integer status 状态:1待入库 2已入库 3已取消
* @request query string inbound_type 入库类型(WMS 编码):B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库
* @request query integer shop_id 店铺/仓库ID
* @response 200 inboundOrderListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { bill_no: billNo, status, inbound_type: inboundType, shop_id: shopId } = ctx.query;
const principalId = ctx.state.principalId;
const where = { principal_id: principalId };
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
if (status !== undefined && status !== '') where.status = Number(status);
if (inboundType !== undefined && inboundType !== '') where.inbound_type = String(inboundType).trim().toUpperCase();
if (shopId) where.shop_id = Number(shopId);
const { count, rows } = await ctx.model.InboundOrder.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
{ model: ctx.model.User, as: 'auditor', attributes: [ 'id', 'nickname', 'username' ] },
],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
}
/**
* @summary 入库单详情
* @router get /api/inbound-orders/{id}
* @apikey
* @request path integer *id 入库单主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
{ model: ctx.model.User, as: 'auditor', attributes: [ 'id', 'nickname', 'username' ] },
{ model: ctx.model.User, as: 'voider', attributes: [ 'id', 'nickname', 'username' ] },
],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 1, bill_id: order.id },
include: [
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
],
});
const data = order.toJSON();
data.items = items;
ctx.body = { code: 0, message: 'success', data };
}
/**
* @summary 新增入库单
* @description 单号由系统按 RK_{自增id} 自动生成(不接受传入);仓库必填;可同时传入 items(stock_items, bill_type=1)一次性写入明细
* @router post /api/inbound-orders
* @apikey
* @request body createInboundOrderRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const { items, warehouse_id: warehouseId } = ctx.request.body;
const principalId = ctx.state.principalId;
if (!warehouseId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项' };
return;
}
const payload = { ...ctx.request.body };
delete payload.items;
// 单号(bill_no)在 MANAGED_FIELDS 内被剥离:一律由系统生成,不接受前端传入
for (const f of MANAGED_FIELDS) delete payload[f];
for (const f of INBOUND_JSON_FIELDS) payload[f] = toJson(payload[f]);
// 入库单类型:直接落库 WMS 编码(RK 组),非法值拒绝;不传时默认 CGRK(采购入库)
const inboundType = normalizeInboundOrderType(payload.inbound_type);
if (payload.inbound_type != null && String(payload.inbound_type).trim() !== '' && !inboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `inbound_type(入库类型)不合法,支持:${INBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
payload.inbound_type = inboundType || DEFAULT_INBOUND_ORDER_TYPE;
// 校验明细关联商品均存在且已启用
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
if (productIds.length) {
const validProducts = await ctx.model.Product.findAll({
where: { id: productIds, status: 1 },
attributes: [ 'id' ],
});
const validIds = new Set(validProducts.map((p) => p.id));
if (productIds.some((id) => !validIds.has(id))) {
ctx.status = 400;
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
return;
}
}
const transaction = await ctx.model.transaction();
try {
const totalAmount = Number(payload.total_amount) || 0;
const order = await ctx.model.InboundOrder.create({
status: 1,
...payload,
bill_no: `RK_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
principal_id: principalId,
warehouse_id: warehouseId,
created_by: ctx.userId,
total_amount: totalAmount,
}, { transaction });
if (Array.isArray(items) && items.length) {
await ctx.model.StockItem.bulkCreate(items.map(item => ({
principal_id: principalId,
bill_type: 1,
bill_id: order.id,
shop_id: item.shop_id || order.shop_id || null,
product_id: item.product_id || null,
combo_product_id: item.combo_product_id || null,
shop_product_id: item.shop_product_id || null,
name: item.name || null,
code: item.code || null,
inventory_type: item.inventory_type === 'CC' ? 'CC' : 'ZP',
spec: item.spec || null,
unit: item.unit || null,
quantity: item.quantity || 0,
plan_in_qty: item.quantity || 0,
price: item.price == null ? null : item.price,
total_amount: Number((Number(item.quantity || 0) * Number(item.price || 0)).toFixed(2)),
remark: item.remark || null,
})), { transaction });
}
// 系统生成单据号:RK_{自增id}
await order.update({ bill_no: `${INBOUND_BILL_PREFIX}_${order.id}` }, { transaction });
await transaction.commit();
await recalcStock(ctx, 1, order.id);
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '新增入库单失败,请稍后重试' };
}
}
/**
* @summary 更新入库单
* @description 仅「待入库(1)」可编辑;只更新单据头字段(不含明细与单号/状态等系统托管字段)
* @router put /api/inbound-orders/{id}
* @apikey
* @request path integer *id 入库单主键ID
* @request body updateInboundOrderRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
// 仅「待入库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改)
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅「待入库」状态的单据可以编辑,如需修改请先驳回' };
return;
}
delete ctx.request.body.principal_id;
delete ctx.request.body.created_by;
for (const f of MANAGED_FIELDS) delete ctx.request.body[f];
for (const f of INBOUND_JSON_FIELDS) ctx.request.body[f] = toJson(ctx.request.body[f]);
// 入库单类型:同样存储 WMS 编码(RK 组),非法值拒绝(影响后续推送与取消的口径一致)
if (ctx.request.body.inbound_type != null && String(ctx.request.body.inbound_type).trim() !== '') {
const inboundType = normalizeInboundOrderType(ctx.request.body.inbound_type);
if (!inboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `inbound_type(入库类型)不合法,支持:${INBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
ctx.request.body.inbound_type = inboundType;
} else {
delete ctx.request.body.inbound_type;
}
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 删除入库单
* @description 物理删除单据,并级联删除其明细(stock_items, bill_type=1)。仅「待入库(1)」「已取消(9)」可删除;
* 已审核(2) 及之后的单据禁止删除,请使用作废接口
* @router delete /api/inbound-orders/{id}
* @apikey
* @request path integer *id 入库单主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== 1 && order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '已审核及之后的单据禁止删除,请使用「作废」' };
return;
}
const transaction = await ctx.model.transaction();
try {
await ctx.model.StockItem.destroy({ where: { bill_type: 1, bill_id: order.id }, transaction });
await order.destroy({ transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '删除失败,请稍后重试' };
}
}
/* -------------------- 状态流转(按序校验) -------------------- */
async _transit(from, to, failMsg) {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== from) {
ctx.status = 400;
ctx.body = { code: 400, message: failMsg };
return;
}
await order.update({ status: to });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 审核:已创建(1) -> 已审核(2),并记录审核人与审核时间 */
async audit() {
const { ctx } = this;
const id = Number(ctx.params.id);
const order = await ctx.model.InboundOrder.findByPk(id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「待入库」状态的单据可以审核' };
return;
}
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 1, bill_id: order.id } });
if (!itemCount) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
await order.update({ status: 2, audit_by: ctx.userId, audit_time: new Date() });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* 推送:已审核(2) -> 已推送(3),并将入库单递交 WMS(entryorder.create)
* 失败时不流转状态,直接返回 WMS 错误信息;
* 例外:WMS 返回「入库单已存在」时视为外部已建单,按已推送(3)补状态(`reused=true`),
* 避免单据因外部单号被占用而卡在已审核(入库单无取消/更新接口)
*/
async push() {
const { ctx } = this;
const orderId = Number(ctx.params.id);
const principalId = ctx.state.principalId;
const order = await ctx.model.InboundOrder.findByPk(orderId, {
include: [
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' };
return;
}
const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (!api) {
ctx.status = 400;
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 1, bill_id: order.id },
include: [ { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'retail_price' ] } ],
order: [[ 'id', 'ASC' ]],
});
// 无明细不允许推送(否则即使推送成功,完成时也不会产生任何库存)
if (!items.length) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法推送' };
return;
}
const client = new QimenWmsClient(api, this.app);
const externalOrderCode = order.bill_no;
try {
const resp = await client.createEntryOrder(order, items, { warehouse: order.warehouse, creator: order.creator });
const success = client.isSuccess(resp);
const pushResult = {
success,
code: resp && resp.code,
message: resp && resp.message,
flag: resp && resp.flag,
entryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
response: resp,
pushedAt: new Date().toISOString(),
inboundType: order.inbound_type,
};
if (!success) {
// 外部单据已存在(驳回后重推):入库单无取消接口,外部单据无法冲正、也不能重复创建,
// 按「已推送」补状态,避免单据因单号被占用而永久卡在已审核(内容以仓库侧单据为准)
if (isDuplicateOrderResponse(resp)) {
const reusedResult = {
...pushResult,
success: true,
reused: true,
reusedReason: '外部入库单已存在,已按「已推送」处理(明细以仓库侧单据为准)',
};
await order.update({
status: 3,
operate_time: new Date(),
pushed_at: new Date(),
wms_push_result: reusedResult,
});
ctx.body = {
code: 0,
message: 'success',
data: { id: order.id, reused: true, wms_response: resp },
};
return;
}
// 推送失败:保留失败结果供排查,不流转状态让用户可重试
// (WMS 未提供入库单取消接口,无法冲正外部单据)
await order.update({ wms_push_result: pushResult, pushed_at: new Date() });
ctx.status = 502;
ctx.body = { code: 502, message: `WMS 返回失败: ${resp && (resp.message || resp.code)}` };
return;
}
await order.update({
status: 3,
operate_time: new Date(),
pushed_at: new Date(),
wms_push_result: pushResult,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } };
} catch (err) {
// 请求异常:记录失败结果与时间,状态保持「已审核」可重试(入库无外部取消接口)
const failResult = {
success: false,
entryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
error: err.message,
pushedAt: new Date().toISOString(),
};
await order.update({ wms_push_result: failResult, pushed_at: new Date() }).catch(() => {});
ctx.status = 502;
ctx.body = { code: 502, message: err.message };
}
}
/** 完成入库:已推送(3) -> 完成(4),并按明细增加系统库存(与 WMS entryorder.confirm 回调共用同一实现) */
async complete() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
let result;
try {
result = await completeInbound(ctx, order);
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: '完成入库失败,请稍后重试' };
return;
}
if (!result.ok) {
ctx.status = result.code;
ctx.body = { code: result.code, message: result.message };
return;
}
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 取消:任意非完成态 -> 已取消(9) */
async cancel() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
ctx.body = { code: 400, message: '已完成单据不能取消' };
return;
}
await order.update({ status: 9 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 恢复:已取消(9) -> 已创建(1) */
async restore() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' };
return;
}
await order.update({ status: 1 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 作废入库单
* @description 仅「已审核(2)」状态可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除
* @router post /api/inbound-orders/{id}/void
* @apikey
* @request path integer *id 入库单主键ID
* @request body voidInboundOrderRequest *body
* @response 200 baseResponse success
*/
async voidOrder() {
const { ctx } = this;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' };
return;
}
const body = ctx.request.body || {};
const reason = body.void_reason ? String(body.void_reason).trim() : '';
await order.update({
status: 5,
void_at: new Date(),
void_by: ctx.userId,
void_reason: reason || null,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 驳回入库单
* @description 审核的反向操作:已审核(2) / 已推送(3) 且未完成(4) 的单据可驳回,驳回后回到「待入库(1)」;
* 驳回会变更单号(在基础单号后追加/递增 `_N`,首次 `_1`、再次 `_2`);
* 已推送(3) 的会先调 WMS `order.cancel`(orderCode=bill_no,orderType=落库的入库单类型)取消外部入库单,
* **外部取消失败则驳回失败、单据保持原状态**(不在外部仍存在的情况下回退本地单据)
* @router post /api/inbound-orders/{id}/reject
* @apikey
* @request path integer *id 入库单主键ID
* @response 200 baseResponse success
*/
async reject() {
const { ctx } = this;
const principalId = ctx.state.principalId;
const order = await ctx.model.InboundOrder.findByPk(ctx.params.id, {
include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '入库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
ctx.body = { code: 400, message: '已完成入库的单据不能驳回' };
return;
}
if (order.status !== 2 && order.status !== 3) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」「已推送」状态的单据可以驳回' };
return;
}
// 仅「已审核」:未推送,无外部单据,直接回退
if (order.status !== 3) {
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, INBOUND_BILL_PREFIX);
await order.update({ status: 1, bill_no: newBillNo });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
return;
}
// 已推送:先调用取消接口冲正外部入库单
const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (!api) {
ctx.status = 400;
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
return;
}
const client = new QimenWmsClient(api, this.app);
const cancel = { attempted: true, success: false, orderType: order.inbound_type };
let resp;
try {
resp = await client.cancelInboundOrder(order);
} catch (err) {
// 请求异常:无法确认外部单据是否已取消,驳回失败并保持原状态供用户重试(与出库单口径一致)
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部入库单失败:${err.message}` };
return;
}
cancel.code = resp && resp.code;
cancel.message = resp && resp.message;
cancel.success = client.isSuccess(resp);
if (!cancel.success) {
// 外部取消失败(含渠道不支持该类型取消):不允许驳回,单据保持「已推送」不变
const hint = isUnsupportedCancelResponse(resp)
? '(当前渠道不支持入库单取消,请先在 WMS 侧处理该外部单据)'
: '';
ctx.logger.warn(`[inbound-reject] 取消外部入库单失败,入库单 ${order.bill_no}(类型 ${order.inbound_type})保持原状态:${cancel.message}`);
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部入库单失败:${resp && (resp.message || resp.code)}${hint}` };
return;
}
// 回到待入库(单号换新,避免再用已被外部占用的单号);清空推送记录(原推送结果不再成立,调用历史见对外 API 日志)
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, INBOUND_BILL_PREFIX);
await order.update({ status: 1, bill_no: newBillNo, pushed_at: null, wms_push_result: null });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no, cancel } };
}
}
module.exports = InboundOrderController;

View File

@ -1,6 +1,16 @@
'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/**
* 状态与生命周期字段由业务事务(状态流转 updateStatus / 外部 WMS 回调 updateWmsStatus)推动,
* 禁止通过新增、更新等通用接口直接写入,避免绕过流程。
*/
const MANAGED_FIELDS = [
'status', 'submit_status', 'submit_at', 'submit_order_no', 'submit_msg',
'wms_status', 'wms_order_no', 'wms_synced_at',
];
/**
* @controller OrderController 订单管理
@ -18,18 +28,19 @@ class OrderController extends Controller {
* @request query integer status 主状态:1待处理 2处理中 3已完成 4已取消
* @request query string wms_status 外部WMS状态,如 CREATED/PICKING/SHIPPED
* @request query integer submit_status 上交状态:0未上交 1上交中 2已上交 3上交失败
* @request query integer shop_id 店铺ID,按店铺过滤,不传则不过滤
* @response 200 orderListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const page = Number(ctx.query.page || 1);
const pageSize = Number(ctx.query.pageSize || 20);
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const {
order_no: orderNo,
status,
wms_status: wmsStatus,
submit_status: submitStatus,
shop_id: shopId,
} = ctx.query;
const principalId = ctx.state.principalId;
@ -39,20 +50,24 @@ class OrderController extends Controller {
if (status !== undefined && status !== '') where.status = Number(status);
if (wmsStatus) where.wms_status = wmsStatus;
if (submitStatus !== undefined && submitStatus !== '') where.submit_status = Number(submitStatus);
if (shopId) where.shop_id = Number(shopId);
const { count, rows } = await ctx.model.Order.findAndCountAll({
where,
offset: (page - 1) * pageSize,
limit: pageSize,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] },
],
});
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
}
/**
* @summary 订单详情
* @description 按主键查询订单,含主状态、WMS 状态与上交状态
* @description 按主键查询订单,含主状态、WMS 状态、上交状态、所属店铺与订单明细
* @router get /api/orders/{id}
* @apikey
* @request path integer *id 订单主键ID
@ -60,7 +75,19 @@ class OrderController extends Controller {
*/
async show() {
const { ctx } = this;
const order = await ctx.model.Order.findByPk(ctx.params.id);
const order = await ctx.model.Order.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{
model: ctx.model.OrderItem,
as: 'items',
include: [
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
],
},
],
});
if (!order) {
ctx.status = 404;
@ -73,7 +100,8 @@ class OrderController extends Controller {
/**
* @summary 新增订单
* @description 订单号 order_no 全局唯一;初始主状态默认 1(待处理)
* @description 订单号 order_no 全局唯一;初始主状态默认 1(待处理);
* 可同时传入 items 数组一次性写入订单明细(明细随订单在同一事务内创建)
* @router post /api/orders
* @apikey
* @request body createOrderRequest *body
@ -81,7 +109,7 @@ class OrderController extends Controller {
*/
async create() {
const { ctx } = this;
const { order_no: orderNo, principal_id: principalId } = ctx.request.body;
const { order_no: orderNo, principal_id: principalId, items } = ctx.request.body;
if (!orderNo || !principalId) {
ctx.status = 400;
@ -96,13 +124,73 @@ class OrderController extends Controller {
return;
}
const order = await ctx.model.Order.create({
status: 1,
submit_status: 0,
...ctx.request.body,
});
const payload = { ...ctx.request.body };
delete payload.items;
for (const f of MANAGED_FIELDS) delete payload[f];
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
const transaction = await ctx.model.transaction();
try {
const order = await ctx.model.Order.create({
status: 1,
submit_status: 0,
...payload,
}, { transaction });
if (Array.isArray(items) && items.length) {
await ctx.model.OrderItem.bulkCreate(items.map(item => ({
...item,
principal_id: principalId,
order_id: order.id,
shop_id: item.shop_id || order.shop_id || null,
parse_status: item.product_id || item.combo_product_id ? 1 : 0,
item_type: item.product_id ? 1 : (item.combo_product_id ? 2 : 0),
})), { transaction });
}
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '新增订单失败,请稍后重试' };
}
}
/**
* @summary 解析订单明细
* @description 批量解析该订单下未解析/解析失败的明细,按商家编码或店铺商品绑定关系匹配系统商品与组合商品
* @router post /api/orders/{id}/parse-items
* @apikey
* @request path integer *id 订单主键ID
* @response 200 parseOrderItemsResponse success
*/
async parseItems() {
const { ctx } = this;
const order = await ctx.model.Order.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '订单不存在' };
return;
}
const items = await ctx.model.OrderItem.findAll({ where: { order_id: order.id } });
let resolved = 0;
let failed = 0;
for (const item of items) {
if (Number(item.parse_status) === 1) continue;
const data = await ctx.controller.orderItem.resolveItem(item, order.principal_id);
await item.update(data);
if (data.parse_status === 1) resolved++;
else failed++;
}
ctx.body = {
code: 0,
message: 'success',
data: { total: items.length, resolved, failed },
};
}
/**
@ -125,6 +213,7 @@ class OrderController extends Controller {
}
delete ctx.request.body.principal_id;
for (const f of MANAGED_FIELDS) delete ctx.request.body[f];
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}

View File

@ -0,0 +1,679 @@
'use strict';
const { Controller } = require('egg');
const recalcStock = require('../utils/recalcStock');
const stock = require('../utils/stock');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes');
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
const API_TYPE_QIMEN = 'qimen';
/** 出库单单号前缀,未提供单据号时由系统按 {前缀}_{自增id} 自动生成(如 CK_123) */
const OUTBOUND_BILL_PREFIX = 'CK';
/**
* 单号与状态/生命周期字段由系统与业务事务(创建 / 审核 / 推送 / 完成 / 驳回 / 作废 / 取消 / 库存回调)推动,
* 禁止通过新增、更新等通用接口直接写入,避免破坏单据对外标识(WMS deliveryOrderCode=bill_no)或绕过状态机。
*/
const MANAGED_FIELDS = [
'bill_no', 'status', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'item_total', 'item_kind',
];
/**
* @controller OutboundOrderController 出库单管理
* 单据头 outbound_orders;明细由 stock_items(bill_type=2)承载,随单据在同一事务内创建
*/
class OutboundOrderController extends Controller {
/**
* @summary 出库单列表
* @router get /api/outbound-orders
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query string bill_no 出库单号,支持模糊匹配
* @request query integer status 状态:1待出库 2已出库 3已取消
* @request query string outbound_type 出库类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单
* @request query integer shop_id 店铺/仓库ID
* @response 200 outboundOrderListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { bill_no: billNo, status, outbound_type: outboundType, shop_id: shopId } = ctx.query;
const principalId = ctx.state.principalId;
const where = { principal_id: principalId };
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
if (status !== undefined && status !== '') where.status = Number(status);
if (outboundType !== undefined && outboundType !== '') where.outbound_type = String(outboundType).trim().toUpperCase();
if (shopId) where.shop_id = Number(shopId);
const { count, rows } = await ctx.model.OutboundOrder.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
}
/**
* @summary 出库单详情
* @router get /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
{ model: ctx.model.User, as: 'voider', attributes: [ 'id', 'nickname', 'username' ] },
],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id },
include: [
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
],
});
const data = order.toJSON();
data.items = items;
ctx.body = { code: 0, message: 'success', data };
}
/**
* @summary 新增出库单
* @description 单号由系统按 CK_{自增id} 自动生成(不接受传入);可同时传入 items(stock_items, bill_type=2)一次性写入明细
* @router post /api/outbound-orders
* @apikey
* @request body createOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const { items, warehouse_id: warehouseId } = ctx.request.body;
const principalId = ctx.state.principalId;
if (!warehouseId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项' };
return;
}
const payload = { ...ctx.request.body };
delete payload.items;
// 单号(bill_no)在 MANAGED_FIELDS 内被剥离:一律由系统生成,不接受前端传入
for (const f of MANAGED_FIELDS) delete payload[f];
// 出库单类型:直接落库 WMS 编码(CK 组),非法值拒绝;不传时默认 PTCK(普通出库单)
const outboundType = normalizeOutboundOrderType(payload.outbound_type);
if (payload.outbound_type != null && String(payload.outbound_type).trim() !== '' && !outboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
payload.outbound_type = outboundType || DEFAULT_OUTBOUND_ORDER_TYPE;
// 校验明细关联商品均存在且已启用
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
if (productIds.length) {
const validProducts = await ctx.model.Product.findAll({
where: { id: productIds, status: 1 },
attributes: [ 'id' ],
});
const validIds = new Set(validProducts.map((p) => p.id));
if (productIds.some((id) => !validIds.has(id))) {
ctx.status = 400;
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
return;
}
}
const transaction = await ctx.model.transaction();
try {
const totalAmount = Number(payload.total_amount) || 0;
// 先用临时单号落库以取得自增 id,随后更新为 CK_{id}
const order = await ctx.model.OutboundOrder.create({
status: 1,
...payload,
bill_no: `CK_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
principal_id: principalId,
warehouse_id: warehouseId,
created_by: ctx.userId,
total_amount: totalAmount,
}, { transaction });
if (Array.isArray(items) && items.length) {
await ctx.model.StockItem.bulkCreate(items.map(item => ({
principal_id: principalId,
bill_type: 2,
bill_id: order.id,
shop_id: item.shop_id || order.shop_id || null,
product_id: item.product_id || null,
combo_product_id: item.combo_product_id || null,
shop_product_id: item.shop_product_id || null,
name: item.name || null,
code: item.code || null,
inventory_type: item.inventory_type === 'CC' ? 'CC' : 'ZP',
spec: item.spec || null,
unit: item.unit || null,
quantity: item.quantity || 0,
plan_out_qty: item.quantity || 0,
price: item.price == null ? null : item.price,
total_amount: Number((Number(item.quantity || 0) * Number(item.price || 0)).toFixed(2)),
remark: item.remark || null,
})), { transaction });
}
// 系统生成单据号:CK_{自增id}
await order.update({ bill_no: `${OUTBOUND_BILL_PREFIX}_${order.id}` }, { transaction });
await transaction.commit();
await recalcStock(ctx, 2, order.id);
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '新增出库单失败,请稍后重试' };
}
}
/**
* @summary 更新出库单
* @description 仅「待出库(1)」可编辑;只更新单据头字段(不含明细与单号/状态等系统托管字段)
* @router put /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @request body updateOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
// 仅「待出库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改)
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅「待出库」状态的单据可以编辑,如需修改请先驳回' };
return;
}
delete ctx.request.body.principal_id;
delete ctx.request.body.created_by;
for (const f of MANAGED_FIELDS) delete ctx.request.body[f];
// 出库单类型:同样存储 WMS 编码(CK 组),非法值拒绝(影响后续推送与取消的口径一致)
if (ctx.request.body.outbound_type != null && String(ctx.request.body.outbound_type).trim() !== '') {
const outboundType = normalizeOutboundOrderType(ctx.request.body.outbound_type);
if (!outboundType) {
ctx.status = 400;
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
return;
}
ctx.request.body.outbound_type = outboundType;
} else {
delete ctx.request.body.outbound_type;
}
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 删除出库单
* @description 物理删除单据,并级联删除其明细(stock_items, bill_type=2)。仅「待出库(1)」「已取消(9)」可删除;
* 已审核(2) 及之后的单据禁止删除,请使用作废接口
* @router delete /api/outbound-orders/{id}
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 1 && order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '已审核及之后的单据禁止删除,请使用「作废」' };
return;
}
const transaction = await ctx.model.transaction();
try {
await ctx.model.StockItem.destroy({ where: { bill_type: 2, bill_id: order.id }, transaction });
await order.destroy({ transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '删除失败,请稍后重试' };
}
}
/** 审核:已创建(1) -> 已审核(2),需先录入明细 */
async audit() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 1) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已创建」状态的单据可以审核' };
return;
}
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
if (!itemCount) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
await order.update({ status: 2 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* 推送:已审核(2) -> 已推送(3),锁定库存(占用可用,防超卖)并递交 WMS(stockout.create)
* 失败时不流转状态,直接返回 WMS 错误信息;推送失败会释放已锁定库存,可重试
*/
async push() {
const { ctx } = this;
const orderId = Number(ctx.params.id);
const principalId = ctx.state.principalId;
const order = await ctx.model.OutboundOrder.findByPk(orderId, {
include: [
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' };
return;
}
const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (!api) {
ctx.status = 400;
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
include: [ { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'retail_price' ] } ],
order: [[ 'id', 'ASC' ]],
});
// 无明细不允许推送(否则既不会锁定库存,也不会向 WMS 发出有效出库单)
if (!items.length) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法推送' };
return;
}
const productIds = items.map(i => Number(i.product_id));
const productMap = productIds.length
? await ctx.model.Product.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: productIds } }, attributes: [ 'id', 'item_code', 'item_name' ] })
: [];
const pmap = new Map(productMap.map(p => [ Number(p.id), p ]));
// stockout.create 的明细行 itemId 为必填:取该仓库已推送商品的 WMS 商品ID
const links = productIds.length
? await ctx.model.WarehouseProduct.findAll({
where: { principal_id: principalId, warehouse_id: order.warehouse_id, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
attributes: [ 'product_id', 'wms_item_id' ],
})
: [];
const wmsItemIdByProduct = {};
for (const l of links) {
if (l.wms_item_id != null) wmsItemIdByProduct[Number(l.product_id)] = Number(l.wms_item_id);
}
// 先锁定库存(占用可用,防止超卖);WMS 推送失败则回滚释放
const reserveTx = await ctx.model.transaction();
try {
for (const it of items) {
const pid = Number(it.product_id);
const qty = Number(it.quantity) || 0;
try {
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 ZC
await stock.lock(ctx, order.principal_id, pid, qty, reserveTx, it.inventory_type === 'CC' ? 'CC' : 'ZC');
} catch (err) {
if (err.code === 'INSUFFICIENT_STOCK') {
const p = pmap.get(pid);
err.message = `库存不足:${p ? `${p.item_name}(${p.item_code})` : '商品#' + pid},可用 ${err.available},需 ${err.require}`;
}
throw err;
}
}
await reserveTx.commit();
} catch (err) {
await reserveTx.rollback();
if (err.code === 'INSUFFICIENT_STOCK') {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
ctx.status = 500;
ctx.body = { code: 500, message: '库存锁定失败,请稍后重试' };
return;
}
// 递交外部 WMS(stockout.create)
const client = new QimenWmsClient(api, this.app);
const externalOrderCode = order.bill_no;
try {
const resp = await client.createStockout(order, items, { warehouse: order.warehouse, wmsItemIdByProduct });
const success = client.isSuccess(resp);
const pushResult = {
success,
code: resp && resp.code,
message: resp && resp.message,
flag: resp && resp.flag,
deliveryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
response: resp,
pushedAt: new Date().toISOString(),
};
if (!success) {
// 推送失败:释放锁定库存,并调 order.cancel 冲正(外部可能已建单)
await this._releaseStock(order, items).catch(() => {});
pushResult.cancelResult = await client.cancelOrder(order)
.catch(err => ({ code: 'EXCEPTION', message: err.message }));
await order.update({ wms_push_result: pushResult, pushed_at: new Date() });
ctx.status = 502;
ctx.body = { code: 502, message: `WMS 返回失败: ${resp && (resp.message || resp.code)}` };
return;
}
await order.update({
status: 3,
operate_time: new Date(),
pushed_at: new Date(),
wms_push_result: pushResult,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } };
} catch (err) {
// 请求异常:释放锁定库存,同样调 order.cancel 冲正,状态保持「已审核」可重试
await this._releaseStock(order, items).catch(() => {});
const cancelResult = await client.cancelOrder(order)
.catch(e => ({ code: 'EXCEPTION', message: e.message }));
const failResult = {
success: false,
deliveryOrderCode: externalOrderCode,
warehouseApiId: api.id,
apiType: api.type,
error: err.message,
cancelResult,
pushedAt: new Date().toISOString(),
};
await order.update({ wms_push_result: failResult, pushed_at: new Date() }).catch(() => {});
ctx.status = 502;
ctx.body = { code: 502, message: err.message };
}
}
/** 推送失败时释放已锁定库存 */
async _releaseStock(order, items) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
await stock.unlock(ctx, order.principal_id, Number(it.product_id), Number(it.quantity) || 0, transaction, it.inventory_type === 'CC' ? 'CC' : 'ZC');
}
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
}
/** 完成出库:已推送(3) -> 完成(4),需有明细(已推送单必然有,此处兜底) */
async complete() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 3) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已推送」状态的单据可以完成出库' };
return;
}
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
if (!itemCount) {
ctx.status = 400;
ctx.body = { code: 400, message: '单据无明细,无法完成出库' };
return;
}
await order.update({ status: 4 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 取消:任意非完成态 -> 已取消(9) */
async cancel() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
ctx.body = { code: 400, message: '已完成单据不能取消' };
return;
}
// 已推送(3)的单据取消时释放已锁定库存
if (order.status === 3) {
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
await stock.unlock(ctx, order.principal_id, Number(it.product_id), Number(it.quantity) || 0, transaction, it.inventory_type === 'CC' ? 'CC' : 'ZC');
}
await order.update({ status: 9 }, { transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '取消失败,请稍后重试' };
}
return;
}
await order.update({ status: 9 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 恢复:已取消(9) -> 已创建(1) */
async restore() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 9) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' };
return;
}
await order.update({ status: 1 });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 作废出库单
* @description 仅「已审核(2)」状态可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除
* @router post /api/outbound-orders/{id}/void
* @apikey
* @request path integer *id 出库单主键ID
* @request body voidOutboundOrderRequest *body
* @response 200 baseResponse success
*/
async voidOrder() {
const { ctx } = this;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status !== 2) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' };
return;
}
const body = ctx.request.body || {};
const reason = body.void_reason ? String(body.void_reason).trim() : '';
await order.update({
status: 5,
void_at: new Date(),
void_by: ctx.userId,
void_reason: reason || null,
});
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/**
* @summary 驳回出库单
* @description 审核的反向操作:已审核(2) / 已推送(3) 且未完成(4) 的单据可驳回,驳回后回到「待出库(1)」;
* 驳回会变更单号(在基础单号后追加/递增 `_N`,首次 `_1`、再次 `_2`);
* 已推送的会先调用 WMS order.cancel 取消外部出库单,再按是否已被发货通知扣减回滚库存
* @router post /api/outbound-orders/{id}/reject
* @apikey
* @request path integer *id 出库单主键ID
* @response 200 baseResponse success
*/
async reject() {
const { ctx } = this;
const principalId = ctx.state.principalId;
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
});
if (!order) {
ctx.status = 404;
ctx.body = { code: 404, message: '出库单不存在' };
return;
}
if (order.status === 4) {
ctx.status = 400;
ctx.body = { code: 400, message: '已完成出库的单据不能驳回' };
return;
}
if (order.status !== 2 && order.status !== 3) {
ctx.status = 400;
ctx.body = { code: 400, message: '只有「已审核」「已推送」状态的单据可以驳回' };
return;
}
// 仅「已审核」:直接回退,未锁定库存
if (order.status !== 3) {
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
await order.update({ status: 1, bill_no: newBillNo });
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
return;
}
// 已推送:先走接口取消外部单据,成功后才回滚库存与状态
const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (!api) {
ctx.status = 400;
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
return;
}
const client = new QimenWmsClient(api, this.app);
let resp;
try {
resp = await client.cancelOrder(order);
} catch (err) {
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部单据失败:${err.message}` };
return;
}
if (!client.isSuccess(resp)) {
ctx.status = 502;
ctx.body = { code: 502, message: `取消外部单据失败:${resp && (resp.message || resp.code)}` };
return;
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
const pid = Number(it.product_id);
const qty = Number(it.quantity) || 0;
// 行级库存类型:CC=残次 -> 残次库存,其余(ZP等)归为正品 ZC
const itemType = it.inventory_type === 'CC' ? 'CC' : 'ZC';
if (order.stock_deducted) {
// 发货通知已按明细扣减总数量(锁定已同步释放):回补总数量
await stock.increase(ctx, order.principal_id, pid, qty, transaction, itemType);
} else {
// 仅推送锁定、尚未扣减:释放锁定
await stock.unlock(ctx, order.principal_id, pid, qty, transaction, itemType);
}
}
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
await order.update({
status: 1,
bill_no: newBillNo,
stock_deducted: 0,
pushed_at: null,
wms_push_result: null,
}, { transaction });
await transaction.commit();
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '驳回失败,请稍后重试' };
}
}
}
module.exports = OutboundOrderController;

View File

@ -0,0 +1,118 @@
'use strict';
/**
* WMS 单据类型编码(入库单 RK 组 / 出库单 CK 组)单一事实来源。
*
* 文档依据(D:\wms\methods):
* - openapi.json `entryorder.create`:字段 `entryOrder.entryOrderType`,可选,默认 SCRK(生产入库)
* - qimen.json `entryorder.create`:字段 `request.entryOrder.orderType`,必填,CGRK/JITRK/THRK/QTRK 等
* - qimen.json `order.cancel`:`request.orderType` 作业类型枚举,RK 组(已实现,取消入库单)
* = B2BRK / SCRK / LYRK / CCRK / CGRK / DBRK / QTRK
*
* 入库单在 OMS 侧直接存储该编码(inbound_orders.inbound_type),
* 推送时作为 entryOrderType 传出,取消(驳回)时作为 orderType 传出,
* 保证「创建用什么类型,取消就用什么类型」,不再做临时映射。
*/
const INBOUND_ORDER_TYPES = {
B2BRK: 'B2B入库',
SCRK: '生产入库',
LYRK: '领用入库',
CCRK: '残次品入库',
CGRK: '采购入库',
DBRK: '调拨入库',
QTRK: '其他入库',
};
/** 入库单类型编码列表(顺序即前端下拉顺序) */
const INBOUND_ORDER_TYPE_LIST = Object.keys(INBOUND_ORDER_TYPES);
/** 未指定入库类型时的默认值(历史上 OMS 默认「采购入库」,对应 CGRK) */
const DEFAULT_INBOUND_ORDER_TYPE = 'CGRK';
/**
* 出库单类型编码(CK 组,对应 WMS 独立出库单表 wms_order_stockout)。
* 文档/源码依据:
* - openapi.json `stockout.create`:字段 `deliveryOrder.orderType`(必填)
* - openapi `order.cancel` / `openapiMethods/order.js`
* CK_TYPES = PTCK / DBCK / B2BCK / QTCK / CGTH → 走 wms_order_stockout 取消
* 注:JYCK/HHCK/BFCK 属于 ORDER 组(wms_order_delivery 发货单),与 stockout 不同链路,
* 出库单(stockout.create 创建)不能用这三个类型,否则取消时找不到单据。
*/
const OUTBOUND_ORDER_TYPES = {
PTCK: '普通出库单',
DBCK: '调拨出库',
B2BCK: 'B2B出库',
QTCK: '其他出库',
CGTH: '采购退货出库单',
};
/** 出库单类型编码列表(顺序即前端下拉顺序) */
const OUTBOUND_ORDER_TYPE_LIST = Object.keys(OUTBOUND_ORDER_TYPES);
/** 未指定出库类型时的默认值(历史上 OMS 默认「销售出库」,对应 PTCK) */
const DEFAULT_OUTBOUND_ORDER_TYPE = 'PTCK';
/**
* 发货单订单类型编码(ORDER 组,对应 WMS 发货单表 wms_order_delivery)。
* 文档/源码依据:
* - D:\wms\methods\qimen.json `order.cancel`:ORDER 组 JYCK / HHCK / BFCK → 取消发货单
* (JYCK=一般交易出库单、HHCK=换货出库、BFCK=补发出库)
* - openapi `order.cancel` 文档:orderType 默认 JYCK(一般交易出库单)
* 发货单在 OMS 侧直接存储该编码(order_deliveries.order_type),默认 JYCK。
*/
const DELIVERY_ORDER_TYPES = {
JYCK: '一般交易出库单',
HHCK: '换货出库',
BFCK: '补发出库',
};
/** 发货单订单类型编码列表(顺序即前端下拉顺序) */
const DELIVERY_ORDER_TYPE_LIST = Object.keys(DELIVERY_ORDER_TYPES);
/** 未指定订单类型时的默认值(一般交易出库单) */
const DEFAULT_DELIVERY_ORDER_TYPE = 'JYCK';
/**
* 归一化入库单类型编码:trim + 大写,非法值返回空串(由调用方决定报错或兜底)
* @param {string} value 入库单类型编码(如 'cgrk')
* @return {string} 合法编码,非法时返回 ''
*/
function normalizeInboundOrderType(value) {
const code = String(value == null ? '' : value).trim().toUpperCase();
return INBOUND_ORDER_TYPE_LIST.includes(code) ? code : '';
}
/**
* 归一化出库单类型编码:trim + 大写,非法值返回空串(由调用方决定报错或兜底)
* @param {string} value 出库单类型编码(如 'qtck')
* @return {string} 合法编码,非法时返回 ''
*/
function normalizeOutboundOrderType(value) {
const code = String(value == null ? '' : value).trim().toUpperCase();
return OUTBOUND_ORDER_TYPE_LIST.includes(code) ? code : '';
}
/**
* 归一化发货单订单类型编码:trim + 大写,非法值返回空串(由调用方决定报错或兜底)
* @param {string} value 订单类型编码(如 'jyck')
* @return {string} 合法编码,非法时返回 ''
*/
function normalizeDeliveryOrderType(value) {
const code = String(value == null ? '' : value).trim().toUpperCase();
return DELIVERY_ORDER_TYPE_LIST.includes(code) ? code : '';
}
module.exports = {
INBOUND_ORDER_TYPES,
INBOUND_ORDER_TYPE_LIST,
DEFAULT_INBOUND_ORDER_TYPE,
normalizeInboundOrderType,
OUTBOUND_ORDER_TYPES,
OUTBOUND_ORDER_TYPE_LIST,
DEFAULT_OUTBOUND_ORDER_TYPE,
normalizeOutboundOrderType,
DELIVERY_ORDER_TYPES,
DELIVERY_ORDER_TYPE_LIST,
DEFAULT_DELIVERY_ORDER_TYPE,
normalizeDeliveryOrderType,
};

View File

@ -0,0 +1,768 @@
'use strict';
const { qimenSign } = require('./sign');
const {
DEFAULT_INBOUND_ORDER_TYPE,
normalizeInboundOrderType,
DEFAULT_OUTBOUND_ORDER_TYPE,
normalizeOutboundOrderType,
DEFAULT_DELIVERY_ORDER_TYPE,
normalizeDeliveryOrderType,
} = require('./orderTypes');
/** 单次请求超时(毫秒) */
const DEFAULT_TIMEOUT_MS = 10000;
/** 业务成功码集合(index.ping 备注:成功通常为 200 或 1;singleitem 文档:1=成功 0=失败) */
const SUCCESS_CODES = new Set([ 1, 200, '1', '200' ]);
/** 对外请求日志中单条报文/URL 最大存储长度(字符) */
const MAX_LOG_BODY = 4000;
/** 出站报文/URL 需脱敏的字段 */
const SENSITIVE_FIELDS = [ 'app_secret', 'password', 'token', 'sign', 'salt' ];
/**
* 对 URL 中的敏感 query 参数脱敏(sign / app_secret),避免凭据落库
* @param {string} rawUrl
* @return {string}
*/
function maskSignInUrl(rawUrl) {
try {
const u = new URL(rawUrl);
for (const key of [ 'sign', 'app_secret' ]) {
if (u.searchParams.has(key)) u.searchParams.set(key, '***');
}
return u.toString();
} catch {
return rawUrl;
}
}
/**
* 对报文对象中的敏感字段脱敏(递归)
* @param {*} value
* @return {*}
*/
function maskObject(value) {
if (!value || typeof value !== 'object') return value;
const result = Array.isArray(value) ? [ ...value ] : { ...value };
for (const key of Object.keys(result)) {
if (SENSITIVE_FIELDS.includes(key.toLowerCase())) {
result[key] = '***';
} else if (result[key] && typeof result[key] === 'object') {
result[key] = maskObject(result[key]);
}
}
return result;
}
/**
* 序列化并限制长度
* @param {*} value
* @param {number} max
* @return {string}
*/
function safeStringify(value, max) {
let text;
try {
text = typeof value === 'string' ? value : JSON.stringify(value);
} catch {
text = '[unserializable]';
}
if (!text) return '';
return text.length > max ? `${text.slice(0, max)}...[truncated]` : text;
}
/**
* 类奇门JSON接口客户端(OMS → WMS)
*
* 封装对 WMS openapi(POST {base_url})的调用与签名。当前聚焦「商品资料推送(singleitem.synchronize)」,
* 后续可在此扩展 deliveryorder / entryorder / inventory 等模块,复用同一套鉴权与报文结构。
*
* 约定(基于 D:/wms/methods/openapi.json + warehouse_notify.json):
* - 鉴权参数 method / app_key / timestamp / sign 通过 query 传递(与 qimen.json 一致)
* - 业务参数通过 JSON body 传递(如 { item: {...} })
* - 签名 sign = MD5(app_secret + timestamp + body_json),与 WMS 出站通知规则一致
* - 时间戳为 Unix 秒,±10 分钟有效
*
* 说明:openapi.json 未显式给出签名算法,此处与同系统出站通知(MD5(secret+timestamp+body))保持一致;
* 若实际 WMS 使用其它签名,仅需替换 _sign 实现。
*
* 每次请求都会异步落库到 api_outbound_logs(前提是构造时传入了 app 实例),用于排查。
*/
class QimenWmsClient {
/**
* @param {Object} warehouseApi 仓库接口配置模型实例(需含 base_url / app_key / app_secret / getFieldValues)
* @param {Egg.Application} [app] egg 应用实例,传入后才会记录对外请求日志
*/
constructor(warehouseApi, app) {
if (!warehouseApi) throw new Error('warehouseApi 不能为空');
this.baseUrl = (warehouseApi.base_url || '').replace(/\/+$/, '');
this.appKey = warehouseApi.app_key || '';
this.appSecret = warehouseApi.app_secret || '';
this.fields = typeof warehouseApi.getFieldValues === 'function'
? warehouseApi.getFieldValues()
: (warehouseApi.extra && typeof warehouseApi.extra === 'object' ? warehouseApi.extra : {});
this.timeoutMs = DEFAULT_TIMEOUT_MS;
// 归属与落库依赖(app 可选,单测/脚本未注入时跳过记录)
this.app = app || null;
this.principalId = warehouseApi.principal_id || null;
this.warehouseId = warehouseApi.warehouse_id || null;
this.warehouseApiId = warehouseApi.id || null;
this.apiType = warehouseApi.type || 'qimen';
}
/**
* 计算签名(与 WMS app/lib/api_sign.js 对齐)
* 参与签名的 query 为 method/app_key/v/timestamp(不含 sign),
* body 用请求体对象(解析后的结构)做稳定序列化后 MD5。
* @param {string} method WMS 方法名
* @param {number} timestamp Unix 秒
* @param {Object} params 请求体对象
*/
_sign(method, timestamp, params) {
const queryForSign = {
method,
app_key: this.appKey,
v: this._apiVersion(),
timestamp: String(timestamp),
};
return qimenSign({ query: queryForSign, body: params, secret: this.appSecret });
}
/**
* 取接口版本号(v 参数),源自配置项 api_version,缺省 V2.0
* @return {string}
*/
_apiVersion() {
return (this.fields && this.fields.api_version) || 'V2.0';
}
/**
* 调用 WMS openapi 方法
* @param {string} method 方法名,如 singleitem.synchronize / index.ping
* @param {Object} params 业务参数(作为 JSON body 发送)
* @return {Promise<{code:number|string,message:string,data:any}>} WMS 返回
*/
async call(method, params = {}) {
if (!this.baseUrl) throw new Error('仓库接口未配置 base_url(WMS openapi 地址)');
if (!this.appKey || !this.appSecret) throw new Error('仓库接口未配置 app_key / app_secret');
const timestamp = Math.floor(Date.now() / 1000);
const bodyJson = JSON.stringify(params);
const sign = this._sign(method, timestamp, params);
const url = new URL(this.baseUrl);
url.searchParams.set('method', method);
url.searchParams.set('app_key', this.appKey);
// v 为 WMS 要求的接口版本号(本地配置项 api_version,默认 V2.0),随系统参数一并传入
url.searchParams.set('v', this._apiVersion());
url.searchParams.set('timestamp', String(timestamp));
url.searchParams.set('sign', sign);
const finalUrl = url.toString();
const start = Date.now();
let responseStatus = null;
let responseText = '';
let isSuccess = false;
let businessCode = null;
let businessMessage = null;
let errorMsg = null;
let result = null;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const resp = await fetch(finalUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: bodyJson,
signal: controller.signal,
});
responseStatus = resp.status;
responseText = await resp.text();
if (!resp.ok) {
errorMsg = `WMS 返回 HTTP ${resp.status}: ${responseText.slice(0, 200)}`;
throw new Error(errorMsg);
}
try {
result = JSON.parse(responseText);
isSuccess = true;
} catch {
errorMsg = `WMS 返回非法 JSON: ${responseText.slice(0, 200)}`;
throw new Error(errorMsg);
}
} catch (err) {
if (!errorMsg) errorMsg = err.message;
throw err;
} finally {
clearTimeout(timer);
if (result) {
businessCode = result.code != null ? String(result.code) : null;
businessMessage = typeof result.message === 'string' ? result.message.slice(0, 255) : null;
}
this._log({
method,
url: finalUrl,
params,
responseStatus,
responseText,
isSuccess,
businessCode,
businessMessage,
error: errorMsg,
durationMs: Date.now() - start,
});
}
return result;
}
/**
* 异步落库对外请求日志(不阻塞主流程,写入失败仅记录到错误日志)
* @param {Object} entry
*/
_log(entry) {
if (!this.app || !this.app.model || !this.app.model.ApiOutboundLog) return;
const payload = {
principal_id: this.principalId,
warehouse_id: this.warehouseId,
warehouse_api_id: this.warehouseApiId,
api_type: this.apiType,
method: entry.method,
url: maskSignInUrl(entry.url),
request_headers: JSON.stringify({ 'Content-Type': 'application/json' }),
request_body: safeStringify(maskObject(entry.params), MAX_LOG_BODY),
response_status: entry.responseStatus,
response_body: safeStringify(entry.responseText, MAX_LOG_BODY),
is_success: entry.isSuccess ? 1 : 0,
business_code: entry.businessCode,
business_message: entry.businessMessage,
error: entry.error ? entry.error.slice(0, 2000) : null,
duration: entry.durationMs,
};
this.app.model.ApiOutboundLog.create(payload).catch(err => {
this.app.logger.error(`[api-outbound-log] 写入失败:${err.message}`);
});
}
/**
* 业务码是否表示成功
* @param result
*/
isSuccess(result) {
if (!result) return false;
if (SUCCESS_CODES.has(result.code)) return true;
// 部分 WMS 用 flag 字段标识成功(如 {"flag":"success","code":1,...})
return result.flag === 'success' || result.flag === 'SUCCESS';
}
/**
* 从 singleitem.synchronize 响应中提取 WMS 内部商品ID(itemId)
* 兼容多种返回形态:
* - { data: { itemId } } / { data: { id } } / { data: <itemId 数字或字符串> }
* - 实测部分 WMS 直接把 itemId 放在响应顶层:{"flag":"success","code":1,"itemId":1001163,...}
* @param {Object} resp WMS 响应
* @return {number|null}
*/
static extractItemId(resp) {
if (!resp) return null;
// 1) data 字段内
if (resp.data != null) {
const d = resp.data;
if (typeof d === 'object') {
if (d.itemId != null) return Number(d.itemId);
if (d.id != null) return Number(d.id);
} else {
return Number(d);
}
}
// 2) 响应顶层(实测结构)
if (resp.itemId != null) return Number(resp.itemId);
if (resp.id != null) return Number(resp.id);
return null;
}
/** 心跳探测 */
async ping() {
return this.call('index.ping', {});
}
/**
* 商品资料推送:将 OMS 商品字段映射为 WMS singleitem.synchronize 的 item 结构并推送
* @param {Object} product OMS 商品(model 实例或 plain 对象)
* @return {Promise<{code,message,data}>}
*/
async pushItem(product) {
return this.call('singleitem.synchronize', { item: this._buildItem(product) });
}
/**
* 取入库单类型编码:入库单本身已按 WMS 编码落库(inbound_orders.inbound_type),
* 这里只做 trim/大写与合法性兜底,不再做语义映射(见 lib/wms/orderTypes.js)
* @param {string} inboundType 入库单类型编码,如 'CGRK'
* @return {string}
*/
_inboundOrderType(inboundType) {
return normalizeInboundOrderType(inboundType) || DEFAULT_INBOUND_ORDER_TYPE;
}
/**
* OMS 库存类型(inventory_type) → WMS orderLine.inventoryType
* WMS 规范:ZP=正品 CC=残次 JS=机损 XS=箱损 FP=废品,默认 ZP
* @param {string} inventoryType
* @return {string}
*/
_mapInventoryType(inventoryType) {
const allowed = [ 'ZP', 'CC', 'JS', 'XS', 'FP' ];
const code = String(inventoryType || 'ZP').toUpperCase();
return allowed.includes(code) ? code : 'ZP';
}
/** 日期格式化为 WMS 要求的 YYYY-MM-DD HH:MM:SS,失败返回空串 */
_fmtDateTime(value) {
if (!value) return '';
const d = value instanceof Date ? value : new Date(value);
if (isNaN(d.getTime())) return '';
const p = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
/**
* 构建 entryorder.create 请求体(对齐 WMS 入库单规范)
* 字段来源:单据头 + 明细(含商品快照),货主编码取接口配置 owner_code,仓库编码取 warehouse.code
* @param {Object} order OMS 入库单(model 实例或 plain,已 include warehouse/creator)
* @param {Array} items 入库明细(stock_items,已 include product)
* @param {Object} [opts] { warehouse, creator }
* @return {Object} { entryOrder, orderLines: { orderLine: [...] } }
*/
_buildEntryOrder(order, items, opts = {}) {
const o = order.get ? order.get({ plain: true }) : order;
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const creator = opts.creator && opts.creator.get ? opts.creator.get({ plain: true }) : (opts.creator || {});
const entryOrder = {
entryOrderCode: o.bill_no || '',
ownerCode: this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '',
warehouseCode: warehouse.code || 'OTHER',
orderCreateTime: this._fmtDateTime(o.created_at),
// openapi 渠道的入库单类型字段是 entryOrderType(默认 SCRK),不是 orderType
entryOrderType: this._inboundOrderType(o.inbound_type),
remark: o.remark || '',
};
if (o.purchase_order_code) entryOrder.purchaseOrderCode = o.purchase_order_code;
if (o.expect_start_time) entryOrder.expectStartTime = this._fmtDateTime(o.expect_start_time);
if (o.expect_end_time) entryOrder.expectEndTime = this._fmtDateTime(o.expect_end_time);
if (o.logistics_code) entryOrder.logisticsCode = o.logistics_code;
if (o.logistics_name) entryOrder.logisticsName = o.logistics_name;
if (o.express_code) entryOrder.expressCode = o.express_code;
if (o.supplier_code) entryOrder.supplierCode = o.supplier_code;
if (o.supplier) entryOrder.supplierName = o.supplier;
const operatorName = o.operator || creator.nickname || creator.username || '';
if (operatorName) entryOrder.operatorName = operatorName;
if (o.operator_code) entryOrder.operatorCode = o.operator_code;
entryOrder.operateTime = this._fmtDateTime(o.operate_time || o.updated_at || new Date());
// 发件人 / 收件人信息(JSON 对象,已是 WMS senderInfo/receiverInfo 结构则直接透传)
if (o.sender_info && typeof o.sender_info === 'object' && !Array.isArray(o.sender_info)) {
entryOrder.senderInfo = o.sender_info;
}
if (o.receiver_info && typeof o.receiver_info === 'object' && !Array.isArray(o.receiver_info)) {
entryOrder.receiverInfo = o.receiver_info;
}
// 扩展属性:{ key: value } 对象
if (o.extend_props && typeof o.extend_props === 'object' && !Array.isArray(o.extend_props)) {
entryOrder.extendProps = o.extend_props;
}
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
const itemCode = i.code || product.item_code || '';
return {
outBizCode: `${o.bill_no || 'RK'}-${idx + 1}`,
orderLineNo: String(idx + 1),
ownerCode: entryOrder.ownerCode,
itemCode,
itemName: i.name || product.item_name || '',
planQty: Number(i.quantity) || 0,
skuProperty: i.spec || product.sku_property || '',
purchasePrice: Number(i.price) || 0,
retailPrice: product.retail_price != null ? Number(product.retail_price) : 0,
inventoryType: this._mapInventoryType(i.inventory_type),
};
});
return {
entryOrder,
orderLines: { orderLine: orderLineList },
};
}
/**
* 入库单推送:将 OMS 入库单映射为 WMS entryorder.create 并推送
* @param {Object} order OMS 入库单(已 include warehouse/creator)
* @param {Array} items 入库明细(已 include product)
* @param {Object} [opts] { warehouse, creator }
* @return {Promise<{code,message,data}>}
*/
async createEntryOrder(order, items, opts = {}) {
return this.call('entryorder.create', this._buildEntryOrder(order, items, opts));
}
/**
* 取出库单类型编码:出库单本身已按 WMS 编码落库(outbound_orders.outbound_type),
* 这里只做 trim/大写与合法性兜底,不再做语义映射(见 lib/wms/orderTypes.js)
* 注:stockout.create 与 order.cancel 必须传同一个值,否则取消时定位不到单据
* @param {string} outboundType 出库单类型编码,如 'QTCK'
* @return {string}
*/
_outboundOrderType(outboundType) {
return normalizeOutboundOrderType(outboundType) || DEFAULT_OUTBOUND_ORDER_TYPE;
}
/**
* 构建 stockout.create(非订单出库单)请求体(对齐 WMS 出库单规范)
* 字段来源:单据头 + 明细(含商品快照);货主编码取接口配置 owner_code,仓库编码取 warehouse.code;
* 明细行 itemId 为 WMS 必填项,取 warehouse_products.wms_item_id(由调用方查好后传入)
* @param {Object} order OMS 出库单(model 实例或 plain,已 include warehouse)
* @param {Array} items 出库明细(stock_items,已 include product)
* @param {Object} [opts] { warehouse, wmsItemIdByProduct }
* @return {Object} { deliveryOrder, orderLines: { orderLine: [...] } }
*/
_buildStockout(order, items, opts = {}) {
const o = order.get ? order.get({ plain: true }) : order;
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
const ownerCode = this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '';
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
const wmsItemId = i.product_id != null ? wmsItemIdByProduct[Number(i.product_id)] : undefined;
const line = {
orderLineNo: String(idx + 1),
ownerCode,
itemCode: i.code || product.item_code || '',
itemName: i.name || product.item_name || '',
planQty: Number(i.quantity) || 0,
inventoryType: this._mapInventoryType(i.inventory_type),
};
// itemId 为 WMS 必填项:仅已推送到该仓库的商品才有 wms_item_id,缺失时不传
if (wmsItemId != null) line.itemId = wmsItemId;
return line;
});
const deliveryOrder = {
deliveryOrderCode: o.bill_no || '',
orderType: this._outboundOrderType(o.outbound_type),
warehouseCode: warehouse.code || 'OTHER',
createTime: this._fmtDateTime(o.created_at),
totalOrderLines: orderLineList.length,
remark: o.remark || '',
};
return {
deliveryOrder,
orderLines: { orderLine: orderLineList },
};
}
/**
* 出库单推送:将 OMS 出库单映射为 WMS stockout.create(非订单出库单)并推送
* @param {Object} order OMS 出库单(已 include warehouse)
* @param {Array} items 出库明细(已 include product)
* @param {Object} [opts] { warehouse, wmsItemIdByProduct }
* @return {Promise<{code,message,data}>}
*/
async createStockout(order, items, opts = {}) {
return this.call('stockout.create', this._buildStockout(order, items, opts));
}
/**
* 出库单取消:调用 order.cancel 取消已推送的外部出库单(stockout)
* 文档/源码依据:`order.cancel`,参数 orderCode(要取消的出库单号)+ orderType;
* openapiMethods/order.js 的 CK_TYPES = PTCK/DBCK/B2BCK/QTCK/CGTH 会按 stockout_order_code
* 定位 wms_order_stockout 并取消(释放锁定、状态置 CANCELLED);ORDER 组(JYCK/HHCK/BFCK)
* 走的是发货单表,与 stockout 不是同一张表,故此处必须传落库的 CK 编码。
* @param {Object} order OMS 出库单(model 实例或 plain)
* @return {Promise<{code,message,data}>} WMS 返回
*/
async cancelOrder(order) {
const o = order.get ? order.get({ plain: true }) : order;
return this.call('order.cancel', {
orderCode: o.bill_no || '',
orderType: this._outboundOrderType(o.outbound_type),
});
}
/**
* 取发货单订单类型编码:OMS 落库已按 WMS 编码(order_deliveries.order_type),
* 这里只做 trim/大写与合法性兜底;ORDER 组 = JYCK / HHCK / BFCK
* 注:deliveryorder.create 与 order.cancel 必须传同一个值,否则取消时定位不到单据
* @param {string} orderType 订单类型编码,如 'JYCK'
* @return {string}
*/
_deliveryOrderType(orderType) {
return normalizeDeliveryOrderType(orderType) || DEFAULT_DELIVERY_ORDER_TYPE;
}
/**
* 发货单明细库存类型:OMS 落 ZP 正品 / CC 残次,WMS orderLine.inventoryType 同口径直接透传
* @param {string} inventoryType
* @return {string}
*/
_mapDeliveryLineInventoryType(inventoryType) {
const code = String(inventoryType || 'ZP').trim().toUpperCase();
return [ 'ZP', 'CC', 'JS', 'XS', 'FP' ].includes(code) ? code : 'ZP';
}
/**
* 构建 deliveryorder.create(订单出库单/发货单)请求体(对齐 WMS 发货单规范)
*
* 字段口径来源:D:/wms/methods/openapi.json `deliveryorder.create`
* - 必填:deliveryOrder.deliveryOrderCode、orderLines.orderLine(非空,每行 planQty > 0)
* - 收件人:receiverInfo.name/mobile/province/city/area/detailAddress 必填(OMS 侧已按同名口径校验)
* - need_oms_waybill 在请求根节点(不在 deliveryOrder 内):手工单恒为 0,即「不用 OMS 取号」
* - 明细:itemId 与 itemCode 二选一,优先传 itemId(warehouse_products.wms_item_id 回写值),缺失时用 itemCode
* @param {Object} order OMS 发货单(model 实例或 plain,已 include warehouse)
* @param {Array} items 发货单明细(order_delivery_items,已 include product 时优先取商品快照)
* @param {Object} [opts] { warehouse, wmsItemIdByItemCode, wmsItemIdByProduct }
* @return {Object} { deliveryOrder, orderLines: { orderLine: [...] }, need_oms_waybill }
*/
_buildDeliveryOrder(order, items, opts = {}) {
const o = order.get ? order.get({ plain: true }) : order;
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
const wmsItemIdByItemCode = opts.wmsItemIdByItemCode || {};
const ownerCode = this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '';
const deliveryOrder = {
deliveryOrderCode: o.delivery_order_code || '',
orderType: this._deliveryOrderType(o.order_type),
warehouseCode: warehouse.code || o.warehouse_code || 'OTHER',
createTime: this._fmtDateTime(o.created_at),
totalOrderLines: (items || []).length,
isUrgency: this._yn(o.is_urgency),
invoiceFlag: this._yn(o.invoice_flag),
};
// 订单标记 / 来源订单号集合 / OAID 来源编码 / 来源平台(未填写时不传,由 WMS 按货主默认兜底)
if (o.order_flag) deliveryOrder.orderFlag = o.order_flag;
if (o.source_platform_code) deliveryOrder.sourcePlatformCode = o.source_platform_code;
if (o.source_platform_name) deliveryOrder.sourcePlatformName = o.source_platform_name;
if (o.pre_delivery_order_code) deliveryOrder.preDeliveryOrderCode = o.pre_delivery_order_code;
if (o.pre_delivery_order_id) deliveryOrder.preDeliveryOrderId = String(o.pre_delivery_order_id);
if (o.place_order_time) deliveryOrder.placeOrderTime = this._fmtDateTime(o.place_order_time);
if (o.pay_time) deliveryOrder.payTime = this._fmtDateTime(o.pay_time);
if (o.pay_no) deliveryOrder.payNo = o.pay_no;
if (o.shop_nick) deliveryOrder.shopNick = o.shop_nick;
if (o.seller_nick) deliveryOrder.sellerNick = o.seller_nick;
if (o.buyer_nick) deliveryOrder.buyerNick = o.buyer_nick;
if (o.seller_message) deliveryOrder.sellerMessage = o.seller_message;
if (o.buyer_message) deliveryOrder.buyerMessage = o.buyer_message;
if (o.source_order_codes) deliveryOrder.sourceOrderCodes = o.source_order_codes;
if (o.oaid_order_source_code) deliveryOrder.oaidOrderSourceCode = o.oaid_order_source_code;
const operatorName = o.operator_name || '';
if (operatorName) deliveryOrder.operatorName = operatorName;
deliveryOrder.operateTime = this._fmtDateTime(o.operate_time || o.updated_at || new Date());
// 金额:金额为空的项不下发(避免把货主默认金额覆盖成 0)
const amountFields = {
totalAmount: o.total_amount,
itemAmount: o.item_amount,
discountAmount: o.discount_amount,
freight: o.freight,
arAmount: o.ar_amount,
gotAmount: o.got_amount,
};
for (const [ key, value ] of Object.entries(amountFields)) {
if (value != null && value !== '') deliveryOrder[key] = Number(value);
}
// 物流:logisticsCode 用于匹配快递设置,expressCode/logisticsAreaCode 为取号回写值
if (o.logistics_code || o.logistics_name) {
deliveryOrder.logisticsCode = o.logistics_code || '';
deliveryOrder.logisticsName = o.logistics_name || '';
}
if (o.express_code) deliveryOrder.expressCode = o.express_code;
if (o.logistics_area_code) deliveryOrder.logisticsAreaCode = o.logistics_area_code;
deliveryOrder.receiverInfo = {
name: o.name || '',
tel: o.tel || '',
mobile: o.mobile || '',
email: o.email || '',
countryCode: o.country_code || '',
province: o.province || '',
city: o.city || '',
area: o.area || '',
town: o.town || '',
detailAddress: o.detail_address || '',
zipCode: o.zip_code || '',
};
if (o.oaid) deliveryOrder.receiverInfo.oaid = o.oaid;
// 扩展属性:{ key: value } 对象(手工单固定写 labels: "手工单")
if (o.extend_props && typeof o.extend_props === 'object' && !Array.isArray(o.extend_props)) {
deliveryOrder.extendProps = o.extend_props;
}
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
const productId = i.product_id != null ? Number(i.product_id) : (product.id != null ? Number(product.id) : null);
// itemId 优先取明细自带的 WMS 商品ID,其次按商品编码/OMS 商品ID 回查 warehouse_products.wms_item_id
const mappedItemId = (i.item_code && wmsItemIdByItemCode[i.item_code])
|| (productId != null ? wmsItemIdByProduct[productId] : undefined);
const itemId = i.item_id != null && i.item_id !== '' ? Number(i.item_id) : mappedItemId;
const line = {
orderLineNo: String(i.order_line_no == null || i.order_line_no === '' ? idx + 1 : i.order_line_no),
itemCode: i.item_code || product.item_code || '',
itemName: i.item_name || product.item_name || '',
planQty: Number(i.plan_qty) || 0,
actualPrice: i.actual_price != null && i.actual_price !== '' ? Number(i.actual_price) : 0,
retailPrice: i.retail_price != null && i.retail_price !== '' ? Number(i.retail_price) : 0,
inventoryType: this._mapDeliveryLineInventoryType(i.inventory_type),
ownerCode: i.owner_code || ownerCode,
};
// itemId 与 itemCode 二选一:有 WMS 内部商品ID 时一并下发,命中率更高
if (itemId != null && !isNaN(itemId)) line.itemId = itemId;
if (i.ext_code) line.extCode = i.ext_code;
if (i.source_order_code) line.sourceOrderCode = i.source_order_code;
if (i.sub_source_order_code) line.subSourceOrderCode = i.sub_source_order_code;
if (i.stock_id) line.stockId = Number(i.stock_id);
if (i.extend_props && typeof i.extend_props === 'object' && !Array.isArray(i.extend_props)) {
line.extendProps = JSON.stringify(i.extend_props);
}
return line;
});
return {
deliveryOrder,
orderLines: { orderLine: orderLineList },
// 手工创建的发货单恒为 0(不用 OMS 取号);该参数在请求根节点
need_oms_waybill: o.need_oms_waybill == null ? 0 : Number(o.need_oms_waybill),
};
}
/**
* 发货单推送:将 OMS 发货单映射为 WMS deliveryorder.create(ORDER 组,落 wms_order_delivery)并推送
* @param {Object} order OMS 发货单(已 include warehouse)
* @param {Array} items 发货单明细
* @param {Object} [opts] { warehouse, wmsItemIdByItemCode, wmsItemIdByProduct }
* @return {Promise<{code,message,data}>} WMS 返回(成功时 data.deliveryOrderId 为 WMS 内部订单ID)
*/
async createDeliveryOrder(order, items, opts = {}) {
return this.call('deliveryorder.create', this._buildDeliveryOrder(order, items, opts));
}
/**
* 发货单取消:调用 order.cancel 取消已推送的外部发货单(ORDER 组:JYCK/HHCK/BFCK)
* 文档/源码依据:openapiMethods/order.js 的 ORDER_TYPES 按 delivery_order_code 定位 wms_order_delivery,
* 取消后释放库存锁定、状态置 CANCELLED,并向开放平台回调 `deliveryorder.cancel` 事件。
* @param {Object} order OMS 发货单(model 实例或 plain)
* @return {Promise<{code,message,data}>} WMS 返回
*/
async cancelDeliveryOrder(order) {
const o = order.get ? order.get({ plain: true }) : order;
return this.call('order.cancel', {
orderCode: o.delivery_order_code || '',
orderType: this._deliveryOrderType(o.order_type),
});
}
/**
* 入库单取消:调用 order.cancel 取消已推送的外部入库单
* 文档/源码依据(D:\wms\methods/qimen.json + app/service/qimenMethods/order.js):
* `order.cancel` 入参 request.orderCode + request.orderType,RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)
* 会把入库单 order_status 置 CANCELLED;openapi 渠道(openapiMethods/order.js)只实现了 ORDER/CK 组,
* 收到 RK 类型会返回业务失败「暂不支持该订单类型的取消操作」——由调用方按「渠道不支持」降级处理。
* @param {Object} order OMS 入库单(model 实例或 plain)
* @return {Promise<{code,message,data}>} WMS 返回
*/
async cancelInboundOrder(order) {
const o = order.get ? order.get({ plain: true }) : order;
return this.call('order.cancel', {
orderCode: o.bill_no || '',
orderType: this._inboundOrderType(o.inbound_type),
});
}
/**
* 库存查询:按 WMS 内部商品ID批量查询库存量(inventory.query)
* @param {number[]} itemIds WMS 内部商品ID列表
* @return {Promise<Array<{itemId:number,itemCode:string,quantity:number,lockQuantity:number}>>}
* 返回 data.items 中的库存明细数组(仅含命中库存记录的商品)
*/
async queryInventory(itemIds = []) {
if (!Array.isArray(itemIds) || itemIds.length === 0) return [];
const resp = await this.call('inventory.query', { itemIds: itemIds.map(Number) });
if (!this.isSuccess(resp)) {
const err = new Error(`WMS 查询库存失败: ${resp && (resp.message || resp.code)}`);
err.wmsResponse = resp;
throw err;
}
// 兼容 data.items 与顶层 items 两种结构
if (resp && resp.data && Array.isArray(resp.data.items)) return resp.data.items;
if (resp && Array.isArray(resp.items)) return resp.items;
return [];
}
_yn(value) {
return value === 'Y' || value === 'y' || value === 1 || value === true ? 'Y' : 'N';
}
/**
* OMS 商品类型 → WMS singleitem.synchronize 的 itemType 英文编码
* 按 WMS 规范仅使用 ZC(正常商品) / CC(残次品) 两种:
* - 本系统商品均为正常品,残次品以 product_stocks 的 item_type=CC 库存行表示;
* - 故推送统一为 ZC(若显式为 'CC' 则直接采用,便于后续为残次单独建 SKU 推送)。
* @param {number|string} itemType OMS 数值类型或直接给定的编码
* @return {string} WMS 英文编码(仅 ZC / CC)
*/
_mapItemType(itemType) {
const code = String(itemType == null ? '' : itemType).toUpperCase();
if (code === 'CC') return 'CC';
return 'ZC';
}
/**
* OMS 商品 → WMS item 字段映射(参数名对齐 openapi.json singleitem.synchronize)
* @param product
*/
_buildItem(product) {
const f = this.fields || {};
const p = product.get ? product.get({ plain: true }) : product;
const nameParts = [ p.item_name ];
if (f.item_name_with_spec && p.sku_property) nameParts.push(p.sku_property);
return {
itemCode: p.item_code,
goodsCode: p.goods_code || '',
itemName: nameParts.join(' ').trim(),
barCode: p.barcode || '',
unit: p.stock_unit || '',
categoryId: p.category_id || 0,
categoryName: p.category_name || '',
itemType: this._mapItemType(p.item_type),
tagPrice: Number(p.tag_price) || 0,
retailPrice: Number(p.retail_price) || 0,
brandName: p.brand_name || '',
isSNMgmt: this._yn(p.is_sn_mgmt),
isShelfLifeMgmt: this._yn(p.is_shelf_life_mgmt),
isBatchMgmt: this._yn(p.is_batch_mgmt),
isAreaSale: this._yn(p.is_area_sale),
length: Number(p.length) || 0,
width: Number(p.width) || 0,
height: Number(p.height) || 0,
volume: Number(p.volume) || 0,
grossWeight: Number(p.gross_weight) || 0,
netWeight: Number(p.net_weight) || 0,
isValid: 'Y',
createTime: p.created_at ? new Date(p.created_at).toISOString() : '',
};
}
}
module.exports = QimenWmsClient;

100
backend/app/lib/wms/sign.js Normal file
View File

@ -0,0 +1,100 @@
'use strict';
/**
* 类奇门接口(WMS openapi)签名算法
*
* 与 WMS 侧 app/lib/api_sign.js 完全对齐:
* bodySign = md5( stableStringify(body) ).toLowerCase()
* canonicalQuery = 按 key 字母序拼接 `k=v&...`,忽略 sign/signature 与 undefined
* sign = md5( canonicalQuery + secret + bodySign ).toLowerCase()
*
* 注意:body 参与签名的是「解析后的对象」经稳定序列化后的结果(与 JSON 线格式无关),
* 因此调用方务必传入与请求体结构一致的对象(而非字符串)。
*/
const crypto = require('crypto');
/** 签名时忽略的 query 字段 */
const DEFAULT_IGNORE_KEYS = [ 'sign', 'signature' ];
function isPlainObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
/**
* 稳定序列化:递归按 key 字母序排列,确保对象键顺序固定(与 WMS 算法一致)
* @param {*} value
* @return {string}
*/
function stableStringify(value) {
if (value === undefined) return '';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map(stableStringify).join(',')}]`;
}
if (!isPlainObject(value)) return JSON.stringify(value);
const keys = Object.keys(value).sort();
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
}
/**
* 归一化参数值为可拼接字符串
* @param {*} value
* @return {string}
*/
function normalizeParamValue(value) {
if (value === undefined || value === null) return '';
if (typeof value === 'object') return stableStringify(value);
return String(value);
}
/**
* 构建按 key 字母序排列的 query 参数串(排除忽略字段与 undefined)
* @param {Object} params
* @param {string[]} ignoreKeys
* @return {string}
*/
function buildCanonicalQuery(params = {}, ignoreKeys = []) {
if (!isPlainObject(params)) throw new Error('query 参数必须是对象');
const ignoreKeySet = new Set((Array.isArray(ignoreKeys) ? ignoreKeys : []).map(k => String(k).toLowerCase()));
const keys = Object.keys(params)
.filter(key => !ignoreKeySet.has(String(key).toLowerCase()))
.filter(key => params[key] !== undefined)
.sort();
return keys.map(key => `${key}=${normalizeParamValue(params[key])}`).join('&');
}
/**
* 计算类奇门接口签名
* @param {Object} options
* @param {Object} options.query 参与签名的 query 参数(不含 sign),值与最终放到 URL 上的保持一致
* @param {*} options.body 请求体对象(与发送 JSON 体结构一致)
* @param {string} options.secret 应用密钥 app_secret
* @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段
* @return {string} 签名(小写 hex)
*/
function qimenSign({ query = {}, body, secret, ignoreKeys } = {}) {
const mergedIgnoreKeys = [ ...DEFAULT_IGNORE_KEYS, ...(Array.isArray(ignoreKeys) ? ignoreKeys : []) ];
const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys);
const serializedBody = typeof body === 'string' ? body : stableStringify(body);
const bodySign = crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex')
.toLowerCase();
const signText = `${canonicalQuery}${String(secret || '').trim()}${bodySign}`;
return crypto.createHash('md5').update(signText, 'utf8').digest('hex')
.toLowerCase();
}
/**
* 恒定时间比较签名(避免比较耗时泄露签名信息)
* @param {string} expected 服务端计算出的签名
* @param {string} provided 调用方传入的签名
* @return {boolean} 是否一致
*/
function timingSafeEqual(expected, provided) {
const left = Buffer.from(String(expected || ''), 'utf8');
const right = Buffer.from(String(provided || ''), 'utf8');
if (left.length !== right.length) return false;
return crypto.timingSafeEqual(left, right);
}
module.exports = { qimenSign, timingSafeEqual, stableStringify, buildCanonicalQuery, DEFAULT_IGNORE_KEYS };

View File

@ -0,0 +1,64 @@
'use strict';
/**
* 入库单模型,对应 inbound_orders 表(单据头)
* @param {Egg.Application} app egg application
* @return {object} inboundOrder model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, DATE } = app.Sequelize;
const InboundOrder = app.model.define('inbound_order', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
bill_no: { type: STRING(50), allowNull: false, comment: '入库单号' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
shop_id: { type: BIGINT.UNSIGNED, comment: '来源店铺/仓库ID' },
inbound_type: {
type: STRING(20),
allowNull: false,
defaultValue: 'CGRK',
comment: 'WMS 入库单类型:B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库',
},
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待入库 2已入库 3已取消' },
supplier: { type: STRING(255), comment: '供应商名称' },
supplier_code: { type: STRING(50), comment: '供应商编码' },
operator: { type: STRING(50), comment: '操作人名称' },
operator_code: { type: STRING(50), comment: '操作员编码' },
operate_time: { type: DATE, comment: '操作时间' },
purchase_order_code: { type: STRING(50), comment: '采购单号(orderType=CGRK 时使用)' },
expect_start_time: { type: DATE, comment: '预期到货开始时间' },
expect_end_time: { type: DATE, comment: '最迟预期到货时间' },
logistics_code: { type: STRING(50), comment: '物流公司编码(SF/YTO/ZTO 等)' },
logistics_name: { type: STRING(200), comment: '物流公司名称' },
express_code: { type: STRING(50), comment: '运单号' },
sender_info: { type: JSON, allowNull: true, comment: '发件人信息(WMS senderInfo)' },
receiver_info: { type: JSON, allowNull: true, comment: '收件人信息(WMS receiverInfo)' },
extend_props: { type: JSON, allowNull: true, comment: '扩展属性(WMS extendProps):{ key: value }' },
created_by: { type: BIGINT.UNSIGNED, comment: '创建人ID(关联 users)' },
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(关联 warehouses)' },
item_total: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细数量合计)' },
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '单据总金额' },
remark: { type: STRING(255), comment: '备注' },
audit_by: { type: BIGINT.UNSIGNED, allowNull: true, comment: '审核人ID(关联 users)' },
audit_time: { type: DATE, allowNull: true, comment: '审核时间' },
pushed_at: { type: DATE, allowNull: true, comment: 'WMS 推送时间' },
wms_push_result: { type: JSON, allowNull: true, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
void_at: { type: DATE, allowNull: true, comment: '作废时间(状态 5=已作废)' },
void_by: { type: BIGINT.UNSIGNED, allowNull: true, comment: '作废人ID(关联 users)' },
void_reason: { type: STRING(255), allowNull: true, comment: '作废原因' },
created_at: { type: DATE, comment: '创建时间' },
updated_at: { type: DATE, comment: '更新时间' },
});
InboundOrder.associate = () => {
app.model.InboundOrder.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.InboundOrder.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' });
app.model.InboundOrder.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
app.model.InboundOrder.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' });
app.model.InboundOrder.belongsTo(app.model.User, { foreignKey: 'audit_by', as: 'auditor' });
app.model.InboundOrder.belongsTo(app.model.User, { foreignKey: 'void_by', as: 'voider' });
};
return InboundOrder;
};

View File

@ -13,6 +13,7 @@ module.exports = app => {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
order_no: { type: STRING(50), allowNull: false, comment: '业务订单号' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
shop_id: { type: BIGINT.UNSIGNED, comment: '所属店铺ID,为空表示未关联店铺' },
order_type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '订单类型' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主状态:1待处理 2处理中 3已完成 4已取消' },
wms_status: { type: STRING(50), comment: '外部WMS状态' },
@ -32,6 +33,8 @@ module.exports = app => {
Order.associate = () => {
app.model.Order.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.Order.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' });
app.model.Order.hasMany(app.model.OrderItem, { foreignKey: 'order_id', as: 'items' });
};
return Order;

View File

@ -0,0 +1,50 @@
'use strict';
/**
* 出库单模型,对应 outbound_orders 表(单据头)
* @param {Egg.Application} app egg application
* @return {object} outboundOrder model
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, DATE } = app.Sequelize;
const OutboundOrder = app.model.define('outbound_order', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
bill_no: { type: STRING(50), allowNull: false, comment: '出库单号' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
shop_id: { type: BIGINT.UNSIGNED, comment: '目标店铺/仓库ID' },
outbound_type: {
type: STRING(20),
allowNull: false,
defaultValue: 'PTCK',
comment: 'WMS 出库单类型:PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单',
},
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待出库 2已出库 3已取消' },
customer: { type: STRING(255), comment: '客户/收货方' },
operator: { type: STRING(50), comment: '操作人' },
created_by: { type: BIGINT.UNSIGNED, comment: '创建人ID(关联 users)' },
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(关联 warehouses)' },
item_total: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细数量合计)' },
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '单据总金额' },
remark: { type: STRING(255), comment: '备注' },
stock_deducted: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '发货通知(notify.delivery)是否已扣减库存:1是 0否(幂等)' },
pushed_at: { type: DATE, allowNull: true, comment: 'WMS 推送时间' },
wms_push_result: { type: JSON, allowNull: true, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
void_at: { type: DATE, allowNull: true, comment: '作废时间(状态 5=已作废)' },
void_by: { type: BIGINT.UNSIGNED, allowNull: true, comment: '作废人ID(关联 users)' },
void_reason: { type: STRING(255), allowNull: true, comment: '作废原因' },
created_at: { type: DATE, comment: '创建时间' },
updated_at: { type: DATE, comment: '更新时间' },
});
OutboundOrder.associate = () => {
app.model.OutboundOrder.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.OutboundOrder.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' });
app.model.OutboundOrder.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
app.model.OutboundOrder.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' });
app.model.OutboundOrder.belongsTo(app.model.User, { foreignKey: 'void_by', as: 'voider' });
};
return OutboundOrder;
};

View File

@ -0,0 +1,47 @@
'use strict';
const stock = require('./stock');
/**
* 完成入库:把「已推送(3)」的入库单置为「已完成(4)」,并按明细增加系统库存。
* - 幂等:已完成的单据直接返回成功(不重复加库存),供 WMS 回调重复推送时安全复用
* - 明细为空时拒绝,避免「空单据」走完流程却不产生任何库存
* - 行级库存类型:inventory_type=CC → product_stocks.item_type='CC',其余(ZP 等)归为正品 ZC
* 复用入口:① 控制器手工「完成」 ② WMS 回调 entryorder.confirm(外部回推驱动)
* @param {Egg.Context} ctx
* @param {Object} order 入库单 model 实例(需含 id / principal_id / status)
* @return {Promise<{ok: boolean, already?: boolean, code?: number, message?: string}>}
*/
module.exports = async function completeInbound(ctx, order) {
if (!order) return { ok: false, code: 404, message: '入库单不存在' };
// 幂等:已完成直接返回
if (order.status === 4) return { ok: true, already: true };
if (order.status !== 3) {
return { ok: false, code: 400, message: '只有「已推送」状态的单据可以完成入库' };
}
const items = await ctx.model.StockItem.findAll({
where: { bill_type: 1, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
attributes: [ 'product_id', 'quantity', 'inventory_type' ],
order: [[ 'product_id', 'ASC' ]],
});
if (!items.length) {
return { ok: false, code: 400, message: '单据无明细,无法完成入库' };
}
const transaction = await ctx.model.transaction();
try {
for (const it of items) {
const p = it.get ? it.get({ plain: true }) : it;
// 行级库存类型:CC=残次 -> product_stocks 的 item_type='CC',其余(ZP等)归为正品 ZC
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
await stock.increase(ctx, order.principal_id, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
}
await order.update({ status: 4 }, { transaction });
await transaction.commit();
return { ok: true };
} catch (err) {
await transaction.rollback();
throw err;
}
};

View File

@ -0,0 +1,33 @@
'use strict';
/**
* 驳回时生成新单号:在基础单号后追加 / 递增 `_N` 后缀(首次 `_1`,再次 `_2` …)。
*
* 背景:已推送(3) 的单据被驳回后回到待处理,若沿用原单号再次推送,外部系统会因
* 「单据已存在」(入库单无法取消时必然发生)或沿用已作废的外部单据而失败;
* 驳回即换号可保证「一次推送对应一个全新的外部单号」。
*
* 基础单号识别规则:
* 1) 系统生成的「{前缀}_{自增id}」(如 RK_2 / CK_2)视为**无后缀**的基础单号,
* 避免把 id 里的 `_2` 误判成后缀(这是与历史手填单号最大的差异点);
* 2) 其它单号(如历史单号 `12`)剥离末尾 `_数字` 作为基础单号。
*
* @param {string} billNo 当前单号
* @param {number|string} id 单据主键(用于还原系统生成的单号)
* @param {string} prefix 单号前缀,入库 RK / 出库 CK
* @return {string} 驳回后的新单号,如 RK_2 -> RK_2_1 -> RK_2_2
*/
function nextRejectedBillNo(billNo, id, prefix) {
const current = String(billNo == null ? '' : billNo).trim();
if (!current) return current;
const systemBase = `${prefix}_${id}`;
const matched = current.match(/^(.+)_(\d+)$/);
// 系统生成的单号本身带 `_id`,先判等,再决定是否剥离后缀
const isSystemBase = current === systemBase;
const base = isSystemBase || !matched ? current : matched[1];
const seq = !isSystemBase && matched && matched[1] === base ? Number(matched[2]) + 1 : 1;
return `${base}_${seq}`;
}
module.exports = nextRejectedBillNo;

115
backend/app/utils/stock.js Normal file
View File

@ -0,0 +1,115 @@
'use strict';
/**
* 商品系统库存(product_stocks)操作工具
* 库存按 item_type(存储类型,与 WMS itemType 对齐)分多行存储:
* ZC=正品 / CC=残次品,每行:可用 = 总数量 - 锁定数量
* - increase / decrease:增加/减少某类型总数量
* - lock / unlock / deduct:占用与扣减(默认 ZC 正品维度,残次品一般只增减小计不动锁定)
* 全部在事务内使用行锁(SELECT ... FOR UPDATE)保证并发安全
*/
async function getOrCreate(ctx, principalId, productId, itemType = 'ZC', transaction) {
let row = await ctx.model.ProductStock.findOne({
where: { principal_id: principalId, product_id: productId, item_type: itemType },
lock: true,
transaction,
});
if (!row) {
row = await ctx.model.ProductStock.create(
{
principal_id: principalId,
product_id: productId,
item_type: itemType,
quantity: 0,
lock_quantity: 0,
available: 0,
},
{ transaction },
);
}
return row;
}
function recompute(row) {
const qty = Number(row.quantity) || 0;
const lock = Number(row.lock_quantity) || 0;
row.available = qty - lock;
}
/** 增加某类型总数量 */
async function increase(ctx, principalId, productId, qty, transaction, itemType = 'ZC') {
const n = Number(qty) || 0;
if (n <= 0) return null;
const row = await getOrCreate(ctx, principalId, productId, itemType, transaction);
row.quantity = Number(row.quantity) + n;
recompute(row);
await row.save({ transaction });
return row;
}
/** 锁定某类型库存:可用不足时抛出「库存不足」(err.code = INSUFFICIENT_STOCK) */
async function lock(ctx, principalId, productId, qty, transaction, itemType = 'ZC') {
const n = Number(qty) || 0;
if (n <= 0) return null;
const row = await getOrCreate(ctx, principalId, productId, itemType, transaction);
const available = Number(row.quantity) - Number(row.lock_quantity);
if (available < n) {
const err = new Error('库存不足');
err.code = 'INSUFFICIENT_STOCK';
err.productId = productId;
err.available = available;
err.require = n;
throw err;
}
row.lock_quantity = Number(row.lock_quantity) + n;
recompute(row);
await row.save({ transaction });
return row;
}
/** 解锁某类型库存(出库单取消/恢复时回滚锁定) */
async function unlock(ctx, principalId, productId, qty, transaction, itemType = 'ZC') {
const n = Number(qty) || 0;
if (n <= 0) return null;
const row = await getOrCreate(ctx, principalId, productId, itemType, transaction);
row.lock_quantity = Math.max(0, Number(row.lock_quantity) - n);
recompute(row);
await row.save({ transaction });
return row;
}
/** 发货扣减:总数量与锁定各减 qty */
async function deduct(ctx, principalId, productId, qty, transaction, itemType = 'ZC') {
const n = Number(qty) || 0;
if (n <= 0) return null;
const row = await getOrCreate(ctx, principalId, productId, itemType, transaction);
row.quantity = Math.max(0, Number(row.quantity) - n);
row.lock_quantity = Math.max(0, Number(row.lock_quantity) - n);
recompute(row);
await row.save({ transaction });
return row;
}
/** 仅减少某类型总数量(库存同步覆盖用:系统多于外部,已直接完成的出库单,不动锁定) */
async function decrease(ctx, principalId, productId, qty, transaction, itemType = 'ZC') {
const n = Number(qty) || 0;
if (n <= 0) return null;
const row = await getOrCreate(ctx, principalId, productId, itemType, transaction);
row.quantity = Math.max(0, Number(row.quantity) - n);
recompute(row);
await row.save({ transaction });
return row;
}
/** 残次品:入库增加总数量(等价于 increase(..., 'CC')) */
async function increaseDefect(ctx, principalId, productId, qty, transaction) {
return increase(ctx, principalId, productId, qty, transaction, 'CC');
}
/** 残次品:仅减少总数量(等价于 decrease(..., 'CC')) */
async function decreaseDefect(ctx, principalId, productId, qty, transaction) {
return decrease(ctx, principalId, productId, qty, transaction, 'CC');
}
module.exports = { getOrCreate, increase, lock, unlock, deduct, decrease, increaseDefect, decreaseDefect };

View File

@ -0,0 +1,20 @@
'use strict';
/**
* 出库单新增 stock_deducted 标记:WMS 发货通知(notify.delivery)是否已扣减库存,
* 用于幂等(避免 WMS 重推时重复扣减)
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('outbound_orders', 'stock_deducted', {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '发货通知(notify.delivery)是否已扣减库存:1是 0否(幂等用)',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('outbound_orders', 'stock_deducted');
},
};

View File

@ -0,0 +1,26 @@
'use strict';
/**
* 出库单新增 WMS 推送字段:
* - pushed_at 推送时间
* - wms_push_result WMS 推送结果(外部单号/返回码/消息/原始报文),用于排查与回显
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('outbound_orders', 'pushed_at', {
type: Sequelize.DATE,
allowNull: true,
comment: 'WMS 推送时间',
});
await queryInterface.addColumn('outbound_orders', 'wms_push_result', {
type: Sequelize.JSON,
allowNull: true,
comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('outbound_orders', 'wms_push_result');
await queryInterface.removeColumn('outbound_orders', 'pushed_at');
},
};

View File

@ -0,0 +1,54 @@
'use strict';
/**
* 入库单 / 出入库明细 补充 WMS entryorder.create 所需的字段:
* - inbound_orders:采购单号、预期到货时间、物流信息、供应商编码、操作员编码、操作时间
* - stock_items:inventory_type(库存类型 ZP=正品 / CC=残次,对齐 WMS 入库单行级 inventoryType)
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING, DATE } = Sequelize;
await queryInterface.addColumn('inbound_orders', 'purchase_order_code', {
type: STRING(50), allowNull: true, comment: '采购单号(orderType=CGRK 时使用)',
});
await queryInterface.addColumn('inbound_orders', 'expect_start_time', {
type: DATE, allowNull: true, comment: '预期到货开始时间',
});
await queryInterface.addColumn('inbound_orders', 'expect_end_time', {
type: DATE, allowNull: true, comment: '最迟预期到货时间',
});
await queryInterface.addColumn('inbound_orders', 'logistics_code', {
type: STRING(50), allowNull: true, comment: '物流公司编码(WMS 标准编码,如 SF/YTO/ZTO)',
});
await queryInterface.addColumn('inbound_orders', 'logistics_name', {
type: STRING(200), allowNull: true, comment: '物流公司名称',
});
await queryInterface.addColumn('inbound_orders', 'express_code', {
type: STRING(50), allowNull: true, comment: '运单号',
});
await queryInterface.addColumn('inbound_orders', 'supplier_code', {
type: STRING(50), allowNull: true, comment: '供应商编码',
});
await queryInterface.addColumn('inbound_orders', 'operator_code', {
type: STRING(50), allowNull: true, comment: '操作员编码',
});
await queryInterface.addColumn('inbound_orders', 'operate_time', {
type: DATE, allowNull: true, comment: '操作时间',
});
await queryInterface.addColumn('stock_items', 'inventory_type', {
type: STRING(10), allowNull: false, defaultValue: 'ZP',
comment: '库存类型:ZP=正品 CC=残次(对齐 WMS 入库单行级 inventoryType)',
});
},
async down(queryInterface) {
const cols = await queryInterface.describeTable('inbound_orders');
for (const c of [ 'purchase_order_code', 'expect_start_time', 'expect_end_time', 'logistics_code', 'logistics_name', 'express_code', 'supplier_code', 'operator_code', 'operate_time' ]) {
if (cols[c]) await queryInterface.removeColumn('inbound_orders', c);
}
const sCols = await queryInterface.describeTable('stock_items');
if (sCols.inventory_type) await queryInterface.removeColumn('stock_items', 'inventory_type');
},
};

View File

@ -0,0 +1,39 @@
'use strict';
/**
* 入库单补充 WMS entryorder.create 的结构化扩展字段:
* - related_orders:关联单据(relatedOrders),数组 [{ orderType, orderCode }]
* - sender_info:发件人信息(senderInfo 对象)
* - receiver_info:收件人信息(receiverInfo 对象)
* - extend_props:扩展属性(extendProps 对象 { key: value })
* 这些字段结构较复杂,用 JSON 列承载,推送时按 WMS 规范组装进报文。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { JSON } = Sequelize;
await queryInterface.addColumn('inbound_orders', 'related_orders', {
type: JSON, allowNull: true,
comment: '关联单据(WMS relatedOrders):[{ orderType: CG/DB/CK/RK, orderCode }]',
});
await queryInterface.addColumn('inbound_orders', 'sender_info', {
type: JSON, allowNull: true,
comment: '发件人信息(WMS senderInfo):{ company,name,zipCode,tel,mobile,email,countryCode,province,city,area,town,detailAddress }',
});
await queryInterface.addColumn('inbound_orders', 'receiver_info', {
type: JSON, allowNull: true,
comment: '收件人信息(WMS receiverInfo):{ company,name,zipCode,tel,mobile,email,countryCode,province,city,area,town,detailAddress }',
});
await queryInterface.addColumn('inbound_orders', 'extend_props', {
type: JSON, allowNull: true,
comment: '扩展属性(WMS extendProps):{ key: value }',
});
},
async down(queryInterface) {
const cols = await queryInterface.describeTable('inbound_orders');
for (const c of [ 'related_orders', 'sender_info', 'receiver_info', 'extend_props' ]) {
if (cols[c]) await queryInterface.removeColumn('inbound_orders', c);
}
},
};

View File

@ -0,0 +1,35 @@
'use strict';
/**
* 入库单 WMS 推送结果留痕:
* - pushed_at:推送到外部仓库的时间
* - wms_push_result:外部仓返回结果(外部单号 / 返回码 / 消息 / 原始报文)JSON
* 幂等:仅当列不存在时才新增,适配已存在相关列的库。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { DATE, JSON } = Sequelize;
const cols = await queryInterface.describeTable('inbound_orders');
if (!cols.pushed_at) {
await queryInterface.addColumn('inbound_orders', 'pushed_at', {
type: DATE,
allowNull: true,
comment: 'WMS 推送时间',
});
}
if (!cols.wms_push_result) {
await queryInterface.addColumn('inbound_orders', 'wms_push_result', {
type: JSON,
allowNull: true,
comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)',
});
}
},
async down(queryInterface) {
const cols = await queryInterface.describeTable('inbound_orders');
if (cols.wms_push_result) await queryInterface.removeColumn('inbound_orders', 'wms_push_result');
if (cols.pushed_at) await queryInterface.removeColumn('inbound_orders', 'pushed_at');
},
};

View File

@ -0,0 +1,33 @@
'use strict';
/**
* 入库单审核留痕:审核人(audit_by)+ 审核时间(audit_time)
* 幂等:仅当列不存在时才新增。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, DATE } = Sequelize;
const cols = await queryInterface.describeTable('inbound_orders');
if (!cols.audit_by) {
await queryInterface.addColumn('inbound_orders', 'audit_by', {
type: BIGINT,
allowNull: true,
comment: '审核人ID(关联 users)',
});
}
if (!cols.audit_time) {
await queryInterface.addColumn('inbound_orders', 'audit_time', {
type: DATE,
allowNull: true,
comment: '审核时间',
});
}
},
async down(queryInterface) {
const cols = await queryInterface.describeTable('inbound_orders');
if (cols.audit_time) await queryInterface.removeColumn('inbound_orders', 'audit_time');
if (cols.audit_by) await queryInterface.removeColumn('inbound_orders', 'audit_by');
},
};

View File

@ -0,0 +1,38 @@
'use strict';
/**
* 入库单 / 出库单「作废」字段:
* - void_at:作废时间
* - void_by:作废人ID(关联 users)
* - void_reason:作废原因(选填)
* 配合状态值 5=已作废 使用:已审核(2) 及之后的单据禁止物理删除,已审核单只能作废。
*/
const TABLES = [ 'inbound_orders', 'outbound_orders' ];
const COLUMNS = [ 'void_at', 'void_by', 'void_reason' ];
module.exports = {
async up(queryInterface, Sequelize) {
const { DATE, BIGINT, STRING } = Sequelize;
for (const table of TABLES) {
await queryInterface.addColumn(table, 'void_at', {
type: DATE, allowNull: true, comment: '作废时间',
});
await queryInterface.addColumn(table, 'void_by', {
type: BIGINT.UNSIGNED, allowNull: true, comment: '作废人ID(关联 users)',
});
await queryInterface.addColumn(table, 'void_reason', {
type: STRING(255), allowNull: true, comment: '作废原因',
});
}
},
async down(queryInterface) {
for (const table of TABLES) {
const cols = await queryInterface.describeTable(table);
for (const c of COLUMNS) {
if (cols[c]) await queryInterface.removeColumn(table, c);
}
}
},
};

View File

@ -0,0 +1,36 @@
'use strict';
/**
* 出入库明细(stock_items)增加「应 / 已」数量字段:
* - plan_in_qty 应入数量(入库明细,创建时取明细数量 quantity)
* - actual_in_qty 已入数量(入库明细,WMS 收货确认 entryorder.confirm 回推写入)
* - plan_out_qty 应出数量(出库明细,创建时取明细数量 quantity)
* - actual_out_qty 已出数量(出库明细,WMS 发货通知 notify.delivery 回推写入)
* 4 列默认 0,前端创建时不输入,由系统维护(应=明细数量,已=外部回推)。
*/
const TABLE = 'stock_items';
const COLUMNS = [ 'plan_in_qty', 'actual_in_qty', 'plan_out_qty', 'actual_out_qty' ];
module.exports = {
async up(queryInterface, Sequelize) {
const { DECIMAL } = Sequelize;
const comments = {
plan_in_qty: '应入数量(入库明细,默认取明细数量)',
actual_in_qty: '已入数量(入库明细,WMS 收货确认回推)',
plan_out_qty: '应出数量(出库明细,默认取明细数量)',
actual_out_qty: '已出数量(出库明细,WMS 发货回推)',
};
for (const c of COLUMNS) {
await queryInterface.addColumn(TABLE, c, {
type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: comments[c],
});
}
},
async down(queryInterface) {
const cols = await queryInterface.describeTable(TABLE);
for (const c of COLUMNS) {
if (cols[c]) await queryInterface.removeColumn(TABLE, c);
}
},
};

View File

@ -0,0 +1,20 @@
'use strict';
/**
* 回填存量出入库明细的「应」数量:应入/应出 = 明细数量(quantity)。
* 新字段建列时默认 0,存量数据需与「应=明细数量」规则对齐;「已」数量保持 0(等外部回推)。
*/
module.exports = {
async up(queryInterface) {
await queryInterface.sequelize.query(
'UPDATE stock_items SET plan_in_qty = quantity WHERE bill_type = 1 AND plan_in_qty = 0',
);
await queryInterface.sequelize.query(
'UPDATE stock_items SET plan_out_qty = quantity WHERE bill_type = 2 AND plan_out_qty = 0',
);
},
async down() {
// 回填动作无需回退(列本身由上一个迁移负责增删)
},
};

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 移除入库单的「关联单据」字段(related_orders)。
* 原因:WMS 接口文档(D:\wms\methods)中 entryorder.create 并无 relatedOrders 参数
* (全量文档搜 relatedOrder 0 命中),该字段推送后不被外部接收,属无效字段,
* 故从推送报文、模型与库表中一并裁剪。
*/
module.exports = {
async up(queryInterface) {
const cols = await queryInterface.describeTable('inbound_orders');
if (cols.related_orders) {
await queryInterface.removeColumn('inbound_orders', 'related_orders');
}
},
async down(queryInterface, Sequelize) {
const cols = await queryInterface.describeTable('inbound_orders');
if (!cols.related_orders) {
await queryInterface.addColumn('inbound_orders', 'related_orders', {
type: Sequelize.JSON,
allowNull: true,
comment: '关联单据:[{ orderType, orderCode }](已废弃)',
});
}
},
};

View File

@ -0,0 +1,57 @@
'use strict';
/**
* 入库单类型(inbound_orders.inbound_type)由内部数字枚举(1采购入库 / 2退货入库 / 9其他)
* 改为直接存储 WMS 入库单类型编码(RK 组 7 值):
* B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 /
* CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库
*
* 原因:
* 1) 推送走 openapi 渠道,entryorder.create 的类型字段是 `entryOrder.entryOrderType`
* (可选,默认 SCRK),需要在库中直接保存外发/已外发的类型,避免推送时临时映射造成口径漂移;
* 2) 取消单据 order.cancel 的 orderType 必须与创建时一致,落库后才能保证
* 「创建用什么类型、取消(驳回)就用什么类型」。
*
* 数据映射:1 -> CGRK(采购入库)、2 -> QTRK(RK 组无退货入库编码)、9 -> QTRK(其他入库)。
*/
const TABLE = 'inbound_orders';
const COLUMN = 'inbound_type';
const COMMENT = 'WMS 入库单类型:B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库';
const VALUE_MAP = { 1: 'CGRK', 2: 'QTRK', 9: 'QTRK' };
const LEGAL_CODES = [ 'B2BRK', 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK' ];
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.changeColumn(TABLE, COLUMN, {
type: STRING(20),
allowNull: false,
defaultValue: 'CGRK',
comment: COMMENT,
});
// 历史数字值 → WMS 编码
for (const [ from, to ] of Object.entries(VALUE_MAP)) {
await queryInterface.sequelize.query(
`UPDATE ${TABLE} SET ${COLUMN} = ? WHERE ${COLUMN} = ?`,
{ replacements: [ to, String(from) ] }
);
}
// 兜底:不在合法编码内的脏值按「其他入库」处理
await queryInterface.sequelize.query(
`UPDATE ${TABLE} SET ${COLUMN} = 'QTRK' WHERE ${COLUMN} NOT IN (${LEGAL_CODES.map(c => `'${c}'`).join(', ')})`
);
},
async down(queryInterface, Sequelize) {
const { TINYINT } = Sequelize;
// 回退映射:采购入库 → 1,其余 → 9
await queryInterface.sequelize.query(`UPDATE ${TABLE} SET ${COLUMN} = '9' WHERE ${COLUMN} <> 'CGRK'`);
await queryInterface.sequelize.query(`UPDATE ${TABLE} SET ${COLUMN} = '1' WHERE ${COLUMN} = 'CGRK'`);
await queryInterface.changeColumn(TABLE, COLUMN, {
type: TINYINT,
allowNull: false,
defaultValue: 1,
comment: '入库类型:1采购入库 2退货入库 9其他',
});
},
};

View File

@ -0,0 +1,58 @@
'use strict';
/**
* 出库单类型(outbound_orders.outbound_type)由内部数字枚举(1销售出库 / 2退货出库 / 9其他)
* 改为直接存储 WMS 出库单类型编码(CK 组 5 值):
* PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单
*
* 原因:
* 1) 出库走 stockout.create,deliveryOrder.orderType 必须是该单据在 WMS 的真实类型;
* 2) 取消走 order.cancel,openapiMethods/order.js 的 CK_TYPES = PTCK/DBCK/B2BCK/QTCK/CGTH
* 会按 stockout_order_code 定位 wms_order_stockout 后取消;而 ORDER 组(JYCK/HHCK/BFCK)
* 查的是发货单表 wms_order_delivery,用 JYCK 取消 stockout 会返回 404「未找到对应的订单」。
* 因此创建与取消必须使用同一套 CK 编码,落库后直传,保证口径一致。
*
* 数据映射:1 -> PTCK(普通出库单)、2 -> CGTH(采购退货出库单)、9 -> QTCK(其他出库)。
*/
const TABLE = 'outbound_orders';
const COLUMN = 'outbound_type';
const COMMENT = 'WMS 出库单类型:PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单';
const VALUE_MAP = { 1: 'PTCK', 2: 'CGTH', 9: 'QTCK' };
const LEGAL_CODES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ];
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.changeColumn(TABLE, COLUMN, {
type: STRING(20),
allowNull: false,
defaultValue: 'PTCK',
comment: COMMENT,
});
// 历史数字值 → WMS 编码
for (const [ from, to ] of Object.entries(VALUE_MAP)) {
await queryInterface.sequelize.query(
`UPDATE ${TABLE} SET ${COLUMN} = ? WHERE ${COLUMN} = ?`,
{ replacements: [ to, String(from) ] }
);
}
// 兜底:不在合法编码内的脏值按「其他出库」处理
await queryInterface.sequelize.query(
`UPDATE ${TABLE} SET ${COLUMN} = 'QTCK' WHERE ${COLUMN} NOT IN (${LEGAL_CODES.map(c => `'${c}'`).join(', ')})`
);
},
async down(queryInterface, Sequelize) {
const { TINYINT } = Sequelize;
// 回退映射:普通出库单 → 1,采购退货出库单 → 2,其余 → 9
await queryInterface.sequelize.query(`UPDATE ${TABLE} SET ${COLUMN} = '9' WHERE ${COLUMN} NOT IN ('PTCK', 'CGTH')`);
await queryInterface.sequelize.query(`UPDATE ${TABLE} SET ${COLUMN} = '2' WHERE ${COLUMN} = 'CGTH'`);
await queryInterface.sequelize.query(`UPDATE ${TABLE} SET ${COLUMN} = '1' WHERE ${COLUMN} = 'PTCK'`);
await queryInterface.changeColumn(TABLE, COLUMN, {
type: TINYINT,
allowNull: false,
defaultValue: 1,
comment: '出库类型:1销售出库 2退货出库 9其他',
});
},
};