统一税率保存参数

This commit is contained in:
钱涛 2022-03-03 13:50:03 +08:00
parent aa528eccd8
commit c183a11cba
25 changed files with 2938 additions and 31 deletions

View File

@ -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();
}

View File

@ -40,7 +40,7 @@ public class TaxAgentDeleteCmd extends AbstractCommonCommand<Map<String, Object>
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<TaxAgent> taxAgents = taxAgentMapper.listBySome(TaxAgentQueryParam.builder().ids(idList).build());
if (CollectionUtils.isEmpty(taxAgents)) {
throw new SalaryRunTimeException("要删除的个税扣缴义务人在不存在或已删除");

View File

@ -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<Map<String, Object>> {
public AddUpDeductionListCmd(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) {
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<String, Object> apidatas = new HashMap<String, Object>(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<WeaTableOperate> 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<String> 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<Long> 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<String> 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<Long> 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<LocalDate> 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;
}
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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<Long> ids;
//@ApiModelProperty("关键字(姓名、部门、工号)")
private String keyword;
//@ApiModelProperty("主键id")
private Long id;
//@ApiModelProperty("申报月份")
private List<String> declareMonth;
//@ApiModelProperty("姓名")
private String username;
//@ApiModelProperty("员工id")
private Long employeeId;
//@ApiModelProperty("个税扣缴义务人的主键id")
private Long taxAgentId;
//@ApiModelProperty("部门id")
private List<Long> departmentIds;
//@ApiModelProperty("工号")
private String jobNum;
//@ApiModelProperty("证件号")
private String idNo;
//@ApiModelProperty("入职日期")
private List<LocalDate> hiredate;
//@ApiModelProperty("手机号")
private String mobile;
//@ApiModelProperty("累计专项附加扣除id获取明细")
private Long accumulatedSpecialAdditionalDeductionId;
}

View File

@ -43,7 +43,7 @@ public class SysTaxRateBase {
/**
* 是否是系统默认的0自定义1系统默认
*/
private Byte systemType;
private Integer systemType;
/**
* 租户ID
*/

View File

@ -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())

View File

@ -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;

View File

@ -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<AddUpDeduction> 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<DataCollectionEmployee> listEmployee();
}

View File

@ -0,0 +1,281 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.engine.salary.mapper.datacollection.AddUpDeductionMapper">
<resultMap id="BaseResultMap" type="com.engine.salary.entity.datacollection.AddUpDeduction">
<result column="add_up_child_education" property="addUpChildEducation"/>
<result column="add_up_continuing_education" property="addUpContinuingEducation"/>
<result column="add_up_housing_loan_interest" property="addUpHousingLoanInterest"/>
<result column="add_up_housing_rent" property="addUpHousingRent"/>
<result column="add_up_support_elderly" property="addUpSupportElderly"/>
<result column="create_time" property="createTime"/>
<result column="creator" property="creator"/>
<result column="declare_month" property="declareMonth"/>
<result column="delete_type" property="deleteType"/>
<result column="employee_id" property="employeeId"/>
<result column="id" property="id"/>
<result column="tax_agent_id" property="taxAgentId"/>
<result column="tenant_key" property="tenantKey"/>
<result column="update_time" property="updateTime"/>
</resultMap>
<!-- 表字段 -->
<sql id="baseColumns">
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
</sql>
<!-- 查询全部 -->
<select id="listAll" resultMap="BaseResultMap">
SELECT
<include refid="baseColumns"/>
FROM hrsa_add_up_deduction t
WHERE delete_type = 0
</select>
<!-- 根据主键获取单条记录 -->
<select id="getById" resultMap="BaseResultMap" parameterType="Long">
SELECT
<include refid="baseColumns"/>
FROM hrsa_add_up_deduction t
WHERE id = #{id} AND delete_type = 0
</select>
<!-- 插入全部字段 -->
<insert id="insert" parameterType="com.engine.salary.entity.datacollection.AddUpDeduction"
keyProperty="id" keyColumn="id" useGeneratedKeys="true"
>
INSERT INTO hrsa_add_up_deduction
<trim prefix="(" suffix=")" suffixOverrides=",">
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,
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
#{addUpChildEducation},
#{addUpContinuingEducation},
#{addUpHousingLoanInterest},
#{addUpHousingRent},
#{addUpSupportElderly},
#{createTime},
#{creator},
#{declareMonth},
#{deleteType},
#{employeeId},
#{id},
#{taxAgentId},
#{tenantKey},
#{updateTime},
</trim>
</insert>
<!-- 插入不为NULL的字段 -->
<insert id="insertIgnoreNull" parameterType="com.engine.salary.entity.datacollection.AddUpDeduction"
keyProperty="id" keyColumn="id" useGeneratedKeys="true"
>
INSERT INTO hrsa_add_up_deduction
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="addUpChildEducation != null">
add_up_child_education,
</if>
<if test="addUpContinuingEducation != null">
add_up_continuing_education,
</if>
<if test="addUpHousingLoanInterest != null">
add_up_housing_loan_interest,
</if>
<if test="addUpHousingRent != null">
add_up_housing_rent,
</if>
<if test="addUpSupportElderly != null">
add_up_support_elderly,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="creator != null">
creator,
</if>
<if test="declareMonth != null">
declare_month,
</if>
<if test="deleteType != null">
delete_type,
</if>
<if test="employeeId != null">
employee_id,
</if>
<if test="id != null">
id,
</if>
<if test="taxAgentId != null">
tax_agent_id,
</if>
<if test="tenantKey != null">
tenant_key,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="addUpChildEducation != null">
#{addUpChildEducation},
</if>
<if test="addUpContinuingEducation != null">
#{addUpContinuingEducation},
</if>
<if test="addUpHousingLoanInterest != null">
#{addUpHousingLoanInterest},
</if>
<if test="addUpHousingRent != null">
#{addUpHousingRent},
</if>
<if test="addUpSupportElderly != null">
#{addUpSupportElderly},
</if>
<if test="createTime != null">
#{createTime},
</if>
<if test="creator != null">
#{creator},
</if>
<if test="declareMonth != null">
#{declareMonth},
</if>
<if test="deleteType != null">
#{deleteType},
</if>
<if test="employeeId != null">
#{employeeId},
</if>
<if test="id != null">
#{id},
</if>
<if test="taxAgentId != null">
#{taxAgentId},
</if>
<if test="tenantKey != null">
#{tenantKey},
</if>
<if test="updateTime != null">
#{updateTime},
</if>
</trim>
</insert>
<!-- 更新,更新全部字段 -->
<update id="update" parameterType="com.engine.salary.entity.datacollection.AddUpDeduction">
UPDATE hrsa_add_up_deduction
<set>
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},
</set>
WHERE id = #{id} AND delete_type = 0
</update>
<!-- 更新不为NULL的字段 -->
<update id="updateIgnoreNull" parameterType="com.engine.salary.entity.datacollection.AddUpDeduction">
UPDATE hrsa_add_up_deduction
<set>
<if test="addUpChildEducation != null">
add_up_child_education=#{addUpChildEducation},
</if>
<if test="addUpContinuingEducation != null">
add_up_continuing_education=#{addUpContinuingEducation},
</if>
<if test="addUpHousingLoanInterest != null">
add_up_housing_loan_interest=#{addUpHousingLoanInterest},
</if>
<if test="addUpHousingRent != null">
add_up_housing_rent=#{addUpHousingRent},
</if>
<if test="addUpSupportElderly != null">
add_up_support_elderly=#{addUpSupportElderly},
</if>
<if test="createTime != null">
create_time=#{createTime},
</if>
<if test="creator != null">
creator=#{creator},
</if>
<if test="declareMonth != null">
declare_month=#{declareMonth},
</if>
<if test="deleteType != null">
delete_type=#{deleteType},
</if>
<if test="employeeId != null">
employee_id=#{employeeId},
</if>
<if test="taxAgentId != null">
tax_agent_id=#{taxAgentId},
</if>
<if test="tenantKey != null">
tenant_key=#{tenantKey},
</if>
<if test="updateTime != null">
update_time=#{updateTime},
</if>
</set>
WHERE id = #{id} AND delete_type = 0
</update>
<!-- 根据主键删除记录 -->
<delete id="delete" parameterType="com.engine.salary.entity.datacollection.AddUpDeduction">
UPDATE hrsa_add_up_deduction
SET delete_type=1
WHERE id = #{id}
AND delete_type = 0
</delete>
<!-- 员工基本信息 -->
<select id="listEmployee" resultType="com.engine.salary.entity.datacollection.DataCollectionEmployee">
select e.ID as employeeId,
e.LASTNAME as username,
d.DEPARTMENTNAME as deparmentName
from hrmresource e
left join hrmdepartment d on e.departmentid = d.id
where e.status not in (4, 5, 6, 7)
</select>
</mapper>

