package com.zy.crm.manager.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page; import com.core.common.DateUtils; import com.core.exception.CoolException; import com.zy.crm.common.model.SettleDto; import com.zy.crm.common.service.OssService; import com.zy.crm.manager.entity.*; import com.zy.crm.manager.service.ContractSalesService; import com.zy.crm.manager.service.ContractService; import com.core.annotations.ManagerAuth; import com.core.common.BaseRes; import com.core.common.Cools; import com.core.common.R; import com.core.domain.KeyValueVo; import com.zy.crm.common.web.BaseController; import com.zy.crm.manager.service.ProcessPermissionsService; import com.zy.crm.manager.utils.ChineseNumberUtils; import com.zy.crm.manager.utils.WordUtils; import com.zy.crm.system.entity.User; import com.zy.crm.system.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.ResponseEntity; import org.springframework.util.ClassUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; @RestController public class ContractController extends BaseController { @Autowired private ContractService contractService; @Autowired private ContractSalesService contractSalesService; @Autowired private OssService ossService; @Autowired private UserService userService; @Autowired private ProcessPermissionsService processPermissionsService; @RequestMapping(value = "/contract/{id}/auth2") @ManagerAuth public R get(@PathVariable("id") String id) { Contract contract = contractService.selectById(String.valueOf(id)); assert contract != null; JSONObject resultObj = JSON.parseObject(JSON.toJSONString(contract)); // 步骤条相关 resultObj.put("step", contract.getSettle() == 5 ? 0 : contract.getSettle() + 1); return R.ok().add(resultObj); } @RequestMapping(value = "/contract/list/auth") @ManagerAuth public R list(@RequestParam(defaultValue = "1")Integer curr, @RequestParam(defaultValue = "10")Integer limit, @RequestParam(required = false)String orderByField, @RequestParam(required = false)String orderByType, @RequestParam(required = false)String condition, @RequestParam Map param){ EntityWrapper wrapper = new EntityWrapper<>(); excludeTrash(param); convert(param, wrapper); allLike(Contract.class, param.keySet(), wrapper, condition); if (!Cools.isEmpty(orderByField)){wrapper.orderBy(humpToLine(orderByField), "asc".equals(orderByType));} return R.ok(contractService.selectPage(new Page<>(curr, limit), wrapper)); } private void convert(Map map, EntityWrapper wrapper){ boolean signUserId = false; boolean signDeptId = false; boolean signHostId = false; for (Map.Entry entry : map.entrySet()){ if (entry.getKey().equals("dept_id")){ signDeptId = true; if (String.valueOf(entry.getValue()).equals("19")){ signHostId = true; } } } for (Map.Entry entry : map.entrySet()){ String val = String.valueOf(entry.getValue()); if (val.contains(RANGE_TIME_LINK)){ String[] dates = val.split(RANGE_TIME_LINK); wrapper.ge(entry.getKey(), DateUtils.convert(dates[0])); wrapper.le(entry.getKey(), DateUtils.convert(dates[1])); } else if (entry.getKey().equals("dept_id")){ if (!val.equals("19")){ wrapper.eq(entry.getKey(), val); } } else if (entry.getKey().equals("user_id") && !signDeptId){ signUserId = true; wrapper.eq(entry.getKey(), val); } else { wrapper.like(entry.getKey(), val); } } if (!signUserId && !signDeptId){ if (getRole().getId()==1){ wrapper.or().eq("host_id",1); }else if (getRole().getId()==2){ wrapper.eq("dept_id",getDeptId()); }else { wrapper.eq("user_id", getUserId()); } } if (signHostId){ wrapper.or().eq("host_id",1); } } @RequestMapping(value = "/contract/add/auth") @ManagerAuth(memo = "添加合同") public R add(Contract contract) { Date now = new Date(); contract.setUserId(getUserId()); //创建人员部门 contract.setDeptId(getDeptId()); contract.setCreateTime(now); contract.setSettle(1); User manager = new User(); try{ manager = userService.getDeptManager(getHostId(), getUser().getDeptId()); // 获取部门领导 }catch (Exception e){ manager = getUser(); } contract.setDirector(manager.getId()); List initNames = new ArrayList<>(); initNames.add("创建合同模板"); initNames.add("提交合同"); initNames.add("部门经理审核"); ProcessPermissions processPermissions = processPermissionsService.selectOne(new EntityWrapper().eq("process_memo", 7).eq("process", "3-1" ));//7:合同管理 User president = userService.selectById(processPermissions.getUserId()); initNames.add("总经办"+president.getNickname()+"审核"); initNames.add("业务员确认"); contract.setSettleMsg(JSON.toJSONString(SettleDto.initContract(manager,getUser(),president,initNames,4))); contract.setUpdateTime(now); contract.setUpdateBy(getUserId()); contractService.insert(contract); return R.ok(); } @RequestMapping(value = "/contract/update/auth") @ManagerAuth(memo = "更新合同") public R update(Contract contract){ if (Cools.isEmpty(contract) || null==contract.getId()){ return R.error(); } contract.setUpdateBy(getUserId()); contract.setUpdateTime(new Date()); contractService.updateById(contract); return R.ok(); } @RequestMapping(value = "/contract/delete/auth") @ManagerAuth(memo = "删除合同") public R delete(@RequestParam(value="ids[]") Long[] ids){ for (Long id : ids){ contractService.deleteById(id); } return R.ok(); } @RequestMapping(value = "/contract/generate/auth") @ManagerAuth(memo = "生成合同") public ResponseEntity generate(@RequestParam Integer id, @RequestParam String contractTemplate){ try { /////////////////////////生成合同数据///////////////////////// Contract contract = contractService.selectById(id); if (contract == null) { return null; } HashMap map = new HashMap<>(); map.put("{{serial}}", contract.getSerial()); map.put("{{customer}}", contract.getCustomer()); map.put("{{address}}", contract.getAddress()); map.put("{{company}}", contract.getCompany()); map.put("{{companyAddress}}", contract.getCompanyAddress()); map.put("{{taxNum}}", contract.getTaxNum()); map.put("{{bank}}", contract.getBank()); map.put("{{bankNum}}", contract.getBankNum()); map.put("{{city}}", contract.getCity()); map.put("{{shippingAddress}}", contract.getShippingAddress()); map.put("{{shippingName}}", contract.getShippingName()); map.put("{{shippingPhone}}", contract.getShippingPhone()); map.put("{{email}}", contract.getEmail()); map.put("{{boss}}", contract.getBoss()); map.put("{{priceChinese}}", ChineseNumberUtils.numberToChinese(contract.getPrice())); map.put("{{priceSci}}", WordUtils.formatNumberForAccounting(contract.getPrice())); SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日"); map.put("{{now}}", format.format(new Date())); /////////////////////////生成合同数据///////////////////////// /////////////////////////生成Tab表格数据///////////////////////// List contractSales = contractSalesService.selectByContractId(contract.getId()); List> tabParam = new ArrayList<>(); ArrayList tabTitle = new ArrayList<>(); tabTitle.add("序号"); tabTitle.add("品名"); tabTitle.add("数量"); tabTitle.add("单位"); tabTitle.add("单价(元)"); tabTitle.add("合计(元)"); tabTitle.add("备注"); tabParam.add(tabTitle); int idx = 1;//tab序号 double totalPrice = 0D; for (ContractSales contractSale : contractSales) { ArrayList list = new ArrayList<>(); list.add(String.valueOf(idx)); list.add(contractSale.getName()); list.add(String.valueOf(contractSale.getNum())); list.add(contractSale.getUnit()); list.add(WordUtils.formatNumberForAccounting(contractSale.getUnitPrice())); list.add(WordUtils.formatNumberForAccounting(contractSale.getTotalPrice())); list.add(contractSale.getMemo()); tabParam.add(list); totalPrice += contractSale.getTotalPrice(); idx++;//序号+1 } //tab最后合计栏 ArrayList tabFooter = new ArrayList<>(); tabFooter.add("合计(大写金额):" + ChineseNumberUtils.numberToChinese(totalPrice)); tabFooter.add("");//合并单元格 tabFooter.add("");//合并单元格 tabFooter.add("");//合并单元格 tabFooter.add("合计:" + WordUtils.formatNumberForAccounting(totalPrice)); tabFooter.add("");//合并单元格 tabFooter.add("");//合并单元格 tabParam.add(tabFooter); /////////////////////////生成Tab表格数据///////////////////////// String fileName = this.getClass().getClassLoader().getResource("contractTemplate/" + contractTemplate + ".docx").getPath();//获取文件路径 // String outPdfPath = fileName.split("\\.")[0]+".pdf"; ResponseEntity generate = WordUtils.generate(fileName, map, tabParam); // WordUtils.documents4jWordToPdf(fileName,outPdfPath); return generate; } catch (Exception e) { return null; } } @RequestMapping(value = "/contract/upload/auth") @ManagerAuth(memo = "上传合同") public R upload(@RequestParam("id") Integer id, @RequestParam("file") MultipartFile[] files) throws IOException { Contract contract = contractService.selectById(id); if (contract == null) { return R.error(); } MultipartFile file = files[0]; SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss"); String path = ClassUtils.getDefaultClassLoader().getResource("contractTemplate/upload").getPath(); //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //上传文件名 String filename = format.format(new Date()) + "_" + file.getOriginalFilename(); //最终文件路径 String filepath = path + "/" + filename; //OSS文件存储路径 String ossPath = "contract/" + filename; //服务器端保存的文件对象 File serverFile = new File(filepath); if(!serverFile.exists()) { try { //创建文件 serverFile.createNewFile(); //将上传的文件写入到服务器端文件内 file.transferTo(serverFile); //上传至OSS ossService.uploadFile(ossPath, serverFile); contract.setFilepath(ossPath); contractService.updateById(contract); } catch (IOException e) { e.printStackTrace(); } } return R.ok(); } @RequestMapping(value = "/contract/download/auth") @ManagerAuth(memo = "下载合同") public R download(@RequestParam("id") Integer id) { Contract contract = contractService.selectById(id); if (contract == null) { return R.error(); } if (Cools.isEmpty(contract.getFilepath())) { return R.error(); } String download = ossService.download(contract.getFilepath());//获取OSS临时下载URL return R.ok().add(download); } @RequestMapping(value = "/contract/export/auth") @ManagerAuth public R export(@RequestBody JSONObject param){ EntityWrapper wrapper = new EntityWrapper<>(); List fields = JSONObject.parseArray(param.getJSONArray("fields").toJSONString(), String.class); Map map = excludeTrash(param.getJSONObject("contract")); convert(map, wrapper); List list = contractService.selectList(wrapper); return R.ok(exportSupport(list, fields)); } @RequestMapping(value = "/contractQuery/auth") @ManagerAuth public R query(String condition) { EntityWrapper wrapper = new EntityWrapper<>(); wrapper.like("id", condition); Page page = contractService.selectPage(new Page<>(0, 10), wrapper); List> result = new ArrayList<>(); for (Contract contract : page.getRecords()){ Map map = new HashMap<>(); map.put("id", contract.getId()); map.put("value", contract.getId()); result.add(map); } return R.ok(result); } @RequestMapping(value = "/contract/check/column/auth") @ManagerAuth public R query(@RequestBody JSONObject param) { Wrapper wrapper = new EntityWrapper().eq(humpToLine(String.valueOf(param.get("key"))), param.get("val")); if (null != contractService.selectOne(wrapper)){ return R.parse(BaseRes.REPEAT).add(getComment(Contract.class, String.valueOf(param.get("key")))); } return R.ok(); } @RequestMapping("/contract/all/get/kv") @ManagerAuth public R getDataKV(@RequestParam(required = false) String condition) { List vos = new ArrayList<>(); Wrapper wrapper = new EntityWrapper().andNew().like("id", condition).orderBy("create_time", false); contractService.selectPage(new Page<>(1, 30), wrapper).getRecords().forEach(item -> vos.add(new KeyValueVo(String.valueOf(item.getId()), item.getId()))); return R.ok().add(vos); } @PostMapping(value = "/contract/approval/auth") @ManagerAuth public R approvalBusinessTrip(@RequestParam Long contractId, @RequestParam(required = false) Long plannerId){ Contract contract = contractService.selectById(contractId); assert contract != null; Date now = new Date(); switch (contract.getSettle()) { case 0: if (Cools.isEmpty(getUser())) { return R.error("抱歉,您没有提交的权限"); } if (!getUserId().equals(getUser().getId())) { return R.error("抱歉,您没有提交的权限"); } // 修改 settle 步骤数据 List list1 = JSON.parseArray(contract.getSettleMsg(), SettleDto.class); for (SettleDto dto : list1) { switch (dto.getStep()) { case 0: dto.setCurr(Boolean.FALSE); break; case 1: dto.setCurr(Boolean.TRUE); dto.setMsg(getUser().getNickname() + "提交完成"); dto.setTime(DateUtils.convert(now)); break; case 2: contract.setDirector(dto.getUserId()); break; default: break; } } contract.setSettleMsg(JSON.toJSONString(list1)); // 修改规划单状态 contract.setSettle(1); contract.setUpdateTime(now); if (!contractService.updateById(contract)) { throw new CoolException("提交失败,请联系管理员"); } break; case 1: // 本部门经理审核 User manager = userService.selectById(contract.getDirector()); if (manager.getId().equals(getUserId())) { // 修改 settle 步骤数据 List list = JSON.parseArray(contract.getSettleMsg(), SettleDto.class); for (SettleDto dto : list) { switch (dto.getStep()) { case 1: dto.setCurr(Boolean.FALSE); break; case 2: dto.setCurr(Boolean.TRUE); dto.setMsg("部门经理" + manager.getNickname() + "审批通过"); dto.setTime(DateUtils.convert(now)); break; case 3: contract.setDirector(dto.getUserId()); break; default: break; } } contract.setSettleMsg(JSON.toJSONString(list)); // 修改规划单状态 contract.setSettle(2); // 申请通过 contract.setUpdateTime(now); if (!contractService.updateById(contract)) { throw new CoolException("审核失败,请联系管理员"); } } else { return R.error("抱歉,您没有审核的权限!!!"); } break; case 2: User planLeader = userService.selectById(contract.getDirector()); if (planLeader.getId().equals(getUserId())) { // 修改 settle 步骤数据 List list = JSON.parseArray(contract.getSettleMsg(), SettleDto.class); for (SettleDto dto : list) { switch (dto.getStep()) { case 2: dto.setCurr(Boolean.FALSE); break; case 3: dto.setCurr(Boolean.TRUE); dto.setMsg("总裁办" + planLeader.getNickname() + "审批通过"); dto.setTime(DateUtils.convert(now)); break; case 4: contract.setDirector(dto.getUserId()); break; default: break; } } contract.setSettleMsg(JSON.toJSONString(list)); // 修改规划单状态 contract.setSettle(3); // 申请通过 contract.setUpdateTime(now); if (!contractService.updateById(contract)) { throw new CoolException("审核失败,请联系管理员"); } } else { return R.error("抱歉,您没有审核的权限!!!"); } break; case 3: // 业务员 User salesman0 = userService.selectById(contract.getUserId()); if (!getUserId().equals(salesman0.getId())) { return R.error("抱歉,您无需确认!!!"); } // 修改 settle 步骤数据 List list2 = JSON.parseArray(contract.getSettleMsg(), SettleDto.class); for (SettleDto dto : list2) { switch (dto.getStep()) { case 3: dto.setCurr(Boolean.TRUE); break; case 4: dto.setCurr(Boolean.TRUE); dto.setMsg("业务员" + salesman0.getNickname() + "以确认"); dto.setTime(DateUtils.convert(new Date())); break; default: break; } } contract.setSettleMsg(JSON.toJSONString(list2)); // 修改规划单状态 contract.setSettle(4); // 审批通过 contract.setUpdateTime(new Date()); if (!contractService.updateById(contract)) { throw new CoolException("确认失败,请联系管理员"); } break; default: return R.error(); } return R.ok("审批成功"); } }