Compare commits

...

7 Commits

Author SHA1 Message Date
liufumingren
f127853592 fix(shops): 视频号授权允许回调地址为空,透传 appId/toUserName,超时调至 15s 2026-08-15 20:12:26 +08:00
liufumingren
2e95fb19d4 perf(query): 运单定位优先序列表直查,减少三表循环扫描 2026-08-15 20:12:26 +08:00
liufumingren
37104079e5 feat(order): 订单/明细 id 防回退——序列表唯一发号 + 分表免重建 + 水位自愈 + 迁移任务执行历史 2026-08-15 20:12:23 +08:00
liufumingren
0eb9e845dd fix(inbox): 函数执行前按群类型校验可用性,拦截货主群越权调用快递群函数 2026-08-15 20:10:37 +08:00
liufumingren
18d33ec645 feat(order.pendingOrder.parseAddress): 支持数组批量入参批量解析,模型切 v4-flash,50 条并行块解析实测 31.6s
- 入参兼容 address 字符串(单条)/address 数组/addresses 数组(批量,上限 50)

- 批量按每 10 条合并一次请求并行发出,Promise.all 聚合按输入顺序返回,失败条目逐条回退单条解析

- 模型 deepseek-v4-flash(仅 parseAddress 内使用,不改全局配置),超时 60s/块 120s

- extractJsonBlock 支持数组 JSON 截取;新增手机号/姓名清洗与正则省市区最终兜底

- 同步 methods/system.json 文档(v0.3.28)与变更记录
2026-08-15 18:27:21 +08:00
liufumingren
75ac14a4ab fix(order.recheckOrder): 团购复核输出拦截订单序号,修正 intercept_status 识别(B2026080700003) 2026-08-15 18:25:43 +08:00
liufumingren
a5945cd678 fix: inbox 群登记按 group_id 去重,群改名只更新名称;唯一索引改为 (warehouse_id, group_id) 2026-08-15 18:22:30 +08:00
24 changed files with 2646 additions and 439 deletions

12
app.js
View File

@ -38,6 +38,18 @@ module.exports = app => {
app.logger.error('❌ 工厂类初始化失败:', error);
}
// 启动初检:异步为已有分表的仓库确保订单 id 序列表存在且水位正确。
// 只做建表 + 水位抬升,不迁移数据(位置指针回填由 backfill-order-id-location 脚本负责);
// 异步执行不阻塞启动,失败仅告警,后续建单/迁移触发时还会再次 ensure。
setImmediate(() => {
const factory = app.model && app.model.OrderDeliveryFactory;
if (factory && typeof factory.ensureAllLocationSequenceTables === 'function') {
factory.ensureAllLocationSequenceTables().catch(error => {
app.logger.warn(`[启动初检] 序列表初检异常: ${error && error.message ? error.message : error}`);
});
}
});
// 验证缓存方法
if (typeof app.setCacheAsync === 'function') {
await app.setCacheAsync('system', 'wms', 10);

View File

@ -105,6 +105,11 @@ module.exports = app => {
deletedAt: 'deleted_at',
paranoid: true,
comment: '站内信群表',
indexes: [
// 群唯一性以 (warehouse_id, group_id) 为准,群名称变化只更新不建新
{ name: 'uk_warehouse_group_id', unique: true, fields: [ 'warehouse_id', 'group_id' ] },
{ name: 'idx_group_id', fields: [ 'group_id' ] },
],
});
return InboxGroup;

View File

