'use strict';
const { up } = require('../../../database/migrations/20251109160640-init-wms_account');
// 打印相关 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' }
];
}
async send(_data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { printer, type, template, data, computerId, timestamp, count } = _data;
console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count);
//生成打印编号并记录到数据库
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":
const { page_width, page_height, template_content } = template;
let htm = `
`;
for (const item of template_content) {
let content = item.content;
for(const key in data) {
console.log("正在匹配字段:", key, "与", item.field_code);
if(item.field_code == key) {
content = data[key];
}
}
console.log("转后的内容:", content);
switch (item.type) {
case "text":
htm += `${content}
`;
break;
case "image":
htm += `
`;
break;
case "barcode":
htm += ``;
break;
case "qrcode":
let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`;
//转换成urlencode
toUrl = encodeURIComponent(toUrl);
let url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`;
htm += ``;
break;
case "line":
htm += ``;
break;
case "rectangle":
htm += ``;
break;
case "table":
let tableHtml = ``;
for (let i = 0; i < item.rows; i++) {
tableHtml += ``;
for (let j = 0; j < item.columns; j++) {
let content = item.content[i] && item.content[i][j] ? item.content[i][j] : '';
tableHtml += `| ${content} | `;
} tableHtml += `
`;
} tableHtml += `
`;
htm += tableHtml;
break;
}
}
htm += ``;
processedData = {
pageWidth: page_width,
pageHeight: page_height,
htm: 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: computerId, data:printData});
console.log('sendToComputer response', res);
//发送成功后更新打印记录状态
if (res.status=="success") {
await printRecord.update({ status: 'sent' });
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
} else {
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;
console.log("ctx.user in PrintService constructor", ctx.user);
const warehouse_id = ctx.user.store_id;
// TODO: 需根据实际分页和条件查询调整
const { page = 1, pageSize = 20, where = {} } = data;
// 字段过滤
const filter = {};
['id', 'name', 'computer_id', 'custom_barcode'].forEach(key => {
if (where[key]) filter[key] = where[key];
});
filter.warehouse_id = warehouse_id;
filter.deleted = 0;
// 查询总数
console.log("ctx.model.PrintStations", ctx.model.PrintStations);
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,
});
let 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++) {
let key = `warehouse:${warehouse_id}:printer:${computers[i].id}`;
const computerInfo = await this.app.redis.get("printer").get(key);
console.log("key and computerInfo", key, computerInfo);
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);
console.log("componentKey and componentInfo", componentKey, componentInfo);
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: list,
pagination: {
hasNext: page * pageSize < total,
hasPrevious: page > 1,
page: page,
pageSize: pageSize,
total: total,
totalPages: Math.ceil(total / pageSize),
},
queryInfo: {
conditions: 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 }
*/
async add(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const { name, computer_id, custom_barcode } = data;
if (!name || !computer_id) return this.fail('参数错误', 1001);
const newItem = await ctx.model.PrintStations.create({
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,
});
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 }
*/
async updateItem(data) {
const { ctx } = this;
const { id, name, computer_id, custom_barcode } = 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;
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);
// 软删除
const result = await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } });
// TODO: 检查 result 是否成功
return this.success('success', { data: null, code: 0 });
}
/**
* 5. 获取打印电脑列表
* @param {Object} data {}
*/
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 { ctx } = this;
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const printerListResult = await this.app.redis.get("printer").get(`printer:${id}:printerList`);
console.log("getComputerPrinter printerListResult", printerListResult);
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 { default, express }
*/
async savePrinters(data) {
const { ctx } = this;
const { defaultPrinter, express } = data;
// express: [{ express_id, name }]
if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001);
// TODO: 需根据打印台ID、快递ID等实际业务调整
// 这里只做示例保存,实际应覆盖原有绑定
// 1. 保存默认打印机
// 2. 保存 express 打印机绑定
// 3. 需用 PrintStationExpress model
// 示例:批量保存
for (const item of express) {
await ctx.model.PrintStationExpress.upsert({
print_station_id: data.print_station_id, // 需传入
express_id: item.express_id,
express_name: item.name,
printer_name: item.name,
is_default: item.name === defaultPrinter ? 1 : 0,
creator_id: ctx.user?.id || '',
creator_name: ctx.user?.name || '',
create_at: new Date(),
update_at: new Date(),
deleted: 0,
});
}
return this.success('success', { data: null, code: 0 });
}
}
module.exports = PrintService;