Browse Source

联系人导入导出1

yusm 1 year ago
parent
commit
cd19d59437

+ 11 - 0
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/controller/ContactsController.java

@@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
@@ -123,6 +124,16 @@ public class ContactsController {
         return contactsService.getContactsDetail(contacts,request);
     }
 
+    @RequestMapping("importData")
+    public HttpRespMsg importData(MultipartFile multipartFile){
+        return contactsService.importData(multipartFile,request);
+    }
+
+    @RequestMapping("exportData")
+    public HttpRespMsg exportData(String customName, String name, String email,String creatorName, String phone, String ownerName) throws Exception {
+        return contactsService.exportData(customName,name,email,creatorName,phone,ownerName,request);
+    }
+
 
 
 

+ 5 - 0
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/ContactsService.java

@@ -4,6 +4,7 @@ import com.management.platform.entity.Contacts;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.management.platform.entity.Custom;
 import com.management.platform.util.HttpRespMsg;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletRequest;
 import java.util.List;
@@ -35,4 +36,8 @@ public interface ContactsService extends IService<Contacts> {
     HttpRespMsg returnContacts(List<Integer> ids);
 
     HttpRespMsg getContactsDetail(Contacts contacts,HttpServletRequest request);
+
+    HttpRespMsg importData(MultipartFile multipartFile, HttpServletRequest request);
+
+    HttpRespMsg exportData(String customName, String name, String email, String creatorName, String phone, String ownerName, HttpServletRequest request) throws Exception;
 }

+ 287 - 3
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/impl/ContactsServiceImpl.java

@@ -1,5 +1,8 @@
 package com.management.platform.service.impl;
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
@@ -9,18 +12,28 @@ import com.management.platform.entity.vo.ContactsVo;
 import com.management.platform.mapper.*;
 import com.management.platform.service.ContactsService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.management.platform.service.WxCorpInfoService;
+import com.management.platform.util.ExcelUtil;
 import com.management.platform.util.HttpRespMsg;
 import org.apache.commons.lang3.StringUtils;
+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.ss.usermodel.CellType;
 import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
