package com.loan.system.service.Impl; import cn.hutool.core.bean.BeanUtil; import com.loan.system.context.BaseContext; import com.loan.system.domain.dto.ContractDTO; import com.loan.system.domain.dto.ContractWrapperDTO; import com.loan.system.domain.dto.query.ContractQueryDTO; import com.loan.system.domain.entity.*; import com.loan.system.domain.enums.*; import com.loan.system.domain.pojo.ContractInformation; import com.loan.system.domain.pojo.Result; import com.loan.system.domain.pojo.TemplateMessage; import com.loan.system.domain.vo.*; import com.loan.system.exception.DescribeException; import com.loan.system.repository.ContractRepository; import com.loan.system.service.*; import com.loan.system.utils.NumberToChineseUtil; import com.loan.system.utils.PoiWordUtil; import com.loan.system.utils.ResultUtil; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import static com.loan.system.domain.enums.ExceptionEnum.FILE_DELETE_ERROR; @Service @RequiredArgsConstructor public class ContractServiceImpl implements ContractService { @Value("${upload.templatePath}") private String contractPath; @Autowired @Lazy private LoanService loanService; private final CustomerService customerService; private final ContractRepository contractRepository; private final DocumentService documentService; private final DictionaryService dictionaryService; private final StepService stepService; private final EsignService esignService; private final ContractBankInfoService contractBankInfoService; private final WxService wxService; private final UserService userService; private final CollateralService collateralService; private final ContractAndCollateralService contractAndCollateralService; @Override public Contract saveContract(ContractDTO contractDTO) { Map contractMap = dictionaryService.contractMap(); Contract contract = BeanUtil.copyProperties(contractDTO, Contract.class); String[] split = contractDTO.getCustomerIds().split(","); contract.setCustomerId(split.length>0?Long.valueOf(split[0]):null); contract.setCustomerId1(split.length>1?Long.valueOf(split[1]):null); contract.setCustomerId2(split.length>2?Long.valueOf(split[2]):null); contract.setId( null); contract.setContractName(contract.getBusinessAttr().equals(BusinessAttrEnum.ESTATE_MORTGAGE.getMsg())?"抵押合同":"质押合同"); if(contract.getContractNo()==null) contract.setContractNo("临时编号:"+UUID.randomUUID().toString().replace("-","")); contract.setIsDelete(false); contract.setSignedByCustomer(false); contract.setIsPush( false); contract.setClearedStatus(DecisionEnum.CLEAR_NOT.getMsg()); contract.setInterestAmount(0.0); contract.setActualAmount(0.0); contract.setIsDisbursementComplete(false); contract.setAmountRate(Double.valueOf(contractMap.get(ContractEnum.PAWN_INTEREST_RATE.getLabel()))); contract.setServiceCost(Double.valueOf(contractMap.get(ContractEnum.MONTHLY_COMPREHENSIVE_FEE.getLabel()))); contract.setLoanRate(Double.valueOf(contractMap.get(ContractEnum.LOAN_INTEREST_RATE.getLabel()))); contract.setCreateTime(LocalDateTime.now() .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); contract.setUpdateTime(LocalDateTime.now() .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); return contractRepository.save(contract); } @Override public Contract findContractByCaseIdAndBusinessAttr(Long caseId, String businessAttr, boolean b) { return contractRepository.findByCaseIdAndBusinessAttrAndIsDelete(caseId,businessAttr,b); } @Override public void updateContractById(Long id, ContractDTO contractDTO, boolean isDelete) { Contract contract = BeanUtil.copyProperties(contractDTO, Contract.class); String[] split = contractDTO.getCustomerIds().split(","); contract.setCustomerId(split.length>0?Long.valueOf(split[0]):null); contract.setCustomerId1(split.length>1?Long.valueOf(split[1]):null); contract.setCustomerId2(split.length>2?Long.valueOf(split[2]):null); contract.setUpdateTime( LocalDateTime.now().format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ))); contractRepository.updateContractById(id,contract,isDelete); } @Override public List findContractByCaseId(Long caseId) { List contracts = contractRepository.findByCaseIdAndIsDelete(caseId, false); return convertContractsToContractVOS( contracts); } @Override public void updateContractById1(Long contractId, Long commitedId,Long signId) { Contract contract = new Contract(); contract.setCommitedId(commitedId); contract.setSignedId(signId); contract.setSignedByCustomer(true); contract.setSignedTime( LocalDateTime.now().format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ))); contract.setUpdateTime( LocalDateTime.now().format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ))); contractRepository.updateContractById(contractId,contract,false); } @Override public void updateIsPushById(Long contractId) { contractRepository.updateIsPushById(contractId); } @Override public List findContractByCaseIdAndIsPush(Long caseId, boolean isPush) { List contracts = contractRepository.findByCaseIdAndIsPush(caseId, isPush, false); return convertContractsToContractVOS( contracts); } @Override public void deleteAllByCaseId(Long caseId) { contractRepository.deleteAllByCaseId(caseId); } @Override public void updateContractNoById(Long id, String contractNo) { contractRepository.updateContractNoById(id,contractNo); } @Override public Contract findContractById(Long contractId) { return contractRepository.findContractById(contractId); } @Override public void updateSignedCustomerById(Long contractId) { contractRepository.updateSignedCustomerById(contractId); } @Override public void deleteSigned(Long sifnedId) { contractRepository.deleteSigned(sifnedId); } @Override public void updateRepayById(String clearedStatus, Double interest, Long currentId, Long contractId, boolean isDelete) { contractRepository.updateRepayById(clearedStatus,interest,currentId,contractId,isDelete); } @Override public List findIntersetByCaseId(Long caseId) { return contractRepository.findIntersetByCaseIdAndIsDelete(caseId,false); } @Override public List findContractByCaseId2(Long caseId) { return contractRepository.findByCaseIdAndIsDelete2(caseId,false); } @Override public boolean existsById(Long contractId) { return contractRepository.existsById(contractId); } @Override public void updateContractStatus(Contract contract, Long caseId) { Long contractId = contract.getId(); updateSignedCustomerById(contractId); if(contract.getSignedId()!=null){ Document document = documentService.findById(contract.getSignedId()); String filePath = document.getFilePath(); if (filePath!=null){ try { Path path = Paths.get(filePath); boolean deleted = Files.deleteIfExists(path); if (deleted) { deleteSigned(contract.getSignedId()); documentService.deleteFileById(contract.getSignedId()); System.out.println("文件删除成功: " + filePath); } else { System.out.println("文件不存在或已被删除: " + filePath); } } catch (IOException e) { throw new DescribeException(FILE_DELETE_ERROR); } } } } @Override public void completeContract(LoanCaseSimpleVO loanCaseSimpleVO, ContractWrapperDTO contractWrapper) { Long caseId = loanCaseSimpleVO.getId(); List contractDTOS = contractWrapper.getContractDTOS(); for (ContractDTO contractDTO : contractDTOS) { contractBankInfoService.addInfo(contractDTO.getBankInfo(),contractDTO.getId()); contractBankInfoService.addInfos(contractDTO.getEntrustBankInfos(),contractDTO.getId()); contractRepository.updateLoanInfoById(contractDTO.getAmountRate(),contractDTO.getServiceCost(),contractDTO.getLoanRate(),contractDTO.getId()); } //合同签约完成 stepService.updateUserId1ByCaseIdAndStepCode(StepPropertyEnum.CONTRACT_SIGN.getCode(), BaseContext.getCurrentId(),caseId); stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(), StepPropertyEnum.CONTRACT_SIGN_PARENT.getCode(),caseId); stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.CONTRACT_SIGN.getCode(),caseId); stepService.tryStartStep(StepPropertyEnum.CONTRACT_SIGN.getCode(),caseId); //TODO:微信消息推送至下一环节:业务员 TemplateMessage message = new TemplateMessage(); Map> data = new HashMap<>(); data.put("character_string6", Collections.singletonMap("value", String.valueOf(caseId)));//caseId data.put("phrase7", Collections.singletonMap("value", StepPropertyEnum.PLAN_REPORT.getLabel()));//当前环节 data.put("thing1", Collections.singletonMap("value", String.valueOf(loanCaseSimpleVO.getBusinessType())));//业务类型 Customer customer = customerService.findByIdAndIsDelete(loanCaseSimpleVO.getCustomerId()); data.put("thing3", Collections.singletonMap("value", customer!=null ? customer.getName() : ""));//客户名称 data.put("amount4",Collections.singletonMap("value", String.valueOf(loanCaseSimpleVO.getTotalLoanAmount())));//典当金额 message.setData(data); List users = userService.findByRoleAndIsDelete(Arrays.asList(RoleEnum.ASSIST_SALES.getMsg(),RoleEnum.LEAD_SALES.getMsg()), false); for (User user : users) { if (user.getId().equals(BaseContext.getCurrentId())) continue; if (user.getOpenid() != null) wxService.sendTemplateMessage(user.getOpenid(), message); } } @Override public void getContractInformation(HttpServletResponse response, Long caseId,Long contractId){ Contract contract = contractRepository.findContractById(contractId); LoanCaseSimpleVO loancase = loanService.findLoanCaseSimpleByIdAndIsDelete(caseId, false); CustomerVO customer = customerService.findByCustomerIdAndIsDelete(loancase.getCustomerId(),false); ContractInformation contractInformation = BeanUtil.copyProperties(contract, ContractInformation.class); if (contract.getSignedId() != null){ Document byId = documentService.findById(contract.getSignedId()); contractInformation.setSignaturePath1(byId.getFilePath()); } String names = ""; String idNumbers = ""; if (contract.getCustomerId()!=null){ Customer customer1 = customerService.findByIdAndIsDelete(contract.getCustomerId()); names = names == "" ? customer1.getName() : names + "、" + customer1.getName(); idNumbers = idNumbers == "" ? customer1.getIdNumber() : idNumbers + "、" + customer1.getIdNumber(); } if (contract.getCustomerId1()!=null){ Customer customer2 = customerService.findByIdAndIsDelete(contract.getCustomerId1()); names = names == "" ? customer2.getName() : names + "、" + customer2.getName(); idNumbers = idNumbers == "" ? customer2.getIdNumber() : idNumbers + "、" + customer2.getIdNumber(); } if (contract.getCustomerId2()!=null){ Customer customer3 = customerService.findByIdAndIsDelete(contract.getCustomerId2()); names = names == "" ? customer3.getName() : names + "、" + customer3.getName(); idNumbers = idNumbers == "" ? customer3.getIdNumber() : idNumbers + "、" + customer3.getIdNumber(); } contractInformation.setName(names); contractInformation.setIdNumber(idNumbers); contractInformation.setContractAmount(NumberToChineseUtil.convertToChinese(contract.getContractAmount())+"万元"); contractInformation.setMobile(customer.getMobile()); contractInformation.setContactAddress1(customer.getContactAddress()); contractInformation.setContractAttr(loancase.getBusinessUsage());//改成借款用途了 contractInformation.setContractType(loancase.getBusinessAttrs());//改成业务属性了 Map contractMap = dictionaryService.contractMap(); contractInformation.setPages1(contractMap.get(ContractEnum.CONTRACT_COPIES.getLabel())); contractInformation.setContactAddress2(contractMap.get(ContractEnum.CONTACT_ADDRESS.getLabel())); contractInformation.setSignaturePath2(contractMap.get(ContractEnum.CONTRACT_PARTY_A.getLabel())); contractInformation.setSignLocation1(contractMap.get(ContractEnum.SIGNATURE_ADDRESS.getLabel())); contractInformation.setSignLocation2(contractMap.get(ContractEnum.SIGNATURE_ADDRESS.getLabel())); List collateralIdsByContractId = contractAndCollateralService.findCollateralIdsByContractId(contract.getId()); if (collateralIdsByContractId != null){ Collateral collateral = collateralService.findCollateralById(collateralIdsByContractId.get(0)); contractInformation.setAddress(collateral.getAddress()); contractInformation.setCollateralArea(collateral.getCollateralArea()+"平方米"); contractInformation.setCollateralNumber(collateral.getCollateralNo()); } String downloadName = contract.getContractName()+"-"+contract.getId(); new PoiWordUtil().writeApprove(response,contractPath+"template1.docx",contractInformation,downloadName); } @Override public ContractInformation getContractInformationById(Long caseId, Long contractId) { Contract contract = contractRepository.findContractById(contractId); LoanCaseSimpleVO loancase = loanService.findLoanCaseSimpleByIdAndIsDelete(caseId, false); CustomerVO customer = customerService.findByCustomerIdAndIsDelete(loancase.getCustomerId(),false); ContractInformation contractInformation = BeanUtil.copyProperties(contract, ContractInformation.class); if (contract.getSignedId() != null){ Document byId = documentService.findById(contract.getSignedId()); contractInformation.setSignaturePath1(byId.getFilePath()); } String names = ""; String idNumbers = ""; if (contract.getCustomerId()!=null){ Customer customer1 = customerService.findByIdAndIsDelete(contract.getCustomerId()); names = names == "" ? customer1.getName() : names + "、" + customer1.getName(); idNumbers = idNumbers == "" ? customer1.getIdNumber() : idNumbers + "、" + customer1.getIdNumber(); } if (contract.getCustomerId1()!=null){ Customer customer2 = customerService.findByIdAndIsDelete(contract.getCustomerId1()); names = names == "" ? customer2.getName() : names + "、" + customer2.getName(); idNumbers = idNumbers == "" ? customer2.getIdNumber() : idNumbers + "、" + customer2.getIdNumber(); } if (contract.getCustomerId2()!=null){ Customer customer3 = customerService.findByIdAndIsDelete(contract.getCustomerId2()); names = names == "" ? customer3.getName() : names + "、" + customer3.getName(); idNumbers = idNumbers == "" ? customer3.getIdNumber() : idNumbers + "、" + customer3.getIdNumber(); } contractInformation.setName(names); contractInformation.setIdNumber(idNumbers); contractInformation.setContractAmount(NumberToChineseUtil.convertToChinese(contract.getContractAmount())); contractInformation.setMobile(customer.getMobile()); contractInformation.setContactAddress1(customer.getContactAddress()); contractInformation.setContractAttr(loancase.getBusinessUsage());//改成借款用途了 contractInformation.setContractType(loancase.getBusinessAttrs());//改成业务属性了 Map contractMap = dictionaryService.contractMap(); contractInformation.setPages1(contractMap.get(ContractEnum.CONTRACT_COPIES.getLabel())); contractInformation.setContactAddress2(contractMap.get(ContractEnum.CONTACT_ADDRESS.getLabel())); contractInformation.setSignaturePath2(contractMap.get(ContractEnum.CONTRACT_PARTY_A.getLabel())); contractInformation.setSignLocation1(contractMap.get(ContractEnum.SIGNATURE_ADDRESS.getLabel())); contractInformation.setSignLocation2(contractMap.get(ContractEnum.SIGNATURE_ADDRESS.getLabel())); List collateralIdsByContractId = contractAndCollateralService.findCollateralIdsByContractId(contract.getId()); if (collateralIdsByContractId != null){ Collateral collateral = collateralService.findCollateralById(collateralIdsByContractId.get(0)); contractInformation.setAddress(collateral.getAddress()); contractInformation.setCollateralArea(collateral.getCollateralArea()); contractInformation.setCollateralNumber(collateral.getCollateralNo()); } return contractInformation; } @Override public void updateClearedStatusById(Long contractId, String msg) { contractRepository.updateClearedStatusById(contractId,msg,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } @Override public List findIdsByCaseId(Long caseId) { return contractRepository.findIdsByCaseIdAndIsDelete(caseId, false); } @Override public void updateActualAmountAndIsCompleteByIds(Map contractIdAndAmount,Boolean isComplete) { for (Map.Entry entry : contractIdAndAmount.entrySet()){ Contract contract = contractRepository.findContractById(entry.getKey()); Double amount = entry.getValue(); isComplete = contract.getIsDisbursementComplete(); if(Math.abs(amount - contract.getContractAmount()) contracts = findContractByCaseId(caseId); return contracts.stream().reduce(0.0, (sum, contract) -> sum + contract.getActualAmount(), Double::sum); } @Override public void updateIsDisbursementById(Long contractId, boolean isDisbursement) { contractRepository.updateISCompleteById(contractId,isDisbursement); } @Override public Result findAllContract(Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); Page data = contractRepository.findAllByIsDelete(false, pageable); List contractVOS = convertContractsToContractVOS(data.getContent()); return ResultUtil.success(data.getTotalElements(), contractVOS); } @Override public Result findAllContractByQuery(Integer pageNum, Integer pageSize, ContractQueryDTO contractQueryDTO) { Pageable pageable = PageRequest.of(pageNum-1, pageSize); Page data = contractRepository.findAllByQuery(contractQueryDTO, pageable); return ResultUtil.success(data.getTotalElements(), convertContractsToContractVOS(data.getContent())); } @Override public void deleteContractById(Long id) { contractRepository.deleteByIdAndIsDelete(id, true); } @Override public void updateIsDisbursementByCaseId(Long caseId) { contractRepository.updateIsDisbursementByCaseIdAndIsDelete(caseId,false); } private List convertContractsToContractVOS(List contracts) { List contractVOS = new ArrayList<>(); for (Contract contract : contracts){ ContractVO contractVO = BeanUtil.copyProperties(contract, ContractVO.class); contractVO.setEsignFlow(esignService.findByContractIdAndNormal(contract.getId())); Customer customer = customerService.findByIdAndIsDelete(contract.getCustomerId()); contractVO.setCustomer(BeanUtil.copyProperties(customer, CustomerVO.class)); Customer customer1 = customerService.findByIdAndIsDelete(contract.getCustomerId1()); contractVO.setCustomer1(BeanUtil.copyProperties(customer1, CustomerVO.class)); Customer customer2 = customerService.findByIdAndIsDelete(contract.getCustomerId2()); contractVO.setCustomer2(BeanUtil.copyProperties(customer2, CustomerVO.class)); String customerNames = ""; if (!ObjectUtils.isEmpty(customer)) customerNames += customer.getName(); if (!ObjectUtils.isEmpty(customer1)) customerNames += "," + customer1.getName(); if (!ObjectUtils.isEmpty(customer2)) customerNames += "," + customer2.getName(); contractVO.setCustomerNames(customerNames); List bankInfoVOS = contractBankInfoService.findByContractIdAndIsDelete(contract.getId(), false); ContractBankInfoVO bankInfo = null; List entrustBankInfoVOS = new ArrayList<>(); for (ContractBankInfoVO bankInfoVO : bankInfoVOS){ if (!bankInfoVO.getIsEntrust()) bankInfo = bankInfoVO; else entrustBankInfoVOS.add(bankInfoVO); } if (bankInfo == null && customer != null){//如果还没填,默认是第一位客户的银行信息 bankInfo = new ContractBankInfoVO(); bankInfo.setPayee(customer.getName()); bankInfo.setCustomerId(customer.getId()); bankInfo.setMobile(customer.getMobile()); bankInfo.setId(-1L); bankInfo.setDisburseBank(customer.getBankName()); bankInfo.setDisburseAccount(customer.getBankAccount()); } contractVO.setBankInfo(bankInfo); contractVO.setEntrustBankInfos(entrustBankInfoVOS); //contractVO.setCustomerName(customer.getName()); contractVOS.add(contractVO); } return contractVOS; } }