Compare commits

..

No commits in common. "6d58d7ff1ff941bd4ecf0936520911c8fa0146aa" and "41ef9b40dedbce141d65f1f490328112cba5e754" have entirely different histories.

27 changed files with 508 additions and 2095 deletions

View File

@ -31,11 +31,6 @@ module.exports = app => {
allowNull: true,
comment: '库存记录ID',
},
stock_id: {
type: BIGINT(20),
allowNull: true,
comment: '商品SKU ID',
},
quantity: {
type: INTEGER(10).UNSIGNED,
allowNull: false,
@ -107,15 +102,11 @@ module.exports = app => {
name: 'idx_wms_picking_order_item_space',
fields: [ 'order_item_id', 'space_id' ],
},
{
name: 'idx_wms_picking_warehouse_stock',
fields: [ 'warehouse_id', 'stock_id' ],
},
],
});
Picking.associate = function() {
const { OrderItems, Storage, LocationSpace, StockWarehouse } = app.model;
const { OrderItems, Storage, LocationSpace } = app.model;
if (OrderItems) {
Picking.belongsTo(OrderItems, {
@ -140,14 +131,6 @@ module.exports = app => {
constraints: false,
});
}
if (StockWarehouse) {
Picking.belongsTo(StockWarehouse, {
foreignKey: 'stock_id',
as: 'stock',
constraints: false,
});
}
};
return Picking;

View File

@ -509,11 +509,6 @@ module.exports = app => {
allowNull: true,
comment: '解除人',
},
initiator_subject_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '发起方主体ID(wms_store.id)',
},
created_at: {
type: DATE,
allowNull: false,
@ -559,17 +554,10 @@ module.exports = app => {
}));
},
},
warehouse_use_status: {
use_status: {
type: INTEGER(1),
allowNull: false,
defaultValue: 1,
comment: '仓库侧使用状态:0-不可用,1-可用',
},
store_use_status: {
type: INTEGER(1),
allowNull: false,
defaultValue: 1,
comment: '货主侧使用状态:0-不可用,1-可用',
comment: '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)',
},
}, {
tableName: 'wms_store_warehouse',
@ -739,11 +727,11 @@ module.exports = app => {
const {
warehouseId,
storeId,
warehouseUseStatus = 1,
useStatus = 1,
} = options;
const where = {
warehouse_use_status: warehouseUseStatus,
use_status: useStatus,
};
if (warehouseId !== undefined && warehouseId !== null) {
@ -763,7 +751,7 @@ module.exports = app => {
warehouseId,
storeId,
required = false,
warehouseUseStatus = 1,
useStatus = 1,
attributes = [ 'store_id', 'store_remask' ],
} = options;
@ -774,7 +762,7 @@ module.exports = app => {
where: this.buildScopedWhere({
warehouseId,
storeId,
warehouseUseStatus,
useStatus,
}),
required,
};

View File

@ -28,17 +28,6 @@ const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:';
const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
const ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_express:request:';
const ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
const ALLOCATE_EXPRESS_PROGRESS_MAP = Object.freeze({
submitted: 5,
running: 50,
success: 100,
failed: 100,
not_found: 0,
unknown: 0,
});
const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:';
const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
@ -528,9 +517,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -1396,88 +1385,6 @@ class PendingOrderService extends OrderBaseService {
}
}
// ========== allocateExpressCode 异步任务进度缓存工具方法 ==========
/**
* 获取快递分配任务缓存键。
*
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getAllocateExpressTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 规范快递分配任务ID。
*
* @param {Object} data 请求体。
* @return {string} 归一化后的任务ID。
*/
normalizeAllocateExpressTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 写入快递分配任务进度。
*
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态与结果。
* @return {Promise<void>} 无返回值。
*/
async setAllocateExpressTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'unknown').trim(),
progress: Number(safePayload.progress || 0),
message: String(safePayload.message || ''),
result: safePayload.result || null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
}
}
/**
* 读取快递分配任务进度。
*
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存结果。
*/
async getAllocateExpressTaskProgress(taskId = '') {
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
return null;
}
}
// ========== syncOrderIds 异步任务进度缓存工具方法 ==========
/**
@ -1591,32 +1498,6 @@ class PendingOrderService extends OrderBaseService {
console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData);
// 前置校验:拣货完成的订单不允许取消分配储位
const rawCancelOrderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
const cancelOrderIds = [ ...new Set(rawCancelOrderIds.map(id => Number(id)).filter(id => Number.isFinite(id) && id > 0)) ];
if (cancelOrderIds.length > 0) {
const model = await this.getOrderModel('order', this.getWarehouseId());
const where = this.buildOrderWhere(cancelOrderIds, this.getWarehouseId());
const orders = await model.findAll({
where,
attributes: [ 'id', 'pick_status' ],
raw: true,
});
const pickedOrderIds = (Array.isArray(orders) ? orders : [])
.filter(o => o.pick_status === 'fin')
.map(o => Number(o.id));
if (pickedOrderIds.length > 0) {
throw new Error(
`以下订单已拣货完成,不允许取消分配储位:${pickedOrderIds.join(', ')}`
);
}
}
try {
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData);
const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData);
@ -1978,10 +1859,15 @@ class PendingOrderService extends OrderBaseService {
/**
* 批量分配待处理订单的快递号,并复用现有运单创建核心链路。
*
* 请求体必须直接传入订单对象数组,订单对象应为来自待处理订单列表或详情的原始订单对象。
* 每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段,
* 前端无需额外拼装或单独构造,直接原样回传订单对象即可。business_key 可为单个序号,也可为序号数组。
* 其余字段会原样透传给运单创建链路。
*
* @param {Object} data 请求体。
* @param {Array<Object>} data.orders 订单对象数组。
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
* @return {Promise<Object>} 统一 success 包装的运单创建结果。
*/
async allocateExpressCode(data) {
const { orders } = data || {};
@ -1989,138 +1875,79 @@ class PendingOrderService extends OrderBaseService {
throw new Error('分配快递号接口仅支持订单对象数组入参');
}
const orderIds = [ ...new Set(
orders
.map(order => Number(order && (order.order_id || order.id)))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
) ];
const { service } = this;
// 生成任务ID,立即返回给前端
const taskId = `exp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.submitted,
message: '分配快递任务已提交',
result: null,
error: '',
};
await this.setAllocateExpressTaskProgress(taskId, taskPayload);
// 后台异步执行
setImmediate(async () => {
try {
const result = await service.systems.express.createWaybillCodePipeline(orders);
return this.success('ok', result);
} catch (error) {
try {
await this.setAllocateExpressTaskProgress(taskId, {
status: 'running',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.running,
message: '快递分配处理中',
});
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
? await orderDeliveryFactory.getCurrentModel()
: null;
const result = await service.systems.express.createWaybillCodePipeline(orders, {
awaitTasks: true,
});
if (orderDeliveryModel && orderIds.length > 0) {
// 查询当前订单的 express_code,只回滚没有运单号的
const currentOrders = await orderDeliveryModel.findAll({
// eslint-disable-next-line array-bracket-spacing
where: { id: { [this.app.Sequelize.Op.in]: orderIds } },
attributes: [ 'id', 'express_code', 'post_status' ],
raw: true,
});
await this.setAllocateExpressTaskProgress(taskId, {
status: 'success',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.success,
message: '快递分配完成',
result,
});
} catch (error) {
const errorMessage = error && error.message ? error.message : String(error);
const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : [])
.filter(o => !String(o.express_code || '').trim())
.map(o => Number(o.id))
.filter(id => id > 0);
// 异常标记和失败日志仍在 asyncTask 内部处理,这里仅记录任务状态
await this.setAllocateExpressTaskProgress(taskId, {
status: 'failed',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.failed,
message: '快递分配失败',
error: errorMessage,
});
// 回滚无运单号订单的 post_status
try {
const orderIds = [ ...new Set(
orders
.map(order => Number(order && (order.order_id || order.id)))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
) ];
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
? await orderDeliveryFactory.getCurrentModel()
: null;
if (orderDeliveryModel && orderIds.length > 0) {
const currentOrders = await orderDeliveryModel.findAll({
if (noWaybillOrderIds.length > 0) {
await orderDeliveryModel.update(
{ post_status: 'none', updated_at: new Date() },
// eslint-disable-next-line array-bracket-spacing
where: { id: { [this.app.Sequelize.Op.in]: orderIds } },
attributes: [ 'id', 'express_code', 'post_status' ],
raw: true,
{ where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } }
);
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', {
orderIds: noWaybillOrderIds,
});
const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : [])
.filter(o => !String(o.express_code || '').trim())
.map(o => Number(o.id))
.filter(id => id > 0);
if (noWaybillOrderIds.length > 0) {
await orderDeliveryModel.update(
{ post_status: 'none', updated_at: new Date() },
// eslint-disable-next-line array-bracket-spacing
{ where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } }
);
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', {
orderIds: noWaybillOrderIds,
});
}
}
} catch (markError) {
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回写订单状态失败,不影响主流程', markError);
}
} catch (markError) {
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError);
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
try {
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') {
const operator = this.getOrderLogOperator() || {};
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
const errorMessage = error && error.message ? String(error.message) : String(error);
/**
* 查询快递分配任务进度。
*
* @param {Object} data 请求体。
* @param {string} data.task_id 任务ID(下划线写法)。
* @param {string} data.taskId 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一 success 包装。
*/
async allocateExpressCodeTaskProgress(data = {}) {
const taskId = this.normalizeAllocateExpressTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
const payloads = orderIds.map(orderId => ({
businessType: 'order',
businessId: String(orderId),
operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED',
operator,
extras: {
message: `分配快递失败:${errorMessage}`,
warehouseId: logWarehouseId,
externalLogType: 'NONE',
},
}));
await operationLogService.createOperationLogs(payloads);
}
} catch (logError) {
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 写入分配快递失败日志失败,不影响主流程', logError);
}
throw error;
}
const cachedTask = await this.getAllocateExpressTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
}
return this.success('ok', {
...cachedTask,
update_time: cachedTask.update_time || Date.now(),
});
}
/**
@ -5713,23 +5540,6 @@ class PendingOrderService extends OrderBaseService {
throw new Error('OrderExpress 模型未加载');
}
// 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入
const existingCompleted = await orderExpressModel.findOne({
where: {
order_id: orderId,
warehouse_id: Number(order.warehouse_id) || warehouseId,
status: 1,
},
attributes: [ 'id', 'waybill_code' ],
raw: true,
});
if (existingCompleted) {
const existingWaybill = String(existingCompleted.waybill_code || '').trim();
throw new Error(
`订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入`
);
}
// 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增
const maxBusinessKey = await orderExpressModel.max('business_key', {
where: {
@ -5769,7 +5579,7 @@ class PendingOrderService extends OrderBaseService {
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: String(orderId),
businessId: logWarehouseId,
operationCode: 'ORDER_MANUAL_WAYBILL',
operator,
extras: {

View File

@ -3684,7 +3684,7 @@ class WaveService extends OrderBaseService {
attributes: [ 'store_id' ],
where: {
warehouse_id: normalizedWarehouseId,
warehouse_use_status: 1,
use_status: 1,
},
raw: true,
});

View File

@ -1845,10 +1845,10 @@ class PrintService extends MainService {
const updateResult = await orderDeliveryModel.update({
print_lock_status: 'warehouse',
print_status: 'fin',
}, {
where: {
id: orderIds,
print_lock_status: 'none',
},
});

View File

@ -71,8 +71,6 @@ class StorageReportMethodService extends MainService {
* @param {string|Date} [data.where.end_time] 结束时间
* @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回
* @param {Array<number|string>} [data.where.store_ids] 货主ID列表
* @param {string} [data.export_mode] 导出模式:'item' 导出含锁定类型的全部变更记录,不传则排除锁定类型
* @param {string} [data.exportMode] 导出模式(驼峰写法,同 export_mode)
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
*/
async export(data = {}) {
@ -97,8 +95,6 @@ class StorageReportMethodService extends MainService {
sortOrder: sortOrderCamel,
} = sort || {};
const exportMode = String(data.export_mode || data.exportMode || '').trim();
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
@ -127,7 +123,7 @@ class StorageReportMethodService extends MainService {
error: '',
});
const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption, exportMode);
const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption);
await this.setExportTaskProgress(taskId, {
task_id: taskId,

View File

@ -26,14 +26,14 @@ class StoreWarehouseStoreService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedRight = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedLog = '*';
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedAuth = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取签约列表(货主侧)。
* 获取签约列表。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
@ -41,7 +41,7 @@ class StoreWarehouseStoreService extends MainService {
async list(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.listForStore !== 'function') {
if (!targetService || typeof targetService.list !== 'function') {
return this.fail('获取签约列表失败', {
code: 500,
});
@ -49,7 +49,7 @@ class StoreWarehouseStoreService extends MainService {
try {
const payload = normalizeStoreWarehousePayload(data);
const result = await targetService.listForStore(payload);
const result = await targetService.list(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '获取签约列表失败', {
@ -84,30 +84,6 @@ class StoreWarehouseStoreService extends MainService {
}
}
/**
* 确认签约:对方主体确认待签约的申请。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
*/
async confirmSign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.confirmSign !== 'function') {
return this.fail('确认签约失败', { code: 500 });
}
try {
const payload = normalizeStoreWarehousePayload(data);
const result = await targetService.confirmSign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '确认签约失败', {
code: Number(error.code) || 500,
});
}
}
/**
* 修改签约名称。
*

View File

@ -19,14 +19,14 @@ class StoreWarehouseWarehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,sign,confirmSign';
const _noNeedRight = 'list';
const _noNeedLog = '*';
const _noNeedAuth = 'list,sign,confirmSign';
const _noNeedAuth = 'list';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 仓库侧获取签约列表(含外部合作仓库)。
* 仓库侧获取签约列表。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
@ -34,13 +34,13 @@ class StoreWarehouseWarehouseService extends MainService {
async list(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.listForWarehouse !== 'function') {
if (!targetService || typeof targetService.list !== 'function') {
return this.fail('获取签约列表失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.listForWarehouse(payload);
const result = await targetService.list(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '获取签约列表失败', {
@ -48,40 +48,6 @@ class StoreWarehouseWarehouseService extends MainService {
});
}
}
/**
* 仓库侧发起签约。
*/
async sign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.sign !== 'function') {
return this.fail('签约失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.sign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '签约失败', { code: Number(error.code) || 500 });
}
}
/**
* 仓库侧确认签约。
*/
async confirmSign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.confirmSign !== 'function') {
return this.fail('确认签约失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.confirmSign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '确认签约失败', { code: Number(error.code) || 500 });
}
}
}
module.exports = StoreWarehouseWarehouseService;

View File

@ -785,7 +785,7 @@ class DeliveryOrderService extends Service {
/**
* 根据货主仓库策略解析订单步骤。
* 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, warehouse_use_status=1),则抛出错误拒绝创建。
* 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, use_status=1),则抛出错误拒绝创建。
*
* @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。
* @param {Object|null} transaction 数据库事务。
@ -806,7 +806,7 @@ class DeliveryOrderService extends Service {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
use_status: 1,
},
attributes: [ 'id' ],
transaction,
@ -814,23 +814,7 @@ class DeliveryOrderService extends Service {
});
if (!relation) {
throw new Error('仓库方已暂停接收推单,无法创建订单,请联系仓库方');
}
const relation2 = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
attributes: [ 'id' ],
transaction,
raw: true,
});
if (!relation2) {
throw new Error('仓库已禁用,无法创建订单,如需继续推单请进入货主后台修改配置');
throw new Error('货主未与当前仓库签约,无法创建订单');
}
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;

View File

@ -2216,7 +2216,7 @@ class ExpressService extends Service {
/**
* 硬删除运单异步失败分组对应的订单快递记录(仅删除 status=0 的未完成记录,保护手工录入等已完成记录)。
* 硬删除运单异步失败分组对应的订单快递记录。
*
* 删除条件必须同时包含订单ID和业务键,若任一订单缺少 business_key,则记录原因并跳过整个分组,避免误删。
*
@ -2279,7 +2279,6 @@ class ExpressService extends Service {
await orderExpressModel.destroy({
where: {
[Op.or]: deleteConditions,
status: 0,
},
});
return true;
@ -2326,17 +2325,13 @@ class ExpressService extends Service {
* business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。
*【已使用】
* @param {Array<Object>} orders 订单与业务键列表。
* @param {Object} [options] 可选配置。
* @param {boolean} [options.awaitTasks=false] 是否等待所有异步任务完成后再返回。
* @param {Function} [options.onBatchComplete] 单批完成回调 ({ processed, total })。
* @return {Promise<Object>} 处理结果,包含 orders、waybill_codes 和 skippedOrders。
*/
async createWaybillCodePipeline(orders = [], options = {}) {
async createWaybillCodePipeline(orders = []) {
const { app } = this;
const { Op } = app.Sequelize;
const orderList = Array.isArray(orders) ? orders : [];
const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`);
const pipelineOptions = options && typeof options === 'object' ? options : {};
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', {
traceId,
@ -2375,58 +2370,8 @@ class ExpressService extends Service {
inputOrderCount: orderList.length,
matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0,
});
// 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
let filteredOrdersArr = orders_arr;
if (orderExpressModel && orders_arr.length > 0) {
const orderIds = orders_arr.map(o => Number(o.id)).filter(id => id > 0);
const completedRows = await orderExpressModel.findAll({
where: {
order_id: { [Op.in]: orderIds },
warehouse_id: warehouseId,
status: 1,
},
attributes: [ 'order_id', 'business_key' ],
raw: true,
});
const skipSet = new Set();
for (const row of completedRows) {
skipSet.add(`${Number(row.order_id)}:${Number(row.business_key)}`);
}
if (skipSet.size > 0) {
const beforeCount = orders_arr.length;
filteredOrdersArr = orders_arr.filter(order => {
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1;
if (businessKey === 1 && skipSet.has(`${Number(order.id)}:1`)) {
return false;
}
return true;
});
if (filteredOrdersArr.length < beforeCount) {
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过已分配运单号(business_key=1)的订单', {
traceId,
skippedCount: beforeCount - filteredOrdersArr.length,
skippedOrderIds: orders_arr
.filter(order => {
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
const businessKey = matchedExpress ? Number(matchedExpress.business_key) : 1;
return businessKey === 1 && skipSet.has(`${Number(order.id)}:1`);
})
.map(o => o.id),
});
}
}
}
if (filteredOrdersArr.length === 0) {
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId });
return { message: '所有订单均已分配运单号,无需处理' };
}
// orders_arr和orderList合并
const ordersWithExpress = filteredOrdersArr.map(order => {
const ordersWithExpress = orders_arr.map(order => {
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
return {
...order,
@ -2488,19 +2433,11 @@ class ExpressService extends Service {
for (const batch of batches) {
// 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。
if (pipelineOptions.awaitTasks) {
await this.asyncTask(batch, {
...groupedOrder.options,
trace_id: traceId,
warehouse_id: warehouseId,
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
} else {
this.asyncTask(batch, {
...groupedOrder.options,
trace_id: traceId,
warehouse_id: warehouseId,
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
}
this.asyncTask(batch, {
...groupedOrder.options,
trace_id: traceId,
warehouse_id: warehouseId,
}, matchedPlatformWithRequestCode, expressInterfaceConfig);
}
}
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', {
@ -2569,55 +2506,17 @@ class ExpressService extends Service {
order_id: order && (order.id || order.order_id),
business_key: order.business_key,
}));
const allOrderIds = err_orders
const failedOrderIds = err_orders
.map(order => Number(order && order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0);
// 查询已成功分配(status=1)的订单,从失败列表中排除,避免误标异常
const successOrderIdSet = new Set();
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (orderExpressModel && allOrderIds.length > 0) {
try {
const successRows = await orderExpressModel.findAll({
where: {
order_id: { [this.app.Sequelize.Op.in]: allOrderIds },
status: 1,
},
attributes: [ 'order_id' ],
raw: true,
});
for (const row of Array.isArray(successRows) ? successRows : []) {
const successOrderId = Number(row && row.order_id);
if (Number.isFinite(successOrderId) && successOrderId > 0) {
successOrderIdSet.add(successOrderId);
}
}
if (successOrderIdSet.size > 0) {
this.ctx.logger.info('[ExpressService.asyncTask] 排除已成功分配的订单,不标记异常', {
traceId,
successOrderIds: Array.from(successOrderIdSet),
});
}
} catch (statusCheckError) {
this.ctx.logger.error('[ExpressService.asyncTask] 查询已成功订单状态失败,降级为全量标记', {
traceId,
error: statusCheckError && statusCheckError.message ? statusCheckError.message : `${statusCheckError}`,
});
}
}
const failedOrderIds = allOrderIds.filter(orderId => !successOrderIdSet.has(orderId));
const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id);
const errorMessage = error && error.message ? String(error.message) : String(error);
if (failedOrderIds.length > 0) {
this.service.systems.orderPendingException.markPendingException(
{
ids: failedOrderIds,
exception_text: `订单快递分配失败: ${errorMessage}`,
}
);
}
this.service.systems.orderPendingException.markPendingException(
{
ids: err_orders.map(order => order.order_id),
exception_text: `订单快递分配失败: ${errorMessage}`,
}
);
await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId);
await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, {
platform_code: options.sys_platform_code,

View File

@ -179,9 +179,8 @@ class OrderPrintSystemService extends OrderBaseService {
* 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码,
* 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。
*
* stock_id 优先读取 wms_picking.stock_id(20260708 新增列),
* 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id,
* 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。
* stock_id 优先读取 wms_order_items.stock_id 列,兜底读取 item_snapshot 内的 stock_id,
* 确保不同来源的订单明细都能正确关联到条码数据。
*
* @param {Array<Object>} orderRows 订单列表。
* @param {number} warehouseId 仓库ID。
@ -213,7 +212,7 @@ class OrderPrintSystemService extends OrderBaseService {
[Op.ne]: 'cancel',
},
},
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status', 'stock_id' ],
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status' ],
order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
@ -286,49 +285,9 @@ class OrderPrintSystemService extends OrderBaseService {
pickingRowsByOrderId.set(orderId, list);
}
// 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id)
const allStockIds = new Set();
// 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表)
for (const row of normalizedPickingRows) {
const stockId = Number(row && row.stock_id || 0);
if (stockId > 0) {
allStockIds.add(stockId);
}
}
// 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据)
for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) {
const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot);
const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0);
if (stockId > 0) {
allStockIds.add(stockId);
}
}
const uniqueStockIds = Array.from(allStockIds);
// 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径)
const stockWarehouseMap = new Map();
if (uniqueStockIds.length > 0) {
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
if (stockWarehouseModel && typeof stockWarehouseModel.findAll === 'function') {
const stockRows = await stockWarehouseModel.findAll({
where: {
id: { [Op.in]: uniqueStockIds },
is_valid: 'Y',
},
attributes: [ 'id', 'item_code', 'item_name' ],
raw: true,
});
for (const row of Array.isArray(stockRows) ? stockRows : []) {
stockWarehouseMap.set(Number(row.id), row);
}
}
}
// 阶段三:构建所有打印项(使用 stock_warehouse 直读数据)
// 阶段一:构建所有打印项并收集 stock_id
const printItemsByOrderId = new Map();
const allStockIds = new Set();
for (const orderRow of rows) {
const orderId = Number(orderRow && orderRow.id || 0);
@ -348,36 +307,27 @@ class OrderPrintSystemService extends OrderBaseService {
custom_name: locationRow.custom_name,
custom_barcode: locationRow.custom_barcode,
}, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]);
// stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id
const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0);
const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0);
const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId;
// 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items)
const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null;
// item_name 优先级:stock_warehouse > order_items > item_snapshot
const itemName = this.getFirstNonEmptyFieldText({
stock_item_name: stockInfo && stockInfo.item_name,
snapshot_item_name: itemSnapshot.item_name,
snapshot_name: itemSnapshot.name,
snapshot_title: itemSnapshot.title,
item_name: orderItemRow.item_name,
}, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
// barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code
}, [ 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
const barcode = this.getFirstNonEmptyFieldText({
stock_item_code: stockInfo && stockInfo.item_code,
barcode: itemSnapshot.barcode,
item_barcode: itemSnapshot.item_barcode,
bar_code: itemSnapshot.bar_code,
item_code: orderItemRow.item_code,
sku_code: itemSnapshot.sku_code,
sku: itemSnapshot.sku,
}, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
}, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0);
// 优先使用列 stock_id,兜底使用 item_snapshot 内的 stock_id
const stockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0);
if (stockId > 0) {
allStockIds.add(stockId);
}
return {
order_item_id: orderItemId,
@ -400,8 +350,9 @@ class OrderPrintSystemService extends OrderBaseService {
printItemsByOrderId.set(orderId, printItems);
}
// 阶段四:批量查询 wms_stock_barcodes 获取所有条码
// 阶段二:批量查询 wms_stock_barcodes 获取所有条码
const barcodeMap = new Map();
const uniqueStockIds = Array.from(allStockIds);
if (uniqueStockIds.length > 0) {
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
@ -434,7 +385,7 @@ class OrderPrintSystemService extends OrderBaseService {
}
}
// 阶段五:注入条码并构建结果映射
// 阶段三:注入条码并构建结果映射
for (const orderRow of rows) {
const orderId = Number(orderRow && orderRow.id || 0);
const printItems = printItemsByOrderId.get(orderId);

View File

@ -714,7 +714,7 @@ class PickSystemService extends Service {
store_id: currentStoreId,
warehouse_id: normalizedWarehouseId,
},
attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'warehouse_use_status', 'store_use_status' ],
attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'use_status' ],
raw: true,
});

