diff --git a/src/com/engine/salary/biz/TaxRateBiz.java b/src/com/engine/salary/biz/TaxRateBiz.java index 5de95c902..e1f3eb817 100644 --- a/src/com/engine/salary/biz/TaxRateBiz.java +++ b/src/com/engine/salary/biz/TaxRateBiz.java @@ -31,20 +31,20 @@ public class TaxRateBiz extends BaseBean { try { TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class); SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class); - TaxRateBase TaxRateBase = taxRateBaseMapper.getById(id); + TaxRateBase taxRateBase = taxRateBaseMapper.getById(id); // 如果自定义税率表中没有再查询系统默认的税率表 - if (Objects.isNull(TaxRateBase)) { + if (Objects.isNull(taxRateBase)) { SysTaxRateBase sysTaxRateBase = sysTaxRateBaseMapper.getById(id); - TaxRateBase = new TaxRateBase(); + taxRateBase = new TaxRateBase(); //fixme 逻辑可能有问题,自定义和系统的id保持一致? if (sysTaxRateBase != null) { - BeanUtils.copyProperties(sysTaxRateBase, TaxRateBase); + BeanUtils.copyProperties(sysTaxRateBase, taxRateBase); } } - return TaxRateBase; + return taxRateBase; } finally { sqlSession.close(); } diff --git a/src/com/engine/salary/cmd/TaxAgent/TaxAgentDeleteCmd.java b/src/com/engine/salary/cmd/TaxAgent/TaxAgentDeleteCmd.java index 09d5e8a3d..54d5104c4 100644 --- a/src/com/engine/salary/cmd/TaxAgent/TaxAgentDeleteCmd.java +++ b/src/com/engine/salary/cmd/TaxAgent/TaxAgentDeleteCmd.java @@ -40,7 +40,7 @@ public class TaxAgentDeleteCmd extends AbstractCommonCommand SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession(); try { TaxAgentMapper taxAgentMapper = sqlSession.getMapper(TaxAgentMapper.class); - +// String sql = MyBatisFactory.sqlSessionFactory.getConfiguration().getMappedStatement("com.engine.salary.mapper.TaxAgentMapper.delete").getBoundSql(TaxAgent.builder().id(1l).build()).getSql(); List taxAgents = taxAgentMapper.listBySome(TaxAgentQueryParam.builder().ids(idList).build()); if (CollectionUtils.isEmpty(taxAgents)) { throw new SalaryRunTimeException("要删除的个税扣缴义务人在不存在或已删除"); diff --git a/src/com/engine/salary/cmd/datacollection/AddUpDeductionListCmd.java b/src/com/engine/salary/cmd/datacollection/AddUpDeductionListCmd.java new file mode 100644 index 000000000..0f3aadfad --- /dev/null +++ b/src/com/engine/salary/cmd/datacollection/AddUpDeductionListCmd.java @@ -0,0 +1,178 @@ +package com.engine.salary.cmd.datacollection; + +import com.cloudstore.eccom.constant.WeaBoolAttr; +import com.cloudstore.eccom.pc.table.WeaTable; +import com.cloudstore.eccom.pc.table.WeaTableColumn; +import com.cloudstore.eccom.pc.table.WeaTableOperate; +import com.cloudstore.eccom.pc.table.WeaTableOperates; +import com.cloudstore.eccom.result.WeaResultMsg; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import weaver.general.PageIdConst; +import weaver.hrm.User; + +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; + +public class AddUpDeductionListCmd extends AbstractCommonCommand> { + + public AddUpDeductionListCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + + String fileds = " t1.id," + + " t1.declare_month," + + " t1.employee_id," + + " e.lastname as username," + + " d.departmentname AS departmentName," + + " e.mobile," + + " e.lloginid as job_num," + + " e.created as hiredate," + + " t2.name AS tax_agent_name," + + " t1.add_up_child_education," + + " t1.add_up_continuing_education," + + " t1.add_up_housing_loan_interest," + + " t1.add_up_housing_rent," + + " t1.add_up_support_elderly"; + + String fromSql = " FROM" + + " hrsa_add_up_deduction t1" + + " LEFT JOIN hrsa_tax_agent t2 ON t1.tax_agent_id = t2.id" + + " LEFT JOIN hrmresource e ON t1.employee_id = e.id" + + " LEFT JOIN hrmdepartment d ON e.departmentid = d.id"; + + + Map apidatas = new HashMap(16); + + WeaResultMsg result = new WeaResultMsg(false); + String pageID = "a4f85287-e3f9-4275-adn9-7d06e54y6rj8"; + String pageUid = pageID + "_" + user.getUID(); + String pageSize = PageIdConst.getPageSize(pageID, user.getUID()); + + + WeaTable table = new WeaTable(); + table.setPageUID(pageUid); + table.setPageID(pageID); + table.setPagesize(pageSize); + table.setBackfields(fileds); + table.setSqlform(fromSql); + table.setSqlwhere(makeSqlWhere()); + table.setSqlorderby("t1.id DESC"); + table.setSqlprimarykey("t1.id"); + table.setSqlisdistinct("false"); + + table.getColumns().add(new WeaTableColumn("id").setDisplay(WeaBoolAttr.FALSE)); + table.getColumns().add(new WeaTableColumn("10%", "姓名", "username", "")); + table.getColumns().add(new WeaTableColumn("10%", "个税扣缴义务人", "taxAgentName", "")); + table.getColumns().add(new WeaTableColumn("10%", "部门", "departmentName", "")); + table.getColumns().add(new WeaTableColumn("10%", "手机号", "mobile", "")); + table.getColumns().add(new WeaTableColumn("10%", "工号", "jobNum", "")); + table.getColumns().add(new WeaTableColumn("10%", "证件号码", "idNo", "")); + table.getColumns().add(new WeaTableColumn("10%", "入职日期", "hiredate", "")); + table.getColumns().add(new WeaTableColumn("20%", "操作", "operate", "")); + + List operateList = new ArrayList<>(); + WeaTableOperate delete = new WeaTableOperate("删除", "", "0"); + operateList.add(delete); + WeaTableOperates weaTableOperates = new WeaTableOperates(); + weaTableOperates.setOperate(operateList); + table.setOperates(weaTableOperates); + + //设置check是否可用 + table.setCheckboxList(null); + table.setCheckboxpopedom(null); + result.putAll(table.makeDataResult()); + result.success(); + apidatas = result.getResultMap(); + return apidatas; + } + + + private String makeSqlWhere() { + + AddUpDeductionQueryParam queryParam = (AddUpDeductionQueryParam) params.get("queryParam"); + //申报月份 + List declareMonth = queryParam.getDeclareMonth(); + if (CollectionUtils.isNotEmpty(declareMonth)) { + queryParam.setDeclareMonth(declareMonth.stream().map(e -> e + "-01 00:00:00").collect(Collectors.toList())); + } + + String sqlWhere = "t1.delete_type = 0 AND t2.delete_type = 0"; + Collection ids = queryParam.getIds(); + if (CollectionUtils.isNotEmpty(ids)) { + String idsStr = ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + sqlWhere += " AND t1.id IN (" + idsStr + ")"; + } + Long employeeId = queryParam.getEmployeeId(); + if (employeeId != null) { + sqlWhere += " AND t1.employee_id =" + employeeId; + } + String keyword = queryParam.getKeyword(); + if (StringUtils.isNotBlank(keyword)) { + sqlWhere += " AND (" + + " e.lastname like '%" + keyword + "%'" + + " OR d.departmentname like '%" + keyword + "%'" + +// " OR e.job_num like ''%"+keyword+"%'" + + " )"; + } + // 申报月份 + List declareMonths = queryParam.getDeclareMonth(); + if (CollectionUtils.isNotEmpty(declareMonths)) { + if (declareMonths.size() == 1) { + sqlWhere += " AND t1.declare_month = " + declareMonths.get(0); + } + if (declareMonths.size() == 2) { + sqlWhere += " AND (t1.declare_month BETWEEN " + declareMonths.get(0) + " AND " + declareMonths.get(1) + ")"; + } + } + //姓名 + String username = queryParam.getUsername(); + if (StringUtils.isNotBlank(username)) { + sqlWhere += " AND e.lastname like '%" + username + "%'"; + } + //个税扣缴义务人 + Long taxAgentId = queryParam.getTaxAgentId(); + if (taxAgentId != null) { + sqlWhere += " AND t1.tax_agent_id = " + taxAgentId; + } + //部门 + List departmentIds = queryParam.getDepartmentIds(); + if (CollectionUtils.isNotEmpty(departmentIds)) { + String departmentStrIds = departmentIds.stream().map(String::valueOf).collect(Collectors.joining(",")); + sqlWhere += " AND d.id IN (" + departmentStrIds + ")"; + } + //工号 + String jobNum = queryParam.getJobNum(); + if (StringUtils.isNotBlank(jobNum)) { + sqlWhere += " AND e.lloginid like '%" + jobNum + "%'"; + } + //入职日期 + List hiredate = queryParam.getHiredate(); + if (CollectionUtils.isNotEmpty(hiredate) && hiredate.size() == 2) { + sqlWhere += " AND (e.created BETWEEN "+hiredate.get(0)+" AND "+hiredate.get(1)+")"; + } + //手机号 + String mobile = queryParam.getMobile(); + if (StringUtils.isNotBlank(mobile)) { + sqlWhere += " AND e.mobile like '%" + mobile + "%'"; + } + + return sqlWhere; + } + + +} diff --git a/src/com/engine/salary/entity/datacollection/AddUpDeduction.java b/src/com/engine/salary/entity/datacollection/AddUpDeduction.java new file mode 100644 index 000000000..6e4b78666 --- /dev/null +++ b/src/com/engine/salary/entity/datacollection/AddUpDeduction.java @@ -0,0 +1,75 @@ +package com.engine.salary.entity.datacollection; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * 数据采集-累计专项附加扣除表 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AddUpDeduction { + /** + * 累计子女教育 + */ + private String addUpChildEducation; + /** + * 累计继续教育 + */ + private String addUpContinuingEducation; + /** + * 累计住房贷款利息 + */ + private String addUpHousingLoanInterest; + /** + * 累计住房租金 + */ + private String addUpHousingRent; + /** + * 累计赡养老人 + */ + private String addUpSupportElderly; + /** + * 创建时间 + */ + private Date createTime; + /** + * 创建人 + */ + private Long creator; + /** + * 申报月份 + */ + private Date declareMonth; + /** + * 是否已删除。0:未删除、1:已删除 + */ + private Integer deleteType; + /** + * 人员信息表的主键id + */ + private Long employeeId; + /** + * 主键 + */ + private Long id; + /** + * 个税扣缴义务人的主键id + */ + private Long taxAgentId; + /** + * 租户ID + */ + private String tenantKey; + /** + * 更新时间 + */ + private Date updateTime; + +} \ No newline at end of file diff --git a/src/com/engine/salary/entity/datacollection/AddUpSituation.java b/src/com/engine/salary/entity/datacollection/AddUpSituation.java new file mode 100644 index 000000000..236d6cf2f --- /dev/null +++ b/src/com/engine/salary/entity/datacollection/AddUpSituation.java @@ -0,0 +1,115 @@ +package com.engine.salary.entity.datacollection; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * 数据采集-累计情况表 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AddUpSituation { + /** + * 累计公积金个人合计 + */ + private String addUpAccumulationFundTotal; + /** + * 累计已预扣预缴税额 + */ + private String addUpAdvanceTax; + /** + * 累计准予扣除的捐赠额 + */ + private String addUpAllowedDonation; + /** + * 累计子女教育 + */ + private String addUpChildEducation; + /** + * 累计继续教育 + */ + private String addUpContinuingEducation; + /** + * 累计企业(职业)年金及其他福利 + */ + private String addUpEnterpriseAndOther; + /** + * 累计住房贷款利息 + */ + private String addUpHousingLoanInterest; + /** + * 累计住房租金 + */ + private String addUpHousingRent; + /** + * 累计收入额 + */ + private String addUpIncome; + /** + * 累计其他扣除 + */ + private String addUpOtherDeduction; + /** + * 累计社保个人合计 + */ + private String addUpSocialSecurityTotal; + /** + * 累计减除费用 + */ + private String addUpSubtraction; + /** + * 累计赡养老人 + */ + private String addUpSupportElderly; + /** + * 累计免税收入 + */ + private String addUpTaxExemptIncome; + /** + * 创建时间 + */ + private Date createTime; + /** + * 创建人 + */ + private Long creator; + /** + * 是否已删除。0:未删除、1:已删除 + */ + private Integer deleteType; + /** + * 人员信息表的主键id + */ + private Long employeeId; + /** + * 主键 + */ + private Long id; + /** + * 个税扣缴义务人的主键id + */ + private Long taxAgentId; + /** + * 税款所属期 + */ + private Date taxYearMonth; + /** + * 租户ID + */ + private String tenantKey; + /** + * 更新时间 + */ + private Date updateTime; + /** + * 年份 + */ + private Integer year; + +} \ No newline at end of file diff --git a/src/com/engine/salary/entity/datacollection/DataCollectionEmployee.java b/src/com/engine/salary/entity/datacollection/DataCollectionEmployee.java new file mode 100644 index 000000000..0e36ee248 --- /dev/null +++ b/src/com/engine/salary/entity/datacollection/DataCollectionEmployee.java @@ -0,0 +1,28 @@ +package com.engine.salary.entity.datacollection; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @Description: 员工基本信息 + * @Author: wangxiangzhong + * @Date: 2022/2/10 16:25 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +//@ApiModel("员工基本信息") +public class DataCollectionEmployee { + +// @ApiModelProperty("员工id") + private Long employeeId; + +// @ApiModelProperty("姓名") + private String username; + +// @ApiModelProperty("部门") + private String deparmentName; +} diff --git a/src/com/engine/salary/entity/datacollection/param/AddUpDeductionQueryParam.java b/src/com/engine/salary/entity/datacollection/param/AddUpDeductionQueryParam.java new file mode 100644 index 000000000..c9cf65691 --- /dev/null +++ b/src/com/engine/salary/entity/datacollection/param/AddUpDeductionQueryParam.java @@ -0,0 +1,62 @@ +package com.engine.salary.entity.datacollection.param; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.util.Collection; +import java.util.List; + +/** + * @Description: 数据采集-累计专项附加扣除 + * @Author: wangxiangzhong + * @Date: 2021-11-10 11:17 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +//("数据采集-累计专项附加扣除查询参数") +public class AddUpDeductionQueryParam{ + + //@ApiModelProperty("主键id") + private Collection ids; + + //@ApiModelProperty("关键字(姓名、部门、工号)") + private String keyword; + + //@ApiModelProperty("主键id") + private Long id; + + //@ApiModelProperty("申报月份") + private List declareMonth; + + //@ApiModelProperty("姓名") + private String username; + + //@ApiModelProperty("员工id") + private Long employeeId; + + //@ApiModelProperty("个税扣缴义务人的主键id") + private Long taxAgentId; + + //@ApiModelProperty("部门id") + private List departmentIds; + + //@ApiModelProperty("工号") + private String jobNum; + + //@ApiModelProperty("证件号") + private String idNo; + + //@ApiModelProperty("入职日期") + private List hiredate; + + //@ApiModelProperty("手机号") + private String mobile; + + //@ApiModelProperty("累计专项附加扣除id(获取明细)") + private Long accumulatedSpecialAdditionalDeductionId; +} diff --git a/src/com/engine/salary/entity/taxrate/SysTaxRateBase.java b/src/com/engine/salary/entity/taxrate/SysTaxRateBase.java index 9d2a33e71..e62c2b758 100644 --- a/src/com/engine/salary/entity/taxrate/SysTaxRateBase.java +++ b/src/com/engine/salary/entity/taxrate/SysTaxRateBase.java @@ -43,7 +43,7 @@ public class SysTaxRateBase { /** * 是否是系统默认的。0:自定义、1:系统默认 */ - private Byte systemType; + private Integer systemType; /** * 租户ID */ diff --git a/src/com/engine/salary/entity/taxrate/bo/TaxRateBO.java b/src/com/engine/salary/entity/taxrate/bo/TaxRateBO.java index 2636bf36c..8b7e2e84e 100644 --- a/src/com/engine/salary/entity/taxrate/bo/TaxRateBO.java +++ b/src/com/engine/salary/entity/taxrate/bo/TaxRateBO.java @@ -121,8 +121,8 @@ public class TaxRateBO { .incomeLowerLimit(e.getIncomeLowerLimit()) .dutyFreeValue(e.getDutyFreeValue()) .dutyFreeRate(e.getDutyFreeRate()) - .taxableIncomeUl(Optional.ofNullable(e.getTaxableIncomeULimit()).orElse(BigDecimal.ZERO)) - .taxableIncomeLl(Optional.ofNullable(e.getTaxableIncomeLLimit()).orElse(BigDecimal.ZERO)) + .taxableIncomeUl(Optional.ofNullable(e.getTaxableIncomeUl()).orElse(BigDecimal.ZERO)) + .taxableIncomeLl(Optional.ofNullable(e.getTaxableIncomeLl()).orElse(BigDecimal.ZERO)) .taxRate(Optional.ofNullable(e.getTaxRate()).orElse(BigDecimal.ZERO)) .taxDeduction(Optional.ofNullable(e.getTaxDeduction()).orElse(BigDecimal.ZERO)) .createTime(new Date()) diff --git a/src/com/engine/salary/entity/taxrate/param/TaxRateDetailSaveParam.java b/src/com/engine/salary/entity/taxrate/param/TaxRateDetailSaveParam.java index 9edf2a857..3ac2c6a3b 100644 --- a/src/com/engine/salary/entity/taxrate/param/TaxRateDetailSaveParam.java +++ b/src/com/engine/salary/entity/taxrate/param/TaxRateDetailSaveParam.java @@ -36,10 +36,10 @@ public class TaxRateDetailSaveParam { private BigDecimal dutyFreeRate; //taxRateDetailMapper("应纳税所得额上限(含)") - private BigDecimal taxableIncomeULimit; + private BigDecimal taxableIncomeUl; //taxRateDetailMapper("应纳税所得额下限(不含)") - private BigDecimal taxableIncomeLLimit; + private BigDecimal taxableIncomeLl; //taxRateDetailMapper("税率") private BigDecimal taxRate; diff --git a/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.java b/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.java new file mode 100644 index 000000000..c3ee314ee --- /dev/null +++ b/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.java @@ -0,0 +1,76 @@ +package com.engine.salary.mapper.datacollection; + +import com.engine.salary.entity.datacollection.AddUpDeduction; +import com.engine.salary.entity.datacollection.DataCollectionEmployee; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface AddUpDeductionMapper { + + /** + * 查询所有记录 + * + * @return 返回集合,没有返回空List + */ + List listAll(); + + + /** + * 根据主键查询 + * + * @param id 主键 + * @return 返回记录,没有返回null + */ + AddUpDeduction getById(Long id); + + /** + * 新增,插入所有字段 + * + * @param addUpDeduction 新增的记录 + * @return 返回影响行数 + */ + int insert(AddUpDeduction addUpDeduction); + + /** + * 新增,忽略null字段 + * + * @param addUpDeduction 新增的记录 + * @return 返回影响行数 + */ + int insertIgnoreNull(AddUpDeduction addUpDeduction); + + /** + * 修改,修改所有字段 + * + * @param addUpDeduction 修改的记录 + * @return 返回影响行数 + */ + int update(AddUpDeduction addUpDeduction); + + /** + * 修改,忽略null字段 + * + * @param addUpDeduction 修改的记录 + * @return 返回影响行数 + */ + int updateIgnoreNull(AddUpDeduction addUpDeduction); + + /** + * 删除记录 + * + * @param addUpDeduction 待删除的记录 + * @return 返回影响行数 + */ + int delete(AddUpDeduction addUpDeduction); + + + /** + * 获取所有员工 + * @return + */ + List listEmployee(); + + +} \ No newline at end of file diff --git a/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.xml b/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.xml new file mode 100644 index 000000000..f1b88380b --- /dev/null +++ b/src/com/engine/salary/mapper/datacollection/AddUpDeductionMapper.xml @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + t + . + add_up_child_education + , t.add_up_continuing_education + , t.add_up_housing_loan_interest + , t.add_up_housing_rent + , t.add_up_support_elderly + , t.create_time + , t.creator + , t.declare_month + , t.delete_type + , t.employee_id + , t.id + , t.tax_agent_id + , t.tenant_key + , t.update_time + + + + + + + + + + + INSERT INTO hrsa_add_up_deduction + + add_up_child_education, + add_up_continuing_education, + add_up_housing_loan_interest, + add_up_housing_rent, + add_up_support_elderly, + create_time, + creator, + declare_month, + delete_type, + employee_id, + id, + tax_agent_id, + tenant_key, + update_time, + + + #{addUpChildEducation}, + #{addUpContinuingEducation}, + #{addUpHousingLoanInterest}, + #{addUpHousingRent}, + #{addUpSupportElderly}, + #{createTime}, + #{creator}, + #{declareMonth}, + #{deleteType}, + #{employeeId}, + #{id}, + #{taxAgentId}, + #{tenantKey}, + #{updateTime}, + + + + + + INSERT INTO hrsa_add_up_deduction + + + + add_up_child_education, + + + add_up_continuing_education, + + + add_up_housing_loan_interest, + + + add_up_housing_rent, + + + add_up_support_elderly, + + + create_time, + + + creator, + + + declare_month, + + + delete_type, + + + employee_id, + + + id, + + + tax_agent_id, + + + tenant_key, + + + update_time, + + + + + #{addUpChildEducation}, + + + #{addUpContinuingEducation}, + + + #{addUpHousingLoanInterest}, + + + #{addUpHousingRent}, + + + #{addUpSupportElderly}, + + + #{createTime}, + + + #{creator}, + + + #{declareMonth}, + + + #{deleteType}, + + + #{employeeId}, + + + #{id}, + + + #{taxAgentId}, + + + #{tenantKey}, + + + #{updateTime}, + + + + + + + UPDATE hrsa_add_up_deduction + + add_up_child_education=#{addUpChildEducation}, + add_up_continuing_education=#{addUpContinuingEducation}, + add_up_housing_loan_interest=#{addUpHousingLoanInterest}, + add_up_housing_rent=#{addUpHousingRent}, + add_up_support_elderly=#{addUpSupportElderly}, + create_time=#{createTime}, + creator=#{creator}, + declare_month=#{declareMonth}, + delete_type=#{deleteType}, + employee_id=#{employeeId}, + tax_agent_id=#{taxAgentId}, + tenant_key=#{tenantKey}, + update_time=#{updateTime}, + + WHERE id = #{id} AND delete_type = 0 + + + + + + UPDATE hrsa_add_up_deduction + + + add_up_child_education=#{addUpChildEducation}, + + + add_up_continuing_education=#{addUpContinuingEducation}, + + + add_up_housing_loan_interest=#{addUpHousingLoanInterest}, + + + add_up_housing_rent=#{addUpHousingRent}, + + + add_up_support_elderly=#{addUpSupportElderly}, + + + create_time=#{createTime}, + + + creator=#{creator}, + + + declare_month=#{declareMonth}, + + + delete_type=#{deleteType}, + + + employee_id=#{employeeId}, + + + tax_agent_id=#{taxAgentId}, + + + tenant_key=#{tenantKey}, + + + update_time=#{updateTime}, + + + WHERE id = #{id} AND delete_type = 0 + + + + + + UPDATE hrsa_add_up_deduction + SET delete_type=1 + WHERE id = #{id} + AND delete_type = 0 + + + + + + + \ No newline at end of file diff --git a/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.java b/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.java new file mode 100644 index 000000000..62c7e68a2 --- /dev/null +++ b/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.java @@ -0,0 +1,67 @@ +package com.engine.salary.mapper.datacollection; + +import com.engine.salary.entity.datacollection.AddUpSituation; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface AddUpSituationMapper { + + /** + * 查询所有记录 + * + * @return 返回集合,没有返回空List + */ + List listAll(); + + + /** + * 根据主键查询 + * + * @param id 主键 + * @return 返回记录,没有返回null + */ + AddUpSituation getById(Long id); + + /** + * 新增,插入所有字段 + * + * @param addUpSituation 新增的记录 + * @return 返回影响行数 + */ + int insert(AddUpSituation addUpSituation); + + /** + * 新增,忽略null字段 + * + * @param addUpSituation 新增的记录 + * @return 返回影响行数 + */ + int insertIgnoreNull(AddUpSituation addUpSituation); + + /** + * 修改,修改所有字段 + * + * @param addUpSituation 修改的记录 + * @return 返回影响行数 + */ + int update(AddUpSituation addUpSituation); + + /** + * 修改,忽略null字段 + * + * @param addUpSituation 修改的记录 + * @return 返回影响行数 + */ + int updateIgnoreNull(AddUpSituation addUpSituation); + + /** + * 删除记录 + * + * @param addUpSituation 待删除的记录 + * @return 返回影响行数 + */ + int delete(AddUpSituation addUpSituation); + +} \ No newline at end of file diff --git a/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.xml b/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.xml new file mode 100644 index 000000000..7ea1a1650 --- /dev/null +++ b/src/com/engine/salary/mapper/datacollection/AddUpSituationMapper.xml @@ -0,0 +1,411 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + t + . + add_up_accumulation_fund_total + , t.add_up_advance_tax + , t.add_up_allowed_donation + , t.add_up_child_education + , t.add_up_continuing_education + , t.add_up_enterprise_and_other + , t.add_up_housing_loan_interest + , t.add_up_housing_rent + , t.add_up_income + , t.add_up_other_deduction + , t.add_up_social_security_total + , t.add_up_subtraction + , t.add_up_support_elderly + , t.add_up_tax_exempt_income + , t.create_time + , t.creator + , t.delete_type + , t.employee_id + , t.id + , t.tax_agent_id + , t.tax_year_month + , t.tenant_key + , t.update_time + , t.year + + + + + + + + + + + INSERT INTO hrsa_add_up_situation + + add_up_accumulation_fund_total, + add_up_advance_tax, + add_up_allowed_donation, + add_up_child_education, + add_up_continuing_education, + add_up_enterprise_and_other, + add_up_housing_loan_interest, + add_up_housing_rent, + add_up_income, + add_up_other_deduction, + add_up_social_security_total, + add_up_subtraction, + add_up_support_elderly, + add_up_tax_exempt_income, + create_time, + creator, + delete_type, + employee_id, + id, + tax_agent_id, + tax_year_month, + tenant_key, + update_time, + year, + + + #{addUpAccumulationFundTotal}, + #{addUpAdvanceTax}, + #{addUpAllowedDonation}, + #{addUpChildEducation}, + #{addUpContinuingEducation}, + #{addUpEnterpriseAndOther}, + #{addUpHousingLoanInterest}, + #{addUpHousingRent}, + #{addUpIncome}, + #{addUpOtherDeduction}, + #{addUpSocialSecurityTotal}, + #{addUpSubtraction}, + #{addUpSupportElderly}, + #{addUpTaxExemptIncome}, + #{createTime}, + #{creator}, + #{deleteType}, + #{employeeId}, + #{id}, + #{taxAgentId}, + #{taxYearMonth}, + #{tenantKey}, + #{updateTime}, + #{year}, + + + + + + INSERT INTO hrsa_add_up_situation + + + + add_up_accumulation_fund_total, + + + add_up_advance_tax, + + + add_up_allowed_donation, + + + add_up_child_education, + + + add_up_continuing_education, + + + add_up_enterprise_and_other, + + + add_up_housing_loan_interest, + + + add_up_housing_rent, + + + add_up_income, + + + add_up_other_deduction, + + + add_up_social_security_total, + + + add_up_subtraction, + + + add_up_support_elderly, + + + add_up_tax_exempt_income, + + + create_time, + + + creator, + + + delete_type, + + + employee_id, + + + id, + + + tax_agent_id, + + + tax_year_month, + + + tenant_key, + + + update_time, + + + year, + + + + + #{addUpAccumulationFundTotal}, + + + #{addUpAdvanceTax}, + + + #{addUpAllowedDonation}, + + + #{addUpChildEducation}, + + + #{addUpContinuingEducation}, + + + #{addUpEnterpriseAndOther}, + + + #{addUpHousingLoanInterest}, + + + #{addUpHousingRent}, + + + #{addUpIncome}, + + + #{addUpOtherDeduction}, + + + #{addUpSocialSecurityTotal}, + + + #{addUpSubtraction}, + + + #{addUpSupportElderly}, + + + #{addUpTaxExemptIncome}, + + + #{createTime}, + + + #{creator}, + + + #{deleteType}, + + + #{employeeId}, + + + #{id}, + + + #{taxAgentId}, + + + #{taxYearMonth}, + + + #{tenantKey}, + + + #{updateTime}, + + + #{year}, + + + + + + + UPDATE hrsa_add_up_situation + + add_up_accumulation_fund_total=#{addUpAccumulationFundTotal}, + add_up_advance_tax=#{addUpAdvanceTax}, + add_up_allowed_donation=#{addUpAllowedDonation}, + add_up_child_education=#{addUpChildEducation}, + add_up_continuing_education=#{addUpContinuingEducation}, + add_up_enterprise_and_other=#{addUpEnterpriseAndOther}, + add_up_housing_loan_interest=#{addUpHousingLoanInterest}, + add_up_housing_rent=#{addUpHousingRent}, + add_up_income=#{addUpIncome}, + add_up_other_deduction=#{addUpOtherDeduction}, + add_up_social_security_total=#{addUpSocialSecurityTotal}, + add_up_subtraction=#{addUpSubtraction}, + add_up_support_elderly=#{addUpSupportElderly}, + add_up_tax_exempt_income=#{addUpTaxExemptIncome}, + create_time=#{createTime}, + creator=#{creator}, + delete_type=#{deleteType}, + employee_id=#{employeeId}, + tax_agent_id=#{taxAgentId}, + tax_year_month=#{taxYearMonth}, + tenant_key=#{tenantKey}, + update_time=#{updateTime}, + year=#{year}, + + WHERE id = #{id} AND delete_type = 0 + + + + + + UPDATE hrsa_add_up_situation + + + add_up_accumulation_fund_total=#{addUpAccumulationFundTotal}, + + + add_up_advance_tax=#{addUpAdvanceTax}, + + + add_up_allowed_donation=#{addUpAllowedDonation}, + + + add_up_child_education=#{addUpChildEducation}, + + + add_up_continuing_education=#{addUpContinuingEducation}, + + + add_up_enterprise_and_other=#{addUpEnterpriseAndOther}, + + + add_up_housing_loan_interest=#{addUpHousingLoanInterest}, + + + add_up_housing_rent=#{addUpHousingRent}, + + + add_up_income=#{addUpIncome}, + + + add_up_other_deduction=#{addUpOtherDeduction}, + + + add_up_social_security_total=#{addUpSocialSecurityTotal}, + + + add_up_subtraction=#{addUpSubtraction}, + + + add_up_support_elderly=#{addUpSupportElderly}, + + + add_up_tax_exempt_income=#{addUpTaxExemptIncome}, + + + create_time=#{createTime}, + + + creator=#{creator}, + + + delete_type=#{deleteType}, + + + employee_id=#{employeeId}, + + + tax_agent_id=#{taxAgentId}, + + + tax_year_month=#{taxYearMonth}, + + + tenant_key=#{tenantKey}, + + + update_time=#{updateTime}, + + + year=#{year}, + + + WHERE id = #{id} AND delete_type = 0 + + + + + + UPDATE hrsa_add_up_situation + SET delete_type=1 + WHERE id = #{id} + AND delete_type = 0 + + + + \ No newline at end of file diff --git a/src/com/engine/salary/process/datacollection/CostImportProcess.java b/src/com/engine/salary/process/datacollection/CostImportProcess.java new file mode 100644 index 000000000..33c88d87f --- /dev/null +++ b/src/com/engine/salary/process/datacollection/CostImportProcess.java @@ -0,0 +1,452 @@ +package com.engine.salary.process.datacollection; + +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.personalIncomeTax.enums.VerificationTypeEnum; +import com.engine.personalIncomeTax.service.ImportLogService; +import com.engine.personalIncomeTax.service.impl.ImportLogServiceImpl; +import com.engine.personalIncomeTax.util.PITUtil; +import org.apache.poi.ss.usermodel.*; +import weaver.conn.RecordSet; +import weaver.file.FileManage; +import weaver.file.FileUploadToPath; +import weaver.file.ImageFileManager; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import javax.servlet.http.HttpServletRequest; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +public class CostImportProcess extends BaseBean { + public CostImportProcess(User user) { + this.user = user; + } + + private User user; + private String keyField; + private int keyFieldIndex = 0; + private String excelfile; + private Sheet sheet; + private Map error = null; + private List> errorInfo = new ArrayList<>(); + + //标准模板字段名称 + private List tempFieldLabel = new ArrayList<>(Arrays.asList(""+ SystemEnv.getHtmlLabelName(714,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(413,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(16126,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005512,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005513,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(25043,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005514,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005515,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005516,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005517,weaver.general.ThreadVarLanguage.getLang())+"", ""+ SystemEnv.getHtmlLabelName(10005518,weaver.general.ThreadVarLanguage.getLang())+"")); + private List tempField = new ArrayList<>(Arrays.asList("workcode", "lastname", "loginid", "verificationType", "verificationId", "month", "childEdu", "loan", "rent", "supportParent", "edu")); + //必填列 + private List requireField = new ArrayList<>(Arrays.asList("month")); + //列序号 + private List fieldIndex = new ArrayList<>(); + + //需要导入的数据 + private List> datas = new ArrayList<>(); + + int processId = 0; + + /** + * map集合创建类 + * + * @param fu 上传参数 + * @return List + */ + public List creatImportMap(FileUploadToPath fu) { + try { + // 初始化数据 + initDataSource(fu); + + // 模板验证 + valExcelTemp(); + + // 读取数据并验证 + readExcel(); + + } catch (NegativeArraySizeException ex) { + deleteFile(); + errorInfo.add(generateErrMsg("Excel"+ SystemEnv.getHtmlLabelName(10003739,weaver.general.ThreadVarLanguage.getLang())+""));//目前尚不清楚,这种异常的产生原因 + writeLog(ex); + } catch (Exception e) { + deleteFile(); + e.printStackTrace(); + errorInfo.add(generateErrMsg("Excel"+ SystemEnv.getHtmlLabelName(10003740,weaver.general.ThreadVarLanguage.getLang())+""));//Excel"+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003740,weaver.general.ThreadVarLanguage.getLang())+" + writeLog(e); + } + + return errorInfo; + } + + private Map generateErrMsg(String msg){ + error = new HashMap(); + error.put("message",msg); + return error; + } + + /** + * 删除文件 + */ + private void deleteFile() { + try { + FileManage.DeleteFile(excelfile); + } catch (Exception ex) { + writeLog(ex); + } + } + + /** + * 获取上传文件,初始化参数 + * + * @param fu + * @return + */ + private void initDataSource(FileUploadToPath fu) throws Exception { + keyField = fu.getParameter("keyField"); + keyFieldIndex = tempField.indexOf(keyField); + excelfile = fu.getParameter("excelfile"); + + requireField.add(keyField); + + try { + ImageFileManager manager = new ImageFileManager(); + manager.getImageFileInfoById(Util.getIntValue(excelfile)); + Workbook workbook = WorkbookFactory.create(manager.getInputStream()); + sheet = workbook.getSheetAt(0); + } catch (FileNotFoundException e) { + } catch (IOException e) { + errorInfo.add(generateErrMsg(SystemEnv.getHtmlLabelName(83618, user.getLanguage()))); //上传文件不是excel文件 + writeLog(e); + throw e; + } catch (IndexOutOfBoundsException e) { + errorInfo.add(generateErrMsg(""+ SystemEnv.getHtmlLabelName(10003741,weaver.general.ThreadVarLanguage.getLang())+"1"+ SystemEnv.getHtmlLabelName(27591,weaver.general.ThreadVarLanguage.getLang())+"sheet"+ SystemEnv.getHtmlLabelName(10005519,weaver.general.ThreadVarLanguage.getLang())+"")); + writeLog(e); + throw e; + } + } + + /** + * 验证模板格式 + * + * @return + */ + private void valExcelTemp() throws Exception { + Row row; + Cell cell; + String cellValue; + Boolean flag; + + try { + row = sheet.getRow(0); + for (int i = 0; i < row.getLastCellNum(); i++) { + cell = row.getCell(i); + + if (cell == null) + continue; + + cellValue = getCellValue(cell); + flag = tempFieldLabel.contains(cellValue); + if (!flag) + errorInfo.add(generateErrMsg(getCellPosition(i, 1) + "[" + cellValue + "]" + " "+ SystemEnv.getHtmlLabelName(10003743,weaver.general.ThreadVarLanguage.getLang())+"")); //不是模板中字段,请检查是否有误 + else + fieldIndex.add(tempFieldLabel.indexOf(cellValue)); + } + } catch (IllegalArgumentException ex) { + errorInfo.add(generateErrMsg("Excel"+ SystemEnv.getHtmlLabelName(10005520,weaver.general.ThreadVarLanguage.getLang())+"")); + writeLog(ex); + throw ex; + } catch (Exception ex) { + errorInfo.add(generateErrMsg("Excel"+ SystemEnv.getHtmlLabelName(10005520,weaver.general.ThreadVarLanguage.getLang())+"")); + writeLog(ex); + throw ex; + } + } + + /** + * 读取excel数据 + * + * @return + */ + private void readExcel() throws Exception { + Row row; + Cell cell; + String cellValue; + + try { + for (int i = 1; i <= sheet.getLastRowNum(); i++) { + row = sheet.getRow(i); + + if (row == null) + continue; + + Map data = new HashMap<>(); + + for (int j = 0; j < row.getLastCellNum(); j++) { + cell = row.getCell(j); + String fieldlable = tempFieldLabel.get(fieldIndex.get(j)); + String fieldname = tempField.get(fieldIndex.get(j)); + if (cell == null && requireField.contains(fieldname)){ + errorInfo.add(generateErrMsg(getCellPosition(j, i + 1) + "[" + fieldlable + "]" + " "+ SystemEnv.getHtmlLabelName(18019,weaver.general.ThreadVarLanguage.getLang())+"")); + break; + } + if(cell == null) + continue; + + cellValue = getCellValue(cell); + if ("".equals(cellValue) && requireField.contains(fieldname)){ + errorInfo.add(generateErrMsg(getCellPosition(j, i + 1) + "[" + fieldlable + "]" + " "+ SystemEnv.getHtmlLabelName(18019,weaver.general.ThreadVarLanguage.getLang())+"")); + break; + } + + data.put(tempField.get(fieldIndex.get(j)), cellValue); + } + + if (!data.isEmpty()){ + Integer resourceId = checkKeyField(data); + if(resourceId != null) + datas.add(data); + else + errorInfo.add(generateErrMsg(getCellPosition(keyFieldIndex, i + 1) + ""+ SystemEnv.getHtmlLabelName(512694,weaver.general.ThreadVarLanguage.getLang())+"")); + } + } + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + private Integer checkKeyField(Map data){ + Integer resourceId = null; + try{ + RecordSet rs = new RecordSet(); + String keyFieldValue = Util.null2String(data.get(keyField)); + String sql = ""; + if(keyField.equals("verificationId")){ + String verificationType = Util.null2String(data.get("verificationType")); + String type = getVerificationType(verificationType); + if("".equals(type) || "1".equals(type)){ + sql = "select id, lastname from hrmresource where certificatenum = ?"; + rs.executeQuery(sql, keyFieldValue); + }else { + sql = "select r.id, r.lastname from hrmresource r, HRM_PIT_BASICINFO i where r.id = i.id and i.verificationtype = ? and i.verificationid = ?"; + rs.executeQuery(sql, type, keyFieldValue); + } + writeLog("type:"+type+", sql:"+sql); + }else{ + sql = "select id, lastname from hrmresource where " + keyField + " = ?"; + rs.executeQuery(sql, keyFieldValue); + } + while(rs.next()){ + resourceId = rs.getInt("id"); + data.put("pid", resourceId); + data.put("lastname", Util.null2String(rs.getString("lastname"))); + } + }catch (Exception ex){ + writeLog(ex); + } + return resourceId; + } + + private String getVerificationType(String verificationType){ + String type = ""; + for (VerificationTypeEnum vt : VerificationTypeEnum.values()) { + if("".equals(vt.getName())) + continue; + if(SystemEnv.getHtmlLabelName(Integer.valueOf(vt.getName()), 7).equals(verificationType)) + type = vt.getValue(); + } + return type; + } + + /** + * 导入数据到数据库 + * + * @return + */ + public void processMap() { + ImportLogService importLogService = (ImportLogService) ServiceUtil.getService(ImportLogServiceImpl.class, this.user); + try { + RecordSet rs = new RecordSet(); + boolean flag = false; + String sql = ""; + int i = 0; + for (Map data : datas) { + int pid = Util.getIntValue(String.valueOf(data.get("pid"))); + String lastname = Util.null2String(data.get("lastname")); + String id = ""; + sql = "select id from hrm_pit_tax where pid = ? and month = ?"; + rs.executeQuery(sql, pid, data.get("month")); + if(rs.next()){ + //update + id = rs.getString("id"); + sql = "update hrm_pit_tax set childEdu = ?, edu = ?, loan = ?, rent = ?, supportParent = ? where id = ?"; + flag = executeSql(sql, new Object[]{data.get("childEdu"), data.get("edu"), data.get("loan"), data.get("rent"), data.get("supportParent"), id}); + }else{ + //create + id = PITUtil.getInstance().getUnquieID(); + sql = "insert into hrm_pit_tax(id, pid, month, childEdu, edu, loan, rent, supportParent) values(?,?,?,?,?,?,?,?)"; + flag = executeSql(sql, new Object[]{id, pid, data.get("month"), data.get("childEdu"), data.get("edu"), data.get("loan"), data.get("rent"), data.get("supportParent")}); + } + + if (flag) { + Map params = new HashMap(); + params.put("pId", processId); + params.put("lineNum", (i + 1)); + params.put("relatedName", lastname); + params.put("msg", ""+ SystemEnv.getHtmlLabelName(15323,weaver.general.ThreadVarLanguage.getLang())+"" + (i + 1) + ""+ SystemEnv.getHtmlLabelName(10003745,weaver.general.ThreadVarLanguage.getLang())+"" + ","+ SystemEnv.getHtmlLabelName(25750,weaver.general.ThreadVarLanguage.getLang())+"!"); + params.put("status", "1"); + params.put("logSmallType", BizLogSmallType4Hrm.HRM_ENGINE_TAX_COST_IMPORT.getCode()); + importLogService.saveImportDeitalLog(params, user); + } else { + Map params = new HashMap(); + params.put("pId", processId); + params.put("lineNum", (i + 1)); + params.put("relatedName", lastname); + params.put("msg", ""+ SystemEnv.getHtmlLabelName(15323,weaver.general.ThreadVarLanguage.getLang())+"" + (i + 1) + ""+ SystemEnv.getHtmlLabelName(10003745,weaver.general.ThreadVarLanguage.getLang())+"" + ","+ SystemEnv.getHtmlLabelName(24945,weaver.general.ThreadVarLanguage.getLang())+"!"); + params.put("status", "0"); + params.put("logSmallType", BizLogSmallType4Hrm.HRM_ENGINE_TAX_COST_IMPORT.getCode()); + importLogService.saveImportDeitalLog(params, user); + } + + i++; + } + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + writeLog(e); + } + } + + /** + * 获取excel单元格值 + * + * @param cell 要读取的单元格对象 + * @return + */ + private String getCellValue(Cell cell) { + String cellValue = ""; + if (cell == null) + return ""; + switch (cell.getCellType()) { + case BOOLEAN://得到Boolean对象的方法 + cellValue = Util.null2String(cell.getBooleanCellValue()); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) {//先看是否是日期格式 + SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM"); + cellValue = sft.format(cell.getDateCellValue()); //读取日期格式 + } else { + cellValue = Util.null2String(new Double(cell.getNumericCellValue())); //读取数字 + if (cellValue.endsWith(".0")) + cellValue = cellValue.substring(0, cellValue.indexOf(".")); + } + break; + case STRING://读取String + cellValue = Util.null2String(cell.getStringCellValue()); + Date d = validDate(cellValue); + if (d != null) + cellValue = new SimpleDateFormat("yyyy-MM-dd").format(d); + break; + } + + return cellValue.trim(); + } + + /** + * excel单元格位置转换 + * + * @param cellIndex 列号 + * @param rowNum 行号 + * @return + */ + private String getCellPosition(int cellIndex, int rowNum) { + + int count = cellIndex / 26; + String cellChar = String.valueOf((char) (cellIndex % 26 + 65)); + String cellPosition = ""; + + if (count != 0) + cellPosition = String.valueOf((char) ((count - 1) + 65)) + cellChar; + else + cellPosition = cellChar; + cellPosition += rowNum; + return cellPosition; + } + + /** + * 验证单元格内容是否为日期 + * + * @param str + * @return + */ + private Date validDate(String str) { + Date d = null; + SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd"); + fmt1.setLenient(false); + SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy/MM/dd"); + fmt2.setLenient(false); + try { + d = fmt1.parse(str); + } catch (Exception e) { + } + try { + d = fmt2.parse(str); + } catch (Exception e) { + + } + return d; + } + + /** + * 设置session属性,匹配监控进程 + * @param request + * @return + */ + public Map init(HttpServletRequest request){ + Map retmap = new HashMap(); + try { + ImportLogService importLogService = (ImportLogService) ServiceUtil.getService(ImportLogServiceImpl.class, user); + Map params = ParamUtil.request2Map(request); + retmap = importLogService.saveImportLog(params, request, user); + if(Util.null2String(retmap.get("status")).equals("1")){ + String importType = "tax"; + processId = Util.getIntValue(Util.null2String(retmap.get("pId"))); + String processName = "hrm"+importType+"PId";; + request.getSession(true).setAttribute(processName, processId); + } + } catch(Exception e) { + writeLog(e) ; + } + return retmap; + } + + /** + * 导入结束后更新日志状态,写入over状态,前端就不再轮询日志 + * @param request + */ + public void over(HttpServletRequest request){ + try { + ImportLogService importLogService = (ImportLogServiceImpl) ServiceUtil.getService(ImportLogServiceImpl.class, user); + Map params = new HashMap(); + params.put("pId", processId); + params.put("status", "over"); + importLogService.saveImportLogStatus(params, user); + + deleteFile(); + } catch(Exception e) { + writeLog(e) ; + } + } + + private boolean executeSql(String sql, Object[] params){ + boolean flag = false; + try{ + flag = new RecordSet().executeUpdate(sql, params); + }catch (Exception ex){ + writeLog(ex); + } + return flag; + } +} diff --git a/src/com/engine/salary/process/datacollection/ExportDeclareRecordsProcess.java b/src/com/engine/salary/process/datacollection/ExportDeclareRecordsProcess.java new file mode 100644 index 000000000..6c13c5522 --- /dev/null +++ b/src/com/engine/salary/process/datacollection/ExportDeclareRecordsProcess.java @@ -0,0 +1,751 @@ +package com.engine.salary.process.datacollection; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.personalIncomeTax.biz.RecordsBiz; +import com.engine.personalIncomeTax.enums.FormTypeEnum; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ExportDeclareRecordsProcess extends BaseBean { + private User user; + private Map params; + + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + private SimpleDateFormat sdfFull = new SimpleDateFormat("yyyyMMddHHmmss"); + + + //模板文件路径 + private String templateFilePath = GCONST.getRootPath() + "hrm/resource/inputexcellfile/taxDeclareTemplate.xls"; + //导出文件路径 + private String outFolder = "hrm/resource/taxTmp/"; + private String outputFolderPath = GCONST.getRootPath() + outFolder; + private List outputFiles = new ArrayList<>(); + + private List> datas = new ArrayList(); + private List errorInfo = new ArrayList(); + + //exceldatas + private HSSFWorkbook workbook; + private HSSFSheet sheet; + private HSSFRow row; + private HSSFCell cell; + + public List getDatas() { + return this.datas; + } + + public void setDatas(List datas) { + this.datas = datas; + } + + public ExportDeclareRecordsProcess(User user, Map params) { + this.user = user; + this.params = params; + } + + public ExportDeclareRecordsProcess() { + + } + + public List getOutputFiles() { + return this.outputFiles; + } + + public void setOutputFiles(List outputFiles) { + this.outputFiles = outputFiles; + } + + public List init() throws Exception { + try { + //验证模板文件是否存在,并创建导出目录 + checkFile(); + + //查询数据 + queryData(); + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + return errorInfo; + } + + /** + * 验证模板文件是否存在,并创建导出目录 + * + * @throws Exception + */ + private void checkFile() throws Exception { + try { + File templateFile = new File(templateFilePath); + if (templateFile.exists()) { + File outputFolder = new File(outputFolderPath); + if (!outputFolder.exists()) + outputFolder.mkdirs(); + else { + deleteDir(outputFolder); + outputFolder.mkdirs(); + } + } else { + errorInfo.add(""+ SystemEnv.getHtmlLabelName(10005521,weaver.general.ThreadVarLanguage.getLang())+""); + } + } catch (Exception ex) { + writeLog(ex); + errorInfo.add(""+ SystemEnv.getHtmlLabelName(10005522,weaver.general.ThreadVarLanguage.getLang())+""); + throw ex; + } + } + + private boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; + } + } + } + // 目录此时为空,可以删除 + return dir.delete(); + } + + /** + * 查询需要导出的数据 + * + * @throws Exception + */ + private void queryData() throws Exception { + try { + String data = Util.null2String(params.get("data")); + JSONArray conditions = JSON.parseArray(data); + for (int i = 0; i < conditions.size(); i++) { + JSONObject condition = (JSONObject) conditions.get(i); + int pid = Util.getIntValue(Util.null2String(condition.get("pid"))); + String year = Util.null2String(condition.get("year")); + + Map importExcelData = new HashMap<>(); + importExcelData.put("year", year); + + //basic info + Map basicInfo = RecordsBiz.getInstance().queryBasicInfo(pid); + if ((boolean) basicInfo.get("requireVerificationId")) { + errorInfo.add("" + basicInfo.get("lastname") + SystemEnv.getHtmlLabelName(506777, user.getLanguage())); + continue; + } + importExcelData.put("basicInfo", basicInfo); + + //查询用户填报了那些类型的数据,未填写的不执行查询填报信息内容查询的函数 + List catalogues = RecordsBiz.getInstance().queryRecordCatalogues(pid, year); + + //child edu info + if (catalogues.contains(FormTypeEnum.CHILD_EDU.getValue())) { + Map childEduInfo = RecordsBiz.getInstance().queryChildEduInfo(pid, year); + importExcelData.put("childEduInfo", childEduInfo); + } + + //edu info + if (catalogues.contains(FormTypeEnum.EDU.getValue())) { + Map eduInfo = RecordsBiz.getInstance().queryEduInfo(pid, year); + importExcelData.put("eduInfo", eduInfo); + } + + //loan info + if (catalogues.contains(FormTypeEnum.LOAN.getValue())) { + Map loanInfo = RecordsBiz.getInstance().queryLoanInfo(pid, year); + importExcelData.put("loanInfo", loanInfo); + } + + //rent info + if (catalogues.contains(FormTypeEnum.RENT.getValue())) { + Map rentInfo = RecordsBiz.getInstance().queryRentInfo(pid, year); + importExcelData.put("rentInfo", rentInfo); + } + + //support paent info + if (catalogues.contains(FormTypeEnum.SUPPORT_PARENT.getValue())) { + Map supportParentInfo = RecordsBiz.getInstance().querySupportParentInfo(pid, year); + importExcelData.put("supportParentInfo", supportParentInfo); + } + + datas.add(importExcelData); + } + } catch (Exception ex) { + writeLog(ex); + errorInfo.add(""+ SystemEnv.getHtmlLabelName(10005523,weaver.general.ThreadVarLanguage.getLang())+""); + throw ex; + } + } + + /** + * 导出excel + * + * @throws Exception + */ + public void doExport() throws Exception { + try { + for (Map data : datas) { + File f = new File(templateFilePath); + FileInputStream inputStream = new FileInputStream(f); + POIFSFileSystem fs = new POIFSFileSystem(inputStream); + workbook = new HSSFWorkbook(fs); + String year = (String) data.get("year"); + writeBasicInfo(year, (Map) data.get("basicInfo")); + if (data.containsKey("childEduInfo")) + writeChildEduInfo((Map) data.get("childEduInfo")); + if (data.containsKey("eduInfo")) + writeEduInfo((Map) data.get("eduInfo")); + if (data.containsKey("loanInfo")) + writeLoanInfo((Map) data.get("loanInfo")); + if (data.containsKey("rentInfo")) + writeRentInfo((Map) data.get("rentInfo")); + if (data.containsKey("supportParentInfo")) + writeSupportParentInfo((Map) data.get("supportParentInfo")); + + String fileName = Util.formatMultiLang(((Map) data.get("basicInfo")).get("lastname").toString(), "7") + "-" + year + "-"+ SystemEnv.getHtmlLabelName(10005524,weaver.general.ThreadVarLanguage.getLang())+""; + Base64.Encoder encoder = Base64.getUrlEncoder(); + fileName = encoder.encodeToString(fileName.getBytes("UTF-8")); + String outputFilePath = outputFolderPath + fileName + ".xls"; + FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); + workbook.write(outputStream); + outputStream.close(); + inputStream.close(); + workbook.close(); + outputFiles.add(fileName + ".xls"); + } + } catch (Exception ex) { + writeLog(ex); + throw ex; + } finally { + } + } + + public void downloadFile(HttpServletRequest request, HttpServletResponse response, String f) throws Exception { + try{ + String path = outputFolderPath + f; + // path是指欲下载的文件的路径。 + File file = new File(path); + // 取得文件名。 + String filename = file.getName(); + String fname = filename.substring(0, filename.lastIndexOf(".")); + Base64.Decoder decoder = Base64.getUrlDecoder(); + fname = new String(decoder.decode(fname), "UTF-8"); + // 取得文件的后缀名。 + String ext = filename.substring(filename.lastIndexOf(".")); + + String name = fname + ext; + + // 以流的形式下载文件。 + InputStream fis = new BufferedInputStream(new FileInputStream(path)); + byte[] buffer = new byte[fis.available()]; + fis.read(buffer); + fis.close(); + + String agent = request.getHeader("User-Agent"); + if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ + response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(name.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + }else{ + response.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(name.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + } + ServletOutputStream out = response.getOutputStream(); + response.setContentType("application/vnd.ms-excel;charset=ISO-8859-1"); + response.setHeader("Content-Length",String.valueOf(file.length())); + //解决某些操作系统环境下载打不开的问题 + out.write(buffer); + + out.flush(); + out.close(); + }catch (Exception ex){ + writeLog(ex); + throw ex; + } + } + + /** + * 写入首页sheet数据 + * + * @param year + * @param data + * @throws Exception + */ + private void writeBasicInfo(String year, Map data) throws Exception { + try { + sheet = workbook.getSheetAt(1); + sheet.setForceFormulaRecalculation(true); + + for (int i = 0; i < 7; i++) { + row = sheet.getRow(i); + switch (i) { + case 0: + cell = row.getCell(3); + cell.setCellValue(year); + cell = row.getCell(9); + cell.setCellValue((String) data.get("lastname")); + break; + case 1: + cell = row.getCell(3); + cell.setCellValue((String) data.get("verificationType")); + cell = row.getCell(9); + cell.setCellValue((String) data.get("verificationId")); + break; + case 2: + cell = row.getCell(3); + cell.setCellValue((String) data.get("mobile")); + cell = row.getCell(9); + cell.setCellValue((String) data.get("nsrsbh")); + break; + case 3: + cell = row.getCell(3); + cell.setCellValue((String) data.get("address")); + cell = row.getCell(9); + cell.setCellValue((String) data.get("email")); + break; + case 5: + cell = row.getCell(3); + cell.setCellValue((String) data.get("hasSpouse")); + cell = row.getCell(9); + cell.setCellValue((String) data.get("spouseLastname")); + break; + case 6: + cell = row.getCell(3); + cell.setCellValue((String) data.get("spouseVerificationType")); + cell = row.getCell(9); + cell.setCellValue((String) data.get("spouseVerificationId")); + break; + } + } + + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + /** + * 写入子女教育支出sheet数据 + * + * @param data + * @throws Exception + */ + private void writeChildEduInfo(Map data) throws Exception { + try { + sheet = workbook.getSheetAt(2); + sheet.setForceFormulaRecalculation(true); + + int i = 0; + int rowId = 2; + String percent = (String) data.get("percent"); + List> children = (List>) data.get("children"); + for (Map child : children) { + String lastname = (String) child.get("lastname"); + String relationship = (String) child.get("relationship"); + String verificationType = (String) child.get("verificationType"); + String verificationId = (String) child.get("verificationId"); + String birthday = (String) child.get("birthday"); + String nationality = (String) child.get("nationality"); + String eduLevel = (String) child.get("eduLevel"); + String startDate = (String) child.get("startDate"); + String endDate = (String) child.get("endDate"); + String stopDate = (String) child.get("stopDate"); + String eduNationality = (String) child.get("eduNationality"); + String school = (String) child.get("school"); + + int rIdx = rowId + i; + if (i > 7) { + row = sheet.createRow(rIdx); + row.createCell(0).setCellValue(i + 1); + row.createCell(1).setCellValue(relationship); + row.createCell(2).setCellValue(lastname); + row.createCell(3).setCellValue(verificationType); + row.createCell(4).setCellValue(verificationId); + row.createCell(5).setCellValue(birthday); + row.createCell(6).setCellValue(nationality); + row.createCell(7).setCellValue(eduLevel); + row.createCell(8).setCellValue(startDate); + row.createCell(9).setCellValue(endDate); + row.createCell(10).setCellValue(stopDate); + row.createCell(11).setCellValue(eduNationality); + row.createCell(12).setCellValue(school); + row.createCell(13).setCellValue(percent); + } else { + row = sheet.getRow(rIdx); + row.getCell(1).setCellValue(relationship); + row.getCell(2).setCellValue(lastname); + row.getCell(3).setCellValue(verificationType); + row.getCell(4).setCellValue(verificationId); + row.getCell(5).setCellFormula(null); + row.getCell(5).setCellValue(birthday); + row.getCell(6).setCellValue(nationality); + row.getCell(7).setCellValue(eduLevel); + row.getCell(8).setCellFormula(null); + row.getCell(8).setCellValue(startDate); + row.getCell(9).setCellValue(endDate); + row.getCell(10).setCellValue(stopDate); + row.getCell(11).setCellValue(eduNationality); + row.getCell(12).setCellValue(school); + row.getCell(13).setCellValue(percent); + } + i++; + } + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + /** + * 写入继续教育sheet数据 + * + * @param data + * @throws Exception + */ + private void writeEduInfo(Map data) throws Exception { + try { + sheet = workbook.getSheetAt(6); + sheet.setForceFormulaRecalculation(true); + + int rowId1 = 3; + int rowId2 = 9; + + List>> edus = (List>>) data.get("edus"); + List> l1 = edus.get(0); + List> l2 = edus.get(1); + if (l1.size() > 0) { + int i = 0; + for (Map edu : l1) { + int rIdx = i + rowId1; + String eduLevel = (String) edu.get("eduLevel"); + String startDate = (String) edu.get("startDate"); + String endDate = (String) edu.get("endDate"); + + if (i > 3) { + row = sheet.createRow(rIdx); + row.createCell(0).setCellValue(i + 1); + row.createCell(1).setCellValue(startDate); + row.createCell(2).setCellValue(endDate); + row.createCell(3).setCellValue(eduLevel); + } else { + row = sheet.getRow(rIdx); + row.getCell(1).setCellValue(startDate); + row.getCell(2).setCellValue(endDate); + row.getCell(3).setCellValue(eduLevel); + } + i++; + } + } + if (l2.size() > 0) { + int i = 0; + if (l1.size() > 4) + rowId2 += l1.size() - 4; + for (Map edu : l2) { + int rIdx = i + rowId2; + String devType = (String) edu.get("devType"); + String issueDate = (String) edu.get("issueDate"); + String certificateName = (String) edu.get("certificateName"); + String certificateNum = (String) edu.get("certificateNum"); + String issueUnit = (String) edu.get("issueUnit"); + + if (i > 3) { + row = sheet.createRow(rIdx); + row.createCell(0).setCellValue(i + 1); + row.createCell(1).setCellValue(devType); + row.createCell(2).setCellValue(issueDate); + row.createCell(3).setCellValue(certificateName); + row.createCell(4).setCellValue(certificateNum); + row.createCell(5).setCellValue(issueUnit); + } else { + row = sheet.getRow(rIdx); + row.getCell(1).setCellValue(devType); + row.getCell(2).setCellValue(issueDate); + row.getCell(3).setCellValue(certificateName); + row.getCell(4).setCellValue(certificateNum); + row.getCell(5).setCellValue(issueUnit); + } + i++; + } + } + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + /** + * 写入住房贷款sheet数据 + * + * @param data + * @throws Exception + */ + private void writeLoanInfo(Map data) throws Exception { + try { + String address = (String) data.get("address"); + String borrower = (String) data.get("borrower"); + String securities = (String) data.get("securities"); + String certificateNum = (String) data.get("certificateNum"); + String beforeMarriage = (String) data.get("beforeMarriage"); + + sheet = workbook.getSheetAt(4); + sheet.setForceFormulaRecalculation(true); + + row = sheet.getRow(1); + row.getCell(2).setCellValue(address); + row = sheet.getRow(2); + row.getCell(1).setCellValue(borrower); + row.getCell(3).setCellValue(securities); + row.getCell(5).setCellValue(certificateNum); + row.getCell(7).setCellValue(beforeMarriage); + + List> loans = (List>) data.get("loans"); + int rowId = 4; + for (Map loan : loans) { + row = sheet.getRow(rowId); + row.getCell(1).setCellValue((String) loan.get("loanMode")); + row.getCell(3).setCellValue((String) loan.get("bank")); + row.getCell(4).setCellValue((String) loan.get("contractNum")); + row.getCell(5).setCellValue((String) loan.get("repayment")); + row.getCell(7).setCellValue((String) loan.get("loanMonth")); + rowId++; + } + + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + /** + * 写入住房租金sheet数据 + * + * @param data + * @throws Exception + */ + private void writeRentInfo(Map data) throws Exception { + try { + String province = Util.null2String(data.get("province")); + String station = (String) data.get("station"); + String rentType = (String) data.get("rentType"); + String lastname = (String) data.get("lastname"); + String orgName = Util.null2String(data.get("orgName")); + String verificationType = (String) data.get("verificationType"); + String verificationId = (String) data.get("verificationId"); + String creditCode = (String) data.get("creditCode"); + String address = (String) data.get("address"); + String contractNum = (String) data.get("contractNum"); + String startDate = (String) data.get("startDate"); + String endDate = (String) data.get("endDate"); + + sheet = workbook.getSheetAt(3); + sheet.setForceFormulaRecalculation(true); + + row = sheet.getRow(3); + row.getCell(1).setCellValue(province); + row.getCell(2).setCellValue(station); + row.getCell(3).setCellValue(rentType); + if (rentType.equals("自然人")) { + row.getCell(4).setCellValue(lastname); + row.getCell(5).setCellValue(verificationType); + row.getCell(6).setCellValue(verificationId); + } else { + row.getCell(4).setCellValue(orgName); + row.getCell(6).setCellValue(creditCode); + } + row.getCell(7).setCellValue(address); + row.getCell(8).setCellValue(contractNum); + row.getCell(9).setCellValue(startDate); + row.getCell(10).setCellValue(endDate); + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + /** + * 写入赡养父母sheet数据 + * + * @param data + * @throws Exception + */ + private void writeSupportParentInfo(Map data) throws Exception { + try { + sheet = workbook.getSheetAt(5); + sheet.setForceFormulaRecalculation(true); + + String cost = (String) data.get("cost"); + String costType = (String) data.get("costType"); + String onlyChild = (String) data.get("onlyChild"); + + List> parents = (List>) data.get("parents"); + List> supports = (List>) data.get("supports"); + + row = sheet.getRow(1); + row.getCell(2).setCellValue(onlyChild); + row.getCell(4).setCellValue(costType); + if(onlyChild.equals("否")){ + row.getCell(6).setCellFormula(null); + row.getCell(6).setCellValue(cost); + } + + int rowId1 = 4; + int rowId2 = 10; + int i = 0; + for (Map parent : parents) { + int rIdx = rowId1 + i; + + String lastname = (String) parent.get("lastname"); + String verificationType = (String) parent.get("verificationType"); + String verificationId = (String) parent.get("verificationId"); + String nationality = (String) parent.get("nationality"); + String relationship = (String) parent.get("relationship"); + String birthday = (String) parent.get("birthday"); + + if (i > 3) { + row = sheet.createRow(rIdx); + row.createCell(0).setCellValue(i + 1); + row.createCell(1).setCellValue(lastname); + row.createCell(2).setCellValue(verificationType); + row.createCell(3).setCellValue(verificationId); + row.createCell(4).setCellValue(nationality); + row.createCell(5).setCellValue(relationship); + row.createCell(6).setCellValue(birthday); + } else { + row = sheet.getRow(rIdx); + row.getCell(1).setCellValue(lastname); + row.getCell(2).setCellValue(verificationType); + row.getCell(3).setCellValue(verificationId); + row.getCell(4).setCellFormula(null); + row.getCell(4).setCellValue(nationality); + row.getCell(5).setCellValue(relationship); + row.getCell(6).setCellFormula(null); + row.getCell(6).setCellValue(birthday); + } + i++; + } + if(onlyChild.equals("否")){ + i = 0; + for (Map support : supports) { + int rIdx = rowId2 + i; + + String lastname = (String) support.get("lastname"); + String verificationType = (String) support.get("verificationType"); + String verificationId = (String) support.get("verificationId"); + String nationality = (String) support.get("nationality"); + + if (i > 3) { + row = sheet.createRow(rIdx); + row.createCell(0).setCellValue(i + 1); + row.createCell(1).setCellValue(lastname); + row.createCell(2).setCellValue(verificationType); + row.createCell(3).setCellValue(verificationId); + row.createCell(4).setCellValue(nationality); + } else { + row = sheet.getRow(rIdx); + row.getCell(1).setCellValue(lastname); + row.getCell(2).setCellValue(verificationType); + row.getCell(3).setCellValue(verificationId); + row.getCell(4).setCellFormula(null); + row.getCell(4).setCellValue(nationality); + } + i++; + } + } + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + public String zipFile() throws Exception { + String fileName = ""+ SystemEnv.getHtmlLabelName(10005524,weaver.general.ThreadVarLanguage.getLang())+"-" + sdfFull.format(Calendar.getInstance().getTime()); + Base64.Encoder encoder = Base64.getUrlEncoder(); + fileName = encoder.encodeToString(fileName.getBytes("UTF-8")); + String filePath = outputFolderPath + fileName + ".zip"; + File zipFile = new File(filePath); + try { + List listKey = new ArrayList<>(); + for(String file : outputFiles){ + listKey.add(outputFolderPath + file); + } + packageZip(zipFile, listKey); + return fileName + ".zip"; + } catch (Exception ex) { + writeLog(ex); + throw ex; + } + } + + private boolean packageZip(File zipFile,List listKey){ + //图片打包操作 + ZipOutputStream zipStream = null; + FileInputStream zipSource = null; + BufferedInputStream bufferStream = null; + try { + zipStream = new ZipOutputStream(new FileOutputStream(zipFile));// 用这个构造最终压缩包的输出流 +// zipSource = null;// 将源头文件格式化为输入流 + + for (String picKey : listKey) { + + File file = new File(picKey); + zipSource = new FileInputStream(file); + + byte[] bufferArea = new byte[1024 * 10];// 读写缓冲区 + + // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样 + String fileName = file.getName(); + // 取得文件的后缀名。 + String ext = fileName.substring(fileName.lastIndexOf(".")); + fileName = fileName.substring(0, fileName.lastIndexOf(".")); + Base64.Decoder decoder = Base64.getUrlDecoder(); + fileName = new String(decoder.decode(fileName), "utf-8"); + ZipEntry zipEntry = new ZipEntry(fileName + ext); + zipStream.putNextEntry(zipEntry);// 定位到该压缩条目位置,开始写入文件到压缩包中 + + bufferStream = new BufferedInputStream(zipSource, 1024 * 10);// 输入缓冲流 + int read = 0; + + // 在任何情况下,b[0] 到 b[off] 的元素以及 b[off+len] 到 b[b.length-1] + // 的元素都不会受到影响。这个是官方API给出的read方法说明,经典! + while ((read = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) { + zipStream.write(bufferArea, 0, read); + } + } + } catch (Exception e) { + // TODO: handle exception + return false; + } finally { + // 关闭流 + try { + if (null != bufferStream) + bufferStream.close(); + if (null != zipStream) + zipStream.close(); + if (null != zipSource) + zipSource.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + return false; + } + } + return true; + } +} diff --git a/src/com/engine/salary/service/AddUpDeductionService.java b/src/com/engine/salary/service/AddUpDeductionService.java new file mode 100644 index 000000000..13d4a3bb7 --- /dev/null +++ b/src/com/engine/salary/service/AddUpDeductionService.java @@ -0,0 +1,9 @@ +package com.engine.salary.service; + +import java.util.Map; + +public interface AddUpDeductionService { + + Map list(Map params); + +} diff --git a/src/com/engine/salary/service/impl/AddUpDeductionServiceImpl.java b/src/com/engine/salary/service/impl/AddUpDeductionServiceImpl.java new file mode 100644 index 000000000..171308975 --- /dev/null +++ b/src/com/engine/salary/service/impl/AddUpDeductionServiceImpl.java @@ -0,0 +1,15 @@ +package com.engine.salary.service.impl; + +import com.engine.core.impl.Service; +import com.engine.salary.cmd.datacollection.AddUpDeductionListCmd; +import com.engine.salary.service.AddUpDeductionService; + +import java.util.Map; + +public class AddUpDeductionServiceImpl extends Service implements AddUpDeductionService { + + @Override + public Map list(Map params) { + return commandExecutor.execute(new AddUpDeductionListCmd(params,user)); + } +} diff --git a/src/com/engine/salary/util/excel/BooleanEnum.java b/src/com/engine/salary/util/excel/BooleanEnum.java new file mode 100644 index 000000000..8c4438435 --- /dev/null +++ b/src/com/engine/salary/util/excel/BooleanEnum.java @@ -0,0 +1,41 @@ +package com.engine.salary.util.excel; + +public enum BooleanEnum { + + True0("是", Boolean.TRUE), + True1("Y", Boolean.TRUE), + True2("TRUE", Boolean.TRUE), + True3("1", Boolean.TRUE), + True4("YES", Boolean.TRUE), + True5("T", Boolean.TRUE), + False0("否", Boolean.FALSE), + False1("N", Boolean.FALSE), + False2("FALSE", Boolean.FALSE), + False3("0", Boolean.FALSE), + False4("NO", Boolean.FALSE), + False5("F", Boolean.FALSE); + + private String name; + private Boolean value; + + private BooleanEnum(String name, Boolean value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean getValue() { + return value; + } + + public void setValue(Boolean value) { + this.value = value; + } +} diff --git a/src/com/engine/salary/util/excel/ExcelParseException.java b/src/com/engine/salary/util/excel/ExcelParseException.java new file mode 100644 index 000000000..432347858 --- /dev/null +++ b/src/com/engine/salary/util/excel/ExcelParseException.java @@ -0,0 +1,36 @@ +package com.engine.salary.util.excel; +import org.apache.commons.lang3.exception.ContextedRuntimeException; + +public class ExcelParseException extends ContextedRuntimeException{ + + private static final long serialVersionUID = -8696742623977630854L; + + public ExcelParseException(String message) { + super(message); + this.msgCode = DEFAULT_CODE; + } + + public ExcelParseException(String message, Throwable cause) { + super(message, cause); + this.msgCode = DEFAULT_CODE; + } + + /** + * 默认异常编码 + */ + private static final String DEFAULT_CODE = "EXCP0000"; + + /** + * 异常编码 + */ + private String msgCode; + + public String getMsgCode() { + return msgCode; + } + + public void setMsgCode(String msgCode) { + this.msgCode = msgCode; + } + +} diff --git a/src/com/engine/salary/util/excel/ExcelParseHelper.java b/src/com/engine/salary/util/excel/ExcelParseHelper.java new file mode 100644 index 000000000..955df8869 --- /dev/null +++ b/src/com/engine/salary/util/excel/ExcelParseHelper.java @@ -0,0 +1,144 @@ +package com.engine.salary.util.excel; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; +import org.apache.commons.lang3.exception.ContextedRuntimeException; +import org.apache.poi.ss.usermodel.Sheet; +import org.springframework.web.multipart.MultipartFile; + +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Excel 解析工具类 + *

