feat(backend): 对外通用回调接口 /openapi 与回调日志
- POST /openapi 入口(controller/openapi.js),协议与 WMS openapi 对齐(method/app_key/sign) - 方法注册表 lib/openapiMethods.js:index.ping、entryorder.confirm/match、deliveryorder.confirm、stockout.confirm、order.cancel - 单据处理公共逻辑 lib/orderCallback.js;请求/响应封装 lib/apiResponse.js、lib/openapiCallback.js - WMS 回调入口 controller/wmsNotify.js 改为复用公共模块 - 回调日志:callback_logs 表 + lib/callbackLog.js(脱敏、fire-and-forget)
This commit is contained in:
parent
11e7b26ced
commit
0a9ee3c593
169
backend/app/controller/openapi.js
Normal file
169
backend/app/controller/openapi.js
Normal file
@ -0,0 +1,169 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { qimenSign, timingSafeEqual } = require('../lib/wms/sign');
|
||||
const { toSuccess, toFailure, nowTimestamp } = require('../lib/apiResponse');
|
||||
const { normalizeTimestamp, isTimestampValid, parseBody } = require('../lib/openapiCallback');
|
||||
const { recordCallbackLog } = require('../lib/callbackLog');
|
||||
const openapiMethods = require('../lib/openapiMethods');
|
||||
|
||||
/**
|
||||
* @controller OpenapiController 对外通用回调接口(公开)
|
||||
*
|
||||
* 外部系统(WMS/第三方)统一通过 POST /openapi 回调 OMS,协议与 WMS /openapi 对齐:
|
||||
* - query:method(模块.动作,如 index.ping)/ app_key / v / timestamp / sign
|
||||
* - body :业务参数 JSON
|
||||
* - 签名:md5(canonicalQuery + app_secret + md5(stableStringify(body)))
|
||||
* - 返回:{ flag, code, message, data, timestamp };失败时 HTTP 状态码与业务码一致
|
||||
*
|
||||
* 处理流程:校验系统参数与时间戳 → 按 app_key 定位仓库接口配置与仓库(数据隔离靠
|
||||
* warehouse_apis.principal_id / warehouse_id)→ 验签 → 按 method 分发到
|
||||
* app/lib/openapiMethods.js 中注册的方法(index.ping / entryorder.confirm / entryorder.match /
|
||||
* deliveryorder.confirm / stockout.confirm / order.cancel),单据处理统一走 app/lib/orderCallback.js。
|
||||
* 每次请求(含未通过校验的)都会写入 callback_logs,记录请求 query/报文与返回报文。
|
||||
*/
|
||||
class OpenapiController extends Controller {
|
||||
/**
|
||||
* 对外回调统一入口:处理请求、按 OpenAPI 协议输出响应,并记录请求与返回
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const startedAt = Date.now();
|
||||
let result;
|
||||
try {
|
||||
result = await this.handle();
|
||||
} catch (err) {
|
||||
ctx.logger.error('[openapi] 处理异常', err);
|
||||
result = { ok: false, httpStatus: 500, code: 500, message: `接口错误: ${err.message}` };
|
||||
}
|
||||
|
||||
const ok = !!result.ok;
|
||||
const httpStatus = ok ? 200 : (result.httpStatus || 500);
|
||||
const body = ok
|
||||
? toSuccess(result.data, result.message || 'ok')
|
||||
: toFailure({ message: result.message || '请求失败', code: result.code || httpStatus, data: result.data });
|
||||
|
||||
ctx.status = httpStatus;
|
||||
ctx.body = body;
|
||||
ctx.type = 'application/json';
|
||||
|
||||
// 回调日志:请求(query/报文)+ 返回(业务码/报文),未通过 app_key 校验的请求同样记录
|
||||
recordCallbackLog(this.app, {
|
||||
method: ctx.query.method,
|
||||
appKey: ctx.query.app_key || ctx.query.appkey,
|
||||
query: ctx.query,
|
||||
requestBody: ctx.request.body,
|
||||
responseBody: body,
|
||||
api: result.api,
|
||||
warehouse: result.warehouse,
|
||||
httpStatus,
|
||||
ok,
|
||||
message: result.message || body.message,
|
||||
duration: Date.now() - startedAt,
|
||||
ip: ctx.ip,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验系统参数、按 app_key 定位仓库、验签并分发到具体 method
|
||||
* @return {Promise<{ok: Boolean, data?: *, message?: String, httpStatus?: Number, code?: Number}>} 处理结果
|
||||
*/
|
||||
async handle() {
|
||||
const { ctx } = this;
|
||||
const query = ctx.query || {};
|
||||
const method = String(query.method || '').trim();
|
||||
const appKey = String(query.app_key || query.appkey || '').trim();
|
||||
const providedSign = String(query.sign || query.signature || '').trim();
|
||||
|
||||
if (!method || !method.includes('.')) {
|
||||
return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: method(需为 模块.动作,如 index.ping)' };
|
||||
}
|
||||
if (!appKey) {
|
||||
return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: app_key' };
|
||||
}
|
||||
if (!providedSign) {
|
||||
return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: sign' };
|
||||
}
|
||||
const timestamp = normalizeTimestamp(query.timestamp);
|
||||
if (timestamp == null) {
|
||||
return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: timestamp' };
|
||||
}
|
||||
if (!isTimestampValid(timestamp)) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: `时间戳已过期或无效,服务器时间: ${nowTimestamp()}`,
|
||||
};
|
||||
}
|
||||
|
||||
// 按 app_key 定位仓库接口配置:一个 app_key 唯一对应「某主体某仓库」的一条启用配置
|
||||
const api = await ctx.model.WarehouseApi.findOne({
|
||||
where: { app_key: appKey, status: 1 },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!api) {
|
||||
return { ok: false, httpStatus: 401, code: 401, message: `app_key 校验失败: 未找到启用的接口配置(app_key=${appKey})` };
|
||||
}
|
||||
if (!api.app_secret) {
|
||||
return { ok: false, httpStatus: 401, code: 401, message: 'app_key 校验失败: 接口配置未设置应用密钥' };
|
||||
}
|
||||
|
||||
// 定位该接口配置所属仓库(主体隔离与仓库编码均由此得出)
|
||||
const warehouse = await ctx.model.Warehouse.findByPk(api.warehouse_id);
|
||||
if (!warehouse) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 403,
|
||||
code: 403,
|
||||
message: `仓库定位失败: 接口配置关联的仓库不存在(warehouse_id=${api.warehouse_id})`,
|
||||
};
|
||||
}
|
||||
|
||||
// 验签:query 全量参与(sign/signature 自动忽略),body 用解析后的对象
|
||||
const body = parseBody(ctx);
|
||||
const expectSign = qimenSign({ query, body, secret: api.app_secret });
|
||||
if (!timingSafeEqual(expectSign, providedSign)) {
|
||||
ctx.logger.warn('[openapi] 签名校验失败', { appKey, method });
|
||||
return { ok: false, httpStatus: 401, code: 401, message: '签名校验失败', api, warehouse };
|
||||
}
|
||||
|
||||
const handler = openapiMethods.resolve(method);
|
||||
if (!handler) {
|
||||
// 未注册的方法必须报错(HTTP 400 + 业务码 400),不静默回执成功,避免调用方误以为已处理
|
||||
ctx.logger.warn('[openapi] 未注册的方法', { appKey, method, supported: openapiMethods.list() });
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: `openapi method 不存在: ${method}(已支持: ${openapiMethods.list().join(', ')})`,
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
|
||||
const handled = await handler(ctx, { api, warehouse, body, query, appKey, method, timestamp });
|
||||
// 方法返回 { ok, message, data }:ok=false 视为业务处理失败(HTTP 400),便于调用方重试/告警
|
||||
if (handled && handled.ok === false) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: handled.message || '业务处理失败',
|
||||
data: handled.data,
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
message: (handled && handled.message) || 'ok',
|
||||
data: handled ? handled.data : null,
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiController;
|
||||
185
backend/app/controller/wmsNotify.js
Normal file
185
backend/app/controller/wmsNotify.js
Normal file
@ -0,0 +1,185 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { qimenSign, timingSafeEqual } = require('../lib/wms/sign');
|
||||
const orderCallback = require('../lib/orderCallback');
|
||||
const stock = require('../utils/stock');
|
||||
|
||||
/** 时间戳时效阈值:±10 分钟(600 秒),与 WMS 文档一致 */
|
||||
const TIME_TOLERANCE_SEC = 600;
|
||||
|
||||
/**
|
||||
* 明细行提取与「实际数量写回」统一走 app/lib/orderCallback.js(与 /openapi 回调共用一份实现)
|
||||
* - 兼容 orderLines.orderLine / orderLines / items 等结构
|
||||
* - 按 itemCode 匹配明细行,写回 actual_in_qty / actual_out_qty
|
||||
*/
|
||||
const extractNotifyLines = orderCallback.extractLines;
|
||||
const applyActualQty = orderCallback.applyActualQty;
|
||||
|
||||
/**
|
||||
* @controller WmsNotifyController WMS 出站通知回调(公开)
|
||||
* 对应 warehouse_notify.json:WMS 处理消息后主动 POST 到本接口,
|
||||
* query 携带 app_key / method / timestamp / sign,body 为 { code, data }。
|
||||
* 先校验外部传入的 app_key 是否在仓库接口配置中存在(无配置则拒绝),
|
||||
* 再用 MD5(app_secret + timestamp + 原始body) 校验签名,失败拒绝。
|
||||
*/
|
||||
class WmsNotifyController extends Controller {
|
||||
async handle() {
|
||||
const { ctx } = this;
|
||||
const { app_key: appKey, method, timestamp, sign } = ctx.query;
|
||||
|
||||
if (!appKey || !method || !timestamp || !sign) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '缺少必要参数 app_key / method / timestamp / sign' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 时间戳时效校验
|
||||
const ts = Number(timestamp);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (!Number.isFinite(ts) || Math.abs(now - ts) > TIME_TOLERANCE_SEC) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'timestamp 已过期或非法(与服务器时间差不得超过 ±10 分钟)' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 检测外部传入 appKey 是否有配置:无配置或已禁用则拒绝
|
||||
const api = await ctx.model.WarehouseApi.findOne({ where: { app_key: appKey, status: 1 } });
|
||||
if (!api) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { code: 403, message: `app_key(${appKey}) 未配置或已禁用` };
|
||||
return;
|
||||
}
|
||||
|
||||
// 签名校验:MD5(app_secret + timestamp + 原始请求体)
|
||||
const rawBody = ctx.request.rawBody || JSON.stringify(ctx.request.body || {});
|
||||
const expectSign = qimenSign(api.app_secret, timestamp, rawBody);
|
||||
if (!timingSafeEqual(expectSign, sign)) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { code: 403, message: '签名校验失败' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 路由处理:按 method 分发;未实现的方法统一回执 200,避免 WMS 无谓重推
|
||||
try {
|
||||
switch (method) {
|
||||
case 'notify.ping':
|
||||
// 连通性探测,直接回执
|
||||
break;
|
||||
case 'notify.reply':
|
||||
case 'notify.stockChange':
|
||||
case 'notify.itemSync':
|
||||
// TODO: 后续接入具体业务(库存回写 / 商品同步结果)。当前仅落日志。
|
||||
ctx.logger.info(`[wms-notify] 收到 ${method}`, {
|
||||
appKey,
|
||||
data: ctx.request.body && ctx.request.body.data,
|
||||
});
|
||||
break;
|
||||
case 'entryorder.confirm':
|
||||
// 入库单确认:外部仓库收货回推后驱动 OMS 完成入库并增加系统库存
|
||||
await this.handleEntryConfirm(ctx, api);
|
||||
break;
|
||||
case 'notify.delivery':
|
||||
await this.handleDelivery(ctx, api);
|
||||
break;
|
||||
default:
|
||||
ctx.logger.warn(`[wms-notify] 未实现的方法 ${method}`, { appKey });
|
||||
}
|
||||
} catch (err) {
|
||||
// 处理异常仍回执 200,异常已记录日志,避免 WMS 重推
|
||||
ctx.logger.error(`[wms-notify] 处理 ${method} 异常`, err);
|
||||
}
|
||||
|
||||
// warehouse_notify.json:外部系统返回 {"code":200} 或 HTTP 非 200 视为推送失败
|
||||
ctx.status = 200;
|
||||
ctx.body = { code: 200, message: 'success' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发货通知(method = notify.delivery):WMS 已发货,扣减系统库存(总数量与锁定各减明细数量)
|
||||
* 通过 deliveryOrderCode / orderCode 关联 OMS 出库单;找不到则按明细 itemCode 兜底扣减
|
||||
* 幂等:已通过出库单关联扣减过的(stock_deducted=1)不再重复扣减
|
||||
*/
|
||||
async handleDelivery(ctx, api) {
|
||||
const data = (ctx.request.body && ctx.request.body.data) || ctx.request.body || {};
|
||||
ctx.logger.info('[wms-notify] notify.delivery', { appKey: api.app_key, data });
|
||||
const principalId = api.principal_id;
|
||||
const code = data.deliveryOrderCode
|
||||
|| (data.deliveryOrder && data.deliveryOrder.deliveryOrderCode)
|
||||
|| data.orderCode
|
||||
|| (data.order && data.order.orderCode);
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
let deducted = false;
|
||||
if (code) {
|
||||
const order = await ctx.model.OutboundOrder.findOne({ where: { bill_no: code, principal_id: principalId } });
|
||||
if (order) {
|
||||
// 回推明细的实际数量写回「已出数量」
|
||||
await applyActualQty(ctx, order.id, 2, 'actual_out_qty', extractNotifyLines(data));
|
||||
}
|
||||
if (order && !order.stock_deducted) {
|
||||
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' ],
|
||||
order: [[ 'product_id', 'ASC' ]],
|
||||
});
|
||||
for (const it of items) {
|
||||
await stock.deduct(ctx, principalId, Number(it.product_id), Number(it.quantity) || 0, transaction);
|
||||
}
|
||||
await order.update({ stock_deducted: 1 }, { transaction });
|
||||
deducted = true;
|
||||
}
|
||||
}
|
||||
// 兜底:按明细 itemCode 扣减(WMS 直接给出发货明细)
|
||||
if (!deducted) {
|
||||
const rawItems = data.items
|
||||
|| data.orderLines
|
||||
|| (data.deliveryOrder && data.deliveryOrder.orderLines)
|
||||
|| (data.deliveryOrder && data.deliveryOrder.items)
|
||||
|| [];
|
||||
for (const it of rawItems) {
|
||||
const itemCode = it.itemCode || it.item_code || (it.item && it.item.itemCode);
|
||||
const qty = Number(it.quantity || it.actualQty || it.planQty || 0);
|
||||
if (!itemCode || qty <= 0) continue;
|
||||
const product = await ctx.model.Product.findOne({ where: { item_code: itemCode, principal_id: principalId } });
|
||||
if (!product) continue;
|
||||
await stock.deduct(ctx, principalId, product.id, qty, transaction);
|
||||
}
|
||||
}
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
ctx.logger.error('[wms-notify] notify.delivery 处理异常', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 入库单确认(method = entryorder.confirm):WMS 已收货回推,驱动 OMS 完成入库并增加库存
|
||||
* 与 /openapi 的 entryorder.confirm 共用同一实现(app/lib/orderCallback.js#confirmInbound),
|
||||
* 报文外层包裹(data / request)由 orderCallback 统一归一化;
|
||||
* 幂等:已完成的单据(状态4)不会重复加库存;失败仅记日志并回执 200,避免 WMS 无谓重推。
|
||||
*/
|
||||
async handleEntryConfirm(ctx, api) {
|
||||
ctx.logger.info('[wms-notify] entryorder.confirm', { appKey: api.app_key, data: ctx.request.body });
|
||||
const result = await orderCallback.confirmInbound(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: api.warehouse_id,
|
||||
data: ctx.request.body || {},
|
||||
}).catch(err => {
|
||||
ctx.logger.error('[wms-notify] entryorder.confirm 处理异常', err);
|
||||
return { ok: false, message: err.message };
|
||||
});
|
||||
|
||||
if (result.ok) {
|
||||
const data = result.data || {};
|
||||
ctx.logger.info(
|
||||
`[wms-notify] entryorder.confirm 已处理 bill_no=${data.bill_no} status=${data.status} 明细更新=${data.actual_qty_updated} 已完成=${data.already_completed}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
ctx.logger.warn(`[wms-notify] entryorder.confirm 未处理:${result.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WmsNotifyController;
|
||||
66
backend/app/lib/apiResponse.js
Normal file
66
backend/app/lib/apiResponse.js
Normal file
@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外通用回调接口(OpenAPI 协议)的响应封装。
|
||||
*
|
||||
* 协议与 WMS /openapi 完全对齐(见 D:\wms\app\lib\api_response.js),
|
||||
* 便于双方用同一套客户端解析返回:
|
||||
* 成功:{ flag: 'success', code: 1, message, data, timestamp }
|
||||
* 失败:{ flag: 'failure', code, message, data: null, timestamp }
|
||||
*
|
||||
* 注意:本文件只服务于「对外」接口,OMS 内部 RESTful 接口仍使用
|
||||
* { code: 0, message, data } 结构,两者不要混用。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 当前时间戳(Unix 秒)
|
||||
* @return {Number} 秒级时间戳
|
||||
*/
|
||||
function nowTimestamp() {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否普通对象(非数组、非 null)
|
||||
* @param {*} value 任意值
|
||||
* @return {Boolean} 是否普通对象
|
||||
*/
|
||||
function isObject(value) {
|
||||
return value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装对外接口成功响应
|
||||
* @param {*} payload 业务数据,写入 data
|
||||
* @param {String} [message] 提示信息
|
||||
* @return {Object} { flag, code, message, data, timestamp }
|
||||
*/
|
||||
function toSuccess(payload, message = 'ok') {
|
||||
return {
|
||||
flag: 'success',
|
||||
code: 1,
|
||||
message,
|
||||
data: payload === undefined ? null : payload,
|
||||
timestamp: nowTimestamp(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装对外接口失败响应
|
||||
* @param {Object} options 失败信息
|
||||
* @param {String} [options.message] 提示信息
|
||||
* @param {Number} [options.code] 业务错误码,默认与 HTTP 状态码一致
|
||||
* @param {*} [options.data] 附加数据,默认 null
|
||||
* @return {Object} { flag, code, message, data, timestamp }
|
||||
*/
|
||||
function toFailure({ message = '请求失败', code, data = null } = {}) {
|
||||
return {
|
||||
flag: 'failure',
|
||||
code: typeof code === 'number' ? code : 500,
|
||||
message,
|
||||
data: isObject(data) || Array.isArray(data) ? data : null,
|
||||
timestamp: nowTimestamp(),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { toSuccess, toFailure, nowTimestamp };
|
||||
96
backend/app/lib/callbackLog.js
Normal file
96
backend/app/lib/callbackLog.js
Normal file
@ -0,0 +1,96 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外回调日志(callback_logs)写入工具。
|
||||
*
|
||||
* 记录外部系统调用 POST /openapi 的请求(query / 报文)与返回(业务码 / 报文),
|
||||
* 用于排查「回调是否到达、method 是否注册、验签是否通过、单据是否处理成功」。
|
||||
* 与 api_outbound_logs(OMS → 外部)方向相反,两者共同覆盖双向链路。
|
||||
*/
|
||||
|
||||
/** 单条文本落库前的最大字符数(超长截断,避免撑爆 TEXT) */
|
||||
const MAX_LOG_TEXT = 4000;
|
||||
/** 落库前需脱敏的字段(大小写不敏感) */
|
||||
const SENSITIVE_KEYS = [ 'sign', 'signature', 'app_secret', 'appsecret', 'password', 'token', 'salt' ];
|
||||
|
||||
/**
|
||||
* 递归脱敏敏感字段
|
||||
* @param {*} value 任意值
|
||||
* @return {*} 脱敏后的副本
|
||||
*/
|
||||
function maskDeep(value) {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
const result = Array.isArray(value) ? [ ...value ] : { ...value };
|
||||
for (const key of Object.keys(result)) {
|
||||
if (SENSITIVE_KEYS.includes(String(key).toLowerCase())) {
|
||||
result[key] = '***';
|
||||
} else if (result[key] && typeof result[key] === 'object') {
|
||||
result[key] = maskDeep(result[key]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化为字符串并按上限截断
|
||||
* @param {*} value 任意值
|
||||
* @param {Number} [max] 最大字符数
|
||||
* @return {String|null} 序列化结果;空值返回 null
|
||||
*/
|
||||
function safeStringify(value, max = MAX_LOG_TEXT) {
|
||||
if (value === undefined || value === null) return null;
|
||||
let text;
|
||||
try {
|
||||
text = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
} catch {
|
||||
text = '[unserializable]';
|
||||
}
|
||||
if (!text) return null;
|
||||
return text.length > max ? `${text.slice(0, max)}...[truncated]` : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录一条对外回调日志
|
||||
* 异步写库(不阻塞回调返回),写入失败只记错误日志,不影响业务结果。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {Object} entry 日志内容
|
||||
* @param {String} entry.method 回调方法名(未传时存空串)
|
||||
* @param {String} [entry.appKey] 请求携带的 app_key
|
||||
* @param {Object} [entry.query] 请求 query(sign 会脱敏)
|
||||
* @param {*} [entry.requestBody] 请求报文(业务参数)
|
||||
* @param {*} [entry.responseBody] 返回报文(完整响应体)
|
||||
* @param {Object} [entry.api] 按 app_key 定位到的接口配置(可能为空)
|
||||
* @param {Object} [entry.warehouse] 接口配置关联的仓库(可能为空)
|
||||
* @param {Number} [entry.httpStatus] 响应 HTTP 状态码
|
||||
* @param {Boolean} [entry.ok] 业务是否成功
|
||||
* @param {String} [entry.message] 提示信息 / 错误信息
|
||||
* @param {Number} [entry.duration] 耗时(毫秒)
|
||||
* @param {String} [entry.ip] 调用方 IP
|
||||
* @return {void}
|
||||
*/
|
||||
function recordCallbackLog(app, entry = {}) {
|
||||
if (!app || !app.model || !app.model.CallbackLog) return;
|
||||
const payload = {
|
||||
principal_id: entry.api ? entry.api.principal_id : null,
|
||||
warehouse_id: (entry.warehouse && entry.warehouse.id) || (entry.api && entry.api.warehouse_id) || null,
|
||||
warehouse_api_id: entry.api ? entry.api.id : null,
|
||||
method: String(entry.method || '').slice(0, 100),
|
||||
app_key: entry.appKey ? String(entry.appKey).slice(0, 100) : null,
|
||||
ip: entry.ip ? String(entry.ip).slice(0, 64) : null,
|
||||
http_status: entry.httpStatus || null,
|
||||
flag: entry.ok ? 'success' : 'failure',
|
||||
business_code: entry.responseBody && entry.responseBody.code != null ? String(entry.responseBody.code).slice(0, 32) : null,
|
||||
message: entry.message ? String(entry.message).slice(0, 500) : null,
|
||||
request_query: safeStringify(maskDeep(entry.query)),
|
||||
request_body: safeStringify(maskDeep(entry.requestBody)),
|
||||
response_body: safeStringify(entry.responseBody),
|
||||
is_success: entry.ok ? 1 : 0,
|
||||
error: entry.ok ? null : safeStringify(entry.message, 2000),
|
||||
duration: entry.duration == null ? null : Number(entry.duration),
|
||||
};
|
||||
app.model.CallbackLog.create(payload).catch(err => {
|
||||
app.logger.error(`[callback-log] 写入失败:${err.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { recordCallbackLog, maskDeep, safeStringify, MAX_LOG_TEXT };
|
||||
83
backend/app/lib/openapiCallback.js
Normal file
83
backend/app/lib/openapiCallback.js
Normal file
@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外通用回调接口(POST /openapi)的公共辅助方法。
|
||||
*
|
||||
* 接口协议与 WMS /openapi 对齐(见 D:\wms\app\service\openapiEntry.js):
|
||||
* - 系统参数走 query:method / app_key / v / timestamp / sign
|
||||
* - 业务参数走 JSON body
|
||||
* - 签名:md5(canonicalQuery + app_secret + md5(stableStringify(body))),见 lib/wms/sign.js
|
||||
*/
|
||||
|
||||
/** 时间戳时效阈值:±10 分钟(秒) */
|
||||
const TIME_TOLERANCE_SEC = 600;
|
||||
|
||||
/** 对外回调接口路径(与 router.js 注册的路由保持一致) */
|
||||
const CALLBACK_PATH = '/openapi';
|
||||
|
||||
/**
|
||||
* 归一化时间戳为 Unix 秒,兼容两种传法:
|
||||
* - 秒(10 位):OMS/WMS openapi 入参使用
|
||||
* - 毫秒(13 位):WMS 出站回调(openapi/callback.js)使用
|
||||
* @param {*} value query 中的 timestamp
|
||||
* @return {Number|null} 秒级时间戳;非法值返回 null
|
||||
*/
|
||||
function normalizeTimestamp(value) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) return null;
|
||||
// 大于 1e11 视为毫秒(1973 年以后的毫秒时间戳均满足该条件)
|
||||
return num > 1e11 ? Math.floor(num / 1000) : Math.floor(num);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断时间戳是否在 ±TIME_TOLERANCE_SEC 时效内
|
||||
* @param {Number} timestampSec 秒级时间戳
|
||||
* @param {Number} [nowSec] 当前秒级时间戳
|
||||
* @return {Boolean} 是否有效
|
||||
*/
|
||||
function isTimestampValid(timestampSec, nowSec = Math.floor(Date.now() / 1000)) {
|
||||
return Math.abs(nowSec - timestampSec) <= TIME_TOLERANCE_SEC;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析请求体为对象(验签需使用「解析后的对象」,与签名方的 stableStringify 对齐)
|
||||
* @param {Object} ctx egg context
|
||||
* @return {Object|String} 解析后的对象;无法解析时返回原始字符串
|
||||
*/
|
||||
function parseBody(ctx) {
|
||||
const parsed = ctx.request.body;
|
||||
if (parsed && typeof parsed === 'object') return parsed;
|
||||
const raw = ctx.request.rawBody;
|
||||
if (!raw) return {};
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return parsed || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装对外回调地址(在接口配置处展示,供外部系统配置)
|
||||
* 形如 http://localhost:6090/openapi(系统参数 method/app_key/timestamp/sign 由调用方自行拼接)
|
||||
* 优先使用 config.omsCallback.baseUrl(部署在网关/Nginx 后时配置),
|
||||
* 未配置时按当前请求的访问地址动态生成(开发环境即为后端实际地址)。
|
||||
* @param {Object} ctx egg context
|
||||
* @return {String} 形如 http(s)://host/openapi
|
||||
*/
|
||||
function buildCallbackUrl(ctx) {
|
||||
const configured = (ctx.app.config.omsCallback && ctx.app.config.omsCallback.baseUrl) || '';
|
||||
const base = String(configured).replace(/\/+$/, '') || `${ctx.protocol}://${ctx.host}`;
|
||||
return `${base}${CALLBACK_PATH}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TIME_TOLERANCE_SEC,
|
||||
CALLBACK_PATH,
|
||||
normalizeTimestamp,
|
||||
isTimestampValid,
|
||||
parseBody,
|
||||
buildCallbackUrl,
|
||||
};
|
||||
169
backend/app/lib/openapiMethods.js
Normal file
169
backend/app/lib/openapiMethods.js
Normal file
@ -0,0 +1,169 @@
|
||||
'use strict';
|
||||
|
||||
const { nowTimestamp } = require('./apiResponse');
|
||||
const orderCallback = require('./orderCallback');
|
||||
|
||||
/**
|
||||
* 对外通用回调接口的方法注册表。
|
||||
*
|
||||
* 命名与 WMS openapi 一致:`模块.动作`,如 index.ping。
|
||||
* 方法签名:async (ctx, payload) => ({ ok, message, data })
|
||||
* - payload.appKey 请求传入的应用Key
|
||||
* - payload.api 按 app_key 定位到的接口配置(warehouse_apis 记录)
|
||||
* - payload.warehouse 该接口配置关联的仓库(warehouse_apis.warehouse_id → warehouses)
|
||||
* - payload.body 业务参数(请求体 JSON 解析结果)
|
||||
* - payload.query 系统参数(method / app_key / v / timestamp 等)
|
||||
* - payload.timestamp 归一化后的秒级时间戳
|
||||
* ok=false 表示业务处理失败(控制器按 HTTP 400 + flag=failure 输出,便于调用方重试/告警);
|
||||
* data 为成功时的业务数据,外层由控制器统一包装为 { flag, code, message, data, timestamp }。
|
||||
*
|
||||
* 单据处理统一走 app/lib/orderCallback.js:按 app_key 定位到的「主体 + 仓库」校验后
|
||||
* 用单据号(inbound_orders.bill_no / outbound_orders.bill_no)定位 OMS 单据;
|
||||
* 新增方法时在 METHODS 中按 `模块.动作` 注册即可。
|
||||
*/
|
||||
const METHODS = {
|
||||
/**
|
||||
* 连通性探测(method = index.ping)
|
||||
* 外部系统配置好回调地址后先调用本方法,确认网络链路与 app_key/签名 是否可用;
|
||||
* 同时回显按 app_key 定位到的仓库,便于确认凭据与仓库的对应关系是否正确。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置(warehouse_apis 记录)
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 业务参数(请求体 JSON)
|
||||
* @param {Object} payload.query 系统参数(method / app_key / v / timestamp 等)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'index.ping': async (ctx, { api, warehouse, body, query }) => {
|
||||
ctx.logger.info('[openapi] index.ping', {
|
||||
appKey: api.app_key,
|
||||
warehouseId: warehouse.id,
|
||||
principalId: api.principal_id,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
message: 'ok',
|
||||
data: {
|
||||
pong: true,
|
||||
method: 'index.ping',
|
||||
app_key: api.app_key,
|
||||
warehouse: {
|
||||
id: warehouse.id,
|
||||
code: warehouse.code,
|
||||
name: warehouse.name,
|
||||
},
|
||||
principal_id: api.principal_id,
|
||||
api_version: query.v || '',
|
||||
echo: body || {},
|
||||
server_time: nowTimestamp(),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* 入库单确认(method = entryorder.confirm):WMS 收货完成
|
||||
* 写回明细「已入数量」,并把「已推送(3)」的单据完成入库(增加系统库存,幂等)
|
||||
* 报文兼容两种结构:顶层字段 / entryOrder 一层嵌套,以及整体包一层 request
|
||||
* (如 WMS 实际回推的 `{ request: { entryOrder: { entryOrderCode }, orderLines } }`,
|
||||
* 由 app/lib/orderCallback.js#unwrapPayload 统一归一化)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 回调报文(含 entryOrderCode / orderCode 与 orderLines)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'entryorder.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmInbound(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 入库单匹配(method = entryorder.match):WMS 反馈入库单与收货单的匹配结果
|
||||
* 仅写回明细「已入数量」并登记匹配信息,不改单据状态、不加库存(等待 entryorder.confirm 确认收货)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 回调报文(含 entryOrderCode / receivingNumber / matchType)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'entryorder.match': (ctx, { api, warehouse, body }) => orderCallback.matchInbound(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 发货单确认(method = deliveryorder.confirm):WMS 已发货出库
|
||||
* 写回明细「已出数量」,扣减系统库存并置「已完成(4)」(幂等,明细以仓库侧为准)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 回调报文(含 deliveryOrderCode / orderCode 与 orderLines)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'deliveryorder.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmOutbound(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 出库单确认(method = stockout.confirm):WMS 出库完成(非订单出库单)
|
||||
* 处理同 deliveryorder.confirm,单号取 stockoutOrderCode / orderCode
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 回调报文(含 stockoutOrderCode / orderCode 与 orderLines)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'stockout.confirm': (ctx, { api, warehouse, body }) => orderCallback.confirmOutbound(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 订单取消通知(method = order.cancel):外部已取消该单据
|
||||
* 未完成(≠4)的单据置为「已取消(9)」,出库单若已推送(3)则同时释放锁定库存
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 回调报文(含 orderCode / deliveryOrderCode / entryOrderCode)
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'order.cancel': (ctx, { api, warehouse, body }) => orderCallback.cancelOrder(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* 按方法名取处理器
|
||||
* 未注册的方法一律视为不支持(调用方需据此报错,不做静默兜底),
|
||||
* 用 hasOwnProperty 判断避免命中 Object 原型上的属性(如 constructor / toString)。
|
||||
* @param {String} method 方法名,如 index.ping
|
||||
* @return {Function|null} 处理器;未注册返回 null
|
||||
*/
|
||||
function resolve(method) {
|
||||
const name = String(method || '').trim();
|
||||
if (!name || !Object.prototype.hasOwnProperty.call(METHODS, name)) return null;
|
||||
const handler = METHODS[name];
|
||||
return typeof handler === 'function' ? handler : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已注册的方法名列表(用于错误提示与联调)
|
||||
* @return {Array<String>} 方法名列表
|
||||
*/
|
||||
function list() {
|
||||
return Object.keys(METHODS);
|
||||
}
|
||||
|
||||
module.exports = { METHODS, resolve, list };
|
||||
370
backend/app/lib/orderCallback.js
Normal file
370
backend/app/lib/orderCallback.js
Normal file
@ -0,0 +1,370 @@
|
||||
'use strict';
|
||||
|
||||
const stock = require('../utils/stock');
|
||||
const completeInbound = require('../utils/completeInbound');
|
||||
|
||||
/**
|
||||
* 外部回调(对外通用回调接口 /openapi)驱动 OMS 单据的共用处理逻辑。
|
||||
*
|
||||
* 调用方:① app/lib/openapiMethods.js 注册的 method 处理器(WMS/第三方 POST /openapi)
|
||||
* ② app/controller/wmsNotify.js(WMS 出站通知 /wms/notify)
|
||||
* 因此「写回实际数量」「按单号定位单据」只保留这一份实现。
|
||||
*
|
||||
* 单据定位规则:app_key 已在控制器侧定位到「主体 + 仓库」,此处按
|
||||
* bill_no(WMS entryOrderCode / deliveryOrderCode / stockoutOrderCode)+ principal_id 查单,
|
||||
* 并校验单据的 warehouse_id 与 app_key 定位到的仓库一致,避免跨仓库误处理。
|
||||
*
|
||||
* 报文结构兼容(见 unwrapPayload):openapi 出站回调整体包一层 request(request.entryOrder.entryOrderCode),
|
||||
* 出站通知 /wms/notify 整体包一层 data,两种结构都会先归一化再按同一组路径取值。
|
||||
*/
|
||||
|
||||
/** 入库单单号候选字段(支持嵌套路径) */
|
||||
const INBOUND_CODE_PATHS = [
|
||||
'entryOrderCode',
|
||||
'entryOrder.entryOrderCode',
|
||||
'orderCode',
|
||||
'order.orderCode',
|
||||
];
|
||||
|
||||
/** 出库单单号候选字段(支持嵌套路径) */
|
||||
const OUTBOUND_CODE_PATHS = [
|
||||
'deliveryOrderCode',
|
||||
'deliveryOrder.deliveryOrderCode',
|
||||
'stockoutOrderCode',
|
||||
'stockoutOrder.stockoutOrderCode',
|
||||
'stockout.stockoutOrderCode',
|
||||
'orderCode',
|
||||
'order.orderCode',
|
||||
];
|
||||
|
||||
/** 入库单匹配信息候选字段 */
|
||||
const MATCH_INFO_PATHS = {
|
||||
match_type: [ 'matchType', 'match_type' ],
|
||||
receiving_number: [ 'receivingNumber', 'receiving.receivingNumber' ],
|
||||
matched_at: [ 'completedAt', 'matchedAt', 'operateTime' ],
|
||||
};
|
||||
|
||||
/**
|
||||
* 归一化回调报文,兼容两种外层包裹:
|
||||
* - openapi 出站回调(WMS → OMS `POST /openapi?method=...`)整体包一层 request,如
|
||||
* `{ request: { entryOrder: { entryOrderCode: 'RK_2_2' }, orderLines: [...] } }`
|
||||
* - 出站通知 `/wms/notify` 整体包一层 data,如 `{ code: 200, data: { entryOrderCode: 'RK_1' } }`
|
||||
* 内层字段优先(同名时覆盖顶层),归一化后调用方按同一组路径取值即可。
|
||||
* @param {Object} data 原始回调报文
|
||||
* @return {Object} 归一化后的报文
|
||||
*/
|
||||
function unwrapPayload(data) {
|
||||
const source = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
||||
const inner = [ source.request, source.data ].find(v => v && typeof v === 'object' && !Array.isArray(v));
|
||||
return inner ? { ...source, ...inner } : source;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按点号路径取值
|
||||
* @param {Object} obj 源对象
|
||||
* @param {String} path 形如 entryOrder.entryOrderCode
|
||||
* @return {*} 取到的值
|
||||
*/
|
||||
function pickPath(obj, path) {
|
||||
return String(path).split('.').reduce((acc, key) => (acc === null || acc === undefined ? acc : acc[key]), obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按候选字段(支持嵌套路径)取第一个非空字符串
|
||||
* @param {Object} data 回调报文
|
||||
* @param {Array<String>} paths 候选字段路径
|
||||
* @return {String} 值(无则空串)
|
||||
*/
|
||||
function pickFirst(data, paths) {
|
||||
for (const path of paths) {
|
||||
const value = pickPath(data, path);
|
||||
if (value !== undefined && value !== null && String(value).trim() !== '') return String(value).trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 从回调报文中提取明细行数组(兼容 orderLines.orderLine / orderLines / items 等结构)
|
||||
* @param {Object} data 回推报文
|
||||
* @return {Array} 明细行数组
|
||||
*/
|
||||
function extractLines(data) {
|
||||
const source = data || {};
|
||||
const raw = source.orderLines
|
||||
|| (source.entryOrder && source.entryOrder.orderLines)
|
||||
|| (source.deliveryOrder && source.deliveryOrder.orderLines)
|
||||
|| (source.stockoutOrder && source.stockoutOrder.orderLines)
|
||||
|| source.items
|
||||
|| [];
|
||||
if (Array.isArray(raw)) return raw;
|
||||
if (raw && Array.isArray(raw.orderLine)) return raw.orderLine;
|
||||
if (raw && Array.isArray(raw.orderLines)) return raw.orderLines;
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把外部回推的实际数量写回单据明细的「已入/已出」数量(按 itemCode 匹配明细行)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Number} orderId 单据头ID
|
||||
* @param {Number} billType 1入库 2出库
|
||||
* @param {String} field actual_in_qty / actual_out_qty
|
||||
* @param {Array} lines 回推明细行
|
||||
* @return {Promise<Number>} 实际更新的明细行数
|
||||
*/
|
||||
async function applyActualQty(ctx, orderId, billType, field, lines) {
|
||||
if (!Array.isArray(lines) || !lines.length) return 0;
|
||||
let updated = 0;
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const itemCode = line.itemCode || line.item_code || (line.item && line.item.itemCode);
|
||||
if (!itemCode) continue;
|
||||
const raw = line.actualQty != null ? line.actualQty
|
||||
: (line.actual_qty != null ? line.actual_qty
|
||||
: (line.quantity != null ? line.quantity : line.planQty));
|
||||
const qty = Number(raw);
|
||||
if (!Number.isFinite(qty)) continue;
|
||||
const [ affected ] = await ctx.model.StockItem.update(
|
||||
{ [field]: qty },
|
||||
{ where: { bill_type: billType, bill_id: orderId, code: itemCode } }
|
||||
);
|
||||
updated += affected;
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按单号 + 主体定位单据,并校验其归属仓库与 app_key 定位到的仓库一致
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 查询参数
|
||||
* @param {String} options.model 模型名(InboundOrder / OutboundOrder)
|
||||
* @param {String} options.code 单据号(bill_no)
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Number} options.warehouseId app_key 定位到的仓库ID
|
||||
* @return {Promise<{order?: Object, error?: String}>} 定位结果
|
||||
*/
|
||||
async function findBill(ctx, { model, code, principalId, warehouseId }) {
|
||||
const order = await ctx.model[model].findOne({ where: { bill_no: code, principal_id: principalId } });
|
||||
if (!order) return { error: `未找到${model === 'InboundOrder' ? '入库' : '出库'}单:${code}` };
|
||||
// 历史单据可能没有 warehouse_id,仅在双方都有值时校验仓库归属
|
||||
if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) {
|
||||
return { error: `单据 ${code} 不属于当前 app_key 对应的仓库` };
|
||||
}
|
||||
return { order };
|
||||
}
|
||||
|
||||
/**
|
||||
* 入库单确认(entryorder.confirm):WMS 收货完成
|
||||
* 写回明细「已入数量」,并把「已推送(3)」的单据完成入库(增加系统库存,幂等)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 处理参数
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Number} options.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} options.data 回调报文
|
||||
* @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果
|
||||
*/
|
||||
async function confirmInbound(ctx, { principalId, warehouseId, data }) {
|
||||
const payload = unwrapPayload(data);
|
||||
const code = pickFirst(payload, INBOUND_CODE_PATHS);
|
||||
if (!code) return { ok: false, message: '缺少入库单号(entryOrderCode / orderCode)' };
|
||||
|
||||
const found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId });
|
||||
if (found.error) return { ok: false, message: found.error };
|
||||
const order = found.order;
|
||||
|
||||
const actualUpdated = await applyActualQty(ctx, order.id, 1, 'actual_in_qty', extractLines(payload));
|
||||
const result = await completeInbound(ctx, order);
|
||||
if (!result.ok) return { ok: false, message: result.message };
|
||||
|
||||
const data_ = {
|
||||
bill_id: order.id,
|
||||
bill_no: order.bill_no,
|
||||
status: result.already ? order.status : 4,
|
||||
already_completed: !!result.already,
|
||||
actual_qty_updated: actualUpdated,
|
||||
};
|
||||
ctx.logger.info('[order-callback] entryorder.confirm 完成', data_);
|
||||
return { ok: true, message: 'ok', data: data_ };
|
||||
}
|
||||
|
||||
/**
|
||||
* 入库单匹配(entryorder.match):WMS 反馈入库单与收货单匹配结果
|
||||
* 仅写回明细「已入数量」并返回匹配信息,不改变单据状态、不增加库存(匹配 ≠ 收货完成)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 处理参数
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Number} options.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} options.data 回调报文
|
||||
* @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果
|
||||
*/
|
||||
async function matchInbound(ctx, { principalId, warehouseId, data }) {
|
||||
const payload = unwrapPayload(data);
|
||||
const code = pickFirst(payload, INBOUND_CODE_PATHS);
|
||||
if (!code) return { ok: false, message: '缺少入库单号(entryOrderCode / orderCode)' };
|
||||
|
||||
const found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId });
|
||||
if (found.error) return { ok: false, message: found.error };
|
||||
const order = found.order;
|
||||
|
||||
const actualUpdated = await applyActualQty(ctx, order.id, 1, 'actual_in_qty', extractLines(payload));
|
||||
const result = {
|
||||
bill_id: order.id,
|
||||
bill_no: order.bill_no,
|
||||
status: order.status,
|
||||
actual_qty_updated: actualUpdated,
|
||||
match_type: pickFirst(payload, MATCH_INFO_PATHS.match_type),
|
||||
receiving_number: pickFirst(payload, MATCH_INFO_PATHS.receiving_number),
|
||||
matched_at: pickFirst(payload, MATCH_INFO_PATHS.matched_at),
|
||||
};
|
||||
ctx.logger.info('[order-callback] entryorder.match 匹配登记', result);
|
||||
return { ok: true, message: 'ok', data: result };
|
||||
}
|
||||
|
||||
/**
|
||||
* 出库单确认(deliveryorder.confirm / stockout.confirm):WMS 已发货出库
|
||||
* 写回明细「已出数量」,扣减系统库存(总数量与锁定各减明细数量,幂等),并置「已完成(4)」
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 处理参数
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Number} options.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} options.data 回调报文
|
||||
* @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果
|
||||
*/
|
||||
async function confirmOutbound(ctx, { principalId, warehouseId, data }) {
|
||||
const payload = unwrapPayload(data);
|
||||
const code = pickFirst(payload, OUTBOUND_CODE_PATHS);
|
||||
if (!code) return { ok: false, message: '缺少出库单号(deliveryOrderCode / stockoutOrderCode / orderCode)' };
|
||||
|
||||
const found = await findBill(ctx, { model: 'OutboundOrder', code, principalId, warehouseId });
|
||||
if (found.error) return { ok: false, message: found.error };
|
||||
const order = found.order;
|
||||
|
||||
const actualUpdated = await applyActualQty(ctx, order.id, 2, 'actual_out_qty', extractLines(payload));
|
||||
|
||||
// 幂等:已完成且已扣减库存的单据不再重复处理
|
||||
if (order.status === 4 && order.stock_deducted) {
|
||||
const done = {
|
||||
bill_id: order.id,
|
||||
bill_no: order.bill_no,
|
||||
status: order.status,
|
||||
already_completed: true,
|
||||
actual_qty_updated: actualUpdated,
|
||||
};
|
||||
ctx.logger.info('[order-callback] 出库单已完成,跳过', done);
|
||||
return { ok: true, message: 'ok', data: done };
|
||||
}
|
||||
if (order.status !== 3 && order.status !== 4) {
|
||||
return { ok: false, message: `单据 ${order.bill_no} 当前状态(${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' ]],
|
||||
});
|
||||
if (!items.length) return { ok: false, message: `单据 ${order.bill_no} 无明细,无法完成出库` };
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
if (!order.stock_deducted) {
|
||||
for (const it of items) {
|
||||
const p = it.get ? it.get({ plain: true }) : it;
|
||||
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
|
||||
await stock.deduct(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
|
||||
}
|
||||
}
|
||||
await order.update({ status: 4, stock_deducted: 1 }, { transaction });
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
|
||||
const result = {
|
||||
bill_id: order.id,
|
||||
bill_no: order.bill_no,
|
||||
status: 4,
|
||||
stock_deducted: 1,
|
||||
already_completed: false,
|
||||
actual_qty_updated: actualUpdated,
|
||||
};
|
||||
ctx.logger.info('[order-callback] 出库确认完成', result);
|
||||
return { ok: true, message: 'ok', data: result };
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单取消通知(order.cancel):外部已取消该单据
|
||||
* 未完成(≠4)的单据置为「已取消(9)」;出库单若已推送(3)则同时释放锁定库存
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 处理参数
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Number} options.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} options.data 回调报文
|
||||
* @return {Promise<{ok: Boolean, message: String, data?: Object}>} 处理结果
|
||||
*/
|
||||
async function cancelOrder(ctx, { principalId, warehouseId, data }) {
|
||||
const payload = unwrapPayload(data);
|
||||
const code = pickFirst(payload, [ ...OUTBOUND_CODE_PATHS, ...INBOUND_CODE_PATHS ]);
|
||||
if (!code) return { ok: false, message: '缺少单号(orderCode / deliveryOrderCode / entryOrderCode)' };
|
||||
|
||||
// 先按出库单定位,再按入库单定位
|
||||
let billType = 2;
|
||||
let found = await findBill(ctx, { model: 'OutboundOrder', code, principalId, warehouseId });
|
||||
if (found.error) {
|
||||
billType = 1;
|
||||
found = await findBill(ctx, { model: 'InboundOrder', code, principalId, warehouseId });
|
||||
}
|
||||
if (found.error) {
|
||||
return { ok: false, message: `未找到可取消的单据:${code}(出入库单均无此单号或不属于当前仓库)` };
|
||||
}
|
||||
const order = found.order;
|
||||
|
||||
if (order.status === 4) return { ok: false, message: `单据 ${code} 已完成,不能取消` };
|
||||
if (order.status === 9) {
|
||||
return { ok: true, message: 'ok', data: { bill_id: order.id, bill_no: order.bill_no, bill_type: billType, status: 9, already_cancelled: true } };
|
||||
}
|
||||
|
||||
// 出库单已推送(3)且未扣减库存:取消时释放锁定库存
|
||||
if (billType === 2 && order.status === 3 && !order.stock_deducted) {
|
||||
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 p = it.get ? it.get({ plain: true }) : it;
|
||||
const itemType = p.inventory_type === 'CC' ? 'CC' : 'ZC';
|
||||
await stock.unlock(ctx, principalId, Number(p.product_id), Number(p.quantity) || 0, transaction, itemType);
|
||||
}
|
||||
await order.update({ status: 9 }, { transaction });
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
await order.update({ status: 9 });
|
||||
}
|
||||
|
||||
const result = {
|
||||
bill_id: order.id,
|
||||
bill_no: order.bill_no,
|
||||
bill_type: billType,
|
||||
status: 9,
|
||||
already_cancelled: false,
|
||||
cancel_reason: pickFirst(data, [ 'cancelReason', 'reason', 'remark' ]),
|
||||
};
|
||||
ctx.logger.info('[order-callback] order.cancel 已取消', result);
|
||||
return { ok: true, message: 'ok', data: result };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
pickFirst,
|
||||
extractLines,
|
||||
applyActualQty,
|
||||
confirmInbound,
|
||||
matchInbound,
|
||||
confirmOutbound,
|
||||
cancelOrder,
|
||||
};
|
||||
35
backend/app/model/callbackLog.js
Normal file
35
backend/app/model/callbackLog.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外回调日志模型,对应 callback_logs 表
|
||||
* 记录外部系统调用 POST /openapi 的请求与返回(含未通过校验的请求),用于排查回调链路
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} callbackLog model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const CallbackLog = app.model.define('callback_log', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, comment: '所属主体ID(app_key 未定位到时为空)' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '关联仓库ID(app_key 未定位到时为空)' },
|
||||
warehouse_api_id: { type: BIGINT.UNSIGNED, comment: '命中的仓库接口配置ID' },
|
||||
method: { type: STRING(100), allowNull: false, defaultValue: '', comment: '回调方法名,如 index.ping / entryorder.confirm' },
|
||||
app_key: { type: STRING(100), comment: '请求携带的 app_key' },
|
||||
ip: { type: STRING(64), comment: '调用方 IP' },
|
||||
http_status: { type: INTEGER, comment: '响应 HTTP 状态码' },
|
||||
flag: { type: STRING(20), comment: '结果标记:success / failure' },
|
||||
business_code: { type: STRING(32), comment: '业务码(成功1,失败见 code)' },
|
||||
message: { type: STRING(500), comment: '提示信息 / 失败原因' },
|
||||
request_query: { type: TEXT, comment: '请求 query JSON(sign 已脱敏)' },
|
||||
request_body: { type: TEXT, comment: '请求报文 JSON(敏感字段已脱敏,超长截断)' },
|
||||
response_body: { type: TEXT, comment: '返回报文 JSON(超长截断)' },
|
||||
is_success: { type: TINYINT, defaultValue: 0, comment: '业务是否成功:1是 0否' },
|
||||
error: { type: TEXT, comment: '失败信息(未注册方法 / 验签失败 / 单据处理失败等)' },
|
||||
duration: { type: INTEGER, comment: '耗时(毫秒)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
return CallbackLog;
|
||||
};
|
||||
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外回调日志表(外部系统 → OMS 的 POST /openapi 请求与返回)
|
||||
* 与 api_outbound_logs(OMS → 外部)方向相反,覆盖回调链路的排查
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'callback_logs',
|
||||
{
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '所属主体ID(app_key 未定位到时为空)' },
|
||||
warehouse_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '关联仓库ID(app_key 未定位到时为空)' },
|
||||
warehouse_api_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '命中的仓库接口配置ID' },
|
||||
method: { type: Sequelize.STRING(100), allowNull: false, defaultValue: '', comment: '回调方法名,如 index.ping / entryorder.confirm' },
|
||||
app_key: { type: Sequelize.STRING(100), allowNull: true, comment: '请求携带的 app_key' },
|
||||
ip: { type: Sequelize.STRING(64), allowNull: true, comment: '调用方 IP' },
|
||||
http_status: { type: Sequelize.INTEGER, allowNull: true, comment: '响应 HTTP 状态码' },
|
||||
flag: { type: Sequelize.STRING(20), allowNull: true, comment: '结果标记:success / failure' },
|
||||
business_code: { type: Sequelize.STRING(32), allowNull: true, comment: '业务码(成功1,失败见 code)' },
|
||||
message: { type: Sequelize.STRING(500), allowNull: true, comment: '提示信息 / 失败原因' },
|
||||
request_query: { type: Sequelize.TEXT, allowNull: true, comment: '请求 query JSON(sign 已脱敏)' },
|
||||
request_body: { type: Sequelize.TEXT, allowNull: true, comment: '请求报文 JSON(敏感字段已脱敏,超长截断)' },
|
||||
response_body: { type: Sequelize.TEXT, allowNull: true, comment: '返回报文 JSON(超长截断)' },
|
||||
is_success: { type: Sequelize.TINYINT, defaultValue: 0, comment: '业务是否成功(1是 0否)' },
|
||||
error: { type: Sequelize.TEXT, allowNull: true, comment: '失败信息(未注册方法 / 验签失败 / 单据处理失败等)' },
|
||||
duration: { type: Sequelize.INTEGER, allowNull: true, comment: '耗时(毫秒)' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '对外回调日志表' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('callback_logs', { fields: [ 'principal_id' ], name: 'idx_cb_log_principal' });
|
||||
await queryInterface.addIndex('callback_logs', { fields: [ 'warehouse_id' ], name: 'idx_cb_log_warehouse' });
|
||||
await queryInterface.addIndex('callback_logs', { fields: [ 'warehouse_api_id' ], name: 'idx_cb_log_api' });
|
||||
await queryInterface.addIndex('callback_logs', { fields: [ 'method' ], name: 'idx_cb_log_method' });
|
||||
await queryInterface.addIndex('callback_logs', { fields: [ 'created_at' ], name: 'idx_cb_log_created' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('callback_logs');
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user