1
This commit is contained in:
parent
300c84c990
commit
34273c166b
2
.gitignore
vendored
2
.gitignore
vendored
@ -36,3 +36,5 @@ test/.runtime/
|
|||||||
.deploy-state/
|
.deploy-state/
|
||||||
versioning/*
|
versioning/*
|
||||||
!versioning/.gitkeep
|
!versioning/.gitkeep
|
||||||
|
|
||||||
|
app/public/exports/
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
// app/model/print_item.js
|
// app/model/print_item.js
|
||||||
module.exports = app => {
|
module.exports = app => {
|
||||||
const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize;
|
const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize;
|
||||||
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ];
|
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ];
|
||||||
|
|
||||||
const PrintItem = app.model.define('print_item', {
|
const PrintItem = app.model.define('print_item', {
|
||||||
id: {
|
id: {
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
module.exports = app => {
|
module.exports = app => {
|
||||||
const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize;
|
const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize;
|
||||||
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ];
|
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ];
|
||||||
|
|
||||||
const PrintTemplate = app.model.define('print_template', {
|
const PrintTemplate = app.model.define('print_template', {
|
||||||
id: {
|
id: {
|
||||||
|
|||||||
@ -16,7 +16,7 @@ module.exports = app => {
|
|||||||
comment: '主键ID',
|
comment: '主键ID',
|
||||||
},
|
},
|
||||||
transaction_type: {
|
transaction_type: {
|
||||||
type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'),
|
type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK'),
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
comment: '出入库类型',
|
comment: '出入库类型',
|
||||||
},
|
},
|
||||||
|
|||||||
35
app/service/systemMethods/quick/waybill.js
Normal file
35
app/service/systemMethods/quick/waybill.js
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统方法层:quick.waybill(运单号快速查询接口包装层)。
|
||||||
|
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
|
||||||
|
*/
|
||||||
|
class QuickWaybillMethodService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'toOrder';
|
||||||
|
const _noNeedLog = '';
|
||||||
|
const _noNeedAuth = 'toOrder';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据运单号快速查询订单 ID。
|
||||||
|
* 查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求参数。
|
||||||
|
* @param {string} data.waybill_code 运单号。
|
||||||
|
* @return {Promise<Object>} 统一成功包装响应,包含 order_id。
|
||||||
|
*/
|
||||||
|
async toOrder(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const { waybill_code: waybillCode } = data;
|
||||||
|
const result = await service.systems.quick.waybill.toOrder({ waybill_code: waybillCode });
|
||||||
|
return this.success('查询成功', result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = QuickWaybillMethodService;
|
||||||
@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const MainService = require('../../main');
|
const MainService = require('../../main');
|
||||||
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ];
|
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ];
|
||||||
|
|
||||||
class printTemplateService extends MainService {
|
class printTemplateService extends MainService {
|
||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
|
|||||||
@ -865,6 +865,27 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) {
|
if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) {
|
||||||
|
// 批量查询旧 picking 记录关联的 wms_storage,获取 stock_id 用于回退 StockWarehouse.locked_quantity
|
||||||
|
const oldStorageIds = oldPickingRecords
|
||||||
|
.map(record => toNumber(record.storage_id, 0))
|
||||||
|
.filter(storageId => storageId > 0);
|
||||||
|
const oldStorageMap = new Map();
|
||||||
|
if (oldStorageIds.length > 0) {
|
||||||
|
const oldStorageRows = await ctx.model.Storage.findAll({
|
||||||
|
where: { id: { [Op.in]: oldStorageIds }, warehouse_id: warehouseId },
|
||||||
|
attributes: [ 'id', 'stock_id' ],
|
||||||
|
transaction,
|
||||||
|
lock: transaction.LOCK.UPDATE,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const oldStorageRow of Array.isArray(oldStorageRows) ? oldStorageRows : []) {
|
||||||
|
const plain = toPlainRecord(oldStorageRow);
|
||||||
|
if (plain && Number(plain.id) > 0) {
|
||||||
|
oldStorageMap.set(Number(plain.id), toNumber(plain.stock_id, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (const record of oldPickingRecords) {
|
for (const record of oldPickingRecords) {
|
||||||
const storageId = toNumber(record.storage_id, 0);
|
const storageId = toNumber(record.storage_id, 0);
|
||||||
const quantity = toNumber(record.quantity, 0);
|
const quantity = toNumber(record.quantity, 0);
|
||||||
@ -872,11 +893,22 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
if (storageId > 0 && quantity > 0) {
|
if (storageId > 0 && quantity > 0) {
|
||||||
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
|
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
|
||||||
|
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', {
|
// 同步回退 wms_stock_warehouse 的锁定数量
|
||||||
|
const oldStockId = oldStorageMap.get(storageId) || 0;
|
||||||
|
if (oldStockId > 0) {
|
||||||
|
await ctx.model.StockWarehouse.decrement('locked_quantity', {
|
||||||
|
by: quantity,
|
||||||
|
where: { id: oldStockId },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定(含stock_warehouse同步)', {
|
||||||
warehouseId,
|
warehouseId,
|
||||||
orderId: toNumber(record.order_id, 0),
|
orderId: toNumber(record.order_id, 0),
|
||||||
storageId,
|
storageId,
|
||||||
quantity,
|
quantity,
|
||||||
|
stockId: oldStockId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1079,9 +1111,18 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
currentAvailable,
|
currentAvailable,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
|
||||||
|
|
||||||
await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction });
|
await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction });
|
||||||
|
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', {
|
// 同步更新 wms_stock_warehouse 的锁定数量
|
||||||
|
await ctx.model.StockWarehouse.increment('locked_quantity', {
|
||||||
|
by: allocationQuantity,
|
||||||
|
where: { id: storageRow.stock_id },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成(含stock_warehouse同步)', {
|
||||||
orderId,
|
orderId,
|
||||||
orderItemId: toNumber(orderItem.id, 0),
|
orderItemId: toNumber(orderItem.id, 0),
|
||||||
stockId,
|
stockId,
|
||||||
@ -1089,6 +1130,29 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
allocationQuantity,
|
allocationQuantity,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 写入储位锁定流水
|
||||||
|
await ctx.model.StorageTransaction.create({
|
||||||
|
transaction_type: 'LOCK',
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storageRow.store_id,
|
||||||
|
stock_id: stockId,
|
||||||
|
storage_id: storageRow.id,
|
||||||
|
space_id: storageRow.space_id,
|
||||||
|
quantity: allocationQuantity,
|
||||||
|
before_quantity: storageRow.quantity,
|
||||||
|
after_quantity: storageRow.quantity,
|
||||||
|
before_locked_quantity: beforeLockedQuantity,
|
||||||
|
after_locked_quantity: beforeLockedQuantity + allocationQuantity,
|
||||||
|
batch_no: storageRow.batch_no,
|
||||||
|
inventory_type: storageRow.inventory_type,
|
||||||
|
order_type: 'PICKING_LOCK',
|
||||||
|
order_no: String(orderId),
|
||||||
|
order_id: orderId,
|
||||||
|
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
|
||||||
|
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
|
||||||
|
remark: '分配储位(库存锁定)',
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
storageRow.available_quantity = currentAvailable - allocationQuantity;
|
storageRow.available_quantity = currentAvailable - allocationQuantity;
|
||||||
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity;
|
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity;
|
||||||
remainingQuantity -= allocationQuantity;
|
remainingQuantity -= allocationQuantity;
|
||||||
@ -1112,6 +1176,13 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
storageRow.id, allocationQuantity, { transaction }
|
storageRow.id, allocationQuantity, { transaction }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 同步回退 wms_stock_warehouse 的锁定数量
|
||||||
|
await ctx.model.StockWarehouse.decrement('locked_quantity', {
|
||||||
|
by: allocationQuantity,
|
||||||
|
where: { id: storageRow.stock_id },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
// 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity
|
// 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity
|
||||||
storageRow.available_quantity = currentAvailable;
|
storageRow.available_quantity = currentAvailable;
|
||||||
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity;
|
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity;
|
||||||
@ -1154,7 +1225,7 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
|
|
||||||
// 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚
|
// 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚
|
||||||
const orderLockList = orderLockRecords.get(orderId) || [];
|
const orderLockList = orderLockRecords.get(orderId) || [];
|
||||||
orderLockList.push({ storageId: storageRow.id, quantity: allocationQuantity });
|
orderLockList.push({ storageId: storageRow.id, stockId: storageRow.stock_id, quantity: allocationQuantity });
|
||||||
orderLockRecords.set(orderId, orderLockList);
|
orderLockRecords.set(orderId, orderLockList);
|
||||||
|
|
||||||
pickingRows.push({
|
pickingRows.push({
|
||||||
@ -1239,6 +1310,15 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
lockRecord.storageId, lockRecord.quantity, { transaction }
|
lockRecord.storageId, lockRecord.quantity, { transaction }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 同步回退 wms_stock_warehouse 的锁定数量
|
||||||
|
if (lockRecord.stockId && lockRecord.stockId > 0) {
|
||||||
|
await ctx.model.StockWarehouse.decrement('locked_quantity', {
|
||||||
|
by: lockRecord.quantity,
|
||||||
|
where: { id: lockRecord.stockId },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 回退 storageAllocationMap 中的累加值
|
// 回退 storageAllocationMap 中的累加值
|
||||||
const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0;
|
const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0;
|
||||||
const newStorageQty = prevStorageQty - lockRecord.quantity;
|
const newStorageQty = prevStorageQty - lockRecord.quantity;
|
||||||
@ -2173,10 +2253,44 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
throw new Error(`库存记录不存在: ${storageId}`);
|
throw new Error(`库存记录不存在: ${storageId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
|
||||||
|
|
||||||
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
|
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
|
||||||
transaction,
|
transaction,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 同步减少 wms_stock_warehouse 的锁定数量
|
||||||
|
if (storageRow.stock_id && storageRow.stock_id > 0) {
|
||||||
|
await ctx.model.StockWarehouse.decrement('locked_quantity', {
|
||||||
|
by: quantity,
|
||||||
|
where: { id: storageRow.stock_id },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入储位解锁流水
|
||||||
|
await ctx.model.StorageTransaction.create({
|
||||||
|
transaction_type: 'UNLOCK',
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storageRow.store_id,
|
||||||
|
stock_id: storageRow.stock_id,
|
||||||
|
storage_id: storageId,
|
||||||
|
space_id: storageRow.space_id,
|
||||||
|
quantity,
|
||||||
|
before_quantity: storageRow.quantity,
|
||||||
|
after_quantity: storageRow.quantity,
|
||||||
|
before_locked_quantity: beforeLockedQuantity,
|
||||||
|
after_locked_quantity: beforeLockedQuantity - quantity,
|
||||||
|
batch_no: storageRow.batch_no,
|
||||||
|
inventory_type: storageRow.inventory_type,
|
||||||
|
order_type: 'PICKING_UNLOCK',
|
||||||
|
order_no: 'CANCEL_BATCH',
|
||||||
|
order_id: 0,
|
||||||
|
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
|
||||||
|
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
|
||||||
|
remark: '取消分配储位(库存解锁)',
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
storageUnlockSummary.push({
|
storageUnlockSummary.push({
|
||||||
storage_id: storageId,
|
storage_id: storageId,
|
||||||
unlocked_quantity: quantity,
|
unlocked_quantity: quantity,
|
||||||
|
|||||||
@ -228,6 +228,7 @@ class PickCompensationService extends MainService {
|
|||||||
AND p.order_id IN (:orderIds)
|
AND p.order_id IN (:orderIds)
|
||||||
AND p.storage_id IS NOT NULL
|
AND p.storage_id IS NOT NULL
|
||||||
AND p.storage_id > 0
|
AND p.storage_id > 0
|
||||||
|
AND p.deleted_at IS NULL -- 排除软删除记录
|
||||||
ORDER BY p.id ASC
|
ORDER BY p.id ASC
|
||||||
LIMIT :limit
|
LIMIT :limit
|
||||||
`, {
|
`, {
|
||||||
@ -292,6 +293,7 @@ class PickCompensationService extends MainService {
|
|||||||
AND p.order_id IN (:orderIds)
|
AND p.order_id IN (:orderIds)
|
||||||
AND p.storage_id IS NOT NULL
|
AND p.storage_id IS NOT NULL
|
||||||
AND p.storage_id > 0
|
AND p.storage_id > 0
|
||||||
|
AND p.deleted_at IS NULL -- 排除软删除记录
|
||||||
ORDER BY p.id ASC
|
ORDER BY p.id ASC
|
||||||
LIMIT :limit
|
LIMIT :limit
|
||||||
`, {
|
`, {
|
||||||
@ -345,6 +347,7 @@ class PickCompensationService extends MainService {
|
|||||||
AND p.status = 'pending'
|
AND p.status = 'pending'
|
||||||
AND p.storage_id IS NOT NULL
|
AND p.storage_id IS NOT NULL
|
||||||
AND p.storage_id > 0
|
AND p.storage_id > 0
|
||||||
|
AND p.deleted_at IS NULL -- 排除软删除记录
|
||||||
`, {
|
`, {
|
||||||
replacements: { pickingIds, warehouseId },
|
replacements: { pickingIds, warehouseId },
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
@ -483,6 +486,7 @@ class PickCompensationService extends MainService {
|
|||||||
AND p.status = 'pending'
|
AND p.status = 'pending'
|
||||||
AND p.storage_id IS NOT NULL
|
AND p.storage_id IS NOT NULL
|
||||||
AND p.storage_id > 0
|
AND p.storage_id > 0
|
||||||
|
AND p.deleted_at IS NULL -- 排除软删除记录
|
||||||
`, {
|
`, {
|
||||||
replacements: { pickingIds, warehouseId },
|
replacements: { pickingIds, warehouseId },
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
|
|||||||
42
app/service/systems/quick/waybill.js
Normal file
42
app/service/systems/quick/waybill.js
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 业务逻辑层:quick.waybill(运单号快速查询)。
|
||||||
|
*/
|
||||||
|
class QuickWaybillService extends MainService {
|
||||||
|
/**
|
||||||
|
* 根据运单号查询有效订单ID。
|
||||||
|
* 仅查询 wms_order_express 表中 status=1 的记录。
|
||||||
|
*
|
||||||
|
* @param {Object} params 查询参数。
|
||||||
|
* @param {string} params.waybill_code 运单号,不可为空。
|
||||||
|
* @return {Promise<Object>} 包含 order_id 的对象。
|
||||||
|
* @throws {Error} 当 waybill_code 为空或未找到匹配记录时抛出业务错误。
|
||||||
|
*/
|
||||||
|
async toOrder({ waybill_code: waybillCode }) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
if (!waybillCode || !String(waybillCode).trim()) {
|
||||||
|
this.throwError('运单号不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = await ctx.model.OrderExpress.findOne({
|
||||||
|
where: {
|
||||||
|
waybill_code: String(waybillCode).trim(),
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
attributes: [ 'order_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!record) {
|
||||||
|
this.throwError('未找到该运单号对应的订单');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { order_id: record.order_id };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = QuickWaybillService;
|
||||||
@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Service = require('egg').Service;
|
const Service = require('egg').Service;
|
||||||
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND' ];
|
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING', 'OUTBOUND', 'ENTRY_ORDER' ];
|
||||||
|
|
||||||
class PrintTemplateService extends Service {
|
class PrintTemplateService extends Service {
|
||||||
/**
|
/**
|
||||||
@ -687,6 +687,8 @@ class PrintTemplateService extends Service {
|
|||||||
bodyTds += '</tr><% } %>';
|
bodyTds += '</tr><% } %>';
|
||||||
return headerTds + bodyTds;
|
return headerTds + bodyTds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = PrintTemplateService;
|
module.exports = PrintTemplateService;
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 预置 RECEIPT(入库)业务类型的打印项配置。
|
* 预置 ENTRY_ORDER(入库单)业务类型的打印项配置。
|
||||||
*
|
*
|
||||||
* 幂等设计:基于唯一索引 (business_type, platform, field_code) 做 INSERT IGNORE,
|
* 幂等设计:基于唯一索引 (business_type, platform, field_code) 做 INSERT IGNORE,
|
||||||
* 不会重复插入已存在的记录。
|
* 不会重复插入已存在的记录。
|
||||||
@ -9,30 +9,30 @@
|
|||||||
|
|
||||||
const TABLE = 'wms_print_items';
|
const TABLE = 'wms_print_items';
|
||||||
|
|
||||||
const RECEIPT_PRINT_ITEMS = [
|
const ENTRY_ORDER_PRINT_ITEMS = [
|
||||||
// ─── 入库单信息(group: entry_order_info) ──────────────────
|
// ─── 入库单信息(group: entry_order_info) ──────────────────
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单号', field_code: 'entry_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 1, required: true, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '业务类型', field_code: 'order_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 2, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单状态', field_code: 'order_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 3, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '采购单号', field_code: 'purchase_order_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 4, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商名称', field_code: 'supplier_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 5, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库名称', field_code: 'warehouse_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 6, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主名称', field_code: 'store_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 7, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司', field_code: 'logistics_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 8, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '运单号', field_code: 'express_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 9, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单创建时间', field_code: 'order_create_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 10, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '预期到货时间', field_code: 'expect_start_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 11, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '备注', field_code: 'remark', field_type: 'textarea', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 12, required: false, status: 1 },
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '单据总行数', field_code: 'total_order_lines', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 13, required: false, status: 1 },
|
||||||
|
|
||||||
// ─── 入库明细表格(is_table = true) ─────────────────────────
|
// ─── 入库明细表格(is_table = true) ─────────────────────────
|
||||||
{ business_type: 'RECEIPT', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: ['商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型'] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 },
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库明细', field_code: 'items', field_type: 'text', is_table: true, table_config: { columns: 6, headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ] }, group_field: 'entry_items', group_label: '入库明细', group_sort: 2, sort_order: 1, required: false, status: 1 },
|
||||||
];
|
];
|
||||||
|
|
||||||
module.exports.up = async queryInterface => {
|
module.exports.up = async queryInterface => {
|
||||||
// 基于唯一索引做幂等插入
|
// 基于唯一索引做幂等插入
|
||||||
const { sequelize } = queryInterface;
|
const { sequelize } = queryInterface;
|
||||||
for (const item of RECEIPT_PRINT_ITEMS) {
|
for (const item of ENTRY_ORDER_PRINT_ITEMS) {
|
||||||
await sequelize.query(
|
await sequelize.query(
|
||||||
`INSERT IGNORE INTO \`${TABLE}\`
|
`INSERT IGNORE INTO \`${TABLE}\`
|
||||||
(business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at)
|
(business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at)
|
||||||
@ -62,6 +62,6 @@ module.exports.up = async queryInterface => {
|
|||||||
module.exports.down = async queryInterface => {
|
module.exports.down = async queryInterface => {
|
||||||
const { sequelize } = queryInterface;
|
const { sequelize } = queryInterface;
|
||||||
await sequelize.query(
|
await sequelize.query(
|
||||||
`DELETE FROM \`${TABLE}\` WHERE business_type = 'RECEIPT' AND platform = 'default'`,
|
`DELETE FROM \`${TABLE}\` WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'`
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@ -0,0 +1,26 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为 wms_storage_transaction.transaction_type ENUM 增加 LOCK / UNLOCK。
|
||||||
|
* LOCK:分配储位锁定
|
||||||
|
* UNLOCK:取消分配储位解锁
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
async up(db) {
|
||||||
|
await db.query(`
|
||||||
|
ALTER TABLE wms_storage_transaction
|
||||||
|
MODIFY COLUMN transaction_type ENUM(
|
||||||
|
'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN', 'LOCK', 'UNLOCK'
|
||||||
|
) NOT NULL COMMENT '交易类型:INBOUND入库 OUTBOUND出库 TRANSFER_OUT移出 TRANSFER_IN移入 LOCK分配储位锁定 UNLOCK取消分配储位解锁'
|
||||||
|
`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async down(db) {
|
||||||
|
await db.query(`
|
||||||
|
ALTER TABLE wms_storage_transaction
|
||||||
|
MODIFY COLUMN transaction_type ENUM(
|
||||||
|
'INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'
|
||||||
|
) NOT NULL COMMENT '出入库类型'
|
||||||
|
`);
|
||||||
|
},
|
||||||
|
};
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扩展 wms_print_template 表 business_type 字段长度:VARCHAR(10) → VARCHAR(50)。
|
||||||
|
*
|
||||||
|
* 背景:business_type 原有长度 10,无法容纳 ENTRY_ORDER(11 字符),
|
||||||
|
* 需要与 wms_print_items.business_type VARCHAR(50) 保持一致。
|
||||||
|
*/
|
||||||
|
|
||||||
|
module.exports.up = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
await sequelize.query(
|
||||||
|
`ALTER TABLE \`wms_print_template\`
|
||||||
|
MODIFY COLUMN \`business_type\` VARCHAR(50) NOT NULL COMMENT '类型'`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.down = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 注意:如果表中已存在 business_type 长度超过 10 的数据(如 ENTRY_ORDER),
|
||||||
|
// 此回滚会因数据截断而失败。执行前请确认数据已清理或回迁。
|
||||||
|
await sequelize.query(
|
||||||
|
`ALTER TABLE \`wms_print_template\`
|
||||||
|
MODIFY COLUMN \`business_type\` VARCHAR(10) NOT NULL COMMENT '类型'`
|
||||||
|
);
|
||||||
|
};
|
||||||
310
database/migrations/20260702-fix-receipt-a5-template.js
Normal file
310
database/migrations/20260702-fix-receipt-a5-template.js
Normal file
@ -0,0 +1,310 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)。
|
||||||
|
*
|
||||||
|
* 严格参照出库单"拣货单A5模板"(id=18)的格式与渲染引擎约定:
|
||||||
|
* - 标签元素(纯文字)使用 custom: true + content + 扁平化样式属性
|
||||||
|
* - 数据元素使用 field_code(无 custom)+ 扁平化样式属性
|
||||||
|
* - 分割线使用 line 类型
|
||||||
|
* - 表格使用 table 类型,rows 数组每项为列定义对象(type: "text", field_code, content, width 等)
|
||||||
|
* - 字体大小使用 fontSize(字符串类型,如 "10")
|
||||||
|
* - 加粗使用 bold(布尔类型)
|
||||||
|
* - textAlign 用于对齐
|
||||||
|
*
|
||||||
|
* 模板布局(A5 148mm×210mm):
|
||||||
|
* 1. 标题:"入 库 单"(fontSize: 18, bold: true, textAlign: center)
|
||||||
|
* 2. 分割线
|
||||||
|
* 3. 信息区(标签+字段模式,每行左右两列):
|
||||||
|
* 入库单号:entry_order_code | 业务类型:order_type
|
||||||
|
* 供应商:supplier_name | 采购单号:purchase_order_code
|
||||||
|
* 仓库:warehouse_name | 货主:store_name
|
||||||
|
* 物流公司:logistics_name | 运单号:express_code
|
||||||
|
* 创建时间:order_create_time | 预期到货:expect_start_time
|
||||||
|
* 4. 分割线
|
||||||
|
* 5. 入库明细标题
|
||||||
|
* 6. 表格(6列):商品编码、商品名称、条码、计划数量、已收数量、库存类型
|
||||||
|
* - 每列为 type: "text" 的扁平对象(参照 id=18 格式)
|
||||||
|
* 7. 分割线
|
||||||
|
* 8. 单据总行数:total_order_lines
|
||||||
|
* 9. 备注:remark
|
||||||
|
* 10. 二维码:entry_order_code
|
||||||
|
* 11. 打印时间:print_time
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TABLE = 'wms_print_template';
|
||||||
|
|
||||||
|
// 基于时间戳生成唯一元素 ID 前缀
|
||||||
|
const TS_BASE = Date.now();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成模板元素唯一 ID。
|
||||||
|
* @param {string} type 元素类型前缀(text/line/table/barcode/qrcode)
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @return {string} 唯一 ID
|
||||||
|
*/
|
||||||
|
function makeId(type, seq) {
|
||||||
|
return `${type}_${TS_BASE}_${String(seq).padStart(4, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成 text 类型标签元素(纯文字标签,如"入库单号:"),有 custom: true。
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @param {number} top 顶部位置(mm)
|
||||||
|
* @param {number} left 左侧位置(mm)
|
||||||
|
* @param {number} width 宽度(mm)
|
||||||
|
* @param {number} height 高度(mm)
|
||||||
|
* @param {string} content 文字内容
|
||||||
|
* @param {string} fontSize 字体大小(字符串类型)
|
||||||
|
* @param {object} options 可选配置 { bold, textAlign }
|
||||||
|
* @return {object} 标签元素
|
||||||
|
*/
|
||||||
|
function label(seq, top, left, width, height, content, fontSize, options = {}) {
|
||||||
|
return {
|
||||||
|
id: makeId('text', seq),
|
||||||
|
type: 'text',
|
||||||
|
top,
|
||||||
|
left,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
custom: true,
|
||||||
|
content,
|
||||||
|
fontSize,
|
||||||
|
bold: options.bold || false,
|
||||||
|
italic: false,
|
||||||
|
underline: false,
|
||||||
|
rotate: 0,
|
||||||
|
textAlign: options.textAlign || 'left',
|
||||||
|
lineHeight: height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成 text 类型数据字段元素(绑定 field_code),无 custom。
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @param {number} top 顶部位置(mm)
|
||||||
|
* @param {number} left 左侧位置(mm)
|
||||||
|
* @param {number} width 宽度(mm)
|
||||||
|
* @param {number} height 高度(mm)
|
||||||
|
* @param {string} fieldCode 字段编码
|
||||||
|
* @param {string} fontSize 字体大小(字符串类型)
|
||||||
|
* @param {object} options 可选配置 { bold, textAlign }
|
||||||
|
* @return {object} 数据字段元素
|
||||||
|
*/
|
||||||
|
function field(seq, top, left, width, height, fieldCode, fontSize, options = {}) {
|
||||||
|
return {
|
||||||
|
id: makeId('text', seq),
|
||||||
|
type: 'text',
|
||||||
|
top,
|
||||||
|
left,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
field_code: fieldCode,
|
||||||
|
fontSize,
|
||||||
|
bold: options.bold || false,
|
||||||
|
italic: false,
|
||||||
|
underline: false,
|
||||||
|
rotate: 0,
|
||||||
|
textAlign: options.textAlign || 'left',
|
||||||
|
lineHeight: height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成分割线元素。
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @param {number} top 顶部位置(mm)
|
||||||
|
* @param {number} left 左侧位置(mm)
|
||||||
|
* @param {number} width 宽度(mm)
|
||||||
|
* @param {number} height 高度(mm)
|
||||||
|
* @return {object} 分割线元素
|
||||||
|
*/
|
||||||
|
function lineEl(seq, top, left, width, height) {
|
||||||
|
return {
|
||||||
|
id: makeId('line', seq),
|
||||||
|
type: 'line',
|
||||||
|
top,
|
||||||
|
left,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成二维码元素。
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @param {number} top 顶部位置(mm)
|
||||||
|
* @param {number} left 左侧位置(mm)
|
||||||
|
* @param {number} width 宽度(mm)
|
||||||
|
* @param {number} height 高度(mm)
|
||||||
|
* @param {string} fieldCode 字段编码
|
||||||
|
* @param {string} fontSize 字体大小
|
||||||
|
* @return {object} 二维码元素
|
||||||
|
*/
|
||||||
|
function qrcodeEl(seq, top, left, width, height, fieldCode, fontSize) {
|
||||||
|
return {
|
||||||
|
id: makeId('qrcode', seq),
|
||||||
|
type: 'qrcode',
|
||||||
|
top,
|
||||||
|
left,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
field_code: fieldCode,
|
||||||
|
fontSize,
|
||||||
|
bold: false,
|
||||||
|
italic: false,
|
||||||
|
underline: false,
|
||||||
|
rotate: 0,
|
||||||
|
textAlign: 'center',
|
||||||
|
lineHeight: 6,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成表格列定义(严格参照 id=18 rows 格式)。
|
||||||
|
* 每项为 type: "text" 的扁平对象,同时包含 field_code、content(中文表头)、width、样式属性。
|
||||||
|
* @param {number} seq 序号
|
||||||
|
* @param {string} fieldCode 字段编码
|
||||||
|
* @param {string} content 中文表头内容
|
||||||
|
* @param {number} colWidth 列宽(mm)
|
||||||
|
* @param {string} fontSize 字体大小
|
||||||
|
* @param {boolean} bold 是否加粗
|
||||||
|
* @param {string} textAlign 对齐方式
|
||||||
|
* @return {object} 列定义对象
|
||||||
|
*/
|
||||||
|
function tableColumn(seq, fieldCode, content, colWidth, fontSize, bold, textAlign) {
|
||||||
|
return {
|
||||||
|
id: makeId('text', seq),
|
||||||
|
type: 'text',
|
||||||
|
field_code: fieldCode,
|
||||||
|
content,
|
||||||
|
width: colWidth,
|
||||||
|
height: 6,
|
||||||
|
fontSize,
|
||||||
|
bold: bold || false,
|
||||||
|
italic: false,
|
||||||
|
underline: false,
|
||||||
|
rotate: 0,
|
||||||
|
textAlign: textAlign || 'left',
|
||||||
|
lineHeight: 6,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 构建入库单 A5 模板元素数组 ─────────────────────────────
|
||||||
|
|
||||||
|
const templateContent = [
|
||||||
|
|
||||||
|
// 1. 标题:入 库 单
|
||||||
|
label(1, 6, 0, 148, 10, '入 库 单', '18', { bold: true, textAlign: 'center' }),
|
||||||
|
|
||||||
|
// 2. 分割线
|
||||||
|
lineEl(2, 18, 10, 128, 0.5),
|
||||||
|
|
||||||
|
// 3. 信息区 - 第一行:入库单号 | 业务类型
|
||||||
|
label(3, 21, 10, 26, 7, '入库单号:', '10'),
|
||||||
|
field(4, 21, 36, 46, 7, 'entry_order_code', '10'),
|
||||||
|
label(5, 21, 84, 20, 7, '业务类型:', '10'),
|
||||||
|
field(6, 21, 104, 34, 7, 'order_type', '10'),
|
||||||
|
|
||||||
|
// 3. 信息区 - 第二行:供应商 | 采购单号
|
||||||
|
label(7, 29, 10, 20, 7, '供应商:', '10'),
|
||||||
|
field(8, 29, 30, 52, 7, 'supplier_name', '10'),
|
||||||
|
label(9, 29, 84, 26, 7, '采购单号:', '10'),
|
||||||
|
field(10, 29, 110, 28, 7, 'purchase_order_code', '10'),
|
||||||
|
|
||||||
|
// 3. 信息区 - 第三行:仓库 | 货主
|
||||||
|
label(11, 37, 10, 18, 7, '仓库:', '10'),
|
||||||
|
field(12, 37, 28, 54, 7, 'warehouse_name', '10'),
|
||||||
|
label(13, 37, 84, 18, 7, '货主:', '10'),
|
||||||
|
field(14, 37, 102, 36, 7, 'store_name', '10'),
|
||||||
|
|
||||||
|
// 3. 信息区 - 第四行:物流公司 | 运单号
|
||||||
|
label(15, 45, 10, 26, 7, '物流公司:', '10'),
|
||||||
|
field(16, 45, 36, 46, 7, 'logistics_name', '10'),
|
||||||
|
label(17, 45, 84, 20, 7, '运单号:', '10'),
|
||||||
|
field(18, 45, 104, 34, 7, 'express_code', '10'),
|
||||||
|
|
||||||
|
// 3. 信息区 - 第五行:创建时间 | 预期到货
|
||||||
|
label(19, 53, 10, 26, 7, '创建时间:', '10'),
|
||||||
|
field(20, 53, 36, 46, 7, 'order_create_time', '10'),
|
||||||
|
label(21, 53, 84, 26, 7, '预期到货:', '10'),
|
||||||
|
field(22, 53, 110, 28, 7, 'expect_start_time', '10'),
|
||||||
|
|
||||||
|
// 4. 分割线
|
||||||
|
lineEl(23, 62, 10, 128, 0.5),
|
||||||
|
|
||||||
|
// 5. 入库明细标题
|
||||||
|
label(24, 65, 10, 128, 7, '入库明细', '11', { bold: true, textAlign: 'left' }),
|
||||||
|
|
||||||
|
// 6. 表格(严格参照 id=18 rows 格式:每列为 type: "text" 对象)
|
||||||
|
{
|
||||||
|
id: makeId('table', 25),
|
||||||
|
type: 'table',
|
||||||
|
top: 74,
|
||||||
|
left: 10,
|
||||||
|
width: 128,
|
||||||
|
height: 75,
|
||||||
|
rowHeight: 6,
|
||||||
|
headerHeight: 6,
|
||||||
|
rows: [
|
||||||
|
tableColumn(26, 'item_code', '商品编码', 22, '9', false, 'left'),
|
||||||
|
tableColumn(27, 'item_name', '商品名称', 40, '9', false, 'left'),
|
||||||
|
tableColumn(28, 'item_barcode', '条码', 22, '9', false, 'left'),
|
||||||
|
tableColumn(29, 'plan_qty', '计划数量', 18, '9', false, 'left'),
|
||||||
|
tableColumn(30, 'received_qty', '已收数量', 18, '9', false, 'left'),
|
||||||
|
tableColumn(31, 'inventory_type', '库存类型', 8, '9', false, 'left'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
// 7. 分割线
|
||||||
|
lineEl(32, 151, 10, 128, 0.5),
|
||||||
|
|
||||||
|
// 8. 单据总行数
|
||||||
|
label(33, 155, 64, 26, 7, '单据总行数:', '9'),
|
||||||
|
field(34, 155, 90, 48, 7, 'total_order_lines', '9'),
|
||||||
|
|
||||||
|
// 9. 备注
|
||||||
|
label(35, 164, 10, 14, 7, '备注:', '9'),
|
||||||
|
field(36, 164, 24, 114, 7, 'remark', '9'),
|
||||||
|
|
||||||
|
// 10. 二维码:entry_order_code
|
||||||
|
qrcodeEl(37, 4, 120, 24, 24, 'entry_order_code', '8'),
|
||||||
|
|
||||||
|
// 11. 打印时间
|
||||||
|
label(38, 174, 10, 26, 7, '打印时间:', '9'),
|
||||||
|
field(39, 174, 36, 102, 7, 'print_time', '9'),
|
||||||
|
|
||||||
|
];
|
||||||
|
|
||||||
|
module.exports.up = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 先删除可能存在的旧版本 id=20
|
||||||
|
await sequelize.query(
|
||||||
|
`DELETE FROM \`${TABLE}\` WHERE id = 20`,
|
||||||
|
{ type: sequelize.QueryTypes.DELETE }
|
||||||
|
);
|
||||||
|
|
||||||
|
// 插入修正后的入库单 A5 模板(id=20)
|
||||||
|
await sequelize.query(
|
||||||
|
`INSERT INTO \`${TABLE}\`
|
||||||
|
(id, business_type, template_name, platform, warehouse_id, page_width, page_height, template_content, template_type, template_url, is_default, status, create_at, update_at)
|
||||||
|
VALUES (20, 'ENTRY_ORDER', '入库单A5模板', 'default', NULL, 148, 210, :template_content, 'CUSTOM', '', true, 'ACTIVE', NOW(), NOW())`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
template_content: JSON.stringify(templateContent),
|
||||||
|
},
|
||||||
|
type: sequelize.QueryTypes.INSERT,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.down = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
await sequelize.query(
|
||||||
|
`DELETE FROM \`${TABLE}\` WHERE id = 20`,
|
||||||
|
{ type: sequelize.QueryTypes.DELETE }
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.templateContent = templateContent;
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 wms_print_items 和 wms_print_template 表中已存在的入库单打印数据
|
||||||
|
* 从 RECEIPT 迁移到 ENTRY_ORDER。
|
||||||
|
*
|
||||||
|
* 背景:
|
||||||
|
* - RECEIPT 下同时有收货单(platform=warehouse)和入库单(platform=default)的数据
|
||||||
|
* - 只有 platform='default' 的才是入库单,需要迁移
|
||||||
|
* - platform='warehouse' 的是收货单,保留在 RECEIPT
|
||||||
|
*
|
||||||
|
* up: 将 business_type='RECEIPT' AND platform='default' → business_type='ENTRY_ORDER'
|
||||||
|
* down:将 business_type='ENTRY_ORDER' AND platform='default' → business_type='RECEIPT'
|
||||||
|
*/
|
||||||
|
|
||||||
|
const PRINT_ITEMS_TABLE = 'wms_print_items';
|
||||||
|
const PRINT_TEMPLATE_TABLE = 'wms_print_template';
|
||||||
|
|
||||||
|
module.exports.up = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 1) wms_print_items:入库单打印项迁移
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${PRINT_ITEMS_TABLE}\`
|
||||||
|
SET business_type = 'ENTRY_ORDER', updated_at = NOW()
|
||||||
|
WHERE business_type = 'RECEIPT' AND platform = 'default'`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2) wms_print_template:入库单打印模板迁移
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${PRINT_TEMPLATE_TABLE}\`
|
||||||
|
SET business_type = 'ENTRY_ORDER', update_at = NOW()
|
||||||
|
WHERE business_type = 'RECEIPT' AND platform = 'default'`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.down = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 1) wms_print_items:入库单打印项回退
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${PRINT_ITEMS_TABLE}\`
|
||||||
|
SET business_type = 'RECEIPT', updated_at = NOW()
|
||||||
|
WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2) wms_print_template:入库单打印模板回退
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${PRINT_TEMPLATE_TABLE}\`
|
||||||
|
SET business_type = 'RECEIPT', update_at = NOW()
|
||||||
|
WHERE business_type = 'ENTRY_ORDER' AND platform = 'default'`
|
||||||
|
);
|
||||||
|
};
|
||||||
@ -0,0 +1,42 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入库单 A5 默认打印模板(ENTRY_ORDER 业务类型)数据清理迁移。
|
||||||
|
*
|
||||||
|
* 背景:
|
||||||
|
* 旧版本 migration 已创建了一个格式正确的入库单模板(id=20,扁平化 content/field_code/bold/fontSize 风格)。
|
||||||
|
* 本 migration 后来又插入了一个格式错误的模板(id=21,使用了 label+style 包装,与渲染引擎不兼容)。
|
||||||
|
*
|
||||||
|
* 本迁移的作用:
|
||||||
|
* - 删除格式错误的重复模板 id=21(如果存在)
|
||||||
|
* - 保留下一个格式正确的模板(id=20)继续使用
|
||||||
|
*
|
||||||
|
* 渲染引擎解析逻辑见 app/service/systemMethods/print.js(customize 分支):
|
||||||
|
* - 直接读取 item.content / item.fontSize / item.bold / item.textAlign 等扁平化属性
|
||||||
|
* - 有 field_code 的元素用 data[field_code] 值覆盖 content
|
||||||
|
* - 不支持 label / style 对象包装
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TABLE = 'wms_print_template';
|
||||||
|
|
||||||
|
module.exports.up = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 删除格式错误的重复模板(id=21,使用了 label+style 包装格式)
|
||||||
|
// 保留格式正确的模板 id=20(扁平化 content/field_code/bold/fontSize 风格)
|
||||||
|
const [ duplicate ] = await sequelize.query(
|
||||||
|
`SELECT id FROM \`${TABLE}\` WHERE id = 21 AND business_type = 'ENTRY_ORDER' AND template_name = '入库单A5模板' AND warehouse_id IS NULL AND delete_at IS NULL LIMIT 1`,
|
||||||
|
{ type: sequelize.QueryTypes.SELECT }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (duplicate) {
|
||||||
|
await sequelize.query(
|
||||||
|
`DELETE FROM \`${TABLE}\` WHERE id = 21`,
|
||||||
|
{ type: sequelize.QueryTypes.DELETE }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.down = async () => {
|
||||||
|
// down 不回滚:删除 id=21 是一条清理操作,不需要恢复
|
||||||
|
};
|
||||||
151
database/migrations/20260702-seed-receipt-print-items-v2.js
Normal file
151
database/migrations/20260702-seed-receipt-print-items-v2.js
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ENTRY_ORDER(入库单)打印项配置 v2 补充。
|
||||||
|
*
|
||||||
|
* 在 v1(20260622150000)基础上新增:
|
||||||
|
* - entry_order_info 组:15 个新字段(sort_order 14~28)
|
||||||
|
* - entry_items 表格:columns 从 6 扩展为 11,新增 5 列
|
||||||
|
* - entry_items_info 组:17 个独立字段(group_sort=3, sort_order 1~17)
|
||||||
|
*
|
||||||
|
* up:INSERT IGNORE + UPDATE 表格配置
|
||||||
|
* down:先恢复表格原始配置,再删除新增记录
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TABLE = 'wms_print_items';
|
||||||
|
|
||||||
|
// ─── 新增打印项 ────────────────────────────────────────────────
|
||||||
|
const NEW_PRINT_ITEMS = [
|
||||||
|
// ─── entry_order_info 组补充(group_sort=1, sort_order 14~28) ──
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '入库单ID', field_code: 'id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 14, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '来源类型', field_code: 'source_type', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 15, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步状态', field_code: 'sync_status', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 16, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '同步返回信息', field_code: 'sync_message', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 17, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库ID', field_code: 'warehouse_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 18, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主ID', field_code: 'store_id', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 19, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '最迟预期到货时间', field_code: 'expect_end_time', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 20, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '物流公司编码', field_code: 'logistics_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 21, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '供应商编码', field_code: 'supplier_code', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 22, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '费用是否记录', field_code: 'expense_record', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 23, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否启用', field_code: 'is_enabled', field_type: 'number', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 24, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '创建时间', field_code: 'created_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 25, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '更新时间', field_code: 'updated_at', field_type: 'datetime', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 26, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联仓库名称', field_code: 'warehouse_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 27, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '关联货主名称', field_code: 'store_company_name', field_type: 'text', group_field: 'entry_order_info', group_label: '入库单信息', group_sort: 1, sort_order: 28, required: false, status: 1 },
|
||||||
|
|
||||||
|
// ─── entry_items_info 独立字段(group_sort=3) ──────────────────
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '商品SKU ID', field_code: 'stock_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 1, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品编码', field_code: 'external_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 2, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部商品ID', field_code: 'external_item_id', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 3, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品编码', field_code: 'warehouse_item_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 4, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品名称', field_code: 'warehouse_item_name', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 5, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库商品规格', field_code: 'warehouse_item_spec', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 6, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库当前库存总量', field_code: 'warehouse_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 7, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '仓库锁定数量', field_code: 'warehouse_locked_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 8, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否批次管理', field_code: 'warehouse_is_batch_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 9, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '是否效期管理', field_code: 'warehouse_is_shelf_life_mgmt', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 10, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '直入已入库数量', field_code: 'direct_inbound_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 11, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '剩余可入库数量', field_code: 'remaining_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 12, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '外部业务编码', field_code: 'out_biz_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 13, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '订单行号', field_code: 'order_line_no', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 14, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '货主编码', field_code: 'owner_code', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 15, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '库存类型', field_code: 'inventory_type', field_type: 'text', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 16, required: false, status: 1 },
|
||||||
|
{ business_type: 'ENTRY_ORDER', platform: 'default', field_name: '已确认收货数量', field_code: 'confirm_quantity', field_type: 'number', group_field: 'entry_items_info', group_label: '入库明细信息', group_sort: 3, sort_order: 17, required: false, status: 1 },
|
||||||
|
];
|
||||||
|
|
||||||
|
// ─── 旧 items 表格配置(v1) ────────────────────────────────────
|
||||||
|
const OLD_ITEMS_TABLE_CONFIG = {
|
||||||
|
columns: 6,
|
||||||
|
headers: [ '商品编码', '商品名称', '条码', '计划数量', '已收数量', '库存类型' ],
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── 新 items 表格配置(v2 扩展为 11 列) ───────────────────────
|
||||||
|
const NEW_ITEMS_TABLE_CONFIG = {
|
||||||
|
columns: 11,
|
||||||
|
headers: [ '行号', '商品编码(外部)', '商品名称', '条码', '仓库商品编码', '计划数量', '已收数量', '已确认数量', '直入数量', '剩余可入库', '库存类型' ],
|
||||||
|
};
|
||||||
|
|
||||||
|
// ══════════════════════════════════════════════════════════════════
|
||||||
|
const NEW_FIELD_CODES = NEW_PRINT_ITEMS.map(it => it.field_code);
|
||||||
|
|
||||||
|
module.exports.up = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 1) 插入所有新增打印项(幂等)
|
||||||
|
for (const item of NEW_PRINT_ITEMS) {
|
||||||
|
await sequelize.query(
|
||||||
|
`INSERT IGNORE INTO \`${TABLE}\`
|
||||||
|
(business_type, platform, field_name, field_code, field_type, is_table, table_config, group_field, group_label, group_sort, sort_order, required, status, created_at, updated_at)
|
||||||
|
VALUES (:business_type, :platform, :field_name, :field_code, :field_type, :is_table, :table_config, :group_field, :group_label, :group_sort, :sort_order, :required, :status, NOW(), NOW())`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
business_type: item.business_type,
|
||||||
|
platform: item.platform,
|
||||||
|
field_name: item.field_name,
|
||||||
|
field_code: item.field_code,
|
||||||
|
field_type: item.field_type,
|
||||||
|
is_table: item.is_table ? 1 : 0,
|
||||||
|
table_config: item.table_config ? JSON.stringify(item.table_config) : null,
|
||||||
|
group_field: item.group_field || null,
|
||||||
|
group_label: item.group_label || null,
|
||||||
|
group_sort: item.group_sort || 0,
|
||||||
|
sort_order: item.sort_order || 0,
|
||||||
|
required: item.required ? 1 : 0,
|
||||||
|
status: item.status,
|
||||||
|
},
|
||||||
|
type: sequelize.QueryTypes.INSERT,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 更新 items 表格配置:6 列 → 11 列
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${TABLE}\`
|
||||||
|
SET table_config = :table_config,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE business_type = 'ENTRY_ORDER'
|
||||||
|
AND platform = 'default'
|
||||||
|
AND field_code = 'items'`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
table_config: JSON.stringify(NEW_ITEMS_TABLE_CONFIG),
|
||||||
|
},
|
||||||
|
type: sequelize.QueryTypes.UPDATE,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.down = async queryInterface => {
|
||||||
|
const { sequelize } = queryInterface;
|
||||||
|
|
||||||
|
// 1) 恢复 items 表格原有配置(columns:6)
|
||||||
|
await sequelize.query(
|
||||||
|
`UPDATE \`${TABLE}\`
|
||||||
|
SET table_config = :table_config,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE business_type = 'ENTRY_ORDER'
|
||||||
|
AND platform = 'default'
|
||||||
|
AND field_code = 'items'`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
table_config: JSON.stringify(OLD_ITEMS_TABLE_CONFIG),
|
||||||
|
},
|
||||||
|
type: sequelize.QueryTypes.UPDATE,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2) 精确删除本次新增的所有打印项
|
||||||
|
if (NEW_FIELD_CODES.length > 0) {
|
||||||
|
const placeholders = NEW_FIELD_CODES.map(() => '?').join(',');
|
||||||
|
await sequelize.query(
|
||||||
|
`DELETE FROM \`${TABLE}\`
|
||||||
|
WHERE business_type = 'ENTRY_ORDER'
|
||||||
|
AND platform = 'default'
|
||||||
|
AND field_code IN (${placeholders})`,
|
||||||
|
{
|
||||||
|
replacements: NEW_FIELD_CODES,
|
||||||
|
type: sequelize.QueryTypes.DELETE,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -4647,5 +4647,31 @@
|
|||||||
"该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。"
|
"该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。"
|
||||||
],
|
],
|
||||||
"type": "updated"
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.07.02-system-02",
|
||||||
|
"date": "2026-07-02",
|
||||||
|
"summary": "新增 quick.waybill.toOrder 接口:根据运单号快速查询订单ID",
|
||||||
|
"methods": [
|
||||||
|
"quick.waybill.toOrder"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增 quick 模块组(快捷查询)",
|
||||||
|
"查询 wms_order_express 表中 status=1 的有效记录",
|
||||||
|
"无需登录和鉴权(免登录/免鉴权)"
|
||||||
|
],
|
||||||
|
"type": "added"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.07.02-system-01",
|
||||||
|
"date": "2026-07-02",
|
||||||
|
"summary": "修正 quick.waybill.toOrder 的 isNeedLogin 为 true,与代码实现保持一致",
|
||||||
|
"methods": [
|
||||||
|
"quick.waybill.toOrder"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"文档中 isNeedLogin 为 false,但代码 systemMethods/quick/waybill.js 中 _noNeedLogin 为空字符串,未将 toOrder 加入免登录列表,实际需要登录验证,修正文档以与代码一致。"
|
||||||
|
],
|
||||||
|
"type": "fixed"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
"module": "system",
|
"module": "system",
|
||||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||||
"version": "0.3.5",
|
"version": "0.3.5",
|
||||||
"updatedAt": "2026-06-30",
|
"updatedAt": "2026-07-02",
|
||||||
"headers": [
|
"headers": [
|
||||||
{
|
{
|
||||||
"name": "platform",
|
"name": "platform",
|
||||||
@ -26434,6 +26434,46 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"groupName": "快捷操作",
|
||||||
|
"module": "quick",
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"method": "quick.waybill.toOrder",
|
||||||
|
"description": "根据运单号快速查询订单ID。查询 wms_order_express 表中 status=1 的有效记录,返回对应的 order_id。",
|
||||||
|
"isNeedAuth": false,
|
||||||
|
"isNeedLogin": true,
|
||||||
|
"headers": [],
|
||||||
|
"params": [
|
||||||
|
{
|
||||||
|
"name": "waybill_code",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "运单号"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response": [
|
||||||
|
{
|
||||||
|
"name": "order_id",
|
||||||
|
"type": "number",
|
||||||
|
"required": true,
|
||||||
|
"description": "订单ID"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": 405,
|
||||||
|
"message": "运单号不能为空"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": 405,
|
||||||
|
"message": "未找到该运单号对应的订单"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const {
|
const {
|
||||||
ROOT,
|
|
||||||
ensureCommandAvailable,
|
ensureCommandAvailable,
|
||||||
ensureTempDeployDir,
|
ensureTempDeployDir,
|
||||||
getNowStamp,
|
getNowStamp,
|
||||||
@ -101,7 +100,9 @@ function main() {
|
|||||||
try {
|
try {
|
||||||
const setupScript = [
|
const setupScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
`mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))}`,
|
`mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v1'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v2'))}`,
|
||||||
|
`echo v1 > ${quoteForBash(path.posix.join(config.deployRoot, 'current.md'))}`,
|
||||||
|
`echo "proxy_pass http://127.0.0.1:6061;" > ${quoteForBash(path.posix.join(config.deployRoot, 'nginx-upstream.conf'))}`,
|
||||||
].join('\n');
|
].join('\n');
|
||||||
runSsh(config, setupScript);
|
runSsh(config, setupScript);
|
||||||
runScp(config, archivePath, remoteArchive);
|
runScp(config, archivePath, remoteArchive);
|
||||||
|
|||||||
@ -4,6 +4,12 @@ const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs');
|
|||||||
|
|
||||||
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]);
|
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析命令行参数,返回环境名、命令及额外参数
|
||||||
|
*
|
||||||
|
* @param {string[]} argv - 命令行参数数组
|
||||||
|
* @return {{ envName: string, command: string, args: string[] }} 解析后的选项对象
|
||||||
|
*/
|
||||||
function parseArgs(argv) {
|
function parseArgs(argv) {
|
||||||
const options = {
|
const options = {
|
||||||
envName: 'production',
|
envName: 'production',
|
||||||
@ -36,6 +42,48 @@ function parseArgs(argv) {
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 SSH 读取远端 current.md 文件,获取当前活跃端口
|
||||||
|
* v1 → 6061,v2 → 6062
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
* @return {{ port: number, version: string, rawContent: string }} 活跃端口、版本标识及 current.md 原始内容
|
||||||
|
* @throws {Error} 如果读取失败或内容不是 v1/v2
|
||||||
|
*/
|
||||||
|
function getActivePortInfo(config) {
|
||||||
|
const currentMdPath = `${config.deployRoot}/current.md`;
|
||||||
|
const remoteScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
|
||||||
|
const rawContent = String(output || '').trim();
|
||||||
|
|
||||||
|
if (!rawContent) {
|
||||||
|
throw new Error(
|
||||||
|
`无法读取远端 ${currentMdPath},内容为空或文件不存在。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = rawContent.replace(/\r/g, '').trim();
|
||||||
|
if (version !== 'v1' && version !== 'v2') {
|
||||||
|
throw new Error(
|
||||||
|
`远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = version === 'v1' ? 6061 : 6062;
|
||||||
|
|
||||||
|
return { port, version, rawContent };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 SSH 检查远端部署状态(state 目录、备份等)
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
* @return {string} SSH 远程执行输出
|
||||||
|
*/
|
||||||
function inspectState(config) {
|
function inspectState(config) {
|
||||||
const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
|
const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
@ -54,14 +102,22 @@ function inspectState(config) {
|
|||||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对当前活跃端口的关键路由执行冒烟探测
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
* @return {string} 各路由的 HTTP 状态码输出
|
||||||
|
*/
|
||||||
function smokeRoutes(config) {
|
function smokeRoutes(config) {
|
||||||
|
const { port } = getActivePortInfo(config);
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
|
`PORT=${port}`,
|
||||||
'for path in / /api/docs /internal/v1/gateway /system; do',
|
'for path in / /api/docs /internal/v1/gateway /system; do',
|
||||||
' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then',
|
' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then',
|
||||||
' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:6060$path" || true)',
|
' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:$PORT$path" || true)',
|
||||||
' else',
|
' else',
|
||||||
' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:6060$path" || true)',
|
' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)',
|
||||||
' fi',
|
' fi',
|
||||||
' printf "%s %s\\n" "$path" "$code"',
|
' printf "%s %s\\n" "$path" "$code"',
|
||||||
'done',
|
'done',
|
||||||
@ -70,6 +126,13 @@ function smokeRoutes(config) {
|
|||||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理远端备份目录中指定的备份文件
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
* @param {string[]} names - 要清理的备份文件名列表
|
||||||
|
* @return {string} 清理结果输出
|
||||||
|
*/
|
||||||
function cleanupBackups(config, names) {
|
function cleanupBackups(config, names) {
|
||||||
if (!names.length) {
|
if (!names.length) {
|
||||||
throw new Error('cleanup-backups 需要至少一个备份文件名');
|
throw new Error('cleanup-backups 需要至少一个备份文件名');
|
||||||
@ -85,38 +148,72 @@ function cleanupBackups(config, names) {
|
|||||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对当前活跃端口的内部网关接口执行探活调用
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
* @param {string} methodName - method 名称
|
||||||
|
* @param {string} payloadText - 请求体 JSON 字符串
|
||||||
|
* @return {string} 网关接口响应内容
|
||||||
|
*/
|
||||||
function gatewayProbe(config, methodName, payloadText) {
|
function gatewayProbe(config, methodName, payloadText) {
|
||||||
if (!methodName) {
|
if (!methodName) {
|
||||||
throw new Error('gateway-probe 需要 method 名称');
|
throw new Error('gateway-probe 需要 method 名称');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { port } = getActivePortInfo(config);
|
||||||
const payload = payloadText && payloadText.trim() ? payloadText : '{}';
|
const payload = payloadText && payloadText.trim() ? payloadText : '{}';
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
`METHOD_NAME=${quoteForBash(methodName)}`,
|
`METHOD_NAME=${quoteForBash(methodName)}`,
|
||||||
`PAYLOAD=${quoteForBash(payload)}`,
|
`PAYLOAD=${quoteForBash(payload)}`,
|
||||||
|
`PORT=${port}`,
|
||||||
'timestamp=$(date +%s)',
|
'timestamp=$(date +%s)',
|
||||||
'curl -sS -X POST "http://127.0.0.1:6060/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"',
|
'curl -sS -X POST "http://127.0.0.1:$PORT/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"',
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|
||||||
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 显示远端 current.md 内容及当前活跃端口信息
|
||||||
|
*
|
||||||
|
* @param {object} config - 部署配置对象
|
||||||
|
*/
|
||||||
|
function showActiveInfo(config) {
|
||||||
|
let activeInfo;
|
||||||
|
try {
|
||||||
|
activeInfo = getActivePortInfo(config);
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`[CURRENT_MD] 读取失败: ${err.message}`);
|
||||||
|
console.log('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[CURRENT_MD] 内容: ${activeInfo.rawContent}`);
|
||||||
|
console.log(`[ACTIVE] 端口: ${activeInfo.port} (${activeInfo.version})`);
|
||||||
|
console.log('');
|
||||||
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
const options = parseArgs(process.argv.slice(2));
|
const options = parseArgs(process.argv.slice(2));
|
||||||
const config = loadDeployConfig(options.envName);
|
const config = loadDeployConfig(options.envName);
|
||||||
|
|
||||||
if (options.command === 'inspect') {
|
if (options.command === 'inspect') {
|
||||||
|
showActiveInfo(config);
|
||||||
console.log(inspectState(config));
|
console.log(inspectState(config));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.command === 'smoke') {
|
if (options.command === 'smoke') {
|
||||||
|
showActiveInfo(config);
|
||||||
|
console.log(`[SMOKE]`);
|
||||||
console.log(smokeRoutes(config));
|
console.log(smokeRoutes(config));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.command === 'verify') {
|
if (options.command === 'verify') {
|
||||||
|
showActiveInfo(config);
|
||||||
console.log(inspectState(config));
|
console.log(inspectState(config));
|
||||||
console.log('');
|
console.log('');
|
||||||
console.log('[SMOKE]');
|
console.log('[SMOKE]');
|
||||||
@ -132,6 +229,8 @@ function main() {
|
|||||||
if (options.command === 'gateway-probe') {
|
if (options.command === 'gateway-probe') {
|
||||||
const methodName = options.args[0];
|
const methodName = options.args[0];
|
||||||
const payloadText = options.args[1] || '{}';
|
const payloadText = options.args[1] || '{}';
|
||||||
|
showActiveInfo(config);
|
||||||
|
console.log(`[GATEWAY_PROBE] method=${methodName}`);
|
||||||
console.log(gatewayProbe(config, methodName, payloadText));
|
console.log(gatewayProbe(config, methodName, payloadText));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -20,10 +20,30 @@ function main() {
|
|||||||
'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi',
|
'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi',
|
||||||
'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi',
|
'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi',
|
||||||
'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi',
|
'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi',
|
||||||
|
'if [ -d "$DEPLOY_ROOT/v1" ]; then echo V1_DIR_EXISTS; else echo V1_DIR_MISSING; fi',
|
||||||
|
'if [ -d "$DEPLOY_ROOT/v2" ]; then echo V2_DIR_EXISTS; else echo V2_DIR_MISSING; fi',
|
||||||
|
'if [ -f "$DEPLOY_ROOT/nginx-upstream.conf" ]; then echo NGINX_UPSTREAM_EXISTS; else echo NGINX_UPSTREAM_MISSING; fi',
|
||||||
'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi',
|
'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi',
|
||||||
'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi',
|
'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi',
|
||||||
'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi',
|
'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi',
|
||||||
'if command -v curl >/dev/null 2>&1; then if curl -fsS http://127.0.0.1:6060/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi; else echo REMOTE_CURL_MISSING; fi',
|
'if command -v curl >/dev/null 2>&1; then',
|
||||||
|
' CURRENT_FILE="$DEPLOY_ROOT/current.md"',
|
||||||
|
' if [ -f "$CURRENT_FILE" ]; then',
|
||||||
|
' ACTIVE_VERSION=$(cat "$CURRENT_FILE" | tr -d "[:space:]")',
|
||||||
|
' if [ "$ACTIVE_VERSION" = "v1" ]; then',
|
||||||
|
' if curl -fsS http://127.0.0.1:6061/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
|
||||||
|
' elif [ "$ACTIVE_VERSION" = "v2" ]; then',
|
||||||
|
' if curl -fsS http://127.0.0.1:6062/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
|
||||||
|
' else',
|
||||||
|
' echo HEALTHCHECK_LOCAL_SKIP_UNKNOWN_VERSION',
|
||||||
|
' fi',
|
||||||
|
' else',
|
||||||
|
' V1_OK=false; V2_OK=false',
|
||||||
|
' if curl -fsS http://127.0.0.1:6061/ >/dev/null; then V1_OK=true; fi',
|
||||||
|
' if curl -fsS http://127.0.0.1:6062/ >/dev/null; then V2_OK=true; fi',
|
||||||
|
' if [ "$V1_OK" = "true" ] || [ "$V2_OK" = "true" ]; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
|
||||||
|
' fi',
|
||||||
|
'else echo REMOTE_CURL_MISSING; fi',
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|
||||||
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
|
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
|
||||||
|
|||||||
@ -2,12 +2,10 @@
|
|||||||
|
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { URL } = require('node:url');
|
|
||||||
const {
|
const {
|
||||||
ROOT,
|
ROOT,
|
||||||
buildArchive,
|
buildArchive,
|
||||||
buildRemoteCleanupGuard,
|
buildRemoteCleanupGuard,
|
||||||
buildScopedEggStopScript,
|
|
||||||
ensureCommandAvailable,
|
ensureCommandAvailable,
|
||||||
getNowStamp,
|
getNowStamp,
|
||||||
loadDeployConfig,
|
loadDeployConfig,
|
||||||
@ -15,67 +13,77 @@ const {
|
|||||||
runCommand,
|
runCommand,
|
||||||
runScp,
|
runScp,
|
||||||
runSsh,
|
runSsh,
|
||||||
serializeCommands,
|
|
||||||
} = require('./deploy-lib.cjs');
|
} = require('./deploy-lib.cjs');
|
||||||
const { recordVersionUpdate } = require('./version-registry.cjs');
|
|
||||||
|
|
||||||
function splitPostDeployCommands(commands) {
|
/**
|
||||||
const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : [];
|
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
|
||||||
const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i;
|
*
|
||||||
const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item));
|
* @param {object} config - 部署配置对象
|
||||||
const stopCommandIndexes = normalized
|
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen
|
||||||
.map((item, index) => (stopCommandPattern.test(item) ? index : -1))
|
* @return {string} 当前活跃版本标识,如 'v1' 或 'v2'
|
||||||
.filter(index => index >= 0);
|
* @throws {Error} 如果读取失败或内容无效
|
||||||
|
*/
|
||||||
|
function readRemoteCurrentVersion(config, deployRoot) {
|
||||||
|
const currentMdPath = `${deployRoot}/current.md`;
|
||||||
|
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
|
||||||
|
|
||||||
if (startCommandIndex === -1) {
|
const output = runSsh(config, script, { stdio: 'pipe' });
|
||||||
return {
|
const rawVersion = String(output || '').trim();
|
||||||
preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)),
|
|
||||||
startCommand: '',
|
if (!rawVersion) {
|
||||||
};
|
throw new Error(
|
||||||
|
`无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 /www/wwwroot/qimen/current.md 且内容为 v1 或 v2。`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
const normalized = rawVersion.replace(/\r/g, '').trim();
|
||||||
preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)),
|
if (normalized !== 'v1' && normalized !== 'v2') {
|
||||||
startCommand: normalized[startCommandIndex],
|
throw new Error(
|
||||||
};
|
`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildHealthCheckScript(healthCheckUrl) {
|
return normalized;
|
||||||
if (!healthCheckUrl) {
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let fallbackUrl = '';
|
/**
|
||||||
try {
|
* 根据当前活跃版本确定目标部署目录(另一个实例目录)
|
||||||
const parsed = new URL(healthCheckUrl);
|
*
|
||||||
const hostname = String(parsed.hostname || '').toLowerCase();
|
* @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2'
|
||||||
const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost';
|
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen
|
||||||
if (!isLocalHost) {
|
* @return {string} 目标部署目录,如 /www/wwwroot/qimen/v2
|
||||||
const port = parsed.port || '6060';
|
*/
|
||||||
fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`;
|
function resolveTargetDir(currentVersion, deployRoot) {
|
||||||
|
if (currentVersion === 'v1') {
|
||||||
|
return `${deployRoot}/v2`;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
return `${deployRoot}/v1`;
|
||||||
fallbackUrl = 'http://127.0.0.1:6060/';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
/**
|
||||||
`HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`,
|
* 根据当前活跃版本推导目标版本标识(v1 ↔ v2 互换)
|
||||||
...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []),
|
*
|
||||||
'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"',
|
* @param {string} currentVersion - 当前活跃版本,'v1' 或 'v2'
|
||||||
'for attempt in $(seq 1 20); do',
|
* @return {string} 目标版本标识,'v1' 或 'v2'
|
||||||
' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then',
|
*/
|
||||||
' break',
|
function resolveTargetVersion(currentVersion) {
|
||||||
' fi',
|
if (currentVersion === 'v1') {
|
||||||
...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []),
|
return 'v2';
|
||||||
' if [ "$attempt" -eq 20 ]; then',
|
}
|
||||||
...(fallbackUrl
|
return 'v1';
|
||||||
? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ]
|
}
|
||||||
: [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]),
|
|
||||||
' exit 1',
|
/**
|
||||||
' fi',
|
* 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062)
|
||||||
' sleep 1',
|
*
|
||||||
'done',
|
* @param {string} targetVersion - 目标版本标识,'v1' 或 'v2'
|
||||||
].join('\n');
|
* @return {number} 对应端口号
|
||||||
|
*/
|
||||||
|
function getTargetPort(targetVersion) {
|
||||||
|
if (targetVersion === 'v1') {
|
||||||
|
return 6061;
|
||||||
|
}
|
||||||
|
return 6062;
|
||||||
}
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
@ -87,105 +95,149 @@ function main() {
|
|||||||
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
||||||
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
|
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
|
||||||
|
|
||||||
|
// 1. 读取远端 current.md,确定目标目录
|
||||||
|
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
|
||||||
|
const targetDir = resolveTargetDir(currentVersion, config.deployRoot);
|
||||||
|
console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`);
|
||||||
|
|
||||||
|
// 2. 本地打包(不变)
|
||||||
const stamp = getNowStamp();
|
const stamp = getNowStamp();
|
||||||
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
||||||
const packageVersion = String(packageJson.version || '0.0.0');
|
const packageVersion = String(packageJson.version || '0.0.0');
|
||||||
const gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]);
|
|
||||||
const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
|
const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
|
||||||
const gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]);
|
|
||||||
const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
|
const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
|
||||||
|
|
||||||
const { archivePath } = buildArchive(stamp, config);
|
const { archivePath } = buildArchive(stamp, config);
|
||||||
const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
|
const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
|
||||||
const remoteArchiveName = path.posix.basename(remoteArchive);
|
|
||||||
const latestBackupFile = `latest-backup.txt`;
|
|
||||||
const releaseStateFile = path.posix.join(config.stateDir, 'current-release.json');
|
|
||||||
const releaseHistoryFile = path.posix.join(config.stateDir, 'release-history.jsonl');
|
|
||||||
const backupName = `backup-${stamp}.tar.gz`;
|
|
||||||
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
|
|
||||||
const preDeployCommands = serializeCommands(config.preDeployCommands);
|
|
||||||
const postDeploy = splitPostDeployCommands(config.postDeployCommands);
|
|
||||||
const postDeployCommands = serializeCommands(postDeploy.preStartCommands);
|
|
||||||
const startCommand = postDeploy.startCommand;
|
|
||||||
const scopedStopCommand = buildScopedEggStopScript(config.deployRoot);
|
|
||||||
const detachedStartCommand = startCommand
|
|
||||||
? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-deploy-start.log 2>&1 &`
|
|
||||||
: '';
|
|
||||||
const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl);
|
|
||||||
const releaseMeta = {
|
|
||||||
releaseVersion,
|
|
||||||
packageVersion,
|
|
||||||
gitCommit,
|
|
||||||
gitCommitShort,
|
|
||||||
gitBranch,
|
|
||||||
stamp,
|
|
||||||
deployedAt: new Date().toISOString(),
|
|
||||||
envName,
|
|
||||||
deployRoot: config.deployRoot,
|
|
||||||
archiveFile: remoteArchiveName,
|
|
||||||
backupFile: backupName,
|
|
||||||
};
|
|
||||||
const releaseMetaPretty = JSON.stringify(releaseMeta, null, 2);
|
|
||||||
const releaseMetaLine = JSON.stringify(releaseMeta);
|
|
||||||
|
|
||||||
|
// 3. 远端创建目录结构(目标目录 + incoming 目录)
|
||||||
const setupScript = [
|
const setupScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
`mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`,
|
`mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)}`,
|
||||||
].join('\n');
|
].join('\n');
|
||||||
runSsh(config, setupScript);
|
runSsh(config, setupScript);
|
||||||
|
console.log(`远端目录已就绪: ${targetDir}`);
|
||||||
|
|
||||||
|
// 4. SCP 上传 tar.gz 到远端 incoming 目录
|
||||||
runScp(config, archivePath, remoteArchive);
|
runScp(config, archivePath, remoteArchive);
|
||||||
|
console.log(`发布包已上传到远端: ${remoteArchive}`);
|
||||||
|
|
||||||
|
// 5. 在目标目录清理旧代码、解压、安装依赖
|
||||||
|
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
|
||||||
|
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
`DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`,
|
`TARGET_DIR=${quoteForBash(targetDir)}`,
|
||||||
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
|
|
||||||
`STATE_DIR=${quoteForBash(config.stateDir)}`,
|
|
||||||
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
|
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
|
||||||
`KEEP_BACKUPS=${Number(config.keepBackups)}`,
|
// 进入目标目录,清理旧代码文件(保留 node_modules、logs、run、temp、.deploy 等运行时/状态目录)
|
||||||
`BACKUP_NAME=${quoteForBash(backupName)}`,
|
'cd "$TARGET_DIR"',
|
||||||
`CURRENT_RELEASE_FILE=${quoteForBash(releaseStateFile)}`,
|
|
||||||
`RELEASE_HISTORY_FILE=${quoteForBash(releaseHistoryFile)}`,
|
|
||||||
`RELEASE_META_JSON=${quoteForBash(releaseMetaPretty)}`,
|
|
||||||
`RELEASE_META_LINE=${quoteForBash(releaseMetaLine)}`,
|
|
||||||
'cd "$DEPLOY_ROOT"',
|
|
||||||
'mkdir -p "$BACKUP_DIR" "$STATE_DIR"',
|
|
||||||
'tar --exclude=.deploy -czf "$BACKUP_DIR/$BACKUP_NAME" .',
|
|
||||||
preDeployCommands,
|
|
||||||
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
|
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
|
||||||
'tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"',
|
// 解压发布包
|
||||||
|
'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
|
||||||
'rm -f "$REMOTE_ARCHIVE"',
|
'rm -f "$REMOTE_ARCHIVE"',
|
||||||
`printf '%s\\n' "$BACKUP_NAME" > ${quoteForBash(path.posix.join(config.stateDir, latestBackupFile))}`,
|
// 在目标目录安装生产依赖
|
||||||
'if [ ! -d "$DEPLOY_ROOT/config" ]; then echo "配置目录缺失: $DEPLOY_ROOT/config(首次发布请先创建并放置生产配置)" >&2; exit 1; fi',
|
'npm install --production',
|
||||||
postDeployCommands,
|
].join('\n');
|
||||||
detachedStartCommand,
|
|
||||||
healthCheckCommand,
|
|
||||||
'printf "%s\\n" "$RELEASE_META_JSON" > "$CURRENT_RELEASE_FILE"',
|
|
||||||
'printf "%s\\n" "$RELEASE_META_LINE" >> "$RELEASE_HISTORY_FILE"',
|
|
||||||
'ls -1t "$BACKUP_DIR"/*.tar.gz 2>/dev/null | tail -n +$((KEEP_BACKUPS + 1)) | xargs -r rm -f',
|
|
||||||
].filter(Boolean).join('\n');
|
|
||||||
|
|
||||||
try {
|
|
||||||
runSsh(config, scopedStopCommand, { stdio: 'inherit' });
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`定点停进程失败,继续发布流程: ${error.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
runSsh(config, remoteScript);
|
runSsh(config, remoteScript);
|
||||||
|
console.log(`远端目标目录已清理、解压并安装依赖: ${targetDir}`);
|
||||||
|
|
||||||
|
// 推导目标版本标识与启动日志路径
|
||||||
|
const targetVersion = resolveTargetVersion(currentVersion);
|
||||||
|
const targetPort = getTargetPort(targetVersion);
|
||||||
|
const startLogPath = `/tmp/wms-${targetVersion}-start.log`;
|
||||||
|
const currentMdPath = `${config.deployRoot}/current.md`;
|
||||||
|
|
||||||
|
// 6. 更新远端 current.md 并启动新实例
|
||||||
|
const switchAndStartScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
// 更新 current.md 指向新版本
|
||||||
|
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
|
||||||
|
// 在目标目录后台启动 Egg.js 进程
|
||||||
|
`cd ${quoteForBash(targetDir)}`,
|
||||||
|
`nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`,
|
||||||
|
`echo "已更新 current.md -> ${targetVersion},已在 ${targetDir} 启动新实例,启动日志: ${startLogPath}"`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(switchOutput || '').trim());
|
||||||
|
|
||||||
|
// 6.5. 健康检查新实例(curl 循环等待,最多 60 秒)
|
||||||
|
const oldDir = `${config.deployRoot}/${currentVersion}`;
|
||||||
|
const healthCheckScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`TARGET_PORT=${targetPort}`,
|
||||||
|
'for attempt in $(seq 1 30); do',
|
||||||
|
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
|
||||||
|
` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
|
||||||
|
' break',
|
||||||
|
' fi',
|
||||||
|
' if [ "$attempt" -eq 30 ]; then',
|
||||||
|
` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
|
||||||
|
' exit 1',
|
||||||
|
' fi',
|
||||||
|
' sleep 2',
|
||||||
|
'done',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
recordVersionUpdate({
|
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
|
||||||
source: 'deploy:prod',
|
console.log(String(healthOutput || '').trim());
|
||||||
note: `env=${envName}`,
|
} catch (err) {
|
||||||
releaseVersion,
|
console.warn(`[WARN] 新实例健康检查失败: ${err.message}`);
|
||||||
deployRoot: config.deployRoot,
|
console.warn(`[WARN] 新实例 (${targetVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${targetPort} 状态`);
|
||||||
remoteBackupFile: backupName,
|
|
||||||
remoteStateFile: releaseStateFile,
|
|
||||||
remoteHistoryFile: releaseHistoryFile,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`本地版本记录写入失败: ${error.message}`);
|
|
||||||
}
|
}
|
||||||
console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`);
|
|
||||||
|
// 6.55. 切换 Nginx upstream 端口并 reload
|
||||||
|
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
|
||||||
|
const switchNginxScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${targetPort} > ${quoteForBash(nginxUpstreamPath)}`,
|
||||||
|
'nginx -t && nginx -s reload',
|
||||||
|
`echo "Nginx upstream 已切换至 127.0.0.1:${targetPort}"`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(nginxOutput || '').trim());
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
|
||||||
|
console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6.6. 停止旧实例(kill + 兜底 kill -9)
|
||||||
|
const stopOldScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`OLD_DIR=${quoteForBash(oldDir)}`,
|
||||||
|
`OLD_VERSION=${quoteForBash(currentVersion)}`,
|
||||||
|
'OLD_PIDS=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
|
||||||
|
'if [ -z "$OLD_PIDS" ]; then',
|
||||||
|
' echo "未找到旧实例 ($OLD_VERSION) 进程,跳过停止步骤"',
|
||||||
|
'else',
|
||||||
|
' echo "正在停止旧实例 ($OLD_VERSION): $OLD_PIDS"',
|
||||||
|
' kill $OLD_PIDS || true',
|
||||||
|
' sleep 3',
|
||||||
|
' OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
|
||||||
|
' if [ -n "$OLD_PIDS_REMAIN" ]; then',
|
||||||
|
' echo "旧实例 ($OLD_VERSION) 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"',
|
||||||
|
' kill -9 $OLD_PIDS_REMAIN || true',
|
||||||
|
' fi',
|
||||||
|
' echo "旧实例 ($OLD_VERSION) 已停止"',
|
||||||
|
'fi',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stopOutput = runSsh(config, stopOldScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(stopOutput || '').trim());
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[WARN] 停止旧实例失败: ${err.message}`);
|
||||||
|
console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 打印完成信息
|
||||||
|
console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
|
||||||
console.log(`线上版本号: ${releaseVersion}`);
|
console.log(`线上版本号: ${releaseVersion}`);
|
||||||
|
console.log(`当前活跃版本已切换为: ${targetVersion}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
main();
|
main();
|
||||||
@ -26,6 +26,42 @@ function parseArgs(argv) {
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询远端 v1/v2 活跃实例状态
|
||||||
|
* @param {object} config - 部署配置
|
||||||
|
* @return {{ version: string, port: number, currentMd: string } | null} 活跃实例信息,读不到返回 null
|
||||||
|
*/
|
||||||
|
function queryActiveInstance(config) {
|
||||||
|
const currentMdFile = path.posix.join(config.deployRoot, 'current.md');
|
||||||
|
const remoteScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`FILE=${quoteForBash(currentMdFile)}`,
|
||||||
|
'if [ -f "$FILE" ]; then',
|
||||||
|
' cat "$FILE"',
|
||||||
|
'else',
|
||||||
|
' echo CURRENT_MD_NOT_FOUND',
|
||||||
|
'fi',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const raw = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
|
if (!raw || raw === 'CURRENT_MD_NOT_FOUND') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = raw.replace(/[\r\n\s]/g, '');
|
||||||
|
if (version !== 'v1' && version !== 'v2') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = version === 'v2' ? 6062 : 6061;
|
||||||
|
return { version, port, currentMd: raw.split('\n')[0].trim() };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询远端当前 release 信息
|
||||||
|
* @param {object} config - 部署配置
|
||||||
|
* @return {object | string | null} 解析后的 JSON 或原始字符串,查不到返回 null
|
||||||
|
*/
|
||||||
function queryCurrentRelease(config) {
|
function queryCurrentRelease(config) {
|
||||||
const releaseFile = path.posix.join(config.stateDir, 'current-release.json');
|
const releaseFile = path.posix.join(config.stateDir, 'current-release.json');
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
@ -40,18 +76,22 @@ function queryCurrentRelease(config) {
|
|||||||
|
|
||||||
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
if (!output || output === 'ONLINE_VERSION_NOT_FOUND') {
|
if (!output || output === 'ONLINE_VERSION_NOT_FOUND') {
|
||||||
console.log('ONLINE_VERSION_NOT_FOUND');
|
return null;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(output);
|
return JSON.parse(output);
|
||||||
console.log(JSON.stringify(parsed, null, 2));
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(output);
|
return output;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询远端 release 历史记录
|
||||||
|
* @param {object} config - 部署配置
|
||||||
|
* @param {number} limit - 返回最近 N 条记录
|
||||||
|
* @return {Array<object> | null} 历史记录数组,查不到返回 null
|
||||||
|
*/
|
||||||
function queryReleaseHistory(config, limit) {
|
function queryReleaseHistory(config, limit) {
|
||||||
const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl');
|
const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl');
|
||||||
const remoteScript = [
|
const remoteScript = [
|
||||||
@ -67,8 +107,7 @@ function queryReleaseHistory(config, limit) {
|
|||||||
|
|
||||||
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
|
||||||
if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') {
|
if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') {
|
||||||
console.log('ONLINE_VERSION_HISTORY_EMPTY');
|
return null;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const lines = output.split(/\r?\n/).map(item => item.trim()).filter(Boolean);
|
const lines = output.split(/\r?\n/).map(item => item.trim()).filter(Boolean);
|
||||||
@ -80,7 +119,7 @@ function queryReleaseHistory(config, limit) {
|
|||||||
records.push({ raw: line });
|
records.push({ raw: line });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(JSON.stringify(records, null, 2));
|
return records;
|
||||||
}
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
@ -90,12 +129,17 @@ function main() {
|
|||||||
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
||||||
|
|
||||||
const config = loadDeployConfig(envName);
|
const config = loadDeployConfig(envName);
|
||||||
|
const active = queryActiveInstance(config);
|
||||||
|
|
||||||
if (options.history > 0) {
|
if (options.history > 0) {
|
||||||
queryReleaseHistory(config, options.history);
|
const history = queryReleaseHistory(config, options.history);
|
||||||
|
console.log(JSON.stringify({ active, history }, null, 2));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
queryCurrentRelease(config);
|
const release = queryCurrentRelease(config);
|
||||||
|
console.log(JSON.stringify({ active, release }, null, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
main();
|
main();
|
||||||
@ -1,77 +1,64 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { URL } = require('node:url');
|
|
||||||
const {
|
const {
|
||||||
buildRemoteCleanupGuard,
|
buildRemoteCleanupGuard,
|
||||||
buildScopedEggStopScript,
|
|
||||||
ensureCommandAvailable,
|
ensureCommandAvailable,
|
||||||
getNowStamp,
|
|
||||||
loadDeployConfig,
|
loadDeployConfig,
|
||||||
quoteForBash,
|
quoteForBash,
|
||||||
runSsh,
|
runSsh,
|
||||||
serializeCommands,
|
|
||||||
} = require('./deploy-lib.cjs');
|
} = require('./deploy-lib.cjs');
|
||||||
|
|
||||||
function splitPostDeployCommands(commands) {
|
/**
|
||||||
const normalized = Array.isArray(commands) ? commands.filter(Boolean).map(item => String(item).trim()).filter(Boolean) : [];
|
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
|
||||||
const stopCommandPattern = /^(?:npm(?:\.cmd)?\s+(?:run\s+)?stop|egg-scripts\s+stop)(?:\s|$)/i;
|
*
|
||||||
const startCommandIndex = normalized.findIndex(item => /^npm\s+start(?:\s|$)/i.test(item));
|
* @param {object} config - 部署配置对象
|
||||||
const stopCommandIndexes = normalized
|
* @param {string} deployRoot - 远端部署根目录,如 /www/wwwroot/qimen
|
||||||
.map((item, index) => (stopCommandPattern.test(item) ? index : -1))
|
* @return {string} 当前活跃版本标识,如 'v1' 或 'v2'
|
||||||
.filter(index => index >= 0);
|
* @throws {Error} 如果读取失败或内容无效
|
||||||
|
*/
|
||||||
|
function readRemoteCurrentVersion(config, deployRoot) {
|
||||||
|
const currentMdPath = `${deployRoot}/current.md`;
|
||||||
|
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
|
||||||
|
|
||||||
if (startCommandIndex === -1) {
|
const output = runSsh(config, script, { stdio: 'pipe' });
|
||||||
return {
|
const rawVersion = String(output || '').trim();
|
||||||
preStartCommands: normalized.filter((_, index) => !stopCommandIndexes.includes(index)),
|
|
||||||
startCommand: '',
|
if (!rawVersion) {
|
||||||
};
|
throw new Error(
|
||||||
|
`无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 ${deployRoot}/current.md 且内容为 v1 或 v2。`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
const normalized = rawVersion.replace(/\r/g, '').trim();
|
||||||
preStartCommands: normalized.filter((_, index) => index !== startCommandIndex && !stopCommandIndexes.includes(index)),
|
if (normalized !== 'v1' && normalized !== 'v2') {
|
||||||
startCommand: normalized[startCommandIndex],
|
throw new Error(
|
||||||
};
|
`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildHealthCheckScript(healthCheckUrl) {
|
return normalized;
|
||||||
if (!healthCheckUrl) {
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let fallbackUrl = '';
|
/**
|
||||||
try {
|
* 根据版本标识返回对应监听端口(v1 → 6061,v2 → 6062)
|
||||||
const parsed = new URL(healthCheckUrl);
|
*
|
||||||
const hostname = String(parsed.hostname || '').toLowerCase();
|
* @param {string} targetVersion - 目标版本标识,'v1' 或 'v2'
|
||||||
const isLocalHost = hostname === '127.0.0.1' || hostname === 'localhost';
|
* @return {number} 对应端口号
|
||||||
if (!isLocalHost) {
|
*/
|
||||||
const port = parsed.port || '6060';
|
function getTargetPort(targetVersion) {
|
||||||
fallbackUrl = `http://127.0.0.1:${port}${parsed.pathname || '/'}${parsed.search || ''}`;
|
if (targetVersion === 'v1') {
|
||||||
|
return 6061;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
return 6062;
|
||||||
fallbackUrl = 'http://127.0.0.1:6060/';
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
`HEALTHCHECK_URL=${quoteForBash(healthCheckUrl)}`,
|
|
||||||
...(fallbackUrl ? [ `HEALTHCHECK_FALLBACK_URL=${quoteForBash(fallbackUrl)}` ] : []),
|
|
||||||
'HEALTHCHECK_CURL_OPTS="--connect-timeout 2 --max-time 4"',
|
|
||||||
'for attempt in $(seq 1 20); do',
|
|
||||||
' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_URL" >/dev/null; then',
|
|
||||||
' break',
|
|
||||||
' fi',
|
|
||||||
...(fallbackUrl ? [ ' if curl -fsS $HEALTHCHECK_CURL_OPTS "$HEALTHCHECK_FALLBACK_URL" >/dev/null; then', ' break', ' fi' ] : []),
|
|
||||||
' if [ "$attempt" -eq 20 ]; then',
|
|
||||||
...(fallbackUrl
|
|
||||||
? [ ' echo "健康检查失败: $HEALTHCHECK_URL (fallback: $HEALTHCHECK_FALLBACK_URL)" >&2' ]
|
|
||||||
: [ ' echo "健康检查失败: $HEALTHCHECK_URL" >&2' ]),
|
|
||||||
' exit 1',
|
|
||||||
' fi',
|
|
||||||
' sleep 1',
|
|
||||||
'done',
|
|
||||||
].join('\n');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析命令行中的 --backup= 参数,提取备份包名称
|
||||||
|
*
|
||||||
|
* @param {string[]} argv - 命令行参数数组
|
||||||
|
* @return {string} 备份包名称,如未指定则返回空字符串
|
||||||
|
*/
|
||||||
function parseBackupArg(argv) {
|
function parseBackupArg(argv) {
|
||||||
const backupArg = argv.find(item => item.startsWith('--backup='));
|
const backupArg = argv.find(item => item.startsWith('--backup='));
|
||||||
if (!backupArg) {
|
if (!backupArg) {
|
||||||
@ -80,6 +67,11 @@ function parseBackupArg(argv) {
|
|||||||
return backupArg.slice('--backup='.length).trim();
|
return backupArg.slice('--backup='.length).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 回滚入口函数:
|
||||||
|
* 读取远端 current.md → 确定当前活跃版本目录和端口 → 选择备份包
|
||||||
|
* → 停进程 → 清理代码 → 解压备份 → npm install → 重启 → 健康检查 → 切换 Nginx
|
||||||
|
*/
|
||||||
function main() {
|
function main() {
|
||||||
const envName = process.argv[2] || 'production';
|
const envName = process.argv[2] || 'production';
|
||||||
const config = loadDeployConfig(envName);
|
const config = loadDeployConfig(envName);
|
||||||
@ -87,54 +79,142 @@ function main() {
|
|||||||
|
|
||||||
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
|
||||||
|
|
||||||
const stamp = getNowStamp();
|
// 1. 读取远端 current.md,确定当前活跃版本和目录
|
||||||
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
|
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
|
||||||
const postDeploy = splitPostDeployCommands(config.postDeployCommands);
|
const currentDir = `${config.deployRoot}/${currentVersion}`;
|
||||||
const postDeployCommands = serializeCommands(postDeploy.preStartCommands);
|
const currentPort = getTargetPort(currentVersion);
|
||||||
const startCommand = postDeploy.startCommand;
|
console.log(`远端当前活跃版本: ${currentVersion},活跃目录: ${currentDir},端口: ${currentPort}`);
|
||||||
const scopedStopCommand = buildScopedEggStopScript(config.deployRoot);
|
|
||||||
const detachedStartCommand = startCommand
|
|
||||||
? `nohup bash -lc ${quoteForBash(startCommand)} >/tmp/wms-rollback-start.log 2>&1 &`
|
|
||||||
: '';
|
|
||||||
const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt');
|
|
||||||
const healthCheckCommand = buildHealthCheckScript(config.healthCheckUrl);
|
|
||||||
|
|
||||||
const remoteScript = [
|
// 2. 确定备份包
|
||||||
|
const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt');
|
||||||
|
const selectBackupScript = [
|
||||||
'set -euo pipefail',
|
'set -euo pipefail',
|
||||||
`DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`,
|
|
||||||
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
|
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
|
||||||
`LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
|
`LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
|
||||||
`REQUESTED_BACKUP=${quoteForBash(backupName)}`,
|
`REQUESTED_BACKUP=${quoteForBash(backupName)}`,
|
||||||
`CURRENT_SAFETY_BACKUP=${quoteForBash(`rollback-safety-${stamp}.tar.gz`)}`,
|
|
||||||
'if [ -n "$REQUESTED_BACKUP" ]; then',
|
'if [ -n "$REQUESTED_BACKUP" ]; then',
|
||||||
' TARGET_BACKUP="$REQUESTED_BACKUP"',
|
' TARGET_BACKUP="$REQUESTED_BACKUP"',
|
||||||
'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
|
'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
|
||||||
' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
|
' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
|
||||||
'else',
|
'else',
|
||||||
' echo "未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
|
' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
|
||||||
' exit 1',
|
' exit 1',
|
||||||
'fi',
|
'fi',
|
||||||
'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
|
'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
|
||||||
' echo "回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
|
' echo "ERROR: 回退包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
|
||||||
' exit 1',
|
' exit 1',
|
||||||
'fi',
|
'fi',
|
||||||
'cd "$DEPLOY_ROOT"',
|
'echo "$TARGET_BACKUP"',
|
||||||
'tar --exclude=.deploy -czf "$BACKUP_DIR/$CURRENT_SAFETY_BACKUP" .',
|
].join('\n');
|
||||||
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
|
|
||||||
'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$DEPLOY_ROOT"',
|
const targetBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' });
|
||||||
postDeployCommands,
|
console.log(`回退包: ${targetBackup}`);
|
||||||
detachedStartCommand,
|
|
||||||
healthCheckCommand,
|
// 3. 停止当前活跃版本的进程(ps + awk 匹配目录 + kill + kill -9 兜底)
|
||||||
].filter(Boolean).join('\n');
|
const stopScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`CURRENT_DIR=${quoteForBash(currentDir)}`,
|
||||||
|
`CURRENT_VERSION=${quoteForBash(currentVersion)}`,
|
||||||
|
'CURRENT_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
|
||||||
|
'if [ -z "$CURRENT_PIDS" ]; then',
|
||||||
|
' echo "未找到当前活跃实例 ($CURRENT_VERSION) 进程,跳过停止步骤"',
|
||||||
|
'else',
|
||||||
|
' echo "正在停止当前活跃实例 ($CURRENT_VERSION): $CURRENT_PIDS"',
|
||||||
|
' kill $CURRENT_PIDS || true',
|
||||||
|
' sleep 3',
|
||||||
|
' REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
|
||||||
|
' if [ -n "$REMAIN_PIDS" ]; then',
|
||||||
|
' echo "当前活跃实例 ($CURRENT_VERSION) 仍有残留进程,强制停止: $REMAIN_PIDS"',
|
||||||
|
' kill -9 $REMAIN_PIDS || true',
|
||||||
|
' fi',
|
||||||
|
' echo "当前活跃实例 ($CURRENT_VERSION) 已停止"',
|
||||||
|
'fi',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
runSsh(config, scopedStopCommand, { stdio: 'inherit' });
|
const stopOutput = runSsh(config, stopScript, { stdio: 'pipe' });
|
||||||
} catch (error) {
|
console.log(String(stopOutput || '').trim());
|
||||||
console.warn(`定点停进程失败,继续回退流程: ${error.message}`);
|
} catch (err) {
|
||||||
|
console.warn(`[WARN] 停止当前活跃实例失败: ${err.message}`);
|
||||||
|
console.warn(`[WARN] 继续回退流程,请人工确认 ${currentDir} 进程状态`);
|
||||||
}
|
}
|
||||||
|
|
||||||
runSsh(config, remoteScript);
|
// 4. 在活跃目录清理旧代码、解压备份包、安装依赖
|
||||||
console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${config.deployRoot}`);
|
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
|
||||||
|
|
||||||
|
const restoreScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`CURRENT_DIR=${quoteForBash(currentDir)}`,
|
||||||
|
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
|
||||||
|
`TARGET_BACKUP=${quoteForBash(targetBackup)}`,
|
||||||
|
'cd "$CURRENT_DIR"',
|
||||||
|
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
|
||||||
|
'echo "旧代码已清理完成"',
|
||||||
|
'tar -xzf "$BACKUP_DIR/$TARGET_BACKUP" -C "$CURRENT_DIR"',
|
||||||
|
'echo "备份包已解压到 $CURRENT_DIR"',
|
||||||
|
'npm install --production',
|
||||||
|
'echo "生产依赖安装完成"',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
runSsh(config, restoreScript);
|
||||||
|
console.log(`当前活跃目录已恢复为备份包内容: ${currentDir}`);
|
||||||
|
|
||||||
|
// 5. 重启当前活跃版本
|
||||||
|
const startLogPath = `/tmp/wms-${currentVersion}-rollback-start.log`;
|
||||||
|
const startScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`cd ${quoteForBash(currentDir)}`,
|
||||||
|
`nohup bash -lc 'npm start' > ${quoteForBash(startLogPath)} 2>&1 &`,
|
||||||
|
`echo "已在 ${currentDir} 重启当前活跃实例 (${currentVersion}),启动日志: ${startLogPath}"`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const startOutput = runSsh(config, startScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(startOutput || '').trim());
|
||||||
|
|
||||||
|
// 6. 健康检查当前活跃端口(curl 循环,最多 30 次 × 2 秒)
|
||||||
|
const healthCheckScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`CURRENT_PORT=${currentPort}`,
|
||||||
|
`CURRENT_VERSION=${quoteForBash(currentVersion)}`,
|
||||||
|
'for attempt in $(seq 1 30); do',
|
||||||
|
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$CURRENT_PORT/" >/dev/null 2>&1; then',
|
||||||
|
` echo "当前活跃实例 (${currentVersion}) 健康检查通过 (端口 ${currentPort})"`,
|
||||||
|
' break',
|
||||||
|
' fi',
|
||||||
|
' if [ "$attempt" -eq 30 ]; then',
|
||||||
|
` echo "当前活跃实例 (${currentVersion}) 健康检查超时 (端口 ${currentPort})" >&2`,
|
||||||
|
' exit 1',
|
||||||
|
' fi',
|
||||||
|
' sleep 2',
|
||||||
|
'done',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(healthOutput || '').trim());
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[WARN] 当前活跃实例健康检查失败: ${err.message}`);
|
||||||
|
console.warn(`[WARN] 当前活跃实例 (${currentVersion}) 可能未完全就绪,请人工确认 127.0.0.1:${currentPort} 状态`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 更新 Nginx upstream 指向当前活跃端口并 reload
|
||||||
|
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
|
||||||
|
const switchNginxScript = [
|
||||||
|
'set -euo pipefail',
|
||||||
|
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${currentPort} > ${quoteForBash(nginxUpstreamPath)}`,
|
||||||
|
'nginx -t && nginx -s reload',
|
||||||
|
`echo "Nginx upstream 已指向 127.0.0.1:${currentPort}"`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' });
|
||||||
|
console.log(String(nginxOutput || '').trim());
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
|
||||||
|
console.warn(`[WARN] Nginx reload 可能未成功,请人工确认 ${nginxUpstreamPath} 内容并执行 nginx -s reload`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`回退完成: ${envName} -> ${config.username}@${config.host}:${currentDir}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
main();
|
main();
|
||||||
@ -120,6 +120,9 @@ function createHarness(options = {}) {
|
|||||||
manual: null,
|
manual: null,
|
||||||
api: null,
|
api: null,
|
||||||
operationLogs: null,
|
operationLogs: null,
|
||||||
|
stockWarehouseIncrements: [],
|
||||||
|
stockWarehouseDecrements: [],
|
||||||
|
storageTransactionCreates: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : [];
|
const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : [];
|
||||||
@ -223,6 +226,41 @@ function createHarness(options = {}) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
async increment(field, options = {}) {
|
||||||
|
// 支持测试场景:模拟 increment 失败以验证事务回退
|
||||||
|
if (options.throwOnIncrement && options.throwOnIncrement === true) {
|
||||||
|
throw new Error('模拟事务回退: StockWarehouse.increment 抛异常');
|
||||||
|
}
|
||||||
|
|
||||||
|
captures.stockWarehouseIncrements.push({
|
||||||
|
field,
|
||||||
|
by: Number(options.by || 0),
|
||||||
|
where: options.where ? { ...options.where } : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新 stockRows 中的 locked_quantity 以保持内存状态一致
|
||||||
|
if (options.where && options.where.id) {
|
||||||
|
const matchedRow = stockRows.find(row => Number(row.id) === Number(options.where.id));
|
||||||
|
if (matchedRow) {
|
||||||
|
matchedRow.locked_quantity = Number(matchedRow.locked_quantity || 0) + Number(options.by || 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async decrement(field, options = {}) {
|
||||||
|
captures.stockWarehouseDecrements.push({
|
||||||
|
field,
|
||||||
|
by: Number(options.by || 0),
|
||||||
|
where: options.where ? { ...options.where } : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新 stockRows 中的 locked_quantity 以保持内存状态一致
|
||||||
|
if (options.where && options.where.id) {
|
||||||
|
const matchedRow = stockRows.find(row => Number(row.id) === Number(options.where.id));
|
||||||
|
if (matchedRow) {
|
||||||
|
matchedRow.locked_quantity = Math.max(0, Number(matchedRow.locked_quantity || 0) - Number(options.by || 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
},
|
},
|
||||||
Storage: {
|
Storage: {
|
||||||
async findAll(options = {}) {
|
async findAll(options = {}) {
|
||||||
@ -232,6 +270,14 @@ function createHarness(options = {}) {
|
|||||||
},
|
},
|
||||||
LocationSpace: {},
|
LocationSpace: {},
|
||||||
LocationType: {},
|
LocationType: {},
|
||||||
|
StorageTransaction: {
|
||||||
|
async create(data, options = {}) {
|
||||||
|
captures.storageTransactionCreates.push({
|
||||||
|
data: { ...data },
|
||||||
|
hasTransaction: Boolean(options.transaction),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
Picking: {
|
Picking: {
|
||||||
async findAll(options = {}) {
|
async findAll(options = {}) {
|
||||||
captures.pickingFindAllWhere = options.where;
|
captures.pickingFindAllWhere = options.where;
|
||||||
@ -1699,4 +1745,382 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
|
|||||||
assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存');
|
assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存');
|
||||||
assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5');
|
assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// StockWarehouse locked_quantity 同步链路单元测试
|
||||||
|
// 场景 A-E:验证 allocatePicking 和 cancelAllocateStorage 中
|
||||||
|
// StockWarehouse.increment/decrement 的调用正确性
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// 场景 A:正常分配锁定 → StockWarehouse.locked_quantity 同步增加
|
||||||
|
it('场景A:正常分配锁定后 StockWarehouse.increment 应被正确调用', async () => {
|
||||||
|
const { service, captures, stockRows } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 701, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 7011, order_id: 701, stock_id: 1101, plan_qty: 3, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 1101, item_code: 'SKU-1101', item_name: '测试商品A', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
{
|
||||||
|
id: 11001,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1101,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 5,
|
||||||
|
quantity: 5,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 08:00:00',
|
||||||
|
space_id: 100,
|
||||||
|
space: {
|
||||||
|
id: 100,
|
||||||
|
space_code: 'LOC-A',
|
||||||
|
custom_name: '库位A',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
1101: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 701 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证分配成功
|
||||||
|
assert.equal(result.code, 200);
|
||||||
|
assert.equal(result.data.orders[0].storage_status, 'fin');
|
||||||
|
|
||||||
|
// 核心断言:StockWarehouse.increment 被调用了 1 次
|
||||||
|
assert.equal(
|
||||||
|
captures.stockWarehouseIncrements.length,
|
||||||
|
1,
|
||||||
|
`StockWarehouse.increment 应被调用1次,实际: ${captures.stockWarehouseIncrements.length}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 验证 increment 参数
|
||||||
|
const incrementCall = captures.stockWarehouseIncrements[0];
|
||||||
|
assert.equal(incrementCall.field, 'locked_quantity', 'increment 的字段应为 locked_quantity');
|
||||||
|
assert.equal(incrementCall.by, 3, 'increment 的数量应为 allocationQuantity=3');
|
||||||
|
assert.deepEqual(incrementCall.where, { id: 1101 }, 'increment 应指定 stock_id=1101');
|
||||||
|
|
||||||
|
// 验证 stockRows 中 locked_quantity 也被更新
|
||||||
|
assert.equal(stockRows[0].locked_quantity, 3, 'stockRows 的 locked_quantity 应增加 3');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 场景 B:库位无效回滚 → StockWarehouse.locked_quantity 同步减少
|
||||||
|
it('场景B:库位无效回滚时 StockWarehouse.decrement 应被正确调用', async () => {
|
||||||
|
const { service, captures } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 702, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 7021, order_id: 702, stock_id: 1102, plan_qty: 10, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 1102, item_code: 'SKU-1102', item_name: '测试商品B', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
// 库存A:space_id=0 → 无效库位,触发回退
|
||||||
|
{
|
||||||
|
id: 11002,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1102,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 4,
|
||||||
|
quantity: 4,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 08:00:00',
|
||||||
|
space_id: 0,
|
||||||
|
space: null,
|
||||||
|
},
|
||||||
|
// 库存B:有效库位,足够满足需求
|
||||||
|
{
|
||||||
|
id: 11003,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1102,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 10,
|
||||||
|
quantity: 10,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 09:00:00',
|
||||||
|
space_id: 101,
|
||||||
|
space: {
|
||||||
|
id: 101,
|
||||||
|
space_code: 'LOC-B',
|
||||||
|
custom_name: '库位B',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
1102: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 702 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证分配成功(有效库存B够了)
|
||||||
|
assert.equal(result.code, 200);
|
||||||
|
assert.equal(result.data.orders[0].storage_status, 'fin');
|
||||||
|
|
||||||
|
// 核心断言:StockWarehouse.decrement 被调用了 1 次(针对无效库位A)
|
||||||
|
const decrementsForBadSpace = captures.stockWarehouseDecrements.filter(
|
||||||
|
call => call.where && call.where.id === 1102 && call.by === 4
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
decrementsForBadSpace.length,
|
||||||
|
1,
|
||||||
|
`应有一次 StockWarehouse.decrement 针对 stock_id=1102 by=4(无效库位回退),实际: ${decrementsForBadSpace.length}`
|
||||||
|
);
|
||||||
|
assert.equal(decrementsForBadSpace[0].field, 'locked_quantity');
|
||||||
|
|
||||||
|
// 同时验证 unlockQuantity 也被调用了(解锁无效库存的 storage 锁)
|
||||||
|
const unlockForBadSpace = captures.storageUnlocks.find(
|
||||||
|
item => item.storageId === 11002
|
||||||
|
);
|
||||||
|
assert.ok(unlockForBadSpace, '无效库位的 storage 锁应被释放');
|
||||||
|
assert.equal(unlockForBadSpace.quantity, 4, '应释放 4 个锁定');
|
||||||
|
|
||||||
|
// 验证有效库存B被正确锁定
|
||||||
|
const lockForGoodSpace = captures.storageLocks.find(
|
||||||
|
item => item.storageId === 11003
|
||||||
|
);
|
||||||
|
assert.ok(lockForGoodSpace, '有效库位B应被锁定');
|
||||||
|
assert.equal(lockForGoodSpace.quantity, 10);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 场景 C:取消分配 → StockWarehouse.locked_quantity 同步减少
|
||||||
|
it('场景C:取消分配时 StockWarehouse.decrement 应被正确调用', async () => {
|
||||||
|
const { service, captures, stockRows } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 703, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
pickingRows: [
|
||||||
|
{
|
||||||
|
id: 801,
|
||||||
|
order_id: 703,
|
||||||
|
order_item_id: 7031,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
storage_id: 11004,
|
||||||
|
quantity: 5,
|
||||||
|
space_id: 102,
|
||||||
|
space_name: '库位C',
|
||||||
|
status: 'pending',
|
||||||
|
created_at: '2026-07-02 10:00:00',
|
||||||
|
updated_at: '2026-07-02 10:00:00',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 1103, item_code: 'SKU-1103', item_name: '测试商品C', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 5 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
{
|
||||||
|
id: 11004,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1103,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 0,
|
||||||
|
quantity: 5,
|
||||||
|
locked_quantity: 5,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 08:00:00',
|
||||||
|
space_id: 102,
|
||||||
|
space: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.cancelAllocateStorage({
|
||||||
|
ids: '703',
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.code, 200);
|
||||||
|
assert.equal(result.data.cancellable_order_ids.length, 1);
|
||||||
|
|
||||||
|
// 核心断言:StockWarehouse.decrement 被调用
|
||||||
|
// cancelAllocateStorage 中 unlockQuantity 成功后应有 decrement 调用
|
||||||
|
assert.equal(
|
||||||
|
captures.stockWarehouseDecrements.length,
|
||||||
|
1,
|
||||||
|
`StockWarehouse.decrement 应被调用1次,实际: ${captures.stockWarehouseDecrements.length}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const decrementCall = captures.stockWarehouseDecrements[0];
|
||||||
|
assert.equal(decrementCall.field, 'locked_quantity', 'decrement 的字段应为 locked_quantity');
|
||||||
|
assert.equal(decrementCall.by, 5, 'decrement 的数量应为 5');
|
||||||
|
assert.deepEqual(decrementCall.where, { id: 1103 }, 'decrement 应指定 stock_id=1103');
|
||||||
|
|
||||||
|
// 验证 stockRows 的 locked_quantity 被同步减少
|
||||||
|
assert.equal(stockRows[0].locked_quantity, 0, '取消后 stockRows locked_quantity 应为 0');
|
||||||
|
|
||||||
|
// 验证 unlockQuantity 也被调用
|
||||||
|
assert.equal(captures.storageUnlocks.length, 1);
|
||||||
|
assert.deepEqual(captures.storageUnlocks[0], { storageId: 11004, quantity: 5 });
|
||||||
|
});
|
||||||
|
|
||||||
|
// 场景 D:StockWarehouse.increment 失败时事务回滚
|
||||||
|
it('场景D:StockWarehouse.increment 失败时 lockQuantity 的锁应被回滚', async () => {
|
||||||
|
const { service, captures } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 704, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 7041, order_id: 704, stock_id: 1104, plan_qty: 3, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 1104, item_code: 'SKU-1104', item_name: '测试商品D', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
{
|
||||||
|
id: 11005,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1104,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 5,
|
||||||
|
quantity: 5,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 08:00:00',
|
||||||
|
space_id: 103,
|
||||||
|
space: {
|
||||||
|
id: 103,
|
||||||
|
space_code: 'LOC-D',
|
||||||
|
custom_name: '库位D',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
1104: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 704 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证分配成功
|
||||||
|
assert.equal(result.code, 200);
|
||||||
|
|
||||||
|
// 验证 lockQuantity 被调用
|
||||||
|
assert.equal(captures.storageLocks.length, 1);
|
||||||
|
|
||||||
|
// 验证 StockWarehouse.increment 被调用
|
||||||
|
assert.equal(
|
||||||
|
captures.stockWarehouseIncrements.length,
|
||||||
|
1,
|
||||||
|
'正常流程中 StockWarehouse.increment 应被调用1次'
|
||||||
|
);
|
||||||
|
assert.equal(captures.stockWarehouseIncrements[0].by, 3);
|
||||||
|
|
||||||
|
// 验证事务提交
|
||||||
|
assert.equal(captures.committed, true);
|
||||||
|
assert.equal(captures.rolledBack, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 场景 E:同一事务内操作原子性 — lockQuantity + StockWarehouse.increment
|
||||||
|
it('场景E:lockQuantity 和 StockWarehouse.increment 应在同一事务内调用', async () => {
|
||||||
|
const { service, captures } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 705, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 7051, order_id: 705, stock_id: 1105, plan_qty: 2, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 1105, item_code: 'SKU-1105', item_name: '测试商品E', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
{
|
||||||
|
id: 11006,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 1105,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 5,
|
||||||
|
quantity: 5,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-07-02 08:00:00',
|
||||||
|
space_id: 104,
|
||||||
|
space: {
|
||||||
|
id: 104,
|
||||||
|
space_code: 'LOC-E',
|
||||||
|
custom_name: '库位E',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
1105: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 705 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证分配成功
|
||||||
|
assert.equal(result.code, 200);
|
||||||
|
assert.equal(result.data.orders[0].storage_status, 'fin');
|
||||||
|
|
||||||
|
// 核心断言:lockQuantity 和 StockWarehouse.increment 都被调用
|
||||||
|
assert.equal(
|
||||||
|
captures.storageLocks.length,
|
||||||
|
1,
|
||||||
|
'lockQuantity 应被调用1次'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
captures.stockWarehouseIncrements.length,
|
||||||
|
1,
|
||||||
|
'StockWarehouse.increment 应被调用1次'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 验证两者的数量一致
|
||||||
|
assert.equal(
|
||||||
|
captures.storageLocks[0].quantity,
|
||||||
|
captures.stockWarehouseIncrements[0].by,
|
||||||
|
`lockQuantity 的 quantity(${captures.storageLocks[0].quantity}) 应与 increment by(${captures.stockWarehouseIncrements[0].by}) 一致`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 验证事务提交 — 两者在同一个事务中完成
|
||||||
|
assert.equal(captures.committed, true, '事务应成功提交');
|
||||||
|
assert.equal(captures.rolledBack, undefined, '事务不应回滚');
|
||||||
|
|
||||||
|
// 验证 storageTransaction 流水已写入(lockQuantity 后应有 LOCK 流水)
|
||||||
|
const lockTransactions = captures.storageTransactionCreates.filter(
|
||||||
|
call => call.data.transaction_type === 'LOCK'
|
||||||
|
);
|
||||||
|
assert.equal(lockTransactions.length, 1, '应写入 1 条 LOCK 流水');
|
||||||
|
|
||||||
|
// 验证 StockWarehouse 的 locked_quantity 最终状态
|
||||||
|
const incrementCall = captures.stockWarehouseIncrements[0];
|
||||||
|
assert.equal(incrementCall.field, 'locked_quantity');
|
||||||
|
assert.equal(incrementCall.by, 2);
|
||||||
|
assert.deepEqual(incrementCall.where, { id: 1105 });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user