WMS_MAIN/app/service/systems/printComputer.js

312 lines
9.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
class PrintComputerService extends Service {
/**
* 通知打印服务刷新电脑信息并推送给客户端。
* @param {number} warehouseId 仓库ID
* @param {number} computerId 电脑ID
* @return {Promise<void>}
*/
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<Object>} { 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<Object>} 更新后的记录
*/
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, recording_directory }
* @return {Promise<Object>} 更新后的记录
*/
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 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,
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,
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<Object>} 更新后的记录
*/
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,
recording_directory: null,
});
// 通知打印服务推送最新信息给客户端
await this.notifyRefreshInfo(warehouseId, id);
return record;
}
/**
* 软删除打印电脑。
* 若存在未删除的关联打印台,则拒绝删除。
* @param {number} id 电脑ID
* @return {Promise<void>}
*/
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;