1
This commit is contained in:
parent
43c60dd934
commit
0b207a1c9c
@ -28,6 +28,14 @@ module.exports = app => {
|
||||
*/
|
||||
const getDefaultInventoryWarningRules = () => DEFAULT_INVENTORY_WARNING_RULES.map(rule => ({ ...rule }));
|
||||
|
||||
const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze({
|
||||
enabled: false,
|
||||
require_recheck: true,
|
||||
require_pack: true,
|
||||
require_weigh: true,
|
||||
require_sync: true,
|
||||
});
|
||||
|
||||
const DEFAULT_SUBJECT_CONFIG = Object.freeze({
|
||||
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
|
||||
max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY,
|
||||
@ -38,6 +46,7 @@ module.exports = app => {
|
||||
group_wave_prefix: 'B',
|
||||
delete_order_wave_prefix: 'A',
|
||||
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
|
||||
auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES,
|
||||
});
|
||||
|
||||
const normalizeSubjectConfigText = (value, defaultValue) => {
|
||||
@ -116,12 +125,46 @@ module.exports = app => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化自动化出库规则配置。
|
||||
*
|
||||
* @param {Object|undefined|null} rawRules 原始自动化出库规则。
|
||||
* @return {Object} 规范化后的自动化出库规则对象。
|
||||
*/
|
||||
const normalizeAutoOutboundRules = rawRules => {
|
||||
if (rawRules === undefined || rawRules === null || rawRules === '') {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
}
|
||||
|
||||
let parsed = rawRules;
|
||||
if (typeof parsed === 'string') {
|
||||
try {
|
||||
parsed = JSON.parse(parsed);
|
||||
} catch (error) {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: normalizeBooleanFlag(parsed.enabled, 'auto_outbound_rules.enabled') === true,
|
||||
require_recheck: parsed.require_recheck !== false,
|
||||
require_pack: parsed.require_pack !== false,
|
||||
require_weigh: parsed.require_weigh !== false,
|
||||
require_sync: parsed.require_sync !== false,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化主体配置,确保默认值与字段约束一致。
|
||||
*
|
||||
* @param {Object|string|null|undefined} rawValue 主体配置原始值。
|
||||
* @return {Object} 规范化后的主体配置对象。
|
||||
*/
|
||||
|
||||
const normalizeSubjectConfig = rawValue => {
|
||||
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
||||
return {
|
||||
@ -240,6 +283,7 @@ module.exports = app => {
|
||||
}
|
||||
|
||||
normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules);
|
||||
normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules);
|
||||
|
||||
return normalized;
|
||||
};
|
||||
|
||||
50
app/schedule/auto_outbound_order.js
Normal file
50
app/schedule/auto_outbound_order.js
Normal file
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 自动化出库定时任务。
|
||||
* 每分钟在单 worker 中扫描一次:当订单满足仓库配置的自动化出库条件时,
|
||||
* 自动标记出库并将订单状态更新为已完成。
|
||||
*
|
||||
* 出库条件(由仓库 subject_config.auto_outbound_rules 控制):
|
||||
* 1. 已复核:recheck_status = 'fin'
|
||||
* 2. 已打包:pack_status = 'fin'
|
||||
* 3. 已称重:wms_order_express.weighing_weight > 0
|
||||
*
|
||||
* 各条件是否必须可由仓库配置独立控制。
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '1m',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行自动化出库任务。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
if (ctx.app._autoOutboundRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._autoOutboundRunning = true;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.systems.orderAutoOutbound.executeAutoOutbound();
|
||||
|
||||
if (result && result.totalProcessed > 0) {
|
||||
ctx.logger.info(
|
||||
`[auto-outbound-order] 本轮自动化出库完成,共处理 ${result.totalProcessed} 条订单`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[auto-outbound-order] 自动化出库任务执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._autoOutboundRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -688,9 +688,10 @@ class OrderBaseService extends MainService {
|
||||
/**
|
||||
* 查询订单关联运单信息。
|
||||
* @param {number|string} orderId 订单ID。
|
||||
* @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name。
|
||||
* @return {Promise<Object[]>} 运单信息列表。
|
||||
*/
|
||||
async getOrderExpressesByOrderId(orderId) {
|
||||
async getOrderExpressesByOrderId(orderId, order) {
|
||||
const normalizedOrderId = Number(orderId || 0);
|
||||
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
@ -706,16 +707,28 @@ class OrderBaseService extends MainService {
|
||||
where: {
|
||||
order_id: normalizedOrderId,
|
||||
},
|
||||
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ],
|
||||
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'weighing_weight', 'business_key', 'create_at' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const sysLogisticsCode = order && order.sys_logistics_code != null
|
||||
? String(order.sys_logistics_code).trim()
|
||||
: '';
|
||||
const sysLogisticsName = order && order.sys_logistics_name != null
|
||||
? String(order.sys_logistics_name).trim()
|
||||
: '';
|
||||
|
||||
return (Array.isArray(rows) ? rows : []).map(row => ({
|
||||
waybill_code: String(row && row.waybill_code || '').trim(),
|
||||
weighing_weight: row && row.weighing_weight != null ? Number(row.weighing_weight) : null,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
logistics_code: String(row && row.logistics_code || '').trim(),
|
||||
logistics_name: String(row && row.logistics_name || '').trim(),
|
||||
logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id),
|
||||
business_key: String(row && row.business_key || '').trim(),
|
||||
create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null,
|
||||
}));
|
||||
}
|
||||
|
||||
@ -1169,7 +1182,7 @@ class OrderBaseService extends MainService {
|
||||
});
|
||||
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
|
||||
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId, order);
|
||||
const logs = await this.getOrderOperationLogs(orderId);
|
||||
return {
|
||||
detail: order,
|
||||
|
||||
@ -425,14 +425,17 @@ class OrderIndexService extends OrderBaseService {
|
||||
* - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。
|
||||
* - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。
|
||||
* - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。
|
||||
* - 运单号模式(order_id = 0):从运单号反查,必传 waybill_code。团购时按 wave_no + business_key 批量设置。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.waybill_code] 运单号,多运单场景必填。
|
||||
* @param {number|string} data.order_id 订单ID。
|
||||
* @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。
|
||||
* @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。
|
||||
* @param {number|string} data.weighing_weight 称重重量(kg)。
|
||||
* @return {Promise<Object>} 统一成功/失败结构。
|
||||
* 单订单:{data: {order_id, waybill_code, weighing_weight}};
|
||||
* 团购批量:{data: {wave_id, wave_no, weighing_weight, success_count, total_count}}。
|
||||
* 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}};
|
||||
* 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}};
|
||||
* 运单号模式单运单:{data: {order_id, waybill_code, weighing_weight}};
|
||||
* 运单号模式团购批量:{data: {wave_id, wave_no, business_key, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}。
|
||||
*/
|
||||
async updateExpressWeighingWeight(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
@ -443,11 +446,21 @@ class OrderIndexService extends OrderBaseService {
|
||||
} = requestData;
|
||||
|
||||
try {
|
||||
const result = await this.service.systems.orderExpress.updateWeighingWeight({
|
||||
orderId,
|
||||
waybillCode,
|
||||
weighingWeight,
|
||||
});
|
||||
let result;
|
||||
if (Number(orderId) === 0) {
|
||||
// 运单号模式:从运单号反查订单与波次
|
||||
result = await this.service.systems.orderExpress.updateWeighingWeightByWaybill({
|
||||
waybillCode,
|
||||
weighingWeight,
|
||||
});
|
||||
} else {
|
||||
// 订单模式
|
||||
result = await this.service.systems.orderExpress.updateWeighingWeight({
|
||||
orderId,
|
||||
waybillCode,
|
||||
weighingWeight,
|
||||
});
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
data: result,
|
||||
|
||||
@ -100,7 +100,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
});
|
||||
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
|
||||
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId, order);
|
||||
|
||||
return {
|
||||
detail: order,
|
||||
@ -1644,7 +1644,8 @@ class PendingOrderService extends OrderBaseService {
|
||||
/**
|
||||
* 批量修改待处理订单的收件地址信息。
|
||||
*
|
||||
* 仅允许在未分配快递(post_status = 'none')时修改,至少提供一个地址字段。
|
||||
* 地址字段仅允许在未分配快递(post_status = 'none')时修改;
|
||||
* remark 不受 post_status 限制,可独立或与地址字段同时传入。
|
||||
* 支持批量操作,返回更新数量和受影响的订单 ID 列表。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
@ -1658,6 +1659,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
* @param {string} [data.area] 区/县。
|
||||
* @param {string} [data.town] 镇/街道。
|
||||
* @param {string} [data.detail_address] 详细地址。
|
||||
* @param {string} [data.remark] 订单留言/备注,对应 wms_order_delivery.remark,最大500字符。
|
||||
* @return {Promise<Object>} 统一 success 包装的更新结果,含 updated_count 与 ids。
|
||||
*/
|
||||
async updateAddress(data = {}) {
|
||||
@ -1677,32 +1679,56 @@ class PendingOrderService extends OrderBaseService {
|
||||
'name', 'mobile', 'tel', 'zip_code',
|
||||
'province', 'city', 'area', 'town', 'detail_address',
|
||||
];
|
||||
const updates = {};
|
||||
const addressUpdates = {};
|
||||
for (const field of addressFields) {
|
||||
const value = requestData[field];
|
||||
if (value !== undefined && value !== null && String(value).trim() !== '') {
|
||||
updates[field] = String(value).trim();
|
||||
addressUpdates[field] = String(value).trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
throw new Error('至少需要提供一个地址字段进行修改');
|
||||
// 处理 remark 字段(不受 post_status 限制,最大500字符)
|
||||
let remarkValue = null;
|
||||
if (requestData.remark !== undefined && requestData.remark !== null) {
|
||||
const trimmed = String(requestData.remark).trim();
|
||||
if (trimmed !== '') {
|
||||
remarkValue = trimmed.substring(0, 500);
|
||||
}
|
||||
}
|
||||
|
||||
updates.updated_at = new Date();
|
||||
const hasAddressUpdates = Object.keys(addressUpdates).length > 0;
|
||||
if (!hasAddressUpdates && remarkValue === null) {
|
||||
throw new Error('至少需要提供一个地址字段或备注进行修改');
|
||||
}
|
||||
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = {
|
||||
...this.buildOrderWhere(orderIds, warehouseId),
|
||||
post_status: 'none',
|
||||
};
|
||||
const baseWhere = this.buildOrderWhere(orderIds, warehouseId);
|
||||
const now = new Date();
|
||||
|
||||
const [ affectedRows ] = await model.update(updates, { where });
|
||||
const count = Number(affectedRows || 0);
|
||||
let addressUpdatedCount = 0;
|
||||
let remarkUpdatedCount = 0;
|
||||
|
||||
// 地址字段更新(受 post_status='none' 限制)
|
||||
if (hasAddressUpdates) {
|
||||
addressUpdates.updated_at = now;
|
||||
const addressWhere = { ...baseWhere, post_status: 'none' };
|
||||
const [ rows ] = await model.update(addressUpdates, { where: addressWhere });
|
||||
addressUpdatedCount = Number(rows || 0);
|
||||
}
|
||||
|
||||
// remark 更新(不受 post_status 限制)
|
||||
if (remarkValue !== null) {
|
||||
const remarkUpdate = { remark: remarkValue, updated_at: now };
|
||||
const [ rows ] = await model.update(remarkUpdate, { where: baseWhere });
|
||||
remarkUpdatedCount = Number(rows || 0);
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
try {
|
||||
const updatedFieldNames = Object.keys(updates).filter(k => k !== 'updated_at');
|
||||
const updatedFieldNames = [
|
||||
...Object.keys(addressUpdates).filter(k => k !== 'updated_at'),
|
||||
...(remarkValue !== null ? [ 'remark' ] : []),
|
||||
];
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: logWarehouseId,
|
||||
@ -1712,8 +1738,10 @@ class PendingOrderService extends OrderBaseService {
|
||||
warehouseId: logWarehouseId,
|
||||
orderIds,
|
||||
updated_fields: updatedFieldNames,
|
||||
updated_count: count,
|
||||
message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],共更新 ${count} 条`,
|
||||
updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount),
|
||||
address_updated_count: addressUpdatedCount,
|
||||
remark_updated_count: remarkUpdatedCount,
|
||||
message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条,备注更新 ${remarkUpdatedCount} 条`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
});
|
||||
@ -1722,7 +1750,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
updated_count: count,
|
||||
updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount),
|
||||
ids: orderIds,
|
||||
});
|
||||
}
|
||||
@ -4434,10 +4462,10 @@ class PendingOrderService extends OrderBaseService {
|
||||
|
||||
// 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding')
|
||||
const model = await this.getOrderModel('order', warehouseId);
|
||||
const where = this.buildOrderWhere([orderId], warehouseId);
|
||||
const where = this.buildOrderWhere([ orderId ], warehouseId);
|
||||
const order = await model.findOne({
|
||||
where,
|
||||
attributes: ['id', 'step', 'outbound_status', 'warehouse_id'],
|
||||
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -4445,7 +4473,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
|
||||
}
|
||||
|
||||
const allowedSteps = new Set([1, 2, 3]);
|
||||
const allowedSteps = new Set([ 1, 2, 3 ]);
|
||||
if (!allowedSteps.has(order.step)) {
|
||||
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`);
|
||||
}
|
||||
|
||||
@ -10626,7 +10626,7 @@ class WaveService extends OrderBaseService {
|
||||
const taskNo = String(taskCreateResult.task_no || '').trim();
|
||||
|
||||
// 查询所有选中波次的 wave_no,用于填充任务波次关联记录
|
||||
let waveNoMap = new Map();
|
||||
const waveNoMap = new Map();
|
||||
if (selectedWaveIds.length > 0) {
|
||||
const waveNoRows = await this.ctx.model.query(
|
||||
`SELECT wave_id, wave_no
|
||||
|
||||
86
app/service/systemMethods/outbound.js
Normal file
86
app/service/systemMethods/outbound.js
Normal file
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 出库相关 method 层入口。
|
||||
* 负责鉴权配置与参数解构,业务逻辑下沉到 systems。
|
||||
*/
|
||||
class OutboundService extends MainService {
|
||||
/**
|
||||
* 初始化 outbound 模块鉴权配置。
|
||||
*
|
||||
* @param {Egg.Context} ctx 上下文对象。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'autoOutbound';
|
||||
const _noNeedLog = 'autoOutbound';
|
||||
const _noNeedAuth = 'autoOutbound';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动触发自动化出库扫描。
|
||||
*
|
||||
* 扫描当前仓库下满足自动化出库条件的订单并执行出库操作。
|
||||
* 条件由仓库 subject_config.auto_outbound_rules 控制:
|
||||
* - recheck_status = 'fin'(已复核)
|
||||
* - pack_status = 'fin'(已打包)
|
||||
* - wms_order_express.weighing_weight > 0(已称重)
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {number} [data.warehouseId] 指定仓库ID,不传则使用当前用户上下文仓库。
|
||||
* @return {Promise<Object>} 执行结果,包含处理数量和仓库详情。
|
||||
*/
|
||||
async autoOutbound(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(requestData.warehouseId) || this.getWarehouseId();
|
||||
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('缺少有效的仓库ID');
|
||||
}
|
||||
|
||||
const storeId = this.getWarehouseId();
|
||||
|
||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||
throw new Error('缺少有效的货主ID');
|
||||
}
|
||||
|
||||
const store = await ctx.model.Store.findOne({
|
||||
where: { id: storeId, status: 1, deleted_at: null },
|
||||
attributes: [ 'id', 'subject_config' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!store) {
|
||||
throw new Error('货主不存在或已禁用');
|
||||
}
|
||||
|
||||
let subjectConfig = store.subject_config;
|
||||
if (typeof subjectConfig === 'string') {
|
||||
try {
|
||||
subjectConfig = JSON.parse(subjectConfig);
|
||||
} catch (error) {
|
||||
throw new Error('subject_config 配置解析失败');
|
||||
}
|
||||
}
|
||||
|
||||
const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||||
|
||||
if (!autoOutboundRules || !autoOutboundRules.enabled) {
|
||||
throw new Error('当前仓库未启用自动化出库');
|
||||
}
|
||||
|
||||
const result = await ctx.service.systems.orderAutoOutbound.processWarehouseAutoOutbound(
|
||||
warehouseId,
|
||||
autoOutboundRules
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OutboundService;
|
||||
@ -688,7 +688,7 @@ class DeliveryOrderService extends Service {
|
||||
items_weight: itemsInfo.total_weight || 0, // 总重量
|
||||
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
|
||||
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
|
||||
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(','),
|
||||
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode,
|
||||
updated_at: new Date(),
|
||||
};
|
||||
|
||||
|
||||
@ -18,6 +18,12 @@ class CustomizeWebhookDriver {
|
||||
data: payload,
|
||||
};
|
||||
|
||||
this.ctx.logger.info('[CustomizeWebhookDriver.send] 发送内容', {
|
||||
hookUrl: String(hook && hook.hook_url || '').substring(0, 80),
|
||||
hookType: String(hook && hook.hook_type || 'customize'),
|
||||
payloadKeys: Object.keys(payload || {}),
|
||||
});
|
||||
|
||||
const response = await this.ctx.curl(String(hook.hook_url || ''), requestOptions);
|
||||
|
||||
return {
|
||||
|
||||
@ -56,6 +56,10 @@ class WecomWebhookDriver {
|
||||
|
||||
async send({ hook, payload }) {
|
||||
const requestData = this.buildRequestData(payload);
|
||||
this.ctx.logger.info('[WecomWebhookDriver.send] 发送内容', {
|
||||
hookUrl: String(hook && hook.hook_url || '').substring(0, 80),
|
||||
requestData,
|
||||
});
|
||||
const requestOptions = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
||||
@ -472,7 +472,7 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'delivery_order_code', 'order_type' ],
|
||||
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
@ -497,11 +497,13 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
||||
}
|
||||
|
||||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||||
const stockId = Number(orderItem && orderItem.stock_id) || 0;
|
||||
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, {
|
||||
orderId: outboundMetaOrderId,
|
||||
orderNo: outboundMetaOrderNo,
|
||||
orderItemId: outboundOrderItemId,
|
||||
});
|
||||
sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined,
|
||||
}, { stockId: stockId > 0 ? stockId : undefined });
|
||||
if (!outboundResult || outboundResult.success !== true) {
|
||||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||||
}
|
||||
@ -551,11 +553,13 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod
|
||||
}
|
||||
|
||||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||||
const stockId = Number(orderItem && orderItem.stock_id) || 0;
|
||||
const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, {
|
||||
orderId: Number(orderRow && orderRow.id) || Number(orderId) || null,
|
||||
orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null,
|
||||
orderItemId: outboundOrderItemId,
|
||||
});
|
||||
sourceOrderCodes: String(orderRow && orderRow.source_order_codes || '').trim() || undefined,
|
||||
}, { stockId: stockId > 0 ? stockId : undefined });
|
||||
if (!outboundResult || outboundResult.success !== true) {
|
||||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||||
}
|
||||
@ -619,6 +623,7 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
order_ids: [ orderId ],
|
||||
order_count: 1,
|
||||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||||
store_id: Number(orderRow && orderRow.store_id) || 0,
|
||||
waybill_code: resolvedWaybillCodes,
|
||||
warehouse_id: warehouseId,
|
||||
handler: 'syncManualOrders',
|
||||
@ -833,7 +838,7 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
||||
event: 'order_sync_completed',
|
||||
businessName: 'order',
|
||||
warehouseId,
|
||||
storeId: Number(context.storeId || context.warehouseId || 0),
|
||||
storeId: Number(syncResult.store_id || context.storeId || context.warehouseId || 0),
|
||||
subject: {
|
||||
id: warehouseId,
|
||||
type: 'warehouse',
|
||||
|
||||
296
app/service/systems/order_auto_outbound.js
Normal file
296
app/service/systems/order_auto_outbound.js
Normal file
@ -0,0 +1,296 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const OUTBOUND_STATUS = 'padding';
|
||||
const OUTBOUND_STEP = 4;
|
||||
const ORDER_STATUS_FINISHED = 'finished';
|
||||
const MAX_BATCH_SIZE = 500;
|
||||
|
||||
/**
|
||||
* 订单自动化出库服务。
|
||||
* 当订单满足仓库配置的自动化出库规则时,自动标记出库并完成订单。
|
||||
*/
|
||||
class OrderAutoOutboundService extends MainService {
|
||||
/**
|
||||
* 获取所有启用了自动化出库的仓库配置。
|
||||
*
|
||||
* @return {Promise<Array<{storeId: number, warehouseId: number, rules: Object}>>} 仓库配置列表。
|
||||
*/
|
||||
async getEnabledAutoOutboundWarehouses() {
|
||||
const { app } = this;
|
||||
const { Store, StoreWarehouse } = app.model;
|
||||
|
||||
if (!Store || !StoreWarehouse) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stores = await Store.findAll({
|
||||
where: {
|
||||
status: 1,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'subject_config' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const result = [];
|
||||
|
||||
for (const store of stores) {
|
||||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(store.subject_config);
|
||||
const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||||
|
||||
if (!autoOutboundRules || !autoOutboundRules.enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const contracts = await StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: store.id,
|
||||
auth_status: 2,
|
||||
},
|
||||
attributes: [ 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const contract of contracts) {
|
||||
result.push({
|
||||
storeId: store.id,
|
||||
warehouseId: contract.warehouse_id,
|
||||
rules: autoOutboundRules,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化 subject_config,支持字符串 JSON 和对象两种格式。
|
||||
*
|
||||
* @param {Object|string} rawConfig 原始主体配置。
|
||||
* @return {Object} 规范化后的配置对象。
|
||||
*/
|
||||
normalizeSubjectConfigForAutoOutbound(rawConfig) {
|
||||
if (!rawConfig) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (typeof rawConfig === 'object' && !Array.isArray(rawConfig)) {
|
||||
return rawConfig;
|
||||
}
|
||||
|
||||
if (typeof rawConfig === 'string') {
|
||||
try {
|
||||
return JSON.parse(rawConfig);
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造自动化出库的订单查询条件。
|
||||
*
|
||||
* @param {Object} rules 自动化出库规则。
|
||||
* @return {Object} Sequelize where 条件对象。
|
||||
*/
|
||||
buildAutoOutboundWhere(rules) {
|
||||
const where = {
|
||||
outbound_status: 'none',
|
||||
status: {
|
||||
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
||||
},
|
||||
};
|
||||
|
||||
if (rules.require_recheck) {
|
||||
where.recheck_status = 'fin';
|
||||
}
|
||||
|
||||
if (rules.require_pack) {
|
||||
where.pack_status = 'fin';
|
||||
}
|
||||
|
||||
if (rules.require_sync) {
|
||||
where.sync_status = 'fin';
|
||||
}
|
||||
|
||||
return where;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库下满足自动化出库条件的订单ID列表。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Object} rules 自动化出库规则。
|
||||
* @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限。
|
||||
* @return {Promise<Array<{id: number}>>} 订单ID列表。
|
||||
*/
|
||||
async findAutoOutboundOrders(warehouseId, rules, limit = MAX_BATCH_SIZE) {
|
||||
const { ctx } = this;
|
||||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
|
||||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||||
if (!orderModel) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const where = this.buildAutoOutboundWhere(rules);
|
||||
|
||||
if (rules.require_weigh) {
|
||||
const orderIdsWithWeigh = await this.findOrderIdsWithWeigh(warehouseId);
|
||||
if (orderIdsWithWeigh.length === 0) {
|
||||
return [];
|
||||
}
|
||||
where.id = { [Op.in]: orderIdsWithWeigh };
|
||||
}
|
||||
|
||||
const orders = await orderModel.findAll({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
limit,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return orders;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找有称重记录的订单ID列表。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Array<number>>} 订单ID列表。
|
||||
*/
|
||||
async findOrderIdsWithWeigh(warehouseId) {
|
||||
const { ctx } = this;
|
||||
const { OrderExpress } = ctx.model;
|
||||
|
||||
if (!OrderExpress) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await OrderExpress.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
weighing_weight: { [Op.gt]: 0 },
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return rows
|
||||
.map(row => Number(row.order_id))
|
||||
.filter(id => Number.isFinite(id) && id > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对指定仓库执行单次自动化出库扫描与执行。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Object} rules 自动化出库规则。
|
||||
* @return {Promise<{warehouseId: number, processedCount: number, errorMessage: string|null}>} 执行结果。
|
||||
*/
|
||||
async processWarehouseAutoOutbound(warehouseId, rules) {
|
||||
const { ctx } = this;
|
||||
const result = {
|
||||
warehouseId,
|
||||
processedCount: 0,
|
||||
errorMessage: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const orders = await this.findAutoOutboundOrders(warehouseId, rules);
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const orderIds = orders.map(order => Number(order.id)).filter(Boolean);
|
||||
if (orderIds.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||||
|
||||
const [ affectedRows ] = await orderModel.update(
|
||||
{
|
||||
outbound_status: OUTBOUND_STATUS,
|
||||
step: OUTBOUND_STEP,
|
||||
status: ORDER_STATUS_FINISHED,
|
||||
updated_at: now,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: { [Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
result.processedCount = Number(affectedRows) || 0;
|
||||
|
||||
if (result.processedCount > 0) {
|
||||
ctx.logger.info(
|
||||
`[auto-outbound] 仓库 ${warehouseId} 自动化出库 ${result.processedCount} 条订单,订单ID: ${orderIds.join(',')}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
result.errorMessage = error.message;
|
||||
ctx.logger.error(`[auto-outbound] 仓库 ${warehouseId} 自动化出库失败: ${error.message}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行全局自动化出库扫描。
|
||||
* 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。
|
||||
*
|
||||
* @return {Promise<{totalProcessed: number, warehouseResults: Array<Object>}>} 全局执行结果。
|
||||
*/
|
||||
async executeAutoOutbound() {
|
||||
const { ctx } = this;
|
||||
|
||||
if (ctx.app._autoOutboundRunning) {
|
||||
ctx.logger.info('[auto-outbound] 上一轮自动化出库尚未结束,跳过本次执行');
|
||||
return { totalProcessed: 0, warehouseResults: [] };
|
||||
}
|
||||
|
||||
ctx.app._autoOutboundRunning = true;
|
||||
|
||||
try {
|
||||
const warehouses = await this.getEnabledAutoOutboundWarehouses();
|
||||
|
||||
if (!warehouses || warehouses.length === 0) {
|
||||
return { totalProcessed: 0, warehouseResults: [] };
|
||||
}
|
||||
|
||||
let totalProcessed = 0;
|
||||
const warehouseResults = [];
|
||||
|
||||
for (const { warehouseId, rules } of warehouses) {
|
||||
const result = await this.processWarehouseAutoOutbound(warehouseId, rules);
|
||||
warehouseResults.push(result);
|
||||
totalProcessed += result.processedCount;
|
||||
}
|
||||
|
||||
return { totalProcessed, warehouseResults };
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[auto-outbound] 全局自动化出库执行失败: ${error.message}`);
|
||||
return { totalProcessed: 0, warehouseResults: [] };
|
||||
} finally {
|
||||
ctx.app._autoOutboundRunning = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderAutoOutboundService;
|
||||
@ -220,8 +220,8 @@ class OrderExpressService extends Service {
|
||||
* @param {number|string} payload.orderId 订单ID。
|
||||
* @param {string} [payload.waybillCode] 运单号,多运单场景必填。
|
||||
* @param {number|string} payload.weighingWeight 称重重量(kg)。
|
||||
* @return {Promise<Object>} 单订单返回 {order_id, waybill_code, weighing_weight};
|
||||
* 团购批量返回 {wave_id, wave_no, weighing_weight, success_count, total_count}。
|
||||
* @return {Promise<Object>} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight};
|
||||
* 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
|
||||
*/
|
||||
async updateWeighingWeight(payload = {}) {
|
||||
const requestData = payload && typeof payload === 'object' ? payload : {};
|
||||
@ -293,10 +293,341 @@ class OrderExpressService extends Service {
|
||||
|
||||
// 团购波次 → 批量设置同一重量
|
||||
return await this._updateWaveOrderWeight(
|
||||
waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel
|
||||
waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel, normalizedOrderId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过运单号更新称重重量(运单号模式,order_id=0 时使用)。
|
||||
*
|
||||
* 从运单号反查 wms_order_express,再定位订单和波次:
|
||||
* - 散单或非团购波次:仅更新该运单的称重重量。
|
||||
* - 团购波次(wave_type=1):按 wave_no + business_key 批量设置同一重量,
|
||||
* 并返回含拆单汇总信息的结构。
|
||||
*
|
||||
* @param {Object} payload 入参对象。
|
||||
* @param {string} payload.waybillCode 运单号(必填)。
|
||||
* @param {number|string} payload.weighingWeight 称重重量(kg)。
|
||||
* @return {Promise<Object>} 单运单返回 {order_id, waybill_code, weighing_weight, items_weight};
|
||||
* 团购批量返回 {wave_id, wave_no, order_id, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
|
||||
*/
|
||||
async updateWeighingWeightByWaybill(payload = {}) {
|
||||
const requestData = payload && typeof payload === 'object' ? payload : {};
|
||||
const { waybillCode, weighingWeight } = requestData;
|
||||
|
||||
const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode);
|
||||
const normalizedWeight = this.normalizeWeighingWeight(weighingWeight);
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
// 按运单号 + 仓库ID 查 wms_order_express
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') {
|
||||
throw this.createBusinessError('运单模型未初始化', 500);
|
||||
}
|
||||
|
||||
const expressRow = await orderExpressModel.findOne({
|
||||
where: {
|
||||
waybill_code: normalizedWaybillCode,
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!expressRow) {
|
||||
throw this.createBusinessError('运单号不存在', 404);
|
||||
}
|
||||
|
||||
const orderId = Number(expressRow.order_id || 0);
|
||||
|
||||
// 查询订单所属波次
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
throw this.createBusinessError('订单模型未初始化', 500);
|
||||
}
|
||||
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: { id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!orderRow) {
|
||||
throw this.createBusinessError('运单号对应的订单不存在', 404);
|
||||
}
|
||||
|
||||
const waveId = Number(orderRow.wave_id || 0);
|
||||
|
||||
// 散单 → 走单个运单逻辑
|
||||
if (waveId === 0) {
|
||||
return await this._updateSingleOrderWeight(
|
||||
orderId, normalizedWaybillCode, normalizedWeight, warehouseId
|
||||
);
|
||||
}
|
||||
|
||||
// 查询波次类型
|
||||
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
|
||||
if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') {
|
||||
throw this.createBusinessError('波次模型未初始化', 500);
|
||||
}
|
||||
|
||||
const waveRow = await waveBatchModel.findOne({
|
||||
where: { wave_id: waveId, warehouse_id: warehouseId },
|
||||
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 非团购波次 → 降级为单运单逻辑
|
||||
if (!waveRow || Number(waveRow.wave_type) !== 1) {
|
||||
return await this._updateSingleOrderWeight(
|
||||
orderId, normalizedWaybillCode, normalizedWeight, warehouseId
|
||||
);
|
||||
}
|
||||
|
||||
// 团购波次 → 按 wave_id 批量设置波次下全部运单
|
||||
return await this._updateWaveAllOrdersWeight(
|
||||
waveId,
|
||||
String(waveRow.wave_no || ''),
|
||||
normalizedWeight,
|
||||
warehouseId,
|
||||
orderDeliveryModel,
|
||||
orderId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新团购波次下所有订单运单的称重重量(内部方法,运单号模式入口)。
|
||||
*
|
||||
* 查询波次下全部订单,按 order_id 批量更新所有运单的 weighing_weight,
|
||||
* 不区分 business_key。与 _updateWaveOrderWeight 功能等价但调用入口不同。
|
||||
*
|
||||
* @param {number} waveId 波次ID。
|
||||
* @param {string} waveNo 波次号。
|
||||
* @param {number} weight 称重重量。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
|
||||
* @param {number} orderId 触发更新的运单对应订单ID。
|
||||
* @return {Promise<{wave_id:number, wave_no:string, order_id:number, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>}
|
||||
* 团购批量更新结果,含拆单汇总信息及触发订单ID。
|
||||
*/
|
||||
async _updateWaveAllOrdersWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) {
|
||||
// 查询波次下所有订单
|
||||
const waveOrders = await orderDeliveryModel.findAll({
|
||||
where: { wave_id: waveId, warehouse_id: warehouseId },
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!waveOrders || waveOrders.length === 0) {
|
||||
throw this.createBusinessError('波次下未找到订单', 404);
|
||||
}
|
||||
|
||||
const orderIds = waveOrders.map(o => Number(o.id));
|
||||
|
||||
// 批量更新波次下全部运单的称重重量
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel || typeof orderExpressModel.update !== 'function') {
|
||||
throw this.createBusinessError('运单模型未初始化', 500);
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const updateWhere = {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
delete_at: null,
|
||||
};
|
||||
|
||||
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
|
||||
const matchingCount = await orderExpressModel.count({ where: updateWhere });
|
||||
if (matchingCount === 0) {
|
||||
throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500);
|
||||
}
|
||||
|
||||
await orderExpressModel.update(
|
||||
{ weighing_weight: weight },
|
||||
{ where: updateWhere }
|
||||
);
|
||||
|
||||
const successCount = matchingCount;
|
||||
|
||||
// 写入操作日志
|
||||
await this._writeWeighActionLog({
|
||||
waveId,
|
||||
waveNo,
|
||||
weight,
|
||||
warehouseId,
|
||||
successCount,
|
||||
totalCount: orderIds.length,
|
||||
});
|
||||
|
||||
// 构建拆单汇总信息(按触发订单 ID 汇总)
|
||||
const summary = await this._buildWaveWeighingSummary(waveId, orderId, warehouseId, weight);
|
||||
|
||||
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: { id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'items_weight' ],
|
||||
raw: true,
|
||||
});
|
||||
const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0;
|
||||
|
||||
return {
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
order_id: orderId,
|
||||
weighing_weight: weight,
|
||||
total_weight: summary.total_weight,
|
||||
split_count: summary.split_count,
|
||||
splits: summary.splits,
|
||||
store_name: summary.store_name,
|
||||
sys_logistics_name: summary.sys_logistics_name,
|
||||
items_weight: itemsWeight,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建团购波次称重拆单汇总信息(内部方法)。
|
||||
*
|
||||
* 查询指定订单下所有运单记录,按 business_key 分组汇总称重重量,
|
||||
* 并获取货主名称与系统快递名称。
|
||||
*
|
||||
* @param {number} waveId 波次ID。
|
||||
* @param {number} orderId 订单ID。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {number} currentWeight 本次设置的称重重量。
|
||||
* @return {Promise<{total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string}>}
|
||||
* 拆单汇总信息。
|
||||
*/
|
||||
async _buildWaveWeighingSummary(waveId, orderId, warehouseId, currentWeight) {
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
|
||||
return {
|
||||
total_weight: currentWeight,
|
||||
split_count: 0,
|
||||
splits: [],
|
||||
store_name: '',
|
||||
sys_logistics_name: '',
|
||||
};
|
||||
}
|
||||
|
||||
// 查询指定订单下所有有效运单记录
|
||||
const expressRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'business_key', 'weighing_weight', 'waybill_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 按 business_key 分组汇总称重重量
|
||||
const splitMap = new Map();
|
||||
for (const row of expressRows) {
|
||||
const bk = row.business_key === null || row.business_key === undefined
|
||||
? '__null__'
|
||||
: String(row.business_key);
|
||||
if (!splitMap.has(bk)) {
|
||||
splitMap.set(bk, {
|
||||
business_key: row.business_key,
|
||||
weighing_weight: 0,
|
||||
waybill_code: row.waybill_code || null,
|
||||
});
|
||||
}
|
||||
const entry = splitMap.get(bk);
|
||||
entry.weighing_weight = Number(
|
||||
(entry.weighing_weight + Number(row.weighing_weight || 0)).toFixed(3)
|
||||
);
|
||||
// 优先取非空的 waybill_code 作为该拆单的代表运单号
|
||||
if (!entry.waybill_code && row.waybill_code) {
|
||||
entry.waybill_code = row.waybill_code;
|
||||
}
|
||||
}
|
||||
|
||||
const splits = [ ...splitMap.values() ];
|
||||
const totalWeight = Number(
|
||||
splits.reduce((sum, s) => sum + s.weighing_weight, 0).toFixed(3)
|
||||
);
|
||||
// split_count:仅统计 waybill_code 不为空的 business_key
|
||||
const splitCount = splits.filter(s => s.waybill_code !== null).length;
|
||||
|
||||
// 获取货主名称
|
||||
const storeName = await this._getStoreName([ orderId ], warehouseId);
|
||||
|
||||
// 获取系统快递名称
|
||||
const sysLogisticsName = await this._getWaveSysLogisticsName([ orderId ], warehouseId);
|
||||
|
||||
return {
|
||||
total_weight: totalWeight,
|
||||
split_count: splitCount,
|
||||
splits,
|
||||
store_name: storeName,
|
||||
sys_logistics_name: sysLogisticsName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取波次下第一个订单的货主名称(shop_nick)。
|
||||
*
|
||||
* @param {number[]} orderIds 订单ID列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 货主名称(shop_nick),获取失败时返回空字符串。
|
||||
*/
|
||||
async _getStoreName(orderIds, warehouseId) {
|
||||
try {
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
return '';
|
||||
}
|
||||
const { Op } = this.app.Sequelize;
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: {
|
||||
id: { [Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
shop_nick: { [Op.ne]: null },
|
||||
},
|
||||
attributes: [ 'shop_nick' ],
|
||||
raw: true,
|
||||
});
|
||||
return orderRow ? String(orderRow.shop_nick || '').trim() : '';
|
||||
} catch (_err) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取波次下订单的系统快递名称。
|
||||
*
|
||||
* 取波次下第一个有值的 sys_logistics_name。
|
||||
*
|
||||
* @param {number[]} orderIds 订单ID列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string>} 系统快递名称,获取失败时返回空字符串。
|
||||
*/
|
||||
async _getWaveSysLogisticsName(orderIds, warehouseId) {
|
||||
try {
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
return '';
|
||||
}
|
||||
const { Op } = this.app.Sequelize;
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: {
|
||||
id: { [Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
sys_logistics_name: { [Op.ne]: null },
|
||||
},
|
||||
attributes: [ 'sys_logistics_name' ],
|
||||
raw: true,
|
||||
});
|
||||
return orderRow ? String(orderRow.sys_logistics_name || '').trim() : '';
|
||||
} catch (_err) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新单个订单运单的称重重量(内部方法)。
|
||||
*
|
||||
@ -304,7 +635,7 @@ class OrderExpressService extends Service {
|
||||
* @param {string} waybillCode 运单号。
|
||||
* @param {number} weight 称重重量。
|
||||
* @param {number|null} warehouseId 仓库ID。
|
||||
* @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。
|
||||
* @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。
|
||||
*/
|
||||
async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) {
|
||||
const rows = await this.findValidOrderExpressRows(orderId, warehouseId);
|
||||
@ -350,10 +681,30 @@ class OrderExpressService extends Service {
|
||||
warehouseId,
|
||||
});
|
||||
|
||||
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
|
||||
let itemsWeight = 0;
|
||||
if (warehouseId) {
|
||||
try {
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: { id: Number(targetRow.order_id), warehouse_id: warehouseId },
|
||||
attributes: [ 'items_weight' ],
|
||||
raw: true,
|
||||
});
|
||||
itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0;
|
||||
}
|
||||
} catch (_err) {
|
||||
// 查询失败时静默降级为 0
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
order_id: Number(targetRow.order_id),
|
||||
waybill_code: String(targetRow.waybill_code || '').trim(),
|
||||
weighing_weight: weight,
|
||||
items_weight: itemsWeight,
|
||||
};
|
||||
}
|
||||
|
||||
@ -365,10 +716,11 @@ class OrderExpressService extends Service {
|
||||
* @param {number} weight 称重重量。
|
||||
* @param {number|null} warehouseId 仓库ID。
|
||||
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
|
||||
* @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, success_count:number, total_count:number}>}
|
||||
* 批量更新结果。
|
||||
* @param {number} [orderId] 触发更新的订单ID,未传时取波次下第一个订单。
|
||||
* @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>}
|
||||
* 团购批量更新结果,含拆单汇总信息。
|
||||
*/
|
||||
async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel) {
|
||||
async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) {
|
||||
// 查询波次下所有订单
|
||||
const waveOrders = await orderDeliveryModel.findAll({
|
||||
where: { wave_id: waveId, warehouse_id: warehouseId },
|
||||
@ -390,24 +742,24 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const updateResult = await orderExpressModel.update(
|
||||
{ weighing_weight: weight },
|
||||
{
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
delete_at: null,
|
||||
},
|
||||
}
|
||||
);
|
||||
const updateWhere = {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
delete_at: null,
|
||||
};
|
||||
|
||||
const successCount = Array.isArray(updateResult)
|
||||
? Number(updateResult[0] || 0)
|
||||
: Number(updateResult || 0);
|
||||
|
||||
if (!Number.isFinite(successCount) || successCount <= 0) {
|
||||
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
|
||||
const matchingCount = await orderExpressModel.count({ where: updateWhere });
|
||||
if (matchingCount === 0) {
|
||||
throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500);
|
||||
}
|
||||
|
||||
await orderExpressModel.update(
|
||||
{ weighing_weight: weight },
|
||||
{ where: updateWhere }
|
||||
);
|
||||
|
||||
const successCount = matchingCount;
|
||||
|
||||
// 写入操作日志
|
||||
await this._writeWeighActionLog({
|
||||
waveId,
|
||||
@ -418,12 +770,30 @@ class OrderExpressService extends Service {
|
||||
totalCount,
|
||||
});
|
||||
|
||||
// 构建拆单汇总信息(按触发订单 ID 汇总,未传时取波次下第一个订单)
|
||||
const scopeOrderId = (Number.isFinite(Number(orderId)) && Number(orderId) > 0)
|
||||
? Number(orderId)
|
||||
: orderIds[0];
|
||||
const summary = await this._buildWaveWeighingSummary(waveId, scopeOrderId, warehouseId, weight);
|
||||
|
||||
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: { id: scopeOrderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'items_weight' ],
|
||||
raw: true,
|
||||
});
|
||||
const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0;
|
||||
|
||||
return {
|
||||
wave_id: waveId,
|
||||
wave_no: waveNo,
|
||||
weighing_weight: weight,
|
||||
success_count: successCount,
|
||||
total_count: totalCount,
|
||||
total_weight: summary.total_weight,
|
||||
split_count: summary.split_count,
|
||||
splits: summary.splits,
|
||||
store_name: summary.store_name,
|
||||
sys_logistics_name: summary.sys_logistics_name,
|
||||
items_weight: itemsWeight,
|
||||
};
|
||||
}
|
||||
|
||||
@ -535,8 +905,6 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容处理:当前端将 wave_id 当作 order_id 传入时,尝试按波次 ID 处理。
|
||||
*
|
||||
* 先用传入的 ID 在 wms_wave_batch 中查找波次:
|
||||
* - 波次不存在 → 抛出"订单不存在"错误。
|
||||
* - 波次存在且 wave_type = 1(团购)→ 走团购批量称重逻辑。
|
||||
|
||||
@ -113,6 +113,21 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
Object.freeze({ value: 'async', label: '异步回调' }),
|
||||
],
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'auto_outbound_rules',
|
||||
name: '自动出库规则',
|
||||
type: 'object',
|
||||
default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true }),
|
||||
required: false,
|
||||
description: '满足条件自动标记出库。全部条件满足时自动标记待出库',
|
||||
item_keys: Object.freeze([
|
||||
Object.freeze({ key: 'enabled', name: '启用', type: 'flag', required: true, description: '是否启用自动出库' }),
|
||||
Object.freeze({ key: 'require_recheck', name: '需已复核', type: 'flag', required: false, description: '是否要求 recheck_status=fin' }),
|
||||
Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, description: '是否要求 pack_status=fin' }),
|
||||
Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, description: '是否要求 weighing_weight>0' }),
|
||||
Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }),
|
||||
]),
|
||||
}),
|
||||
Object.freeze({
|
||||
key: INTERNAL_WAVE_STRATEGY_VERSION_KEY,
|
||||
name: '仓库波次策略版本号',
|
||||
|
||||
@ -251,11 +251,13 @@ class stockStoreService extends Service {
|
||||
/**
|
||||
* 查询商品对应的库存记录与可用量。
|
||||
*
|
||||
* @param {number|string} itemId 商品 ID。
|
||||
* @param {number|string} itemId 商品 ID(StockStore.id)。
|
||||
* @param {Object|null} transaction 数据库事务。
|
||||
* @param {Object} [opts] 可选配置。
|
||||
* @param {number} [opts.stockId] 当传入有效的 stockId 时,跳过 StockStore 映射层,直接使用该 stockId 查询 StockWarehouse。
|
||||
* @return {Promise<Object>} 库存查询结果。
|
||||
*/
|
||||
async getItemStorages(itemId, transaction) {
|
||||
async getItemStorages(itemId, transaction, opts = {}) {
|
||||
const {
|
||||
ctx,
|
||||
app,
|
||||
@ -263,6 +265,72 @@ class stockStoreService extends Service {
|
||||
const cacheKey = `storages:${itemId}`;
|
||||
|
||||
try {
|
||||
const { stockId } = opts;
|
||||
|
||||
// stockId 快速路径:跳过 StockStore 映射,直接用 stockId 查 StockWarehouse
|
||||
if (Number.isFinite(stockId) && stockId > 0) {
|
||||
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
|
||||
where: {
|
||||
id: stockId,
|
||||
is_valid: 'Y',
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [
|
||||
'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight',
|
||||
],
|
||||
transaction,
|
||||
lock: transaction?.LOCK?.UPDATE,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (stockWarehouse) {
|
||||
const quantity = parseInt(stockWarehouse.quantity) || 0;
|
||||
const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0;
|
||||
const canUse = quantity - lockedQuantity;
|
||||
const grossWeight = parseInt(stockWarehouse.gross_weight) || 0;
|
||||
|
||||
const storage = {
|
||||
id: stockWarehouse.id,
|
||||
storeId: Number(stockWarehouse.store_id) || 0,
|
||||
warehouseId: Number(stockWarehouse.warehouse_id) || 0,
|
||||
quantity,
|
||||
lockedQuantity,
|
||||
canUse,
|
||||
grossWeight,
|
||||
_updatedAt: Date.now(),
|
||||
exists: true,
|
||||
};
|
||||
|
||||
// 异步更新缓存
|
||||
const cached = await app.getCacheAsync(cacheKey);
|
||||
if (!cached) {
|
||||
const ttl = this._calculateCacheTTL(storage);
|
||||
app.setCacheAsync(cacheKey, storage, ttl);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
stock: {
|
||||
id: itemId,
|
||||
stock_id: stockId,
|
||||
store_id: storage.storeId,
|
||||
warehouse_id: storage.warehouseId,
|
||||
},
|
||||
storage,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// stockWarehouse 不存在
|
||||
app.logger.warn(`[库存记录缺失-stockId快速路径] itemId=${itemId}, stockId=${stockId}`);
|
||||
return {
|
||||
success: false,
|
||||
error: '已更改未同步推送到仓库',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
// 1. 获取商品信息
|
||||
const itemInfo = await this.getItemInfoWithCache(itemId);
|
||||
|
||||
@ -688,8 +756,9 @@ class stockStoreService extends Service {
|
||||
* @param {number} itemId 商品ID (StockStore.id)
|
||||
* @param {number} quantity 入库数量(正数)
|
||||
* @param {Object} transaction 数据库事务
|
||||
* @param {Object} [opts] 可选配置,透传给 getItemStorages。
|
||||
*/
|
||||
async inbound(itemId, quantity, transaction) {
|
||||
async inbound(itemId, quantity, transaction, opts = {}) {
|
||||
const {
|
||||
ctx,
|
||||
app,
|
||||
@ -707,7 +776,7 @@ class stockStoreService extends Service {
|
||||
try {
|
||||
return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => {
|
||||
// 2. 获取商品和库存信息(复用)
|
||||
const stockResult = await this.getItemStorages(itemId, currentTransaction);
|
||||
const stockResult = await this.getItemStorages(itemId, currentTransaction, opts);
|
||||
|
||||
if (!stockResult.success) {
|
||||
if (hasExternalTransaction) {
|
||||
@ -921,6 +990,44 @@ class stockStoreService extends Service {
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量查询拣货行对应的库存批次号(wms_storage.batch_no)。
|
||||
*
|
||||
* @param {Array<Object>} pickingRows 拣货分配记录列表
|
||||
* @param {Object|null} transaction 事务对象
|
||||
* @return {Promise<Map<number, string>>} storage_id → batch_no 映射表
|
||||
*/
|
||||
async getPickingBatchMap(pickingRows, transaction) {
|
||||
const { ctx, app } = this;
|
||||
const map = new Map();
|
||||
if (!Array.isArray(pickingRows) || pickingRows.length === 0) {
|
||||
return map;
|
||||
}
|
||||
|
||||
const storageIds = [ ...new Set(pickingRows.map(r => Number(r.storage_id)).filter(id => id > 0)) ];
|
||||
if (storageIds.length === 0) {
|
||||
return map;
|
||||
}
|
||||
|
||||
try {
|
||||
const storageRows = await ctx.model.Storage.findAll({
|
||||
where: { id: { [app.Sequelize.Op.in]: storageIds } },
|
||||
attributes: [ 'id', 'batch_no' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
for (const sr of storageRows) {
|
||||
if (sr && sr.batch_no) {
|
||||
map.set(Number(sr.id), String(sr.batch_no).trim());
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
app.logger.warn(`[getPickingBatchMap] 查询 storage batch_no 失败,降级跳过: ${error.message}`);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成出库流水写入明细,优先按拣货分配逐条记录。
|
||||
*
|
||||
@ -928,9 +1035,10 @@ class stockStoreService extends Service {
|
||||
* @param {number} options.outboundQty 本次出库总数量。
|
||||
* @param {Array<Object>} options.pickingRows 拣货分配记录。
|
||||
* @param {Object} options.basePayload 流水公共字段。
|
||||
* @param {Map<number, string>} options.pickingBatchMap storage_id → batch_no 映射表。
|
||||
* @return {Array<Object>} 待写入的出库流水列表。
|
||||
*/
|
||||
buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload }) {
|
||||
buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload, pickingBatchMap = new Map() }) {
|
||||
const payloads = [];
|
||||
const normalizedRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||||
let consumedQty = 0;
|
||||
@ -947,11 +1055,15 @@ class stockStoreService extends Service {
|
||||
}
|
||||
|
||||
const transactionQty = Math.min(pickingQty, remainingQty);
|
||||
const storageId = pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null;
|
||||
const batchNo = storageId ? (pickingBatchMap.get(storageId) || null) : null;
|
||||
|
||||
payloads.push({
|
||||
...basePayload,
|
||||
storage_id: pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null,
|
||||
storage_id: storageId,
|
||||
space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null,
|
||||
quantity: transactionQty,
|
||||
batch_no: batchNo || basePayload.batch_no || null,
|
||||
});
|
||||
consumedQty += transactionQty;
|
||||
}
|
||||
@ -983,8 +1095,9 @@ class stockStoreService extends Service {
|
||||
* @param {number} quantity 出库数量(正数)
|
||||
* @param {Object} transaction 数据库事务
|
||||
* @param {Object} meta 出库元信息(订单、明细等)
|
||||
* @param {Object} [opts] 可选配置,透传给 getItemStorages。
|
||||
*/
|
||||
async outbound(itemId, quantity, transaction, meta = {}) {
|
||||
async outbound(itemId, quantity, transaction, meta = {}, opts = {}) {
|
||||
const {
|
||||
ctx,
|
||||
app,
|
||||
@ -1004,7 +1117,7 @@ class stockStoreService extends Service {
|
||||
try {
|
||||
return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => {
|
||||
// 2. 获取商品和库存信息(复用)
|
||||
const stockResult = await this.getItemStorages(itemId, currentTransaction);
|
||||
const stockResult = await this.getItemStorages(itemId, currentTransaction, opts);
|
||||
|
||||
if (!stockResult.success) {
|
||||
if (hasExternalTransaction) {
|
||||
@ -1107,6 +1220,9 @@ class stockStoreService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取拣货行对应的库存批次号(wms_storage.batch_no)
|
||||
const pickingBatchMap = await this.getPickingBatchMap(pickingRows, currentTransaction);
|
||||
|
||||
const baseTransactionPayload = {
|
||||
transaction_type: 'OUTBOUND',
|
||||
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
|
||||
@ -1134,6 +1250,7 @@ class stockStoreService extends Service {
|
||||
outboundQty,
|
||||
pickingRows,
|
||||
basePayload: baseTransactionPayload,
|
||||
pickingBatchMap,
|
||||
});
|
||||
|
||||
for (const payload of transactionPayloads) {
|
||||
|
||||
@ -80,25 +80,22 @@ class StockTransactionService extends Service {
|
||||
}
|
||||
|
||||
let sourceOrderCodes = String(data.source_order_codes || '').trim();
|
||||
let waveNo = null;
|
||||
|
||||
// 兜底查询 source_order_codes(仅当调用方未传入时),用 try-catch 防止拖垮事务
|
||||
const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery;
|
||||
if (orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') {
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: {
|
||||
id: orderId,
|
||||
},
|
||||
attributes: [ 'id', 'source_order_codes', 'wave_no' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
if (orderRow) {
|
||||
if (!sourceOrderCodes) {
|
||||
if (!sourceOrderCodes && orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') {
|
||||
try {
|
||||
const orderRow = await orderDeliveryModel.findOne({
|
||||
where: { id: orderId },
|
||||
attributes: [ 'id', 'source_order_codes' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
if (orderRow) {
|
||||
sourceOrderCodes = String(orderRow.source_order_codes || '').trim();
|
||||
}
|
||||
const normalizedWaveNo = String(orderRow.wave_no || '').trim();
|
||||
waveNo = normalizedWaveNo || null;
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[resolveOutboundOrderReference] 查询订单 source_order_codes 失败,降级跳过: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,7 +106,7 @@ class StockTransactionService extends Service {
|
||||
return {
|
||||
orderId,
|
||||
orderNo: sourceOrderCodes,
|
||||
batchNo: waveNo,
|
||||
batchNo: data.batch_no ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -3158,5 +3158,66 @@
|
||||
"成功返回运单记录的 id、order_id、waybill_code、create_at"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.06.09-system-01",
|
||||
"date": "2026-06-09",
|
||||
"summary": "order.pendingOrder.updateAddress 新增 remark 字段:订单留言/备注批量覆盖,不受 post_status 限制",
|
||||
"methods": [
|
||||
"order.pendingOrder.updateAddress"
|
||||
],
|
||||
"notes": [
|
||||
"在 params 中新增 remark 字段(string,可选,最大500字符),支持批量覆盖所选订单的 remark",
|
||||
"remark 更新不受 post_status 限制,可对所有订单生效(地址字段仍仅允许 post_status='none')",
|
||||
"更新 description 明确 remark 与地址字段的独立性",
|
||||
"更新 response 中 updated_count 说明:取地址更新行数与备注更新行数的最大值",
|
||||
"更新 errors 中缺少字段的错误描述,改为「至少需要提供一个地址字段或备注进行修改」",
|
||||
"业务代码已同步实现,本次仅同步文档"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.06.09-system-02",
|
||||
"date": "2026-06-09",
|
||||
"summary": "order.updateExpressWeighingWeight 新增运单号模式文档:order_id=0 时从运单号反查,支持散单与团购批量两种返回结构",
|
||||
"methods": [
|
||||
"order.updateExpressWeighingWeight"
|
||||
],
|
||||
"notes": [
|
||||
"order_id 参数说明补充:设为0时切换为运单号模式,需配合 waybill_code 使用。",
|
||||
"waybill_code 参数说明补充:运单号模式(order_id=0)下必填。",
|
||||
"description 更新:明确订单模式与运单号模式两种路径及团购波次批量行为。",
|
||||
"response 新增运单号散单场景字段(order_id、waybill_code、weighing_weight)与运单号团购批量场景字段(wave_no、business_key、weighing_weight、success_count)。",
|
||||
"errors 新增运单号模式相关错误码:运单号不存在(404)、运单号对应的订单不存在(404)、波次下未找到订单(404)、批量更新失败(500)。",
|
||||
"仅文档同步,不修改业务代码。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.06.09-system-03",
|
||||
"date": "2026-06-09",
|
||||
"summary": "order.updateExpressWeighingWeight 团购返回新增拆单汇总字段,移除 success_count/total_count",
|
||||
"methods": [
|
||||
"order.updateExpressWeighingWeight"
|
||||
],
|
||||
"notes": [
|
||||
"团购批量模式 response 新增 total_weight(所有拆单重量累加)、split_count(waybill_code 非空的 business_key 数量)、splits(按 business_key 分组的拆单明细数组,每项含 business_key/weighing_weight/waybill_code)、store_name(货主名称)和 sys_logistics_name(系统快递名称)。",
|
||||
"移除 response 中的 success_count 与 total_count 字段,改为由 total_weight 和 split_count 提供汇总信息。",
|
||||
"更新 description 以反映团购模式返回拆单汇总结构。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.06.10-system-01",
|
||||
"date": "2026-06-10",
|
||||
"summary": "order.detail 接口文档:expresses 数组新增字段 weighing_weight、sys_logistics_code、sys_logistics_name、business_key、created_at",
|
||||
"methods": [
|
||||
"order.detail"
|
||||
],
|
||||
"notes": [
|
||||
"expresses 数组新增字段:weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)",
|
||||
"字段来源:getOrderExpressesByOrderId 方法中 sys_logistics_code/sys_logistics_name 取自订单表 sys_logistics_code/sys_logistics_name,其余字段取自 OrderExpress 表"
|
||||
],
|
||||
"type": "updated"
|
||||
}
|
||||
]
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.5",
|
||||
"updatedAt": "2026-06-08",
|
||||
"updatedAt": "2026-06-10",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -1620,41 +1620,46 @@
|
||||
{
|
||||
"name": "order",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "订单头对象(raw 行数据)"
|
||||
},
|
||||
{
|
||||
"name": "detail",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "等同于 order"
|
||||
},
|
||||
{
|
||||
"name": "orderItems / items",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "商品明细数组"
|
||||
},
|
||||
{
|
||||
"name": "expresses",
|
||||
"type": "array",
|
||||
"description": "运单信息数组"
|
||||
"required": true,
|
||||
"description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)"
|
||||
},
|
||||
{
|
||||
"name": "waybill_codes",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "去重后的运单号字符串数组"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"description": "订单ID 为空或格式错误"
|
||||
"message": "订单ID 为空或格式错误"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"description": "订单不存在或不属于当前仓库"
|
||||
"message": "订单不存在或不属于当前仓库"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"description": "内部错误"
|
||||
"message": "内部错误"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -1937,7 +1942,7 @@
|
||||
},
|
||||
{
|
||||
"method": "order.updateExpressWeighingWeight",
|
||||
"description": "更新订单运单称重重量。规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入。",
|
||||
"description": "更新订单运单称重重量。支持两种模式:1) 订单模式(order_id>0):规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入;团购波次批量设置同一重量到波次下所有订单运单,并返回拆单汇总信息(total_weight/split_count/splits/store_name/sys_logistics_name)。2) 运单号模式(order_id=0):从运单号反查订单与波次,散单/非团购波次仅更新单个运单重量,团购波次按 wave_no+business_key 批量设置并返回拆单汇总信息。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -1954,14 +1959,14 @@
|
||||
"type": "number|string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "订单ID,必填且必须为正整数。"
|
||||
"description": "订单ID,必填且必须为数字。订单模式下为正整数,设为0时切换为运单号模式(需配合 waybill_code 使用)。"
|
||||
},
|
||||
{
|
||||
"name": "waybill_code",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "运单号;订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。"
|
||||
"description": "运单号。订单模式下:订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。运单号模式(order_id=0)下必填。"
|
||||
},
|
||||
{
|
||||
"name": "weighing_weight",
|
||||
@ -1975,26 +1980,74 @@
|
||||
{
|
||||
"name": "order_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "订单ID(成功时返回于 data 对象中)。"
|
||||
"required": false,
|
||||
"description": "订单ID。订单模式及运单号散单模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "waybill_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "写入重量的运单号(成功时返回于 data 对象中)。"
|
||||
"required": false,
|
||||
"description": "写入重量的运单号。订单模式及运单号散单模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "weighing_weight",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "已写入的称重重量(kg,成功时返回于 data 对象中)。"
|
||||
"description": "已写入的称重重量(kg)。"
|
||||
},
|
||||
{
|
||||
"name": "wave_no",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "波次号。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "business_key",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "业务键。运单号团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "wave_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "波次ID。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "total_weight",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "所有拆单重量累加(kg)。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "split_count",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "waybill_code 非空的 business_key 数量。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "splits",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"description": "按 business_key 分组的拆单明细。每项含 business_key(业务键)、weighing_weight(该拆单累加重量)、waybill_code(代表运单号)。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "store_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "货主名称(订单 shop_nick)。团购批量模式返回。"
|
||||
},
|
||||
{
|
||||
"name": "sys_logistics_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "系统快递名称。团购批量模式返回。"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 400,
|
||||
"message": "order_id 必填且必须为正整数"
|
||||
"message": "order_id 必填且必须为数字(订单模式下为正整数;设为 0 时为运单号模式)"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
@ -2020,13 +2073,37 @@
|
||||
"code": 404,
|
||||
"message": "waybill_code 未匹配到该订单下的运单记录"
|
||||
},
|
||||
{
|
||||
"code": 404,
|
||||
"message": "运单号不存在(运单号模式)"
|
||||
},
|
||||
{
|
||||
"code": 404,
|
||||
"message": "运单号对应的订单不存在(运单号模式)"
|
||||
},
|
||||
{
|
||||
"code": 404,
|
||||
"message": "波次下未找到订单(团购批量模式)"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "订单快递模型未初始化"
|
||||
"message": "运单模型未初始化"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "订单模型未初始化"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "波次模型未初始化"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "更新称重重量失败"
|
||||
},
|
||||
{
|
||||
"code": 500,
|
||||
"message": "批量更新称重重量失败,波次下无有效运单记录(团购批量模式)"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -3853,7 +3930,7 @@
|
||||
},
|
||||
{
|
||||
"method": "order.pendingOrder.updateAddress",
|
||||
"description": "批量修改待处理订单的收件地址信息。仅允许修改 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。",
|
||||
"description": "批量修改待处理订单的收件地址信息和备注。地址字段修改仅允许 post_status='none'(未分配快递)的订单;remark 字段修改不受 post_status 限制可对所有订单生效。至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)或 remark,空值和纯空白会被忽略。更新成功后写入操作日志。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -3934,6 +4011,13 @@
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "详细地址"
|
||||
},
|
||||
{
|
||||
"name": "remark",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "订单留言/备注,最大500字符。非空时批量覆盖所选订单的 remark 字段,不受 post_status 限制。"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -3941,7 +4025,7 @@
|
||||
"name": "updated_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "实际更新的订单行数"
|
||||
"description": "实际更新的订单行数(取地址更新行数与备注更新行数的最大值)。remark 字段的更新计数独立于地址字段。"
|
||||
},
|
||||
{
|
||||
"name": "ids",
|
||||
@ -3957,11 +4041,11 @@
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "至少需要提供一个地址字段进行修改"
|
||||
"message": "至少需要提供一个地址字段或备注进行修改"
|
||||
},
|
||||
{
|
||||
"code": 400,
|
||||
"message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则更新行数为 0,不会报错但实际无更新"
|
||||
"message": "仅允许修改 post_status='none'(未分配快递)的订单(地址字段);若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。remark 字段不受此限制。"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user