'use strict'; const Service = require('egg').Service; class PrintTemplateService extends Service { /** * 获取指定业务类型的模板列表 * @param {string} businessType 业务类型 * @return {Promise} 模板列表 */ async listTemplatesByType(businessType) { console.log('获取业务类型模板列表, businessType:', businessType); return await this.getTemplatesByType(businessType); } /** * 获取打印模板树 * @return {Promise} 树状结构 */ 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 = Object.keys(businessTypeItems); // 2. 查询所有打印模板,按业务类型分组 const templates = await ctx.model.PrintTemplate.findAll({ where: { status: 'ACTIVE', 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].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} 模板列表 */ async getTemplatesByType(businessType) { const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; console.log(businessType, warehouseId); try { const templates = await ctx.model.PrintTemplate.findAll({ where: { status: 'ACTIVE', business_type: businessType, warehouse_id: { [Op.or]: [ warehouseId, null ], }, }, order: [ [ 'is_default', 'DESC' ], [ 'create_at', 'DESC' ], ], }); console.log(`查询到${templates.length}个模板,businessType: ${businessType}, warehouseId: ${warehouseId}`); 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 []; } } async save(data) { const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; console.log('保存打印模板数据:', data); const { id, template_name, business_type, page_width, page_height, template_content } = data; try { if (id) { // 更新现有模板 const template = await ctx.model.PrintTemplate.findOne({ where: { id, warehouse_id: warehouseId, }, }); if (!template) { throw new Error('模板不存在或无权限'); } await template.update({ template_name, business_type, page_width, page_height, template_content, }); return { message: '模板更新成功', code: 200 }; } // 创建新模板 await ctx.model.PrintTemplate.create({ template_name, business_type, page_width, page_height, template_content, warehouse_id: warehouseId, status: 'ACTIVE', }); return { message: '模板创建成功', code: 200 }; } catch (error) { ctx.logger.error('保存打印模板失败:', error); throw new Error('保存打印模板失败'); } } 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; const platform = 'default'; const template_type = 'CUSTOM'; const template_url = ''; const existingTemplate = await ctx.model.PrintTemplate.findOne({ where: { business_type, 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, 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 = `
`; // 遍历所有元素 for (let i = 0; i < elements.length; i++) { const el = elements[i]; xml += this.renderElement(el, i); } xml += '
'; 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 = ``; switch (el.type) { case 'text': if (el.field_code) { layout += `]]>`; } else { layout += ``; } break; case 'image': if (el.field_code) { layout += `]]>`; } else { layout += ``; } break; case 'qrcode': if (el.field_code) { layout += `]]>`; } else { layout += ``; } break; case 'barcode': if (el.field_code) { layout += `]]>`; } else { layout += ``; } break; case 'table': const tableContent = this.renderTable(el, index); layout += `${tableContent}
`; break; case 'shape': } return `${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 tableText = ''; const rows = el.rows || []; // 表头 let headerTds = ''; let bodyTds = '<% for(var i=0; i<(_data.items.length); i++) { %>'; for (let i = 0; i < el.rows; i++) { headerTds += `${el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`}`; bodyTds += `]]>`; } headerTds += ''; bodyTds += '<%}%>'; return headerTds + bodyTds; } } module.exports = PrintTemplateService;