jz.kai vor 5 Jahren
Ursprung
Commit
730d971e7c

+ 158 - 163
src/main/java/com/jpsoft/smart/modules/base/controller/PersonInfoController.java

@@ -1,6 +1,10 @@
 package com.jpsoft.smart.modules.base.controller;
 
 import com.github.pagehelper.Page;
+import com.jpsoft.smart.config.OSSConfig;
+import com.jpsoft.smart.modules.common.utils.CheckIdCard;
+import com.jpsoft.smart.modules.common.utils.OSSUtil;
+import com.jpsoft.smart.modules.common.utils.POIUtils;
 import com.jpsoft.smart.modules.common.utils.PojoUtils;
 import com.jpsoft.smart.modules.common.dto.Sort;
 import com.jpsoft.smart.modules.common.dto.MessageResult;
@@ -13,6 +17,8 @@ import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Sheet;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -31,6 +37,8 @@ import java.util.*;
 public class PersonInfoController {
     private Logger logger = LoggerFactory.getLogger(getClass());
 
+    @Autowired
+    private OSSConfig ossConfig;
     @Autowired
     private PersonInfoService personInfoService;
     @Autowired
@@ -382,167 +390,154 @@ public class PersonInfoController {
         return msgResult;
     }
 
-//    @ApiOperation(value="导入企业人员")
-//    @PostMapping("importXls")
-//    @ApiImplicitParams({
-//            @ApiImplicitParam(name = "companyId",value = "企业ID", required = true, paramType = "form",dataType = "String"),
-//            @ApiImplicitParam(name = "uploadFile",value = "上传文件", required = true,paramType="form", dataType = "__file")
-//    })
-//    public MessageResult<String> importXls(@RequestParam(value="companyId",defaultValue="") String companyId,
-//                                           MultipartFile uploadFile,
-//                                           @RequestAttribute String subject){
-//        User user = userService.get(subject);
-//
-//        MessageResult<String> msgResult = new MessageResult<>();
-//        PersonInfo personInfo = new PersonInfo();
-//
-//        try {
-//            POIUtils poiUtils = new POIUtils(uploadFile.getInputStream());
-//            int sheetIndex = 0;
-//            Sheet sheet1 = poiUtils.getSheetAt(sheetIndex);
-//
-//            int affectCount = 0;
-//            int failCount = 0;
-//            int validateColIndex = 7;
-//
-//            for(int rowIndex=1 ; rowIndex<=sheet1.getLastRowNum(); rowIndex++){
-//                try {
-//                    String name = (String)poiUtils.getCellValue(sheetIndex,rowIndex,1);
-//                    String cardType = (String)poiUtils.getCellValue(sheetIndex,rowIndex,2);
-//                    String cardNo = (String)poiUtils.getCellValue(sheetIndex,rowIndex,3);
-//                    String sex = (String)poiUtils.getCellValue(sheetIndex,rowIndex,4);
-////                  String age = array[5].toString();
-//                    String jobName = (String)poiUtils.getCellValue(sheetIndex,rowIndex,5);
-//                    String healthStatus = (String)poiUtils.getCellValue(sheetIndex,rowIndex,6);
-//
-//                    if(StringUtils.isEmpty(name)){
-//                        break;
-//                    }
-//
-//                    Map<String, Object> searchParams = new HashMap<>();
-//                    searchParams.put("companyId", company.getId());
-//                    searchParams.put("cardNo", cardNo);
-//                    searchParams.put("delFlag", false);
-//
-//                    List<Sort> sortList = new ArrayList<>();
-//                    Page<CompanyMember> page = companyMemberService.pageSearch(searchParams, 1, 100, sortList);
-//
-//                    if (page.size() > 0) {
-//                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证已导入!");
-//                        failCount++;
-//                        continue;
-//                    } else {
-//                        companyMember.setId(UUID.randomUUID().toString());
-//                        if (StringUtils.isNotEmpty(company.getId())) companyMember.setCompanyId(company.getId());
-//                        if (StringUtils.isNotEmpty(name)) companyMember.setName(name);
-//
-//                        CheckIdCard cic = null;
-//
-//                        if(StringUtils.isEmpty(cardNo)){
-//                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证不能为空!");
-//                            failCount++;
-//                            continue;
-//                        }
-//                        else{
-//                            cardNo = cardNo.trim().toUpperCase();
-//                        }
-//
-//                        for(DataDictionary dd : ddList){
-//                            if(dd.getName().equals(cardType)) {
-//                                companyMember.setCardType(dd.getValue());
-//                                break;
-//                            }
-//                        }
-//
-//                        if (StringUtils.isEmpty(companyMember.getCardType())){
-//                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("证件类型未选择!");
-//                            failCount++;
-//                            continue;
-//                        }
-//
-//                        if (cardType.contains("身份证")) {
-//                            cic = new CheckIdCard(cardNo);
-//
-//                            if (!cic.validate()){
-//                                sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证验证失败!");
-//                                failCount++;
-//
-//                                continue;
-//                            }
-//                        }
-//
-//                        companyMember.setCardNo(cardNo);
-//
-//                        List<Jobs> jobsList = jobsService.findByName(jobsName);
-//
-//                        if (jobsList.size() > 0) {
-//                            companyMember.setJobsId(jobsList.get(0).getId());
-//                        }
-//
-//                        if (StringUtils.isNotEmpty(healthStatus)) companyMember.setHealthStatus(healthStatus);
-//
-//                        companyMember.setStatus("0");
-//                        companyMember.setDelFlag(false);
-//                        companyMember.setCreateBy(principal.getName());
-//                        companyMember.setCreateTime(new Date());
-//
-//                        if (companyMemberService.insert(companyMember) > 0) {
-//                            affectCount++;
-//                        }
-//                    }
-//                }
-//                catch(Exception innerEx){
-//                    logger.error(innerEx.getMessage(),innerEx);
-//                }
-//            }
-//
-//            if (failCount>0){
-//                //有导入失败的记录
-//                msgResult.setResult(false);
-//                msgResult.setMessage("数据成功导入" + affectCount + "条,有" + failCount + "条数据未导入成功,错误原因请查看报表。");
-//
-//                //todo 只保留错误数据的sheet
-//                int rowIndex = 1;
-//
-//                while(rowIndex<= sheet1.getLastRowNum()){
-//                    Cell cell = sheet1.getRow(rowIndex).getCell(validateColIndex);
-//
-//                    if (cell==null || StringUtils.isEmpty(cell.getStringCellValue())){
-//                        sheet1.removeRow(sheet1.getRow(rowIndex));
-//
-//                        if (rowIndex<sheet1.getLastRowNum()) {
-//                            sheet1.shiftRows(rowIndex + 1, sheet1.getLastRowNum(), -1); //删除后下面行上移,则不需要移动rowIndex
-//                        }
-//                    }
-//                    else {
-//                        rowIndex++;
-//                    }
-//                }
-//
-//                //todo 将wb保存到oss
-//                ByteArrayOutputStream output = new ByteArrayOutputStream();
-//                poiUtils.getWorkbook().write(output);
-//
-//                byte[] buffer = output.toByteArray();
-//                ByteArrayInputStream input = new ByteArrayInputStream(buffer);
-//
-//                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);
-//
-//                //todo 返回导入失败报表下载链接
-//                msgResult.setData(downloadUrl);
-//            }
-//            else{
-//                msgResult.setResult(true);
-//                msgResult.setMessage("数据成功导入" + affectCount + "条");
-//            }
-//        }
-//        catch(Exception ex){
-//            logger.error(ex.getMessage(),ex);
-//
-//            msgResult.setResult(false);
-//            msgResult.setMessage(ex.getMessage());
-//        }
-//
-//        return msgResult;
-//    }
+    @ApiOperation(value="导入人员(非企业账户需要输入企业ID)")
+    @PostMapping("importXls")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "companyId",value = "企业ID", required = false, paramType = "form",dataType = "String"),
+            @ApiImplicitParam(name = "uploadFile",value = "上传文件", required = true,paramType="form", dataType = "__file")
+    })
+    public MessageResult<String> importXls(@RequestParam(value="companyId",defaultValue="") String companyId,
+                                           MultipartFile uploadFile,
+                                           @RequestAttribute String subject){
+        User user = userService.get(subject);
+        if(StringUtils.isEmpty(companyId)){
+            companyId = user.getCompanyId();
+        }
+
+        MessageResult<String> msgResult = new MessageResult<>();
+        PersonInfo personInfo = new PersonInfo();
+
+        try {
+            POIUtils poiUtils = new POIUtils(uploadFile.getInputStream());
+            int sheetIndex = 0;
+            Sheet sheet1 = poiUtils.getSheetAt(sheetIndex);
+
+            int affectCount = 0;
+            int failCount = 0;
+            int validateColIndex = 7;
+
+            for(int rowIndex=1 ; rowIndex<=sheet1.getLastRowNum(); rowIndex++){
+                try {
+                    String name = (String)poiUtils.getCellValue(sheetIndex,rowIndex,1);
+                    String idCard = (String)poiUtils.getCellValue(sheetIndex,rowIndex,2);
+                    String phone = (String)poiUtils.getCellValue(sheetIndex,rowIndex,3);
+                    String position1 = (String)poiUtils.getCellValue(sheetIndex,rowIndex,4);
+                    String position2 = (String)poiUtils.getCellValue(sheetIndex,rowIndex,5);
+                    String position3 = (String)poiUtils.getCellValue(sheetIndex,rowIndex,6);
+                    String position4 = (String)poiUtils.getCellValue(sheetIndex,rowIndex,7);
+                    String position5 = (String)poiUtils.getCellValue(sheetIndex,rowIndex,8);
+                    String enabledFace = (String)poiUtils.getCellValue(sheetIndex,rowIndex,9);
+                    String enabledCard = (String)poiUtils.getCellValue(sheetIndex,rowIndex,10);
+                    String enabledApp = (String)poiUtils.getCellValue(sheetIndex,rowIndex,11);
+                    String enabledGuest = (String)poiUtils.getCellValue(sheetIndex,rowIndex,12);
+
+                    if(StringUtils.isEmpty(name)){
+                        break;
+                    }
+
+                    Map<String, Object> searchParams = new HashMap<>();
+                    searchParams.put("companyId", companyId);
+                    searchParams.put("idCard", idCard);
+                    List<Sort> sortList = new ArrayList<>();
+                    Page<PersonInfo> page = personInfoService.pageSearch(searchParams, 1, 1,false, sortList);
+
+                    if (page.size() > 0) {
+                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证已导入!");
+                        failCount++;
+                        continue;
+                    } else {
+                        personInfo.setCompanyId(companyId);
+                        personInfo.setName(name);
+
+                        CheckIdCard cic = null;
+                        if(StringUtils.isEmpty(idCard)){
+                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证不能为空!");
+                            failCount++;
+                            continue;
+                        }
+                        else{
+                            idCard = idCard.trim().toUpperCase();
+                        }
+
+                        cic = new CheckIdCard(idCard);
+                        if (!cic.validate()){
+                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证验证失败!");
+                            failCount++;
+                            continue;
+                        }
+
+                        personInfo.setIdCard(idCard);
+                        personInfo.setPhone(phone);
+                        personInfo.setPosition1(position1);
+                        personInfo.setPosition2(position2);
+                        personInfo.setPosition3(position3);
+                        personInfo.setPosition4(position4);
+                        personInfo.setPosition5(position5);
+                        personInfo.setFaceEnabled(Boolean.valueOf(enabledFace));
+                        personInfo.setCardEnabled(Boolean.valueOf(enabledCard));
+                        personInfo.setAppEnabled(Boolean.valueOf(enabledApp));
+                        personInfo.setGuestEnabled(Boolean.valueOf(enabledGuest));
+                        personInfo.setDelFlag(false);
+                        personInfo.setCreateBy(subject);
+                        personInfo.setCreateTime(new Date());
+
+                        if (personInfoService.insert(personInfo) > 0) {
+                            affectCount++;
+                        }
+                    }
+                }
+                catch(Exception innerEx){
+                    logger.error(innerEx.getMessage(),innerEx);
+                }
+            }
+
+            if (failCount>0){
+                //有导入失败的记录
+                msgResult.setResult(false);
+                msgResult.setMessage("数据成功导入" + affectCount + "条,有" + failCount + "条数据未导入成功,错误原因请查看报表。");
+
+                //todo 只保留错误数据的sheet
+                int rowIndex = 1;
+
+                while(rowIndex<= sheet1.getLastRowNum()){
+                    Cell cell = sheet1.getRow(rowIndex).getCell(validateColIndex);
+
+                    if (cell==null || StringUtils.isEmpty(cell.getStringCellValue())){
+                        sheet1.removeRow(sheet1.getRow(rowIndex));
+
+                        if (rowIndex<sheet1.getLastRowNum()) {
+                            sheet1.shiftRows(rowIndex + 1, sheet1.getLastRowNum(), -1); //删除后下面行上移,则不需要移动rowIndex
+                        }
+                    }
+                    else {
+                        rowIndex++;
+                    }
+                }
+
+                //todo 将wb保存到oss
+                ByteArrayOutputStream output = new ByteArrayOutputStream();
+                poiUtils.getWorkbook().write(output);
+
+                byte[] buffer = output.toByteArray();
+                ByteArrayInputStream input = new ByteArrayInputStream(buffer);
+
+                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);
+
+                //todo 返回导入失败报表下载链接
+                msgResult.setData(downloadUrl);
+            }
+            else{
+                msgResult.setResult(true);
+                msgResult.setMessage("数据成功导入" + affectCount + "条");
+            }
+        }
+        catch(Exception ex){
+            logger.error(ex.getMessage(),ex);
+
+            msgResult.setResult(false);
+            msgResult.setMessage(ex.getMessage());
+        }
+
+        return msgResult;
+    }
 }