Copyright: Copyright (c) 2022

+ *

Company: 泛微软件

+ * + * @author qiantao + * @version 1.0 + **/ +public class ExcelParseHelper { + + //待校验的行号 + private static final int PARSE_EXCEL_ROW_VALID_CELL_INDEX = 0; + //字符开始下标 + private static final int CHARACTER_FIRST_INDEX = 0; + + /** + * 将 Excel 解析为 JavaBean 对象 + * + * @param file excel文件 + * @param clazz 解析bean的类 + * @param sheetIndex excel中第几个sheet,从0开始 + * @param rowIndex 从第几行开始解析,第一行是0 + * @param standardCellNum 模板验证,该sheet应有多少列 + * @return + */ + public static List parse(MultipartFile file, Class clazz, int sheetIndex, int rowIndex, int standardCellNum) { + List> result = parse(file, sheetIndex, rowIndex, standardCellNum); + List list = new ArrayList(); + for (List rowDatas : result) { + T t = setField(clazz, rowDatas); + list.add(t); + } + return list; + } + + /** + * 获取excel数据。 + * + * @param file 文件 + * @param sheetIndex 解析第几个sheet + * @param rowIndex 从第几行开始解析,第一行为 0,依次类推 + * @return 二维数据集合 + */ + private static List> parse(MultipartFile file, int sheetIndex, int rowIndex, int standardCellNum) { + Sheet sheet = ExcelSupport.parseFile(file, sheetIndex); + int rowCount = sheet.getPhysicalNumberOfRows(); // 总行数 + int cellCount = sheet.getRow(PARSE_EXCEL_ROW_VALID_CELL_INDEX).getPhysicalNumberOfCells(); // 总列数 + + Validate.isTrue(standardCellNum == cellCount, "Error in excel template! Page %s sheet should have %s column data, existing in %s column , please check the template!", sheetIndex, standardCellNum, cellCount); + + List> result = new ArrayList>(); + for (; rowIndex < rowCount; rowIndex++) { + List cellResult = new ArrayList(); + for (int j = 0; j < cellCount; j++) { + cellResult.add(ExcelSupport.getCellValue(sheet, rowIndex, j)); + } + result.add(cellResult); + } + return result; + } + + /** + * 为对象的每一个属性赋值 + * + * @param clazz + * @param rowDatas + * @param + * @return + */ + private static T setField(Class clazz, List rowDatas) { + try { + T obj = clazz.newInstance(); + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class); + if (excelProperty == null) { + continue; + } + int index = excelProperty.index(); + Object value = getFieldValue(field, rowDatas.get(index), excelProperty); + field.setAccessible(true); + field.set(obj, value); + } + return obj; + } catch (Exception e) { + throw new ExcelParseException(e.getMessage(), e); + } + } + + /** + * 获取javaBean属性值 + * + * @param field javaBean的对象属性 + * @param value excel中对应的值 + * @param excelProperty javaBean中解析excel注解,包含日期格式、错误提示信息 + * @return + */ + @SuppressWarnings("rawtypes") + private static Object getFieldValue(Field field, String value, ExcelProperty excelProperty) { + if (StringUtils.isEmpty(value)) { + return null; + } + Object val = null; + try { + Class typeClass = field.getType(); + if (typeClass == Integer.class) { + val = Integer.valueOf(value); + } else if (typeClass == Long.class) { + val = Long.valueOf(value); + } else if (typeClass == Float.class) { + val = Float.valueOf(value); + } else if (typeClass == Double.class) { + val = Double.valueOf(value); + } else if (typeClass == Date.class) { + val = ExcelSupport.getDate(value, excelProperty.format()); + } else if (typeClass == Short.class) { + val = Short.valueOf(value); + } else if (typeClass == Character.class) { + val = value.charAt(CHARACTER_FIRST_INDEX); + } else if (typeClass == BigDecimal.class) { + val = new BigDecimal(value); + } else { + val = value; + } + } catch (Exception e) { + throw new ContextedRuntimeException(excelProperty.msg(), e); + } + return val; + } +} diff --git a/src/com/engine/salary/util/excel/ExcelProperty.java b/src/com/engine/salary/util/excel/ExcelProperty.java new file mode 100644 index 000000000..e2dd66f3a --- /dev/null +++ b/src/com/engine/salary/util/excel/ExcelProperty.java @@ -0,0 +1,15 @@ +package com.engine.salary.util.excel; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ExcelProperty { + public int index(); // 指定 JavaBean 的属性对应 excel 的第几列 + public String format() default "yyyy-MM-dd"; // 当 JavaBean 的属性为 Date 类型时,指定 Date 的格式化模式 + public String msg() default "解析错误";//当因excel中数据格式错误而造成的解析异常时,提示的错误信息 +} diff --git a/src/com/engine/salary/util/excel/ExcelSupport.java b/src/com/engine/salary/util/excel/ExcelSupport.java new file mode 100644 index 000000000..bb3d243aa --- /dev/null +++ b/src/com/engine/salary/util/excel/ExcelSupport.java @@ -0,0 +1,111 @@ +package com.engine.salary.util.excel; + +import org.apache.commons.lang3.Validate; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import static org.apache.poi.ss.usermodel.CellType.*; + + +public class ExcelSupport { + + private static final String pattern = "yyyy-MM-dd HH:mm:ss"; + + //excel类型 + private static final String EXCEL_TYPE_XLSX = "xlsx"; + private static final String EXCEL_TYPE_XLS = "xls"; + + /** + * 解析文件,获取单个sheet + * + * @param file 文件 + * @param sheetIndex sheet下标,从0开始 + * @return sheet + */ + public static Sheet parseFile(MultipartFile file, int sheetIndex) { + Workbook workBook = null; + try (InputStream ins = file.getInputStream();) { + String fileName = file.getOriginalFilename(); + if (fileName.endsWith(EXCEL_TYPE_XLSX)) { + workBook = new XSSFWorkbook(ins); + } else if (fileName.endsWith(EXCEL_TYPE_XLS)) { + workBook = new HSSFWorkbook(ins); + } else { + throw new IllegalArgumentException("File format error! Only xlsx and xls types are supported"); + } + return workBook.getSheetAt(sheetIndex); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + /** + * 返回指定单元格的数据 + * + * @param sheet 指定sheet + * @param rowIndex 第几行,从0开始 + * @param cellIndex 第几列,从0开始 + * @return 值 + */ + public static String getCellValue(Sheet sheet, int rowIndex, int cellIndex) { + Validate.notNull(sheet.getRow(rowIndex), "Line %s is empty and cannot be resolved", rowIndex); + return getCellValue(sheet.getRow(rowIndex).getCell(cellIndex)); + } + + /** + * 格式化解析的数据 + */ + public static String getCellValue(Cell cell) { + String cellValue = ""; + if (cell != null) { + switch (cell.getCellType()) { + case NUMERIC: // 数值类型 + if (DateUtil.isCellDateFormatted(cell)) { + cellValue = getDateStr(cell.getDateCellValue(), pattern); + } else { + cell.setCellType(STRING); + cellValue = cell.getStringCellValue(); + } + break; + case STRING: // 字符串类型 + cellValue = cell.getStringCellValue(); + break; + case BOOLEAN: // 布尔类型 + cellValue = String.valueOf(cell.getBooleanCellValue()); + break; + case FORMULA: // 公式类型 + cellValue = String.valueOf(cell.getCellFormula()); + break; + case BLANK: // 空白类型 + cellValue = ""; + break; + case ERROR: + cellValue = ""; + break; + default: + cellValue = cell.toString().trim(); + break; + } + } + return cellValue.trim(); + } + + public static Date getDate(String dateStr, String pattern) { + try { + return new SimpleDateFormat(pattern).parse(dateStr); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + + private static String getDateStr(Date date, String pattern) { + return new SimpleDateFormat(pattern).format(date); + } +} diff --git a/src/com/engine/salary/web/AddUpDeductionController.java b/src/com/engine/salary/web/AddUpDeductionController.java index 8a1df57ff..c6b9b06ce 100644 --- a/src/com/engine/salary/web/AddUpDeductionController.java +++ b/src/com/engine/salary/web/AddUpDeductionController.java @@ -1,4 +1,64 @@ package com.engine.salary.web; +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam; +import com.engine.salary.service.AddUpDeductionService; +import com.engine.salary.service.impl.AddUpDeductionServiceImpl; +import com.engine.salary.util.ResponseResult; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + public class AddUpDeductionController { + + private AddUpDeductionService getService(User user) { + return (AddUpDeductionService) ServiceUtil.getService(AddUpDeductionServiceImpl.class, user); + } + + @POST + @Path("/list") + @Produces(MediaType.APPLICATION_JSON) + public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionQueryParam queryParam) { + User user = HrmUserVarify.getUser(request, response); + Map map = ParamUtil.request2Map(request); + map.put("queryParam", queryParam); + return ResponseResult.run(getService(user)::list, map); + } + + +// /** +// * 下载导入模板 +// * @return +// */ +// @POST() +// @Path("/downloadTemplate") +// @ApiOperation("下载导入模板") +// @WeaPermission +// public WeaResult> downloadTemplate(@RequestBody AddUpDeductionQueryParam queryParam) { +// return WeaResult.success(service.downloadTemplate(queryParam, UserContext.getCurrentEmployeeId(), TenantContext.getCurrentTenantKey())); +// } + + + /** + * 导出 + * @param queryParam + * @return + */ +// @POST +// @Path("/export") +// @Produces(MediaType.APPLICATION_JSON) +// public WeaResult> export(@RequestBody AddUpDeductionQueryParam queryParam) { +// return WeaResult.success(service.export(queryParam, UserContext.getCurrentEmployeeId(), TenantContext.getCurrentTenantKey())); +// } + } diff --git a/src/com/engine/salary/web/BaseController.java b/src/com/engine/salary/web/BaseController.java deleted file mode 100644 index 8284833bc..000000000 --- a/src/com/engine/salary/web/BaseController.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.engine.salary.web; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -public class BaseController { - @SuppressWarnings("unchecked") - protected Map getRequestParams(HttpServletRequest request, HttpServletResponse response){ - Map params = new HashMap(); - Enumeration em = request.getParameterNames(); - while(em.hasMoreElements()){ - String paramname = em.nextElement(); - params.put(paramname, request.getParameter(paramname)); - } - return params; - } -}