@ -18,7 +18,9 @@ const {
buildColumnLine,
buildColumnLines,
buildIndexLines,
isColumnDefinitionDifferent,
parseManagedTableName,
AUTO_INCREMENT_SAFE_MARGIN,
} = require('./order_delivery_table_schema');
const LANES = Object.freeze({
@ -111,6 +113,7 @@ module.exports = app => {
constructor() {
this.modelCache = new Map();
this.inflightInitCache = new Map();
this.locationTableReady = new Map();
this.app = app;
}
@ -539,32 +542,7 @@ module.exports = app => {
}
for (const columnName of expectedAttributeNames) {
const expectedColumn = expectedAttributes[columnName];
const actualColumn = tables[columnName] || {};
const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function'
? expectedColumn.type.toSql().toLowerCase()
: String(expectedColumn.type || '').toLowerCase();
const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase();
const expectedAllowNull = expectedColumn.allowNull !== false;
const actualAllowNull = actualColumn.allowNull !== false;
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue')
? expectedColumn.defaultValue
: undefined;
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue')
? actualColumn.defaultValue
: undefined;
if (expectedType && actualType && expectedType !== actualType) {
return true;
}
if (expectedAllowNull !== actualAllowNull) {
return true;
}
const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault);
const normalizedActualDefault = actualDefault == null ? null : String(actualDefault);
if (normalizedExpectedDefault !== normalizedActualDefault) {
if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) {
return true;
}
}
@ -678,6 +656,92 @@ module.exports = app => {
}
}
/**
* 获取同仓库共享 id 序列的全部分表的 MAX(id) 基线。
*
* 多表共用 id 契约:订单迁移到配送表时显式复制源 id,因此新分配的
* id 必须大于所有分表已占用的 id。
*
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<number>} 最大 id,无任何分表时返回 0。
*/
async getSharedIdBaseline(warehouseId) {
const tables = [
buildManagedTableName(warehouseId, 'current'),
buildManagedTableName(warehouseId, 'dispatch'),
buildManagedTableName(warehouseId, 'history'),
buildManagedTableName(warehouseId, 'outsourced'),
];
let existingTableSet = null;
try {
existingTableSet = new Set(await this.app.model.getQueryInterface().showAllTables());
} catch (error) {
existingTableSet = null;
}
let baseline = 0;
for (const relatedTable of tables) {
const exists = existingTableSet
? existingTableSet.has(relatedTable)
: await this.checkTableExists(relatedTable);
if (!exists) {
continue;
}
const [ rows ] = await this.app.model.query(
`SELECT COALESCE(MAX(id), 0) AS maxId FROM ${quoteIdentifier(relatedTable)}`
);
const maxId = Number(rows && rows[0] && rows[0].maxId || 0);
if (Number.isFinite(maxId) && maxId > baseline) {
baseline = maxId;
}
}
return baseline;
}
/**
* 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列
* 的全部分表(current/dispatch/history/outsourced)的 MAX(id)。
*
* 多表共用 id 契约:订单迁移到配送表时显式复制源 id。因此 current 表的
* 自增序列必须全局单调——新分配的 id 不能与任何分表已占用的 id 重叠。
* 若高 id 订单已迁走(current 表 MAX(id) 变小),表重建会把水位重置为
* current.MAX(id)+1,与配送表已占用的 id 重叠,后续迁移显式插入会撞主键。
* 所以水位基准必须取所有分表的最大 MAX(id)。
*
* @param {string} tableName 表名。
* @return {Promise<void>}
*/
async ensureAutoIncrementWatermark(tableName) {
const parsed = parseManagedTableName(tableName);
if (!parsed) {
return;
}
const baseline = await this.getSharedIdBaseline(parsed.warehouseId);
if (!Number.isFinite(baseline) || baseline <= 0) {
return;
}
const autoIncrement = await this.getTableAutoIncrement(tableName);
if (autoIncrement === null || autoIncrement > baseline) {
return;
}
// 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号,
// 导致修复后水位再次低于已分配 id(MySQL 不会把计数器降到当前已分配值以下,
// 余量仅作为并发窗口的缓冲)
const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN;
await this.app.model.query(`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`);
this.app.logger.warn(
`订单工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}`
);
}
/**
* 确保单个目标表与模型结构一致。
* @param {string} tableName 表名。
@ -695,29 +759,310 @@ module.exports = app => {
? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists)
: true;
if (!needsSync) {
return false;
}
if (!tableExists) {
await dynamicModel.sync({ force: false });
return true;
}
await this.assertManagedTableDataConstraints(tableName, modelType);
await this.alterManagedTableSchema(tableName, modelType, warehouseId, dynamicModel);
return true;
if (needsSync) {
await this.assertManagedTableDataConstraints(tableName, modelType);
await this.alterManagedTableSchema(tableName, modelType, warehouseId);
}
// 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位)
await this.ensureAutoIncrementWatermark(tableName);
return needsSync;
}
/**
* 读取表的当前 AUTO_INCREMENT 水位。
* @param {string} tableName 表名。
* @return {Promise<number|null>} 自增水位,非自增表返回 null。
*/
async getTableAutoIncrement(tableName) {
const [ rows ] = await this.app.model.query(
'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?',
{ replacements: [ tableName ] }
);
const rawValue = rows && rows[0] && rows[0].autoIncrement;
const value = Number(rawValue);
return Number.isFinite(value) ? value : null;
}
/**
* 获取仓库订单 id 序列表名。
*
* 每仓库一张序列表:id 自增发号,location 记录订单数据当前所在表位。
*
* @param {number|string} warehouseId 仓库ID。
* @return {string} 序列表名。
*/
getLocationSequenceTableName(warehouseId) {
return `wms_order_id_location_${warehouseId}`;
}
/**
* 确保仓库订单 id 序列表存在,并将其自增水位抬升到同仓库所有
* 订单分表 MAX(id) 之上(避开存量订单 id)。
*
* 注意:本方法可能执行 DDL(隐式提交),必须在事务外调用。
*
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<void>}
*/
async ensureLocationSequenceTable(warehouseId) {
const tableName = this.getLocationSequenceTableName(warehouseId);
// 进程内已初始化过则跳过:避免每次建单都重复 showAllTables + 分表 MAX 核对
if (this.locationTableReady.get(warehouseId)) {
return;
}
// 并发去重:同一仓库并发的 ensure 共享同一个初始化 Promise,
// 保证「建表 + 抬水位」只执行一次,其余调用等待完成后直接返回。
return await this.runModelInitializer(`init_seq_${warehouseId}`, async () => {
if (this.locationTableReady.get(warehouseId)) {
return;
}
// 先算基线再建表:建表语句直接携带正确水位。
// 消除「先建表(水位=1)再 ALTER」之间的发号窗口——否则窗口内
// 并发建单/多 worker 发号会拿到 1,与存量订单 id 冲突。
const baseline = await this.getSharedIdBaseline(warehouseId);
const safeTarget = baseline > 0 ? baseline + AUTO_INCREMENT_SAFE_MARGIN : 0;
const exists = await this.checkTableExists(tableName);
if (!exists) {
const autoIncrementClause = safeTarget > 0 ? ` AUTO_INCREMENT = ${safeTarget}` : '';
try {
await this.app.model.query(
`CREATE TABLE ${quoteIdentifier(tableName)} (
\`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
\`location\` VARCHAR(20) NOT NULL DEFAULT 'current',
PRIMARY KEY (\`id\`)
) ENGINE=InnoDB${autoIncrementClause} DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'`
);
this.app.logger.info(`创建订单 id 序列表成功: ${tableName}${safeTarget > 0 ? `, 初始水位=${safeTarget}` : ''}`);
} catch (createError) {
const errorCode = createError
&& ((createError.original && createError.original.code)
|| (createError.parent && createError.parent.code)
|| createError.code);
if (errorCode !== 'ER_TABLE_EXISTS') {
throw createError;
}
// 并发窗口:其他 worker 已建表,转入下方已存在核对分支
this.app.logger.warn(`订单 id 序列表 ${tableName} 已被并发创建,转入水位核对`);
}
}
// 表已存在(或刚被并发创建):核对并抬升水位
if (safeTarget > 0) {
const autoIncrement = await this.getTableAutoIncrement(tableName);
// ai 为 null(MariaDB 新建表/计数器未初始化)同样视为需要抬升
if (autoIncrement === null || autoIncrement <= baseline) {
await this.app.model.query(
`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`
);
this.app.logger.warn(
`订单 id 序列表 ${tableName} 水位抬升至 ${safeTarget}(分表最大 id=${baseline},原水位=${autoIncrement ?? 'null'})`
);
}
}
this.locationTableReady.set(warehouseId, true);
});
}
/**
* 启动初检:为当前库中已存在的订单分表仓库确保序列表存在且水位正确。
*
* 仅做「建表 + 水位抬升」,不迁移任何数据——存量订单的位置指针回填由
* `script/backfill-order-id-location.cjs` 脚本负责。单个仓库失败仅告警,
* 不影响其他仓库与服务启动。
*
* @return {Promise<number>} 完成初检的仓库数。
*/
async ensureAllLocationSequenceTables() {
const managedTableNames = await this.listManagedTableNames();
const warehouseIds = Array.from(new Set(
managedTableNames
.map(tableName => {
const parsed = parseManagedTableName(tableName);
return parsed ? parsed.warehouseId : null;
})
.filter(Boolean)
));
let checkedCount = 0;
for (const warehouseId of warehouseIds) {
try {
await this.ensureLocationSequenceTable(warehouseId);
checkedCount += 1;
} catch (error) {
this.app.logger.warn(`[启动初检] 仓库 ${warehouseId} 序列表初始化失败: ${error.message}`);
}
}
if (warehouseIds.length > 0) {
this.app.logger.info(`[启动初检] 订单 id 序列表初检完成: ${checkedCount}/${warehouseIds.length} 个仓库`);
}
return checkedCount;
}
/**
* 从仓库序列表分配全局订单 id(在调用方事务内执行,随事务回滚)。
*
* 调用方必须在事务外先调用 ensureLocationSequenceTable 完成建表。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @param {string} [location='current'] 初始位置(current/dispatch/history/outsourced)。
* @return {Promise<number>} 新分配的订单 id。
*/
async allocateOrderId(warehouseId, transaction = null, location = 'current') {
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
// 不允许在事务内隐式 DDL,交给调用方在事务外初始化
throw new Error(`订单 id 序列表 ${tableName} 不存在,请先调用 ensureLocationSequenceTable`);
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const queryResult = await this.app.model.query(
`INSERT INTO ${quoteIdentifier(tableName)} (\`location\`) VALUES (?)`,
{ replacements: [ location ], ...options }
);
// sequelize.query 对 INSERT 的返回形态随驱动不同,兼容解析:
// - mysql2: [ insertId, affectedRows ](首个元素是数字)
// - 其他包装: [{ insertId, affectedRows }, ...]
const raw = Array.isArray(queryResult) ? queryResult[0] : queryResult;
let insertId = 0;
if (typeof raw === 'number') {
insertId = raw;
} else if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
insertId = Number(raw.insertId || 0);
} else if (Array.isArray(raw) && raw.length > 0 && typeof raw[0] === 'number') {
insertId = Number(raw[0]);
}
if (!Number.isFinite(insertId) || insertId <= 0) {
throw new Error('订单 id 分配失败');
}
return insertId;
}
/**
* 更新订单在序列表中的位置指针(迁移时调用)。
*
* 存量订单(序列表无记录)以显式 id 补录;显式插入值大于当前水位时
* MySQL 会自动推进序列表自增,保证后续发号不与存量 id 冲突。
*
* @param {number|string} orderId 订单ID。
* @param {number|string} warehouseId 仓库ID。
* @param {string} location 新位置。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<void>}
*/
async updateOrderLocation(orderId, warehouseId, location, transaction = null) {
const tableName = this.getLocationSequenceTableName(warehouseId);
const options = transaction ? { transaction } : {};
await this.app.model.query(
`INSERT INTO ${quoteIdentifier(tableName)} (\`id\`, \`location\`) VALUES (?, ?) ON DUPLICATE KEY UPDATE \`location\` = VALUES(\`location\`)`,
{ replacements: [ Number(orderId), location ], ...options }
);
}
/**
* 查询单个订单当前所在表位。
*
* @param {number|string} orderId 订单ID。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<string|null>} 位置(current/dispatch/history/outsourced),
* 无记录返回 null(存量订单未回填)。
*/
async getOrderLocation(orderId, warehouseId, transaction = null) {
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
return null;
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const [ rows ] = await this.app.model.query(
`SELECT \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` = ? LIMIT 1`,
{ replacements: [ Number(orderId) ], ...options }
);
return rows && rows[0] ? String(rows[0].location) : null;
}
/**
* 批量查询订单当前所在表位。
*
* @param {Array<number|string>} orderIds 订单ID列表。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<Map<number, string>>} orderId → location;
* 无记录的订单不在 Map 中(存量订单未回填)。
*/
async getOrderLocations(orderIds, warehouseId, transaction = null) {
const result = new Map();
const normalizedIds = Array.from(new Set(
(Array.isArray(orderIds) ? orderIds : [ orderIds ])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0)
));
if (normalizedIds.length === 0) {
return result;
}
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
return result;
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const placeholders = normalizedIds.map(() => '?').join(',');
const [ rows ] = await this.app.model.query(
`SELECT \`id\`, \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` IN (${placeholders})`,
{ replacements: normalizedIds, ...options }
);
for (const row of rows || []) {
result.set(Number(row.id), String(row.location));
}
return result;
}
/**
* 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。
*
* 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明
* 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为
* MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史
* 低值,与配送表已复制的 id 重叠,导致后续迁移主键冲突。
*
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} dynamicModel 已构建的动态模型(用于索引同步)。
* @return {Promise<void>}
*/
async alterManagedTableSchema(tableName, type, warehouseId, dynamicModel) {
async alterManagedTableSchema(tableName, type, warehouseId) {
const queryInterface = this.app.model.getQueryInterface();
const sequelize = this.app.model;
const actualColumns = await queryInterface.describeTable(tableName);
@ -727,17 +1072,27 @@ module.exports = app => {
const expectedColumnNames = Object.keys(expectedAttributes);
const clauses = [];
// ADD 新增列 / CHANGE 变更列
// ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE——对 AUTO_INCREMENT
// 列重新声明列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为
// MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史低值,
// 与配送表已复制的 id 重叠,导致后续迁移主键冲突。
for (const columnName of expectedColumnNames) {
const columnDef = buildColumnLine(columnName, expectedAttributes[columnName]);
const expectedAttribute = expectedAttributes[columnName];
if (columnName === 'id') {
continue;
}
const columnDef = buildColumnLine(columnName, expectedAttribute);
if (!actualColumnNames.has(columnName)) {
clauses.push(`ADD COLUMN ${columnDef}`);
} else {
} else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) {
clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`);
}
}
// DROP 多余列(现有表有但期望模型没有的列)
// DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP)
const expectedColumnSet = new Set(expectedColumnNames);
for (const columnName of actualColumnNames) {
if (!expectedColumnSet.has(columnName)) {
@ -745,12 +1100,39 @@ module.exports = app => {
}
}
const previousAutoIncrement = await this.getTableAutoIncrement(tableName);
if (clauses.length > 0) {
await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`);
}
// 索引同步仍委托 Sequelize sync({ alter: true }) 处理(仅触发索引差异)
await dynamicModel.sync({ alter: true });
// 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位
const currentAutoIncrement = await this.getTableAutoIncrement(tableName);
if (previousAutoIncrement !== null
&& currentAutoIncrement !== null
&& currentAutoIncrement < previousAutoIncrement) {
await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`);
this.app.logger.warn(
`订单工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}`
);
}
// 索引同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置自增水位,
// 且无法可靠检测 AUTO_INCREMENT 属性差异。改为仅补齐缺失索引,不重建、不删除已有索引。
const existingIndexNames = new Set((await queryInterface.showIndex(tableName))
.map(index => index.Key_name || index.name || '')
.filter(Boolean));
for (const indexDef of this.getIndexes(warehouseId, type)) {
if (existingIndexNames.has(indexDef.name)) {
continue;
}
await queryInterface.addIndex(tableName, indexDef.fields, {
name: indexDef.name,
unique: Boolean(indexDef.unique),
});
}
}
/**
@ -781,7 +1163,8 @@ module.exports = app => {
const tableName = this.generateTableName(warehouseId, modelType);
const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName);
await dynamicModel.sync({ alter: true });
// 统一走差异检测 + 自增水位保护的同步路径,不再使用 sync({ alter: true })
await this.ensureManagedTableSchema(tableName, modelType, warehouseId, dynamicModel);
this.app.logger.info(`创建/同步物理表成功: ${tableName}`);
}

View File

@ -7,6 +7,16 @@ const MANAGED_TYPES = Object.freeze({
OUTSOURCED: 'outsourced',
});
/**
* 自增水位修复时的安全余量。
*
* 修复水位时会读取各分表 MAX(id) 作为基准,但读取与 SET 之间存在并发窗口:
* 其他请求可能正在抢号分配更大的 id。若 SET 值刚好是 MAX(id)+1,并发插入
* 提交后表内 max 可能再次超过水位。预留余量(跳过若干 id)可避免该竞态,
* BIGINT 空间下跳过几十个 id 无实际影响。
*/
const AUTO_INCREMENT_SAFE_MARGIN = 50;
const TABLE_PATTERNS = Object.freeze([
{
type: MANAGED_TYPES.DISPATCH,
@ -210,7 +220,10 @@ function formatDefaultValue(defaultValue) {
}
if (defaultValue && typeof defaultValue.toSql === 'function') {
return defaultValue.toSql();
const rawSql = String(defaultValue.toSql());
// Sequelize.NOW 的 toSql() 返回 'NOW',MySQL/MariaDB 的 DATETIME 列
// 默认值必须写成 CURRENT_TIMESTAMP,否则生成 DEFAULT NOW 非法语法
return rawSql.trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : rawSql;
}
if (typeof defaultValue === 'string') {
@ -230,12 +243,11 @@ function formatDefaultValue(defaultValue) {
}
/**
* 将 Sequelize 属性定义转换为 DDL 列片段。
* @param {string} columnName 列名。
* 生成属性的类型 SQL 片段。
* @param {Object} attribute Sequelize 属性定义。
* @return {string} DDL 列片段。
* @return {string} 类型 SQL 片段。
*/
function buildColumnLine(columnName, attribute) {
function buildColumnTypeSql(attribute) {
let typeSql;
if (attribute.type && Array.isArray(attribute.type.values)) {
@ -249,6 +261,129 @@ function buildColumnLine(columnName, attribute) {
typeSql = String(attribute.type || '');
}
// 无 dialect 绑定时 DataTypes.DATE 序列化为 'DATE',
// 但 MySQL 实际列类型是 DATETIME;DDL 若输出 DATE 会把时间部分截断
if (typeSql && String(typeSql).trim().toUpperCase() === 'DATE') {
typeSql = 'DATETIME';
}
return typeSql;
}
/**
* 归一化列类型 SQL,用于模型定义与实际表结构的语义比对。
*
* 消除不会影响语义的差异,避免比对恒真而反复执行 ALTER:
* - INTEGER 与 INT 在 MySQL 中是同义词;
* - 整型 display width(如 BIGINT(20)、INT(11))不影响语义,
* 且 MySQL 8.0.19+ 的 information_schema 不再返回 display width;
* - 大小写与空格差异。
*
* @param {string} sql 类型 SQL。
* @return {string} 归一化后的类型 SQL。
*/
function normalizeColumnTypeSql(sql) {
let normalized = String(sql || '')
.trim()
.replace(/\s+/g, ' ')
.toUpperCase();
normalized = normalized.replace(/^INTEGER\b/, 'INT');
normalized = normalized.replace(/^(TINYINT|SMALLINT|MEDIUMINT|INT|BIGINT)\s*\(\s*\d+\s*\)/, '$1');
// Sequelize 无 dialect 绑定时 DATE 序列化为 'DATE',而 MySQL 实际列类型为 DATETIME
if (normalized === 'DATE') {
normalized = 'DATETIME';
}
// 删除逗号两侧空格(ENUM 值列表、DECIMAL(18, 2) 等)
normalized = normalized.replace(/\s*,\s*/g, ',');
return normalized;
}
/**
* 判断列定义是否与模型期望存在语义差异。
*
* 与 needsTableSchemaSync / alterManagedTableSchema 共用同一套比较规则,
* 保证“判定需要同步”与“生成 ALTER 子句”不会漂移。
*
* @param {string} columnName 列名。
* @param {Object} expectedAttribute 模型期望的属性定义。
* @param {Object} actualColumn describeTable 返回的实际列定义。
* @return {boolean} 是否存在语义差异。
*/
function isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumn) {
const expectedType = normalizeColumnTypeSql(buildColumnTypeSql(expectedAttribute));
const actualType = normalizeColumnTypeSql(actualColumn && (actualColumn.type || actualColumn.Type) || '');
if (expectedType && actualType && expectedType !== actualType) {
return true;
}
// 主键/自增列在建表时由 Sequelize 自动补 NOT NULL,
// 即使模型定义未显式声明 allowNull: false,实际列也是 NOT NULL
const expectedAllowNull = expectedAttribute.primaryKey || expectedAttribute.autoIncrement
? false
: expectedAttribute.allowNull !== false;
const actualAllowNull = (actualColumn && actualColumn.allowNull) !== false;
if (expectedAllowNull !== actualAllowNull) {
return true;
}
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedAttribute, 'defaultValue')
? expectedAttribute.defaultValue
: undefined;
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn || {}, 'defaultValue')
? actualColumn.defaultValue
: undefined;
// Sequelize.literal(如 CURRENT_TIMESTAMP)提取其原始表达式参与比较;
// Sequelize.NOW 的 val 为 'NOW',与表内实际 DEFAULT CURRENT_TIMESTAMP 归一
const extractDefaultValue = value => {
if (value && typeof value === 'object' && typeof value.val === 'string') {
return String(value.val).trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : value.val;
}
return value;
};
const normalizedExpectedDefault = extractDefaultValue(expectedDefault) == null
? null
: String(extractDefaultValue(expectedDefault));
const normalizedActualDefault = extractDefaultValue(actualDefault) == null
? null
: String(extractDefaultValue(actualDefault));
if (normalizedExpectedDefault === normalizedActualDefault) {
return false;
}
// 数字默认值允许不同文本表示(如 '0' 与 '0.00'),只要数值相等即视为一致
if (normalizedExpectedDefault !== null && normalizedActualDefault !== null) {
const expectedNumber = Number(normalizedExpectedDefault);
const actualNumber = Number(normalizedActualDefault);
if (normalizedExpectedDefault !== ''
&& normalizedActualDefault !== ''
&& Number.isFinite(expectedNumber)
&& Number.isFinite(actualNumber)
&& expectedNumber === actualNumber) {
return false;
}
}
return true;
}
/**
* 将 Sequelize 属性定义转换为 DDL 列片段。
* @param {string} columnName 列名。
* @param {Object} attribute Sequelize 属性定义。
* @return {string} DDL 列片段。
*/
function buildColumnLine(columnName, attribute) {
const typeSql = buildColumnTypeSql(attribute);
const parts = [ `\`${columnName}\``, typeSql ];
if (attribute.allowNull === false) {
@ -283,6 +418,12 @@ function buildTableAttributes(app, type) {
const modelType = normalizeManagedType(type);
const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes);
// 分表 id 统一由仓库序列表显式分配,分表自身不再携带自增序列。
// 保留两套发号序列(分表自增 + 序列表)会在降级等场景产生区间重叠的冲突 id,
// 这里从模型层移除 autoIncrement:新建分表不再带 AUTO_INCREMENT;
// 已有分表结构保持不变(不执行任何 id 列变更),显式 id 插入不受影响。
attributes.id = { ...attributes.id, autoIncrement: false };
if (isDispatchType(modelType)) {
const { ENUM } = app.Sequelize;
attributes.dispatch_lane = {
@ -513,6 +654,7 @@ function parseManagedTableName(tableName) {
module.exports = {
MANAGED_TYPES,
AUTO_INCREMENT_SAFE_MARGIN,
normalizeManagedType,
isDispatchType,
isHistoryType,
@ -525,6 +667,9 @@ module.exports = {
buildTableComment,
buildTableOptions,
buildIndexOptions,
buildColumnTypeSql,
normalizeColumnTypeSql,
isColumnDefinitionDifferent,
buildColumnLine,
buildColumnLines,
buildIndexLines,

View File

@ -5,6 +5,20 @@ const {
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
} = require('../lib/warehouse_shard_guard');
const {
isColumnDefinitionDifferent,
buildColumnLine,
AUTO_INCREMENT_SAFE_MARGIN,
} = require('./order_delivery_table_schema');
/**
* 转义 SQL 标识符。
* @param {string} identifier 标识符。
* @return {string} 转义后的标识符。
*/
function quoteIdentifier(identifier) {
return `\`${String(identifier).replace(/`/g, '``')}\``;
}
/**
* 克隆模型属性定义。
@ -266,7 +280,11 @@ module.exports = app => {
getTableAttributes(type) {
const mainModel = this.app.model.OrderItems;
const attributes = cloneAttributes(mainModel && mainModel.rawAttributes);
// 模型 timestamps:true 会向 rawAttributes 注入 createdAt/updatedAt
// (与显式定义的 created_at/updated_at 指向同一列),结构对齐时会被
// 误判为缺失列而 ADD COLUMN,导致重复列与无默认值报错,剔除这两个注入属性。
delete attributes.createdAt;
delete attributes.updatedAt;
// 保留 id 字段的 autoIncrement,与 order_delivery_factory 行为一致,
// 确保分表 wms_order_items_{warehouseId} 的 bulkCreate 能正常自增生成 id
@ -389,33 +407,7 @@ module.exports = app => {
}
for (const columnName of expectedAttributeNames) {
const expectedColumn = expectedAttributes[columnName];
const actualColumn = tables[columnName] || {};
const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function'
? expectedColumn.type.toSql().toLowerCase()
: String(expectedColumn.type || '').toLowerCase();
const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase();
const expectedAllowNull = expectedColumn.allowNull !== false;
const actualAllowNull = actualColumn.allowNull !== false;
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue')
? expectedColumn.defaultValue
: undefined;
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue')
? actualColumn.defaultValue
: undefined;
if (expectedType && actualType && expectedType !== actualType) {
return true;
}
if (expectedAllowNull !== actualAllowNull) {
return true;
}
const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault);
const normalizedActualDefault = actualDefault == null ? null : String(actualDefault);
if (normalizedExpectedDefault !== normalizedActualDefault) {
if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) {
return true;
}
}
@ -438,6 +430,170 @@ module.exports = app => {
return false;
}
/**
* 读取表的当前 AUTO_INCREMENT 水位。
* @param {string} tableName 表名。
* @return {Promise<number|null>} 自增水位,非自增表返回 null。
*/
async getTableAutoIncrement(tableName) {
const [ rows ] = await this.app.model.query(
'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?',
{ replacements: [ tableName ] }
);
const rawValue = rows && rows[0] && rows[0].autoIncrement;
const value = Number(rawValue);
return Number.isFinite(value) ? value : null;
}
/**
* 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列
* 的全部分表(current/dispatch/history)的 MAX(id)。
*
* 明细迁移到配送明细表时同样显式复制源 id,因此 current 明细表的
* 自增序列必须全局单调,水位基准取所有分表的最大 MAX(id)。
*
* @param {string} tableName 表名。
* @return {Promise<void>}
*/
async ensureAutoIncrementWatermark(tableName) {
const sequelize = this.app.model;
const matched = /^wms_order_items_(\d+)(?:_(dispatch|history))?$/.exec(tableName);
const relatedTables = matched
? [
tableName,
`wms_order_items_${matched[1]}`,
`wms_order_items_${matched[1]}_dispatch`,
`wms_order_items_${matched[1]}_history`,
]
: [ tableName ];
let existingTableSet = null;
try {
existingTableSet = new Set(await sequelize.getQueryInterface().showAllTables());
} catch (error) {
existingTableSet = null;
}
let baseline = 0;
for (const relatedTable of new Set(relatedTables)) {
const exists = existingTableSet
? existingTableSet.has(relatedTable)
: await this.checkTableExists(relatedTable);
if (!exists) {
continue;
}
const [ rows ] = await sequelize.query(
`SELECT COALESCE(MAX(id), 0) AS maxId FROM \`${relatedTable}\``
);
const maxId = Number(rows && rows[0] && rows[0].maxId || 0);
if (Number.isFinite(maxId) && maxId > baseline) {
baseline = maxId;
}
}
if (!Number.isFinite(baseline) || baseline <= 0) {
return;
}
const autoIncrement = await this.getTableAutoIncrement(tableName);
if (autoIncrement === null || autoIncrement > baseline) {
return;
}
// 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号
const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN;
await sequelize.query(`ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${safeTarget}`);
this.app.logger.warn(
`订单商品工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}`
);
}
/**
* 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。
*
* 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明
* 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为
* MAX(id)+1,与 dispatch/history 已复制的 id 重叠,导致后续迁移主键冲突。
* 索引同步仅补齐缺失索引,不重建、不删除已有索引。
*
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<void>}
*/
async alterManagedTableSchema(tableName, type, warehouseId) {
const sequelize = this.app.model;
const queryInterface = sequelize.getQueryInterface();
const actualColumns = await queryInterface.describeTable(tableName);
const expectedAttributes = this.getTableAttributes(type);
const quotedTableName = quoteIdentifier(tableName);
const actualColumnNames = new Set(Object.keys(actualColumns || {}));
const expectedColumnNames = Object.keys(expectedAttributes);
const clauses = [];
// ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE,避免重建表重置自增水位
for (const columnName of expectedColumnNames) {
const expectedAttribute = expectedAttributes[columnName];
if (columnName === 'id') {
continue;
}
const columnDef = buildColumnLine(columnName, expectedAttribute);
if (!actualColumnNames.has(columnName)) {
clauses.push(`ADD COLUMN ${columnDef}`);
} else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) {
clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`);
}
}
// DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP)
const expectedColumnSet = new Set(expectedColumnNames);
for (const columnName of actualColumnNames) {
if (!expectedColumnSet.has(columnName)) {
clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`);
}
}
const previousAutoIncrement = await this.getTableAutoIncrement(tableName);
if (clauses.length > 0) {
await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`);
}
// 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位
const currentAutoIncrement = await this.getTableAutoIncrement(tableName);
if (previousAutoIncrement !== null
&& currentAutoIncrement !== null
&& currentAutoIncrement < previousAutoIncrement) {
await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`);
this.app.logger.warn(
`订单商品工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}`
);
}
// 仅补齐缺失索引,不重建、不删除已有索引
const existingIndexNames = new Set((await queryInterface.showIndex(tableName))
.map(index => index.Key_name || index.name || '')
.filter(Boolean));
for (const indexDef of this.generateIndexes(warehouseId)) {
if (existingIndexNames.has(indexDef.name)) {
continue;
}
await queryInterface.addIndex(tableName, indexDef.fields, {
name: indexDef.name,
unique: Boolean(indexDef.unique),
});
}
}
/**
* 确保目标表与模型结构一致。
* @param {string} tableName 表名。
@ -453,12 +609,21 @@ module.exports = app => {
? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists)
: true;
if (!needsSync) {
return false;
if (!tableExists) {
await dynamicModel.sync({ force: false });
return true;
}
await dynamicModel.sync({ alter: true });
return true;
if (needsSync) {
// 结构同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置
// 自增水位(与 dispatch/history 已复制 id 重叠,后续迁移主键冲突)。
// 改为手工差异 ALTER + 补齐索引,并跳过 id 列 CHANGE。
await this.alterManagedTableSchema(tableName, type, warehouseId);
}
// 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位)
await this.ensureAutoIncrementWatermark(tableName);
return needsSync;
}
/**
@ -470,7 +635,8 @@ module.exports = app => {
const tableName = this.generateTableName(warehouseId, type);
const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
await dynamicModel.sync({ alter: true });
// 统一走差异检测 + 自增水位保护的同步路径,不再直接 sync({ alter: true })
await this.ensureManagedTableSchema(tableName, type, warehouseId, dynamicModel);
this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`);
}

View File

@ -4,6 +4,9 @@ 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 分钟
const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:history';
const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录
const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天
/**
* 将本次执行日志写入缓存。
@ -23,6 +26,36 @@ async function writeExecutionLogToCache(ctx, logEntry) {
}
}
/**
* 将本次执行日志追加到历史记录缓存(保留最近 N 次)。
*
* 用于不翻日志文件也能观察定时任务每轮执行情况(selected/created/status/error),
* 便于排查「订单满足迁移条件但迟迟未切表」类问题。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} logEntry 日志条目。
* @return {Promise<void>} 无返回值。
*/
async function appendExecutionHistory(ctx, logEntry) {
try {
if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') {
return;
}
const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY);
const history = Array.isArray(rawHistory) ? rawHistory : [];
history.unshift(logEntry);
await ctx.app.setCacheAsync(
EXECUTION_LOG_HISTORY_CACHE_KEY,
history.slice(0, EXECUTION_LOG_HISTORY_MAX),
EXECUTION_LOG_HISTORY_TTL
);
} catch (err) {
// 历史日志写入失败不影响主流程
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行历史缓存失败: ${err.message}`);
}
}
/**
* 提取错误详情,方便定位问题位置。
*
@ -139,6 +172,7 @@ module.exports = {
warehouse_ids: result ? result.warehouseIds : [],
};
await writeExecutionLogToCache(ctx, logEntry);
ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY}`);
await appendExecutionHistory(ctx, logEntry);
ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY}`);
},
};

View File

@ -538,7 +538,7 @@ class InboxFunctionsService extends Service {
// ========== 第一步:运单号精确匹配 ==========
const exactExpress = await ctx.model.OrderExpress.findOne({
attributes: [ 'delivery_order_code' ],
attributes: [ 'delivery_order_code', 'order_id' ],
where: {
waybill_code: keyword,
store_id: storeId,
@ -548,11 +548,38 @@ class InboxFunctionsService extends Service {
});
if (exactExpress && exactExpress.delivery_order_code) {
// 用运单关联的发货单号精确查找订单
found = await findInDeliveryTables({
store_id: storeId,
delivery_order_code: exactExpress.delivery_order_code,
});
// 运单精确匹配:先通过序列表定位订单所在分表,命中只查一张表;
// 未命中(存量订单无指针)回退三表按单号遍历
const exactOrderId = Number(exactExpress.order_id || 0);
if (exactOrderId > 0 && factory && typeof factory.getOrderLocation === 'function') {
try {
const locatedAt = await factory.getOrderLocation(exactOrderId, warehouseId);
if (locatedAt) {
const locatedCfg = tableConfigs.find(cfg => cfg.key === locatedAt);
if (locatedCfg) {
const locatedModel = await locatedCfg.getModel(factory, warehouseId);
if (locatedModel) {
const locatedRow = await locatedModel.findOne({
attributes,
where: { id: exactOrderId, store_id: storeId },
raw: true,
});
if (locatedRow) {
found = { table: locatedCfg.key, table_label: locatedCfg.label, ...locatedRow };
}
}
}
}
} catch (_err) { /* 定位失败,降级三表遍历 */ }
}
if (!found) {
// 用运单关联的发货单号精确查找订单
found = await findInDeliveryTables({
store_id: storeId,
delivery_order_code: exactExpress.delivery_order_code,
});
}
}
// ========== 第二步:运单未命中 → 模糊搜索发货单号 / 平台单号 ==========
@ -3054,16 +3081,32 @@ class InboxFunctionsService extends Service {
const orderMissingWbs = [];
for (const e of validList) {
// 第二步:查订单行(当前表 → 历史表 → 配送表),取波次信息
// 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历)
let orderRow = null;
const factory = ctx.model.OrderDeliveryFactory;
const tableGetters = [
(f, wid) => f.getCurrentModel(wid),
(f, wid) => f.getHistoryModel(wid),
(f, wid) => f.getDispatchModel(wid),
{ location: 'current', getModel: (f, wid) => f.getCurrentModel(wid) },
{ location: 'history', getModel: (f, wid) => f.getHistoryModel(wid) },
{ location: 'dispatch', getModel: (f, wid) => f.getDispatchModel(wid) },
];
for (const getModel of tableGetters) {
let location = null;
try {
if (factory && typeof factory.getOrderLocation === 'function') {
location = await factory.getOrderLocation(e.order_id, warehouseId);
}
} catch (err) { /* ignore */ }
const orderedGetters = location
? [
...tableGetters.filter(entry => entry.location === location),
...tableGetters.filter(entry => entry.location !== location),
]
: tableGetters;
for (const entry of orderedGetters) {
try {
const model = await getModel(ctx.model.OrderDeliveryFactory, warehouseId);
const model = await entry.getModel(factory, warehouseId);
if (!model) continue;
orderRow = await model.findOne({
attributes: [ 'id', 'wave_id', 'wave_no', 'pack_status' ],
@ -3831,6 +3874,24 @@ class InboxFunctionsService extends Service {
};
}
// 群类型权限过滤:按当前群的活跃分组校验函数可用性,
// 防止货主群调用快递群专属函数(如 handleExpressFeedback)等越权调用。
// 无 groups 服务的场景(单元测试直接实例化)跳过校验,由调用方保证上下文。
const groupsSvc = this.ctx.service && this.ctx.service.inbox && this.ctx.service.inbox.groups;
if (groupsSvc && typeof groupsSvc.isFunctionAvailable === 'function') {
const activeGroups = groupsSvc.resolveActiveGroups();
if (!groupsSvc.isFunctionAvailable(def, activeGroups)) {
this.ctx.logger.warn(
`[inbox functions] 越权调用被拦截: ${name} ` +
`groups=${(def.groups || []).join(',')} active=${activeGroups.join(',')}`
);
return {
success: false,
error: `函数 ${name} 在当前群类型下不可用,请通过对应类型的群发起`,
};
}
}
try {
const result = await def.handler(params);
return result && typeof result === 'object' ? result : { success: true, data: result };

View File

@ -145,20 +145,61 @@ class InboxReceiverService extends Service {
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
// 自动登记群(幂等 upsert)
// 自动登记群:优先按 (group_id, warehouse_id) 幂等 upsert。
// 群ID不变、仅名称变化时只更新名称,不重复建群。
const groupName = String(data.group_name || '').trim();
if (groupName) {
try {
await ctx.model.InboxGroup.findOrCreate({
where: { group_name: groupName, warehouse_id: warehouseId },
defaults: {
group_id: extGroupId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
},
});
if (extGroupId) {
const group = await ctx.model.InboxGroup.findOne({
where: { group_id: extGroupId, warehouse_id: warehouseId },
});
if (group) {
// 群已存在:名称变化时更新名称,不新建
if (group.group_name !== groupName) {
const oldName = group.group_name;
await group.update({ group_name: groupName });
ctx.logger.info(
`[inbox] 群名称已更新 group_id=${extGroupId}: ${oldName} → ${groupName}`
);
}
} else {
// 群ID不存在:优先兼容同名群回填群ID;都没有才新建。
// 注意表上已无 (group_name, warehouse_id) 唯一索引,名称维度不再保证唯一。
const byName = await ctx.model.InboxGroup.findOne({
where: { group_name: groupName, warehouse_id: warehouseId },
});
if (byName) {
await byName.update({ group_id: extGroupId });
ctx.logger.info(
`[inbox] 同名群回填群ID group_id=${extGroupId} name=${groupName}`
);
} else {
await ctx.model.InboxGroup.create({
group_name: groupName,
group_id: extGroupId,
warehouse_id: warehouseId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
});
}
}
} else {
// 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容)
await ctx.model.InboxGroup.findOrCreate({
where: { group_name: groupName, warehouse_id: warehouseId },
defaults: {
group_id: null,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
},
});
}
} catch (groupErr) {
ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`);
}

View File

@ -34,7 +34,13 @@ class deliveryorderServer extends MainService {
const info = this.getInfo();
const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, info, 'QM');
if (res.success) {
return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode });
return this.success(res.message, {
createTime: this.app.formatDate(new Date()),
// addOrder 成功返回 data.orderId,兼容历史字段 deliveryOrderId
deliveryOrderId: (res.data && (res.data.orderId || res.data.deliveryOrderId)) || '',
warehouseCode: info.warehouseCode,
logisticsCode: (res.data && res.data.logisticsCode) || '',
});
}
return this.fail(res.message, { createTime: this.app.formatDate(new Date()) });
}

