fix: 定时任务同步日志 + 基础设施修复 + 权限迁移(收尾)

【定时任务】sync_outbound_orders_to_delivery: 执行日志写缓存 + 错误详情提取(parent/validation)

【基础设施】system.js: snake_case→camelCase 服务路由转换(兼容 express_interface 等)

【看板】dashboard: queryWarehouseStats 支持 storeId 货主维度过滤

【订单基类】order/base: getOrderModel 兼容无上下文时传入 warehouseId(货主侧场景)

【库存】inventory: 全量移库软删除→硬删除(force destroy)释放唯一键 + 唯一约束/校验错误友好提示

【快递平台】express_platform: KS(快手)平台 receiver.phone 不传(平台要求)

【迁移】delivery 自增起点 + supervisor CS 权限修复
This commit is contained in:
liufumingren 2026-07-27 03:49:27 +08:00
parent b2ae5683e1
commit 81350c0d6b
14 changed files with 253 additions and 39 deletions

View File

@ -2,6 +2,69 @@
const SHORT_TASK_QUERY_TIMEOUT_MS = 15000;
const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000;
const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution';
const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟
/**
* 将本次执行日志写入缓存。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} logEntry 日志条目。
* @return {Promise<void>}
*/
async function writeExecutionLogToCache(ctx, logEntry) {
try {
if (ctx.app && typeof ctx.app.setCacheAsync === 'function') {
await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL);
}
} catch (err) {
// 缓存写入失败不影响主流程
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行日志缓存失败: ${err.message}`);
}
}
/**
* 提取错误详情,方便定位问题位置。
*
* @param {Error} error 错误对象。
* @return {Object} 错误详情。
*/
function extractErrorDetail(error) {
if (!error) return {};
const detail = {
name: error.name || '',
message: error.message || '',
code: error.code || '',
};
// Sequelize 父级错误(通常包含 SQL 信息)
if (error.parent) {
detail.parent = {
name: error.parent.name || '',
message: error.parent.message || '',
code: error.parent.code || '',
sql: error.parent.sql || '',
};
}
// SequelizeValidationError 的 fields 列表
if (Array.isArray(error.errors)) {
detail.validation_errors = error.errors.map(e => ({
message: e.message,
type: e.type,
path: e.path,
value: String(e.value ?? ''),
}));
}
// 堆栈前 3 行(定位调用链)
if (error.stack) {
detail.stack_top = error.stack.split('\n').slice(0, 4).map(s => s.trim());
}
return detail;
}
/**
* 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。
@ -31,21 +94,51 @@ module.exports = {
ctx.app._syncOutboundOrdersToDeliveryRunning = true;
const startedAt = Date.now();
let status = 'success';
let errorMessage = '';
let errorDetail = null;
let result = null;
try {
const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({
result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({
queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS,
executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS,
});
if (result && result.retryableFailure) {
status = 'retryable_failure';
errorMessage = `retryableFailureType=${result.retryableFailureType}, timeoutCount=${result.timeoutCount || 0}`;
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`);
} else if (result && result.totalCreated > 0) {
ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`);
}
// 始终输出汇总日志(含 0 条场景,确认定时任务在跑)
ctx.logger.info(`[sync-outbound-orders-to-delivery] 本轮完成 selected=${result ? result.totalSelected : 0} created=${result ? result.totalCreated : 0} skipped=${result ? result.totalSkipped : 0} timeout=${result ? result.totalTimeout : 0}`);
} catch (error) {
ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`);
status = 'error';
errorMessage = error.message;
errorDetail = extractErrorDetail(error);
ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`, errorDetail);
} finally {
ctx.app._syncOutboundOrdersToDeliveryRunning = false;
}
// 写入执行日志到缓存
const logEntry = {
executed_at: new Date().toISOString(),
duration_ms: Date.now() - startedAt,
status,
error_message: errorMessage,
error_detail: errorDetail,
total_selected: result ? result.totalSelected : 0,
total_created: result ? result.totalCreated : 0,
total_skipped: result ? result.totalSkipped : 0,
total_timeout: result ? result.totalTimeout : 0,
warehouse_ids: result ? result.warehouseIds : [],
};
await writeExecutionLogToCache(ctx, logEntry);
ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY}`);
},
};

