feat(order): from_key 改为承载上游应用 appKey 字符串

背景:from_key 是「回原通道」的应用标识,出库单回传与取号业务分支都依赖它。
历史只存过奇门/ERP 的纯数字 appKey(聚水潭 23060081、吉客云 24869601),
OpenAPI 创建来源的 appKey 是字符串(wms_api_app.self_app_key,如
WMSD08A3696BBA9551F261C88BBF7F462BD),INTEGER 列无法承载,
normalizeOrderFromKey 会把字符串归一化成 null,导致 API 渠道订单 from_key 全为空。

改动:
- from_key 列 INTEGER(11) -> VARCHAR(100),迁移覆盖基表与全部分表
  (current/history/dispatch/outsourced),整数改字符串需重建表,
  迁移在改列后校验并恢复 AUTO_INCREMENT 水位,避免分表 id 区间重叠
- normalizeOrderFromKey 不再按整数归一化,改为去空白 + 截断 100 落库
- DY 平台聚水潭判断改为字符串比较,兼容改造后的存量数据

落库口径:QM 取 wms_qimen_apps.app_key,API 取 wms_api_app.self_app_key,
MANUAL/STOCKOUT 为空。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-04 04:46:38 +08:00
parent 28c862b7c9
commit 765bb2c0f7
4 changed files with 236 additions and 15 deletions

View File

