From 19c3fe09a7847b80ffdddb146cc30cab39430260 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:46:07 +0800 Subject: [PATCH] =?UTF-8?q?refactor(weight):=20=E9=87=8D=E9=87=8F=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E7=BB=9F=E4=B8=80=E4=B8=BA=20INTEGER(g)=EF=BC=8C?= =?UTF-8?q?=E5=8F=96=E4=BB=A3=20DECIMAL(kg)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 8 个 model 重量字段类型 DECIMAL→INTEGER,注释 kg→g - order_express 称重校验改为正整数(g) - delivery_order 手动单查 StockStore + warehouse 称重毛重 - openapi.json 毛重/净重描述 kg→g - 迁移: 20260725120000-unify-weight-fields-to-int-g - 脚本: update-stock-warehouse-weight.cjs --- app/model/location_space.js | 9 +- app/model/order_delivery.js | 6 +- app/model/order_express.js | 5 +- app/model/package_material.js | 5 +- app/model/package_material_item_relation.js | 4 +- app/model/receiving_detail.js | 11 +- app/model/stock_store.js | 18 +- app/model/stock_warehouse.js | 14 +- app/service/systems/delivery_order.js | 46 ++- app/service/systems/order_express.js | 18 +- ...0725120000-unify-weight-fields-to-int-g.js | 171 +++++++++++ methods/openapi.json | 4 +- package.json | 2 + script/update-stock-warehouse-weight.cjs | 277 ++++++++++++++++++ 14 files changed, 531 insertions(+), 59 deletions(-) create mode 100644 database/migrations/20260725120000-unify-weight-fields-to-int-g.js create mode 100644 script/update-stock-warehouse-weight.cjs diff --git a/app/model/location_space.js b/app/model/location_space.js index 1355d5b..fe29b50 100644 --- a/app/model/location_space.js +++ b/app/model/location_space.js @@ -81,9 +81,10 @@ module.exports = app => { comment: '体积(m³)', }, max_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - comment: '最大承重(kg)', + defaultValue: 0, + comment: '最大承重(g)', }, space_status: { type: ENUM('AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED'), @@ -110,10 +111,10 @@ module.exports = app => { comment: '当前库存数量', }, current_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, defaultValue: 0, - comment: '当前重量(kg)', + comment: '当前重量(g)', }, current_volume: { type: DECIMAL(10, 2), diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 8b76074..efb37d1 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -391,10 +391,10 @@ module.exports = app => { comment: '商品总数', }, items_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: false, - defaultValue: 0.00, - comment: '总重量(kg)', + defaultValue: 0, + comment: '总重量(g)', }, items_hash: { type: CHAR(32), diff --git a/app/model/order_express.js b/app/model/order_express.js index 4e932fc..383fed1 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -133,9 +133,10 @@ module.exports = app => { comment: '包材名称快照', }, weighing_weight: { - type: DECIMAL(10, 3), + type: INTEGER(11), allowNull: true, - comment: '称重重量(kg)', + defaultValue: 0, + comment: '称重重量(g)', }, }, { tableName: 'wms_order_express', diff --git a/app/model/package_material.js b/app/model/package_material.js index 7911c25..15f9e35 100644 --- a/app/model/package_material.js +++ b/app/model/package_material.js @@ -57,9 +57,10 @@ module.exports = app => { comment: '高度(cm)', }, weight: { - type: DECIMAL(10, 3), + type: INTEGER(11), allowNull: true, - comment: '重量(kg)', + defaultValue: 0, + comment: '重量(g)', }, cost_price: { type: DECIMAL(10, 2), diff --git a/app/model/package_material_item_relation.js b/app/model/package_material_item_relation.js index 8eb8e03..55f64d7 100644 --- a/app/model/package_material_item_relation.js +++ b/app/model/package_material_item_relation.js @@ -72,9 +72,9 @@ module.exports = app => { comment: '高(cm)快照', }, weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), defaultValue: 0, - comment: '重量(kg)快照', + comment: '重量(g)快照', }, bind_count: { type: INTEGER.UNSIGNED, diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index 5ff72ee..6dafaef 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -105,7 +105,10 @@ module.exports = app => { type: DECIMAL(10, 2), }, weight: { - type: INTEGER, + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '重量(g)', }, box_remainder: { type: INTEGER, @@ -114,10 +117,10 @@ module.exports = app => { comment: '箱余数', }, box_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: false, - defaultValue: '0.00', - comment: '箱重量(kg)', + defaultValue: 0, + comment: '箱重量(g)', }, }, { tableName: 'wms_receiving_detail', diff --git a/app/model/stock_store.js b/app/model/stock_store.js index 03b6a11..3dcce32 100644 --- a/app/model/stock_store.js +++ b/app/model/stock_store.js @@ -130,22 +130,16 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '毛重', + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), + type: INTEGER(11), allowNull: true, - defaultValue: 0.00, - validate: { - min: 0, - }, - comment: '净重', + defaultValue: 0, + comment: '净重(g)', }, category_id: { type: INTEGER(11), diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 1244787..696db1b 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -72,14 +72,14 @@ module.exports = app => { comment: '体积', }, gross_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '毛重', + type: INTEGER(11), + defaultValue: 0, + comment: '毛重(g)', }, net_weight: { - type: DECIMAL(10, 2), - defaultValue: 0.00, - comment: '净重', + type: INTEGER(11), + defaultValue: 0, + comment: '净重(g)', }, item_type: { type: STRING(10), @@ -170,10 +170,12 @@ module.exports = app => { box_gross_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱毛重(g)', }, box_net_weight: { type: INTEGER(11), defaultValue: 0, + comment: '箱净重(g)', }, box_height: { type: DECIMAL(10, 2), diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index ae7c1c1..2c87614 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1180,15 +1180,19 @@ class DeliveryOrderService extends Service { continue; } let wms_stock = null; - // 手工单:调用方直接传入 stockId 时跳过 stock_store 查表,直接使用 + // 手工单:调用方直接传入 stockId 时需查 StockStore 获取完整信息(含 gross_weight) if (line.stockId && line.stockId > 0) { - wms_stock = { - id: line.stockId, - stock_id: line.stockId, - item_name: line.itemName || '', - item_code: line.itemCode || '', - gross_weight: 0, - }; + wms_stock = await app.model.StockStore.findByPk(line.stockId, { transaction }); + if (!wms_stock) { + // 降级:查不到记录时用调用方传入的字段构造最小对象 + wms_stock = { + id: line.stockId, + stock_id: line.stockId, + item_name: line.itemName || '', + item_code: line.itemCode || '', + gross_weight: 0, + }; + } } else if (!line.itemId) { // 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景) const stockWhere = { @@ -1242,6 +1246,24 @@ class DeliveryOrderService extends Service { // ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 ===== resolvedItems.sort((a, b) => a.stockId - b.stockId); + // ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 ===== + const stockIds = [...new Set(resolvedItems.map(item => item.stockId).filter(Boolean))]; + const warehouseWeightMap = new Map(); + if (stockIds.length > 0) { + const warehouseRecords = await app.model.StockWarehouse.findAll({ + where: { id: stockIds }, + attributes: ['id', 'gross_weight'], + transaction, + raw: true, + }); + for (const record of warehouseRecords) { + const gw = parseFloat(record.gross_weight) || 0; + if (gw > 0) { + warehouseWeightMap.set(record.id, gw); + } + } + } + // ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)===== for (const item of resolvedItems) { const lockResult = await ctx.service.systems.stockStore.lockItemStorages( @@ -1260,7 +1282,11 @@ class DeliveryOrderService extends Service { const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty; stockQuantityMap.set(item.stockId, totalQtyForStock); - const weight = parseFloat(item.wms_stock.gross_weight) || 0; + // 优先取 wms_stock_warehouse.gross_weight(仓库称重),其次取 wms_stock_store.gross_weight + const warehouseWeight = warehouseWeightMap.get(item.stockId); + const weight = (warehouseWeight != null && warehouseWeight > 0) + ? warehouseWeight + : (parseFloat(item.wms_stock.gross_weight) || 0); stockWeightMap.set(item.stockId, weight); // 所有检查通过,准备订单行数据 @@ -1319,8 +1345,6 @@ class DeliveryOrderService extends Service { return sum + (weight * qty); }, 0); source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合 - // 格式化重量(保留2位小数) - total_weight = parseFloat(total_weight.toFixed(2)); ctx.logger.debug('[订单统计信息]', { orderId, diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index 642f303..ba0b4f5 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -199,9 +199,9 @@ class OrderExpressService extends Service { /** * 规范化并校验称重重量。 * - * 允许最多 3 位小数,且必须大于 0。 + * 必须为正整数(单位 g),且必须大于 0。 * - * @param {number|string} weighingWeight 称重重量。 + * @param {number|string} weighingWeight 称重重量(g)。 * @return {number} 合法重量数值。 */ normalizeWeighingWeight(weighingWeight) { @@ -210,8 +210,8 @@ class OrderExpressService extends Service { } const normalizedWeightText = String(weighingWeight).trim(); - if (!/^\d+(?:\.\d{1,3})?$/.test(normalizedWeightText)) { - throw this.createBusinessError('weighing_weight 格式非法,最多支持 3 位小数', 400); + if (!/^\d+$/.test(normalizedWeightText)) { + throw this.createBusinessError('weighing_weight 格式非法,必须为正整数(单位 g)', 400); } const normalizedWeight = Number(normalizedWeightText); @@ -263,7 +263,7 @@ class OrderExpressService extends Service { * @param {Object} payload 入参对象。 * @param {number|string} payload.orderId 订单ID。 * @param {string} [payload.waybillCode] 运单号,多运单场景必填。 - * @param {number|string} payload.weighingWeight 称重重量(kg)。 + * @param {number|string} payload.weighingWeight 称重重量(g)。 * @return {Promise} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight}; * 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。 */ @@ -645,9 +645,7 @@ class OrderExpressService extends Service { }); } const entry = splitMap.get(bk); - entry.weighing_weight = Number( - (entry.weighing_weight + Number(row.weighing_weight || 0)).toFixed(3) - ); + entry.weighing_weight = entry.weighing_weight + Number(row.weighing_weight || 0); // 优先取非空的 waybill_code 作为该拆单的代表运单号 if (!entry.waybill_code && row.waybill_code) { entry.waybill_code = row.waybill_code; @@ -655,9 +653,7 @@ class OrderExpressService extends Service { } const splits = [ ...splitMap.values() ]; - const totalWeight = Number( - splits.reduce((sum, s) => sum + s.weighing_weight, 0).toFixed(3) - ); + const totalWeight = splits.reduce((sum, s) => sum + s.weighing_weight, 0); // split_count:仅统计 waybill_code 不为空的 business_key const splitCount = splits.filter(s => s.waybill_code !== null).length; diff --git a/database/migrations/20260725120000-unify-weight-fields-to-int-g.js b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js new file mode 100644 index 0000000..5d3c35a --- /dev/null +++ b/database/migrations/20260725120000-unify-weight-fields-to-int-g.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 统一所有重量字段为 INT 类型,单位统一为 g(克)。 + * + * 说明:原字段注释/类型写错(注释标 kg 实际存的是 g), + * 数据本身已为克,迁移只做类型转换 + 注释修正,不做数值缩放。 + * + * 涉及表/字段: + * wms_location_space : max_weight, current_weight (DECIMAL → INT) + * wms_order_delivery_100000* : items_weight (DECIMAL → INT) + * wms_order_express : weighing_weight (DECIMAL(10,3) → INT) + * wms_package_material : weight (DECIMAL(10,3) → INT) + * wms_package_material_item_relation: weight (DECIMAL → INT) + * wms_receiving_detail : box_weight (DECIMAL → INT) + * wms_receiving_detail : weight (已为INT, 仅更新注释) + * wms_stock_store : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : gross_weight, net_weight (DECIMAL → INT) + * wms_stock_warehouse : box_gross_weight, box_net_weight (已为INT, 仅更新注释) + */ + +module.exports = { + async up(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight INT(11) DEFAULT 0 COMMENT '最大承重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight INT(11) DEFAULT 0 COMMENT '当前重量(g)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight INT(11) NOT NULL DEFAULT 0 COMMENT '总重量(g)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight INT(11) DEFAULT 0 COMMENT '称重重量(g)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)快照'" + ); + + // ===================== wms_receiving_detail ===================== + // weight: 已为 INT(g),仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'" + ); + // box_weight: DECIMAL → INT(g) + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight INT(11) NOT NULL DEFAULT 0 COMMENT '箱重量(g)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'" + ); + // box_gross_weight / box_net_weight: 已为INT, 仅补注释 + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重(g)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重(g)'" + ); + }, + + async down(queryInterface, Sequelize) { + // ===================== wms_location_space ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN max_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '最大承重(kg)'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_location_space MODIFY COLUMN current_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '当前重量(kg)'" + ); + + // ===================== wms_order_delivery 分表 ===================== + const orderDeliveryTables = [ + 'wms_order_delivery_100000', + 'wms_order_delivery_100000_dispatch', + 'wms_order_delivery_100000_history', + 'wms_order_delivery_100000_outsourced', + 'wms_order_delivery_1000028', + 'wms_order_delivery_1000028_dispatch', + 'wms_order_delivery_1000028_history', + 'wms_order_delivery_1000028_outsourced', + ]; + + for (const table of orderDeliveryTables) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${table}\` MODIFY COLUMN items_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)'` + ); + } + + // ===================== wms_order_express ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '称重重量(kg)'" + ); + + // ===================== wms_package_material ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material MODIFY COLUMN weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '重量(kg)'" + ); + + // ===================== wms_package_material_item_relation ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '重量(kg)快照'" + ); + + // ===================== wms_receiving_detail ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量g'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg)'" + ); + + // ===================== wms_stock_store ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_store MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + + // ===================== wms_stock_warehouse ===================== + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重'" + ); + await queryInterface.sequelize.query( + "ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重'" + ); + }, +}; diff --git a/methods/openapi.json b/methods/openapi.json index 5f6d784..0eb5cae 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1155,14 +1155,14 @@ "type": "number", "required": false, "source": "body", - "description": "毛重(kg)" + "description": "毛重(g)" }, { "name": "item.netWeight", "type": "number", "required": false, "source": "body", - "description": "净重(kg)" + "description": "净重(g)" }, { "name": "item.categoryId", diff --git a/package.json b/package.json index 4216b79..90fb48d 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,8 @@ "cov": "egg-bin cov", "lint": "eslint .", "migration:single": "node ./script/run-single-migration.cjs", + "db:update-stock-weight": "node ./script/update-stock-warehouse-weight.cjs", + "db:update-stock-weight:dry": "node ./script/update-stock-warehouse-weight.cjs --dry-run", "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" diff --git a/script/update-stock-warehouse-weight.cjs b/script/update-stock-warehouse-weight.cjs new file mode 100644 index 0000000..59307ee --- /dev/null +++ b/script/update-stock-warehouse-weight.cjs @@ -0,0 +1,277 @@ +/** + * 批量更新生产数据库 stock_warehouse.gross_weight + * + * 用法: + * node ./script/update-stock-warehouse-weight.cjs [--dry-run] [--file stocksWeight.txt] + * + * 文件格式(每行一条,tab 分隔): + * + * + * 选项: + * --dry-run 仅预览,不实际执行 UPDATE + * --file 指定数据文件路径,默认 ./stocksWeight.txt + */ + +const fs = require('fs'); +const path = require('path'); +const readline = require('readline'); + +// ─── 解析命令行参数 ─────────────────────────────────────────── +const args = process.argv.slice(2); +const dryRun = args.includes('--dry-run'); +const fileIndex = args.indexOf('--file'); +const dataFile = fileIndex !== -1 ? args[fileIndex + 1] : path.join(__dirname, '..', 'stocksWeight.txt'); + +// ─── 加载数据库配置(复用 database/config.js 的生产环境路由逻辑) ── +function loadDbConfig() { + const projectRoot = path.resolve(__dirname, '..'); + + // 加载默认配置 + const defaultConfigPath = path.join(projectRoot, 'config', 'config.default.js'); + const defaultConfigFactory = require(defaultConfigPath); + const defaultConfig = typeof defaultConfigFactory === 'function' + ? defaultConfigFactory({ name: 'update-stock-weight', baseDir: projectRoot }) + : defaultConfigFactory; + + // 生产环境使用 config.default.js 中的 sequelize 配置 + const sequelizeConfig = defaultConfig && defaultConfig.sequelize; + if (sequelizeConfig && sequelizeConfig.host) { + return { + host: sequelizeConfig.host, + port: Number(sequelizeConfig.port || 3306), + user: sequelizeConfig.username, + password: sequelizeConfig.password, + database: sequelizeConfig.database || 'wms', + }; + } + + // 兜底:使用 mysql.clients.wms + const mysqlClient = defaultConfig && defaultConfig.mysql && defaultConfig.mysql.clients && defaultConfig.mysql.clients.wms; + if (mysqlClient) { + return { + host: mysqlClient.host, + port: Number(mysqlClient.port || 3306), + user: mysqlClient.user, + password: mysqlClient.password, + database: mysqlClient.database, + }; + } + + throw new Error('无法解析生产数据库配置'); +} + +// ─── 解析数据文件 ────────────────────────────────────────────── +async function parseDataFile(filePath) { + const records = []; + const errors = []; + + if (!fs.existsSync(filePath)) { + throw new Error(`数据文件不存在: ${filePath}`); + } + + const fileStream = fs.createReadStream(filePath, 'utf8'); + const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); + + let lineNo = 0; + for await (const line of rl) { + lineNo++; + const trimmed = line.trim(); + if (!trimmed) continue; // 跳过空行 + + const parts = trimmed.split(/\s+/); + if (parts.length < 2) { + errors.push(`第 ${lineNo} 行格式错误(需要 id 和 weight): "${trimmed}"`); + continue; + } + + const id = parseInt(parts[0], 10); + const weight = parseFloat(parts[1]); + + if (isNaN(id) || id <= 0) { + errors.push(`第 ${lineNo} 行 ID 无效: "${parts[0]}"`); + continue; + } + if (isNaN(weight) || weight < 0) { + errors.push(`第 ${lineNo} 行重量无效: "${parts[1]}"`); + continue; + } + + records.push({ id, weight }); + } + + return { records, errors }; +} + +// ─── 主流程 ──────────────────────────────────────────────────── +(async () => { + console.log('═══════════════════════════════════════════════'); + console.log(' 生产数据库 - stock_warehouse 重量批量更新'); + console.log('═══════════════════════════════════════════════'); + console.log(` 数据文件: ${dataFile}`); + console.log(` 模式: ${dryRun ? 'DRY-RUN(仅预览,不实际更新)' : '正式执行'}`); + console.log(''); + + // 1. 解析数据文件 + let records, errors; + try { + ({ records, errors } = await parseDataFile(dataFile)); + } catch (e) { + console.error(`[ERROR] 读取数据文件失败: ${e.message}`); + process.exit(1); + } + + if (errors.length > 0) { + console.error(`[WARNING] 数据文件存在 ${errors.length} 行解析错误:`); + errors.forEach(e => console.error(` - ${e}`)); + if (records.length === 0) { + console.error('[ERROR] 没有有效的记录可以处理,退出。'); + process.exit(1); + } + console.error(` 将继续处理其余 ${records.length} 条有效记录。\n`); + } + + console.log(` 共解析 ${records.length} 条有效记录。\n`); + + // 2. 连接数据库 + const dbConfig = loadDbConfig(); + console.log(`[DB] 生产环境 → ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`); + console.log(''); + + const mysql = require('mysql2/promise'); + const connection = await mysql.createConnection({ + host: dbConfig.host, + port: dbConfig.port, + user: dbConfig.user, + password: dbConfig.password, + database: dbConfig.database, + charset: 'utf8mb4', + }); + + try { + // 3. 预览:查询现有记录 + const ids = records.map(r => r.id); + console.log('[预览] 查询现有记录...'); + const [existingRows] = await connection.query( + `SELECT id, item_code, item_name, gross_weight FROM wms_stock_warehouse WHERE id IN (?) ORDER BY id`, + [ids] + ); + + const existingMap = new Map(); + existingRows.forEach(row => { + existingMap.set(row.id, row); + }); + + const notFound = ids.filter(id => !existingMap.has(id)); + if (notFound.length > 0) { + console.error(`[WARNING] 以下 ${notFound.length} 个 ID 在 stock_warehouse 表中不存在:`); + console.error(` ${notFound.join(', ')}`); + console.error(''); + } + + // 4. 显示变更预览 + console.log('───────────────────────────────────────────────'); + console.log(' 变更预览(前 30 条):'); + console.log('───────────────────────────────────────────────'); + console.log(' ID | 商品编码 | 商品名称 | 旧重量 → 新重量'); + console.log(' ----------|---------------|-------------------------|----------------'); + + let displayCount = 0; + const changes = []; + for (const { id, weight } of records) { + const existing = existingMap.get(id); + if (existing) { + const oldWeight = Number(existing.gross_weight) || 0; + if (oldWeight !== weight) { + changes.push({ id, weight, oldWeight, itemCode: existing.item_code, itemName: existing.item_name }); + if (displayCount < 30) { + const code = (existing.item_code || '').padEnd(13); + const name = (existing.item_name || '').substring(0, 24).padEnd(24); + console.log(` ${String(id).padEnd(10)}| ${code}| ${name}| ${oldWeight} → ${weight}`); + displayCount++; + } + } + } + } + + if (changes.length > 30) { + console.log(` ... 还有 ${changes.length - 30} 条变更,省略显示`); + } + console.log(''); + + const unchangedCount = records.length - changes.length - notFound.length; + console.log(` 汇总: 共 ${records.length} 条记录`); + console.log(` - 需要更新: ${changes.length} 条`); + console.log(` - 无需变更: ${unchangedCount} 条`); + console.log(` - ID 不存在: ${notFound.length} 条`); + console.log(''); + + if (changes.length === 0) { + console.log(' 没有需要更新的记录,退出。'); + return; + } + + // 5. dry-run 模式到此为止 + if (dryRun) { + console.log('[DRY-RUN] 预览完成,未执行任何 UPDATE。'); + console.log(' 去掉 --dry-run 参数即可正式执行。'); + return; + } + + // 6. 确认执行 + console.log('═══════════════════════════════════════════════'); + console.log(' ⚠️ 即将在生产数据库执行 UPDATE 操作!'); + console.log(` ⚠️ 将更新 ${changes.length} 条 stock_warehouse.gross_weight 记录`); + console.log('═══════════════════════════════════════════════'); + console.log(''); + console.log(' 请在 10 秒内按 Ctrl+C 取消,或等待自动执行...'); + + // 倒计时 + for (let i = 5; i > 0; i--) { + process.stdout.write(` ${i}...`); + await new Promise(resolve => setTimeout(resolve, 1000)); + } + console.log('\n'); + + // 7. 执行更新 + console.log('[执行] 开始批量更新...'); + let successCount = 0; + let failCount = 0; + const failures = []; + + for (const { id, weight } of changes) { + try { + await connection.query( + 'UPDATE wms_stock_warehouse SET gross_weight = ? WHERE id = ?', + [weight, id] + ); + successCount++; + if (successCount % 50 === 0) { + console.log(` 进度: ${successCount}/${changes.length} 条已更新`); + } + } catch (e) { + failCount++; + failures.push({ id, weight, error: e.message }); + console.error(` [FAIL] id=${id}: ${e.message}`); + } + } + + // 8. 输出结果 + console.log(''); + console.log('═══════════════════════════════════════════════'); + console.log(' 执行完成'); + console.log('═══════════════════════════════════════════════'); + console.log(` 成功: ${successCount} 条`); + console.log(` 失败: ${failCount} 条`); + if (failures.length > 0) { + console.log(' 失败详情:'); + failures.forEach(f => console.log(` id=${f.id}: ${f.error}`)); + } + console.log(''); + + } finally { + await connection.end(); + } +})().catch(e => { + console.error(`[FATAL] ${e.stack || e.message}`); + process.exit(1); +});