Ver Fonte

客户管家 自定义下载模板 导入

Min há 1 ano atrás
pai
commit
767ac36cdd

+ 13 - 11
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/controller/ProductController.java

@@ -2,12 +2,16 @@ package com.management.platform.controller;
 
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.management.platform.entity.Product;
-import com.management.platform.entity.Task;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.management.platform.entity.*;
 import com.management.platform.mapper.UserMapper;
 import com.management.platform.service.ProductService;
 import com.management.platform.service.TaskService;
 import com.management.platform.util.HttpRespMsg;
+import com.management.platform.util.MessageUtils;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddressList;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 import org.springframework.web.bind.annotation.RestController;
@@ -15,6 +19,11 @@ import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
 
 /**
  * <p>
@@ -80,16 +89,9 @@ public class ProductController {
         return msg;
     }
 
-    @RequestMapping("/getTemplate")
-    public HttpRespMsg getTemplate(Integer id){
-        HttpRespMsg msg=new HttpRespMsg();
-        return msg;
-    }
-
     @RequestMapping("/importData")
-    public HttpRespMsg importData(MultipartFile file){
-        HttpRespMsg msg=new HttpRespMsg();
-        return msg;
+    public HttpRespMsg importData(MultipartFile multipartFile){
+        return productService.importData(multipartFile);
     }
 
 }

+ 5 - 0
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/controller/SysFormController.java

@@ -82,5 +82,10 @@ public class SysFormController {
         }
         return msg;
     }
+
+    @RequestMapping("/getExportTemplate")
+    public HttpRespMsg getExportTemplate(String code){
+        return sysFormService.getExportTemplate(code);
+    }
 }
 

+ 3 - 3
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/entity/Product.java

@@ -17,7 +17,7 @@ import lombok.experimental.Accessors;
  * </p>
  *
  * @author Seyason
- * @since 2024-02-28
+ * @since 2024-03-08
  */
 @Data
 @EqualsAndHashCode(callSuper = false)