View File

@ -163,10 +163,34 @@ class DeliveryOrderService extends OrderBaseService {
{ label: 'current', getModel: () => factory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => factory.getHistoryModel(warehouseId) },
];
const remainingIds = new Set(orderIds.map(String));
// 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历
const normalizedOrderIds = orderIds.map(Number).filter(n => Number.isFinite(n) && n > 0);
let locationMap = new Map();
try {
if (typeof factory.getOrderLocations === 'function') {
locationMap = await factory.getOrderLocations(normalizedOrderIds, warehouseId);
}
} catch (e) {
dbg(` locationMap ERROR: ${e.message}`);
}
dbg(` locationMap size: ${locationMap.size}`);
const idsByLabel = { dispatch: [], current: [], history: [] };
const unresolvedIds = [];
for (const id of normalizedOrderIds) {
const location = locationMap.get(id);
if (location && idsByLabel[location]) {
idsByLabel[location].push(id);
} else {
unresolvedIds.push(id);
}
}
for (const entry of tableDefs) {
if (remainingIds.size === 0) break;
dbg(` trying table: ${entry.label}, remainingIds=[${[ ...remainingIds ].join(',')}]`);
const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ];
if (targetIds.length === 0) continue;
dbg(` trying table: ${entry.label}, targetIds=[${targetIds.join(',')}]`);
try {
const model = await entry.getModel();
dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`);
@ -174,7 +198,7 @@ class DeliveryOrderService extends OrderBaseService {
dbg(` ${entry.label} model invalid, skip`);
continue;
}
const whereClause = { id: [ ...remainingIds ].map(Number) };
const whereClause = { id: targetIds };
dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`);
const rows = await model.findAll({
attributes: [
@ -193,7 +217,7 @@ class DeliveryOrderService extends OrderBaseService {
for (const r of (rows || [])) {
dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`);
const rid = String(r.id);
if (!orderMap.has(rid)) { orderMap.set(rid, r); remainingIds.delete(rid); }
if (!orderMap.has(rid)) { orderMap.set(rid, r); }
}
} catch (e) {
dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`);
@ -329,33 +353,58 @@ class DeliveryOrderService extends OrderBaseService {
return [];
}
const attributes = [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
];
const tableOrders = [
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
];
// 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历
const normalizedIds = [ ...new Set((orderIds || []).map(Number).filter(id => Number.isFinite(id) && id > 0)) ];
let locationMap = new Map();
try {
if (typeof orderDeliveryFactory.getOrderLocations === 'function') {
locationMap = await orderDeliveryFactory.getOrderLocations(normalizedIds, warehouseId);
}
} catch (_err) {
locationMap = new Map();
}
const idsByLabel = { dispatch: [], current: [], history: [] };
const unresolvedIds = [];
for (const id of normalizedIds) {
const location = locationMap.get(id);
if (location && idsByLabel[location]) {
idsByLabel[location].push(id);
} else {
unresolvedIds.push(id);
}
}
const resultMap = new Map();
const remainingIds = new Set(orderIds.map(id => String(id)));
for (const entry of tableOrders) {
if (remainingIds.size === 0) break;
const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ];
if (targetIds.length === 0) continue;
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') continue;
const rows = await model.findAll({
attributes: [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
],
attributes,
where: {
id: { [Op.in]: [ ...remainingIds ].map(Number) },
id: { [Op.in]: targetIds },
},
raw: true,
});
@ -364,7 +413,6 @@ class DeliveryOrderService extends OrderBaseService {
const rid = String(r.id);
if (!resultMap.has(rid)) {
resultMap.set(rid, r);
remainingIds.delete(rid);
}
}
} catch (_err) {

View File

@ -531,6 +531,139 @@ function reverseInferAddress(parsed) {
return { ...parsed, province: province || '', city: city || '', area: area || '' };
}
/**
* 从模型返回的文本中截取 JSON 片段(对象或数组),并清理 markdown 代码块标记。
* 对象取第一个 { 到最后一个 },数组取第一个 [ 到最后一个 ],自动忽略前后多余文本。
*
* @param {string} text 模型原始返回文本。
* @return {string} 截取后的 JSON 字符串;无有效片段时返回原文 trim。
*/
function extractJsonBlock(text) {
if (!text) return '';
let s = String(text).trim();
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
const firstBrace = s.indexOf('{');
const firstBracket = s.indexOf('[');
let start = -1;
if (firstBrace === -1) {
start = firstBracket;
} else if (firstBracket === -1) {
start = firstBrace;
} else {
start = Math.min(firstBrace, firstBracket);
}
const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));
if (start === -1 || end === -1 || end <= start) {
return s;
}
return s.slice(start, end + 1);
}
const ADDRESS_PARSE_FIELDS = [
'province', 'city', 'area', 'town', 'detailAddress', 'name', 'mobile',
];
/**
* 从任意文本(如思维链模型的 reasoning_content)中提取地址解析字段,
* 支持 "province":"xx"、province=xx、province:xx 等常见写法。
*
* @param {string} text 原始文本。
* @return {Object|null} 提取到的字段对象;一个字段都没提取到则返回 null。
*/
function salvageFieldsFromText(text) {
if (!text) return null;
const src = String(text);
const out = {};
let foundAny = false;
for (const field of ADDRESS_PARSE_FIELDS) {
const patterns = [
new RegExp(`["']?${field}["']?\\s*[::=]\\s*["']([^"']{0,80})["']`, 'i'),
new RegExp(`["']?${field}["']?\\s*[::=]\\s*([^\\s,,;;\\n"']{0,80})`, 'i'),
];
for (const re of patterns) {
const m = src.match(re);
if (m && m[1] && m[1].trim()) {
out[field] = m[1].trim();
foundAny = true;
break;
}
}
}
return foundAny ? out : null;
}
/**
* 清洗手机号:仅保留合法 11 位大陆手机号;兜底提取的脏数据(如整段地址)置空。
*
* @param {*} mobile 原始手机号字段。
* @return {string} 合法手机号或空字符串。
*/
function sanitizeMobile(mobile) {
const m = String(mobile || '').trim();
return /^1[3-9]\d{9}$/.test(m) ? m : '';
}
/**
* 清洗收件人姓名:过滤过长的字符串与明显混入地址信息的脏数据。
*
* @param {*} name 原始姓名字段。
* @return {string} 合法姓名或空字符串。
*/
function sanitizeName(name) {
const n = String(name || '').trim();
if (!n || n.length > 20) return '';
if (/[省市县区镇街道路号村组栋座楼室单元乡]/.test(n)) return '';
return n;
}
/**
* 地址解析最终兜底:AI 解析与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序
* 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。
*
* @param {string} text 原始地址字符串。
* @return {Object} { province, city, area, town },识别不到的字段为空字符串。
*/
function extractAddressByRegex(text) {
const src = String(text || '');
const result = { province: '', city: '', area: '', town: '' };
if (!src) return result;
// 省份:全称与简称按长度降序匹配,避免"河北/河南"等前缀误配
const shorten = p => p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, '');
const provincePattern = PROVINCE_LIST
.reduce((list, p) => {
const short = shorten(p);
if (short !== p) list.push(short);
list.push(p);
return list;
}, [])
.sort((a, b) => b.length - a.length)
.join('|');
const provinceMatch = src.match(new RegExp(`(${provincePattern})`));
if (!provinceMatch) return result;
const provinceToken = provinceMatch[1];
const fullProvince = PROVINCE_LIST.find(p => p.startsWith(provinceToken));
result.province = fullProvince || provinceToken;
const rest = src.slice(provinceMatch.index + provinceToken.length);
const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/);
if (!cityMatch) return result;
result.city = cityMatch[1];
const restAfterCity = rest.slice(cityMatch.index + cityMatch[1].length);
const areaMatch = restAfterCity.match(/([\u4e00-\u9fa5]{2,10}?(?:自治县|区|县|市))/);
if (!areaMatch) return result;
result.area = areaMatch[1];
const restAfterArea = restAfterCity.slice(areaMatch.index + areaMatch[1].length);
const townMatch = restAfterArea.match(/([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/);
if (townMatch) {
result.town = townMatch[1];
}
return result;
}
class PendingOrderService extends OrderBaseService {
/**
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
@ -3149,7 +3282,12 @@ class PendingOrderService extends OrderBaseService {
}
}
const newOrder = await model.create(newOrderData);
// 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增,
// 避免分表自增与序列表发号区间重叠产生冲突 id
await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseId);
const allocatedOrderId = await this.ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseId, null, 'current');
const newOrder = await model.create({ ...newOrderData, id: allocatedOrderId });
const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id);
// 5. 克隆订单明细
@ -3214,28 +3352,196 @@ class PendingOrderService extends OrderBaseService {
/**
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
*
* 支持单条解析与数组批量解析两种模式:
* - 单条:data.address 传字符串,返回单条解析结果(与原行为一致)
* - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list,
* 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目
*
* 采用"AI 解析 + 反向识别兜底"双层策略:
* 1. 先由 DeepSeek AI 进行语义级地址解析
* 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全
* 3. 仅在两层策略均无法确定 province 时才判定失败
*
* @param {Object} data 请求数据。
* @param {string} data.address 原始地址字符串(必填)。
* @return {Promise<Object>} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。
* @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。
* @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。
* @return {Promise<Object>} 解析结果;批量模式返回 data.list 数组。
*/
async parseAddress(data = {}) {
const address = String(data.address || '').trim();
// 批量模式:addresses 数组优先,其次 address 数组
const rawAddresses = Array.isArray(data.addresses)
? data.addresses
: (Array.isArray(data.address) ? data.address : null);
if (rawAddresses) {
if (!rawAddresses.length) {
return this.fail('地址数组不能为空');
}
if (rawAddresses.length > 50) {
return this.fail('单次批量解析最多支持 50 条地址');
}
// 批量提速:每 10 条合并为一次 DeepSeek 请求(实测 10 条约 18s、无截断),
// 所有块异步并行发出,全部完成后按输入顺序聚合返回;失败/缺失条目逐条回退单条解析。
const CHUNK_SIZE = 10;
const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' };
const toListItem = r => ({
address: r.address,
flag: r.flag,
message: r.message,
...(r.fields || EMPTY_FIELDS),
});
const chunks = [];
for (let i = 0; i < rawAddresses.length; i += CHUNK_SIZE) {
chunks.push(rawAddresses.slice(i, i + CHUNK_SIZE));
}
const chunkResults = await Promise.all(chunks.map(chunk => this._parseAddressBatchOneShot(chunk)));
const results = await Promise.all(rawAddresses.map((item, idx) => {
const r = chunkResults[Math.floor(idx / CHUNK_SIZE)];
const inChunk = r && r[idx % CHUNK_SIZE];
return inChunk && inChunk.ok ? inChunk : this._parseSingleAddress(item);
}));
return this.success('地址解析成功', { list: results.map(toListItem) });
}
// 单条模式(向后兼容)
const single = await this._parseSingleAddress(data.address);
if (!single.ok) {
return this.fail(single.message);
}
return this.success('地址解析成功', single.fields);
}
/**
* 块内一次性解析:把一组地址(建议 10 条)合并为一次 DeepSeek 请求,
* 让模型按编号返回 JSON 数组,省去逐条请求的网络开销。
*
* @param {string[]} addressList 地址字符串数组。
* @return {Promise<Array|null>} 与入参顺序对齐的逐条结果数组;
* 请求失败/JSON 解析失败/被截断时返回 null,由调用方逐条回退单条解析。
*/
async _parseAddressBatchOneShot(addressList) {
const apiKey = this.config.deepseek.apiKey;
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) return null;
const numbered = addressList.map((a, i) => `${i + 1}. ${a}`).join('\n');
const prompt = `你是一个专业的中文地址解析助手。请一次性解析以下 ${addressList.length} 条地址,按编号顺序返回JSON数组,每条为:
{"index":编号,"province":"省","city":"市","area":"区/县","town":"乡镇/街道","detailAddress":"详细地址","name":"收件人","mobile":"手机号"}
规则:
1. 地址重复拼接时先智能去重再解析
2. 直辖市:province与city都填直辖市名,area填市辖区名
3. 无法识别的字段填空字符串
4. 只返回JSON数组,不含解释或markdown
地址列表:
${numbered}`;
try {
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model: 'deepseek-v4-flash',
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: 32000,
},
timeout: 120000,
});
if (result.status !== 200 || !result.data) {
return null;
}
const choice = result.data.choices?.[0] || {};
// 被截断时整体回退,避免残缺数组造成大量错位
if ((choice.finish_reason || '') === 'length') {
return null;
}
const content = String(choice.message?.content || '').trim();
const arr = JSON.parse(extractJsonBlock(content));
if (!Array.isArray(arr)) {
return null;
}
this.ctx.logger.info('[parseAddress] 批量块请求完成:入参 %d 条,finish_reason=%s,返回 %d 条', addressList.length, choice.finish_reason, arr.length);
return addressList.map((address, idx) => {
if (!String(address || '').trim()) {
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
}
const item = arr.find(x => x && Number(x.index) === idx + 1);
if (!item) {
return { address, ok: false, flag: 'failure', message: '批量解析未返回该条结果', fields: null };
}
let province = String(item.province || '').trim();
let city = String(item.city || '').trim();
let area = String(item.area || '').trim();
let town = String(item.town || '').trim();
const detailAddress = String(item.detailAddress || '').trim();
const name = sanitizeName(item.name);
const mobile = sanitizeMobile(item.mobile);
// 反向识别兜底 + 正则兜底,与单条解析保持一致
const inferred = reverseInferAddress({ province, city, area, town, detailAddress, name, mobile });
province = inferred.province;
city = inferred.city;
area = inferred.area;
if (!province) {
const regexResult = extractAddressByRegex(address);
if (regexResult.province) {
province = regexResult.province;
city = city || regexResult.city;
area = area || regexResult.area;
town = town || regexResult.town;
}
}
if (!province || province === '暂未识别' || province === '其他') {
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
}
return {
address,
ok: true,
flag: 'success',
message: 'ok',
fields: { province, city, area, town, detailAddress, name, mobile },
};
});
} catch (error) {
this.ctx.logger.warn('[parseAddress] 批量一次性解析失败,将逐条回退: %s', error.message);
return null;
}
}
/**
* 解析单条地址(parseAddress 单条/批量模式共用)。
*
* @param {*} item 原始地址。
* @return {Promise<Object>} { address, ok, flag, message, fields };fields 为解析字段对象或 null。
*/
async _parseSingleAddress(item) {
const address = String(item || '').trim();
if (!address) {
return this.fail('地址字符串不能为空');
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
}
const apiKey = this.config.deepseek.apiKey;
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) {
return this.fail('DeepSeek API Key 未配置');
return { address, ok: false, flag: 'failure', message: 'DeepSeek API Key 未配置', fields: null };
}
try {
// 仅在 parseAddress 使用 v4-flash(速度优先,适合批量解析),不改全局配置
const model = 'deepseek-v4-flash';
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
规则:
@ -3252,73 +3558,143 @@ class PendingOrderService extends OrderBaseService {
- "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市
4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。
5. detailAddress去除省市区部分,只保留街道/村/门牌号
6. 只返回纯JSON,不含解释或markdown
6. 地址字符串若出现重复拼接(如"陕西省延安市志丹县"出现两次),先智能去重再解析,合并保留重复部分中的街道/村信息
7. 只返回纯JSON,不含解释或markdown
地址字符串: "${address}"
请返回JSON:`;
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model: 'deepseek-v4-pro',
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: 500,
},
timeout: 15000,
});
if (result.status !== 200 || !result.data) {
return this.fail('地址解析服务请求失败');
}
const content = result.data.choices?.[0]?.message?.content || '';
this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content);
// 清理可能的 markdown 代码块标记
let jsonStr = content.trim();
jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
try {
const parsed = JSON.parse(jsonStr);
let province = String(parsed.province || '').trim();
let city = String(parsed.city || '').trim();
let area = String(parsed.area || '').trim();
const town = String(parsed.town || '').trim();
const detailAddress = String(parsed.detailAddress || '').trim();
const name = String(parsed.name || '').trim();
const mobile = String(parsed.mobile || '').trim();
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
const inferred = reverseInferAddress({
province,
city,
area,
town,
detailAddress,
name,
mobile,
const requestDeepSeek = async maxTokens => {
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model,
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: maxTokens,
},
timeout: 60000,
});
province = inferred.province;
city = inferred.city;
area = inferred.area;
// 反向识别后仍无 province 才判定失败
if (!province || province === '暂未识别' || province === '其他') {
return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试');
if (result.status !== 200 || !result.data) {
return null;
}
const choice = result.data.choices?.[0] || {};
return {
content: String(choice.message?.content || '').trim(),
reasoningContent: String(choice.message?.reasoning_content || '').trim(),
finishReason: choice.finish_reason || '',
};
};
return this.success('地址解析成功', {
// deepseek-v4-flash 为思维链模型,max_tokens 过小时推理会耗尽全部配额,
// 导致 content 为空且 finish_reason=length。首次给足 3000 tokens,
// 仍被截断且无法从 reasoning_content 兜底时,加大到 8000 重试一次。
let response = await requestDeepSeek(3000);
if (
response
&& response.finishReason === 'length'
&& !response.content
&& !salvageFieldsFromText(response.reasoningContent)
) {
this.ctx.logger.warn('[parseAddress] 首次调用被截断(finish_reason=length),以 max_tokens=8000 重试');
response = await requestDeepSeek(8000);
}
if (!response) {
return { address, ok: false, flag: 'failure', message: '地址解析服务请求失败', fields: null };
}
const { content, reasoningContent, finishReason } = response;
this.ctx.logger.info('[parseAddress] DeepSeek原始返回 finish_reason=%s content: %s', finishReason, content || '(空)');
const tryParseJson = raw => {
try {
return JSON.parse(raw);
} catch (parseError) {
return null;
}
};
// 清理 markdown 代码块标记,并截取第一个 { 到最后一个 } 之间的 JSON 片段
let parsed = tryParseJson(extractJsonBlock(content));
if (!parsed) {
// 轻量修复:去除对象/数组内的尾随逗号后重试
parsed = tryParseJson(extractJsonBlock(content).replace(/,\s*([}\]])/g, '$1'));
}
// JSON 解析失败时,尝试从 content 或 reasoning_content 文本中做字段级提取兜底
if (!parsed) {
parsed = salvageFieldsFromText(content || reasoningContent);
if (parsed) {
this.ctx.logger.warn('[parseAddress] 正文字段提取兜底结果: %j', parsed);
}
}
if (!parsed) {
this.ctx.logger.warn('[parseAddress] JSON解析失败,finish_reason=%s,原始返回: %s', finishReason, content || reasoningContent);
if (finishReason === 'length') {
return { address, ok: false, flag: 'failure', message: '地址解析超时,请重试', fields: null };
}
return { address, ok: false, flag: 'failure', message: '地址解析结果格式异常,请重试', fields: null };
}
let province = String(parsed.province || '').trim();
let city = String(parsed.city || '').trim();
let area = String(parsed.area || '').trim();
let town = String(parsed.town || '').trim();
const detailAddress = String(parsed.detailAddress || '').trim();
const name = sanitizeName(parsed.name);
const mobile = sanitizeMobile(parsed.mobile);
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
const inferred = reverseInferAddress({
province,
city,
area,
town,
detailAddress,
name,
mobile,
});
province = inferred.province;
city = inferred.city;
area = inferred.area;
// --- 最终兜底:AI 与映射表均失败时,用正则从原始地址提取省市区 ---
if (!province) {
const regexResult = extractAddressByRegex(address);
if (regexResult.province) {
province = regexResult.province;
city = city || regexResult.city;
area = area || regexResult.area;
if (!town) {
town = regexResult.town;
}
this.ctx.logger.warn('[parseAddress] 正则兜底解析结果: %j', regexResult);
}
}
// 反向识别后仍无 province 才判定失败
if (!province || province === '暂未识别' || province === '其他') {
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
}
return {
address,
ok: true,
flag: 'success',
message: 'ok',
fields: {
province,
city,
area,
@ -3326,14 +3702,11 @@ class PendingOrderService extends OrderBaseService {
detailAddress,
name,
mobile,
});
} catch (parseError) {
this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content);
return this.fail('地址解析结果格式异常,请重试');
}
},
};
} catch (error) {
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
return this.fail(`地址解析失败: ${error.message}`);
return { address, ok: false, flag: 'failure', message: `地址解析失败: ${error.message}`, fields: null };
}
}

View File

@ -671,6 +671,28 @@ class RecheckOrderService extends OrderBaseService {
};
}
/**
* 判断订单拦截状态是否属于"已进入拦截流程"的状态。
* 拦截状态枚举(wms_order_delivery.intercept_status)实际取值为:
* none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse /
* returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。
* 其中 requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功,
* intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。
* @param {string} status 拦截状态。
* @return {boolean} 是否为拦截流程状态。
*/
isInterceptedOrderStatus(status = '') {
const normalizedStatus = String(status || '').trim();
return [
'intercepted',
'requested',
'requesting',
'intercepting',
'intercepted_in_transit',
'intercepted_at_warehouse',
].includes(normalizedStatus);
}
/**
* 构建团购波次列表视图(团单模式)。
* 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。
@ -682,8 +704,8 @@ class RecheckOrderService extends OrderBaseService {
* pick_mode、total_orders、processed_orders、creator、create_time、update_time、
* order_count、box_no、reviewed_count、unreviewed_count、printed_count、unprinted_count、
* stocks(非拦截订单合并后的商品明细)、
* intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index、order_id、
* delivery_order_code、intercept_status 等字段)、
* intercepted(拦截订单列表,仅当波次中存在拦截订单时出现,每项含 wave_index(波次内序号)、order_id、
* delivery_order_code、waybill_no、intercept_status 等字段)、
* items_weight(订单商品总重量,取自波次内首个正常订单)、
* suggested_package_material(推荐包材信息,无推荐时为 null)、
* first_waybill_no(波次内首个正常订单的运单号,用于包材绑定等后续操作,无正常订单时为第一个订单的运单号,均无则为空字符串)。
@ -757,7 +779,7 @@ class RecheckOrderService extends OrderBaseService {
const normalOrders = [];
for (const order of orders) {
const interceptStatus = String(order.intercept_status || '').trim();
if (interceptStatus === 'intercepted') {
if (this.isInterceptedOrderStatus(interceptStatus)) {
interceptedOrders.push(order);
} else {
normalOrders.push(order);
@ -787,11 +809,12 @@ class RecheckOrderService extends OrderBaseService {
store_remark: String(item.store_remark || '').trim(),
}));
// 构建拦截订单列表
// 构建拦截订单列表(wave_index 即波次内序号,供前端展示拦截订单的序号)
const intercepted = interceptedOrders.map(order => ({
wave_index: Number(order.wave_index || 0),
order_id: Number(order.order_id || 0),
delivery_order_code: String(order.delivery_order_code || '').trim(),
waybill_no: String(order.waybill_no || '').trim(),
intercept_status: String(order.intercept_status || '').trim(),
}));
@ -1754,7 +1777,7 @@ class RecheckOrderService extends OrderBaseService {
const interceptedOrders = [];
for (const order of orderList) {
if (String(order.intercept_status || '').trim() === 'intercepted') {
if (this.isInterceptedOrderStatus(String(order.intercept_status || '').trim())) {
interceptedOrders.push(order);
} else {
normalOrders.push(order);

View File

@ -149,6 +149,10 @@ class ShopsMethodService extends MainService {
callbackurl,
callback_url: callbackUrlSnake,
callbackUrl,
appId,
app_id: appIdSnake,
toUserName,
to_user_name: toUserNameSnake,
} = data || {};
return await this.callShopsSystem('getAuthorizeSessionKey', {
@ -156,6 +160,8 @@ class ShopsMethodService extends MainService {
callbackurl: callbackurl !== undefined
? callbackurl
: (callbackUrlSnake !== undefined ? callbackUrlSnake : callbackUrl),
appId: appId !== undefined ? appId : appIdSnake,
toUserName: toUserName !== undefined ? toUserName : toUserNameSnake,
}, '获取授权会话失败');
}
}

View File

@ -628,7 +628,6 @@ class DeliveryOrderService extends Service {
*/
async addOrder(data, info, createChannel = '') {
const { ctx } = this;
const operationLogs = [];
let warehouseIdStr;
try {
warehouseIdStr = normalizeWarehouseShardId(info.warehouseId);
@ -655,255 +654,360 @@ class DeliveryOrderService extends Service {
|| 'MANUAL'
).trim().toUpperCase() || 'MANUAL';
// 开启事务
const transaction = await ctx.model.transaction();
// 订单 id 序列表初始化可能执行 DDL(隐式提交),必须在事务外先完成
try {
if (!info.storeId) {
throw new Error('非法参数');
}
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
throw new Error('订单信息不完整');
}
await ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseIdStr);
} catch (error) {
// 初始化失败不降级:后续发号会直接失败并回滚建单,绝不让分表自增介入发号
ctx.logger.warn('[DeliveryOrderService.addOrder] 序列表初始化失败,本次建单将失败:', error.message);
}
// 检查订单是否已存在(根据唯一索引)
const existingOrder = await DeliveryModel.findOne({
where: {
delivery_order_code: deliveryOrder.deliveryOrderCode,
store_id: info.storeId,
warehouse_id: info.warehouseId,
},
attributes: [ 'id' ],
transaction,
});
if (existingOrder) {
await transaction.rollback();
return {
success: true,
message: '订单已存在',
data: { deliveryOrderId: existingOrder.id },
};
}
// 单次建单执行体:重试时复用,事务随每次尝试重新开启
const createOnce = async operationLogs => {
// 开启事务
const transaction = await ctx.model.transaction();
// 准备订单数据
const step = await this.resolveOrderStep(info, transaction);
const orderData = await this.prepareOrderData(
deliveryOrder,
info,
normalizedCreateChannel,
step,
operationLogs,
requestExtendProps
);
try {
if (!info.storeId) {
throw new Error('非法参数');
}
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
throw new Error('订单信息不完整');
}
// 创建订单
const createdOrder = await DeliveryModel.create(orderData, { transaction });
const orderId = createdOrder.id;
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.CREATE,
`订单创建成功,orderId:${orderId}`,
{ prepend: true }
);
// 检查订单是否已存在(根据唯一索引)
const existingOrder = await DeliveryModel.findOne({
where: {
delivery_order_code: deliveryOrder.deliveryOrderCode,
store_id: info.storeId,
warehouse_id: info.warehouseId,
},
attributes: [ 'id' ],
transaction,
});
if (existingOrder) {
await transaction.rollback();
return {
success: true,
message: '订单已存在',
data: { deliveryOrderId: existingOrder.id },
};
}
// 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑
info.createChannel = normalizedCreateChannel;
let itemsInfo = null;
// 添加订单明细
if (orderLines && (orderLines.orderLine)) {
itemsInfo = await this.addOrderLines(
orderLines.orderLine,
orderId,
// 准备订单数据
const step = await this.resolveOrderStep(info, transaction);
const orderData = await this.prepareOrderData(
deliveryOrder,
info,
transaction
normalizedCreateChannel,
step,
operationLogs,
requestExtendProps
);
} else {
throw new Error('[订单无明细]');
}
// 更新订单统计信息 - 直接使用itemsInfo中的计算结果
if (itemsInfo) {
const stats = {
items: itemsInfo.items_str || '', // 原始结构字符串
items_count: itemsInfo.stock_count || 0, // 商品种类数
items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果)
items_weight: itemsInfo.total_weight || 0, // 总重量
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode,
updated_at: new Date(),
};
// 创建订单:订单 id 统一由仓库序列表分配,显式写入 current 分表。
// 不再回退分表自增:分表自增序列与序列表发号区间重叠会产生冲突 id,
// 发号失败时直接抛错,由事务回滚,杜绝脏 id 落库。
const orderId = await ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseIdStr, transaction, 'current');
await DeliveryModel.create({ ...orderData, id: orderId }, { transaction });
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.CREATE,
`订单创建成功,orderId:${orderId}`,
{ prepend: true }
);
// ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) =====
try {
const receiverInfo = deliveryOrder.receiverInfo;
const shopNick = deliveryOrder.shopNick;
const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city));
// 将建单渠道注入 info,供 addOrderLines 区分 MANUAL 降级逻辑
info.createChannel = normalizedCreateChannel;
if (hasEnoughData) {
const address = [
receiverInfo?.province || '',
receiverInfo?.city || '',
receiverInfo?.area || '',
receiverInfo?.town || '',
receiverInfo?.detail_address || '',
].join('').trim();
const matchResult = await ctx.service.systems.expressPolicy.matchPolicy(
info.warehouseId,
{
storeId: info.storeId,
customShopName: shopNick || '',
address: address || '',
weight: itemsInfo.total_weight || null,
prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合
}
);
if (matchResult && matchResult.expressCode) {
const expressList = await ctx.service.systems.express.getExpressList();
const matchedExpress = expressList.find(
item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim()
);
let logisticsCode;
let logisticsName;
let sysLogisticsCode;
let sysLogisticsName;
if (matchedExpress) {
if (matchedExpress.is_system_setting) {
// 自定义映射:sys 写映射的系统快递,logistics 写自定义编码
sysLogisticsCode = String(matchedExpress.express_code || '').trim();
const sysItem = expressList.find(
item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode
);
sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode;
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim();
} else {
// 系统快递:4 字段一致
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim();
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsName;
}
} else {
// 未在列表中,fallback
logisticsCode = String(matchResult.expressCode).trim();
logisticsName = logisticsCode;
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsCode;
}
stats.logistics_code = logisticsCode;
stats.logistics_name = logisticsName;
stats.sys_logistics_code = sysLogisticsCode;
stats.sys_logistics_name = sysLogisticsName;
stats.weight_type = matchResult.weightType;
stats.updated_at = new Date();
// 写入操作日志:命中了哪条策略
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH,
`快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}`
);
ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
logisticsCode,
sysLogisticsCode,
weightType: matchResult.weightType,
policyName: matchResult.policyName,
policyId: matchResult.policyId,
totalWeight: itemsInfo.total_weight,
});
} else if (hasEnoughData) {
// 策略未命中:记快递降级日志(取已落库的初始快递值)
const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code;
const fallbackName = orderData.sys_logistics_name || orderData.logistics_name;
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
);
}
}
} catch (policyErr) {
ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', {
let itemsInfo = null;
// 添加订单明细
if (orderLines && (orderLines.orderLine)) {
itemsInfo = await this.addOrderLines(
orderLines.orderLine,
orderId,
error: policyErr.message,
info,
transaction
);
} else {
throw new Error('[订单无明细]');
}
// 更新订单统计信息 - 直接使用itemsInfo中的计算结果
if (itemsInfo) {
const stats = {
items: itemsInfo.items_str || '', // 原始结构字符串
items_count: itemsInfo.stock_count || 0, // 商品种类数
items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果)
items_weight: itemsInfo.total_weight || 0, // 总重量
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
source_order_codes: ((itemsInfo.stats && itemsInfo.stats.source_order_codes) || []).filter(code => code).join(',') || deliveryOrder.deliveryOrderCode,
updated_at: new Date(),
};
// ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) =====
try {
const receiverInfo = deliveryOrder.receiverInfo;
const shopNick = deliveryOrder.shopNick;
const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city));
if (hasEnoughData) {
const address = [
receiverInfo?.province || '',
receiverInfo?.city || '',
receiverInfo?.area || '',
receiverInfo?.town || '',
receiverInfo?.detail_address || '',
].join('').trim();
const matchResult = await ctx.service.systems.expressPolicy.matchPolicy(
info.warehouseId,
{
storeId: info.storeId,
customShopName: shopNick || '',
address: address || '',
weight: itemsInfo.total_weight || null,
prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合
}
);
if (matchResult && matchResult.expressCode) {
const expressList = await ctx.service.systems.express.getExpressList();
const matchedExpress = expressList.find(
item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim()
);
let logisticsCode;
let logisticsName;
let sysLogisticsCode;
let sysLogisticsName;
if (matchedExpress) {
if (matchedExpress.is_system_setting) {
// 自定义映射:sys 写映射的系统快递,logistics 写自定义编码
sysLogisticsCode = String(matchedExpress.express_code || '').trim();
const sysItem = expressList.find(
item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode
);
sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode;
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim();
} else {
// 系统快递:4 字段一致
logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim();
logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim();
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsName;
}
} else {
// 未在列表中,fallback
logisticsCode = String(matchResult.expressCode).trim();
logisticsName = logisticsCode;
sysLogisticsCode = logisticsCode;
sysLogisticsName = logisticsCode;
}
stats.logistics_code = logisticsCode;
stats.logistics_name = logisticsName;
stats.sys_logistics_code = sysLogisticsCode;
stats.sys_logistics_name = sysLogisticsName;
stats.weight_type = matchResult.weightType;
stats.updated_at = new Date();
// 写入操作日志:命中了哪条策略
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH,
`快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}`
);
ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
logisticsCode,
sysLogisticsCode,
weightType: matchResult.weightType,
policyName: matchResult.policyName,
policyId: matchResult.policyId,
totalWeight: itemsInfo.total_weight,
});
} else if (hasEnoughData) {
// 策略未命中:记快递降级日志(取已落库的初始快递值)
const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code;
const fallbackName = orderData.sys_logistics_name || orderData.logistics_name;
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
);
}
}
} catch (policyErr) {
ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', {
orderId,
error: policyErr.message,
});
}
await DeliveryModel.update(
stats,
{
where: { id: orderId },
transaction,
}
);
// 记录详细日志
ctx.logger.info('[订单统计信息已更新]', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
stats: {
items_count: stats.items_count,
items_total: stats.items_total,
items_weight: stats.items_weight,
items_hash_preview: stats.items_hash?.substring(0, 8) + '...',
items_crc: stats.items_crc,
},
});
}
await DeliveryModel.update(
stats,
{
where: { id: orderId },
transaction,
}
);
await transaction.commit();
// 记录详细日志
ctx.logger.info('[订单统计信息已更新]', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
stats: {
items_count: stats.items_count,
items_total: stats.items_total,
items_weight: stats.items_weight,
items_hash_preview: stats.items_hash?.substring(0, 8) + '...',
items_crc: stats.items_crc,
},
await this.flushOrderOperationLogs(operationLogs, orderId, {
warehouseId: info.warehouseId,
createChannel: normalizedCreateChannel,
});
// 异步处理订单后续流程
this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => {
ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, {
orderId,
error: error.message,
});
});
return {
success: true,
message: '订单创建成功',
data: {
orderId,
step,
stats: itemsInfo ? {
items_count: itemsInfo.stock_count,
items_total: itemsInfo.item_total_count,
items_weight: itemsInfo.total_weight,
source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [],
} : null,
},
};
} catch (error) {
console.error('创建订单失败:', error);
// 回滚事务(安全处理,防止事务已结束导致二次回滚异常)
await transaction.rollback().catch(rollbackErr => {
console.error('回滚事务失败:', rollbackErr.message);
});
throw error;
}
};
// 主键冲突(分表自增水位与已有数据重叠)允许修复水位后重试一次
for (let attempt = 1; attempt <= 2; attempt++) {
const operationLogs = [];
try {
return await createOnce(operationLogs);
} catch (error) {
if (this.isPrimaryKeyDuplicate(error) && attempt === 1) {
try {
const factory = ctx.model.OrderDeliveryFactory;
const tableName = factory.generateTableName(warehouseIdStr, 'current');
await factory.ensureAutoIncrementWatermark(tableName);
ctx.logger.warn('[DeliveryOrderService.addOrder] 主键冲突,已修复自增水位,重试建单', {
deliveryOrderCode: deliveryOrder && deliveryOrder.deliveryOrderCode,
warehouseId: warehouseIdStr,
storeId: info.storeId,
error: error.message,
});
} catch (repairError) {
ctx.logger.warn('[DeliveryOrderService.addOrder] 自增水位修复失败,放弃重试', {
error: repairError.message,
});
}
continue;
}
return {
success: false,
message: `订单创建失败: ${this.formatOrderCreateError(error, deliveryOrder)}`,
data: null,
};
}
}
return {
success: false,
message: '订单创建失败: 主键冲突重试后仍未成功',
data: null,
};
}
/**
* 判断是否为分表主键自增冲突。
*
* 分表自增水位被破坏(显式 id 导入、表重建、迁移复制 id)后,自增插入会与
* 已有主键重叠,Sequelize 抛出的 UniqueConstraintError 对外 message 为
* “Validation error”,需按 errors[].path 识别。
*
* @param {Error} error Sequelize 错误对象。
* @return {boolean} 是否为主键唯一冲突。
*/
isPrimaryKeyDuplicate(error) {
if (!error || error.name !== 'SequelizeUniqueConstraintError' || !Array.isArray(error.errors)) {
return false;
}
return error.errors.some(item => item
&& item.type === 'unique violation'
&& (item.path === 'PRIMARY' || item.path === 'id'));
}
/**
* 将建单异常格式化为可读的失败原因。
*
* Sequelize 唯一约束错误的 message 固定为 “Validation error”,若不解析
* errors/parent 会掩盖真实原因,这里优先提取具体冲突字段与值。
*
* @param {Error} error 原始异常。
* @param {Object} [deliveryOrder] 请求中的发货单信息。
* @return {string} 可读的失败原因。
*/
formatOrderCreateError(error, deliveryOrder) {
if (error && error.name === 'SequelizeUniqueConstraintError' && Array.isArray(error.errors)) {
const primaryDup = error.errors.find(item => item
&& item.type === 'unique violation'
&& (item.path === 'PRIMARY' || item.path === 'id'));
if (primaryDup) {
return `订单ID主键冲突(id=${primaryDup.value} 已被占用):分表自增水位与已有数据重叠,已尝试修复并重试,请再次提交`;
}
await transaction.commit();
const codeDup = error.errors.find(item => item && item.path === 'delivery_order_code');
if (codeDup) {
const orderCode = (deliveryOrder && deliveryOrder.deliveryOrderCode) || codeDup.value;
return `订单号 ${orderCode} 已存在`;
}
await this.flushOrderOperationLogs(operationLogs, orderId, {
warehouseId: info.warehouseId,
createChannel: normalizedCreateChannel,
});
// 异步处理订单后续流程
this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => {
ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, {
orderId,
error: error.message,
});
});
return {
success: true,
message: '订单创建成功',
data: {
orderId,
step,
stats: itemsInfo ? {
items_count: itemsInfo.stock_count,
items_total: itemsInfo.item_total_count,
items_weight: itemsInfo.total_weight,
source_order_codes: (itemsInfo.stats && itemsInfo.stats.source_order_codes) || [],
} : null,
},
};
} catch (error) {
console.error('创建订单失败:', error);
// 回滚事务(安全处理,防止事务已结束导致二次回滚异常)
await transaction.rollback().catch(rollbackErr => {
console.error('回滚事务失败:', rollbackErr.message);
});
return {
success: false,
message: `订单创建失败: ${error.message}`,
data: null,
};
const firstItem = error.errors[0] || {};
return String(firstItem.message || error.message || '唯一约束冲突').trim();
}
const parentSqlMessage = error && error.parent && error.parent.sqlMessage;
if (parentSqlMessage) {
return `${error.message} (${parentSqlMessage})`;
}
return String((error && error.message) || '').trim() || '未知错误';
}
/**

View File

@ -405,6 +405,12 @@ class OrderDeliveryMigrationService extends MainService {
const deadlineAt = Number.isFinite(executionTimeoutMs) && executionTimeoutMs > 0
? Date.now() + executionTimeoutMs
: 0;
// 序列表初始化可能执行 DDL(隐式提交),必须在事务外完成。
// 初始化失败直接终止迁移:位置指针与配送表写入必须在同一事务内原子完成,
// 没有序列表则无法保证索引一致,宁可迁移失败重试也不产生错位指针。
await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(normalizedWarehouseId);
const transaction = await this.ctx.model.transaction();
const { Op } = this.ctx.app.Sequelize;
let sourceRows = [];
@ -538,6 +544,22 @@ class OrderDeliveryMigrationService extends MainService {
await targetOrderModel.bulkCreate(rowsToCreate, {
...this.buildMigrationQueryOptions(transaction, queryTimeoutMs),
});
// 更新序列表位置指针:current → dispatch。与上方 bulkCreate 处于同一事务,
// 任一步失败整体回滚,保证配送表数据与位置索引原子一致(存量订单自动补录,
// 显式 id 大于序列表水位时 MySQL 会自动推进,后续发号不会与存量 id 冲突)。
const locationFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!locationFactory || typeof locationFactory.updateOrderLocation !== 'function') {
throw new Error('订单工厂缺少 updateOrderLocation,无法同步序列表位置指针');
}
for (const row of rowsToCreate) {
await locationFactory.updateOrderLocation(
Number(row.id),
normalizedWarehouseId,
'dispatch',
transaction
);
}
}
assertMigrationDeadline('查询配送表订单');

View File

@ -318,6 +318,16 @@ class OrderExpressService extends Service {
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(normalizedOrderId, warehouseId);
if (preferredLocation) {
orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
let orderRow = null;
let orderDeliveryModel = null;
for (const entry of orderTableOrders) {
@ -440,6 +450,16 @@ class OrderExpressService extends Service {
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
let orderRow = null;
let orderDeliveryModel = null;
for (const entry of orderTableOrders) {

View File

@ -691,11 +691,6 @@ class ShopsService extends Service {
const authUrl = 'http://61.160.223.183:3012/api';
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const callbackUrl = this.normalizeText(
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
'callbackurl',
{ required: true, maxLength: 500 }
);
const appId = data.appId || '';
const toUserName = data.toUserName || '';
const shop = await this.findShopById(shopId, { allowDeleted: false });
@ -712,6 +707,12 @@ class ShopsService extends Service {
});
const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode;
// 视频号授权不依赖回调地址,允许 callbackurl 为空;其他平台仍必填
const callbackUrl = this.normalizeText(
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
'callbackurl',
{ required: platName !== '视频号', maxLength: 500 }
);
const requestData = {
RedirectCodeUrl: callbackUrl,
command: 'saveShop',
@ -735,7 +736,7 @@ class ShopsService extends Service {
const respone = await ctx.curl(authUrl, {
method: 'POST',
dataType: 'json',
timeout: 5000,
timeout: 15000,
data: requestData,
});
await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600);

View File

@ -73,6 +73,16 @@ class WaybillService extends MainService {
},
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
// 遍历多表查询订单的 wave_id 和 wave_no
let orderRow = null;
for (const entry of tableOrders) {

View File

@ -848,6 +848,16 @@ class WorkbenchService extends Service {
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
let orderRow = null;
let orderDeliveryModel = null;
for (const entry of tableOrders) {

View File

@ -0,0 +1,138 @@
'use strict';
const TABLE_NAME = 'wms_inbox_group';
/** 合并重复记录时允许从重复行补齐到保留行的字段 */
const FILLABLE_FIELDS = [
'store_id',
'group_type',
'sub_type',
'source_type',
'source_extra',
'express_interfaces',
'system_express_code',
];
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
}
async function dropIndexIfExists(queryInterface, tableName, indexName) {
if (await indexExists(queryInterface, tableName, indexName)) {
await queryInterface.removeIndex(tableName, indexName);
console.log(`[idx] ${tableName}.${indexName} 已删除`);
}
}
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
if (await indexExists(queryInterface, tableName, indexName)) {
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
return;
}
await queryInterface.addIndex(tableName, options.fields, {
name: indexName,
unique: !!options.unique,
});
console.log(`[idx] ${tableName}.${indexName} 已创建`);
}
/**
* 合并 (warehouse_id, group_id) 相同的重复群记录,为唯一索引铺路。
* 保留策略:is_blocked=0(启用)优先,其次 created_at 最早;
* 群名称取 updated_at 最新一条的名称;其余字段为空时从重复行补齐;其余行软删除。
*
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @return {Promise<void>}
*/
async function mergeDuplicateGroups(queryInterface) {
const q = queryInterface.sequelize;
const dupGroups = await q.query(
`SELECT warehouse_id, group_id
FROM \`${TABLE_NAME}\`
WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL
GROUP BY warehouse_id, group_id
HAVING COUNT(*) > 1`,
{ type: q.QueryTypes.SELECT }
);
for (const g of dupGroups) {
const rows = await q.query(
`SELECT * FROM \`${TABLE_NAME}\`
WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL
ORDER BY is_blocked ASC, created_at ASC, id ASC`,
{ replacements: [ g.warehouse_id, g.group_id ], type: q.QueryTypes.SELECT }
);
if (!rows || rows.length < 2) continue;
const keep = rows[0];
const nameRow = [ ...rows ].sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0];
const dropIds = rows.filter(r => r.id !== keep.id).map(r => r.id);
const updates = {};
if (keep.group_name !== nameRow.group_name) {
updates.group_name = nameRow.group_name;
}
for (const field of FILLABLE_FIELDS) {
if (keep[field] === null || keep[field] === undefined || keep[field] === '') {
for (const row of rows) {
if (row.id === keep.id) continue;
if (row[field] !== null && row[field] !== undefined && row[field] !== '') {
updates[field] = row[field];
break;
}
}
}
}
if (Object.keys(updates).length > 0) {
const setClauses = Object.keys(updates).map(k => `\`${k}\` = ?`).join(', ');
await q.query(
`UPDATE \`${TABLE_NAME}\` SET ${setClauses}, updated_at = NOW() WHERE id = ?`,
{ replacements: [ ...Object.values(updates), keep.id ] }
);
console.log(`[dedupe] 保留 id=${keep.id} group_id=${g.group_id},更新: ${JSON.stringify(updates)}`);
}
const placeholders = dropIds.map(() => '?').join(',');
await q.query(
`UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
{ replacements: dropIds }
);
console.log(`[dedupe] 软删除 id=${dropIds.join(',')} group_id=${g.group_id}`);
}
}
module.exports = {
// eslint-disable-next-line no-unused-vars
up: async (queryInterface, Sequelize) => {
// 1. 清理 (warehouse_id, group_id) 重复记录,否则唯一索引无法创建
await mergeDuplicateGroups(queryInterface);
// 2. 删除错误的唯一索引 uk_group_warehouse(group_name, warehouse_id)
// 群名称会变化,不应作为唯一约束维度
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_group_warehouse');
// 3. 删除与唯一索引覆盖范围重复的普通索引 idx_warehouse_group_id
await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id');
// 4. 新建唯一索引 (warehouse_id, group_id)
// group_id 允许 NULL,MySQL 唯一索引允许多个 NULL,不影响无群ID的记录
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id', {
fields: [ 'warehouse_id', 'group_id' ],
unique: true,
});
},
down: async queryInterface => {
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id');
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id', {
fields: [ 'warehouse_id', 'group_id' ],
});
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_group_warehouse', {
fields: [ 'group_name', 'warehouse_id' ],
unique: true,
});
},
};

View File

@ -1,4 +1,39 @@
[
{
"version": "2026.08.15-recheckOrder.scanOrder.groupInterceptSeq",
"date": "2026-08-15",
"type": "fixed",
"summary": "修复 order.recheckOrder.scanOrder 团购模式拦截订单识别:原逻辑仅匹配不存在的 'intercepted' 状态,导致已进入拦截流程的订单(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse)被当作正常订单,团购复核数据不输出拦截订单及其序号。现统一按真实拦截状态枚举归类到波次项 intercepted 列表,并输出 wave_index 波次内序号",
"methods": [
"order.recheckOrder.scanOrder",
"order.recheckOrder.scanTask"
],
"notes": [
"新增 isInterceptedOrderStatus 辅助方法:intercepted / requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse 均视为拦截流程状态",
"buildGroupWaveList 拦截订单分离改用 isInterceptedOrderStatus,拦截订单不再进入正常订单校验与统计,仓库已拦截订单不再阻断整个团购扫描视图加载",
"团购波次项 intercepted 列表每项新增 waybill_no 字段,wave_index 为波次内序号(优先读取 wms_order_wave_index 真实序号,无记录时降级数组临时序号)",
"confirmRecheckByWaveId 团购波次批量复核同步修正拦截识别,拦截订单不再被批量标记复核",
"同步更新 methods/system.json 中 scanOrder 团购波次项 intercepted 字段说明"
],
"module": "order"
},
{
"version": "2026.08.15-parseAddress.batch",
"date": "2026-08-15",
"type": "enhanced",
"summary": "parseAddress 支持数组批量入参:addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(含失败条目逐条错误信息)",
"methods": [
"order.pendingOrder.parseAddress"
],
"notes": [
"入参兼容三种形态:address 字符串(单条,原行为不变)、address 字符串数组、addresses 字符串数组(优先)",
"批量解析:按每 10 条合并为一个 DeepSeek 请求并行发出(deepseek-v4-flash),全部返回后按输入顺序聚合,单次上限 50 条;失败/缺失条目逐条回退单条解析,不影响其他条目",
"批量响应 data.list 每条元素包含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure、message 为具体错误原因、解析字段为空字符串,不影响其他条目",
"抽取 _parseSingleAddress 私有方法复用单条解析逻辑,单条响应结构与之前完全一致",
"同步更新 methods/system.json 中 parseAddress 的参数与响应字段说明"
],
"module": "order"
},
{
"version": "2026.08.14-afterSale.detail-desc-first-step",
"date": "2026-08-14",

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.27",
"updatedAt": "2026-08-13",
"version": "0.3.28",
"updatedAt": "2026-08-15",
"headers": [
{
"name": "platform",
@ -4241,7 +4241,7 @@
},
{
"method": "order.pendingOrder.parseAddress",
"description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号",
"description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号。支持单条解析与数组批量解析:address 传字符串时返回单条结果,addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(失败条目 flag=failure 不影响其他条目)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
@ -4251,7 +4251,14 @@
"type": "string",
"required": true,
"source": "body",
"description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\""
"description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"。也支持传字符串数组批量解析(与 addresses 二选一)"
},
{
"name": "addresses",
"type": "string[]",
"required": false,
"source": "body",
"description": "批量地址字符串数组,单次最多 50 条,按数组顺序返回解析结果"
}
],
"requestBody": [],
@ -4315,6 +4322,72 @@
"type": "string",
"required": false,
"description": "收件人手机号,如 13800138000"
},
{
"name": "data.list",
"type": "array",
"required": false,
"description": "批量解析时返回的结果数组,按输入顺序排列;每条含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure 且解析字段为空字符串"
},
{
"name": "data.list[].address",
"type": "string",
"required": false,
"description": "原始地址字符串(原样返回)"
},
{
"name": "data.list[].flag",
"type": "string",
"required": false,
"description": "该条解析状态:success=成功,failure=失败"
},
{
"name": "data.list[].message",
"type": "string",
"required": false,
"description": "该条解析提示:成功为 ok,失败为具体错误原因"
},
{
"name": "data.list[].province",
"type": "string",
"required": false,
"description": "省份,如 广东省"
},
{
"name": "data.list[].city",
"type": "string",
"required": false,
"description": "城市,如 广州市"
},
{
"name": "data.list[].area",
"type": "string",
"required": false,
"description": "区/县,如 天河区"
},
{
"name": "data.list[].town",
"type": "string",
"required": false,
"description": "乡镇/街道,如 员村街道"
},
{
"name": "data.list[].detailAddress",
"type": "string",
"required": false,
"description": "详细地址,如 体育西路100号"
},
{
"name": "data.list[].name",
"type": "string",
"required": false,
"description": "收件人姓名,如 张三"
},
{
"name": "data.list[].mobile",
"type": "string",
"required": false,
"description": "收件人手机号,如 13800138000"
}
],
"errors": [
@ -4322,6 +4395,14 @@
"code": 400,
"message": "地址字符串不能为空"
},
{
"code": 400,
"message": "地址数组不能为空"
},
{
"code": 400,
"message": "单次批量解析最多支持 50 条地址"
},
{
"code": 500,
"message": "地址解析失败(AI服务异常或密钥未配置)"
@ -4331,7 +4412,8 @@
"方法部署位置:systemMethods/order/pendingOrder/parseAddress",
"使用 DeepSeek AI 模型进行智能解析",
"解析结果可直接回填到 createOrder 的收件人信息字段",
"未识别到的字段返回空字符串"
"未识别到的字段返回空字符串",
"批量解析:addresses 或 address 传字符串数组,按每 10 条合并为一个请求并行发出,全部返回后按输入顺序聚合,单条失败不影响其他条目(模型 deepseek-v4-flash)"
]
},
{
@ -5774,6 +5856,38 @@
}
]
},
{
"name": "intercepted",
"type": "array",
"description": "[团购波次项] 拦截订单列表,仅当波次内存在已进入拦截流程的订单时返回(intercept_status 为 requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse,以及历史遗留值 intercepted)。每项含 wave_index(波次内序号)、order_id、delivery_order_code、waybill_no、intercept_status",
"children": [
{
"name": "wave_index",
"type": "number",
"description": "波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)"
},
{
"name": "order_id",
"type": "number",
"description": "订单ID"
},
{
"name": "delivery_order_code",
"type": "string",
"description": "发货单号"
},
{
"name": "waybill_no",
"type": "string",
"description": "运单号"
},
{
"name": "intercept_status",
"type": "string",
"description": "拦截状态(requested / requesting / intercepting / intercepted_in_transit / intercepted_at_warehouse / intercepted)"
}
]
},
{
"name": "items_weight",
"type": "number|null",

View File

@ -0,0 +1,245 @@
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const ROOT = process.cwd();
const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js');
const SLOT_LOCATIONS = [
{ suffix: '_dispatch', location: 'dispatch' },
{ suffix: '_history', location: 'history' },
{ suffix: '_outsourced', location: 'outsourced' },
];
function parseArgs(argv) {
const args = {
dryRun: false,
dbClient: 'wms',
configPath: DEFAULT_CONFIG_PATH,
warehouseId: null,
batchSize: 1000,
};
for (const item of argv) {
if (item === '--dry-run') {
args.dryRun = true;
continue;
}
if (item.startsWith('--warehouse-id=')) {
const raw = String(item.split('=')[1] || '').trim();
args.warehouseId = Number(raw);
continue;
}
if (item.startsWith('--batch-size=')) {
const raw = Number(item.split('=')[1] || 0);
if (Number.isFinite(raw) && raw > 0) {
args.batchSize = Math.min(50000, Math.max(100, Math.floor(raw)));
}
continue;
}
if (item.startsWith('--db-client=')) {
args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
continue;
}
if (item.startsWith('--config-path=')) {
args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim());
continue;
}
}
return args;
}
function loadDbClient(configPath, dbClientName) {
if (!fs.existsSync(configPath)) {
throw new Error(`Config file not found: ${configPath}`);
}
const configFactory = require(configPath);
const cfg = typeof configFactory === 'function'
? configFactory({ name: 'wms-order-id-location-backfill' })
: configFactory;
const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[dbClientName];
if (!dbClient) {
throw new Error(`MySQL client not found in config.mysql.clients: ${dbClientName}`);
}
return dbClient;
}
function parseManagedTableName(tableName) {
const suffixMatch = /^wms_order_delivery_(\d+)(?:_(dispatch|history|outsourced))?$/.exec(tableName);
if (!suffixMatch) {
return null;
}
return {
warehouseId: Number(suffixMatch[1]),
location: suffixMatch[2] || 'current',
};
}
async function ensureSequenceTable(conn, warehouseId, dryRun) {
const tableName = `wms_order_id_location_${warehouseId}`;
const [ rows ] = await conn.query(
`SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
[ tableName ]
);
if (rows.length > 0) {
return tableName;
}
if (dryRun) {
console.log(`[dry-run] would create sequence table ${tableName}`);
return tableName;
}
await conn.query(
`CREATE TABLE \`${tableName}\` (
\`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
\`location\` VARCHAR(20) NOT NULL DEFAULT 'current',
PRIMARY KEY (\`id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'`
);
console.log(`created sequence table ${tableName}`);
return tableName;
}
async function countMissing(conn, sourceTable, seqTable) {
const [ rows ] = await conn.query(
`SELECT COUNT(*) AS cnt FROM \`${sourceTable}\` d `
+ `LEFT JOIN \`${seqTable}\` s ON s.id = d.id WHERE s.id IS NULL`
);
return Number(rows[0].cnt || 0);
}
async function fetchMissingBatch(conn, sourceTable, seqTable, batchSize) {
const [ rows ] = await conn.query(
`SELECT d.id FROM \`${sourceTable}\` d `
+ `LEFT JOIN \`${seqTable}\` s ON s.id = d.id WHERE s.id IS NULL `
+ `ORDER BY d.id ASC LIMIT ${batchSize}`
);
return (rows || []).map(row => Number(row.id)).filter(id => Number.isFinite(id) && id > 0);
}
async function upsertIds(conn, seqTable, location, ids, dryRun) {
if (ids.length === 0) {
return 0;
}
if (dryRun) {
console.log(`[dry-run] would insert ${ids.length} rows into ${seqTable} (location=${location}, first=${ids[0]}, last=${ids[ids.length - 1]})`);
return ids.length;
}
const values = ids.map(() => '(?, ?)').join(',');
const replacements = [];
for (const id of ids) {
replacements.push(id, location);
}
const [ result ] = await conn.query(
`INSERT INTO \`${seqTable}\` (\`id\`, \`location\`) VALUES ${values} `
+ 'ON DUPLICATE KEY UPDATE `location` = VALUES(`location`)',
replacements
);
return Number((result && result.affectedRows) || 0);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const dbClient = loadDbClient(args.configPath, args.dbClient);
const conn = await mysql.createConnection({
host: dbClient.host,
port: Number(dbClient.port),
user: dbClient.user,
password: dbClient.password,
database: dbClient.database,
charset: dbClient.charset || 'utf8mb4',
});
try {
console.log(`connected: ${dbClient.host}:${dbClient.port}/${dbClient.database}, dryRun=${args.dryRun}`);
const [ tableRows ] = await conn.query(
"SELECT TABLE_NAME FROM information_schema.TABLES "
+ "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'wms_order_delivery\\\\_%' "
+ "ORDER BY TABLE_NAME"
);
const tables = (tableRows || [])
.map(row => ({ tableName: row.TABLE_NAME, parsed: parseManagedTableName(row.TABLE_NAME) }))
.filter(item => item.parsed !== null)
.filter(item => !args.warehouseId || item.parsed.warehouseId === args.warehouseId);
const warehouseIds = [ ...new Set(tables.map(item => item.parsed.warehouseId)) ].sort((a, b) => a - b);
console.log(`found warehouses: [${warehouseIds.join(', ')}], tables: ${tables.length}`);
let totalInserted = 0;
for (const warehouseId of warehouseIds) {
const seqTable = await ensureSequenceTable(conn, warehouseId, args.dryRun);
const warehouseTables = tables.filter(item => item.parsed.warehouseId === warehouseId);
for (const { tableName, parsed } of warehouseTables) {
const missingCount = await countMissing(conn, tableName, seqTable);
if (missingCount === 0) {
console.log(`[${tableName}] no missing ids`);
continue;
}
console.log(`[${tableName}] missing ids: ${missingCount} (location=${parsed.location})`);
let inserted = 0;
for (;;) {
const batch = await fetchMissingBatch(conn, tableName, seqTable, args.batchSize);
if (batch.length === 0) {
break;
}
const affected = await upsertIds(conn, seqTable, parsed.location, batch, args.dryRun);
inserted += affected;
if (batch.length < args.batchSize) {
break;
}
}
console.log(`[${tableName}] done: inserted=${inserted}`);
totalInserted += inserted;
}
// 回填(显式 id)可能不会推进序列表自增计数器,结束时统一把水位
// 抬升到 max(id)+安全余量,保证后续发号不与存量 id 冲突
const [ seqMaxRows ] = await conn.query(
`SELECT COALESCE(MAX(id), 0) AS maxId FROM \`${seqTable}\``
);
const seqMaxId = Number(seqMaxRows[0].maxId || 0);
if (seqMaxId > 0) {
const safeTarget = seqMaxId + 50;
if (args.dryRun) {
console.log(`[dry-run] would raise ${seqTable} auto_increment to ${safeTarget}`);
} else {
await conn.query(`ALTER TABLE \`${seqTable}\` AUTO_INCREMENT = ${safeTarget}`);
console.log(`[${seqTable}] auto_increment raised to ${safeTarget}`);
}
}
}
console.log(`TOTAL inserted (or would insert): ${totalInserted}`);
} finally {
await conn.end();
}
}
main().catch(error => {
console.error('FAILED:', error && error.message);
process.exit(1);
});