View File

@ -326,15 +326,9 @@ class SettingStoreWarehouseService extends Service {
where.auth_status = authStatus;
}
const rawUseStatus = data.use_status !== undefined ? data.use_status
: (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status);
const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null);
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
if (useStatus !== null) {
if (currentSubject.isWarehouse) {
where.warehouse_use_status = useStatus;
} else {
where.store_use_status = useStatus;
}
where.use_status = useStatus;
}
return where;
@ -390,7 +384,7 @@ class SettingStoreWarehouseService extends Service {
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : '';
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
let isAuthValid = false;
let remainingDays = 0;
@ -427,11 +421,7 @@ class SettingStoreWarehouseService extends Service {
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
ended_by: item.ended_by ? Number(item.ended_by) : null,
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
use_status: currentIsWarehouse
? Number(item.warehouse_use_status || 0)
: Number(item.store_use_status || 0),
warehouse_use_status: Number(item.warehouse_use_status || 0),
store_use_status: Number(item.store_use_status || 0),
use_status: Number(item.use_status || 0),
is_auth_valid: isAuthValid,
remaining_days: remainingDays,
};
@ -496,21 +486,7 @@ class SettingStoreWarehouseService extends Service {
return {
code: 200,
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
return {
id: serialized.id,
store_id: serialized.store_id,
warehouse_id: serialized.warehouse_id,
counterparty_name: serialized.counterparty_name,
remask: serialized.remask,
use_status: serialized.use_status,
auth_status: serialized.auth_status,
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
};
}),
list: rows.map(item => this.serializeRelation(item, currentSubject)),
total: Number(count || 0),
page,
page_size: pageSize,
@ -525,90 +501,148 @@ class SettingStoreWarehouseService extends Service {
async sign(data = {}) {
const action = this.normalizeSignAction(data.action || data.mode);
if (action === 'preview') {
const currentSubject = await this.getCurrentSubject();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
return {
code: 200,
data: {
mode: 'preview',
current_subject: { store_id: currentSubject.id, company_name: currentSubject.company_name, role: currentSubject.isWarehouse ? 'warehouse' : 'store' },
counterparty: { id: Number(counterparty.id || 0), company_name: counterparty.company_name || '', role: currentSubject.isWarehouse ? 'store' : 'warehouse' },
},
};
if (data.temp_code || data.tempCode || action === 'preview') {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
.includes(Number(currentSubject.id));
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
throw this.createError('需由对方主体确认后才可生效', 400);
}
const relationPatch = {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_status: 2,
apply_reason: payload.apply_reason || '',
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
print_quantity: Number(payload.print_quantity || 0),
review_time: new Date(),
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
actual_end: null,
applied_by: Number(payload.initiated_by || 0) || accountId,
reviewed_by: accountId,
ended_by: null,
use_status: 1,
};
if (payload.store_remask !== undefined) {
relationPatch.store_remask = payload.store_remask;
}
if (payload.warehouse_remask !== undefined) {
relationPatch.warehouse_remask = payload.warehouse_remask;
}
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: relationPatch.store_id,
warehouse_id: relationPatch.warehouse_id,
},
transaction,
});
const isCreate = !relation;
if (relation) {
await relation.update(relationPatch, { transaction });
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) throw this.createError('auth_end 不能早于 auth_start', 400);
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
const relationPatch = {
store_id: pair.storeId, warehouse_id: pair.warehouseId, auth_status: 1,
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
apply_time: new Date(), print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
review_time: null, auth_start: authStart, auth_end: authEnd, actual_end: null,
applied_by: accountId, reviewed_by: null, ended_by: null, initiator_subject_id: currentSubject.id,
warehouse_use_status: 1, store_use_status: 1, print_quantity_locked: 0,
};
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
const remask = this.resolveRemaskValue(data, currentSubject);
const payload = {
initiated_by: accountId,
initiator_subject_id: currentSubject.id,
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
initiator_name: currentSubject.company_name,
counterparty_id: Number(counterparty.id || 0),
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
counterparty_name: counterparty.company_name || '',
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_start: authStart.toISOString(),
auth_end: authEnd ? authEnd.toISOString() : null,
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
remask: remask || '',
created_at: new Date().toISOString(),
...this.buildCurrentRemaskPatch(data, currentSubject),
};
let relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: pair.storeId, warehouse_id: pair.warehouseId }, transaction });
const isCreate = !relation;
const signPayload = await this.saveTempSignPayload(payload);
if (relation) {
if (relation.applied_by === accountId && relation.auth_status === 1) {
await relation.update(relationPatch, { transaction });
} else if (relation.applied_by === accountId && relation.auth_status >= 2) {
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
await transaction.rollback();
return { code: 200, data: { mode: 'already_confirmed', exists_status: relation.auth_status, exists_status_label: '已签约', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } };
} else {
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
await transaction.rollback();
return { code: 200, data: { mode: 'already_exists', exists_status: relation.auth_status, exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } };
}
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
await transaction.commit();
return { code: 200, data: { mode: 'initiate', contract: this.trimContract(this.serializeRelation(result, currentSubject)), action: isCreate ? 'create' : 'update' } };
} catch (error) { await transaction.rollback(); throw error; }
}
trimContract(serialized) {
return { id: serialized.id, store_id: serialized.store_id, warehouse_id: serialized.warehouse_id, counterparty_name: serialized.counterparty_name, remask: serialized.remask, use_status: serialized.use_status, auth_status: serialized.auth_status, auth_status_label: serialized.auth_status_label, auth_end: serialized.auth_end, print_quantity: serialized.print_quantity, has_qimen_config: serialized.has_qimen_config };
}
async confirmSign(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const relationId = this.toPositiveNumber(data.id, 'id');
if (!relationId) throw this.createError('id 参数不能为空', 400);
const relation = await ctx.model.StoreWarehouse.findOne({ where: { id: relationId }, include: this.getRelationIncludes(), transaction });
if (!relation) throw this.createError('签约关系不存在', 404);
if (relation.auth_status !== 1) throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400);
const isCurrentStore = relation.store_id === currentSubject.id;
const isCurrentWarehouse = relation.warehouse_id === currentSubject.id;
if (!isCurrentStore && !isCurrentWarehouse) throw this.createError('当前主体不在此签约关系中', 403);
if (relation.initiator_subject_id === currentSubject.id) throw this.createError('发起方不能确认自己的签约申请', 403);
await relation.update({ auth_status: 2, review_time: new Date(), reviewed_by: accountId }, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
await transaction.commit();
return { code: 200, data: { mode: 'confirm', contract: this.trimContract(this.serializeRelation(result, currentSubject)) } };
} catch (error) { await transaction.rollback(); throw error; }
return {
code: 200,
data: {
mode: 'initiate',
temp_code: signPayload.tempCode,
expires_at: signPayload.expiresAt,
expires_in: signPayload.expiresIn,
can_confirm: false,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
},
},
};
}
async rename(data = {}) {
@ -648,14 +682,11 @@ class SettingStoreWarehouseService extends Service {
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const nextUseStatus = this.normalizeStatusFlag(
data.use_status !== undefined ? data.use_status : data.warehouse_use_status,
'warehouse_use_status', 0);
const patch = currentSubject.isWarehouse
? { warehouse_use_status: nextUseStatus }
: { store_use_status: nextUseStatus };
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
await relation.update(patch, { transaction });
await relation.update({
use_status: nextUseStatus,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),

View File

@ -566,9 +566,9 @@ class stockStoreService extends Service {
store_id: normalizedStoreId,
warehouse_id: normalizedWarehouseId,
auth_status: 2,
warehouse_use_status: 1,
use_status: 1,
},
attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ],
attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ],
raw: true,
});
@ -630,9 +630,9 @@ class stockStoreService extends Service {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
use_status: 1,
},
attributes: [ 'id', 'policy_config', 'auth_status', 'warehouse_use_status', 'store_use_status' ],
attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ],
transaction,
raw: true,
});