View File

@ -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<AddUpSituation> 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);
}

View File

@ -0,0 +1,411 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.engine.salary.mapper.datacollection.AddUpSituationMapper">
<resultMap id="BaseResultMap" type="com.engine.salary.entity.datacollection.AddUpSituation">
<result column="add_up_accumulation_fund_total" property="addUpAccumulationFundTotal"/>
<result column="add_up_advance_tax" property="addUpAdvanceTax"/>
<result column="add_up_allowed_donation" property="addUpAllowedDonation"/>
<result column="add_up_child_education" property="addUpChildEducation"/>
<result column="add_up_continuing_education" property="addUpContinuingEducation"/>
<result column="add_up_enterprise_and_other" property="addUpEnterpriseAndOther"/>
<result column="add_up_housing_loan_interest" property="addUpHousingLoanInterest"/>
<result column="add_up_housing_rent" property="addUpHousingRent"/>
<result column="add_up_income" property="addUpIncome"/>
<result column="add_up_other_deduction" property="addUpOtherDeduction"/>
<result column="add_up_social_security_total" property="addUpSocialSecurityTotal"/>
<result column="add_up_subtraction" property="addUpSubtraction"/>
<result column="add_up_support_elderly" property="addUpSupportElderly"/>
<result column="add_up_tax_exempt_income" property="addUpTaxExemptIncome"/>
<result column="create_time" property="createTime"/>
<result column="creator" property="creator"/>
<result column="delete_type" property="deleteType"/>
<result column="employee_id" property="employeeId"/>
<result column="id" property="id"/>
<result column="tax_agent_id" property="taxAgentId"/>
<result column="tax_year_month" property="taxYearMonth"/>
<result column="tenant_key" property="tenantKey"/>
<result column="update_time" property="updateTime"/>
<result column="year" property="year"/>
</resultMap>
<!-- 表字段 -->
<sql id="baseColumns">
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
</sql>
<!-- 查询全部 -->
<select id="listAll" resultMap="BaseResultMap">
SELECT
<include refid="baseColumns"/>
FROM hrsa_add_up_situation t
WHERE delete_type = 0
</select>
<!-- 根据主键获取单条记录 -->
<select id="getById" resultMap="BaseResultMap" parameterType="Long">
SELECT
<include refid="baseColumns"/>
FROM hrsa_add_up_situation t
WHERE id = #{id} AND delete_type = 0
</select>
<!-- 插入全部字段 -->
<insert id="insert" parameterType="com.engine.salary.entity.datacollection.AddUpSituation"
keyProperty="id" keyColumn="id" useGeneratedKeys="true"
>
INSERT INTO hrsa_add_up_situation
<trim prefix="(" suffix=")" suffixOverrides=",">
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,
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
#{addUpAccumulationFundTotal},
#{addUpAdvanceTax},
#{addUpAllowedDonation},
#{addUpChildEducation},
#{addUpContinuingEducation},
#{addUpEnterpriseAndOther},
#{addUpHousingLoanInterest},
#{addUpHousingRent},
#{addUpIncome},
#{addUpOtherDeduction},
#{addUpSocialSecurityTotal},
#{addUpSubtraction},
#{addUpSupportElderly},
#{addUpTaxExemptIncome},
#{createTime},
#{creator},
#{deleteType},
#{employeeId},
#{id},
#{taxAgentId},
#{taxYearMonth},
#{tenantKey},
#{updateTime},
#{year},
</trim>
</insert>
<!-- 插入不为NULL的字段 -->
<insert id="insertIgnoreNull" parameterType="com.engine.salary.entity.datacollection.AddUpSituation"
keyProperty="id" keyColumn="id" useGeneratedKeys="true"
>
INSERT INTO hrsa_add_up_situation
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="addUpAccumulationFundTotal != null">
add_up_accumulation_fund_total,
</if>
<if test="addUpAdvanceTax != null">
add_up_advance_tax,
</if>
<if test="addUpAllowedDonation != null">
add_up_allowed_donation,
</if>
<if test="addUpChildEducation != null">
add_up_child_education,
</if>
<if test="addUpContinuingEducation != null">
add_up_continuing_education,
</if>
<if test="addUpEnterpriseAndOther != null">
add_up_enterprise_and_other,
</if>
<if test="addUpHousingLoanInterest != null">
add_up_housing_loan_interest,
</if>
<if test="addUpHousingRent != null">
add_up_housing_rent,
</if>
<if test="addUpIncome != null">
add_up_income,
</if>
<if test="addUpOtherDeduction != null">
add_up_other_deduction,
</if>
<if test="addUpSocialSecurityTotal != null">
add_up_social_security_total,
</if>
<if test="addUpSubtraction != null">
add_up_subtraction,
</if>
<if test="addUpSupportElderly != null">
add_up_support_elderly,
</if>
<if test="addUpTaxExemptIncome != null">
add_up_tax_exempt_income,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="creator != null">
creator,
</if>
<if test="deleteType != null">
delete_type,
</if>
<if test="employeeId != null">
employee_id,
</if>
<if test="id != null">
id,
</if>
<if test="taxAgentId != null">
tax_agent_id,
</if>
<if test="taxYearMonth != null">
tax_year_month,
</if>
<if test="tenantKey != null">
tenant_key,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="year != null">
year,
</if>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="addUpAccumulationFundTotal != null">
#{addUpAccumulationFundTotal},
</if>
<if test="addUpAdvanceTax != null">
#{addUpAdvanceTax},
</if>
<if test="addUpAllowedDonation != null">
#{addUpAllowedDonation},
</if>
<if test="addUpChildEducation != null">
#{addUpChildEducation},
</if>
<if test="addUpContinuingEducation != null">
#{addUpContinuingEducation},
</if>
<if test="addUpEnterpriseAndOther != null">
#{addUpEnterpriseAndOther},
</if>
<if test="addUpHousingLoanInterest != null">
#{addUpHousingLoanInterest},
</if>
<if test="addUpHousingRent != null">
#{addUpHousingRent},
</if>
<if test="addUpIncome != null">
#{addUpIncome},
</if>
<if test="addUpOtherDeduction != null">
#{addUpOtherDeduction},
</if>
<if test="addUpSocialSecurityTotal != null">
#{addUpSocialSecurityTotal},
</if>
<if test="addUpSubtraction != null">
#{addUpSubtraction},
</if>
<if test="addUpSupportElderly != null">
#{addUpSupportElderly},
</if>
<if test="addUpTaxExemptIncome != null">
#{addUpTaxExemptIncome},
</if>
<if test="createTime != null">
#{createTime},
</if>
<if test="creator != null">
#{creator},
</if>
<if test="deleteType != null">
#{deleteType},
</if>
<if test="employeeId != null">
#{employeeId},
</if>
<if test="id != null">
#{id},
</if>
<if test="taxAgentId != null">
#{taxAgentId},
</if>
<if test="taxYearMonth != null">
#{taxYearMonth},
</if>
<if test="tenantKey != null">
#{tenantKey},
</if>
<if test="updateTime != null">
#{updateTime},
</if>
<if test="year != null">
#{year},
</if>
</trim>
</insert>
<!-- 更新,更新全部字段 -->
<update id="update" parameterType="com.engine.salary.entity.datacollection.AddUpSituation">
UPDATE hrsa_add_up_situation
<set>
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},
</set>
WHERE id = #{id} AND delete_type = 0
</update>
<!-- 更新不为NULL的字段 -->
<update id="updateIgnoreNull" parameterType="com.engine.salary.entity.datacollection.AddUpSituation">
UPDATE hrsa_add_up_situation
<set>
<if test="addUpAccumulationFundTotal != null">
add_up_accumulation_fund_total=#{addUpAccumulationFundTotal},
</if>
<if test="addUpAdvanceTax != null">
add_up_advance_tax=#{addUpAdvanceTax},
</if>
<if test="addUpAllowedDonation != null">
add_up_allowed_donation=#{addUpAllowedDonation},
</if>
<if test="addUpChildEducation != null">
add_up_child_education=#{addUpChildEducation},
</if>
<if test="addUpContinuingEducation != null">
add_up_continuing_education=#{addUpContinuingEducation},
</if>
<if test="addUpEnterpriseAndOther != null">
add_up_enterprise_and_other=#{addUpEnterpriseAndOther},
</if>
<if test="addUpHousingLoanInterest != null">
add_up_housing_loan_interest=#{addUpHousingLoanInterest},
</if>
<if test="addUpHousingRent != null">
add_up_housing_rent=#{addUpHousingRent},
</if>
<if test="addUpIncome != null">
add_up_income=#{addUpIncome},
</if>
<if test="addUpOtherDeduction != null">
add_up_other_deduction=#{addUpOtherDeduction},
</if>
<if test="addUpSocialSecurityTotal != null">
add_up_social_security_total=#{addUpSocialSecurityTotal},
</if>
<if test="addUpSubtraction != null">
add_up_subtraction=#{addUpSubtraction},
</if>
<if test="addUpSupportElderly != null">
add_up_support_elderly=#{addUpSupportElderly},
</if>
<if test="addUpTaxExemptIncome != null">
add_up_tax_exempt_income=#{addUpTaxExemptIncome},
</if>
<if test="createTime != null">
create_time=#{createTime},
</if>
<if test="creator != null">
creator=#{creator},
</if>
<if test="deleteType != null">
delete_type=#{deleteType},
</if>
<if test="employeeId != null">
employee_id=#{employeeId},
</if>
<if test="taxAgentId != null">
tax_agent_id=#{taxAgentId},
</if>
<if test="taxYearMonth != null">
tax_year_month=#{taxYearMonth},
</if>
<if test="tenantKey != null">
tenant_key=#{tenantKey},
</if>
<if test="updateTime != null">
update_time=#{updateTime},
</if>
<if test="year != null">
year=#{year},
</if>
</set>
WHERE id = #{id} AND delete_type = 0
</update>
<!-- 根据主键删除记录 -->
<delete id="delete" parameterType="com.engine.salary.entity.datacollection.AddUpSituation">
UPDATE hrsa_add_up_situation
SET delete_type=1
WHERE id = #{id}
AND delete_type = 0
</delete>
</mapper>