View File

@ -0,0 +1,205 @@
/**
* 合并 wms_inbox_group 中 (warehouse_id, group_id) 相同的重复群记录。
*
* 背景:receiver.js 历史上按 (group_name, warehouse_id) 登记群,
* 群改名后会插入同群ID的新记录,产生重复。
* 合并策略:
* 1. 保留记录:is_blocked=0(启用)优先,其次 created_at 最早。
* 2. 保留记录的名称:取 updated_at 最新一条的名称(即当前最新群名)。
* 3. 其余字段:保留记录为空时,从重复记录中补齐非空值。
* 4. 其余重复记录软删除(deleted_at = NOW())。
*
* 用法:
* node script/merge-inbox-group-duplicates.cjs --dry-run # 只预览,默认
* node script/merge-inbox-group-duplicates.cjs --apply # 实际执行
*/
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const ROOT = process.cwd();
const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js');
const TABLE_NAME = 'wms_inbox_group';
/** 允许从重复记录补齐到保留记录的字段 */
const FILLABLE_FIELDS = [
'store_id',
'group_type',
'sub_type',
'source_type',
'source_extra',
'express_interfaces',
'system_express_code',
];
function parseArgs(argv) {
const args = { dryRun: true, apply: false, dbClient: 'wms', configPath: DEFAULT_CONFIG_PATH };
for (const item of argv) {
if (item === '--apply') args.apply = true;
if (item === '--dry-run') args.dryRun = true;
if (item.startsWith('--db-client=')) args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
if (item.startsWith('--config-path=')) args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim());
}
if (args.apply) args.dryRun = false;
return args;
}
function loadDbClient(configPath, dbClientName) {
if (!fs.existsSync(configPath)) {
throw new Error(`Config file not found: ${configPath}`);
}
const configFactory = require(configPath);
const cfg = typeof configFactory === 'function'
? configFactory({ name: 'wms-inbox-group-merge' })
: configFactory;
const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[dbClientName];
if (!dbClient) {
throw new Error(`MySQL client not found in config.mysql.clients: ${dbClientName}`);
}
return dbClient;
}
async function findDuplicateGroups(conn) {
const [ rows ] = await conn.query(
`SELECT warehouse_id, group_id, COUNT(*) AS cnt
FROM \`${TABLE_NAME}\`
WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL
GROUP BY warehouse_id, group_id
HAVING cnt > 1
ORDER BY warehouse_id, group_id`
);
return rows || [];
}
async function fetchGroupRows(conn, warehouseId, groupId) {
const [ rows ] = await conn.query(
`SELECT id, group_name, group_id, warehouse_id, store_id, group_type, sub_type,
source_type, source_extra, express_interfaces, system_express_code,
ai_enabled, is_blocked, created_at, updated_at, deleted_at
FROM \`${TABLE_NAME}\`
WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL`,
[ warehouseId, groupId ]
);
return rows || [];
}
function pickKeepRow(rows) {
// 启用优先,其次创建时间最早,最后 id 最小
return [ ...rows ].sort((a, b) => {
if (Number(a.is_blocked) !== Number(b.is_blocked)) return Number(a.is_blocked) - Number(b.is_blocked);
if (a.created_at !== b.created_at) return new Date(a.created_at) - new Date(b.created_at);
return a.id - b.id;
})[0];
}
function pickNewestNameRow(rows) {
return [ ...rows ].sort((a, b) => {
const da = new Date(a.updated_at);
const db = new Date(b.updated_at);
if (da !== db) return db - da;
return b.id - a.id;
})[0];
}
function buildMergePlan(rows) {
const keepRow = pickKeepRow(rows);
const nameRow = pickNewestNameRow(rows);
const dropRows = rows.filter(r => r.id !== keepRow.id);
const updates = {};
if (keepRow.group_name !== nameRow.group_name) {
updates.group_name = nameRow.group_name;
}
// 保留记录字段为空时,从重复记录补齐非空值
for (const field of FILLABLE_FIELDS) {
if (keepRow[field] === null || keepRow[field] === undefined || keepRow[field] === '') {
for (const row of rows) {
if (row.id === keepRow.id) continue;
if (row[field] !== null && row[field] !== undefined && row[field] !== '') {
updates[field] = row[field];
break;
}
}
}
}
return { keepRow, nameRow, dropRows, updates };
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const dbClient = loadDbClient(args.configPath, args.dbClient);
const conn = await mysql.createConnection({
host: dbClient.host,
port: dbClient.port,
user: dbClient.user,
password: dbClient.password,
database: dbClient.database,
});
try {
const duplicates = await findDuplicateGroups(conn);
console.log(`发现 ${duplicates.length} 组重复群 (group_id 相同):\n`);
if (duplicates.length === 0) {
console.log('无重复群,无需处理。');
return;
}
let mergedCount = 0;
let updateCount = 0;
for (const dup of duplicates) {
const rows = await fetchGroupRows(conn, dup.warehouse_id, dup.group_id);
if (rows.length < 2) continue;
const { keepRow, nameRow, dropRows, updates } = buildMergePlan(rows);
mergedCount += 1;
if (Object.keys(updates).length > 0) updateCount += 1;
console.log(
`[${dup.warehouse_id}] ${dup.group_id} (${rows.length} 条): ` +
`保留 id=${keepRow.id} "${keepRow.group_name}"`
);
if (updates.group_name) {
console.log(` 名称更新: "${keepRow.group_name}" → "${updates.group_name}"`);
}
const otherUpdates = { ...updates };
delete otherUpdates.group_name;
if (Object.keys(otherUpdates).length > 0) {
console.log(` 字段补齐: ${JSON.stringify(otherUpdates)}`);
}
for (const drop of dropRows) {
console.log(` 软删除: id=${drop.id} "${drop.group_name}" (${drop.is_blocked ? '屏蔽' : '启用'})`);
}
console.log(` 最新名称来源: id=${nameRow.id} "${nameRow.group_name}"`);
if (!args.dryRun) {
if (Object.keys(updates).length > 0) {
await conn.query(
`UPDATE \`${TABLE_NAME}\` SET ? WHERE id = ?`,
[ updates, keepRow.id ]
);
}
for (const drop of dropRows) {
await conn.query(
`UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id = ?`,
[ drop.id ]
);
}
}
}
console.log(`\n${args.dryRun ? '[dry-run] 预览完成' : '执行完成'}: ` +
`共 ${mergedCount} 组重复群,其中 ${updateCount} 组需要更新保留记录。`);
} finally {
await conn.end();
}
}
main().catch(err => {
console.error('执行失败:', err.message);
process.exit(1);
});