From f40370baca6fb499b5920c116a8e272eb03b48bb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 27 Jul 2026 03:47:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(print):=20=E6=89=93=E5=8D=B0=E7=94=B5?= =?UTF-8?q?=E8=84=91=E7=AE=A1=E7=90=86=E5=A2=9E=E5=BC=BA=EF=BC=88=E5=BD=95?= =?UTF-8?q?=E5=88=B6=E3=80=81=E8=BD=AF=E5=88=A0=E9=99=A4=E3=80=81=E7=8B=AC?= =?UTF-8?q?=E7=AB=8B=E6=8E=A5=E5=8F=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - print_computer: 新增录制字段(is_recording/recording_size/remote_play_url/recording_directory/deleted_at) - print_stations: 新增 deleted_at 软删除 - 新增 printComputer service (systemMethods + systems) - order_print 重构: 商品信息从 picking 表直读,不再依赖 order_items - 8 条迁移: 录制→软删除→权限→目录 --- app/model/print_computer.js | 38 ++- app/model/print_stations.js | 6 + app/service/systemMethods/printComputer.js | 81 +++++ app/service/systems/order_print.js | 138 +------- app/service/systems/printComputer.js | 319 ++++++++++++++++++ ...00-add-print-qty-log-export-permissions.js | 202 +++++++++++ ...-add-is-recording-to-wms-print-computer.js | 28 ++ ...00-add-deleted-at-to-wms-print-computer.js | 28 ++ ...00-add-deleted-at-to-wms-print-stations.js | 28 ++ ...25150000-add-print-computer-permissions.js | 86 +++++ ...-recording-fields-to-wms-print-computer.js | 42 +++ ...0260725170000-add-recording-permissions.js | 82 +++++ ...cording-directory-to-wms-print-computer.js | 28 ++ 13 files changed, 981 insertions(+), 125 deletions(-) create mode 100644 app/service/systemMethods/printComputer.js create mode 100644 app/service/systems/printComputer.js create mode 100644 database/migrations/20260720160000-add-print-qty-log-export-permissions.js create mode 100644 database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js create mode 100644 database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js create mode 100644 database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js create mode 100644 database/migrations/20260725150000-add-print-computer-permissions.js create mode 100644 database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js create mode 100644 database/migrations/20260725170000-add-recording-permissions.js create mode 100644 database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js diff --git a/app/model/print_computer.js b/app/model/print_computer.js index 5f7ec6e..4f60b0e 100644 --- a/app/model/print_computer.js +++ b/app/model/print_computer.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { INTEGER, BIGINT, STRING, DATE } = app.Sequelize; + const { INTEGER, BIGINT, STRING, DATE, BOOLEAN } = app.Sequelize; const PrintComputer = app.model.define('print_computer', { id: { @@ -32,6 +32,42 @@ module.exports = app => { allowNull: true, comment: '上次登录时间', }, + is_recording: { + type: BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }, + recording_size_value: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }, + recording_size_unit: { + type: STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }, + remote_play_url: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }, + recording_directory: { + type: STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径', + }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, }, { tableName: 'wms_print_computer', freezeTableName: true, diff --git a/app/model/print_stations.js b/app/model/print_stations.js index 51278fe..eb4c5b0 100644 --- a/app/model/print_stations.js +++ b/app/model/print_stations.js @@ -136,6 +136,12 @@ module.exports = app => { defaultValue: 0, comment: '软删除标记:0-未删除,1-已删除', }, + deleted_at: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, subject_config: { type: JSON_TYPE, allowNull: true, diff --git a/app/service/systemMethods/printComputer.js b/app/service/systemMethods/printComputer.js new file mode 100644 index 0000000..d137003 --- /dev/null +++ b/app/service/systemMethods/printComputer.js @@ -0,0 +1,81 @@ +'use strict'; + +const MainService = require('../main'); + +class PrintComputerService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 打印电脑列表。 + * @param {Object} data 查询参数 { pagination, where } + * @return {Promise} 列表数据与分页信息 + */ + async list(data) { + try { + const result = await this.service.systems.printComputer.list(data || {}); + return this.success('获取成功', result); + } catch (e) { return this.fail(e.message); } + } + + /** + * 更新打印电脑。 + * @param {Object} data { id, name? } + * @return {Promise} 更新后的电脑记录 + */ + async update(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('更新成功', await this.service.systems.printComputer.update(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 设置录制电脑(会先取消同仓库下其他录制电脑)。 + * @param {Object} data { id, recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @return {Promise} 设置结果 + */ + async setRecording(data) { + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('设置录制成功', await this.service.systems.printComputer.setRecording(parseInt(id), fields)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 取消录制电脑。 + * @param {Object} data { id } + * @return {Promise} 取消结果 + */ + async cancelRecording(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + return this.success('取消录制成功', await this.service.systems.printComputer.cancelRecording(parseInt(id))); + } catch (e) { return this.fail(e.message); } + } + + /** + * 软删除打印电脑。 + * @param {Object} data { id } + * @return {Promise} 删除结果 + */ + async delete(data) { + try { + const { id } = data || {}; + if (!id) return this.fail('ID不能为空'); + await this.service.systems.printComputer.delete(parseInt(id)); + return this.success('删除成功'); + } catch (e) { return this.fail(e.message); } + } +} + +module.exports = PrintComputerService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index accd80f..02399b1 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -179,9 +179,9 @@ class OrderPrintSystemService extends OrderBaseService { * 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码, * 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。 * - * stock_id 优先读取 wms_picking.stock_id(20260708 新增列), - * 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id, - * 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。 + * 商品信息(item_name / barcode / stock_id / quantity)全部从 wms_picking + * 直读,不再反查 order_items 表,彻底消除因订单迁移导致 order_item_id + * 错配的风险。 * * @param {Array} orderRows 订单列表。 * @param {number} warehouseId 仓库ID。 @@ -223,68 +223,7 @@ class OrderPrintSystemService extends OrderBaseService { return resultMap; } - const orderItemIds = Array.from(new Set(normalizedPickingRows - .map(row => Number(row && row.order_item_id || 0)) - .filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0))); - - const orderItemModelFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; - const orderItemModel = orderItemModelFactory && typeof orderItemModelFactory.getCurrentModel === 'function' - ? await orderItemModelFactory.getCurrentModel(warehouseId) - : null; - - const orderItemRows = orderItemModel && typeof orderItemModel.findAll === 'function' && orderItemIds.length > 0 - ? await orderItemModel.findAll({ - where: { - id: { - [Op.in]: orderItemIds, - }, - }, - attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], - raw: true, - }) - : []; - - const orderItemMap = new Map(); - for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { - const orderItemId = Number(row && row.id || 0); - if (orderItemId > 0) { - orderItemMap.set(orderItemId, row); - } - } - - // 兜底:若 current items 表未命中全部 orderItemId,补查 dispatch items 表 - // 配送表订单的 items 可能已迁移到 dispatch items 表,getCurrentModel 查不到 - const foundItemIds = new Set([ ...orderItemMap.keys() ]); - const missingItemIds = orderItemIds.filter(id => !foundItemIds.has(id)); - const dispatchItemRows = []; - if (missingItemIds.length > 0 && orderItemModelFactory && typeof orderItemModelFactory.getDispatchModel === 'function') { - try { - const dispatchItemModel = await orderItemModelFactory.getDispatchModel(warehouseId); - if (dispatchItemModel && typeof dispatchItemModel.findAll === 'function') { - const dispatchRows = await dispatchItemModel.findAll({ - where: { - id: { - [Op.in]: missingItemIds, - }, - }, - attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ], - raw: true, - }); - if (Array.isArray(dispatchRows)) { - for (const row of dispatchRows) { - const orderItemId = Number(row && row.id || 0); - if (orderItemId > 0 && !orderItemMap.has(orderItemId)) { - orderItemMap.set(orderItemId, row); - dispatchItemRows.push(row); - } - } - } - } - } catch (err) { - this.ctx.logger.warn('[buildPrintOrderRowMapWithPicking] dispatch items 兜底查询失败:%s', err.message); - } - } - + // 库位兜底:space_name 为空时通过 space_id 补查 location_space 表 const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows .filter(row => !String(row && row.space_name || '').trim()) .map(row => Number(row && row.space_id || 0)) @@ -307,6 +246,7 @@ class OrderPrintSystemService extends OrderBaseService { const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) .map(row => [ Number(row && row.id || 0), row ])); + // 按 order_id 分组 picking 行 const pickingRowsByOrderId = new Map(); for (const row of normalizedPickingRows) { const orderId = Number(row && row.order_id || 0); @@ -319,38 +259,17 @@ class OrderPrintSystemService extends OrderBaseService { pickingRowsByOrderId.set(orderId, list); } - // 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id) + // 阶段一:从 picking.stock_id 收集所有 stock_id const allStockIds = new Set(); - - // 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表) for (const row of normalizedPickingRows) { const stockId = Number(row && row.stock_id || 0); if (stockId > 0) { allStockIds.add(stockId); } } - - // 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据) - for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { - const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); - const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); - if (stockId > 0) { - allStockIds.add(stockId); - } - } - - // 1c) 从 dispatch items 兜底收集 stock_id(配送表订单的 items 可能在 dispatch items 表) - for (const row of dispatchItemRows) { - const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot); - const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0); - if (stockId > 0) { - allStockIds.add(stockId); - } - } - const uniqueStockIds = Array.from(allStockIds); - // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径) + // 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称 const stockWarehouseMap = new Map(); if (uniqueStockIds.length > 0) { const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse; @@ -369,7 +288,7 @@ class OrderPrintSystemService extends OrderBaseService { } } - // 阶段三:构建所有打印项(使用 stock_warehouse 直读数据) + // 阶段三:构建所有打印项(全部从 picking + stock_warehouse 直取) const printItemsByOrderId = new Map(); for (const orderRow of rows) { @@ -380,9 +299,8 @@ class OrderPrintSystemService extends OrderBaseService { } const printItems = pickingList.map(pickingRow => { - const orderItemId = Number(pickingRow && pickingRow.order_item_id || 0); - const orderItemRow = orderItemMap.get(orderItemId) || {}; - const itemSnapshot = this.normalizeItemSnapshot(orderItemRow.item_snapshot); + const stockId = Number(pickingRow && pickingRow.stock_id || 0); + const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {}; const pickLocation = this.getFirstNonEmptyFieldText({ space_name: pickingRow && pickingRow.space_name, @@ -391,40 +309,12 @@ class OrderPrintSystemService extends OrderBaseService { custom_barcode: locationRow.custom_barcode, }, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]); - // stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id - const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0); - const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0); - const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId; - - // 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items) - const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null; - - // item_name 优先级:stock_warehouse > order_items > item_snapshot - const itemName = this.getFirstNonEmptyFieldText({ - stock_item_name: stockInfo && stockInfo.item_name, - snapshot_item_name: itemSnapshot.item_name, - snapshot_name: itemSnapshot.name, - snapshot_title: itemSnapshot.title, - item_name: orderItemRow.item_name, - }, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]); - - // barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code - const barcode = this.getFirstNonEmptyFieldText({ - stock_item_code: stockInfo && stockInfo.item_code, - barcode: itemSnapshot.barcode, - item_barcode: itemSnapshot.item_barcode, - bar_code: itemSnapshot.bar_code, - item_code: orderItemRow.item_code, - sku_code: itemSnapshot.sku_code, - sku: itemSnapshot.sku, - }, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); - - const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); + const quantity = Number(pickingRow && pickingRow.quantity || 0); return { - order_item_id: orderItemId, - item_name: itemName, - barcode, + order_item_id: Number(pickingRow && pickingRow.order_item_id || 0), + item_name: stockInfo ? String(stockInfo.item_name || '').trim() : '', + barcode: stockInfo ? String(stockInfo.item_code || '').trim() : '', quantity: quantity > 0 ? quantity : 0, pick_location: pickLocation, stock_id: stockId > 0 ? stockId : undefined, diff --git a/app/service/systems/printComputer.js b/app/service/systems/printComputer.js new file mode 100644 index 0000000..f973085 --- /dev/null +++ b/app/service/systems/printComputer.js @@ -0,0 +1,319 @@ +'use strict'; + +const Service = require('egg').Service; + +class PrintComputerService extends Service { + /** + * 通知打印服务刷新电脑信息并推送给客户端。 + * @param {number} warehouseId 仓库ID + * @param {number} computerId 电脑ID + * @return {Promise} + */ + async notifyRefreshInfo(warehouseId, computerId) { + const printServiceUrl = this.ctx.app.config.printService.url; + try { + await this.ctx.curl(`${printServiceUrl}/auth/refreshInfo`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId }, + dataType: 'json', + }); + } catch (err) { + this.ctx.logger.warn(`通知打印服务刷新电脑 ${computerId} 信息失败: ${err.message}`); + } + } + + /** + * 打印电脑列表(仓库隔离,分页+筛选)。 + * @param {Object} params 查询参数 + * @param {Object} [params.pagination] 分页 { page, pageSize } + * @param {Object} [params.where] 筛选 { is_recording, is_online } + * @return {Promise} { list, pagination } + */ + async list(params = {}) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { pagination = {}, where = {} } = params; + + const page = Math.max(1, parseInt(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20)); + + const queryWhere = { + warehouse_id: warehouseId, + deleted_at: null, + }; + + // DB 层筛选:is_recording + if (where.is_recording !== undefined && where.is_recording !== null && where.is_recording !== '') { + queryWhere.is_recording = parseInt(where.is_recording) === 1; + } + + // is_online 筛选参数 + const filterOnline = where.is_online !== undefined && where.is_online !== null && where.is_online !== ''; + const onlineValue = filterOnline ? parseInt(where.is_online) : null; + + const redisPrinter = ctx.app.redis.get('printer'); + + if (filterOnline) { + // 有在线状态筛选:先查全量 DB,Redis 标注后内存过滤再分页 + const allRows = await ctx.model.PrintComputer.findAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + // Redis 标注在线状态 + const enriched = await Promise.all(allRows.map(async row => { + const onlineKey = `warehouse:${warehouseId}:printer:${row.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + row.is_online = onlineInfo ? 1 : 0; + return row; + })); + + // 内存过滤 + const filtered = enriched.filter(row => row.is_online === onlineValue); + const total = filtered.length; + const list = filtered.slice((page - 1) * pageSize, page * pageSize); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < total, + }, + }; + } + + // 无在线状态筛选:DB 分页查询 + const { count, rows } = await ctx.model.PrintComputer.findAndCountAll({ + where: queryWhere, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + }); + + // 从 Redis 读取在线状态并附加到每条记录 + const list = await Promise.all(rows.map(async row => { + const plain = row.get ? row.get({ plain: true }) : row; + const onlineKey = `warehouse:${warehouseId}:printer:${plain.id}`; + const onlineInfo = await redisPrinter.get(onlineKey); + plain.is_online = onlineInfo ? 1 : 0; + return plain; + })); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 更新打印电脑。 + * @param {number} id 电脑ID + * @param {Object} data 要更新的字段 { name } + * @return {Promise} 更新后的记录 + */ + async update(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + const fields = {}; + if (data.name !== undefined) { + const name = String(data.name).trim(); + if (!name) throw new Error('电脑名称不能为空'); + fields.name = name; + } + + if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段'); + + await record.update(fields); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 设置录制电脑。 + * 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。 + * @param {number} id 电脑ID + * @param {Object} data { recording_size_value, recording_size_unit, remote_play_url, recording_directory } + * @return {Promise} 更新后的记录 + */ + async setRecording(id, data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + // 参数校验 + if (data.recording_size_value === undefined || data.recording_size_value === null) { + throw new Error('录制大小不能为空'); + } + const sizeValue = parseInt(data.recording_size_value); + if (!Number.isInteger(sizeValue) || sizeValue <= 0) { + throw new Error('录制大小必须为正整数'); + } + + const VALID_UNITS = [ 'KB', 'MB', 'GB', 'TB' ]; + const unit = String(data.recording_size_unit || '').trim().toUpperCase(); + if (!VALID_UNITS.includes(unit)) { + throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`); + } + + const url = String(data.remote_play_url || '').trim(); + if (!/^https?:\/\/.+/.test(url)) { + throw new Error('远程播放地址必须以 http:// 或 https:// 开头'); + } + + const directory = String(data.recording_directory || '').trim(); + if (!directory) { + throw new Error('录制目录不能为空'); + } + + // 校验目标电脑存在 + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 先将同仓库下其他已设为录制的电脑取消 + const [ affectedCount ] = await ctx.model.PrintComputer.update( + { + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + remote_play_url: null, + recording_directory: null, + }, + { + where: { + warehouse_id: warehouseId, + is_recording: true, + deleted_at: null, + }, + } + ); + + // 设置当前电脑为录制 + await record.update({ + is_recording: true, + recording_size_value: sizeValue, + recording_size_unit: unit, + remote_play_url: url, + recording_directory: directory, + }); + + // 通知打印服务推送最新信息:当前电脑 + 被取消的其他电脑 + await this.notifyRefreshInfo(warehouseId, id); + // 查询被取消的其他电脑ID并逐一通知 + if (affectedCount > 0) { + const cancelledComputers = await ctx.model.PrintComputer.findAll({ + where: { + warehouse_id: warehouseId, + is_recording: false, + deleted_at: null, + id: { [ctx.app.Sequelize.Op.ne]: id }, + }, + attributes: [ 'id' ], + raw: true, + order: [[ 'id', 'DESC' ]], + limit: affectedCount, + }); + for (const comp of cancelledComputers) { + await this.notifyRefreshInfo(warehouseId, comp.id); + } + } + + return record; + } + + /** + * 取消录制电脑。 + * @param {number} id 电脑ID + * @return {Promise} 更新后的记录 + */ + async cancelRecording(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + await record.update({ + is_recording: false, + recording_size_value: null, + recording_size_unit: null, + remote_play_url: null, + recording_directory: null, + }); + + // 通知打印服务推送最新信息给客户端 + await this.notifyRefreshInfo(warehouseId, id); + + return record; + } + + /** + * 软删除打印电脑。 + * 若存在未删除的关联打印台,则拒绝删除。 + * @param {number} id 电脑ID + * @return {Promise} + */ + async delete(id) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + + const record = await ctx.model.PrintComputer.findOne({ + where: { id, warehouse_id: warehouseId, deleted_at: null }, + }); + if (!record) throw new Error('打印电脑不存在或无权操作'); + + // 检查是否有关联的未删除打印台 + const stationCount = await ctx.model.PrintStations.count({ + where: { + computer_id: id, + warehouse_id: warehouseId, + deleted_at: null, + }, + }); + + if (stationCount > 0) { + throw new Error(`该电脑下存在 ${stationCount} 个未删除的打印台,请先删除打印台后再删除电脑`); + } + + await record.update({ deleted_at: new Date() }); + + // 通知打印服务注销电脑连接 + const printServiceUrl = ctx.app.config.printService.url; + try { + await ctx.curl(`${printServiceUrl}/auth/logout`, { + method: 'POST', + contentType: 'json', + data: { warehouse: warehouseId, computerId: id }, + dataType: 'json', + }); + } catch (err) { + ctx.logger.warn(`通知打印服务注销电脑 ${id} 失败: ${err.message}`); + } + } +} + +module.exports = PrintComputerService; diff --git a/database/migrations/20260720160000-add-print-qty-log-export-permissions.js b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js new file mode 100644 index 0000000..fdc0d75 --- /dev/null +++ b/database/migrations/20260720160000-add-print-qty-log-export-permissions.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * 面单余额变更日志导出权限迁移。 + * + * 变更内容: + * 1. 新增 2 条 api 权限记录: + * - storeWarehouse.store.exportPrintQuantityLogs — 导出面单余额变更日志 + * - storeWarehouse.store.exportPrintQuantityLogsTaskProgress — 查询导出任务进度 + * 2. 将上述权限授权给 财务以上角色组: + * - 货主管理员 (id=5) + * - 经理 (id=8) + * (超级管理员 id=2/7 的 permissions='*' 无需更新) + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +/** 需要授权的角色ID(财务以上:货主管理员 + 经理) */ +const TARGET_ROLE_IDS = [5, 8]; + +/** @type {{path: string, name: string, meta_title: string, type: string}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'storeWarehouse.store.exportPrintQuantityLogs', + name: 'storeWarehouse.store.exportPrintQuantityLogs', + meta_title: '导出面单余额变更日志', + type: 'api', + }, + { + path: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + name: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress', + meta_title: '查询面单余额导出任务进度', + type: 'api', + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw || raw === '*') return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + // ─── 1. 插入新权限记录 ───────────────────────────────── + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在: ${perm.path} (id=${existing[0].id})`); + insertedIds.push(Number(existing[0].id)); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, meta_title, type, status, created_at, update_at) + VALUES (:path, :name, :meta_title, :type, 1, NOW(), NOW())`, + { replacements: { path: perm.path, name: perm.name, meta_title: perm.meta_title, type: perm.type } } + ); + + const newId = Number(result); + insertedIds.push(newId); + console.log(`[Migration] 新增权限: ${perm.path} (id=${newId})`); + } + + // ─── 2. 授权给财务以上角色组 ────────────────────────── + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) { + console.log(`[Migration] 角色不存在: id=${roleId}`); + continue; + } + + const raw = roleRows[0].permissions; + // 跳过 permissions='*' 的角色(已拥有全部权限) + if (raw === '*') { + console.log(`[Migration] 角色 id=${roleId} 已有全部权限(*),跳过`); + continue; + } + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + const newIds = insertedIds.filter(id => !currentIds.includes(id)); + + if (newIds.length === 0) { + console.log(`[Migration] 角色 id=${roleId} 已拥有目标权限,跳过`); + continue; + } + + const merged = [ ...currentIds, ...newIds ]; + await saveRolePermissions(queryInterface, roleId, merged); + console.log(`[Migration] 角色 id=${roleId} 授权成功,新增权限: [${newIds.join(', ')}]`); + } + + console.log( + `[Migration] 面单余额导出权限迁移完成:` + + `新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色` + ); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // ─── 1. 从角色权限中移除新增的权限ID ───────────────── + const allPaths = NEW_PERMISSIONS.map(p => p.path); + + for (const roleId of TARGET_ROLE_IDS) { + const [ roleRows ] = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + + if (!roleRows || roleRows.length === 0) continue; + + const raw = roleRows[0].permissions; + if (!raw || raw === '*') continue; + + const currentIds = await getRolePermissionIds(queryInterface, roleId); + // 查询需要移除的权限ID + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type = 'api'`, + { replacements: { paths: allPaths } } + ); + const removeIds = permRows.map(r => Number(r.id)); + const filtered = currentIds.filter(id => !removeIds.includes(id)); + + if (filtered.length !== currentIds.length) { + await saveRolePermissions(queryInterface, roleId, filtered); + console.log(`[Migration] 角色 id=${roleId} 已移除导出权限`); + } + } + + // ─── 2. 删除新增的权限记录 ─────────────────────────── + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration] 已删除权限: ${perm.path}`); + } + + console.log('[Migration] 面单余额导出权限回滚完成'); +}; diff --git a/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js new file mode 100644 index 0000000..9eb4535 --- /dev/null +++ b/database/migrations/20260725120000-add-is-recording-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'is_recording', { + type: Sequelize.BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否作为录制电脑,1-是,0-否', + }); + }, + + /** + * 回滚删除打印台电脑表的"是否作为录制电脑"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'is_recording'); + }, +}; diff --git a/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js new file mode 100644 index 0000000..29469be --- /dev/null +++ b/database/migrations/20260725130000-add-deleted-at-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台电脑表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台电脑表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js new file mode 100644 index 0000000..2fa89e0 --- /dev/null +++ b/database/migrations/20260725140000-add-deleted-at-to-wms-print-stations.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印台表新增软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_stations', 'deleted_at', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }); + }, + + /** + * 回滚删除打印台表的软删除时间字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_stations', 'deleted_at'); + }, +}; diff --git a/database/migrations/20260725150000-add-print-computer-permissions.js b/database/migrations/20260725150000-add-print-computer-permissions.js new file mode 100644 index 0000000..0cdfe6f --- /dev/null +++ b/database/migrations/20260725150000-add-print-computer-permissions.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑模块 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 3 条 API 权限 + const permissions = [ + { path: 'print_computer.list', name: '打印电脑-列表', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.update', name: '打印电脑-更新', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.delete', name: '打印电脑-删除', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('print_computer.list', 'print_computer.update', 'print_computer.delete') ORDER BY id` + ); + const ids = rows.map(r => r.id); + if (ids.length !== 3) { + throw new Error(`权限插入异常:期望 3 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色(排除 permissions='*' 的超级管理员角色) + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = ['print_computer.list', 'print_computer.update', 'print_computer.delete']; + + // 1. 查询权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + // 2. 从角色权限中移除 + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + // 3. 删除权限记录 + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js new file mode 100644 index 0000000..dd12a85 --- /dev/null +++ b/database/migrations/20260725160000-add-recording-fields-to-wms-print-computer.js @@ -0,0 +1,42 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_size_value', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '录制大小数值', + }); + await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', { + type: Sequelize.STRING(10), + allowNull: true, + defaultValue: null, + comment: '录制存储单位:KB/MB/GB/TB', + }); + await queryInterface.addColumn('wms_print_computer', 'remote_play_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '远程播放地址', + }); + }, + + /** + * 回滚删除录制相关字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'remote_play_url'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit'); + await queryInterface.removeColumn('wms_print_computer', 'recording_size_value'); + }, +}; diff --git a/database/migrations/20260725170000-add-recording-permissions.js b/database/migrations/20260725170000-add-recording-permissions.js new file mode 100644 index 0000000..4542c82 --- /dev/null +++ b/database/migrations/20260725170000-add-recording-permissions.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = { + /** + * 新增打印电脑录制相关 API 权限,并授权客服主管及以上角色。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const now = new Date(); + + // 1. 插入 2 条 API 权限 + const permissions = [ + { path: 'print_computer.setRecording', name: '打印电脑-设置录制', type: 'api', status: 1, created_at: now, update_at: now }, + { path: 'print_computer.cancelRecording', name: '打印电脑-取消录制', type: 'api', status: 1, created_at: now, update_at: now }, + ]; + + await queryInterface.bulkInsert('wms_permission', permissions); + + // 2. 查询刚插入的权限 ID + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('print_computer.setRecording', 'print_computer.cancelRecording') ORDER BY id` + ); + const ids = rows.map(r => r.id); + if (ids.length !== 2) { + throw new Error(`权限插入异常:期望 2 条,实际 ${ids.length} 条`); + } + + // 3. 授权客服主管及以上角色 + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 0 + `); + } + }, + + /** + * 回滚:删除权限记录并从角色权限中移除。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const paths = ['print_computer.setRecording', 'print_computer.cancelRecording']; + + const [rows] = await queryInterface.sequelize.query( + `SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')` + ); + const ids = rows.map(r => r.id); + + const roleIds = [2, 5, 7, 8, 22, 26, 28, 29]; + for (const permId of ids) { + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + permissions, + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}')) + ), + updated_at = NOW() + WHERE id IN (${roleIds.join(',')}) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '${permId}', '$') = 1 + `); + } + + await queryInterface.bulkDelete('wms_permission', { + path: { [Sequelize.Op.in]: paths }, + }); + }, +}; diff --git a/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js new file mode 100644 index 0000000..e20fdd0 --- /dev/null +++ b/database/migrations/20260725180000-add-recording-directory-to-wms-print-computer.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + /** + * 为打印电脑表新增录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_print_computer', 'recording_directory', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '录制目录路径,如 D:/record', + }); + }, + + /** + * 回滚删除录制目录字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_print_computer', 'recording_directory'); + }, +};