View File

@ -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<String,Object> error = null;
private List<Map<String, Object>> errorInfo = new ArrayList<>();
//标准模板字段名称
private List<String> 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<String> tempField = new ArrayList<>(Arrays.asList("workcode", "lastname", "loginid", "verificationType", "verificationId", "month", "childEdu", "loan", "rent", "supportParent", "edu"));
//必填列
private List<String> requireField = new ArrayList<>(Arrays.asList("month"));
//列序号
private List<Integer> fieldIndex = new ArrayList<>();
//需要导入的数据
private List<Map<String, Object>> 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<String, Object> generateErrMsg(String msg){
error = new HashMap<String,Object>();
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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> params = new HashMap<String, Object>();
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<String, Object> params = new HashMap<String, Object>();
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<String, Object> init(HttpServletRequest request){
Map<String, Object> retmap = new HashMap<String, Object>();
try {
ImportLogService importLogService = (ImportLogService) ServiceUtil.getService(ImportLogServiceImpl.class, user);
Map<String, Object> 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<String, Object> params = new HashMap<String, Object>();
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;
}
}

View File

@ -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<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;
}
}

View File

@ -0,0 +1,9 @@
package com.engine.salary.service;
import java.util.Map;
public interface AddUpDeductionService {
Map<String, Object> list(Map<String, Object> params);
}

