package com.engine.salary.entity.salaryBill.bo; import cn.hutool.core.io.FileUtil; import com.cloudstore.dev.api.bean.MessageBean; import com.cloudstore.dev.api.bean.MessageType; import com.cloudstore.dev.api.util.Util_Message; import com.engine.salary.annotation.SalaryFormulaVar; import com.engine.salary.constant.HrmSalaryPayrollConf; import com.engine.salary.constant.SalaryArchiveConstant; import com.engine.salary.constant.SalaryBillConstant; import com.engine.salary.constant.SalaryTemplateSalaryItemSetGroupConstant; import com.engine.salary.encrypt.AESEncryptUtil; import com.engine.salary.entity.datacollection.DataCollectionEmployee; import com.engine.salary.entity.salaryBill.dto.*; import com.engine.salary.entity.salaryBill.po.SalaryTemplatePO; import com.engine.salary.entity.salaryformula.dto.SalaryFormulaEmployeeDTO; import com.engine.salary.enums.salarybill.MessageChannelEnum; import com.engine.salary.enums.salarybill.SalaryTemplateTextContentPositionEnum; import com.engine.salary.enums.salarybill.SalaryTemplateWhetherEnum; import com.engine.salary.util.SalaryDateUtil; import com.engine.salary.util.SalaryI18nUtil; import com.engine.salary.util.pdf.HtmlToPdf; import com.fapiao.neon.util.Base64Utils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weaver.common.MessageUtil; import weaver.conn.RecordSet; import weaver.email.EmailWorkRunnable; import weaver.file.ImageFileManager; import weaver.general.Util; import weaver.hrm.company.SubCompanyComInfo; import weaver.hrm.resource.ResourceComInfo; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import static com.engine.salary.constant.HrmSalaryPayrollConf.HAS_SIGN; public class SalaryBillBO { private static final Logger log = LoggerFactory.getLogger(SalaryBillBO.class); @Override public String toString() { return "SalaryBillBO{}"; } // // /** // * 根据模板内容转为工资单模板对象 // * 注意:不要通过反序列化,可能会因为历史原因修改字段名称而无法序列化 // * // * @param salaryTemplateContent // * @return // */ // public static SalaryTemplatePO buildSalaryTemplateContent(String salaryTemplateContent) { // Map map = JsonUtil.parseMap(salaryTemplateContent, Object.class); // return SalaryTemplatePO.builder() // .id(Long.valueOf(map.getOrDefault("id", "0").toString())) // .name(map.getOrDefault("name", "").toString()) // .salarySobId(Long.valueOf(map.getOrDefault("salarySobId", "0").toString())) // .useType(Integer.valueOf(map.getOrDefault("useType", "0").toString())) // .description(map.getOrDefault("description", "").toString()) // .emailStatus(Integer.valueOf(map.getOrDefault("emailStatus", "0").toString())) // .sendEmailId(Long.valueOf(map.getOrDefault("sendEmailId", "0").toString())) //// .msgStatus(Integer.valueOf(map.getOrDefault("msgStatus","0").toString())) //// .imStatus(Integer.valueOf(map.getOrDefault("imStatus","0").toString())) //// .cloudBridgeStatus(Integer.valueOf(map.getOrDefault("cloudBridgeStatus","0").toString())) // .theme(map.getOrDefault("theme", "").toString()) // .background(map.getOrDefault("background", "").toString()) // .textContent(map.getOrDefault("textContent", "").toString()) // .textContentPosition(Integer.valueOf(map.getOrDefault("textContentPosition", "0").toString())) // .salaryItemNullStatus(Integer.valueOf(map.getOrDefault("salaryItemNullStatus", "0").toString())) // .salaryItemZeroStatus(Integer.valueOf(map.getOrDefault("salaryItemZeroStatus", "0").toString())) // .salaryItemSetting(map.getOrDefault("salaryItemSetting", "").toString()) // .replenishName(map.getOrDefault("replenishName", "").toString()) //// .replTheme(map.getOrDefault("replTheme","").toString()) //// .replBackground(map.getOrDefault("replBackground","").toString()) //// .replTextContent(map.getOrDefault("replTextContent","").toString()) //// .replTextContentPosition(Integer.valueOf(map.getOrDefault("replTextContentPosition","0").toString())) //// .replSalaryItemNullStatus(Integer.valueOf(map.getOrDefault("replSalaryItemNullStatus","0").toString())) //// .replSalaryItemZeroStatus(Integer.valueOf(map.getOrDefault("replSalaryItemZeroStatus","0").toString())) //// .replenishSalaryItemSetting(map.getOrDefault("replenishSalaryItemSetting","").toString()) // .build(); // } /** * 构建人员字段 * 与SalaryAcctResultBO.buildEmployeeFieldName()的key value对调了一下 * * @return */ public static Map buildEmployeeFieldName() { Field[] declaredFields = SalaryFormulaEmployeeDTO.class.getDeclaredFields(); Map employeeFieldNameMap = Maps.newHashMapWithExpectedSize(declaredFields.length); for (Field declaredField : declaredFields) { if (!declaredField.isAnnotationPresent(SalaryFormulaVar.class)) { continue; } SalaryFormulaVar annotation = declaredField.getAnnotation(SalaryFormulaVar.class); employeeFieldNameMap.put(SalaryI18nUtil.getI18nLabel(annotation.labelId(), annotation.defaultLabel()), declaredField.getName()); } return employeeFieldNameMap; } /** * 构建工资单中的人员信息 * * @param simpleEmployee */ public static void buildEmployeeInfo(SalaryBillSendDTO salaryBillSendParam, DataCollectionEmployee simpleEmployee) { SalaryTemplateSalaryItemSetListDTO employeeInformation = salaryBillSendParam.getEmployeeInformation(); Map employeeField = salaryBillSendParam.getEmployeeField(); if (employeeInformation == null || simpleEmployee == null) { return; } if (CollectionUtils.isNotEmpty(employeeInformation.getItems())) { //获取员工信息的字段名和中文描述的map关系 SalaryFormulaEmployeeDTO salaryFormulaEmployeeDTO = SalaryFormulaEmployeeDTO.builder() .employeeId(simpleEmployee.getEmployeeId()) .taxAgentName(salaryBillSendParam.getTaxAgentName()) .departmentName(simpleEmployee.getDepartmentName()) .companystartdate(simpleEmployee.getCompanystartdate()) .email(StringUtils.isEmpty(simpleEmployee.getEmail()) ? "" : simpleEmployee.getEmail()) .sex(simpleEmployee.getSex() == null ? "" : simpleEmployee.getSex()) .mobile(StringUtils.isEmpty(simpleEmployee.getMobile()) ? "" : simpleEmployee.getMobile()).jobtitleName(simpleEmployee.getJobtitleName()) .status(StringUtils.isEmpty(simpleEmployee.getStatus()) ? "" : simpleEmployee.getStatus()) .telephone(StringUtils.isEmpty(simpleEmployee.getTelephone()) ? "" : simpleEmployee.getTelephone()) .username(StringUtils.isEmpty(simpleEmployee.getUsername()) ? "" : simpleEmployee.getUsername()) .workcode(simpleEmployee.getWorkcode()) .idNo(simpleEmployee.getIdNo()) .statusName(simpleEmployee.getStatusName()) .accountType(simpleEmployee.getAccountType()) .accountTypeName(simpleEmployee.getAccountTypeName()) .build(); List items = employeeInformation.getItems(); // 1.SalaryAcctResultBO.buildEmployeeFieldName()的取法 // Set> entries = employeeField.entrySet(); // for (SalaryTemplateSalaryItemListDTO e : items) { // Optional> entry = entries.stream().filter(f -> Objects.equals(e.getName(), f.getValue())).findFirst(); // if (entry.isPresent()) { // String key = entry.get().getKey(); // if (StringUtils.isNotBlank(key)) { // String getter = "get" + key.substring(0, 1).toUpperCase() + key.substring(1); // try { // Method method = salaryFormulaEmployeeDTO.getClass().getMethod(getter); // Object invoke = method.invoke(salaryFormulaEmployeeDTO); // e.setSalaryItemValue((String) invoke); // } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { // log.error("no such method", e); // } // } // } // } // 2.SalaryBillBO.buildEmployeeFieldName() for (SalaryTemplateSalaryItemListDTO e : items) { String employeeFieldName = employeeField.get(e.getName()); if (!StringUtils.isEmpty(employeeFieldName)) { String getter = "get" + employeeFieldName.substring(0, 1).toUpperCase() + employeeFieldName.substring(1); try { Method method = salaryFormulaEmployeeDTO.getClass().getMethod(getter); Object invoke = method.invoke(salaryFormulaEmployeeDTO); e.setSalaryItemValue(Util.null2String(invoke)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { log.error("no such method", e); } } } } } /** * 获取工资单标题 * * @return */ public static String getBillTitle(String theme, Date salaryMonth, Long employeeId) { String companyName = ""; if (theme.contains("${companyName}")) { if (employeeId != null) { ResourceComInfo resourceComInfo = null; SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); try { resourceComInfo = new ResourceComInfo(); subCompanyComInfo = new SubCompanyComInfo(); } catch (Exception e) { log.error("资源异常", e); } companyName = subCompanyComInfo.getSubCompanyname(resourceComInfo.getSubCompanyID(employeeId + "")); companyName = Util.formatMultiLang(companyName); } } return theme.replace("${companyName}", companyName) .replace("${salaryMonth}", new SimpleDateFormat("yyyy年MM月").format(salaryMonth)) .replace("${salaryYear}", new SimpleDateFormat("yyyy年").format(salaryMonth)); } // /** // * 构建发送消息 // * // * @param e // * @param allEmployeeMap // * @param salaryBillSendParam // * @param currentEmployeeId // * @param currentTenantKey // * @return // */ // public static SendMessageEntity buildSendMessage(Map e, Map allEmployeeMap, SalaryBillSendDTO salaryBillSendParam, Long currentEmployeeId, String currentTenantKey) { // // 构建用户基本信息 // SalaryBillBO.buildEmployeeInfo(salaryBillSendParam.getEmployeeInformation(), allEmployeeMap.get(e.get("employeeId").toString()), salaryBillSendParam.getEmployeeField()); // // 消息接收者 // List receivers = Collections.singletonList(SalaryBillBO.buildUser(Long.valueOf(e.get("employeeId").toString()), Optional.ofNullable(e.get("email")).orElse("").toString(), currentTenantKey)); // Entity entity = SalaryBillBO.buildEntity(e.get("id").toString(), currentEmployeeId, salaryBillSendParam.getEntityName()); // EmailEntity emailInfo = new EmailEntity(); // // 邮箱打开 // if (salaryBillSendParam.isEnableEmail()) { // String emailContent = SalaryBillBO.buildEmailContent(e, salaryBillSendParam); // emailInfo = SalaryBillBO.buildEmailInfo(salaryBillSendParam.getText(), emailContent, salaryBillSendParam.getSalaryTemplate().getSendEmailId()); // } // return SalaryBillBO.buildSendMessageEntity(salaryBillSendParam, receivers, entity, emailInfo); // } /** * 发送Em消息 */ public static void sendMsg(SalaryBillSendDTO salaryBillSendParam, Long id, Long employeeId) { SalaryTemplatePO template = salaryBillSendParam.getSalaryTemplate(); String background = template.getBackground(); String billTitle = getBillTitle(template.getTheme(), salaryBillSendParam.getSalaryDate(), employeeId); MessageType messageType = MessageType.newInstance(499); // 消息来源(见文档第四点补充 必填) Set userIdList = new HashSet<>(); // 接收人id 必填 userIdList.add(employeeId.toString()); String title = billTitle; // 标题 String context = "点击查看详情"; // 内容 // PC端链接 String linkUrl = weaver.general.GCONST.getContextPath() + "/spa/hrmSalary/static/index.html#/main/hrmSalary/mobilepayroll?id=" + id + "&salaryCode=" + AESEncryptUtil.encrypt4SalaryBill(employeeId.toString()); // 移动端链接 String linkMobileUrl = weaver.general.GCONST.getContextPath() + "/spa/hrmSalary/static/index.html#/main/hrmSalary/mobilepayroll?type=phone&id=" + id + "&salaryCode=" + AESEncryptUtil.encrypt4SalaryBill(employeeId.toString()); try { MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl, linkMobileUrl); messageBean.setCreater(Integer.parseInt(salaryBillSendParam.getSendUser().getUID() + ""));// 创建人id messageBean.setBizState("0");// 需要修改消息为已处理等状态时传入,表示消息最初状态为待处理 messageBean.setTargetId("499|" + id); //消息来源code +“|”+业务id需要修改消息为已处理等状态时传入 if (StringUtils.isNotBlank(background)) { messageBean.setPictureUrl(background); } else { messageBean.setPictureUrl("/hrm/hrm_e9/images/payroll.jpg?pictype=jpg"); } Util_Message.store(messageBean); } catch (IOException e) { log.error("消息发送失败", e); } } public static void sendEmail(Map e, SalaryBillSendDTO salaryBillSendParam) { String content = genPayrollHtmlContent(e, salaryBillSendParam); // 消息接收者 String receivers = Optional.ofNullable(e.get("email")).orElse("").toString(); String title = getBillTitle(salaryBillSendParam.getSalaryTemplate().getTheme(), salaryBillSendParam.getSalaryDate(), Long.valueOf(e.get("employeeId").toString())); if (StringUtils.isNotBlank(receivers)) { EmailWorkRunnable.threadModeReminder(receivers, title, content); } } public static void genPdf(Map e, SalaryBillSendDTO salaryBillSendParam) { String content = genPayrollHtmlContent(e, salaryBillSendParam); String yyyyMM = SalaryDateUtil.getFormatYearMonth(salaryBillSendParam.getSalaryDate()); Long sendId = salaryBillSendParam.getSalarySend().getId(); Object id = e.getOrDefault("id", 1L); String htmlPath = HrmSalaryPayrollConf.GEN_PATH + yyyyMM + File.separator + sendId + File.separator + id + ".html"; FileUtil.del(htmlPath); File touch = FileUtil.touch(htmlPath); FileUtil.appendUtf8String(content, touch); String pdfPath = HrmSalaryPayrollConf.GEN_PATH + yyyyMM + File.separator + sendId + File.separator + id + ".pdf"; FileUtil.del(pdfPath); HtmlToPdf.convert(HrmSalaryPayrollConf.TO_PDF_TOOL_PATH, htmlPath, pdfPath); } /** * 合并pdff * * @param pdfPath 最终合并的pdf * @param filesToMerge 待合并的pdf */ public static void mergePdf(String pdfPath, List filesToMerge) { // 创建PDF合并工具实例 PDFMergerUtility merger = new PDFMergerUtility(); // 遍历要合并的PDF文件列表 for (String file : filesToMerge) { if (FileUtil.isFile(file)) { try { merger.addSource(file); // 将每个文件添加到合并工具 } catch (FileNotFoundException e) { log.error("PDF合并失败1", e); } } } // 设置合并后的目标文件 merger.setDestinationFileName(pdfPath); try { // 执行合并操作 FileUtil.del(pdfPath); merger.mergeDocuments(); } catch (IOException e) { log.error("PDF合并失败2", e); } } @NotNull private static String genPayrollHtmlContent(Map e, SalaryBillSendDTO salaryBillSendParam) { StringBuilder emailContent = new StringBuilder(); emailContent.append(""); emailContent.append("
"); SalaryBillBO.buildEmailContent(emailContent, e, salaryBillSendParam); // 构建水印内容 buildEmailWatermarkContent(emailContent, e, salaryBillSendParam); emailContent.append("
"); return emailContent.toString(); } public static byte[] readInputStream(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; try { while ((length = is.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.flush(); } catch (IOException e) { log.error(e.getMessage(), e); } byte[] data = baos.toByteArray(); try { is.close(); baos.close(); } catch (IOException e) { log.error(e.getMessage(), e); } return data; } public static void sendSMS(Map e, SalaryBillSendDTO salaryBillSendParam) { SalaryTemplateSMSSetDTO smsSetting = salaryBillSendParam.getSmsSetting(); String content = smsSetting != null ? smsSetting.getContent() : ""; if (StringUtils.isBlank(content)) { return; } content = content.replace("\n", "\r\n") .replace("{薪资所属月}", SalaryDateUtil.getFormatYearMonth(salaryBillSendParam.getSalaryDate())); for (SalaryTemplateSalaryItemListDTO item : salaryBillSendParam.getEmployeeInformation().getItems()) { content = content.replace("{" + item.getName() + "}", Util.null2String(item.getSalaryItemValue())); } for (SalaryTemplateSalaryItemSetListDTO salaryTemplateSalaryItemSetListDTO : salaryBillSendParam.getSalaryItemSetList()) { for (SalaryTemplateSalaryItemListDTO item : salaryTemplateSalaryItemSetListDTO.getItems()) { if (content.contains("{" + item.getName() + "}")) { content = content.replace("{" + item.getName() + "}", e.getOrDefault(item.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX, "").toString()); } } } try { if (e.get("mobile") != null) { MessageUtil.sendSMS(e.get("mobile").toString(), content); } else { log.error("发送短信失败,{}手机号为空", e.getOrDefault("username", "")); } } catch (Exception ex) { log.error("发送短信失败", ex); } } // /** // * 构建发送消息 // * // * @return // */ // public static SendMessageEntity buildSendMessageEntity(SalaryBillSendDTO salaryBillSendParam, List receivers, Entity entity, EmailEntity emailInfo) { // SendMessageEntity smg = new SendMessageEntity(); // // 模块 // smg.setModule(MessageModule.HRSA); // // 事件 // smg.setEvent(MessageEvent.PAYROLL); // // // 发送者 // smg.setSender(salaryBillSendParam.getSendUser() == null ? UserEntity.SYSTEM_USER : salaryBillSendParam.getSendUser()); // // 接收者 // smg.setReceivers(receivers); // // 发送通道 // smg.setChannels(salaryBillSendParam.getSendChannels()); // // // 消息内容 // smg.setText(salaryBillSendParam.getTitle()); // // // 1.im // smg.setEntity(entity); // // 2.云桥 // smg.setPcUrl(entity.getPcUrl()); // smg.setAppUrl(entity.getH5Url()); // smg.setTitle(salaryBillSendParam.getTitle()); // smg.setContent(salaryBillSendParam.getTitle()); // smg.setPicUrl(salaryBillSendParam.getPicUrl()); // // 3.邮件 // smg.setEmailInfo(emailInfo); // // return smg; // } // // /** // * 构建用户 // * // * @return // */ // public static UserEntity buildUser(Long employeeId, String email, String tenantKey) { // UserEntity user = new UserEntity(employeeId, tenantKey); // if (!StringUtils.isEmpty(email)) { // user.setEmail(email); // } // return user; // } /** * 构建发送通道 * * @param salaryTemplate * @return */ public static Set buildSendChannels(SalaryTemplatePO salaryTemplate) { Set channels = new HashSet<>(); if (salaryTemplate.getMsgStatus() == null || salaryTemplate.getMsgStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue())) { channels.add(MessageChannelEnum.MSG); } if (salaryTemplate.getEmailStatus() != null && salaryTemplate.getEmailStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()) && MessageUtil.checkSendEmail()) { channels.add(MessageChannelEnum.EMAIL); } if (salaryTemplate.getSmsStatus() != null && salaryTemplate.getSmsStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()) && MessageUtil.checkSendSMS()) { channels.add(MessageChannelEnum.SMS); } return channels; } // // /** // * 构建实体 // * // * @param id // * @param currentEmployeeId // * @param name // * @return // */ // public static Entity buildEntity(String id, Long currentEmployeeId, String name) { // Entity e = new Entity(); // e.setId(String.valueOf(IdGenerator.generate())); // e.setModule(EntityType.hrmsalary.name()); // e.setName(name); // e.setH5Url("/mobile/salary/mySalaryBill/view/" + id); //// e.setH5LinkeType(1); // e.setPcUrl("/sp/salary/mySalaryBill/view/" + id); //// e.setPcLinkeType(0); // // // im添加创建人创建时间、可在对应通道的模板中的内容或辅助信息标题等加上变量${creator}$和${createTime}$ // e.setCreatorId(currentEmployeeId); // e.setCreateTime(new Date()); // return e; // } // // /** // * 构建邮件信息 // * // * @param emailSubject 邮件主题 // * @param emailContent 邮件内容 // * @param mailUserAccountId 邮箱账号id // * @return // */ // public static EmailEntity buildEmailInfo(String emailSubject, String emailContent, Long mailUserAccountId) { // EmailEntity entity = new EmailEntity(); // entity.setEmailContent(emailContent); // entity.setEmailSubject(emailSubject); // // 发送者邮箱 // entity.setMailUserAccountId(mailUserAccountId); // return entity; // } // // /** // * 构建撤回消息 // * // * @param msgId // * @param text // * @param title // * @param currentEmployeeId // * @param currentTenantKey // * @return // */ // public static CancleMessageEntity buildCancleMessageEntity(long msgId, String text, String title, Long currentEmployeeId, String currentTenantKey) { // CancleMessageEntity cme = new CancleMessageEntity(); // cme.setMsgId(msgId); // // 模块 // cme.setModule(MessageModule.HRSA); // // 事件 // cme.setEvent(MessageEvent.PAYROLL); // // cme.setText(text); // // Entity entity = new Entity(); // entity.setId(String.valueOf(IdGenerator.generate())); // entity.setModule(EntityType.hrmsalary.name()); // entity.setName(title); // cme.setEntity(entity); // UserEntity user = new UserEntity(currentEmployeeId, currentTenantKey); // cme.setOperator(user); // return cme; // } /** * 构建邮件内容 * 注意:样式只能在标签style属性中使用,否则样式不生效 * * @param e * @param salaryBillSendParam * @return */ public static void buildEmailContent(StringBuilder emailContent, Map e, SalaryBillSendDTO salaryBillSendParam) { emailContent.append("
"); // 1.标题 emailContent.append("
"); // emailContent.append(salaryBillSendParam.getTitle()); emailContent.append(getBillTitle(salaryBillSendParam.getSalaryTemplate().getTheme(), salaryBillSendParam.getSalaryDate(), Long.valueOf(e.get("employeeId").toString()))); emailContent.append("
"); // 2.发送时间 emailContent.append("
"); emailContent.append(SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now())); emailContent.append("
"); // 3.背景图-base64 // if (!StringUtils.isEmpty(salaryBillSendParam.getBackgroundBase64())) { // emailContent.append("
"); // } // 3.背景图-url // if (StringUtils.isNotEmpty(salaryBillSendParam.getSalaryTemplate().getBackground())) { // emailContent.append("
"); // } // 是否只有一个分组,如果是,则将文本内容放进薪资项目表格前后 boolean isOnlyOneGroup = salaryBillSendParam.getSalaryItemSetList().stream().filter(st -> CollectionUtils.isNotEmpty(st.getItems())).count() == 1; if (isOnlyOneGroup) { buildOnlyOneGroupMailMain(emailContent, e, salaryBillSendParam); } else { buildMailMain(emailContent, e, salaryBillSendParam); } //签章 if (HAS_SIGN) { RecordSet rs = new RecordSet(); rs.execute("select * from DocSignature where hrmresid=" + e.getOrDefault("employeeId", "1") + " order by markid"); if (rs.next()) { int imagefileid = rs.getInt("imagefileid"); InputStream imageInputStream = ImageFileManager.getInputStreamById(imagefileid); byte[] data = readInputStream(imageInputStream); String imageBase64 = "data:image/jpeg;base64," + Base64Utils.encodeToString(data); emailContent.append("
\n" + " " + "
"); } } emailContent.append("
"); } /** * 构建邮件内容主体 * * @param emailContent * @param e * @param salaryBillSendParam */ private static void buildMailMain(StringBuilder emailContent, Map e, SalaryBillSendDTO salaryBillSendParam) { // 薪资项是否显示 boolean isHideNull = salaryBillSendParam.getSalaryTemplate().getSalaryItemNullStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()); boolean isHideZero = salaryBillSendParam.getSalaryTemplate().getSalaryItemZeroStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()); // 3.文本内容-如果在薪资项目前 emailContent.append("
"); emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent()); emailContent.append("
"); // 4.薪资项目内容 emailContent.append("
"); for (SalaryTemplateSalaryItemSetListDTO salaryItemSet : salaryBillSendParam.getSalaryItemSetList()) { if (CollectionUtils.isEmpty(salaryItemSet.getItems())) { continue; } emailContent.append("
"); if (!salaryItemSet.getGroupId().equals(SalaryTemplateSalaryItemSetGroupConstant.NO_TYPE_GROUP_ID)) { emailContent.append("
"); // 4.1.薪资项目组名 emailContent.append(salaryItemSet.getGroupName()); emailContent.append("
"); } emailContent.append(""); emailContent.append(""); List items = salaryItemSet.getItems(); List> itemsPartition = Lists.partition(items, 3); itemsPartition.forEach(itemPartition -> { emailContent.append(""); for (int i = 0; i < itemPartition.size(); i++) { SalaryTemplateSalaryItemListDTO salaryItem = itemPartition.get(i); // 员工基本信息 if (salaryItemSet.getGroupId().equals(SalaryTemplateSalaryItemSetGroupConstant.EMPLOYEE_INFO_GROUP_ID) && salaryBillSendParam.getEmployeeInformation() != null) { Optional optionalEmpItem = salaryBillSendParam.getEmployeeInformation().getItems().stream().filter(f -> f.getId().equals(salaryItem.getId())).findFirst(); // 4.2.员工信息 emailContent.append(""); emailContent.append(""); } else { for (Object keyName : e.keySet()) { if ((salaryItem.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX).equals(keyName.toString())) { String itemValue = Util.null2String(e.get(keyName.toString())); boolean isHide = (isHideNull && StringUtils.isEmpty(itemValue)) || (isHideZero && NumberUtils.isCreatable(e.getOrDefault(keyName.toString(), "0").toString()) && BigDecimal.ZERO.compareTo(new BigDecimal(e.getOrDefault(keyName.toString(), "0").toString())) == 0); if (!isHide) { // 4.2.薪资项目 emailContent.append(""); emailContent.append(""); } break; } } } } emailContent.append(""); }); emailContent.append(""); emailContent.append("
"); emailContent.append((optionalEmpItem.isPresent() ? optionalEmpItem.get().getName() : "")); emailContent.append(""); emailContent.append((optionalEmpItem.isPresent() ? optionalEmpItem.get().getSalaryItemValue() : "")); emailContent.append(""); emailContent.append(salaryItem.getName()); emailContent.append(""); emailContent.append(itemValue.replaceAll("null", "")); emailContent.append("
"); emailContent.append("
"); } emailContent.append("
"); // 5.文本内容-如果在薪资项目后 emailContent.append("
"); emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent()); emailContent.append("
"); } /** * 构建邮件内容主体 *

* 只有无分类,则将文本内容放进薪资项目表格前后 * * @param emailContent * @param e * @param salaryBillSendParam */ private static void buildOnlyOneGroupMailMain(StringBuilder emailContent, Map e, SalaryBillSendDTO salaryBillSendParam) { // 薪资项是否显示 boolean isHideNull = salaryBillSendParam.getSalaryTemplate().getSalaryItemNullStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()); boolean isHideZero = salaryBillSendParam.getSalaryTemplate().getSalaryItemZeroStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()); // 4.薪资项目内容 emailContent.append("

"); for (SalaryTemplateSalaryItemSetListDTO salaryItemSet : salaryBillSendParam.getSalaryItemSetList()) { if (CollectionUtils.isEmpty(salaryItemSet.getItems())) { continue; } emailContent.append("
"); emailContent.append("
"); // 3.文本内容-如果在薪资项目前 emailContent.append("
"); emailContent.append("
"); emailContent.append(""); emailContent.append(salaryBillSendParam.getRemarkI18n()); emailContent.append(""); emailContent.append("
"); emailContent.append("
"); emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent()); emailContent.append("
"); emailContent.append("
"); emailContent.append(""); emailContent.append(""); List items = salaryItemSet.getItems(); List> itemsPartition = Lists.partition(items, 3); itemsPartition.forEach(itemPartition -> { emailContent.append(""); for (int i = 0; i < itemPartition.size(); i++) { SalaryTemplateSalaryItemListDTO salaryItem = itemPartition.get(i); for (Object keyName : e.keySet()) { if ((salaryItem.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX).equals(keyName.toString())) { String itemValue = Util.null2String(e.get(keyName.toString())); boolean isHide = (isHideNull && StringUtils.isEmpty(itemValue)) || (isHideZero && NumberUtils.isCreatable(e.getOrDefault(keyName.toString(), "0").toString()) && BigDecimal.ZERO.compareTo(new BigDecimal(e.getOrDefault(keyName.toString(), "0").toString())) == 0); if (!isHide) { // 4.2.薪资项目 emailContent.append(""); emailContent.append(""); } break; } } } emailContent.append(""); }); emailContent.append(""); emailContent.append("
"); emailContent.append(salaryItem.getName()); emailContent.append(""); emailContent.append(itemValue.replaceAll("null", "")); emailContent.append("
"); // 5.文本内容-如果在薪资项目后 emailContent.append("
"); emailContent.append("
"); emailContent.append(""); emailContent.append(salaryBillSendParam.getRemarkI18n()); emailContent.append(""); emailContent.append("
"); emailContent.append("
"); emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent()); emailContent.append("
"); emailContent.append("
"); emailContent.append("
"); emailContent.append("
"); } emailContent.append("
"); } public static String HRM_Name = "HRM_Name"; public static String HRM_Num = "HRM_Num"; public static String HRM_Mobile = "HRM_Mobile"; public static String HRM_Email = "HRM_Email"; public static String HRM_CurrentOperatorId = "HRM_CurrentOperatorId"; public static String HRM_Department = "HRM_Department"; public static String HRM_SecondDepartment = "HRM_SecondDepartment"; public static String HRM_CurrentDate = "HRM_CurrentDate"; public static String HRM_CurrentTime = "HRM_CurrentTime"; public static String HRM_prefix = "$"; /** * 构建水印 *

* 当前所拥有的变量 * "HRM_Name",当前操作者姓名 * "HRM_Num",当前操作者编号 * "HRM_Mobile",当前操作者移动电话 * "HRM_Email",当前操作者电子邮件 * "HRM_CurrentOperatorId",当前操作者人员ID * "HRM_Department",当前操作者部门 * "HRM_SecondDepartment",当前操作者分部 * "HRM_CurrentDate",当前日期 * "HRM_CurrentTime"当前时间 * * @param emailContent * @param e * @param salaryBillSendParam */ private static void buildEmailWatermarkContent(StringBuilder emailContent, Map e, SalaryBillSendDTO salaryBillSendParam) { if (Objects.isNull(salaryBillSendParam.getWatermarkSetting())) { return; } String emailWmContentTemplate = salaryBillSendParam.getEmailWmContentTemplate(); List wmTextFieldIds = salaryBillSendParam.getWmTextFieldIds(); // 没有变量,则直接返回 if (CollectionUtils.isEmpty(wmTextFieldIds)) { emailContent.append(emailWmContentTemplate); } else { for (String wmTextFieldId : wmTextFieldIds) { // 当前操作者姓名 if (HRM_Name.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Name, Optional.ofNullable(e.get("username")).orElse(StringUtils.EMPTY).toString()); // 当前操作者编号 } else if (HRM_Num.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Num, Optional.ofNullable(e.get("jobNum")).orElse(StringUtils.EMPTY).toString()); // 当前操作者移动电话 } else if (HRM_Mobile.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Mobile, Optional.ofNullable(e.get("mobile")).orElse(StringUtils.EMPTY).toString()); // 当前操作者电子邮件 } else if (HRM_Email.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Email, Optional.ofNullable(e.get("email")).orElse(StringUtils.EMPTY).toString()); // 当前操作者人员ID } else if (HRM_CurrentOperatorId.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentOperatorId, Optional.ofNullable(e.get("id")).orElse(StringUtils.EMPTY).toString()); // 当前操作者分部 } else if (HRM_Department.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Department, Optional.ofNullable(e.get("department")).orElse(StringUtils.EMPTY).toString()); } else if (HRM_SecondDepartment.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_SecondDepartment, Optional.ofNullable(e.get("subCompanyName")).orElse(StringUtils.EMPTY).toString()); // 当前日期 } else if (HRM_CurrentDate.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentDate, SalaryDateUtil.getFormatLocalDate(LocalDate.now())); // 当前时间 } else if (HRM_CurrentTime.equals(wmTextFieldId)) { emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentTime, SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now())); } } emailContent.append(emailWmContentTemplate); } } /** * 获取工资单水印文本动态变量 * * @param domain * @param salaryBillWatermark * @return */ public static List getWmTextFieldIds(String domain, SalaryBillWatermarkDTO salaryBillWatermark) { List wmTextFieldIds = Collections.emptyList(); // 没有水印、关闭水印、或者系统水印,则不拼接 // if (Objects.isNull(salaryBillWatermark) || !salaryBillWatermark.getWatermarkStatus() || !SalaryTemplateWatermarkTypeEnum.CUSTOM.getValue().equals(salaryBillWatermark.getWatermarkType())) { if (Objects.isNull(salaryBillWatermark) || !salaryBillWatermark.getWatermarkStatus()) { return wmTextFieldIds; } String wmClassify = salaryBillWatermark.getWmSetting().getOrDefault("wmClassify", StringUtils.EMPTY).toString(); if ("text".equals(wmClassify)) { wmTextFieldIds = (List) salaryBillWatermark.getWmSetting().getOrDefault("wmSelectedFieldIds", Collections.emptyList()); List empFields = Arrays.asList(HRM_Name, HRM_Num, HRM_Mobile, HRM_Email, HRM_CurrentOperatorId, HRM_Department, HRM_SecondDepartment); if (wmTextFieldIds.contains(HRM_SecondDepartment)) { // 需要查分部 salaryBillWatermark.getWmSetting().put("needQuerySubDepart", true); } // 需要查人员 salaryBillWatermark.getWmSetting().put("needQueryEmp", wmTextFieldIds.stream().anyMatch(empFields::contains)); salaryBillWatermark.getWmSetting().remove("wmImg"); } else if ("image".equals(wmClassify)) { List> wmImgs = Collections.emptyList(); try { wmImgs = (List>) salaryBillWatermark.getWmSetting().getOrDefault("wmImg", Collections.emptyList()); } catch (Exception exception) { log.error("工资单水印图片转换失败"); } if (CollectionUtils.isNotEmpty(wmImgs)) { Map map = wmImgs.get(0); String fileid = map.getOrDefault("fileid", StringUtils.EMPTY).toString(); if (StringUtils.isNotEmpty(fileid)) { String imgSrc = domain + String.format("/weaver/weaver.file.FileDownload?fileid=%s", fileid); // String imgSrc = domain + String.format("/papi/file/preview?type=imgs&fileId=%s&random=123456", fileid); salaryBillWatermark.getWmSetting().put("wmImg", imgSrc); } } salaryBillWatermark.getWmSetting().remove("wmText"); salaryBillWatermark.getWmSetting().remove("wmSelectedFieldIds"); } // 作为快照,去掉不必要的属性,节省空间 salaryBillWatermark.getWmSetting().remove("wmOriginText"); salaryBillWatermark.getWmSetting().remove("pureWmText"); return wmTextFieldIds; } public static String buildEmailWmContentTemplate(boolean isEnableEmail, SalaryBillWatermarkDTO watermarkSetting) { String emailWmContentTemplate = StringUtils.EMPTY; // 没有水印、关闭水印,则不拼接 if (!isEnableEmail || Objects.isNull(watermarkSetting) || !watermarkSetting.getWatermarkStatus()) { return emailWmContentTemplate; } String wmClassify = watermarkSetting.getWmSetting().getOrDefault("wmClassify", StringUtils.EMPTY).toString(); String variable = StringUtils.EMPTY; if ("text".equals(wmClassify)) { variable = watermarkSetting.getWmSetting().getOrDefault("wmText", StringUtils.EMPTY).toString(); } else if ("image".equals(wmClassify)) { // String imgSrc = watermarkSetting.getWmSetting().getOrDefault("wmImg", StringUtils.EMPTY).toString(); // variable = ""; // watermarkSetting.getWmSetting().put("wmImg", imgSrc); // 邮件不支持图片水印 return emailWmContentTemplate; } if (StringUtils.isEmpty(variable)) { return emailWmContentTemplate; } String wmNoTransparent = watermarkSetting.getWmSetting().getOrDefault("wmNoTransparent", "0.15").toString(); double wmRotate = new Double(watermarkSetting.getWmSetting().getOrDefault("wmRotate", 0).toString()); double noTransparent = new Double(wmNoTransparent) / 100.00; StringBuilder emailWmContentTemp = new StringBuilder(); emailWmContentTemp.append("

"); emailWmContentTemp.append("
"); for (int i = 0; i < 20; i++) { emailWmContentTemp.append("
"); for (int j = 0; j < 8; j++) { emailWmContentTemp.append("
"); // 赋值 emailWmContentTemp.append(variable); emailWmContentTemp.append("
"); } emailWmContentTemp.append("
"); } emailWmContentTemp.append("
"); emailWmContentTemp.append("
"); return emailWmContentTemp.toString(); } public static String handleWmText(String wmText, List wmTextFieldIds, DataCollectionEmployee simpleEmployee) { for (String wmTextFieldId : wmTextFieldIds) { // 当前操作者姓名 if (SalaryBillConstant.HRM_Name.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Name, Objects.isNull(simpleEmployee) ? StringUtils.EMPTY : simpleEmployee.getUsername()); // 当前操作者编号 } else if (SalaryBillConstant.HRM_Num.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Num, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getWorkcode()) ? StringUtils.EMPTY : simpleEmployee.getWorkcode()); // 当前操作者移动电话 } else if (SalaryBillConstant.HRM_Mobile.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Mobile, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getMobile()) ? StringUtils.EMPTY : simpleEmployee.getMobile()); // 当前操作者电子邮件 } else if (SalaryBillConstant.HRM_Email.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Email, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getEmail()) ? StringUtils.EMPTY : simpleEmployee.getEmail()); // 当前操作者人员ID } else if (SalaryBillConstant.HRM_CurrentOperatorId.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentOperatorId, Objects.isNull(simpleEmployee) ? StringUtils.EMPTY : simpleEmployee.getEmployeeId().toString()); // 当前操作者部门 } else if (SalaryBillConstant.HRM_Department.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Department, Objects.isNull(simpleEmployee) || Objects.isNull(simpleEmployee.getDepartmentName()) ? StringUtils.EMPTY : simpleEmployee.getDepartmentName()); // 当前操作者分部 } else if (SalaryBillConstant.HRM_SecondDepartment.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_SecondDepartment, Objects.isNull(simpleEmployee) || Objects.isNull(simpleEmployee.getSubcompanyName()) ? StringUtils.EMPTY : simpleEmployee.getSubcompanyName()); // 当前日期 } else if (SalaryBillConstant.HRM_CurrentDate.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentDate, SalaryDateUtil.getFormatLocalDate(LocalDate.now())); // 当前时间 } else if (SalaryBillConstant.HRM_CurrentTime.equals(wmTextFieldId)) { wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentTime, SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now())); } } return wmText; } }