累计附加扣除-条件接口

This commit is contained in:
钱涛 2022-03-04 10:10:38 +08:00
parent b028ad6845
commit 97cc5d154f
13 changed files with 702 additions and 968 deletions

View File

@ -0,0 +1,143 @@
package com.engine.salary.biz;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO;
import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam;
import com.engine.salary.mapper.datacollection.AddUpDeductionMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import weaver.conn.mybatis.MyBatisFactory;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class AddUpDeductionBiz extends BaseBean {
/**
* 查询列表
*
* @param param
* @return
*/
public List<AddUpDeductionListDTO> list(AddUpDeductionQueryParam param) {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
List<AddUpDeductionListDTO> list = mapper.list(param);
return list;
} finally {
sqlSession.close();
}
}
/**
* excel标题
*/
private final static List<String> title = Arrays.asList("姓名", "个税扣缴义务人", "部门", "手机号", "工号", "证件号码", "入职日期", "累计子女教育", "累计继续教育", "累计住房贷款利息", "累计住房租金", "累计赡养老人");
/**
* 导出
*
* @param param
* @return
*/
public HSSFWorkbook export(AddUpDeductionQueryParam param) {
//获取操作按钮资源
List<List<String>> rowList = getExcelRowList(param);
//获取excel
return getWorkbook(rowList);
}
/**
* 获取excel
*
* @param rowList 行列表
* @return workbook
*/
private HSSFWorkbook getWorkbook(List<List<String>> rowList) {
HSSFWorkbook workbook = new HSSFWorkbook();
// 设置title样式
HSSFCellStyle titleCellStyle = workbook.createCellStyle();
HSSFFont titleFont = workbook.createFont();
titleFont.setFontName("仿宋");
titleFont.setFontHeightInPoints((short) 15);
titleCellStyle.setFont(titleFont);
titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
titleCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());//背景色
titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置主体样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);// 设置字体大小
cellStyle.setFont(font);// 选择需要用到的字体格式
cellStyle.setWrapText(true);
HSSFSheet sheet = workbook.createSheet("0");
for (int rowIndex = 0; rowIndex < rowList.size(); rowIndex++) {
List<String> infoList = rowList.get(rowIndex);
HSSFRow row = sheet.createRow(rowIndex);
for (int cellIndex = 0; cellIndex < infoList.size(); cellIndex++) {
HSSFCell cell = row.createCell(cellIndex);
cell.setCellType(CellType.STRING);
if (rowIndex == 0) {
cell.setCellStyle(titleCellStyle);
} else {
cell.setCellStyle(cellStyle);
}
cell.setCellValue(infoList.get(cellIndex));
sheet.setColumnWidth(cellIndex, 35 * 256);
}
}
return workbook;
}
/**
* 获取excel数据行
*
* @return 导出数据行集合
*/
private List<List<String>> getExcelRowList(AddUpDeductionQueryParam param) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
List<AddUpDeductionListDTO> list = list(param);
final List<List<String>> dataRowList = Optional.ofNullable(list)
.map(List::stream)
.map(operatorStream -> operatorStream.map(dto -> {
List<String> cellList = new ArrayList<>();
cellList.add(Util.null2String(dto.getUsername()));
cellList.add(Util.null2String(dto.getTaxAgentName()));
cellList.add(Util.null2String(dto.getDepartmentName()));
cellList.add(Util.null2String(dto.getMobile()));
cellList.add(Util.null2String(dto.getJobNum()));
cellList.add(Util.null2String(dto.getIdNo()));
cellList.add(dto.getHiredate()==null?"":formatter.format(dto.getHiredate()));
cellList.add(String.valueOf(dto.getAddUpChildEducation()));
cellList.add(String.valueOf(dto.getAddUpContinuingEducation()));
cellList.add(String.valueOf(dto.getAddUpHousingLoanInterest()));
cellList.add(String.valueOf(dto.getAddUpHousingRent()));
cellList.add(String.valueOf(dto.getAddUpSupportElderly()));
return cellList;
}).collect(Collectors.toList()))
.orElse(Collections.emptyList());
List<List<String>> rowList = new ArrayList<>();
rowList.add(title);
rowList.addAll(dataRowList);
return rowList;
}
}