View File

@ -1437,7 +1437,7 @@ class InventoryService extends Service {
// ────────── 3. 检查货主配置:是否允许收货单快捷入库 ──────────
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 },
where: { store_id: storeId, warehouse_id: warehouseId, use_status: 1 },
attributes: [ 'id', 'policy_config' ],
});

View File

@ -166,7 +166,7 @@ class ReceivingService extends Service {
as: 'store',
attributes: [ 'store_remask' ],
where: {
warehouse_use_status: 1,
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
@ -1621,7 +1621,7 @@ class ReceivingService extends Service {
where: {
store_id,
warehouse_id,
warehouse_use_status: 1,
use_status: 1,
},
});
if (store) {
@ -1791,7 +1791,7 @@ class ReceivingService extends Service {
where: {
warehouse_id: warehouseId,
store_id: normalizedStoreId,
warehouse_use_status: 1,
use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
@ -1993,7 +1993,7 @@ class ReceivingService extends Service {
where: {
warehouse_id: warehouseId,
store_id: storeId,
warehouse_use_status: 1,
use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
@ -2093,7 +2093,7 @@ class ReceivingService extends Service {
as: 'store',
attributes: [ 'store_remask' ],
where: {
warehouse_use_status: 1,
use_status: 1,
warehouse_id: warehouseId,
},
required: false,

View File

@ -514,10 +514,9 @@ class StorageReportService extends Service {
* @param {Object} [sort] 排序参数
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sortOrder] 排序顺序
* @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录
* @return {Promise<Object>} excel 上传结果
*/
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '') {
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null) {
const { ctx, app } = this;
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort);
if (!searchResult || searchResult.code !== 200) {
@ -553,12 +552,6 @@ class StorageReportService extends Service {
replacements.storeIds = normalizedStoreIds;
}
const normalizedExportMode = String(exportMode || '').trim();
if (normalizedExportMode !== 'item') {
whereClauses.push('t.transaction_type != :excludeLockType');
replacements.excludeLockType = 'LOCK';
}
const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction';
const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id';
const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type';

View File

@ -950,7 +950,7 @@ class StoreService extends Service {
try {
const stores = await ctx.model.StoreWarehouse.findAll({
where: {
warehouse_use_status: 1,
use_status: 1,
warehouse_id: ctx.user.store_id,
},
attributes: [

View File

@ -854,14 +854,14 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 获取签约对方主体信息(不校验项目角色,仓库可签仓库、货主可签货主)。
* 获取签约对方主体信息。
*
* @param {number} counterpartyId 对方主体 ID。
* @param {string} [_expectedRole] 期望角色(已废弃,保留参数兼容)。
* @param {string} expectedRole 期望角色。
* @return {Promise<Object>} 对方主体对象。
* @throws {Error} 对方主体不存在时抛出,状态码为 404。
* @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。
*/
async getCounterparty(counterpartyId, _expectedRole) {
async getCounterparty(counterpartyId, expectedRole) {
const { ctx } = this;
const counterparty = await ctx.model.Store.findOne({
where: {
@ -874,55 +874,24 @@ class SettingStoreWarehouseService extends Service {
throw this.createError('签约对象不存在', 404);
}
const isWarehouse = counterparty.project === 'warehouse';
if (expectedRole === 'warehouse' && !isWarehouse) {
throw this.createError('目标对象不是仓库主体,无法签约', 400);
}
if (expectedRole === 'store' && isWarehouse) {
throw this.createError('目标对象不是货主主体,无法签约', 400);
}
return counterparty;
}
/**
* 构建列表查询条件(按 store_id 维度)。
*
* 当前主体始终作为 store_id 方(货主方/消费方),对方为 warehouse_id 方(仓库方/提供方)。
* 构建列表查询条件。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} where 查询条件。
*/
buildListWhereByStoreId(data, currentSubject) {
const where = {
store_id: currentSubject.id,
};
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
}
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
if (counterpartyId) {
where.warehouse_id = counterpartyId;
}
const authStatus = this.normalizeAuthStatus(data.auth_status);
if (authStatus !== null) {
where.auth_status = authStatus;
}
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null);
if (useStatus !== null) {
where.store_use_status = useStatus;
}
return where;
}
/**
* 构建列表查询条件(兼容旧逻辑,保留以供其他方法使用)。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} where 查询条件。
* @deprecated 新代码请使用 buildListWhereByStoreId。
*/
buildListWhere(data, currentSubject) {
const where = {};
@ -954,15 +923,9 @@ class SettingStoreWarehouseService extends Service {
where.auth_status = authStatus;
}
const rawUseStatus = data.use_status !== undefined ? data.use_status
: (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status);
const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null);
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
if (useStatus !== null) {
if (currentSubject.isWarehouse) {
where.warehouse_use_status = useStatus;
} else {
where.store_use_status = useStatus;
}
where.use_status = useStatus;
}
return where;
@ -1285,19 +1248,25 @@ class SettingStoreWarehouseService extends Service {
/**
* 解析成对的合同主体 ID。
*
* 规则:当前主体(签约发起方)始终为 store_id 方(货主方/消费方),
* 对方始终为 warehouse_id 方(仓库方/提供方)。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。
* @throws {Error} 对方主体参数非法时抛出,状态码为 400。
*/
resolvePairIds(data, currentSubject) {
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (data.store_id && Number(data.store_id) !== currentSubject.id ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id / 对方主体ID');
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
if (currentSubject.isWarehouse) {
return {
storeId: counterpartyId,
warehouseId: currentSubject.id,
counterpartyId,
};
}
return {
storeId: currentSubject.id,
@ -1324,14 +1293,10 @@ class SettingStoreWarehouseService extends Service {
const authStatus = Number(item.auth_status || 0);
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
// 当前主体始终在 store_id 方(货主方/消费方),对方始终在 warehouse_id 方(仓库方/提供方)
const counterparty = item.warehouse;
const counterpartyRole = counterparty && counterparty.project === 'warehouse' ? 'warehouse' : 'store';
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
const counterpartyName = counterparty && counterparty.company_name ? counterparty.company_name : '';
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
let isAuthValid = false;
let remainingDays = 0;
@ -1353,7 +1318,6 @@ class SettingStoreWarehouseService extends Service {
warehouse_name: warehouseName,
counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0,
counterparty_name: counterpartyName,
counterparty_role: counterpartyRole,
current_subject_role: currentIsWarehouse ? 'warehouse' : 'store',
auth_status: authStatus,
auth_status_label: AUTH_STATUS_LABELS[authStatus] || '',
@ -1370,11 +1334,8 @@ class SettingStoreWarehouseService extends Service {
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
ended_by: item.ended_by ? Number(item.ended_by) : null,
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
use_status: currentIsWarehouse
? Number(item.warehouse_use_status || 0)
: Number(item.store_use_status || 0),
warehouse_use_status: Number(item.warehouse_use_status || 0),
store_use_status: Number(item.store_use_status || 0),
use_status: Number(item.use_status || 0),
policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null,
is_auth_valid: isAuthValid,
remaining_days: remainingDays,
api_config: normalizedQimenConfig || null,
@ -1383,11 +1344,7 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 获取受限范围内的签约关系(兼容新旧签约数据)。
*
* 新数据:当前主体在 store_id(发起方/消费方)。
* 旧数据:仓库主体可能在 warehouse_id(提供方)。
* 使用 OR 查询两边,确保新旧数据都能被操作。
* 获取受限范围内的签约关系。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
@ -1397,27 +1354,21 @@ class SettingStoreWarehouseService extends Service {
*/
async findScopedRelation(data, currentSubject, transaction) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const scopedWhere = {};
const where = currentSubject.isWarehouse
? { warehouse_id: currentSubject.id }
: { store_id: currentSubject.id };
const relationId = this.resolveRelationId(data);
if (relationId) {
scopedWhere.id = relationId;
where.id = relationId;
} else {
const pair = this.resolvePairIds(data, currentSubject);
scopedWhere.store_id = pair.storeId;
scopedWhere.warehouse_id = pair.warehouseId;
where.store_id = pair.storeId;
where.warehouse_id = pair.warehouseId;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where: {
...scopedWhere,
[Op.or]: [
{ store_id: currentSubject.id },
{ warehouse_id: currentSubject.id },
],
},
where,
include: this.getRelationIncludes(),
transaction,
});
@ -1430,169 +1381,11 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 货主侧查询签约关系列表。
*
* 当前货主主体在 store_id 方,对方仓库在 warehouse_id 方。
* 查询签约关系列表。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async listForStore(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentSubject = await this.getCurrentSubject();
const page = this.normalizePage(data.page, 'page', 1, 1000000);
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const where = this.buildListWhereByStoreId(data, currentSubject);
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
if (keyword) {
where[Op.or] = [
{ store_remask: { [Op.like]: `%${keyword}%` } },
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
where,
include: this.getRelationIncludes(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0);
const qimenConfigMap = contractIds.length
? await this.getQimenConfigMap(contractIds)
: new Map();
return {
code: 200,
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
return {
id: serialized.id,
store_id: serialized.store_id,
warehouse_id: serialized.warehouse_id,
counterparty_id: serialized.counterparty_id,
counterparty_name: serialized.counterparty_name,
counterparty_role: serialized.counterparty_role,
remask: serialized.remask,
use_status: serialized.use_status,
auth_status: serialized.auth_status,
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
has_qimen_config: serialized.has_qimen_config,
needs_my_confirm: Number(item.auth_status || 0) === 1
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
};
}),
total: Number(count || 0),
page,
page_size: pageSize,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
},
};
}
/**
* 仓库侧查询签约关系列表。
*
* 当前仓库主体在 store_id 方(消费方),对方(可能是仓库或货主)在 warehouse_id 方(提供方)。
* 支持查询仓库与外部合作仓库的关系。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async listForWarehouse(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentSubject = await this.getCurrentSubject();
const page = this.normalizePage(data.page, 'page', 1, 1000000);
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const where = this.buildListWhereByStoreId(data, currentSubject);
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
if (keyword) {
where[Op.or] = [
{ store_remask: { [Op.like]: `%${keyword}%` } },
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
where,
include: this.getRelationIncludes(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0);
const qimenConfigMap = contractIds.length
? await this.getQimenConfigMap(contractIds)
: new Map();
return {
code: 200,
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
return {
id: serialized.id,
store_id: serialized.store_id,
store_name: serialized.store_name,
warehouse_id: serialized.warehouse_id,
warehouse_name: serialized.warehouse_name,
counterparty_id: serialized.counterparty_id,
counterparty_name: serialized.counterparty_name,
counterparty_role: serialized.counterparty_role,
remask: serialized.remask,
use_status: serialized.store_use_status,
auth_status: serialized.auth_status,
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
has_qimen_config: serialized.has_qimen_config,
needs_my_confirm: Number(item.auth_status || 0) === 1
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
};
}),
total: Number(count || 0),
page,
page_size: pageSize,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
},
};
}
/**
* 查询签约关系列表(旧版,保留向后兼容)。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
* @deprecated 新代码请使用 listForStore 或 listForWarehouse。
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
@ -1631,22 +1424,10 @@ class SettingStoreWarehouseService extends Service {
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
delete serialized.api_config;
delete serialized.apiConfig;
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
return {
id: serialized.id,
store_id: serialized.store_id,
warehouse_id: serialized.warehouse_id,
counterparty_name: serialized.counterparty_name,
remask: serialized.remask,
use_status: serialized.use_status,
auth_status: serialized.auth_status,
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
has_qimen_config: serialized.has_qimen_config,
needs_my_confirm: Number(item.auth_status || 0) === 1
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
};
return serialized;
}),
total: Number(count || 0),
page,
@ -1668,219 +1449,171 @@ class SettingStoreWarehouseService extends Service {
*/
async sign(data = {}) {
const action = this.normalizeSignAction(data.action || data.mode);
if (action === 'preview') {
const currentSubject = await this.getCurrentSubject();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
return {
code: 200,
data: {
mode: 'preview',
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: counterparty.project === 'warehouse' ? 'warehouse' : 'store',
},
},
};
}
if (data.temp_code || data.tempCode || action === 'preview') {
const { ctx } = this;
const transaction = await ctx.model.transaction();
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
.includes(Number(currentSubject.id));
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
const relationPatch = {
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_status: 1,
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
apply_time: new Date(),
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
review_time: null,
auth_start: authStart,
auth_end: authEnd,
actual_end: null,
applied_by: accountId,
reviewed_by: null,
ended_by: null,
initiator_subject_id: currentSubject.id,
warehouse_use_status: 1,
store_use_status: 1,
print_quantity_locked: 0,
};
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
},
transaction,
});
const isCreate = !relation;
if (relation) {
if (relation.applied_by === accountId && relation.auth_status === 1) {
await relation.update(relationPatch, { transaction });
} else if (relation.applied_by === accountId && relation.auth_status >= 2) {
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: {
mode: 'already_confirmed',
exists_status: relation.auth_status,
exists_status_label: '已签约',
contract: this.trimContract(this.serializeRelation(existing, currentSubject)),
},
};
} else {
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
await transaction.rollback();
return {
code: 200,
data: {
mode: 'already_exists',
exists_status: relation.auth_status,
exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认',
contract: this.trimContract(this.serializeRelation(existing, currentSubject)),
},
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
throw this.createError('需由对方主体确认后才可生效', 400);
}
const relationPatch = {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_status: 2,
apply_reason: payload.apply_reason || '',
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
print_quantity: Number(payload.print_quantity || 0),
review_time: new Date(),
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
actual_end: null,
applied_by: Number(payload.initiated_by || 0) || accountId,
reviewed_by: accountId,
ended_by: null,
use_status: 1,
};
if (payload.store_remask !== undefined) {
relationPatch.store_remask = payload.store_remask;
}
if (payload.warehouse_remask !== undefined) {
relationPatch.warehouse_remask = payload.warehouse_remask;
}
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: relationPatch.store_id,
warehouse_id: relationPatch.warehouse_id,
},
transaction,
});
const isCreate = !relation;
if (relation) {
await relation.update(relationPatch, { transaction });
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SIGN',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(payload.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const wasExisting = !!relation._previousDataValues;
await transaction.commit();
return {
code: 200,
data: {
mode: 'initiate',
contract: this.trimContract(this.serializeRelation(result, currentSubject)),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 精简签约对象,仅保留前端需要的字段。
*/
trimContract(serialized) {
return {
id: serialized.id,
store_id: serialized.store_id,
warehouse_id: serialized.warehouse_id,
counterparty_name: serialized.counterparty_name,
remask: serialized.remask,
use_status: serialized.use_status,
auth_status: serialized.auth_status,
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
has_qimen_config: serialized.has_qimen_config,
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
const remask = this.resolveRemaskValue(data, currentSubject);
const payload = {
initiated_by: accountId,
initiator_subject_id: currentSubject.id,
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
initiator_name: currentSubject.company_name,
counterparty_id: Number(counterparty.id || 0),
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
counterparty_name: counterparty.company_name || '',
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_start: authStart.toISOString(),
auth_end: authEnd ? authEnd.toISOString() : null,
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
remask: remask || '',
created_at: new Date().toISOString(),
...this.buildCurrentRemaskPatch(data, currentSubject),
};
}
/**
* 确认签约:对方主体确认待签约的申请,状态从 1(申请中)变为 2(已通过)。
* 发起方不能确认自己的申请。
*
* @param {Object} [data={}] 请求参数。
* @param {number} data.id 签约关系ID。
* @return {Promise<Object>} 接口响应对象。
*/
async confirmSign(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
const signPayload = await this.saveTempSignPayload(payload);
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const relationId = this.resolveRelationId(data);
if (!relationId) {
throw this.createError('id 参数不能为空', 400);
}
const relation = await ctx.model.StoreWarehouse.findOne({
where: { id: relationId },
include: this.getRelationIncludes(),
transaction,
});
if (!relation) {
throw this.createError('签约关系不存在', 404);
}
if (relation.auth_status !== 1) {
throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400);
}
// 确定当前主体在签约中的角色
const isCurrentStore = relation.store_id === currentSubject.id;
const isCurrentWarehouse = relation.warehouse_id === currentSubject.id;
if (!isCurrentStore && !isCurrentWarehouse) {
throw this.createError('当前主体不在此签约关系中', 403);
}
// 发起签约的主体不能确认自己的申请,必须由对方主体确认
if (relation.initiator_subject_id === currentSubject.id) {
throw this.createError('发起方不能确认自己的签约申请', 403);
}
await relation.update({
auth_status: 2,
review_time: new Date(),
reviewed_by: accountId,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await transaction.commit();
return {
code: 200,
data: {
mode: 'confirm',
contract: this.trimContract(this.serializeRelation(result, currentSubject)),
return {
code: 200,
data: {
mode: 'initiate',
temp_code: signPayload.tempCode,
expires_at: signPayload.expiresAt,
expires_in: signPayload.expiresIn,
can_confirm: false,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
},
},
};
}
/**
@ -2662,14 +2395,11 @@ class SettingStoreWarehouseService extends Service {
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const nextUseStatus = this.normalizeStatusFlag(
data.use_status !== undefined ? data.use_status : data.warehouse_use_status,
'warehouse_use_status', 0);
const patch = currentSubject.isWarehouse
? { warehouse_use_status: nextUseStatus }
: { store_use_status: nextUseStatus };
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
await relation.update(patch, { transaction });
await relation.update({
use_status: nextUseStatus,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
@ -2939,8 +2669,7 @@ class SettingStoreWarehouseService extends Service {
applied_by: accountId,
reviewed_by: accountId,
ended_by: null,
warehouse_use_status: 1,
store_use_status: 1,
use_status: 1,
};
if (storeRemask !== null) {

View File

@ -1,25 +0,0 @@
'use strict';
/**
* 将 wms_store_warehouse.use_status 重命名为 warehouse_use_status,
* 并新增 store_use_status 供货主端独立控制使用状态。
*/
module.exports = {
async up(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_store_warehouse
CHANGE COLUMN use_status warehouse_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '仓库侧使用状态:0-不可用,1-可用',
ADD COLUMN store_use_status INT(1) NOT NULL DEFAULT 1 COMMENT '货主侧使用状态:0-不可用,1-可用' AFTER warehouse_use_status
`);
},
async down(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_store_warehouse
DROP COLUMN store_use_status,
CHANGE COLUMN warehouse_use_status use_status INT(1) NOT NULL DEFAULT 1 COMMENT '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)'
`);
},
};

View File

@ -1,24 +0,0 @@
'use strict';
/**
* wms_store_warehouse 增加 initiator_subject_id 记录发起方主体 ID,
* 用于区分签-约发起方(与 applied_by 账号 ID 互补)。
*/
module.exports = {
async up(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_store_warehouse
ADD COLUMN initiator_subject_id BIGINT(20) UNSIGNED NULL COMMENT '发起方主体ID(wms_store.id)'
AFTER ended_by
`);
},
async down(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_store_warehouse
DROP COLUMN initiator_subject_id
`);
},
};

View File

@ -1,34 +0,0 @@
'use strict';
/**
* 为 wms_picking 表新增 stock_id 字段及联合索引。
*
* 用途:消除面单打印自定义区对 wms_order_items 明细表的强依赖,
* 使打印链路可通过 wms_picking.stock_id 直读商品信息与条码数据。
*/
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(`
ALTER TABLE wms_picking
ADD COLUMN stock_id BIGINT(20) DEFAULT NULL COMMENT '商品SKU ID' AFTER storage_id,
ADD INDEX idx_wms_picking_warehouse_stock (warehouse_id, stock_id)
`);
// 回填已有 picking 记录的 stock_id(通过 storage 链路补全)
await queryInterface.sequelize.query(`
UPDATE wms_picking p
INNER JOIN wms_storage s ON p.storage_id = s.id
SET p.stock_id = s.stock_id
WHERE p.stock_id IS NULL
AND p.storage_id IS NOT NULL
`);
},
down: async queryInterface => {
await queryInterface.sequelize.query(`
ALTER TABLE wms_picking
DROP INDEX idx_wms_picking_warehouse_stock,
DROP COLUMN stock_id
`);
},
};

View File

@ -1,42 +1,4 @@
[
{
"version": "2026.07.09-system-01",
"date": "2026-07-09",
"type": "updated",
"summary": "签约 sign 方法改造:统一当前主体→store_id,解除角色校验,仓库可签仓库",
"methods": [
"storeWarehouse.store.sign",
"storeWarehouse.warehouse.sign"
],
"notes": [
"resolvePairIds:统一当前主体始终在 store_id(货主方/消费方),对方在 warehouse_id(仓库方/提供方)。不再根据 isWarehouse 分支。",
"getCounterparty:移除 expectedRole 角色校验(仓库不再只能签货主,可签仓库)。",
"findScopedRelation:改为 OR 查询 store_id/warehouse_id 两边,兼容新旧签约数据。",
"sign preview:counterparty.role 改为根据对方 project 真实返回(warehouse/store),不再硬编码反推。",
"签仓库:仓库发起签约时对方 ID 传 counterparty_id,系统自动将当前仓库放 store_id。"
],
"module": "storeWarehouse"
},
{
"version": "2026.07.08-system-01",
"date": "2026-07-08",
"type": "updated",
"summary": "storeWarehouse.store.list 与 storeWarehouse.warehouse.list 拆分实现,不再共用;仓库侧支持查询外部合作仓库",
"methods": [
"storeWarehouse.store.list",
"storeWarehouse.warehouse.list"
],
"notes": [
"拆分:store.list 调用 listForStore,warehouse.list 调用 listForWarehouse,不再共用同一个 list 方法。",
"新规则:两个方法均按 store_id = 当前主体ID 过滤(主体在 store_id 为货主方/消费方,对方在 warehouse_id 为仓库方/提供方)。",
"warehouse.list 新增支持查询外部合作仓库:当对方主体的 project='warehouse' 时为仓库-仓库合作,counterparty_role='warehouse'。",
"响应新增 counterparty_role 字段(store/warehouse),标识对方主体的真实角色。",
"warehouse.list 响应 use_status 改为 store_use_status(仓库在 store_id 方时,己方启用状态应为 store_use_status)。",
"旧 list 方法保留标记为 @deprecated,保持向后兼容。",
"新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件。"
],
"module": "storeWarehouse"
},
{
"version": "2026.07.06-system-01",
"date": "2026-07-06",

View File

@ -22650,7 +22650,7 @@
"list": [
{
"method": "storeWarehouse.store.list",
"description": "查询当前主体可见的签约列表(当前主体在 store_id 方,对方在 warehouse_id 方)",
"description": "查询当前主体可见的仓库-货主签约列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -22725,11 +22725,6 @@
"type": "string",
"description": "对方主体名称"
},
{
"name": "data.list[].counterparty_role",
"type": "string",
"description": "对方主体角色:warehouse 或 store"
},
{
"name": "data.list[].current_subject_role",
"type": "string",
@ -22806,14 +22801,9 @@
"description": "备注名(当前为仓库则返回货主备注名,反之亦然)"
},
{
"name": "data.list[].warehouse_use_status",
"name": "data.list[].use_status",
"type": "number",
"description": "仓库侧启用状态:0=禁用 1=启用"
},
{
"name": "data.list[].store_use_status",
"type": "number",
"description": "货主侧启用状态:0=禁用 1=启用"
"description": "启用状态:0=禁用 1=启用"
},
{
"name": "data.list[].policy_config",
@ -22870,7 +22860,7 @@
},
{
"method": "storeWarehouse.store.sign",
"description": "发起或确认签约(当前主体始终为 store_id 方/消费方,对方为 warehouse_id 方/提供方,支持仓库签仓库)",
"description": "发起或确认仓库-货主签约",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -22883,11 +22873,18 @@
],
"params": [
{
"name": "counterparty_id",
"name": "store_id",
"type": "number",
"required": true,
"required": false,
"source": "body",
"description": "对方主体 ID(兼容 warehouse_id / store_id),当前主体自动识别"
"description": "货主ID;由仓库侧发起时必传"
},
{
"name": "warehouse_id",
"type": "number",
"required": false,
"source": "body",
"description": "仓库ID;由货主侧发起时必传"
},
{
"name": "temp_code",
@ -22947,11 +22944,11 @@
"description": "签约关系ID,兼容 contract_id"
},
{
"name": "warehouse_use_status",
"name": "use_status",
"type": "number",
"required": false,
"source": "body",
"description": "仓库侧使用状态,0=停用,1=恢复"
"description": "使用状态,0=停用,1=恢复"
}
],
"response": [],
@ -23604,7 +23601,7 @@
"list": [
{
"method": "storeWarehouse.warehouse.list",
"description": "仓库侧查询签约列表(支持查询外部合作仓库),当前仓库在 store_id 方(消费方),对方在 warehouse_id 方(提供方)",
"description": "仓库侧查询当前仓库可见的货主签约列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -23635,150 +23632,41 @@
"type": "string",
"required": false,
"source": "body",
"description": "搜索关键字,模糊匹配己方备注名、对方备注名、己方公司名、对方公司名"
},
{
"name": "warehouse_id",
"type": "number",
"required": false,
"source": "body",
"description": "对方主体 ID(兼容 counterparty_id)"
"description": "搜索关键字,模糊匹配货主备注名、仓库备注名、货主公司名、仓库公司名"
},
{
"name": "auth_status",
"type": "number",
"type": "string",
"required": false,
"source": "body",
"description": "授权状态筛选:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期"
},
{
"name": "use_status",
"type": "number",
"required": false,
"source": "body",
"description": "己方启用状态:0=禁用 1=启用"
"description": "授权状态筛选"
}
],
"response": [
{
"name": "data.list",
"name": "list",
"type": "array",
"description": "签约关系列表"
"description": "签约列表"
},
{
"name": "data.list[].id",
"name": "total",
"type": "number",
"description": "签约关系主键 ID"
"description": "总条数"
},
{
"name": "data.list[].store_id",
"type": "number",
"description": "己方主体 ID(当前仓库)"
},
{
"name": "data.list[].store_name",
"type": "string",
"description": "己方主体名称"
},
{
"name": "data.list[].warehouse_id",
"type": "number",
"description": "对方主体 ID"
},
{
"name": "data.list[].warehouse_name",
"type": "string",
"description": "对方主体名称"
},
{
"name": "data.list[].counterparty_id",
"type": "number",
"description": "对方主体 ID(同 warehouse_id)"
},
{
"name": "data.list[].counterparty_name",
"type": "string",
"description": "对方主体名称"
},
{
"name": "data.list[].counterparty_role",
"type": "string",
"description": "对方主体角色:warehouse(外部合作仓库)或 store(货主)"
},
{
"name": "data.list[].remask",
"type": "string",
"description": "己方对本次签约的备注名"
},
{
"name": "data.list[].use_status",
"type": "number",
"description": "己方启用状态:0=禁用 1=启用"
},
{
"name": "data.list[].auth_status",
"type": "number",
"description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期"
},
{
"name": "data.list[].auth_status_label",
"type": "string",
"description": "签约状态中文标签"
},
{
"name": "data.list[].auth_end",
"type": "string|null",
"description": "授权结束时间"
},
{
"name": "data.list[].print_quantity",
"type": "number",
"description": "面单余额数量"
},
{
"name": "data.list[].has_qimen_config",
"type": "boolean",
"description": "是否已配置奇门"
},
{
"name": "data.list[].needs_my_confirm",
"type": "boolean",
"description": "是否需要当前仓库确认签约(对方发起且状态为申请中)"
},
{
"name": "data.total",
"type": "number",
"description": "总记录数"
},
{
"name": "data.page",
"name": "page",
"type": "number",
"description": "当前页码"
},
{
"name": "data.page_size",
"name": "page_size",
"type": "number",
"description": "每页条数"
},
{
"name": "data.current_subject",
"name": "current_subject",
"type": "object",
"description": "当前主体信息"
},
{
"name": "data.current_subject.store_id",
"type": "number",
"description": "当前主体 ID"
},
{
"name": "data.current_subject.company_name",
"type": "string",
"description": "当前主体公司名称"
},
{
"name": "data.current_subject.role",
"type": "string",
"description": "当前主体角色:warehouse"
"description": "当前主体信息,含 store_id、company_name、role(warehouse/store)"
}
],
"errors": [

View File

@ -1,180 +0,0 @@
'use strict';
const assert = require('node:assert/strict');
const PendingOrderService = require('../../../../../app/service/systemMethods/order/pendingOrder');
/**
* 创建 manualWaybill 操作日志回归测试上下文。
*
* 仅覆盖 operationLog.createOperationLog 的 businessId 传入值。
*/
function createManualWaybillLogHarness(options = {}) {
const calls = {
operationLogPayload: null,
orderExpressCreatePayload: null,
orderDeliveryUpdatePayload: null,
syncOrderIdsPayload: null,
};
const warehouseId = options.warehouseId || 100000;
const testOrderId = options.orderId || 999001;
const orderRow = {
id: testOrderId,
step: options.orderStep || 1,
outbound_status: options.outboundStatus || 'none',
warehouse_id: warehouseId,
store_id: options.storeId || 1000000,
};
const orderExpressMax = options.orderExpressMax !== undefined ? options.orderExpressMax : null;
const ctx = {
app: {
Sequelize: {
Op: {
in: 'in',
},
},
},
user: {
store_id: warehouseId,
employees_id: '9001',
employees_name: '测试员',
},
model: {
OrderExpress: {
async max(field, whereOptions) {
return orderExpressMax;
},
async create(values) {
calls.orderExpressCreatePayload = values;
return {
id: 10001,
...values,
};
},
},
OrderDeliveryFactory: {
getCurrentModel: () => {
throw new Error('应使用 getOrderModel,不是 OrderDeliveryFactory');
},
},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
calls.operationLogPayload = payload;
return { id: 1 };
},
},
storeWarehouse: {
async getContractConfig() {
return null;
},
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
const service = new PendingOrderService(ctx);
// 注入 mock getOrderModel / buildOrderWhere / success / getWarehouseId
service.getWarehouseId = () => warehouseId;
service.getOrderLogOperator = () => ({
id: ctx.user && ctx.user.employees_id,
name: ctx.user && ctx.user.employees_name,
});
service.getOrderLogWarehouseId = () => warehouseId;
service.getOrderModel = async () => ({
async findOne(query) {
return orderRow;
},
async update(values, whereOpts) {
calls.orderDeliveryUpdatePayload = { values, where: whereOpts.where };
return [ 1 ];
},
});
service.buildOrderWhere = (orderIds) => ({
id: { [ctx.app.Sequelize.Op.in]: orderIds },
warehouse_id: warehouseId,
});
service.success = (msg, data) => ({ code: 0, msg, data });
service.syncOrderIds = (payload) => {
calls.syncOrderIdsPayload = payload;
return Promise.resolve();
};
return { service, calls, ctx };
}
describe('test/app/service/systems/express.manualWaybill.guard.test.js — manualWaybill 操作日志', () => {
it('createOperationLog 的 businessId 应为 String(orderId),而非仓库ID', async () => {
const testOrderId = 888001;
const { service, calls } = createManualWaybillLogHarness({
orderId: testOrderId,
warehouseId: 100000,
});
await service.manualWaybill({
order_id: testOrderId,
waybill_code: 'SF1234567890',
});
assert.ok(calls.operationLogPayload, '应调用 createOperationLog');
assert.equal(calls.operationLogPayload.businessType, 'order');
assert.equal(calls.operationLogPayload.businessId, String(testOrderId),
`businessId 应为订单ID "${testOrderId}",而非仓库ID`);
assert.equal(calls.operationLogPayload.operationCode, 'ORDER_MANUAL_WAYBILL');
assert.equal(calls.operationLogPayload.extras.warehouseId, 100000);
assert.equal(calls.operationLogPayload.extras.orderId, testOrderId);
assert.equal(calls.operationLogPayload.extras.waybillCode, 'SF1234567890');
});
it('businessId 不应为 warehouseId(回归验证)', async () => {
const testOrderId = 888002;
const warehouseId = 100000;
const { service, calls } = createManualWaybillLogHarness({
orderId: testOrderId,
warehouseId,
});
await service.manualWaybill({
order_id: testOrderId,
waybill_code: 'YT9876543210',
});
assert.ok(calls.operationLogPayload, '应调用 createOperationLog');
assert.notEqual(calls.operationLogPayload.businessId, String(warehouseId),
`businessId 不应为仓库ID "${warehouseId}"`);
assert.equal(calls.operationLogPayload.businessId, String(testOrderId),
`businessId 应为订单ID "${testOrderId}"`);
});
it('business_key 从已有最大值递增', async () => {
const testOrderId = 888003;
const { service, calls } = createManualWaybillLogHarness({
orderId: testOrderId,
orderExpressMax: 3,
});
await service.manualWaybill({
order_id: testOrderId,
waybill_code: 'EMS0000000001',
});
assert.ok(calls.orderExpressCreatePayload);
assert.equal(calls.orderExpressCreatePayload.business_key, 4, '应从 max(3)+1=4 递增');
assert.equal(calls.orderExpressCreatePayload.status, 1, '手工录入 status 应为 1');
});
});

View File

@ -1,407 +0,0 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressService = require('../../../../app/service/systems/express');
// ============================================================================
// Harness: hardDeleteWaybillAsyncOrderExpressRows
// ============================================================================
function createHardDeleteHarness(options = {}) {
const calls = {
destroyCount: 0,
destroyWhere: null,
loggerErrors: [],
};
const orderExpressModel = {
async destroy(whereOptions) {
calls.destroyCount += 1;
calls.destroyWhere = whereOptions;
if (typeof options.destroy === 'function') {
return await options.destroy(whereOptions);
}
return 1;
},
};
const ctx = {
app: {
Sequelize: {
Op: {
or: 'or',
},
},
},
model: {
OrderExpress: options.orderExpressModel !== undefined ? options.orderExpressModel : orderExpressModel,
},
logger: {
info() {},
warn() {},
error(...args) {
calls.loggerErrors.push(args);
},
},
};
const service = new ExpressService(ctx);
return { service, calls, ctx };
}
// ============================================================================
// Harness: createWaybillCodePipeline — skip business_key=1 + status=1
// ============================================================================
function createPipelineSkipHarness(options = {}) {
const calls = {
asyncTaskPayloads: [],
printPlatformFindAllQueries: [],
listByWarehousePlatformCodePayloads: [],
orderExpressFindAllQueries: [],
loggerInfoMessages: [],
};
const orderDeliveryRows = Array.isArray(options.orderDeliveryRows)
? options.orderDeliveryRows
: [
{
id: 1,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
{
id: 2,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
];
const orderExpressRows = Array.isArray(options.orderExpressRows)
? options.orderExpressRows
: [];
const platformList = Array.isArray(options.platformList) ? options.platformList : [{
code: 'PDD',
print_platform_id: 901,
default_express_interface: 'POLYAPI',
}];
const printPlatformRows = Array.isArray(options.printPlatformRows) ? options.printPlatformRows : [
{
id: 901,
platform_code: 'PDD_PRINT',
request_platform_code: 'OPEN_API',
},
];
const listData = Array.isArray(options.listData) ? options.listData : [];
const ctx = {
app: {
Sequelize: {
Op: {
in: 'in',
},
},
},
user: {
store_id: 100000,
},
model: {
OrderExpress: {
async findAll(query) {
calls.orderExpressFindAllQueries.push(query);
return orderExpressRows;
},
},
OrderDeliveryFactory: {
async getCurrentModel() {
return {
async findAll() {
return orderDeliveryRows;
},
async update() {
return [ 1 ];
},
};
},
},
PrintPlatform: {
async findAll(query) {
calls.printPlatformFindAllQueries.push(query);
return printPlatformRows;
},
},
},
service: {
systems: {
platform: {
async getPlatformList() {
return platformList;
},
},
setting: {
expressInterface: {
async listByWarehousePlatformCode(payload) {
calls.listByWarehousePlatformCodePayloads.push(payload);
return { data: listData };
},
},
},
},
},
logger: {
info(...args) {
calls.loggerInfoMessages.push(args.map(a => String(a)).join(' '));
},
warn() {},
error() {},
},
};
const service = new ExpressService(ctx);
service.asyncTask = (batch, opts, matchedPlatform, expressInterfaceConfig) => {
calls.asyncTaskPayloads.push({ batch, opts, matchedPlatform, expressInterfaceConfig });
};
return { service, calls, ctx };
}
// ============================================================================
// Tests: hardDeleteWaybillAsyncOrderExpressRows
// ============================================================================
describe('test/app/service/systems/express.manualWaybill.guard.test.js', () => {
describe('hardDeleteWaybillAsyncOrderExpressRows — status:0 过滤', () => {
it('destroy 应包含 status:0 条件,保护 status=1 的手工记录', async () => {
const { service, calls } = createHardDeleteHarness();
await service.hardDeleteWaybillAsyncOrderExpressRows(
[
{ order_id: 100, business_key: 1 },
{ order_id: 200, business_key: 2 },
],
{ platform_code: 'PDD', error_message: '测试失败' }
);
assert.equal(calls.destroyCount, 1);
assert.ok(calls.destroyWhere, 'destroy 应被调用');
assert.ok(calls.destroyWhere.where, 'where 条件应存在');
assert.equal(calls.destroyWhere.where.status, 0, 'status 必须为 0');
assert.ok(Array.isArray(calls.destroyWhere.where.or), 'or 条件应存在');
assert.equal(calls.destroyWhere.where.or.length, 2);
});
it('缺少 business_key 时应返回 false,不调用 destroy', async () => {
const { service, calls } = createHardDeleteHarness();
const result = await service.hardDeleteWaybillAsyncOrderExpressRows(
[{ order_id: 100 }],
{ platform_code: 'JD' }
);
assert.equal(result, false);
assert.equal(calls.destroyCount, 0, '缺少 business_key 不应调用 destroy');
});
it('缺少 order_id 时应返回 false,不调用 destroy', async () => {
const { service, calls } = createHardDeleteHarness();
const result = await service.hardDeleteWaybillAsyncOrderExpressRows(
[{ business_key: 1 }],
{ platform_code: 'JD' }
);
assert.equal(result, false);
assert.equal(calls.destroyCount, 0);
});
it('OrderExpress 模型不可用时应返回 false', async () => {
const { service, calls } = createHardDeleteHarness({
orderExpressModel: null,
});
const result = await service.hardDeleteWaybillAsyncOrderExpressRows(
[{ order_id: 100, business_key: 1 }],
{}
);
assert.equal(result, false);
assert.equal(calls.destroyCount, 0);
});
it('空数组应返回 false', async () => {
const { service, calls } = createHardDeleteHarness();
const result = await service.hardDeleteWaybillAsyncOrderExpressRows([], {});
assert.equal(result, false);
assert.equal(calls.destroyCount, 0);
});
it('destroy 抛异常时应返回 false 并记录错误日志', async () => {
const { service, calls } = createHardDeleteHarness({
destroy: async () => {
throw new Error('DB 连接失败');
},
});
const result = await service.hardDeleteWaybillAsyncOrderExpressRows(
[{ order_id: 100, business_key: 1 }],
{ platform_code: 'PDD', error_message: 'err' }
);
assert.equal(result, false);
assert.equal(calls.destroyCount, 1);
assert.ok(calls.loggerErrors.length > 0, '应记录错误日志');
});
});
// ==========================================================================
// Tests: createWaybillCodePipeline — 跳过已分配运单的订单
// ==========================================================================
describe('createWaybillCodePipeline — 跳过 business_key=1 已分配订单', () => {
it('订单已有 status=1 且传入 business_key=1 时,应跳过该订单', async () => {
const { service, calls } = createPipelineSkipHarness({
orderDeliveryRows: [
{
id: 101,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
{
id: 102,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
orderExpressRows: [
{ order_id: 101, business_key: 1, status: 1 },
],
});
await service.createWaybillCodePipeline([
{ order_id: 101, business_key: 1 },
{ order_id: 102, business_key: 1 },
]);
// 订单 101 应被跳过,只有 102 进入 asyncTask
assert.equal(calls.asyncTaskPayloads.length, 1, '只有未分配的订单应进入 asyncTask');
const batch = calls.asyncTaskPayloads[0].batch;
const batchOrderIds = batch.map(o => o.id);
assert.ok(!batchOrderIds.includes(101), '订单 101 不应在 batch 中');
assert.ok(batchOrderIds.includes(102), '订单 102 应在 batch 中');
});
it('订单有 status=1 但传入 business_key=2 时,不应跳过(不同 business_key)', async () => {
const { service, calls } = createPipelineSkipHarness({
orderDeliveryRows: [
{
id: 201,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
orderExpressRows: [
{ order_id: 201, business_key: 1, status: 1 },
],
});
await service.createWaybillCodePipeline([
{ order_id: 201, business_key: 2 },
]);
// business_key=2 不同于已完成的 business_key=1,不应跳过
assert.equal(calls.asyncTaskPayloads.length, 1, 'business_key 不同时不应跳过');
});
it('订单有 status=1 但 business_key 不是 1 时,传入 business_key=1 应跳过', async () => {
const { service, calls } = createPipelineSkipHarness({
orderDeliveryRows: [
{
id: 301,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
orderExpressRows: [
{ order_id: 301, business_key: 2, status: 1 },
],
});
await service.createWaybillCodePipeline([
{ order_id: 301, business_key: 1 },
]);
// skipSet 中有 "301:2",但过滤条件是 businessKey===1 && skipSet.has("301:1")
// 这里 skipSet 中没有 "301:1",所以不应跳过
assert.equal(calls.asyncTaskPayloads.length, 1, 'skipSet 中无匹配的 business_key=1 时不应跳过');
});
it('全部订单均已完成时,应直接返回无需处理', async () => {
const { service, calls } = createPipelineSkipHarness({
orderDeliveryRows: [
{
id: 401,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
orderExpressRows: [
{ order_id: 401, business_key: 1, status: 1 },
],
});
const result = await service.createWaybillCodePipeline([
{ order_id: 401, business_key: 1 },
]);
assert.equal(calls.asyncTaskPayloads.length, 0, '全部跳过时不应调用 asyncTask');
assert.equal(result.message, '所有订单均已分配运单号,无需处理');
});
it('无 status=1 记录时,所有订单正常进入 pipeline', async () => {
const { service, calls } = createPipelineSkipHarness({
orderDeliveryRows: [
{
id: 501,
sys_platform_code: 'PDD',
logistics_code: 'SF',
sys_platform_name: '拼多多',
logistics_name: '顺丰',
store_id: 100000,
},
],
orderExpressRows: [],
});
await service.createWaybillCodePipeline([
{ order_id: 501, business_key: 1 },
]);
assert.equal(calls.asyncTaskPayloads.length, 1, '无已完成记录时所有订单应正常处理');
});
});
});

View File

@ -1,73 +0,0 @@
# 20260707-手工运单号硬删除误删修复单元测试报告
## 测试目标
验证上一轮三轮修复(`hardDeleteWaybillAsyncOrderExpressRows` 加 `status:0` 过滤、`manualWaybill` 操作日志 `businessId` 修正、`createWaybillCodePipeline` 跳过已分配订单)是否符合预期。
## 测试类型
单元测试(Unit Test)
## 测试范围
| 被测方法 | 被测文件 | 测试用例数 | 通过 | 失败 |
|----------|---------|-----------|------|------|
| `hardDeleteWaybillAsyncOrderExpressRows` | `app/service/systems/express.js` | 6 | 6 | 0 |
| `createWaybillCodePipeline` | `app/service/systems/express.js` | 5 | 5 | 0 |
| `manualWaybill` | `app/service/systemMethods/order/pendingOrder.js` | 3 | 3 | 0 |
## 测试产物
- `test/app/service/systems/express.manualWaybill.guard.test.js` — hardDelete + pipeline 跳过逻辑测试
- `test/app/service/systemMethods/order/pendingOrder.manualWaybill.log.test.js` — manualWaybill 操作日志测试
## 测试结果摘要
### ✅ 全部 14 个测试用例通过(0 失败)
### 1. hardDeleteWaybillAsyncOrderExpressRows — status:0 过滤
| 用例 | 结果 |
|------|------|
| destroy 应包含 status:0 条件,保护 status=1 的手工记录 | ✅ PASS |
| 缺少 business_key 时应返回 false,不调用 destroy | ✅ PASS |
| 缺少 order_id 时应返回 false,不调用 destroy | ✅ PASS |
| OrderExpress 模型不可用时应返回 false | ✅ PASS |
| 空数组应返回 false | ✅ PASS |
| destroy 抛异常时应返回 false 并记录错误日志 | ✅ PASS |
### 2. createWaybillCodePipeline — 跳过 business_key=1 已分配订单
| 用例 | 结果 |
|------|------|
| 订单已有 status=1 且传入 business_key=1 时,应跳过该订单 | ✅ PASS |
| 订单有 status=1 但传入 business_key=2 时,不应跳过(不同 business_key) | ✅ PASS |
| 订单有 status=1 但 business_key 不是 1 时,传入 business_key=1 应跳过 | ✅ PASS |
| 全部订单均已完成时,应直接返回无需处理 | ✅ PASS |
| 无 status=1 记录时,所有订单正常进入 pipeline | ✅ PASS |
### 3. manualWaybill — 操作日志 businessId 修正
| 用例 | 结果 |
|------|------|
| createOperationLog 的 businessId 应为 String(orderId),而非仓库ID | ✅ PASS |
| businessId 不应为 warehouseId(回归验证) | ✅ PASS |
| business_key 从已有最大值递增 | ✅ PASS |
## 关键验证点
1. **三层防护闭环验证**:
- 第 1 层(pipeline 入口):`business_key=1` + 已完成的订单在 pipeline 入口即被过滤
- 第 2 层(trans 内):`createWaybillCode` 的 `completedOrderKeySet` 事务内二次校验
- 第 3 层(失败清理):`hardDeleteWaybillAsyncOrderExpressRows` 仅删 `status=0`
2. **操作日志可检索性**:`manualWaybill` 的 `businessId` 已修正为订单 ID,可通过订单 ID 检索操作日志
3. **向后兼容**:
- `business_key ≠ 1` 的已分配订单不会被误跳过
- 无已完成记录时 pipeline 正常运作
## 结论与建议
三轮修复均通过单元测试验证,符合预期行为:
- 手工录入的运单号(`status=1`)不再被失败清理逻辑误删
- 操作日志可正确按订单 ID 检索
- pipeline 入口即过滤已分配订单,避免无效异步任务提交