View File

@ -14,8 +14,10 @@ class systemService extends Service {
const classs = servicePath.split('.');
let systemMethods = this.ctx.service.systemMethods;
for (let i = 0; i < classs.length; i++) {
const className = classs[i];
systemMethods = systemMethods[className];
const rawClassName = classs[i];
// Egg.js 将文件名 snake_case 自动转为 camelCase,需做对应转换
const camelName = rawClassName.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
systemMethods = systemMethods[camelName] || systemMethods[rawClassName];
}
// 检查服务是否存在
if (!systemMethods) {

View File

@ -47,11 +47,11 @@ class dashboardService extends MainService {
}
// 跨仓并行查询并汇总
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid).catch(() => null)));
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid, storeId).catch(() => null)));
return this.success('ok', this.mergeStoreStats(results.filter(Boolean)));
}
async queryWarehouseStats(warehouseId) {
async queryWarehouseStats(warehouseId, storeId = null) {
const { ctx } = this;
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
@ -61,9 +61,10 @@ class dashboardService extends MainService {
step: { [Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Op.ne]: 'padding' },
status: { [Op.ne]: 'cancel' },
store_id: { [Op.in]: [] }, // 占位,后续填充
};
delete pendingBase.store_id;
if (storeId) {
pendingBase.store_id = storeId;
}
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
@ -89,7 +90,7 @@ class dashboardService extends MainService {
model.count({ where: { ...pendingBase, print_status: 'none' } }),
model.count({ where: { ...pendingBase, pick_status: 'none' } }),
model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }),
model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }),
model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd }, ...(storeId ? { store_id: storeId } : {}) } }),
model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }),
model.count({ where: { ...pendingBase, step: 3 } }),
]);

View File