View File

@ -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<String, Object> list(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionListCmd(params,user));
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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 解析工具类
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @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 <T> List<T> parse(MultipartFile file, Class<T> clazz, int sheetIndex, int rowIndex, int standardCellNum) {
List<List<String>> result = parse(file, sheetIndex, rowIndex, standardCellNum);
List<T> list = new ArrayList<T>();
for (List<String> rowDatas : result) {
T t = setField(clazz, rowDatas);
list.add(t);
}
return list;
}
/**
* <strong>获取excel数据</strong>
*
* @param file 文件
* @param sheetIndex 解析第几个sheet
* @param rowIndex 从第几行开始解析第一行为 0依次类推
* @return 二维数据集合
*/
private static List<List<String>> 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<List<String>> result = new ArrayList<List<String>>();
for (; rowIndex < rowCount; rowIndex++) {
List<String> cellResult = new ArrayList<String>();
for (int j = 0; j < cellCount; j++) {
cellResult.add(ExcelSupport.getCellValue(sheet, rowIndex, j));
}
result.add(cellResult);
}
return result;
}
/**
* 为对象的每一个属性赋值
*
* @param clazz
* @param rowDatas
* @param <T>
* @return
*/
private static <T> T setField(Class<T> clazz, List<String> 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);
}
}
/**
* <strong>获取javaBean属性值</strong>
*
* @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;
}
}

View File

@ -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中数据格式错误而造成的解析异常时提示的错误信息
}

View File

@ -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);
}
}

View File

@ -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<String, Object> map = ParamUtil.request2Map(request);
map.put("queryParam", queryParam);
return ResponseResult.run(getService(user)::list, map);
}
// /**
// * 下载导入模板
// * @return
// */
// @POST()
// @Path("/downloadTemplate")
// @ApiOperation("下载导入模板")
// @WeaPermission
// public WeaResult<Map<String, Object>> 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<Map<String, Object>> export(@RequestBody AddUpDeductionQueryParam queryParam) {
// return WeaResult.success(service.export(queryParam, UserContext.getCurrentEmployeeId(), TenantContext.getCurrentTenantKey()));
// }
}

View File

@ -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<String,Object> getRequestParams(HttpServletRequest request, HttpServletResponse response){
Map<String, Object> params = new HashMap<String, Object>();
Enumeration<String> em = request.getParameterNames();
while(em.hasMoreElements()){
String paramname = em.nextElement();
params.put(paramname, request.getParameter(paramname));
}
return params;
}
}