WMS_MAIN/app/service/systems/setting/print_template.js
liufumingren 0c3518e65d 1
2026-05-13 03:18:39 +08:00

693 lines
21 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';
const Service = require('egg').Service;
const SUPPORTED_BUSINESS_TYPES = [ 'STOCK', 'RECEIPT', 'PICKING' ];
class PrintTemplateService extends Service {
/**
* 标准化并校验业务类型
* @param {string} businessType 业务类型
* @param {boolean} required 是否必填
* @return {string|null} 标准化后的业务类型
*/
normalizeAndValidateBusinessType(businessType, required = true) {
const normalizedBusinessType = String(businessType || '').trim().toUpperCase();
if (!normalizedBusinessType) {
if (required) {
throw new Error('business_type 参数不能为空');
}
return null;
}
if (!SUPPORTED_BUSINESS_TYPES.includes(normalizedBusinessType)) {
throw new Error(`business_type 参数非法,仅支持:${SUPPORTED_BUSINESS_TYPES.join('、')}`);
}
return normalizedBusinessType;
}
/**
* 获取指定业务类型的模板列表
* @param {string} businessType 业务类型
* @return {Promise<Array>} 模板列表
*/
async listTemplatesByType(businessType) {
const normalizedBusinessType = this.normalizeAndValidateBusinessType(businessType);
return await this.getTemplatesByType(normalizedBusinessType);
}
/**
* 获取打印模板树
* @return {Promise<Array>} 树状结构
*/
async getTree() {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 获取当前用户仓库ID
const warehouseId = ctx.user.store_id;
try {
// 1. 获取所有业务类型及打印项
const businessTypeItems = await this.getBusinessTypesAndItem();
const businessTypes = SUPPORTED_BUSINESS_TYPES;
// 2. 查询所有打印模板,按业务类型分组
const templates = await ctx.model.PrintTemplate.findAll({
where: {
status: 'ACTIVE',
business_type: {
[Op.in]: SUPPORTED_BUSINESS_TYPES,
},
warehouse_id: {
[Op.or]: [ warehouseId, null ],
},
},
order: [
[ 'business_type', 'ASC' ],
[ 'is_default', 'DESC' ],
[ 'create_at', 'DESC' ],
],
});
const templatesByType = {};
templates.forEach(template => {
const type = template.business_type;
if (!templatesByType[type]) templatesByType[type] = [];
templatesByType[type].push({
...template.toJSON(),
name: template.template_name,
key: `template_${template.id}`,
title: `${template.template_name}(${template.page_width}mmx${template.page_height}mm)`,
editable: template.warehouse_id !== null,
deletable: template.warehouse_id !== null,
isDefault: template.is_default,
isGeneral: template.warehouse_id === null,
selectable: true,
type: 'template',
});
});
// 3. 构建树结构,业务类型节点下children为所有模板,printItems属性为所有打印项
const tree = businessTypes.map(businessType => {
const children = templatesByType[businessType] || [];
return {
key: `type_${businessType}`,
title: businessType,
type: 'category',
businessType,
children,
printItems: businessTypeItems[businessType] ? (businessTypeItems[businessType].groupList || []) : [],
editable: false,
deletable: false,
isGeneral: false,
selectable: false,
};
});
return tree;
} catch (error) {
ctx.logger.error('获取打印模板树失败:', error);
throw new Error('获取打印模板失败');
}
}
/**
* 获取指定业务类型的模板列表
* @param {string} businessType 业务类型
* @return {Promise<Array>} 模板列表
*/
async getTemplatesByType(businessType) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const normalizedBusinessType = this.normalizeAndValidateBusinessType(businessType);
const warehouseId = ctx.user.store_id;
try {
const templates = await ctx.model.PrintTemplate.findAll({
where: {
status: 'ACTIVE',
business_type: normalizedBusinessType,
warehouse_id: {
[Op.or]: [ warehouseId, null ],
},
},
order: [
[ 'is_default', 'DESC' ],
[ 'create_at', 'DESC' ],
],
});
return templates.map(template => {
const { warehouse_id } = template;
return {
...template.toJSON(),
editable: warehouse_id !== null,
deletable: warehouse_id !== null,
isGeneral: warehouse_id === null,
};
});
} catch (error) {
ctx.logger.error('获取业务类型模板失败:', error);
return [];
}
}
/**
* 保存打印模板(创建或更新)
* @param {Object} data 模板数据
* @return {Promise<Object>} 保存结果
*/
async save(data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { id, template_name, business_type, page_width, page_height, template_content } = data;
const normalizedBusinessType = this.normalizeAndValidateBusinessType(business_type, !id);
try {
if (id) {
// 更新现有模板
const template = await ctx.model.PrintTemplate.findOne({
where: {
id,
warehouse_id: warehouseId,
},
});
if (!template) {
throw new Error('模板不存在或无权限');
}
const updatePayload = {
template_name,
page_width,
page_height,
template_content,
};
if (normalizedBusinessType) {
updatePayload.business_type = normalizedBusinessType;
}
await template.update(updatePayload);
return { message: '模板更新成功', code: 200 };
}
// 创建新模板
await ctx.model.PrintTemplate.create({
template_name,
business_type: normalizedBusinessType,
page_width,
page_height,
template_content,
warehouse_id: warehouseId,
status: 'ACTIVE',
});
return { message: '模板创建成功', code: 200 };
} catch (error) {
ctx.logger.error('保存打印模板失败:', error);
throw new Error('保存打印模板失败');
}
}
/**
* 创建打印模板
* @param {Object} data 模板数据
* @return {Promise<Object>} 创建结果
*/
async createTemplate(data = {}) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const now = new Date();
const {
template_name,
business_type,
page_width,
page_height,
template_content = [],
is_default = false,
} = data;
if (!String(template_name || '').trim()) {
throw new Error('template_name 参数不能为空');
}
if (page_width === undefined || page_width === null || String(page_width).trim() === '') {
throw new Error('page_width 参数不能为空');
}
if (page_height === undefined || page_height === null || String(page_height).trim() === '') {
throw new Error('page_height 参数不能为空');
}
const normalizedBusinessType = this.normalizeAndValidateBusinessType(business_type);
const platform = 'default';
const template_type = 'CUSTOM';
const template_url = '';
const existingTemplate = await ctx.model.PrintTemplate.findOne({
where: {
business_type: normalizedBusinessType,
platform,
template_type,
warehouse_id: warehouseId,
},
order: [[ 'id', 'DESC' ]],
});
if (existingTemplate) {
if (existingTemplate.status === 'ACTIVE') {
throw new Error('同一业务类型和平台下已存在自定义模板');
}
await existingTemplate.update({
template_name,
page_width,
page_height,
template_content,
template_url,
is_default,
status: 'ACTIVE',
delete_at: null,
update_at: now,
});
return {
message: '模板创建成功',
code: 200,
data: {
id: existingTemplate.id,
},
};
}
let created;
try {
created = await ctx.model.PrintTemplate.create({
template_name,
business_type: normalizedBusinessType,
page_width,
page_height,
template_content,
platform,
template_type,
template_url,
is_default,
warehouse_id: warehouseId,
status: 'ACTIVE',
create_at: now,
update_at: now,
delete_at: null,
}, {
validate: false,
});
} catch (error) {
if (error?.name === 'SequelizeUniqueConstraintError') {
throw new Error('同一业务类型和平台下已存在自定义模板');
}
const details = Array.isArray(error?.errors)
? error.errors.map(item => `${item.path || 'unknown'}:${item.message}`).join(';')
: '';
const errMsg = [ error?.name, error?.message, details ].filter(Boolean).join(' | ');
throw new Error(errMsg || '模板创建失败');
}
return {
message: '模板创建成功',
code: 200,
data: {
id: created.id,
},
};
}
async deleteTemplate(id) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const template = await ctx.model.PrintTemplate.findOne({
where: {
id,
warehouse_id: warehouseId,
status: 'ACTIVE',
},
});
if (!template) {
throw new Error('模板不存在或无权限');
}
await template.update({
status: 'DISABLED',
delete_at: new Date(),
update_at: new Date(),
});
return {
message: '模板删除成功',
code: 200,
data: {
id,
},
};
}
/**
* 获取所有业务类型(用于下拉选择)- 支持分组展示
* @return {Object} 业务类型及打印项列表,包含分组信息
*/
async getBusinessTypesAndItem() {
const { ctx, app } = this;
const cacheKey = 'print_item:business_types_and_items_v2';
try {
// 1. 先查缓存
let result = await app.getCacheAsync(cacheKey);
if (result) {
return result;
}
// 2. 未命中缓存则查库
const printItems = await ctx.model.PrintItem.findAll({
where: {
status: 1,
},
order: [
[ 'business_type', 'ASC' ],
[ 'group_sort', 'ASC' ], // 先按分组排序
[ 'sort_order', 'ASC' ], // 再按字段排序
],
});
result = {};
// 3. 处理数据:按业务类型 + 分组字段双重分组
printItems.forEach(item => {
const type = item.business_type;
const groupField = item.group_field || 'ungrouped'; // 无分组的归入"未分组"
const groupLabel = item.group_label || 'common.ungrouped'; // 分组标题(国际化key)
// 初始化业务类型
if (!result[type]) {
result[type] = {
businessType: type,
groups: {}, // 按group_field分组
tableItems: [], // 表格类型的打印项
ungrouped: [], // 未分组的打印项
};
}
// 转换为JSON
const itemJson = {
...item.toJSON(),
key: `item_${item.id}`,
title: item.field_name,
groupConfig: item.group_field ? {
field: item.group_field,
label: item.group_label,
sort: item.group_sort,
} : null,
};
if (groupField !== 'ungrouped') {
// 有分组的普通字段
if (!result[type].groups[groupField]) {
result[type].groups[groupField] = {
groupField,
groupLabel,
groupSort: item.group_sort || 999,
fields: [],
};
}
result[type].groups[groupField].fields.push(itemJson);
} else {
// 未分组的普通字段
result[type].ungrouped.push(itemJson);
}
});
// 5. 对每个业务类型内的分组进行排序
Object.keys(result).forEach(type => {
// 对分组进行排序
const groups = result[type].groups;
result[type].groupList = Object.values(groups).sort((a, b) => {
return (a.groupSort || 999) - (b.groupSort || 999);
});
// 对分组内的字段排序
result[type].groupList.forEach(group => {
group.fields.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
});
// 对未分组字段排序
result[type].ungrouped.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
// 对表格字段排序
result[type].tableItems.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
});
// 6. 写入缓存(5分钟)
await app.setCacheAsync(cacheKey, result, 300);
return result;
} catch (error) {
ctx.logger.error('获取业务类型及打印项失败:', error);
return {};
}
}
/**
* 获取按分组组织的打印项(用于打印预览)
* @param {string} businessType - 业务类型
* @param {string} platform - 平台
* @return {Object} 分组后的打印项
*/
async getGroupedPrintItems(businessType, platform) {
const { ctx } = this;
const items = await ctx.model.PrintItem.findAll({
where: {
business_type: businessType,
platform: platform || 'default',
status: 1,
},
order: [
[ 'group_sort', 'ASC' ],
[ 'sort_order', 'ASC' ],
],
});
const result = {
tableItems: [], // 表格项目
groupItems: {}, // 分组项目
ungrouped: [], // 未分组项目
};
items.forEach(item => {
const itemJson = item.toJSON();
if (item.is_table) {
// 表格项目
result.tableItems.push({
...itemJson,
config: item.table_config,
});
} else if (item.group_field) {
// 分组项目
if (!result.groupItems[item.group_field]) {
result.groupItems[item.group_field] = {
groupField: item.group_field,
groupLabel: item.group_label,
groupSort: item.group_sort,
fields: [],
};
}
result.groupItems[item.group_field].fields.push(itemJson);
} else {
// 未分组项目
result.ungrouped.push(itemJson);
}
});
// 转换分组对象为数组并排序
result.groupList = Object.values(result.groupItems)
.sort((a, b) => (a.groupSort || 999) - (b.groupSort || 999));
return result;
}
/**
* 获取表格配置(用于渲染动态表格)
* @param {string} businessType - 业务类型
* @param {string} platform - 平台
* @return {Array} 表格配置列表
*/
async getTableConfigs(businessType, platform) {
const { ctx } = this;
const tables = await ctx.model.PrintItem.findAll({
where: {
business_type: businessType,
platform: platform || 'default',
is_table: true,
status: 1,
},
order: [[ 'sort_order', 'ASC' ]],
});
return tables.map(table => ({
id: table.id,
fieldName: table.field_name,
fieldCode: table.field_code,
config: table.table_config,
groupField: table.group_field,
groupSort: table.group_sort,
}));
}
/**
* 清空业务类型缓存
*/
async clearBusinessTypesCache() {
const { app } = this;
const cacheKey = 'print_item:business_types_and_items_v2';
await app.delCacheAsync(cacheKey);
}
async getXmlByTemplate(id) {
const { ctx } = this;
try {
const template = await ctx.model.PrintTemplate.findOne({
where: {
id,
},
});
if (!template) {
throw new Error('模板不存在');
}
const xmlResult = this.buildXmlFromElements(template, template.template_content);
return xmlResult;
} catch (error) {
ctx.logger.error('根据模板生成XML失败:', error);
throw new Error('生成XML失败');
}
}
buildXmlFromElements(template, elements) {
// XML头
let xml = `<?xml version="1.0" encoding="UTF-8"?>
<page
xmlns="http://cloudprint.cainiao.com/print"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd"
xmlns:editor="http://cloudprint.cainiao.com/schema/editor"
width="${template.page_width || 76}" height="${template.page_height || 130}" splitable="false">
<header height="0"></header>
`;
// 遍历所有元素
for (let i = 0; i < elements.length; i++) {
const el = elements[i];
xml += this.renderElement(el, i);
}
xml += '</page>';
return xml;
}
renderElement(el, index) {
const [ styleText, textStyleText ] = this.computeItemStyle(el, index);
let widthAndHeightText = `width="${el.width || 50}" height="${el.height || 20}" `;
if (el.type === 'table') {
widthAndHeightText = '';
}
let layout = `<layout style="${styleText}" left="${el.left || 0}" top="${el.top || 0}" ${widthAndHeightText} rotation="${el.rotation || 0}" >`;
switch (el.type) {
case 'text':
if (el.field_code) {
layout += `<text style="${textStyleText}"><![CDATA[<%=_data.${el.field_code}%>]]></text>`;
} else {
layout += `<text style="${textStyleText}"><![CDATA[${el.content || ''}]]></text>`;
}
break;
case 'image':
if (el.field_code) {
layout += `<image><![CDATA[<%=_data.${el.field_code}%>]]></image>`;
} else {
layout += `<image><![CDATA[${el.content || ''}]]></image>`;
}
break;
case 'qrcode':
if (el.field_code) {
layout += `<barcode type="qrcode" ratioMode="keepRatio"><![CDATA[<%=_data.${el.field_code}%>]]></barcode>`;
} else {
layout += `<barcode type="qrcode" ratioMode="keepRatio"><![CDATA[${el.content || ''}]]></barcode>`;
}
break;
case 'barcode':
if (el.field_code) {
layout += `<barcode type="code128" style="hideText:true;rotation:0" ratioMode="keepRatio"><![CDATA[<%=_data.${el.field_code}%>]]></barcode>`;
} else {
layout += `<barcode type="code128" style="hideText:true;rotation:0" ratioMode="keepRatio"><![CDATA[${el.content || ''}]]></barcode>`;
}
break;
case 'table': {
const tableContent = this.renderTable(el, index);
layout += `<table>${tableContent}</table>`;
break;
}
case 'shape':
break;
default:
break;
}
return `${layout}
</layout>
`;
}
computeItemStyle(item, index) {
const base = {
border: '1px dashed #999',
transform: `rotate(${(item.rotate || 0) * 90}deg)`,
zIndex: index,
};
const textStyleBase = {
fontSize: (item.fontSize || 12),
align: item.textAlign || 'left',
lineHeight: (item.lineHeight || 6),
fontWeight: item.bold ? 'bold' : 'normal',
};
const textStyleText = Object.entries(textStyleBase).map(([ key, value ]) => `${key}:${value}`).join(';') + ';';
const styleText = Object.entries(base).map(([ key, value ]) => `${key}:${value}`).join(';') + ';';
return [ styleText, textStyleText ];
}
computeTableItemStyle(item, index) {
const base = {
border: '1px dashed #999',
fontSize: (item.fontSize || 12),
textAlign: item.textAlign || 'left',
lineHeight: (item.lineHeight || 6),
transform: `rotate(${(item.rotate || 0) * 90}deg)`,
zIndex: index,
overflow: 'hidden',
};
const styleText = Object.entries(base).map(([ key, value ]) => `${key}:${value}`).join(';') + ';';
return styleText;
}
renderTable(el, index) {
const rows = Array.isArray(el.rows) ? el.rows : [];
const fieldCode = String(el.field_code || '').trim();
if (!fieldCode || rows.length === 0) {
return '';
}
let headerTds = '<tr>';
let bodyTds = '<% const tableRows = Array.isArray(_data.items) ? _data.items : []; for (var rowIndex = 0; rowIndex < tableRows.length; rowIndex++) { %><tr>';
for (let i = 0; i < rows.length; i++) {
const headerText = el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`;
headerTds += `<td style="${this.computeTableItemStyle(el, index)}">${headerText}</td>`;
bodyTds += `<td style="${this.computeTableItemStyle(el, index)}"><![CDATA[<%=(tableRows[rowIndex] && tableRows[rowIndex].${fieldCode}_col${i + 1} !== undefined ? tableRows[rowIndex].${fieldCode}_col${i + 1} : '')%>]]></td>`;
}
headerTds += '</tr>';
bodyTds += '</tr><% } %>';
return headerTds + bodyTds;
}
}
module.exports = PrintTemplateService;