+import java.io.*;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
 import java.time.LocalDateTime;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 import java.util.stream.Collectors;
 
 /**
@@ -52,6 +65,19 @@ public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts> i
     @Resource
     private ContactsDocumentMapper contactsDocumentMapper;
 
+    @Resource
+    private WxCorpInfoService wxCorpInfoService;
+    @Resource
+    private SysDictMapper sysDictMapper;
+
+    @Resource
+    private SysFormMapper sysFormMapper;
+    @Resource
+    private ExcelExportServiceImpl excelExportService;
+
+    @Value(value = "${upload.path}")
+    private String path;
+
 
     @Override
     @Transactional
@@ -276,6 +302,264 @@ public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts> i
         return msg;
     }
 
+    @Override
+    public HttpRespMsg importData(MultipartFile multipartFile, HttpServletRequest request) {
+        HttpRespMsg msg=new HttpRespMsg();
+        String fileName = multipartFile.getOriginalFilename();
+        File file = new File(fileName == null ? "file" : fileName);
+        User user = userMapper.selectById(request.getHeader("token"));
+        Integer companyId = user.getCompanyId();
+        WxCorpInfo wxCorpInfo = wxCorpInfoService.getOne(new LambdaQueryWrapper<WxCorpInfo>().eq(WxCorpInfo::getCompanyId, companyId));
+        List<Contacts> contactsList = contactsMapper.selectList(new LambdaQueryWrapper<Contacts>().eq(Contacts::getCompanyId, companyId));
+        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getCompanyId, companyId));
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+
+        try {
+            inputStream = multipartFile.getInputStream();
+            outputStream = new FileOutputStream(file);
+            byte[] buffer = new byte[4096];
+            int temp = 0;
+            while ((temp = inputStream.read(buffer, 0, 4096)) != -1) {
+                outputStream.write(buffer, 0, temp);
+            }
+            inputStream.close();
+            outputStream.close();
+
+            //解析表格
+            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
+            //我们只需要第一个sheet
+            HSSFSheet sheet = workbook.getSheetAt(0);
+            //由于第一行需要指明列对应的标题
+            int rowNum = sheet.getLastRowNum();
+            //获取当前表单模板 校验规则
+            SysForm sysForm = sysFormMapper.selectOne(new LambdaQueryWrapper<SysForm>().eq(SysForm::getCode, "Contacts").eq(SysForm::getCompanyId, companyId).eq(SysForm::getIsCurrent, 1));
+            if(sysForm==null){
+                msg.setError("当前模块未配置自定义模板,需先完成配置");
+                return msg;
+            }
+
+            String config = sysForm.getConfig();
+            JSONObject configOb = JSON.parseObject(config);
+            JSONArray configObJSONArray = configOb.getJSONArray("list");
+
+            List<Contacts>  importContactsList=new ArrayList<>();
+            List<String> userNameList=new ArrayList<>();
+            HttpRespMsg respMsg=new HttpRespMsg();
+
+            for (int rowIndex = 1; rowIndex <= rowNum; rowIndex++) {
+                HSSFRow row = sheet.getRow(rowIndex);
+                if (row == null) {
+                    continue;
+                }
+                //跳过空行
+                if (ExcelUtil.isRowEmpty(row)) {
+                    continue;
+                }
+                //获取到当前行的列数据
+                int cellNum = row.getLastCellNum();
+
+                for (int i = 0; i < cellNum; i++) {
+                    JSONObject item = configObJSONArray.getJSONObject(i);
+                    String modelName = item.getString("model");
+                    HSSFCell cell = row.getCell(i);
+                    if(cell!=null){
+                        switch (item.getString("type")){
+                            case "time":cell.setCellType(CellType.NUMERIC);
+                                break;
+                            case "int":cell.setCellType(CellType.NUMERIC);
+                                break;
+                            default:cell.setCellType(CellType.STRING);
+                        }
+                    }
+                    if(modelName.equals("inchargerId")){
+                        if(!org.springframework.util.StringUtils.isEmpty(cell.getStringCellValue())){
+                            userNameList.add(cell.getStringCellValue());
+                        }
+                    }
+
+                }
+            }
+
+            System.out.println("参与搜素的人员列表"+userNameList + userNameList.size());
+            if(wxCorpInfo!=null&&wxCorpInfo.getSaasSyncContact()==1&&userNameList.size()>0){
+                respMsg = wxCorpInfoService.getBatchSearchUserInfo(wxCorpInfo, userNameList,null);
+                if(respMsg.code.equals("0")){
+                    msg.setError("姓名为["+String.valueOf(respMsg.data)+"]的人员存在重复,请使用工号!");
+                    return msg;
+                }
+            }
+            List<User> targetUserList= (List<User>) respMsg.data;
+
+            for (int rowIndex = 1; rowIndex <= rowNum; rowIndex++) {
+                HSSFRow row = sheet.getRow(rowIndex);
+                if (row == null) {
+                    continue;
+                }
+                //跳过空行
+                if (ExcelUtil.isRowEmpty(row)) {
+                    continue;
+                }
+                //获取到当前行的列数据
+                int cellNum = row.getLastCellNum();
+                Contacts contacts=new Contacts();
+                contacts.setCompanyId(companyId);
+                contacts.setCreatorId(user.getId());
+                for (int i = 0; i < cellNum; i++) {
+                    JSONObject item = configObJSONArray.getJSONObject(i);
+                    String modelName = item.getString("model");
+                    String className = modelName.substring(0, 1).toUpperCase() + modelName.substring(1);
+                    String getter="get"+className;
+                    String setter="set"+className;
+                    HSSFCell cell = row.getCell(i);
+                    if(cell!=null){
+                        switch (item.getString("type")){
+                            case "time":cell.setCellType(CellType.NUMERIC);
+                                break;
+                            case "int":cell.setCellType(CellType.NUMERIC);
+                                break;
+                            default:cell.setCellType(CellType.STRING);
+                        }
+                    }
+                    Class<Contacts> contactsClass = Contacts.class;
+                    Field field = contactsClass.getDeclaredField(modelName);
+                    Class<?> type = field.getType();
+                    Method method = contactsClass.getMethod(setter, type);
+                    //校验当前列是否为必填
+                    JSONObject options = item.getJSONObject("options");
+                    JSONObject rules = options.getJSONObject("rules");
+                    Boolean required = rules.getBoolean("required");
+                    if(required){
+                        if(StringUtils.isEmpty(cell.getStringCellValue())){
+                            msg.setError(item.getString("label")+"值不能为空值");
+                            return msg;
+                        }
+                    }
+                    /*if(modelName.equals("contactsCode")){
+                        if(!org.springframework.util.StringUtils.isEmpty(cell.getStringCellValue())){
+                            //系统中同公司已存在的产品编码 更新
+                            Optional<Contacts> first = contactsList.stream().filter(p ->p.getContactsCode()!=null&& p.getContactsCode().equals(cell.getStringCellValue())).findFirst();
+                            if(first.isPresent()){
+                                contacts.setId(first.get().getId());
+                            }
+                        }
+                    }*/
+                    if(modelName.equals("inchargerId")){
+                        if(!StringUtils.isEmpty(cell.getStringCellValue())){
+                            String userName = cell.getStringCellValue();
+                            Optional<User> first;
+                            if(wxCorpInfo!=null&&wxCorpInfo.getSaasSyncContact()==1){
+                                Optional<User> optional = targetUserList.stream().filter(tl -> tl.getName().equals(userName)).findFirst();
+                                first= userList.stream().filter(u ->(u.getJobNumber()!=null&&u.getJobNumber().equals(userName))||(optional.isPresent()&&u.getCorpwxUserid()!=null&&u.getCorpwxUserid().equals(optional.get().getCorpwxUserid()))).findFirst();
+                            }else {
+                                first= userList.stream().filter(u -> u.getName().equals(userName)||(u.getJobNumber()!=null&&u.getJobNumber().equals(userName))).findFirst();
+                            }
+                            if (first.isPresent()) {
+                                contacts.setOwnerId(first.get().getId());
+                            } else {
+                                throw new Exception("["+userName+"]在系统中不存在");
+                            }
+                        }
+                    }
+                    /*if(cell.getCellType()==CellType.STRING.getCode()&&!StringUtils.isEmpty(cell.getStringCellValue())){
+                        method.invoke(contacts,cell.getStringCellValue());
+                    } else if (cell.getCellType()==CellType.NUMERIC.getCode()) {
+
+
+                    }*/
+                    if (cell != null && cell.getCellTypeEnum() != CellType.BLANK) {
+                        if (cell.getCellTypeEnum() == CellType.STRING && cell.getStringCellValue() != null && !cell.getStringCellValue().isEmpty()) {
+                            // 字符串类型不为空
+                            method.invoke(contacts,cell.getStringCellValue());
+                        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
+                            // 数值类型不为空
+                            double numericCellValue = cell.getNumericCellValue();
+                            if (type.getSimpleName().equals("Integer")){
+                                int intValue = (int) numericCellValue;
+                                method.invoke(contacts,intValue);
+                            }
+                            else {
+                                method.invoke(contacts, numericCellValue);
+                            }
+                        }
+                    }
+
+                }
+                importContactsList.add(contacts);
+            }
+
+            if(importContactsList.size()>0){
+                if(!saveOrUpdateBatch(importContactsList)){
+                    msg.setError("验证失败");
+                    return msg;
+                }
+            }
+
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+
+    return msg;
+    }
+
+    @Override
+    public HttpRespMsg exportData(String customName, String name, String email, String creatorName, String phone, String ownerName, HttpServletRequest request)  throws Exception{
+
+        User user = userMapper.selectById(request.getHeader("token"));
+        SysForm sysForm = sysFormMapper.selectOne(new LambdaQueryWrapper<SysForm>().eq(SysForm::getCompanyId, user.getCompanyId()).eq(SysForm::getCode, "Contacts").eq(SysForm::getIsCurrent, 1));
+        WxCorpInfo wxCorpInfo = wxCorpInfoService.getOne(new LambdaQueryWrapper<WxCorpInfo>().eq(WxCorpInfo::getCompanyId, user.getCompanyId()));
+        String config = sysForm.getConfig();
+        JSONObject configOb = JSON.parseObject(config);
+        JSONArray configObJSONArray = configOb.getJSONArray("list");
+        List<List<String>> dataList=new ArrayList<>();
+        List<String> titleList=new ArrayList<>();
+        for (int i = 0; i < configObJSONArray.size(); i++) {
+            JSONObject item = configObJSONArray.getJSONObject(i);
+            titleList.add(item.getString("label"));
+        }
+        dataList.add(titleList);
+
+        Map<String, Object> map = new HashMap<>();
+        map.put("customName", customName);
+        map.put("name", name);
+        map.put("phone", phone);
+        map.put("ownerName", ownerName);
+        map.put("email", email);
+        map.put("creatorName", creatorName);
+        Page<ContactsVo> pageContacts = contactsMapper.pageContacts(new Page<>(-1,-1), map);
+        List<ContactsVo> records = pageContacts.getRecords();
+
+        for (ContactsVo contactsVo : records) {
+            List<String> item=new ArrayList<>();
+            for (int i = 0; i < configObJSONArray.size(); i++) {
+                JSONObject target = configObJSONArray.getJSONObject(i);
+                String model = target.getString("model");
+                String targetName = model.substring(0, 1).toUpperCase() + model.substring(1);
+                Class<? extends ContactsVo> aClass = contactsVo.getClass();
+                String value="";
+//                String value = String.valueOf(aClass.getMethod("get" + targetName).invoke(contactsVo)==null?"":aClass.getMethod("get" + targetName).invoke(contactsVo));
+                /*if(model.equals("inchargerId")){
+                    if(wxCorpInfo!=null&&wxCorpInfo.getSaasSyncContact()==1){
+                        value = "$userName"+String.valueOf(aClass.getMethod("getInchargerName").invoke(product))+"$";
+                    }else {
+                        value = String.valueOf(aClass.getMethod("getInchargerName").invoke(product));
+                    }
+                }*/
+                if(model.equals("sex")){
+                    value = String.valueOf(aClass.getMethod("getSex").invoke(contactsVo));
+                }
+                if(model.equals("name")){
+                    value = String.valueOf(aClass.getMethod("getName").invoke(contactsVo));
+                }
+                item.add(value);
+            }
+            dataList.add(item);
+        }
+        String fileName="联系人表导出_"+ System.currentTimeMillis();
+        return excelExportService.exportGeneralExcelByTitleAndList(wxCorpInfo,fileName,dataList,path);
+    }
 
 
 }