Compare commits
8 Commits
da56253d4a
...
02596feb3d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02596feb3d | ||
|
|
02b3a5e813 | ||
|
|
d6e4de6edc | ||
|
|
05b71b2f31 | ||
|
|
8ee12374b3 | ||
|
|
f747e73aea | ||
|
|
5759c1fb19 | ||
|
|
fbb12cf205 |
@ -8,5 +8,19 @@ class TemplateController extends Controller {
|
||||
const result = await service.systems.setting.printTemplate.getXmlByTemplate(ctx.params.id);
|
||||
ctx.body = result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出抖音面单自定义区模板 XML(douyin1.xml)
|
||||
*/
|
||||
async douyinCustomArea() {
|
||||
const { ctx } = this;
|
||||
ctx.type = 'application/xml';
|
||||
ctx.body = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<layout id="CUSTOM_AREA" width="97" height="60" left="0" top="111" style="">
|
||||
<layout width="57" height="30" left="2" top="2" style="">
|
||||
<text style="fontFamily:宋体;fontSize:9;fontWeight:600"><![CDATA[<%=_data.productInfo%>]]></text>
|
||||
</layout>
|
||||
</layout>`;
|
||||
}
|
||||
}
|
||||
module.exports = TemplateController;
|
||||
|
||||
56
app/controller/warehouse.js
Normal file
56
app/controller/warehouse.js
Normal file
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
class WarehouseController extends Controller {
|
||||
/**
|
||||
* 输出仓库 API 统一失败响应。
|
||||
* @param {number} httpStatus HTTP 状态码。
|
||||
* @param {string} message 错误消息。
|
||||
* @param {number} [code=httpStatus] 业务错误码。
|
||||
* @return {void} 无返回值。
|
||||
*/
|
||||
writeFailureResponse(httpStatus, message, code = httpStatus) {
|
||||
const { ctx } = this;
|
||||
ctx.status = httpStatus;
|
||||
ctx.body = toFailure({
|
||||
message,
|
||||
httpStatus,
|
||||
code,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
|
||||
/**
|
||||
* 仓库 API 统一入口,仅负责转发到 warehouse service 并输出标准响应。
|
||||
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.warehouse.processRequest();
|
||||
if (result.ok) {
|
||||
ctx.status = Number(result.httpStatus) || 200;
|
||||
ctx.body = toSuccess(result.data, result.message || 'ok');
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeFailureResponse(
|
||||
Number(result.httpStatus) || 500,
|
||||
String(result.message || '请求失败'),
|
||||
Number(result.code) || Number(result.httpStatus) || 500
|
||||
);
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = String(error && error.message || '请求失败');
|
||||
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseController;
|
||||
@ -1584,8 +1584,10 @@ function resolveDouyinParams(orderExpress) {
|
||||
* @param {Object} orderExpress 快递单对象。
|
||||
* @param {Object} orderDelivery 订单对象。
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
* @param {string[]} extraCustomLines 额外的自定义文本行。
|
||||
* @param {string} customAreaBaseUrl 自定义区模板出口域名。
|
||||
*/
|
||||
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
|
||||
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = [], customAreaBaseUrl = '') {
|
||||
if (platform !== 'douyin') {
|
||||
return;
|
||||
}
|
||||
@ -1697,7 +1699,8 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
|
||||
}
|
||||
const customContent = contents[1];
|
||||
if (!toTrimmedString(customContent.templateURL)) {
|
||||
customContent.templateURL = 'http://www.ye4s.com/mb/douyin1.xml';
|
||||
const baseUrl = toTrimmedString(customAreaBaseUrl) || 'http://www.ye4s.com';
|
||||
customContent.templateURL = baseUrl + '/mb/douyin1.xml';
|
||||
}
|
||||
customContent.data = isPlainObject(customContent.data) ? customContent.data : {};
|
||||
customContent.data.productInfo = customProductInfo || '无拣货信息';
|
||||
@ -2415,7 +2418,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
extraCustomLines
|
||||
extraCustomLines,
|
||||
options.customAreaBaseUrl
|
||||
);
|
||||
|
||||
applyJdExpressFieldMapping(
|
||||
|
||||
@ -44,9 +44,15 @@ module.exports = app => {
|
||||
// OpenAPI 入口
|
||||
router.post('/openapi', controller.openapi.index);
|
||||
|
||||
// 仓库 OpenAPI 入口
|
||||
router.post('/warehouse', controller.warehouse.index);
|
||||
|
||||
// 打印模板
|
||||
router.get('/template/xml/:id', controller.template.xml);
|
||||
|
||||
// 打印自定义区模板(抖音面单等)
|
||||
router.get('/mb/douyin1.xml', controller.template.douyinCustomArea);
|
||||
|
||||
// 打印台设置
|
||||
router.get('/auth/printSetting/:code', controller.auth.printerSetting);
|
||||
router.post('/auth/printSetting/', controller.auth.printerSetting);
|
||||
|
||||
@ -65,15 +65,61 @@ class OpenapiOrderService extends MainService {
|
||||
return this.fail('取消失败,已通知拦截执行');
|
||||
}
|
||||
|
||||
await existingOrder.update({
|
||||
// 检查是否在波次中,若在波次中需清除波次关联
|
||||
const existingWaveId = Number(existingOrder.wave_id || 0);
|
||||
|
||||
const updateValues = {
|
||||
status: 'cancel',
|
||||
outbound_status: 'fin',
|
||||
step: 4,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
};
|
||||
if (existingWaveId > 0) {
|
||||
updateValues.wave_id = 0;
|
||||
updateValues.wave_no = '';
|
||||
}
|
||||
|
||||
await existingOrder.update(updateValues, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 波次清理:删除波次索引、重建波次索引、更新波次统计
|
||||
if (existingWaveId > 0) {
|
||||
await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId,
|
||||
orderIds: [ existingOrder.id ],
|
||||
transaction,
|
||||
});
|
||||
|
||||
await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: [ existingWaveId ],
|
||||
orderModel: DeliveryModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const WaveBatch = ctx.model.WaveBatch;
|
||||
if (WaveBatch) {
|
||||
const wave = await WaveBatch.findOne({
|
||||
where: { wave_id: existingWaveId, warehouse_id: warehouseId },
|
||||
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (wave) {
|
||||
const totalOrders = Number(wave.total_orders);
|
||||
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
|
||||
if (normalizedTotalOrders <= 0) {
|
||||
await WaveBatch.update(
|
||||
{ total_orders: 0, wave_status: -1, update_time: new Date() },
|
||||
{ where: { wave_id: existingWaveId, warehouse_id: warehouseId }, transaction }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 释放储位分配锁定库存
|
||||
await this.releaseStockLockForCancel({
|
||||
orderId: existingOrder.id,
|
||||
|
||||
@ -238,48 +238,52 @@ class orderServer extends MainService {
|
||||
|
||||
await existingOrder.update(updateValues, { transaction });
|
||||
|
||||
// 波次清理:删除波次索引、更新波次统计
|
||||
// 波次清理:删除波次索引、重建波次索引、更新波次统计
|
||||
if (existingWaveId > 0) {
|
||||
try {
|
||||
await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId: info.warehouseId,
|
||||
orderIds: [existingOrder.id],
|
||||
await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId: info.warehouseId,
|
||||
orderIds: [ existingOrder.id ],
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 重建受影响波次的订单索引(wave_index 重新排序)
|
||||
await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId: info.warehouseId,
|
||||
waveIds: [ existingWaveId ],
|
||||
orderModel: DeliveryModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const WaveBatch = ctx.model.WaveBatch;
|
||||
if (WaveBatch) {
|
||||
await WaveBatch.decrement('total_orders', {
|
||||
by: 1,
|
||||
where: {
|
||||
wave_id: existingWaveId,
|
||||
warehouse_id: info.warehouseId,
|
||||
total_orders: { [Op.gt]: 0 },
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const WaveBatch = ctx.model.WaveBatch;
|
||||
if (WaveBatch) {
|
||||
await WaveBatch.decrement('total_orders', {
|
||||
by: 1,
|
||||
where: {
|
||||
wave_id: existingWaveId,
|
||||
warehouse_id: info.warehouseId,
|
||||
total_orders: { [Op.gt]: 0 },
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
const wave = await WaveBatch.findOne({
|
||||
where: { wave_id: existingWaveId, warehouse_id: info.warehouseId },
|
||||
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const wave = await WaveBatch.findOne({
|
||||
where: { wave_id: existingWaveId, warehouse_id: info.warehouseId },
|
||||
attributes: ['wave_id', 'total_orders', 'wave_status'],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (wave) {
|
||||
const totalOrders = Number(wave.total_orders);
|
||||
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
|
||||
if (normalizedTotalOrders <= 0) {
|
||||
await WaveBatch.update(
|
||||
{ total_orders: 0, wave_status: -1, update_time: new Date() },
|
||||
{ where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction }
|
||||
);
|
||||
}
|
||||
if (wave) {
|
||||
const totalOrders = Number(wave.total_orders);
|
||||
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
|
||||
if (normalizedTotalOrders <= 0) {
|
||||
await WaveBatch.update(
|
||||
{ total_orders: 0, wave_status: -1, update_time: new Date() },
|
||||
{ where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction }
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (waveErr) {
|
||||
ctx.logger.warn('[QimenOrderCancel] 清理波次关联失败,不影响订单取消', waveErr);
|
||||
}
|
||||
}
|
||||
|
||||
@ -297,7 +301,7 @@ class orderServer extends MainService {
|
||||
try {
|
||||
ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange(
|
||||
info.warehouseId,
|
||||
[existingOrder.id],
|
||||
[ existingOrder.id ],
|
||||
{ triggerScan: true, source: 'qimenCancel' }
|
||||
);
|
||||
} catch (scanErr) {
|
||||
|
||||
@ -1992,13 +1992,22 @@ class PendingOrderService extends OrderBaseService {
|
||||
* 批量分配待处理订单的快递号,并复用现有运单创建核心链路。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<Object>} data.orders 订单对象数组。
|
||||
* @param {Array<number>} data.ids 订单 ID 数组(推荐)。
|
||||
* @param {Array<Object>} [data.orders] 订单对象数组(兼容旧格式,新调用方请使用 ids)。
|
||||
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
|
||||
*/
|
||||
async allocateExpressCode(data) {
|
||||
const { orders } = data || {};
|
||||
if (!Array.isArray(orders)) {
|
||||
throw new Error('分配快递号接口仅支持订单对象数组入参');
|
||||
const { ids, orders: legacyOrders } = data || {};
|
||||
|
||||
// 新格式:ids,直接转为管线所需格式(business_key 固定为 1)
|
||||
let orders;
|
||||
if (Array.isArray(ids) && ids.length > 0) {
|
||||
orders = ids.map(id => ({ order_id: Number(id), business_key: 1 }));
|
||||
} else if (Array.isArray(legacyOrders)) {
|
||||
// 兼容旧格式:orders 对象数组
|
||||
orders = legacyOrders;
|
||||
} else {
|
||||
throw new Error('分配快递号接口需要传入 ids(订单ID数组)或 orders(订单对象数组)');
|
||||
}
|
||||
|
||||
const { service } = this;
|
||||
@ -2345,6 +2354,18 @@ class PendingOrderService extends OrderBaseService {
|
||||
orderIds: waveOrderIds,
|
||||
transaction: undefined,
|
||||
});
|
||||
|
||||
// 重建受影响波次的订单索引(wave_index 重新排序)
|
||||
const affectedWaveIds = [ ...new Set(ordersWithWave
|
||||
.map(order => Number(order.wave_id))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||||
if (affectedWaveIds.length > 0) {
|
||||
await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: affectedWaveIds,
|
||||
orderModel: model,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (WaveBatch) {
|
||||
@ -3014,14 +3035,37 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const originalWaveId = Number(original.wave_id || 0);
|
||||
|
||||
// 3. 取消原订单
|
||||
await model.update({
|
||||
// 3. 取消原订单(若在波次中需清除波次关联)
|
||||
const cancelUpdateValues = {
|
||||
status: 'cancel',
|
||||
step: 9,
|
||||
outbound_status: 'padding',
|
||||
updated_at: now,
|
||||
}, { where });
|
||||
};
|
||||
if (originalWaveId > 0) {
|
||||
cancelUpdateValues.wave_id = 0;
|
||||
cancelUpdateValues.wave_no = '';
|
||||
}
|
||||
await model.update(cancelUpdateValues, { where });
|
||||
|
||||
// 克隆时清理波次索引(不影响主流程)
|
||||
if (originalWaveId > 0) {
|
||||
try {
|
||||
await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||||
warehouseId,
|
||||
orderIds: [ orderId ],
|
||||
});
|
||||
await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: [ originalWaveId ],
|
||||
orderModel: model,
|
||||
});
|
||||
} catch (waveErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 清理波次关联失败,不影响克隆', waveErr);
|
||||
}
|
||||
}
|
||||
|
||||
// 记录原订单"克隆"日志
|
||||
try {
|
||||
|
||||
@ -3012,7 +3012,7 @@ class WaveService extends OrderBaseService {
|
||||
AND o.lock_status = 'none'
|
||||
INNER JOIN (
|
||||
SELECT
|
||||
COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key,
|
||||
src.items_hash AS structure_key,
|
||||
COUNT(1) AS same_structure_count
|
||||
FROM ${orderTableName} src
|
||||
WHERE src.warehouse_id = :warehouseId
|
||||
@ -3025,9 +3025,9 @@ class WaveService extends OrderBaseService {
|
||||
AND src.outbound_status != 'padding'
|
||||
AND src.intercept_status = 'none'
|
||||
AND src.lock_status = 'none'
|
||||
GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, '')))
|
||||
GROUP BY src.items_hash
|
||||
) same_structure
|
||||
ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, '')))
|
||||
ON same_structure.structure_key = o.items_hash
|
||||
INNER JOIN wms_wave_strategy s
|
||||
ON s.id = m.strategy_id
|
||||
AND s.warehouse_id = :warehouseId
|
||||
@ -7061,39 +7061,14 @@ class WaveService extends OrderBaseService {
|
||||
|
||||
const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0);
|
||||
|
||||
await this.deleteOrderWaveIndexByOrderIds({
|
||||
// 重建受影响波次的订单索引(wave_index 重新排序),并获取各波次剩余订单数量
|
||||
const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
orderIds: removedOrderIds,
|
||||
waveIds: affectedWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const remainingRows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'wave_id',
|
||||
[ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ],
|
||||
],
|
||||
where: {
|
||||
wave_id: {
|
||||
[Op.in]: affectedWaveIds,
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
group: [ 'wave_id' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const remainingCountMap = new Map();
|
||||
for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const remainingCount = Number(row && row.remaining_count || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0);
|
||||
}
|
||||
|
||||
const updatedWaveIds = [];
|
||||
const emptiedWaveIds = [];
|
||||
|
||||
@ -7171,6 +7146,173 @@ class WaveService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重排指定波次的订单索引(wave_index)。
|
||||
*
|
||||
* 用于修正历史数据中因各种原因导致的 wave_index 不连续问题。
|
||||
* 内部调用 replaceOrderWaveIndexByWaveIds 完成索引重建,并同步更新 wms_wave_batch.total_orders。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {Array<number|string>|number|string} [data.wave_ids] 波次ID集合。
|
||||
* @param {Array<number|string>|number|string} [data.waveIds] 波次ID集合(驼峰写法)。
|
||||
* @return {Promise<Object>} 重排结果,含各波次重排前后的订单数量。
|
||||
*/
|
||||
async resortWaveIndex(data = {}) {
|
||||
const contextWarehouseId = Number(this.getWarehouseId() || 0);
|
||||
if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) {
|
||||
throw new Error('未识别到当前仓库上下文');
|
||||
}
|
||||
|
||||
const warehouseId = contextWarehouseId;
|
||||
const rawWaveIds = data && (
|
||||
data.wave_ids !== undefined ? data.wave_ids
|
||||
: data.waveIds !== undefined ? data.waveIds
|
||||
: data.wave_id !== undefined ? data.wave_id
|
||||
: data.waveId !== undefined ? data.waveId
|
||||
: null
|
||||
);
|
||||
const normalizedWaveIds = this.normalizeIdsInput(rawWaveIds);
|
||||
if (normalizedWaveIds.length === 0) {
|
||||
throw new Error('wave_ids 参数不能为空或格式错误');
|
||||
}
|
||||
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
const transaction = await this.ctx.model.transaction();
|
||||
|
||||
try {
|
||||
// 重排前记录各波次每单的 wave_index,用于对比是否实际发生重排
|
||||
const beforeRows = await this.ctx.model.query(`
|
||||
SELECT wave_id, order_id, wave_index
|
||||
FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)
|
||||
ORDER BY wave_id, order_id
|
||||
`, {
|
||||
replacements: { warehouseId, waveIds: normalizedWaveIds },
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const beforeIndexMap = new Map(); // waveId -> Map(orderId -> wave_index)
|
||||
const beforeCountMap = new Map();
|
||||
for (const row of (Array.isArray(beforeRows) ? beforeRows : [])) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const orderId = Number(row && row.order_id || 0);
|
||||
const waveIndex = Number(row && row.wave_index || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) continue;
|
||||
if (!beforeIndexMap.has(waveId)) beforeIndexMap.set(waveId, new Map());
|
||||
if (Number.isInteger(orderId) && orderId > 0) {
|
||||
beforeIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0);
|
||||
}
|
||||
beforeCountMap.set(waveId, (beforeCountMap.get(waveId) || 0) + 1);
|
||||
}
|
||||
|
||||
// 重建波次索引(内部先删后插,wave_index 从 1 开始连续编号)
|
||||
const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: normalizedWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 重排后查询各波次每单的 wave_index,用于对比是否实际发生变化
|
||||
const afterRows = await this.ctx.model.query(`
|
||||
SELECT wave_id, order_id, wave_index
|
||||
FROM wms_order_wave_index
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)
|
||||
ORDER BY wave_id, order_id
|
||||
`, {
|
||||
replacements: { warehouseId, waveIds: normalizedWaveIds },
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const afterIndexMap = new Map(); // waveId -> Map(orderId -> wave_index)
|
||||
for (const row of (Array.isArray(afterRows) ? afterRows : [])) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const orderId = Number(row && row.order_id || 0);
|
||||
const waveIndex = Number(row && row.wave_index || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) continue;
|
||||
if (!afterIndexMap.has(waveId)) afterIndexMap.set(waveId, new Map());
|
||||
if (Number.isInteger(orderId) && orderId > 0) {
|
||||
afterIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0);
|
||||
}
|
||||
}
|
||||
|
||||
// 同步更新 wms_wave_batch.total_orders
|
||||
const waveDetails = [];
|
||||
for (const waveId of normalizedWaveIds) {
|
||||
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
|
||||
const beforeCount = Number(beforeCountMap.get(waveId) || 0);
|
||||
|
||||
if (remainingCount > 0) {
|
||||
await this.ctx.model.query(`
|
||||
UPDATE wms_wave_batch
|
||||
SET total_orders = :remainingCount,
|
||||
processed_orders = LEAST(processed_orders, :remainingCount),
|
||||
update_time = NOW()
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id = :waveId
|
||||
`, {
|
||||
replacements: { warehouseId, waveId, remainingCount },
|
||||
transaction,
|
||||
});
|
||||
} else {
|
||||
await this.ctx.model.query(`
|
||||
UPDATE wms_wave_batch
|
||||
SET total_orders = 0,
|
||||
processed_orders = 0,
|
||||
wave_status = -1,
|
||||
update_time = NOW()
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id = :waveId
|
||||
`, {
|
||||
replacements: { warehouseId, waveId },
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
// 对比每单重排前后的 wave_index,判断是否实际发生变化
|
||||
const beforeOrderMap = beforeIndexMap.get(waveId) || new Map();
|
||||
const afterOrderMap = afterIndexMap.get(waveId) || new Map();
|
||||
const allOrderIds = new Set([ ...beforeOrderMap.keys(), ...afterOrderMap.keys() ]);
|
||||
let hasChanged = beforeCount !== remainingCount;
|
||||
if (!hasChanged) {
|
||||
for (const oid of allOrderIds) {
|
||||
if (beforeOrderMap.get(oid) !== afterOrderMap.get(oid)) {
|
||||
hasChanged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
waveDetails.push({
|
||||
wave_id: waveId,
|
||||
before_index_count: beforeCount,
|
||||
after_index_count: remainingCount,
|
||||
reordered: hasChanged,
|
||||
});
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
const totalBefore = waveDetails.reduce((sum, w) => sum + w.before_index_count, 0);
|
||||
const totalAfter = waveDetails.reduce((sum, w) => sum + w.after_index_count, 0);
|
||||
|
||||
return this.success('ok', {
|
||||
warehouse_id: warehouseId,
|
||||
wave_count: normalizedWaveIds.length,
|
||||
total_before_index_count: totalBefore,
|
||||
total_after_index_count: totalAfter,
|
||||
waves: waveDetails,
|
||||
});
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量移除异常订单任务提交接口。
|
||||
*
|
||||
@ -9203,6 +9345,15 @@ class WaveService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
// 关闭自动加团前,重建波次订单索引(wave_index 重新排序),确保序号连续
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
await this.replaceOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds: updatedWaveIds,
|
||||
orderModel,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const updateSql = `
|
||||
UPDATE wms_wave_batch
|
||||
SET wave_status = 1,
|
||||
@ -9969,7 +10120,7 @@ class WaveService extends OrderBaseService {
|
||||
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
const orderTableName = this.getModelTableSqlName(orderModel);
|
||||
const structureExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.items_hash, '')), ''), TRIM(COALESCE(${alias}.items, '')))`;
|
||||
const structureExpr = alias => `${alias}.items_hash`;
|
||||
const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`;
|
||||
const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : '';
|
||||
const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : '';
|
||||
@ -12110,6 +12261,13 @@ class WaveService extends OrderBaseService {
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 清理波次订单索引
|
||||
await this.deleteOrderWaveIndexByWaveIds({
|
||||
warehouseId,
|
||||
waveIds,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0) {
|
||||
hasReleasedWaves = true;
|
||||
}
|
||||
|
||||
@ -6,29 +6,35 @@ const apiSignLib = require('../../lib/api_sign');
|
||||
const API_APP_CACHE_PREFIX = 'openapi:api-app';
|
||||
const API_APP_CACHE_TTL_SECONDS = 300;
|
||||
const OPENAPI_INTERFACE_TYPE_ID = 2;
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
|
||||
class ApiSignService extends Service {
|
||||
/**
|
||||
* 构建 API 应用配置缓存键。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @param {number} [interfaceTypeId] 接口类型 ID,用于区分不同入口的缓存。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getApiAppCacheKey(appKey) {
|
||||
return `${API_APP_CACHE_PREFIX}:${String(appKey || '').trim()}`;
|
||||
getApiAppCacheKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
|
||||
const prefix = interfaceTypeId === WAREHOUSE_INTERFACE_TYPE_ID
|
||||
? 'warehouse:api-app'
|
||||
: API_APP_CACHE_PREFIX;
|
||||
return `${prefix}:${String(appKey || '').trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 app_key 查询 API 应用可用配置(带缓存)。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @param {number} [interfaceTypeId=2] 接口类型 ID,2=货主级 / 3=仓库级。
|
||||
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
|
||||
*/
|
||||
async getApiAppConfigByAppKey(appKey) {
|
||||
async getApiAppConfigByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
|
||||
const normalizedAppKey = String(appKey || '').trim();
|
||||
if (!normalizedAppKey) {
|
||||
throw new Error('appKey 不能为空');
|
||||
}
|
||||
|
||||
const cacheKey = this.getApiAppCacheKey(normalizedAppKey);
|
||||
const cacheKey = this.getApiAppCacheKey(normalizedAppKey, interfaceTypeId);
|
||||
if (this.app && typeof this.app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
@ -41,9 +47,10 @@ class ApiSignService extends Service {
|
||||
}
|
||||
|
||||
const row = await this.ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id' ],
|
||||
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
|
||||
where: {
|
||||
self_app_key: normalizedAppKey,
|
||||
interface_type_id: interfaceTypeId,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
@ -56,10 +63,6 @@ class ApiSignService extends Service {
|
||||
throw new Error('API 应用已禁用');
|
||||
}
|
||||
|
||||
if (Number(row.interface_type_id) !== OPENAPI_INTERFACE_TYPE_ID) {
|
||||
throw new Error('app_key 无效或不可用');
|
||||
}
|
||||
|
||||
if (!row.self_app_secret) {
|
||||
throw new Error('API 应用缺少 self_app_secret 配置');
|
||||
}
|
||||
@ -68,6 +71,8 @@ class ApiSignService extends Service {
|
||||
id: row.id,
|
||||
appKey: row.self_app_key,
|
||||
selfAppSecret: row.self_app_secret,
|
||||
interfaceTypeId: Number(row.interface_type_id),
|
||||
warehouseId: row.warehouse_id ? Number(row.warehouse_id) : null,
|
||||
};
|
||||
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
@ -83,10 +88,11 @@ class ApiSignService extends Service {
|
||||
/**
|
||||
* 根据 app_key 查询 API 应用密钥信息。
|
||||
* @param {string} appKey 开放接口 app_key。
|
||||
* @param {number} [interfaceTypeId=2] 接口类型 ID。
|
||||
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
|
||||
*/
|
||||
async getApiAppSecretByAppKey(appKey) {
|
||||
return await this.getApiAppConfigByAppKey(appKey);
|
||||
async getApiAppSecretByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
|
||||
return await this.getApiAppConfigByAppKey(appKey, interfaceTypeId);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -97,12 +103,13 @@ class ApiSignService extends Service {
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.providedSign 请求中携带的 sign。
|
||||
* @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。
|
||||
* @param {number} [options.interfaceTypeId=2] 接口类型 ID。
|
||||
* @return {Promise<Object>} 验签结果。
|
||||
*/
|
||||
async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys } = {}) {
|
||||
async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID } = {}) {
|
||||
let appConfig;
|
||||
try {
|
||||
appConfig = await this.getApiAppSecretByAppKey(appKey);
|
||||
appConfig = await this.getApiAppSecretByAppKey(appKey, interfaceTypeId);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
@ -137,6 +144,8 @@ class ApiSignService extends Service {
|
||||
sign: verifyResult.expectedSign,
|
||||
appId: appConfig.id,
|
||||
appKey: appConfig.appKey,
|
||||
interfaceTypeId: appConfig.interfaceTypeId,
|
||||
warehouseId: appConfig.warehouseId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -318,11 +318,11 @@ class DeliveryOrderService extends Service {
|
||||
* 优先级:
|
||||
* 1. 先匹配平台列表里的基础平台项;
|
||||
* 2. 再匹配平台列表里的系统设置项;
|
||||
* 3. 兜底:签约策略 default_platform_code(货主-仓库级)→ 货主 subject_config.default_platform_code。
|
||||
* 3. 兜底:合约 policy_config.default_platform_code。
|
||||
*
|
||||
* @param {string} sourcePlatformCode 外部平台编码。
|
||||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||||
* @param {Object} [policyConfig={}] 货主-仓库签约策略配置。
|
||||
* @param {Object} storeSubjectConfig 合约 policy_config。
|
||||
* @param {Object} [policyConfig={}] 合约策略配置。
|
||||
* @param {Object} [info={}] 上下文信息。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 平台快照。
|
||||
@ -350,7 +350,7 @@ class DeliveryOrderService extends Service {
|
||||
sourcePlatformCode: externalCode,
|
||||
});
|
||||
|
||||
// 兜底优先级:签约策略(货主-仓库级)→ 货主 subject_config
|
||||
// 兜底优先级:合约 policy_config
|
||||
const policyDefaultCode = String(policyConfig && policyConfig.default_platform_code || '').trim();
|
||||
const ownerDefaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
|
||||
const defaultCode = policyDefaultCode || ownerDefaultCode;
|
||||
@ -458,10 +458,10 @@ class DeliveryOrderService extends Service {
|
||||
/**
|
||||
* 解析是否启用外部快递编码。
|
||||
*
|
||||
* 优先级:显式值 -> policy_config -> storeSubjectConfig,均未提供时默认关闭。
|
||||
* 优先级:显式值 -> policy_config,均未提供时默认关闭。
|
||||
*
|
||||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||||
* @param {Object} policyConfig 仓库策略配置。
|
||||
* @param {Object} storeSubjectConfig 合约 policy_config(与 policyConfig 同源)。
|
||||
* @param {Object} policyConfig 合约策略配置。
|
||||
* @param {any} explicitValue 显式指定值。
|
||||
* @return {boolean} 是否启用外部快递编码。
|
||||
*/
|
||||
@ -484,21 +484,36 @@ class DeliveryOrderService extends Service {
|
||||
/**
|
||||
* 解析订单快递快照。
|
||||
*
|
||||
* 优先级:
|
||||
* 1. 先读取是否启用外部快递编码开关;
|
||||
* 2. 开关关闭时,直接使用货主默认快递回填四个快递字段;
|
||||
* 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退货主默认快递。
|
||||
* 默认快递编码统一从合约 policy_config 读取。
|
||||
*
|
||||
* 分支路由:
|
||||
* 1. 先读取是否启用外部快递编码开关;
|
||||
* 2. 开关关闭时,直接使用合约默认快递回填四个快递字段;
|
||||
* 3. 开关开启时,先匹配 wms_express_setting,再匹配 wms_express,最后回退默认快递。
|
||||
*
|
||||
* @param {string} logisticsCode 外部快递编码。
|
||||
* @param {Object} storeSubjectConfig 货主签约配置。
|
||||
* @param {Object} [info={}] 上下文信息。
|
||||
* @param {Object} storeSubjectConfig 合约 policy_config。
|
||||
* @param {Object} [info={}] 上下文信息,可含 policyConfig / enableExternalExpressCode / warehouseId。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 快递快照。
|
||||
*/
|
||||
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}, operationLogs = []) {
|
||||
const expressList = await this.ctx.service.systems.express.getExpressList();
|
||||
const externalCode = String(logisticsCode || '').trim();
|
||||
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim();
|
||||
|
||||
// 默认快递编码统一从合约 policy_config 读取
|
||||
const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object'
|
||||
? info.policyConfig
|
||||
: {};
|
||||
const contractConfig = storeSubjectConfig && typeof storeSubjectConfig === 'object'
|
||||
? storeSubjectConfig
|
||||
: {};
|
||||
const defaultCode = String(
|
||||
contractConfig.default_express_code
|
||||
|| policyConfig.default_express_code
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
const fallbackExpress = this.findCodeOption(expressList, defaultCode);
|
||||
const fallbackLogisticsCode = String(
|
||||
fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode)
|
||||
@ -509,9 +524,6 @@ class DeliveryOrderService extends Service {
|
||||
const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode')
|
||||
? info.enableExternalExpressCode
|
||||
: undefined;
|
||||
const policyConfig = info && info.policyConfig && typeof info.policyConfig === 'object'
|
||||
? info.policyConfig
|
||||
: {};
|
||||
const isEnableExternalExpressCode = this.resolveEnableExternalExpressCode(
|
||||
storeSubjectConfig,
|
||||
policyConfig,
|
||||
@ -1040,15 +1052,14 @@ class DeliveryOrderService extends Service {
|
||||
receiverInfo,
|
||||
} = deliveryOrder;
|
||||
|
||||
const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId);
|
||||
const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId);
|
||||
const enableExternalExpressCode = this.resolveEnableExternalExpressCode(storeSubjectConfig, policyConfig);
|
||||
const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, policyConfig, {
|
||||
const enableExternalExpressCode = this.resolveEnableExternalExpressCode(policyConfig, policyConfig);
|
||||
const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, policyConfig, policyConfig, {
|
||||
deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
}, operationLogs);
|
||||
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, {
|
||||
const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, policyConfig, {
|
||||
deliveryOrderCode,
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
@ -1532,14 +1543,7 @@ class DeliveryOrderService extends Service {
|
||||
buildExpressAllocateRequest(context) {
|
||||
const order = context && context.order ? context.order : {};
|
||||
return {
|
||||
orders: [{
|
||||
order_id: Number(order.id || context.orderId || 0),
|
||||
business_key: 1,
|
||||
sys_platform_code: String(order.sys_platform_code || '').trim(),
|
||||
logistics_code: String(order.logistics_code || '').trim(),
|
||||
store_id: Number(order.store_id || context.storeId || 0),
|
||||
warehouse_id: Number(order.warehouse_id || context.warehouseId || 0),
|
||||
}],
|
||||
ids: [ Number(order.id || context.orderId || 0) ],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -58,6 +58,8 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([
|
||||
'logistics_code',
|
||||
'extend_props',
|
||||
'buyer_nick',
|
||||
'pay_no',
|
||||
'from_key'
|
||||
]);
|
||||
|
||||
class ExpressService extends Service {
|
||||
@ -2460,7 +2462,7 @@ class ExpressService extends Service {
|
||||
[Op.in]: [ 1, 2, 3, 4 ],
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -2481,7 +2483,7 @@ class ExpressService extends Service {
|
||||
[Op.in]: [ 4 ],
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id','pay_no','from_key' ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
@ -3106,6 +3108,9 @@ class ExpressService extends Service {
|
||||
id: {
|
||||
[Op.in]: stepUpdatableIds,
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
@ -706,7 +706,7 @@ class ExpressPlatformService extends MainService {
|
||||
let playload = {
|
||||
object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
|
||||
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
|
||||
plattradeno: order.source_order_codes || order.delivery_order_code || '',
|
||||
plattradeno: listByWarehousePlatformCode.platform_code === 'DY' && order.from_key == 23060081? order.pay_no : order.source_order_codes || order.delivery_order_code || '',
|
||||
ismultiplepieces: order.package_count > 1 ? 1 : 0,
|
||||
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
|
||||
logistictype: order.logistics_code || '',
|
||||
|
||||
@ -402,6 +402,11 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}
|
||||
const orderMap = new Map();
|
||||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||||
if (orderRow && Number(orderRow.id) > 0) {
|
||||
// 分发前过滤:已同步完成的订单不再派发
|
||||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||||
service.ctx.logger.info(`[syncManualOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||||
continue;
|
||||
}
|
||||
orderMap.set(Number(orderRow.id), orderRow);
|
||||
}
|
||||
}
|
||||
@ -413,6 +418,10 @@ async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}
|
||||
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||||
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||||
const batchResults = await Promise.all(batch.map(orderId => {
|
||||
const dispathedOrderRow = orderMap.get(orderId);
|
||||
if (!dispathedOrderRow) {
|
||||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||||
}
|
||||
return processManualOrderInternal(
|
||||
service,
|
||||
orderModel,
|
||||
@ -484,7 +493,7 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
});
|
||||
@ -509,7 +518,8 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
|
||||
await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => {
|
||||
let resolvedOrderRow = orderRow;
|
||||
if (!resolvedOrderRow && orderModel && typeof orderModel.findOne === 'function') {
|
||||
// 最小修复:始终执行 SELECT ... FOR UPDATE,不再因 orderRow 已传入而跳过
|
||||
if (orderModel && typeof orderModel.findOne === 'function') {
|
||||
resolvedOrderRow = await orderModel.findOne({
|
||||
where: {
|
||||
id: orderId,
|
||||
@ -569,6 +579,9 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
status: {
|
||||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
@ -642,6 +655,9 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
status: {
|
||||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
@ -815,6 +831,11 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
const orderMap = new Map();
|
||||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||||
if (orderRow && Number(orderRow.id) > 0) {
|
||||
// 分发前过滤:已同步完成的订单不再派发
|
||||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||||
service.ctx.logger.info(`[syncApiOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||||
continue;
|
||||
}
|
||||
orderMap.set(Number(orderRow.id), orderRow);
|
||||
}
|
||||
}
|
||||
@ -826,6 +847,10 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
|
||||
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||||
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||||
const batchResults = await Promise.all(batch.map(orderId => {
|
||||
const dispathedOrderRow = orderMap.get(orderId);
|
||||
if (!dispathedOrderRow) {
|
||||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||||
}
|
||||
return processLocalChannelOrderInternal(
|
||||
service,
|
||||
createChannel,
|
||||
@ -1156,6 +1181,11 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||||
const orderMap = new Map();
|
||||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||||
if (orderRow && Number(orderRow.id) > 0) {
|
||||
// 分发前过滤:已同步完成的订单不再派发,避免重复同步覆盖 error 等异常状态
|
||||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||||
service.ctx.logger.info(`[syncQmOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||||
continue;
|
||||
}
|
||||
orderMap.set(Number(orderRow.id), orderRow);
|
||||
}
|
||||
}
|
||||
@ -1182,6 +1212,12 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||||
for (let i = 0; i < orderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||||
const batch = orderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||||
const batchResults = await Promise.all(batch.map(orderId => {
|
||||
// 分发时二次检查:orderRow 不在 map 中则跳过
|
||||
const dispathedOrderRow = orderMap.get(orderId);
|
||||
if (!dispathedOrderRow) {
|
||||
service.ctx.logger.info(`[syncQmOrders] 订单已过滤,跳过 orderId=${orderId}`);
|
||||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||||
}
|
||||
return processQmOrderInternal(
|
||||
service,
|
||||
orderModel,
|
||||
@ -1189,7 +1225,7 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||||
qimenClient,
|
||||
orderId,
|
||||
warehouseId,
|
||||
orderMap.get(orderId),
|
||||
dispathedOrderRow,
|
||||
itemsByOrderId.get(orderId) || [],
|
||||
context,
|
||||
waybillCodeMap.get(orderId)
|
||||
|
||||
@ -3055,6 +3055,7 @@ ${waveFilterSql}
|
||||
documentId,
|
||||
packageMaterialName: suggestedPackageMaterialName,
|
||||
extraCustomLines,
|
||||
customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '',
|
||||
},
|
||||
});
|
||||
const printData = this.extractSinglePlatformPrintData(printPayload);
|
||||
|
||||
@ -1328,6 +1328,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
status: {
|
||||
[ctx.app.Sequelize.Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
@ -1831,7 +1834,11 @@ class OrderStorageAllocationService extends MainService {
|
||||
order_flag: snBatchForbiddenReason,
|
||||
updated_at: now,
|
||||
}, {
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: snFailIds }, warehouse_id: warehouseId },
|
||||
where: {
|
||||
id: { [ctx.app.Sequelize.Op.in]: snFailIds },
|
||||
warehouse_id: warehouseId,
|
||||
status: { [ctx.app.Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
@ -1845,7 +1852,11 @@ class OrderStorageAllocationService extends MainService {
|
||||
order_flag: fastFailReason,
|
||||
updated_at: now,
|
||||
}, {
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: expressFailIds }, warehouse_id: warehouseId },
|
||||
where: {
|
||||
id: { [ctx.app.Sequelize.Op.in]: expressFailIds },
|
||||
warehouse_id: warehouseId,
|
||||
status: { [ctx.app.Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
@ -690,12 +690,17 @@ class EntryService extends Service {
|
||||
const receivedQty = Number(item.received_quantity) || 0;
|
||||
const completed = receivedQty > 0 ? receivedQty : directInQty;
|
||||
|
||||
const stockDetail = stockMap.get(Number(item.stock_id));
|
||||
const stock = stockDetail
|
||||
? (s => { delete s.quantity; delete s.locked_quantity; return s; })({ ...stockDetail })
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
stock_id: item.stock_id,
|
||||
planned: planQty,
|
||||
completed,
|
||||
stock: stockMap.get(Number(item.stock_id)) || null,
|
||||
stock,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
274
app/service/warehouse.js
Normal file
274
app/service/warehouse.js
Normal file
@ -0,0 +1,274 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
|
||||
class WarehouseService extends Service {
|
||||
/**
|
||||
* 解析 warehouse method,拆分为服务路径与动作名。
|
||||
* @param {string} methodName method 名称。
|
||||
* @return {{ servicePath: string, actionName: string }} 解析结果。
|
||||
*/
|
||||
resolveWarehouseMethod(methodName = '') {
|
||||
const method = String(methodName || '').trim();
|
||||
const parts = method.split('.').filter(Boolean);
|
||||
const actionName = parts.pop() || '';
|
||||
const servicePath = parts.join('.');
|
||||
|
||||
return {
|
||||
servicePath,
|
||||
actionName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据服务路径查找 warehouseMethods 下的目标服务。
|
||||
* @param {string} servicePath 服务路径。
|
||||
* @return {Object|null} 目标服务实例。
|
||||
*/
|
||||
getWarehouseMethodService(servicePath = '') {
|
||||
const { ctx } = this;
|
||||
const pathSegments = String(servicePath || '').split('.').filter(Boolean);
|
||||
let methodService = ctx.service.warehouseMethods;
|
||||
|
||||
if (pathSegments.length === 0) {
|
||||
return methodService;
|
||||
}
|
||||
|
||||
for (const segment of pathSegments) {
|
||||
methodService = methodService && methodService[segment];
|
||||
}
|
||||
|
||||
return methodService || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发 warehouse method 到 warehouseMethods 目录。
|
||||
* 分发前统一注入仓库上下文(warehouseId/appKey)。
|
||||
* @param {string} methodName method 名称。
|
||||
* @param {Object} body 请求体。
|
||||
* @param {Object} query 请求 query。
|
||||
* @param {Object} warehouseInfo 仓库上下文信息。
|
||||
* @return {Promise<Object>} method 执行结果。
|
||||
*/
|
||||
async dispatchWarehouseMethod(methodName, body, query, warehouseInfo) {
|
||||
const { servicePath, actionName } = this.resolveWarehouseMethod(methodName);
|
||||
const methodService = this.getWarehouseMethodService(servicePath);
|
||||
|
||||
if (!methodService || typeof methodService[actionName] !== 'function') {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: `warehouse method 不存在: ${methodName}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 统一注入仓库上下文到方法服务实例
|
||||
if (warehouseInfo && typeof methodService.setInfo === 'function') {
|
||||
methodService.setInfo(
|
||||
null, // storeId
|
||||
warehouseInfo.warehouseId,
|
||||
warehouseInfo.appKey,
|
||||
null, // customerId
|
||||
null // warehouseCode
|
||||
);
|
||||
}
|
||||
|
||||
const methodResult = await methodService[actionName]({
|
||||
body,
|
||||
query,
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
httpStatus: 200,
|
||||
code: 1,
|
||||
message: 'ok',
|
||||
data: methodResult,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 warehouse 基础 query 参数。
|
||||
* @param {Object} query 请求 query 参数。
|
||||
* @return {boolean} 是否通过基础参数校验。
|
||||
*/
|
||||
validateWarehouseParams(query) {
|
||||
const requiredFields = [ 'method', 'v', 'timestamp' ];
|
||||
for (const field of requiredFields) {
|
||||
if (!query || !query[field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof query.method !== 'string' || !query.method.includes('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取并解析 JSON 请求体。
|
||||
* @return {Promise<Object>} 解析后的 JSON 对象。
|
||||
*/
|
||||
async parseJsonBody() {
|
||||
const { ctx } = this;
|
||||
let jsonData = '';
|
||||
|
||||
if (ctx.request.rawBody) {
|
||||
jsonData = ctx.request.rawBody;
|
||||
} else if (ctx.request.body !== undefined) {
|
||||
jsonData = typeof ctx.request.body === 'string'
|
||||
? ctx.request.body
|
||||
: JSON.stringify(ctx.request.body);
|
||||
} else {
|
||||
jsonData = await new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
ctx.req.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
ctx.req.on('end', () => {
|
||||
resolve(data);
|
||||
});
|
||||
ctx.req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
jsonData = jsonData ? String(jsonData) : '';
|
||||
if (!jsonData || jsonData.trim() === '') {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: 'json数据为空',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(jsonData);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: 'json数据解析错误',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取并归一化 warehouse 所需的 appKey 与 sign。
|
||||
* @param {Object} query 请求 query 参数。
|
||||
* @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。
|
||||
*/
|
||||
normalizeSignFields(query = {}) {
|
||||
const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim();
|
||||
const providedSign = String(query.sign || query.signature || '').trim();
|
||||
|
||||
return {
|
||||
appKey,
|
||||
providedSign,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 warehouse 请求并返回统一结果。
|
||||
* 核心差异:使用 interface_type_id=3(仓库级),无需合约关联,直接取 warehouse_id。
|
||||
* @return {Promise<Object>} 统一结果对象。
|
||||
*/
|
||||
async processRequest() {
|
||||
const { ctx } = this;
|
||||
const query = ctx.query || {};
|
||||
|
||||
if (!this.validateWarehouseParams(query)) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: '参数缺失或错误: method/v/timestamp',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 时间戳时效校验(±10分钟)
|
||||
const nowTs = Math.floor(Date.now() / 1000);
|
||||
const reqTs = Number(query.timestamp);
|
||||
if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: `时间戳已过期或无效,服务器时间: ${nowTs}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const body = await this.parseJsonBody();
|
||||
if (body && body.ok === false) {
|
||||
return body;
|
||||
}
|
||||
|
||||
const { appKey, providedSign } = this.normalizeSignFields(query);
|
||||
if (!appKey) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: '参数缺失或错误: app_key',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const { systems: systemsService } = ctx.service;
|
||||
const apiSignService = systemsService.apiSign;
|
||||
|
||||
// 仓库级验签:interface_type_id = 3
|
||||
const verifyResult = await apiSignService.verifyRequestSignByAppKey({
|
||||
appKey,
|
||||
query,
|
||||
body,
|
||||
providedSign,
|
||||
interfaceTypeId: WAREHOUSE_INTERFACE_TYPE_ID,
|
||||
});
|
||||
|
||||
if (!verifyResult.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 401,
|
||||
code: 401,
|
||||
message: `签名校验失败: ${verifyResult.message}`,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 仓库级无需合约关联,直接使用 api_app.warehouse_id
|
||||
const warehouseId = verifyResult.warehouseId;
|
||||
if (!warehouseId) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 403,
|
||||
code: 403,
|
||||
message: 'API 应用未绑定仓库',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const queryWithAppKey = {
|
||||
...query,
|
||||
app_key: verifyResult.appKey,
|
||||
};
|
||||
|
||||
return await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, {
|
||||
warehouseId,
|
||||
appKey: verifyResult.appKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseService;
|
||||
22
app/service/warehouseMethods/index.js
Normal file
22
app/service/warehouseMethods/index.js
Normal file
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class WarehouseIndexService extends MainService {
|
||||
/**
|
||||
* 心跳接口,返回服务可用性与仓库上下文信息。
|
||||
* @return {Promise<Object>} 心跳响应。
|
||||
*/
|
||||
async ping() {
|
||||
const { warehouseId, appKey } = this.getInfo();
|
||||
|
||||
return {
|
||||
warehouse_id: warehouseId,
|
||||
app_key: appKey,
|
||||
server_time: Math.floor(Date.now() / 1000),
|
||||
status: 'ok',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseIndexService;
|
||||
88
app/service/warehouseMethods/store.js
Normal file
88
app/service/warehouseMethods/store.js
Normal file
@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class WarehouseStoreService extends MainService {
|
||||
/**
|
||||
* 查询当前仓库下已授权的货主列表。
|
||||
* 返回货主基本信息(id、公司名、联系人、联系电话、授权状态)。
|
||||
* @param {Object} options 请求参数。
|
||||
* @param {Object} options.body 请求体。
|
||||
* @return {Promise<Object>} 货主列表。
|
||||
*/
|
||||
async list({ body = {} } = {}) {
|
||||
const { ctx } = this;
|
||||
const { warehouseId } = this.getInfo();
|
||||
|
||||
const page = Math.max(1, Number(body.page) || 1);
|
||||
const pageSize = Math.min(100, Math.max(1, Number(body.pageSize) || 20));
|
||||
|
||||
// 通过 store_warehouse 关联查询已授权的货主
|
||||
const { StoreWarehouse, Store } = ctx.model;
|
||||
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
auth_status: 2, // 已通过
|
||||
warehouse_use_status: 1, // 仓库侧可用
|
||||
};
|
||||
|
||||
const { count: total, rows } = await StoreWarehouse.findAndCountAll({
|
||||
attributes: [
|
||||
'id',
|
||||
'store_id',
|
||||
'auth_status',
|
||||
'auth_start',
|
||||
'auth_end',
|
||||
'store_remask',
|
||||
'warehouse_remask',
|
||||
],
|
||||
where,
|
||||
include: [
|
||||
{
|
||||
model: Store,
|
||||
as: 'store',
|
||||
attributes: [
|
||||
'id',
|
||||
'company_name',
|
||||
'contact_person',
|
||||
'contact_phone',
|
||||
'status',
|
||||
],
|
||||
required: true,
|
||||
where: {
|
||||
status: 1, // 启用
|
||||
},
|
||||
},
|
||||
],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const list = rows.map(row => ({
|
||||
store_id: row['store.id'],
|
||||
company_name: row['store.company_name'],
|
||||
contact_person: row['store.contact_person'],
|
||||
contact_phone: row['store.contact_phone'],
|
||||
contract_id: row.id,
|
||||
auth_status: row.auth_status,
|
||||
auth_start: row.auth_start,
|
||||
auth_end: row.auth_end,
|
||||
store_remask: row.store_remask,
|
||||
warehouse_remask: row.warehouse_remask,
|
||||
}));
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseStoreService;
|
||||
@ -210,6 +210,8 @@ module.exports = appInfo => {
|
||||
batchSize: 50,
|
||||
force: false,
|
||||
};
|
||||
// 打印自定义区模板出口域名
|
||||
config.customAreaBaseUrl = 'https://api.ye4s.com';
|
||||
|
||||
return {
|
||||
...config,
|
||||
|
||||
@ -1907,14 +1907,14 @@
|
||||
{
|
||||
"version": "2026.04.18-system-02",
|
||||
"date": "2026-04-18",
|
||||
"summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配快递号入口,复用 express.createWaybillCodePipeline。",
|
||||
"summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配首单快递号(异步接口),复用 express.createWaybillCodePipeline。",
|
||||
"methods": [
|
||||
"order.pendingOrder.allocateExpressCode"
|
||||
],
|
||||
"notes": [
|
||||
"该接口直接接收订单对象数组入参;订单对象应为来自待处理订单列表或详情的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code、logistics_code 为订单对象自带字段,前端无需额外拼装或单独构造,直接原样回传订单对象即可。",
|
||||
"实际的运单创建、归一化与跳过逻辑由 express.createWaybillCodePipeline 处理。",
|
||||
"接口返回值与现有分配链路一致,已用统一 success 包装返回。"
|
||||
"异步接口:调用后立即返回 task_id,后台执行运单创建,通过 allocateExpressCodeTaskProgress 查询进度。",
|
||||
"入参为 ids(订单 ID 数组),sys_platform_code/logistics_code 等由后端从数据库读取。",
|
||||
"拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
|
||||
22
methods/changes/warehouse.json
Normal file
22
methods/changes/warehouse.json
Normal file
@ -0,0 +1,22 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.01-warehouse-01",
|
||||
"date": "2026-08-01",
|
||||
"type": "added",
|
||||
"summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表",
|
||||
"methods": [
|
||||
"index.ping",
|
||||
"store.list"
|
||||
],
|
||||
"notes": [
|
||||
"POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。",
|
||||
"签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。",
|
||||
"时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。",
|
||||
"无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。",
|
||||
"index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。",
|
||||
"store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。",
|
||||
"api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。"
|
||||
],
|
||||
"module": "warehouse"
|
||||
}
|
||||
]
|
||||
@ -3227,7 +3227,7 @@
|
||||
},
|
||||
{
|
||||
"method": "order.pendingOrder.allocateExpressCode",
|
||||
"description": "批量分配待处理订单的快递号,接收订单对象数组,复用 express.createWaybillCodePipeline。",
|
||||
"description": "批量分配待处理订单的首单快递号(异步接口)。调用后立即返回 task_id,后台异步执行运单创建;可通过 order.pendingOrder.allocateExpressCodeTaskProgress 查询进度。拆单场景请使用 order.pendingOrder.allocateSubOrderNumber。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -3240,11 +3240,11 @@
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "orders",
|
||||
"type": "array",
|
||||
"name": "ids",
|
||||
"type": "array<number>",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "订单对象数组;每个对象应为待处理订单列表或详情中获取的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段,前端无需额外拼装或从外部构造,直接原样回传订单对象即可。其余字段会原样透传给运单创建链路。business_key 说明:business_key 是运单创建的序号键数组(例如:新分配 1 个运单号时传 [1];订单拆单时可能传 [2,3]),该字段会在 createWaybillCodePipeline 的返回 data 中原样返回,便于前端关联订单与运单创建结果。"
|
||||
"description": "订单 ID 数组,例如 [123456, 789012]。sys_platform_code、logistics_code 等字段由后端直接从数据库读取,前端无需传参。"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -3270,7 +3270,7 @@
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "createWaybillCodePipeline 返回的运单创建结果,包含 success/failed 列表与 summary 等字段"
|
||||
"description": "异步受理结果。包含 task_id(任务 ID,用于查询进度)、status(submitted)、message、update_time 等字段。实际运单分配结果需通过 allocateExpressCodeTaskProgress 接口查询。"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
|
||||
203
methods/warehouse.json
Normal file
203
methods/warehouse.json
Normal file
@ -0,0 +1,203 @@
|
||||
{
|
||||
"module": "warehouse",
|
||||
"description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 HMAC-SHA256 签名鉴权(interface_type_id=3)",
|
||||
"version": "1.0.0",
|
||||
"updatedAt": "2026-08-01",
|
||||
"http": {
|
||||
"path": "/warehouse",
|
||||
"method": "POST"
|
||||
},
|
||||
"headers": [],
|
||||
"methods": {
|
||||
"groups": [
|
||||
{
|
||||
"groupName": "基础模块",
|
||||
"module": "index",
|
||||
"list": [
|
||||
{
|
||||
"method": "index.ping",
|
||||
"description": "心跳接口,验证仓库 API 应用连通性,返回仓库上下文与应用信息",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [],
|
||||
"response": [
|
||||
{
|
||||
"name": "warehouse_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "当前仓库 ID"
|
||||
},
|
||||
{
|
||||
"name": "app_key",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "当前请求的 AppKey"
|
||||
},
|
||||
{
|
||||
"name": "server_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "服务器 Unix 时间戳(秒)"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "服务状态,正常时返回 ok"
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"notes": [
|
||||
"模块:基础模块",
|
||||
"方法部署位置:warehouseMethods/index.ping",
|
||||
"无需 body 参数,GET query 参数满足 method/v/timestamp/app_key/sign 即可",
|
||||
"timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"groupName": "货主模块",
|
||||
"module": "store",
|
||||
"list": [
|
||||
{
|
||||
"method": "store.list",
|
||||
"description": "查询当前仓库下已授权的货主列表,返回货主基本信息与授权状态(需 auth_status=2 已通过 + store.status=1 启用 + warehouse_use_status=1 可用)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "page",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "页码,默认 1",
|
||||
"defaultValue": 1
|
||||
},
|
||||
{
|
||||
"name": "pageSize",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "每页数量,默认 20,最大 100",
|
||||
"defaultValue": 20
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "货主列表",
|
||||
"children": [
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "货主 ID(wms_store.id)"
|
||||
},
|
||||
{
|
||||
"name": "company_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "公司全称"
|
||||
},
|
||||
{
|
||||
"name": "contact_person",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "联系人"
|
||||
},
|
||||
{
|
||||
"name": "contact_phone",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "联系电话"
|
||||
},
|
||||
{
|
||||
"name": "contract_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "授权关系 ID(wms_store_warehouse.id)"
|
||||
},
|
||||
{
|
||||
"name": "auth_status",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "授权状态:2=已通过"
|
||||
},
|
||||
{
|
||||
"name": "auth_start",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "授权开始日期"
|
||||
},
|
||||
{
|
||||
"name": "auth_end",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "授权结束日期"
|
||||
},
|
||||
{
|
||||
"name": "store_remask",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "商家备注"
|
||||
},
|
||||
{
|
||||
"name": "warehouse_remask",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "仓库备注"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pagination",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "分页信息",
|
||||
"children": [
|
||||
{
|
||||
"name": "page",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "当前页码"
|
||||
},
|
||||
{
|
||||
"name": "pageSize",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "每页数量"
|
||||
},
|
||||
{
|
||||
"name": "total",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "总记录数"
|
||||
},
|
||||
{
|
||||
"name": "totalPages",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "总页数"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"notes": [
|
||||
"模块:货主模块",
|
||||
"方法部署位置:warehouseMethods/store.list",
|
||||
"仓库隔离:自动使用当前 API 应用绑定的 warehouse_id",
|
||||
"仅返回已通过授权(auth_status=2)、仓库侧可用(warehouse_use_status=1)、货主启用(store.status=1)的记录",
|
||||
"分页查询:默认 20 条/页,最大 100 条/页"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -47,8 +47,7 @@
|
||||
{
|
||||
"data": {
|
||||
"productInfo": "#0 B1340646-1-1 商品总数 【2】\nE1区06-11-01 6949517008816;6949517008342;6949517008229 【1】 0\nE1区06-08-01 69000007 【1】 0\n\n验视员:"
|
||||
},
|
||||
"templateURL": "http://www.ye4s.com/mb/douyin1.xml"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -148,6 +148,33 @@ function main() {
|
||||
const startLogPath = `/tmp/wms-${targetVersion}-start.log`;
|
||||
const currentMdPath = `${config.deployRoot}/current.md`;
|
||||
|
||||
// 5.5. 强制清理目标端口残留进程,防止端口占用导致启动失败
|
||||
const killPortScript = [
|
||||
'set -euo pipefail',
|
||||
`TARGET_PORT=${targetPort}`,
|
||||
'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
|
||||
'if [ -n "$PORT_PID" ]; then',
|
||||
` echo "检测到端口 $TARGET_PORT 被进程 $PORT_PID 占用,强制停止..."`,
|
||||
' kill -9 "$PORT_PID" 2>/dev/null || true',
|
||||
' sleep 1',
|
||||
' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)',
|
||||
' if [ -n "$PORT_PID_CHECK" ]; then',
|
||||
` echo "[WARN] 端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,尝试再次强制停止..."`,
|
||||
' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
|
||||
' fi',
|
||||
` echo "端口 $TARGET_PORT 已释放"`,
|
||||
'else',
|
||||
` echo "端口 $TARGET_PORT 空闲,无需清理"`,
|
||||
'fi',
|
||||
].join('\n');
|
||||
|
||||
try {
|
||||
const killPortOutput = runSsh(config, killPortScript, { stdio: 'pipe' });
|
||||
console.log(String(killPortOutput || '').trim());
|
||||
} catch (err) {
|
||||
console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`);
|
||||
}
|
||||
|
||||
// 6. 更新远端 current.md 并启动新实例
|
||||
const switchAndStartScript = [
|
||||
'set -euo pipefail',
|
||||
@ -162,17 +189,17 @@ function main() {
|
||||
const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
|
||||
console.log(String(switchOutput || '').trim());
|
||||
|
||||
// 6.5. 健康检查新实例(curl 循环等待,最多 10 秒)
|
||||
// 6.5. 健康检查新实例(curl 循环等待,最多 20 秒)
|
||||
const oldDir = `${config.deployRoot}/${currentVersion}`;
|
||||
const healthCheckScript = [
|
||||
'set -euo pipefail',
|
||||
`TARGET_PORT=${targetPort}`,
|
||||
'for attempt in $(seq 1 5); do',
|
||||
'for attempt in $(seq 1 10); do',
|
||||
' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
|
||||
` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
|
||||
' break',
|
||||
' fi',
|
||||
' if [ "$attempt" -eq 5 ]; then',
|
||||
' if [ "$attempt" -eq 10 ]; then',
|
||||
` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
|
||||
' exit 1',
|
||||
' fi',
|
||||
@ -185,8 +212,8 @@ function main() {
|
||||
console.log(String(healthOutput || '').trim());
|
||||
} catch (err) {
|
||||
// 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例
|
||||
console.error(`[ERROR] 新实例健康检查失败 (10s 超时): ${err.message}`);
|
||||
console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例`);
|
||||
console.error(`[ERROR] 新实例健康检查失败 (20s 超时): ${err.message}`);
|
||||
console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例。可检查启动日志 ${startLogPath}`);
|
||||
|
||||
// 回滚:将 current.md 恢复为旧版本
|
||||
const revertCurrentMdScript = [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user