@@ -119,8 +119,8 @@ public class Product extends Model<Product> {
     /**
      * 描述
      */
-    @TableField("desc")
-    private String desc;
+    @TableField("descs")
+    private String descs;
 
 
     @Override

+ 3 - 0
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/ProductService.java

@@ -3,6 +3,7 @@ package com.management.platform.service;
 import com.management.platform.entity.Product;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.management.platform.util.HttpRespMsg;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * <p>
@@ -15,4 +16,6 @@ import com.management.platform.util.HttpRespMsg;
 public interface ProductService extends IService<Product> {
 
     HttpRespMsg getList(Integer companyId,String userId, String productName, String productCode, Integer pageIndex, Integer pageSize);
+
+    HttpRespMsg importData(MultipartFile multipartFile);
 }

+ 2 - 0
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/SysFormService.java

@@ -2,6 +2,7 @@ package com.management.platform.service;
 
 import com.management.platform.entity.SysForm;
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.management.platform.util.HttpRespMsg;
 
 /**
  * <p>
@@ -13,4 +14,5 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface SysFormService extends IService<SysForm> {
 
+    HttpRespMsg getExportTemplate(String code);
 }

+ 133 - 2
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/impl/ProductServiceImpl.java

@@ -1,19 +1,36 @@
 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.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.management.platform.entity.Product;
+import com.management.platform.entity.SysForm;
 import com.management.platform.mapper.ProductMapper;
+import com.management.platform.mapper.SysFormMapper;
+import com.management.platform.mapper.UserMapper;
 import com.management.platform.service.ProductService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.management.platform.util.ExcelUtil;
 import com.management.platform.util.HttpRespMsg;
+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.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.*;
 
 /**
  * <p>
@@ -28,6 +45,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
 
     @Resource
     private ProductMapper productMapper;
+    @Resource
+    private HttpServletRequest request;
+    @Resource
+    private UserMapper userMapper;
+    @Resource
+    private SysFormMapper sysFormMapper;
+    @Value(value = "${upload.path}")
+    private String path;
 
     @Override
     public HttpRespMsg getList(Integer companyId,String userId, String productName, String productCode, Integer pageIndex, Integer pageSize) {
@@ -50,4 +75,110 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> impl
         msg.setData(map);
         return msg;
     }
+
+    @Override
+    public HttpRespMsg importData(MultipartFile multipartFile) {
+        HttpRespMsg msg=new HttpRespMsg();
+        String fileName = multipartFile.getOriginalFilename();
+        File file = new File(fileName == null ? "file" : fileName);
+        Integer companyId = userMapper.selectById(request.getHeader("token")).getCompanyId();
+        List<Product> productList = productMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::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, "Product").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<Product>  importProductList=new ArrayList<>();
+            for (int rowIndex = 0; rowIndex <= rowNum; rowIndex++) {
+                HSSFRow row = sheet.getRow(rowIndex);
+                if (row == null) {
+                    continue;
+                }
+                //跳过空行
+                if (ExcelUtil.isRowEmpty(row)) {
+                    continue;
+                }
+                //获取到当前行的列数据
+                int cellNum = row.getLastCellNum();
+                Product product=new Product();
+                product.setCompanyId(companyId);
+                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;
+                            default:cell.setCellType(CellType.STRING);
+                        }
+                    }
+//                    Class<?> productClass = Class.forName("com.management.platform.entity.Product");
+                    Class<Product> productClass = Product.class;
+                    Method method = productClass.getMethod(setter, String.class);
+                    //校验当前列是否为必填
+                    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("productCode")){
+                        if(!StringUtils.isEmpty(cell.getStringCellValue())){
+                            //系统中同公司已存在的产品编码 更新
+                            Optional<Product> first = productList.stream().filter(p ->p.getProductCode()!=null&& p.getProductCode().equals(cell.getStringCellValue())).findFirst();
+                            if(first.isPresent()){
+                                product.setId(first.get().getId());
+                            }
+                        }
+                    }
+                    if(!StringUtils.isEmpty(cell.getStringCellValue())){
+                        method.invoke(product,cell.getStringCellValue());
+                    }
+                }
+                importProductList.add(product);
+            }
+            if(importProductList.size()>0){
+               if(!saveOrUpdateBatch(importProductList)){
+                   msg.setError("验证失败");
+                   return msg;
+               }
+            }
+        } catch (IOException | NoSuchMethodException e) {
+            e.printStackTrace();
+        } catch (IllegalAccessException e) {
+            e.printStackTrace();
+        } catch (InvocationTargetException e) {
+            e.printStackTrace();
+        }
+        return msg;
+    }
 }

+ 233 - 1
fhKeeper/formulahousekeeper/management-crm/src/main/java/com/management/platform/service/impl/SysFormServiceImpl.java

@@ -1,11 +1,32 @@
 package com.management.platform.service.impl;
 
-import com.management.platform.entity.SysForm;
+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.management.platform.entity.*;
+import com.management.platform.mapper.CompanyMapper;
 import com.management.platform.mapper.SysFormMapper;
+import com.management.platform.mapper.UserMapper;
 import com.management.platform.service.SysFormService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.management.platform.util.HttpRespMsg;
+import com.management.platform.util.MessageUtils;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddressList;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
 /**
  * <p>
  *  服务实现类
@@ -17,4 +38,215 @@ import org.springframework.stereotype.Service;
 @Service
 public class SysFormServiceImpl extends ServiceImpl<SysFormMapper, SysForm> implements SysFormService {
 
+    @Resource
+    private CompanyMapper companyMapper;
+    @Resource
+    private HttpServletRequest request;
+    @Resource
+    private UserMapper userMapper;
+    @Resource
+    private SysFormMapper sysFormMapper;
+    @Value(value = "${upload.path}")
+    private String path;
+
+    @Override
+    public HttpRespMsg getExportTemplate(String code) {
+        HttpRespMsg msg=new HttpRespMsg();
+        List<String> heads = new ArrayList<>();
+        Integer companyId = userMapper.selectById(request.getHeader("token")).getCompanyId();
+        Company company = companyMapper.selectById(companyId);
+        //根据code获取当前公司配置的表单模板
+        SysForm sysForm = sysFormMapper.selectOne(new LambdaQueryWrapper<SysForm>().eq(SysForm::getCompanyId, companyId).eq(SysForm::getCode, code).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");
+        for (int i = 0; i < configObJSONArray.size(); i++) {
+            JSONObject item = configObJSONArray.getJSONObject(i);
+            heads.add(item.getString("label"));
+        }
+        List<List<String>> allList = new ArrayList<>();
+        allList.add(heads);
+        String title;
+        switch (code){
+            case "Clue":title = company.getCompanyName()+"_线索导入模板";
+            break;
+            case "Custom":title = company.getCompanyName()+"_客户导入模板";
+                break;
+            case "Order":title = company.getCompanyName()+"_订单导入模板";
+                break;
+            case "Product":title = company.getCompanyName()+"_产品导入模板";
+                break;
+            case "Task":title = company.getCompanyName()+"_任务导入模板";
+                break;
+            case "Contacts":title = company.getCompanyName()+"_联系人导入模板";
+                break;
+            case "Business":title = company.getCompanyName()+"_商机导入模板";
+                break;
+            default:title="";
+        }
+        String result=MessageUtils.message("file.excelScu");
+        String fileName= title+".xls";
+        try {
+//            response.reset();
+//            response.setHeader("Content-disposition",
+//                "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
+//            //设置文件头编码格式
+//            response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");//设置类型
+//            response.setHeader("Cache-Control","no-cache");//设置头
+//            response.setDateHeader("Expires", 0);//设置日期头
+            // 创建工作簿
+            HSSFWorkbook workBook = new HSSFWorkbook();
+            // 创建工作类
+            HSSFSheet sheet = workBook.createSheet();
+            //设置首行冻结
+            sheet.createFreezePane(0, 1);
+            sheet.setDefaultColumnWidth(16);
+            //设置字体样式
+            HSSFFont headFont = workBook.createFont();
+            headFont.setBold(true);
+            headFont.setFontHeightInPoints((short) 10);
+            headFont.setFontName("黑体");
+
+            HSSFFont titleFont = workBook.createFont();
+            titleFont.setBold(true);
+            titleFont.setFontHeightInPoints((short) 10);
+            titleFont.setFontName("黑体");
+
+            HSSFFont font = workBook.createFont();
+            font.setFontHeightInPoints((short) 10);
+            font.setFontName("宋体");
+
+            //设置单元格样式
+            CellStyle headStyle = workBook.createCellStyle();
+            headStyle.setFont(headFont);
+            headStyle.setAlignment(HorizontalAlignment.CENTER);
+            headStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
+            headStyle.setWrapText(true);
+            headStyle.setBorderBottom(BorderStyle.THIN); //下边框
+            headStyle.setBorderLeft(BorderStyle.THIN);//左边框
+            headStyle.setBorderTop(BorderStyle.THIN);//上边框
+            headStyle.setBorderRight(BorderStyle.THIN);//右边框
+
+            String color = "c0c0c0";    //此处得到的color为16进制的字符串
+            //转为RGB码
+            int r = Integer.parseInt((color.substring(0,2)),16);   //转为16进制
+            int g = Integer.parseInt((color.substring(2,4)),16);
+            int b = Integer.parseInt((color.substring(4,6)),16);
+
+            //自定义cell颜色
+            HSSFPalette palette = workBook.getCustomPalette();
+            //这里的9是索引
+            palette.setColorAtIndex((short)9, (byte) r, (byte) g, (byte) b);
+
+            CellStyle titleStyle = workBook.createCellStyle();
+            titleStyle.setFont(titleFont);
+            titleStyle.setAlignment(HorizontalAlignment.CENTER);
+            titleStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
+            titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);  //填充单元格
+            titleStyle.setFillForegroundColor((short)9);    //填色
+            titleStyle.setWrapText(true);
+            titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
+            titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
+            titleStyle.setBorderTop(BorderStyle.THIN);//上边框
+            titleStyle.setBorderRight(BorderStyle.THIN);//右边框
+
+            CellStyle cellStyle = workBook.createCellStyle();
+            cellStyle.setFont(font);
+            cellStyle.setAlignment(HorizontalAlignment.CENTER);
+            cellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
+            cellStyle.setWrapText(true);
+            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
+            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
+            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
+            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
+
+            if(allList.size() > 0) {
+                int start = 0;
+                for(List<String> rowList : allList) {
+                    HSSFRow row = sheet.createRow(start);
+                    row.setHeightInPoints(24);
+                    for(int i = 0; i < rowList.size(); i++) {
+                        HSSFCell cell = row.createCell(i);
+                        ClientAnchor anchor = new HSSFClientAnchor();
+                        if(start == 0) {
+                            cell.setCellStyle(titleStyle);
+                            // 关键修改
+                            anchor.setDx1(0);
+                            anchor.setDx2(0);
+                            anchor.setDy1(0);
+                            anchor.setDy2(0);
+                            anchor.setCol1(cell.getColumnIndex());
+                            anchor.setRow1(cell.getRowIndex());
+                            anchor.setCol2(cell.getColumnIndex() + 5);
+                            anchor.setRow2(cell.getRowIndex() + 6);
+                            // 结束
+                            Drawing drawing = sheet.createDrawingPatriarch();
+                            Comment comment = null;
+                            String[] textList=null;
+                            DVConstraint constraint =null;
+                            CellRangeAddressList regions =null;
+                            HSSFDataValidation data_validation_list =null;
+//                            switch (rowList.get(i)){
+//                                case "是否为公共项目":
+//                                case "Whether it is a public project":
+//                                    // 加载下拉列表内容
+//                                    //textList= new String[]{"是", "否"};
+//                                    textList= new String[]{MessageUtils.message("excel.yes"), MessageUtils.message("excel.no")};
+//                                    constraint = DVConstraint
+//                                            .createExplicitListConstraint(textList);
+//                                    // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
+//                                    regions = new CellRangeAddressList(1,
+//                                            1000, i, i);
+//                                    // 数据有效性对象
+//                                    data_validation_list = new HSSFDataValidation(
+//                                            regions, constraint);
+//                                    sheet.addValidationData(data_validation_list);
+//                                    comment = drawing.createCellComment(anchor);
+//                                    // 输入批注信息
+//                                    //comment.setString(new HSSFRichTextString("是否为公共项目\n" +
+//                                    //"是:公共项目\n" +
+//                                    //"否:普通项目"));
+//                                    comment.setString(new HSSFRichTextString(MessageUtils.message("excel.publicProject")+"\n" +
+//                                            MessageUtils.message("excel.yesPublic")+"\n" +
+//                                            MessageUtils.message("excel.noPublic")));
+//                                    cell.setCellComment(comment);
+//                                    break;
+//                            }
+                        }else {
+                            cell.setCellStyle(cellStyle);
+                        }
+                        cell.setCellValue(rowList.get(i));
+                    }
+                    start++;
+                }
+            }
+            //用于非传统ajax;
+//            String headStr = "attachment; filename=\"" + fileName + "\"";
+//            response.setContentType("APPLICATION/OCTET-STREAM");//返回格式为流
+//            response.setHeader("Content-Disposition", headStr);
+//            //普通下载不需要以上三行,注掉即可
+//            OutputStream os = response.getOutputStream();//在线下载
+            File dir = null;
+            dir = new File(path);
+            // D://cloud/upload 文件上传后所存储的位置,部署到服务器上时配置服务器地址即可
+            if (!dir.exists()) {
+                dir.mkdirs();
+            }
+            FileOutputStream os = new FileOutputStream(path+fileName);//保存到本地
+            workBook.write(os);
+            os.flush();
+            os.close();
+        }catch(Exception e) {
+            e.printStackTrace();
+            //msg.setError("已存在模板名称为["+fileName+"]的文件,请删除后重新下载");
+            msg.setError(MessageUtils.message("file.duplicateTemplate",fileName));
+            return msg;
+        }
+        msg.data= "/upload/"+fileName;
+        return msg;
+    }
 }

+ 2 - 2
fhKeeper/formulahousekeeper/management-crm/src/main/resources/mapper/ProductMapper.xml

@@ -20,12 +20,12 @@
         <result column="plate3" property="plate3" />
         <result column="plate4" property="plate4" />
         <result column="plate5" property="plate5" />
-        <result column="desc" property="desc" />
+        <result column="descs" property="descs" />
     </resultMap>
 
     <!-- 通用查询结果列 -->
     <sql id="Base_Column_List">
-        id, company_id, product_name, product_code, type, unit, price, status, incharger_id, create_time, creator_id, plate1, plate2, plate3, plate4, plate5, desc
+        id, company_id, product_name, product_code, type, unit, price, status, incharger_id, create_time, creator_id, plate1, plate2, plate3, plate4, plate5, descs
     </sql>
 
 </mapper>