@ -387,9 +387,9 @@ module.exports = app => {
comment: '仓库ID',
},
from_key: {
type: INTEGER(11),
type: STRING(100),
allowNull: true,
comment: '来源键',
comment: '来源键(上游对接应用 appKey:QM=wms_qimen_apps.app_key,API=wms_api_app.self_app_key)',
},
items: {
type: TEXT,

View File

@ -1307,26 +1307,22 @@ class DeliveryOrderService extends Service {
}
/**
* 标准化订单来源键。
* 标准化订单来源键(上游对接应用的 appKey)。
*
* 奇门/ERP 的 appKey 是纯数字(如 23060081),OpenAPI 应用的是字符串
* (如 WMSD08A3696BBA9551F261C88BBF7F462BD),统一按字符串落库,
* 供出库单回传与取号业务分支回源使用。
*
* @param {any} value 来源键原始值。
* @return {number|null} 有限整数返回整数值,否则返回 null。
* @return {string|null} 去空后的字符串(超长截断到 100),无值返回 null。
*/
normalizeOrderFromKey(value) {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string' && value.trim() === '') {
return null;
}
const normalizedValue = Number(value);
if (Number.isFinite(normalizedValue) && Number.isInteger(normalizedValue)) {
return normalizedValue;
}
return null;
const text = String(value).trim();
return text ? text.slice(0, 100) : null;
}
/**

View File

@ -841,7 +841,7 @@ class ExpressPlatformService extends MainService {
console.log('order', order);
const expressListItem = ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code) || {};
let plattradeno = order.oaid_order_source_code || order.source_order_codes || '';
if (listByWarehousePlatformCode.platform_code === 'DY' && order.from_key === 23060081 && !!order.pay_no && plattradeno.indexOf(',') > -1) {
if (listByWarehousePlatformCode.platform_code === 'DY' && String(order.from_key || '') === '23060081' && !!order.pay_no && plattradeno.indexOf(',') > -1) {
plattradeno = order.pay_no;
}
let playload = {

View File

@ -0,0 +1,225 @@
'use strict';
/**
* 订单表 from_key 由 INTEGER(11) 改为 VARCHAR(100),用于承载上游对接应用的 appKey。
*
* 背景:from_key 是「回原通道」的应用标识(出库单回传、取号业务分支都依赖它),
* 历史上只存过奇门/ERP 的纯数字 appKey(如聚水潭 23060081、吉客云 24869601)。
* OpenAPI 创建来源的 appKey 是字符串(wms_api_app.self_app_key,如
* WMSD08A3696BBA9551F261C88BBF7F462BD),INTEGER 列无法承载,
* 导致 API 渠道订单 from_key 全部落空。
*
* 落库口径(统一为“上游对接应用 appKey”):
* - QM :wms_qimen_apps.app_key
* - API :wms_api_app.self_app_key
* - MANUAL / STOCKOUT:NULL
*
* 覆盖范围:基表 wms_order_delivery + 全部分表
* (wms_order_delivery_{wh} 及 _{wh}_history / _{wh}_dispatch / _{wh}_outsourced)。
*
* 注意:INTEGER → VARCHAR 在 MySQL 中需要重建表,重建会把 AUTO_INCREMENT
* 重置为 MAX(id)+1。若原水位更高(曾删除数据),会与其它分表 id 区间重叠产生
* 主键冲突,因此每张表改列后都要恢复原 AUTO_INCREMENT 水位。
*
* 幂等:列已是字符类型则跳过。
*/
const BASE_TABLE = 'wms_order_delivery';
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
const COLUMN_NAME = 'from_key';
const COLUMN_COMMENT = '来源键(上游对接应用 appKey:QM=wms_qimen_apps.app_key,API=wms_api_app.self_app_key)';
/**
* 列举库内全部订单分表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<string[]>} 分表名列表。
*/
async function listOrderShards(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
+ 'ORDER BY TABLE_NAME'
);
return (rows || [])
.map(row => String(row.tableName || row.TABLE_NAME || ''))
.filter(name => SHARD_PATTERN.test(name));
}
/**
* 判断表是否存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<boolean>} 是否存在。
*/
async function tableExists(queryInterface, tableName) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?',
{ replacements: [ tableName ] }
);
return Number(rows && rows[0] && rows[0].total || 0) > 0;
}
/**
* 读取列当前类型。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} columnName 列名。
* @return {Promise<string|null>} 类型字符串,列不存在返回 null。
*/
async function getColumnType(queryInterface, tableName, columnName) {
const described = await queryInterface.describeTable(tableName);
const column = described && described[columnName];
return column ? String(column.type || '') : null;
}
/**
* 判断类型是否为字符类型。
* @param {string} type 类型字符串。
* @return {boolean} 是否字符类型。
*/
function isStringType(type) {
return /char|text/i.test(String(type || ''));
}
/**
* 读取表当前 AUTO_INCREMENT 水位。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<number|null>} 水位,无自增主键返回 null。
*/
async function getAutoIncrement(queryInterface, tableName) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?',
{ replacements: [ tableName ] }
);
const value = rows && rows[0] && rows[0].autoIncrement;
return value === null || value === undefined ? null : Number(value);
}
/**
* 重建表后若自增水位被重置为更低值则恢复,避免与其它分表 id 重叠。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {number|null} previousAutoIncrement 改列前的水位。
* @return {Promise<boolean>} 是否执行了恢复。
*/
async function restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement) {
if (previousAutoIncrement === null) {
return false;
}
const currentAutoIncrement = await getAutoIncrement(queryInterface, tableName);
if (currentAutoIncrement === null || currentAutoIncrement >= previousAutoIncrement) {
return false;
}
await queryInterface.sequelize.query(
`ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${previousAutoIncrement}`
);
return true;
}
module.exports = {
/**
* 执行迁移:把 from_key 改为 VARCHAR(100)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 构造器。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
if (!await tableExists(queryInterface, tableName)) {
results.push({ tableName, action: 'skip', reason: 'table_missing' });
continue;
}
const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME);
if (currentType === null) {
results.push({ tableName, action: 'skip', reason: 'column_missing' });
continue;
}
if (isStringType(currentType)) {
results.push({ tableName, action: 'skip', reason: 'already_string', currentType });
continue;
}
const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName);
await queryInterface.changeColumn(tableName, COLUMN_NAME, {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: null,
comment: COLUMN_COMMENT,
});
const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement);
results.push({ tableName, action: 'altered', from: currentType, autoIncrementRestored });
}
console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] up results:', JSON.stringify(results));
},
/**
* 回滚迁移:把 from_key 改回 INTEGER(11)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 构造器。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
if (!await tableExists(queryInterface, tableName)) {
results.push({ tableName, action: 'skip', reason: 'table_missing' });
continue;
}
const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME);
if (currentType === null) {
results.push({ tableName, action: 'skip', reason: 'column_missing' });
continue;
}
if (!isStringType(currentType)) {
results.push({ tableName, action: 'skip', reason: 'already_integer', currentType });
continue;
}
// 字符串 appKey 无法回滚进 INTEGER 列,先阻断避免截断成 0 造成脏数据
const [ incompatibleRows ] = await queryInterface.sequelize.query(
`SELECT COUNT(*) AS total FROM \`${tableName}\` `
+ `WHERE ${COLUMN_NAME} IS NOT NULL AND ${COLUMN_NAME} <> '' `
+ `AND ${COLUMN_NAME} NOT REGEXP '^-?[0-9]+$'`
);
const incompatibleCount = Number(incompatibleRows && incompatibleRows[0] && incompatibleRows[0].total || 0);
if (incompatibleCount > 0) {
results.push({ tableName, action: 'skip', reason: 'non_numeric_data', incompatibleCount });
continue;
}
const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName);
await queryInterface.changeColumn(tableName, COLUMN_NAME, {
type: Sequelize.INTEGER(11),
allowNull: true,
defaultValue: null,
comment: '来源键',
});
const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement);
results.push({ tableName, action: 'reverted', autoIncrementRestored });
}
console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] down results:', JSON.stringify(results));
},
};