@ -581,13 +581,24 @@ class OrderBaseService extends MainService {
async getOrderModel(moduleName = 'order', warehouseId = null) {
const { ctx } = this;
const config = this.getModuleConfig(moduleName);
const contextWarehouseId = this.getWarehouseId();
let contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
const hasContextWarehouseId = contextWarehouseId !== null
&& contextWarehouseId !== undefined
&& contextWarehouseId !== '';
const hasParamWarehouseId = warehouseId !== null
&& warehouseId !== undefined
&& warehouseId !== '';
if (!hasContextWarehouseId && !hasParamWarehouseId) {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
if (!hasContextWarehouseId) {
contextWarehouseId = warehouseId;
}
if (hasContextWarehouseId && hasParamWarehouseId
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
@ -646,15 +657,26 @@ class OrderBaseService extends MainService {
*/
async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
const { ctx } = this;
const contextWarehouseId = this.getWarehouseId();
let contextWarehouseId = this.getWarehouseId();
const normalizedTableType = this.resolveOrderTableType({ tableType });
const actualWarehouseId = warehouseId ?? contextWarehouseId;
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
const hasContextWarehouseId = contextWarehouseId !== null
&& contextWarehouseId !== undefined
&& contextWarehouseId !== '';
const hasActualWarehouseId = actualWarehouseId !== null
&& actualWarehouseId !== undefined
&& actualWarehouseId !== '';
if (!hasContextWarehouseId && !hasActualWarehouseId) {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
if (!hasContextWarehouseId) {
contextWarehouseId = actualWarehouseId;
}
if (hasContextWarehouseId && hasActualWarehouseId
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
@ -680,15 +702,26 @@ class OrderBaseService extends MainService {
*/
async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
const { ctx } = this;
const contextWarehouseId = this.getWarehouseId();
let contextWarehouseId = this.getWarehouseId();
const normalizedTableType = this.resolveOrderTableType({ tableType });
const actualWarehouseId = warehouseId ?? contextWarehouseId;
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
const hasContextWarehouseId = contextWarehouseId !== null
&& contextWarehouseId !== undefined
&& contextWarehouseId !== '';
const hasActualWarehouseId = actualWarehouseId !== null
&& actualWarehouseId !== undefined
&& actualWarehouseId !== '';
if (!hasContextWarehouseId && !hasActualWarehouseId) {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
if (!hasContextWarehouseId) {
contextWarehouseId = actualWarehouseId;
}
if (hasContextWarehouseId && hasActualWarehouseId
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}

View File

@ -436,7 +436,7 @@ class OrderIndexService extends OrderBaseService {
* @param {Object} data 请求体。
* @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。
* @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。
* @param {number|string} data.weighing_weight 称重重量(kg)。
* @param {number|string} data.weighing_weight 称重重量(g)。
* @return {Promise<Object>} 统一成功/失败结构。
* 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}};
* 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}};

View File

@ -3191,7 +3191,7 @@ class PendingOrderService extends OrderBaseService {
Authorization: `Bearer ${apiKey}`,
},
data: {
model: 'deepseek-chat',
model: 'deepseek-v4-pro',
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
@ -3207,6 +3207,7 @@ class PendingOrderService extends OrderBaseService {
}
const content = result.data.choices?.[0]?.message?.content || '';
this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content);
// 清理可能的 markdown 代码块标记
let jsonStr = content.trim();

View File

@ -12,7 +12,7 @@ class OrderPrintService extends OrderBaseService {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}

View File

@ -708,7 +708,7 @@ class ExpressPlatformService extends MainService {
procode: order.procode || '普通商品',
codpaymoney: order.ar_amount ?? null,
packagemoney: order.item_amount ?? null,
weight: Number(order.items_weight) || 0,
weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位
supporpaymoney: order.total_amount ?? null,
length: Number(order.length) || 0,
width: Number(order.width) || 0,
@ -743,7 +743,7 @@ class ExpressPlatformService extends MainService {
receiver: {
name: order.name || '',
company: order.company || '',
phone: order.mobile || order.tel || '',
phone: order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''),
mobile: order.mobile || order.tel || '',
country: order.country_code || 'CN',
province: order.province || '',

View File

@ -76,7 +76,7 @@ class LocationService extends Service {
width: cellWidth,
height: cellHeight,
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
max_weight: 100, // 默认100kg
max_weight: 100000, // 默认100000g
space_status: 'AVAILABLE',
is_enabled: true,
relative_x: relativeX,

View File

@ -1115,7 +1115,7 @@ class LocationZoneService extends Service {
width: cellWidth,
height: cellHeight,
volume: cellLength * cellWidth * cellHeight / 1000000,
max_weight: 100,
max_weight: 100000,
space_status: 'AVAILABLE',
is_enabled: true,
relative_x: relativeX,

View File

@ -50,7 +50,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([
{ header: '商品种数', key: 'items_count', width: 12 },
{ header: '商品件数', key: 'items_total', width: 12 },
{ header: '商品重量', key: 'items_weight', width: 12 },
{ header: '称重重量(kg)', key: 'weighing_weight', width: 14 },
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
{ header: '订单金额', key: 'total_amount', width: 14 },
{ header: '实收金额', key: 'got_amount', width: 14 },
{ header: '创建时间', key: 'create_at', width: 20 },
@ -99,7 +99,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
{ header: '商品种数', key: 'items_count', width: 12 },
{ header: '商品件数', key: 'items_total', width: 12 },
{ header: '商品重量', key: 'items_weight', width: 12 },
{ header: '称重重量(kg)', key: 'weighing_weight', width: 14 },
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
{ header: '订单金额', key: 'total_amount', width: 14 },
{ header: '实收金额', key: 'got_amount', width: 14 },
{ header: '创建时间', key: 'create_at', width: 20 },

View File

@ -465,13 +465,10 @@ class InventoryService extends Service {
});
if (isFullTransfer) {
// 全量移库且合并:删除原记录
await ctx.model.Storage.update({
is_enabled: 0,
delete_at: new Date(),
updated_at: new Date(),
}, {
// 全量移库且合并:硬删除原记录,释放唯一键
await ctx.model.Storage.destroy({
where: { id: storageId },
force: true,
transaction,
});
srcSpaceDelta.qtyDelta -= srcRecord.quantity;
@ -930,13 +927,10 @@ class InventoryService extends Service {
});
if (isFullTransfer) {
// 全量:软删除原记录
await ctx.model.Storage.update({
is_enabled: 0,
delete_at: new Date(),
updated_at: new Date(),
}, {
// 全量:硬删除原记录,释放唯一键
await ctx.model.Storage.destroy({
where: { id: srcRecord.id },
force: true,
transaction,
});
} else {
@ -1157,6 +1151,21 @@ class InventoryService extends Service {
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
}
if (error.name === 'SequelizeUniqueConstraintError') {
return {
code: 409,
message: '目标库位已存在该商品同批次同类型的库存记录,合并移库失败,请稍后重试或使用 transferLocation 逐条移库',
data: null,
};
}
if (error.name === 'SequelizeValidationError') {
ctx.logger.error('[inventory.transferByProduct] Sequelize 校验失败', {
errors: error.errors?.map(e => ({ path: e.path, message: e.message, value: e.value })),
});
return { code: 400, message: `数据校验失败: ${error.errors?.map(e => e.message).join('; ') || error.message}`, data: null };
}
throw error;
}
}

View File

@ -0,0 +1,18 @@
'use strict';
module.exports = {
async up(queryInterface) {
// 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+
// 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大
await queryInterface.sequelize.query(
"ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000"
);
},
async down(queryInterface) {
// 回滚:重置为默认(MAX(id)+1)
await queryInterface.sequelize.query(
'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 1'
);
},
};

View File

@ -0,0 +1,57 @@
'use strict';
/**
* 修复:客服组-主管 补充缺失权限,使其不低于下属(客服组-员工)
*
* 背景:
* 迁移 20260608033847 的设计意图是「客服组-主管」与「客服组-员工」权限一致。
* 但后续新增权限时,主管遗漏了 5 个权限,导致员工(162个) > 主管(159个) 的越级现象。
*
* 变更:
* - 客服组-主管 (id=28) 补充 [62, 63, 363, 396, 397] 共 5 个权限
* - 补后:主管 164 个权限 > 员工 162 个权限(主管额外保留 309, 392)
*
* 补充权限明细:
* | ID | 路径 | 名称 | 类型 |
* |-----|-----------------------------------------------|-------------|-----------|
* | 62 | stock.saveWarehouseStock | 保存商品资料 | api |
* | 63 | stock.saveWarehouseStockBarcode | 修改商品条码 | api |
* | 363 | storeWarehouse.store.queryPrintQuantityLogs | 货主面单余额 | api |
* | 396 | shipperSigning | 外部仓库 | web_pages |
* | 397 | storeWarehouse.store.confirmSign | 签约确定 | api |
*/
const TABLE = 'wms_role';
const ROLE_ID = 28;
const NEW_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,62,63,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,363,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,396,397,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]';
const OLD_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]';
/**
* @param {import('sequelize').QueryInterface} queryInterface
*/
module.exports.up = async queryInterface => {
const [result] = await queryInterface.sequelize.query(
`UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW()
WHERE id = :id AND is_system = 1`,
{ replacements: { id: ROLE_ID, permissions: NEW_PERMISSIONS } }
);
const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0;
console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限补充:补充 5 个权限,实际更新 ${affected} 行`);
};
/**
* @param {import('sequelize').QueryInterface} queryInterface
*/
module.exports.down = async queryInterface => {
const [result] = await queryInterface.sequelize.query(
`UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW()
WHERE id = :id AND is_system = 1`,
{ replacements: { id: ROLE_ID, permissions: OLD_PERMISSIONS } }
);
const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0;
console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限回滚:实际回滚 ${affected} 行`);
};