2026-05-14 15:57:51 +08:00

493 lines
19 KiB
JavaScript
Raw 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';
// 打印相关 Service
const MainService = require('../main');
/**
* 打印 Service
* 参考 indexService 初始化方式,后续可扩展具体业务函数
*/
class PrintService extends MainService {
constructor(ctx) {
super(ctx);
// 初始化免登录、免权限、免日志、免认证等配置
const _noNeedLogin = '';
const _noNeedRight = '*';
const _noNeedLog = '';
const _noNeedAuth = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
this.defaultComponents = [
{ name: '抖音', port: '13888' },
{ name: '拼多多', port: '5000' },
{ name: '快手', port: '16888/ks/printer' },
{ name: '京东', port: '9113' },
{ name: '菜鸟', port: '13528' },
{ name: '视频号', port: '12705' },
{ name: '小红书', port: '10818' },
{ name: 'LODOP', port: '8000' },
];
}
/**
* 发送打印任务到打印电脑。
* 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。
* @param {Object} _data 打印请求参数
* @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 可不传)
* @param {string} _data.type 打印类型,支持 customize/express
* @param {Object} [_data.template] 打印模板对象(customize 必填)
* @param {Object} _data.data 打印业务数据
* @param {string} _data.computerId 打印电脑 ID
* @param {string} [_data.timestamp] 业务时间戳
* @param {number} [_data.count] 打印份数
* @returns {Promise<Object>} 统一返回结构
*/
async send(_data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { printer, type, template, data, computerId, timestamp, count } = _data;
// 生成打印编号并记录到数据库
const printRecord = await ctx.model.PrintRecord.create({
warehouse_id: warehouseId,
computer_id: computerId,
printer,
type,
data: { template, data },
status: 'pending',
});
// 处理后的数据
let processedData = {};
switch (type) {
case 'customize': {
if (printer === undefined || printer === null || printer === '') {
return this.fail('type=customize 时 printer 参数不能为空', { code: 400 });
}
if (!template || typeof template !== 'object' || Array.isArray(template)) {
return this.fail('type=customize 时 template 参数不能为空', { code: 400 });
}
const { page_width, page_height, template_content } = template;
if (page_width === undefined || page_width === null || page_width === '') {
return this.fail('type=customize 时 page_width 参数不能为空', { code: 400 });
}
if (page_height === undefined || page_height === null || page_height === '') {
return this.fail('type=customize 时 page_height 参数不能为空', { code: 400 });
}
if (!Array.isArray(template_content)) {
return this.fail('type=customize 时 template_content 必须是数组', { code: 400 });
}
let htm = `<body style="position:relative; width:${page_width}mm; height:${page_height}mm;margin:0; padding:0;overflow:hidden;">`;
for (const item of template_content) {
let content = item.content;
for (const key in data) {
if (String(item.field_code) === key) {
content = data[key];
}
}
switch (item.type) {
case 'text':
htm += `<div style="
position:absolute;
width:${item.width}mm;
height:${item.height}mm;
left:${item.left}mm;
top:${item.top}mm;
font-size:${item.fontSize}pt;
font-weight:${item.bold ? 'bold' : 'normal'};
font-style:${item.italic ? 'italic' : 'normal'};
text-decoration:${item.underline ? 'underline' : 'none'};
text-align:${item.textAlign};
transform: rotate(${item.rotate}deg);
line-height: ${item.lineHeight}mm;
};
">${content}</div>`;
break;
case 'image':
htm += `<img src="${content}" style="position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;" />`;
break;
case 'barcode':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
"><img style="width:100%; height:100%;" src="https://ye4s.wms.gztbyc.com/barcode/build?text=${content.slice(-13)}&type=C128&foreground=%23000000&width=2&height=${parseInt(item.height / 25.4 * 96)}" /></div>`;
break;
case 'qrcode': {
let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`;
// 转换成urlencode
toUrl = encodeURIComponent(toUrl);
const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`;
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
"><img style="width:100%; height:100%;" src="${url}" /></div>`;
break;
}
case 'line':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
border-top: ${item.line_width}px ${item.line_style} ${item.line_color};
"></div>`;
break;
case 'rectangle':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
border: ${item.line_width}px ${item.line_style} ${item.line_color};
"></div>`;
break;
case 'table': {
let tableHtml = `<table style="position:absolute; left:${item.left}mm; top:${item.top}mm; border-collapse: collapse;">`;
for (let i = 0; i < item.rows; i++) {
tableHtml += '<tr>';
for (let j = 0; j < item.columns; j++) {
const content = item.content[i] && item.content[i][j] ? item.content[i][j] : '';
tableHtml += `<td style="border: ${item.line_width}px ${item.line_style} ${item.line_color}; width:${item.width / item.columns}mm; height:${item.height / item.rows}mm;">${content}</td>`;
} tableHtml += '</tr>';
} tableHtml += '</table>';
htm += tableHtml;
break;
}
default:
break;
}
}
htm += '</body>';
processedData = {
pageWidth: page_width,
pageHeight: page_height,
htm,
lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ],
};
break;
}
case 'express':
break;
default:
return this.fail('不支持的打印类型', 1001);
}
const printData = {
printer,
type,
template,
data: processedData,
timestamp,
count,
printId: printRecord.id,
};
const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData });
// 发送成功后更新打印记录状态
if (res.status === 'success') {
await printRecord.update({ status: 'sent' });
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
}
await printRecord.update({ status: 'failed', error_message: res.error });
return this.fail(res.error, { code: 504, printId: printRecord.id });
}
async getPrintResult(data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { printId } = data;
if (!printId) return this.fail('参数错误', 1001);
const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true });
if (!record) return this.fail('打印记录不存在', 1002);
return this.success('success', { ...record, code: 0 });
}
async getPrintRecordItem(data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true });
if (!item) return this.fail('打印记录不存在', 1002);
return this.success('success', { ...item, code: 0 });
}
/**
* 1. 查询打印台列表
* @param {Object} data { page, pageSize, where }
*/
async getList(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const requestData = data && typeof data === 'object' ? data : {};
const { whereValue } = this.prepareWhereContext(requestData);
const { page = 1, pageSize = 20 } = requestData;
// 字段过滤
const filter = {};
[ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => {
const value = whereValue[key];
if (value !== undefined && value !== null && value !== '') filter[key] = value;
});
filter.warehouse_id = warehouse_id;
filter.deleted = 0;
// 查询总数
const total = await ctx.model.PrintStations.count({ where: filter });
// 查询分页数据
const list = await ctx.model.PrintStations.findAll({
where: filter,
offset: (page - 1) * pageSize,
limit: pageSize,
order: [[ 'create_at', 'DESC' ]],
raw: true,
});
const computers = list.map(item => {
const computer = {
id: item.computer_id,
is_online: 0,
components: this.defaultComponents.map(component => ({
name: component.name,
is_online: 0,
})),
};
return computer;
});
// 动态属性处理(如 is_online、components)
for (let i = 0; i < computers.length; i++) {
const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`;
const computerInfo = await this.app.redis.get('printer').get(key);
if (computerInfo) {
computers[i].is_online = 1;
computers[i].components = await Promise.all(computers[i].components.map(async component => {
const componentKey = `printer:${computers[i].id}:name:${component.name}:status`;
const componentInfo = await this.app.redis.get('printer').get(componentKey);
if (componentInfo && componentInfo === 'connected') {
component.is_online = 1;
}
return component;
}));
}
}
for (const item of list) {
const computer = computers.find(c => c.id === item.computer_id);
item.is_online = computer ? computer.is_online : 0;
item.components = computer ? computer.components : this.defaultComponents.map(component => ({
name: component.name,
is_online: 0,
}));
}
const result = {
code: 200,
data: {
list,
pagination: {
hasNext: page * pageSize < total,
hasPrevious: page > 1,
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
queryInfo: {
conditions: this.ctx.where || {},
hasBarcodeSearch: false,
sortField: 'id',
sortOrder: 'DESC',
},
summary: {
total_available: total,
total_items: pageSize,
total_locked: 0,
total_quantity: 0,
},
},
};
return this.success('success', result);
}
/**
* 2. 获取单个打印台
* @param {Object} data { id }
*/
async getItem(data) {
const { ctx } = this;
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true });
if (!item) return this.fail('打印台不存在', 1002);
return this.success('success', { ...item, code: 0 });
}
/**
* 3. 添加打印台
* @param {Object} data { id, name, computer_id, custom_barcode }
* @returns {Promise<Object>} 返回新增结果。
*/
async add(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const { name, computer_id, custom_barcode, subject_config } = data;
if (!name || !computer_id) return this.fail('参数错误', 1001);
const createPayload = {
warehouse_id,
name,
computer_id,
custom_barcode,
creator_id: ctx.user?.employees_id || '',
creator_name: ctx.user?.employees_name || '',
default_printer_name: data.default_printer_name || '',
create_at: new Date(),
update_at: new Date(),
deleted: 0,
};
if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) {
try {
createPayload.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config);
} catch (error) {
return this.fail(error.message, 1001);
}
}
const newItem = await ctx.model.PrintStations.create(createPayload);
return this.success('添加打印台成功', { data: newItem, code: 0 });
}
async hasName(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const { name, id } = data;
if (!name) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true });
return this.success('success', { exists: !!item, code: 0 });
}
/**
* 3. 修改打印台
* @param {Object} data { id, name, computer_id, custom_barcode }
* @returns {Promise<Object>} 返回更新结果。
*/
async updateItem(data) {
const { ctx } = this;
const { id, name, computer_id, custom_barcode, subject_config } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { id } });
if (!item) return this.fail('打印台不存在', 1002);
// 只更新允许字段
if (name !== undefined) item.name = name;
if (computer_id !== undefined) item.computer_id = computer_id;
if (custom_barcode !== undefined) item.custom_barcode = custom_barcode;
if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) {
try {
item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config);
} catch (error) {
return this.fail(error.message, 1001);
}
}
await item.save();
return this.success('success', { data: null, code: 0 });
}
/**
* 4. 删除打印台
* @param {Object} data { ids }
*/
async del(data) {
const { ctx } = this;
const { ids } = data;
if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001);
// 软删除
await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } });
// TODO: 检查 result 是否成功
return this.success('success', { data: null, code: 0 });
}
/**
* 5. 获取打印电脑列表
*/
async getComputer() {
const { ctx } = this;
// TODO: 打印电脑状态需根据实际业务实现
const warehouseId = ctx.user.store_id;
const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } });
return this.success('success', { data: list, code: 0 });
}
/**
* 7. 获取打印电脑的所有打印机
* @param {Object} data { id }
*/
async getComputerPrinter(data) {
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`);
const printerList = JSON.parse(printerListResult);
let printers = [];
if (!printerList || !printerList.data || printerList.data.length === 0) {
printers = [];
} else {
printers = printerList.data;
}
return this.success('success', { data: printers, code: 0 });
}
/**
* 8. 保存打印台的默认打印机与快递绑定打印机配置。
* @param {Object} data 请求参数。
* @param {string} data.defaultPrinter 默认打印机名称,必填。
* @param {Array<Object>} data.express 快递绑定数组,必填。
* @param {number|string} data.print_station_id 打印台 ID,必填。
* @returns {Promise<Object>} 保存结果。
*/
async savePrinters(data) {
const { ctx } = this;
const { defaultPrinter, express, print_station_id } = data;
if (!defaultPrinter || !Array.isArray(express) || !print_station_id) return this.fail('参数错误', { code: 1001 });
const item = await ctx.model.PrintStations.findOne({
where: {
id: print_station_id,
deleted: 0,
},
});
if (!item) return this.fail('打印台不存在', { code: 1002 });
const expressBindPrinter = express.map(expressItem => {
const sourceItem = expressItem && typeof expressItem === 'object' ? expressItem : {};
return {
printer_name: sourceItem.printer_name || sourceItem.name || defaultPrinter,
express_code: sourceItem.express_code || sourceItem.express_id,
};
});
const rawSubjectConfig = item.subject_config && typeof item.subject_config === 'object' && !Array.isArray(item.subject_config)
? item.subject_config
: {};
const mergedSubjectConfig = {
...rawSubjectConfig,
express_bind_printer: expressBindPrinter,
};
try {
item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(mergedSubjectConfig);
} catch (error) {
return this.fail(error.message, { code: 1001 });
}
item.default_printer_name = defaultPrinter;
item.update_at = new Date();
await item.save();
return this.success('success', { data: null, code: 0 });
}
}
module.exports = PrintService;