View File

@ -115,7 +115,7 @@ public class TaxRateBiz extends BaseBean {
}
public List<TaxRateBase> list(String tenantKey) {
public List<TaxRateBase> list() {
List<TaxRateBase> resultList = Lists.newArrayList();
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {

View File

@ -3,12 +3,14 @@ package com.engine.salary.cmd.datacollection;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.salary.biz.AddUpDeductionBiz;
import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import weaver.hrm.User;
import java.util.HashMap;
import java.util.Map;
public class AddUpDeductionExportCmd extends AbstractCommonCommand<Map<String, Object>> {
public class AddUpDeductionExportCmd extends AbstractCommonCommand<HSSFWorkbook> {
public AddUpDeductionExportCmd(Map<String, Object> params, User user) {
this.user = user;
@ -21,11 +23,12 @@ public class AddUpDeductionExportCmd extends AbstractCommonCommand<Map<String, O
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> apidatas = new HashMap<String, Object>(16);
public HSSFWorkbook execute(CommandContext commandContext) {
AddUpDeductionQueryParam addUpDeductionQueryParam = (AddUpDeductionQueryParam) params.get("addUpDeductionQueryParam");
AddUpDeductionBiz addUpDeductionBiz = new AddUpDeductionBiz();
HSSFWorkbook workbook = addUpDeductionBiz.export(addUpDeductionQueryParam);
return apidatas;
return workbook;
}
}

View File

@ -0,0 +1,105 @@
package com.engine.salary.cmd.datacollection;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AddUpDeductionGetSearchConditionCmd extends AbstractCommonCommand<Map<String, Object>> {
public AddUpDeductionGetSearchConditionCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> apidatas = new HashMap<String, Object>();
ConditionFactory conditionFactory = new ConditionFactory(user);
//条件组
List<SearchConditionGroup> addGroups = new ArrayList<SearchConditionGroup>();
List<SearchConditionItem> conditionItems = new ArrayList<SearchConditionItem>();
//文本输入框
SearchConditionItem username = conditionFactory.createCondition(ConditionType.INPUT,25034, "username");
username.setColSpan(2);//定义一行显示条件数默认值为2,当值为1时标识该条件单独占一行
username.setFieldcol(16); //条件输入框所占宽度默认值18
username.setLabelcol(8);
username.setViewAttr(2); // 编辑权限 1只读2可编辑 3必填 默认2
username.setLabel("姓名"); //设置文本值 这个将覆盖多语言标签的值
conditionItems.add(username);
SearchConditionItem departmentName = conditionFactory.createCondition(ConditionType.BROWSER,502227,"browser","departmentName");
departmentName.setColSpan(2);
departmentName.setFieldcol(12);
departmentName.setLabelcol(6);
departmentName.setViewAttr(2);
departmentName.setIsQuickSearch(false);
departmentName.setLabel("部门");
conditionItems.add(departmentName);
SearchConditionItem jobNum = conditionFactory.createCondition(ConditionType.INPUT,25034, "jobNum");
jobNum.setColSpan(2);
jobNum.setFieldcol(16);
jobNum.setLabelcol(8);
jobNum.setViewAttr(2);
jobNum.setLabel("工号");
conditionItems.add(jobNum);
SearchConditionItem idNo = conditionFactory.createCondition(ConditionType.INPUT,25034, "idNo");
idNo.setColSpan(2);
idNo.setFieldcol(16);
idNo.setLabelcol(8);
idNo.setViewAttr(2);
idNo.setLabel("证件号码");
conditionItems.add(idNo);
//日期范围选项
List<SearchConditionOption> dateOptions = new ArrayList<SearchConditionOption>();
dateOptions.add(new SearchConditionOption("6", SystemEnv.getHtmlLabelName(32530, user.getLanguage()),true));//指定日期范围(必须为6)
SearchConditionItem hiredate = conditionFactory.createCondition(ConditionType.RANGEPICKER, 18648, new String[]{"hiredate","hiredate"});
hiredate.setFieldcol(16);
hiredate.setLabelcol(8);
hiredate.setViewAttr(2);
hiredate.setLabel("入职日期");
hiredate.setOptions(dateOptions);
conditionItems.add(hiredate);
SearchConditionItem mobile = conditionFactory.createCondition(ConditionType.INPUT,25034, "mobile");
mobile.setColSpan(2);
mobile.setFieldcol(16);
mobile.setLabelcol(8);
mobile.setViewAttr(2);
mobile.setLabel("手机号");
conditionItems.add(mobile);
addGroups.add(new SearchConditionGroup("常用条件",true,conditionItems));
apidatas.put("condition",addGroups);
return apidatas;
}
}

View File

@ -40,7 +40,7 @@ public class AddUpDeductionListCmd extends AbstractCommonCommand<Map<String, Obj
" e.lastname as username," +
" d.departmentname AS departmentName," +
" e.mobile," +
" e.lloginid as job_num," +
" e.workcode as job_num," +
" e.created as hiredate," +
" t2.name AS tax_agent_name," +
" t1.add_up_child_education," +
@ -126,7 +126,7 @@ public class AddUpDeductionListCmd extends AbstractCommonCommand<Map<String, Obj
sqlWhere += " AND (" +
" e.lastname like '%" + keyword + "%'" +
" OR d.departmentname like '%" + keyword + "%'" +
// " OR e.job_num like ''%"+keyword+"%'" +
" OR e.workcode like ''%"+keyword+"%'" +
" )";
}
// 申报月份
@ -158,7 +158,7 @@ public class AddUpDeductionListCmd extends AbstractCommonCommand<Map<String, Obj
//工号
String jobNum = queryParam.getJobNum();
if (StringUtils.isNotBlank(jobNum)) {
sqlWhere += " AND e.lloginid like '%" + jobNum + "%'";
sqlWhere += " AND e.workcode like '%" + jobNum + "%'";
}
//入职日期
List<LocalDate> hiredate = queryParam.getHiredate();

View File

@ -0,0 +1,96 @@
package com.engine.salary.entity.datacollection.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.Date;
/**
* 数据采集-累计专项附加扣除
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @author qiantao
* @version 1.0
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AddUpDeductionListDTO {
/**
* 主键id
*/
private Long id;
/**
* 员工id
*/
private Long employeeId;
/**
* 姓名
*/
private String username;
/**
* 个税扣缴义务人
*/
private String taxAgentName;
/**
* 部门
*/
private String departmentName;
/**
* 手机号
*/
private String mobile;
/**
* 工号
*/
private String jobNum;
/**
* 证件号码
*/
private String idNo;
/**
* 入职日期
*/
@JsonFormat(pattern = "yyyy-MM-dd")
private Date hiredate;
/**
* 累计子女教育
*/
private BigDecimal addUpChildEducation;
/**
* 累计继续教育
*/
private BigDecimal addUpContinuingEducation;
/**
* 累计住房贷款利息
*/
private BigDecimal addUpHousingLoanInterest;
/**
* 累计住房租金
*/
private BigDecimal addUpHousingRent;
/**
* 累计赡养老人
*/
private BigDecimal addUpSupportElderly;
}

View File

@ -10,53 +10,57 @@ import java.util.Collection;
import java.util.List;
/**
* @Description: 数据采集-累计专项附加扣除
* @Author: wangxiangzhong
* @Date: 2021-11-10 11:17
*/
* 数据采集-累计专项附加扣除查询参数
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @author qiantao
* @version 1.0
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
//("数据采集-累计专项附加扣除查询参数")
public class AddUpDeductionQueryParam{
public class AddUpDeductionQueryParam {
//@ApiModelProperty("主键id")
/**
* 主键id
*/
private Collection<Long> ids;
//@ApiModelProperty("关键字(姓名、部门、工号)")
//关键字姓名部门工号
private String keyword;
//@ApiModelProperty("主键id")
//主键id
private Long id;
//@ApiModelProperty("申报月份")
//申报月份
private List<String> declareMonth;
//@ApiModelProperty("姓名")
//姓名
private String username;
//@ApiModelProperty("员工id")
//员工id
private Long employeeId;
//@ApiModelProperty("个税扣缴义务人的主键id")
//个税扣缴义务人的主键id
private Long taxAgentId;
//@ApiModelProperty("部门id")
//部门id
private List<Long> departmentIds;
//@ApiModelProperty("工号")
//工号
private String jobNum;
//@ApiModelProperty("证件号")
//证件号
private String idNo;
//@ApiModelProperty("入职日期")
//入职日期
private List<LocalDate> hiredate;
//@ApiModelProperty("手机号")
//手机号
private String mobile;
//@ApiModelProperty("累计专项附加扣除id获取明细")
//累计专项附加扣除id获取明细
private Long accumulatedSpecialAdditionalDeductionId;
}

View File

@ -2,7 +2,10 @@ package com.engine.salary.mapper.datacollection;
import com.engine.salary.entity.datacollection.AddUpDeduction;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO;
import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@ -72,5 +75,12 @@ public interface AddUpDeductionMapper {
*/
List<DataCollectionEmployee> listEmployee();
/**
* 查询数据采集-累计专项附加扣除列表
* @param param
* @return
*/
List<AddUpDeductionListDTO> list(@Param("param") AddUpDeductionQueryParam param);
}

View File

@ -278,4 +278,244 @@
</select>
<!-- E10 sql -->
<sql id="addUpDeductionColumn">
t1.id,
t1.declare_month,
t1.employee_id,
e.lastname as usename,
d.departmentname AS departmentName,
e.mobile,
e.workcode 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
</sql>
<sql id="paramSql">
<if test="param.ids != null and param.ids.size()>0">
AND t1.id IN
<foreach collection="param.ids" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<if test="param.employeeId != null">
AND t1.employee_id = #{param.employeeId}
</if>
<!-- 关键字(姓名、部门、工号 -->
<if test="param.keyword != null and param.keyword != ''">
AND
(
e.lastname like CONCAT('%',#{param.keyword},'%')
OR d.departmentname like CONCAT('%',#{param.keyword},'%')
OR e.workcode like CONCAT('%',#{param.keyword},'%')
)
</if>
<!-- 申报月份 -->
<if test="param.declareMonth != null">
<if test="param.declareMonth.size() == 1">
AND t1.declare_month = #{param.declareMonth[0]}
</if>
<if test="param.declareMonth.size() == 2">
AND (t1.declare_month BETWEEN #{param.declareMonth[0]} AND #{param.declareMonth[1]})
</if>
</if>
<!-- 姓名 -->
<if test="param.username != null and param.username != ''">
AND e.lastname like CONCAT('%',#{param.username},'%')
</if>
<!-- 个税扣缴义务人 -->
<if test="param.taxAgentId != null">
AND t1.tax_agent_id = #{param.taxAgentId}
</if>
<!-- 部门 -->
<if test="param.departmentIds != null and param.departmentIds.size()>0">
AND d.id IN
<foreach collection="param.departmentIds" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<!-- 工号 -->
<if test="param.jobNum != null and param.jobNum != ''">
AND e.workcode like CONCAT('%',#{param.jobNum},'%')
</if>
<!-- 入职日期 -->
<if test="param.hiredate != null and param.hiredate.size() == 2">
AND (e.created BETWEEN #{param.hiredate[0]} AND #{param.hiredate[1]})
</if>
<!-- 手机号 -->
<if test="param.mobile != null and param.mobile != ''">
AND e.mobile like CONCAT('%',#{param.mobile},'%')
</if>
</sql>
<sql id="paramSql" databaseId="oracle">
<if test="param.ids != null and param.ids.size()>0">
AND t1.id IN
<foreach collection="param.ids" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<if test="param.employeeId != null">
AND t1.employee_id = #{param.employeeId}
</if>
<if test="param.keyword != null and param.keyword != ''">
AND
(
e.lastname like '%'||#{param.keyword}||'%'
OR d.departmentname like '%'||#{param.keyword}||'%'
OR e.workcode like '%'||#{param.keyword}||'%'
)
</if>
<if test="param.declareMonth != null">
<if test="param.declareMonth.size() == 1">
AND t1.declare_month = #{param.declareMonth[0]}
</if>
<if test="param.declareMonth.size() == 2">
AND (t1.declare_month BETWEEN #{param.declareMonth[0]} AND #{param.declareMonth[1]})
</if>
</if>
<if test="param.username != null and param.username != ''">
AND e.lastname like '%'||#{param.username}||'%'
</if>
<if test="param.taxAgentId != null">
AND t1.tax_agent_id = #{param.taxAgentId}
</if>
<if test="param.departmentIds != null and param.departmentIds.size()>0">
AND d.id IN
<foreach collection="param.departmentIds" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<if test="param.jobNum != null and param.jobNum != ''">
AND e.workcode like '%'||#{param.jobNum}||'%'
</if>
<if test="param.hiredate != null and param.hiredate.size() == 2">
AND (e.created BETWEEN #{param.hiredate[0]} AND #{param.hiredate[1]})
</if>
<if test="param.mobile != null and param.mobile != ''">
AND e.mobile like '%'||#{param.mobile}||'%'
</if>
</sql>
<sql id="paramSql" databaseId="sqlserver">
<if test="param.ids != null and param.ids.size()>0">
AND t1.id IN
<foreach collection="param.ids" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<if test="param.employeeId != null">
AND t1.employee_id = #{param.employeeId}
</if>
<if test="param.keyword != null and param.keyword != ''">
AND
(
e.lastname like '%'+#{param.keyword}+'%'
OR d.departmentname like '%'+#{param.keyword}+'%'
OR e.workcode like '%'+#{param.keyword}+'%'
)
</if>
<if test="param.declareMonth != null">
<if test="param.declareMonth.size() == 1">
AND t1.declare_month = #{param.declareMonth[0]}
</if>
<if test="param.declareMonth.size() == 2">
AND (t1.declare_month BETWEEN #{param.declareMonth[0]} AND #{param.declareMonth[1]})
</if>
</if>
<if test="param.username != null and param.username != ''">
AND e.lastname like '%'+#{param.username}+'%'
</if>
<if test="param.taxAgentId != null">
AND t1.tax_agent_id = #{param.taxAgentId}
</if>
<if test="param.departmentIds != null and param.departmentIds.size()>0">
AND d.id IN
<foreach collection="param.departmentIds" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</if>
<if test="param.jobNum != null and param.jobNum != ''">
AND e.workcode like '%'+#{param.jobNum}+'%'
</if>
<if test="param.hiredate != null and param.hiredate.size() == 2">
AND (e.created BETWEEN #{param.hiredate[0]} AND #{param.hiredate[1]})
</if>
<if test="param.mobile != null and param.mobile != ''">
AND e.mobile like '%'+#{param.mobile}+'%'
</if>
</sql>
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO">
SELECT
<include refid="addUpDeductionColumn"/>
FROM
hrsa_add_up_deduction t1
LEFT JOIN hrsa_tax_agent t2 ON t1.tax_agent_id = t2.id
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO" databaseId="oracle">
SELECT
<include refid="addUpDeductionColumn"/>
FROM
hrsa_add_up_deduction t1
LEFT JOIN hrsa_tax_agent t2 ON t1.tax_agent_id = t2.id
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO" databaseId="sqlserver">
SELECT
<include refid="addUpDeductionColumn"/>
FROM
hrsa_add_up_deduction t1
LEFT JOIN hrsa_tax_agent t2 ON t1.tax_agent_id = t2.id
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
</mapper>

View File

@ -1,925 +0,0 @@
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.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
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<String, Object> 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<String> outputFiles = new ArrayList<>();
private List<Map<String, Object>> 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<String, Object> params) {
this.user = user;
this.params = params;
}
public ExportDeclareRecordsProcess() {
}
public List<String> getOutputFiles() {
return this.outputFiles;
}
public void setOutputFiles(List<String> 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<String, Object> importExcelData = new HashMap<>();
importExcelData.put("year", year);
//basic info
Map<String, Object> 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<String> catalogues = RecordsBiz.getInstance().queryRecordCatalogues(pid, year);
//child edu info
if (catalogues.contains(FormTypeEnum.CHILD_EDU.getValue())) {
Map<String, Object> childEduInfo = RecordsBiz.getInstance().queryChildEduInfo(pid, year);
importExcelData.put("childEduInfo", childEduInfo);
}
//edu info
if (catalogues.contains(FormTypeEnum.EDU.getValue())) {
Map<String, Object> eduInfo = RecordsBiz.getInstance().queryEduInfo(pid, year);
importExcelData.put("eduInfo", eduInfo);
}
//loan info
if (catalogues.contains(FormTypeEnum.LOAN.getValue())) {
Map<String, Object> loanInfo = RecordsBiz.getInstance().queryLoanInfo(pid, year);
importExcelData.put("loanInfo", loanInfo);
}
//rent info
if (catalogues.contains(FormTypeEnum.RENT.getValue())) {
Map<String, Object> rentInfo = RecordsBiz.getInstance().queryRentInfo(pid, year);
importExcelData.put("rentInfo", rentInfo);
}
//support paent info
if (catalogues.contains(FormTypeEnum.SUPPORT_PARENT.getValue())) {
Map<String, Object> 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<String, Object> 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<String, Object>) data.get("basicInfo"));
if (data.containsKey("childEduInfo"))
writeChildEduInfo((Map<String, Object>) data.get("childEduInfo"));
if (data.containsKey("eduInfo"))
writeEduInfo((Map<String, Object>) data.get("eduInfo"));
if (data.containsKey("loanInfo"))
writeLoanInfo((Map<String, Object>) data.get("loanInfo"));
if (data.containsKey("rentInfo"))
writeRentInfo((Map<String, Object>) data.get("rentInfo"));
if (data.containsKey("supportParentInfo"))
writeSupportParentInfo((Map<String, Object>) data.get("supportParentInfo"));
String fileName = Util.formatMultiLang(((Map<String, Object>) 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("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")"));
}else{
response.setHeader("content-disposition", "attachment; filename=\"" +
URLEncoder.encode(name.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"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<String, Object> 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<String, Object> data) throws Exception {
try {
sheet = workbook.getSheetAt(2);
sheet.setForceFormulaRecalculation(true);
int i = 0;
int rowId = 2;
String percent = (String) data.get("percent");
List<Map<String, Object>> children = (List<Map<String, Object>>) data.get("children");
for (Map<String, Object> 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<String, Object> data) throws Exception {
try {
sheet = workbook.getSheetAt(6);
sheet.setForceFormulaRecalculation(true);
int rowId1 = 3;
int rowId2 = 9;
List<List<Map<String, Object>>> edus = (List<List<Map<String, Object>>>) data.get("edus");
List<Map<String, Object>> l1 = edus.get(0);
List<Map<String, Object>> l2 = edus.get(1);
if (l1.size() > 0) {
int i = 0;
for (Map<String, Object> 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<String, Object> 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<String, Object> 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<Map<String, Object>> loans = (List<Map<String, Object>>) data.get("loans");
int rowId = 4;
for (Map<String, Object> 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<String, Object> 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<String, Object> 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<Map<String, Object>> parents = (List<Map<String, Object>>) data.get("parents");
List<Map<String, Object>> supports = (List<Map<String, Object>>) 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<String, Object> 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<String, Object> 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<String> 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<String> 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;
}
/**
* 解析操作按钮excel时sheet下标
*/
private static final int OPERATOR_PARSE_EXCEL_SHEET_INDEX = 0;
/**
* 解析操作按钮excel时开始行
*/
private static final int OPERATOR_PARSE_EXCEL_BEGIN_ROW_INDEX = 1;
/**
* 解析操作按钮excel时应有多少列
*/
private static final int OPERATOR_PARSE_EXCEL_VALID_CELL_NUM = 5;
// @Override
// public void importOperator(MultipartFile file, String tenantCode, String systemId) {
//
// //验证导入参数
// if (file == null) {
// throw new OPERBIZException(OperatorExceptionCode.IMPORT_FILE_IS_EMPTY);
// }
// validOperator(tenantCode, systemId);
//
// //解析文件获取元素集合
// List<OperatorBaseDto> operatorList = ExcelParseHelper.parse(file, OperatorBaseDto.class,
// OPERATOR_PARSE_EXCEL_SHEET_INDEX, OPERATOR_PARSE_EXCEL_BEGIN_ROW_INDEX, OPERATOR_PARSE_EXCEL_VALID_CELL_NUM);
// //操作人
// final String userId = JWTUtil.getUserId();
// //当前时间
// final long currentTime = new Date().getTime();
// //操作集合
// final List<OperatorBaseDto> list = operatorList.stream()
// .peek(operator -> {//初始化值
// operator.setTenantCode(tenantCode);
// operator.setSystemId(systemId);
// operator.setUseStatus(NORMAL_STATUS);
// operator.setCreateUser(userId);
// operator.setCreateTime(currentTime);
// operator.setUpdateUser(userId);
// operator.setUpdateTime(currentTime);
// })
// .filter(operator -> StringUtils.isNoneBlank(operator.getOperatorFlag(), operator.getOperatorName(), operator.getIcon())) //过滤不合法元素
// .collect(Collectors
// .collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OperatorBaseDto::getOperatorFlag))),
// ArrayList::new));
//
// //将操作按新增或更新分类
// final Pair<List<OperatorBaseDto>, List<OperatorBaseDto>> operatorListPair = classifyOperator(tenantCode, systemId, list);
// final List<OperatorBaseDto> addlist = operatorListPair.getLeft();
// final List<OperatorBaseDto> updateList = operatorListPair.getRight();
//
// //批量新增
// operatorDalService.batchAdd(this.convertListFromSource(addlist));
//
// //逐条更新
// updateList.forEach(operatorBaseDto -> operatorDalService.updateByFlag(this.convertBeanFromSource(operatorBaseDto)));
// }
/**
* excel标题
*/
// private final static List<String> title = Arrays.asList("Operation identification", "Operation name", "Icon", "Sort number", "custom");
//
// public HSSFWorkbook exportOperator(String tenantCode, String systemId) {
//
//
//
// //获取操作按钮资源
//// List<List<String>> rowList = getExcelRowList(tenantCode, systemId);
//
// //获取excel
// return getWorkbook(rowList);
// }
/**
* 获取excel
*
* @param rowList 行列表
* @return workbook
*/
private HSSFWorkbook getWorkbook(List<List<String>> rowList) {
HSSFWorkbook workbook = new HSSFWorkbook();
// 设置title样式
HSSFCellStyle titleCellStyle = workbook.createCellStyle();
HSSFFont titleFont = workbook.createFont();
titleFont.setFontName("仿宋");
titleFont.setFontHeightInPoints((short) 15);
titleCellStyle.setFont(titleFont);
titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
titleCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());//背景色
titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置主体样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);// 设置字体大小
cellStyle.setFont(font);// 选择需要用到的字体格式
cellStyle.setWrapText(true);
HSSFSheet sheet = workbook.createSheet("0");
for (int rowIndex = 0; rowIndex < rowList.size(); rowIndex++) {
List<String> infoList = rowList.get(rowIndex);
HSSFRow row = sheet.createRow(rowIndex);
for (int cellIndex = 0; cellIndex < infoList.size(); cellIndex++) {
HSSFCell cell = row.createCell(cellIndex);
cell.setCellType(CellType.STRING);
if (rowIndex == 0) {
cell.setCellStyle(titleCellStyle);
} else {
cell.setCellStyle(cellStyle);
}
cell.setCellValue(infoList.get(cellIndex));
sheet.setColumnWidth(cellIndex, 35 * 256);
}
}
return workbook;
}
/**
* 获取excel数据行
*
* @param tenantCode 租户
* @param systemId 系统id
* @return 导出数据行集合
*/
// private List<List<String>> getExcelRowList(String tenantCode, String systemId) {
// final List<OperatorBaseDo> operatorBaseDoList = operatorDalService.selectOperatorListInOneSystem(tenantCode, systemId, null);
// final List<List<String>> dataRowList = Optional.ofNullable(operatorBaseDoList)
// .map(List::stream)
// .map(operatorStream -> operatorStream.map(operatorBaseDo -> {
// List<String> cellList = new ArrayList<>();
// cellList.add(operatorBaseDo.getOperatorFlag());
// cellList.add(operatorBaseDo.getOperatorName());
// cellList.add(operatorBaseDo.getIcon());
// cellList.add(operatorBaseDo.getSort() == null ? "" : operatorBaseDo.getSort().toString());
// cellList.add(operatorBaseDo.getCustom());
// return cellList;
// }).collect(Collectors.toList()))
// .orElse(Collections.emptyList());
//
// List<List<String>> rowList = new ArrayList<>();
// rowList.add(title);
// rowList.addAll(dataRowList);
// return rowList;
// }
}

View File

@ -1,9 +1,14 @@
package com.engine.salary.service;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.util.Map;
public interface AddUpDeductionService {
Map<String, Object> list(Map<String, Object> params);
HSSFWorkbook export(Map<String, Object> params);
Map<String, Object> getSearchCondition(Map<String, Object> params);
}

View File

@ -1,8 +1,11 @@
package com.engine.salary.service.impl;
import com.engine.core.impl.Service;
import com.engine.salary.cmd.datacollection.AddUpDeductionExportCmd;
import com.engine.salary.cmd.datacollection.AddUpDeductionGetSearchConditionCmd;
import com.engine.salary.cmd.datacollection.AddUpDeductionListCmd;
import com.engine.salary.service.AddUpDeductionService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.util.Map;
@ -12,4 +15,14 @@ public class AddUpDeductionServiceImpl extends Service implements AddUpDeduction
public Map<String, Object> list(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionListCmd(params,user));
}
@Override
public HSSFWorkbook export(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionExportCmd(params,user));
}
@Override
public Map<String, Object> getSearchCondition(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionGetSearchConditionCmd(params,user));
}
}

View File

@ -7,6 +7,7 @@ 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 org.apache.poi.hssf.usermodel.HSSFWorkbook;
import weaver.general.GCONST;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
@ -17,7 +18,10 @@ import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
@ -28,6 +32,19 @@ public class AddUpDeductionController {
return (AddUpDeductionService) ServiceUtil.getService(AddUpDeductionServiceImpl.class, user);
}
/**
* 数据采集-累计专项附加扣除列表的高级搜索
* @return
*/
@GET
@Path("/getSearchCondition")
@Produces(MediaType.APPLICATION_JSON)
public String getSearchCondition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return ResponseResult.run(getService(user)::getSearchCondition, ParamUtil.request2Map(request));
}
@POST
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
@ -42,10 +59,10 @@ public class AddUpDeductionController {
@GET
@Path("/downloadTemplate")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getAll() {
public Response getAll(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
//模板文件路径
String templateFilePath = GCONST.getRootPath() + "hrm/resource/inputexcellfile/taxDeclareTemplate.xls";
String templateFilePath = GCONST.getRootPath() + "salary/addUpDeduction/addUpDeductionTemplate.xlsx";
File file = new File(templateFilePath);
@ -65,18 +82,41 @@ public class AddUpDeductionController {
}
/**
* 导出
*
* @param
* @return
*/
@GET
@Path("/export")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
Map<String, Object> map = ParamUtil.request2Map(request);
map.put("addUpDeductionQueryParam", new AddUpDeductionQueryParam());
// /**
// * 导出
// * @param queryParam
// * @return
// */
// @POST
// @Path("/export")
// @Produces(MediaType.APPLICATION_JSON)
// public WeaResult<Map<String, Object>> export(@RequestBody AddUpDeductionQueryParam queryParam) {
// return WeaResult.success(service.export(queryParam, UserContext.getCurrentEmployeeId(), TenantContext.getCurrentTenantKey()));
// }
HSSFWorkbook workbook = getService(user).export(map);
String fileName = null;
try {
fileName = URLEncoder.encode("累计专项附加扣除导入模板.xlsx", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
workbook.write(outputStream);
outputStream.flush();
}
};
response.setContentType("application/octet-stream");
return Response.ok(output)
.header("Content-disposition", "attachment;filename=" + fileName)
.header("Cache-Control", "no-cache").build();
}
}