+ 198 - 0
src/main/java/com/jpsoft/smart/modules/common/utils/CheckIdCard.java

@@ -0,0 +1,198 @@
+package com.jpsoft.smart.modules.common.utils;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+/**
+ * 验证身份证号码 身份证号码, 可以解析身份证号码的各个字段,以及验证身份证号码是否有效; 身份证号码构成:6位地址编码+8位生日+3位顺序码+1位校验码
+ * 
+ * @ClassName: CheckIdCard
+ * @Description: TODO
+ * @author suncy
+ * @date 2013-1-4 上午11:06:09
+ * 
+ */
+public class CheckIdCard {
+	private String cardNumber; // 完整的身份证号码
+	private Boolean cacheValidateResult = null; // 缓存身份证是否有效,因为验证有效性使用频繁且计算复杂
+	private Date cacheBirthDate = null; // 缓存出生日期,因为出生日期使用频繁且计算复杂
+	private final static String BIRTH_DATE_FORMAT = "yyyyMMdd"; // 身份证号码中的出生日期的格式
+	private final static Date MINIMAL_BIRTH_DATE = new Date(-2209017600000L); // 身份证的最小出生日期,1900年1月1日
+	private final static int NEW_CARD_NUMBER_LENGTH = 18;
+	private final static int OLD_CARD_NUMBER_LENGTH = 15;
+	private final static char[] VERIFY_CODE = { '1', '0', 'X', '9', '8', '7',
+			'6', '5', '4', '3', '2' }; // 18位身份证中最后一位校验码
+	private final static int[] VERIFY_CODE_WEIGHT = { 7, 9, 10, 5, 8, 4, 2, 1,
+			6, 3, 7, 9, 10, 5, 8, 4, 2 };// 18位身份证中,各个数字的生成校验码时的权值
+
+	public boolean validate() {
+		if (null == cacheValidateResult) {
+			boolean result = true;
+			result = result && (null != cardNumber); // 身份证号不能为空
+			result = result && NEW_CARD_NUMBER_LENGTH == cardNumber.length(); // 身份证号长度是18(新证)
+			// 身份证号的前17位必须是阿拉伯数字
+			for (int i = 0; result && i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
+				char ch = cardNumber.charAt(i);
+				result = result && ch >= '0' && ch <= '9';
+			}
+			// 身份证号的第18位校验正确
+			result = result
+					&& (calculateVerifyCode(cardNumber) == cardNumber
+							.charAt(NEW_CARD_NUMBER_LENGTH - 1));
+			// 出生日期不能晚于当前时间,并且不能早于1900年
+			try {
+				Date birthDate = this.getBirthDate();
+				result = result && null != birthDate;
+				result = result && birthDate.before(new Date());
+				result = result && birthDate.after(MINIMAL_BIRTH_DATE);
+				/**
+				 * 出生日期中的年、月、日必须正确,比如月份范围是[1,12],日期范围是[1,31],还需要校验闰年、大月、小月的情况时,
+				 * 月份和日期相符合
+				 */
+				String birthdayPart = this.getBirthDayPart();
+				String realBirthdayPart = this.createBirthDateParser().format(
+						birthDate);
+				result = result && (birthdayPart.equals(realBirthdayPart));
+			} catch (Exception e) {
+				result = false;
+			}
+			cacheValidateResult = Boolean.valueOf(result);// TODO
+			// 完整身份证号码的省市县区检验规则
+		}
+		return cacheValidateResult;
+	}
+
+	/**
+	 * 如果是15位身份证号码,则自动转换为18位
+	 * 
+	 * @param cardNumber
+	 * @return
+	 */
+	public CheckIdCard(String cardNumber) {
+		if (null != cardNumber) {
+			cardNumber = cardNumber.trim();
+			if (OLD_CARD_NUMBER_LENGTH == cardNumber.length()) {
+				cardNumber = contertToNewCardNumber(cardNumber);
+			}
+		}
+		this.cardNumber = cardNumber;
+	}
+
+	public String getCardNumber() {
+		return cardNumber;
+	}
+
+	public String getAddressCode() {
+		this.checkIfValid();
+		return this.cardNumber.substring(0, 6);
+	}
+
+	public Date getBirthDate() {
+		if (null == this.cacheBirthDate) {
+			try {
+				this.cacheBirthDate = this.createBirthDateParser().parse(
+						this.getBirthDayPart());
+			} catch (Exception e) {
+				throw new RuntimeException("身份证的出生日期无效");
+			}
+		}
+		return new Date(this.cacheBirthDate.getTime());
+	}
+
+	public boolean isMale() {
+		return 1 == this.getGenderCode();
+	}
+
+	public boolean isFemal() {
+		return false == this.isMale();
+	}
+
+	/**
+	 * 获取身份证的第17位,奇数为男性,偶数为女性
+	 * 
+	 * @return
+	 */
+	private int getGenderCode() {
+		this.checkIfValid();
+		char genderCode = this.cardNumber.charAt(NEW_CARD_NUMBER_LENGTH - 2);
+		return (((int) (genderCode - '0')) & 0x1);
+	}
+
+	private String getBirthDayPart() {
+		return this.cardNumber.substring(6, 14);
+	}
+
+	private SimpleDateFormat createBirthDateParser() {
+		return new SimpleDateFormat(BIRTH_DATE_FORMAT);
+	}
+
+	private void checkIfValid() {
+		if (false == this.validate()) {
+			throw new RuntimeException("身份证号码不正确!");
+		}
+	}
+
+	/**
+	 * 校验码(第十八位数):
+	 * 
+	 * 十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0...16 ,先对前17位数字的权求和;
+	 * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
+	 * 2; 计算模 Y = mod(S, 11)< 通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9
+	 * 8 7 6 5 4 3 2
+	 * 
+	 * @param cardNumber
+	 * @return
+	 */
+	private static char calculateVerifyCode(CharSequence cardNumber) {
+		int sum = 0;
+		for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
+			char ch = cardNumber.charAt(i);
+			sum += ((int) (ch - '0')) * VERIFY_CODE_WEIGHT[i];
+		}
+		return VERIFY_CODE[sum % 11];
+	}
+	
+	/**  
+     * 获取年龄
+     */    
+    public Integer getAge() {    
+        try {    
+            boolean validateAccess = validate();    
+            if (validateAccess) {
+                // 获取出生日期    
+                Date birthdate = getBirthDate();    
+                GregorianCalendar currentDay = new GregorianCalendar();
+                currentDay.setTime(birthdate);    
+                int year = currentDay.get(Calendar.YEAR);
+                //获取年龄  
+                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy");
+                String nowYear=simpleDateFormat.format(new Date());  
+                return Integer.parseInt(nowYear)-year;     
+            }else{
+            	return null;
+            }
+        } catch (Exception e) {    
+            return null; 
+        }    
+    }    
+
+	/**
+	 * 把15位身份证号码转换到18位身份证号码<br>
+	 * 15位身份证号码与18位身份证号码的区别为:<br>
+	 * 1、15位身份证号码中,"出生年份"字段是2位,转换时需要补入"19",表示20世纪<br>
+	 * 2、15位身份证无最后一位校验码。18位身份证中,校验码根据根据前17位生成
+	 * 
+	 * @param oldCardNumber
+	 * @return
+	 */
+	private static String contertToNewCardNumber(String oldCardNumber) {
+		StringBuilder buf = new StringBuilder(NEW_CARD_NUMBER_LENGTH);
+		buf.append(oldCardNumber.substring(0, 6));
+		buf.append("19");
+		buf.append(oldCardNumber.substring(6));
+		buf.append(CheckIdCard.calculateVerifyCode(buf));
+		return buf.toString();
+	}
+}